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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
48,072
|
Bug 48072 Complete relationship information in the structure model
|
Complete the set of relationships surfaced by the structure model (e.g. including support for declare parents etc.) - Mik you had a document listing the things yet to be done here?
|
resolved fixed
|
f24286d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-23T10:03:14Z
| 2003-12-04T15:00:00Z
|
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.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.FieldInstruction;
import org.apache.bcel.generic.GETSTATIC;
import org.apache.bcel.generic.INVOKEINTERFACE;
import org.apache.bcel.generic.INVOKESPECIAL;
import org.apache.bcel.generic.INVOKESTATIC;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.PUTSTATIC;
import org.apache.bcel.generic.Type;
import org.apache.bcel.util.ClassPath;
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.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 {
private ClassPathManager classPath;
//private ClassPathManager aspectPath = null;
// private List aspectPathEntries;
// ---- constructors
public BcelWorld() {
this("");
}
public BcelWorld(String cp) {
this(makeDefaultClasspath(cp), IMessageHandler.THROW);
}
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) {
//this.aspectPath = new ClassPathManager(aspectPath, handler);
this.classPath = new ClassPathManager(classPath, handler);
setMessageHandler(handler);
}
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();
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 static BcelObjectType getBcelObjectType(ResolvedTypeX concreteAspect) {
//XXX need error checking
return (BcelObjectType) ((ResolvedTypeX.Name)concreteAspect).getDelegate();
}
}
|
48,091
|
Bug 48091 Lazy instantiation of thisJoinPoint
|
In cases where the body of advice refers to a non-statically evaluable portion of thisJoinPoint (so that it can't be optimized by the compiler to thisJoinPointStaticPart), the JoinPoint object is currently always created before entering the advice body - even if the JoinPoint object would never actually be accessed (because of a test within the advice for example). Since a) thisJoinPoint is often used in tracing applications b) tracing applications tend to be very pervasive, c) they must have low overhead when tracing is disabled, and d) creation of thisJoinPoint objects is expensive (v. expensive compared to just testing a flag) it would be nice if there was a way to create JoinPoint objects lazily on first actual reference within the advice body.
|
resolved fixed
|
0c83343
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-24T02:28:54Z
| 2003-12-04T17:46:40Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/BuildArgParser.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.ajc;
import java.io.*;
import java.util.*;
import org.aspectj.ajdt.internal.core.builder.*;
import org.aspectj.bridge.*;
import org.aspectj.util.*;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.internal.compiler.batch.Main;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
public class BuildArgParser extends Main {
private static final String BUNDLE_NAME = "org.aspectj.ajdt.ajc.messages";
private static boolean LOADED_BUNDLE = false;
static {
bundle = ResourceBundle.getBundle(BUNDLE_NAME);
if (!LOADED_BUNDLE) {
LOADED_BUNDLE = true;
}
}
/** to initialize super's PrintWriter but refer to underlying StringWriter */
private static class StringPrintWriter extends PrintWriter {
public final StringWriter stringWriter;
StringPrintWriter(StringWriter sw) {
super(sw);
this.stringWriter = sw;
}
}
/** @return multi-line String usage for the compiler */
public static String getUsage() {
return Main.bind("misc.usage");
}
/**
* StringWriter sink for some errors.
* This only captures errors not handled by any IMessageHandler parameter
* and only when no PrintWriter is set in the constructor.
* XXX This relies on (Sun's) implementation of StringWriter,
* which returns the actual (not copy) internal StringBuffer.
*/
private final StringBuffer errorSink;
private IMessageHandler handler;
/**
* Overrides super's bundle.
*/
public BuildArgParser(PrintWriter writer, IMessageHandler handler) {
super(writer, writer, false);
if (writer instanceof StringPrintWriter) {
errorSink = ((StringPrintWriter) writer).stringWriter.getBuffer();
} else {
errorSink = null;
}
this.handler = handler;
}
/** Set up to capture messages using getOtherMessages(boolean) */
public BuildArgParser(IMessageHandler handler) {
this(new StringPrintWriter(new StringWriter()),handler);
}
/**
* Generate build configuration for the input args,
* passing to handler any error messages.
* @param args the String[] arguments for the build configuration
* @return AjBuildConfig per args,
* which will be invalid unless there are no handler errors.
*/
public AjBuildConfig genBuildConfig(String[] args) {
return genBuildConfig(args, true, null);
}
/**
* 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 genBuildConfig(String[] args, boolean setClasspath, File configFile) {
AjBuildConfig buildConfig = new AjBuildConfig();
buildConfig.setConfigFile(configFile);
try {
// sets filenames to be non-null in order to make sure that file paramters are ignored
super.filenames = new String[] { "" };
AjcConfigParser parser = new AjcConfigParser(buildConfig, handler);
parser.parseCommandLine(args);
boolean incrementalMode = buildConfig.isIncrementalMode()
|| buildConfig.isIncrementalFileMode();
List fileList = new ArrayList();
List files = parser.getFiles();
if (!LangUtil.isEmpty(files)) {
if (incrementalMode) {
MessageUtil.error(handler, "incremental mode only handles source files using -sourceroots");
} else {
fileList.addAll(files);
}
}
List javaArgList = new ArrayList();
// disable all special eclipse warnings by default
//??? might want to instead override getDefaultOptions()
javaArgList.add("-warn:none");
// these next four lines are some nonsense to fool the eclipse batch compiler
// without these it will go searching for reasonable values from properties
//TODO fix org.eclipse.jdt.internal.compiler.batch.Main so this hack isn't needed
javaArgList.add("-classpath");
javaArgList.add(System.getProperty("user.dir"));
javaArgList.add("-bootclasspath");
javaArgList.add(System.getProperty("user.dir"));
javaArgList.addAll(parser.getUnparsedArgs());
super.configure((String[])javaArgList.toArray(new String[javaArgList.size()]));
if (!proceed) {
buildConfig.doNotProceed();
return buildConfig;
}
if (buildConfig.getSourceRoots() != null) {
for (Iterator i = buildConfig.getSourceRoots().iterator(); i.hasNext(); ) {
fileList.addAll(collectSourceRootFiles((File)i.next()));
}
}
buildConfig.setFiles(fileList);
if (destinationPath != null) { // XXX ?? unparsed but set?
buildConfig.setOutputDir(new File(destinationPath));
}
if (setClasspath) {
buildConfig.setClasspath(getClasspath(parser));
}
if (incrementalMode
&& (0 == buildConfig.getSourceRoots().size())) {
MessageUtil.error(handler, "specify a source root when in incremental mode");
}
setDebugOptions();
buildConfig.setJavaOptions(options);
} catch (InvalidInputException iie) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
location = new SourceLocation(buildConfig.getConfigFile(), 0);
}
IMessage m = new Message(iie.getMessage(), IMessage.ERROR, null, location);
handler.handleMessage(m);
}
return buildConfig;
}
// from super...
public void printVersion() {
System.err.println("AspectJ Compiler " + Version.text + " built on " + Version.time_text); //$NON-NLS-1$
System.err.flush();
}
public void printUsage() {
System.out.println(bind("misc.usage")); //$NON-NLS-1$
System.out.flush();
}
/**
* Get messages not dumped to handler or any PrintWriter.
* @param flush if true, empty errors
* @return null if none, String otherwise
* @see BuildArgParser()
*/
public String getOtherMessages(boolean flush) {
if (null == errorSink) {
return null;
}
String result = errorSink.toString().trim();
if (0 == result.length()) {
result = null;
}
if (flush) {
errorSink.setLength(0);
}
return result;
}
private void setDebugOptions() {
options.put(
CompilerOptions.OPTION_LocalVariableAttribute,
CompilerOptions.GENERATE);
options.put(
CompilerOptions.OPTION_LineNumberAttribute,
CompilerOptions.GENERATE);
options.put(
CompilerOptions.OPTION_SourceFileAttribute,
CompilerOptions.GENERATE);
}
private Collection collectSourceRootFiles(File dir) {
return Arrays.asList(FileUtil.listFiles(dir, FileUtil.aspectjSourceFileFilter));
}
/**
* If the classpath is not set, we use the environment's java.class.path, but remove
* the aspectjtools.jar entry from that list in order to prevent wierd bootstrap issues
* (refer to bug#39959).
*/
public List getClasspath(AjcConfigParser parser) {
List ret = new ArrayList();
if (parser.bootclasspath == null) {
addClasspath(System.getProperty("sun.boot.class.path", ""), ret);
} else {
addClasspath(parser.bootclasspath, ret);
}
String extdirs = parser.extdirs;
if (extdirs == null) {
extdirs = System.getProperty("java.ext.dirs", "");
}
addExtDirs(extdirs, ret);
if (parser.classpath == null) {
addClasspath(System.getProperty("java.class.path", ""), ret);
List fixedList = new ArrayList();
for (Iterator it = ret.iterator(); it.hasNext(); ) {
String entry = (String)it.next();
if (!entry.endsWith("aspectjtools.jar")) {
fixedList.add(entry);
}
}
ret = fixedList;
} else {
addClasspath(parser.classpath, ret);
}
//??? eclipse seems to put outdir on the classpath
//??? we're brave and believe we don't need it
return ret;
}
private void addExtDirs(String extdirs, List classpathCollector) {
StringTokenizer tokenizer = new StringTokenizer(extdirs, File.pathSeparator);
while (tokenizer.hasMoreTokens()) {
// classpathCollector.add(tokenizer.nextToken());
File dirFile = new File((String)tokenizer.nextToken());
if (dirFile.canRead() && dirFile.isDirectory()) {
File[] files = dirFile.listFiles(FileUtil.ZIP_FILTER);
for (int i = 0; i < files.length; i++) {
classpathCollector.add(files[i].getAbsolutePath());
}
} else {
// XXX alert on invalid -extdirs entries
}
}
}
private void addClasspath(String classpath, List classpathCollector) {
StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator);
while (tokenizer.hasMoreTokens()) {
classpathCollector.add(tokenizer.nextToken());
}
}
private class AjcConfigParser extends ConfigParser {
private String bootclasspath = null;
private String classpath = null;
private String extdirs = null;
private List unparsedArgs = new ArrayList();
private AjBuildConfig buildConfig;
private IMessageHandler handler;
public AjcConfigParser(AjBuildConfig buildConfig, IMessageHandler handler) {
this.buildConfig = buildConfig;
this.handler = handler;
}
public List getUnparsedArgs() {
return unparsedArgs;
}
/**
* Extract AspectJ-specific options (except for argfiles).
* Caller should warn when sourceroots is empty but in
* incremental mode.
* Signals warnings or errors through handler set in constructor.
*/
public void parseOption(String arg, LinkedList args) { // XXX use ListIterator.remove()
int nextArgIndex = args.indexOf(arg)+1; // XXX assumes unique
// trim arg?
if (LangUtil.isEmpty(arg)) {
showWarning("empty arg found");
} else if (arg.equals("-inpath")) {;
if (args.size() > nextArgIndex) {
buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_Inpath, CompilerOptions.PRESERVE);
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)) {
buildConfig.getInpath().add(file);
} else {
if (file.isDirectory()) {
buildConfig.getInpath().add(file);
} else
showError("bad inpath component: " + filename);
}
}
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("-noweave") || arg.equals( "-XnoWeave")) {
buildConfig.setNoWeave(true);
} else if (arg.equals("-XserializableAspects")) {
buildConfig.setXserializableAspects(true);
} else if (arg.equals("-XnoInline")) {
buildConfig.setXnoInline(true);
} else if (arg.equals("-Xlintfile")) {
if (args.size() > nextArgIndex) {
File lintSpecFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue());
// XXX relax restriction on props file suffix?
if (lintSpecFile.canRead() && lintSpecFile.getName().endsWith(".properties")) {
buildConfig.setLintSpecFile(lintSpecFile);
} else {
showError("bad -Xlintfile file: " + lintSpecFile);
buildConfig.setLintSpecFile(null);
}
args.remove(args.get(nextArgIndex));
} else {
showError("-Xlintfile requires .properties file argument");
}
} else if (arg.equals("-Xlint")) {
buildConfig.getAjOptions().put(
AjCompilerOptions.OPTION_Xlint,
CompilerOptions.GENERATE);
buildConfig.setLintMode(AjBuildConfig.AJLINT_DEFAULT);
} else if (arg.startsWith("-Xlint:")) {
if (7 < arg.length()) {
buildConfig.setLintMode(arg.substring(7));
} else {
showError("invalid lint option " + arg);
}
} else if (arg.equals("-bootclasspath")) {
if (args.size() > nextArgIndex) {
bootclasspath = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
args.remove(args.get(nextArgIndex));
} else {
showError("-bootclasspath requires classpath entries");
}
} else if (arg.equals("-classpath")) {
if (args.size() > nextArgIndex) {
classpath = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
args.remove(args.get(nextArgIndex));
} else {
showError("-classpath requires classpath entries");
}
} else if (arg.equals("-extdirs")) {
if (args.size() > nextArgIndex) {
extdirs = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
args.remove(args.get(nextArgIndex));
} else {
showError("-extdirs requires list of external directories");
}
// error on directory unless -d, -{boot}classpath, or -extdirs
} else if (arg.equals("-d")) {
dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-classpath")) {
// dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-bootclasspath")) {
// dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-extdirs")) {
// dirLookahead(arg, args, nextArgIndex);
} else if (new File(arg).isDirectory()) {
showError("dir arg not permitted: " + arg);
} else {
// argfile, @file parsed by superclass
// no eclipse options parsed:
// -d args, -help (handled),
// -classpath, -target, -1.3, -1.4, -source [1.3|1.4]
// -nowarn, -warn:[...], -deprecation, -noImportError,
// -proceedOnError, -g:[...], -preserveAllLocals,
// -referenceInfo, -encoding, -verbose, -log, -time
// -noExit, -repeat
unparsedArgs.add(arg);
}
}
protected void dirLookahead(String arg, LinkedList argList, int nextArgIndex) {
unparsedArgs.add(arg);
ConfigParser.Arg next = (ConfigParser.Arg) argList.get(nextArgIndex);
String value = next.getValue();
if (!LangUtil.isEmpty(value)) {
if (new File(value).isDirectory()) {
unparsedArgs.add(value);
argList.remove(next);
return;
}
}
}
public void showError(String message) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
location = new SourceLocation(buildConfig.getConfigFile(), 0);
}
IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.ERROR, null, location);
handler.handleMessage(errorMessage);
// MessageUtil.error(handler, CONFIG_MSG + message);
}
protected void showWarning(String message) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
location = new SourceLocation(buildConfig.getConfigFile(), 0);
}
IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.WARNING, null, location);
handler.handleMessage(errorMessage);
// MessageUtil.warn(handler, message);
}
protected File makeFile(File dir, String name) {
name = name.replace('/', File.separatorChar);
File ret = new File(name);
if (dir == null || ret.isAbsolute()) return ret;
try {
dir = dir.getCanonicalFile();
} catch (IOException ioe) { }
return new File(dir, name);
}
}
}
|
48,091
|
Bug 48091 Lazy instantiation of thisJoinPoint
|
In cases where the body of advice refers to a non-statically evaluable portion of thisJoinPoint (so that it can't be optimized by the compiler to thisJoinPointStaticPart), the JoinPoint object is currently always created before entering the advice body - even if the JoinPoint object would never actually be accessed (because of a test within the advice for example). Since a) thisJoinPoint is often used in tracing applications b) tracing applications tend to be very pervasive, c) they must have low overhead when tracing is disabled, and d) creation of thisJoinPoint objects is expensive (v. expensive compared to just testing a flag) it would be nice if there was a way to create JoinPoint objects lazily on first actual reference within the advice body.
|
resolved fixed
|
0c83343
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-24T02:28:54Z
| 2003-12-04T17:46: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.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
/**
* All configuration information needed to run the AspectJ compiler.
*/
public class AjBuildConfig { // XXX needs bootclasspath?
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*/ 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 Map javaOptions = new HashMap();
private Map ajOptions = new HashMap();
private File configFile;
private boolean generateModelMode = false;
private boolean emacsSymMode = false;
private boolean noWeave = false;
private boolean XserializableAspects = false;
private boolean XnoInline = false;
private String lintMode = AJLINT_DEFAULT;
private File lintSpecFile = null;
/** 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;
/**
* 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( ) {
javaOptions.put(
CompilerOptions.OPTION_LocalVariableAttribute,
//CompilerOptions.DO_NOT_GENERATE);
CompilerOptions.GENERATE);
javaOptions.put(
CompilerOptions.OPTION_LineNumberAttribute,
//CompilerOptions.DO_NOT_GENERATE);
CompilerOptions.GENERATE);
javaOptions.put(
CompilerOptions.OPTION_SourceFileAttribute,
//CompilerOptions.DO_NOT_GENERATE);
CompilerOptions.GENERATE);
javaOptions.put(
CompilerOptions.OPTION_PreserveUnusedLocal,
CompilerOptions.OPTIMIZE_OUT);
// javaOptions.put(
// CompilerOptions.OPTION_ReportUnreachableCode,
// CompilerOptions.IGNORE);
// javaOptions.put(
// CompilerOptions.OPTION_ReportInvalidImport,
// CompilerOptions.ERROR);
javaOptions.put(
CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod,
CompilerOptions.WARNING);
javaOptions.put(
CompilerOptions.OPTION_ReportMethodWithConstructorName,
CompilerOptions.WARNING);
javaOptions.put(
CompilerOptions.OPTION_ReportDeprecation,
CompilerOptions.WARNING);
javaOptions.put(
CompilerOptions.OPTION_ReportHiddenCatchBlock,
CompilerOptions.WARNING);
javaOptions.put(
CompilerOptions.OPTION_ReportUnusedLocal,
CompilerOptions.IGNORE);
javaOptions.put(
CompilerOptions.OPTION_ReportUnusedParameter,
CompilerOptions.IGNORE);
javaOptions.put(
CompilerOptions.OPTION_ReportSyntheticAccessEmulation,
CompilerOptions.IGNORE);
javaOptions.put(
CompilerOptions.OPTION_ReportNonExternalizedStringLiteral,
CompilerOptions.IGNORE);
javaOptions.put(
CompilerOptions.OPTION_ReportAssertIdentifier,
CompilerOptions.IGNORE);
javaOptions.put(
CompilerOptions.OPTION_Compliance,
CompilerOptions.VERSION_1_3);
javaOptions.put(
CompilerOptions.OPTION_Source,
CompilerOptions.VERSION_1_3);
javaOptions.put(
CompilerOptions.OPTION_TargetPlatform,
CompilerOptions.VERSION_1_1);
}
/**
* 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;
}
public File getOutputDir() {
return outputDir;
}
public void setFiles(List files) {
this.files = files;
}
public void setOutputDir(File outputDir) {
this.outputDir = outputDir;
}
public Map getAjOptions() {
return ajOptions;
}
/**
* @return the Map expected by org.eclipse.jdt.core.internal.Compiler.
*/
public Map getJavaOptions() {
return javaOptions;
}
public void setAjOptions(Map ajOptions) {
this.ajOptions = ajOptions;
}
public void setJavaOptions(Map javaOptions) {
this.javaOptions = javaOptions;
}
/**
* This includes all entries from -bootclasspath, -extdirs, -classpath,
*/
public List getClasspath() { // XXX setters don't respect javadoc contract...
return classpath;
}
public void setClasspath(List classpath) {
this.classpath = classpath;
}
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 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 boolean isEmacsSymMode() {
return emacsSymMode;
}
public void setEmacsSymMode(boolean emacsSymMode) {
this.emacsSymMode = emacsSymMode;
}
public boolean isGenerateModelMode() {
return generateModelMode;
}
public void setGenerateModelMode(boolean structureModelMode) {
this.generateModelMode = structureModelMode;
}
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 injars, inpath, aspectpath
* entries, specified classpath (bootclasspath, extdirs, and
* classpath), and output dir or jar
*/
public List getFullClasspath() {
List full = new ArrayList();
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 String getLintMode() {
return lintMode;
}
public File getLintSpecFile() {
return lintSpecFile;
}
public List getAspectpath() {
return aspectpath;
}
public boolean isNoWeave() {
return noWeave;
}
public void setLintMode(String lintMode) {
this.lintMode = lintMode;
}
public void setLintSpecFile(File lintSpecFile) {
this.lintSpecFile = lintSpecFile;
}
public void setAspectpath(List aspectpath) {
this.aspectpath = aspectpath;
}
public void setNoWeave(boolean noWeave) {
this.noWeave = noWeave;
}
public boolean isXserializableAspects() {
return XserializableAspects;
}
public void setXserializableAspects(boolean xserializableAspects) {
XserializableAspects = xserializableAspects;
}
public boolean isXnoInline() {
return XnoInline;
}
public void setXnoInline(boolean xnoInline) {
XnoInline = xnoInline;
}
/** @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
join(ajOptions, global.ajOptions);
join(aspectpath, global.aspectpath);
join(classpath, global.classpath);
if (null == configFile) {
configFile = global.configFile; // XXX correct?
}
if (!emacsSymMode && global.emacsSymMode) {
emacsSymMode = true;
}
join(files, global.files);
if (!generateModelMode && global.generateModelMode) {
generateModelMode = true;
}
if (null == incrementalFile) {
incrementalFile = global.incrementalFile;
}
if (!incrementalMode && global.incrementalMode) {
incrementalMode = true;
}
join(inJars, global.inJars);
join(inPath, global.inPath);
join(javaOptions, global.javaOptions);
if ((null == lintMode)
|| (AJLINT_DEFAULT.equals(lintMode))) {
lintMode = global.lintMode;
}
if (null == lintSpecFile) {
lintSpecFile = global.lintSpecFile;
}
if (!noWeave && global.noWeave) {
noWeave = 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 (!XnoInline && global.XnoInline) {
XnoInline = true;
}
if (!XserializableAspects && global.XserializableAspects) {
XserializableAspects = 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;
}
}
|
48,091
|
Bug 48091 Lazy instantiation of thisJoinPoint
|
In cases where the body of advice refers to a non-statically evaluable portion of thisJoinPoint (so that it can't be optimized by the compiler to thisJoinPointStaticPart), the JoinPoint object is currently always created before entering the advice body - even if the JoinPoint object would never actually be accessed (because of a test within the advice for example). Since a) thisJoinPoint is often used in tracing applications b) tracing applications tend to be very pervasive, c) they must have low overhead when tracing is disabled, and d) creation of thisJoinPoint objects is expensive (v. expensive compared to just testing a flag) it would be nice if there was a way to create JoinPoint objects lazily on first actual reference within the advice body.
|
resolved fixed
|
0c83343
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-24T02:28:54Z
| 2003-12-04T17:46: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 org.aspectj.ajdt.internal.compiler.AjCompiler;
import org.aspectj.ajdt.internal.compiler.lookup.*;
import org.aspectj.ajdt.internal.compiler.parser.AjParser;
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.weaver.World;
import org.aspectj.weaver.bcel.*;
import org.eclipse.jdt.core.compiler.*;
import org.eclipse.jdt.internal.compiler.*;
import org.eclipse.jdt.internal.compiler.batch.*;
import org.eclipse.jdt.internal.compiler.batch.FileSystem;
import org.eclipse.jdt.internal.compiler.env.*;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
//import org.eclipse.jdt.internal.compiler.util.HashtableOfObject;
public class AjBuildManager {
static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false;
private IProgressListener progressListener = null;
private int compiledCount;
private int sourceFileCount;
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 {
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);
//}
setupModel();
if (batch) {
initBcelWorld(handler);
}
if (handler.hasErrors()) {
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?
}
performCompilation(buildConfig.getFiles());
if (handler.hasErrors()) {
return false;
}
} else {
// done already?
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
// bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel());
// }
// System.err.println("XXXX start inc ");
List files = state.getFilesToCompile(true);
for (int i = 0; (i < 5) && !files.isEmpty(); i++) {
// System.err.println("XXXX inc: " + files);
performCompilation(files);
if (handler.hasErrors()) {
return false;
}
files = state.getFilesToCompile(false);
}
if (!files.isEmpty()) {
return batchBuild(buildConfig, baseHandler);
}
}
// XXX not in Mik's incremental
if (buildConfig.isEmacsSymMode()) {
new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel();
}
// have to tell state we succeeded or next is not incremental
state.successfulCompile(buildConfig);
/*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();
}
return !handler.hasErrors();
} finally {
handler = null;
}
}
private void setupModel() {
String rootLabel = "<root>";
IHierarchy model = AsmManager.getDefault().getHierarchy();
IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA;
if (buildConfig.getConfigFile() != null) {
rootLabel = buildConfig.getConfigFile().getName();
model.setConfigFile(
buildConfig.getConfigFile().getAbsolutePath()
);
kind = IProgramElement.Kind.FILE_LST;
}
model.setRoot(new ProgramElement(rootLabel, kind, new ArrayList()));
model.setFileMap(new HashMap());
setStructureModel(model);
}
/** init only on initial batch compile? no file-specific options */
private void initBcelWorld(IMessageHandler handler) throws IOException {
bcelWorld = new BcelWorld(buildConfig.getClasspath(), handler, null);
bcelWorld.setXnoInline(buildConfig.isXnoInline());
bcelWeaver = new BcelWeaver(bcelWorld);
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();
bcelWeaver.addJarFile(inJar, buildConfig.getOutputDir(),false);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
bcelWeaver.addJarFile(inPathElement,buildConfig.getOutputDir(),true);
}
if (buildConfig.getSourcePathResources() != null) {
for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) {
// File resource = (File)i.next();
String resource = (String)i.next();
bcelWeaver.addResource(resource, (File)buildConfig.getSourcePathResources().get(resource), buildConfig.getOutputDir());
// bcelWeaver.addResource(resource, buildConfig.getOutputDir());
}
}
//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 = (String) buildConfig.getJavaOptions().get(CompilerOptions.OPTION_Encoding);
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 = (String) buildConfig.getJavaOptions().get(CompilerOptions.OPTION_Encoding);
if ("".equals(defaultEncoding)) //$NON-NLS-1$
defaultEncoding = null; //$NON-NLS-1$
for (int i = 0; i < fileCount; i++) {
String encoding = encodings[i];
if (encoding == null)
encoding = defaultEncoding;
units[i] = new CompilationUnit(null, filenames[i], encoding);
}
return units;
}
public String extractDestinationPathFromSourceFile(CompilationResult result) {
ICompilationUnit compilationUnit = result.compilationUnit;
if (compilationUnit != null) {
char[] fileName = compilationUnit.getFileName();
int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName);
if (lastIndex == -1) {
return System.getProperty("user.dir"); //$NON-NLS-1$
}
return new String(CharOperation.subarray(fileName, 0, lastIndex));
}
return System.getProperty("user.dir"); //$NON-NLS-1$
}
public void performCompilation(List files) {
if (progressListener != null) {
compiledCount = 0;
sourceFileCount = files.size();
progressListener.setText("compiling source files");
}
//System.err.println("got files: " + files);
String[] filenames = new String[files.size()];
String[] encodings = new String[files.size()];
//System.err.println("filename: " + this.filenames);
for (int i=0; i < files.size(); i++) {
filenames[i] = ((File)files.get(i)).getPath();
}
List cps = buildConfig.getFullClasspath();
String[] classpaths = new String[cps.size()];
for (int i=0; i < cps.size(); i++) {
classpaths[i] = (String)cps.get(i);
}
//System.out.println("compiling");
INameEnvironment environment = getLibraryAccess(classpaths, filenames);
if (!state.classesFromName.isEmpty()) {
environment = new StatefulNameEnvironment(environment, state.classesFromName);
}
AjCompiler compiler = new AjCompiler(
environment,
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
buildConfig.getJavaOptions(),
getBatchRequestor(),
getProblemFactory());
AjProblemReporter pr =
new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(),
compiler.options, getProblemFactory());
compiler.problemReporter = pr;
AjLookupEnvironment le =
new AjLookupEnvironment(compiler, compiler.options, pr, environment);
EclipseFactory factory = new EclipseFactory(le);
// ew.setLint(bcelWorld.getLint());
// ew.setXnoInline(buildConfig.isXnoInline());
le.factory = factory;
pr.factory = factory;
le.factory.buildManager = this;
compiler.lookupEnvironment = le;
compiler.parser =
new AjParser(
pr,
compiler.options.parseLiteralExpressionsAsConstants);
CompilerOptions options = compiler.options;
options.produceReferenceInfo(true); //TODO turn off when not needed
compiler.compile(getCompilationUnits(filenames, encodings));
// cleanup
environment.cleanup();
}
/*
* Answer the component to which will be handed back compilation results from the compiler
*/
public ICompilerRequestor getBatchRequestor() {
return new ICompilerRequestor() {
int lineDelta = 0;
public void acceptResult(CompilationResult compilationResult) {
if (progressListener != null) {
compiledCount++;
progressListener.setProgress((compiledCount/2.0)/sourceFileCount);
progressListener.setText("compiled: " + new String(compilationResult.getFileName()));
}
if (compilationResult.hasProblems() || compilationResult.hasTasks()) {
IProblem[] problems = compilationResult.getAllProblems();
for (int i=0; i < problems.length; i++) {
IMessage message =
EclipseAdapterUtils.makeMessage(compilationResult.compilationUnit, problems[i]);
handler.handleMessage(message);
}
}
outputClassFiles(compilationResult);
}
};
}
private boolean proceedOnError() {
return true; //???
}
public void outputClassFiles(CompilationResult unitResult) {
if (unitResult == null) return;
String sourceFileName = new String(unitResult.fileName);
if (!(unitResult.hasErrors() && !proceedOnError())) {
List unwovenClassFiles = new ArrayList();
Enumeration classFiles = unitResult.compiledTypes.elements();
while (classFiles.hasMoreElements()) {
ClassFile classFile = (ClassFile) classFiles.nextElement();
String filename = new String(classFile.fileName());
filename = filename.replace('/', File.separatorChar) + ".class";
File destinationPath = buildConfig.getOutputDir();
if (destinationPath == null) {
filename = new File(filename).getName();
filename = new File(extractDestinationPathFromSourceFile(unitResult), filename).getPath();
} else {
filename = new File(destinationPath, filename).getPath();
}
//System.out.println("classfile: " + filename);
unwovenClassFiles.add(new UnwovenClassFile(filename, classFile.getBytes()));
}
state.noteClassesFromFile(unitResult, sourceFileName, unwovenClassFiles);
// System.out.println("file: " + sourceFileName);
// for (int i=0; i < unitResult.simpleNameReferences.length; i++) {
// System.out.println("simple: " + new String(unitResult.simpleNameReferences[i]));
// }
// for (int i=0; i < unitResult.qualifiedReferences.length; i++) {
// System.out.println("qualified: " +
// new String(CharOperation.concatWith(unitResult.qualifiedReferences[i], '/')));
// }
} else {
state.noteClassesFromFile(null, sourceFileName, Collections.EMPTY_LIST);
}
}
private void setBuildConfig(AjBuildConfig buildConfig) {
this.buildConfig = buildConfig;
handler.reset();
}
String makeClasspathString() {
if (buildConfig == null || buildConfig.getClasspath() == null) return "";
StringBuffer buf = new StringBuffer();
boolean first = true;
for (Iterator it = buildConfig.getClasspath().iterator(); it.hasNext(); ) {
if (first) { first = false; }
else { buf.append(File.pathSeparator); }
buf.append(it.next().toString());
}
return buf.toString();
}
/**
* This will return null if aspectjrt.jar is present and has the correct version.
* Otherwise it will return a string message indicating the problem.
*/
public String checkRtJar(AjBuildConfig buildConfig) {
// omitting dev info
if (Version.text.equals(Version.DEVELOPMENT)) {
// in the development version we can't do this test usefully
// MessageUtil.info(holder, "running development version of aspectj compiler");
return null;
}
if (buildConfig == null || buildConfig.getClasspath() == null) return "no classpath specified";
for (Iterator it = buildConfig.getClasspath().iterator(); it.hasNext(); ) {
File p = new File( (String)it.next() );
if (p.isFile() && p.getName().equals("aspectjrt.jar")) {
try {
String version = null;
Manifest manifest = new JarFile(p).getManifest();
if (manifest == null) {
return "no manifest found in " + p.getAbsolutePath() +
", expected " + Version.text;
}
Attributes attr = manifest.getAttributes("org/aspectj/lang/");
if (null != attr) {
version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
if (null != version) {
version = version.trim();
}
}
// assume that users of development aspectjrt.jar know what they're doing
if (Version.DEVELOPMENT.equals(version)) {
// MessageUtil.info(holder,
// "running with development version of aspectjrt.jar in " +
// p.getAbsolutePath());
return null;
} else if (!Version.text.equals(version)) {
return "bad version number found in " + p.getAbsolutePath() +
" expected " + Version.text + " found " + version;
}
} catch (IOException ioe) {
return "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe;
}
return null;
} else {
// might want to catch other classpath errors
}
}
return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString();
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("AjBuildManager(");
buf.append(")");
return buf.toString();
}
public void setStructureModel(IHierarchy structureModel) {
this.structureModel = structureModel;
}
/**
* Returns null if there is no structure model
*/
public IHierarchy getStructureModel() {
return structureModel;
}
public IProgressListener getProgressListener() {
return progressListener;
}
public void setProgressListener(IProgressListener progressListener) {
this.progressListener = progressListener;
}
} // class AjBuildManager
|
48,091
|
Bug 48091 Lazy instantiation of thisJoinPoint
|
In cases where the body of advice refers to a non-statically evaluable portion of thisJoinPoint (so that it can't be optimized by the compiler to thisJoinPointStaticPart), the JoinPoint object is currently always created before entering the advice body - even if the JoinPoint object would never actually be accessed (because of a test within the advice for example). Since a) thisJoinPoint is often used in tracing applications b) tracing applications tend to be very pervasive, c) they must have low overhead when tracing is disabled, and d) creation of thisJoinPoint objects is expensive (v. expensive compared to just testing a flag) it would be nice if there was a way to create JoinPoint objects lazily on first actual reference within the advice body.
|
resolved fixed
|
0c83343
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-24T02:28:54Z
| 2003-12-04T17:46: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(ImageTestCase.class);
suite.addTestSuite(MultipleCompileTestCase.class);
// XXX suite.addTestSuite(VerifyWeaveTestCase.class);
//suite.addTestSuite(WorkingCommandTestCase.class);
//$JUnit-END$
return suite;
}
public AjdtBatchTests(String name) { super(name); }
}
|
48,091
|
Bug 48091 Lazy instantiation of thisJoinPoint
|
In cases where the body of advice refers to a non-statically evaluable portion of thisJoinPoint (so that it can't be optimized by the compiler to thisJoinPointStaticPart), the JoinPoint object is currently always created before entering the advice body - even if the JoinPoint object would never actually be accessed (because of a test within the advice for example). Since a) thisJoinPoint is often used in tracing applications b) tracing applications tend to be very pervasive, c) they must have low overhead when tracing is disabled, and d) creation of thisJoinPoint objects is expensive (v. expensive compared to just testing a flag) it would be nice if there was a way to create JoinPoint objects lazily on first actual reference within the advice body.
|
resolved fixed
|
0c83343
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-24T02:28:54Z
| 2003-12-04T17:46:40Z
|
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/CommandTestCase.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.batch;
import org.aspectj.ajdt.ajc.*;
import org.aspectj.ajdt.ajc.AjdtCommand;
import org.aspectj.bridge.ICommand;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.IMessageHolder;
import org.aspectj.bridge.MessageHandler;
import org.aspectj.weaver.bcel.LazyClassGen;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
public abstract class CommandTestCase extends TestCase {
/**
* Constructor for CommandTestCase.
* @param name
*/
public CommandTestCase(String name) {
super(name);
}
public static final int[] NO_ERRORS = new int[0];
public static final int[] TOP_ERROR = new int[0];
public static void checkCompile(String source, int[] expectedErrors) {
List args = new ArrayList();
args.add("-verbose");
args.add("-d");
args.add("out");
args.add("-classpath");
args.add(getRuntimeClasspath() + File.pathSeparator +
"../lib/junit/junit.jar");
args.add("-g"); //XXX need this to get sourcefile and line numbers, shouldn't
args.add(AjdtAjcTests.TESTDATA_PATH + "/" + source);
runCompiler(args, expectedErrors);
}
public void checkMultipleCompile(String source) throws InterruptedException {
List args = new ArrayList();
args.add("-verbose");
args.add("-d");
args.add("out");
args.add("-classpath");
args.add(getRuntimeClasspath());
args.add(AjdtAjcTests.TESTDATA_PATH + "/" + source);
ICommand compiler = runCompiler(args, NO_ERRORS);
Thread.sleep(100);
rerunCompiler(compiler);
}
public void rerunCompiler(ICommand command) {
MessageHandler myHandler = new MessageHandler();
// List recompiledFiles = new ArrayList();
if (!command.repeatCommand(myHandler)) {
assertTrue("recompile failed", false);
}
assertEquals(0, myHandler.numMessages(IMessage.ERROR, true));
}
public static ICommand runCompiler(List args, int[] expectedErrors) {
ICommand command = new AjdtCommand();
MessageHandler myHandler = new MessageHandler();
myHandler.setInterceptor(org.aspectj.tools.ajc.Main.MessagePrinter.TERSE);
boolean result = command.runCommand((String[])args.toArray(new String[args.size()]), myHandler);
System.out.println("result: " + result);
// System.out.println("errors: " + Arrays.asList(myHandler.getErrors()));
// System.out.println("warnings: " + Arrays.asList(myHandler.getWarnings()));
int nErrors = myHandler.numMessages(IMessage.ERROR, IMessageHolder.EQUAL);
if (expectedErrors == NO_ERRORS) {
if (0 != nErrors) {
String s = ""+Arrays.asList(myHandler.getErrors());
assertTrue("unexpected errors: " + s, false);
}
} else if (expectedErrors == TOP_ERROR) { // ?? what is this?
assertTrue("expected error", nErrors > 0);
} else {
List errors = new ArrayList(Arrays.asList(myHandler.getErrors()));
for (int i=0, len=expectedErrors.length; i < len; i++) {
int line = expectedErrors[i];
boolean found = false;
for (Iterator iter = errors.iterator(); iter.hasNext(); ) {
IMessage m = (IMessage)iter.next();
if (m.getSourceLocation() != null && m.getSourceLocation().getLine() == line) {
found = true;
iter.remove();
}
}
assertTrue("didn't find error on line " + line, found);
}
if (errors.size() > 0) {
assertTrue("didn't expect errors: " + errors, false);
}
}
return command;
}
public static void printGenerated(String path, String name) throws IOException {
String fullpath = AjdtAjcTests.TESTDATA_PATH + "/" + path;
LazyClassGen.disassemble(fullpath, name, System.out);
}
/** incremental test case adapter to JUnit */
public class IncCase extends IncrementalCase {
protected void fail(IMessageHandler handler, String mssg) {
assertTrue(mssg, false);
}
protected void message(
IMessage.Kind kind,
String mssg,
IMessageHandler handler) {
if ((kind == IMessage.FAIL) || (kind == IMessage.ABORT)) {
assertTrue(mssg, false);
} else {
System.err.println("IncCase " + kind + ": " + mssg); // XXX
}
super.message(kind, mssg, handler);
}
}
/** get the location of the org.aspectj.lang & runtime classes */
protected static String getRuntimeClasspath() {
return "../runtime/bin" + File.pathSeparator +
System.getProperty("aspectjrt.path");
}
}
|
48,091
|
Bug 48091 Lazy instantiation of thisJoinPoint
|
In cases where the body of advice refers to a non-statically evaluable portion of thisJoinPoint (so that it can't be optimized by the compiler to thisJoinPointStaticPart), the JoinPoint object is currently always created before entering the advice body - even if the JoinPoint object would never actually be accessed (because of a test within the advice for example). Since a) thisJoinPoint is often used in tracing applications b) tracing applications tend to be very pervasive, c) they must have low overhead when tracing is disabled, and d) creation of thisJoinPoint objects is expensive (v. expensive compared to just testing a flag) it would be nice if there was a way to create JoinPoint objects lazily on first actual reference within the advice body.
|
resolved fixed
|
0c83343
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-24T02:28:54Z
| 2003-12-04T17:46:40Z
|
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/PerformanceTestCase.java
| |
48,091
|
Bug 48091 Lazy instantiation of thisJoinPoint
|
In cases where the body of advice refers to a non-statically evaluable portion of thisJoinPoint (so that it can't be optimized by the compiler to thisJoinPointStaticPart), the JoinPoint object is currently always created before entering the advice body - even if the JoinPoint object would never actually be accessed (because of a test within the advice for example). Since a) thisJoinPoint is often used in tracing applications b) tracing applications tend to be very pervasive, c) they must have low overhead when tracing is disabled, and d) creation of thisJoinPoint objects is expensive (v. expensive compared to just testing a flag) it would be nice if there was a way to create JoinPoint objects lazily on first actual reference within the advice body.
|
resolved fixed
|
0c83343
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-24T02:28:54Z
| 2003-12-04T17:46:40Z
|
runtime/src/org/aspectj/runtime/reflect/Factory.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.reflect;
import org.aspectj.lang.*;
import org.aspectj.lang.reflect.*;
public final class Factory {
Class lexicalClass;
ClassLoader lookupClassLoader;
String filename;
public Factory(String filename, Class lexicalClass) {
//System.out.println("making
this.filename = filename;
this.lexicalClass = lexicalClass;
lookupClassLoader = lexicalClass.getClassLoader();
}
public JoinPoint.StaticPart makeSJP(String kind, Signature sig, SourceLocation loc) {
return new JoinPointImpl.StaticPartImpl(kind, sig, loc);
}
public JoinPoint.StaticPart makeSJP(String kind, Signature sig, int l, int c) {
return new JoinPointImpl.StaticPartImpl(kind, sig, makeSourceLoc(l, c));
}
public JoinPoint.StaticPart makeSJP(String kind, Signature sig, int l) {
return new JoinPointImpl.StaticPartImpl(kind, sig, makeSourceLoc(l, -1));
}
public static JoinPoint makeJP(JoinPoint.StaticPart staticPart,
Object _this, Object target, Object[] args)
{
return new JoinPointImpl(staticPart, _this, target, args);
}
public MethodSignature makeMethodSig(String stringRep) {
MethodSignatureImpl ret = new MethodSignatureImpl(stringRep);
ret.setLookupClassLoader(lookupClassLoader);
return ret;
}
public ConstructorSignature makeConstructorSig(String stringRep) {
ConstructorSignatureImpl ret = new ConstructorSignatureImpl(stringRep);
ret.setLookupClassLoader(lookupClassLoader);
return ret;
}
public FieldSignature makeFieldSig(String stringRep) {
FieldSignatureImpl ret = new FieldSignatureImpl(stringRep);
ret.setLookupClassLoader(lookupClassLoader);
return ret;
}
public AdviceSignature makeAdviceSig(String stringRep) {
AdviceSignatureImpl ret = new AdviceSignatureImpl(stringRep);
ret.setLookupClassLoader(lookupClassLoader);
return ret;
}
public InitializerSignature makeInitializerSig(String stringRep) {
InitializerSignatureImpl ret = new InitializerSignatureImpl(stringRep);
ret.setLookupClassLoader(lookupClassLoader);
return ret;
}
public CatchClauseSignature makeCatchClauseSig(String stringRep) {
CatchClauseSignatureImpl ret = new CatchClauseSignatureImpl(stringRep);
ret.setLookupClassLoader(lookupClassLoader);
return ret;
}
public SourceLocation makeSourceLoc(int line, int col)
{
return new SourceLocationImpl(lexicalClass, this.filename, line, col);
}
}
|
48,091
|
Bug 48091 Lazy instantiation of thisJoinPoint
|
In cases where the body of advice refers to a non-statically evaluable portion of thisJoinPoint (so that it can't be optimized by the compiler to thisJoinPointStaticPart), the JoinPoint object is currently always created before entering the advice body - even if the JoinPoint object would never actually be accessed (because of a test within the advice for example). Since a) thisJoinPoint is often used in tracing applications b) tracing applications tend to be very pervasive, c) they must have low overhead when tracing is disabled, and d) creation of thisJoinPoint objects is expensive (v. expensive compared to just testing a flag) it would be nice if there was a way to create JoinPoint objects lazily on first actual reference within the advice body.
|
resolved fixed
|
0c83343
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-24T02:28:54Z
| 2003-12-04T17:46:40Z
|
weaver/src/org/aspectj/weaver/Lint.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
public class Lint {
/* private */ Map kinds = new HashMap();
/* private */ World world;
public final Kind invalidAbsoluteTypeName =
new Kind("invalidAbsoluteTypeName", "no match for this type name: {0}");
public final Kind invalidWildcardTypeName =
new Kind("invalidWildcardTypeName", "no match for this type pattern: {0}");
public final Kind unresolvableMember =
new Kind("unresolvableMember", "can not resolve this member: {0}");
public final Kind typeNotExposedToWeaver =
new Kind("typeNotExposedToWeaver", "this affected type is not exposed to the weaver: {0}");
public final Kind shadowNotInStructure =
new Kind("shadowNotInStructure", "the shadow for this join point is not exposed in the structure model: {0}");
public final Kind unmatchedSuperTypeInCall =
new Kind("unmatchedSuperTypeInCall", "does not match because declaring type is {0}, if match desired use target({1})");
public Lint(World world) {
this.world = world;
}
public void setAll(String messageKind) {
setAll(getMessageKind(messageKind));
}
private void setAll(IMessage.Kind messageKind) {
for (Iterator i = kinds.values().iterator(); i.hasNext(); ) {
Kind kind = (Kind)i.next();
kind.setKind(messageKind);
}
}
public void setFromProperties(File file) {
try {
InputStream s = new FileInputStream(file);
setFromProperties(s);
} catch (IOException ioe) {
MessageUtil.error(world.getMessageHandler(), "problem loading Xlint properties file: " +
file.getPath() + ", " + ioe.getMessage());
}
}
public void loadDefaultProperties() {
InputStream s = getClass().getResourceAsStream("XlintDefault.properties");
if (s == null) {
MessageUtil.warn(world.getMessageHandler(), "couldn't load XlintDefault.properties");
return;
}
try {
setFromProperties(s);
} catch (IOException ioe) {
MessageUtil.error(world.getMessageHandler(), "problem loading XlintDefault.properties, " +
ioe.getMessage());
}
}
private void setFromProperties(InputStream s) throws IOException {
Properties p = new Properties();
p.load(s);
setFromProperties(p);
}
public void setFromProperties(Properties properties) {
for (Iterator i = properties.entrySet().iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry)i.next();
Kind kind = (Kind)kinds.get(entry.getKey());
if (kind == null) {
MessageUtil.error(world.getMessageHandler(), "invalid Xlint key: " + entry.getKey());
} else {
kind.setKind(getMessageKind((String)entry.getValue()));
}
}
}
private IMessage.Kind getMessageKind(String v) {
if (v.equals("ignore")) return null;
else if (v.equals("warning")) return IMessage.WARNING;
else if (v.equals("error")) return IMessage.ERROR;
MessageUtil.error(world.getMessageHandler(),
"invalid Xlint message kind (must be one of ignore, warning, error): " + v);
return null;
}
public class Kind {
private String name;
private String message;
private IMessage.Kind kind = IMessage.WARNING;
public Kind(String name, String message) {
this.name = name;
this.message = message;
kinds.put(this.name, this);
}
public boolean isEnabled() {
return kind != null;
}
public IMessage.Kind getKind() {
return kind;
}
public void setKind(IMessage.Kind kind) {
this.kind = kind;
}
public void signal(String info, ISourceLocation location) {
if (kind == null) return;
String text = MessageFormat.format(message, new Object[] {info} );
text += " [Xlint:" + name + "]";
world.getMessageHandler().handleMessage(new Message(text, kind, null, location));
}
public void signal(String[] infos, ISourceLocation location, ISourceLocation[] extraLocations) {
if (kind == null) return;
String text = MessageFormat.format(message, infos );
text += " [Xlint:" + name + "]";
world.getMessageHandler().handleMessage(
new Message(text, "", kind, location, null, extraLocations));
}
}
}
|
48,091
|
Bug 48091 Lazy instantiation of thisJoinPoint
|
In cases where the body of advice refers to a non-statically evaluable portion of thisJoinPoint (so that it can't be optimized by the compiler to thisJoinPointStaticPart), the JoinPoint object is currently always created before entering the advice body - even if the JoinPoint object would never actually be accessed (because of a test within the advice for example). Since a) thisJoinPoint is often used in tracing applications b) tracing applications tend to be very pervasive, c) they must have low overhead when tracing is disabled, and d) creation of thisJoinPoint objects is expensive (v. expensive compared to just testing a flag) it would be nice if there was a way to create JoinPoint objects lazily on first actual reference within the advice body.
|
resolved fixed
|
0c83343
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-24T02:28:54Z
| 2003-12-04T17:46:40Z
|
weaver/src/org/aspectj/weaver/World.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.asm.IHierarchy;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.weaver.patterns.DeclarePrecedence;
import org.aspectj.weaver.patterns.Pointcut;
public abstract class World {
protected IMessageHandler messageHandler = IMessageHandler.SYSTEM_ERR;
protected ICrossReferenceHandler xrefHandler = null;
protected Map typeMap = new HashMap(); // Signature to ResolvedType
protected CrosscuttingMembersSet crosscuttingMembersSet = new CrosscuttingMembersSet(this);
protected IHierarchy model = null;
protected Lint lint = new Lint(this);
protected boolean XnoInline;
protected World() {
super();
typeMap.put("B", ResolvedTypeX.BYTE);
typeMap.put("S", ResolvedTypeX.SHORT);
typeMap.put("I", ResolvedTypeX.INT);
typeMap.put("J", ResolvedTypeX.LONG);
typeMap.put("F", ResolvedTypeX.FLOAT);
typeMap.put("D", ResolvedTypeX.DOUBLE);
typeMap.put("C", ResolvedTypeX.CHAR);
typeMap.put("Z", ResolvedTypeX.BOOLEAN);
typeMap.put("V", ResolvedTypeX.VOID);
}
public ResolvedTypeX[] resolve(TypeX[] types) {
int len = types.length;
ResolvedTypeX[] ret = new ResolvedTypeX[len];
for (int i=0; i<len; i++) {
ret[i] = resolve(types[i]);
}
return ret;
}
public ResolvedTypeX resolve(TypeX ty) {
return resolve(ty, false);
}
public ResolvedTypeX resolve(TypeX ty, boolean allowMissing) {
//System.out.println("resolve: " + ty + " world " + typeMap.keySet());
String signature = ty.getSignature();
ResolvedTypeX ret = (ResolvedTypeX)typeMap.get(signature);
if (ret != null) return ret;
if (ty.isArray()) {
ret = new ResolvedTypeX.Array(signature, this, resolve(ty.getComponentType(), allowMissing));
} else {
ret = resolveObjectType(ty);
if (!allowMissing && ret == ResolvedTypeX.MISSING) {
//Thread.currentThread().dumpStack();
MessageUtil.error(messageHandler, "can't find type " + ty.getName());
// + " on classpath " + classPath);
}
}
//System.out.println("ret: " + ret);
typeMap.put(signature, ret);
return ret;
}
//XXX helper method might be bad
public ResolvedTypeX resolve(String name) {
return resolve(TypeX.forName(name));
}
protected final ResolvedTypeX resolveObjectType(TypeX ty) {
ResolvedTypeX.Name name = new ResolvedTypeX.Name(ty.getSignature(), this);
ResolvedTypeX.ConcreteName concreteName = resolveObjectType(name);
if (concreteName == null) return ResolvedTypeX.MISSING;
name.setDelegate(concreteName);
return name;
}
protected abstract ResolvedTypeX.ConcreteName resolveObjectType(ResolvedTypeX.Name ty);
protected final boolean isCoerceableFrom(TypeX type, TypeX other) {
return resolve(type).isCoerceableFrom(other);
}
protected final boolean isAssignableFrom(TypeX type, TypeX other) {
return resolve(type).isAssignableFrom(other);
}
public boolean needsNoConversionFrom(TypeX type, TypeX other) {
return resolve(type).needsNoConversionFrom(other);
}
protected final boolean isInterface(TypeX type) {
return resolve(type).isInterface();
}
protected final ResolvedTypeX getSuperclass(TypeX type) {
return resolve(type).getSuperclass();
}
protected final TypeX[] getDeclaredInterfaces(TypeX type) {
return resolve(type).getDeclaredInterfaces();
}
protected final int getModifiers(TypeX type) {
return resolve(type).getModifiers();
}
protected final ResolvedMember[] getDeclaredFields(TypeX type) {
return resolve(type).getDeclaredFields();
}
protected final ResolvedMember[] getDeclaredMethods(TypeX type) {
return resolve(type).getDeclaredMethods();
}
protected final ResolvedMember[] getDeclaredPointcuts(TypeX type) {
return resolve(type).getDeclaredPointcuts();
}
// ---- members
// XXX should we worry about dealing with context and looking up access?
public ResolvedMember resolve(Member member) {
ResolvedTypeX declaring = member.getDeclaringType().resolve(this);
ResolvedMember ret;
if (member.getKind() == Member.FIELD) {
ret = declaring.lookupField(member);
} else {
ret = declaring.lookupMethod(member);
}
if (ret != null) return ret;
return declaring.lookupSyntheticMember(member);
}
protected int getModifiers(Member member) {
ResolvedMember r = resolve(member);
if (r == null) throw new BCException("bad resolve of " + member);
return r.getModifiers();
}
protected String[] getParameterNames(Member member) {
return resolve(member).getParameterNames();
}
protected TypeX[] getExceptions(Member member) {
return resolve(member).getExceptions();
}
// ---- pointcuts
public ResolvedPointcutDefinition findPointcut(TypeX typeX, String name) {
throw new RuntimeException("not implemented yet");
}
/**
* Get the shadow mungers of this world.
*
* @return a list of {@link IShadowMunger}s appropriate for this world.
*/
//public abstract List getShadowMungers();
// ---- empty world
public static final World EMPTY = new World() {
public List getShadowMungers() { return Collections.EMPTY_LIST; }
public ResolvedTypeX.ConcreteName resolveObjectType(ResolvedTypeX.Name ty) {
return null;
}
public Advice concreteAdvice(AjAttribute.AdviceAttribute attribute, Pointcut p, Member m) {
throw new RuntimeException("unimplemented");
}
public ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedTypeX aspectType) {
throw new RuntimeException("unimplemented");
}
};
public abstract Advice concreteAdvice(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature);
public final Advice concreteAdvice(
AdviceKind kind,
Pointcut p,
Member signature,
int extraParameterFlags,
IHasSourceLocation loc)
{
AjAttribute.AdviceAttribute attribute =
new AjAttribute.AdviceAttribute(kind, p, extraParameterFlags, loc.getStart(), loc.getEnd(), loc.getSourceContext());
return concreteAdvice(attribute, p, signature);
}
public ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField) {
throw new RuntimeException("unimplemented");
}
public abstract ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedTypeX aspectType);
/**
* Nobody should hold onto a copy of this message handler, or setMessageHandler won't
* work right.
*/
public IMessageHandler getMessageHandler() {
return messageHandler;
}
public void setMessageHandler(IMessageHandler messageHandler) {
this.messageHandler = messageHandler;
}
public void setXRefHandler(ICrossReferenceHandler xrefHandler) {
this.xrefHandler = xrefHandler;
}
public void showMessage(
Kind kind,
String message,
ISourceLocation loc1,
ISourceLocation loc2)
{
if (loc1 != null) {
messageHandler.handleMessage(new Message(message, kind, null, loc1));
if (loc2 != null) {
messageHandler.handleMessage(new Message(message, kind, null, loc2));
}
} else {
messageHandler.handleMessage(new Message(message, kind, null, loc2));
}
}
// public void addDeclare(ResolvedTypeX onType, Declare declare, boolean forWeaving) {
// // this is not extensible, oh well
// if (declare instanceof DeclareErrorOrWarning) {
// ShadowMunger m = new Checker((DeclareErrorOrWarning)declare);
// onType.addShadowMunger(m);
// } else if (declare instanceof DeclareDominates) {
// declareDominates.add(declare);
// } else if (declare instanceof DeclareParents) {
// declareParents.add(declare);
// } else if (declare instanceof DeclareSoft) {
// DeclareSoft d = (DeclareSoft)declare;
// declareSoft.add(d);
// if (forWeaving) {
// ShadowMunger m = Advice.makeSoftener(this, d.getPointcut().concretize(onType, 0), d.getException());
// onType.addShadowMunger(m);
// }
// } else {
// throw new RuntimeException("unimplemented");
// }
// }
/**
* Same signature as org.aspectj.util.PartialOrder.PartialComparable.compareTo
*/
public int compareByDominates(ResolvedTypeX aspect1, ResolvedTypeX aspect2) {
//System.out.println("dom compare: " + aspect1 + " with " + aspect2);
//System.out.println(crosscuttingMembersSet.getDeclareDominates());
//??? We probably want to cache this result. This is order N where N is the
//??? number of dominates declares in the whole system.
//??? This method can be called a large number of times.
int order = 0;
for (Iterator i = crosscuttingMembersSet.getDeclareDominates().iterator(); i.hasNext(); ) {
DeclarePrecedence d = (DeclarePrecedence)i.next();
int thisOrder = d.compare(aspect1, aspect2);
//System.out.println("comparing: " + thisOrder + ": " + d);
if (thisOrder != 0) {
if (order != 0 && order != thisOrder) {
throw new BCException("conflicting dominates orders");
} else {
order = thisOrder;
}
}
}
return order;
}
public int comparePrecedence(ResolvedTypeX aspect1, ResolvedTypeX aspect2) {
//System.err.println("compare precedence " + aspect1 + ", " + aspect2);
if (aspect1.equals(aspect2)) return 0;
int ret = compareByDominates(aspect1, aspect2);
if (ret != 0) return ret;
if (aspect1.isAssignableFrom(aspect2)) return -1;
else if (aspect2.isAssignableFrom(aspect1)) return +1;
return 0;
}
public List getDeclareParents() {
return crosscuttingMembersSet.getDeclareParents();
}
public List getDeclareSoft() {
return crosscuttingMembersSet.getDeclareSofts();
}
public CrosscuttingMembersSet getCrosscuttingMembersSet() {
return crosscuttingMembersSet;
}
public IHierarchy getModel() {
return model;
}
public void setModel(IHierarchy model) {
this.model = model;
}
public Lint getLint() {
return lint;
}
public void setLint(Lint lint) {
this.lint = lint;
}
public boolean isXnoInline() {
return XnoInline;
}
public void setXnoInline(boolean xnoInline) {
XnoInline = xnoInline;
}
public ResolvedTypeX.Name lookupOrCreateName(TypeX ty) {
String signature = ty.getSignature();
ResolvedTypeX.Name ret = (ResolvedTypeX.Name)typeMap.get(signature);
if (ret == null) {
ret = new ResolvedTypeX.Name(signature, this);
typeMap.put(signature, ret);
}
return ret;
}
}
|
48,091
|
Bug 48091 Lazy instantiation of thisJoinPoint
|
In cases where the body of advice refers to a non-statically evaluable portion of thisJoinPoint (so that it can't be optimized by the compiler to thisJoinPointStaticPart), the JoinPoint object is currently always created before entering the advice body - even if the JoinPoint object would never actually be accessed (because of a test within the advice for example). Since a) thisJoinPoint is often used in tracing applications b) tracing applications tend to be very pervasive, c) they must have low overhead when tracing is disabled, and d) creation of thisJoinPoint objects is expensive (v. expensive compared to just testing a flag) it would be nice if there was a way to create JoinPoint objects lazily on first actual reference within the advice body.
|
resolved fixed
|
0c83343
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-24T02:28:54Z
| 2003-12-04T17:46:40Z
|
weaver/src/org/aspectj/weaver/bcel/BcelAdvice.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.util.*;
import java.util.Collection;
import java.util.Collections;
import org.apache.bcel.generic.*;
import org.aspectj.weaver.*;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
import org.aspectj.weaver.patterns.*;
/**
* Advice implemented for bcel.
*
* @author Erik Hilsdale
* @author Jim Hugunin
*/
public class BcelAdvice extends Advice {
private Test pointcutTest;
private ExposedState exposedState;
public BcelAdvice(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature,
ResolvedTypeX concreteAspect)
{
super(attribute, pointcut, signature);
this.concreteAspect = concreteAspect;
}
// !!! must only be used for testing
public BcelAdvice(AdviceKind kind, Pointcut pointcut, Member signature,
int extraArgumentFlags,
int start, int end, ISourceContext sourceContext, ResolvedTypeX concreteAspect)
{
this(new AjAttribute.AdviceAttribute(kind, pointcut, extraArgumentFlags, start, end, sourceContext),
pointcut, signature, concreteAspect);
thrownExceptions = Collections.EMPTY_LIST; //!!! interaction with unit tests
}
// ---- implementations of ShadowMunger's methods
public void specializeOn(Shadow shadow) {
if (getKind() == AdviceKind.Around) {
((BcelShadow)shadow).initializeForAroundClosure();
}
//XXX this case is just here for supporting lazy test code
if (getKind() == null) {
exposedState = new ExposedState(0);
return;
}
if (getKind().isPerEntry()) {
exposedState = new ExposedState(0);
} else if (getKind().isCflow()) {
exposedState = new ExposedState(nFreeVars);
} else if (getSignature() != null) {
exposedState = new ExposedState(getSignature());
} else {
exposedState = new ExposedState(0);
return; //XXX this case is just here for supporting lazy test code
}
pointcutTest = getPointcut().findResidue(shadow, exposedState);
// these initializations won't be performed by findResidue, but need to be
// so that the joinpoint is primed for weaving
if (getKind() == AdviceKind.PerThisEntry) {
shadow.getThisVar();
} else if (getKind() == AdviceKind.PerTargetEntry) {
shadow.getTargetVar();
}
// make sure thisJoinPoint parameters are initialized
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
((BcelShadow)shadow).getThisJoinPointStaticPartVar();
}
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
((BcelShadow)shadow).getThisJoinPointVar();
}
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
((BcelShadow)shadow).getThisEnclosingJoinPointStaticPartVar();
}
}
private boolean canInline(Shadow s) {
if (attribute.isProceedInInners()) return false;
//XXX this guard seems to only be needed for bad test cases
if (concreteAspect == null || concreteAspect == ResolvedTypeX.MISSING) return false;
if (concreteAspect.getWorld().isXnoInline()) return false;
//System.err.println("isWoven? " + ((BcelObjectType)concreteAspect).getLazyClassGen().getWeaverState());
return BcelWorld.getBcelObjectType(concreteAspect).getLazyClassGen().isWoven();
}
public void implementOn(Shadow s) {
BcelShadow shadow = (BcelShadow) s;
if (getKind() == AdviceKind.Before) {
shadow.weaveBefore(this);
} else if (getKind() == AdviceKind.AfterReturning) {
shadow.weaveAfterReturning(this);
} else if (getKind() == AdviceKind.AfterThrowing) {
TypeX catchType =
hasExtraParameter()
? getExtraParameterType()
: TypeX.THROWABLE;
shadow.weaveAfterThrowing(this, catchType);
} else if (getKind() == AdviceKind.After) {
shadow.weaveAfter(this);
} else if (getKind() == AdviceKind.Around) {
if (!canInline(s)) {
shadow.weaveAroundClosure(this, hasDynamicTests());
} else {
shadow.weaveAroundInline(this, hasDynamicTests());
}
} else if (getKind() == AdviceKind.InterInitializer) {
shadow.weaveAfterReturning(this);
} else if (getKind().isCflow()) {
shadow.weaveCflowEntry(this, getSignature());
} else if (getKind() == AdviceKind.PerThisEntry) {
shadow.weavePerObjectEntry(this, (BcelVar)shadow.getThisVar());
} else if (getKind() == AdviceKind.PerTargetEntry) {
shadow.weavePerObjectEntry(this, (BcelVar)shadow.getTargetVar());
} else if (getKind() == AdviceKind.Softener) {
shadow.weaveSoftener(this, ((ExactTypePattern)exceptionType).getType());
} else {
throw new BCException("unimplemented kind: " + getKind());
}
}
// ---- implementations
private Collection collectCheckedExceptions(TypeX[] excs) {
if (excs == null || excs.length == 0) return Collections.EMPTY_LIST;
Collection ret = new ArrayList();
World world = concreteAspect.getWorld();
ResolvedTypeX runtimeException = world.resolve(TypeX.RUNTIME_EXCEPTION);
ResolvedTypeX error = world.resolve(TypeX.ERROR);
for (int i=0, len=excs.length; i < len; i++) {
ResolvedTypeX t = world.resolve(excs[i]);
if (!(runtimeException.isAssignableFrom(t) || error.isAssignableFrom(t))) {
ret.add(t);
}
}
return ret;
}
private Collection thrownExceptions = null;
public Collection getThrownExceptions() {
if (thrownExceptions == null) {
//??? can we really lump in Around here, how does this interact with Throwable
if (concreteAspect != null && concreteAspect.getWorld() != null && // null tests for test harness
(getKind().isAfter() || getKind() == AdviceKind.Before || getKind() == AdviceKind.Around))
{
World world = concreteAspect.getWorld();
ResolvedMember m = world.resolve(signature);
if (m == null) {
thrownExceptions = Collections.EMPTY_LIST;
} else {
thrownExceptions = collectCheckedExceptions(m.getExceptions());
}
} else {
thrownExceptions = Collections.EMPTY_LIST;
}
}
return thrownExceptions;
}
// only call me after prepare has been called
public boolean hasDynamicTests() {
// if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) {
// TypeX extraParameterType = getExtraParameterType();
// if (! extraParameterType.equals(TypeX.OBJECT)
// && ! extraParameterType.isPrimitive())
// return true;
// }
return pointcutTest != null &&
!(pointcutTest == Literal.TRUE);// || pointcutTest == Literal.NO_TEST);
}
/**
* get the instruction list for the really simple version of this advice.
* Is broken apart
* for other advice, but if you want it in one block, this is the method to call.
*
* @param s The shadow around which these instructions will eventually live.
* @param extraArgVar The var that will hold the return value or thrown exception
* for afterX advice
* @param ifNoAdvice The instructionHandle to jump to if the dynamic
* tests for this munger fails.
*/
InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice)
{
BcelShadow shadow = (BcelShadow) s;
InstructionFactory fact = shadow.getFactory();
BcelWorld world = shadow.getWorld();
InstructionList il = new InstructionList();
// we test to see if we have the right kind of thing...
// after throwing does this just by the exception mechanism.
if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) {
TypeX extraParameterType = getExtraParameterType();
if (! extraParameterType.equals(TypeX.OBJECT)
&& ! extraParameterType.isPrimitive()) {
il.append(
BcelRenderer.renderTest(
fact,
world,
Test.makeInstanceof(
extraArgVar, getExtraParameterType().resolve(world)),
null,
ifNoAdvice,
null));
}
}
il.append(getAdviceArgSetup(shadow, extraArgVar, null));
il.append(getNonTestAdviceInstructions(shadow));
InstructionHandle ifYesAdvice = il.getStart();
il.insert(getTestInstructions(shadow, ifYesAdvice, ifNoAdvice, ifYesAdvice));
return il;
}
public InstructionList getAdviceArgSetup(
BcelShadow shadow,
BcelVar extraVar,
InstructionList closureInstantiation)
{
InstructionFactory fact = shadow.getFactory();
BcelWorld world = shadow.getWorld();
InstructionList il = new InstructionList();
// if (targetAspectField != null) {
// il.append(fact.createFieldAccess(
// targetAspectField.getDeclaringType().getName(),
// targetAspectField.getName(),
// BcelWorld.makeBcelType(targetAspectField.getType()),
// Constants.GETSTATIC));
// }
//
//System.err.println("BcelAdvice: " + exposedState);
if (exposedState.getAspectInstance() != null) {
il.append(
BcelRenderer.renderExpr(fact, world, exposedState.getAspectInstance()));
}
for (int i = 0, len = exposedState.size(); i < len; i++) {
BcelVar v = (BcelVar) exposedState.get(i);
if (v == null) continue;
TypeX desiredTy = getSignature().getParameterTypes()[i];
v.appendLoadAndConvert(il, fact, desiredTy.resolve(world));
}
if (getKind() == AdviceKind.Around) {
il.append(closureInstantiation);
} else if (hasExtraParameter()) {
extraVar.appendLoadAndConvert(
il,
fact,
getExtraParameterType().resolve(world));
}
// handle thisJoinPoint parameters
// these need to be in that same order as parameters in
// org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
shadow.getThisJoinPointBcelVar().appendLoad(il, fact);
}
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
return il;
}
public InstructionList getNonTestAdviceInstructions(BcelShadow shadow) {
return new InstructionList(
Utility.createInvoke(shadow.getFactory(), shadow.getWorld(), getSignature()));
}
public InstructionList getTestInstructions(
BcelShadow shadow,
InstructionHandle sk,
InstructionHandle fk,
InstructionHandle next)
{
//System.err.println("test: " + pointcutTest);
return BcelRenderer.renderTest(
shadow.getFactory(),
shadow.getWorld(),
pointcutTest,
sk,
fk,
next);
}
public int compareTo(Object other) {
if (!(other instanceof BcelAdvice)) return 0;
BcelAdvice o = (BcelAdvice)other;
//System.err.println("compareTo: " + this + ", " + o);
if (kind.getPrecedence() != o.kind.getPrecedence()) {
if (kind.getPrecedence() > o.kind.getPrecedence()) return +1;
else return -1;
}
if (kind.isCflow()) {
// System.err.println("sort: " + this + " innerCflowEntries " + innerCflowEntries);
// System.err.println(" " + o + " innerCflowEntries " + o.innerCflowEntries);
boolean isBelow = (kind == AdviceKind.CflowBelowEntry);
if (this.innerCflowEntries.contains(o)) return isBelow ? +1 : -1;
else if (o.innerCflowEntries.contains(this)) return isBelow ? -1 : +1;
else return 0;
}
if (kind.isPerEntry() || kind == AdviceKind.Softener) {
return 0;
}
//System.out.println("compare: " + this + " with " + other);
World world = concreteAspect.getWorld();
int ret =
concreteAspect.getWorld().compareByDominates(
concreteAspect,
o.concreteAspect);
if (ret != 0) return ret;
ResolvedTypeX declaringAspect = getDeclaringAspect().resolve(world);
ResolvedTypeX o_declaringAspect = o.getDeclaringAspect().resolve(world);
if (declaringAspect == o_declaringAspect) {
if (kind.isAfter() || o.kind.isAfter()) {
return this.getStart() < o.getStart() ? -1: +1;
} else {
return this.getStart()< o.getStart() ? +1: -1;
}
} else if (declaringAspect.isAssignableFrom(o_declaringAspect)) {
return -1;
} else if (o_declaringAspect.isAssignableFrom(declaringAspect)) {
return +1;
} else {
return 0;
}
}
public BcelVar[] getExposedStateAsBcelVars() {
//System.out.println("vars: " + Arrays.asList(exposedState.vars));
if (exposedState == null) return BcelVar.NONE;
int len = exposedState.vars.length;
BcelVar[] ret = new BcelVar[len];
for (int i=0; i < len; i++) {
ret[i] = (BcelVar)exposedState.vars[i];
}
return ret; //(BcelVar[]) exposedState.vars;
}
}
|
48,091
|
Bug 48091 Lazy instantiation of thisJoinPoint
|
In cases where the body of advice refers to a non-statically evaluable portion of thisJoinPoint (so that it can't be optimized by the compiler to thisJoinPointStaticPart), the JoinPoint object is currently always created before entering the advice body - even if the JoinPoint object would never actually be accessed (because of a test within the advice for example). Since a) thisJoinPoint is often used in tracing applications b) tracing applications tend to be very pervasive, c) they must have low overhead when tracing is disabled, and d) creation of thisJoinPoint objects is expensive (v. expensive compared to just testing a flag) it would be nice if there was a way to create JoinPoint objects lazily on first actual reference within the advice body.
|
resolved fixed
|
0c83343
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-24T02:28:54Z
| 2003-12-04T17:46:40Z
|
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.generic.ACONST_NULL;
import org.apache.bcel.generic.ArrayType;
import org.apache.bcel.generic.BranchInstruction;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.DUP;
import org.apache.bcel.generic.DUP_X1;
import org.apache.bcel.generic.FieldInstruction;
import org.apache.bcel.generic.INVOKESPECIAL;
import org.apache.bcel.generic.INVOKESTATIC;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionConstants;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.InstructionTargeter;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.NEW;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.ReturnInstruction;
import org.apache.bcel.generic.SWAP;
import org.apache.bcel.generic.TargetLostException;
import org.apache.bcel.generic.Type;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Var;
/*
* Some fun implementation stuff:
*
* * expressionKind advice is non-execution advice
* * may have a target.
* * if the body is extracted, it will be extracted into
* a static method. The first argument to the static
* method is the target
* * advice may expose a this object, but that's the advice's
* consideration, not ours. This object will NOT be cached in another
* local, but will always come from frame zero.
*
* * non-expressionKind advice is execution advice
* * may have a this.
* * target is same as this, and is exposed that way to advice
* (i.e., target will not be cached, will always come from frame zero)
* * if the body is extracted, it will be extracted into a method
* with same static/dynamic modifier as enclosing method. If non-static,
* target of callback call will be this.
*
* * because of these two facts, the setup of the actual arguments (including
* possible target) callback method is the same for both kinds of advice:
* push the targetVar, if it exists (it will not exist for advice on static
* things), then push all the argVars.
*
* Protected things:
*
* * the above is sufficient for non-expressionKind advice for protected things,
* since the target will always be this.
*
* * For expressionKind things, we have to modify the signature of the callback
* method slightly. For non-static expressionKind things, we modify
* the first argument of the callback method NOT to be the type specified
* by the method/field signature (the owner), but rather we type it to
* the currentlyEnclosing type. We are guaranteed this will be fine,
* since the verifier verifies that the target is a subtype of the currently
* enclosingType.
*
* Worries:
*
* * ConstructorCalls will be weirder than all of these, since they
* supposedly don't have a target (according to AspectJ), but they clearly
* do have a target of sorts, just one that needs to be pushed on the stack,
* dupped, and not touched otherwise until the constructor runs.
*
* @author Jim Hugunin
* @author Erik Hilsdale
*
*/
public class BcelShadow extends Shadow {
private ShadowRange range;
private final BcelWorld world;
private final LazyMethodGen enclosingMethod;
private boolean fallsThrough; //XXX not used anymore
// ---- initialization
/**
* This generates an unassociated shadow, rooted in a particular method but not rooted
* to any particular point in the code. It should be given to a rooted ShadowRange
* in the {@link ShadowRange#associateWithShadow(BcelShadow)} method.
*/
public BcelShadow(
BcelWorld world,
Kind kind,
Member signature,
LazyMethodGen enclosingMethod,
BcelShadow enclosingShadow)
{
super(kind, signature, enclosingShadow);
this.world = world;
this.enclosingMethod = enclosingMethod;
fallsThrough = kind.argsOnStack();
}
// ---- copies all state, including Shadow's mungers...
public BcelShadow copyInto(LazyMethodGen recipient, BcelShadow enclosing) {
BcelShadow s = new BcelShadow(world, getKind(), getSignature(), recipient, enclosing);
List src = mungers;
List dest = s.mungers;
for (Iterator i = src.iterator(); i.hasNext(); ) {
dest.add(i.next());
}
return s;
}
// ---- overridden behaviour
public World getIWorld() {
return world;
}
private void deleteNewAndDup() {
final ConstantPoolGen cpg = getEnclosingClass().getConstantPoolGen();
int depth = 1;
InstructionHandle ih = range.getStart();
while (true) {
Instruction inst = ih.getInstruction();
if (inst instanceof INVOKESPECIAL
&& ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) {
depth++;
} else if (inst instanceof NEW) {
depth--;
if (depth == 0) break;
}
ih = ih.getPrev();
}
// now IH points to the NEW. We're followed by the DUP, and that is followed
// by the actual instruciton we care about.
InstructionHandle newHandle = ih;
InstructionHandle endHandle = newHandle.getNext();
InstructionHandle nextHandle;
if (endHandle.getInstruction() instanceof DUP) {
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else if (endHandle.getInstruction() instanceof DUP_X1) {
InstructionHandle dupHandle = endHandle;
endHandle = endHandle.getNext();
nextHandle = endHandle.getNext();
if (endHandle.getInstruction() instanceof SWAP) {}
else {
// XXX see next XXX comment
throw new RuntimeException("Unhandled kind of new " + endHandle);
}
retargetFrom(newHandle, nextHandle);
retargetFrom(dupHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else {
endHandle = newHandle;
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
// add a POP here... we found a NEW w/o a dup or anything else, so
// we must be in statement context.
getRange().insert(InstructionConstants.POP, Range.OutsideAfter);
}
// assert (dupHandle.getInstruction() instanceof DUP);
try {
range.getBody().delete(newHandle, endHandle);
} catch (TargetLostException e) {
throw new BCException("shouldn't happen");
}
}
private void retargetFrom(InstructionHandle old, InstructionHandle fresh) {
InstructionTargeter[] sources = old.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
sources[i].updateTarget(old, fresh);
}
}
}
protected void prepareForMungers() {
// if we're a constructor call, we need to remove the new:dup or the new:dup_x1:swap,
// and store all our
// arguments on the frame.
// ??? This is a bit of a hack (for the Java langauge). We do this because
// we sometime add code "outsideBefore" when dealing with weaving join points. We only
// do this for exposing state that is on the stack. It turns out to just work for
// everything except for constructor calls and exception handlers. If we were to clean
// this up, every ShadowRange would have three instructionHandle points, the start of
// the arg-setup code, the start of the running code, and the end of the running code.
if (getKind() == ConstructorCall) {
deleteNewAndDup();
initializeArgVars();
} else if (getKind() == ExceptionHandler) {
ShadowRange range = getRange();
InstructionList body = range.getBody();
InstructionHandle start = range.getStart();
InstructionHandle freshIh = body.insert(start, InstructionConstants.NOP);
InstructionTargeter[] targeters = start.getTargeters();
for (int i = 0; i < targeters.length; i++) {
InstructionTargeter t = targeters[i];
if (t instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) t;
er.updateTarget(start, freshIh, body);
}
}
}
// now we ask each munger to request our state
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
munger.specializeOn(this);
}
// If we are an expression kind, we require our target/arguments on the stack
// before we do our actual thing. However, they may have been removed
// from the stack as the shadowMungers have requested state.
// if any of our shadowMungers requested either the arguments or target,
// the munger will have added code
// to pop the target/arguments into temporary variables, represented by
// targetVar and argVars. In such a case, we must make sure to re-push the
// values.
// If we are nonExpressionKind, we don't expect arguments on the stack
// so this is moot. If our argVars happen to be null, then we know that
// no ShadowMunger has squirrelled away our arguments, so they're still
// on the stack.
InstructionFactory fact = getFactory();
if (getKind().argsOnStack() && argVars != null) {
range.insert(
BcelRenderer.renderExprs(fact, world, argVars),
Range.InsideBefore);
if (targetVar != null) {
range.insert(
BcelRenderer.renderExpr(fact, world, targetVar),
Range.InsideBefore);
}
if (getKind() == ConstructorCall) {
range.insert((Instruction) InstructionFactory.createDup(1), Range.InsideBefore);
range.insert(
fact.createNew(
(ObjectType) BcelWorld.makeBcelType(
getSignature().getDeclaringType())),
Range.InsideBefore);
}
}
}
// ---- getters
public ShadowRange getRange() {
return range;
}
public void setRange(ShadowRange range) {
this.range = range;
}
public int getSourceLine() {
if (range == null) {
if (getEnclosingMethod().hasBody()) {
return Utility.getSourceLine(getEnclosingMethod().getBody().getStart());
} else {
return 0;
}
}
int ret = Utility.getSourceLine(range.getStart());
if (ret < 0) return 0;
return ret;
}
// overrides
public TypeX getEnclosingType() {
return getEnclosingClass().getType();
}
public LazyClassGen getEnclosingClass() {
return enclosingMethod.getEnclosingClass();
}
public BcelWorld getWorld() {
return world;
}
// ---- factory methods
public static BcelShadow makeConstructorExecution(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle justBeforeStart)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
ConstructorExecution,
world.makeMethodSignature(enclosingMethod),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, justBeforeStart.getNext()),
Range.genEnd(body));
return s;
}
public static BcelShadow makeStaticInitialization(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
InstructionList body = enclosingMethod.getBody();
// move the start past ajc$preClinit
InstructionHandle clinitStart = body.getStart();
if (clinitStart.getInstruction() instanceof InvokeInstruction) {
InvokeInstruction ii = (InvokeInstruction)clinitStart.getInstruction();
if (ii
.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen())
.equals(NameMangler.AJC_PRE_CLINIT_NAME)) {
clinitStart = clinitStart.getNext();
}
}
InstructionHandle clinitEnd = body.getEnd();
//XXX should move the end before the postClinit, but the return is then tricky...
// if (clinitEnd.getInstruction() instanceof InvokeInstruction) {
// InvokeInstruction ii = (InvokeInstruction)clinitEnd.getInstruction();
// if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen()).equals(NameMangler.AJC_POST_CLINIT_NAME)) {
// clinitEnd = clinitEnd.getPrev();
// }
// }
BcelShadow s =
new BcelShadow(
world,
StaticInitialization,
world.makeMethodSignature(enclosingMethod),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, clinitStart),
Range.genEnd(body, clinitEnd));
return s;
}
/** Make the shadow for an exception handler. Currently makes an empty shadow that
* only allows before advice to be woven into it.
*/
public static BcelShadow makeExceptionHandler(
BcelWorld world,
ExceptionRange exceptionRange,
LazyMethodGen enclosingMethod,
InstructionHandle startOfHandler,
BcelShadow enclosingShadow)
{
InstructionList body = enclosingMethod.getBody();
TypeX catchType = exceptionRange.getCatchType();
TypeX inType = enclosingMethod.getEnclosingClass().getType();
BcelShadow s =
new BcelShadow(
world,
ExceptionHandler,
Member.makeExceptionHandlerSignature(inType, catchType),
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;
}
/** create an init join point associated w/ an interface in the body of a constructor */
public static BcelShadow makeIfaceInitialization(
BcelWorld world,
LazyMethodGen constructor,
BcelShadow ifaceCExecShadow,
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, ifaceCExecShadow.getRange().getStart());
InstructionHandle end = Range.genEnd(body, ifaceCExecShadow.getRange().getEnd());
r.associateWithTargets(start, end);
return s;
}
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)
{
return makeShadowForMethod(world, enclosingMethod, MethodExecution,
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 BcelVar thisJoinPointStaticPartVar = null;
// private BcelVar thisEnclosingJoinPointStaticPartVar = null;
public final Var getThisJoinPointVar() {
return getThisJoinPointBcelVar();
}
public final Var getThisJoinPointStaticPartVar() {
return getThisJoinPointStaticPartBcelVar();
}
public final Var getThisEnclosingJoinPointStaticPartVar() {
return getThisEnclosingJoinPointStaticPartBcelVar();
}
public BcelVar getThisJoinPointBcelVar() {
if (thisJoinPointVar == null) {
thisJoinPointVar = genTempVar(TypeX.forName("org.aspectj.lang.JoinPoint"));
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());
}
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));
il.append(thisJoinPointVar.createStore(fact));
range.insert(il, Range.OutsideBefore);
}
return thisJoinPointVar;
}
public BcelVar getThisJoinPointStaticPartBcelVar() {
if (thisJoinPointStaticPartVar == null) {
Field field = getEnclosingClass().getTjpField(this);
thisJoinPointStaticPartVar =
new BcelFieldRef(
world.resolve(TypeX.forName("org.aspectj.lang.JoinPoint$StaticPart")),
getEnclosingClass().getClassName(),
field.getName());
}
return thisJoinPointStaticPartVar;
}
public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() {
if (enclosingShadow == null) {
// the enclosing of an execution is itself
return getThisJoinPointStaticPartBcelVar();
} else {
return ((BcelShadow)enclosingShadow).getThisJoinPointStaticPartBcelVar();
}
}
//??? need to better understand all the enclosing variants
public Member getEnclosingCodeSignature() {
if (getKind().isEnclosingKind()) {
return getSignature();
} else if (enclosingShadow == null) {
return getEnclosingMethod().getMemberView();
} else {
return enclosingShadow.getSignature();
}
}
private InstructionList makeArgsObjectArray() {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY);
final InstructionList il = new InstructionList();
int alen = getArgCount() ;
il.append(Utility.createConstant(fact, alen));
il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(il, fact);
int stateIndex = 0;
for (int i = 0, len = getArgCount(); i<len; i++) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, (BcelVar)getArgVar(i));
stateIndex++;
}
arrayVar.appendLoad(il, fact);
return il;
}
// ---- initializing var tables
/* initializing this is doesn't do anything, because this
* is protected from side-effects, so we don't need to copy its location
*/
private void initializeThisVar() {
if (thisVar != null) return;
thisVar = new BcelVar(getThisType().resolve(world), 0);
thisVar.setPositionInAroundState(0);
}
public void initializeTargetVar() {
InstructionFactory fact = getFactory();
if (targetVar != null) return;
if (getKind().isTargetSameAsThis()) {
if (hasThis()) initializeThisVar();
targetVar = thisVar;
} else {
initializeArgVars(); // gotta pop off the args before we find the target
TypeX type = getTargetType();
targetVar = genTempVar(type, "ajc$target");
range.insert(targetVar.createStore(fact), Range.OutsideBefore);
targetVar.setPositionInAroundState(hasThis() ? 1 : 0);
}
}
public void initializeArgVars() {
if (argVars != null) return;
InstructionFactory fact = getFactory();
int len = getArgCount();
argVars = new BcelVar[len];
int positionOffset = (hasTarget() ? 1 : 0) +
((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
if (getKind().argsOnStack()) {
// we move backwards because we're popping off the stack
for (int i = len - 1; i >= 0; i--) {
TypeX type = getArgType(i);
BcelVar tmp = genTempVar(type, "ajc$arg" + i);
range.insert(tmp.createStore(getFactory()), Range.OutsideBefore);
int position = i;
position += positionOffset;
tmp.setPositionInAroundState(position);
argVars[i] = tmp;
}
} else {
int index = 0;
if (arg0HoldsThis()) index++;
for (int i = 0; i < len; i++) {
TypeX type = getArgType(i);
BcelVar tmp = genTempVar(type, "ajc$arg" + i);
range.insert(tmp.createCopyFrom(fact, index), Range.OutsideBefore);
argVars[i] = tmp;
int position = i;
position += positionOffset;
// System.out.println("set position: " + tmp + ", " + position + " in " + this);
// System.out.println(" hasThis: " + hasThis() + ", hasTarget: " + hasTarget());
tmp.setPositionInAroundState(position);
index += type.getSize();
}
}
}
public void initializeForAroundClosure() {
initializeArgVars();
if (hasTarget()) initializeTargetVar();
if (hasThis()) initializeThisVar();
// System.out.println("initialized: " + this + " thisVar = " + thisVar);
}
// ---- weave methods
void weaveBefore(BcelAdvice munger) {
range.insert(
munger.getAdviceInstructions(this, null, range.getRealStart()),
Range.InsideBefore);
}
public void weaveAfter(BcelAdvice munger) {
weaveAfterThrowing(munger, TypeX.THROWABLE);
weaveAfterReturning(munger);
}
/**
* We guarantee that the return value is on the top of the stack when
* munger.getAdviceInstructions() will be run
* (Unless we have a void return type in which case there's nothing)
*/
public void weaveAfterReturning(BcelAdvice munger) {
// InstructionFactory fact = getFactory();
List returns = new ArrayList();
Instruction ret = null;
for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
if (ih.getInstruction() instanceof ReturnInstruction) {
returns.add(ih);
ret = Utility.copyInstruction(ih.getInstruction());
}
}
InstructionList retList;
InstructionHandle afterAdvice;
if (ret != null) {
retList = new InstructionList(ret);
afterAdvice = retList.getStart();
} else /* if (munger.hasDynamicTests()) */ {
retList = new InstructionList(InstructionConstants.NOP);
afterAdvice = retList.getStart();
// } else {
// retList = new InstructionList();
// afterAdvice = null;
}
InstructionList advice = new InstructionList();
BcelVar tempVar = null;
if (munger.hasExtraParameter()) {
TypeX tempVarType = getReturnType();
if (tempVarType.equals(ResolvedTypeX.VOID)) {
tempVar = genTempVar(TypeX.OBJECT);
advice.append(InstructionConstants.ACONST_NULL);
tempVar.appendStore(advice, getFactory());
} else {
tempVar = genTempVar(tempVarType);
advice.append(InstructionFactory.createDup(tempVarType.getSize()));
tempVar.appendStore(advice, getFactory());
}
}
advice.append(munger.getAdviceInstructions(this, tempVar, afterAdvice));
if (ret != null) {
InstructionHandle gotoTarget = advice.getStart();
for (Iterator i = returns.iterator(); i.hasNext();) {
InstructionHandle ih = (InstructionHandle) i.next();
Utility.replaceInstruction(
ih,
InstructionFactory.createBranchInstruction(
Constants.GOTO,
gotoTarget),
enclosingMethod);
}
range.append(advice);
range.append(retList);
} else {
range.append(advice);
range.append(retList);
}
}
public void weaveAfterThrowing(BcelAdvice munger, TypeX catchType) {
// a good optimization would be not to generate anything here
// if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
// a shadow, inside me).
if (getRange().getStart().getNext() == getRange().getEnd()) return;
InstructionFactory fact = getFactory();
InstructionList handler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
exceptionVar.appendStore(handler, fact);
InstructionList endHandler = new InstructionList(
exceptionVar.createLoad(fact));
handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart()));
handler.append(endHandler);
handler.append(InstructionConstants.ATHROW);
InstructionHandle handlerStart = handler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = handler.append(InstructionConstants.NOP);
handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
InstructionHandle protectedEnd = handler.getStart();
range.insert(handler, Range.InsideAfter);
enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(),
handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), //???Type.THROWABLE,
// high priority if our args are on the stack
getKind().hasHighPriorityExceptions());
}
//??? this shares a lot of code with the above weaveAfterThrowing
//??? would be nice to abstract that to say things only once
public void weaveSoftener(BcelAdvice munger, TypeX catchType) {
// a good optimization would be not to generate anything here
// if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
// a shadow, inside me).
if (getRange().getStart().getNext() == getRange().getEnd()) return;
InstructionFactory fact = getFactory();
InstructionList handler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
exceptionVar.appendStore(handler, fact);
handler.append(fact.createNew(NameMangler.SOFT_EXCEPTION_TYPE));
handler.append(InstructionFactory.createDup(1));
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createInvoke(NameMangler.SOFT_EXCEPTION_TYPE, "<init>",
Type.VOID, new Type[] { Type.THROWABLE }, Constants.INVOKESPECIAL)); //??? special
handler.append(InstructionConstants.ATHROW);
InstructionHandle handlerStart = handler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = range.getEnd();//handler.append(fact.NOP);
handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
InstructionHandle protectedEnd = handler.getStart();
range.insert(handler, Range.InsideAfter);
enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(),
handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType),
// high priority if our args are on the stack
getKind().hasHighPriorityExceptions());
}
public void weavePerObjectEntry(final BcelAdvice munger, final BcelVar onVar) {
final InstructionFactory fact = getFactory();
InstructionList entryInstructions = new InstructionList();
InstructionList entrySuccessInstructions = new InstructionList();
onVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
Utility.createInvoke(fact, world,
AjcMemberMaker.perObjectBind(munger.getConcreteAspect())));
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveCflowEntry(final BcelAdvice munger, final Member cflowStackField) {
final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry ||
munger.getKind() == AdviceKind.PerCflowEntry;
final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionFactory fact = getFactory();
final BcelVar testResult = genTempVar(ResolvedTypeX.BOOLEAN);
InstructionList entryInstructions = new InstructionList();
{
InstructionList entrySuccessInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
entryInstructions.append(Utility.createConstant(fact, 0));
testResult.appendStore(entryInstructions, fact);
entrySuccessInstructions.append(Utility.createConstant(fact, 1));
testResult.appendStore(entrySuccessInstructions, fact);
}
if (isPer) {
entrySuccessInstructions.append(
fact.createInvoke(munger.getConcreteAspect().getName(),
NameMangler.PERCFLOW_PUSH_METHOD,
Type.VOID,
new Type[] { },
Constants.INVOKESTATIC));
} else {
BcelVar[] cflowStateVars = munger.getExposedStateAsBcelVars();
BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY);
int alen = cflowStateVars.length;
entrySuccessInstructions.append(Utility.createConstant(fact, alen));
entrySuccessInstructions.append(
(Instruction) fact.createNewArray(Type.OBJECT, (short) 1));
arrayVar.appendStore(entrySuccessInstructions, fact);
for (int i = 0; i < alen; i++) {
arrayVar.appendConvertableArrayStore(
entrySuccessInstructions,
fact,
i,
cflowStateVars[i]);
}
entrySuccessInstructions.append(
Utility.createGet(fact, cflowStackField));
arrayVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID,
new Type[] { objectArrayType },
Constants.INVOKEVIRTUAL));
}
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
}
// this is the same for both per and non-per
weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) {
public InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice) {
InstructionList exitInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
testResult.appendLoad(exitInstructions, fact);
exitInstructions.append(
InstructionFactory.createBranchInstruction(
Constants.IFEQ,
ifNoAdvice));
}
exitInstructions.append(Utility.createGet(fact, cflowStackField));
exitInstructions
.append(
fact
.createInvoke(
NameMangler.CFLOW_STACK_TYPE,
"pop",
Type.VOID,
new Type[] {
}, Constants.INVOKEVIRTUAL));
return exitInstructions;
}
});
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveAroundInline(
BcelAdvice munger,
boolean hasDynamicTest)
{
/* Implementation notes:
*
* AroundInline still extracts the instructions of the original shadow into
* an extracted method. This allows inlining of even that advice that doesn't
* call proceed or calls proceed more than once.
*
* It extracts the instructions of the original shadow into a method.
*
* Then it extracts the instructions of the advice into a new method defined on
* this enclosing class. This new method can then be specialized as below.
*
* Then it searches in the instructions of the advice for any call to the
* proceed method.
*
* At such a call, there is stuff on the stack representing the arguments to
* proceed. Pop these into the frame.
*
* Now build the stack for the call to the extracted method, taking values
* either from the join point state or from the new frame locs from proceed.
* Now call the extracted method. The right return value should be on the
* stack, so no cast is necessary.
*
* If only one call to proceed is made, we can re-inline the original shadow.
* We are not doing that presently.
*
* If the body of the advice can be determined to not alter the stack, or if
* this shadow doesn't care about the stack, i.e. method-execution, then the
* new method for the advice can also be re-lined. We are not doing that
* presently.
*/
// !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...);
Member mungerSig = munger.getSignature();
ResolvedTypeX declaringType = world.resolve(mungerSig.getDeclaringType());
//??? might want some checks here to give better errors
BcelObjectType ot = BcelWorld.getBcelObjectType(declaringType);
LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig);
if (!adviceMethod.getCanInline())
{
weaveAroundClosure(munger, hasDynamicTest);
return;
}
// We can't inline around methods if they have around advice on them, this
// is because the weaving will extract the body and hence the proceed call.
//??? should consider optimizations to recognize simple cases that don't require body extraction
enclosingMethod.setCanInline(false);
// start by exposing various useful things into the frame
final InstructionFactory fact = getFactory();
// now generate the aroundBody method
LazyMethodGen extractedMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()));
// 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.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()));
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars();
String closureClassName =
NameMangler.makeClosureClassName(
getEnclosingClass().getType(),
getEnclosingClass().getNewGeneratedNameTag());
Member constructorSig = new Member(Member.CONSTRUCTOR,
TypeX.forName(closureClassName), 0, "<init>",
"([Ljava/lang/Object;)V");
BcelVar closureHolder = null;
// This is not being used currently since getKind() == preinitializaiton
// cannot happen in around advice
if (getKind() == PreInitialization) {
closureHolder = genTempVar(AjcMemberMaker.AROUND_CLOSURE_TYPE);
}
InstructionList closureInstantiation =
makeClosureInstantiation(constructorSig, closureHolder);
/*LazyMethodGen constructor = */
makeClosureClassAndReturnConstructor(
closureClassName,
callbackMethod,
makeProceedArgumentMap(adviceVars)
);
InstructionList returnConversionCode;
if (getKind() == PreInitialization) {
returnConversionCode = new InstructionList();
BcelVar stateTempVar = genTempVar(TypeX.OBJECTARRAY);
closureHolder.appendLoad(returnConversionCode, fact);
returnConversionCode.append(
Utility.createInvoke(
fact,
world,
AjcMemberMaker.aroundClosurePreInitializationGetter()));
stateTempVar.appendStore(returnConversionCode, fact);
Type[] stateTypes = getSuperConstructorParameterTypes();
returnConversionCode.append(InstructionConstants.ALOAD_0); // put "this" back on the stack
for (int i = 0, len = stateTypes.length; i < len; i++) {
stateTempVar.appendConvertableArrayLoad(
returnConversionCode,
fact,
i,
world.resolve(BcelWorld.fromBcel(stateTypes[i])));
}
} else {
returnConversionCode =
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType()),
callbackMethod.getReturnType());
if (!isFallsThrough()) {
returnConversionCode.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
}
}
InstructionList advice = new InstructionList();
advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation));
// advice.append(closureInstantiation);
advice.append(munger.getNonTestAdviceInstructions(this));
advice.append(returnConversionCode);
if (!hasDynamicTest) {
range.append(advice);
} else {
InstructionList callback = makeCallToCallback(callbackMethod);
InstructionList postCallback = new InstructionList();
if (terminatesWithReturn()) {
callback.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
} else {
advice.append(
InstructionFactory.createBranchInstruction(
Constants.GOTO,
postCallback.append(InstructionConstants.NOP)));
}
range.append(
munger.getTestInstructions(
this,
advice.getStart(),
callback.getStart(),
advice.getStart()));
range.append(advice);
range.append(callback);
range.append(postCallback);
}
}
// exposed for testing
InstructionList makeCallToCallback(LazyMethodGen callbackMethod) {
InstructionFactory fact = getFactory();
InstructionList callback = new InstructionList();
if (thisVar != null) {
callback.append(InstructionConstants.ALOAD_0);
}
if (targetVar != null && targetVar != thisVar) {
callback.append(BcelRenderer.renderExpr(fact, world, targetVar));
}
callback.append(BcelRenderer.renderExprs(fact, world, argVars));
// remember to render tjps
if (thisJoinPointVar != null) {
callback.append(BcelRenderer.renderExpr(fact, world, thisJoinPointVar));
}
callback.append(Utility.createInvoke(fact, callbackMethod));
return callback;
}
/** side-effect-free */
private InstructionList makeClosureInstantiation(Member constructor, BcelVar holder) {
// LazyMethodGen constructor) {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY);
//final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionList il = new InstructionList();
int alen = getArgCount() + (thisVar == null ? 0 : 1) +
((targetVar != null && targetVar != thisVar) ? 1 : 0) +
(thisJoinPointVar == null ? 0 : 1);
il.append(Utility.createConstant(fact, alen));
il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(il, fact);
int stateIndex = 0;
if (thisVar != null) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisVar);
thisVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
if (targetVar != null && targetVar != thisVar) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, targetVar);
targetVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
for (int i = 0, len = getArgCount(); i<len; i++) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, argVars[i]);
argVars[i].setPositionInAroundState(stateIndex);
stateIndex++;
}
if (thisJoinPointVar != null) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisJoinPointVar);
thisJoinPointVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
il.append(fact.createNew(new ObjectType(constructor.getDeclaringType().getName())));
il.append(new DUP());
arrayVar.appendLoad(il, fact);
il.append(Utility.createInvoke(fact, world, constructor));
if (getKind() == PreInitialization) {
il.append(InstructionConstants.DUP);
holder.appendStore(il, fact);
}
return il;
}
private IntMap makeProceedArgumentMap(BcelVar[] adviceArgs) {
//System.err.println("coming in with " + Arrays.asList(adviceArgs));
IntMap ret = new IntMap();
for(int i = 0, len = adviceArgs.length; i < len; i++) {
BcelVar v = (BcelVar) adviceArgs[i];
if (v == null) continue; // XXX we don't know why this is required
int pos = v.getPositionInAroundState();
if (pos >= 0) { // need this test to avoid args bound via cflow
ret.put(pos, i);
}
}
//System.err.println("returning " + ret);
return ret;
}
/**
*
*
* @param callbackMethod the method we will call back to when our run method gets called.
*
* @param proceedMap A map from state position to proceed argument position. May be
* non covering on state position.
*/
private LazyMethodGen makeClosureClassAndReturnConstructor(
String closureClassName,
LazyMethodGen callbackMethod,
IntMap proceedMap)
{
String superClassName = "org.aspectj.runtime.internal.AroundClosure";
Type objectArrayType = new ArrayType(Type.OBJECT, 1);
LazyClassGen closureClass = new LazyClassGen(closureClassName,
superClassName,
getEnclosingClass().getFileName(),
Modifier.PUBLIC,
new String[] {});
InstructionFactory fact = new InstructionFactory(closureClass.getConstantPoolGen());
// constructor
LazyMethodGen constructor = new LazyMethodGen(Modifier.PUBLIC,
Type.VOID,
"<init>",
new Type[] {objectArrayType},
new String[] {},
closureClass);
InstructionList cbody = constructor.getBody();
cbody.append(InstructionFactory.createLoad(Type.OBJECT, 0));
cbody.append(InstructionFactory.createLoad(objectArrayType, 1));
cbody.append(fact.createInvoke(superClassName, "<init>", Type.VOID,
new Type[] {objectArrayType}, Constants.INVOKESPECIAL));
cbody.append(InstructionFactory.createReturn(Type.VOID));
closureClass.addMethodGen(constructor);
// method
LazyMethodGen runMethod = new LazyMethodGen(Modifier.PUBLIC,
Type.OBJECT,
"run",
new Type[] {objectArrayType},
new String[] {},
closureClass);
InstructionList mbody = runMethod.getBody();
BcelVar proceedVar = new BcelVar(TypeX.OBJECTARRAY.resolve(world), 1);
// int proceedVarIndex = 1;
BcelVar stateVar =
new BcelVar(TypeX.OBJECTARRAY.resolve(world), runMethod.allocateLocal(1));
// int stateVarIndex = runMethod.allocateLocal(1);
mbody.append(InstructionFactory.createThis());
mbody.append(fact.createGetField(superClassName, "state", objectArrayType));
mbody.append(stateVar.createStore(fact));
// mbody.append(fact.createStore(objectArrayType, stateVarIndex));
Type[] stateTypes = callbackMethod.getArgumentTypes();
for (int i=0, len=stateTypes.length; i < len; i++) {
Type stateType = stateTypes[i];
ResolvedTypeX stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
if (proceedMap.hasKey(i)) {
mbody.append(
proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i),
stateTypeX));
} else {
mbody.append(
stateVar.createConvertableArrayLoad(fact, i,
stateTypeX));
}
}
mbody.append(Utility.createInvoke(fact, callbackMethod));
if (getKind() == PreInitialization) {
mbody.append(Utility.createSet(
fact,
AjcMemberMaker.aroundClosurePreInitializationField()));
mbody.append(InstructionConstants.ACONST_NULL);
} else {
mbody.append(
Utility.createConversion(
fact,
callbackMethod.getReturnType(),
Type.OBJECT));
}
mbody.append(InstructionFactory.createReturn(Type.OBJECT));
closureClass.addMethodGen(runMethod);
// class
getEnclosingClass().addGeneratedInner(closureClass);
return constructor;
}
// ---- extraction methods
public LazyMethodGen extractMethod(String newMethodName) {
LazyMethodGen.assertGoodBody(range.getBody(), newMethodName);
if (!getKind().allowsExtraction()) throw new BCException();
LazyMethodGen freshMethod = createMethodGen(newMethodName);
// 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);
return freshMethod;
}
private void addPreInitializationReturnCode(
LazyMethodGen extractedMethod,
Type[] superConstructorTypes)
{
InstructionList body = extractedMethod.getBody();
final InstructionFactory fact = getFactory();
BcelVar arrayVar = new BcelVar(
world.resolve(TypeX.OBJECTARRAY),
extractedMethod.allocateLocal(1));
int len = superConstructorTypes.length;
body.append(Utility.createConstant(fact, len));
body.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(body, fact);
for (int i = len - 1; i >= 0; i++) {
// convert thing on top of stack to object
body.append(
Utility.createConversion(fact, superConstructorTypes[i], Type.OBJECT));
// push object array
arrayVar.appendLoad(body, fact);
// swap
body.append(InstructionConstants.SWAP);
// do object array store.
body.append(Utility.createConstant(fact, i));
body.append(InstructionConstants.SWAP);
body.append(InstructionFactory.createArrayStore(Type.OBJECT));
}
arrayVar.appendLoad(body, fact);
body.append(InstructionConstants.ARETURN);
}
private Type[] getSuperConstructorParameterTypes() {
// assert getKind() == PreInitialization
InstructionHandle superCallHandle = getRange().getEnd().getNext();
InvokeInstruction superCallInstruction =
(InvokeInstruction) superCallHandle.getInstruction();
return superCallInstruction.getArgumentTypes(
getEnclosingClass().getConstantPoolGen());
}
/** make a map from old frame location to new frame location. Any unkeyed frame
* location picks out a copied local */
private IntMap makeRemap() {
IntMap ret = new IntMap(5);
int reti = 0;
if (thisVar != null) {
ret.put(0, reti++); // thisVar guaranteed to be 0
}
if (targetVar != null && targetVar != thisVar) {
ret.put(targetVar.getSlot(), reti++);
}
for (int i = 0, len = argVars.length; i < len; i++) {
ret.put(argVars[i].getSlot(), reti);
reti += argVars[i].getType().getSize();
}
if (thisJoinPointVar != null) {
ret.put(thisJoinPointVar.getSlot(), reti++);
}
// we not only need to put the arguments, we also need to remap their
// aliases, which we so helpfully put into temps at the beginning of this join
// point.
if (! getKind().argsOnStack()) {
int oldi = 0;
int newi = 0;
// if we're passing in a this and we're not argsOnStack we're always
// passing in a target too
if (arg0HoldsThis()) { ret.put(0, 0); oldi++; newi+=1; }
//assert targetVar == thisVar
for (int i = 0; i < getArgCount(); i++) {
TypeX type = getArgType(i);
ret.put(oldi, newi);
oldi += type.getSize();
newi += type.getSize();
}
}
// System.err.println("making remap for : " + this);
// if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot());
// if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot());
// System.err.println(ret);
return ret;
}
/**
* The new method always static.
* It may take some extra arguments: this, target.
* If it's argsOnStack, then it must take both this/target
* If it's argsOnFrame, it shares this and target.
* ??? rewrite this to do less array munging, please
*/
private LazyMethodGen createMethodGen(String newMethodName) {
Type[] parameterTypes = BcelWorld.makeBcelTypes(getArgTypes());
int modifiers = Modifier.FINAL;
// XXX some bug
// if (! isExpressionKind() && getSignature().isStrict(world)) {
// modifiers |= Modifier.STRICT;
// }
modifiers |= Modifier.STATIC;
if (targetVar != null && targetVar != thisVar) {
TypeX targetType = getTargetType();
ResolvedMember resolvedMember = getSignature().resolve(world);
if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) &&
!samePackage(targetType.getPackageName(), getEnclosingType().getPackageName()))
{
if (!targetType.isAssignableFrom(getThisType(), world)) {
throw new BCException("bad bytecode");
}
targetType = getThisType();
}
parameterTypes = addType(BcelWorld.makeBcelType(targetType), parameterTypes);
}
if (thisVar != null) {
TypeX thisType = getThisType();
parameterTypes = addType(BcelWorld.makeBcelType(thisType), parameterTypes);
}
// We always want to pass down thisJoinPoint in case we have already woven
// some advice in here. If we only have a single piece of around advice on a
// join point, it is unnecessary to accept (and pass) tjp.
if (thisJoinPointVar != null) {
parameterTypes = addTypeToEnd(LazyClassGen.tjpType, parameterTypes);
}
TypeX returnType;
if (getKind() == PreInitialization) {
returnType = TypeX.OBJECTARRAY;
} else {
returnType = getReturnType();
}
return
new LazyMethodGen(
modifiers,
BcelWorld.makeBcelType(returnType),
newMethodName,
parameterTypes,
new String[0],
// XXX again, we need to look up methods!
// TypeX.getNames(getSignature().getExceptions(world)),
getEnclosingClass());
}
private boolean samePackage(String p1, String p2) {
if (p1 == null) return p2 == null;
if (p2 == null) return false;
return p1.equals(p2);
}
private Type[] addType(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[0] = type;
System.arraycopy(types, 0, ret, 1, len);
return ret;
}
private Type[] addTypeToEnd(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[len] = type;
System.arraycopy(types, 0, ret, 0, len);
return ret;
}
public BcelVar genTempVar(TypeX typeX) {
return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize()));
}
// public static final boolean CREATE_TEMP_NAMES = true;
public BcelVar genTempVar(TypeX typeX, String localName) {
BcelVar tv = genTempVar(typeX);
// if (CREATE_TEMP_NAMES) {
// for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
// if (Range.isRangeHandle(ih)) continue;
// ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot()));
// }
// }
return tv;
}
// eh doesn't think we need to garbage collect these (64K is a big number...)
private int genTempVarIndex(int size) {
return enclosingMethod.allocateLocal(size);
}
public InstructionFactory getFactory() {
return getEnclosingClass().getFactory();
}
public ISourceLocation getSourceLocation() {
int sourceLine = getSourceLine();
if (sourceLine == 0) {
// 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;
}
}
|
50,570
|
Bug 50570 CatchClauseSignature has broken operation
|
It looks like the getParameterName() operation on org.aspectj.lang.reflect. CatchClauseSignature is not working. Instead of returning the name of the exception as declared in the matched handler, returns the string value "<missing>". Here is a test case that shows the problem :- ------START OF TEST CASE CODE----------- public class MyApp { public void doSomething() { // Get around "unreachable code error... if (true) { throw new BusinessException("Surprise!!"); } System.out.println("Busy doing something."); } public static void main(String[] args) { try { MyApp m = new MyApp(); m.doSomething(); } catch (BusinessException be) { System.out.println("Exception caught : " + be.getMessage()); } } } class BusinessException extends RuntimeException { BusinessException(String message) { super(message); } } aspect AppMonitor { pointcut problemHandling() : handler(Throwable+); before() : problemHandling() { CatchClauseSignature cSig = (CatchClauseSignature) thisJoinPointStaticPart.getSignature(); System.out.println( "MONITOR::\tCaught a " + cSig.getParameterType().getName() + " called " + cSig.getParameterName()); } } ------END OF TEST CASE CODE----------- The output from running the above was ... MONITOR:: Caught a BusinessException called <missing> Exception caught : Surprise !!!! Operating system : Windows XP AspectJ : 1.1.1 final and also on latest from CVS HEAD
|
resolved fixed
|
19bac86
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-28T01:12:17Z
| 2004-01-25T17:00:00Z
|
tests/bugs/HandlerSig.java
| |
50,570
|
Bug 50570 CatchClauseSignature has broken operation
|
It looks like the getParameterName() operation on org.aspectj.lang.reflect. CatchClauseSignature is not working. Instead of returning the name of the exception as declared in the matched handler, returns the string value "<missing>". Here is a test case that shows the problem :- ------START OF TEST CASE CODE----------- public class MyApp { public void doSomething() { // Get around "unreachable code error... if (true) { throw new BusinessException("Surprise!!"); } System.out.println("Busy doing something."); } public static void main(String[] args) { try { MyApp m = new MyApp(); m.doSomething(); } catch (BusinessException be) { System.out.println("Exception caught : " + be.getMessage()); } } } class BusinessException extends RuntimeException { BusinessException(String message) { super(message); } } aspect AppMonitor { pointcut problemHandling() : handler(Throwable+); before() : problemHandling() { CatchClauseSignature cSig = (CatchClauseSignature) thisJoinPointStaticPart.getSignature(); System.out.println( "MONITOR::\tCaught a " + cSig.getParameterType().getName() + " called " + cSig.getParameterName()); } } ------END OF TEST CASE CODE----------- The output from running the above was ... MONITOR:: Caught a BusinessException called <missing> Exception caught : Surprise !!!! Operating system : Windows XP AspectJ : 1.1.1 final and also on latest from CVS HEAD
|
resolved fixed
|
19bac86
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-28T01:12:17Z
| 2004-01-25T17:00:00Z
|
weaver/src/org/aspectj/weaver/Member.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.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import org.aspectj.util.TypeSafeEnum;
public class Member implements Comparable {
private final Kind kind;
private final TypeX declaringType;
protected final int modifiers; // protected because ResolvedMember uses it
private final TypeX returnType;
private final String name;
private final TypeX[] parameterTypes;
private final String signature;
public Member(
Kind kind,
TypeX declaringType,
int modifiers,
String name,
String signature)
{
this.kind = kind;
this.declaringType = declaringType;
this.modifiers = modifiers;
this.name = name;
this.signature = signature;
if (kind == FIELD) {
this.returnType = TypeX.forSignature(signature);
this.parameterTypes = TypeX.NONE;
} else {
Object[] returnAndParams = signatureToTypes(signature);
this.returnType = (TypeX) returnAndParams[0];
this.parameterTypes = (TypeX[]) returnAndParams[1];
}
}
public Member(
Kind kind,
TypeX declaringType,
int modifiers,
TypeX returnType,
String name,
TypeX[] parameterTypes)
{
super();
this.kind = kind;
this.declaringType = declaringType;
this.modifiers = modifiers;
this.returnType = returnType;
this.name = name;
this.parameterTypes = parameterTypes;
if (kind == FIELD) {
this.signature = returnType.getSignature();
} else {
this.signature = typesToSignature(returnType, parameterTypes);
}
}
public ResolvedMember resolve(World world) {
return world.resolve(this);
}
// ---- utility methods
/** returns an Object[] pair of TypeX, TypeX[] representing return type,
* argument types parsed from the JVM bytecode signature of a method. Yes,
* this should actually return a nice statically-typed pair object, but we
* don't have one of those.
*
* <blockquote><pre>
* TypeX.signatureToTypes("()[Z")[0].equals(Type.forSignature("[Z"))
* TypeX.signatureToTypes("(JJ)I")[1]
* .equals(TypeX.forSignatures(new String[] {"J", "J"}))
* </pre></blockquote>
*
* @param signature the JVM bytecode method signature string we want to break apart
* @return a pair of TypeX, TypeX[] representing the return types and parameter types.
*/
public static String typesToSignature(TypeX returnType, TypeX[] paramTypes) {
StringBuffer buf = new StringBuffer();
buf.append("(");
for (int i = 0, len = paramTypes.length; i < len; i++) {
buf.append(paramTypes[i].getSignature());
}
buf.append(")");
buf.append(returnType.getSignature());
return buf.toString();
}
/** returns an Object[] pair of TypeX, TypeX[] representing return type,
* argument types parsed from the JVM bytecode signature of a method. Yes,
* this should actually return a nice statically-typed pair object, but we
* don't have one of those.
*
* <blockquote><pre>
* TypeX.signatureToTypes("()[Z")[0].equals(Type.forSignature("[Z"))
* TypeX.signatureToTypes("(JJ)I")[1]
* .equals(TypeX.forSignatures(new String[] {"J", "J"}))
* </pre></blockquote>
*
* @param signature the JVM bytecode method signature string we want to break apart
* @return a pair of TypeX, TypeX[] representing the return types and parameter types.
*/
private static Object[] signatureToTypes(String sig) {
List l = new ArrayList();
int i = 1;
while (true) {
char c = sig.charAt(i);
if (c == ')') break;
int start = i;
while (c == '[') c = sig.charAt(++i);
if (c == 'L') {
i = sig.indexOf(';', start) + 1;
l.add(TypeX.forSignature(sig.substring(start, i)));
} else {
l.add(TypeX.forSignature(sig.substring(start, ++i)));
}
}
TypeX[] paramTypes = (TypeX[]) l.toArray(new TypeX[l.size()]);
TypeX returnType = TypeX.forSignature(sig.substring(i+1, sig.length()));
return new Object[] { returnType, paramTypes };
}
// ---- factory methods
public static Member field(String declaring, int mods, String name, String signature) {
return field(declaring, mods, TypeX.forSignature(signature), name);
}
public static Member field(TypeX declaring, int mods, String name, TypeX type) {
return new Member(FIELD, declaring, mods, type, name, TypeX.NONE);
}
public static Member method(TypeX declaring, int mods, String name, String signature) {
Object[] pair = signatureToTypes(signature);
return method(declaring, mods, (TypeX) pair[0], name, (TypeX[]) pair[1]);
}
public static Member pointcut(TypeX declaring, String name, String signature) {
Object[] pair = signatureToTypes(signature);
return pointcut(declaring, 0, (TypeX) pair[0], name, (TypeX[]) pair[1]);
}
private static Member field(String declaring, int mods, TypeX ty, String name) {
return new Member(
FIELD,
TypeX.forName(declaring),
mods,
ty,
name,
TypeX.NONE);
}
public static Member method(TypeX declTy, int mods, TypeX rTy, String name, TypeX[] paramTys) {
return new Member(
//??? this calls <clinit> a method
name.equals("<init>") ? CONSTRUCTOR : METHOD,
declTy,
mods,
rTy,
name,
paramTys);
}
private static Member pointcut(TypeX declTy, int mods, TypeX rTy, String name, TypeX[] paramTys) {
return new Member(
POINTCUT,
declTy,
mods,
rTy,
name,
paramTys);
}
public static Member makeExceptionHandlerSignature(TypeX inType, TypeX catchType) {
return new Member(
HANDLER,
inType,
Modifier.STATIC,
"<catch>",
"(" + catchType.getSignature() + ")V");
}
// ---- parsing methods
/** Takes a string in this form:
*
* <blockquote><pre>
* static? TypeName TypeName.Id
* </pre></blockquote>
* Pretty much just for testing, and as such should perhaps be moved.
*/
public static Member fieldFromString(String str) {
str = str.trim();
final int len = str.length();
int i = 0;
int mods = 0;
if (str.startsWith("static", i)) {
mods = Modifier.STATIC;
i += 6;
while (Character.isWhitespace(str.charAt(i))) i++;
}
int start = i;
while (! Character.isWhitespace(str.charAt(i))) i++;
TypeX retTy = TypeX.forName(str.substring(start, i));
start = i;
i = str.lastIndexOf('.');
TypeX declaringTy = TypeX.forName(str.substring(start, i).trim());
start = ++i;
String name = str.substring(start, len).trim();
return new Member(
FIELD,
declaringTy,
mods,
retTy,
name,
TypeX.NONE);
}
/** Takes a string in this form:
*
* <blockquote><pre>
* (static|interface|private)? TypeName TypeName . Id ( TypeName , ...)
* </pre></blockquote>
* Pretty much just for testing, and as such should perhaps be moved.
*/
public static Member methodFromString(String str) {
str = str.trim();
// final int len = str.length();
int i = 0;
int mods = 0;
if (str.startsWith("static", i)) {
mods = Modifier.STATIC;
i += 6;
} else if (str.startsWith("interface", i)) {
mods = Modifier.INTERFACE;
i += 9;
} else if (str.startsWith("private", i)) {
mods = Modifier.PRIVATE;
i += 7;
}
while (Character.isWhitespace(str.charAt(i))) i++;
int start = i;
while (! Character.isWhitespace(str.charAt(i))) i++;
TypeX returnTy = TypeX.forName(str.substring(start, i));
start = i;
i = str.indexOf('(', i);
i = str.lastIndexOf('.', i);
TypeX declaringTy = TypeX.forName(str.substring(start, i).trim());
start = ++i;
i = str.indexOf('(', i);
String name = str.substring(start, i).trim();
start = ++i;
i = str.indexOf(')', i);
String[] paramTypeNames = parseIds(str.substring(start, i).trim());
return method(declaringTy, mods, returnTy, name, TypeX.forNames(paramTypeNames));
}
private static String[] parseIds(String str) {
if (str.length() == 0) return ZERO_STRINGS;
List l = new ArrayList();
int start = 0;
while (true) {
int i = str.indexOf(',', start);
if (i == -1) {
l.add(str.substring(start).trim());
break;
}
l.add(str.substring(start, i).trim());
start = i+1;
}
return (String[]) l.toArray(new String[l.size()]);
}
private static final String[] ZERO_STRINGS = new String[0];
// ---- things we know without resolution
public boolean equals(Object other) {
if (! (other instanceof Member)) return false;
Member o = (Member) other;
return (kind == o.kind
&& name.equals(o.name)
&& signature.equals(o.signature)
&& declaringType.equals(o.declaringType));
}
public int compareTo(Object other) {
Member o = (Member) other;
int i = getName().compareTo(o.getName());
if (i != 0) return i;
return getSignature().compareTo(o.getSignature());
}
/**
* Equality is checked based on the underlying signature, so the hash code
* of a member is based on its kind, name, signature, and declaring type. The
* algorithm for this was taken from page 38 of effective java.
*/
private volatile int hashCode = 0;
public int hashCode() {
if (hashCode == 0) {
int result = 17;
result = 37*result + kind.hashCode();
result = 37*result + name.hashCode();
result = 37*result + signature.hashCode();
result = 37*result + declaringType.hashCode();
hashCode = result;
}
return hashCode;
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append(returnType);
buf.append(' ');
buf.append(declaringType);
buf.append('.');
buf.append(name);
if (kind != FIELD) {
buf.append("(");
if (parameterTypes.length != 0) {
buf.append(parameterTypes[0]);
for (int i=1, len = parameterTypes.length; i < len; i++) {
buf.append(", ");
buf.append(parameterTypes[i]);
}
}
buf.append(")");
}
return buf.toString();
}
public String toLongString() {
StringBuffer buf = new StringBuffer();
buf.append(kind);
buf.append(' ');
if (modifiers != 0) {
buf.append(Modifier.toString(modifiers));
buf.append(' ');
}
buf.append(toString());
buf.append(" <");
buf.append(signature);
buf.append(" >");
return buf.toString();
}
public Kind getKind() { return kind; }
public TypeX getDeclaringType() { return declaringType; }
public TypeX getReturnType() { return returnType; }
public TypeX getType() { return returnType; }
public String getName() { return name; }
public TypeX[] getParameterTypes() { return parameterTypes; }
public String getSignature() { return signature; }
public int getArity() { return parameterTypes.length; }
public boolean isCompatibleWith(Member am) {
if (kind != METHOD || am.getKind() != METHOD) return true;
if (! name.equals(am.getName())) return true;
if (! equalTypes(getParameterTypes(), am.getParameterTypes())) return true;
return getReturnType().equals(am.getReturnType());
}
private static boolean equalTypes(TypeX[] a, TypeX[] b) {
int len = a.length;
if (len != b.length) return false;
for (int i = 0; i < len; i++) {
if (!a[i].equals(b[i])) return false;
}
return true;
}
// ---- things we know only with resolution
public int getModifiers(World world) {
return world.getModifiers(this);
}
public TypeX[] getExceptions(World world) {
return world.getExceptions(this);
}
public final boolean isProtected(World world) {
return Modifier.isProtected(world.getModifiers(this));
}
public final boolean isStatic(World world) {
return Modifier.isStatic(world.getModifiers(this));
}
public final boolean isStrict(World world) {
return Modifier.isStrict(world.getModifiers(this));
}
public final boolean isStatic() {
return Modifier.isStatic(modifiers);
}
public final boolean isInterface() {
return Modifier.isInterface(modifiers); // this is kinda weird
}
public final boolean isPrivate() {
return Modifier.isPrivate(modifiers);
}
public final int getCallsiteModifiers() {
return modifiers & ~ Modifier.INTERFACE;
}
public final String getExtractableName() {
if (name.equals("<init>")) return "init$";
else if (name.equals("<clinit>")) return "clinit$";
else return name;
}
// ---- fields 'n' stuff
public static final Member[] NONE = new Member[0];
public static class Kind extends TypeSafeEnum {
public Kind(String name, int key) { super(name, key); }
public static Kind read(DataInputStream s) throws IOException {
int key = s.readByte();
switch(key) {
case 1: return METHOD;
case 2: return FIELD;
case 3: return CONSTRUCTOR;
case 4: return STATIC_INITIALIZATION;
case 5: return POINTCUT;
case 6: return ADVICE;
case 7: return HANDLER;
}
throw new BCException("weird kind " + key);
}
}
public static final Kind METHOD = new Kind("METHOD", 1);
public static final Kind FIELD = new Kind("FIELD", 2);
public static final Kind CONSTRUCTOR = new Kind("CONSTRUCTOR", 3);
public static final Kind STATIC_INITIALIZATION = new Kind("STATIC_INITIALIZATION", 4);
public static final Kind POINTCUT = new Kind("POINTCUT", 5);
public static final Kind ADVICE = new Kind("ADVICE", 6);
public static final Kind HANDLER = new Kind("HANDLER", 7);
public Collection/*ResolvedTypeX*/ getDeclaringTypes(World world) {
ResolvedTypeX myType = getDeclaringType().resolve(world);
Collection ret = new HashSet();
if (kind == CONSTRUCTOR) {
// this is wrong if the member doesn't exist, but that doesn't matter
ret.add(myType);
} else if (isStatic() || kind == FIELD) {
walkUpStatic(ret, myType);
} else {
walkUp(ret, myType);
}
return ret;
}
private boolean walkUp(Collection acc, ResolvedTypeX curr) {
if (acc.contains(curr)) return true;
boolean b = false;
for (Iterator i = curr.getDirectSupertypes(); i.hasNext(); ) {
b |= walkUp(acc, (ResolvedTypeX)i.next());
}
if (!b) {
b = curr.lookupMemberNoSupers(this) != null;
}
if (b) acc.add(curr);
return b;
}
private boolean walkUpStatic(Collection acc, ResolvedTypeX curr) {
if (curr.lookupMemberNoSupers(this) != null) {
acc.add(curr);
return true;
} else {
boolean b = false;
for (Iterator i = curr.getDirectSupertypes(); i.hasNext(); ) {
b |= walkUpStatic(acc, (ResolvedTypeX)i.next());
}
if (b) acc.add(curr);
return b;
}
}
// ---- reflective thisJoinPoint stuff
public String getSignatureMakerName() {
if (getName().equals("<clinit>")) return "makeInitializerSig";
Kind kind = getKind();
if (kind == METHOD) {
return "makeMethodSig";
} else if (kind == CONSTRUCTOR) {
return "makeConstructorSig";
} else if (kind == FIELD) {
return "makeFieldSig";
} else if (kind == HANDLER) {
return "makeCatchClauseSig";
} else if (kind == STATIC_INITIALIZATION) {
return "makeInitializerSig";
} else if (kind == ADVICE) {
return "makeAdviceSig";
} else {
throw new RuntimeException("unimplemented");
}
}
public String getSignatureType() {
Kind kind = getKind();
if (getName().equals("<clinit>")) return "org.aspectj.lang.reflect.InitializerSignature";
if (kind == METHOD) {
return "org.aspectj.lang.reflect.MethodSignature";
} else if (kind == CONSTRUCTOR) {
return "org.aspectj.lang.reflect.ConstructorSignature";
} else if (kind == FIELD) {
return "org.aspectj.lang.reflect.FieldSignature";
} else if (kind == HANDLER) {
return "org.aspectj.lang.reflect.CatchClauseSignature";
} else if (kind == STATIC_INITIALIZATION) {
return "org.aspectj.lang.reflect.InitializerSignature";
} else if (kind == ADVICE) {
return "org.aspectj.lang.reflect.AdviceSignature";
} else {
throw new RuntimeException("unimplemented");
}
}
public String getSignatureString(World world) {
if (getName().equals("<clinit>")) return getStaticInitializationSignatureString(world);
Kind kind = getKind();
if (kind == METHOD) {
return getMethodSignatureString(world);
} else if (kind == CONSTRUCTOR) {
return getConstructorSignatureString(world);
} else if (kind == FIELD) {
return getFieldSignatureString(world);
} else if (kind == HANDLER) {
return getHandlerSignatureString(world);
} else if (kind == STATIC_INITIALIZATION) {
return getStaticInitializationSignatureString(world);
} else if (kind == ADVICE) {
return getAdviceSignatureString(world);
} else {
throw new RuntimeException("unimplemented");
}
}
private String getHandlerSignatureString(World world) {
StringBuffer buf = new StringBuffer();
buf.append(makeString(0));
buf.append('-');
//buf.append(getName());
buf.append('-');
buf.append(makeString(getDeclaringType()));
buf.append('-');
buf.append(makeString(getParameterTypes()[0]));
buf.append('-');
//XXX we don't actually try to find the handler parameter name
//XXX it probably wouldn't be too hard
String pName = "<missing>";
//String[] pNames = getParameterNames(world);
//if (pNames != null) pName = pNames[0];
buf.append(pName);
buf.append('-');
return buf.toString();
}
private String getStaticInitializationSignatureString(World world) {
StringBuffer buf = new StringBuffer();
buf.append(makeString(getModifiers(world)));
buf.append('-');
//buf.append(getName());
buf.append('-');
buf.append(makeString(getDeclaringType()));
buf.append('-');
return buf.toString();
}
protected String getAdviceSignatureString(World world) {
StringBuffer buf = new StringBuffer();
buf.append(makeString(getModifiers(world)));
buf.append('-');
buf.append(getName());
buf.append('-');
buf.append(makeString(getDeclaringType()));
buf.append('-');
buf.append(makeString(getParameterTypes()));
buf.append('-');
buf.append(makeString(getParameterNames(world)));
buf.append('-');
buf.append(makeString(getExceptions(world)));
buf.append('-');
buf.append(makeString(getReturnType()));
buf.append('-');
return buf.toString();
}
protected String getMethodSignatureString(World world) {
StringBuffer buf = new StringBuffer();
buf.append(makeString(getModifiers(world)));
buf.append('-');
buf.append(getName());
buf.append('-');
buf.append(makeString(getDeclaringType()));
buf.append('-');
buf.append(makeString(getParameterTypes()));
buf.append('-');
buf.append(makeString(getParameterNames(world)));
buf.append('-');
buf.append(makeString(getExceptions(world)));
buf.append('-');
buf.append(makeString(getReturnType()));
buf.append('-');
return buf.toString();
}
protected String getConstructorSignatureString(World world) {
StringBuffer buf = new StringBuffer();
buf.append(makeString(getModifiers(world)));
buf.append('-');
buf.append('-');
buf.append(makeString(getDeclaringType()));
buf.append('-');
buf.append(makeString(getParameterTypes()));
buf.append('-');
buf.append(makeString(getParameterNames(world)));
buf.append('-');
buf.append(makeString(getExceptions(world)));
buf.append('-');
return buf.toString();
}
protected String getFieldSignatureString(World world) {
StringBuffer buf = new StringBuffer();
buf.append(makeString(getModifiers(world)));
buf.append('-');
buf.append(getName());
buf.append('-');
buf.append(makeString(getDeclaringType()));
buf.append('-');
buf.append(makeString(getReturnType()));
buf.append('-');
return buf.toString();
}
protected String makeString(int i) {
return Integer.toString(i, 16); //??? expensive
}
protected String makeString(TypeX t) {
// this is the inverse of the odd behavior for Class.forName w/ arrays
if (t.isArray()) {
// this behavior matches the string used by the eclipse compiler for Foo.class literals
return t.getSignature().replace('/', '.');
} else {
return t.getName();
}
}
protected String makeString(TypeX[] types) {
if (types == null) return "";
StringBuffer buf = new StringBuffer();
for (int i = 0, len=types.length; i < len; i++) {
buf.append(makeString(types[i]));
buf.append(':');
}
return buf.toString();
}
protected String makeString(String[] names) {
if (names == null) return "";
StringBuffer buf = new StringBuffer();
for (int i = 0, len=names.length; i < len; i++) {
buf.append(names[i]);
buf.append(':');
}
return buf.toString();
}
public String[] getParameterNames(World world) {
return world.getParameterNames(this);
}
// ----
}
|
50,570
|
Bug 50570 CatchClauseSignature has broken operation
|
It looks like the getParameterName() operation on org.aspectj.lang.reflect. CatchClauseSignature is not working. Instead of returning the name of the exception as declared in the matched handler, returns the string value "<missing>". Here is a test case that shows the problem :- ------START OF TEST CASE CODE----------- public class MyApp { public void doSomething() { // Get around "unreachable code error... if (true) { throw new BusinessException("Surprise!!"); } System.out.println("Busy doing something."); } public static void main(String[] args) { try { MyApp m = new MyApp(); m.doSomething(); } catch (BusinessException be) { System.out.println("Exception caught : " + be.getMessage()); } } } class BusinessException extends RuntimeException { BusinessException(String message) { super(message); } } aspect AppMonitor { pointcut problemHandling() : handler(Throwable+); before() : problemHandling() { CatchClauseSignature cSig = (CatchClauseSignature) thisJoinPointStaticPart.getSignature(); System.out.println( "MONITOR::\tCaught a " + cSig.getParameterType().getName() + " called " + cSig.getParameterName()); } } ------END OF TEST CASE CODE----------- The output from running the above was ... MONITOR:: Caught a BusinessException called <missing> Exception caught : Surprise !!!! Operating system : Windows XP AspectJ : 1.1.1 final and also on latest from CVS HEAD
|
resolved fixed
|
19bac86
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-28T01:12:17Z
| 2004-01-25T17:00:00Z
|
weaver/src/org/aspectj/weaver/ResolvedMember.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.lang.reflect.Modifier;
import org.aspectj.bridge.ISourceLocation;
/**
* This is the declared member, i.e. it will always correspond to an
* actual method/... declaration
*/
public class ResolvedMember extends Member implements IHasPosition {
protected String[] parameterNames = null;
protected TypeX[] checkedExceptions = TypeX.NONE;
// these three fields hold the source location of this member
protected int start, end;
protected ISourceContext sourceContext = null;
//XXX deprecate this in favor of the constructor below
public ResolvedMember(
Kind kind,
TypeX declaringType,
int modifiers,
TypeX returnType,
String name,
TypeX[] parameterTypes)
{
super(kind, declaringType, modifiers, returnType, name, parameterTypes);
}
public ResolvedMember(
Kind kind,
TypeX declaringType,
int modifiers,
TypeX returnType,
String name,
TypeX[] parameterTypes,
TypeX[] checkedExceptions)
{
super(kind, declaringType, modifiers, returnType, name, parameterTypes);
this.checkedExceptions = checkedExceptions;
}
public ResolvedMember(
Kind kind,
TypeX declaringType,
int modifiers,
String name,
String signature)
{
super(kind, declaringType, modifiers, name, signature);
}
public static final ResolvedMember[] NONE = new ResolvedMember[0];
// ----
public final int getModifiers(World world) {
return modifiers;
}
public final int getModifiers() {
return modifiers;
}
// ----
public final TypeX[] getExceptions(World world) {
return getExceptions();
}
public TypeX[] getExceptions() {
return checkedExceptions;
}
public ShadowMunger getAssociatedShadowMunger() {
return null;
}
// ??? true or false?
public boolean isAjSynthetic() {
return true;
}
public boolean isSynthetic() {
return false;
}
public void write(DataOutputStream s) throws IOException {
getKind().write(s);
getDeclaringType().write(s);
s.writeInt(modifiers);
s.writeUTF(getName());
s.writeUTF(getSignature());
TypeX.writeArray(getExceptions(), s);
s.writeInt(getStart());
s.writeInt(getEnd());
}
public static void writeArray(ResolvedMember[] members, DataOutputStream s) throws IOException {
s.writeInt(members.length);
for (int i = 0, len = members.length; i < len; i++) {
members[i].write(s);
}
}
public static ResolvedMember readResolvedMember(DataInputStream s, ISourceContext sourceContext) throws IOException {
ResolvedMember m = new ResolvedMember(Kind.read(s), TypeX.read(s), s.readInt(), s.readUTF(), s.readUTF());
m.checkedExceptions = TypeX.readArray(s);
m.start = s.readInt();
m.end = s.readInt();
m.sourceContext = sourceContext;
return m;
}
public static ResolvedMember[] readResolvedMemberArray(DataInputStream s, ISourceContext context) throws IOException {
int len = s.readInt();
ResolvedMember[] members = new ResolvedMember[len];
for (int i=0; i < len; i++) {
members[i] = ResolvedMember.readResolvedMember(s, context);
}
return members;
}
public ResolvedMember resolve(World world) {
return this;
}
public ISourceContext getSourceContext(World world) {
return getDeclaringType().resolve(world).getSourceContext();
}
public final String[] getParameterNames() {
return parameterNames;
}
public final String[] getParameterNames(World world) {
return getParameterNames();
}
public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() {
return null;
}
public ISourceLocation getSourceLocation() {
//System.out.println("get context: " + this + " is " + sourceContext);
if (sourceContext == null) {
//System.err.println("no context: " + this);
return null;
}
return sourceContext.makeSourceLocation(this);
}
public int getEnd() {
return end;
}
public ISourceContext getSourceContext() {
return sourceContext;
}
public int getStart() {
return start;
}
public void setPosition(int sourceStart, int sourceEnd) {
this.start = sourceStart;
this.end = sourceEnd;
}
public void setSourceContext(ISourceContext sourceContext) {
this.sourceContext = sourceContext;
}
public boolean isAbstract() {
return Modifier.isAbstract(modifiers);
}
public boolean isPublic() {
return Modifier.isPublic(modifiers);
}
public boolean isVisible(ResolvedTypeX fromType) {
World world = fromType.getWorld();
return ResolvedTypeX.isVisible(getModifiers(), getDeclaringType().resolve(world),
fromType);
}
public void setCheckedExceptions(TypeX[] checkedExceptions) {
this.checkedExceptions = checkedExceptions;
}
}
|
50,570
|
Bug 50570 CatchClauseSignature has broken operation
|
It looks like the getParameterName() operation on org.aspectj.lang.reflect. CatchClauseSignature is not working. Instead of returning the name of the exception as declared in the matched handler, returns the string value "<missing>". Here is a test case that shows the problem :- ------START OF TEST CASE CODE----------- public class MyApp { public void doSomething() { // Get around "unreachable code error... if (true) { throw new BusinessException("Surprise!!"); } System.out.println("Busy doing something."); } public static void main(String[] args) { try { MyApp m = new MyApp(); m.doSomething(); } catch (BusinessException be) { System.out.println("Exception caught : " + be.getMessage()); } } } class BusinessException extends RuntimeException { BusinessException(String message) { super(message); } } aspect AppMonitor { pointcut problemHandling() : handler(Throwable+); before() : problemHandling() { CatchClauseSignature cSig = (CatchClauseSignature) thisJoinPointStaticPart.getSignature(); System.out.println( "MONITOR::\tCaught a " + cSig.getParameterType().getName() + " called " + cSig.getParameterName()); } } ------END OF TEST CASE CODE----------- The output from running the above was ... MONITOR:: Caught a BusinessException called <missing> Exception caught : Surprise !!!! Operating system : Windows XP AspectJ : 1.1.1 final and also on latest from CVS HEAD
|
resolved fixed
|
19bac86
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-01-28T01:12:17Z
| 2004-01-25T17:00:00Z
|
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.generic.ACONST_NULL;
import org.apache.bcel.generic.ArrayType;
import org.apache.bcel.generic.BranchInstruction;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.DUP;
import org.apache.bcel.generic.DUP_X1;
import org.apache.bcel.generic.FieldInstruction;
import org.apache.bcel.generic.INVOKESPECIAL;
import org.apache.bcel.generic.INVOKESTATIC;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionConstants;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.InstructionTargeter;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.NEW;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.ReturnInstruction;
import org.apache.bcel.generic.SWAP;
import org.apache.bcel.generic.TargetLostException;
import org.apache.bcel.generic.Type;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Var;
/*
* Some fun implementation stuff:
*
* * expressionKind advice is non-execution advice
* * may have a target.
* * if the body is extracted, it will be extracted into
* a static method. The first argument to the static
* method is the target
* * advice may expose a this object, but that's the advice's
* consideration, not ours. This object will NOT be cached in another
* local, but will always come from frame zero.
*
* * non-expressionKind advice is execution advice
* * may have a this.
* * target is same as this, and is exposed that way to advice
* (i.e., target will not be cached, will always come from frame zero)
* * if the body is extracted, it will be extracted into a method
* with same static/dynamic modifier as enclosing method. If non-static,
* target of callback call will be this.
*
* * because of these two facts, the setup of the actual arguments (including
* possible target) callback method is the same for both kinds of advice:
* push the targetVar, if it exists (it will not exist for advice on static
* things), then push all the argVars.
*
* Protected things:
*
* * the above is sufficient for non-expressionKind advice for protected things,
* since the target will always be this.
*
* * For expressionKind things, we have to modify the signature of the callback
* method slightly. For non-static expressionKind things, we modify
* the first argument of the callback method NOT to be the type specified
* by the method/field signature (the owner), but rather we type it to
* the currentlyEnclosing type. We are guaranteed this will be fine,
* since the verifier verifies that the target is a subtype of the currently
* enclosingType.
*
* Worries:
*
* * ConstructorCalls will be weirder than all of these, since they
* supposedly don't have a target (according to AspectJ), but they clearly
* do have a target of sorts, just one that needs to be pushed on the stack,
* dupped, and not touched otherwise until the constructor runs.
*
* @author Jim Hugunin
* @author Erik Hilsdale
*
*/
public class BcelShadow extends Shadow {
private ShadowRange range;
private final BcelWorld world;
private final LazyMethodGen enclosingMethod;
private boolean fallsThrough; //XXX not used anymore
// ---- initialization
/**
* This generates an unassociated shadow, rooted in a particular method but not rooted
* to any particular point in the code. It should be given to a rooted ShadowRange
* in the {@link ShadowRange#associateWithShadow(BcelShadow)} method.
*/
public BcelShadow(
BcelWorld world,
Kind kind,
Member signature,
LazyMethodGen enclosingMethod,
BcelShadow enclosingShadow)
{
super(kind, signature, enclosingShadow);
this.world = world;
this.enclosingMethod = enclosingMethod;
fallsThrough = kind.argsOnStack();
}
// ---- copies all state, including Shadow's mungers...
public BcelShadow copyInto(LazyMethodGen recipient, BcelShadow enclosing) {
BcelShadow s = new BcelShadow(world, getKind(), getSignature(), recipient, enclosing);
List src = mungers;
List dest = s.mungers;
for (Iterator i = src.iterator(); i.hasNext(); ) {
dest.add(i.next());
}
return s;
}
// ---- overridden behaviour
public World getIWorld() {
return world;
}
private void deleteNewAndDup() {
final ConstantPoolGen cpg = getEnclosingClass().getConstantPoolGen();
int depth = 1;
InstructionHandle ih = range.getStart();
while (true) {
Instruction inst = ih.getInstruction();
if (inst instanceof INVOKESPECIAL
&& ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) {
depth++;
} else if (inst instanceof NEW) {
depth--;
if (depth == 0) break;
}
ih = ih.getPrev();
}
// now IH points to the NEW. We're followed by the DUP, and that is followed
// by the actual instruciton we care about.
InstructionHandle newHandle = ih;
InstructionHandle endHandle = newHandle.getNext();
InstructionHandle nextHandle;
if (endHandle.getInstruction() instanceof DUP) {
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else if (endHandle.getInstruction() instanceof DUP_X1) {
InstructionHandle dupHandle = endHandle;
endHandle = endHandle.getNext();
nextHandle = endHandle.getNext();
if (endHandle.getInstruction() instanceof SWAP) {}
else {
// XXX see next XXX comment
throw new RuntimeException("Unhandled kind of new " + endHandle);
}
retargetFrom(newHandle, nextHandle);
retargetFrom(dupHandle, nextHandle);
retargetFrom(endHandle, nextHandle);
} else {
endHandle = newHandle;
nextHandle = endHandle.getNext();
retargetFrom(newHandle, nextHandle);
// add a POP here... we found a NEW w/o a dup or anything else, so
// we must be in statement context.
getRange().insert(InstructionConstants.POP, Range.OutsideAfter);
}
// assert (dupHandle.getInstruction() instanceof DUP);
try {
range.getBody().delete(newHandle, endHandle);
} catch (TargetLostException e) {
throw new BCException("shouldn't happen");
}
}
private void retargetFrom(InstructionHandle old, InstructionHandle fresh) {
InstructionTargeter[] sources = old.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
sources[i].updateTarget(old, fresh);
}
}
}
protected void prepareForMungers() {
// if we're a constructor call, we need to remove the new:dup or the new:dup_x1:swap,
// and store all our
// arguments on the frame.
// ??? This is a bit of a hack (for the Java langauge). We do this because
// we sometime add code "outsideBefore" when dealing with weaving join points. We only
// do this for exposing state that is on the stack. It turns out to just work for
// everything except for constructor calls and exception handlers. If we were to clean
// this up, every ShadowRange would have three instructionHandle points, the start of
// the arg-setup code, the start of the running code, and the end of the running code.
if (getKind() == ConstructorCall) {
deleteNewAndDup();
initializeArgVars();
} else if (getKind() == ExceptionHandler) {
ShadowRange range = getRange();
InstructionList body = range.getBody();
InstructionHandle start = range.getStart();
InstructionHandle freshIh = body.insert(start, InstructionConstants.NOP);
InstructionTargeter[] targeters = start.getTargeters();
for (int i = 0; i < targeters.length; i++) {
InstructionTargeter t = targeters[i];
if (t instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) t;
er.updateTarget(start, freshIh, body);
}
}
}
// now we ask each munger to request our state
isThisJoinPointLazy = world.isXlazyTjp();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
munger.specializeOn(this);
}
initializeThisJoinPoint();
// If we are an expression kind, we require our target/arguments on the stack
// before we do our actual thing. However, they may have been removed
// from the stack as the shadowMungers have requested state.
// if any of our shadowMungers requested either the arguments or target,
// the munger will have added code
// to pop the target/arguments into temporary variables, represented by
// targetVar and argVars. In such a case, we must make sure to re-push the
// values.
// If we are nonExpressionKind, we don't expect arguments on the stack
// so this is moot. If our argVars happen to be null, then we know that
// no ShadowMunger has squirrelled away our arguments, so they're still
// on the stack.
InstructionFactory fact = getFactory();
if (getKind().argsOnStack() && argVars != null) {
range.insert(
BcelRenderer.renderExprs(fact, world, argVars),
Range.InsideBefore);
if (targetVar != null) {
range.insert(
BcelRenderer.renderExpr(fact, world, targetVar),
Range.InsideBefore);
}
if (getKind() == ConstructorCall) {
range.insert((Instruction) InstructionFactory.createDup(1), Range.InsideBefore);
range.insert(
fact.createNew(
(ObjectType) BcelWorld.makeBcelType(
getSignature().getDeclaringType())),
Range.InsideBefore);
}
}
}
// ---- getters
public ShadowRange getRange() {
return range;
}
public void setRange(ShadowRange range) {
this.range = range;
}
public int getSourceLine() {
if (range == null) {
if (getEnclosingMethod().hasBody()) {
return Utility.getSourceLine(getEnclosingMethod().getBody().getStart());
} else {
return 0;
}
}
int ret = Utility.getSourceLine(range.getStart());
if (ret < 0) return 0;
return ret;
}
// overrides
public TypeX getEnclosingType() {
return getEnclosingClass().getType();
}
public LazyClassGen getEnclosingClass() {
return enclosingMethod.getEnclosingClass();
}
public BcelWorld getWorld() {
return world;
}
// ---- factory methods
public static BcelShadow makeConstructorExecution(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle justBeforeStart)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
ConstructorExecution,
world.makeMethodSignature(enclosingMethod),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, justBeforeStart.getNext()),
Range.genEnd(body));
return s;
}
public static BcelShadow makeStaticInitialization(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
InstructionList body = enclosingMethod.getBody();
// move the start past ajc$preClinit
InstructionHandle clinitStart = body.getStart();
if (clinitStart.getInstruction() instanceof InvokeInstruction) {
InvokeInstruction ii = (InvokeInstruction)clinitStart.getInstruction();
if (ii
.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen())
.equals(NameMangler.AJC_PRE_CLINIT_NAME)) {
clinitStart = clinitStart.getNext();
}
}
InstructionHandle clinitEnd = body.getEnd();
//XXX should move the end before the postClinit, but the return is then tricky...
// if (clinitEnd.getInstruction() instanceof InvokeInstruction) {
// InvokeInstruction ii = (InvokeInstruction)clinitEnd.getInstruction();
// if (ii.getName(enclosingMethod.getEnclosingClass().getConstantPoolGen()).equals(NameMangler.AJC_POST_CLINIT_NAME)) {
// clinitEnd = clinitEnd.getPrev();
// }
// }
BcelShadow s =
new BcelShadow(
world,
StaticInitialization,
world.makeMethodSignature(enclosingMethod),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, clinitStart),
Range.genEnd(body, clinitEnd));
return s;
}
/** Make the shadow for an exception handler. Currently makes an empty shadow that
* only allows before advice to be woven into it.
*/
public static BcelShadow makeExceptionHandler(
BcelWorld world,
ExceptionRange exceptionRange,
LazyMethodGen enclosingMethod,
InstructionHandle startOfHandler,
BcelShadow enclosingShadow)
{
InstructionList body = enclosingMethod.getBody();
TypeX catchType = exceptionRange.getCatchType();
TypeX inType = enclosingMethod.getEnclosingClass().getType();
BcelShadow s =
new BcelShadow(
world,
ExceptionHandler,
Member.makeExceptionHandlerSignature(inType, catchType),
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;
}
/** create an init join point associated w/ an interface in the body of a constructor */
public static BcelShadow makeIfaceInitialization(
BcelWorld world,
LazyMethodGen constructor,
Member interfaceConstructorSignature)
{
InstructionList body = constructor.getBody();
// TypeX inType = constructor.getEnclosingClass().getType();
BcelShadow s =
new BcelShadow(
world,
Initialization,
interfaceConstructorSignature,
constructor,
null);
s.fallsThrough = true;
// ShadowRange r = new ShadowRange(body);
// r.associateWithShadow(s);
// InstructionHandle start = Range.genStart(body, handle);
// InstructionHandle end = Range.genEnd(body, handle);
//
// r.associateWithTargets(start, end);
return s;
}
public void initIfaceInitializer(InstructionHandle end) {
final InstructionList body = enclosingMethod.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(this);
InstructionHandle nop = body.insert(end, InstructionConstants.NOP);
r.associateWithTargets(
Range.genStart(body, nop),
Range.genEnd(body, nop));
}
// public static BcelShadow makeIfaceConstructorExecution(
// BcelWorld world,
// LazyMethodGen constructor,
// InstructionHandle next,
// Member interfaceConstructorSignature)
// {
// // final InstructionFactory fact = constructor.getEnclosingClass().getFactory();
// InstructionList body = constructor.getBody();
// // TypeX inType = constructor.getEnclosingClass().getType();
// BcelShadow s =
// new BcelShadow(
// world,
// ConstructorExecution,
// interfaceConstructorSignature,
// constructor,
// null);
// s.fallsThrough = true;
// ShadowRange r = new ShadowRange(body);
// r.associateWithShadow(s);
// // ??? this may or may not work
// InstructionHandle start = Range.genStart(body, next);
// //InstructionHandle end = Range.genEnd(body, body.append(start, fact.NOP));
// InstructionHandle end = Range.genStart(body, next);
// //body.append(start, fact.NOP);
//
// r.associateWithTargets(start, end);
// return s;
// }
/** Create an initialization join point associated with a constructor, but not
* with any body of code yet. If this is actually matched, it's range will be set
* when we inline self constructors.
*
* @param constructor The constructor starting this initialization.
*/
public static BcelShadow makeUnfinishedInitialization(
BcelWorld world,
LazyMethodGen constructor)
{
return new BcelShadow(
world,
Initialization,
world.makeMethodSignature(constructor),
constructor,
null);
}
public static BcelShadow makeUnfinishedPreinitialization(
BcelWorld world,
LazyMethodGen constructor)
{
BcelShadow ret = new BcelShadow(
world,
PreInitialization,
world.makeMethodSignature(constructor),
constructor,
null);
ret.fallsThrough = true;
return ret;
}
public static BcelShadow makeMethodExecution(
BcelWorld world,
LazyMethodGen enclosingMethod,
boolean lazyInit)
{
if (!lazyInit) return makeMethodExecution(world, enclosingMethod);
BcelShadow s =
new BcelShadow(
world,
MethodExecution,
enclosingMethod.getMemberView(),
enclosingMethod,
null);
return s;
}
public void init() {
if (range != null) return;
final InstructionList body = enclosingMethod.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(this);
r.associateWithTargets(
Range.genStart(body),
Range.genEnd(body));
}
public static BcelShadow makeMethodExecution(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
return makeShadowForMethod(world, enclosingMethod, MethodExecution,
enclosingMethod.getMemberView()); //world.makeMethodSignature(enclosingMethod));
}
public static BcelShadow makeShadowForMethod(BcelWorld world,
LazyMethodGen enclosingMethod, Shadow.Kind kind, Member sig)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
kind,
sig,
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body),
Range.genEnd(body));
return s;
}
public static BcelShadow makeAdviceExecution(
BcelWorld world,
LazyMethodGen enclosingMethod)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
AdviceExecution,
world.makeMethodSignature(enclosingMethod, Member.ADVICE),
enclosingMethod,
null);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(Range.genStart(body), Range.genEnd(body));
return s;
}
// constructor call shadows are <em>initially</em> just around the
// call to the constructor. If ANY advice gets put on it, we move
// the NEW instruction inside the join point, which involves putting
// all the arguments in temps.
public static BcelShadow makeConstructorCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
Member sig = BcelWorld.makeMethodSignature(
enclosingMethod.getEnclosingClass(),
(InvokeInstruction) callHandle.getInstruction());
BcelShadow s =
new BcelShadow(
world,
ConstructorCall,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeMethodCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
MethodCall,
BcelWorld.makeMethodSignature(
enclosingMethod.getEnclosingClass(),
(InvokeInstruction) callHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeShadowForMethodCall(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle callHandle,
BcelShadow enclosingShadow,
Kind kind,
ResolvedMember sig)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
kind,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, callHandle),
Range.genEnd(body, callHandle));
retargetAllBranches(callHandle, r.getStart());
return s;
}
public static BcelShadow makeFieldGet(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle getHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldGet,
BcelWorld.makeFieldSignature(
enclosingMethod.getEnclosingClass(),
(FieldInstruction) getHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, getHandle),
Range.genEnd(body, getHandle));
retargetAllBranches(getHandle, r.getStart());
return s;
}
public static BcelShadow makeFieldSet(
BcelWorld world,
LazyMethodGen enclosingMethod,
InstructionHandle setHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldSet,
BcelWorld.makeFieldSignature(
enclosingMethod.getEnclosingClass(),
(FieldInstruction) setHandle.getInstruction()),
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, setHandle),
Range.genEnd(body, setHandle));
retargetAllBranches(setHandle, r.getStart());
return s;
}
public static void retargetAllBranches(InstructionHandle from, InstructionHandle to) {
InstructionTargeter[] sources = from.getTargeters();
if (sources != null) {
for (int i = sources.length - 1; i >= 0; i--) {
InstructionTargeter source = sources[i];
if (source instanceof BranchInstruction) {
source.updateTarget(from, to);
}
}
}
}
// // ---- type access methods
// private ObjectType getTargetBcelType() {
// return (ObjectType) BcelWorld.makeBcelType(getTargetType());
// }
// private Type getArgBcelType(int arg) {
// return BcelWorld.makeBcelType(getArgType(arg));
// }
// ---- kinding
/**
* If the end of my range has no real instructions following then
* my context needs a return at the end.
*/
public boolean terminatesWithReturn() {
return getRange().getRealNext() == null;
}
/**
* Is arg0 occupied with the value of this
*/
public boolean arg0HoldsThis() {
if (getKind().isEnclosingKind()) {
return !getSignature().isStatic();
} else if (enclosingShadow == null) {
//XXX this is mostly right
// this doesn't do the right thing for calls in the pre part of introduced constructors.
return !enclosingMethod.isStatic();
} else {
return ((BcelShadow)enclosingShadow).arg0HoldsThis();
}
}
// ---- argument getting methods
private BcelVar thisVar = null;
private BcelVar targetVar = null;
private BcelVar[] argVars = null;
public Var getThisVar() {
if (!hasThis()) {
throw new IllegalStateException("no this");
}
initializeThisVar();
return thisVar;
}
public Var getTargetVar() {
if (!hasTarget()) {
throw new IllegalStateException("no target");
}
initializeTargetVar();
return targetVar;
}
public Var getArgVar(int i) {
initializeArgVars();
return argVars[i];
}
// reflective thisJoinPoint support
private BcelVar thisJoinPointVar = null;
private boolean isThisJoinPointLazy;
private int lazyTjpConsumers = 0;
private BcelVar thisJoinPointStaticPartVar = null;
// private BcelVar thisEnclosingJoinPointStaticPartVar = null;
public final Var getThisJoinPointStaticPartVar() {
return getThisJoinPointStaticPartBcelVar();
}
public final Var getThisEnclosingJoinPointStaticPartVar() {
return getThisEnclosingJoinPointStaticPartBcelVar();
}
public void requireThisJoinPoint(boolean hasGuardTest) {
if (!hasGuardTest) {
isThisJoinPointLazy = false;
} else {
lazyTjpConsumers++;
}
if (thisJoinPointVar == null) {
thisJoinPointVar = genTempVar(TypeX.forName("org.aspectj.lang.JoinPoint"));
}
}
public Var getThisJoinPointVar() {
requireThisJoinPoint(false);
return thisJoinPointVar;
}
void initializeThisJoinPoint() {
if (thisJoinPointVar == null) return;
if (isThisJoinPointLazy) {
isThisJoinPointLazy = checkLazyTjp();
}
if (isThisJoinPointLazy) {
createThisJoinPoint(); // make sure any state needed is initialized, but throw the instructions out
if (lazyTjpConsumers == 1) return; // special case only one lazyTjpUser
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
il.append(InstructionConstants.ACONST_NULL);
il.append(thisJoinPointVar.createStore(fact));
range.insert(il, Range.OutsideBefore);
} else {
InstructionFactory fact = getFactory();
InstructionList il = createThisJoinPoint();
il.append(thisJoinPointVar.createStore(fact));
range.insert(il, Range.OutsideBefore);
}
}
private boolean checkLazyTjp() {
// check for around advice
for (Iterator i = mungers.iterator(); i.hasNext();) {
ShadowMunger munger = (ShadowMunger) i.next();
if (munger instanceof Advice) {
if ( ((Advice)munger).getKind() == AdviceKind.Around) {
world.getLint().canNotImplementLazyTjp.signal(
new String[] {toString()},
getSourceLocation(),
new ISourceLocation[] { munger.getSourceLocation() }
);
return false;
}
}
}
return true;
}
InstructionList loadThisJoinPoint() {
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
if (isThisJoinPointLazy) {
il.append(createThisJoinPoint());
if (lazyTjpConsumers > 1) {
il.append(thisJoinPointVar.createStore(fact));
InstructionHandle end = il.append(thisJoinPointVar.createLoad(fact));
il.insert(InstructionFactory.createBranchInstruction(Constants.IFNONNULL, end));
il.insert(thisJoinPointVar.createLoad(fact));
}
} else {
thisJoinPointVar.appendLoad(il, fact);
}
return il;
}
InstructionList createThisJoinPoint() {
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
BcelVar staticPart = getThisJoinPointStaticPartBcelVar();
staticPart.appendLoad(il, fact);
if (hasThis()) {
((BcelVar)getThisVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
if (hasTarget()) {
((BcelVar)getTargetVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
switch(getArgCount()) {
case 0:
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 1:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.resolve(ResolvedTypeX.OBJECT));
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 2:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.resolve(ResolvedTypeX.OBJECT));
((BcelVar)getArgVar(1)).appendLoadAndConvert(il, fact, world.resolve(ResolvedTypeX.OBJECT));
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
default:
il.append(makeArgsObjectArray());
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, new ArrayType(Type.OBJECT, 1)},
Constants.INVOKESTATIC));
break;
}
return il;
}
public BcelVar getThisJoinPointStaticPartBcelVar() {
if (thisJoinPointStaticPartVar == null) {
Field field = getEnclosingClass().getTjpField(this);
thisJoinPointStaticPartVar =
new BcelFieldRef(
world.resolve(TypeX.forName("org.aspectj.lang.JoinPoint$StaticPart")),
getEnclosingClass().getClassName(),
field.getName());
}
return thisJoinPointStaticPartVar;
}
public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() {
if (enclosingShadow == null) {
// the enclosing of an execution is itself
return getThisJoinPointStaticPartBcelVar();
} else {
return ((BcelShadow)enclosingShadow).getThisJoinPointStaticPartBcelVar();
}
}
//??? need to better understand all the enclosing variants
public Member getEnclosingCodeSignature() {
if (getKind().isEnclosingKind()) {
return getSignature();
} else if (enclosingShadow == null) {
return getEnclosingMethod().getMemberView();
} else {
return enclosingShadow.getSignature();
}
}
private InstructionList makeArgsObjectArray() {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY);
final InstructionList il = new InstructionList();
int alen = getArgCount() ;
il.append(Utility.createConstant(fact, alen));
il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(il, fact);
int stateIndex = 0;
for (int i = 0, len = getArgCount(); i<len; i++) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, (BcelVar)getArgVar(i));
stateIndex++;
}
arrayVar.appendLoad(il, fact);
return il;
}
// ---- initializing var tables
/* initializing this is doesn't do anything, because this
* is protected from side-effects, so we don't need to copy its location
*/
private void initializeThisVar() {
if (thisVar != null) return;
thisVar = new BcelVar(getThisType().resolve(world), 0);
thisVar.setPositionInAroundState(0);
}
public void initializeTargetVar() {
InstructionFactory fact = getFactory();
if (targetVar != null) return;
if (getKind().isTargetSameAsThis()) {
if (hasThis()) initializeThisVar();
targetVar = thisVar;
} else {
initializeArgVars(); // gotta pop off the args before we find the target
TypeX type = getTargetType();
targetVar = genTempVar(type, "ajc$target");
range.insert(targetVar.createStore(fact), Range.OutsideBefore);
targetVar.setPositionInAroundState(hasThis() ? 1 : 0);
}
}
public void initializeArgVars() {
if (argVars != null) return;
InstructionFactory fact = getFactory();
int len = getArgCount();
argVars = new BcelVar[len];
int positionOffset = (hasTarget() ? 1 : 0) +
((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
if (getKind().argsOnStack()) {
// we move backwards because we're popping off the stack
for (int i = len - 1; i >= 0; i--) {
TypeX type = getArgType(i);
BcelVar tmp = genTempVar(type, "ajc$arg" + i);
range.insert(tmp.createStore(getFactory()), Range.OutsideBefore);
int position = i;
position += positionOffset;
tmp.setPositionInAroundState(position);
argVars[i] = tmp;
}
} else {
int index = 0;
if (arg0HoldsThis()) index++;
for (int i = 0; i < len; i++) {
TypeX type = getArgType(i);
BcelVar tmp = genTempVar(type, "ajc$arg" + i);
range.insert(tmp.createCopyFrom(fact, index), Range.OutsideBefore);
argVars[i] = tmp;
int position = i;
position += positionOffset;
// System.out.println("set position: " + tmp + ", " + position + " in " + this);
// System.out.println(" hasThis: " + hasThis() + ", hasTarget: " + hasTarget());
tmp.setPositionInAroundState(position);
index += type.getSize();
}
}
}
public void initializeForAroundClosure() {
initializeArgVars();
if (hasTarget()) initializeTargetVar();
if (hasThis()) initializeThisVar();
// System.out.println("initialized: " + this + " thisVar = " + thisVar);
}
// ---- weave methods
void weaveBefore(BcelAdvice munger) {
range.insert(
munger.getAdviceInstructions(this, null, range.getRealStart()),
Range.InsideBefore);
}
public void weaveAfter(BcelAdvice munger) {
weaveAfterThrowing(munger, TypeX.THROWABLE);
weaveAfterReturning(munger);
}
/**
* We guarantee that the return value is on the top of the stack when
* munger.getAdviceInstructions() will be run
* (Unless we have a void return type in which case there's nothing)
*/
public void weaveAfterReturning(BcelAdvice munger) {
// InstructionFactory fact = getFactory();
List returns = new ArrayList();
Instruction ret = null;
for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
if (ih.getInstruction() instanceof ReturnInstruction) {
returns.add(ih);
ret = Utility.copyInstruction(ih.getInstruction());
}
}
InstructionList retList;
InstructionHandle afterAdvice;
if (ret != null) {
retList = new InstructionList(ret);
afterAdvice = retList.getStart();
} else /* if (munger.hasDynamicTests()) */ {
retList = new InstructionList(InstructionConstants.NOP);
afterAdvice = retList.getStart();
// } else {
// retList = new InstructionList();
// afterAdvice = null;
}
InstructionList advice = new InstructionList();
BcelVar tempVar = null;
if (munger.hasExtraParameter()) {
TypeX tempVarType = getReturnType();
if (tempVarType.equals(ResolvedTypeX.VOID)) {
tempVar = genTempVar(TypeX.OBJECT);
advice.append(InstructionConstants.ACONST_NULL);
tempVar.appendStore(advice, getFactory());
} else {
tempVar = genTempVar(tempVarType);
advice.append(InstructionFactory.createDup(tempVarType.getSize()));
tempVar.appendStore(advice, getFactory());
}
}
advice.append(munger.getAdviceInstructions(this, tempVar, afterAdvice));
if (ret != null) {
InstructionHandle gotoTarget = advice.getStart();
for (Iterator i = returns.iterator(); i.hasNext();) {
InstructionHandle ih = (InstructionHandle) i.next();
Utility.replaceInstruction(
ih,
InstructionFactory.createBranchInstruction(
Constants.GOTO,
gotoTarget),
enclosingMethod);
}
range.append(advice);
range.append(retList);
} else {
range.append(advice);
range.append(retList);
}
}
public void weaveAfterThrowing(BcelAdvice munger, TypeX catchType) {
// a good optimization would be not to generate anything here
// if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
// a shadow, inside me).
if (getRange().getStart().getNext() == getRange().getEnd()) return;
InstructionFactory fact = getFactory();
InstructionList handler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
exceptionVar.appendStore(handler, fact);
InstructionList endHandler = new InstructionList(
exceptionVar.createLoad(fact));
handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart()));
handler.append(endHandler);
handler.append(InstructionConstants.ATHROW);
InstructionHandle handlerStart = handler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = handler.append(InstructionConstants.NOP);
handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
InstructionHandle protectedEnd = handler.getStart();
range.insert(handler, Range.InsideAfter);
enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(),
handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), //???Type.THROWABLE,
// high priority if our args are on the stack
getKind().hasHighPriorityExceptions());
}
//??? this shares a lot of code with the above weaveAfterThrowing
//??? would be nice to abstract that to say things only once
public void weaveSoftener(BcelAdvice munger, TypeX catchType) {
// a good optimization would be not to generate anything here
// if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
// a shadow, inside me).
if (getRange().getStart().getNext() == getRange().getEnd()) return;
InstructionFactory fact = getFactory();
InstructionList handler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
exceptionVar.appendStore(handler, fact);
handler.append(fact.createNew(NameMangler.SOFT_EXCEPTION_TYPE));
handler.append(InstructionFactory.createDup(1));
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createInvoke(NameMangler.SOFT_EXCEPTION_TYPE, "<init>",
Type.VOID, new Type[] { Type.THROWABLE }, Constants.INVOKESPECIAL)); //??? special
handler.append(InstructionConstants.ATHROW);
InstructionHandle handlerStart = handler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = range.getEnd();//handler.append(fact.NOP);
handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
InstructionHandle protectedEnd = handler.getStart();
range.insert(handler, Range.InsideAfter);
enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(),
handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType),
// high priority if our args are on the stack
getKind().hasHighPriorityExceptions());
}
public void weavePerObjectEntry(final BcelAdvice munger, final BcelVar onVar) {
final InstructionFactory fact = getFactory();
InstructionList entryInstructions = new InstructionList();
InstructionList entrySuccessInstructions = new InstructionList();
onVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
Utility.createInvoke(fact, world,
AjcMemberMaker.perObjectBind(munger.getConcreteAspect())));
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveCflowEntry(final BcelAdvice munger, final Member cflowStackField) {
final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry ||
munger.getKind() == AdviceKind.PerCflowEntry;
final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionFactory fact = getFactory();
final BcelVar testResult = genTempVar(ResolvedTypeX.BOOLEAN);
InstructionList entryInstructions = new InstructionList();
{
InstructionList entrySuccessInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
entryInstructions.append(Utility.createConstant(fact, 0));
testResult.appendStore(entryInstructions, fact);
entrySuccessInstructions.append(Utility.createConstant(fact, 1));
testResult.appendStore(entrySuccessInstructions, fact);
}
if (isPer) {
entrySuccessInstructions.append(
fact.createInvoke(munger.getConcreteAspect().getName(),
NameMangler.PERCFLOW_PUSH_METHOD,
Type.VOID,
new Type[] { },
Constants.INVOKESTATIC));
} else {
BcelVar[] cflowStateVars = munger.getExposedStateAsBcelVars();
BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY);
int alen = cflowStateVars.length;
entrySuccessInstructions.append(Utility.createConstant(fact, alen));
entrySuccessInstructions.append(
(Instruction) fact.createNewArray(Type.OBJECT, (short) 1));
arrayVar.appendStore(entrySuccessInstructions, fact);
for (int i = 0; i < alen; i++) {
arrayVar.appendConvertableArrayStore(
entrySuccessInstructions,
fact,
i,
cflowStateVars[i]);
}
entrySuccessInstructions.append(
Utility.createGet(fact, cflowStackField));
arrayVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID,
new Type[] { objectArrayType },
Constants.INVOKEVIRTUAL));
}
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
}
// this is the same for both per and non-per
weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) {
public InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice) {
InstructionList exitInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
testResult.appendLoad(exitInstructions, fact);
exitInstructions.append(
InstructionFactory.createBranchInstruction(
Constants.IFEQ,
ifNoAdvice));
}
exitInstructions.append(Utility.createGet(fact, cflowStackField));
exitInstructions
.append(
fact
.createInvoke(
NameMangler.CFLOW_STACK_TYPE,
"pop",
Type.VOID,
new Type[] {
}, Constants.INVOKEVIRTUAL));
return exitInstructions;
}
});
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveAroundInline(
BcelAdvice munger,
boolean hasDynamicTest)
{
/* Implementation notes:
*
* AroundInline still extracts the instructions of the original shadow into
* an extracted method. This allows inlining of even that advice that doesn't
* call proceed or calls proceed more than once.
*
* It extracts the instructions of the original shadow into a method.
*
* Then it extracts the instructions of the advice into a new method defined on
* this enclosing class. This new method can then be specialized as below.
*
* Then it searches in the instructions of the advice for any call to the
* proceed method.
*
* At such a call, there is stuff on the stack representing the arguments to
* proceed. Pop these into the frame.
*
* Now build the stack for the call to the extracted method, taking values
* either from the join point state or from the new frame locs from proceed.
* Now call the extracted method. The right return value should be on the
* stack, so no cast is necessary.
*
* If only one call to proceed is made, we can re-inline the original shadow.
* We are not doing that presently.
*
* If the body of the advice can be determined to not alter the stack, or if
* this shadow doesn't care about the stack, i.e. method-execution, then the
* new method for the advice can also be re-lined. We are not doing that
* presently.
*/
// !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...);
Member mungerSig = munger.getSignature();
ResolvedTypeX declaringType = world.resolve(mungerSig.getDeclaringType());
//??? might want some checks here to give better errors
BcelObjectType ot = BcelWorld.getBcelObjectType(declaringType);
LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig);
if (!adviceMethod.getCanInline())
{
weaveAroundClosure(munger, hasDynamicTest);
return;
}
// We can't inline around methods if they have around advice on them, this
// is because the weaving will extract the body and hence the proceed call.
//??? should consider optimizations to recognize simple cases that don't require body extraction
enclosingMethod.setCanInline(false);
// start by exposing various useful things into the frame
final InstructionFactory fact = getFactory();
// now generate the aroundBody method
LazyMethodGen extractedMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()));
// 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.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()));
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars();
String closureClassName =
NameMangler.makeClosureClassName(
getEnclosingClass().getType(),
getEnclosingClass().getNewGeneratedNameTag());
Member constructorSig = new Member(Member.CONSTRUCTOR,
TypeX.forName(closureClassName), 0, "<init>",
"([Ljava/lang/Object;)V");
BcelVar closureHolder = null;
// This is not being used currently since getKind() == preinitializaiton
// cannot happen in around advice
if (getKind() == PreInitialization) {
closureHolder = genTempVar(AjcMemberMaker.AROUND_CLOSURE_TYPE);
}
InstructionList closureInstantiation =
makeClosureInstantiation(constructorSig, closureHolder);
/*LazyMethodGen constructor = */
makeClosureClassAndReturnConstructor(
closureClassName,
callbackMethod,
makeProceedArgumentMap(adviceVars)
);
InstructionList returnConversionCode;
if (getKind() == PreInitialization) {
returnConversionCode = new InstructionList();
BcelVar stateTempVar = genTempVar(TypeX.OBJECTARRAY);
closureHolder.appendLoad(returnConversionCode, fact);
returnConversionCode.append(
Utility.createInvoke(
fact,
world,
AjcMemberMaker.aroundClosurePreInitializationGetter()));
stateTempVar.appendStore(returnConversionCode, fact);
Type[] stateTypes = getSuperConstructorParameterTypes();
returnConversionCode.append(InstructionConstants.ALOAD_0); // put "this" back on the stack
for (int i = 0, len = stateTypes.length; i < len; i++) {
stateTempVar.appendConvertableArrayLoad(
returnConversionCode,
fact,
i,
world.resolve(BcelWorld.fromBcel(stateTypes[i])));
}
} else {
returnConversionCode =
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType()),
callbackMethod.getReturnType());
if (!isFallsThrough()) {
returnConversionCode.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
}
}
InstructionList advice = new InstructionList();
advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation));
// advice.append(closureInstantiation);
advice.append(munger.getNonTestAdviceInstructions(this));
advice.append(returnConversionCode);
if (!hasDynamicTest) {
range.append(advice);
} else {
InstructionList callback = makeCallToCallback(callbackMethod);
InstructionList postCallback = new InstructionList();
if (terminatesWithReturn()) {
callback.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
} else {
advice.append(
InstructionFactory.createBranchInstruction(
Constants.GOTO,
postCallback.append(InstructionConstants.NOP)));
}
range.append(
munger.getTestInstructions(
this,
advice.getStart(),
callback.getStart(),
advice.getStart()));
range.append(advice);
range.append(callback);
range.append(postCallback);
}
}
// exposed for testing
InstructionList makeCallToCallback(LazyMethodGen callbackMethod) {
InstructionFactory fact = getFactory();
InstructionList callback = new InstructionList();
if (thisVar != null) {
callback.append(InstructionConstants.ALOAD_0);
}
if (targetVar != null && targetVar != thisVar) {
callback.append(BcelRenderer.renderExpr(fact, world, targetVar));
}
callback.append(BcelRenderer.renderExprs(fact, world, argVars));
// remember to render tjps
if (thisJoinPointVar != null) {
callback.append(BcelRenderer.renderExpr(fact, world, thisJoinPointVar));
}
callback.append(Utility.createInvoke(fact, callbackMethod));
return callback;
}
/** side-effect-free */
private InstructionList makeClosureInstantiation(Member constructor, BcelVar holder) {
// LazyMethodGen constructor) {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(TypeX.OBJECTARRAY);
//final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionList il = new InstructionList();
int alen = getArgCount() + (thisVar == null ? 0 : 1) +
((targetVar != null && targetVar != thisVar) ? 1 : 0) +
(thisJoinPointVar == null ? 0 : 1);
il.append(Utility.createConstant(fact, alen));
il.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(il, fact);
int stateIndex = 0;
if (thisVar != null) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisVar);
thisVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
if (targetVar != null && targetVar != thisVar) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, targetVar);
targetVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
for (int i = 0, len = getArgCount(); i<len; i++) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, argVars[i]);
argVars[i].setPositionInAroundState(stateIndex);
stateIndex++;
}
if (thisJoinPointVar != null) {
arrayVar.appendConvertableArrayStore(il, fact, stateIndex, thisJoinPointVar);
thisJoinPointVar.setPositionInAroundState(stateIndex);
stateIndex++;
}
il.append(fact.createNew(new ObjectType(constructor.getDeclaringType().getName())));
il.append(new DUP());
arrayVar.appendLoad(il, fact);
il.append(Utility.createInvoke(fact, world, constructor));
if (getKind() == PreInitialization) {
il.append(InstructionConstants.DUP);
holder.appendStore(il, fact);
}
return il;
}
private IntMap makeProceedArgumentMap(BcelVar[] adviceArgs) {
//System.err.println("coming in with " + Arrays.asList(adviceArgs));
IntMap ret = new IntMap();
for(int i = 0, len = adviceArgs.length; i < len; i++) {
BcelVar v = (BcelVar) adviceArgs[i];
if (v == null) continue; // XXX we don't know why this is required
int pos = v.getPositionInAroundState();
if (pos >= 0) { // need this test to avoid args bound via cflow
ret.put(pos, i);
}
}
//System.err.println("returning " + ret);
return ret;
}
/**
*
*
* @param callbackMethod the method we will call back to when our run method gets called.
*
* @param proceedMap A map from state position to proceed argument position. May be
* non covering on state position.
*/
private LazyMethodGen makeClosureClassAndReturnConstructor(
String closureClassName,
LazyMethodGen callbackMethod,
IntMap proceedMap)
{
String superClassName = "org.aspectj.runtime.internal.AroundClosure";
Type objectArrayType = new ArrayType(Type.OBJECT, 1);
LazyClassGen closureClass = new LazyClassGen(closureClassName,
superClassName,
getEnclosingClass().getFileName(),
Modifier.PUBLIC,
new String[] {});
InstructionFactory fact = new InstructionFactory(closureClass.getConstantPoolGen());
// constructor
LazyMethodGen constructor = new LazyMethodGen(Modifier.PUBLIC,
Type.VOID,
"<init>",
new Type[] {objectArrayType},
new String[] {},
closureClass);
InstructionList cbody = constructor.getBody();
cbody.append(InstructionFactory.createLoad(Type.OBJECT, 0));
cbody.append(InstructionFactory.createLoad(objectArrayType, 1));
cbody.append(fact.createInvoke(superClassName, "<init>", Type.VOID,
new Type[] {objectArrayType}, Constants.INVOKESPECIAL));
cbody.append(InstructionFactory.createReturn(Type.VOID));
closureClass.addMethodGen(constructor);
// method
LazyMethodGen runMethod = new LazyMethodGen(Modifier.PUBLIC,
Type.OBJECT,
"run",
new Type[] {objectArrayType},
new String[] {},
closureClass);
InstructionList mbody = runMethod.getBody();
BcelVar proceedVar = new BcelVar(TypeX.OBJECTARRAY.resolve(world), 1);
// int proceedVarIndex = 1;
BcelVar stateVar =
new BcelVar(TypeX.OBJECTARRAY.resolve(world), runMethod.allocateLocal(1));
// int stateVarIndex = runMethod.allocateLocal(1);
mbody.append(InstructionFactory.createThis());
mbody.append(fact.createGetField(superClassName, "state", objectArrayType));
mbody.append(stateVar.createStore(fact));
// mbody.append(fact.createStore(objectArrayType, stateVarIndex));
Type[] stateTypes = callbackMethod.getArgumentTypes();
for (int i=0, len=stateTypes.length; i < len; i++) {
Type stateType = stateTypes[i];
ResolvedTypeX stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
if (proceedMap.hasKey(i)) {
mbody.append(
proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i),
stateTypeX));
} else {
mbody.append(
stateVar.createConvertableArrayLoad(fact, i,
stateTypeX));
}
}
mbody.append(Utility.createInvoke(fact, callbackMethod));
if (getKind() == PreInitialization) {
mbody.append(Utility.createSet(
fact,
AjcMemberMaker.aroundClosurePreInitializationField()));
mbody.append(InstructionConstants.ACONST_NULL);
} else {
mbody.append(
Utility.createConversion(
fact,
callbackMethod.getReturnType(),
Type.OBJECT));
}
mbody.append(InstructionFactory.createReturn(Type.OBJECT));
closureClass.addMethodGen(runMethod);
// class
getEnclosingClass().addGeneratedInner(closureClass);
return constructor;
}
// ---- extraction methods
public LazyMethodGen extractMethod(String newMethodName) {
LazyMethodGen.assertGoodBody(range.getBody(), newMethodName);
if (!getKind().allowsExtraction()) throw new BCException();
LazyMethodGen freshMethod = createMethodGen(newMethodName);
// 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);
return freshMethod;
}
private void addPreInitializationReturnCode(
LazyMethodGen extractedMethod,
Type[] superConstructorTypes)
{
InstructionList body = extractedMethod.getBody();
final InstructionFactory fact = getFactory();
BcelVar arrayVar = new BcelVar(
world.resolve(TypeX.OBJECTARRAY),
extractedMethod.allocateLocal(1));
int len = superConstructorTypes.length;
body.append(Utility.createConstant(fact, len));
body.append((Instruction)fact.createNewArray(Type.OBJECT, (short)1));
arrayVar.appendStore(body, fact);
for (int i = len - 1; i >= 0; i++) {
// convert thing on top of stack to object
body.append(
Utility.createConversion(fact, superConstructorTypes[i], Type.OBJECT));
// push object array
arrayVar.appendLoad(body, fact);
// swap
body.append(InstructionConstants.SWAP);
// do object array store.
body.append(Utility.createConstant(fact, i));
body.append(InstructionConstants.SWAP);
body.append(InstructionFactory.createArrayStore(Type.OBJECT));
}
arrayVar.appendLoad(body, fact);
body.append(InstructionConstants.ARETURN);
}
private Type[] getSuperConstructorParameterTypes() {
// assert getKind() == PreInitialization
InstructionHandle superCallHandle = getRange().getEnd().getNext();
InvokeInstruction superCallInstruction =
(InvokeInstruction) superCallHandle.getInstruction();
return superCallInstruction.getArgumentTypes(
getEnclosingClass().getConstantPoolGen());
}
/** make a map from old frame location to new frame location. Any unkeyed frame
* location picks out a copied local */
private IntMap makeRemap() {
IntMap ret = new IntMap(5);
int reti = 0;
if (thisVar != null) {
ret.put(0, reti++); // thisVar guaranteed to be 0
}
if (targetVar != null && targetVar != thisVar) {
ret.put(targetVar.getSlot(), reti++);
}
for (int i = 0, len = argVars.length; i < len; i++) {
ret.put(argVars[i].getSlot(), reti);
reti += argVars[i].getType().getSize();
}
if (thisJoinPointVar != null) {
ret.put(thisJoinPointVar.getSlot(), reti++);
}
// we not only need to put the arguments, we also need to remap their
// aliases, which we so helpfully put into temps at the beginning of this join
// point.
if (! getKind().argsOnStack()) {
int oldi = 0;
int newi = 0;
// if we're passing in a this and we're not argsOnStack we're always
// passing in a target too
if (arg0HoldsThis()) { ret.put(0, 0); oldi++; newi+=1; }
//assert targetVar == thisVar
for (int i = 0; i < getArgCount(); i++) {
TypeX type = getArgType(i);
ret.put(oldi, newi);
oldi += type.getSize();
newi += type.getSize();
}
}
// System.err.println("making remap for : " + this);
// if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot());
// if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot());
// System.err.println(ret);
return ret;
}
/**
* The new method always static.
* It may take some extra arguments: this, target.
* If it's argsOnStack, then it must take both this/target
* If it's argsOnFrame, it shares this and target.
* ??? rewrite this to do less array munging, please
*/
private LazyMethodGen createMethodGen(String newMethodName) {
Type[] parameterTypes = BcelWorld.makeBcelTypes(getArgTypes());
int modifiers = Modifier.FINAL;
// XXX some bug
// if (! isExpressionKind() && getSignature().isStrict(world)) {
// modifiers |= Modifier.STRICT;
// }
modifiers |= Modifier.STATIC;
if (targetVar != null && targetVar != thisVar) {
TypeX targetType = getTargetType();
ResolvedMember resolvedMember = getSignature().resolve(world);
if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) &&
!samePackage(targetType.getPackageName(), getEnclosingType().getPackageName()))
{
if (!targetType.isAssignableFrom(getThisType(), world)) {
throw new BCException("bad bytecode");
}
targetType = getThisType();
}
parameterTypes = addType(BcelWorld.makeBcelType(targetType), parameterTypes);
}
if (thisVar != null) {
TypeX thisType = getThisType();
parameterTypes = addType(BcelWorld.makeBcelType(thisType), parameterTypes);
}
// We always want to pass down thisJoinPoint in case we have already woven
// some advice in here. If we only have a single piece of around advice on a
// join point, it is unnecessary to accept (and pass) tjp.
if (thisJoinPointVar != null) {
parameterTypes = addTypeToEnd(LazyClassGen.tjpType, parameterTypes);
}
TypeX returnType;
if (getKind() == PreInitialization) {
returnType = TypeX.OBJECTARRAY;
} else {
returnType = getReturnType();
}
return
new LazyMethodGen(
modifiers,
BcelWorld.makeBcelType(returnType),
newMethodName,
parameterTypes,
new String[0],
// XXX again, we need to look up methods!
// TypeX.getNames(getSignature().getExceptions(world)),
getEnclosingClass());
}
private boolean samePackage(String p1, String p2) {
if (p1 == null) return p2 == null;
if (p2 == null) return false;
return p1.equals(p2);
}
private Type[] addType(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[0] = type;
System.arraycopy(types, 0, ret, 1, len);
return ret;
}
private Type[] addTypeToEnd(Type type, Type[] types) {
int len = types.length;
Type[] ret = new Type[len+1];
ret[len] = type;
System.arraycopy(types, 0, ret, 0, len);
return ret;
}
public BcelVar genTempVar(TypeX typeX) {
return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize()));
}
// public static final boolean CREATE_TEMP_NAMES = true;
public BcelVar genTempVar(TypeX typeX, String localName) {
BcelVar tv = genTempVar(typeX);
// if (CREATE_TEMP_NAMES) {
// for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
// if (Range.isRangeHandle(ih)) continue;
// ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot()));
// }
// }
return tv;
}
// eh doesn't think we need to garbage collect these (64K is a big number...)
private int genTempVarIndex(int size) {
return enclosingMethod.allocateLocal(size);
}
public InstructionFactory getFactory() {
return getEnclosingClass().getFactory();
}
public ISourceLocation getSourceLocation() {
int sourceLine = getSourceLine();
if (sourceLine == 0) {
// 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;
}
}
|
45,489
|
Bug 45489 Structure model is wrong when re-opened
|
Some elements have the wrong kinds when a saved structure model is loaded. E.g. if I close then re-open the eclipse workbench classes are shown as interface in the outline view. Also if I traverse the tree with the code below I get the wrong kinds assigned to classed, interfaces, aspects and import declarations. List list = StructureModelUtil.getPackagesInModel(); for(Iterator i = list.iterator(); i.hasNext();){ Object[] o = (Object[])i.next(); IProgramElement node = (IProgramElement)o[0]; List files = StructureModelUtil.getFilesInPackage(node); for(Iterator i2 = files.iterator(); i2.hasNext();){ IProgramElement file = (IProgramElement)i2.next (); System.out.println("file " + file.getKind ().toString() + ", " + file.getName()); boolean added2 = false; List file_children = file.getChildren(); // file children can be classes, aspects or other things for(Iterator i3 = file_children.iterator(); i3.hasNext();){ IProgramElement file_child = (IProgramElement)i3.next(); System.out.println("kind: " + file_child.getKind().toString() +", " + file_child.getName());
|
resolved fixed
|
669cd7c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-19T16:02:06Z
| 2003-10-24T10:06:40Z
|
ajde/testsrc/org/aspectj/ajde/AjdeTests.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.ajde;
import junit.framework.*;
public class AjdeTests extends TestCase {
public static String TESTDATA_PATH = "../ajde/testdata";
public static Test suite() {
TestSuite suite = new TestSuite(AjdeTests.class.getName());
//$JUnit-BEGIN$
suite.addTestSuite(BuildOptionsTest.class);
suite.addTestSuite(BuildConfigurationTests.class);
suite.addTestSuite(StructureModelRegressionTest.class);
suite.addTestSuite(StructureModelTest.class);
suite.addTestSuite(VersionTest.class);
suite.addTestSuite(CompilerMessagesTest.class);
suite.addTestSuite(AsmDeclarationsTest.class);
suite.addTestSuite(AsmRelationshipsTest.class);
suite.addTestSuite(InpathTestcase.class);
suite.addTestSuite(ResourceCopyTestCase.class);
suite.addTestSuite(ModelPerformanceTest.class);
//$JUnit-END$
return suite;
}
public AjdeTests(String name) { super(name); }
}
|
45,489
|
Bug 45489 Structure model is wrong when re-opened
|
Some elements have the wrong kinds when a saved structure model is loaded. E.g. if I close then re-open the eclipse workbench classes are shown as interface in the outline view. Also if I traverse the tree with the code below I get the wrong kinds assigned to classed, interfaces, aspects and import declarations. List list = StructureModelUtil.getPackagesInModel(); for(Iterator i = list.iterator(); i.hasNext();){ Object[] o = (Object[])i.next(); IProgramElement node = (IProgramElement)o[0]; List files = StructureModelUtil.getFilesInPackage(node); for(Iterator i2 = files.iterator(); i2.hasNext();){ IProgramElement file = (IProgramElement)i2.next (); System.out.println("file " + file.getKind ().toString() + ", " + file.getName()); boolean added2 = false; List file_children = file.getChildren(); // file children can be classes, aspects or other things for(Iterator i3 = file_children.iterator(); i3.hasNext();){ IProgramElement file_child = (IProgramElement)i3.next(); System.out.println("kind: " + file_child.getKind().toString() +", " + file_child.getName());
|
resolved fixed
|
669cd7c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-19T16:02:06Z
| 2003-10-24T10:06:40Z
|
ajde/testsrc/org/aspectj/ajde/SavedModelConsistencyTest.java
| |
45,489
|
Bug 45489 Structure model is wrong when re-opened
|
Some elements have the wrong kinds when a saved structure model is loaded. E.g. if I close then re-open the eclipse workbench classes are shown as interface in the outline view. Also if I traverse the tree with the code below I get the wrong kinds assigned to classed, interfaces, aspects and import declarations. List list = StructureModelUtil.getPackagesInModel(); for(Iterator i = list.iterator(); i.hasNext();){ Object[] o = (Object[])i.next(); IProgramElement node = (IProgramElement)o[0]; List files = StructureModelUtil.getFilesInPackage(node); for(Iterator i2 = files.iterator(); i2.hasNext();){ IProgramElement file = (IProgramElement)i2.next (); System.out.println("file " + file.getKind ().toString() + ", " + file.getName()); boolean added2 = false; List file_children = file.getChildren(); // file children can be classes, aspects or other things for(Iterator i3 = file_children.iterator(); i3.hasNext();){ IProgramElement file_child = (IProgramElement)i3.next(); System.out.println("kind: " + file_child.getKind().toString() +", " + file_child.getName());
|
resolved fixed
|
669cd7c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-19T16:02:06Z
| 2003-10-24T10:06:40Z
|
asm/src/org/aspectj/asm/IProgramElement.java
|
/* *******************************************************************
* Copyright (c) 2003 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Mik Kersten initial implementation
* ******************************************************************/
package org.aspectj.asm;
import java.io.*;
import java.util.*;
import org.aspectj.bridge.*;
/**
* Represents program elements in the AspectJ containment hierarchy.
*
* @author Mik Kersten
*/
public interface IProgramElement extends Serializable {
public List/*IProgramElement*/ getChildren();
public void setChildren(List children);
public void addChild(IProgramElement child);
public IProgramElement getParent();
public void setParent(IProgramElement parent);
public String getName();
public void setName(String name);
public String getDetails();
public void setDetails(String details);
public IProgramElement.Kind getKind();
public void setKind(Kind kind);
public List getModifiers();
public void setModifiers(int i);
public Accessibility getAccessibility();
public String getDeclaringType(); // TODO: remove (Emacs uses it)
public String getPackageName();
public void setReturnType(String returnType);
public String getReturnType();
public String toSignatureString();
public void setRunnable(boolean value);
public boolean isRunnable();
public boolean isImplementor();
public void setImplementor(boolean value);
public boolean isOverrider();
public void setOverrider(boolean value);
public IMessage getMessage();
public void setMessage(IMessage message);
public ISourceLocation getSourceLocation();
public void setSourceLocation(ISourceLocation sourceLocation);
public String toString();
/**
* Includes information about the origin of the node.
*/
public String toLinkLabelString();
/**
* Includes name, parameter types (if any) and details (if any).
*/
public String toLabelString();
public List getParameterTypes();
public void setParameterTypes(List list);
public List getParameterNames();
public void setParameterNames(List list);
/**
* The format of the string handle is not specified, but is stable across
* compilation sessions.
*
* @return a string representtaion of this element
*/
public String getHandleIdentifier();
/**
* @return a string representation of this node and all of its children (recursive)
*/
public String toLongString();
public String getBytecodeName();
public String getBytecodeSignature();
public void setBytecodeName(String bytecodeName);
public void setBytecodeSignature(String bytecodeSignature);
public IProgramElement walk(HierarchyWalker walker);
/**
* Uses "typesafe enum" pattern.
*/
public static class Modifiers implements Serializable {
public static final Modifiers STATIC = new Modifiers("static");
public static final Modifiers FINAL = new Modifiers("final");
public static final Modifiers ABSTRACT = new Modifiers("abstract");
public static final Modifiers SYNCHRONIZED = new Modifiers("synchronized");
public static final Modifiers VOLATILE = new Modifiers("volatile");
public static final Modifiers STRICTFP = new Modifiers("strictfp");
public static final Modifiers TRANSIENT = new Modifiers("transient");
public static final Modifiers NATIVE = new Modifiers("native");
public static final Modifiers[] ALL = { STATIC, FINAL, ABSTRACT, SYNCHRONIZED, TRANSIENT, VOLATILE, STRICTFP, NATIVE };
private final String name;
private Modifiers(String name) {
this.name = name;
}
public String toString() {
return name;
}
// The 4 declarations below are necessary for serialization
private static int nextOrdinal = 0;
private final int ordinal = nextOrdinal++;
private Object readResolve() throws ObjectStreamException {
return ALL[ordinal];
}
}
/**
* Uses "typesafe enum" pattern.
*/
public static class Accessibility implements Serializable {
public static final Accessibility PUBLIC = new Accessibility("public");
public static final Accessibility PACKAGE = new Accessibility("package");
public static final Accessibility PROTECTED = new Accessibility("protected");
public static final Accessibility PRIVATE = new Accessibility("private");
public static final Accessibility PRIVILEGED = new Accessibility("privileged");
public static final Accessibility[] ALL = { PUBLIC, PACKAGE, PROTECTED, PRIVATE, PRIVILEGED };
private final String name;
private Accessibility(String name) {
this.name = name;
}
public String toString() {
return name;
}
// The 4 declarations below are necessary for serialization
private static int nextOrdinal = 0;
private final int ordinal = nextOrdinal++;
private Object readResolve() throws ObjectStreamException {
return ALL[ordinal];
}
}
/**
* Uses "typesafe enum" pattern.
*/
public static class Kind implements Serializable {
public static final Kind PROJECT = new Kind("project");
public static final Kind PACKAGE = new Kind("package");
public static final Kind FILE = new Kind("file");
public static final Kind FILE_JAVA = new Kind("java source file");
public static final Kind FILE_ASPECTJ = new Kind("aspect source file");
public static final Kind FILE_LST = new Kind("build configuration file");
public static final Kind IMPORT_REFERENCE = new Kind("import reference");
public static final Kind CLASS = new Kind("class");
public static final Kind INTERFACE = new Kind("interface");
public static final Kind ASPECT = new Kind("aspect");
public static final Kind INITIALIZER = new Kind("initializer");
public static final Kind INTER_TYPE_FIELD = new Kind("inter-type field");
public static final Kind INTER_TYPE_METHOD = new Kind("inter-type method");
public static final Kind INTER_TYPE_CONSTRUCTOR = new Kind("inter-type constructor");
public static final Kind INTER_TYPE_PARENT = new Kind("inter-type parent");
public static final Kind CONSTRUCTOR = new Kind("constructor");
public static final Kind METHOD = new Kind("method");
public static final Kind FIELD = new Kind("field");
public static final Kind POINTCUT = new Kind("pointcut");
public static final Kind ADVICE = new Kind("advice");
public static final Kind DECLARE_PARENTS = new Kind("declare parents");
public static final Kind DECLARE_WARNING = new Kind("declare warning");
public static final Kind DECLARE_ERROR = new Kind("declare error");
public static final Kind DECLARE_SOFT = new Kind("declare soft");
public static final Kind DECLARE_PRECEDENCE= new Kind("declare precedence");
public static final Kind CODE = new Kind("code");
public static final Kind ERROR = new Kind("error");
public static final Kind[] ALL =
{
PROJECT,
PACKAGE,
FILE,
FILE_JAVA,
FILE_ASPECTJ,
FILE_LST,
CLASS,
INTERFACE,
IMPORT_REFERENCE,
ASPECT,
INITIALIZER,
INTER_TYPE_FIELD,
INTER_TYPE_METHOD,
INTER_TYPE_CONSTRUCTOR,
INTER_TYPE_PARENT,
CONSTRUCTOR,
METHOD,
FIELD,
POINTCUT,
ADVICE,
DECLARE_PARENTS,
DECLARE_WARNING,
DECLARE_ERROR,
DECLARE_SOFT,
DECLARE_PRECEDENCE,
CODE,
ERROR };
public static Kind getKindForString(String kindString) {
for (int i = 0; i < ALL.length; i++) {
if (ALL[i].toString().equals(kindString)) return ALL[i];
}
return ERROR;
}
private final String name;
private Kind(String name) {
this.name = name;
}
public String toString() {
return name;
}
public static List getNonAJMemberKinds() {
List list = new ArrayList();
list.add(METHOD);
list.add(FIELD);
list.add(CONSTRUCTOR);
return list;
}
public boolean isMemberKind() {
return this == FIELD
|| this == METHOD
|| this == CONSTRUCTOR
|| this == POINTCUT
|| this == ADVICE;
}
public boolean isInterTypeMemberKind() {
return this == INTER_TYPE_CONSTRUCTOR
|| this == INTER_TYPE_FIELD
|| this == INTER_TYPE_METHOD;
}
public boolean isTypeKind() {
return this == CLASS
|| this == INTERFACE
|| this == ASPECT;
}
public boolean isSourceFileKind() {
return this == FILE_ASPECTJ
|| this == FILE_JAVA;
}
public boolean isDeclareKind() {
return name.startsWith("declare");
}
// The 4 declarations below are necessary for serialization
private static int nextOrdinal = 0;
private final int ordinal = nextOrdinal++;
private Object readResolve() throws ObjectStreamException {
return ALL[ordinal];
}
}
}
|
51,929
|
Bug 51929 Advice calling protected super method causing java.lang.VerifyError 'Bad access to protected data'
|
A java.lang.VerifyError is thrown at runtime complaining about 'Bad access to protected data' when advice, on a sub-aspect, that calls a protected method, on the super-aspect, is woven into a class. However another call to the same method woven into the same class but due to advice declared in the super-aspect works fine. The aspects were woven into precompiled (by sun's 1.4 javac) classes. The verify error occurs under both sun's 1.4 and blackdowns 1.3 VMs, and presumably all VMs. Workaround: Making the protected method public fixes the verify error. A test case is available in CVS: tests/bugs/protectedvf/... tests/ajcTestFailing.xml
|
resolved fixed
|
6ddae42
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-19T22:09:16Z
| 2004-02-13T02:40:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AccessForInlineVisitor.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
//import java.util.Arrays;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.lookup.InlineAccessFieldBinding;
import org.aspectj.ajdt.internal.compiler.lookup.InterTypeFieldBinding;
import org.aspectj.ajdt.internal.compiler.lookup.InterTypeMethodBinding;
import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedFieldBinding;
import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedHandler;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.ResolvedMember;
import org.eclipse.jdt.internal.compiler.ASTVisitor;
//import org.eclipse.jdt.internal.compiler.AbstractSyntaxTreeVisitorAdapter;
import org.eclipse.jdt.internal.compiler.ast.AllocationExpression;
import org.eclipse.jdt.internal.compiler.ast.AssertStatement;
import org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess;
import org.eclipse.jdt.internal.compiler.ast.FieldReference;
import org.eclipse.jdt.internal.compiler.ast.MessageSend;
import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference;
import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference;
import org.eclipse.jdt.internal.compiler.ast.SingleNameReference;
import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference;
import org.eclipse.jdt.internal.compiler.ast.ThisReference;
import org.eclipse.jdt.internal.compiler.lookup.ArrayBinding;
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
/**
* Walks the body of around advice
*
* Makes sure that all member accesses are to public members. Will
* convert to use access methods when needed to ensure that. This
* makes it much simpler (and more modular) to inline the body of
* an around.
*
* ??? constructors are handled different and require access to the
* target type. changes to org.eclipse.jdt.internal.compiler.ast.AllocationExpression
* would be required to fix this issue.
*
* @author Jim Hugunin
*/
public class AccessForInlineVisitor extends ASTVisitor {
PrivilegedHandler handler;
AspectDeclaration inAspect;
EclipseFactory world; // alias for inAspect.world
// set to true for ClassLiteralAccess and AssertStatement
// ??? A better answer would be to transform these into inlinable forms
public boolean isInlinable = true;
public AccessForInlineVisitor(AspectDeclaration inAspect, PrivilegedHandler handler) {
this.inAspect = inAspect;
this.world = inAspect.factory;
this.handler = handler;
}
public void endVisit(SingleNameReference ref, BlockScope scope) {
if (ref.binding instanceof FieldBinding) {
ref.binding = getAccessibleField((FieldBinding)ref.binding);
}
}
public void endVisit(QualifiedNameReference ref, BlockScope scope) {
//System.err.println("qref: " + ref + ", " + ref.binding.getClass().getName() + ", " + ref.codegenBinding.getClass().getName());
//System.err.println(" others: " + Arrays.asList(ref.otherBindings));
if (ref.binding instanceof FieldBinding) {
ref.binding = getAccessibleField((FieldBinding)ref.binding);
}
if (ref.otherBindings != null) {
for (int i=0, len=ref.otherBindings.length; i < len; i++) {
if (ref.otherBindings[i] instanceof FieldBinding) {
ref.otherBindings[i] = getAccessibleField((FieldBinding)ref.otherBindings[i]);
}
}
}
}
public void endVisit(FieldReference ref, BlockScope scope) {
if (ref.binding instanceof FieldBinding) {
ref.binding = getAccessibleField((FieldBinding)ref.binding);
}
}
public void endVisit(MessageSend send, BlockScope scope) {
if (send instanceof Proceed) return;
if (send.binding == null || !send.binding.isValidBinding()) return;
if (send.isSuperAccess() && !send.binding.isStatic()) {
send.receiver = new ThisReference(send.sourceStart, send.sourceEnd);
MethodBinding superAccessBinding = getSuperAccessMethod((MethodBinding)send.binding);
AstUtil.replaceMethodBinding(send, superAccessBinding);
} else if (!isPublic(send.binding)) {
send.syntheticAccessor = getAccessibleMethod((MethodBinding)send.binding);
}
}
public void endVisit(AllocationExpression send, BlockScope scope) {
if (send.binding == null || !send.binding.isValidBinding()) return;
//XXX TBD
if (isPublic(send.binding)) return;
makePublic(send.binding.declaringClass);
send.binding = handler.getPrivilegedAccessMethod(send.binding, send);
}
public void endVisit(
QualifiedTypeReference ref,
BlockScope scope)
{
makePublic(ref.resolvedType); //getTypeBinding(scope)); //??? might be trouble
}
public void endVisit(
SingleTypeReference ref,
BlockScope scope)
{
makePublic(ref.resolvedType); //getTypeBinding(scope)); //??? might be trouble
}
private FieldBinding getAccessibleField(FieldBinding binding) {
//System.err.println("checking field: " + binding);
if (!binding.isValidBinding()) return binding;
makePublic(binding.declaringClass);
if (isPublic(binding)) return binding;
if (binding instanceof PrivilegedFieldBinding) return binding;
if (binding instanceof InterTypeFieldBinding) return binding;
if (binding.isPrivate() && binding.declaringClass != inAspect.binding) {
binding.modifiers = AstUtil.makePackageVisible(binding.modifiers);
}
ResolvedMember m = EclipseFactory.makeResolvedMember(binding);
if (inAspect.accessForInline.containsKey(m)) return (FieldBinding)inAspect.accessForInline.get(m);
FieldBinding ret = new InlineAccessFieldBinding(inAspect, binding);
//System.err.println(" made accessor: " + ret);
inAspect.accessForInline.put(m, ret);
return ret;
}
private MethodBinding getAccessibleMethod(MethodBinding binding) {
if (!binding.isValidBinding()) return binding;
makePublic(binding.declaringClass); //???
if (isPublic(binding)) return binding;
if (binding instanceof InterTypeMethodBinding) return binding;
if (binding.isPrivate() && binding.declaringClass != inAspect.binding) {
binding.modifiers = AstUtil.makePackageVisible(binding.modifiers);
}
ResolvedMember m = EclipseFactory.makeResolvedMember(binding);
if (inAspect.accessForInline.containsKey(m)) return (MethodBinding)inAspect.accessForInline.get(m);
MethodBinding ret = world.makeMethodBinding(
AjcMemberMaker.inlineAccessMethodForMethod(inAspect.typeX, m)
);
inAspect.accessForInline.put(m, ret);
return ret;
}
static class SuperAccessMethodPair {
public ResolvedMember originalMethod;
public MethodBinding accessMethod;
public SuperAccessMethodPair(ResolvedMember originalMethod, MethodBinding accessMethod) {
this.originalMethod = originalMethod;
this.accessMethod = accessMethod;
}
}
private MethodBinding getSuperAccessMethod(MethodBinding binding) {
ResolvedMember m = EclipseFactory.makeResolvedMember(binding);
ResolvedMember superAccessMember = AjcMemberMaker.superAccessMethod(inAspect.typeX, m);
if (inAspect.superAccessForInline.containsKey(superAccessMember)) {
return ((SuperAccessMethodPair)inAspect.superAccessForInline.get(superAccessMember)).accessMethod;
}
MethodBinding ret = world.makeMethodBinding(superAccessMember);
inAspect.superAccessForInline.put(superAccessMember, new SuperAccessMethodPair(m, ret));
return ret;
}
private boolean isPublic(FieldBinding fieldBinding) {
// these are always effectively public to the inliner
if (fieldBinding instanceof InterTypeFieldBinding) return true;
return fieldBinding.isPublic();
}
private boolean isPublic(MethodBinding methodBinding) {
// these are always effectively public to the inliner
if (methodBinding instanceof InterTypeMethodBinding) return true;
return methodBinding.isPublic();
}
private void makePublic(TypeBinding binding) {
if (binding == null || !binding.isValidBinding()) return; // has already produced an error
if (binding instanceof ReferenceBinding) {
ReferenceBinding rb = (ReferenceBinding)binding;
if (!rb.isPublic()) handler.notePrivilegedTypeAccess(rb, null); //???
} else if (binding instanceof ArrayBinding) {
makePublic( ((ArrayBinding)binding).leafComponentType );
} else {
return;
}
}
public void endVisit(AssertStatement assertStatement, BlockScope scope) {
isInlinable = false;
}
public void endVisit(ClassLiteralAccess classLiteral, BlockScope scope) {
isInlinable = false;
}
}
|
51,929
|
Bug 51929 Advice calling protected super method causing java.lang.VerifyError 'Bad access to protected data'
|
A java.lang.VerifyError is thrown at runtime complaining about 'Bad access to protected data' when advice, on a sub-aspect, that calls a protected method, on the super-aspect, is woven into a class. However another call to the same method woven into the same class but due to advice declared in the super-aspect works fine. The aspects were woven into precompiled (by sun's 1.4 javac) classes. The verify error occurs under both sun's 1.4 and blackdowns 1.3 VMs, and presumably all VMs. Workaround: Making the protected method public fixes the verify error. A test case is available in CVS: tests/bugs/protectedvf/... tests/ajcTestFailing.xml
|
resolved fixed
|
6ddae42
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-19T22:09:16Z
| 2004-02-13T02:40:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.util.*;
import org.aspectj.ajdt.internal.compiler.ast.*;
import org.aspectj.ajdt.internal.core.builder.*;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.weaver.*;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.internal.compiler.ast.*;
import org.eclipse.jdt.internal.compiler.impl.*;
import org.eclipse.jdt.internal.compiler.lookup.*;
/**
*
* @author Jim Hugunin
*/
public class EclipseFactory {
public static boolean DEBUG = false;
public AjBuildManager buildManager;
private LookupEnvironment lookupEnvironment;
private Map/*TypeX, TypeBinding*/ typexToBinding = new HashMap();
//XXX currently unused
// private Map/*TypeBinding, ResolvedTypeX*/ bindingToResolvedTypeX = new HashMap();
public static EclipseFactory fromLookupEnvironment(LookupEnvironment env) {
AjLookupEnvironment aenv = (AjLookupEnvironment)env;
return aenv.factory;
}
public static EclipseFactory fromScopeLookupEnvironment(Scope scope) {
return fromLookupEnvironment(AstUtil.getCompilationUnitScope(scope).environment);
}
public EclipseFactory(LookupEnvironment lookupEnvironment) {
this.lookupEnvironment = lookupEnvironment;
}
public World getWorld() {
return buildManager.getWorld();
}
public void showMessage(
Kind kind,
String message,
ISourceLocation loc1,
ISourceLocation loc2)
{
getWorld().showMessage(kind, message, loc1, loc2);
}
public ResolvedTypeX fromEclipse(ReferenceBinding binding) {
if (binding == null) return ResolvedTypeX.MISSING;
//??? this seems terribly inefficient
//System.err.println("resolving: " + binding.getClass() + ", name = " + getName(binding));
ResolvedTypeX ret = getWorld().resolve(fromBinding(binding));
//System.err.println(" got: " + ret);
return ret;
}
public ResolvedTypeX[] fromEclipse(ReferenceBinding[] bindings) {
if (bindings == null) {
return ResolvedTypeX.NONE;
}
int len = bindings.length;
ResolvedTypeX[] ret = new ResolvedTypeX[len];
for (int i=0; i < len; i++) {
ret[i] = fromEclipse(bindings[i]);
}
return ret;
}
private static String getName(TypeBinding binding) {
if (binding instanceof ReferenceBinding) {
return new String(
CharOperation.concatWith(((ReferenceBinding)binding).compoundName, '.'));
}
String packageName = new String(binding.qualifiedPackageName());
String className = new String(binding.qualifiedSourceName()).replace('.', '$');
if (packageName.length() > 0) {
className = packageName + "." + className;
}
//XXX doesn't handle arrays correctly (or primitives?)
return new String(className);
}
//??? going back and forth between strings and bindings is a waste of cycles
public static TypeX fromBinding(TypeBinding binding) {
if (binding instanceof HelperInterfaceBinding) {
return ((HelperInterfaceBinding) binding).getTypeX();
}
if (binding == null || binding.qualifiedSourceName() == null) {
return ResolvedTypeX.MISSING;
}
return TypeX.forName(getName(binding));
}
public static TypeX[] fromBindings(TypeBinding[] bindings) {
if (bindings == null) return TypeX.NONE;
int len = bindings.length;
TypeX[] ret = new TypeX[len];
for (int i=0; i<len; i++) {
ret[i] = fromBinding(bindings[i]);
}
return ret;
}
public static ASTNode astForLocation(IHasPosition location) {
return new EmptyStatement(location.getStart(), location.getEnd());
}
public Collection getDeclareParents() {
return getWorld().getDeclareParents();
}
public Collection finishedTypeMungers = null;
public boolean areTypeMungersFinished() {
return finishedTypeMungers != null;
}
public void finishTypeMungers() {
// make sure that type mungers are
Collection ret = new ArrayList();
Collection baseTypeMungers =
getWorld().getCrosscuttingMembersSet().getTypeMungers();
for (Iterator i = baseTypeMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) i.next();
EclipseTypeMunger etm = makeEclipseTypeMunger(munger);
if (etm != null) ret.add(etm);
}
finishedTypeMungers = ret;
}
public EclipseTypeMunger makeEclipseTypeMunger(ConcreteTypeMunger concrete) {
//System.err.println("make munger: " + concrete);
//!!! can't do this if we want incremental to work right
//if (concrete instanceof EclipseTypeMunger) return (EclipseTypeMunger)concrete;
//System.err.println(" was not eclipse");
if (concrete.getMunger() != null && EclipseTypeMunger.supportsKind(concrete.getMunger().getKind())) {
AbstractMethodDeclaration method = null;
if (concrete instanceof EclipseTypeMunger) {
method = ((EclipseTypeMunger)concrete).getSourceMethod();
}
EclipseTypeMunger ret =
new EclipseTypeMunger(this, concrete.getMunger(), concrete.getAspectType(), method);
if (ret.getSourceLocation() == null) {
ret.setSourceLocation(concrete.getSourceLocation());
}
return ret;
} else {
return null;
}
}
public Collection getTypeMungers() {
//??? assert finishedTypeMungers != null
return finishedTypeMungers;
}
public static ResolvedMember makeResolvedMember(MethodBinding binding) {
//System.err.println("member for: " + binding + ", " + new String(binding.declaringClass.sourceName));
ResolvedMember ret = new ResolvedMember(
binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD,
fromBinding(binding.declaringClass),
binding.modifiers,
fromBinding(binding.returnType),
new String(binding.selector),
fromBindings(binding.parameters),
fromBindings(binding.thrownExceptions));
return ret;
}
public static ResolvedMember makeResolvedMember(FieldBinding binding) {
return new ResolvedMember(
Member.FIELD,
fromBinding(binding.declaringClass),
binding.modifiers,
fromBinding(binding.type),
new String(binding.name),
TypeX.NONE);
}
public TypeBinding makeTypeBinding(TypeX typeX) {
TypeBinding ret = (TypeBinding)typexToBinding.get(typeX);
if (ret == null) {
ret = makeTypeBinding1(typeX);
typexToBinding.put(typeX, ret);
}
if (ret == null) {
System.out.println("can't find: " + typeX);
}
return ret;
}
private TypeBinding makeTypeBinding1(TypeX typeX) {
if (typeX.isPrimitive()) {
if (typeX == ResolvedTypeX.BOOLEAN) return BaseTypes.BooleanBinding;
if (typeX == ResolvedTypeX.BYTE) return BaseTypes.ByteBinding;
if (typeX == ResolvedTypeX.CHAR) return BaseTypes.CharBinding;
if (typeX == ResolvedTypeX.DOUBLE) return BaseTypes.DoubleBinding;
if (typeX == ResolvedTypeX.FLOAT) return BaseTypes.FloatBinding;
if (typeX == ResolvedTypeX.INT) return BaseTypes.IntBinding;
if (typeX == ResolvedTypeX.LONG) return BaseTypes.LongBinding;
if (typeX == ResolvedTypeX.SHORT) return BaseTypes.ShortBinding;
if (typeX == ResolvedTypeX.VOID) return BaseTypes.VoidBinding;
throw new RuntimeException("weird primitive type " + typeX);
} else if (typeX.isArray()) {
int dim = 0;
while (typeX.isArray()) {
dim++;
typeX = typeX.getComponentType();
}
return lookupEnvironment.createArrayType(makeTypeBinding(typeX), dim);
} else {
String n = typeX.getName();
char[][] name = CharOperation.splitOn('.', n.toCharArray());
return lookupEnvironment.getType(name);
}
}
public TypeBinding[] makeTypeBindings(TypeX[] types) {
int len = types.length;
TypeBinding[] ret = new TypeBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = makeTypeBinding(types[i]);
}
return ret;
}
// just like the code above except it returns an array of ReferenceBindings
private ReferenceBinding[] makeReferenceBindings(TypeX[] types) {
int len = types.length;
ReferenceBinding[] ret = new ReferenceBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = (ReferenceBinding)makeTypeBinding(types[i]);
}
return ret;
}
public FieldBinding makeFieldBinding(ResolvedMember member) {
return new FieldBinding(member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
member.getModifiers(),
(ReferenceBinding)makeTypeBinding(member.getDeclaringType()),
Constant.NotAConstant);
}
public MethodBinding makeMethodBinding(ResolvedMember member) {
return new MethodBinding(member.getModifiers(),
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
makeReferenceBindings(member.getExceptions()),
(ReferenceBinding)makeTypeBinding(member.getDeclaringType()));
}
public MethodBinding makeMethodBindingForCall(Member member) {
return new MethodBinding(member.getCallsiteModifiers(),
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
new ReferenceBinding[0],
(ReferenceBinding)makeTypeBinding(member.getDeclaringType()));
}
public void finishedCompilationUnit(CompilationUnitDeclaration unit) {
if (buildManager.doGenerateModel()) {
AsmHierarchyBuilder.build(unit, buildManager.getStructureModel());
}
}
public void addTypeBinding(TypeBinding binding) {
typexToBinding.put(fromBinding(binding), binding);
}
public Shadow makeShadow(ASTNode location, ReferenceContext context) {
return EclipseShadow.makeShadow(this, location, context);
}
public Shadow makeShadow(ReferenceContext context) {
return EclipseShadow.makeShadow(this, (ASTNode) context, context);
}
public void addSourceTypeBinding(SourceTypeBinding binding) {
TypeDeclaration decl = binding.scope.referenceContext;
ResolvedTypeX.Name name = getWorld().lookupOrCreateName(TypeX.forName(getName(binding)));
EclipseSourceType t = new EclipseSourceType(name, this, binding, decl);
name.setDelegate(t);
if (decl instanceof AspectDeclaration) {
((AspectDeclaration)decl).typeX = name;
((AspectDeclaration)decl).concreteName = t;
}
ReferenceBinding[] memberTypes = binding.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
addSourceTypeBinding((SourceTypeBinding) memberTypes[i]);
}
}
}
|
51,929
|
Bug 51929 Advice calling protected super method causing java.lang.VerifyError 'Bad access to protected data'
|
A java.lang.VerifyError is thrown at runtime complaining about 'Bad access to protected data' when advice, on a sub-aspect, that calls a protected method, on the super-aspect, is woven into a class. However another call to the same method woven into the same class but due to advice declared in the super-aspect works fine. The aspects were woven into precompiled (by sun's 1.4 javac) classes. The verify error occurs under both sun's 1.4 and blackdowns 1.3 VMs, and presumably all VMs. Workaround: Making the protected method public fixes the verify error. A test case is available in CVS: tests/bugs/protectedvf/... tests/ajcTestFailing.xml
|
resolved fixed
|
6ddae42
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-19T22:09:16Z
| 2004-02-13T02:40:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/InlineAccessFieldBinding.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 org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.weaver.AjcMemberMaker;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.InvocationSite;
import org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.eclipse.jdt.internal.compiler.lookup.SyntheticAccessMethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
/**
* Used for field references within the body of an around advice
* to force the use of public access methods. This makes it possible
* for around advice to be inlined into any shadow to which it applies.
*
* ??? this is very similar to PrivilegedFieldBinding and is somewhat related
* to InterTypeFieldBinding. Maybe they have a common supertype?
*
* @author Jim Hugunin
*/
public class InlineAccessFieldBinding extends FieldBinding {
public SimpleSyntheticAccessMethodBinding reader;
public SimpleSyntheticAccessMethodBinding writer;
public FieldBinding baseField;
public InlineAccessFieldBinding(AspectDeclaration inAspect, FieldBinding baseField) {
super(baseField, baseField.declaringClass);
this.reader = new SimpleSyntheticAccessMethodBinding(
inAspect.factory.makeMethodBinding(
AjcMemberMaker.inlineAccessMethodForFieldGet(
inAspect.typeX, EclipseFactory.makeResolvedMember(baseField)
)));
this.writer = new SimpleSyntheticAccessMethodBinding(inAspect.factory.makeMethodBinding(
AjcMemberMaker.inlineAccessMethodForFieldSet(
inAspect.typeX, EclipseFactory.makeResolvedMember(baseField)
)));
this.constant = ASTNode.NotAConstant;
this.baseField = baseField;
}
public boolean canBeSeenBy(TypeBinding receiverType, InvocationSite invocationSite, Scope scope) {
return true;
}
public SyntheticAccessMethodBinding getAccessMethod(boolean isReadAccess) {
if (isReadAccess) return reader;
else return writer;
}
public boolean alwaysNeedsAccessMethod(boolean isReadAccess) { return true; }
public FieldBinding getFieldBindingForLookup() { return baseField; }
public String toString() { return "InlineAccess(" + baseField + ")"; }
}
|
51,929
|
Bug 51929 Advice calling protected super method causing java.lang.VerifyError 'Bad access to protected data'
|
A java.lang.VerifyError is thrown at runtime complaining about 'Bad access to protected data' when advice, on a sub-aspect, that calls a protected method, on the super-aspect, is woven into a class. However another call to the same method woven into the same class but due to advice declared in the super-aspect works fine. The aspects were woven into precompiled (by sun's 1.4 javac) classes. The verify error occurs under both sun's 1.4 and blackdowns 1.3 VMs, and presumably all VMs. Workaround: Making the protected method public fixes the verify error. A test case is available in CVS: tests/bugs/protectedvf/... tests/ajcTestFailing.xml
|
resolved fixed
|
6ddae42
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-19T22:09:16Z
| 2004-02-13T02:40:00Z
|
tests/bugs/protectedvf/main/Driver.java
|
package main;
public class Driver{
public static void main(String[] args) {
Driver d = new Driver();
d.doStuff();
d.doOtherStuff();
}
private void doOtherStuff() {
System.out.println("doing other stuff");
}
private void doStuff() {
System.out.println("doing stuff");
}
}
|
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07:46:40Z
|
ajde/testdata/ReweavableTest/CalculatePI.java
| |
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07:46:40Z
|
ajde/testdata/ReweavableTest/tjp/Demo.java
| |
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07:46:40Z
|
ajde/testdata/ReweavableTest/tjp/GetInfo.java
| |
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07:46:40Z
|
ajde/testsrc/org/aspectj/ajde/AjdeTests.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.ajde;
import junit.framework.*;
public class AjdeTests extends TestCase {
public static String TESTDATA_PATH = "../ajde/testdata";
public static Test suite() {
TestSuite suite = new TestSuite(AjdeTests.class.getName());
//$JUnit-BEGIN$
suite.addTestSuite(BuildOptionsTest.class);
suite.addTestSuite(BuildConfigurationTests.class);
suite.addTestSuite(StructureModelRegressionTest.class);
suite.addTestSuite(StructureModelTest.class);
suite.addTestSuite(VersionTest.class);
suite.addTestSuite(CompilerMessagesTest.class);
suite.addTestSuite(AsmDeclarationsTest.class);
suite.addTestSuite(AsmRelationshipsTest.class);
suite.addTestSuite(InpathTestcase.class);
suite.addTestSuite(ResourceCopyTestCase.class);
suite.addTestSuite(ModelPerformanceTest.class);
suite.addTestSuite(SavedModelConsistencyTest. class);
//$JUnit-END$
return suite;
}
public AjdeTests(String name) { super(name); }
}
|
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07:46:40Z
|
ajde/testsrc/org/aspectj/ajde/ReweavableTestCase.java
| |
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07:46:40Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/BuildArgParser.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.ajc;
import java.io.*;
import java.util.*;
import org.aspectj.ajdt.internal.core.builder.*;
import org.aspectj.bridge.*;
import org.aspectj.util.*;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.internal.compiler.batch.Main;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
public class BuildArgParser extends Main {
private static final String BUNDLE_NAME = "org.aspectj.ajdt.ajc.messages";
private static boolean LOADED_BUNDLE = false;
static {
bundle = ResourceBundle.getBundle(BUNDLE_NAME);
if (!LOADED_BUNDLE) {
LOADED_BUNDLE = true;
}
}
/** to initialize super's PrintWriter but refer to underlying StringWriter */
private static class StringPrintWriter extends PrintWriter {
public final StringWriter stringWriter;
StringPrintWriter(StringWriter sw) {
super(sw);
this.stringWriter = sw;
}
}
/** @return multi-line String usage for the compiler */
public static String getUsage() {
return Main.bind("misc.usage");
}
/**
* StringWriter sink for some errors.
* This only captures errors not handled by any IMessageHandler parameter
* and only when no PrintWriter is set in the constructor.
* XXX This relies on (Sun's) implementation of StringWriter,
* which returns the actual (not copy) internal StringBuffer.
*/
private final StringBuffer errorSink;
private IMessageHandler handler;
/**
* Overrides super's bundle.
*/
public BuildArgParser(PrintWriter writer, IMessageHandler handler) {
super(writer, writer, false);
if (writer instanceof StringPrintWriter) {
errorSink = ((StringPrintWriter) writer).stringWriter.getBuffer();
} else {
errorSink = null;
}
this.handler = handler;
}
/** Set up to capture messages using getOtherMessages(boolean) */
public BuildArgParser(IMessageHandler handler) {
this(new StringPrintWriter(new StringWriter()),handler);
}
/**
* Generate build configuration for the input args,
* passing to handler any error messages.
* @param args the String[] arguments for the build configuration
* @return AjBuildConfig per args,
* which will be invalid unless there are no handler errors.
*/
public AjBuildConfig genBuildConfig(String[] args) {
return genBuildConfig(args, true, null);
}
/**
* 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 genBuildConfig(String[] args, boolean setClasspath, File configFile) {
AjBuildConfig buildConfig = new AjBuildConfig();
buildConfig.setConfigFile(configFile);
try {
// sets filenames to be non-null in order to make sure that file paramters are ignored
super.filenames = new String[] { "" };
AjcConfigParser parser = new AjcConfigParser(buildConfig, handler);
parser.parseCommandLine(args);
boolean incrementalMode = buildConfig.isIncrementalMode()
|| buildConfig.isIncrementalFileMode();
List fileList = new ArrayList();
List files = parser.getFiles();
if (!LangUtil.isEmpty(files)) {
if (incrementalMode) {
MessageUtil.error(handler, "incremental mode only handles source files using -sourceroots");
} else {
fileList.addAll(files);
}
}
List javaArgList = new ArrayList();
// disable all special eclipse warnings by default
//??? might want to instead override getDefaultOptions()
javaArgList.add("-warn:none");
// these next four lines are some nonsense to fool the eclipse batch compiler
// without these it will go searching for reasonable values from properties
//TODO fix org.eclipse.jdt.internal.compiler.batch.Main so this hack isn't needed
javaArgList.add("-classpath");
javaArgList.add(System.getProperty("user.dir"));
javaArgList.add("-bootclasspath");
javaArgList.add(System.getProperty("user.dir"));
javaArgList.addAll(parser.getUnparsedArgs());
super.configure((String[])javaArgList.toArray(new String[javaArgList.size()]));
if (!proceed) {
buildConfig.doNotProceed();
return buildConfig;
}
if (buildConfig.getSourceRoots() != null) {
for (Iterator i = buildConfig.getSourceRoots().iterator(); i.hasNext(); ) {
fileList.addAll(collectSourceRootFiles((File)i.next()));
}
}
buildConfig.setFiles(fileList);
if (destinationPath != null) { // XXX ?? unparsed but set?
buildConfig.setOutputDir(new File(destinationPath));
}
if (setClasspath) {
buildConfig.setClasspath(getClasspath(parser));
}
if (incrementalMode
&& (0 == buildConfig.getSourceRoots().size())) {
MessageUtil.error(handler, "specify a source root when in incremental mode");
}
setDebugOptions();
buildConfig.setJavaOptions(options);
} catch (InvalidInputException iie) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
location = new SourceLocation(buildConfig.getConfigFile(), 0);
}
IMessage m = new Message(iie.getMessage(), IMessage.ERROR, null, location);
handler.handleMessage(m);
}
return buildConfig;
}
// from super...
public void printVersion() {
System.err.println("AspectJ Compiler " + Version.text + " built on " + Version.time_text); //$NON-NLS-1$
System.err.flush();
}
public void printUsage() {
System.out.println(bind("misc.usage")); //$NON-NLS-1$
System.out.flush();
}
/**
* Get messages not dumped to handler or any PrintWriter.
* @param flush if true, empty errors
* @return null if none, String otherwise
* @see BuildArgParser()
*/
public String getOtherMessages(boolean flush) {
if (null == errorSink) {
return null;
}
String result = errorSink.toString().trim();
if (0 == result.length()) {
result = null;
}
if (flush) {
errorSink.setLength(0);
}
return result;
}
private void setDebugOptions() {
options.put(
CompilerOptions.OPTION_LocalVariableAttribute,
CompilerOptions.GENERATE);
options.put(
CompilerOptions.OPTION_LineNumberAttribute,
CompilerOptions.GENERATE);
options.put(
CompilerOptions.OPTION_SourceFileAttribute,
CompilerOptions.GENERATE);
}
private Collection collectSourceRootFiles(File dir) {
return Arrays.asList(FileUtil.listFiles(dir, FileUtil.aspectjSourceFileFilter));
}
/**
* If the classpath is not set, we use the environment's java.class.path, but remove
* the aspectjtools.jar entry from that list in order to prevent wierd bootstrap issues
* (refer to bug#39959).
*/
public List getClasspath(AjcConfigParser parser) {
List ret = new ArrayList();
if (parser.bootclasspath == null) {
addClasspath(System.getProperty("sun.boot.class.path", ""), ret);
} else {
addClasspath(parser.bootclasspath, ret);
}
String extdirs = parser.extdirs;
if (extdirs == null) {
extdirs = System.getProperty("java.ext.dirs", "");
}
addExtDirs(extdirs, ret);
if (parser.classpath == null) {
addClasspath(System.getProperty("java.class.path", ""), ret);
List fixedList = new ArrayList();
for (Iterator it = ret.iterator(); it.hasNext(); ) {
String entry = (String)it.next();
if (!entry.endsWith("aspectjtools.jar")) {
fixedList.add(entry);
}
}
ret = fixedList;
} else {
addClasspath(parser.classpath, ret);
}
//??? eclipse seems to put outdir on the classpath
//??? we're brave and believe we don't need it
return ret;
}
private void addExtDirs(String extdirs, List classpathCollector) {
StringTokenizer tokenizer = new StringTokenizer(extdirs, File.pathSeparator);
while (tokenizer.hasMoreTokens()) {
// classpathCollector.add(tokenizer.nextToken());
File dirFile = new File((String)tokenizer.nextToken());
if (dirFile.canRead() && dirFile.isDirectory()) {
File[] files = dirFile.listFiles(FileUtil.ZIP_FILTER);
for (int i = 0; i < files.length; i++) {
classpathCollector.add(files[i].getAbsolutePath());
}
} else {
// XXX alert on invalid -extdirs entries
}
}
}
private void addClasspath(String classpath, List classpathCollector) {
StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator);
while (tokenizer.hasMoreTokens()) {
classpathCollector.add(tokenizer.nextToken());
}
}
private class AjcConfigParser extends ConfigParser {
private String bootclasspath = null;
private String classpath = null;
private String extdirs = null;
private List unparsedArgs = new ArrayList();
private AjBuildConfig buildConfig;
private IMessageHandler handler;
public AjcConfigParser(AjBuildConfig buildConfig, IMessageHandler handler) {
this.buildConfig = buildConfig;
this.handler = handler;
}
public List getUnparsedArgs() {
return unparsedArgs;
}
/**
* Extract AspectJ-specific options (except for argfiles).
* Caller should warn when sourceroots is empty but in
* incremental mode.
* Signals warnings or errors through handler set in constructor.
*/
public void parseOption(String arg, LinkedList args) { // XXX use ListIterator.remove()
int nextArgIndex = args.indexOf(arg)+1; // XXX assumes unique
// trim arg?
if (LangUtil.isEmpty(arg)) {
showWarning("empty arg found");
} else if (arg.equals("-inpath")) {;
if (args.size() > nextArgIndex) {
buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_Inpath, CompilerOptions.PRESERVE);
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)) {
buildConfig.getInpath().add(file);
} else {
if (file.isDirectory()) {
buildConfig.getInpath().add(file);
} else
showError("bad inpath component: " + filename);
}
}
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("-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.equals("-XnoInline")) {
buildConfig.setXnoInline(true);
} else if (arg.equals("-Xlintfile")) {
if (args.size() > nextArgIndex) {
File lintSpecFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue());
// XXX relax restriction on props file suffix?
if (lintSpecFile.canRead() && lintSpecFile.getName().endsWith(".properties")) {
buildConfig.setLintSpecFile(lintSpecFile);
} else {
showError("bad -Xlintfile file: " + lintSpecFile);
buildConfig.setLintSpecFile(null);
}
args.remove(args.get(nextArgIndex));
} else {
showError("-Xlintfile requires .properties file argument");
}
} else if (arg.equals("-Xlint")) {
buildConfig.getAjOptions().put(
AjCompilerOptions.OPTION_Xlint,
CompilerOptions.GENERATE);
buildConfig.setLintMode(AjBuildConfig.AJLINT_DEFAULT);
} else if (arg.startsWith("-Xlint:")) {
if (7 < arg.length()) {
buildConfig.setLintMode(arg.substring(7));
} else {
showError("invalid lint option " + arg);
}
} else if (arg.equals("-bootclasspath")) {
if (args.size() > nextArgIndex) {
bootclasspath = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
args.remove(args.get(nextArgIndex));
} else {
showError("-bootclasspath requires classpath entries");
}
} else if (arg.equals("-classpath")) {
if (args.size() > nextArgIndex) {
classpath = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
args.remove(args.get(nextArgIndex));
} else {
showError("-classpath requires classpath entries");
}
} else if (arg.equals("-extdirs")) {
if (args.size() > nextArgIndex) {
extdirs = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
args.remove(args.get(nextArgIndex));
} else {
showError("-extdirs requires list of external directories");
}
// error on directory unless -d, -{boot}classpath, or -extdirs
} else if (arg.equals("-d")) {
dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-classpath")) {
// dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-bootclasspath")) {
// dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-extdirs")) {
// dirLookahead(arg, args, nextArgIndex);
} else if (new File(arg).isDirectory()) {
showError("dir arg not permitted: " + arg);
} else {
// argfile, @file parsed by superclass
// no eclipse options parsed:
// -d args, -help (handled),
// -classpath, -target, -1.3, -1.4, -source [1.3|1.4]
// -nowarn, -warn:[...], -deprecation, -noImportError,
// -proceedOnError, -g:[...], -preserveAllLocals,
// -referenceInfo, -encoding, -verbose, -log, -time
// -noExit, -repeat
unparsedArgs.add(arg);
}
}
protected void dirLookahead(String arg, LinkedList argList, int nextArgIndex) {
unparsedArgs.add(arg);
ConfigParser.Arg next = (ConfigParser.Arg) argList.get(nextArgIndex);
String value = next.getValue();
if (!LangUtil.isEmpty(value)) {
if (new File(value).isDirectory()) {
unparsedArgs.add(value);
argList.remove(next);
return;
}
}
}
public void showError(String message) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
location = new SourceLocation(buildConfig.getConfigFile(), 0);
}
IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.ERROR, null, location);
handler.handleMessage(errorMessage);
// MessageUtil.error(handler, CONFIG_MSG + message);
}
protected void showWarning(String message) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
location = new SourceLocation(buildConfig.getConfigFile(), 0);
}
IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.WARNING, null, location);
handler.handleMessage(errorMessage);
// MessageUtil.warn(handler, message);
}
protected File makeFile(File dir, String name) {
name = name.replace('/', File.separatorChar);
File ret = new File(name);
if (dir == null || ret.isAbsolute()) return ret;
try {
dir = dir.getCanonicalFile();
} catch (IOException ioe) { }
return new File(dir, name);
}
}
}
|
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07:46: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.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
/**
* All configuration information needed to run the AspectJ compiler.
*/
public class AjBuildConfig { // XXX needs bootclasspath?
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*/ 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 Map javaOptions = new HashMap();
private Map ajOptions = new HashMap();
private File configFile;
private boolean generateModelMode = false;
private boolean emacsSymMode = false;
private boolean noWeave = false;
private boolean XserializableAspects = false;
private boolean XlazyTjp = false;
private boolean XnoInline = false;
private String lintMode = AJLINT_DEFAULT;
private File lintSpecFile = null;
/** 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;
/**
* 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( ) {
javaOptions.put(
CompilerOptions.OPTION_LocalVariableAttribute,
//CompilerOptions.DO_NOT_GENERATE);
CompilerOptions.GENERATE);
javaOptions.put(
CompilerOptions.OPTION_LineNumberAttribute,
//CompilerOptions.DO_NOT_GENERATE);
CompilerOptions.GENERATE);
javaOptions.put(
CompilerOptions.OPTION_SourceFileAttribute,
//CompilerOptions.DO_NOT_GENERATE);
CompilerOptions.GENERATE);
javaOptions.put(
CompilerOptions.OPTION_PreserveUnusedLocal,
CompilerOptions.OPTIMIZE_OUT);
// javaOptions.put(
// CompilerOptions.OPTION_ReportUnreachableCode,
// CompilerOptions.IGNORE);
// javaOptions.put(
// CompilerOptions.OPTION_ReportInvalidImport,
// CompilerOptions.ERROR);
javaOptions.put(
CompilerOptions.OPTION_ReportOverridingPackageDefaultMethod,
CompilerOptions.WARNING);
javaOptions.put(
CompilerOptions.OPTION_ReportMethodWithConstructorName,
CompilerOptions.WARNING);
javaOptions.put(
CompilerOptions.OPTION_ReportDeprecation,
CompilerOptions.WARNING);
javaOptions.put(
CompilerOptions.OPTION_ReportHiddenCatchBlock,
CompilerOptions.WARNING);
javaOptions.put(
CompilerOptions.OPTION_ReportUnusedLocal,
CompilerOptions.IGNORE);
javaOptions.put(
CompilerOptions.OPTION_ReportUnusedParameter,
CompilerOptions.IGNORE);
javaOptions.put(
CompilerOptions.OPTION_ReportSyntheticAccessEmulation,
CompilerOptions.IGNORE);
javaOptions.put(
CompilerOptions.OPTION_ReportNonExternalizedStringLiteral,
CompilerOptions.IGNORE);
javaOptions.put(
CompilerOptions.OPTION_ReportAssertIdentifier,
CompilerOptions.IGNORE);
javaOptions.put(
CompilerOptions.OPTION_Compliance,
CompilerOptions.VERSION_1_3);
javaOptions.put(
CompilerOptions.OPTION_Source,
CompilerOptions.VERSION_1_3);
javaOptions.put(
CompilerOptions.OPTION_TargetPlatform,
CompilerOptions.VERSION_1_1);
}
/**
* 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;
}
public File getOutputDir() {
return outputDir;
}
public void setFiles(List files) {
this.files = files;
}
public void setOutputDir(File outputDir) {
this.outputDir = outputDir;
}
public Map getAjOptions() {
return ajOptions;
}
/**
* @return the Map expected by org.eclipse.jdt.core.internal.Compiler.
*/
public Map getJavaOptions() {
return javaOptions;
}
public void setAjOptions(Map ajOptions) {
this.ajOptions = ajOptions;
}
public void setJavaOptions(Map javaOptions) {
this.javaOptions = javaOptions;
}
/**
* This includes all entries from -bootclasspath, -extdirs, -classpath,
*/
public List getClasspath() { // XXX setters don't respect javadoc contract...
return classpath;
}
public void setClasspath(List classpath) {
this.classpath = classpath;
}
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 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 boolean isEmacsSymMode() {
return emacsSymMode;
}
public void setEmacsSymMode(boolean emacsSymMode) {
this.emacsSymMode = emacsSymMode;
}
public boolean isGenerateModelMode() {
return generateModelMode;
}
public void setGenerateModelMode(boolean structureModelMode) {
this.generateModelMode = structureModelMode;
}
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 injars, inpath, aspectpath
* entries, specified classpath (bootclasspath, extdirs, and
* classpath), and output dir or jar
*/
public List getFullClasspath() {
List full = new ArrayList();
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 String getLintMode() {
return lintMode;
}
public File getLintSpecFile() {
return lintSpecFile;
}
public List getAspectpath() {
return aspectpath;
}
public boolean isNoWeave() {
return noWeave;
}
public void setLintMode(String lintMode) {
this.lintMode = lintMode;
}
public void setLintSpecFile(File lintSpecFile) {
this.lintSpecFile = lintSpecFile;
}
public void setAspectpath(List aspectpath) {
this.aspectpath = aspectpath;
}
public void setNoWeave(boolean noWeave) {
this.noWeave = noWeave;
}
public boolean isXserializableAspects() {
return XserializableAspects;
}
public void setXserializableAspects(boolean xserializableAspects) {
XserializableAspects = xserializableAspects;
}
public boolean isXnoInline() {
return XnoInline;
}
public void setXnoInline(boolean xnoInline) {
XnoInline = xnoInline;
}
/** @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
join(ajOptions, global.ajOptions);
join(aspectpath, global.aspectpath);
join(classpath, global.classpath);
if (null == configFile) {
configFile = global.configFile; // XXX correct?
}
if (!emacsSymMode && global.emacsSymMode) {
emacsSymMode = true;
}
join(files, global.files);
if (!generateModelMode && global.generateModelMode) {
generateModelMode = true;
}
if (null == incrementalFile) {
incrementalFile = global.incrementalFile;
}
if (!incrementalMode && global.incrementalMode) {
incrementalMode = true;
}
join(inJars, global.inJars);
join(inPath, global.inPath);
join(javaOptions, global.javaOptions);
if ((null == lintMode)
|| (AJLINT_DEFAULT.equals(lintMode))) {
lintMode = global.lintMode;
}
if (null == lintSpecFile) {
lintSpecFile = global.lintSpecFile;
}
if (!noWeave && global.noWeave) {
noWeave = 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 (!XnoInline && global.XnoInline) {
XnoInline = true;
}
if (!XserializableAspects && global.XserializableAspects) {
XserializableAspects = 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 boolean isXlazyTjp() {
return XlazyTjp;
}
public void setXlazyTjp(boolean b) {
XlazyTjp = b;
}
}
|
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07:46: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 org.aspectj.ajdt.internal.compiler.AjCompiler;
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.weaver.World;
import org.aspectj.weaver.bcel.*;
import org.eclipse.jdt.core.compiler.*;
import org.eclipse.jdt.internal.compiler.*;
import org.eclipse.jdt.internal.compiler.batch.*;
import org.eclipse.jdt.internal.compiler.batch.FileSystem;
import org.eclipse.jdt.internal.compiler.env.*;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.parser.Parser;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
//import org.eclipse.jdt.internal.compiler.util.HashtableOfObject;
public class AjBuildManager {
static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false;
private IProgressListener progressListener = null;
private int compiledCount;
private int sourceFileCount;
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 {
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);
//}
setupModel();
if (batch) {
initBcelWorld(handler);
}
if (handler.hasErrors()) {
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?
}
performCompilation(buildConfig.getFiles());
if (handler.hasErrors()) {
return false;
}
} else {
// done already?
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
// bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel());
// }
// System.err.println("XXXX start inc ");
List files = state.getFilesToCompile(true);
for (int i = 0; (i < 5) && !files.isEmpty(); i++) {
// System.err.println("XXXX inc: " + files);
performCompilation(files);
if (handler.hasErrors()) {
return false;
}
files = state.getFilesToCompile(false);
}
if (!files.isEmpty()) {
return batchBuild(buildConfig, baseHandler);
}
}
// XXX not in Mik's incremental
if (buildConfig.isEmacsSymMode()) {
new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel();
}
// have to tell state we succeeded or next is not incremental
state.successfulCompile(buildConfig);
/*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();
}
return !handler.hasErrors();
} finally {
handler = null;
}
}
private void setupModel() {
String rootLabel = "<root>";
IHierarchy model = AsmManager.getDefault().getHierarchy();
IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA;
if (buildConfig.getConfigFile() != null) {
rootLabel = buildConfig.getConfigFile().getName();
model.setConfigFile(
buildConfig.getConfigFile().getAbsolutePath()
);
kind = IProgramElement.Kind.FILE_LST;
}
model.setRoot(new ProgramElement(rootLabel, kind, new ArrayList()));
model.setFileMap(new HashMap());
setStructureModel(model);
}
/** init only on initial batch compile? no file-specific options */
private void initBcelWorld(IMessageHandler handler) throws IOException {
bcelWorld = new BcelWorld(buildConfig.getClasspath(), handler, null);
bcelWorld.setXnoInline(buildConfig.isXnoInline());
bcelWorld.setXlazyTjp(buildConfig.isXlazyTjp());
bcelWeaver = new BcelWeaver(bcelWorld);
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();
bcelWeaver.addJarFile(inJar, buildConfig.getOutputDir(),false);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
bcelWeaver.addJarFile(inPathElement,buildConfig.getOutputDir(),true);
}
if (buildConfig.getSourcePathResources() != null) {
for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) {
// File resource = (File)i.next();
String resource = (String)i.next();
bcelWeaver.addResource(resource, (File)buildConfig.getSourcePathResources().get(resource), buildConfig.getOutputDir());
// bcelWeaver.addResource(resource, buildConfig.getOutputDir());
}
}
//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 = (String) buildConfig.getJavaOptions().get(CompilerOptions.OPTION_Encoding);
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 = (String) buildConfig.getJavaOptions().get(CompilerOptions.OPTION_Encoding);
if ("".equals(defaultEncoding)) //$NON-NLS-1$
defaultEncoding = null; //$NON-NLS-1$
for (int i = 0; i < fileCount; i++) {
String encoding = encodings[i];
if (encoding == null)
encoding = defaultEncoding;
units[i] = new CompilationUnit(null, filenames[i], encoding);
}
return units;
}
public String extractDestinationPathFromSourceFile(CompilationResult result) {
ICompilationUnit compilationUnit = result.compilationUnit;
if (compilationUnit != null) {
char[] fileName = compilationUnit.getFileName();
int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName);
if (lastIndex == -1) {
return System.getProperty("user.dir"); //$NON-NLS-1$
}
return new String(CharOperation.subarray(fileName, 0, lastIndex));
}
return System.getProperty("user.dir"); //$NON-NLS-1$
}
public void performCompilation(List files) {
if (progressListener != null) {
compiledCount = 0;
sourceFileCount = files.size();
progressListener.setText("compiling source files");
}
//System.err.println("got files: " + files);
String[] filenames = new String[files.size()];
String[] encodings = new String[files.size()];
//System.err.println("filename: " + this.filenames);
for (int i=0; i < files.size(); i++) {
filenames[i] = ((File)files.get(i)).getPath();
}
List cps = buildConfig.getFullClasspath();
String[] classpaths = new String[cps.size()];
for (int i=0; i < cps.size(); i++) {
classpaths[i] = (String)cps.get(i);
}
//System.out.println("compiling");
INameEnvironment environment = getLibraryAccess(classpaths, filenames);
if (!state.classesFromName.isEmpty()) {
environment = new StatefulNameEnvironment(environment, state.classesFromName);
}
AjCompiler compiler = new AjCompiler(
environment,
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
buildConfig.getJavaOptions(),
getBatchRequestor(),
getProblemFactory());
AjProblemReporter pr =
new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(),
compiler.options, getProblemFactory());
compiler.problemReporter = pr;
AjLookupEnvironment le =
new AjLookupEnvironment(compiler, compiler.options, pr, environment);
EclipseFactory factory = new EclipseFactory(le);
// ew.setLint(bcelWorld.getLint());
// ew.setXnoInline(buildConfig.isXnoInline());
le.factory = factory;
pr.factory = factory;
le.factory.buildManager = this;
compiler.lookupEnvironment = le;
compiler.parser =
new Parser(
pr,
compiler.options.parseLiteralExpressionsAsConstants);
CompilerOptions options = compiler.options;
options.produceReferenceInfo(true); //TODO turn off when not needed
compiler.compile(getCompilationUnits(filenames, encodings));
// cleanup
environment.cleanup();
}
/*
* Answer the component to which will be handed back compilation results from the compiler
*/
public ICompilerRequestor getBatchRequestor() {
return new ICompilerRequestor() {
int lineDelta = 0;
public void acceptResult(CompilationResult compilationResult) {
if (progressListener != null) {
compiledCount++;
progressListener.setProgress((compiledCount/2.0)/sourceFileCount);
progressListener.setText("compiled: " + new String(compilationResult.getFileName()));
}
if (compilationResult.hasProblems() || compilationResult.hasTasks()) {
IProblem[] problems = compilationResult.getAllProblems();
for (int i=0; i < problems.length; i++) {
IMessage message =
EclipseAdapterUtils.makeMessage(compilationResult.compilationUnit, problems[i]);
handler.handleMessage(message);
}
}
outputClassFiles(compilationResult);
}
};
}
private boolean proceedOnError() {
return true; //???
}
public void outputClassFiles(CompilationResult unitResult) {
if (unitResult == null) return;
String sourceFileName = new String(unitResult.fileName);
if (!(unitResult.hasErrors() && !proceedOnError())) {
List unwovenClassFiles = new ArrayList();
Enumeration classFiles = unitResult.compiledTypes.elements();
while (classFiles.hasMoreElements()) {
ClassFile classFile = (ClassFile) classFiles.nextElement();
String filename = new String(classFile.fileName());
filename = filename.replace('/', File.separatorChar) + ".class";
File destinationPath = buildConfig.getOutputDir();
if (destinationPath == null) {
filename = new File(filename).getName();
filename = new File(extractDestinationPathFromSourceFile(unitResult), filename).getPath();
} else {
filename = new File(destinationPath, filename).getPath();
}
//System.out.println("classfile: " + filename);
unwovenClassFiles.add(new UnwovenClassFile(filename, classFile.getBytes()));
}
state.noteClassesFromFile(unitResult, sourceFileName, unwovenClassFiles);
// System.out.println("file: " + sourceFileName);
// for (int i=0; i < unitResult.simpleNameReferences.length; i++) {
// System.out.println("simple: " + new String(unitResult.simpleNameReferences[i]));
// }
// for (int i=0; i < unitResult.qualifiedReferences.length; i++) {
// System.out.println("qualified: " +
// new String(CharOperation.concatWith(unitResult.qualifiedReferences[i], '/')));
// }
} else {
state.noteClassesFromFile(null, sourceFileName, Collections.EMPTY_LIST);
}
}
private void setBuildConfig(AjBuildConfig buildConfig) {
this.buildConfig = buildConfig;
handler.reset();
}
String makeClasspathString() {
if (buildConfig == null || buildConfig.getClasspath() == null) return "";
StringBuffer buf = new StringBuffer();
boolean first = true;
for (Iterator it = buildConfig.getClasspath().iterator(); it.hasNext(); ) {
if (first) { first = false; }
else { buf.append(File.pathSeparator); }
buf.append(it.next().toString());
}
return buf.toString();
}
/**
* This will return null if aspectjrt.jar is present and has the correct version.
* Otherwise it will return a string message indicating the problem.
*/
public String checkRtJar(AjBuildConfig buildConfig) {
// omitting dev info
if (Version.text.equals(Version.DEVELOPMENT)) {
// in the development version we can't do this test usefully
// MessageUtil.info(holder, "running development version of aspectj compiler");
return null;
}
if (buildConfig == null || buildConfig.getClasspath() == null) return "no classpath specified";
for (Iterator it = buildConfig.getClasspath().iterator(); it.hasNext(); ) {
File p = new File( (String)it.next() );
if (p.isFile() && p.getName().equals("aspectjrt.jar")) {
try {
String version = null;
Manifest manifest = new JarFile(p).getManifest();
if (manifest == null) {
return "no manifest found in " + p.getAbsolutePath() +
", expected " + Version.text;
}
Attributes attr = manifest.getAttributes("org/aspectj/lang/");
if (null != attr) {
version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
if (null != version) {
version = version.trim();
}
}
// assume that users of development aspectjrt.jar know what they're doing
if (Version.DEVELOPMENT.equals(version)) {
// MessageUtil.info(holder,
// "running with development version of aspectjrt.jar in " +
// p.getAbsolutePath());
return null;
} else if (!Version.text.equals(version)) {
return "bad version number found in " + p.getAbsolutePath() +
" expected " + Version.text + " found " + version;
}
} catch (IOException ioe) {
return "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe;
}
return null;
} else {
// might want to catch other classpath errors
}
}
return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString();
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("AjBuildManager(");
buf.append(")");
return buf.toString();
}
public void setStructureModel(IHierarchy structureModel) {
this.structureModel = structureModel;
}
/**
* Returns null if there is no structure model
*/
public IHierarchy getStructureModel() {
return structureModel;
}
public IProgressListener getProgressListener() {
return progressListener;
}
public void setProgressListener(IProgressListener progressListener) {
this.progressListener = progressListener;
}
} // class AjBuildManager
|
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07:46:40Z
|
taskdefs/src/org/aspectj/tools/ant/taskdefs/AjcTask.java
|
/* *******************************************************************
* Copyright (c) 2001-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC)
* 2003-2004 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the 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
* Wes Isberg 2003-2004 changes
* ******************************************************************/
package org.aspectj.tools.ant.taskdefs;
import java.io.*;
import java.util.*;
import org.apache.tools.ant.*;
import org.apache.tools.ant.taskdefs.*;
import org.apache.tools.ant.types.*;
import org.aspectj.bridge.*;
import org.aspectj.tools.ajc.Main;
import org.aspectj.tools.ajc.Main.MessagePrinter;
import org.aspectj.util.*;
/**
* This runs the AspectJ 1.1 compiler,
* supporting all the command-line options.
* In 1.1.1, ajc copies resources from input jars,
* but you can copy resources from the source directories
* using sourceRootCopyFilter.
* When not forking, things will be copied as needed
* for each iterative compile,
* but when forking things are only copied at the
* completion of a successful compile.
* <p>
* See the development environment guide for
* usage documentation.
*
* @since AspectJ 1.1, Ant 1.5
*/
public class AjcTask extends MatchingTask {
/*
* This task mainly converts ant specification for ajc,
* verbosely ignoring improper input.
* It also has some special features for non-obvious clients:
* (1) Javac compiler adapter supported in
* <code>setupAjc(AjcTask, Javac, File)</code>
* and
* <code>readArguments(String[])</code>;
* (2) testing is supported by
* (a) permitting the same specification to be re-run
* with added flags (settings once made cannot be
* removed); and
* (b) permitting recycling the task with
* <code>reset()</code> (untested).
*
* The parts that do more than convert ant specs are
* (a) code for forking;
* (b) code for copying resources.
*
* If you maintain/upgrade this task, keep in mind:
* (1) changes to the semantics of ajc (new options, new
* values permitted, etc.) will have to be reflected here.
* (2) the clients:
* the iajc ant script, Javac compiler adapter,
* maven clients of iajc, and testing code.
*/
// XXX move static methods after static initializer
/**
* This method extracts javac arguments to ajc,
* and add arguments to make ajc behave more like javac
* in copying resources.
* <p>
* Pass ajc-specific options using compilerarg sub-element:
* <pre>
* <javac srcdir="src">
* <compilerarg compiler="..." line="-argfile src/args.lst"/>
* <javac>
* </pre>
* Some javac arguments are not supported in this component (yet):
* <pre>
* String memoryInitialSize;
* boolean includeAntRuntime = true;
* boolean includeJavaRuntime = false;
* </pre>
* Other javac arguments are not supported in ajc 1.1:
* <pre>
* boolean optimize;
* String forkedExecutable;
* FacadeTaskHelper facade;
* boolean depend;
* String debugLevel;
* Path compileSourcepath;
* </pre>
* @param javac the Javac command to implement (not null)
* @param ajc the AjcTask to adapt (not null)
* @param destDir the File class destination directory (may be null)
* @return null if no error, or String error otherwise
*/
public String setupAjc(Javac javac) {
if (null == javac) {
return "null javac";
}
AjcTask ajc = this;
// no null checks b/c AjcTask handles null input gracefully
ajc.setProject(javac.getProject());
ajc.setLocation(javac.getLocation());
ajc.setTaskName("javac-iajc");
ajc.setDebug(javac.getDebug());
ajc.setDeprecation(javac.getDeprecation());
ajc.setFailonerror(javac.getFailonerror());
final boolean fork = javac.isForkedJavac();
ajc.setFork(fork);
if (fork) {
ajc.setMaxmem(javac.getMemoryMaximumSize());
}
ajc.setNowarn(javac.getNowarn());
ajc.setListFileArgs(javac.getListfiles());
ajc.setVerbose(javac.getVerbose());
ajc.setTarget(javac.getTarget());
ajc.setSource(javac.getSource());
ajc.setEncoding(javac.getEncoding());
File javacDestDir = javac.getDestdir();
if (null != javacDestDir) {
ajc.setDestdir(javacDestDir);
// filter requires dest dir
// mimic Javac task's behavior in copying resources,
ajc.setSourceRootCopyFilter("**/CVS/*,**/*.java,**/*.aj");
}
ajc.setBootclasspath(javac.getBootclasspath());
ajc.setExtdirs(javac.getExtdirs());
ajc.setClasspath(javac.getClasspath());
// ignore srcDir -- all files picked up in recalculated file list
// ajc.setSrcDir(javac.getSrcdir());
ajc.addFiles(javac.getFileList());
// arguments can override the filter, add to paths, override options
ajc.readArguments(javac.getCurrentCompilerArgs());
return null;
}
/**
* Find aspectjtools.jar on the task or system classpath.
* Accept <code>aspectj{-}tools{...}.jar</code>
* mainly to support build systems using maven-style
* re-naming
* (e.g., <code>aspectj-tools-1.1.0.jar</code>.
* Note that we search the task classpath first,
* though an entry on the system classpath would be loaded first,
* because it seems more correct as the more specific one.
* @return readable File for aspectjtools.jar, or null if not found.
*/
public static File findAspectjtoolsJar() {
File result = null;
ClassLoader loader = AjcTask.class.getClassLoader();
if (loader instanceof AntClassLoader) {
AntClassLoader taskLoader = (AntClassLoader) loader;
String cp = taskLoader.getClasspath();
String[] cps = LangUtil.splitClasspath(cp);
for (int i = 0; (i < cps.length) && (null == result); i++) {
result = isAspectjtoolsjar(cps[i]);
}
}
if (null == result) {
final Path classpath = Path.systemClasspath;
final String[] paths = classpath.list();
for (int i = 0; (i < paths.length) && (null == result); i++) {
result = isAspectjtoolsjar(paths[i]);
}
}
return (null == result? null : result.getAbsoluteFile());
}
/** @return File if readable jar with aspectj tools name, or null */
private static File isAspectjtoolsjar(String path) {
if (null == path) {
return null;
}
final String prefix = "aspectj";
final String infix = "tools";
final String altInfix = "-tools";
final String suffix = ".jar";
final int prefixLength = 7; // prefix.length();
final int minLength = 16;
// prefixLength + infix.length() + suffix.length();
if (!path.endsWith(suffix)) {
return null;
}
int loc = path.lastIndexOf(prefix);
if ((-1 != loc) && ((loc + minLength) <= path.length())) {
String rest = path.substring(loc+prefixLength);
if (-1 != rest.indexOf(File.pathSeparator)) {
return null;
}
if (rest.startsWith(infix)
|| rest.startsWith(altInfix)) {
File result = new File(path);
if (result.canRead() && result.isFile()) {
return result;
}
}
}
return null;
}
/**
* Maximum length (in chars) of command line
* before converting to an argfile when forking
*/
private static final int MAX_COMMANDLINE = 4096;
private static final File DEFAULT_DESTDIR = new File(".") {
public String toString() {
return "(no destination dir specified)";
}
};
/** do not throw BuildException on fail/abort message with usage */
private static final String USAGE_SUBSTRING = "AspectJ-specific options";
/** valid -X[...] options other than -Xlint variants */
private static final List VALID_XOPTIONS;
/** valid warning (-warn:[...]) variants */
private static final List VALID_WARNINGS;
/** valid debugging (-g:[...]) variants */
private static final List VALID_DEBUG;
/**
* -Xlint variants (error, warning, ignore)
* @see org.aspectj.weaver.Lint
*/
private static final List VALID_XLINT;
public static final String COMMAND_EDITOR_NAME
= AjcTask.class.getName() + ".COMMAND_EDITOR";
static final String[] TARGET_INPUTS = new String []
{ "1.1", "1.2", "1.3", "1.4" };
static final String[] SOURCE_INPUTS = new String []
{ "1.3", "1.4" };
static final String[] COMPLIANCE_INPUTS = new String []
{ "1.3", "1.4" };
private static final ICommandEditor COMMAND_EDITOR;
static {
String[] xs = new String[]
{ "serializableAspects", "incrementalFile"
//, "targetNearSource", "OcodeSize",
};
VALID_XOPTIONS = Collections.unmodifiableList(Arrays.asList(xs));
xs = new String[]
{"constructorName", "packageDefaultMethod", "deprecation",
"maskedCatchBlocks", "unusedLocals", "unusedArguments",
"unusedImports", "syntheticAccess", "assertIdentifier", "none" };
VALID_WARNINGS = Collections.unmodifiableList(Arrays.asList(xs));
xs = new String[] {"none", "lines", "vars", "source" };
VALID_DEBUG = Collections.unmodifiableList(Arrays.asList(xs));
xs = new String[] { "error", "warning", "ignore"};
VALID_XLINT = Collections.unmodifiableList(Arrays.asList(xs));
ICommandEditor editor = null;
try {
String editorClassName = System.getProperty(COMMAND_EDITOR_NAME);
if (null != editorClassName) {
ClassLoader cl = AjcTask.class.getClassLoader();
Class editorClass = cl.loadClass(editorClassName);
editor = (ICommandEditor) editorClass.newInstance();
}
} catch (Throwable t) {
System.err.println("Warning: unable to load command editor");
t.printStackTrace(System.err);
}
COMMAND_EDITOR = editor;
}
// ---------------------------- state and Ant interface thereto
private boolean verbose;
private boolean listFileArgs;
private boolean failonerror;
private boolean fork;
private String maxMem;
// ------- single entries dumped into cmd
protected GuardedCommand cmd;
// ------- lists resolved in addListArgs() at execute() time
private Path srcdir;
private Path injars;
private Path inpath;
private Path classpath;
private Path bootclasspath;
private Path forkclasspath;
private Path extdirs;
private Path aspectpath;
private Path argfiles;
private List ignored;
private Path sourceRoots;
private File xweaveDir;
// ----- added by adapter - integrate better?
private List /* File */ adapterFiles;
private String[] adapterArguments;
private IMessageHolder messageHolder;
private ICommandEditor commandEditor;
// -------- resource-copying
/** true if copying injar non-.class files to the output jar */
private boolean copyInjars;
private boolean copyInpath;
/** non-null if copying all source root files but the filtered ones */
private String sourceRootCopyFilter;
/** directory sink for classes */
private File destDir;
/** zip file sink for classes */
private File outjar;
/** track whether we've supplied any temp outjar */
private boolean outjarFixedup;
/**
* When possibly copying resources to the output jar,
* pass ajc a fake output jar to copy from,
* so we don't change the modification time of the output jar
* when copying injars/inpath into the actual outjar.
*/
private File tmpOutjar;
private boolean executing;
/** non-null only while executing in same vm */
private Main main;
/** true only when executing in other vm */
private boolean executingInOtherVM;
/** true if -incremental */
private boolean inIncrementalMode;
/** true if -XincrementalFile (i.e, setTagFile)*/
private boolean inIncrementalFileMode;
// also note MatchingTask grabs source files...
public AjcTask() {
reset();
}
/** to use this same Task more than once (testing) */
public void reset() { // XXX possible to reset MatchingTask?
// need declare for "all fields initialized in ..."
adapterArguments = null;
adapterFiles = new ArrayList();
argfiles = null;
executing = false;
aspectpath = null;
bootclasspath = null;
classpath = null;
cmd = new GuardedCommand();
copyInjars = false;
copyInpath = false;
destDir = DEFAULT_DESTDIR;
executing = false;
executingInOtherVM = false;
extdirs = null;
failonerror = true; // non-standard default
forkclasspath = null;
inIncrementalMode = false;
inIncrementalFileMode = false;
ignored = new ArrayList();
injars = null;
inpath = null;
listFileArgs = false;
maxMem = null;
messageHolder = null;
outjar = null;
sourceRootCopyFilter = null;
sourceRoots = null;
srcdir = null;
tmpOutjar = null;
verbose = false;
xweaveDir = null;
}
protected void ignore(String ignored) {
this.ignored.add(ignored + " at " + getLocation());
}
//---------------------- option values
// used by entries with internal commas
protected String validCommaList(String list, List valid, String label) {
return validCommaList(list, valid, label, valid.size());
}
protected String validCommaList(String list, List valid, String label, int max) {
StringBuffer result = new StringBuffer();
StringTokenizer st = new StringTokenizer(list, ",");
int num = 0;
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
num++;
if (num > max) {
ignore("too many entries for -"
+ label
+ ": "
+ token);
break;
}
if (!valid.contains(token)) {
ignore("bad commaList entry for -"
+ label
+ ": "
+ token);
} else {
if (0 < result.length()) {
result.append(",");
}
result.append(token);
}
}
return (0 == result.length() ? null : result.toString());
}
public void setIncremental(boolean incremental) {
cmd.addFlag("-incremental", incremental);
inIncrementalMode = incremental;
}
public void setHelp(boolean help) {
cmd.addFlag("-help", help);
}
public void setVersion(boolean version) {
cmd.addFlag("-version", version);
}
public void setXNoweave(boolean noweave) {
cmd.addFlag("-XnoWeave", noweave);
}
public void setNowarn(boolean nowarn) {
cmd.addFlag("-nowarn", nowarn);
}
public void setDeprecation(boolean deprecation) {
cmd.addFlag("-deprecation", deprecation);
}
public void setWarn(String warnings) {
warnings = validCommaList(warnings, VALID_WARNINGS, "warn");
cmd.addFlag("-warn:" + warnings, (null != warnings));
}
public void setDebug(boolean debug) {
cmd.addFlag("-g", debug);
}
public void setDebugLevel(String level) {
level = validCommaList(level, VALID_DEBUG, "g");
cmd.addFlag("-g:" + level, (null != level));
}
public void setEmacssym(boolean emacssym) {
cmd.addFlag("-emacssym", emacssym);
}
/**
* -Xlint - set default level of -Xlint messages to warning
* (same as </code>-Xlint:warning</code>)
*/
public void setXlintwarnings(boolean xlintwarnings) {
cmd.addFlag("-Xlint", xlintwarnings);
}
/** -Xlint:{error|warning|info} - set default level for -Xlint messages
* @param xlint the String with one of error, warning, ignored
*/
public void setXlint(String xlint) {
xlint = validCommaList(xlint, VALID_XLINT, "Xlint", 1);
cmd.addFlag("-Xlint:" + xlint, (null != xlint));
}
/**
* -Xlintfile {lint.properties} - enable or disable specific forms
* of -Xlint messages based on a lint properties file
* (default is
* <code>org/aspectj/weaver/XLintDefault.properties</code>)
* @param xlintFile the File with lint properties
*/
public void setXlintfile(File xlintFile) {
cmd.addFlagged("-Xlintfile", xlintFile.getAbsolutePath());
}
public void setPreserveAllLocals(boolean preserveAllLocals) {
cmd.addFlag("-preserveAllLocals", preserveAllLocals);
}
public void setNoImportError(boolean noImportError) {
cmd.addFlag("-warn:-unusedImport", noImportError);
}
public void setEncoding(String encoding) {
cmd.addFlagged("-encoding", encoding);
}
public void setLog(File file) {
cmd.addFlagged("-log", file.getAbsolutePath());
}
public void setProceedOnError(boolean proceedOnError) {
cmd.addFlag("-proceedOnError", proceedOnError);
}
public void setVerbose(boolean verbose) {
cmd.addFlag("-verbose", verbose);
this.verbose = verbose;
}
public void setListFileArgs(boolean listFileArgs) {
this.listFileArgs = listFileArgs;
}
public void setReferenceInfo(boolean referenceInfo) {
cmd.addFlag("-referenceInfo", referenceInfo);
}
public void setProgress(boolean progress) {
cmd.addFlag("-progress", progress);
}
public void setTime(boolean time) {
cmd.addFlag("-time", time);
}
public void setNoExit(boolean noExit) {
cmd.addFlag("-noExit", noExit);
}
public void setFailonerror(boolean failonerror) {
this.failonerror = failonerror;
}
/**
* @return true if fork was set
*/
public boolean isForked() {
return fork;
}
public void setFork(boolean fork) {
this.fork = fork;
}
public void setMaxmem(String maxMem) {
this.maxMem = maxMem;
}
// ----------------
public void setTagFile(File file) {
inIncrementalMode = true;
cmd.addFlagged(Main.CommandController.TAG_FILE_OPTION,
file.getAbsolutePath());
inIncrementalFileMode = true;
}
public void setOutjar(File file) {
if (DEFAULT_DESTDIR != destDir) {
String e = "specifying both output jar ("
+ file
+ ") and destination dir ("
+ destDir
+ ")";
throw new BuildException(e);
}
outjar = file;
outjarFixedup = false;
tmpOutjar = null;
}
public void setDestdir(File dir) {
if (null != outjar) {
String e = "specifying both output jar ("
+ outjar
+ ") and destination dir ("
+ dir
+ ")";
throw new BuildException(e);
}
cmd.addFlagged("-d", dir.getAbsolutePath());
destDir = dir;
}
/**
* @param input a String in TARGET_INPUTS
*/
public void setTarget(String input) {
String ignore = cmd.addOption("-target", TARGET_INPUTS, input);
if (null != ignore) {
ignore(ignore);
}
}
/**
* Language compliance level.
* If not set explicitly, eclipse default holds.
* @param input a String in COMPLIANCE_INPUTS
*/
public void setCompliance(String input) {
String ignore = cmd.addOption(null, COMPLIANCE_INPUTS, input);
if (null != ignore) {
ignore(ignore);
}
}
/**
* Source compliance level.
* If not set explicitly, eclipse default holds.
* @param input a String in SOURCE_INPUTS
*/
public void setSource(String input) {
String ignore = cmd.addOption("-source", SOURCE_INPUTS, input);
if (null != ignore) {
ignore(ignore);
}
}
/**
* Flag to copy all non-.class contents of injars
* to outjar after compile completes.
* Requires both injars and outjar.
* @param doCopy
*/
public void setCopyInjars(boolean doCopy){
ignore("copyInJars");
log("copyInjars not required since 1.1.1.\n", Project.MSG_WARN);
//this.copyInjars = doCopy;
}
/**
* Option to copy all files from
* all source root directories
* except those specified here.
* If this is specified and sourceroots are specified,
* then this will copy all files except
* those specified in the filter pattern.
* Requires sourceroots.
*
* @param filter a String acceptable as an excludes
* filter for an Ant Zip fileset.
*/
public void setSourceRootCopyFilter(String filter){
this.sourceRootCopyFilter = filter;
}
public void setX(String input) { // ajc-only eajc-also docDone
StringTokenizer tokens = new StringTokenizer(input, ",", false);
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken().trim();
if (1 < token.length()) {
if (VALID_XOPTIONS.contains(token)) {
cmd.addFlag("-X" + token, true);
} else {
ignore("-X" + token);
}
}
}
}
/** direct API for testing */
public void setMessageHolder(IMessageHolder holder) {
this.messageHolder = holder;
}
/**
* Setup custom message handling.
* @param className the String fully-qualified-name of a class
* reachable from this object's class loader,
* implementing IMessageHolder, and
* having a public no-argument constructor.
* @throws BuildException if unable to create instance of className
*/
public void setMessageHolderClass(String className) {
try {
Class mclass = Class.forName(className);
IMessageHolder holder = (IMessageHolder) mclass.newInstance();
setMessageHolder(holder);
} catch (Throwable t) {
String m = "unable to instantiate message holder: " + className;
throw new BuildException(m, t);
}
}
/** direct API for testing */
public void setCommandEditor(ICommandEditor editor) {
this.commandEditor = editor;
}
/**
* Setup command-line filter.
* To do this staticly, define the environment variable
* <code>org.aspectj.tools.ant.taskdefs.AjcTask.COMMAND_EDITOR</code>
* with the <code>className</code> parameter.
* @param className the String fully-qualified-name of a class
* reachable from this object's class loader,
* implementing ICommandEditor, and
* having a public no-argument constructor.
* @throws BuildException if unable to create instance of className
*/
public void setCommandEditorClass(String className) { // skip Ant interface?
try {
Class mclass = Class.forName(className);
setCommandEditor((ICommandEditor) mclass.newInstance());
} catch (Throwable t) {
String m = "unable to instantiate command editor: " + className;
throw new BuildException(m, t);
}
}
//---------------------- Path lists
/**
* Add path elements to source path and return result.
* Elements are added even if they do not exist.
* @param source the Path to add to - may be null
* @param toAdd the Path to add - may be null
* @return the (never-null) Path that results
*/
protected Path incPath(Path source, Path toAdd) {
if (null == source) {
source = new Path(project);
}
if (null != toAdd) {
source.append(toAdd);
}
return source;
}
public void setSourcerootsref(Reference ref) {
createSourceRoots().setRefid(ref);
}
public void setSourceRoots(Path roots) {
sourceRoots = incPath(sourceRoots, roots);
}
public Path createSourceRoots() {
if (sourceRoots == null) {
sourceRoots = new Path(project);
}
return sourceRoots.createPath();
}
public void setXWeaveDir(File file) {
if ((null != file) && file.isDirectory()
&& file.canRead()) {
xweaveDir = file;
}
}
public void setInjarsref(Reference ref) {
createInjars().setRefid(ref);
}
public void setInpathref(Reference ref) {
createInpath().setRefid(ref);
}
public void setInjars(Path path) {
injars = incPath(injars, path);
}
public void setInpath(Path path) {
inpath = incPath(inpath,path);
}
public Path createInjars() {
if (injars == null) {
injars = new Path(project);
}
return injars.createPath();
}
public Path createInpath() {
if (inpath == null) {
inpath = new Path(project);
}
return inpath.createPath();
}
public void setClasspath(Path path) {
classpath = incPath(classpath, path);
}
public void setClasspathref(Reference classpathref) {
createClasspath().setRefid(classpathref);
}
public Path createClasspath() {
if (classpath == null) {
classpath = new Path(project);
}
return classpath.createPath();
}
public void setBootclasspath(Path path) {
bootclasspath = incPath(bootclasspath, path);
}
public void setBootclasspathref(Reference bootclasspathref) {
createBootclasspath().setRefid(bootclasspathref);
}
public Path createBootclasspath() {
if (bootclasspath == null) {
bootclasspath = new Path(project);
}
return bootclasspath.createPath();
}
public void setForkclasspath(Path path) {
forkclasspath = incPath(forkclasspath, path);
}
public void setForkclasspathref(Reference forkclasspathref) {
createForkclasspath().setRefid(forkclasspathref);
}
public Path createForkclasspath() {
if (forkclasspath == null) {
forkclasspath = new Path(project);
}
return forkclasspath.createPath();
}
public void setExtdirs(Path path) {
extdirs = incPath(extdirs, path);
}
public void setExtdirsref(Reference ref) {
createExtdirs().setRefid(ref);
}
public Path createExtdirs() {
if (extdirs == null) {
extdirs = new Path(project);
}
return extdirs.createPath();
}
public void setAspectpathref(Reference ref) {
createAspectpath().setRefid(ref);
}
public void setAspectpath(Path path) {
aspectpath = incPath(aspectpath, path);
}
public Path createAspectpath() {
if (aspectpath == null) {
aspectpath = new Path(project);
}
return aspectpath.createPath();
}
public void setSrcDir(Path path) {
srcdir = incPath(srcdir, path);
}
public Path createSrc() {
return createSrcdir();
}
public Path createSrcdir() {
if (srcdir == null) {
srcdir = new Path(project);
}
return srcdir.createPath();
}
/** @return true if in incremental mode (command-line or file) */
public boolean isInIncrementalMode() {
return inIncrementalMode;
}
/** @return true if in incremental file mode */
public boolean isInIncrementalFileMode() {
return inIncrementalFileMode;
}
public void setArgfilesref(Reference ref) {
createArgfiles().setRefid(ref);
}
public void setArgfiles(Path path) { // ajc-only eajc-also docDone
argfiles = incPath(argfiles, path);
}
public Path createArgfiles() {
if (argfiles == null) {
argfiles = new Path(project);
}
return argfiles.createPath();
}
// ------------------------------ run
/**
* Compile using ajc per settings.
* @exception BuildException if the compilation has problems
* or if there were compiler errors and failonerror is true.
*/
public void execute() throws BuildException {
if (executing) {
throw new IllegalStateException("already executing");
} else {
executing = true;
}
setupOptions();
verifyOptions();
try {
String[] args = makeCommand();
if (verbose || listFileArgs) { // XXX if listFileArgs, only do that
log("ajc " + Arrays.asList(args), Project.MSG_VERBOSE);
}
if (!fork) {
executeInSameVM(args);
} else { // when forking, Adapter handles failonerror
executeInOtherVM(args);
}
} catch (BuildException e) {
throw e;
} catch (Throwable x) {
System.err.println(Main.renderExceptionForUser(x));
throw new BuildException("IGNORE -- See "
+ LangUtil.unqualifiedClassName(x)
+ " rendered to System.err");
} finally {
executing = false;
if (null != tmpOutjar) {
tmpOutjar.delete();
}
}
}
/**
* Halt processing.
* This tells main in the same vm to quit.
* It fails when running in forked mode.
* @return true if not in forked mode
* and main has quit or been told to quit
*/
public boolean quit() {
if (executingInOtherVM) {
return false;
}
Main me = main;
if (null != me) {
me.quit();
}
return true;
}
// package-private for testing
String[] makeCommand() {
ArrayList result = new ArrayList();
if (0 < ignored.size()) {
for (Iterator iter = ignored.iterator(); iter.hasNext();) {
log("ignored: " + iter.next(), Project.MSG_INFO);
}
}
// when copying resources, use temp jar for class output
// then copy temp jar contents and resources to output jar
if ((null != outjar) && !outjarFixedup) {
if (copyInjars || copyInpath || (null != sourceRootCopyFilter)) {
String path = outjar.getAbsolutePath();
int len = FileUtil.zipSuffixLength(path);
if (len < 1) {
log("not copying resources - weird outjar: " + path);
} else {
path = path.substring(0, path.length()-len) + ".tmp.jar";
tmpOutjar = new File(path);
}
}
if (null == tmpOutjar) {
cmd.addFlagged("-outjar", outjar.getAbsolutePath());
} else {
cmd.addFlagged("-outjar", tmpOutjar.getAbsolutePath());
}
outjarFixedup = true;
}
result.addAll(cmd.extractArguments());
addListArgs(result);
String[] command = (String[]) result.toArray(new String[0]);
if (null != commandEditor) {
command = commandEditor.editCommand(command);
} else if (null != COMMAND_EDITOR) {
command = COMMAND_EDITOR.editCommand(command);
}
return command;
}
/**
* Create any pseudo-options required to implement
* some of the macro options
* @throws BuildException if options conflict
*/
protected void setupOptions() {
if (null != xweaveDir) {
if (DEFAULT_DESTDIR != destDir) {
throw new BuildException("weaveDir forces destdir");
}
if (null != outjar) {
throw new BuildException("weaveDir forces outjar");
}
if (null != injars) {
throw new BuildException("weaveDir incompatible with injars now");
}
if (null != inpath) {
throw new BuildException("weaveDir incompatible with inpath now");
}
File injar = zipDirectory(xweaveDir);
setInjars(new Path(getProject(), injar.getAbsolutePath()));
setDestdir(xweaveDir);
}
}
protected File zipDirectory(File dir) {
File tempDir = new File(".");
try {
tempDir = File.createTempFile("AjcTest", ".tmp");
tempDir.mkdirs();
tempDir.deleteOnExit(); // XXX remove zip explicitly..
} catch (IOException e) {
// ignore
}
// File result = new File(tempDir,
String filename = "AjcTask-"
+ System.currentTimeMillis()
+ ".zip";
File result = new File(filename);
Zip zip = new Zip();
zip.setProject(getProject());
zip.setDestFile(result);
zip.setTaskName(getTaskName() + " - zip");
FileSet fileset = new FileSet();
fileset.setDir(dir);
zip.addFileset(fileset);
zip.execute();
Delete delete = new Delete();
delete.setProject(getProject());
delete.setTaskName(getTaskName() + " - delete");
delete.setDir(dir);
delete.execute();
Mkdir mkdir = new Mkdir();
mkdir.setProject(getProject());
mkdir.setTaskName(getTaskName() + " - mkdir");
mkdir.setDir(dir);
mkdir.execute();
return result;
}
/**
* @throw BuildException if options conflict
*/
protected void verifyOptions() {
StringBuffer sb = new StringBuffer();
if (fork && isInIncrementalMode() && !isInIncrementalFileMode()) {
sb.append("can fork incremental only using tag file.\n");
}
if ((null != sourceRootCopyFilter) && (null == outjar)
&& (DEFAULT_DESTDIR == destDir)) {
final String REQ = " requires dest dir or output jar.\n";
sb.append("sourceRootCopyFilter");
sb.append(REQ);
}
if (0 < sb.length()) {
throw new BuildException(sb.toString());
}
}
/**
* Run the compile in the same VM by
* loading the compiler (Main),
* setting up any message holders,
* doing the compile,
* and converting abort/failure and error messages
* to BuildException, as appropriate.
* @throws BuildException if abort or failure messages
* or if errors and failonerror.
*
*/
protected void executeInSameVM(String[] args) {
if (null != maxMem) {
log("maxMem ignored unless forked: " + maxMem, Project.MSG_WARN);
}
IMessageHolder holder = messageHolder;
int numPreviousErrors;
if (null == holder) {
MessageHandler mhandler = new MessageHandler(true);
final IMessageHandler delegate
= verbose ? MessagePrinter.VERBOSE: MessagePrinter.TERSE;
mhandler.setInterceptor(delegate);
if (!verbose) {
mhandler.ignore(IMessage.INFO);
}
holder = mhandler;
numPreviousErrors = 0;
} else {
numPreviousErrors = holder.numMessages(IMessage.ERROR, true);
}
{
Main newmain = new Main();
newmain.setHolder(holder);
newmain.setCompletionRunner(new Runnable() {
public void run() {
doCompletionTasks();
}
});
if (null != main) {
MessageUtil.fail(holder, "still running prior main");
return;
}
main = newmain;
}
try {
main.runMain(args, false);
} finally {
main = null;
}
if (failonerror) {
int errs = holder.numMessages(IMessage.ERROR, false);
errs -= numPreviousErrors;
if (0 < errs) {
String m = errs + " errors";
MessageUtil.print(System.err, holder, "", MessageUtil.MESSAGE_ALL, MessageUtil.PICK_ERROR, true);
throw new BuildException(m);
}
}
// Throw BuildException if there are any fail or abort
// messages.
// The BuildException message text has a list of class names
// for the exceptions found in the messages, or the
// number of fail/abort messages found if there were
// no exceptions for any of the fail/abort messages.
// The interceptor message handler should have already
// printed the messages, including any stack traces.
// HACK: this ignores the Usage message
{
IMessage[] fails = holder.getMessages(IMessage.FAIL, true);
if (!LangUtil.isEmpty(fails)) {
StringBuffer sb = new StringBuffer();
String prefix = "fail due to ";
int numThrown = 0;
for (int i = 0; i < fails.length; i++) {
String message = fails[i].getMessage();
if (LangUtil.isEmpty(message)) {
message = "<no message>";
} else if (-1 != message.indexOf(USAGE_SUBSTRING)) {
continue;
}
Throwable t = fails[i].getThrown();
if (null != t) {
numThrown++;
sb.append(prefix);
sb.append(LangUtil.unqualifiedClassName(t.getClass()));
String thrownMessage = t.getMessage();
if (!LangUtil.isEmpty(thrownMessage)) {
sb.append(" \"" + thrownMessage + "\"");
}
}
sb.append("\"" + message + "\"");
prefix = ", ";
}
if (0 < sb.length()) {
sb.append(" (" + numThrown + " exceptions)");
throw new BuildException(sb.toString());
}
}
}
}
/**
* Execute in a separate VM.
* Differences from normal same-VM execution:
* <ul>
* <li>ignores any message holder {class} set</li>
* <li>No resource-copying between interative runs</li>
* <li>failonerror fails when process interface fails
* to return negative values</li>
* </ul>
* @param args String[] of the complete compiler command to execute
*
* @see DefaultCompilerAdapter#executeExternalCompile(String[], int)
* @throws BuildException if ajc aborts (negative value)
* or if failonerror and there were compile errors.
*/
protected void executeInOtherVM(String[] args) {
if (null != messageHolder) {
log("message holder ignored when forking: "
+ messageHolder.getClass().getName(), Project.MSG_WARN);
}
CommandlineJava javaCmd = new CommandlineJava();
javaCmd.setClassname(org.aspectj.tools.ajc.Main.class.getName());
final Path vmClasspath = javaCmd.createClasspath(getProject());
{
File aspectjtools = null;
int vmClasspathSize = vmClasspath.size();
if ((null != forkclasspath)
&& (0 != forkclasspath.size())) {
vmClasspath.addExisting(forkclasspath);
} else {
aspectjtools = findAspectjtoolsJar();
if (null != aspectjtools) {
vmClasspath.createPathElement().setLocation(aspectjtools);
}
}
int newVmClasspathSize = vmClasspath.size();
if (vmClasspathSize == newVmClasspathSize) {
String m = "unable to find aspectjtools to fork - ";
if (null != aspectjtools) {
m += "tried " + aspectjtools.toString();
} else if (null != forkclasspath) {
m += "tried " + forkclasspath.toString();
} else {
m += "define forkclasspath or put aspectjtools on classpath";
}
throw new BuildException(m);
}
}
if (null != maxMem) {
javaCmd.setMaxmemory(maxMem);
}
File tempFile = null;
int numArgs = args.length;
args = GuardedCommand.limitTo(args, MAX_COMMANDLINE, getLocation());
if (args.length != numArgs) {
tempFile = new File(args[1]);
}
try {
String[] javaArgs = javaCmd.getCommandline();
String[] both = new String[javaArgs.length + args.length];
System.arraycopy(javaArgs,0,both,0,javaArgs.length);
System.arraycopy(args,0,both,javaArgs.length,args.length);
// try to use javaw instead on windows
if (both[0].endsWith("java.exe")) {
String path = both[0];
path = path.substring(0, path.length()-4);
path = path + "w.exe";
File javaw = new File(path);
if (javaw.canRead() && javaw.isFile()) {
both[0] = path;
}
}
if (verbose) { // XXX also when ant is verbose...
log("forking " + Arrays.asList(both));
}
int result = execInOtherVM(both);
if (0 > result) {
throw new BuildException("failure[" + result + "] running ajc");
} else if (failonerror && (0 < result)) {
throw new BuildException("compile errors: " + result);
}
// when forking, do completion only at end and when successful
doCompletionTasks();
} finally {
if (null != tempFile) {
tempFile.delete();
}
}
}
/**
* Execute in another process using the same JDK
* and the base directory of the project. XXX correct?
* @param args
* @return
*/
protected int execInOtherVM(String[] args) {
try {
Project project = getProject();
LogStreamHandler handler = new LogStreamHandler(this,
Project.MSG_INFO, Project.MSG_WARN);
Execute exe = new Execute(handler);
exe.setAntRun(project);
exe.setWorkingDirectory(project.getBaseDir());
exe.setCommandline(args);
try {
if (executingInOtherVM) {
String s = "already running in other vm?";
throw new BuildException(s, location);
}
executingInOtherVM = true;
exe.execute();
} finally {
executingInOtherVM = false;
}
return exe.getExitValue();
} catch (IOException e) {
String m = "Error executing command " + Arrays.asList(args);
throw new BuildException(m, e, location);
}
}
// ------------------------------ setup and reporting
/** @return null if path null or empty, String rendition otherwise */
protected static void addFlaggedPath(String flag, Path path, List list) {
if (!LangUtil.isEmpty(flag)
&& ((null != path) && (0 < path.size()))) {
list.add(flag);
list.add(path.toString());
}
}
/**
* Add to list any path or plural arguments.
*/
protected void addListArgs(List list) throws BuildException {
addFlaggedPath("-classpath", classpath, list);
addFlaggedPath("-bootclasspath", bootclasspath, list);
addFlaggedPath("-extdirs", extdirs, list);
addFlaggedPath("-aspectpath", aspectpath, list);
addFlaggedPath("-injars", injars, list);
addFlaggedPath("-inpath", inpath, list);
addFlaggedPath("-sourceroots", sourceRoots, list);
if (argfiles != null) {
String[] files = argfiles.list();
for (int i = 0; i < files.length; i++) {
File argfile = project.resolveFile(files[i]);
if (check(argfile, files[i], false, location)) {
list.add("-argfile");
list.add(argfile.getAbsolutePath());
}
}
}
if (srcdir != null) {
// todo: ignore any srcdir if any argfiles and no explicit includes
String[] dirs = srcdir.list();
for (int i = 0; i < dirs.length; i++) {
File dir = project.resolveFile(dirs[i]);
check(dir, dirs[i], true, location);
// relies on compiler to prune non-source files
String[] files = getDirectoryScanner(dir).getIncludedFiles();
for (int j = 0; j < files.length; j++) {
File file = new File(dir, files[j]);
if (FileUtil.hasSourceSuffix(file)) {
list.add(file.getAbsolutePath());
}
}
}
}
if (0 < adapterFiles.size()) {
for (Iterator iter = adapterFiles.iterator(); iter.hasNext();) {
File file = (File) iter.next();
if (file.canRead() && FileUtil.hasSourceSuffix(file)) {
list.add(file.getAbsolutePath());
} else {
log("skipping file: " + file, Project.MSG_WARN);
}
}
}
}
/**
* Throw BuildException unless file is valid.
* @param file the File to check
* @param name the symbolic name to print on error
* @param isDir if true, verify file is a directory
* @param loc the Location used to create sensible BuildException
* @return
* @throws BuildException unless file valid
*/
protected final boolean check(File file, String name,
boolean isDir, Location loc) {
loc = loc != null ? loc : location;
if (file == null) {
throw new BuildException(name + " is null!", loc);
}
if (!file.exists()) {
throw new BuildException(file + " doesn't exist!", loc);
}
if (isDir ^ file.isDirectory()) {
String e = file + " should" + (isDir ? "" : "n't") +
" be a directory!";
throw new BuildException(e, loc);
}
return true;
}
/**
* Called when compile or incremental compile is completing,
* this completes the output jar or directory
* by copying resources if requested.
* Note: this is a callback run synchronously by the compiler.
* That means exceptions thrown here are caught by Main.run(..)
* and passed to the message handler.
*/
protected void doCompletionTasks() {
if (!executing) {
throw new IllegalStateException("should be executing");
}
if (null != outjar) {
completeOutjar();
} else {
completeDestdir();
}
}
/**
* Complete the destination directory
* by copying resources from the source root directories
* (if the filter is specified)
* and non-.class files from the input jars
* (if XCopyInjars is enabled).
*/
private void completeDestdir() {
if (!copyInjars && (null == sourceRootCopyFilter)) {
return;
} else if ((destDir == DEFAULT_DESTDIR)
|| !destDir.canWrite()) {
String s = "unable to copy resources to destDir: " + destDir;
throw new BuildException(s);
}
final Project project = getProject();
if (copyInjars) { // XXXX remove as unused since 1.1.1
if (null != inpath) {
log("copyInjars does not support inpath.\n", Project.MSG_WARN);
}
String taskName = getTaskName() + " - unzip";
String[] paths = injars.list();
if (!LangUtil.isEmpty(paths)) {
PatternSet patternSet = new PatternSet();
patternSet.setProject(project);
patternSet.setIncludes("**/*");
patternSet.setExcludes("**/*.class");
for (int i = 0; i < paths.length; i++) {
Expand unzip = new Expand();
unzip.setProject(project);
unzip.setTaskName(taskName);
unzip.setDest(destDir);
unzip.setSrc(new File(paths[i]));
unzip.addPatternset(patternSet);
unzip.execute();
}
}
}
if ((null != sourceRootCopyFilter) && (null != sourceRoots)) {
String[] paths = sourceRoots.list();
if (!LangUtil.isEmpty(paths)) {
Copy copy = new Copy();
copy.setProject(project);
copy.setTodir(destDir);
for (int i = 0; i < paths.length; i++) {
FileSet fileSet = new FileSet();
fileSet.setDir(new File(paths[i]));
fileSet.setIncludes("**/*");
fileSet.setExcludes(sourceRootCopyFilter);
copy.addFileset(fileSet);
}
copy.execute();
}
}
}
/**
* Complete the output jar
* by copying resources from the source root directories
* if the filter is specified.
* and non-.class files from the input jars if enabled.
*/
private void completeOutjar() {
if (((null == tmpOutjar) || !tmpOutjar.canRead())
|| (!copyInjars && (null == sourceRootCopyFilter))) {
return;
}
Zip zip = new Zip();
Project project = getProject();
zip.setProject(project);
zip.setTaskName(getTaskName() + " - zip");
zip.setDestFile(outjar);
ZipFileSet zipfileset = new ZipFileSet();
zipfileset.setProject(project);
zipfileset.setSrc(tmpOutjar);
zipfileset.setIncludes("**/*.class");
zip.addZipfileset(zipfileset);
if (copyInjars) {
String[] paths = injars.list();
if (!LangUtil.isEmpty(paths)) {
for (int i = 0; i < paths.length; i++) {
File jarFile = new File(paths[i]);
zipfileset = new ZipFileSet();
zipfileset.setProject(project);
zipfileset.setSrc(jarFile);
zipfileset.setIncludes("**/*");
zipfileset.setExcludes("**/*.class");
zip.addZipfileset(zipfileset);
}
}
}
if ((null != sourceRootCopyFilter) && (null != sourceRoots)) {
String[] paths = sourceRoots.list();
if (!LangUtil.isEmpty(paths)) {
for (int i = 0; i < paths.length; i++) {
File srcRoot = new File(paths[i]);
FileSet fileset = new FileSet();
fileset.setProject(project);
fileset.setDir(srcRoot);
fileset.setIncludes("**/*");
fileset.setExcludes(sourceRootCopyFilter);
zip.addFileset(fileset);
}
}
}
zip.execute();
}
// -------------------------- compiler adapter interface extras
/**
* Add specified source files.
*/
void addFiles(File[] paths) {
for (int i = 0; i < paths.length; i++) {
addFile(paths[i]);
}
}
/**
* Add specified source file.
*/
void addFile(File path) {
if (null != path) {
adapterFiles.add(path);
}
}
/**
* Read arguments in as if from a command line,
* mainly to support compiler adapter compilerarg subelement.
*
* @param args the String[] of arguments to read
*/
public void readArguments(String[] args) { // XXX slow, stupid, unmaintainable
if ((null == args) || (0 == args.length)) {
return;
}
/** String[] wrapper with increment, error reporting */
class Args {
final String[] args;
int index = 0;
Args(String[] args) {
this.args = args; // not null or empty
}
boolean hasNext() {
return index < args.length;
}
String next() {
String err = null;
if (!hasNext()) {
err = "need arg for flag " + args[args.length-1];
} else {
String s = args[index++];
if (null == s) {
err = "null value";
} else {
s = s.trim();
if (0 == s.trim().length()) {
err = "no value";
} else {
return s;
}
}
}
err += " at [" + index + "] of " + Arrays.asList(args);
throw new BuildException(err);
}
} // class Args
Args in = new Args(args);
String flag;
while (in.hasNext()) {
flag = in.next();
if ("-1.3".equals(flag)) {
setCompliance("1.3");
} else if ("-1.4".equals(flag)) {
setCompliance("1.4");
// } else if ("-1.5".equals(flag)) {
// setCompliance("1.5");
} else if ("-argfile".equals(flag)) {
setArgfiles(new Path(project, in.next()));
} else if ("-aspectpath".equals(flag)) {
setAspectpath(new Path(project, in.next()));
} else if ("-classpath".equals(flag)) {
setClasspath(new Path(project, in.next()));
} else if ("-Xcopyinjars".equals(flag)) {
setCopyInjars(true); // ignored - will be flagged by setter
} else if ("-g".equals(flag)) {
setDebug(true);
} else if (flag.startsWith("-g:")) {
setDebugLevel(flag.substring(2));
} else if ("-deprecation".equals(flag)) {
setDeprecation(true);
} else if ("-d".equals(flag)) {
setDestdir(new File(in.next()));
} else if ("-emacssym".equals(flag)) {
setEmacssym(true);
} else if ("-encoding".equals(flag)) {
setEncoding(in.next());
} else if ("-Xfailonerror".equals(flag)) {
setFailonerror(true);
} else if ("-fork".equals(flag)) {
setFork(true);
} else if ("-forkclasspath".equals(flag)) {
setForkclasspath(new Path(project, in.next()));
} else if ("-help".equals(flag)) {
setHelp(true);
} else if ("-incremental".equals(flag)) {
setIncremental(true);
} else if ("-injars".equals(flag)) {
setInjars(new Path(project, in.next()));
} else if ("-inpath".equals(flag)) {
setInpath(new Path(project,in.next()));
} else if ("-Xlistfileargs".equals(flag)) {
setListFileArgs(true);
} else if ("-Xmaxmem".equals(flag)) {
setMaxmem(in.next());
} else if ("-Xmessageholderclass".equals(flag)) {
setMessageHolderClass(in.next());
} else if ("-noexit".equals(flag)) {
setNoExit(true);
} else if ("-noimport".equals(flag)) {
setNoExit(true);
} else if ("-noExit".equals(flag)) {
setNoExit(true);
} else if ("-noImportError".equals(flag)) {
setNoImportError(true);
} else if ("-noWarn".equals(flag)) {
setNowarn(true);
} else if ("-noexit".equals(flag)) {
setNoExit(true);
} else if ("-outjar".equals(flag)) {
setOutjar(new File(in.next()));
} else if ("-preserveAllLocals".equals(flag)) {
setPreserveAllLocals(true);
} else if ("-proceedOnError".equals(flag)) {
setProceedOnError(true);
} else if ("-progress".equals(flag)) {
setProgress(true);
} else if ("-referenceInfo".equals(flag)) {
setReferenceInfo(true);
} else if ("-source".equals(flag)) {
setSource(in.next());
} else if ("-Xsourcerootcopyfilter".equals(flag)) {
setSourceRootCopyFilter(in.next());
} else if ("-sourceroots".equals(flag)) {
setSourceRoots(new Path(project, in.next()));
} else if ("-Xsrcdir".equals(flag)) {
setSrcDir(new Path(project, in.next()));
} else if ("-Xtagfile".equals(flag)) {
setTagFile(new File(in.next()));
} else if ("-target".equals(flag)) {
setTarget(in.next());
} else if ("-time".equals(flag)) {
setTime(true);
} else if ("-time".equals(flag)) {
setTime(true);
} else if ("-verbose".equals(flag)) {
setVerbose(true);
} else if ("-version".equals(flag)) {
setVersion(true);
} else if ("-warn".equals(flag)) {
setWarn(in.next());
} else if (flag.startsWith("-warn:")) {
setWarn(flag.substring(6));
} else if ("-Xlint".equals(flag)) {
setXlintwarnings(true);
} else if (flag.startsWith("-Xlint:")) {
setXlint(flag.substring(7));
} else if ("-Xlintfile".equals(flag)) {
setXlintfile(new File(in.next()));
} else if ("-Xnoweave".equals(flag)) {
setXNoweave(true);
} else if (flag.startsWith("@")) {
File file = new File(flag.substring(1));
if (file.canRead()) {
setArgfiles(new Path(project, file.getPath()));
} else {
ignore(flag);
}
} else {
File file = new File(flag);
if (file.isFile()
&& file.canRead()
&& FileUtil.hasSourceSuffix(file)) {
addFile(file);
} else {
ignore(flag);
}
}
}
}
/**
* Commandline wrapper that
* only permits addition of non-empty values
* and converts to argfile form if necessary.
*/
public static class GuardedCommand {
Commandline command;
//int size;
static boolean isEmpty(String s) {
return ((null == s) || (0 == s.trim().length()));
}
GuardedCommand() {
command = new Commandline();
}
void addFlag(String flag, boolean doAdd) {
if (doAdd && !isEmpty(flag)) {
command.createArgument().setValue(flag);
//size += 1 + flag.length();
}
}
/** @return null if added or ignoreString otherwise */
String addOption(String prefix, String[] validOptions, String input) {
if (isEmpty(input)) {
return null;
}
for (int i = 0; i < validOptions.length; i++) {
if (input.equals(validOptions[i])) {
if (isEmpty(prefix)) {
addFlag(input, true);
} else {
addFlagged(prefix, input);
}
return null;
}
}
return (null == prefix ? input : prefix + " " + input);
}
void addFlagged(String flag, String argument) {
if (!isEmpty(flag) && !isEmpty(argument)) {
command.addArguments(new String[] {flag, argument});
//size += 1 + flag.length() + argument.length();
}
}
// private void addFile(File file) {
// if (null != file) {
// String path = file.getAbsolutePath();
// addFlag(path, true);
// }
// }
List extractArguments() {
ArrayList result = new ArrayList();
String[] cmds = command.getArguments();
if (!LangUtil.isEmpty(cmds)) {
result.addAll(Arrays.asList(cmds));
}
return result;
}
/**
* Adjust args for size if necessary by creating
* an argument file, which should be deleted by the client
* after the compiler run has completed.
* @param max the int maximum length of the command line (in char)
* @return the temp File for the arguments (if generated),
* for deletion when done.
* @throws IllegalArgumentException if max is negative
*/
static String[] limitTo(String[] args, int max,
Location location) {
if (max < 0) {
throw new IllegalArgumentException("negative max: " + max);
}
// sigh - have to count anyway for now
int size = 0;
for (int i = 0; (i < args.length) && (size < max); i++) {
size += 1 + (null == args[i] ? 0 : args[i].length());
}
if (size <= max) {
return args;
}
File tmpFile = null;
PrintWriter out = null;
// adapted from DefaultCompilerAdapter.executeExternalCompile
try {
String userDirName = System.getProperty("user.dir");
File userDir = new File(userDirName);
tmpFile = File.createTempFile("argfile", "", userDir);
out = new PrintWriter(new FileWriter(tmpFile));
for (int i = 0; i < args.length; i++) {
out.println(args[i]);
}
out.flush();
return new String[] {"-argfile", tmpFile.getAbsolutePath()};
} catch (IOException e) {
throw new BuildException("Error creating temporary file",
e, location);
} finally {
if (out != null) {
try {out.close();} catch (Throwable t) {}
}
}
}
}
}
|
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07:46:40Z
|
testing/src/org/aspectj/testing/harness/bridge/CompilerRun.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC),
* 2003 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the 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
* Wes Isberg 2003 updates
* ******************************************************************/
package org.aspectj.testing.harness.bridge;
import java.io.*;
import java.util.*;
import org.aspectj.bridge.*;
import org.aspectj.testing.ajde.CompileCommand;
import org.aspectj.testing.run.*;
import org.aspectj.testing.taskdefs.AjcTaskCompileCommand;
import org.aspectj.testing.util.options.*;
import org.aspectj.testing.util.options.Option.*;
import org.aspectj.testing.xml.*;
import org.aspectj.util.*;
/**
* Run the compiler once.
* The lifecycle is as follows:
* <ul>
* <li>Spec (specification) is created.</li>
* <li>This is created using the Spec.</li>
* <li>setupAjcRun(Sandbox, Validator) is invoked,
* at which point this populates the shared sandbox
* with values derived from the spec and also
* sets up internal state based on both the sandbox
* and the spec.</li>
* <li>run(IRunStatus) is invoked, and this runs the compiler
* based on internal state, the spec, and the sandbox.</li>
* </ul>
* Programmer notes:
* <ul>
* <li>Paths are resolved absolutely, which fails to test the
* compiler's ability to find files relative to a source base</li>
* <li>This does not enforce the lifecycle.</li>
* <li>This must be used as the initial compile
* before doing an incremental compile.
* In that case, staging must be enabled.</li>
* </ul>
*/
public class CompilerRun implements IAjcRun {
// static final String JAVAC_COMPILER
// = JavacCompileCommand.class.getName();
static final String[] RA_String = new String[0];
static final String[] JAR_SUFFIXES = new String[] { ".jar", ".zip" };
static final String[] SOURCE_SUFFIXES =
(String[]) FileUtil.SOURCE_SUFFIXES.toArray(new String[0]);
/** specifications, set on construction */
Spec spec;
//------------ calculated during setup
/** get shared stuff during setup */
Sandbox sandbox;
/**
* During run, these String are passed as the source and arg files to compile.
* The list is set up in setupAjcRun(..), when arg files are prefixed with "@".
*/
final List /*String*/
arguments;
/**
* During run, these String are collapsed and passed as the injar option.
* The list is set up in setupAjcRun(..).
*/
final List /*String*/
injars;
/**
* During run, these String are collapsed and passed as the inpath option.
* The list is set up in setupAjcRun(..),
* which extracts only directories from the files attribute.
*/
final List inpaths;
private CompilerRun(Spec spec) {
if (null == spec) {
throw new IllegalArgumentException("null spec");
}
this.spec = spec;
arguments = new ArrayList();
injars = new ArrayList();
inpaths = new ArrayList();
}
/**
* This checks that the spec is reasonable and does setup:
* <ul>
* <li>calculate and set sandbox testBaseSrcDir as {Sandbox.testBaseDir}/
* {Spec.testSrcDirOffset}/<li>
* <li>get the list of source File to compile as {Sandbox.testBaseSrcDir} /
* {Spec.getPaths..}</li>
* <li>get the list of extraClasspath entries to add to default classpath as
* {Sandbox.testBaseSrcDir} / {Spec.classpath..}</li>
* <li>get the list of aspectpath entries to use as the aspectpath as
* {Sandbox. testBaseSrcDir} / {Spec.aspectpath..}</li>
* </ul>
* All sources must be readable at this time,
* unless spec.badInput is true (for invalid-input tests).
* If staging, the source files and source roots are copied
* to a separate staging directory so they can be modified
* for incremental tests. Note that (as of this writing) the
* compiler only handles source roots for incremental tests.
* @param classesDir the File
* @see org.aspectj.testing.harness.bridge.AjcTest.IAjcRun#setup(File, File)
* @throws AbortException containing IOException or IllegalArgumentException
* if the staging operations fail
*/
public boolean setupAjcRun(Sandbox sandbox, Validator validator) {
if (!validator.nullcheck(spec.getOptionsArray(), "localOptions")
|| !validator.nullcheck(sandbox, "sandbox")
|| !validator.nullcheck(spec.compiler, "compilerName")
|| !validator.canRead(Globals.F_aspectjrt_jar, "aspectjrt.jar")
|| !validator.canRead(
Globals.F_testingclient_jar,
"testing-client.jar")) {
return false;
}
this.sandbox = sandbox;
String rdir = spec.testSrcDirOffset;
File testBaseSrcDir;
if ((null == rdir) || (0 == rdir.length())) {
testBaseSrcDir = sandbox.testBaseDir;
} else {
testBaseSrcDir = new File(sandbox.testBaseDir, rdir);
// XXX what if rdir is two levels deep?
if (!validator
.canReadDir(testBaseSrcDir, "sandbox.testBaseSrcDir")) {
return false;
}
}
sandbox.setTestBaseSrcDir(testBaseSrcDir, this);
// Sources come as relative paths - check read, copy if staging.
// This renders paths absolute before run(RunStatusI) is called.
// For a compile run to support relative paths + source base,
// change so the run calculates the paths (differently when staging)
final String[] inpathPaths;
final String[] injarPaths;
final String[] srcPaths;
{
final String[] paths = spec.getPathsArray();
srcPaths =
LangUtil.endsWith(
paths,
CompilerRun.SOURCE_SUFFIXES,
true);
injarPaths =
LangUtil.endsWith(paths, CompilerRun.JAR_SUFFIXES, true);
inpathPaths =
LangUtil.selectDirectories(paths, testBaseSrcDir);
if (!spec.badInput) {
int found = inpathPaths.length + injarPaths.length + srcPaths.length;
if (paths.length != found) {
validator.fail("found " + found + " of " + paths.length + " sources");
}
}
}
// validate readable for sources
if (!spec.badInput) {
if (!validator.canRead(testBaseSrcDir, srcPaths, "sources")
|| !validator.canRead(testBaseSrcDir, injarPaths, "injars")
|| !validator.canRead(testBaseSrcDir, inpathPaths, "inpaths")
|| !validator.canRead(
testBaseSrcDir,
spec.argfiles,
"argfiles")
|| !validator.canRead(
testBaseSrcDir,
spec.classpath,
"classpath")
|| !validator.canRead(
testBaseSrcDir,
spec.aspectpath,
"aspectpath")
|| !validator.canRead(
testBaseSrcDir,
spec.sourceroots,
"sourceroots")
|| !validator.canRead(
testBaseSrcDir,
spec.extdirs,
"extdirs")) {
return false;
}
}
int numSources =
srcPaths.length
+ injarPaths.length
+ inpathPaths.length
+ spec.argfiles.length
+ spec.sourceroots.length;
if (!spec.badInput && (numSources < 1)) {
validator.fail(
"no input jars, arg files, or source files or roots");
return false;
}
final File[] argFiles =
FileUtil.getBaseDirFiles(testBaseSrcDir, spec.argfiles);
final File[] injarFiles =
FileUtil.getBaseDirFiles(testBaseSrcDir, injarPaths);
final File[] inpathFiles =
FileUtil.getBaseDirFiles(testBaseSrcDir, inpathPaths);
final File[] aspectFiles =
FileUtil.getBaseDirFiles(testBaseSrcDir, spec.aspectpath);
final File[] extdirFiles =
FileUtil.getBaseDirFiles(testBaseSrcDir, spec.extdirs);
final File[] classFiles =
FileUtil.getBaseDirFiles(testBaseSrcDir, spec.classpath);
// hmm - duplicates validation above, verifying getBaseDirFiles?
if (!spec.badInput) {
if (!validator.canRead(argFiles, "argFiles")
|| !validator.canRead(injarFiles, "injarFiles")
|| !validator.canRead(inpathFiles, "inpathFiles")
|| !validator.canRead(aspectFiles, "aspectFiles")
|| !validator.canRead(classFiles, "classFiles")) {
return false;
}
}
final File[] srcFiles;
File[] sourcerootFiles = new File[0];
// source text files are copied when staging incremental tests
if (!spec.isStaging()) {
// XXX why this? was always? || (testBaseSrcDir != sandbox.stagingDir))) {
srcFiles =
FileUtil.getBaseDirFiles(
testBaseSrcDir,
srcPaths,
CompilerRun.SOURCE_SUFFIXES);
if (!LangUtil.isEmpty(spec.sourceroots)) {
sourcerootFiles =
FileUtil.getBaseDirFiles(
testBaseSrcDir,
spec.sourceroots,
null);
}
} else { // staging - copy files
if (spec.badInput) {
validator.info(
"badInput ignored - files checked when staging");
}
try {
// copy all files, then remove tagged ones
// XXX make copyFiles support a filter?
srcFiles =
FileUtil.copyFiles(
testBaseSrcDir,
srcPaths,
sandbox.stagingDir);
if (!LangUtil.isEmpty(spec.sourceroots)) {
sourcerootFiles =
FileUtil.copyFiles(
testBaseSrcDir,
spec.sourceroots,
sandbox.stagingDir);
// delete incremental files in sourceroot after copying // XXX inefficient
FileFilter pickIncFiles = new FileFilter() {
// an incremental file has an extra "." in name
// most .java files don't, because they are named after
// the principle type they contain, and simple type names
// have no dots.
public boolean accept(File file) {
if (file.isDirectory()) {
// continue recursion
return true;
}
String path = file.getPath();
// only source files are relevant to staging
if (!FileUtil.hasSourceSuffix(path)) {
return false;
}
int first = path.indexOf(".");
int last = path.lastIndexOf(".");
return (first != last);
}
};
for (int i = 0; i < sourcerootFiles.length; i++) {
FileUtil.deleteContents(
sourcerootFiles[i],
pickIncFiles,
false);
}
if (0 < sourcerootFiles.length) {
FileUtil.sleepPastFinalModifiedTime(
sourcerootFiles);
}
}
File[] files =
FileUtil.getBaseDirFiles(sandbox.stagingDir, srcPaths);
if (0 < files.length) {
FileUtil.sleepPastFinalModifiedTime(files);
}
} catch (IllegalArgumentException e) {
validator.fail("staging - bad input", e);
return false;
} catch (IOException e) {
validator.fail("staging - operations", e);
return false;
}
}
if (!spec.badInput
&& !validator.canRead(srcFiles, "copied paths")) {
return false;
}
arguments.clear();
if (!LangUtil.isEmpty(extdirFiles)) {
arguments.add("-extdirs");
String sr = FileUtil.flatten(extdirFiles, null);
arguments.add(sr);
}
if (!LangUtil.isEmpty(sourcerootFiles)) {
arguments.add("-sourceroots");
String sr = FileUtil.flatten(sourcerootFiles, null);
arguments.add(sr);
}
if (!LangUtil.isEmpty(srcFiles)) {
arguments.addAll(Arrays.asList(FileUtil.getPaths(srcFiles)));
}
injars.clear();
if (!LangUtil.isEmpty(injarFiles)) {
injars.addAll(Arrays.asList(FileUtil.getPaths(injarFiles)));
}
inpaths.clear();
if (!LangUtil.isEmpty(inpathFiles)) {
inpaths.addAll(Arrays.asList(FileUtil.getPaths(inpathFiles)));
}
if (!LangUtil.isEmpty(argFiles)) {
String[] ra = FileUtil.getPaths(argFiles);
for (int j = 0; j < ra.length; j++) {
arguments.add("@" + ra[j]);
}
if (!spec.badInput && spec.isStaging) {
validator.fail(
"warning: files listed in argfiles not staged");
}
}
// save classpath and aspectpath in sandbox for this and other clients
final boolean checkReadable = !spec.badInput;
int size = spec.includeClassesDir ? 3 : 2;
File[] cp = new File[size + classFiles.length];
System.arraycopy(classFiles, 0, cp, 0, classFiles.length);
int index = classFiles.length;
if (spec.includeClassesDir) {
cp[index++] = sandbox.classesDir;
}
cp[index++] = Globals.F_aspectjrt_jar;
cp[index++] = Globals.F_testingclient_jar;
sandbox.setClasspath(cp, checkReadable, this);
// set aspectpath
if (0 < aspectFiles.length) {
sandbox.setAspectpath(aspectFiles, checkReadable, this);
}
// set bootclasspath if set for forking
AbstractRunSpec.Fork fork = spec.getFork();
String bootclasspath = fork.getJavaBootclasspath();
if (fork.fork() && (!LangUtil.isEmpty(bootclasspath))) {
sandbox.setBootclasspath(bootclasspath, this);
}
return true;
}
/**
* Setup result evaluation and command line, run, and evaluate result.
* <li>setup an AjcMessageHandler using the expected messages from
* {@link Spec#getMessages()}.<li>
* <li>heed any globals interpreted into a TestSetup by reading
* {@link Spec@getOptions()}. For a list of supported globals, see
* {@link setupArgs(ArrayList, IMessageHandler}.</li>
* <li>construct a command line, using as classpath
* {@link Sandbox.classpathToString()}<li>
* <li>construct a compiler using {@link Spec#compiler}
* or any overriding value set in TestSetup.<li>
* <li>Just before running, set the compiler in the sandbox using
* {@link Sandbox.setCompiler(ICommand)}.<li>
* <li>After running, report AjcMessageHandler results to the status parameter.
* If the AjcMessageHandler reports a failure, then send info messages
* for the Spec, TestSetup, and command line.<li>
* @see org.aspectj.testing.run.IRun#run(IRunStatus)
*/
public boolean run(IRunStatus status) {
if (null == spec.testSetup) {
MessageUtil.abort(
status,
"no test setup - adoptParentValues not called");
return false;
} else if (!spec.testSetup.result) {
MessageUtil.abort(status, spec.testSetup.failureReason);
return false;
}
// boolean ignoreWarnings =
// (spec.testSetup.ignoreWarningsSet
// && spec.testSetup.ignoreWarnings);
AjcMessageHandler handler =
new AjcMessageHandler(spec.getMessages());
handler.init();
boolean handlerResult = false;
boolean result = false;
boolean commandResult = false;
ArrayList argList = new ArrayList();
final Spec.TestSetup setupResult = spec.testSetup;
try {
argList.add("-d");
String outputDirPath = sandbox.classesDir.getAbsolutePath();
try { // worth it to try for canonical?
outputDirPath = sandbox.classesDir.getCanonicalPath();
} catch (IOException e) {
MessageUtil.abort(
status,
"canonical " + sandbox.classesDir,
e);
}
argList.add(outputDirPath);
String path = sandbox.classpathToString(this);
if (!LangUtil.isEmpty(path)) {
argList.add("-classpath");
argList.add(path);
}
path = sandbox.getBootclasspath(this);
if (!LangUtil.isEmpty(path)) {
argList.add("-bootclasspath");
argList.add(path);
}
path = sandbox.aspectpathToString(this);
if (!LangUtil.isEmpty(path)) {
argList.add("-aspectpath");
argList.add(path);
}
if (0 < injars.size()) {
argList.add("-injars");
argList.add(
FileUtil.flatten(
(String[]) injars.toArray(new String[0]),
null));
}
if (0 < inpaths.size()) {
argList.add("-inpath");
argList.add(
FileUtil.flatten(
(String[]) inpaths.toArray(new String[0]),
null));
}
// put specified arguments last, for better badInput tests
argList.addAll(setupResult.commandOptions);
// add both java/aspectj and argfiles
argList.addAll(arguments);
// XXX hack - seek on request as a side effect. reimplement as listener
if (null != setupResult.seek) {
String slopPrefix = Spec.SEEK_MESSAGE_PREFIX + " slop - ";
PrintStream slop =
MessageUtil.handlerPrintStream(
status,
IMessage.INFO,
System.err,
slopPrefix);
List found =
FileUtil.lineSeek(
setupResult.seek,
arguments,
false,
slop);
if (!LangUtil.isEmpty(found)) {
for (Iterator iter = found.iterator();
iter.hasNext();
) {
MessageUtil.info(
status,
Spec.SEEK_MESSAGE_PREFIX + iter.next());
}
}
}
ICommand compiler = spec.reuseCompiler
// throws IllegalStateException if null
? sandbox.getCommand(this)
: ReflectionFactory.makeCommand(setupResult.compilerName, status);
DirChanges dirChanges = null;
if (null == compiler) {
MessageUtil.fail(
status,
"unable to make compiler " + setupResult.compilerName);
return false;
} else {
if (setupResult.compilerName != Spec.DEFAULT_COMPILER) {
MessageUtil.info(
status,
"compiler: " + setupResult.compilerName);
}
if (status.aborted()) {
MessageUtil.debug(
status,
"aborted, but compiler valid?: " + compiler);
} else {
// same DirChanges handling for JavaRun, CompilerRun, IncCompilerRun
// XXX around advice or template method/class
if (!LangUtil.isEmpty(spec.dirChanges)) {
LangUtil.throwIaxIfFalse(
1 == spec.dirChanges.size(),
"expecting 0..1 dirChanges");
dirChanges =
new DirChanges(
(DirChanges.Spec) spec.dirChanges.get(0));
if (!dirChanges
.start(status, sandbox.classesDir)) {
return false; // setup failed
}
}
MessageUtil.info(
status,
compiler + "(" + argList + ")");
sandbox.setCommand(compiler, this);
String[] args = (String[]) argList.toArray(RA_String);
commandResult = compiler.runCommand(args, handler);
}
}
handlerResult = handler.passed();
if (!handlerResult) {
return false;
} else {
result = (commandResult == handler.expectingCommandTrue());
if (!result) {
String m =
commandResult
? "compile did not fail as expected"
: "compile failed unexpectedly";
MessageUtil.fail(status, m);
} else if (null != dirChanges) {
result = dirChanges.end(status, sandbox.testBaseDir);
}
}
return result;
} finally {
if (!handlerResult) { // more debugging context in case of failure
MessageUtil.info(handler, spec.toLongString());
MessageUtil.info(handler, "" + argList);
if (null != setupResult) {
MessageUtil.info(handler, "" + setupResult);
}
}
handler.report(status);
// XXX weak - actual messages not reported in real-time, no fast-fail
}
}
public String toString() {
return "CompilerRun(" + spec + ")";
}
/**
* Initializer/factory for CompilerRun
* any path or file is relative to this test base dir
*/
public static class Spec extends AbstractRunSpec {
public static final String XMLNAME = "compile";
public static final String DEFAULT_COMPILER =
ReflectionFactory.ECLIPSE;
static final String SEEK_PREFIX = "-seek:";
static final String SEEK_MESSAGE_PREFIX = "found: ";
private static final CRSOptions CRSOPTIONS = new CRSOptions();
/**
* Retitle description to title, paths to files, do comment,
* staging, badInput,
* do dirChanges, and print no chidren.
*/
private static final AbstractRunSpec.XMLNames NAMES =
new AbstractRunSpec.XMLNames(
AbstractRunSpec.XMLNames.DEFAULT,
"title",
null,
null,
null,
"files",
null,
null,
null,
false,
false,
true);
/**
* If the source version warrants, add a -bootclasspath
* entry to the list of arguments to add.
* This will fail and return an error String if the
* required library is not found.
* @param sourceVersion the String (if any) describing the -source option
* (expecting one of [null, "1.3", "1.4", "1.5"].
* @param compilerName the String name of the target compiler
* @param toAdd the ArrayList to add -bootclasspath to
* @return the String describing any errors, or null if no errors
*/
private static String updateBootclasspathForSourceVersion(
String sourceVersion,
String compilerName,
ArrayList toAdd) {
if (null == sourceVersion) {
return null;
}
if (3 != sourceVersion.length()) {
throw new IllegalArgumentException(
"bad version: " + sourceVersion);
}
if (null == toAdd) {
throw new IllegalArgumentException("null toAdd");
}
int version = sourceVersion.charAt(2) - '0';
switch (version) {
case (3) :
if (LangUtil.supportsJava("1.4")) {
if (!FileUtil.canReadFile(Globals.J2SE13_RTJAR)) {
return "no 1.3 libraries to handle -source 1.3";
}
toAdd.add("-bootclasspath");
toAdd.add(Globals.J2SE13_RTJAR.getAbsolutePath());
}
break;
case (4) :
if (!LangUtil.supportsJava("1.4")) {
if (ReflectionFactory
.ECLIPSE
.equals(compilerName)) {
return "run eclipse under 1.4 to handle -source 1.4";
}
if (!FileUtil.canReadFile(Globals.J2SE14_RTJAR)) {
return "no 1.4 libraries to handle -source 1.4";
}
toAdd.add("-bootclasspath");
toAdd.add(Globals.J2SE14_RTJAR.getAbsolutePath());
}
break;
case (5) :
return "1.5 not supported in CompilerRun";
case (0) :
// ignore - no version specified
break;
default :
throw new Error("unexpected version: " + version);
}
return null;
}
static CRSOptions testAccessToCRSOptions() {
return CRSOPTIONS;
}
static Options testAccessToOptions() {
return CRSOPTIONS.getOptions();
}
private static String[] copy(String[] input) {
if (null == input) {
return null;
}
String[] result = new String[input.length];
System.arraycopy(input, 0, result, 0, input.length);
return result;
}
/** @return true if javac is available on the classpath */
// private static boolean haveJavac() { // XXX copy/paste from JavaCWrapper.java
// Class compilerClass = null;
// try {
// compilerClass = Class.forName("com.sun.tools.javac.Main");
// } catch (ClassNotFoundException ce1) {
// try {
// compilerClass = Class.forName("sun.tools.javac.Main");
// } catch (ClassNotFoundException ce2) {
// }
// }
// return (null != compilerClass);
// }
protected String compiler;
// use same command - see also IncCompiler.Spec.fresh
protected boolean reuseCompiler;
protected boolean permitAnyCompiler;
protected boolean includeClassesDir;
protected TestSetup testSetup;
protected String[] argfiles = new String[0];
protected String[] aspectpath = new String[0];
protected String[] classpath = new String[0];
protected String[] sourceroots = new String[0];
protected String[] extdirs = new String[0];
/** src path = {suiteParentDir}/{testBaseDirOffset}/{testSrcDirOffset}/{path} */
protected String testSrcDirOffset;
public Spec() {
super(XMLNAME);
setXMLNames(NAMES);
compiler = DEFAULT_COMPILER;
}
protected void initClone(Spec spec)
throws CloneNotSupportedException {
super.initClone(spec);
spec.argfiles = copy(argfiles);
spec.aspectpath = copy(aspectpath);
spec.classpath = copy(classpath);
spec.compiler = compiler;
spec.includeClassesDir = includeClassesDir;
spec.reuseCompiler = reuseCompiler;
spec.permitAnyCompiler = permitAnyCompiler;
spec.sourceroots = copy(sourceroots);
spec.extdirs = copy(extdirs);
spec.testSetup = null;
if (null != testSetup) {
spec.testSetup = (TestSetup) testSetup.clone();
}
spec.testSrcDirOffset = testSrcDirOffset;
}
public Object clone() throws CloneNotSupportedException {
Spec result = new Spec();
initClone(result);
return result;
}
public void setIncludeClassesDir(boolean include) {
this.includeClassesDir = include;
}
public void setReuseCompiler(boolean reuse) {
this.reuseCompiler = reuse;
}
public void setPermitAnyCompiler(boolean permitAny) {
this.permitAnyCompiler = permitAny;
}
public void setCompiler(String compilerName) {
this.compiler = compilerName;
}
public void setTestSrcDirOffset(String s) {
if (null != s) {
testSrcDirOffset = s;
}
}
/** override to set dirToken to Sandbox.CLASSES and default suffix to ".class" */
public void addDirChanges(DirChanges.Spec spec) {
if (null == spec) {
return;
}
spec.setDirToken(Sandbox.CLASSES_DIR);
spec.setDefaultSuffix(".class");
super.addDirChanges(spec);
}
public String toLongString() {
return getPrintName() + "(" + super.containedSummary() + ")";
}
public String toString() {
return getPrintName() + "(" + super.containedSummary() + ")";
}
/** bean mapping for writers */
public void setFiles(String paths) {
addPaths(paths);
}
/**
* Add to default classpath
* (which includes aspectjrt.jar and testing-client.jar).
* @param files comma-delimited list of classpath entries - ignored if
* null or empty
*/
public void setClasspath(String files) {
if (!LangUtil.isEmpty(files)) {
classpath = XMLWriter.unflattenList(files);
}
}
/**
* Set source roots, deleting any old ones
* @param files comma-delimited list of directories
* - ignored if null or empty
*/
public void setSourceroots(String dirs) {
if (!LangUtil.isEmpty(dirs)) {
sourceroots = XMLWriter.unflattenList(dirs);
}
}
/**
* Set extension dirs, deleting any old ones
* @param files comma-delimited list of directories
* - ignored if null or empty
*/
public void setExtdirs(String dirs) {
if (!LangUtil.isEmpty(dirs)) {
extdirs = XMLWriter.unflattenList(dirs);
}
}
/**
* Set aspectpath, deleting any old ones
* @param files comma-delimited list of aspect jars - ignored if null or
* empty
*/
public void setAspectpath(String files) {
if (!LangUtil.isEmpty(files)) {
aspectpath = XMLWriter.unflattenList(files);
}
}
/**
* Set argfiles, deleting any old ones
* @param files comma-delimited list of argfiles - ignored if null or empty
*/
public void setArgfiles(String files) {
if (!LangUtil.isEmpty(files)) {
argfiles = XMLWriter.unflattenList(files);
}
}
/** @return String[] copy of argfiles array */
public String[] getArgfilesArray() {
String[] argfiles = this.argfiles;
if (LangUtil.isEmpty(argfiles)) {
return new String[0];
}
return (String[]) LangUtil.copy(argfiles);
}
/**
* This implementation skips if:
* <ul>
* <li>incremental test, but using ajc (not eclipse)</li>
* <li>usejavac, but javac is not available on the classpath</li>
* <li>eclipse, but -usejavac or -preprocess test</li>
* <li>-source 1.4, but running under 1.2 (XXX design)</li>
* <li>local/global option conflicts (-lenient/-strict)</li>
* <li>semantic conflicts (e.g., -lenient/-strict)</li>
* </ul>
* @return false if this wants to be skipped, true otherwise
*/
protected boolean doAdoptParentValues(
RT parentRuntime,
IMessageHandler handler) {
if (!super.doAdoptParentValues(parentRuntime, handler)) {
return false;
}
testSetup = setupArgs(handler);
if (!testSetup.result) {
skipMessage(handler, testSetup.failureReason);
}
return testSetup.result;
}
private String getShortCompilerName() {
String compilerClassName = compiler;
if (null != testSetup) {
compilerClassName = testSetup.compilerName;
}
if (null != compilerClassName) {
int loc = compilerClassName.lastIndexOf(".");
if (-1 != loc) {
compilerClassName =
compilerClassName.substring(loc + 1);
}
}
return compilerClassName;
}
/** @return a CompilerRun with this as spec if setup completes successfully. */
public IRunIterator makeRunIterator(
Sandbox sandbox,
Validator validator) {
CompilerRun run = new CompilerRun(this);
if (run.setupAjcRun(sandbox, validator)) {
// XXX need name for compilerRun
return new WrappedRunIterator(this, run);
}
return null;
}
protected String getPrintName() {
return "CompilerRun.Spec " + getShortCompilerName();
}
/**
* Each non-incremental run, fold the global flags in with
* the run flags, which may involve adding or removing from
* either list, depending on the flag prefix:
* <ul>
* <li>-foo: use -foo unless forced off.<li>
* <li>^foo: (force off) remove any -foo option from the run flags</li>
* <li>!foo: (force on) require the -foo flag </li>
* </ul>
* If there is a force conflict, then the test is skipped
* ("skipping" info message, TestSetup.result is false).
* This means an option local to the test which was specified
* without forcing may be overridden by a globally-forced option.
* <p>
* There are some flags which are interpreted by the test
* and removed from the list of flags passed to the command
* (see testFlag()):
* <ul>
* <li>eclipse: use the new eclipse compiler (can force)</li>
* <li>ajc: use the old ajc compiler (can force)</li>
* <li>ignoreWarnings: ignore warnings in result evaluations (no force)</li>
* </ul>
* <p>
* There are some flags which are inconsistent with each other.
* These are treated as conflicts and the test is skipped:
* <ul>
* <li>lenient, strict</li>
* </ul>
* <p>
* <p>
* This also interprets any relevant System properties,
* e.g., from <code>JavaRun.BOOTCLASSPATH_KEY</code>.
* <p>
* Finally, compiler limitations are enforced here by skipping
* tests which the compiler cannot do:
* <ul>
* <li>eclipse does not do -lenient, -strict, -usejavac, -preprocess,
* -XOcodeSize, -XSerializable, XaddSafePrefix,
* -XserializableAspects,-XtargetNearSource</li>
* <li>ajc does not run in incremental (staging) mode,
* nor with -usejavac if javac is not on the classpath</li>
* </ul>
* <u>Errors</u>:This will remove an arg not prefixed by [-|!|^] after
* providing an info message.
* <u>TestSetup Result</u>:
* If this completes successfully, then TestSetup.result is true,
* and commandOptions is not null, and any test flags (ignore warning,
* compiler) are reflected in the TestSetup.
* If this fails, then TestSetup.result is false,
* and a TestSetup.failreason is set.
* This means the test is skipped.
* @return TestSetup with results
* (TestSetup result=false if the run should not continue)
*/
protected TestSetup setupArgs(IMessageHandler handler) {
// warning: HarnessSelectionTest checks for specific error wording
final Spec spec = this;
final TestSetup result = new TestSetup();
result.compilerName = spec.compiler;
// urk - s.b. null, but expected
Values values = gatherValues(result);
if ((null == values) || (null != result.failureReason)) {
return checkResult(result);
}
// send info messages about
// forced staging when -incremental
// or staging but no -incremental flag
Option.Family getFamily =
CRSOPTIONS.crsIncrementalOption.getFamily();
final boolean haveIncrementalFlag =
(null != values.firstInFamily(getFamily));
if (spec.isStaging()) {
if (!haveIncrementalFlag) {
MessageUtil.info(
handler,
"staging but no -incremental flag");
}
} else if (haveIncrementalFlag) {
spec.setStaging(true);
MessageUtil.info(handler, "-incremental forcing staging");
}
if (hasInvalidOptions(values, result)) {
return checkResult(result);
}
// set compiler in result
getFamily = CRSOPTIONS.ajccompilerOption.getFamily();
Option.Value compiler = values.firstInFamily(getFamily);
if (null != compiler) {
result.compilerName
= CRSOPTIONS.compilerClassName(compiler.option);
if (null == result.compilerName) {
result.failureReason =
"unable to get class name for " + compiler;
return checkResult(result);
}
}
String compilerName =
(null == result.compilerName
? spec.compiler
: result.compilerName);
// check compiler semantics
if (hasCompilerSpecErrors(compilerName, values, result)) {
return checkResult(result);
}
// add toadd and finish result
ArrayList args = new ArrayList();
String[] rendered = values.render();
if (!LangUtil.isEmpty(rendered)) {
args.addAll(Arrays.asList(rendered));
}
// update bootclasspath
getFamily = CRSOPTIONS.crsSourceOption.getFamily();
Option.Value source = values.firstInFamily(getFamily);
if (null != source) {
String sourceVersion = source.unflatten()[1];
ArrayList toAdd = new ArrayList();
/*String err =*/
updateBootclasspathForSourceVersion(
sourceVersion,
spec.compiler,
toAdd);
args.addAll(toAdd);
}
result.commandOptions = args;
result.result = true;
return checkResult(result);
}
/**
* Ensure exit invariant:
* <code>result.result == (null == result.failureReason)
* == (null != result.commandOptions)</code>
* @param result the TestSetup to verify
* @return result
* @throws Error if invariant is not true
*/
TestSetup checkResult(TestSetup result) {
String err = null;
if (null == result) {
err = "null result";
} else if (result.result != (null == result.failureReason)) {
err =
result.result
? "expected no failure: " + result.failureReason
: "fail for no reason";
} else if (result.result != (null != result.commandOptions)) {
err =
result.result
? "expected command options"
: "unexpected command options";
}
if (null != err) {
throw new Error(err);
}
return result;
}
boolean hasInvalidOptions(Values values, TestSetup result) {
// not supporting 1.0 options any more
for (Iterator iter = CRSOPTIONS.invalidOptions.iterator();
iter.hasNext();
) {
Option option = (Option) iter.next();
if (null != values.firstOption(option)) {
result.failureReason =
"invalid option in harness: " + option;
return true;
}
}
return false;
}
boolean hasCompilerSpecErrors(
String compilerName,
Values values,
TestSetup result) {
/*
* Describe any semantic conflicts between options.
* This skips:
* - old 1.0 options, including lenient v. strict
* - old ajc options, include !incremental and usejavac w/o javac
* - invalid eclipse options (mostly ajc)
* @param compilerName the String name of the target compiler
* @return a String describing any conflicts, or null if none
*/
if (!permitAnyCompiler
&& (!(ReflectionFactory.ECLIPSE.equals(compilerName)
|| ReflectionFactory.OLD_AJC.equals(compilerName)
|| CRSOptions.AJDE_COMPILER.equals(compilerName)
|| CRSOptions.AJCTASK_COMPILER.equals(compilerName)
|| permitAnyCompiler
))) {
//|| BUILDER_COMPILER.equals(compilerName))
result.failureReason =
"unrecognized compiler: " + compilerName;
return true;
}
// not supporting ajc right now
if (null
!= values.firstOption(CRSOPTIONS.ajccompilerOption)) {
result.failureReason = "ajc not supported";
return true;
}
// not supporting 1.0 options any more
for (Iterator iter = CRSOPTIONS.ajc10Options.iterator();
iter.hasNext();
) {
Option option = (Option) iter.next();
if (null != values.firstOption(option)) {
result.failureReason = "old ajc 1.0 option: " + option;
return true;
}
}
return false;
}
protected Values gatherValues(TestSetup result) {
final Spec spec = this;
// ---- local option values
final Values localValues;
final Options options = CRSOPTIONS.getOptions();
try {
String[] input = getOptionsArray();
// this handles reading options,
// flattening two-String options, etc.
localValues = options.acceptInput(input);
// all local values should be picked up
String err = Options.missedMatchError(input, localValues);
if (!LangUtil.isEmpty(err)) {
result.failureReason = err;
return null;
}
} catch (InvalidInputException e) {
result.failureReason = e.getFullMessage();
return null;
}
// ---- global option values
StringBuffer errs = new StringBuffer();
final Values globalValues =
spec.runtime.extractOptions(options, true, errs);
if (errs.length() > 0) {
result.failureReason = errs.toString();
return null;
}
final Values combined =
Values.wrapValues(
new Values[] { localValues, globalValues });
String err = combined.resolve();
if (null != err) {
result.failureReason = err;
return null;
}
return handleTestArgs(combined, result);
}
// final int len = globalValues.length() + localValues.length();
// final Option.Value[] combinedValues = new Option.Value[len];
// System.arraycopy(
// globalValues,
// 0,
// combinedValues,
// 0,
// globalValues.length());
// System.arraycopy(
// localValues,
// 0,
// combinedValues,
// globalValues.length(),
// localValues.length());
//
// result.compilerName = spec.compiler;
// if (0 < combinedValues.length) {
// // this handles option forcing, etc.
// String err = Options.resolve(combinedValues);
// if (null != err) {
// result.failureReason = err;
// return null;
// }
// if (!handleTestArgs(combinedValues, result)) {
// return null;
// }
// }
// return Values.wrapValues(combinedValues);
// }
/**
* This interprets and nullifies values for the test.
* @param values the Option.Value[] being processed
* @param result the TestSetup to modify
* @return false if error (caller should return), true otherwise
*/
Values handleTestArgs(Values values, final TestSetup result) {
final Option.Family compilerFamily =
CRSOPTIONS.ajccompilerOption.getFamily();
Values.Selector selector = new Values.Selector() {
protected boolean accept(Option.Value value) {
if (null == value) {
return false;
}
Option option = value.option;
if (compilerFamily.sameFamily(option.getFamily())) {
if (value.prefix.isSet()) {
String compilerClass
= CRSOPTIONS.compilerClassName(option);
if (null == compilerClass) {
result.failureReason =
"unrecognized compiler: " + value;
throw Values.Selector.STOP;
}
if (!CRSOPTIONS.compilerIsLoadable(option)) {
result.failureReason =
"unable to load compiler: " + option;
throw Values.Selector.STOP;
}
result.compilerName = compilerClass;
}
return true;
} else if (
CRSOPTIONS.crsIgnoreWarnings.sameOptionIdentifier(
option)) {
result.ignoreWarnings = value.prefix.isSet();
result.ignoreWarningsSet = true;
return true;
}
return false;
}
};
return values.nullify(selector);
}
// /**
// * This interprets and nullifies values for the test.
// * @param values the Option.Value[] being processed
// * @param result the TestSetup to modify
// * @return false if error (caller should return), true otherwise
// */
// boolean handleTestArgs(Option.Value[] values, TestSetup result) {
// if (!LangUtil.isEmpty(values)) {
// for (int i = 0; i < values.length; i++) {
// Option.Value value = values[i];
// if (null == value) {
// continue;
// }
// Option option = value.option;
// if (option.sameOptionFamily(ECLIPSE_OPTION)) {
// if (!value.prefix.isSet()) {
// values[i] = null;
// continue;
// }
// String compilerClass =
// (String) COMPILER_OPTION_TO_CLASSNAME.get(
// option);
// if (null == compilerClass) {
// result.failureReason =
// "unrecognized compiler: " + value;
// return false;
// }
// result.compilerName = compilerClass;
// values[i] = null;
// } else if (
// option.sameOptionFamily(crsIgnoreWarnings)) {
// result.ignoreWarnings = value.prefix.isSet();
// result.ignoreWarningsSet = true;
// values[i] = null;
// }
// }
// }
// return true;
// }
// XXX need keys, cache...
/** @return index of global in argList, ignoring first char */
protected int indexOf(String global, ArrayList argList) {
int max = argList.size();
for (int i = 0; i < max; i++) {
if (global
.equals(((String) argList.get(i)).substring(1))) {
return i;
}
}
return -1;
}
/**
* Write this out as a compile element as defined in
* AjcSpecXmlReader.DOCTYPE.
* @see AjcSpecXmlReader#DOCTYPE
* @see IXmlWritable#writeXml(XMLWriter)
*/
public void writeXml(XMLWriter out) {
out.startElement(xmlElementName, false);
if (!LangUtil.isEmpty(testSrcDirOffset)) {
out.printAttribute("dir", testSrcDirOffset);
}
super.writeAttributes(out);
if (!DEFAULT_COMPILER.equals(compiler)) {
out.printAttribute("compiler", compiler);
}
if (reuseCompiler) {
out.printAttribute("reuseCompiler", "true");
}
// test-only feature
// if (permitAnyCompiler) {
// out.printAttribute("permitAnyCompiler", "true");
// }
if (includeClassesDir) {
out.printAttribute("includeClassesDir", "true");
}
if (!LangUtil.isEmpty(argfiles)) {
out.printAttribute(
"argfiles",
XMLWriter.flattenFiles(argfiles));
}
if (!LangUtil.isEmpty(aspectpath)) {
out.printAttribute(
"aspectpath",
XMLWriter.flattenFiles(aspectpath));
}
if (!LangUtil.isEmpty(sourceroots)) {
out.printAttribute(
"sourceroots",
XMLWriter.flattenFiles(sourceroots));
}
if (!LangUtil.isEmpty(extdirs)) {
out.printAttribute(
"extdirs",
XMLWriter.flattenFiles(extdirs));
}
out.endAttributes();
if (!LangUtil.isEmpty(dirChanges)) {
DirChanges.Spec.writeXml(out, dirChanges);
}
SoftMessage.writeXml(out, getMessages());
out.endElement(xmlElementName);
}
/**
* Encapsulate the directives that can be set using
* global arguments supplied in {@link Spec.getOptions()}.
* This supports changing the compiler and ignoring warnings.
*/
class TestSetup {
/** null unless overriding the compiler to be used */
String compilerName;
/**
* true if we should tell AjcMessageHandler whether
* to ignore warnings in its result evaluation
*/
boolean ignoreWarningsSet;
/** if telling AjcMessageHandler, what we tell it */
boolean ignoreWarnings;
/** false if setup failed */
boolean result;
/** if setup failed, this has the reason why */
String failureReason;
/** beyond running test, also seek text in sources */
String seek;
/** if setup completed, this has the combined global/local options */
ArrayList commandOptions;
public Object clone() {
TestSetup testSetup = new TestSetup();
testSetup.compilerName = compilerName;
testSetup.ignoreWarnings = ignoreWarnings;
testSetup.ignoreWarningsSet = ignoreWarningsSet;
testSetup.result = result;
testSetup.failureReason = failureReason;
testSetup.seek = seek;
if (null != commandOptions) {
testSetup.commandOptions = new ArrayList();
testSetup.commandOptions.addAll(commandOptions);
}
return testSetup;
}
public String toString() {
return "TestSetup("
+ (null == compilerName ? "" : compilerName + " ")
+ (!ignoreWarningsSet
? ""
: (ignoreWarnings ? "" : "do not ")
+ "ignore warnings ")
+ (result ? "" : "setup failed")
+ ")";
}
}
/**
* Options-related stuff in the spec.
*/
static class CRSOptions {
// static final String BUILDER_COMPILER =
// "org.aspectj.ajdt.internal.core.builder.Builder.Command";
static final String AJDE_COMPILER =
CompileCommand.class.getName();
static final String AJCTASK_COMPILER =
AjcTaskCompileCommand.class.getName();
private final Map compilerOptionToLoadable = new TreeMap();
/*
* The options field in a compiler test permits some arbitrary
* command-line options to be set. It does not permit things
* like classpath, aspectpath, files, etc. which are set
* using other fields in the test specification, so the options
* permitted are a subset of those permitted on the command-line.
*
* Global options specified on the harness command-line are
* adopted for the compiler command-line if they are permitted
* in the options field. That means we have to detect each
* permitted option, rather than just letting all through
* for the compiler.
*
* Conversely, some options are targeted not at the compiler,
* but at the test itself (e.g., to ignore warnings, or to
* select a compiler.
*
* The harness can run many compilers, and they differ in
* which options are permitted. You can specify a compiler
* as an option (e.g., -eclipse). So the set of constraints
* on the list of permitted options can differ from test to test.
*
* The following code sets up the lists of permitted options
* and breaks out subsets for different compiler-variant checks.
* Most options are created but not named, but some options
* are named to detect corresponding values for further
* processing. e.g., the compiler options are saved so
* we can do per-compiler option verification.
*
*/
private final Options crsOptions;
private final Family compilerFamily;
private final Option crsIncrementalOption;
private final Option crsSourceOption;
// these are options handled/absorbed by CompilerRun
private final Option crsIgnoreWarnings;
private final Option eclipseOption;
private final Option buildercompilerOption;
private final Option ajdecompilerOption;
private final Option javacOption;
private final Option ajctaskcompilerOption;
private final Option ajccompilerOption;
private final Map compilerOptionToClassname;
private final Set compilerOptions;
// compiler verification - permit but flag ajc 1.0 options
private final List ajc10Options;
private final List invalidOptions;
private CRSOptions() {
crsOptions = new Options(true);
Option.Factory factory = new Option.Factory("CompilerRun");
// compiler options go in map
eclipseOption =
factory.create(
"eclipse",
"compiler",
Option.FORCE_PREFIXES,
false);
compilerFamily = eclipseOption.getFamily();
buildercompilerOption =
factory.create(
"builderCompiler",
"compiler",
Option.FORCE_PREFIXES,
false);
ajctaskcompilerOption =
factory.create(
"ajctaskCompiler",
"compiler",
Option.FORCE_PREFIXES,
false);
ajdecompilerOption =
factory.create(
"ajdeCompiler",
"compiler",
Option.FORCE_PREFIXES,
false);
ajccompilerOption =
factory.create(
"ajc",
"compiler",
Option.FORCE_PREFIXES,
false);
javacOption =
factory.create(
"javac",
"compiler",
Option.FORCE_PREFIXES,
false);
Map map = new TreeMap();
map.put(eclipseOption, ReflectionFactory.ECLIPSE);
//map.put(BUILDERCOMPILER_OPTION, BUILDER_COMPILER);
map.put(
ajctaskcompilerOption,
AJCTASK_COMPILER);
map.put(ajdecompilerOption, AJDE_COMPILER);
map.put(ajccompilerOption, ReflectionFactory.OLD_AJC);
//map.put(JAVAC_OPTION, "XXX javac option not supported");
compilerOptionToClassname =
Collections.unmodifiableMap(map);
compilerOptions =
Collections.unmodifiableSet(
compilerOptionToClassname.keySet());
// options not permitted in the harness
List list = new ArrayList();
list.add(factory.create("workingdir"));
list.add(factory.create("argfile"));
list.add(factory.create("sourceroots"));
list.add(factory.create("outjar"));
invalidOptions = Collections.unmodifiableList(list);
// other options added directly
crsIncrementalOption = factory.create("incremental");
crsIgnoreWarnings = factory.create("ignoreWarnings");
crsSourceOption =
factory
.create(
"source",
"source",
Option.FORCE_PREFIXES,
false,
new String[][] { new String[] { "1.3", "1.4", "1.5" }
});
// ajc 1.0 options
// workingdir above in invalid options
list = new ArrayList();
list.add(factory.create("usejavac"));
list.add(factory.create("preprocess"));
list.add(factory.create("nocomment"));
list.add(factory.create("porting"));
list.add(factory.create("XOcodeSize"));
list.add(factory.create("XTargetNearSource"));
list.add(factory.create("XaddSafePrefix"));
list.add(
factory.create(
"lenient",
"lenient",
Option.FORCE_PREFIXES,
false));
list.add(
factory.create(
"strict",
"lenient",
Option.FORCE_PREFIXES,
false));
ajc10Options = Collections.unmodifiableList(list);
// -warn:.. and -g/-g:.. are not exclusive
if (!(factory.setupFamily("debug", true)
&& factory.setupFamily("warning", true))) {
System.err.println("CompilerRun debug/warning fail!");
}
Option[] options =
new Option[] {
crsIncrementalOption,
crsIgnoreWarnings,
crsSourceOption,
factory.create(
"Xlint",
"XLint",
Option.FORCE_PREFIXES,
true),
factory.create("verbose"),
factory.create("emacssym"),
factory.create("referenceInfo"),
factory.create("nowarn"),
factory.create("deprecation"),
factory.create("noImportError"),
factory.create("proceedOnError"),
factory.create("preserveAllLocals"),
factory.create(
"warn",
"warning",
Option.STANDARD_PREFIXES,
true),
factory.create(
"g",
"debug",
Option.STANDARD_PREFIXES,
false),
factory.create(
"g:",
"debug",
Option.STANDARD_PREFIXES,
true),
factory.create(
"1.3",
"compliance",
Option.FORCE_PREFIXES,
false),
factory.create(
"1.4",
"compliance",
Option.FORCE_PREFIXES,
false),
factory.create(
"1.5",
"compliance",
Option.FORCE_PREFIXES,
false),
factory
.create(
"target",
"target",
Option.FORCE_PREFIXES,
false,
new String[][] { new String[] {
"1.1",
"1.2",
"1.3",
"1.4",
"1.5" }}),
factory.create("XnoInline"),
factory.create("XnoWeave"),
factory.create("XserializableAspects")
};
// among options not permitted: extdirs...
for (int i = 0; i < options.length; i++) {
crsOptions.addOption(options[i]);
}
for (Iterator iter = compilerOptions.iterator();
iter.hasNext();
) {
crsOptions.addOption((Option) iter.next());
}
// these are recognized but records with them are skipped
for (Iterator iter = ajc10Options.iterator();
iter.hasNext();
) {
crsOptions.addOption((Option) iter.next());
}
crsOptions.freeze();
}
Options getOptions() {
return crsOptions;
}
/**
* @return unmodifiable Set of options sharing the
* family "compiler".
*/
Set compilerOptions() {
return compilerOptions;
}
/**
* @param option the compiler Option to get name for
* @return null if option is null or not a compiler option,
* or the fully-qualified classname of the ICommand
* implementing the compiler.
*/
String compilerClassName(Option option) {
if ((null == option)
|| (!compilerFamily.sameFamily(option.getFamily()))) {
return null;
}
return (String) compilerOptionToClassname.get(option);
}
/**
* Check that the compiler class associated with a compiler
* option can be loaded. This check only happens once;
* the result is cached (by compilerOption key) for later calls.
* @param compilerOption the Option (family compiler) to check
* @return true if compiler class for this option can be loaded
*/
boolean compilerIsLoadable(Option compilerOption) {
LangUtil.throwIaxIfNull(compilerOption, "compilerName");
synchronized (compilerOptionToLoadable) {
Boolean result =
(Boolean) compilerOptionToLoadable.get(
compilerOption);
if (null == result) {
MessageHandler sink = new MessageHandler();
String compilerClassname =
(String) compilerOptionToClassname.get(
compilerOption);
if (null == compilerClassname) {
result = Boolean.FALSE;
} else {
ICommand c =
ReflectionFactory.makeCommand(
compilerClassname,
sink);
if ((null == c)
|| sink.hasAnyMessage(
IMessage.ERROR,
true)) {
result = Boolean.FALSE;
} else {
result = Boolean.TRUE;
}
}
compilerOptionToLoadable.put(
compilerOption,
result);
}
return result.booleanValue();
}
}
} // CompilerRun.Spec.CRSOptions
} // CompilerRun.Spec
} // CompilerRun
|
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07:46: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.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) {
Advice ret = world.concreteAdvice(isBelow ? AdviceKind.CflowBelowEntry : AdviceKind.CflowEntry,
entry, stackField, 0, entry);
//0);
ret.innerCflowEntries = innerCflowEntries;
ret.nFreeVars = nFreeVars;
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) {
Advice ret = world.concreteAdvice(AdviceKind.Softener,
entry, null, 0, entry);
ret.exceptionType = exceptionType;
//System.out.println("made ret: " + ret + " with " + exceptionType);
return ret;
}
public Advice(AjAttribute.AdviceAttribute attribute, Pointcut pointcut, Member signature)
{
super(pointcut, attribute.getStart(), attribute.getEnd(), attribute.getSourceContext());
this.attribute = attribute;
this.kind = attribute.getKind(); // alias
this.signature = signature;
}
public boolean match(Shadow shadow, World world) {
if (super.match(shadow, world)) {
if (shadow.getKind() == Shadow.ExceptionHandler) {
if (kind.isAfter() || kind == AdviceKind.Around) {
world.showMessage(IMessage.WARNING,
"Only before advice is supported on handler join points (compiler limitation)",
getSourceLocation(), shadow.getSourceLocation());
return false;
}
}
if (hasExtraParameter() && kind == AdviceKind.AfterReturning) {
return getExtraParameterType().isConvertableFrom(shadow.getReturnType(), world);
} else if (kind == AdviceKind.PerTargetEntry) {
return shadow.hasTarget();
} else if (kind == AdviceKind.PerThisEntry) {
return shadow.hasThis();
} else if (kind == AdviceKind.Around) {
if (shadow.getKind() == Shadow.PreInitialization) {
world.showMessage(IMessage.ERROR,
"around on pre-initialization not supported (compiler limitation)",
getSourceLocation(), shadow.getSourceLocation());
return false;
} else if (shadow.getKind() == Shadow.Initialization) {
world.showMessage(IMessage.ERROR,
"around on initialization not supported (compiler limitation)",
getSourceLocation(), shadow.getSourceLocation());
return false;
} else if (shadow.getKind() == Shadow.StaticInitialization &&
shadow.getEnclosingType().isInterface(world))
{
world.showMessage(IMessage.ERROR,
"around on staticinitialization of interface \'" +
shadow.getEnclosingType().getName() +
"\' not supported (compiler limitation)",
getSourceLocation(), shadow.getSourceLocation());
return false;
} else {
//System.err.println(getSignature().getReturnType() + " from " + shadow.getReturnType());
if (getSignature().getReturnType() == ResolvedTypeX.VOID) {
if (shadow.getReturnType() != ResolvedTypeX.VOID) {
world.showMessage(IMessage.ERROR,
"applying to join point that doesn't return void: " + shadow,
getSourceLocation(), shadow.getSourceLocation());
return false;
}
} else if (getSignature().getReturnType().equals(TypeX.OBJECT)) {
return true;
} else if(!shadow.getReturnType().isAssignableFrom(getSignature().getReturnType(), world)) {
//System.err.println(this + ", " + sourceContext + ", " + start);
world.showMessage(IMessage.ERROR,
"incompatible return type applying to " + shadow,
getSourceLocation(), shadow.getSourceLocation());
return false;
}
}
}
return true;
} else {
return false;
}
}
// ----
public AdviceKind getKind() {
return kind;
}
public Member getSignature() {
return signature;
}
public boolean hasExtraParameter() {
return (getExtraParameterFlags() & ExtraArgument) != 0;
}
protected int getExtraParameterFlags() {
return attribute.getExtraParameterFlags();
}
protected int getExtraParameterCount() {
return countOnes(getExtraParameterFlags() & ParameterMask);
}
public static int countOnes(int bits) {
int ret = 0;
while (bits != 0) {
if ((bits & 1) != 0) ret += 1;
bits = bits >> 1;
}
return ret;
}
public int getBaseParameterCount() {
return getSignature().getParameterTypes().length - getExtraParameterCount();
}
public TypeX getExtraParameterType() {
if (!hasExtraParameter()) return ResolvedTypeX.MISSING;
return signature.getParameterTypes()[getBaseParameterCount()];
}
public TypeX getDeclaringAspect() {
return signature.getDeclaringType();
}
protected String extraParametersToString() {
if (getExtraParameterFlags() == 0) {
return "";
} else {
return "(extraFlags: " + getExtraParameterFlags() + ")";
}
}
public Pointcut getPointcut() {
return pointcut;
}
// ----
/** @param fromType is guaranteed to be a non-abstract aspect
* @param perClause has been concretized at a higher level
*/
public ShadowMunger concretize(ResolvedTypeX fromType, World world, PerClause clause) {
// assert !fromType.isAbstract();
Pointcut p = pointcut.concretize(fromType, signature.getArity(), this);
if (clause != null) {
p = new AndPointcut(clause, p);
p.state = Pointcut.CONCRETE;
}
Advice munger = world.concreteAdvice(attribute, p, signature);
munger.concreteAspect = fromType;
//System.err.println("concretizing here " + p + " with clause " + clause);
return munger;
}
// ---- from object
public String toString() {
return "("
+ getKind()
+ extraParametersToString()
+ ": "
+ pointcut
+ "->"
+ signature
+ ")";
}
public boolean equals(Object other) {
if (! (other instanceof Advice)) return false;
Advice o = (Advice) other;
return o.attribute.equals(attribute)
&& o.pointcut.equals(pointcut)
&& o.signature.equals(signature);
}
private volatile int hashCode = 0;
public int hashCode() {
if (hashCode == 0) {
int result = 17;
result = 37*result + kind.hashCode();
result = 37*result + pointcut.hashCode();
if (signature != null) result = 37*result + signature.hashCode();
hashCode = result;
}
return hashCode;
}
// ---- fields
public static final int ExtraArgument = 1;
public static final int ThisJoinPoint = 2;
public static final int ThisJoinPointStaticPart = 4;
public static final int ThisEnclosingJoinPointStaticPart = 8;
public static final int ParameterMask = 0xf;
public static final int CanInline = 0x40;
// for testing only
public void setLexicalPosition(int lexicalPosition) {
start = lexicalPosition;
}
public ResolvedTypeX getConcreteAspect() {
return concreteAspect;
}
}
|
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07:46:40Z
|
weaver/src/org/aspectj/weaver/CrosscuttingMembers.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the 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.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.aspectj.weaver.patterns.Declare;
import org.aspectj.weaver.patterns.DeclareErrorOrWarning;
import org.aspectj.weaver.patterns.DeclareParents;
import org.aspectj.weaver.patterns.DeclarePrecedence;
import org.aspectj.weaver.patterns.DeclareSoft;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
/**
* This holds on to all members that have an invasive effect outside of
* there own compilation unit. These members need to be all gathered up and in
* a world before any weaving can take place.
*
* They are also important in the compilation process and need to be gathered
* up before the inter-type declaration weaving stage (unsurprisingly).
*
* All members are concrete.
*
* @author Jim Hugunin
*/
public class CrosscuttingMembers {
private ResolvedTypeX inAspect;
private World world;
private PerClause perClause;
private List shadowMungers = new ArrayList(4);
private List typeMungers = new ArrayList(4);
private List declareParents = new ArrayList(4);
private List declareSofts = new ArrayList(0);
private List declareDominates = new ArrayList(4);
public CrosscuttingMembers(ResolvedTypeX inAspect) {
this.inAspect = inAspect;
this.world = inAspect.getWorld();
}
// public void addConcreteShadowMungers(Collection c) {
// shadowMungers.addAll(c);
// }
public void addConcreteShadowMunger(ShadowMunger m) {
// assert m is concrete
shadowMungers.add(m);
}
public void addShadowMungers(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); ) {
addShadowMunger( (ShadowMunger)i.next() );
}
}
private void addShadowMunger(ShadowMunger m) {
if (inAspect.isAbstract()) return; // we don't do mungers for abstract aspects
addConcreteShadowMunger(m.concretize(inAspect, world, perClause));
}
public void addTypeMungers(Collection c) {
typeMungers.addAll(c);
}
public void addTypeMunger(ConcreteTypeMunger m) {
if (m == null) return; //???
typeMungers.add(m);
}
public void addDeclares(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); ) {
addDeclare( (Declare)i.next() );
}
}
public void addDeclare(Declare declare) {
// this is not extensible, oh well
if (declare instanceof DeclareErrorOrWarning) {
ShadowMunger m = new Checker((DeclareErrorOrWarning)declare);
addShadowMunger(m);
} else if (declare instanceof DeclarePrecedence) {
declareDominates.add(declare);
} else if (declare instanceof DeclareParents) {
DeclareParents dp = (DeclareParents)declare;
exposeTypes(dp.getParents().getExactTypes());
declareParents.add(dp);
} else if (declare instanceof DeclareSoft) {
DeclareSoft d = (DeclareSoft)declare;
Pointcut concretePointcut = d.getPointcut().concretize(inAspect, 0);
declareSofts.add(new DeclareSoft(d.getException(), concretePointcut));
ShadowMunger m = Advice.makeSoftener(world, concretePointcut, d.getException());
addConcreteShadowMunger(m);
} else {
throw new RuntimeException("unimplemented");
}
}
public void exposeTypes(Collection typesToExpose) {
for (Iterator i = typesToExpose.iterator(); i.hasNext(); ) {
exposeType((TypeX)i.next());
}
}
public void exposeType(TypeX typeToExpose) {
if (typeToExpose == ResolvedTypeX.MISSING) return;
ResolvedMember member = new ResolvedMember(
Member.STATIC_INITIALIZATION, typeToExpose, 0, ResolvedTypeX.VOID, "", TypeX.NONE);
addTypeMunger(world.concreteTypeMunger(
new PrivilegedAccessMunger(member), inAspect));
}
public void addPrivilegedAccesses(Collection accessedMembers) {
for (Iterator i = accessedMembers.iterator(); i.hasNext(); ) {
addPrivilegedAccess( (ResolvedMember)i.next() );
}
}
private void addPrivilegedAccess(ResolvedMember member) {
//System.err.println("add priv access: " + member);
addTypeMunger(world.concreteTypeMunger(new PrivilegedAccessMunger(member), inAspect));
}
public Collection getCflowEntries() {
ArrayList ret = new ArrayList();
for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) {
ShadowMunger m = (ShadowMunger)i.next();
if (m instanceof Advice) {
Advice a = (Advice)m;
if (a.getKind().isCflow()) {
ret.add(a);
}
}
}
return ret;
}
public boolean replaceWith(CrosscuttingMembers other) {
boolean changed = false;
if (perClause == null || !perClause.equals(other.perClause)) {
changed = true;
perClause = other.perClause;
}
//XXX all of the below should be set equality rather than list equality
//System.err.println("old: " + shadowMungers + " new: " + other.shadowMungers);
if (!shadowMungers.equals(other.shadowMungers)) {
changed = true;
shadowMungers = other.shadowMungers;
}
if (!typeMungers.equals(other.typeMungers)) {
changed = true;
typeMungers = other.typeMungers;
}
if (!declareDominates.equals(other.declareDominates)) {
changed = true;
declareDominates = other.declareDominates;
}
if (!declareParents.equals(other.declareParents)) {
changed = true;
declareParents = other.declareParents;
}
if (!declareSofts.equals(other.declareSofts)) {
changed = true;
declareSofts = other.declareSofts;
}
return changed;
}
public PerClause getPerClause() {
return perClause;
}
public void setPerClause(PerClause perClause) {
this.perClause = perClause.concretize(inAspect);
}
public List getDeclareDominates() {
return declareDominates;
}
public List getDeclareParents() {
return declareParents;
}
public List getDeclareSofts() {
return declareSofts;
}
public List getShadowMungers() {
return shadowMungers;
}
public List getTypeMungers() {
return typeMungers;
}
}
|
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07:46:40Z
|
weaver/src/org/aspectj/weaver/CrosscuttingMembersSet.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.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* This holds on to all CrosscuttingMembers for a world. It handles
* management of change.
*
* @author Jim Hugunin
*/
public class CrosscuttingMembersSet {
private World world;
private Map members = new HashMap();
private List shadowMungers = null;
private List typeMungers = null;
private List declareSofts = null;
private List declareParents = null;
private List declareDominates = null;
public CrosscuttingMembersSet(World world) {
this.world = world;
}
/**
* @return whether or not that was a change to the global signature
* XXX for efficiency we will need a richer representation than this
*/
public boolean addOrReplaceAspect(ResolvedTypeX aspectType) {
CrosscuttingMembers xcut = (CrosscuttingMembers)members.get(aspectType);
if (xcut == null) {
members.put(aspectType, aspectType.collectCrosscuttingMembers());
clearCaches();
return true;
} else {
if (xcut.replaceWith(aspectType.collectCrosscuttingMembers())) {
clearCaches();
return true;
} else {
return false;
}
}
}
public void addAdviceLikeDeclares(ResolvedTypeX aspectType) {
CrosscuttingMembers xcut = (CrosscuttingMembers)members.get(aspectType);
xcut.addDeclares(aspectType.collectDeclares(true));
}
public boolean deleteAspect(TypeX aspectType) {
boolean isAspect = members.remove(aspectType) != null;
clearCaches();
return isAspect;
}
public boolean containsAspect(TypeX aspectType) {
return members.containsKey(aspectType);
}
//XXX only for testing
public void addFixedCrosscuttingMembers(ResolvedTypeX aspectType) {
members.put(aspectType, aspectType.crosscuttingMembers);
clearCaches();
}
private void clearCaches() {
shadowMungers = null;
typeMungers = null;
declareSofts = null;
declareParents = null;
declareDominates = null;
}
public List getShadowMungers() {
if (shadowMungers == null) {
ArrayList ret = new ArrayList();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getShadowMungers());
}
shadowMungers = ret;
}
return shadowMungers;
}
public List getTypeMungers() {
if (typeMungers == null) {
ArrayList ret = new ArrayList();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getTypeMungers());
}
typeMungers = ret;
}
return typeMungers;
}
public List getDeclareSofts() {
if (declareSofts == null) {
ArrayList ret = new ArrayList();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareSofts());
}
declareSofts = ret;
}
return declareSofts;
}
public List getDeclareParents() {
if (declareParents == null) {
ArrayList ret = new ArrayList();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareParents());
}
declareParents = ret;
}
return declareParents;
}
public List getDeclareDominates() {
if (declareDominates == null) {
ArrayList ret = new ArrayList();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareDominates());
}
declareDominates = ret;
}
return declareDominates;
}
}
|
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07:46:40Z
|
weaver/src/org/aspectj/weaver/Shadow.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.aspectj.asm.IRelationship;
import org.aspectj.bridge.*;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.util.PartialOrder;
import org.aspectj.util.TypeSafeEnum;
import org.aspectj.weaver.ast.Var;
/*
* The superclass of anything representing a the shadow of a join point. A shadow represents
* some bit of code, and encompasses both entry and exit from that code. All shadows have a kind
* and a signature.
*/
public abstract class Shadow {
private final Kind kind;
private final Member signature;
protected final Shadow enclosingShadow;
protected List mungers = new ArrayList(1);
// ----
protected Shadow(Kind kind, Member signature, Shadow enclosingShadow) {
this.kind = kind;
this.signature = signature;
this.enclosingShadow = enclosingShadow;
}
// ----
public abstract World getIWorld();
/**
* could this(*) pcd ever match
*/
public final boolean hasThis() {
if (getKind().neverHasThis()) {
return false;
} else if (getKind().isEnclosingKind()) {
return !getSignature().isStatic();
} else if (enclosingShadow == null) {
return false;
} else {
return enclosingShadow.hasThis();
}
}
/**
* the type of the this object here
*
* @throws IllegalStateException if there is no this here
*/
public final TypeX getThisType() {
if (!hasThis()) throw new IllegalStateException("no this");
if (getKind().isEnclosingKind()) {
return getSignature().getDeclaringType();
} else {
return enclosingShadow.getThisType();
}
}
/**
* a var referencing this
*
* @throws IllegalStateException if there is no target here
*/
public abstract Var getThisVar();
/**
* could target(*) pcd ever match
*/
public final boolean hasTarget() {
if (getKind().neverHasTarget()) {
return false;
} else if (getKind().isTargetSameAsThis()) {
return hasThis();
} else {
return !getSignature().isStatic();
}
}
/**
* the type of the target object here
*
* @throws IllegalStateException if there is no target here
*/
public final TypeX getTargetType() {
if (!hasTarget()) throw new IllegalStateException("no target");
return getSignature().getDeclaringType();
}
/**
* a var referencing the target
*
* @throws IllegalStateException if there is no target here
*/
public abstract Var getTargetVar();
public TypeX[] getArgTypes() {
if (getKind() == FieldSet) return new TypeX[] { getSignature().getReturnType() };
return getSignature().getParameterTypes();
}
public TypeX getArgType(int arg) {
if (getKind() == FieldSet) return getSignature().getReturnType();
return getSignature().getParameterTypes()[arg];
}
public int getArgCount() {
if (getKind() == FieldSet) return 1;
return getSignature()
.getParameterTypes().length;
}
public abstract TypeX getEnclosingType();
public abstract Var getArgVar(int i);
public abstract Var getThisJoinPointVar();
public abstract Var getThisJoinPointStaticPartVar();
public abstract Var getThisEnclosingJoinPointStaticPartVar();
public abstract Member getEnclosingCodeSignature();
/** returns the kind of shadow this is, representing what happens under this shadow
*/
public Kind getKind() {
return kind;
}
/** returns the signature of the thing under this shadow
*/
public Member getSignature() {
return signature;
}
public TypeX getReturnType() {
if (kind == ConstructorCall) return getSignature().getDeclaringType();
else if (kind == FieldSet) return ResolvedTypeX.VOID;
return getSignature().getReturnType();
}
/**
* These names are the ones that will be returned by thisJoinPoint.getKind()
* Those need to be documented somewhere
*/
public static final Kind MethodCall = new Kind(JoinPoint.METHOD_CALL, 1, true);
public static final Kind ConstructorCall = new Kind(JoinPoint.CONSTRUCTOR_CALL, 2, true);
public static final Kind MethodExecution = new Kind(JoinPoint.METHOD_EXECUTION, 3, false);
public static final Kind ConstructorExecution = new Kind(JoinPoint.CONSTRUCTOR_EXECUTION, 4, false);
public static final Kind FieldGet = new Kind(JoinPoint.FIELD_GET, 5, true);
public static final Kind FieldSet = new Kind(JoinPoint.FIELD_SET, 6, true);
public static final Kind StaticInitialization = new Kind(JoinPoint.STATICINITIALIZATION, 7, false);
public static final Kind PreInitialization = new Kind(JoinPoint.PREINTIALIZATION, 8, false);
public static final Kind AdviceExecution = new Kind(JoinPoint.ADVICE_EXECUTION, 9, false);
public static final Kind Initialization = new Kind(JoinPoint.INITIALIZATION, 10, false);
public static final Kind ExceptionHandler = new Kind(JoinPoint.EXCEPTION_HANDLER, 11, true);
public static final int MAX_SHADOW_KIND = 11;
public static final Kind[] SHADOW_KINDS = new Kind[] {
MethodCall, ConstructorCall, MethodExecution, ConstructorExecution,
FieldGet, FieldSet, StaticInitialization, PreInitialization,
AdviceExecution, Initialization, ExceptionHandler,
};
/** A type-safe enum representing the kind of shadows
*/
public static final class Kind extends TypeSafeEnum {
private boolean argsOnStack; //XXX unused
public Kind(String name, int key, boolean argsOnStack) {
super(name, key);
this.argsOnStack = argsOnStack;
}
public String toLegalJavaIdentifier() {
return getName().replace('-', '_');
}
public boolean argsOnStack() {
return !isTargetSameAsThis();
}
// !!! this is false for handlers!
public boolean allowsExtraction() {
return true;
}
// XXX revisit along with removal of priorities
public boolean hasHighPriorityExceptions() {
return !isTargetSameAsThis();
}
/**
* These are all the shadows that contains other shadows within them and
* are often directly associated with methods.
*/
public boolean isEnclosingKind() {
return this == MethodExecution || this == ConstructorExecution ||
this == AdviceExecution || this == StaticInitialization
|| this == Initialization;
}
public boolean isTargetSameAsThis() {
return this == MethodExecution
|| this == ConstructorExecution
|| this == StaticInitialization
|| this == PreInitialization
|| this == AdviceExecution
|| this == Initialization;
}
public boolean neverHasTarget() {
return this == ConstructorCall
|| this == ExceptionHandler
|| this == PreInitialization
|| this == StaticInitialization;
}
public boolean neverHasThis() {
return this == PreInitialization
|| this == StaticInitialization;
}
public String getSimpleName() {
int dash = getName().lastIndexOf('-');
if (dash == -1) return getName();
else return getName().substring(dash+1);
}
public static Kind read(DataInputStream s) throws IOException {
int key = s.readByte();
switch(key) {
case 1: return MethodCall;
case 2: return ConstructorCall;
case 3: return MethodExecution;
case 4: return ConstructorExecution;
case 5: return FieldGet;
case 6: return FieldSet;
case 7: return StaticInitialization;
case 8: return PreInitialization;
case 9: return AdviceExecution;
case 10: return Initialization;
case 11: return ExceptionHandler;
}
throw new BCException("unknown kind: " + key);
}
}
protected boolean checkMunger(ShadowMunger munger) {
for (Iterator i = munger.getThrownExceptions().iterator(); i.hasNext(); ) {
if (!checkCanThrow(munger, (ResolvedTypeX)i.next() )) return false;
}
return true;
}
protected boolean checkCanThrow(ShadowMunger munger, ResolvedTypeX resolvedTypeX) {
if (getKind() == ExceptionHandler) {
//XXX much too lenient rules here, need to walk up exception handlers
return true;
}
if (!isDeclaredException(resolvedTypeX, getSignature())) {
getIWorld().showMessage(IMessage.ERROR, "can't throw checked exception \'" + resolvedTypeX +
"\' at this join point \'" + this +"\'", // from advice in \'" + munger. + "\'",
getSourceLocation(), munger.getSourceLocation());
}
return true;
}
private boolean isDeclaredException(
ResolvedTypeX resolvedTypeX,
Member member)
{
ResolvedTypeX[] excs = getIWorld().resolve(member.getExceptions(getIWorld()));
for (int i=0, len=excs.length; i < len; i++) {
if (excs[i].isAssignableFrom(resolvedTypeX)) return true;
}
return false;
}
public void addMunger(ShadowMunger munger) {
if (checkMunger(munger)) this.mungers.add(munger);
}
public final void implement() {
sortMungers();
if (mungers == null) return;
prepareForMungers();
implementMungers();
}
private void sortMungers() {
List sorted = PartialOrder.sort(mungers);
if (sorted == null) {
// this means that we have circular dependencies
for (Iterator i = mungers.iterator(); i.hasNext(); ) {
ShadowMunger m = (ShadowMunger)i.next();
getIWorld().getMessageHandler().handleMessage(
MessageUtil.error("circular dependency at " + this, m.getSourceLocation()));
}
}
mungers = sorted;
}
/** Prepare the shadow for implementation. After this is done, the shadow
* should be in such a position that each munger simply needs to be implemented.
*/
protected void prepareForMungers() {
throw new RuntimeException("Generic shadows cannot be prepared");
}
/** Actually implement the (non-empty) mungers associated with this shadow */
private void implementMungers() {
World world = getIWorld();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
munger.implementOn(this);
if (world.xrefHandler != null) {
world.xrefHandler.addCrossReference(munger.getSourceLocation(),this.getSourceLocation(),IRelationship.Kind.ADVICE);
}
if (world.getModel() != null) {
//System.err.println("munger: " + munger + " on " + this);
AsmRelationshipProvider.adviceMunger(world.getModel(), this, munger);
}
}
}
public String makeReflectiveFactoryString() {
return null; //XXX
}
public abstract ISourceLocation getSourceLocation();
// ---- utility
public String toString() {
return getKind() + "(" + getSignature() + ")"; // + getSourceLines();
}
}
|
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07: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.Collections;
import java.util.Iterator;
import java.util.List;
import org.aspectj.bridge.IMessage;
import org.aspectj.weaver.bcel.BcelTypeMunger;
public class WeaverStateInfo {
private List/*Entry*/ typeMungers;
private boolean oldStyle;
public WeaverStateInfo() {
this(new ArrayList(), false);
}
private WeaverStateInfo(List typeMungers, boolean oldStyle) {
this.typeMungers = typeMungers;
this.oldStyle = oldStyle;
}
private static final int UNTOUCHED=0, WOVEN=2, EXTENDED=3;
public static final WeaverStateInfo read(DataInputStream s, ISourceContext context) throws IOException {
byte b = s.readByte();
switch(b) {
case UNTOUCHED:
throw new RuntimeException("unexpected UNWOVEN");
case WOVEN:
return new WeaverStateInfo(Collections.EMPTY_LIST, true);
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));
}
return new WeaverStateInfo(l, false);
}
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");
s.writeByte(EXTENDED);
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);
}
}
public void addConcreteMunger(ConcreteTypeMunger munger) {
typeMungers.add(new Entry(munger.getAspectType(), munger.getMunger()));
}
public String toString() {
return "WeaverStateInfo(" + typeMungers + ", " + oldStyle + ")";
}
public List getTypeMungers(ResolvedTypeX onType) {
World world = onType.getWorld();
List ret = new ArrayList();
for (Iterator i = typeMungers.iterator(); i.hasNext();) {
Entry entry = (Entry) i.next();
ResolvedTypeX aspectType = world.resolve(entry.aspectType, true);
if (aspectType == ResolvedTypeX.MISSING) {
world.showMessage(IMessage.ERROR, "aspect " + entry.aspectType +
" is needed when using type " + onType,
onType.getSourceLocation(), null);
continue;
}
ret.add(new BcelTypeMunger(entry.typeMunger, aspectType));
}
return ret;
}
public boolean isOldStyle() {
return oldStyle;
}
}
|
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07:46:40Z
|
weaver/src/org/aspectj/weaver/bcel/BcelCflowStackFieldAdder.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 org.apache.bcel.Constants;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.generic.FieldGen;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.Type;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
public class BcelCflowStackFieldAdder extends BcelTypeMunger {
private ResolvedMember cflowStackField;
public BcelCflowStackFieldAdder(ResolvedMember cflowStackField) {
super(null, null);
this.cflowStackField = cflowStackField;
}
public boolean munge(BcelClassWeaver weaver) {
LazyClassGen gen = weaver.getLazyClassGen();
if (!gen.getType().equals(cflowStackField.getDeclaringType())) return false;
Field f = new FieldGen(cflowStackField.getModifiers(),
BcelWorld.makeBcelType(cflowStackField.getReturnType()),
cflowStackField.getName(),
gen.getConstantPoolGen()).getField();
gen.addField(f);
LazyMethodGen clinit = gen.getAjcPreClinit(); //StaticInitializer();
InstructionList setup = new InstructionList();
InstructionFactory fact = gen.getFactory();
setup.append(fact.createNew(new ObjectType(NameMangler.CFLOW_STACK_TYPE)));
setup.append(InstructionFactory.createDup(1));
setup.append(fact.createInvoke(
NameMangler.CFLOW_STACK_TYPE,
"<init>",
Type.VOID,
new Type[0],
Constants.INVOKESPECIAL));
setup.append(Utility.createSet(fact, cflowStackField));
clinit.getBody().insert(setup);
return true;
}
public ResolvedMember getMatchingSyntheticMember(Member member) {
return null;
}
public ResolvedMember getSignature() {
return cflowStackField;
}
public boolean matches(ResolvedTypeX onType) {
return onType.equals(cflowStackField.getDeclaringType());
}
}
|
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07:46:40Z
|
weaver/src/org/aspectj/weaver/bcel/BcelClassWeaver.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.bcel.Constants;
import org.apache.bcel.generic.BranchInstruction;
import org.apache.bcel.generic.CPInstruction;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.FieldInstruction;
import org.apache.bcel.generic.INVOKESPECIAL;
import org.apache.bcel.generic.IndexedInstruction;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionConstants;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.InstructionTargeter;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.LocalVariableInstruction;
import org.apache.bcel.generic.NEW;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.PUTFIELD;
import org.apache.bcel.generic.PUTSTATIC;
import org.apache.bcel.generic.RET;
import org.apache.bcel.generic.ReturnInstruction;
import org.apache.bcel.generic.Select;
import org.apache.bcel.generic.Type;
import org.aspectj.bridge.IMessage;
import org.aspectj.util.PartialOrder;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.IClassWeaver;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.Shadow.Kind;
import org.aspectj.weaver.patterns.FastMatchInfo;
class BcelClassWeaver implements IClassWeaver {
/**
* This is called from {@link BcelWeaver} to perform the per-class weaving process.
*/
public static boolean weave(
BcelWorld world,
LazyClassGen clazz,
List shadowMungers,
List typeMungers)
{
boolean b = new BcelClassWeaver(world, clazz, shadowMungers, typeMungers).weave();
//System.out.println(clazz.getClassName() + ", " + clazz.getType().getWeaverState());
//clazz.print();
return b;
}
// --------------------------------------------
private final LazyClassGen clazz;
private final List shadowMungers;
private final List typeMungers;
private final BcelObjectType ty; // alias of clazz.getType()
private final BcelWorld world; // alias of ty.getWorld()
private final ConstantPoolGen cpg; // alias of clazz.getConstantPoolGen()
private final InstructionFactory fact; // alias of clazz.getFactory();
private final List addedLazyMethodGens = new ArrayList();
private final Set addedDispatchTargets = new HashSet();
private List addedSuperInitializersAsList = null; // List<IfaceInitList>
private final Map addedSuperInitializers = new HashMap(); // Interface -> IfaceInitList
private List addedThisInitializers = new ArrayList(); // List<NewFieldMunger>
private List addedClassInitializers = new ArrayList(); // List<NewFieldMunger>
private BcelShadow clinitShadow = null;
/**
* This holds the initialization and pre-initialization shadows for this class
* that were actually matched by mungers (if no match, then we don't even create the
* shadows really).
*/
private final List initializationShadows = new ArrayList(1);
private BcelClassWeaver(
BcelWorld world,
LazyClassGen clazz,
List shadowMungers,
List typeMungers)
{
super();
// assert world == clazz.getType().getWorld()
this.world = world;
this.clazz = clazz;
this.shadowMungers = shadowMungers;
this.typeMungers = typeMungers;
this.ty = clazz.getBcelObjectType();
this.cpg = clazz.getConstantPoolGen();
this.fact = clazz.getFactory();
fastMatchShadowMungers(shadowMungers);
initializeSuperInitializerMap(ty.getResolvedTypeX());
}
private List[] perKindShadowMungers;
private boolean canMatchBodyShadows = false;
private boolean canMatchInitialization = false;
private void fastMatchShadowMungers(List shadowMungers) {
perKindShadowMungers = new List[Shadow.MAX_SHADOW_KIND+1];
for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) {
Shadow.Kind kind = Shadow.SHADOW_KINDS[i];
ArrayList mungers = new ArrayList(0);
perKindShadowMungers[kind.getKey()] = mungers;
fastMatchShadowMungers(shadowMungers, mungers, kind);
if (mungers.isEmpty()) {
perKindShadowMungers[kind.getKey()] = null;
} else {
if (kind == Shadow.Initialization) {
canMatchInitialization = true;
} else if (!kind.isEnclosingKind()) {
canMatchBodyShadows = true;
}
}
}
}
private boolean canMatch(Shadow.Kind kind) {
return perKindShadowMungers[kind.getKey()] != null;
}
private void fastMatchShadowMungers(List shadowMungers, ArrayList mungers, Kind kind) {
FastMatchInfo info = new FastMatchInfo(clazz.getType(), kind);
for (Iterator i = shadowMungers.iterator(); i.hasNext();) {
ShadowMunger munger = (ShadowMunger) i.next();
if (munger.getPointcut().fastMatch(info).maybeTrue()) mungers.add(munger);
}
}
private void initializeSuperInitializerMap(ResolvedTypeX child) {
ResolvedTypeX[] superInterfaces = child.getDeclaredInterfaces();
for (int i=0, len=superInterfaces.length; i < len; i++) {
if (ty.getResolvedTypeX().isTopmostImplementor(superInterfaces[i])) {
if (addSuperInitializer(superInterfaces[i])) {
initializeSuperInitializerMap(superInterfaces[i]);
}
}
}
}
private boolean addSuperInitializer(ResolvedTypeX onType) {
IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType);
if (l != null) return false;
l = new IfaceInitList(onType);
addedSuperInitializers.put(onType, l);
return true;
}
public void addInitializer(ConcreteTypeMunger cm) {
NewFieldTypeMunger m = (NewFieldTypeMunger) cm.getMunger();
ResolvedTypeX onType = m.getSignature().getDeclaringType().resolve(world);
if (m.getSignature().isStatic()) {
addedClassInitializers.add(cm);
} else {
if (onType == ty.getResolvedTypeX()) {
addedThisInitializers.add(cm);
} else {
IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType);
l.list.add(cm);
}
}
}
private static class IfaceInitList implements PartialOrder.PartialComparable {
final ResolvedTypeX onType;
List list = new ArrayList();
IfaceInitList(ResolvedTypeX onType) {
this.onType = onType;
}
public int compareTo(Object other) {
IfaceInitList o = (IfaceInitList)other;
if (onType.isAssignableFrom(o.onType)) return +1;
else if (o.onType.isAssignableFrom(onType)) return -1;
else return 0;
}
public int fallbackCompareTo(Object other) {
return 0;
}
}
// XXX this is being called, but the result doesn't seem to be being used
public boolean addDispatchTarget(ResolvedMember m) {
return addedDispatchTargets.add(m);
}
public void addLazyMethodGen(LazyMethodGen gen) {
addedLazyMethodGens.add(gen);
}
public void addOrReplaceLazyMethodGen(LazyMethodGen mg) {
if (alreadyDefined(clazz, mg)) return;
for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) {
LazyMethodGen existing = (LazyMethodGen)i.next();
if (signaturesMatch(mg, existing)) {
if (existing.definingType == null) {
// this means existing was introduced on the class itself
return;
} else if (mg.definingType.isAssignableFrom(existing.definingType)) {
// existing is mg's subtype and dominates mg
return;
} else if (existing.definingType.isAssignableFrom(mg.definingType)) {
// mg is existing's subtype and dominates existing
i.remove();
addedLazyMethodGens.add(mg);
return;
} else {
throw new BCException("conflict between: " + mg + " and " + existing);
}
}
}
addedLazyMethodGens.add(mg);
}
private boolean alreadyDefined(LazyClassGen clazz, LazyMethodGen mg) {
for (Iterator i = clazz.getMethodGens().iterator(); i.hasNext(); ) {
LazyMethodGen existing = (LazyMethodGen)i.next();
if (signaturesMatch(mg, existing)) {
if (!mg.isAbstract() && existing.isAbstract()) {
i.remove();
return false;
}
return true;
}
}
return false;
}
private boolean signaturesMatch(LazyMethodGen mg, LazyMethodGen existing) {
return mg.getName().equals(existing.getName()) &&
mg.getSignature().equals(existing.getSignature());
}
// ----
public boolean weave() {
if (clazz.isWoven()) {
world.showMessage(IMessage.ERROR,
"class \'" + clazz.getType().getName() + "\' is already woven",
ty.getSourceLocation(), null);
return false;
}
boolean isChanged = false;
// we want to "touch" all aspects
if (clazz.getType().isAspect()) isChanged = true;
// start by munging all typeMungers
for (Iterator i = typeMungers.iterator(); i.hasNext(); ) {
Object o = i.next();
if ( !(o instanceof BcelTypeMunger) ) {
//???System.err.println("surprising: " + o);
continue;
}
BcelTypeMunger munger = (BcelTypeMunger)o;
isChanged |= munger.munge(this);
}
// XXX do major sort of stuff
// sort according to: Major: type hierarchy
// within each list: dominates
// don't forget to sort addedThisInitialiers according to dominates
addedSuperInitializersAsList = new ArrayList(addedSuperInitializers.values());
addedSuperInitializersAsList = PartialOrder.sort(addedSuperInitializersAsList);
if (addedSuperInitializersAsList == null) {
throw new BCException("circularity in inter-types");
}
// this will create a static initializer if there isn't one
// this is in just as bad taste as NOPs
LazyMethodGen staticInit = clazz.getStaticInitializer();
staticInit.getBody().insert(genInitInstructions(addedClassInitializers, true));
// now go through each method, and match against each method. This
// sets up each method's {@link LazyMethodGen#matchedShadows} field,
// and it also possibly adds to {@link #initializationShadows}.
List methodGens = new ArrayList(clazz.getMethodGens());
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen)i.next();
//mg.getBody();
if (! mg.hasBody()) continue;
isChanged |= match(mg);
}
if (! isChanged) return false;
// now we weave all but the initialization shadows
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen)i.next();
if (! mg.hasBody()) continue;
implement(mg);
}
// if we matched any initialization shadows, we inline and weave
if (! initializationShadows.isEmpty()) {
inlineSelfConstructors(methodGens);
positionAndImplement(initializationShadows);
}
// finally, if we changed, we add in the introduced methods.
if (isChanged) {
clazz.getOrCreateWeaverStateInfo();
weaveInAddedMethods();
}
return isChanged;
}
private void inlineSelfConstructors(List methodGens) {
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen) i.next();
if (! mg.getName().equals("<init>")) continue;
InstructionHandle ih = findSuperOrThisCall(mg);
if (ih != null && isThisCall(ih)) {
LazyMethodGen donor = getCalledMethod(ih);
inlineMethod(donor, mg, ih);
}
}
}
private void positionAndImplement(List initializationShadows) {
for (Iterator i = initializationShadows.iterator(); i.hasNext(); ) {
BcelShadow s = (BcelShadow) i.next();
positionInitializationShadow(s);
//s.getEnclosingMethod().print();
s.implement();
}
}
private void positionInitializationShadow(BcelShadow s) {
LazyMethodGen mg = s.getEnclosingMethod();
InstructionHandle call = findSuperOrThisCall(mg);
InstructionList body = mg.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow((BcelShadow) s);
if (s.getKind() == Shadow.PreInitialization) {
// XXX assert first instruction is an ALOAD_0.
// a pre shadow goes from AFTER the first instruction (which we believe to
// be an ALOAD_0) to just before the call to super
r.associateWithTargets(
Range.genStart(body, body.getStart().getNext()),
Range.genEnd(body, call.getPrev()));
} else {
// assert s.getKind() == Shadow.Initialization
r.associateWithTargets(
Range.genStart(body, call.getNext()),
Range.genEnd(body));
}
}
private boolean isThisCall(InstructionHandle ih) {
INVOKESPECIAL inst = (INVOKESPECIAL) ih.getInstruction();
return inst.getClassName(cpg).equals(clazz.getName());
}
/** inline a particular call in bytecode.
*
* @param donor the method we want to inline
* @param recipient the method containing the call we want to inline
* @param call the instructionHandle in recipient's body holding the call we want to
* inline.
*/
public static void inlineMethod(
LazyMethodGen donor,
LazyMethodGen recipient,
InstructionHandle call)
{
// assert recipient.contains(call)
/* Implementation notes:
*
* We allocate two slots for every tempvar so we don't screw up
* longs and doubles which may share space. This could be conservatively avoided
* (no reference to a long/double instruction, don't do it) or packed later.
* Right now we don't bother to pack.
*
* Allocate a new var for each formal param of the inlined. Fill with stack
* contents. Then copy the inlined instructions in with the appropriate remap
* table. Any framelocs used by locals in inlined are reallocated to top of
* frame,
*/
final InstructionFactory fact = recipient.getEnclosingClass().getFactory();
IntMap frameEnv = new IntMap();
// this also sets up the initial environment
InstructionList argumentStores =
genArgumentStores(donor, recipient, frameEnv, fact);
InstructionList inlineInstructions =
genInlineInstructions(donor, recipient, frameEnv, fact, false);
inlineInstructions.insert(argumentStores);
recipient.getBody().append(call, inlineInstructions);
Utility.deleteInstruction(call, recipient);
}
/** generate the instructions to be inlined.
*
* @param donor the method from which we will copy (and adjust frame and jumps)
* instructions.
* @param recipient the method the instructions will go into. Used to get the frame
* size so we can allocate new frame locations for locals in donor.
* @param frameEnv an environment to map from donor frame to recipient frame,
* initially populated with argument locations.
* @param fact an instruction factory for recipient
*/
static InstructionList genInlineInstructions(
LazyMethodGen donor,
LazyMethodGen recipient,
IntMap frameEnv,
InstructionFactory fact,
boolean keepReturns)
{
InstructionList footer = new InstructionList();
InstructionHandle end = footer.append(InstructionConstants.NOP);
InstructionList ret = new InstructionList();
InstructionList sourceList = donor.getBody();
Map srcToDest = new HashMap();
ConstantPoolGen donorCpg = donor.getEnclosingClass().getConstantPoolGen();
ConstantPoolGen recipientCpg = recipient.getEnclosingClass().getConstantPoolGen();
boolean isAcrossClass = donorCpg != recipientCpg;
// first pass: copy the instructions directly, populate the srcToDest map,
// fix frame instructions
for (InstructionHandle src = sourceList.getStart();
src != null;
src = src.getNext())
{
Instruction fresh = Utility.copyInstruction(src.getInstruction());
InstructionHandle dest;
if (fresh instanceof CPInstruction) {
// need to reset index to go to new constant pool. This is totally
// a computation leak... we're testing this LOTS of times. Sigh.
if (isAcrossClass) {
CPInstruction cpi = (CPInstruction) fresh;
cpi.setIndex(
recipientCpg.addConstant(
donorCpg.getConstant(cpi.getIndex()),
donorCpg));
}
}
if (src.getInstruction() == Range.RANGEINSTRUCTION) {
dest = ret.append(Range.RANGEINSTRUCTION);
} else if (fresh instanceof ReturnInstruction) {
if (keepReturns) {
dest = ret.append(fresh);
} else {
dest =
ret.append(InstructionFactory.createBranchInstruction(Constants.GOTO, end));
}
} else if (fresh instanceof BranchInstruction) {
dest = ret.append((BranchInstruction) fresh);
} else if (
fresh instanceof LocalVariableInstruction || fresh instanceof RET) {
IndexedInstruction indexed = (IndexedInstruction) fresh;
int oldIndex = indexed.getIndex();
int freshIndex;
if (!frameEnv.hasKey(oldIndex)) {
freshIndex = recipient.allocateLocal(2);
frameEnv.put(oldIndex, freshIndex);
} else {
freshIndex = frameEnv.get(oldIndex);
}
indexed.setIndex(freshIndex);
dest = ret.append(fresh);
} else {
dest = ret.append(fresh);
}
srcToDest.put(src, dest);
}
// second pass: retarget branch instructions, copy ranges and tags
Map tagMap = new HashMap();
Map shadowMap = new HashMap();
for (InstructionHandle dest = ret.getStart(), src = sourceList.getStart();
dest != null;
dest = dest.getNext(), src = src.getNext()) {
Instruction inst = dest.getInstruction();
// retarget branches
if (inst instanceof BranchInstruction) {
BranchInstruction branch = (BranchInstruction) inst;
InstructionHandle oldTarget = branch.getTarget();
InstructionHandle newTarget =
(InstructionHandle) srcToDest.get(oldTarget);
if (newTarget == null) {
// assert this is a GOTO
// this was a return instruction we previously replaced
} else {
branch.setTarget(newTarget);
if (branch instanceof Select) {
Select select = (Select) branch;
InstructionHandle[] oldTargets = select.getTargets();
for (int k = oldTargets.length - 1; k >= 0; k--) {
select.setTarget(
k,
(InstructionHandle) srcToDest.get(oldTargets[k]));
}
}
}
}
//copy over tags and range attributes
InstructionTargeter[] srcTargeters = src.getTargeters();
if (srcTargeters != null) {
for (int j = srcTargeters.length - 1; j >= 0; j--) {
InstructionTargeter old = srcTargeters[j];
if (old instanceof Tag) {
Tag oldTag = (Tag) old;
Tag fresh = (Tag) tagMap.get(oldTag);
if (fresh == null) {
fresh = oldTag.copy();
tagMap.put(oldTag, fresh);
}
dest.addTargeter(fresh);
} else if (old instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) old;
if (er.getStart() == src) {
ExceptionRange freshEr =
new ExceptionRange(
recipient.getBody(),
er.getCatchType(),
er.getPriority());
freshEr.associateWithTargets(
dest,
(InstructionHandle)srcToDest.get(er.getEnd()),
(InstructionHandle)srcToDest.get(er.getHandler()));
}
} else if (old instanceof ShadowRange) {
ShadowRange oldRange = (ShadowRange) old;
if (oldRange.getStart() == src) {
BcelShadow oldShadow = oldRange.getShadow();
BcelShadow freshEnclosing =
oldShadow.getEnclosingShadow() == null
? null
: (BcelShadow) shadowMap.get(oldShadow.getEnclosingShadow());
BcelShadow freshShadow =
oldShadow.copyInto(recipient, freshEnclosing);
ShadowRange freshRange = new ShadowRange(recipient.getBody());
freshRange.associateWithShadow(freshShadow);
freshRange.associateWithTargets(
dest,
(InstructionHandle) srcToDest.get(oldRange.getEnd()));
shadowMap.put(oldRange, freshRange);
//recipient.matchedShadows.add(freshShadow);
// XXX should go through the NEW copied shadow and update
// the thisVar, targetVar, and argsVar
// ??? Might want to also go through at this time and add
// "extra" vars to the shadow.
}
}
}
}
}
if (!keepReturns) ret.append(footer);
return ret;
}
/** generate the argument stores in preparation for inlining.
*
* @param donor the method we will inline from. Used to get the signature.
* @param recipient the method we will inline into. Used to get the frame size
* so we can allocate fresh locations.
* @param frameEnv an empty environment we populate with a map from donor frame to
* recipient frame.
* @param fact an instruction factory for recipient
*/
private static InstructionList genArgumentStores(
LazyMethodGen donor,
LazyMethodGen recipient,
IntMap frameEnv,
InstructionFactory fact)
{
InstructionList ret = new InstructionList();
int donorFramePos = 0;
// writing ret back to front because we're popping.
if (! donor.isStatic()) {
int targetSlot = recipient.allocateLocal(Type.OBJECT);
ret.insert(InstructionFactory.createStore(Type.OBJECT, targetSlot));
frameEnv.put(donorFramePos, targetSlot);
donorFramePos += 1;
}
Type[] argTypes = donor.getArgumentTypes();
for (int i = 0, len = argTypes.length; i < len; i++) {
Type argType = argTypes[i];
int argSlot = recipient.allocateLocal(argType);
ret.insert(InstructionFactory.createStore(argType, argSlot));
frameEnv.put(donorFramePos, argSlot);
donorFramePos += argType.getSize();
}
return ret;
}
/** get a called method: Assumes the called method is in this class,
* and the reference to it is exact (a la INVOKESPECIAL).
*
* @param ih The InvokeInstruction instructionHandle pointing to the called method.
*/
private LazyMethodGen getCalledMethod(
InstructionHandle ih)
{
InvokeInstruction inst = (InvokeInstruction) ih.getInstruction();
String methodName = inst.getName(cpg);
String signature = inst.getSignature(cpg);
return clazz.getLazyMethodGen(methodName, signature);
}
private void weaveInAddedMethods() {
Collections.sort(addedLazyMethodGens,
new Comparator() {
public int compare(Object a, Object b) {
LazyMethodGen aa = (LazyMethodGen) a;
LazyMethodGen bb = (LazyMethodGen) b;
int i = aa.getName().compareTo(bb.getName());
if (i != 0) return i;
return aa.getSignature().compareTo(bb.getSignature());
}
}
);
for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) {
clazz.addMethodGen((LazyMethodGen)i.next());
}
}
void addPerSingletonField(Member field) {
ObjectType aspectType = (ObjectType) BcelWorld.makeBcelType(field.getReturnType());
String aspectName = field.getReturnType().getName();
LazyMethodGen clinit = clazz.getStaticInitializer();
InstructionList setup = new InstructionList();
InstructionFactory fact = clazz.getFactory();
setup.append(fact.createNew(aspectType));
setup.append(InstructionFactory.createDup(1));
setup.append(fact.createInvoke(
aspectName,
"<init>",
Type.VOID,
new Type[0],
Constants.INVOKESPECIAL));
setup.append(
fact.createFieldAccess(
aspectName,
field.getName(),
aspectType,
Constants.PUTSTATIC));
clinit.getBody().insert(setup);
}
/**
* Returns null if this is not a Java constructor, and then we won't
* weave into it at all
*/
private InstructionHandle findSuperOrThisCall(LazyMethodGen mg) {
int depth = 1;
InstructionHandle start = mg.getBody().getStart();
while (true) {
if (start == null) return null;
Instruction inst = start.getInstruction();
if (inst instanceof INVOKESPECIAL
&& ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) {
depth--;
if (depth == 0) return start;
} else if (inst instanceof NEW) {
depth++;
}
start = start.getNext();
}
}
// ----
private boolean match(LazyMethodGen mg) {
BcelShadow enclosingShadow;
List shadowAccumulator = new ArrayList();
// we want to match ajsynthetic constructors...
if (mg.getName().equals("<init>")) {
// XXX the enclosing join point is wrong for things before ignoreMe.
InstructionHandle superOrThisCall = findSuperOrThisCall(mg);
// we don't walk bodies of things where it's a wrong constructor thingie
if (superOrThisCall == null) return false;
enclosingShadow = BcelShadow.makeConstructorExecution(world, mg, superOrThisCall);
// walk the body
boolean beforeSuperOrThisCall = true;
if (shouldWeaveBody(mg)) {
if (canMatchBodyShadows) {
for (InstructionHandle h = mg.getBody().getStart();
h != null;
h = h.getNext()) {
if (h == superOrThisCall) {
beforeSuperOrThisCall = false;
continue;
}
match(mg, h, beforeSuperOrThisCall ? null : enclosingShadow, shadowAccumulator);
}
}
match(enclosingShadow, shadowAccumulator);
}
// XXX we don't do pre-inits of interfaces
// now add interface inits
if (superOrThisCall != null && ! isThisCall(superOrThisCall)) {
InstructionHandle curr = enclosingShadow.getRange().getStart();
for (Iterator i = addedSuperInitializersAsList.iterator(); i.hasNext(); ) {
IfaceInitList l = (IfaceInitList) i.next();
Member ifaceInitSig = AjcMemberMaker.interfaceConstructor(l.onType);
BcelShadow initShadow =
BcelShadow.makeIfaceInitialization(world, mg, ifaceInitSig);
// insert code in place
InstructionList inits = genInitInstructions(l.list, false);
if (match(initShadow, shadowAccumulator) || !inits.isEmpty()) {
initShadow.initIfaceInitializer(curr);
initShadow.getRange().insert(inits, Range.OutsideBefore);
}
}
// now we add our initialization code
InstructionList inits = genInitInstructions(addedThisInitializers, false);
enclosingShadow.getRange().insert(inits, Range.OutsideBefore);
}
// actually, you only need to inline the self constructors that are
// in a particular group (partition the constructors into groups where members
// call or are called only by those in the group). Then only inline
// constructors
// in groups where at least one initialization jp matched. Future work.
boolean addedInitialization =
match(
BcelShadow.makeUnfinishedInitialization(world, mg),
initializationShadows);
addedInitialization |=
match(
BcelShadow.makeUnfinishedPreinitialization(world, mg),
initializationShadows);
mg.matchedShadows = shadowAccumulator;
return addedInitialization || !shadowAccumulator.isEmpty();
} else if (!shouldWeaveBody(mg)) { //.isAjSynthetic()) {
return false;
} else {
if (mg.getName().equals("<clinit>")) {
clinitShadow = enclosingShadow = BcelShadow.makeStaticInitialization(world, mg);
//System.err.println(enclosingShadow);
} else if (mg.isAdviceMethod()) {
enclosingShadow = BcelShadow.makeAdviceExecution(world, mg);
} else {
AjAttribute.EffectiveSignatureAttribute effective = mg.getEffectiveSignature();
if (effective == null) {
enclosingShadow = BcelShadow.makeMethodExecution(world, mg, !canMatchBodyShadows);
} else if (effective.isWeaveBody()) {
enclosingShadow =
BcelShadow.makeShadowForMethod(
world,
mg,
effective.getShadowKind(),
effective.getEffectiveSignature());
} else {
return false;
}
}
if (canMatchBodyShadows) {
for (InstructionHandle h = mg.getBody().getStart();
h != null;
h = h.getNext()) {
match(mg, h, enclosingShadow, shadowAccumulator);
}
}
if (match(enclosingShadow, shadowAccumulator)) {
enclosingShadow.init();
}
mg.matchedShadows = shadowAccumulator;
return !shadowAccumulator.isEmpty();
}
}
private boolean shouldWeaveBody(LazyMethodGen mg) {
if (mg.isAjSynthetic()) return mg.getName().equals("<clinit>");
AjAttribute.EffectiveSignatureAttribute a = mg.getEffectiveSignature();
if (a != null) return a.isWeaveBody();
return true;
}
/**
* first sorts the mungers, then gens the initializers in the right order
*/
private InstructionList genInitInstructions(List list, boolean isStatic) {
list = PartialOrder.sort(list);
if (list == null) {
throw new BCException("circularity in inter-types");
}
InstructionList ret = new InstructionList();
for (Iterator i = list.iterator(); i.hasNext();) {
ConcreteTypeMunger cmunger = (ConcreteTypeMunger) i.next();
NewFieldTypeMunger munger = (NewFieldTypeMunger) cmunger.getMunger();
ResolvedMember initMethod = munger.getInitMethod(cmunger.getAspectType());
if (!isStatic) ret.append(InstructionConstants.ALOAD_0);
ret.append(Utility.createInvoke(fact, world, initMethod));
}
return ret;
}
private void match(
LazyMethodGen mg,
InstructionHandle ih,
BcelShadow enclosingShadow,
List shadowAccumulator)
{
Instruction i = ih.getInstruction();
if (i instanceof FieldInstruction) {
FieldInstruction fi = (FieldInstruction) i;
if (fi instanceof PUTFIELD || fi instanceof PUTSTATIC) {
// check for sets of constant fields. We first check the previous
// instruction. If the previous instruction is a LD_WHATEVER (push
// constant on the stack) then we must resolve the field to determine
// if it's final. If it is final, then we don't generate a shadow.
InstructionHandle prevHandle = ih.getPrev();
Instruction prevI = prevHandle.getInstruction();
if (Utility.isConstantPushInstruction(prevI)) {
Member field = BcelWorld.makeFieldSignature(clazz, (FieldInstruction) i);
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
} else if (Modifier.isFinal(resolvedField.getModifiers())) {
// it's final, so it's the set of a final constant, so it's
// not a join point according to 1.0.6 and 1.1.
} else {
matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else {
matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else {
matchGetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else if (i instanceof InvokeInstruction) {
InvokeInstruction ii = (InvokeInstruction) i;
if (ii.getMethodName(clazz.getConstantPoolGen()).equals("<init>")) {
match(
BcelShadow.makeConstructorCall(world, mg, ih, enclosingShadow),
shadowAccumulator);
} else if (ii instanceof INVOKESPECIAL) {
String onTypeName = ii.getClassName(cpg);
if (onTypeName.equals(mg.getEnclosingClass().getName())) {
// we are private
matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator);
} else {
// we are a super call, and this is not a join point in AspectJ-1.{0,1}
}
} else {
matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator);
}
}
// performance optimization... we only actually care about ASTORE instructions,
// since that's what every javac type thing ever uses to start a handler, but for
// now we'll do this for everybody.
if (Range.isRangeHandle(ih)) return;
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters != null) {
for (int j = 0; j < targeters.length; j++) {
InstructionTargeter t = targeters[j];
if (t instanceof ExceptionRange) {
// assert t.getHandler() == ih
ExceptionRange er = (ExceptionRange) t;
if (er.getCatchType() == null) continue;
if (isInitFailureHandler(ih)) return;
match(
BcelShadow.makeExceptionHandler(
world,
er,
mg, ih, enclosingShadow),
shadowAccumulator);
}
}
}
}
private boolean isInitFailureHandler(InstructionHandle ih) {
if (ih.getInstruction() instanceof PUTSTATIC) {
String name = ((PUTSTATIC)ih.getInstruction()).getFieldName(cpg);
if (name.equals(NameMangler.INITFAILURECAUSE_FIELD_NAME)) return true;
}
return false;
}
private void matchSetInstruction(
LazyMethodGen mg,
InstructionHandle ih,
BcelShadow enclosingShadow,
List shadowAccumulator) {
FieldInstruction fi = (FieldInstruction) ih.getInstruction();
Member field = BcelWorld.makeFieldSignature(clazz, fi);
// synthetic fields are never join points
if (field.getName().startsWith(NameMangler.PREFIX)) return;
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
return;
} else if (
Modifier.isFinal(resolvedField.getModifiers())
&& Utility.isConstantPushInstruction(ih.getPrev().getInstruction())) {
// it's the set of a final constant, so it's
// not a join point according to 1.0.6 and 1.1.
return;
} else if (resolvedField.isSynthetic()) {
// sets of synthetics aren't join points in 1.1
return;
} else {
match(
BcelShadow.makeFieldSet(world, mg, ih, enclosingShadow),
shadowAccumulator);
}
}
private void matchGetInstruction(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) {
FieldInstruction fi = (FieldInstruction) ih.getInstruction();
Member field = BcelWorld.makeFieldSignature(clazz, fi);
// synthetic fields are never join points
if (field.getName().startsWith(NameMangler.PREFIX)) return;
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
return;
} else if (resolvedField.isSynthetic()) {
// sets of synthetics aren't join points in 1.1
return;
} else {
match(BcelShadow.makeFieldGet(world, mg, ih, enclosingShadow), shadowAccumulator);
}
}
private void matchInvokeInstruction(LazyMethodGen mg,
InstructionHandle ih,
InvokeInstruction invoke,
BcelShadow enclosingShadow,
List shadowAccumulator)
{
String methodName = invoke.getName(cpg);
if (methodName.startsWith(NameMangler.PREFIX)) {
Member method =
BcelWorld.makeMethodSignature(clazz, invoke);
ResolvedMember declaredSig = method.resolve(world);
//System.err.println(method + ", declaredSig: " +declaredSig);
if (declaredSig == null) return;
if (declaredSig.getKind() == Member.FIELD) {
Shadow.Kind kind;
if (method.getReturnType().equals(ResolvedTypeX.VOID)) {
kind = Shadow.FieldSet;
} else {
kind = Shadow.FieldGet;
}
match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow,
kind, declaredSig),
shadowAccumulator);
} else {
AjAttribute.EffectiveSignatureAttribute effectiveSig =
declaredSig.getEffectiveSignature();
if (effectiveSig == null) return;
//System.err.println("call to inter-type member: " + effectiveSig);
if (effectiveSig.isWeaveBody()) return;
match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow,
effectiveSig.getShadowKind(), effectiveSig.getEffectiveSignature()),
shadowAccumulator);
}
} else {
match(
BcelShadow.makeMethodCall(world, mg, ih, enclosingShadow),
shadowAccumulator);
}
}
private boolean match(BcelShadow shadow, List shadowAccumulator) {
//System.err.println("match: " + shadow);
boolean isMatched = false;
for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) {
ShadowMunger munger = (ShadowMunger)i.next();
if (munger.match(shadow, world)) {
shadow.addMunger(munger);
isMatched = true;
}
}
if (isMatched) shadowAccumulator.add(shadow);
return isMatched;
}
// ----
private void implement(LazyMethodGen mg) {
List shadows = mg.matchedShadows;
if (shadows == null) return;
// We depend on a partial order such that inner shadows are earlier on the list
// than outer shadows. That's fine. This order is preserved if:
// A preceeds B iff B.getStart() is LATER THAN A.getStart().
for (Iterator i = shadows.iterator(); i.hasNext(); ) {
BcelShadow shadow = (BcelShadow)i.next();
shadow.implement();
}
mg.matchedShadows = null;
}
// ----
public LazyClassGen getLazyClassGen() {
return clazz;
}
public List getShadowMungers() {
return shadowMungers;
}
public BcelWorld getWorld() {
return world;
}
}
|
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07: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.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.JavaClass;
import org.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();
}
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 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();
}
}
|
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07:46:40Z
|
weaver/src/org/aspectj/weaver/bcel/BcelWeaver.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.JavaClass;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IProgressListener;
import org.aspectj.util.FileUtil;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.CrosscuttingMembersSet;
import org.aspectj.weaver.IWeaver;
import org.aspectj.weaver.NewParentTypeMunger;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.patterns.DeclareParents;
import org.aspectj.weaver.patterns.FastMatchInfo;
public class BcelWeaver implements IWeaver {
private BcelWorld world;
private CrosscuttingMembersSet xcutSet;
private IProgressListener progressListener = null;
private double progressMade;
private double progressPerClassFile;
public BcelWeaver(BcelWorld world) {
super();
this.world = world;
this.xcutSet = world.getCrosscuttingMembersSet();
}
public BcelWeaver() {
this(new BcelWorld());
}
// ---- fields
private Map sourceJavaClasses = new HashMap(); /* String -> UnwovenClassFile */
private List addedClasses = new ArrayList(); /* List<UnovenClassFile> */
private List deletedTypenames = new ArrayList(); /* List<String> */
private Map resources = new HashMap(); /* String -> UnwovenClassFile */
private boolean needToReweaveWorld = false;
private List shadowMungerList = null; // setup by prepareForWeave
private List typeMungerList = null; // setup by prepareForWeave
private List declareParentsList = null; // setup by prepareForWeave
private ZipOutputStream zipOutputStream;
// ----
// only called for testing
public void setShadowMungers(List l) {
shadowMungerList = l;
}
public void addLibraryAspect(String aspectName) {
ResolvedTypeX type = world.resolve(aspectName);
//System.out.println("type: " + type + " for " + aspectName);
if (type.isAspect()) {
xcutSet.addOrReplaceAspect(type);
} else {
throw new RuntimeException("unimplemented");
}
}
public void addLibraryJarFile(File inFile) throws IOException {
ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered
List addedAspects = new ArrayList();
while (true) {
ZipEntry entry = inStream.getNextEntry();
if (entry == null) break;
if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
continue;
}
ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName());
JavaClass jc = parser.parse();
inStream.closeEntry();
ResolvedTypeX type = world.addSourceObjectType(jc).getResolvedTypeX();
if (type.isAspect()) {
addedAspects.add(type);
}
}
inStream.close();
for (Iterator i = addedAspects.iterator(); i.hasNext();) {
ResolvedTypeX aspectX = (ResolvedTypeX) i.next();
xcutSet.addOrReplaceAspect(aspectX);
}
}
/**
* Add any .class files in the directory to the outdir. Anything other than .class files in
* the directory (or its subdirectories) are considered resources and are also copied.
*
*/
public void addDirectoryContents(File inFile,File outDir) throws IOException {
// Get a list of all files (i.e. everything that isnt a directory)
File[] files = FileUtil.listFiles(inFile,new FileFilter() {
public boolean accept(File f) {
boolean accept = !f.isDirectory();
return accept;
}
});
// For each file, add it either as a real .class file or as a resource
for (int i = 0; i < files.length; i++) {
FileInputStream fis = new FileInputStream(files[i]);
byte[] bytes = FileUtil.readAsByteArray(fis);
// String relativePath = files[i].getPath();
// ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
// or we are in trouble...
String filename = files[i].getAbsolutePath().substring(
inFile.getAbsolutePath().length()+1);
UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir,filename).getAbsolutePath(),bytes);
if (filename.endsWith(".class")) {
// System.err.println("BCELWeaver: processing class from input directory "+classFile);
this.addClassFile(classFile);
} else {
// System.err.println("BCELWeaver: processing resource from input directory "+filename);
addResource(filename,classFile);
}
fis.close();
}
}
/** Adds all class files in the jar
*/
public void addJarFile(File inFile, File outDir, boolean canBeDirectory) throws IOException {
// System.err.println("? addJarFile(" + inFile + ", " + outDir + ")");
needToReweaveWorld = true;
// Is this a directory we are looking at?
if (inFile.isDirectory() && canBeDirectory) {
addDirectoryContents(inFile,outDir);
} else {
ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered
while (true) {
ZipEntry entry = inStream.getNextEntry();
if (entry == null) break;
byte[] bytes = FileUtil.readAsByteArray(inStream);
String filename = entry.getName();
UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes);
if (filename.endsWith(".class")) {
this.addClassFile(classFile);
}
else if (!entry.isDirectory()) {
/* bug-44190 Copy meta-data */
addResource(filename,classFile);
}
inStream.closeEntry();
}
inStream.close();
}
}
public void addResource(String name, File inPath, File outDir) throws IOException {
/* Eliminate CVS files. Relative paths use "/" */
if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) {
// System.err.println("? addResource('" + name + "')");
// BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(inPath));
// byte[] bytes = new byte[(int)inPath.length()];
// inStream.read(bytes);
// inStream.close();
byte[] bytes = FileUtil.readAsByteArray(inPath);
UnwovenClassFile resourceFile = new UnwovenClassFile(new File(outDir, name).getAbsolutePath(), bytes);
addResource(name,resourceFile);
}
}
/** Should be addOrReplace
*/
public void addClassFile(UnwovenClassFile classFile) {
addedClasses.add(classFile);
if (null != sourceJavaClasses.put(classFile.getClassName(), classFile)) {
// throw new RuntimeException(classFile.getClassName());
}
world.addSourceObjectType(classFile.getJavaClass());
}
public void deleteClassFile(String typename) {
deletedTypenames.add(typename);
sourceJavaClasses.remove(typename);
world.deleteSourceObjectType(TypeX.forName(typename));
}
public void addResource (String name, UnwovenClassFile resourceFile) {
/* bug-44190 Change error to warning and copy first resource */
if (!resources.containsKey(name)) {
resources.put(name, resourceFile);
}
else {
world.showMessage(IMessage.WARNING, "duplicate resource: '" + name + "'",
null, null);
}
}
// ---- weave preparation
public void prepareForWeave() {
needToReweaveWorld = false;
// update mungers
for (Iterator i = addedClasses.iterator(); i.hasNext(); ) {
UnwovenClassFile jc = (UnwovenClassFile)i.next();
String name = jc.getClassName();
ResolvedTypeX type = world.resolve(name);
//System.err.println("added: " + type + " aspect? " + type.isAspect());
if (type.isAspect()) {
needToReweaveWorld |= xcutSet.addOrReplaceAspect(type);
}
}
for (Iterator i = deletedTypenames.iterator(); i.hasNext(); ) {
String name = (String)i.next();
if (xcutSet.deleteAspect(TypeX.forName(name))) needToReweaveWorld = true;
}
shadowMungerList = xcutSet.getShadowMungers();
typeMungerList = xcutSet.getTypeMungers();
declareParentsList = xcutSet.getDeclareParents();
//XXX this gets us a stable (but completely meaningless) order
Collections.sort(
shadowMungerList,
new Comparator() {
public int compare(Object o1, Object o2) {
return o1.toString().compareTo(o2.toString());
}
});
}
public void dumpUnwoven(File file) throws IOException {
BufferedOutputStream os = FileUtil.makeOutputStream(file);
this.zipOutputStream = new ZipOutputStream(os);
dumpUnwoven();
/* BUG 40943*/
dumpResourcesToOutJar();
zipOutputStream.close(); //this flushes and closes the acutal file
}
public void dumpUnwoven() throws IOException {
Collection filesToDump = new HashSet(sourceJavaClasses.values());
for (Iterator i = filesToDump.iterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
dumpUnchanged(classFile);
}
}
public void dumpResourcesToOutPath() throws IOException {
// System.err.println("? dumpResourcesToOutPath() resources=" + resources.keySet());
Iterator i = resources.keySet().iterator();
while (i.hasNext()) {
UnwovenClassFile res = (UnwovenClassFile)resources.get(i.next());
dumpUnchanged(res);
}
}
/* BUG #40943 */
public void dumpResourcesToOutJar() throws IOException {
// System.err.println("? dumpResourcesToOutJar() resources=" + resources.keySet());
Iterator i = resources.keySet().iterator();
while (i.hasNext()) {
String name = (String)i.next();
UnwovenClassFile res = (UnwovenClassFile)resources.get(name);
writeZipEntry(name,res.getBytes());
}
}
// ---- weaving
public Collection weave(File file) throws IOException {
OutputStream os = FileUtil.makeOutputStream(file);
this.zipOutputStream = new ZipOutputStream(os);
Collection c = weave();
/* BUG 40943*/
dumpResourcesToOutJar();
zipOutputStream.close(); //this flushes and closes the acutal file
return c;
}
public Collection weave() throws IOException {
prepareForWeave();
Collection filesToWeave;
if (needToReweaveWorld) {
filesToWeave = sourceJavaClasses.values();
} else {
filesToWeave = addedClasses;
}
Collection wovenClassNames = new ArrayList();
world.showMessage(IMessage.INFO, "might need to weave " + filesToWeave +
"(world=" + needToReweaveWorld + ")", null, null);
//System.err.println("typeMungers: " + typeMungerList);
// clear all state from files we'll be reweaving
for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
String className = classFile.getClassName();
BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
classType.resetState();
}
//XXX this isn't quite the right place for this...
for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
String className = classFile.getClassName();
ResolvedTypeX onType = world.resolve(className);
weave(onType);
}
// first weave into aspects
for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
String className = classFile.getClassName();
BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
if (classType.isAspect()) {
weave(classFile, classType);
wovenClassNames.add(className);
}
}
// then weave into non-aspects
for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
String className = classFile.getClassName();
BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
if (! classType.isAspect()) {
weave(classFile, classType);
wovenClassNames.add(className);
}
}
if (zipOutputStream != null && !needToReweaveWorld) {
Collection filesToDump = new HashSet(sourceJavaClasses.values());
filesToDump.removeAll(filesToWeave);
for (Iterator i = filesToDump.iterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
dumpUnchanged(classFile);
}
}
addedClasses = new ArrayList();
deletedTypenames = new ArrayList();
return wovenClassNames;
}
public void weave(ResolvedTypeX onType) {
onType.clearInterTypeMungers();
// need to do any declare parents before the matching below
for (Iterator i = declareParentsList.iterator(); i.hasNext(); ) {
DeclareParents p = (DeclareParents)i.next();
List newParents = p.findMatchingNewParents(onType);
if (!newParents.isEmpty()) {
BcelObjectType classType = BcelWorld.getBcelObjectType(onType);
//System.err.println("need to do declare parents for: " + onType);
for (Iterator j = newParents.iterator(); j.hasNext(); ) {
ResolvedTypeX newParent = (ResolvedTypeX)j.next();
if (newParent.isClass()) {
world.showMessage(IMessage.ERROR,
"can't use declare parents to change superclass of binary form \'" +
onType.getName() + "\' (implementation limitation)",
p.getSourceLocation(), null);
continue;
}
classType.addParent(newParent);
ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent);
onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, null));
}
}
}
for (Iterator i = typeMungerList.iterator(); i.hasNext(); ) {
ConcreteTypeMunger m = (ConcreteTypeMunger)i.next();
if (m.matches(onType)) {
onType.addInterTypeMunger(m);
}
}
}
// exposed for ClassLoader dynamic weaving
public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
return weave(classFile, classType, false);
}
// non-private for testing
LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
LazyClassGen ret = weave(classFile, classType, true);
if (progressListener != null) {
progressMade += progressPerClassFile;
progressListener.setProgress(progressMade);
progressListener.setText("woven: " + classFile.getFilename());
}
return ret;
}
private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException {
if (classType.isSynthetic()) {
if (dump) dumpUnchanged(classFile);
return null;
}
// JavaClass javaClass = classType.getJavaClass();
List shadowMungers = fastMatch(shadowMungerList, classType.getResolvedTypeX());
List typeMungers = classType.getResolvedTypeX().getInterTypeMungers();
classType.getResolvedTypeX().checkInterTypeMungers();
LazyClassGen clazz = null;
if (shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect()) {
clazz = classType.getLazyClassGen();
//System.err.println("got lazy gen: " + clazz + ", " + clazz.getWeaverState());
try {
boolean isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers);
if (isChanged) {
if (dump) dump(classFile, clazz);
return clazz;
}
} catch (RuntimeException re) {
System.err.println("trouble in: ");
//XXXclazz.print(System.err);
throw re;
} catch (Error re) {
System.err.println("trouble in: ");
clazz.print(System.err);
throw re;
}
}
// this is very odd return behavior trying to keep everyone happy
if (dump) {
dumpUnchanged(classFile);
return clazz;
} else {
return null;
}
}
// ---- writing
private void dumpUnchanged(UnwovenClassFile classFile) throws IOException {
if (zipOutputStream != null) {
writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes());
} else {
classFile.writeUnchangedBytes();
}
}
private String getEntryName(String className) {
//XXX what does bcel's getClassName do for inner names
return className.replace('.', '/') + ".class";
}
private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException {
if (zipOutputStream != null) {
String mainClassName = classFile.getJavaClass().getClassName();
writeZipEntry(getEntryName(mainClassName),
clazz.getJavaClass(world).getBytes());
if (!clazz.getChildClasses(world).isEmpty()) {
for (Iterator i = clazz.getChildClasses(world).iterator(); i.hasNext();) {
UnwovenClassFile.ChildClass c = (UnwovenClassFile.ChildClass) i.next();
writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes);
}
}
} else {
classFile.writeWovenBytes(
clazz.getJavaClass(world).getBytes(),
clazz.getChildClasses(world)
);
}
}
private void writeZipEntry(String name, byte[] bytes) throws IOException {
ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right
zipOutputStream.putNextEntry(newEntry);
zipOutputStream.write(bytes);
zipOutputStream.closeEntry();
}
private List fastMatch(List list, ResolvedTypeX type) {
if (list == null) return Collections.EMPTY_LIST;
// here we do the coarsest grained fast match with no kind constraints
// this will remove all obvious non-matches and see if we need to do any weaving
FastMatchInfo info = new FastMatchInfo(type, null);
List result = new ArrayList();
Iterator iter = list.iterator();
while (iter.hasNext()) {
ShadowMunger munger = (ShadowMunger)iter.next();
if (munger.getPointcut().fastMatch(info).maybeTrue()) {
result.add(munger);
}
}
return result;
}
public void setProgressListener(IProgressListener listener, double previousProgress, double progressPerClassFile) {
progressListener = listener;
this.progressMade = previousProgress;
this.progressPerClassFile = progressPerClassFile;
}
}
|
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07:46:40Z
|
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.SortedMap;
import java.util.TreeMap;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.Attribute;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.classfile.Unknown;
import org.apache.bcel.generic.ClassGen;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.FieldGen;
import org.apache.bcel.generic.InstructionConstants;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.PUSH;
import org.apache.bcel.generic.RETURN;
import org.apache.bcel.generic.Type;
import org.aspectj.bridge.IMessage;
import org.aspectj.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.ResolvedTypeX;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverStateInfo;
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;
// ----
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;
Method[] methods = myGen.getMethods();
for (int i = 0; i < methods.length; i++) {
addMethodGen(new LazyMethodGen(methods[i], this));
}
}
// 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 List getMethodGens() {
return methodGens; //???Collections.unmodifiableList(methodGens);
}
private void writeBack(BcelWorld world) {
if (myType != null && myType.getWeaverState() != null) {
myGen.addAttribute(BcelAttributes.bcelAttribute(
new AjAttribute.WeaverState(myType.getWeaverState()),
getConstantPoolGen()));
}
addAjcInitializers();
int len = methodGens.size();
myGen.setMethods(new Method[0]);
calculateSourceDebugExtensionOffsets();
for (int i = 0; i < len; i++) {
LazyMethodGen gen = (LazyMethodGen) methodGens.get(i);
// we skip empty clinits
if (isEmptyClinit(gen)) continue;
myGen.addMethod(gen.getMethod());
}
if (inlinedFiles.size() != 0) {
if (hasSourceDebugExtensionAttribute(myGen)) {
world.showMessage(
IMessage.WARNING,
"overwriting JSR45 information for "
+ getFileName()
+ " (compiler limitation)",
null,
null);
}
myGen.addAttribute(getSourceDebugExtensionAttribute());
}
}
private static boolean hasSourceDebugExtensionAttribute(ClassGen gen) {
ConstantPoolGen pool = gen.getConstantPool();
Attribute[] attrs = gen.getAttributes();
for (int i = 0; i < attrs.length; i++) {
if ("SourceDebugExtension"
.equals(((ConstantUtf8) pool.getConstant(attrs[i].getNameIndex())).getBytes())) {
return true;
}
}
return false;
}
public JavaClass getJavaClass(BcelWorld world) {
writeBack(world);
return myGen.getJavaClass();
}
public void addGeneratedInner(LazyClassGen newClass) {
classGens.add(newClass);
}
public void addInterface(TypeX typeX) {
myGen.addInterface(typeX.getName());
}
public void setSuperClass(TypeX typeX) {
myGen.setSuperclassName(typeX.getName());
}
// non-recursive, may be a bug, ha ha.
private List getClassGens() {
List ret = new ArrayList();
ret.add(this);
ret.addAll(classGens);
return ret;
}
public List getChildClasses(BcelWorld world) {
if (classGens.isEmpty()) return Collections.EMPTY_LIST;
List ret = new ArrayList();
for (Iterator i = classGens.iterator(); i.hasNext();) {
LazyClassGen clazz = (LazyClassGen) i.next();
byte[] bytes = clazz.getJavaClass(world).getBytes();
String name = clazz.getName();
int index = name.lastIndexOf('$');
// XXX this could be bad, check use of dollar signs.
name = name.substring(index+1);
ret.add(new UnwovenClassFile.ChildClass(name, bytes));
}
return ret;
}
public String toString() {
return toShortString();
}
public String toShortString() {
String s =
org.apache.bcel.classfile.Utility.accessToString(myGen.getAccessFlags(), true);
if (s != "")
s += " ";
s += org.apache.bcel.classfile.Utility.classOrInterface(myGen.getAccessFlags());
s += " ";
s += myGen.getClassName();
return s;
}
public String toLongString() {
ByteArrayOutputStream s = new ByteArrayOutputStream();
print(new PrintStream(s));
return new String(s.toByteArray());
}
public void print() { print(System.out); }
public void print(PrintStream out) {
List classGens = getClassGens();
for (Iterator iter = classGens.iterator(); iter.hasNext();) {
LazyClassGen element = (LazyClassGen) iter.next();
element.printOne(out);
if (iter.hasNext()) out.println();
}
}
private void printOne(PrintStream out) {
out.print(toShortString());
out.print(" extends ");
out.print(
org.apache.bcel.classfile.Utility.compactClassName(
myGen.getSuperclassName(),
false));
int size = myGen.getInterfaces().length;
if (size > 0) {
out.print(" implements ");
for (int i = 0; i < size; i++) {
out.print(myGen.getInterfaceNames()[i]);
if (i < size - 1)
out.print(", ");
}
}
out.print(":");
out.println();
// XXX make sure to pass types correctly around, so this doesn't happen.
if (myType != null) {
myType.printWackyStuff(out);
}
Field[] fields = myGen.getFields();
for (int i = 0, len = fields.length; i < len; i++) {
out.print(" ");
out.println(fields[i]);
}
List methodGens = getMethodGens();
for (Iterator iter = methodGens.iterator(); iter.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) iter.next();
// we skip empty clinits
if (isEmptyClinit(gen)) continue;
gen.print(out);
if (iter.hasNext()) out.println();
}
// out.println(" ATTRIBS: " + Arrays.asList(myGen.getAttributes()));
out.println("end " + toShortString());
}
private boolean isEmptyClinit(LazyMethodGen gen) {
if (!gen.getName().equals("<clinit>")) return false;
//System.err.println("checking clinig: " + gen);
InstructionHandle start = gen.getBody().getStart();
while (start != null) {
if (Range.isRangeHandle(start) || (start.getInstruction() instanceof RETURN)) {
start = start.getNext();
} else {
return false;
}
}
return true;
}
public ConstantPoolGen getConstantPoolGen() {
return constantPoolGen;
}
public String getName() {
return myGen.getClassName();
}
public boolean isWoven() {
return myType.getWeaverState() != null;
}
public 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;
ret = new FieldGen(Modifier.STATIC | Modifier.PUBLIC | Modifier.FINAL,
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();
}
public void addField(Field field) {
myGen.addField(field);
}
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()));
}
}
|
36,430
|
Bug 36430 Support -Xreweavable option
| null |
resolved fixed
|
16a0abd
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-24T13:43:56Z
| 2003-04-13T07: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.List;
import org.aspectj.util.FileUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.CrosscuttingMembers;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Test;
public class CflowPointcut extends Pointcut {
private Pointcut entry;
private boolean isBelow;
private int[] freeVars;
/**
* Used to indicate that we're in the context of a cflow when concretizing if's
*
* Will be removed or replaced with something better when we handle this
* as a non-error
*/
public static final ResolvedPointcutDefinition CFLOW_MARKER =
new ResolvedPointcutDefinition(null, 0, null, TypeX.NONE, Pointcut.makeMatchesNothing(Pointcut.RESOLVED));
public CflowPointcut(Pointcut entry, boolean isBelow, int[] freeVars) {
this.entry = entry;
this.isBelow = isBelow;
this.freeVars = freeVars;
}
public FuzzyBoolean fastMatch(FastMatchInfo type) {
return FuzzyBoolean.MAYBE;
}
public FuzzyBoolean match(Shadow shadow) {
//??? this is not maximally efficient
return FuzzyBoolean.MAYBE;
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.CFLOW);
entry.write(s);
s.writeBoolean(isBelow);
FileUtil.writeIntArray(freeVars, s);
writeLocation(s);
}
public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException {
CflowPointcut ret = new CflowPointcut(Pointcut.read(s, context), s.readBoolean(), FileUtil.readIntArray(s));
ret.readLocation(context, s);
return ret;
}
public void resolveBindings(IScope scope, Bindings bindings) {
if (bindings == null) {
entry.resolveBindings(scope, null);
entry.state = RESOLVED;
freeVars = new int[0];
} else {
//??? for if's sake we might need to be more careful here
Bindings entryBindings = new Bindings(bindings.size());
entry.resolveBindings(scope, entryBindings);
entry.state = RESOLVED;
freeVars = entryBindings.getUsedFormals();
bindings.mergeIn(entryBindings, scope);
}
}
public boolean equals(Object other) {
if (!(other instanceof CflowPointcut)) return false;
CflowPointcut o = (CflowPointcut)other;
return o.entry.equals(this.entry) && o.isBelow == this.isBelow;
}
public int hashCode() {
int result = 17;
result = 37*result + entry.hashCode();
result = 37*result + (isBelow ? 0 : 1);
return result;
}
public String toString() {
return "cflow" + (isBelow ? "below" : "") + "(" + entry + ")";
}
public Test findResidue(Shadow shadow, ExposedState state) {
throw new RuntimeException("unimplemented");
}
public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) {
//make this remap from formal positions to arrayIndices
IntMap entryBindings = new IntMap();
for (int i=0, len=freeVars.length; i < len; i++) {
int freeVar = freeVars[i];
//int formalIndex = bindings.get(freeVar);
entryBindings.put(freeVar, i);
}
entryBindings.copyContext(bindings);
//System.out.println(this + " bindings: " + entryBindings);
World world = inAspect.getWorld();
Pointcut concreteEntry;
ResolvedTypeX concreteAspect = bindings.getConcreteAspect();
CrosscuttingMembers xcut = concreteAspect.crosscuttingMembers;
Collection previousCflowEntries = xcut.getCflowEntries();
entryBindings.pushEnclosingDefinition(CFLOW_MARKER);
try {
concreteEntry = entry.concretize(inAspect, entryBindings);
} finally {
entryBindings.popEnclosingDefinitition();
}
List innerCflowEntries = new ArrayList(xcut.getCflowEntries());
innerCflowEntries.removeAll(previousCflowEntries);
ResolvedMember cflowField = new ResolvedMember(
Member.FIELD, concreteAspect, Modifier.STATIC | Modifier.PUBLIC | Modifier.FINAL,
NameMangler.cflowStack(xcut),
TypeX.forName(NameMangler.CFLOW_STACK_TYPE).getSignature());
//System.out.println("adding field to: " + inAspect + " field " + cflowField);
// add field and initializer to inAspect
//XXX and then that info above needs to be mapped down here to help with
//XXX getting the exposed state right
concreteAspect.crosscuttingMembers.addConcreteShadowMunger(
Advice.makeCflowEntry(world, concreteEntry, isBelow, cflowField, freeVars.length, innerCflowEntries));
concreteAspect.crosscuttingMembers.addTypeMunger(
world.makeCflowStackFieldAdder(cflowField));
List slots = new ArrayList();
for (int i=0, len=freeVars.length; i < len; i++) {
int freeVar = freeVars[i];
// we don't need to keep state that isn't actually exposed to advice
//??? this means that we will store some state that we won't actually use, optimize this later
if (!bindings.hasKey(freeVar)) continue;
int formalIndex = bindings.get(freeVar);
ResolvedTypeX formalType =
bindings.getAdviceSignature().getParameterTypes()[formalIndex].resolve(world);
ConcreteCflowPointcut.Slot slot =
new ConcreteCflowPointcut.Slot(formalIndex, formalType, i);
slots.add(slot);
}
return new ConcreteCflowPointcut(cflowField, slots);
}
}
|
51,320
|
Bug 51320 ClasscastException on concretization of if(false)
|
I get the following exception when weaving the attached aspect on the dev build. java.lang.ClassCastException at org.aspectj.weaver.patterns.IfPointcut.concretize1(IfPointcut.java:156) at org.aspectj.weaver.patterns.IfPointcut.concretize(IfPointcut.java:143) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:119) at org.aspectj.weaver.Checker.concretize(Checker.java:35) at org.aspectj.weaver.CrosscuttingMembers. addShadowMunger(CrosscuttingMembers.java:78) at org.aspectj.weaver.CrosscuttingMembers.addDeclare(CrosscuttingMembers. java:102) at org.aspectj.weaver.CrosscuttingMembers.addDeclares(CrosscuttingMembers. java:92) at org.aspectj.weaver.CrosscuttingMembersSet. addAdviceLikeDeclares(CrosscuttingMembersSet.java:65) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment. addAdviceLikeDeclares(AjLookupEnvironment.java:147) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment. completeTypeBindings(AjLookupEnvironment.java:122) at org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java: 300) at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:314) at org.aspectj.ajdt.internal.core.builder.AjBuildManager. performCompilation(AjBuildManager.java:384) at org.aspectj.ajdt.internal.core.builder.AjBuildManager. doBuild(AjBuildManager.java:125) at org.aspectj.ajdt.internal.core.builder.AjBuildManager. batchBuild(AjBuildManager.java:70) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:104) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:53) at org.aspectj.tools.ajc.Main.run(Main.java:234) at org.aspectj.tools.ajc.Main.runMain(Main.java:170) at org.aspectj.tools.ajc.Main.main(Main.java:81)
|
resolved fixed
|
fbc0aa3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-25T11:14:32Z
| 2004-02-07T16:06:40Z
|
tests/bugs/DecwClassCastException.java
| |
51,320
|
Bug 51320 ClasscastException on concretization of if(false)
|
I get the following exception when weaving the attached aspect on the dev build. java.lang.ClassCastException at org.aspectj.weaver.patterns.IfPointcut.concretize1(IfPointcut.java:156) at org.aspectj.weaver.patterns.IfPointcut.concretize(IfPointcut.java:143) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:119) at org.aspectj.weaver.Checker.concretize(Checker.java:35) at org.aspectj.weaver.CrosscuttingMembers. addShadowMunger(CrosscuttingMembers.java:78) at org.aspectj.weaver.CrosscuttingMembers.addDeclare(CrosscuttingMembers. java:102) at org.aspectj.weaver.CrosscuttingMembers.addDeclares(CrosscuttingMembers. java:92) at org.aspectj.weaver.CrosscuttingMembersSet. addAdviceLikeDeclares(CrosscuttingMembersSet.java:65) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment. addAdviceLikeDeclares(AjLookupEnvironment.java:147) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment. completeTypeBindings(AjLookupEnvironment.java:122) at org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java: 300) at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:314) at org.aspectj.ajdt.internal.core.builder.AjBuildManager. performCompilation(AjBuildManager.java:384) at org.aspectj.ajdt.internal.core.builder.AjBuildManager. doBuild(AjBuildManager.java:125) at org.aspectj.ajdt.internal.core.builder.AjBuildManager. batchBuild(AjBuildManager.java:70) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:104) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:53) at org.aspectj.tools.ajc.Main.run(Main.java:234) at org.aspectj.tools.ajc.Main.runMain(Main.java:170) at org.aspectj.tools.ajc.Main.main(Main.java:81)
|
resolved fixed
|
fbc0aa3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-25T11:14:32Z
| 2004-02-07T16:06:40Z
|
weaver/src/org/aspectj/weaver/patterns/ArgsPointcut.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the 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.util.FuzzyBoolean;
import org.aspectj.weaver.BetaException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
/**
* args(arguments)
*
* @author Erik Hilsdale
* @author Jim Hugunin
*/
public class ArgsPointcut extends NameBindingPointcut {
TypePatternList arguments;
public ArgsPointcut(TypePatternList arguments) {
this.arguments = arguments;
}
public FuzzyBoolean fastMatch(FastMatchInfo type) {
return FuzzyBoolean.MAYBE;
}
public FuzzyBoolean match(Shadow shadow) {
FuzzyBoolean ret =
arguments.matches(shadow.getIWorld().resolve(shadow.getArgTypes()), TypePattern.DYNAMIC);
return ret;
}
public 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 postRead(ResolvedTypeX enclosingType) {
arguments.postRead(enclosingType);
}
public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) {
TypePatternList args = arguments.resolveReferences(bindings);
if (inAspect.crosscuttingMembers != null) {
inAspect.crosscuttingMembers.exposeTypes(args.getExactTypes());
}
return new ArgsPointcut(args);
}
private Test findResidueNoEllipsis(Shadow shadow, ExposedState state, TypePattern[] patterns) {
int len = shadow.getArgCount();
//System.err.println("boudn to : " + len + ", " + patterns.length);
if (patterns.length != len) {
return Literal.FALSE;
}
Test ret = Literal.TRUE;
for (int i=0; i < len; i++) {
TypeX argType = shadow.getArgType(i);
TypePattern type = patterns[i];
if (!(type instanceof BindingTypePattern)) {
if (type.matchesInstanceof(shadow.getIWorld().resolve(argType)).alwaysTrue()) {
continue;
}
}
ret = Test.makeAnd(ret,
exposeStateForVar(shadow.getArgVar(i), type, state,shadow.getIWorld()));
}
return ret;
}
public Test findResidue(Shadow shadow, ExposedState state) {
if (arguments.matches(shadow.getIWorld().resolve(shadow.getArgTypes()), TypePattern.DYNAMIC).alwaysFalse()) {
return Literal.FALSE;
}
int ellipsisCount = arguments.ellipsisCount;
if (ellipsisCount == 0) {
return findResidueNoEllipsis(shadow, state, arguments.getTypePatterns());
} else if (ellipsisCount == 1) {
TypePattern[] patternsWithEllipsis = arguments.getTypePatterns();
TypePattern[] patternsWithoutEllipsis = new TypePattern[shadow.getArgCount()];
int lenWithEllipsis = patternsWithEllipsis.length;
int lenWithoutEllipsis = patternsWithoutEllipsis.length;
// l1+1 >= l0
int indexWithEllipsis = 0;
int indexWithoutEllipsis = 0;
while (indexWithoutEllipsis < lenWithoutEllipsis) {
TypePattern p = patternsWithEllipsis[indexWithEllipsis++];
if (p == TypePattern.ELLIPSIS) {
int newLenWithoutEllipsis =
lenWithoutEllipsis - (lenWithEllipsis-indexWithEllipsis);
while (indexWithoutEllipsis < newLenWithoutEllipsis) {
patternsWithoutEllipsis[indexWithoutEllipsis++] = TypePattern.ANY;
}
} else {
patternsWithoutEllipsis[indexWithoutEllipsis++] = p;
}
}
return findResidueNoEllipsis(shadow, state, patternsWithoutEllipsis);
} else {
throw new BetaException("unimplemented");
}
}
public String toString() {
return "args" + arguments.toString() + "";
}
}
|
51,320
|
Bug 51320 ClasscastException on concretization of if(false)
|
I get the following exception when weaving the attached aspect on the dev build. java.lang.ClassCastException at org.aspectj.weaver.patterns.IfPointcut.concretize1(IfPointcut.java:156) at org.aspectj.weaver.patterns.IfPointcut.concretize(IfPointcut.java:143) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:119) at org.aspectj.weaver.Checker.concretize(Checker.java:35) at org.aspectj.weaver.CrosscuttingMembers. addShadowMunger(CrosscuttingMembers.java:78) at org.aspectj.weaver.CrosscuttingMembers.addDeclare(CrosscuttingMembers. java:102) at org.aspectj.weaver.CrosscuttingMembers.addDeclares(CrosscuttingMembers. java:92) at org.aspectj.weaver.CrosscuttingMembersSet. addAdviceLikeDeclares(CrosscuttingMembersSet.java:65) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment. addAdviceLikeDeclares(AjLookupEnvironment.java:147) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment. completeTypeBindings(AjLookupEnvironment.java:122) at org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java: 300) at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:314) at org.aspectj.ajdt.internal.core.builder.AjBuildManager. performCompilation(AjBuildManager.java:384) at org.aspectj.ajdt.internal.core.builder.AjBuildManager. doBuild(AjBuildManager.java:125) at org.aspectj.ajdt.internal.core.builder.AjBuildManager. batchBuild(AjBuildManager.java:70) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:104) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:53) at org.aspectj.tools.ajc.Main.run(Main.java:234) at org.aspectj.tools.ajc.Main.runMain(Main.java:170) at org.aspectj.tools.ajc.Main.main(Main.java:81)
|
resolved fixed
|
fbc0aa3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-25T11:14:32Z
| 2004-02-07T16:06:40Z
|
weaver/src/org/aspectj/weaver/patterns/CflowPointcut.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.aspectj.util.FileUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.CrosscuttingMembers;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Test;
public class CflowPointcut extends Pointcut {
private Pointcut entry;
private boolean isBelow;
private int[] freeVars;
/**
* Used to indicate that we're in the context of a cflow when concretizing if's
*
* Will be removed or replaced with something better when we handle this
* as a non-error
*/
public static final ResolvedPointcutDefinition CFLOW_MARKER =
new ResolvedPointcutDefinition(null, 0, null, TypeX.NONE, Pointcut.makeMatchesNothing(Pointcut.RESOLVED));
public CflowPointcut(Pointcut entry, boolean isBelow, int[] freeVars) {
this.entry = entry;
this.isBelow = isBelow;
this.freeVars = freeVars;
}
public FuzzyBoolean fastMatch(FastMatchInfo type) {
return FuzzyBoolean.MAYBE;
}
public FuzzyBoolean match(Shadow shadow) {
//??? this is not maximally efficient
return FuzzyBoolean.MAYBE;
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.CFLOW);
entry.write(s);
s.writeBoolean(isBelow);
FileUtil.writeIntArray(freeVars, s);
writeLocation(s);
}
public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException {
CflowPointcut ret = new CflowPointcut(Pointcut.read(s, context), s.readBoolean(), FileUtil.readIntArray(s));
ret.readLocation(context, s);
return ret;
}
public void resolveBindings(IScope scope, Bindings bindings) {
if (bindings == null) {
entry.resolveBindings(scope, null);
entry.state = RESOLVED;
freeVars = new int[0];
} else {
//??? for if's sake we might need to be more careful here
Bindings entryBindings = new Bindings(bindings.size());
entry.resolveBindings(scope, entryBindings);
entry.state = RESOLVED;
freeVars = entryBindings.getUsedFormals();
bindings.mergeIn(entryBindings, scope);
}
}
public boolean equals(Object other) {
if (!(other instanceof CflowPointcut)) return false;
CflowPointcut o = (CflowPointcut)other;
return o.entry.equals(this.entry) && o.isBelow == this.isBelow;
}
public int hashCode() {
int result = 17;
result = 37*result + entry.hashCode();
result = 37*result + (isBelow ? 0 : 1);
return result;
}
public String toString() {
return "cflow" + (isBelow ? "below" : "") + "(" + entry + ")";
}
public Test findResidue(Shadow shadow, ExposedState state) {
throw new RuntimeException("unimplemented");
}
public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) {
//make this remap from formal positions to arrayIndices
IntMap entryBindings = new IntMap();
for (int i=0, len=freeVars.length; i < len; i++) {
int freeVar = freeVars[i];
//int formalIndex = bindings.get(freeVar);
entryBindings.put(freeVar, i);
}
entryBindings.copyContext(bindings);
//System.out.println(this + " bindings: " + entryBindings);
World world = inAspect.getWorld();
Pointcut concreteEntry;
ResolvedTypeX concreteAspect = bindings.getConcreteAspect();
CrosscuttingMembers xcut = concreteAspect.crosscuttingMembers;
Collection previousCflowEntries = xcut.getCflowEntries();
entryBindings.pushEnclosingDefinition(CFLOW_MARKER);
try {
concreteEntry = entry.concretize(inAspect, entryBindings);
} finally {
entryBindings.popEnclosingDefinitition();
}
List innerCflowEntries = new ArrayList(xcut.getCflowEntries());
innerCflowEntries.removeAll(previousCflowEntries);
ResolvedMember cflowField = new ResolvedMember(
Member.FIELD, concreteAspect, Modifier.STATIC | Modifier.PUBLIC | Modifier.FINAL,
NameMangler.cflowStack(xcut),
TypeX.forName(NameMangler.CFLOW_STACK_TYPE).getSignature());
//System.out.println("adding field to: " + inAspect + " field " + cflowField);
// add field and initializer to inAspect
//XXX and then that info above needs to be mapped down here to help with
//XXX getting the exposed state right
concreteAspect.crosscuttingMembers.addConcreteShadowMunger(
Advice.makeCflowEntry(world, concreteEntry, isBelow, cflowField, freeVars.length, innerCflowEntries,inAspect));
concreteAspect.crosscuttingMembers.addTypeMunger(
world.makeCflowStackFieldAdder(cflowField));
List slots = new ArrayList();
for (int i=0, len=freeVars.length; i < len; i++) {
int freeVar = freeVars[i];
// we don't need to keep state that isn't actually exposed to advice
//??? this means that we will store some state that we won't actually use, optimize this later
if (!bindings.hasKey(freeVar)) continue;
int formalIndex = bindings.get(freeVar);
ResolvedTypeX formalType =
bindings.getAdviceSignature().getParameterTypes()[formalIndex].resolve(world);
ConcreteCflowPointcut.Slot slot =
new ConcreteCflowPointcut.Slot(formalIndex, formalType, i);
slots.add(slot);
}
return new ConcreteCflowPointcut(cflowField, slots);
}
}
|
51,320
|
Bug 51320 ClasscastException on concretization of if(false)
|
I get the following exception when weaving the attached aspect on the dev build. java.lang.ClassCastException at org.aspectj.weaver.patterns.IfPointcut.concretize1(IfPointcut.java:156) at org.aspectj.weaver.patterns.IfPointcut.concretize(IfPointcut.java:143) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:119) at org.aspectj.weaver.Checker.concretize(Checker.java:35) at org.aspectj.weaver.CrosscuttingMembers. addShadowMunger(CrosscuttingMembers.java:78) at org.aspectj.weaver.CrosscuttingMembers.addDeclare(CrosscuttingMembers. java:102) at org.aspectj.weaver.CrosscuttingMembers.addDeclares(CrosscuttingMembers. java:92) at org.aspectj.weaver.CrosscuttingMembersSet. addAdviceLikeDeclares(CrosscuttingMembersSet.java:65) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment. addAdviceLikeDeclares(AjLookupEnvironment.java:147) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment. completeTypeBindings(AjLookupEnvironment.java:122) at org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java: 300) at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:314) at org.aspectj.ajdt.internal.core.builder.AjBuildManager. performCompilation(AjBuildManager.java:384) at org.aspectj.ajdt.internal.core.builder.AjBuildManager. doBuild(AjBuildManager.java:125) at org.aspectj.ajdt.internal.core.builder.AjBuildManager. batchBuild(AjBuildManager.java:70) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:104) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:53) at org.aspectj.tools.ajc.Main.run(Main.java:234) at org.aspectj.tools.ajc.Main.runMain(Main.java:170) at org.aspectj.tools.ajc.Main.main(Main.java:81)
|
resolved fixed
|
fbc0aa3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-25T11:14:32Z
| 2004-02-07T16:06:40Z
|
weaver/src/org/aspectj/weaver/patterns/IfPointcut.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.aspectj.bridge.IMessage;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.ast.*;
import org.aspectj.weaver.ast.Expr;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
public class IfPointcut extends Pointcut {
public ResolvedMember testMethod;
public int extraParameterFlags;
public Pointcut residueSource;
int baseArgsCount;
//XXX some way to compute args
public IfPointcut(ResolvedMember testMethod, int extraParameterFlags) {
this.testMethod = testMethod;
this.extraParameterFlags = extraParameterFlags;
}
public FuzzyBoolean fastMatch(FastMatchInfo type) {
return FuzzyBoolean.MAYBE;
}
public FuzzyBoolean match(Shadow shadow) {
//??? this is not maximally efficient
return FuzzyBoolean.MAYBE;
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.IF);
testMethod.write(s);
s.writeByte(extraParameterFlags);
writeLocation(s);
}
public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException {
IfPointcut ret = new IfPointcut(ResolvedMember.readResolvedMember(s, context), s.readByte());
ret.readLocation(context, s);
return ret;
}
public void resolveBindings(IScope scope, Bindings bindings) {
//??? all we need is good error messages in here in cflow contexts
}
public boolean equals(Object other) {
if (!(other instanceof IfPointcut)) return false;
IfPointcut o = (IfPointcut)other;
return o.testMethod.equals(this.testMethod);
}
public int hashCode() {
int result = 17;
result = 37*result + testMethod.hashCode();
return result;
}
public String toString() {
return "if(" + testMethod + ")";
}
//??? The implementation of name binding and type checking in if PCDs is very convoluted
// There has to be a better way...
private boolean findingResidue = false;
public Test findResidue(Shadow shadow, ExposedState state) {
if (findingResidue) return Literal.TRUE;
findingResidue = true;
try {
ExposedState myState = new ExposedState(baseArgsCount);
//System.out.println(residueSource);
//??? we throw out the test that comes from this walk. All we want here
// is bindings for the arguments
residueSource.findResidue(shadow, myState);
//System.out.println(myState);
Test ret = Literal.TRUE;
List args = new ArrayList();
for (int i=0; i < baseArgsCount; i++) {
Var v = myState.get(i);
args.add(v);
ret = Test.makeAnd(ret,
Test.makeInstanceof(v,
testMethod.getParameterTypes()[i].resolve(shadow.getIWorld())));
}
// handle thisJoinPoint parameters
if ((extraParameterFlags & Advice.ThisJoinPoint) != 0) {
args.add(shadow.getThisJoinPointVar());
}
if ((extraParameterFlags & Advice.ThisJoinPointStaticPart) != 0) {
args.add(shadow.getThisJoinPointStaticPartVar());
}
if ((extraParameterFlags & Advice.ThisEnclosingJoinPointStaticPart) != 0) {
args.add(shadow.getThisEnclosingJoinPointStaticPartVar());
}
ret = Test.makeAnd(ret, Test.makeCall(testMethod, (Expr[])args.toArray(new Expr[args.size()])));
return ret;
} finally {
findingResidue = false;
}
}
public Pointcut concretize(ResolvedTypeX inAspect, IntMap bindings) {
return this.concretize1(inAspect, bindings);
}
private IfPointcut partiallyConcretized = null;
public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) {
//System.err.println("concretize: " + this + " already: " + partiallyConcretized);
if (partiallyConcretized != null) {
return partiallyConcretized;
}
IfPointcut ret = new IfPointcut(testMethod, extraParameterFlags);
partiallyConcretized = ret;
if (bindings.directlyInAdvice()) {
ShadowMunger advice = bindings.getEnclosingAdvice();
ret.baseArgsCount = ((Advice)advice).getBaseParameterCount();
ret.residueSource = advice.getPointcut().concretize(inAspect, ret.baseArgsCount, advice);
} else {
ResolvedPointcutDefinition def = bindings.peekEnclosingDefinitition();
if (def == CflowPointcut.CFLOW_MARKER) {
inAspect.getWorld().showMessage(IMessage.ERROR,
"if not supported lexically within cflow (compiler limitation)",
getSourceLocation(), null);
return Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
}
ret.baseArgsCount = def.getParameterTypes().length;
IntMap newBindings = IntMap.idMap(ret.baseArgsCount);
newBindings.copyContext(bindings);
ret.residueSource = def.getPointcut().concretize(inAspect, newBindings);
}
return ret;
}
}
|
51,320
|
Bug 51320 ClasscastException on concretization of if(false)
|
I get the following exception when weaving the attached aspect on the dev build. java.lang.ClassCastException at org.aspectj.weaver.patterns.IfPointcut.concretize1(IfPointcut.java:156) at org.aspectj.weaver.patterns.IfPointcut.concretize(IfPointcut.java:143) at org.aspectj.weaver.patterns.Pointcut.concretize(Pointcut.java:119) at org.aspectj.weaver.Checker.concretize(Checker.java:35) at org.aspectj.weaver.CrosscuttingMembers. addShadowMunger(CrosscuttingMembers.java:78) at org.aspectj.weaver.CrosscuttingMembers.addDeclare(CrosscuttingMembers. java:102) at org.aspectj.weaver.CrosscuttingMembers.addDeclares(CrosscuttingMembers. java:92) at org.aspectj.weaver.CrosscuttingMembersSet. addAdviceLikeDeclares(CrosscuttingMembersSet.java:65) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment. addAdviceLikeDeclares(AjLookupEnvironment.java:147) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment. completeTypeBindings(AjLookupEnvironment.java:122) at org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java: 300) at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:314) at org.aspectj.ajdt.internal.core.builder.AjBuildManager. performCompilation(AjBuildManager.java:384) at org.aspectj.ajdt.internal.core.builder.AjBuildManager. doBuild(AjBuildManager.java:125) at org.aspectj.ajdt.internal.core.builder.AjBuildManager. batchBuild(AjBuildManager.java:70) at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:104) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java:53) at org.aspectj.tools.ajc.Main.run(Main.java:234) at org.aspectj.tools.ajc.Main.runMain(Main.java:170) at org.aspectj.tools.ajc.Main.main(Main.java:81)
|
resolved fixed
|
fbc0aa3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-02-25T11:14:32Z
| 2004-02-07T16:06:40Z
|
weaver/src/org/aspectj/weaver/patterns/ThisOrTargetPointcut.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the 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.IntMap;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
import org.aspectj.weaver.ast.Var;
//
/**
* Corresponds to target or this pcd.
*
* <p>type is initially a WildTypePattern. If it stays that way, it's a this(Foo)
* type deal.
* however, the resolveBindings method may convert it to a BindingTypePattern,
* in which
* case, it's a this(foo) type deal.
*
* @author Erik Hilsdale
* @author Jim Hugunin
*/
public class ThisOrTargetPointcut extends NameBindingPointcut {
private boolean isThis;
private TypePattern type;
public ThisOrTargetPointcut(boolean isThis, TypePattern type) {
this.isThis = isThis;
this.type = type;
}
public FuzzyBoolean fastMatch(FastMatchInfo type) {
return FuzzyBoolean.MAYBE;
}
private boolean couldMatch(Shadow shadow) {
return isThis ? shadow.hasThis() : shadow.hasTarget();
}
public FuzzyBoolean match(Shadow shadow) {
if (!couldMatch(shadow)) return FuzzyBoolean.NO;
TypeX typeToMatch = isThis ? shadow.getThisType() : shadow.getTargetType();
//if (typeToMatch == ResolvedTypeX.MISSING) return FuzzyBoolean.NO;
return type.matches(typeToMatch.resolve(shadow.getIWorld()), TypePattern.DYNAMIC);
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Pointcut.THIS_OR_TARGET);
s.writeBoolean(isThis);
type.write(s);
writeLocation(s);
}
public static Pointcut read(DataInputStream s, ISourceContext context) throws IOException {
boolean isThis = s.readBoolean();
TypePattern type = TypePattern.read(s, context);
ThisOrTargetPointcut ret = new ThisOrTargetPointcut(isThis, type);
ret.readLocation(context, s);
return ret;
}
public void resolveBindings(IScope scope, Bindings bindings) {
type = type.resolveBindings(scope, bindings, true, true);
// ??? handle non-formal
}
public void postRead(ResolvedTypeX enclosingType) {
type.postRead(enclosingType);
}
public boolean equals(Object other) {
if (!(other instanceof ThisOrTargetPointcut)) return false;
ThisOrTargetPointcut o = (ThisOrTargetPointcut)other;
return o.isThis == this.isThis && o.type.equals(this.type);
}
public int hashCode() {
int result = 17;
result = 37*result + (isThis ? 0 : 1);
result = 37*result + type.hashCode();
return result;
}
public String toString() {
return (isThis ? "this(" : "target(") + type + ")";
}
public Test findResidue(Shadow shadow, ExposedState state) {
if (!couldMatch(shadow)) return Literal.FALSE;
if (type == TypePattern.ANY) return Literal.TRUE;
Var var = isThis ? shadow.getThisVar() : shadow.getTargetVar();
return exposeStateForVar(var, type, state, shadow.getIWorld());
}
public Pointcut concretize1(ResolvedTypeX inAspect, IntMap bindings) {
TypePattern newType = type.remapAdviceFormals(bindings);
if (inAspect.crosscuttingMembers != null) {
inAspect.crosscuttingMembers.exposeType(newType.getExactType());
}
return new ThisOrTargetPointcut(isThis, newType);
}
}
|
52,394
|
Bug 52394 inter-type declarations cause JRockit Crash
| null |
resolved fixed
|
5d73494
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-04T16:09:34Z
| 2004-02-18T18:46:40Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AspectClinit.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.weaver.AjcMemberMaker;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.Clinit;
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.eclipse.jdt.internal.compiler.codegen.ExceptionLabel;
import org.eclipse.jdt.internal.compiler.codegen.Label;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
public class AspectClinit extends Clinit {
private boolean hasPre, hasPost;
private FieldBinding initFailureField;
public AspectClinit(Clinit old, CompilationResult compilationResult, boolean hasPre, boolean hasPost, FieldBinding initFailureField) {
super(compilationResult);
this.needFreeReturn = old.needFreeReturn;
this.sourceEnd = old.sourceEnd;
this.sourceStart = old.sourceStart;
this.declarationSourceEnd = old.declarationSourceEnd;
this.declarationSourceStart = old.declarationSourceStart;
this.hasPre = hasPre;
this.hasPost = hasPost;
this.initFailureField = initFailureField;
}
private ExceptionLabel handlerLabel;
protected void generateSyntheticCode(
ClassScope classScope,
CodeStream codeStream)
{
if (initFailureField != null) {
handlerLabel = new ExceptionLabel(codeStream, classScope.getJavaLangThrowable());
}
if (hasPre) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope);
codeStream.invokestatic(world.makeMethodBindingForCall(
AjcMemberMaker.ajcPreClinitMethod(
EclipseFactory.fromBinding(classScope.referenceContext.binding)
)));
}
super.generateSyntheticCode(classScope, codeStream);
}
protected void generatePostSyntheticCode(
ClassScope classScope,
CodeStream codeStream)
{
super.generatePostSyntheticCode(classScope, codeStream);
if (hasPost) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope);
codeStream.invokestatic(world.makeMethodBindingForCall(
AjcMemberMaker.ajcPostClinitMethod(
EclipseFactory.fromBinding(classScope.referenceContext.binding)
)));
}
if (initFailureField != null) {
handlerLabel.placeEnd();
Label endLabel = new Label(codeStream);
codeStream.goto_(endLabel);
handlerLabel.place();
codeStream.putstatic(initFailureField);
endLabel.place();
}
}
}
|
52,394
|
Bug 52394 inter-type declarations cause JRockit Crash
| null |
resolved fixed
|
5d73494
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-04T16:09:34Z
| 2004-02-18T18:46:40Z
|
weaver/src/org/aspectj/weaver/bcel/BcelClassWeaver.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.bcel.Constants;
import org.apache.bcel.generic.BranchInstruction;
import org.apache.bcel.generic.CPInstruction;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.FieldInstruction;
import org.apache.bcel.generic.INVOKESPECIAL;
import org.apache.bcel.generic.IndexedInstruction;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionConstants;
import org.apache.bcel.generic.InstructionFactory;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.InstructionTargeter;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.LocalVariableInstruction;
import org.apache.bcel.generic.NEW;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.PUTFIELD;
import org.apache.bcel.generic.PUTSTATIC;
import org.apache.bcel.generic.RET;
import org.apache.bcel.generic.ReturnInstruction;
import org.apache.bcel.generic.Select;
import org.apache.bcel.generic.Type;
import org.aspectj.bridge.IMessage;
import org.aspectj.util.PartialOrder;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.IClassWeaver;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.Shadow.Kind;
import org.aspectj.weaver.patterns.FastMatchInfo;
class BcelClassWeaver implements IClassWeaver {
/**
* This is called from {@link BcelWeaver} to perform the per-class weaving process.
*/
public static boolean weave(
BcelWorld world,
LazyClassGen clazz,
List shadowMungers,
List typeMungers)
{
boolean b = new BcelClassWeaver(world, clazz, shadowMungers, typeMungers).weave();
//System.out.println(clazz.getClassName() + ", " + clazz.getType().getWeaverState());
//clazz.print();
return b;
}
// --------------------------------------------
private final LazyClassGen clazz;
private final List shadowMungers;
private final List typeMungers;
private final BcelObjectType ty; // alias of clazz.getType()
private final BcelWorld world; // alias of ty.getWorld()
private final ConstantPoolGen cpg; // alias of clazz.getConstantPoolGen()
private final InstructionFactory fact; // alias of clazz.getFactory();
private final List addedLazyMethodGens = new ArrayList();
private final Set addedDispatchTargets = new HashSet();
// Static setting across BcelClassWeavers
private static boolean inReweavableMode = false;
private static boolean compressReweavableAttributes = false;
private List addedSuperInitializersAsList = null; // List<IfaceInitList>
private final Map addedSuperInitializers = new HashMap(); // Interface -> IfaceInitList
private List addedThisInitializers = new ArrayList(); // List<NewFieldMunger>
private List addedClassInitializers = new ArrayList(); // List<NewFieldMunger>
private BcelShadow clinitShadow = null;
/**
* This holds the initialization and pre-initialization shadows for this class
* that were actually matched by mungers (if no match, then we don't even create the
* shadows really).
*/
private final List initializationShadows = new ArrayList(1);
private BcelClassWeaver(
BcelWorld world,
LazyClassGen clazz,
List shadowMungers,
List typeMungers)
{
super();
// assert world == clazz.getType().getWorld()
this.world = world;
this.clazz = clazz;
this.shadowMungers = shadowMungers;
this.typeMungers = typeMungers;
this.ty = clazz.getBcelObjectType();
this.cpg = clazz.getConstantPoolGen();
this.fact = clazz.getFactory();
fastMatchShadowMungers(shadowMungers);
initializeSuperInitializerMap(ty.getResolvedTypeX());
}
private List[] perKindShadowMungers;
private boolean canMatchBodyShadows = false;
private boolean canMatchInitialization = false;
private void fastMatchShadowMungers(List shadowMungers) {
perKindShadowMungers = new List[Shadow.MAX_SHADOW_KIND+1];
for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) {
Shadow.Kind kind = Shadow.SHADOW_KINDS[i];
ArrayList mungers = new ArrayList(0);
perKindShadowMungers[kind.getKey()] = mungers;
fastMatchShadowMungers(shadowMungers, mungers, kind);
if (mungers.isEmpty()) {
perKindShadowMungers[kind.getKey()] = null;
} else {
if (kind == Shadow.Initialization) {
canMatchInitialization = true;
} else if (!kind.isEnclosingKind()) {
canMatchBodyShadows = true;
}
}
}
}
private boolean canMatch(Shadow.Kind kind) {
return perKindShadowMungers[kind.getKey()] != null;
}
private void fastMatchShadowMungers(List shadowMungers, ArrayList mungers, Kind kind) {
FastMatchInfo info = new FastMatchInfo(clazz.getType(), kind);
for (Iterator i = shadowMungers.iterator(); i.hasNext();) {
ShadowMunger munger = (ShadowMunger) i.next();
if (munger.getPointcut().fastMatch(info).maybeTrue()) mungers.add(munger);
}
}
private void initializeSuperInitializerMap(ResolvedTypeX child) {
ResolvedTypeX[] superInterfaces = child.getDeclaredInterfaces();
for (int i=0, len=superInterfaces.length; i < len; i++) {
if (ty.getResolvedTypeX().isTopmostImplementor(superInterfaces[i])) {
if (addSuperInitializer(superInterfaces[i])) {
initializeSuperInitializerMap(superInterfaces[i]);
}
}
}
}
private boolean addSuperInitializer(ResolvedTypeX onType) {
IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType);
if (l != null) return false;
l = new IfaceInitList(onType);
addedSuperInitializers.put(onType, l);
return true;
}
public void addInitializer(ConcreteTypeMunger cm) {
NewFieldTypeMunger m = (NewFieldTypeMunger) cm.getMunger();
ResolvedTypeX onType = m.getSignature().getDeclaringType().resolve(world);
if (m.getSignature().isStatic()) {
addedClassInitializers.add(cm);
} else {
if (onType == ty.getResolvedTypeX()) {
addedThisInitializers.add(cm);
} else {
IfaceInitList l = (IfaceInitList) addedSuperInitializers.get(onType);
l.list.add(cm);
}
}
}
private static class IfaceInitList implements PartialOrder.PartialComparable {
final ResolvedTypeX onType;
List list = new ArrayList();
IfaceInitList(ResolvedTypeX onType) {
this.onType = onType;
}
public int compareTo(Object other) {
IfaceInitList o = (IfaceInitList)other;
if (onType.isAssignableFrom(o.onType)) return +1;
else if (o.onType.isAssignableFrom(onType)) return -1;
else return 0;
}
public int fallbackCompareTo(Object other) {
return 0;
}
}
// XXX this is being called, but the result doesn't seem to be being used
public boolean addDispatchTarget(ResolvedMember m) {
return addedDispatchTargets.add(m);
}
public void addLazyMethodGen(LazyMethodGen gen) {
addedLazyMethodGens.add(gen);
}
public void addOrReplaceLazyMethodGen(LazyMethodGen mg) {
if (alreadyDefined(clazz, mg)) return;
for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) {
LazyMethodGen existing = (LazyMethodGen)i.next();
if (signaturesMatch(mg, existing)) {
if (existing.definingType == null) {
// this means existing was introduced on the class itself
return;
} else if (mg.definingType.isAssignableFrom(existing.definingType)) {
// existing is mg's subtype and dominates mg
return;
} else if (existing.definingType.isAssignableFrom(mg.definingType)) {
// mg is existing's subtype and dominates existing
i.remove();
addedLazyMethodGens.add(mg);
return;
} else {
throw new BCException("conflict between: " + mg + " and " + existing);
}
}
}
addedLazyMethodGens.add(mg);
}
private boolean alreadyDefined(LazyClassGen clazz, LazyMethodGen mg) {
for (Iterator i = clazz.getMethodGens().iterator(); i.hasNext(); ) {
LazyMethodGen existing = (LazyMethodGen)i.next();
if (signaturesMatch(mg, existing)) {
if (!mg.isAbstract() && existing.isAbstract()) {
i.remove();
return false;
}
return true;
}
}
return false;
}
private boolean signaturesMatch(LazyMethodGen mg, LazyMethodGen existing) {
return mg.getName().equals(existing.getName()) &&
mg.getSignature().equals(existing.getSignature());
}
// ----
public boolean weave() {
if (clazz.isWoven() && !clazz.isReweavable()) {
world.showMessage(IMessage.ERROR,
"class \'" + clazz.getType().getName() + "\' is already woven and has not been built with -Xreweavable",
ty.getSourceLocation(), null);
return false;
}
Set aspectsAffectingType = null;
if (inReweavableMode) aspectsAffectingType = new HashSet();
boolean isChanged = false;
// we want to "touch" all aspects
if (clazz.getType().isAspect()) isChanged = true;
// start by munging all typeMungers
for (Iterator i = typeMungers.iterator(); i.hasNext(); ) {
Object o = i.next();
if ( !(o instanceof BcelTypeMunger) ) {
//???System.err.println("surprising: " + o);
continue;
}
BcelTypeMunger munger = (BcelTypeMunger)o;
boolean typeMungerAffectedType = munger.munge(this);
if (typeMungerAffectedType) {
isChanged = true;
if (inReweavableMode) aspectsAffectingType.add(munger.getAspectType().getName());
}
}
// XXX do major sort of stuff
// sort according to: Major: type hierarchy
// within each list: dominates
// don't forget to sort addedThisInitialiers according to dominates
addedSuperInitializersAsList = new ArrayList(addedSuperInitializers.values());
addedSuperInitializersAsList = PartialOrder.sort(addedSuperInitializersAsList);
if (addedSuperInitializersAsList == null) {
throw new BCException("circularity in inter-types");
}
// this will create a static initializer if there isn't one
// this is in just as bad taste as NOPs
LazyMethodGen staticInit = clazz.getStaticInitializer();
staticInit.getBody().insert(genInitInstructions(addedClassInitializers, true));
// now go through each method, and match against each method. This
// sets up each method's {@link LazyMethodGen#matchedShadows} field,
// and it also possibly adds to {@link #initializationShadows}.
List methodGens = new ArrayList(clazz.getMethodGens());
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen)i.next();
//mg.getBody();
if (! mg.hasBody()) continue;
boolean shadowMungerMatched = match(mg);
if (shadowMungerMatched) {
// For matching mungers, add their declaring aspects to the list that affected this type
if (inReweavableMode) aspectsAffectingType.addAll(findAspectsForMungers(mg));
isChanged = true;
}
}
if (! isChanged) return false;
// now we weave all but the initialization shadows
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen)i.next();
if (! mg.hasBody()) continue;
implement(mg);
}
// if we matched any initialization shadows, we inline and weave
if (! initializationShadows.isEmpty()) {
inlineSelfConstructors(methodGens);
positionAndImplement(initializationShadows);
}
// finally, if we changed, we add in the introduced methods.
if (isChanged) {
clazz.getOrCreateWeaverStateInfo();
weaveInAddedMethods();
}
if (inReweavableMode) {
WeaverStateInfo wsi = clazz.getOrCreateWeaverStateInfo();
wsi.addAspectsAffectingType(aspectsAffectingType);
wsi.setUnwovenClassFileData(ty.getJavaClass().getBytes());
wsi.setReweavable(true,compressReweavableAttributes);
} else {
clazz.getOrCreateWeaverStateInfo().setReweavable(false,false);
}
return isChanged;
}
private Set findAspectsForMungers(LazyMethodGen mg) {
Set aspectsAffectingType = new HashSet();
for (Iterator iter = mg.matchedShadows.iterator(); iter.hasNext();) {
BcelShadow aShadow = (BcelShadow) iter.next();
// Mungers in effect on that shadow
for (Iterator iter2 = aShadow.getMungers().iterator();iter2.hasNext();) {
ShadowMunger aMunger = (ShadowMunger) iter2.next();
if (aMunger instanceof BcelAdvice) {
BcelAdvice bAdvice = (BcelAdvice)aMunger;
aspectsAffectingType.add(bAdvice.getConcreteAspect().getName());
} else {
// It is a 'Checker' - we don't need to remember aspects that only contributed Checkers...
}
}
}
return aspectsAffectingType;
}
private void inlineSelfConstructors(List methodGens) {
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen mg = (LazyMethodGen) i.next();
if (! mg.getName().equals("<init>")) continue;
InstructionHandle ih = findSuperOrThisCall(mg);
if (ih != null && isThisCall(ih)) {
LazyMethodGen donor = getCalledMethod(ih);
inlineMethod(donor, mg, ih);
}
}
}
private void positionAndImplement(List initializationShadows) {
for (Iterator i = initializationShadows.iterator(); i.hasNext(); ) {
BcelShadow s = (BcelShadow) i.next();
positionInitializationShadow(s);
//s.getEnclosingMethod().print();
s.implement();
}
}
private void positionInitializationShadow(BcelShadow s) {
LazyMethodGen mg = s.getEnclosingMethod();
InstructionHandle call = findSuperOrThisCall(mg);
InstructionList body = mg.getBody();
ShadowRange r = new ShadowRange(body);
r.associateWithShadow((BcelShadow) s);
if (s.getKind() == Shadow.PreInitialization) {
// XXX assert first instruction is an ALOAD_0.
// a pre shadow goes from AFTER the first instruction (which we believe to
// be an ALOAD_0) to just before the call to super
r.associateWithTargets(
Range.genStart(body, body.getStart().getNext()),
Range.genEnd(body, call.getPrev()));
} else {
// assert s.getKind() == Shadow.Initialization
r.associateWithTargets(
Range.genStart(body, call.getNext()),
Range.genEnd(body));
}
}
private boolean isThisCall(InstructionHandle ih) {
INVOKESPECIAL inst = (INVOKESPECIAL) ih.getInstruction();
return inst.getClassName(cpg).equals(clazz.getName());
}
/** inline a particular call in bytecode.
*
* @param donor the method we want to inline
* @param recipient the method containing the call we want to inline
* @param call the instructionHandle in recipient's body holding the call we want to
* inline.
*/
public static void inlineMethod(
LazyMethodGen donor,
LazyMethodGen recipient,
InstructionHandle call)
{
// assert recipient.contains(call)
/* Implementation notes:
*
* We allocate two slots for every tempvar so we don't screw up
* longs and doubles which may share space. This could be conservatively avoided
* (no reference to a long/double instruction, don't do it) or packed later.
* Right now we don't bother to pack.
*
* Allocate a new var for each formal param of the inlined. Fill with stack
* contents. Then copy the inlined instructions in with the appropriate remap
* table. Any framelocs used by locals in inlined are reallocated to top of
* frame,
*/
final InstructionFactory fact = recipient.getEnclosingClass().getFactory();
IntMap frameEnv = new IntMap();
// this also sets up the initial environment
InstructionList argumentStores =
genArgumentStores(donor, recipient, frameEnv, fact);
InstructionList inlineInstructions =
genInlineInstructions(donor, recipient, frameEnv, fact, false);
inlineInstructions.insert(argumentStores);
recipient.getBody().append(call, inlineInstructions);
Utility.deleteInstruction(call, recipient);
}
/** generate the instructions to be inlined.
*
* @param donor the method from which we will copy (and adjust frame and jumps)
* instructions.
* @param recipient the method the instructions will go into. Used to get the frame
* size so we can allocate new frame locations for locals in donor.
* @param frameEnv an environment to map from donor frame to recipient frame,
* initially populated with argument locations.
* @param fact an instruction factory for recipient
*/
static InstructionList genInlineInstructions(
LazyMethodGen donor,
LazyMethodGen recipient,
IntMap frameEnv,
InstructionFactory fact,
boolean keepReturns)
{
InstructionList footer = new InstructionList();
InstructionHandle end = footer.append(InstructionConstants.NOP);
InstructionList ret = new InstructionList();
InstructionList sourceList = donor.getBody();
Map srcToDest = new HashMap();
ConstantPoolGen donorCpg = donor.getEnclosingClass().getConstantPoolGen();
ConstantPoolGen recipientCpg = recipient.getEnclosingClass().getConstantPoolGen();
boolean isAcrossClass = donorCpg != recipientCpg;
// first pass: copy the instructions directly, populate the srcToDest map,
// fix frame instructions
for (InstructionHandle src = sourceList.getStart();
src != null;
src = src.getNext())
{
Instruction fresh = Utility.copyInstruction(src.getInstruction());
InstructionHandle dest;
if (fresh instanceof CPInstruction) {
// need to reset index to go to new constant pool. This is totally
// a computation leak... we're testing this LOTS of times. Sigh.
if (isAcrossClass) {
CPInstruction cpi = (CPInstruction) fresh;
cpi.setIndex(
recipientCpg.addConstant(
donorCpg.getConstant(cpi.getIndex()),
donorCpg));
}
}
if (src.getInstruction() == Range.RANGEINSTRUCTION) {
dest = ret.append(Range.RANGEINSTRUCTION);
} else if (fresh instanceof ReturnInstruction) {
if (keepReturns) {
dest = ret.append(fresh);
} else {
dest =
ret.append(InstructionFactory.createBranchInstruction(Constants.GOTO, end));
}
} else if (fresh instanceof BranchInstruction) {
dest = ret.append((BranchInstruction) fresh);
} else if (
fresh instanceof LocalVariableInstruction || fresh instanceof RET) {
IndexedInstruction indexed = (IndexedInstruction) fresh;
int oldIndex = indexed.getIndex();
int freshIndex;
if (!frameEnv.hasKey(oldIndex)) {
freshIndex = recipient.allocateLocal(2);
frameEnv.put(oldIndex, freshIndex);
} else {
freshIndex = frameEnv.get(oldIndex);
}
indexed.setIndex(freshIndex);
dest = ret.append(fresh);
} else {
dest = ret.append(fresh);
}
srcToDest.put(src, dest);
}
// second pass: retarget branch instructions, copy ranges and tags
Map tagMap = new HashMap();
Map shadowMap = new HashMap();
for (InstructionHandle dest = ret.getStart(), src = sourceList.getStart();
dest != null;
dest = dest.getNext(), src = src.getNext()) {
Instruction inst = dest.getInstruction();
// retarget branches
if (inst instanceof BranchInstruction) {
BranchInstruction branch = (BranchInstruction) inst;
InstructionHandle oldTarget = branch.getTarget();
InstructionHandle newTarget =
(InstructionHandle) srcToDest.get(oldTarget);
if (newTarget == null) {
// assert this is a GOTO
// this was a return instruction we previously replaced
} else {
branch.setTarget(newTarget);
if (branch instanceof Select) {
Select select = (Select) branch;
InstructionHandle[] oldTargets = select.getTargets();
for (int k = oldTargets.length - 1; k >= 0; k--) {
select.setTarget(
k,
(InstructionHandle) srcToDest.get(oldTargets[k]));
}
}
}
}
//copy over tags and range attributes
InstructionTargeter[] srcTargeters = src.getTargeters();
if (srcTargeters != null) {
for (int j = srcTargeters.length - 1; j >= 0; j--) {
InstructionTargeter old = srcTargeters[j];
if (old instanceof Tag) {
Tag oldTag = (Tag) old;
Tag fresh = (Tag) tagMap.get(oldTag);
if (fresh == null) {
fresh = oldTag.copy();
tagMap.put(oldTag, fresh);
}
dest.addTargeter(fresh);
} else if (old instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) old;
if (er.getStart() == src) {
ExceptionRange freshEr =
new ExceptionRange(
recipient.getBody(),
er.getCatchType(),
er.getPriority());
freshEr.associateWithTargets(
dest,
(InstructionHandle)srcToDest.get(er.getEnd()),
(InstructionHandle)srcToDest.get(er.getHandler()));
}
} else if (old instanceof ShadowRange) {
ShadowRange oldRange = (ShadowRange) old;
if (oldRange.getStart() == src) {
BcelShadow oldShadow = oldRange.getShadow();
BcelShadow freshEnclosing =
oldShadow.getEnclosingShadow() == null
? null
: (BcelShadow) shadowMap.get(oldShadow.getEnclosingShadow());
BcelShadow freshShadow =
oldShadow.copyInto(recipient, freshEnclosing);
ShadowRange freshRange = new ShadowRange(recipient.getBody());
freshRange.associateWithShadow(freshShadow);
freshRange.associateWithTargets(
dest,
(InstructionHandle) srcToDest.get(oldRange.getEnd()));
shadowMap.put(oldRange, freshRange);
//recipient.matchedShadows.add(freshShadow);
// XXX should go through the NEW copied shadow and update
// the thisVar, targetVar, and argsVar
// ??? Might want to also go through at this time and add
// "extra" vars to the shadow.
}
}
}
}
}
if (!keepReturns) ret.append(footer);
return ret;
}
/** generate the argument stores in preparation for inlining.
*
* @param donor the method we will inline from. Used to get the signature.
* @param recipient the method we will inline into. Used to get the frame size
* so we can allocate fresh locations.
* @param frameEnv an empty environment we populate with a map from donor frame to
* recipient frame.
* @param fact an instruction factory for recipient
*/
private static InstructionList genArgumentStores(
LazyMethodGen donor,
LazyMethodGen recipient,
IntMap frameEnv,
InstructionFactory fact)
{
InstructionList ret = new InstructionList();
int donorFramePos = 0;
// writing ret back to front because we're popping.
if (! donor.isStatic()) {
int targetSlot = recipient.allocateLocal(Type.OBJECT);
ret.insert(InstructionFactory.createStore(Type.OBJECT, targetSlot));
frameEnv.put(donorFramePos, targetSlot);
donorFramePos += 1;
}
Type[] argTypes = donor.getArgumentTypes();
for (int i = 0, len = argTypes.length; i < len; i++) {
Type argType = argTypes[i];
int argSlot = recipient.allocateLocal(argType);
ret.insert(InstructionFactory.createStore(argType, argSlot));
frameEnv.put(donorFramePos, argSlot);
donorFramePos += argType.getSize();
}
return ret;
}
/** get a called method: Assumes the called method is in this class,
* and the reference to it is exact (a la INVOKESPECIAL).
*
* @param ih The InvokeInstruction instructionHandle pointing to the called method.
*/
private LazyMethodGen getCalledMethod(
InstructionHandle ih)
{
InvokeInstruction inst = (InvokeInstruction) ih.getInstruction();
String methodName = inst.getName(cpg);
String signature = inst.getSignature(cpg);
return clazz.getLazyMethodGen(methodName, signature);
}
private void weaveInAddedMethods() {
Collections.sort(addedLazyMethodGens,
new Comparator() {
public int compare(Object a, Object b) {
LazyMethodGen aa = (LazyMethodGen) a;
LazyMethodGen bb = (LazyMethodGen) b;
int i = aa.getName().compareTo(bb.getName());
if (i != 0) return i;
return aa.getSignature().compareTo(bb.getSignature());
}
}
);
for (Iterator i = addedLazyMethodGens.iterator(); i.hasNext(); ) {
clazz.addMethodGen((LazyMethodGen)i.next());
}
}
void addPerSingletonField(Member field) {
ObjectType aspectType = (ObjectType) BcelWorld.makeBcelType(field.getReturnType());
String aspectName = field.getReturnType().getName();
LazyMethodGen clinit = clazz.getStaticInitializer();
InstructionList setup = new InstructionList();
InstructionFactory fact = clazz.getFactory();
setup.append(fact.createNew(aspectType));
setup.append(InstructionFactory.createDup(1));
setup.append(fact.createInvoke(
aspectName,
"<init>",
Type.VOID,
new Type[0],
Constants.INVOKESPECIAL));
setup.append(
fact.createFieldAccess(
aspectName,
field.getName(),
aspectType,
Constants.PUTSTATIC));
clinit.getBody().insert(setup);
}
/**
* Returns null if this is not a Java constructor, and then we won't
* weave into it at all
*/
private InstructionHandle findSuperOrThisCall(LazyMethodGen mg) {
int depth = 1;
InstructionHandle start = mg.getBody().getStart();
while (true) {
if (start == null) return null;
Instruction inst = start.getInstruction();
if (inst instanceof INVOKESPECIAL
&& ((INVOKESPECIAL) inst).getName(cpg).equals("<init>")) {
depth--;
if (depth == 0) return start;
} else if (inst instanceof NEW) {
depth++;
}
start = start.getNext();
}
}
// ----
private boolean match(LazyMethodGen mg) {
BcelShadow enclosingShadow;
List shadowAccumulator = new ArrayList();
// we want to match ajsynthetic constructors...
if (mg.getName().equals("<init>")) {
// XXX the enclosing join point is wrong for things before ignoreMe.
InstructionHandle superOrThisCall = findSuperOrThisCall(mg);
// we don't walk bodies of things where it's a wrong constructor thingie
if (superOrThisCall == null) return false;
enclosingShadow = BcelShadow.makeConstructorExecution(world, mg, superOrThisCall);
// walk the body
boolean beforeSuperOrThisCall = true;
if (shouldWeaveBody(mg)) {
if (canMatchBodyShadows) {
for (InstructionHandle h = mg.getBody().getStart();
h != null;
h = h.getNext()) {
if (h == superOrThisCall) {
beforeSuperOrThisCall = false;
continue;
}
match(mg, h, beforeSuperOrThisCall ? null : enclosingShadow, shadowAccumulator);
}
}
match(enclosingShadow, shadowAccumulator);
}
// XXX we don't do pre-inits of interfaces
// now add interface inits
if (superOrThisCall != null && ! isThisCall(superOrThisCall)) {
InstructionHandle curr = enclosingShadow.getRange().getStart();
for (Iterator i = addedSuperInitializersAsList.iterator(); i.hasNext(); ) {
IfaceInitList l = (IfaceInitList) i.next();
Member ifaceInitSig = AjcMemberMaker.interfaceConstructor(l.onType);
BcelShadow initShadow =
BcelShadow.makeIfaceInitialization(world, mg, ifaceInitSig);
// insert code in place
InstructionList inits = genInitInstructions(l.list, false);
if (match(initShadow, shadowAccumulator) || !inits.isEmpty()) {
initShadow.initIfaceInitializer(curr);
initShadow.getRange().insert(inits, Range.OutsideBefore);
}
}
// now we add our initialization code
InstructionList inits = genInitInstructions(addedThisInitializers, false);
enclosingShadow.getRange().insert(inits, Range.OutsideBefore);
}
// actually, you only need to inline the self constructors that are
// in a particular group (partition the constructors into groups where members
// call or are called only by those in the group). Then only inline
// constructors
// in groups where at least one initialization jp matched. Future work.
boolean addedInitialization =
match(
BcelShadow.makeUnfinishedInitialization(world, mg),
initializationShadows);
addedInitialization |=
match(
BcelShadow.makeUnfinishedPreinitialization(world, mg),
initializationShadows);
mg.matchedShadows = shadowAccumulator;
return addedInitialization || !shadowAccumulator.isEmpty();
} else if (!shouldWeaveBody(mg)) { //.isAjSynthetic()) {
return false;
} else {
if (mg.getName().equals("<clinit>")) {
clinitShadow = enclosingShadow = BcelShadow.makeStaticInitialization(world, mg);
//System.err.println(enclosingShadow);
} else if (mg.isAdviceMethod()) {
enclosingShadow = BcelShadow.makeAdviceExecution(world, mg);
} else {
AjAttribute.EffectiveSignatureAttribute effective = mg.getEffectiveSignature();
if (effective == null) {
enclosingShadow = BcelShadow.makeMethodExecution(world, mg, !canMatchBodyShadows);
} else if (effective.isWeaveBody()) {
enclosingShadow =
BcelShadow.makeShadowForMethod(
world,
mg,
effective.getShadowKind(),
effective.getEffectiveSignature());
} else {
return false;
}
}
if (canMatchBodyShadows) {
for (InstructionHandle h = mg.getBody().getStart();
h != null;
h = h.getNext()) {
match(mg, h, enclosingShadow, shadowAccumulator);
}
}
if (match(enclosingShadow, shadowAccumulator)) {
enclosingShadow.init();
}
mg.matchedShadows = shadowAccumulator;
return !shadowAccumulator.isEmpty();
}
}
private boolean shouldWeaveBody(LazyMethodGen mg) {
if (mg.isAjSynthetic()) return mg.getName().equals("<clinit>");
AjAttribute.EffectiveSignatureAttribute a = mg.getEffectiveSignature();
if (a != null) return a.isWeaveBody();
return true;
}
/**
* first sorts the mungers, then gens the initializers in the right order
*/
private InstructionList genInitInstructions(List list, boolean isStatic) {
list = PartialOrder.sort(list);
if (list == null) {
throw new BCException("circularity in inter-types");
}
InstructionList ret = new InstructionList();
for (Iterator i = list.iterator(); i.hasNext();) {
ConcreteTypeMunger cmunger = (ConcreteTypeMunger) i.next();
NewFieldTypeMunger munger = (NewFieldTypeMunger) cmunger.getMunger();
ResolvedMember initMethod = munger.getInitMethod(cmunger.getAspectType());
if (!isStatic) ret.append(InstructionConstants.ALOAD_0);
ret.append(Utility.createInvoke(fact, world, initMethod));
}
return ret;
}
private void match(
LazyMethodGen mg,
InstructionHandle ih,
BcelShadow enclosingShadow,
List shadowAccumulator)
{
Instruction i = ih.getInstruction();
if (i instanceof FieldInstruction) {
FieldInstruction fi = (FieldInstruction) i;
if (fi instanceof PUTFIELD || fi instanceof PUTSTATIC) {
// check for sets of constant fields. We first check the previous
// instruction. If the previous instruction is a LD_WHATEVER (push
// constant on the stack) then we must resolve the field to determine
// if it's final. If it is final, then we don't generate a shadow.
InstructionHandle prevHandle = ih.getPrev();
Instruction prevI = prevHandle.getInstruction();
if (Utility.isConstantPushInstruction(prevI)) {
Member field = BcelWorld.makeFieldSignature(clazz, (FieldInstruction) i);
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
} else if (Modifier.isFinal(resolvedField.getModifiers())) {
// it's final, so it's the set of a final constant, so it's
// not a join point according to 1.0.6 and 1.1.
} else {
matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else {
matchSetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else {
matchGetInstruction(mg, ih, enclosingShadow, shadowAccumulator);
}
} else if (i instanceof InvokeInstruction) {
InvokeInstruction ii = (InvokeInstruction) i;
if (ii.getMethodName(clazz.getConstantPoolGen()).equals("<init>")) {
match(
BcelShadow.makeConstructorCall(world, mg, ih, enclosingShadow),
shadowAccumulator);
} else if (ii instanceof INVOKESPECIAL) {
String onTypeName = ii.getClassName(cpg);
if (onTypeName.equals(mg.getEnclosingClass().getName())) {
// we are private
matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator);
} else {
// we are a super call, and this is not a join point in AspectJ-1.{0,1}
}
} else {
matchInvokeInstruction(mg, ih, ii, enclosingShadow, shadowAccumulator);
}
}
// performance optimization... we only actually care about ASTORE instructions,
// since that's what every javac type thing ever uses to start a handler, but for
// now we'll do this for everybody.
if (Range.isRangeHandle(ih)) return;
InstructionTargeter[] targeters = ih.getTargeters();
if (targeters != null) {
for (int j = 0; j < targeters.length; j++) {
InstructionTargeter t = targeters[j];
if (t instanceof ExceptionRange) {
// assert t.getHandler() == ih
ExceptionRange er = (ExceptionRange) t;
if (er.getCatchType() == null) continue;
if (isInitFailureHandler(ih)) return;
match(
BcelShadow.makeExceptionHandler(
world,
er,
mg, ih, enclosingShadow),
shadowAccumulator);
}
}
}
}
private boolean isInitFailureHandler(InstructionHandle ih) {
if (ih.getInstruction() instanceof PUTSTATIC) {
String name = ((PUTSTATIC)ih.getInstruction()).getFieldName(cpg);
if (name.equals(NameMangler.INITFAILURECAUSE_FIELD_NAME)) return true;
}
return false;
}
private void matchSetInstruction(
LazyMethodGen mg,
InstructionHandle ih,
BcelShadow enclosingShadow,
List shadowAccumulator) {
FieldInstruction fi = (FieldInstruction) ih.getInstruction();
Member field = BcelWorld.makeFieldSignature(clazz, fi);
// synthetic fields are never join points
if (field.getName().startsWith(NameMangler.PREFIX)) return;
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
return;
} else if (
Modifier.isFinal(resolvedField.getModifiers())
&& Utility.isConstantPushInstruction(ih.getPrev().getInstruction())) {
// it's the set of a final constant, so it's
// not a join point according to 1.0.6 and 1.1.
return;
} else if (resolvedField.isSynthetic()) {
// sets of synthetics aren't join points in 1.1
return;
} else {
match(
BcelShadow.makeFieldSet(world, mg, ih, enclosingShadow),
shadowAccumulator);
}
}
private void matchGetInstruction(LazyMethodGen mg, InstructionHandle ih, BcelShadow enclosingShadow, List shadowAccumulator) {
FieldInstruction fi = (FieldInstruction) ih.getInstruction();
Member field = BcelWorld.makeFieldSignature(clazz, fi);
// synthetic fields are never join points
if (field.getName().startsWith(NameMangler.PREFIX)) return;
ResolvedMember resolvedField = field.resolve(world);
if (resolvedField == null) {
// we can't find the field, so it's not a join point.
return;
} else if (resolvedField.isSynthetic()) {
// sets of synthetics aren't join points in 1.1
return;
} else {
match(BcelShadow.makeFieldGet(world, mg, ih, enclosingShadow), shadowAccumulator);
}
}
private void matchInvokeInstruction(LazyMethodGen mg,
InstructionHandle ih,
InvokeInstruction invoke,
BcelShadow enclosingShadow,
List shadowAccumulator)
{
String methodName = invoke.getName(cpg);
if (methodName.startsWith(NameMangler.PREFIX)) {
Member method =
BcelWorld.makeMethodSignature(clazz, invoke);
ResolvedMember declaredSig = method.resolve(world);
//System.err.println(method + ", declaredSig: " +declaredSig);
if (declaredSig == null) return;
if (declaredSig.getKind() == Member.FIELD) {
Shadow.Kind kind;
if (method.getReturnType().equals(ResolvedTypeX.VOID)) {
kind = Shadow.FieldSet;
} else {
kind = Shadow.FieldGet;
}
match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow,
kind, declaredSig),
shadowAccumulator);
} else {
AjAttribute.EffectiveSignatureAttribute effectiveSig =
declaredSig.getEffectiveSignature();
if (effectiveSig == null) return;
//System.err.println("call to inter-type member: " + effectiveSig);
if (effectiveSig.isWeaveBody()) return;
match(BcelShadow.makeShadowForMethodCall(world, mg, ih, enclosingShadow,
effectiveSig.getShadowKind(), effectiveSig.getEffectiveSignature()),
shadowAccumulator);
}
} else {
match(
BcelShadow.makeMethodCall(world, mg, ih, enclosingShadow),
shadowAccumulator);
}
}
private boolean match(BcelShadow shadow, List shadowAccumulator) {
//System.err.println("match: " + shadow);
boolean isMatched = false;
for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) {
ShadowMunger munger = (ShadowMunger)i.next();
if (munger.match(shadow, world)) {
shadow.addMunger(munger);
isMatched = true;
}
}
if (isMatched) shadowAccumulator.add(shadow);
return isMatched;
}
// ----
private void implement(LazyMethodGen mg) {
List shadows = mg.matchedShadows;
if (shadows == null) return;
// We depend on a partial order such that inner shadows are earlier on the list
// than outer shadows. That's fine. This order is preserved if:
// A preceeds B iff B.getStart() is LATER THAN A.getStart().
for (Iterator i = shadows.iterator(); i.hasNext(); ) {
BcelShadow shadow = (BcelShadow)i.next();
shadow.implement();
}
mg.matchedShadows = null;
}
// ----
public LazyClassGen getLazyClassGen() {
return clazz;
}
public List getShadowMungers() {
return shadowMungers;
}
public BcelWorld getWorld() {
return world;
}
// Called by the BcelWeaver to let us know all BcelClassWeavers need to collect reweavable info
public static void setReweavableMode(boolean mode,boolean compress) {
inReweavableMode = mode;
compressReweavableAttributes = compress;
}
}
|
50,776
|
Bug 50776 fail in compiling aspect with overriding method introduction with different throws clause
|
A first class (class A) declares only one method with some exceptions in the throws clause ( void m() throws Exception ). A second class (class B) extends it without redefinig the method. An aspect declares a method introduction in the class B, with the same name, signature and return type of the one in class A, but without throws clause; this is a legal override. In the second class (class B) each invocation to the overriden method doesn't need a try-catch block, because it refers to his hown method that raises no exception. This code compiles using ajc version 1.0.6 (built Jul 24, 2002 6:21 PM PST) running on java 1.4.0 But not using AspectJ Compiler 1.1.1 AspectJ Compiler 1.1.0 class A{ public A(){} public void m() throws Exception{} } class B extends A{ public B(){} public void some_code(){ m();} } aspect C{ public void B.m(){} }
|
resolved fixed
|
c798923
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-05T10:50:50Z
| 2004-01-28T17:13:20Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/InterTypeMemberFinder.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.Arrays;
import java.util.List;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.IMemberFinder;
import org.eclipse.jdt.internal.compiler.lookup.InvocationSite;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ProblemFieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
import org.eclipse.jdt.core.compiler.CharOperation;
public class InterTypeMemberFinder implements IMemberFinder {
private List interTypeFields = new ArrayList();
private List interTypeMethods = new ArrayList();
public SourceTypeBinding sourceTypeBinding;
public FieldBinding getField(
SourceTypeBinding sourceTypeBinding,
char[] fieldName,
InvocationSite site,
Scope scope)
{
FieldBinding retField = sourceTypeBinding.getFieldBase(fieldName, false); // XXX may need to get the correct value for second parameter in the future
if (interTypeFields.isEmpty()) return retField;
int fieldLength = fieldName.length;
for (int i=0, len=interTypeFields.size(); i < len; i++) {
FieldBinding field = (FieldBinding)interTypeFields.get(i);
if (field.name.length == fieldLength && CharOperation.prefixEquals(field.name, fieldName)) {
retField = resolveConflicts(sourceTypeBinding, retField, field, site, scope);
}
}
return retField;
}
private FieldBinding resolveConflicts(
SourceTypeBinding sourceTypeBinding,
FieldBinding retField,
FieldBinding field,
InvocationSite site,
Scope scope)
{
if (retField == null) return field;
if (site != null) {
if (!field.canBeSeenBy(sourceTypeBinding, site, scope)) return retField;
if (!retField.canBeSeenBy(sourceTypeBinding, site, scope)) return field;
}
//XXX need dominates check on aspects
return new ProblemFieldBinding(retField.declaringClass, retField.name, ProblemReporter.Ambiguous);
}
// private void reportConflicts(SourceTypeBinding sourceTypeBinding,
// MethodBinding m1, MethodBinding m2)
// {
// if (m1 == m2) {
// System.err.println("odd that we're ecomparing the same: " + m1);
// return;
// }
//
// if (!m1.areParametersEqual(m2)) return;
// if (m1 instanceof InterTypeMethodBinding) {
// if (m2 instanceof InterTypeMethodBinding) {
// reportConflictsBoth(sourceTypeBinding,
// (InterTypeMethodBinding)m1,
// (InterTypeMethodBinding)m2);
// } else {
// reportConflictsOne(sourceTypeBinding,
// (InterTypeMethodBinding)m1,
// m2);
// }
// } else if (m2 instanceof InterTypeMethodBinding) {
// reportConflictsOne(sourceTypeBinding,
// (InterTypeMethodBinding)m2,
// m1);
// } else {
// reportConflictsNone(sourceTypeBinding,
// m2,
// m1);
// }
// }
// private void reportConflicts(
// SourceTypeBinding sourceTypeBinding,
// MethodBinding m1,
// MethodBinding m2)
// {
// //System.err.println("compare: " + m1 + " with " + m2);
//
// if (m1 == m2) {
// System.err.println("odd that we're ecomparing the same: " + m1);
// return;
// }
//
// if (!m1.areParametersEqual(m2)) return;
//
// //System.err.println("t1: " + getTargetType(m1) + ", " + getTargetType(m2));
//
// if (getTargetType(m1) != getTargetType(m2)) return;
//
// if (m1.declaringClass == m2.declaringClass) {
// duplicateMethodBinding(m1, m2);
// return;
// }
//
//
// if (m1.isPublic() || m2.isPublic()) {
// duplicateMethodBinding(m1, m2);
// return;
// }
//
// // handle the wierd case where the aspect is a subtype of the target
// if (m2.isProtected()) {
// if (m2.declaringClass.isSuperclassOf(m1.declaringClass)) {
// duplicateMethodBinding(m1, m2);
// }
// // don't return because we also want to do the package test
// }
//
// if (!m1.isPrivate() || !m2.isPrivate()) {
// // at least package visible
// if (m1.declaringClass.getPackage() == m2.declaringClass.getPackage()) {
// duplicateMethodBinding(m1, m2);
// }
// return;
// }
//
// //XXX think about inner types some day
// }
////
private boolean isVisible(MethodBinding m1, ReferenceBinding s) {
if (m1.declaringClass == s) return true;
if (m1.isPublic()) return true;
//don't need to handle protected
//if (m1.isProtected()) {
if (!m1.isPrivate()) {
// at least package visible
return (m1.declaringClass.getPackage() == s.getPackage());
}
return false;
}
//
// private void duplicateMethodBinding(MethodBinding m1, MethodBinding m2) {
// ReferenceBinding t1 = m1.declaringClass;
// ReferenceBinding t2 = m2.declaringClass;
//
//
//
//
//
//
// if (!(t1 instanceof SourceTypeBinding) || !(t2 instanceof SourceTypeBinding)) {
// throw new RuntimeException("unimplemented");
// }
//
// SourceTypeBinding s1 = (SourceTypeBinding)t1;
// SourceTypeBinding s2 = (SourceTypeBinding)t2;
//
// if (m1.sourceMethod() != null) {
// s1.scope.problemReporter().duplicateMethodInType(s2, m1.sourceMethod());
// }
// if (m2.sourceMethod() != null) {
// s2.scope.problemReporter().duplicateMethodInType(s1, m2.sourceMethod());
// }
// }
// private void reportConflictsNone(
// SourceTypeBinding sourceTypeBinding,
// MethodBinding m2,
// MethodBinding m1)
// {
// throw new RuntimeException("not possible");
// }
// ReferenceBinding t1 = getDeclaringClass(m1);
// //.declaringClass;
// ReferenceBinding t2 = getDeclaringClass(m2);
// //.declaringClass;
//
// if (t1 == t2) {
// AbstractMethodDeclaration methodDecl = m2.sourceMethod(); // cannot be retrieved after binding is lost
// System.err.println("duplicate: " + t1 + ", " + t2);
// sourceTypeBinding.scope.problemReporter().duplicateMethodInType(sourceTypeBinding, methodDecl);
// methodDecl.binding = null;
// //methods[m] = null; //XXX duplicate problem reports
// return;
// }
//
// if (!(t1 instanceof SourceTypeBinding) || !(t2 instanceof SourceTypeBinding)) {
// throw new RuntimeException("unimplemented");
// }
//
// SourceTypeBinding s1 = (SourceTypeBinding)t1;
// SourceTypeBinding s2 = (SourceTypeBinding)t2;
//
//
// if (m1.canBeSeenBy(s1, null, s2.scope) || m2.canBeSeenBy(s2, null, s1.scope)) {
// s1.scope.problemReporter().duplicateMethodInType(s2, m1.sourceMethod());
// s2.scope.problemReporter().duplicateMethodInType(s1, m2.sourceMethod());
// }
// }
// private ReferenceBinding getTargetType(MethodBinding m2) {
// if (m2 instanceof InterTypeMethodBinding) {
// return ((InterTypeMethodBinding)m2).getTargetType();
// }
//
// return m2.declaringClass;
// }
//XXX conflicts
public MethodBinding[] getMethods(
SourceTypeBinding sourceTypeBinding,
char[] selector) {
// System.err.println("getMethods: " + new String(sourceTypeBinding.signature()) +
// ", " + new String(selector));
MethodBinding[] orig = sourceTypeBinding.getMethodsBase(selector);
if (interTypeMethods.isEmpty()) return orig;
List ret = new ArrayList(Arrays.asList(orig));
// System.err.println("declared method: " + ret + " inters = " + interTypeMethods);
for (int i=0, len=interTypeMethods.size(); i < len; i++) {
MethodBinding method = (MethodBinding)interTypeMethods.get(i);
if (CharOperation.equals(selector, method.selector)) {
ret.add(method);
}
}
if (ret.isEmpty()) return SourceTypeBinding.NoMethods;
// System.err.println("method: " + ret);
// check for conflicts
// int len = ret.size();
// if (len > 1) {
// for (int i=0; i <len; i++) {
// MethodBinding m1 = (MethodBinding)ret.get(i);
// for (int j=i+1; j < len; j++) {
// MethodBinding m2 = (MethodBinding)ret.get(j);
// //reportConflicts(sourceTypeBinding, m1, m2);
// }
// }
// }
//System.err.println("got methods: " + ret + " on " + sourceTypeBinding);
return (MethodBinding[])ret.toArray(new MethodBinding[ret.size()]);
}
public MethodBinding getExactMethod(
SourceTypeBinding sourceTypeBinding,
char[] selector,
TypeBinding[] argumentTypes)
{
MethodBinding ret = sourceTypeBinding.getExactMethodBase(selector, argumentTypes);
if (ret != null) return ret;
for (int i=0, len=interTypeMethods.size(); i < len; i++) {
MethodBinding im =
(MethodBinding)interTypeMethods.get(i);
if (matches(im, selector, argumentTypes)) {
return im;
}
}
return null;
}
// if (isVisible(im, sourceTypeBinding)) {
// if (ret == null) {
// ret = im;
// } else {
// ret = resolveOverride(ret, im);
// }
// }
// }
// }
// return ret;
// }
// private MethodBinding resolveOverride(MethodBinding m1, MethodBinding m2) {
// ReferenceBinding t1 = getTargetType(m1);
// ReferenceBinding t2 = getTargetType(m2);
// if (t1 == t2) {
// //XXX also need a test for completely matching sigs
// if (m1.isAbstract()) return m2;
// else if (m2.isAbstract()) return m1;
//
//
// if (m1 instanceof InterTypeMethodBinding) {
// //XXX need to handle dominates here
// EclipseWorld world = EclipseWorld.fromScopeLookupEnvironment(sourceTypeBinding.scope);
// int cmp = compareAspectPrecedence(world.fromEclipse(m1.declaringClass),
// world.fromEclipse(m2.declaringClass));
// if (cmp < 0) return m2;
// else if (cmp > 0) return m1;
// }
//
// duplicateMethodBinding(m1, m2);
// return null;
// }
// if (t1.isSuperclassOf(t2)) {
// return m2;
// }
// if (t2.isSuperclassOf(t1)) {
// return m1;
// }
//
// duplicateMethodBinding(m1, m2);
// return null;
// }
// private int compareAspectPrecedence(ResolvedTypeX a1, ResolvedTypeX a2) {
// World world = a1.getWorld();
// int ret = world.compareByDominates(a1, a2);
// if (ret == 0) {
// if (a1.isAssignableFrom(a2)) return -1;
// if (a2.isAssignableFrom(a1)) return +1;
// }
// return ret;
// }
//
private boolean matches(MethodBinding m1, MethodBinding m2) {
return matches(m1, m2.selector, m2.parameters);
// &&
// (isVisible(m1, m2.declaringClass) || isVisible(m2, m1.declaringClass));
}
private boolean matches(MethodBinding method, char[] selector, TypeBinding[] argumentTypes) {
if (!CharOperation.equals(selector, method.selector)) return false;
int argCount = argumentTypes.length;
if (method.parameters.length != argCount) return false;
TypeBinding[] toMatch = method.parameters;
for (int p = 0; p < argCount; p++) {
if (toMatch[p] != argumentTypes[p]) return false;
}
return true;
}
public void addInterTypeField(FieldBinding binding) {
//System.err.println("adding: " + binding + " to " + this);
interTypeFields.add(binding);
}
public void addInterTypeMethod(MethodBinding binding) {
// check for conflicts with existing methods, should really check type as well...
//System.err.println("adding: " + binding + " to " + sourceTypeBinding);
if (isVisible(binding, sourceTypeBinding)) {
MethodBinding[] baseMethods = sourceTypeBinding.methods;
for (int i=0, len=baseMethods.length; i < len; i++) {
MethodBinding b = baseMethods[i];
if (matches(binding, b)) {
// this always means we should remove the existing method
if (b.sourceMethod() != null) {
b.sourceMethod().binding = null;
}
sourceTypeBinding.removeMethod(i);
//System.err.println(" left: " + Arrays.asList(sourceTypeBinding.methods));
break;
}
}
}
interTypeMethods.add(binding);
}
}
|
50,776
|
Bug 50776 fail in compiling aspect with overriding method introduction with different throws clause
|
A first class (class A) declares only one method with some exceptions in the throws clause ( void m() throws Exception ). A second class (class B) extends it without redefinig the method. An aspect declares a method introduction in the class B, with the same name, signature and return type of the one in class A, but without throws clause; this is a legal override. In the second class (class B) each invocation to the overriden method doesn't need a try-catch block, because it refers to his hown method that raises no exception. This code compiles using ajc version 1.0.6 (built Jul 24, 2002 6:21 PM PST) running on java 1.4.0 But not using AspectJ Compiler 1.1.1 AspectJ Compiler 1.1.0 class A{ public A(){} public void m() throws Exception{} } class B extends A{ public B(){} public void some_code(){ m();} } aspect C{ public void B.m(){} }
|
resolved fixed
|
c798923
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-05T10:50:50Z
| 2004-01-28T17:13:20Z
|
tests/bugs/IntertypeDifferentThrows.java
| |
44,272
|
Bug 44272 retitle warning to "circular {advice} dependency at ..."
|
When writing aspects with cycles in the advice precedence, get warning "circular dependency at {join point}" -- should be "circular advice dependency..." or "circular advice precedences at {join point} -- reorder the advice in the aspect". FWIW, here's an example of circularity in advice precedence: ---- aspect A { pointcut crun() : execution (void run()) ; before() : crun() {} after() returning : crun() {} void around() : crun() { proceed(); } } ---- See programming guide for more discussion of circularity in advice precedence.
|
resolved fixed
|
0109534
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-15T17:27:56Z
| 2003-10-07T04:13:20Z
|
tests/bugs/CircularAdvicePrecedence.java
| |
44,272
|
Bug 44272 retitle warning to "circular {advice} dependency at ..."
|
When writing aspects with cycles in the advice precedence, get warning "circular dependency at {join point}" -- should be "circular advice dependency..." or "circular advice precedences at {join point} -- reorder the advice in the aspect". FWIW, here's an example of circularity in advice precedence: ---- aspect A { pointcut crun() : execution (void run()) ; before() : crun() {} after() returning : crun() {} void around() : crun() { proceed(); } } ---- See programming guide for more discussion of circularity in advice precedence.
|
resolved fixed
|
0109534
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-15T17:27:56Z
| 2003-10-07T04:13:20Z
|
weaver/src/org/aspectj/weaver/Shadow.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.aspectj.asm.IRelationship;
import org.aspectj.bridge.*;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.util.PartialOrder;
import org.aspectj.util.TypeSafeEnum;
import org.aspectj.weaver.ast.Var;
/*
* The superclass of anything representing a the shadow of a join point. A shadow represents
* some bit of code, and encompasses both entry and exit from that code. All shadows have a kind
* and a signature.
*/
public abstract class Shadow {
private final Kind kind;
private final Member signature;
protected final Shadow enclosingShadow;
protected List mungers = new ArrayList(1);
// ----
protected Shadow(Kind kind, Member signature, Shadow enclosingShadow) {
this.kind = kind;
this.signature = signature;
this.enclosingShadow = enclosingShadow;
}
// ----
public abstract World getIWorld();
public List /*ShadowMunger*/ getMungers() {
return mungers;
}
/**
* could this(*) pcd ever match
*/
public final boolean hasThis() {
if (getKind().neverHasThis()) {
return false;
} else if (getKind().isEnclosingKind()) {
return !getSignature().isStatic();
} else if (enclosingShadow == null) {
return false;
} else {
return enclosingShadow.hasThis();
}
}
/**
* the type of the this object here
*
* @throws IllegalStateException if there is no this here
*/
public final TypeX getThisType() {
if (!hasThis()) throw new IllegalStateException("no this");
if (getKind().isEnclosingKind()) {
return getSignature().getDeclaringType();
} else {
return enclosingShadow.getThisType();
}
}
/**
* a var referencing this
*
* @throws IllegalStateException if there is no target here
*/
public abstract Var getThisVar();
/**
* could target(*) pcd ever match
*/
public final boolean hasTarget() {
if (getKind().neverHasTarget()) {
return false;
} else if (getKind().isTargetSameAsThis()) {
return hasThis();
} else {
return !getSignature().isStatic();
}
}
/**
* the type of the target object here
*
* @throws IllegalStateException if there is no target here
*/
public final TypeX getTargetType() {
if (!hasTarget()) throw new IllegalStateException("no target");
return getSignature().getDeclaringType();
}
/**
* a var referencing the target
*
* @throws IllegalStateException if there is no target here
*/
public abstract Var getTargetVar();
public TypeX[] getArgTypes() {
if (getKind() == FieldSet) return new TypeX[] { getSignature().getReturnType() };
return getSignature().getParameterTypes();
}
public TypeX getArgType(int arg) {
if (getKind() == FieldSet) return getSignature().getReturnType();
return getSignature().getParameterTypes()[arg];
}
public int getArgCount() {
if (getKind() == FieldSet) return 1;
return getSignature()
.getParameterTypes().length;
}
public abstract TypeX getEnclosingType();
public abstract Var getArgVar(int i);
public abstract Var getThisJoinPointVar();
public abstract Var getThisJoinPointStaticPartVar();
public abstract Var getThisEnclosingJoinPointStaticPartVar();
public abstract Member getEnclosingCodeSignature();
/** returns the kind of shadow this is, representing what happens under this shadow
*/
public Kind getKind() {
return kind;
}
/** returns the signature of the thing under this shadow
*/
public Member getSignature() {
return signature;
}
public TypeX getReturnType() {
if (kind == ConstructorCall) return getSignature().getDeclaringType();
else if (kind == FieldSet) return ResolvedTypeX.VOID;
return getSignature().getReturnType();
}
/**
* These names are the ones that will be returned by thisJoinPoint.getKind()
* Those need to be documented somewhere
*/
public static final Kind MethodCall = new Kind(JoinPoint.METHOD_CALL, 1, true);
public static final Kind ConstructorCall = new Kind(JoinPoint.CONSTRUCTOR_CALL, 2, true);
public static final Kind MethodExecution = new Kind(JoinPoint.METHOD_EXECUTION, 3, false);
public static final Kind ConstructorExecution = new Kind(JoinPoint.CONSTRUCTOR_EXECUTION, 4, false);
public static final Kind FieldGet = new Kind(JoinPoint.FIELD_GET, 5, true);
public static final Kind FieldSet = new Kind(JoinPoint.FIELD_SET, 6, true);
public static final Kind StaticInitialization = new Kind(JoinPoint.STATICINITIALIZATION, 7, false);
public static final Kind PreInitialization = new Kind(JoinPoint.PREINTIALIZATION, 8, false);
public static final Kind AdviceExecution = new Kind(JoinPoint.ADVICE_EXECUTION, 9, false);
public static final Kind Initialization = new Kind(JoinPoint.INITIALIZATION, 10, false);
public static final Kind ExceptionHandler = new Kind(JoinPoint.EXCEPTION_HANDLER, 11, true);
public static final int MAX_SHADOW_KIND = 11;
public static final Kind[] SHADOW_KINDS = new Kind[] {
MethodCall, ConstructorCall, MethodExecution, ConstructorExecution,
FieldGet, FieldSet, StaticInitialization, PreInitialization,
AdviceExecution, Initialization, ExceptionHandler,
};
/** A type-safe enum representing the kind of shadows
*/
public static final class Kind extends TypeSafeEnum {
private boolean argsOnStack; //XXX unused
public Kind(String name, int key, boolean argsOnStack) {
super(name, key);
this.argsOnStack = argsOnStack;
}
public String toLegalJavaIdentifier() {
return getName().replace('-', '_');
}
public boolean argsOnStack() {
return !isTargetSameAsThis();
}
// !!! this is false for handlers!
public boolean allowsExtraction() {
return true;
}
// XXX revisit along with removal of priorities
public boolean hasHighPriorityExceptions() {
return !isTargetSameAsThis();
}
/**
* These are all the shadows that contains other shadows within them and
* are often directly associated with methods.
*/
public boolean isEnclosingKind() {
return this == MethodExecution || this == ConstructorExecution ||
this == AdviceExecution || this == StaticInitialization
|| this == Initialization;
}
public boolean isTargetSameAsThis() {
return this == MethodExecution
|| this == ConstructorExecution
|| this == StaticInitialization
|| this == PreInitialization
|| this == AdviceExecution
|| this == Initialization;
}
public boolean neverHasTarget() {
return this == ConstructorCall
|| this == ExceptionHandler
|| this == PreInitialization
|| this == StaticInitialization;
}
public boolean neverHasThis() {
return this == PreInitialization
|| this == StaticInitialization;
}
public String getSimpleName() {
int dash = getName().lastIndexOf('-');
if (dash == -1) return getName();
else return getName().substring(dash+1);
}
public static Kind read(DataInputStream s) throws IOException {
int key = s.readByte();
switch(key) {
case 1: return MethodCall;
case 2: return ConstructorCall;
case 3: return MethodExecution;
case 4: return ConstructorExecution;
case 5: return FieldGet;
case 6: return FieldSet;
case 7: return StaticInitialization;
case 8: return PreInitialization;
case 9: return AdviceExecution;
case 10: return Initialization;
case 11: return ExceptionHandler;
}
throw new BCException("unknown kind: " + key);
}
}
protected boolean checkMunger(ShadowMunger munger) {
for (Iterator i = munger.getThrownExceptions().iterator(); i.hasNext(); ) {
if (!checkCanThrow(munger, (ResolvedTypeX)i.next() )) return false;
}
return true;
}
protected boolean checkCanThrow(ShadowMunger munger, ResolvedTypeX resolvedTypeX) {
if (getKind() == ExceptionHandler) {
//XXX much too lenient rules here, need to walk up exception handlers
return true;
}
if (!isDeclaredException(resolvedTypeX, getSignature())) {
getIWorld().showMessage(IMessage.ERROR, "can't throw checked exception \'" + resolvedTypeX +
"\' at this join point \'" + this +"\'", // from advice in \'" + munger. + "\'",
getSourceLocation(), munger.getSourceLocation());
}
return true;
}
private boolean isDeclaredException(
ResolvedTypeX resolvedTypeX,
Member member)
{
ResolvedTypeX[] excs = getIWorld().resolve(member.getExceptions(getIWorld()));
for (int i=0, len=excs.length; i < len; i++) {
if (excs[i].isAssignableFrom(resolvedTypeX)) return true;
}
return false;
}
public void addMunger(ShadowMunger munger) {
if (checkMunger(munger)) this.mungers.add(munger);
}
public final void implement() {
sortMungers();
if (mungers == null) return;
prepareForMungers();
implementMungers();
}
private void sortMungers() {
List sorted = PartialOrder.sort(mungers);
if (sorted == null) {
// this means that we have circular dependencies
for (Iterator i = mungers.iterator(); i.hasNext(); ) {
ShadowMunger m = (ShadowMunger)i.next();
getIWorld().getMessageHandler().handleMessage(
MessageUtil.error("circular dependency at " + this, m.getSourceLocation()));
}
}
mungers = sorted;
}
/** Prepare the shadow for implementation. After this is done, the shadow
* should be in such a position that each munger simply needs to be implemented.
*/
protected void prepareForMungers() {
throw new RuntimeException("Generic shadows cannot be prepared");
}
/** Actually implement the (non-empty) mungers associated with this shadow */
private void implementMungers() {
World world = getIWorld();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
munger.implementOn(this);
if (world.xrefHandler != null) {
world.xrefHandler.addCrossReference(munger.getSourceLocation(),this.getSourceLocation(),IRelationship.Kind.ADVICE);
}
if (world.getModel() != null) {
//System.err.println("munger: " + munger + " on " + this);
AsmRelationshipProvider.adviceMunger(world.getModel(), this, munger);
}
}
}
public String makeReflectiveFactoryString() {
return null; //XXX
}
public abstract ISourceLocation getSourceLocation();
// ---- utility
public String toString() {
return getKind() + "(" + getSignature() + ")"; // + getSourceLines();
}
}
|
44,272
|
Bug 44272 retitle warning to "circular {advice} dependency at ..."
|
When writing aspects with cycles in the advice precedence, get warning "circular dependency at {join point}" -- should be "circular advice dependency..." or "circular advice precedences at {join point} -- reorder the advice in the aspect". FWIW, here's an example of circularity in advice precedence: ---- aspect A { pointcut crun() : execution (void run()) ; before() : crun() {} after() returning : crun() {} void around() : crun() { proceed(); } } ---- See programming guide for more discussion of circularity in advice precedence.
|
resolved fixed
|
0109534
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-15T17:27:56Z
| 2003-10-07T04:13:20Z
|
weaver/src/org/aspectj/weaver/patterns/DeclarePrecedence.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.List;
import org.aspectj.bridge.IMessage;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.ResolvedTypeX;
public class DeclarePrecedence extends Declare {
private TypePatternList patterns;
public DeclarePrecedence(List patterns) {
this(new TypePatternList(patterns));
}
private DeclarePrecedence(TypePatternList patterns) {
this.patterns = patterns;
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("declare precedence: ");
buf.append(patterns);
buf.append(";");
return buf.toString();
}
public boolean equals(Object other) {
if (!(other instanceof DeclarePrecedence)) return false;
DeclarePrecedence o = (DeclarePrecedence)other;
return o.patterns.equals(patterns);
}
public int hashCode() {
return patterns.hashCode();
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Declare.DOMINATES);
patterns.write(s);
writeLocation(s);
}
public static Declare read(DataInputStream s, ISourceContext context) throws IOException {
Declare ret = new DeclarePrecedence(TypePatternList.read(s, context));
ret.readLocation(context, s);
return ret;
}
public void resolve(IScope scope) {
patterns = patterns.resolveBindings(scope, Bindings.NONE, false, false);
boolean seenStar = false;
for (int i=0; i < patterns.size(); i++) {
TypePattern pi = patterns.get(i);
if (pi.isStar()) {
if (seenStar) {
scope.getWorld().showMessage(IMessage.ERROR,
"circularity in declare dominates, '*' occurs more than once",
pi.getSourceLocation(), null);
}
seenStar = true;
continue;
}
ResolvedTypeX exactType = pi.getExactType().resolve(scope.getWorld());
if (exactType == ResolvedTypeX.MISSING) continue;
for (int j=0; j < patterns.size(); j++) {
if (j == i) continue;
TypePattern pj = patterns.get(j);
if (pj.isStar()) continue;
if (pj.matchesStatically(exactType)) {
scope.getWorld().showMessage(IMessage.ERROR,
"circularity in declare dominates, '" + exactType.getName() +
"' matches two patterns", pi.getSourceLocation(), pj.getSourceLocation());
}
}
}
}
public TypePatternList getPatterns() {
return patterns;
}
private int matchingIndex(ResolvedTypeX a) {
int knownMatch = -1;
int starMatch = -1;
for (int i=0, len=patterns.size(); i < len; i++) {
TypePattern p = patterns.get(i);
if (p.isStar()) {
starMatch = i;
} else if (p.matchesStatically(a)) {
if (knownMatch != -1) {
a.getWorld().showMessage(IMessage.ERROR, "multiple matches for " + a +
", matches both " + patterns.get(knownMatch) + " and " + p,
patterns.get(knownMatch).getSourceLocation(), p.getSourceLocation());
return -1;
} else {
knownMatch = i;
}
}
}
if (knownMatch == -1) return starMatch;
else return knownMatch;
}
public int compare(ResolvedTypeX aspect1, ResolvedTypeX aspect2) {
int index1 = matchingIndex(aspect1);
int index2 = matchingIndex(aspect2);
//System.out.println("a1: " + aspect1 + ", " + aspect2 + " = " + index1 + ", " + index2);
if (index1 == -1 || index2 == -1) return 0;
if (index1 == index2) return 0;
else if (index1 > index2) return -1;
else return +1;
}
public boolean isAdviceLike() {
return false;
}
}
|
51,322
|
Bug 51322 Introduce Unknown Type to class causes Null pointer exception
| null |
resolved fixed
|
5c67166
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-15T22:38:03Z
| 2004-02-07T21:40:00Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/InterTypeMethodDeclaration.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import java.lang.reflect.Modifier;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseTypeMunger;
import org.aspectj.weaver.*;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
//import org.eclipse.jdt.internal.compiler.flow.FlowContext;
import org.eclipse.jdt.internal.compiler.flow.FlowInfo;
import org.eclipse.jdt.internal.compiler.flow.InitializationFlowContext;
import org.eclipse.jdt.internal.compiler.lookup.*;
import org.eclipse.jdt.internal.compiler.parser.Parser;
/**
* An inter-type method declaration.
*
* @author Jim Hugunin
*/
public class InterTypeMethodDeclaration extends InterTypeDeclaration {
public InterTypeMethodDeclaration(CompilationResult result, TypeReference onType) {
super(result, onType);
}
public void parseStatements(Parser parser, CompilationUnitDeclaration unit) {
if (ignoreFurtherInvestigation)
return;
if (!Modifier.isAbstract(declaredModifiers)) {
parser.parse(this, unit);
}
}
public void analyseCode(
ClassScope currentScope,
InitializationFlowContext flowContext,
FlowInfo flowInfo)
{
if (Modifier.isAbstract(declaredModifiers)) return;
super.analyseCode(currentScope, flowContext, flowInfo);
}
public void resolve(ClassScope upperScope) {
if (munger == null) ignoreFurtherInvestigation = true;
if (ignoreFurtherInvestigation) return;
if (!Modifier.isStatic(declaredModifiers)) {
this.arguments = AstUtil.insert(
AstUtil.makeFinalArgument("ajc$this_".toCharArray(), onTypeBinding),
this.arguments);
binding.parameters = AstUtil.insert(onTypeBinding, binding.parameters);
}
super.resolve(upperScope);
}
public void resolveStatements() {
if ((modifiers & AccSemicolonBody) != 0) {
if ((declaredModifiers & AccAbstract) == 0)
scope.problemReporter().methodNeedingAbstractModifier(this);
} else {
// the method HAS a body --> abstract native modifiers are forbiden
if (((declaredModifiers & AccAbstract) != 0))
scope.problemReporter().methodNeedingNoBody(this);
}
if (!Modifier.isAbstract(declaredModifiers)) super.resolveStatements();
if (Modifier.isStatic(declaredModifiers)) {
// Check the target for ITD is not an interface
if (onTypeBinding.isInterface()) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"methods in interfaces cannot be declared static");
}
}
}
public EclipseTypeMunger build(ClassScope classScope) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope);
resolveOnType(classScope);
if (ignoreFurtherInvestigation) return null;
binding = classScope.referenceContext.binding.resolveTypesFor(binding);
ResolvedMember sig = new ResolvedMember(Member.METHOD, EclipseFactory.fromBinding(onTypeBinding),
declaredModifiers, EclipseFactory.fromBinding(binding.returnType), new String(declaredSelector),
EclipseFactory.fromBindings(binding.parameters),
world.fromEclipse(binding.thrownExceptions));
NewMethodTypeMunger myMunger = new NewMethodTypeMunger(sig, null);
setMunger(myMunger);
ResolvedTypeX aspectType = world.fromEclipse(classScope.referenceContext.binding);
ResolvedMember me =
myMunger.getDispatchMethod(aspectType);
this.selector = binding.selector = me.getName().toCharArray();
return new EclipseTypeMunger(world, myMunger, aspectType, this);
}
private AjAttribute makeAttribute() {
return new AjAttribute.TypeMunger(munger);
}
public void generateCode(ClassScope classScope, ClassFile classFile) {
if (ignoreFurtherInvestigation) {
//System.err.println("no code for " + this);
return;
}
classFile.extraAttributes.add(new EclipseAttributeAdapter(makeAttribute()));
if (!Modifier.isAbstract(declaredModifiers)) {
super.generateCode(classScope, classFile);
}
generateDispatchMethod(classScope, classFile);
}
public void generateDispatchMethod(ClassScope classScope, ClassFile classFile) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope);
TypeX aspectType = EclipseFactory.fromBinding(classScope.referenceContext.binding);
ResolvedMember signature = munger.getSignature();
ResolvedMember dispatchMember =
AjcMemberMaker.interMethodDispatcher(signature, aspectType);
MethodBinding dispatchBinding = world.makeMethodBinding(dispatchMember);
MethodBinding introducedMethod =
world.makeMethodBinding(AjcMemberMaker.interMethod(signature, aspectType, onTypeBinding.isInterface()));
classFile.generateMethodInfoHeader(dispatchBinding);
int methodAttributeOffset = classFile.contentsOffset;
int attributeNumber = classFile.generateMethodInfoAttribute(dispatchBinding,
makeEffectiveSignatureAttribute(signature, Shadow.MethodCall, false));
int codeAttributeOffset = classFile.contentsOffset;
classFile.generateCodeAttributeHeader();
CodeStream codeStream = classFile.codeStream;
codeStream.reset(this, classFile);
codeStream.initializeMaxLocals(dispatchBinding);
MethodBinding methodBinding = introducedMethod;
TypeBinding[] parameters = methodBinding.parameters;
int length = parameters.length;
int resolvedPosition;
if (methodBinding.isStatic())
resolvedPosition = 0;
else {
codeStream.aload_0();
resolvedPosition = 1;
}
for (int i = 0; i < length; i++) {
codeStream.load(parameters[i], resolvedPosition);
if ((parameters[i] == DoubleBinding) || (parameters[i] == LongBinding))
resolvedPosition += 2;
else
resolvedPosition++;
}
// TypeBinding type;
if (methodBinding.isStatic())
codeStream.invokestatic(methodBinding);
else {
if (methodBinding.declaringClass.isInterface()){
codeStream.invokeinterface(methodBinding);
} else {
codeStream.invokevirtual(methodBinding);
}
}
AstUtil.generateReturn(dispatchBinding.returnType, codeStream);
classFile.completeCodeAttribute(codeAttributeOffset);
attributeNumber++;
classFile.completeMethodInfo(methodAttributeOffset, attributeNumber);
}
protected Shadow.Kind getShadowKindForBody() {
return Shadow.MethodExecution;
}
}
|
51,322
|
Bug 51322 Introduce Unknown Type to class causes Null pointer exception
| null |
resolved fixed
|
5c67166
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-15T22:38:03Z
| 2004-02-07T21:40:00Z
|
tests/bugs/Pr51322.java
| |
54,965
|
Bug 54965 Incremental compilation does twice as much work as necessary
|
When I added support for -outjar in the test harness, I was surprised to find duplicate entry exceptions coming from the output file writing to the outjar. I traced it through, and found that every source file passed to an incremental compile is in fact compiled twice! The first time round we note the references, and of course each file has a reference to itself. Then we call "AjState.getFilesToCompile" looking to see if there are any further files to compile in another iteration. This method does not remember the set of files it just compiled, so since we have referenced each type we just compiled, and we have no reord of that fact, we compile them again. Second time around, the bytecodes are identical to the previous go, so recordClassFile doesn't note their dependents - and thus this time we terminate.
|
resolved fixed
|
41c6f6d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-16T15:07:19Z
| 2004-03-16T15:13:20Z
|
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.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.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();
ArrayList/*<String>*/ qualifiedStrings;
ArrayList/*<String>*/ simpleStrings;
Set addedFiles;
Set deletedFiles;
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;
}
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);
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);
if (modTime >= lastBuildTime) {
ret.add(file);
}
}
return ret;
}
public List getFilesToCompile(boolean firstPass) {
List sourceFiles = new ArrayList();
if (firstPass) {
Collection modifiedFiles = getModifiedFiles();
//System.out.println("modified: " + modifiedFiles);
sourceFiles.addAll(modifiedFiles);
//??? eclipse IncrementalImageBuilder appears to do this
// for (Iterator i = modifiedFiles.iterator(); i.hasNext();) {
// File file = (File) i.next();
// addDependentsOf(file);
// }
sourceFiles.addAll(addedFiles);
deleteClassFiles();
addAffectedSourceFiles(sourceFiles);
} else {
addAffectedSourceFiles(sourceFiles);
}
return sourceFiles;
}
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 deleteClassFile(UnwovenClassFile classFile) {
classesFromName.remove(classFile.getClassName());
buildManager.bcelWeaver.deleteClassFile(classFile.getClassName());
try {
classFile.deleteRealFile();
} catch (IOException e) {
//!!! might be okay to ignore
}
}
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 sourceFiles) {
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 (!sourceFiles.contains(file)) { //??? O(n**2)
sourceFiles.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());
}
}
}
|
54,625
|
Bug 54625 Incremental support does not work with outjar
|
Either fix the class file deleting etc. to work with jars, or always do a batch build when working with outjars.
|
resolved fixed
|
1a4c02c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-16T15:16:46Z
| 2004-03-12T14: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.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.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();
ArrayList/*<String>*/ qualifiedStrings;
ArrayList/*<String>*/ simpleStrings;
Set addedFiles;
Set deletedFiles;
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;
}
// if (newBuildConfig.getOutputJar() != null) 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);
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);
if (modTime >= lastBuildTime) {
ret.add(file);
}
}
return ret;
}
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();
addAffectedSourceFiles(thisTime,thisTime);
} else {
addAffectedSourceFiles(thisTime,compiledSourceFiles);
}
compiledSourceFiles = thisTime;
return thisTime;
}
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 deleteClassFile(UnwovenClassFile classFile) {
classesFromName.remove(classFile.getClassName());
buildManager.bcelWeaver.deleteClassFile(classFile.getClassName());
try {
classFile.deleteRealFile();
} catch (IOException e) {
//!!! might be okay to ignore
}
}
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());
}
}
}
|
47,910
|
Bug 47910 ajc -outjar jarfile does not contain MANIFEST.MF
|
I call ajc -sourceroots <mydir> -outjar <my.jar> and an output file is created with a .jar extension, but it is not a valid jar file because there is no MANIFEST.MF file. I see that the text for ajc says: -outjar <file> put output classes in zip file <file> which might imply that it is supposed to be a zip file, but a parameter called - outjar which creates a zip file doesn't really make sense. If -outjar is used, the resulting file should be a valid jar file, i.e. with a META-INF/MANIFEST.MF file inside.
|
resolved fixed
|
34dbb0c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-17T12:25:49Z
| 2003-12-02T18:33:20Z
|
ajde/testdata/JarManifestTest/src/Main.java
| |
47,910
|
Bug 47910 ajc -outjar jarfile does not contain MANIFEST.MF
|
I call ajc -sourceroots <mydir> -outjar <my.jar> and an output file is created with a .jar extension, but it is not a valid jar file because there is no MANIFEST.MF file. I see that the text for ajc says: -outjar <file> put output classes in zip file <file> which might imply that it is supposed to be a zip file, but a parameter called - outjar which creates a zip file doesn't really make sense. If -outjar is used, the resulting file should be a valid jar file, i.e. with a META-INF/MANIFEST.MF file inside.
|
resolved fixed
|
34dbb0c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-17T12:25:49Z
| 2003-12-02T18:33:20Z
|
ajde/testsrc/org/aspectj/ajde/AjdeTests.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.ajde;
import junit.framework.*;
public class AjdeTests extends TestCase {
public static String TESTDATA_PATH = "../ajde/testdata";
public static Test suite() {
TestSuite suite = new TestSuite(AjdeTests.class.getName());
//$JUnit-BEGIN$
suite.addTestSuite(BuildOptionsTest.class);
suite.addTestSuite(BuildConfigurationTests.class);
suite.addTestSuite(StructureModelRegressionTest.class);
suite.addTestSuite(StructureModelTest.class);
suite.addTestSuite(VersionTest.class);
suite.addTestSuite(CompilerMessagesTest.class);
suite.addTestSuite(AsmDeclarationsTest.class);
suite.addTestSuite(AsmRelationshipsTest.class);
suite.addTestSuite(InpathTestcase.class);
suite.addTestSuite(ReweavableTestCase.class);
suite.addTestSuite(ResourceCopyTestCase.class);
suite.addTestSuite(ModelPerformanceTest.class);
suite.addTestSuite(SavedModelConsistencyTest. class);
//$JUnit-END$
return suite;
}
public AjdeTests(String name) { super(name); }
}
|
47,910
|
Bug 47910 ajc -outjar jarfile does not contain MANIFEST.MF
|
I call ajc -sourceroots <mydir> -outjar <my.jar> and an output file is created with a .jar extension, but it is not a valid jar file because there is no MANIFEST.MF file. I see that the text for ajc says: -outjar <file> put output classes in zip file <file> which might imply that it is supposed to be a zip file, but a parameter called - outjar which creates a zip file doesn't really make sense. If -outjar is used, the resulting file should be a valid jar file, i.e. with a META-INF/MANIFEST.MF file inside.
|
resolved fixed
|
34dbb0c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-17T12:25:49Z
| 2003-12-02T18:33:20Z
|
ajde/testsrc/org/aspectj/ajde/InpathTestcase.java
|
/* *******************************************************************
* Copyright (c) 2003 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Mik Kersten initial implementation
* Andy Clement Copied/changed for -inpath testing
* ******************************************************************/
package org.aspectj.ajde;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import org.aspectj.util.FileUtil;
/**
* @author websterm
*/
public class InpathTestcase extends AjdeTestCase {
public static final String PROJECT_DIR = "InpathTest";
public static final String binDir = "bin";
public static final String indir1Name = "indir1";
public static final String indir2Name = "indir2";
public static final String injarName = "injar.jar";
public static final String outjarName = "/bin/output.jar";
/**
* Constructor for JarResourceCopyTestCase.
* @param arg0
*/
public InpathTestcase(String arg0) {
super(arg0);
}
/*
* Ensure the output directpry in clean
*/
protected void setUp() throws Exception {
super.setUp(PROJECT_DIR);
FileUtil.deleteContents(openFile(binDir));
}
/**
* Inputs to the compiler:
* inpath = 'indir1/'
* source = 'src'
* output = a jar file
*
* Expected result = output jar file contains contents of indir1 and
* class file for source that was in src
*/
public void testInpathToOutjar() {
Set inpath = new HashSet();
File indir1 = openFile(indir1Name);
inpath.add(indir1);
ideManager.getProjectProperties().setInpath(inpath);
File outjar = openFile(outjarName);
ideManager.getProjectProperties().setOutJar(outjar.getAbsolutePath());
assertTrue("Build failed", doSynchronousBuild("build.lst"));
assertTrue("Build warnings", ideManager.getCompilationSourceLineTasks().isEmpty());
Set expectedOutputJarContents = new HashSet();
// From indir1
// If we don't copy resources, these next three files won't make it.
// expectedOutputJarContents.add("META-INF/MANIFEST.MF");
// expectedOutputJarContents.add("META-INF/test.xml");
// expectedOutputJarContents.add("test/test.props");
expectedOutputJarContents.add("test/TestProperties.class");
// From src
expectedOutputJarContents.add("Main.class");
compareJars(indir1, "src", outjar, expectedOutputJarContents);
// Tidy up
FileUtil.deleteContents(openFile(binDir));
openFile(binDir).delete();
assertFalse(openFile(binDir).exists());
}
/**
* Similar to the first test but outputs to a directory rather than
* a jar.
*
*/
public void testInpathToBin() {
Set inpath = new HashSet();
File indir1 = openFile(indir1Name);
inpath.add(indir1);
ideManager.getProjectProperties().setInpath(inpath);
assertTrue("Build failed", doSynchronousBuild("build.lst"));
assertTrue(
"Build warnings",
ideManager.getCompilationSourceLineTasks().isEmpty());
Set expectedBindirContents = new HashSet();
// From indir1
// If we don't copy resources, these next three files won't make it
// expectedBindirContents.add("META-INF/MANIFEST.MF");
// expectedBindirContents.add("META-INF/test.xml");
// expectedBindirContents.add("test/test.props");
expectedBindirContents.add("test/TestProperties.class");
// From src
expectedBindirContents.add("Main.class");
compareIndirToBin(indir1, "src", "bin", expectedBindirContents);
// Tidy up
FileUtil.deleteContents(openFile(binDir));
openFile(binDir).delete();
assertFalse(openFile(binDir).exists());
}
/**
* Inputs to the compiler:
* inpath is 'indir2' that contains a helloworld source file and class file.
* source is 'src2' which contains Aspect.java which weaves before advice into the HelloWorld code from 'indir2'
*
* Expected result: HelloWorld copied through to output jar and 'weaved'. Compiled version of Aspect.java put into
* the output jar. The HelloWorld.java source file is also copied through to the output jar.
*
* An extra check is done at the end of this test to verify that HelloWorld has changed size (due to the weaving).
*/
public void testInpathToOutjar2() {
Set inpath = new HashSet();
File indir2 = openFile(indir2Name);
inpath.add(indir2);
ideManager.getProjectProperties().setInpath(inpath);
File outjar = openFile(outjarName);
ideManager.getProjectProperties().setOutJar(outjar.getAbsolutePath());
assertTrue("Build failed", doSynchronousBuild("build2.lst"));
assertTrue(
"Build warnings",
ideManager.getCompilationSourceLineTasks().isEmpty());
Set expectedOutputJarContents = new HashSet();
// From indir1
expectedOutputJarContents.add("example/HelloWorld.class");
// If we don't copy resources, this file won't make it
// expectedOutputJarContents.add("example/HelloWorld.java");
// From src
expectedOutputJarContents.add("Aspect.class");
compareJars(indir2, "src", outjar, expectedOutputJarContents);
// Extra test. The HelloWorld class from the input directory should have been woven
// by the aspect - verify that the size of the HelloWorld class in the output directory
// is a different size to the input version.
int outputsize = fetchFromJar(outjar, "example/HelloWorld.class");
try {
FileInputStream fis = new FileInputStream(openFile(indir2Name+"/example/HelloWorld.class"));
byte[] filedata = FileUtil.readAsByteArray(fis);
int inputsize = filedata.length;
assertTrue("Weaving of Aspect should have occurred but the input and output size for HelloWorld.class are the same",
(inputsize!=outputsize));
} catch (Exception e) {
e.printStackTrace();
fail();
}
FileUtil.deleteContents(openFile(binDir));
openFile(binDir).delete();
assertFalse(openFile(binDir).exists());
}
/**
* More complex inpath - a jar and a directory
*
* Inputs:
* -inpath injar.jar;indir2
* source is 'src2' which contains Aspect.java
*
* Expected result: Result should be a directory containing the contents of injar.jar and indir2 and the
* Aspect.class file.
*
*/
public void testInpathAndInjarToBin() {
Set inpath = new HashSet();
File indir2 = openFile(indir2Name);
inpath.add(indir2);
inpath.add(openFile(injarName));
ideManager.getProjectProperties().setInpath(inpath);
assertTrue("Build failed", doSynchronousBuild("build2.lst"));
assertTrue("Build warnings",ideManager.getCompilationSourceLineTasks().isEmpty());
Set expectedBindirContents = new HashSet();
// From indir1
expectedBindirContents.add("example/HelloWorld.class");
// If we don't copy resources, this file won't make it
// expectedBindirContents.add("example/HelloWorld.java");
// From injar.jar
expectedBindirContents.add("props/resources.properties");
// From src
expectedBindirContents.add("Aspect.class");
compareIndirToBin(indir2, "src", "bin", expectedBindirContents);
// Check the input and output versions of HelloWorld.class are different sizes
try {
FileInputStream fis1 = new FileInputStream(openFile("indir2/example/HelloWorld.class"));
byte[] filedata1 = FileUtil.readAsByteArray(fis1);
int inputsize = filedata1.length;
FileInputStream fis2 = new FileInputStream(openFile("bin/example/HelloWorld.class"));
byte[] filedata2 = FileUtil.readAsByteArray(fis2);
int outputsize = filedata2.length;
assertTrue("Weaving of Aspect should have occurred but the input and output size for HelloWorld.class are the same",
(outputsize!=inputsize));
fis1.close();
fis2.close();
} catch (Exception e) {
e.printStackTrace();
fail();
}
FileUtil.deleteContents(openFile(binDir));
openFile(binDir).delete();
assertFalse(openFile(binDir).exists());
}
// Return the size of specified entry from the output jar file
public int fetchFromJar(File outjarFile, String filename) {
int ret = -1;
try {
ZipInputStream outjar;
outjar =
new ZipInputStream(new java.io.FileInputStream(outjarFile));
ZipEntry entry;
while (null != (entry = outjar.getNextEntry())) {
String zipentryname = entry.getName();
if (zipentryname.equals(filename)) {
byte[] filedata = FileUtil.readAsByteArray(outjar);
ret = filedata.length;
outjar.closeEntry();
break;
}
outjar.closeEntry();
}
outjar.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
/*
* Ensure -outjar contains all non-Java resouces from injars
*/
public void compareJars(
File dirFile,
String sourceDir,
File outjarFile,
Set expectedOutputJarContents) {
try {
assertTrue(
"outjar older than injar",
(outjarFile.lastModified() > dirFile.lastModified()));
// Go through the output jar file, for each element, remove it from
// the expectedOutputJarContents - when we finish, the expectedOutputJarContents
// set should be empty!
ZipInputStream outjar =
new ZipInputStream(new java.io.FileInputStream(outjarFile));
ZipEntry entry;
while (null != (entry = outjar.getNextEntry())) {
String fileName = entry.getName();
fileName = fileName.replace('\\', '/');
if (fileName.indexOf("CVS") == -1) {
boolean b = expectedOutputJarContents.remove(fileName);
assertTrue(
"Unexpectedly found : " + fileName + " in outjar",
b);
}
outjar.closeEntry();
}
outjar.close();
assertTrue(
"Didnt make it into the output jar: "
+ expectedOutputJarContents.toString(),
expectedOutputJarContents.isEmpty());
} catch (IOException ex) {
fail(ex.toString());
}
}
/*
* Ensure -outjar contains all non-Java resouces from source and injars
*/
public void compareSourceToOutjar(String indirName, File outjarFile) {
HashSet resources = new HashSet();
listSourceResources(indirName, resources);
try {
ZipInputStream outjar =
new ZipInputStream(new java.io.FileInputStream(outjarFile));
ZipEntry entry;
while (null != (entry = outjar.getNextEntry())) {
String fileName = entry.getName();
if (!fileName.endsWith(".class")) {
boolean b = resources.remove(fileName);
assertTrue(fileName, b);
}
outjar.closeEntry();
}
outjar.close();
assertTrue(
"Missing resources: " + resources.toString(),
resources.isEmpty());
} catch (IOException ex) {
fail(ex.toString());
}
}
/*
* Ensure bin contains all non-Java resouces from source and injars
*/
public void compareIndirToBin(
File indirFile,
String sourceDir,
String outdirName,
Set expectedOutdirContents) {
// byte[] inManifest = null;
File binBase = openFile(outdirName);
String[] toResources = FileUtil.listFiles(binBase);
for (int i = 0; i < toResources.length; i++) {
String fileName = toResources[i];
if (fileName.indexOf("CVS") == -1) {
boolean b = expectedOutdirContents.remove(fileName);
assertTrue("Extraneous resources: " + fileName, b);
}
}
assertTrue(
"Missing resources: " + expectedOutdirContents.toString(),
expectedOutdirContents.isEmpty());
}
/**
* @param resources
*/
// private void dumpResources(HashSet resources) {
// System.err.println("Dump: " + resources.size() + " resources");
// for (Iterator iter = resources.iterator(); iter.hasNext();) {
// Object element = (Object) iter.next();
// System.err.println(" Resource: " + element);
// }
// }
private void listSourceResources(String indirName, Set resources) {
File srcBase = openFile(indirName);
File[] fromResources =
FileUtil.listFiles(srcBase, aspectjResourceFileFilter);
for (int i = 0; i < fromResources.length; i++) {
String name = FileUtil.normalizedPath(fromResources[i], srcBase);
//System.err.println("Checking "+name);
if (!name.startsWith("CVS/")
&& (-1 == name.indexOf("/CVS/"))
&& !name.endsWith("/CVS")) {
resources.add(name);
}
}
}
// private byte[] listDirResources(File directory, Set resources) {
// return listDirResources(
// directory.getAbsolutePath(),
// directory,
// resources);
// }
// private byte[] listDirResources(
// String prefix,
// File directory,
// Set resources) {
// byte[] manifest = null;
//
// File[] resourceFiles = directory.listFiles(new FileFilter() {
// public boolean accept(File arg0) {
// boolean accept =
// !arg0.getName().endsWith(".class") && !arg0.isDirectory();
// return accept;
// }
// });
// for (int i = 0; i < resourceFiles.length; i++) {
// File f = resourceFiles[i];
// String name = f.getAbsolutePath();
// if (f.getAbsolutePath().startsWith(prefix))
// name = name.substring(prefix.length());
// name = name.replace('\\', '/');
//
// resources.add(resourceFiles[i]);
// }
// File[] subdirs = directory.listFiles(new FileFilter() {
// public boolean accept(File arg0) {
// return arg0.isDirectory();
// }
// });
// for (int i = 0; i < subdirs.length; i++) {
// listDirResources(prefix, subdirs[i], resources);
// }
//
// return manifest;
// }
public static final FileFilter aspectjResourceFileFilter =
new FileFilter() {
public boolean accept(File pathname) {
String name = pathname.getName().toLowerCase();
return (
!name.endsWith(".class")
&& !name.endsWith(".java")
&& !name.endsWith(".aj"));
}
};
/*
* Ensure bin contains all non-Java resouces from source and injars
*/
public void compareDirs(String indirName, String outdirName) {
File binBase = openFile(outdirName);
File[] toResources =
FileUtil.listFiles(binBase, aspectjResourceFileFilter);
HashSet resources = new HashSet();
listSourceResources(indirName, resources);
for (int i = 0; i < toResources.length; i++) {
String fileName = FileUtil.normalizedPath(toResources[i], binBase);
boolean b = resources.remove(fileName);
assertTrue("Extraneous resources: " + fileName, b);
}
assertTrue(
"Missing resources: " + resources.toString(),
resources.isEmpty());
}
}
|
47,910
|
Bug 47910 ajc -outjar jarfile does not contain MANIFEST.MF
|
I call ajc -sourceroots <mydir> -outjar <my.jar> and an output file is created with a .jar extension, but it is not a valid jar file because there is no MANIFEST.MF file. I see that the text for ajc says: -outjar <file> put output classes in zip file <file> which might imply that it is supposed to be a zip file, but a parameter called - outjar which creates a zip file doesn't really make sense. If -outjar is used, the resulting file should be a valid jar file, i.e. with a META-INF/MANIFEST.MF file inside.
|
resolved fixed
|
34dbb0c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-17T12:25:49Z
| 2003-12-02T18:33:20Z
|
ajde/testsrc/org/aspectj/ajde/JarManifestTest.java
| |
47,910
|
Bug 47910 ajc -outjar jarfile does not contain MANIFEST.MF
|
I call ajc -sourceroots <mydir> -outjar <my.jar> and an output file is created with a .jar extension, but it is not a valid jar file because there is no MANIFEST.MF file. I see that the text for ajc says: -outjar <file> put output classes in zip file <file> which might imply that it is supposed to be a zip file, but a parameter called - outjar which creates a zip file doesn't really make sense. If -outjar is used, the resulting file should be a valid jar file, i.e. with a META-INF/MANIFEST.MF file inside.
|
resolved fixed
|
34dbb0c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-17T12:25:49Z
| 2003-12-02T18:33:20Z
|
ajde/testsrc/org/aspectj/ajde/ResourceCopyTestCase.java
|
/* *******************************************************************
* Copyright (c) 2003 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Mik Kersten initial implementation
* ******************************************************************/
package org.aspectj.ajde;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import org.aspectj.util.FileUtil;
/**
* @author websterm
*/
public class ResourceCopyTestCase extends AjdeTestCase {
public static final String PROJECT_DIR = "bug-36071a";
public static final String srcDir = PROJECT_DIR + "/src";
public static final String binDir = "bin";
public static final String injar1Name = "input1.jar";
public static final String injar2Name = "input2.jar";
public static final String outjarName = "/bin/output.jar";
/**
* Constructor for JarResourceCopyTestCase.
* @param arg0
*/
public ResourceCopyTestCase(String arg0) {
super(arg0);
}
/*
* Ensure the output directpry in clean
*/
protected void setUp() throws Exception {
super.setUp(PROJECT_DIR);
FileUtil.deleteContents(openFile(binDir));
}
public void testSrcToBin () {
assertTrue(!Ajde.getDefault().getTaskListManager().hasWarning());
assertTrue("Build failed",doSynchronousBuild("config1.lst"));
compareDirs("src","bin");
}
public void testInjarsToOutjar () {
Set injars = new HashSet();
File injar1 = openFile(injar1Name);
injars.add(injar1);
ideManager.getProjectProperties().setInJars(injars);
File outjar = openFile(outjarName);
ideManager.getProjectProperties().setOutJar(outjar.getAbsolutePath());
assertTrue("Build failed",doSynchronousBuild("config2.lst"));
assertTrue("Build warnings",ideManager.getCompilationSourceLineTasks().isEmpty());
compareJars(injar1,"src",outjar);
}
public void testDuplicateResources () {
Set injars = new HashSet();
File injar1 = openFile(injar1Name);
File injar2 = openFile(injar2Name);
injars.add(injar1);
injars.add(injar2);
ideManager.getProjectProperties().setInJars(injars);
File outjar = openFile(outjarName);
ideManager.getProjectProperties().setOutJar(outjar.getAbsolutePath());
assertTrue("Build should have suceeded",doSynchronousBuild("config2.lst"));
assertFalse("Build warnings for duplicate resource expected",ideManager.getCompilationSourceLineTasks().isEmpty());
List msgs = NullIdeManager.getIdeManager().getCompilationSourceLineTasks();
assertTrue("Wrong message",((NullIdeTaskListManager.SourceLineTask)msgs.get(0)).message.getMessage().startsWith("duplicate resource: "));
compareJars(injar1,"src",outjar);
}
public void testSrcToOutjar () {
File outjar = openFile(outjarName);
ideManager.getProjectProperties().setOutJar(outjar.getAbsolutePath());
assertTrue("Build failed",doSynchronousBuild("config1.lst"));
compareSourceToOutjar("src",outjar);
}
public void testInjarsToBin () {
Set injars = new HashSet();
File injar1 = openFile(injar1Name);
injars.add(injar1);
ideManager.getProjectProperties().setInJars(injars);
assertTrue("Build failed",doSynchronousBuild("config2.lst"));
assertTrue("Build warnings",ideManager.getCompilationSourceLineTasks().isEmpty());
compareInjarsToBin(injar1,"src","bin");
}
/*
* Ensure bin contains all non-Java resouces from source and injars
*/
public void compareDirs (String indirName, String outdirName) {
File binBase = openFile(outdirName);
File[] toResources = FileUtil.listFiles(binBase,aspectjResourceFileFilter);
HashSet resources = new HashSet();
listSourceResources(indirName,resources);
for (int i = 0; i < toResources.length; i++) {
String fileName = FileUtil.normalizedPath(toResources[i],binBase);
boolean b = resources.remove(fileName);
assertTrue("Extraneous resources: " + fileName,b);
}
assertTrue("Missing resources: " + resources.toString(), resources.isEmpty());
}
/*
* Ensure -outjar contains all non-Java resouces from injars
*/
public void compareJars (File injarFile, String indirName, File outjarFile) {
HashSet resources = new HashSet();
try {
assertTrue("outjar older than injar",(outjarFile.lastModified() > injarFile.lastModified()));
byte[] inManifest = listJarResources(injarFile,resources);
listSourceResources(indirName,resources);
ZipInputStream outjar = new ZipInputStream(new java.io.FileInputStream(outjarFile));
ZipEntry entry;
while (null != (entry = outjar.getNextEntry())) {
String fileName = entry.getName();
if (!fileName.endsWith(".class")) {
/* Ensure we copied right JAR manifest */
if (fileName.equalsIgnoreCase("meta-inf/Manifest.mf")) {
byte[] outManifest = FileUtil.readAsByteArray(outjar);
assertTrue("Wrong manifest has been copied",Arrays.equals(inManifest,outManifest));
}
boolean b = resources.remove(fileName);
assertTrue(fileName,b);
}
outjar.closeEntry();
}
outjar.close();
assertTrue(resources.toString(),resources.isEmpty());
}
catch (IOException ex) {
fail(ex.toString());
}
}
/*
* Ensure -outjar conatins all non-Java resouces from source and injars
*/
public void compareSourceToOutjar (String indirName, File outjarFile) {
HashSet resources = new HashSet();
listSourceResources(indirName,resources);
try {
ZipInputStream outjar = new ZipInputStream(new java.io.FileInputStream(outjarFile));
ZipEntry entry;
while (null != (entry = outjar.getNextEntry())) {
String fileName = entry.getName();
if (!fileName.endsWith(".class")) {
boolean b = resources.remove(fileName);
assertTrue(fileName,b);
}
outjar.closeEntry();
}
outjar.close();
assertTrue("Missing resources: " + resources.toString(), resources.isEmpty());
}
catch (IOException ex) {
fail(ex.toString());
}
}
/*
* Ensure bin contains all non-Java resouces from source and injars
*/
public void compareInjarsToBin(File injarFile, String indirName, String outdirName) {
HashSet resources = new HashSet();
try {
byte[] inManifest = listJarResources(injarFile,resources);
listSourceResources(indirName,resources);
File binBase = openFile(outdirName);
File[] toResources = FileUtil.listFiles(binBase,aspectjResourceFileFilter);
for (int i = 0; i < toResources.length; i++) {
String fileName = FileUtil.normalizedPath(toResources[i],binBase);
/* Ensure we copied the right JAR manifest */
if (fileName.equalsIgnoreCase("meta-inf/Manifest.mf")) {
byte[] outManifest = FileUtil.readAsByteArray(toResources[i]);
assertTrue("Wrong manifest has been copied",Arrays.equals(inManifest,outManifest));
}
boolean b = resources.remove(fileName);
assertTrue("Extraneous resources: " + fileName,b);
}
assertTrue("Missing resources: " + resources.toString(), resources.isEmpty());
}
catch (IOException ex) {
fail(ex.toString());
}
}
private void listSourceResources (String indirName, Set resources) {
File srcBase = openFile(indirName);
File[] fromResources = FileUtil.listFiles(srcBase,aspectjResourceFileFilter);
for (int i = 0; i < fromResources.length; i++) {
String name = FileUtil.normalizedPath(fromResources[i],srcBase);
if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) {
resources.add(name);
}
}
}
private byte[] listJarResources (File injarFile, Set resources) {
byte[] manifest = null;
try {
ZipInputStream injar = new ZipInputStream(new java.io.FileInputStream(injarFile));
ZipEntry entry;
while (null != (entry = injar.getNextEntry())) {
String fileName = entry.getName();
if (!entry.isDirectory() && !fileName.endsWith(".class")) {
/* JAR manifests shouldn't be copied */
if (fileName.equalsIgnoreCase("meta-inf/Manifest.mf")) {
manifest = FileUtil.readAsByteArray(injar);
}
resources.add(fileName);
}
injar.closeEntry();
}
injar.close();
}
catch (IOException ex) {
fail(ex.toString());
}
return manifest;
}
public static final FileFilter aspectjResourceFileFilter = new FileFilter() {
public boolean accept(File pathname) {
String name = pathname.getName().toLowerCase();
return (!name.endsWith(".class") && !name.endsWith(".java") && !name.endsWith(".aj"));
}
};
}
|
47,910
|
Bug 47910 ajc -outjar jarfile does not contain MANIFEST.MF
|
I call ajc -sourceroots <mydir> -outjar <my.jar> and an output file is created with a .jar extension, but it is not a valid jar file because there is no MANIFEST.MF file. I see that the text for ajc says: -outjar <file> put output classes in zip file <file> which might imply that it is supposed to be a zip file, but a parameter called - outjar which creates a zip file doesn't really make sense. If -outjar is used, the resulting file should be a valid jar file, i.e. with a META-INF/MANIFEST.MF file inside.
|
resolved fixed
|
34dbb0c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-17T12:25:49Z
| 2003-12-02T18:33:20Z
|
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 java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.aspectj.ajdt.internal.compiler.AjCompilerAdapter;
import org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor;
import org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider;
import org.aspectj.ajdt.internal.compiler.InterimCompilationResult;
import org.aspectj.ajdt.internal.compiler.lookup.*;
import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter;
import org.aspectj.asm.*;
//import org.aspectj.asm.internal.*;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.*;
import org.aspectj.util.FileUtil;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.*;
import org.eclipse.jdt.core.compiler.*;
import org.eclipse.jdt.internal.compiler.*;
import org.eclipse.jdt.internal.compiler.batch.*;
import org.eclipse.jdt.internal.compiler.batch.FileSystem;
import org.eclipse.jdt.internal.compiler.env.*;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.parser.Parser;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
//import org.eclipse.jdt.internal.compiler.util.HashtableOfObject;
public class AjBuildManager implements IOutputClassFileNameProvider,ICompilerAdapterFactory {
private static final String CANT_WRITE_RESULT = "unable to write compilation result";
static final boolean COPY_INPATH_DIR_RESOURCES = false;
static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false;
private IProgressListener progressListener = null;
private int compiledCount;
private int sourceFileCount;
private ZipOutputStream zos;
private boolean batchCompile = true;
private INameEnvironment environment;
private IHierarchy structureModel;
public AjBuildConfig buildConfig;
AjState state = new AjState(this);
BcelWeaver bcelWeaver;
public BcelWorld bcelWorld;
public CountingMessageHandler handler;
public AjBuildManager(IMessageHandler holder) {
super();
this.handler = CountingMessageHandler.makeCountingMessageHandler(holder);
}
/** @return true if we should generate a model as a side-effect */
public boolean doGenerateModel() {
return buildConfig.isGenerateModelMode();
}
public boolean batchBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler)
throws IOException, AbortException {
return doBuild(buildConfig, baseHandler, true);
}
public boolean incrementalBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler)
throws IOException, AbortException {
return doBuild(buildConfig, baseHandler, false);
}
/** @throws AbortException if check for runtime fails */
protected boolean doBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler,
boolean batch) throws IOException, AbortException {
boolean ret = true;
batchCompile = batch;
try {
if (batch) {
this.state = new AjState(this);
}
boolean canIncremental = state.prepareForNextBuild(buildConfig);
if (!canIncremental && !batch) { // retry as batch?
return doBuild(buildConfig, baseHandler, true);
}
this.handler =
CountingMessageHandler.makeCountingMessageHandler(baseHandler);
// XXX duplicate, no? remove?
String check = checkRtJar(buildConfig);
if (check != null) {
if (FAIL_IF_RUNTIME_NOT_FOUND) {
MessageUtil.error(handler, check);
return false;
} else {
MessageUtil.warn(handler, check);
}
}
// if (batch) {
setBuildConfig(buildConfig);
//}
// if (batch) {
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
setupModel();
// }
// }
if (batch) {
initBcelWorld(handler);
}
if (handler.hasErrors()) {
return false;
}
if (buildConfig.getOutputJar() != null) {
if (!openOutputStream(buildConfig.getOutputJar())) return false;
}
if (batch) {
// System.err.println("XXXX batch: " + buildConfig.getFiles());
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
bcelWorld.setModel(AsmManager.getDefault().getHierarchy());
// in incremental build, only get updated model?
}
performCompilation(buildConfig.getFiles());
if (handler.hasErrors()) {
return false;
}
} else {
// done already?
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
// bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel());
// }
// System.err.println("XXXX start inc ");
List files = state.getFilesToCompile(true);
for (int i = 0; (i < 5) && !files.isEmpty(); i++) {
// System.err.println("XXXX inc: " + files);
performCompilation(files);
if (handler.hasErrors()) {
return false;
}
files = state.getFilesToCompile(false);
}
if (!files.isEmpty()) {
return batchBuild(buildConfig, baseHandler);
}
}
// XXX not in Mik's incremental
if (buildConfig.isEmacsSymMode()) {
new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel();
}
// have to tell state we succeeded or next is not incremental
state.successfulCompile(buildConfig);
copyResourcesToDestination();
/*boolean weaved = *///weaveAndGenerateClassFiles();
// if not weaved, then no-op build, no model changes
// but always returns true
// XXX weaved not in Mik's incremental
if (buildConfig.isGenerateModelMode()) {
AsmManager.getDefault().fireModelUpdated();
}
} finally {
if (zos != null) {
closeOutputStream();
}
ret = !handler.hasErrors();
handler = null;
}
return ret;
}
private boolean openOutputStream(File outJar) {
try {
OutputStream os = FileUtil.makeOutputStream(buildConfig.getOutputJar());
zos = new ZipOutputStream(os);
} catch (IOException ex) {
IMessage message =
new Message("Unable to open outjar "
+ outJar.getPath()
+ "(" + ex.getMessage()
+ ")",
new SourceLocation(outJar,0),
true);
handler.handleMessage(message);
return false;
}
return true;
}
private void closeOutputStream() {
try {
if (zos != null) zos.close();
zos = null;
} catch (IOException ex) {
IMessage message =
new Message("Unable to write outjar "
+ buildConfig.getOutputJar().getPath()
+ "(" + ex.getMessage()
+ ")",
new SourceLocation(buildConfig.getOutputJar(),0),
true);
handler.handleMessage(message);
}
}
private void copyResourcesToDestination() throws IOException {
// resources that we need to copy are contained in the injars and inpath only
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File inJar = (File)i.next();
copyResourcesFromJarFile(inJar);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (inPathElement.isDirectory()) {
copyResourcesFromDirectory(inPathElement);
} else {
copyResourcesFromJarFile(inPathElement);
}
}
if (buildConfig.getSourcePathResources() != null) {
for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) {
String resource = (String)i.next();
File from = (File)buildConfig.getSourcePathResources().get(resource);
copyResourcesFromFile(from,resource,from);
}
}
}
private void copyResourcesFromJarFile(File jarFile) throws IOException {
ZipInputStream inStream = null;
try {
inStream = new ZipInputStream(new FileInputStream(jarFile));
while (true) {
ZipEntry entry = inStream.getNextEntry();
if (entry == null) break;
String filename = entry.getName();
if (!entry.isDirectory() && acceptResource(filename)) {
byte[] bytes = FileUtil.readAsByteArray(inStream);
writeResource(filename,bytes,jarFile);
}
inStream.closeEntry();
}
} finally {
if (inStream != null) inStream.close();
}
}
private void copyResourcesFromDirectory(File dir) throws IOException {
if (!COPY_INPATH_DIR_RESOURCES) return;
// Get a list of all files (i.e. everything that isnt a directory)
File[] files = FileUtil.listFiles(dir,new FileFilter() {
public boolean accept(File f) {
boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")) ;
return accept;
}
});
// For each file, add it either as a real .class file or as a resource
for (int i = 0; i < files.length; i++) {
// ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
// or we are in trouble...
String filename = files[i].getAbsolutePath().substring(
dir.getAbsolutePath().length()+1);
copyResourcesFromFile(files[i],filename,dir);
}
}
private void copyResourcesFromFile(File f,String filename,File src) throws IOException {
if (!acceptResource(filename)) return;
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
byte[] bytes = FileUtil.readAsByteArray(fis);
// String relativePath = files[i].getPath();
writeResource(filename,bytes,src);
} finally {
if (fis != null) fis.close();
}
}
private void writeResource(String filename, byte[] content, File srcLocation) throws IOException {
if (state.resources.contains(filename)) {
IMessage msg = new Message("duplicate resource: '" + filename + "'",
IMessage.WARNING,
null,
new SourceLocation(srcLocation,0));
handler.handleMessage(msg);
return;
}
if (zos != null) {
ZipEntry newEntry = new ZipEntry(filename); //??? get compression scheme right
zos.putNextEntry(newEntry);
zos.write(content);
zos.closeEntry();
} else {
OutputStream fos =
FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),filename));
fos.write(content);
fos.close();
}
state.resources.add(filename);
}
private boolean acceptResource(String resourceName) {
if (
(resourceName.startsWith("CVS/")) ||
(resourceName.indexOf("/CVS/") != -1) ||
(resourceName.endsWith("/CVS")) ||
(resourceName.endsWith(".class"))
)
{
return false;
} else {
return true;
}
}
/**
* Responsible for managing the ASM model between builds. Contains the policy for
* maintaining the persistance of elements in the model.
*
* TODO: implement incremental policy.
*/
private void setupModel() {
String rootLabel = "<root>";
IHierarchy model = AsmManager.getDefault().getHierarchy();
AsmManager.getDefault().getRelationshipMap().clear();
IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA;
if (buildConfig.getConfigFile() != null) {
rootLabel = buildConfig.getConfigFile().getName();
model.setConfigFile(
buildConfig.getConfigFile().getAbsolutePath()
);
kind = IProgramElement.Kind.FILE_LST;
}
model.setRoot(new ProgramElement(rootLabel, kind, new ArrayList()));
model.setFileMap(new HashMap());
setStructureModel(model);
}
/** init only on initial batch compile? no file-specific options */
private void initBcelWorld(IMessageHandler handler) throws IOException {
bcelWorld = new BcelWorld(buildConfig.getClasspath(), handler, null);
bcelWorld.setXnoInline(buildConfig.isXnoInline());
bcelWorld.setXlazyTjp(buildConfig.isXlazyTjp());
bcelWeaver = new BcelWeaver(bcelWorld);
state.binarySourceFiles = new HashMap();
for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext();) {
File f = (File) i.next();
bcelWeaver.addLibraryJarFile(f);
}
// String lintMode = buildConfig.getLintMode();
if (buildConfig.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT)) {
bcelWorld.getLint().loadDefaultProperties();
} else {
bcelWorld.getLint().setAll(buildConfig.getLintMode());
}
if (buildConfig.getLintSpecFile() != null) {
bcelWorld.getLint().setFromProperties(buildConfig.getLintSpecFile());
}
//??? incremental issues
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File inJar = (File)i.next();
List unwovenClasses = bcelWeaver.addJarFile(inJar, buildConfig.getOutputDir(),false);
state.binarySourceFiles.put(inJar.getPath(), unwovenClasses);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
List unwovenClasses = bcelWeaver.addJarFile(inPathElement,buildConfig.getOutputDir(),true);
state.binarySourceFiles.put(inPathElement.getPath(),unwovenClasses); // good enough for ajc to lump these together
}
// if (buildConfig.getSourcePathResources() != null) {
// // XXX buildConfig.getSourcePathResources always returns null (CompileCommand.java)
// for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) {
// // File resource = (File)i.next();
// String resource = (String)i.next();
// bcelWeaver.addResource(resource, (File)buildConfig.getSourcePathResources().get(resource), buildConfig.getOutputDir());
// // bcelWeaver.addResource(resource, buildConfig.getOutputDir());
// }
// }
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 = (String) buildConfig.getJavaOptions().get(CompilerOptions.OPTION_Encoding);
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 = (String) buildConfig.getJavaOptions().get(CompilerOptions.OPTION_Encoding);
if ("".equals(defaultEncoding)) //$NON-NLS-1$
defaultEncoding = null; //$NON-NLS-1$
for (int i = 0; i < fileCount; i++) {
String encoding = encodings[i];
if (encoding == null)
encoding = defaultEncoding;
units[i] = new CompilationUnit(null, filenames[i], encoding);
}
return units;
}
public String extractDestinationPathFromSourceFile(CompilationResult result) {
ICompilationUnit compilationUnit = result.compilationUnit;
if (compilationUnit != null) {
char[] fileName = compilationUnit.getFileName();
int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName);
if (lastIndex == -1) {
return System.getProperty("user.dir"); //$NON-NLS-1$
}
return new String(CharOperation.subarray(fileName, 0, lastIndex));
}
return System.getProperty("user.dir"); //$NON-NLS-1$
}
public void performCompilation(List files) {
if (progressListener != null) {
compiledCount = 0;
sourceFileCount = files.size();
progressListener.setText("compiling source files");
}
//System.err.println("got files: " + files);
String[] filenames = new String[files.size()];
String[] encodings = new String[files.size()];
//System.err.println("filename: " + this.filenames);
for (int i=0; i < files.size(); i++) {
filenames[i] = ((File)files.get(i)).getPath();
}
List cps = buildConfig.getFullClasspath();
String[] classpaths = new String[cps.size()];
for (int i=0; i < cps.size(); i++) {
classpaths[i] = (String)cps.get(i);
}
//System.out.println("compiling");
environment = getLibraryAccess(classpaths, filenames);
if (!state.classesFromName.isEmpty()) {
environment = new StatefulNameEnvironment(environment, state.classesFromName);
}
org.eclipse.jdt.internal.compiler.Compiler.setCompilerAdapterFactory(this);
org.eclipse.jdt.internal.compiler.Compiler compiler =
new org.eclipse.jdt.internal.compiler.Compiler(environment,
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
buildConfig.getJavaOptions(),
getBatchRequestor(),
getProblemFactory());
CompilerOptions options = compiler.options;
options.produceReferenceInfo(true); //TODO turn off when not needed
compiler.compile(getCompilationUnits(filenames, encodings));
// 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);
}
};
}
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(
unitResult.compilationUnit,
CANT_WRITE_RESULT,
ex);
handler.handleMessage(message);
}
}
}
if (unitResult.hasProblems() || unitResult.hasTasks()) {
IProblem[] problems = unitResult.getAllProblems();
for (int i=0; i < problems.length; i++) {
IMessage message =
EclipseAdapterUtils.makeMessage(unitResult.compilationUnit, problems[i]);
handler.handleMessage(message);
}
}
}
private void writeDirectoryEntry(
CompilationResult unitResult,
ClassFile classFile,
String filename)
throws IOException {
File destinationPath = buildConfig.getOutputDir();
String outFile;
if (destinationPath == null) {
outFile = new File(filename).getName();
outFile = new File(extractDestinationPathFromSourceFile(unitResult), outFile).getPath();
} else {
outFile = new File(destinationPath, filename).getPath();
}
BufferedOutputStream os =
FileUtil.makeOutputStream(new File(outFile));
os.write(classFile.getBytes());
os.close();
}
private void writeZipEntry(ClassFile classFile, String name)
throws IOException {
name = name.replace(File.separatorChar,'/');
ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right
zos.putNextEntry(newEntry);
zos.write(classFile.getBytes());
zos.closeEntry();
}
};
}
protected boolean proceedOnError() {
return true; //???
}
// public void noteClassFiles(AjCompiler.InterimResult result) {
// if (result == null) return;
// CompilationResult unitResult = result.result;
// String sourceFileName = result.fileName();
// if (!(unitResult.hasErrors() && !proceedOnError())) {
// List unwovenClassFiles = new ArrayList();
// Enumeration classFiles = unitResult.compiledTypes.elements();
// while (classFiles.hasMoreElements()) {
// ClassFile classFile = (ClassFile) classFiles.nextElement();
// String filename = new String(classFile.fileName());
// filename = filename.replace('/', File.separatorChar) + ".class";
//
// File destinationPath = buildConfig.getOutputDir();
// if (destinationPath == null) {
// filename = new File(filename).getName();
// filename = new File(extractDestinationPathFromSourceFile(unitResult), filename).getPath();
// } else {
// filename = new File(destinationPath, filename).getPath();
// }
//
// //System.out.println("classfile: " + filename);
// unwovenClassFiles.add(new UnwovenClassFile(filename, classFile.getBytes()));
// }
// state.noteClassesFromFile(unitResult, sourceFileName, unwovenClassFiles);
//// System.out.println("file: " + sourceFileName);
//// for (int i=0; i < unitResult.simpleNameReferences.length; i++) {
//// System.out.println("simple: " + new String(unitResult.simpleNameReferences[i]));
//// }
//// for (int i=0; i < unitResult.qualifiedReferences.length; i++) {
//// System.out.println("qualified: " +
//// new String(CharOperation.concatWith(unitResult.qualifiedReferences[i], '/')));
//// }
// } else {
// state.noteClassesFromFile(null, sourceFileName, Collections.EMPTY_LIST);
// }
// }
//
private void setBuildConfig(AjBuildConfig buildConfig) {
this.buildConfig = buildConfig;
handler.reset();
}
String makeClasspathString() {
if (buildConfig == null || buildConfig.getClasspath() == null) return "";
StringBuffer buf = new StringBuffer();
boolean first = true;
for (Iterator it = buildConfig.getClasspath().iterator(); it.hasNext(); ) {
if (first) { first = false; }
else { buf.append(File.pathSeparator); }
buf.append(it.next().toString());
}
return buf.toString();
}
/**
* This will return null if aspectjrt.jar is present and has the correct version.
* Otherwise it will return a string message indicating the problem.
*/
public String checkRtJar(AjBuildConfig buildConfig) {
// omitting dev info
if (Version.text.equals(Version.DEVELOPMENT)) {
// in the development version we can't do this test usefully
// MessageUtil.info(holder, "running development version of aspectj compiler");
return null;
}
if (buildConfig == null || buildConfig.getClasspath() == null) return "no classpath specified";
for (Iterator it = buildConfig.getClasspath().iterator(); it.hasNext(); ) {
File p = new File( (String)it.next() );
if (p.isFile() && p.getName().equals("aspectjrt.jar")) {
try {
String version = null;
Manifest manifest = new JarFile(p).getManifest();
if (manifest == null) {
return "no manifest found in " + p.getAbsolutePath() +
", expected " + Version.text;
}
Attributes attr = manifest.getAttributes("org/aspectj/lang/");
if (null != attr) {
version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
if (null != version) {
version = version.trim();
}
}
// assume that users of development aspectjrt.jar know what they're doing
if (Version.DEVELOPMENT.equals(version)) {
// MessageUtil.info(holder,
// "running with development version of aspectjrt.jar in " +
// p.getAbsolutePath());
return null;
} else if (!Version.text.equals(version)) {
return "bad version number found in " + p.getAbsolutePath() +
" expected " + Version.text + " found " + version;
}
} catch (IOException ioe) {
return "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe;
}
return null;
} else {
// might want to catch other classpath errors
}
}
return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString();
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("AjBuildManager(");
buf.append(")");
return buf.toString();
}
public void setStructureModel(IHierarchy structureModel) {
this.structureModel = structureModel;
}
/**
* Returns null if there is no structure model
*/
public IHierarchy getStructureModel() {
return structureModel;
}
public IProgressListener getProgressListener() {
return progressListener;
}
public void setProgressListener(IProgressListener progressListener) {
this.progressListener = progressListener;
}
/* (non-Javadoc)
* @see org.aspectj.ajdt.internal.compiler.AjCompiler.IOutputClassFileNameProvider#getOutputClassFileName(char[])
*/
public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) {
String filename = new String(eclipseClassFileName);
filename = filename.replace('/', File.separatorChar) + ".class";
File destinationPath = buildConfig.getOutputDir();
String outFile;
if (destinationPath == null) {
outFile = new File(filename).getName();
outFile = new File(extractDestinationPathFromSourceFile(result), outFile).getPath();
} else {
outFile = new File(destinationPath, filename).getPath();
}
return outFile;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler)
*/
public ICompilerAdapter getAdapter(org.eclipse.jdt.internal.compiler.Compiler forCompiler) {
// complete compiler config and return a suitable adapter...
AjProblemReporter pr =
new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(),
forCompiler.options, getProblemFactory());
forCompiler.problemReporter = pr;
AjLookupEnvironment le =
new AjLookupEnvironment(forCompiler, forCompiler.options, pr, environment);
EclipseFactory factory = new EclipseFactory(le);
le.factory = factory;
pr.factory = factory;
le.factory.buildManager = this;
forCompiler.lookupEnvironment = le;
forCompiler.parser =
new Parser(
pr,
forCompiler.options.parseLiteralExpressionsAsConstants);
return new AjCompilerAdapter(forCompiler,batchCompile,bcelWorld,bcelWeaver,
factory,
getInterimResultRequestor(),this,
state.binarySourceFiles,
state.resultsFromFile.values(),
buildConfig.isNoWeave());
}
} // class AjBuildManager
|
47,910
|
Bug 47910 ajc -outjar jarfile does not contain MANIFEST.MF
|
I call ajc -sourceroots <mydir> -outjar <my.jar> and an output file is created with a .jar extension, but it is not a valid jar file because there is no MANIFEST.MF file. I see that the text for ajc says: -outjar <file> put output classes in zip file <file> which might imply that it is supposed to be a zip file, but a parameter called - outjar which creates a zip file doesn't really make sense. If -outjar is used, the resulting file should be a valid jar file, i.e. with a META-INF/MANIFEST.MF file inside.
|
resolved fixed
|
34dbb0c
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-17T12:25:49Z
| 2003-12-02T18:33:20Z
|
weaver/src/org/aspectj/weaver/bcel/BcelWeaver.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.JavaClass;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IProgressListener;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.util.FileUtil;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.CrosscuttingMembersSet;
import org.aspectj.weaver.IClassFileProvider;
import org.aspectj.weaver.IWeaveRequestor;
import org.aspectj.weaver.IWeaver;
import org.aspectj.weaver.NewParentTypeMunger;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.ResolvedTypeX;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.patterns.DeclareParents;
import org.aspectj.weaver.patterns.FastMatchInfo;
public class BcelWeaver implements IWeaver {
private BcelWorld world;
private CrosscuttingMembersSet xcutSet;
private IProgressListener progressListener = null;
private double progressMade;
private double progressPerClassFile;
private boolean inReweavableMode = false;
public BcelWeaver(BcelWorld world) {
super();
this.world = world;
this.xcutSet = world.getCrosscuttingMembersSet();
}
public BcelWeaver() {
this(new BcelWorld());
}
// ---- fields
// private Map sourceJavaClasses = new HashMap(); /* String -> UnwovenClassFile */
private List addedClasses = new ArrayList(); /* List<UnovenClassFile> */
private List deletedTypenames = new ArrayList(); /* List<String> */
// private Map resources = new HashMap(); /* String -> UnwovenClassFile */
private boolean needToReweaveWorld = false;
private List shadowMungerList = null; // setup by prepareForWeave
private List typeMungerList = null; // setup by prepareForWeave
private List declareParentsList = null; // setup by prepareForWeave
private ZipOutputStream zipOutputStream;
// ----
// only called for testing
public void setShadowMungers(List l) {
shadowMungerList = l;
}
public void addLibraryAspect(String aspectName) {
ResolvedTypeX type = world.resolve(aspectName);
//System.out.println("type: " + type + " for " + aspectName);
if (type.isAspect()) {
xcutSet.addOrReplaceAspect(type);
} else {
throw new RuntimeException("unimplemented");
}
}
public void addLibraryJarFile(File inFile) throws IOException {
ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered
List addedAspects = new ArrayList();
while (true) {
ZipEntry entry = inStream.getNextEntry();
if (entry == null) break;
if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
continue;
}
ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName());
JavaClass jc = parser.parse();
inStream.closeEntry();
ResolvedTypeX type = world.addSourceObjectType(jc).getResolvedTypeX();
if (type.isAspect()) {
addedAspects.add(type);
}
}
inStream.close();
for (Iterator i = addedAspects.iterator(); i.hasNext();) {
ResolvedTypeX aspectX = (ResolvedTypeX) i.next();
xcutSet.addOrReplaceAspect(aspectX);
}
}
// The ANT copy task should be used to copy resources across.
private final static boolean CopyResourcesFromInpathDirectoriesToOutput=false;
private Set alreadyConfirmedReweavableState;
/**
* Add any .class files in the directory to the outdir. Anything other than .class files in
* the directory (or its subdirectories) are considered resources and are also copied.
*
*/
public List addDirectoryContents(File inFile,File outDir) throws IOException {
List addedClassFiles = new ArrayList();
// Get a list of all files (i.e. everything that isnt a directory)
File[] files = FileUtil.listFiles(inFile,new FileFilter() {
public boolean accept(File f) {
boolean accept = !f.isDirectory();
return accept;
}
});
// For each file, add it either as a real .class file or as a resource
for (int i = 0; i < files.length; i++) {
FileInputStream fis = new FileInputStream(files[i]);
byte[] bytes = FileUtil.readAsByteArray(fis);
// String relativePath = files[i].getPath();
// ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
// or we are in trouble...
String filename = files[i].getAbsolutePath().substring(
inFile.getAbsolutePath().length()+1);
UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir,filename).getAbsolutePath(),bytes);
if (filename.endsWith(".class")) {
// System.err.println("BCELWeaver: processing class from input directory "+classFile);
this.addClassFile(classFile);
addedClassFiles.add(classFile);
// } else {
// if (CopyResourcesFromInpathDirectoriesToOutput) {
// // System.err.println("BCELWeaver: processing resource from input directory "+filename);
// addResource(filename,classFile);
// }
}
fis.close();
}
return addedClassFiles;
}
/** Adds all class files in the jar
*/
public List addJarFile(File inFile, File outDir, boolean canBeDirectory){
// System.err.println("? addJarFile(" + inFile + ", " + outDir + ")");
List addedClassFiles = new ArrayList();
needToReweaveWorld = true;
ZipInputStream inStream = null;
try {
// Is this a directory we are looking at?
if (inFile.isDirectory() && canBeDirectory) {
addedClassFiles.addAll(addDirectoryContents(inFile,outDir));
} else {
inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered
while (true) {
ZipEntry entry = inStream.getNextEntry();
if (entry == null) break;
byte[] bytes = FileUtil.readAsByteArray(inStream);
String filename = entry.getName();
UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes);
if (filename.endsWith(".class")) {
this.addClassFile(classFile);
addedClassFiles.add(classFile);
}
// else if (!entry.isDirectory()) {
//
// /* bug-44190 Copy meta-data */
// addResource(filename,classFile);
// }
inStream.closeEntry();
}
inStream.close();
}
} catch (FileNotFoundException ex) {
IMessage message = new Message(
"Could not find input jar file " + inFile.getPath() + ", ignoring",
new SourceLocation(inFile,0),
false);
world.getMessageHandler().handleMessage(message);
} catch (IOException ex) {
IMessage message = new Message(
"Could not read input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")",
new SourceLocation(inFile,0),
true);
world.getMessageHandler().handleMessage(message);
} finally {
if (inStream != null) {
try {inStream.close();}
catch (IOException ex) {
IMessage message = new Message(
"Could not close input jar file " + inFile.getPath() + "(" + ex.getMessage() + ")",
new SourceLocation(inFile,0),
true);
world.getMessageHandler().handleMessage(message);
}
}
}
return addedClassFiles;
}
// public void addResource(String name, File inPath, File outDir) throws IOException {
//
// /* Eliminate CVS files. Relative paths use "/" */
// if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) {
//// System.err.println("? addResource('" + name + "')");
//// BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(inPath));
//// byte[] bytes = new byte[(int)inPath.length()];
//// inStream.read(bytes);
//// inStream.close();
// byte[] bytes = FileUtil.readAsByteArray(inPath);
// UnwovenClassFile resourceFile = new UnwovenClassFile(new File(outDir, name).getAbsolutePath(), bytes);
// addResource(name,resourceFile);
// }
// }
public boolean needToReweaveWorld() {
return needToReweaveWorld;
}
/** Should be addOrReplace
*/
public void addClassFile(UnwovenClassFile classFile) {
addedClasses.add(classFile);
// if (null != sourceJavaClasses.put(classFile.getClassName(), classFile)) {
//// throw new RuntimeException(classFile.getClassName());
// }
world.addSourceObjectType(classFile.getJavaClass());
}
public void deleteClassFile(String typename) {
deletedTypenames.add(typename);
// sourceJavaClasses.remove(typename);
world.deleteSourceObjectType(TypeX.forName(typename));
}
// public void addResource (String name, UnwovenClassFile resourceFile) {
// /* bug-44190 Change error to warning and copy first resource */
// if (!resources.containsKey(name)) {
// resources.put(name, resourceFile);
// }
// else {
// world.showMessage(IMessage.WARNING, "duplicate resource: '" + name + "'",
// null, null);
// }
// }
// ---- weave preparation
public void prepareForWeave() {
needToReweaveWorld = false;
// update mungers
for (Iterator i = addedClasses.iterator(); i.hasNext(); ) {
UnwovenClassFile jc = (UnwovenClassFile)i.next();
String name = jc.getClassName();
ResolvedTypeX type = world.resolve(name);
//System.err.println("added: " + type + " aspect? " + type.isAspect());
if (type.isAspect()) {
needToReweaveWorld |= xcutSet.addOrReplaceAspect(type);
}
}
for (Iterator i = deletedTypenames.iterator(); i.hasNext(); ) {
String name = (String)i.next();
if (xcutSet.deleteAspect(TypeX.forName(name))) needToReweaveWorld = true;
}
shadowMungerList = xcutSet.getShadowMungers();
typeMungerList = xcutSet.getTypeMungers();
declareParentsList = xcutSet.getDeclareParents();
//XXX this gets us a stable (but completely meaningless) order
Collections.sort(
shadowMungerList,
new Comparator() {
public int compare(Object o1, Object o2) {
return o1.toString().compareTo(o2.toString());
}
});
}
// public void dumpUnwoven(File file) throws IOException {
// BufferedOutputStream os = FileUtil.makeOutputStream(file);
// this.zipOutputStream = new ZipOutputStream(os);
// dumpUnwoven();
// /* BUG 40943*/
// dumpResourcesToOutJar();
// zipOutputStream.close(); //this flushes and closes the acutal file
// }
//
//
// public void dumpUnwoven() throws IOException {
// Collection filesToDump = new HashSet(sourceJavaClasses.values());
// for (Iterator i = filesToDump.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// dumpUnchanged(classFile);
// }
// }
// public void dumpResourcesToOutPath() throws IOException {
//// System.err.println("? dumpResourcesToOutPath() resources=" + resources.keySet());
// Iterator i = resources.keySet().iterator();
// while (i.hasNext()) {
// UnwovenClassFile res = (UnwovenClassFile)resources.get(i.next());
// dumpUnchanged(res);
// }
// //resources = new HashMap();
// }
//
/* BUG #40943 */
// public void dumpResourcesToOutJar() throws IOException {
//// System.err.println("? dumpResourcesToOutJar() resources=" + resources.keySet());
// Iterator i = resources.keySet().iterator();
// while (i.hasNext()) {
// String name = (String)i.next();
// UnwovenClassFile res = (UnwovenClassFile)resources.get(name);
// writeZipEntry(name,res.getBytes());
// }
// resources = new HashMap();
// }
//
// // halfway house for when the jar is managed outside of the weaver, but the resources
// // to be copied are known in the weaver.
// public void dumpResourcesToOutJar(ZipOutputStream zos) throws IOException {
// this.zipOutputStream = zos;
// dumpResourcesToOutJar();
// }
// ---- weaving
// Used by some test cases only...
public Collection weave(File file) throws IOException {
OutputStream os = FileUtil.makeOutputStream(file);
this.zipOutputStream = new ZipOutputStream(os);
prepareForWeave();
Collection c = weave( new IClassFileProvider() {
public Iterator getClassFileIterator() {
return addedClasses.iterator();
}
public IWeaveRequestor getRequestor() {
return new IWeaveRequestor() {
public void acceptResult(UnwovenClassFile result) {
try {
writeZipEntry(result.filename, result.bytes);
} catch(IOException ex) {}
}
public void processingReweavableState() {}
public void addingTypeMungers() {}
public void weavingAspects() {}
public void weavingClasses() {}
public void weaveCompleted() {}
};
}
});
// /* BUG 40943*/
// dumpResourcesToOutJar();
zipOutputStream.close(); //this flushes and closes the acutal file
return c;
}
// public Collection weave() throws IOException {
// prepareForWeave();
// Collection filesToWeave;
//
// if (needToReweaveWorld) {
// filesToWeave = sourceJavaClasses.values();
// } else {
// filesToWeave = addedClasses;
// }
//
// Collection wovenClassNames = new ArrayList();
// world.showMessage(IMessage.INFO, "might need to weave " + filesToWeave +
// "(world=" + needToReweaveWorld + ")", null, null);
//
//
// //System.err.println("typeMungers: " + typeMungerList);
//
// prepareToProcessReweavableState();
// // clear all state from files we'll be reweaving
// for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// String className = classFile.getClassName();
// BcelObjectType classType = getClassType(className);
// processReweavableStateIfPresent(className, classType);
// }
//
//
//
// //XXX this isn't quite the right place for this...
// for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// String className = classFile.getClassName();
// addTypeMungers(className);
// }
//
// // first weave into aspects
// for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// String className = classFile.getClassName();
// BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
// if (classType.isAspect()) {
// weave(classFile, classType);
// wovenClassNames.add(className);
// }
// }
//
// // then weave into non-aspects
// for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// String className = classFile.getClassName();
// BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
// if (! classType.isAspect()) {
// weave(classFile, classType);
// wovenClassNames.add(className);
// }
// }
//
// if (zipOutputStream != null && !needToReweaveWorld) {
// Collection filesToDump = new HashSet(sourceJavaClasses.values());
// filesToDump.removeAll(filesToWeave);
// for (Iterator i = filesToDump.iterator(); i.hasNext(); ) {
// UnwovenClassFile classFile = (UnwovenClassFile)i.next();
// dumpUnchanged(classFile);
// }
// }
//
// addedClasses = new ArrayList();
// deletedTypenames = new ArrayList();
//
// return wovenClassNames;
// }
// variation of "weave" that sources class files from an external source.
public Collection weave(IClassFileProvider input) throws IOException {
Collection wovenClassNames = new ArrayList();
IWeaveRequestor requestor = input.getRequestor();
requestor.processingReweavableState();
prepareToProcessReweavableState();
// clear all state from files we'll be reweaving
for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
String className = classFile.getClassName();
BcelObjectType classType = getClassType(className);
processReweavableStateIfPresent(className, classType);
}
requestor.addingTypeMungers();
//XXX this isn't quite the right place for this...
for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
String className = classFile.getClassName();
addTypeMungers(className);
}
requestor.weavingAspects();
// first weave into aspects
for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
String className = classFile.getClassName();
BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
if (classType.isAspect()) {
weaveAndNotify(classFile, classType,requestor);
wovenClassNames.add(className);
}
}
requestor.weavingClasses();
// then weave into non-aspects
for (Iterator i = input.getClassFileIterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile)i.next();
String className = classFile.getClassName();
BcelObjectType classType = BcelWorld.getBcelObjectType(world.resolve(className));
if (! classType.isAspect()) {
weaveAndNotify(classFile, classType, requestor);
wovenClassNames.add(className);
}
}
addedClasses = new ArrayList();
deletedTypenames = new ArrayList();
requestor.weaveCompleted();
return wovenClassNames;
}
public void prepareToProcessReweavableState() {
if (inReweavableMode)
world.showMessage(IMessage.INFO, "weaver operating in reweavable mode. Need to verify any required types exist.", null, null);
alreadyConfirmedReweavableState = new HashSet();
}
public void processReweavableStateIfPresent(String className, BcelObjectType classType) {
// If the class is marked reweavable, check any aspects around when it was built are in this world
WeaverStateInfo wsi = classType.getWeaverState();
if (wsi!=null && wsi.isReweavable()) { // Check all necessary types are around!
world.showMessage(IMessage.INFO,"processing reweavable type "+className+": "+classType.getSourceLocation().getSourceFile(),null,null);
Set aspectsPreviouslyInWorld = wsi.getAspectsAffectingType();
if (aspectsPreviouslyInWorld!=null) {
for (Iterator iter = aspectsPreviouslyInWorld.iterator(); iter.hasNext();) {
String requiredTypeName = (String) iter.next();
if (!alreadyConfirmedReweavableState.contains(requiredTypeName)) {
ResolvedTypeX rtx = world.resolve(TypeX.forName(requiredTypeName),true);
boolean exists = rtx!=ResolvedTypeX.MISSING;
if (!exists) {
world.showMessage(IMessage.ERROR, "type " + requiredTypeName +
" is needed by reweavable type " + className,
classType.getSourceLocation(), null);
} else {
if (!world.getMessageHandler().isIgnoring(IMessage.INFO))
world.showMessage(IMessage.INFO,"successfully verified type "+requiredTypeName+
" exists. Originates from "+rtx.getSourceLocation().getSourceFile(),null,null);
alreadyConfirmedReweavableState.add(requiredTypeName);
}
}
}
}
classType.setJavaClass(Utility.makeJavaClass(classType.getJavaClass().getFileName(), wsi.getUnwovenClassFileData()));
} else {
classType.resetState();
}
}
private void weaveAndNotify(UnwovenClassFile classFile, BcelObjectType classType,
IWeaveRequestor requestor) throws IOException {
LazyClassGen clazz = weaveWithoutDump(classFile,classType);
classType.finishedWith();
//clazz is null if the classfile was unchanged by weaving...
if (clazz != null) {
UnwovenClassFile[] newClasses = getClassFilesFor(clazz);
for (int i = 0; i < newClasses.length; i++) {
requestor.acceptResult(newClasses[i]);
}
} else {
requestor.acceptResult(classFile);
}
}
// helper method
public BcelObjectType getClassType(String forClass) {
return BcelWorld.getBcelObjectType(world.resolve(forClass));
}
public void addTypeMungers(String typeName) {
weave(world.resolve(typeName));
}
public UnwovenClassFile[] getClassFilesFor(LazyClassGen clazz) {
List childClasses = clazz.getChildClasses(world);
UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()];
ret[0] = new UnwovenClassFile(clazz.getFileName(),clazz.getJavaClass(world).getBytes());
int index = 1;
for (Iterator iter = childClasses.iterator(); iter.hasNext();) {
UnwovenClassFile.ChildClass element = (UnwovenClassFile.ChildClass) iter.next();
UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes);
ret[index++] = childClass;
}
return ret;
}
public void weave(ResolvedTypeX onType) {
onType.clearInterTypeMungers();
// need to do any declare parents before the matching below
for (Iterator i = declareParentsList.iterator(); i.hasNext(); ) {
DeclareParents p = (DeclareParents)i.next();
List newParents = p.findMatchingNewParents(onType);
if (!newParents.isEmpty()) {
BcelObjectType classType = BcelWorld.getBcelObjectType(onType);
//System.err.println("need to do declare parents for: " + onType);
for (Iterator j = newParents.iterator(); j.hasNext(); ) {
ResolvedTypeX newParent = (ResolvedTypeX)j.next();
if (newParent.isClass()) {
world.showMessage(IMessage.ERROR,
"can't use declare parents to change superclass of binary form \'" +
onType.getName() + "\' (implementation limitation)",
p.getSourceLocation(), null);
continue;
}
classType.addParent(newParent);
ResolvedTypeMunger newParentMunger = new NewParentTypeMunger(newParent);
onType.addInterTypeMunger(new BcelTypeMunger(newParentMunger, xcutSet.findAspectDeclaringParents(p)));
}
}
}
for (Iterator i = typeMungerList.iterator(); i.hasNext(); ) {
ConcreteTypeMunger m = (ConcreteTypeMunger)i.next();
if (m.matches(onType)) {
onType.addInterTypeMunger(m);
}
}
}
// exposed for ClassLoader dynamic weaving
public LazyClassGen weaveWithoutDump(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
return weave(classFile, classType, false);
}
// non-private for testing
LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException {
LazyClassGen ret = weave(classFile, classType, true);
if (progressListener != null) {
progressMade += progressPerClassFile;
progressListener.setProgress(progressMade);
progressListener.setText("woven: " + classFile.getFilename());
}
return ret;
}
private LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType, boolean dump) throws IOException {
if (classType.isSynthetic()) {
if (dump) dumpUnchanged(classFile);
return null;
}
// JavaClass javaClass = classType.getJavaClass();
List shadowMungers = fastMatch(shadowMungerList, classType.getResolvedTypeX());
List typeMungers = classType.getResolvedTypeX().getInterTypeMungers();
classType.getResolvedTypeX().checkInterTypeMungers();
LazyClassGen clazz = null;
if (shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect()) {
clazz = classType.getLazyClassGen();
//System.err.println("got lazy gen: " + clazz + ", " + clazz.getWeaverState());
try {
boolean isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers);
if (isChanged) {
if (dump) dump(classFile, clazz);
return clazz;
}
} catch (RuntimeException re) {
System.err.println("trouble in: ");
//XXXclazz.print(System.err);
throw re;
} catch (Error re) {
System.err.println("trouble in: ");
clazz.print(System.err);
throw re;
}
}
// this is very odd return behavior trying to keep everyone happy
if (dump) {
dumpUnchanged(classFile);
return clazz;
} else {
return null;
}
}
// ---- writing
private void dumpUnchanged(UnwovenClassFile classFile) throws IOException {
if (zipOutputStream != null) {
writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes());
} else {
classFile.writeUnchangedBytes();
}
}
private String getEntryName(String className) {
//XXX what does bcel's getClassName do for inner names
return className.replace('.', '/') + ".class";
}
private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException {
if (zipOutputStream != null) {
String mainClassName = classFile.getJavaClass().getClassName();
writeZipEntry(getEntryName(mainClassName),
clazz.getJavaClass(world).getBytes());
if (!clazz.getChildClasses(world).isEmpty()) {
for (Iterator i = clazz.getChildClasses(world).iterator(); i.hasNext();) {
UnwovenClassFile.ChildClass c = (UnwovenClassFile.ChildClass) i.next();
writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes);
}
}
} else {
classFile.writeWovenBytes(
clazz.getJavaClass(world).getBytes(),
clazz.getChildClasses(world)
);
}
}
private void writeZipEntry(String name, byte[] bytes) throws IOException {
ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right
zipOutputStream.putNextEntry(newEntry);
zipOutputStream.write(bytes);
zipOutputStream.closeEntry();
}
private List fastMatch(List list, ResolvedTypeX type) {
if (list == null) return Collections.EMPTY_LIST;
// here we do the coarsest grained fast match with no kind constraints
// this will remove all obvious non-matches and see if we need to do any weaving
FastMatchInfo info = new FastMatchInfo(type, null);
List result = new ArrayList();
Iterator iter = list.iterator();
while (iter.hasNext()) {
ShadowMunger munger = (ShadowMunger)iter.next();
if (munger.getPointcut().fastMatch(info).maybeTrue()) {
result.add(munger);
}
}
return result;
}
public void setProgressListener(IProgressListener listener, double previousProgress, double progressPerClassFile) {
progressListener = listener;
this.progressMade = previousProgress;
this.progressPerClassFile = progressPerClassFile;
}
public void setReweavableMode(boolean mode,boolean compress) {
inReweavableMode = mode;
WeaverStateInfo.setReweavableModeDefaults(mode,compress);
BcelClassWeaver.setReweavableMode(mode,compress);
}
public boolean isReweavable() {
return inReweavableMode;
}
}
|
40,192
|
Bug 40192 build cancel during weaving
|
The build can not be cancelled during the bytecode weaving stage.
|
resolved fixed
|
183fc23
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-18T13:00:01Z
| 2003-07-16T10:06:40Z
|
ajde/src/org/aspectj/ajde/internal/BuildNotifierAdapter.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:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.ajde.internal;
import org.aspectj.ajde.Ajde;
import org.aspectj.ajde.BuildProgressMonitor;
import org.aspectj.ajdt.internal.core.builder.AjBuildManager;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.IProgressListener;
public class BuildNotifierAdapter implements IProgressListener {
private BuildProgressMonitor progressMonitor;
private AjBuildManager buildManager;
// private int numCompilationUnitPasses = 1;
// private int completedPasses = 0;
private boolean cancelRequested = false;
public BuildNotifierAdapter(BuildProgressMonitor progressMonitor, AjBuildManager buildManager) {
this.progressMonitor = progressMonitor;
this.buildManager = buildManager;
}
public void begin() {
progressMonitor.start(Ajde.getDefault().getConfigurationManager().getActiveConfigFile());
progressMonitor.setProgressText("starting build...");
}
public void cancelBuild() {
progressMonitor.setProgressText("cancelling build...");
cancelRequested = true;
}
public void setProgress(double percentDone) {
progressMonitor.setProgressBarVal((int)(percentDone * progressMonitor.getProgressBarMax()));
}
public void setText(String text) {
progressMonitor.setProgressText(text);
}
}
|
40,192
|
Bug 40192 build cancel during weaving
|
The build can not be cancelled during the bytecode weaving stage.
|
resolved fixed
|
183fc23
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-18T13:00:01Z
| 2003-07-16T10:06:40Z
|
ajde/testdata/BuildCancelling/Cl1.java
| |
40,192
|
Bug 40192 build cancel during weaving
|
The build can not be cancelled during the bytecode weaving stage.
|
resolved fixed
|
183fc23
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-18T13:00:01Z
| 2003-07-16T10:06:40Z
|
ajde/testdata/BuildCancelling/Cl2.java
| |
40,192
|
Bug 40192 build cancel during weaving
|
The build can not be cancelled during the bytecode weaving stage.
|
resolved fixed
|
183fc23
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-18T13:00:01Z
| 2003-07-16T10:06:40Z
|
ajde/testdata/BuildCancelling/Cl3.java
| |
40,192
|
Bug 40192 build cancel during weaving
|
The build can not be cancelled during the bytecode weaving stage.
|
resolved fixed
|
183fc23
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-18T13:00:01Z
| 2003-07-16T10:06:40Z
|
ajde/testdata/BuildCancelling/HW.java
| |
40,192
|
Bug 40192 build cancel during weaving
|
The build can not be cancelled during the bytecode weaving stage.
|
resolved fixed
|
183fc23
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-18T13:00:01Z
| 2003-07-16T10:06:40Z
|
ajde/testsrc/org/aspectj/ajde/AjdeTests.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.ajde;
import junit.framework.*;
public class AjdeTests extends TestCase {
public static String TESTDATA_PATH = "../ajde/testdata";
public static Test suite() {
TestSuite suite = new TestSuite(AjdeTests.class.getName());
//$JUnit-BEGIN$
suite.addTestSuite(BuildOptionsTest.class);
suite.addTestSuite(BuildConfigurationTests.class);
suite.addTestSuite(StructureModelRegressionTest.class);
suite.addTestSuite(StructureModelTest.class);
suite.addTestSuite(VersionTest.class);
suite.addTestSuite(CompilerMessagesTest.class);
suite.addTestSuite(AsmDeclarationsTest.class);
suite.addTestSuite(AsmRelationshipsTest.class);
suite.addTestSuite(InpathTestcase.class);
suite.addTestSuite(ReweavableTestCase.class);
suite.addTestSuite(ResourceCopyTestCase.class);
suite.addTestSuite(ModelPerformanceTest.class);
suite.addTestSuite(SavedModelConsistencyTest. class);
suite.addTestSuite(JarManifestTest.class);
//$JUnit-END$
return suite;
}
public AjdeTests(String name) { super(name); }
}
|
40,192
|
Bug 40192 build cancel during weaving
|
The build can not be cancelled during the bytecode weaving stage.
|
resolved fixed
|
183fc23
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-18T13:00:01Z
| 2003-07-16T10:06:40Z
|
ajde/testsrc/org/aspectj/ajde/BuildCancellingTest.java
| |
40,192
|
Bug 40192 build cancel during weaving
|
The build can not be cancelled during the bytecode weaving stage.
|
resolved fixed
|
183fc23
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-18T13:00:01Z
| 2003-07-16T10:06:40Z
|
bridge/src/org/aspectj/bridge/IProgressListener.java
|
/* *******************************************************************
* Copyright (c) 2003 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.bridge;
/**
* Used to give progress information typically to IDEs
*/
public interface IProgressListener {
/**
* @param text the current phase of processing
*/
public void setText(String text);
/**
* @param percentDone how much work is completed so far
*/
public void setProgress(double percentDone);
}
|
40,192
|
Bug 40192 build cancel during weaving
|
The build can not be cancelled during the bytecode weaving stage.
|
resolved fixed
|
183fc23
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-18T13:00:01Z
| 2003-07-16T10:06: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.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.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.Compiler;
import org.eclipse.jdt.internal.compiler.ICompilerAdapter;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
/**
* @author colyer
*
* Adapts standard JDT Compiler to add in AspectJ specific behaviours.
*/
public class AjCompilerAdapter implements ICompilerAdapter {
private Compiler compiler;
private BcelWeaver weaver;
private EclipseFactory eWorld;
private boolean isBatchCompile;
private boolean reportedErrors;
private boolean isXNoWeave;
private IIntermediateResultsRequestor intermediateResultsRequestor;
private IOutputClassFileNameProvider outputFileNameProvider;
private WeaverMessageHandler weaverMessageHandler;
private List /* InterimCompilationResult */ binarySources = new ArrayList();
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,
IOutputClassFileNameProvider outputFileNameProvider,
Map binarySourceEntries, /* fileName |-> List<UnwovenClassFile> */
Collection /* InterimCompilationResult */ resultSetForFullWeave,
boolean isXNoWeave) {
this.compiler = compiler;
this.isBatchCompile = isBatchCompile;
this.weaver = weaver;
this.intermediateResultsRequestor = intRequestor;
this.outputFileNameProvider = outputFileNameProvider;
this.isXNoWeave = isXNoWeave;
this.resultSetForFullWeave = resultSetForFullWeave;
this.eWorld = eFactory;
IMessageHandler msgHandler = world.getMessageHandler();
weaverMessageHandler = new WeaverMessageHandler(msgHandler, compiler);
world.setMessageHandler(weaverMessageHandler);
addBinarySource(binarySourceEntries);
}
public void beforeCompiling(ICompilationUnit[] sourceUnits) {
resultsPendingWeave = new ArrayList();
reportedErrors = false;
}
public void afterCompiling() {
try {
if (isXNoWeave || reportedErrors) {
// no point weaving... just tell the requestor we're done
notifyRequestor();
} else {
weave(); // notification happens as weave progresses...
}
} catch (IOException ex) {
AbortCompilation ac = new AbortCompilation(null,ex);
throw ac;
}
}
public void beforeProcessing(CompilationUnitDeclaration unit) {
eWorld.showMessage(IMessage.INFO, "compiling " + new String(unit.getFileName()), null, null);
}
public void afterProcessing(CompilationUnitDeclaration unit, int unitIndex) {
eWorld.finishedCompilationUnit(unit);
InterimCompilationResult intRes = new InterimCompilationResult(unit.compilationResult,outputFileNameProvider);
if (unit.compilationResult.hasErrors()) reportedErrors = true;
if (intermediateResultsRequestor != null) {
intermediateResultsRequestor.acceptResult(intRes);
}
if (isXNoWeave) {
acceptResult(unit.compilationResult);
} else {
resultsPendingWeave.add(intRes);
}
}
public void beforeResolving(CompilationUnitDeclaration unit, ICompilationUnit sourceUnit, boolean verifyMethods, boolean analyzeCode, boolean generateCode) {
resultsPendingWeave = new ArrayList();
reportedErrors = false;
}
public void afterResolving(CompilationUnitDeclaration unit, ICompilationUnit sourceUnit, boolean verifyMethods, boolean analyzeCode, boolean generateCode) {
InterimCompilationResult intRes = new InterimCompilationResult(unit.compilationResult,outputFileNameProvider);
if (unit.compilationResult.hasErrors()) reportedErrors = true;
if (isXNoWeave || !generateCode) {
acceptResult(unit.compilationResult);
} else if (generateCode){
resultsPendingWeave.add(intRes);
try {
weave();
} catch (IOException ex) {
AbortCompilation ac = new AbortCompilation(null,ex);
throw ac;
}
}
}
// helper methods...
// ==================================================================================
/*
* Called from the weaverAdapter once it has finished weaving the class files
* associated with a given compilation result.
*/
public void acceptResult(CompilationResult result) {
compiler.requestor.acceptResult(result.tagAsAccepted());
if (compiler.unitsToProcess != null) {
for (int i = 0; i < compiler.unitsToProcess.length; i++) {
if (compiler.unitsToProcess[i] != null) {
if (compiler.unitsToProcess[i].compilationResult == result) {
compiler.unitsToProcess[i] = null;
}
}
}
}
}
private void addBinarySource(Map binarySourceEntries) {
// Map is fileName |-> List<UnwovenClassFile>
for (Iterator binIter = binarySourceEntries.keySet().iterator(); binIter.hasNext();) {
String sourceFileName = (String) binIter.next();
List unwovenClassFiles = (List) binarySourceEntries.get(sourceFileName);
CompilationResult result = new CompilationResult(sourceFileName.toCharArray(),0,0,20);
result.noSourceAvailable();
InterimCompilationResult binarySource =
new InterimCompilationResult(result,unwovenClassFiles);
binarySources.add(binarySource);
}
}
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 (isBatchCompile) {
resultsPendingWeave.addAll(binarySources);
// passed into the compiler, the set of classes in injars and inpath...
} else if (weaver.needToReweaveWorld()) {
addAllKnownClassesToWeaveList();
}
weaver.weave(new WeaverAdapter(this,weaverMessageHandler));
}
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);
}
}
}
}
|
40,192
|
Bug 40192 build cancel during weaving
|
The build can not be cancelled during the bytecode weaving stage.
|
resolved fixed
|
183fc23
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-18T13:00:01Z
| 2003-07-16T10:06:40Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/WeaverAdapter.java
|
/*******************************************************************************
* Copyright (c) 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.aspectj.ajdt.internal.compiler;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import org.aspectj.weaver.IClassFileProvider;
import org.aspectj.weaver.IWeaveRequestor;
import org.aspectj.weaver.bcel.UnwovenClassFile;
/**
* @author colyer
* This class provides the weaver with a source of class files to weave (via the
* iterator and IClassFileProvider interfaces). It receives results back from the
* weaver via the IWeaveRequestor interface.
*/
public class WeaverAdapter implements IClassFileProvider, IWeaveRequestor, Iterator {
private AjCompilerAdapter compilerAdapter;
private Iterator resultIterator;
private int classFileIndex = 0;
private InterimCompilationResult nowProcessing;
private InterimCompilationResult lastReturnedResult;
private WeaverMessageHandler weaverMessageHandler;
private boolean finalPhase = false;
public WeaverAdapter(AjCompilerAdapter forCompiler,
WeaverMessageHandler weaverMessageHandler) {
this.compilerAdapter = forCompiler;
this.weaverMessageHandler = weaverMessageHandler;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.IClassFileProvider#getClassFileIterator()
*/
public Iterator getClassFileIterator() {
classFileIndex = 0;
nowProcessing = null;
lastReturnedResult = null;
resultIterator = compilerAdapter.resultsPendingWeave.iterator();
return this;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.IClassFileProvider#getRequestor()
*/
public IWeaveRequestor getRequestor() {
return this;
}
// Iteration
// ================================================================
/* (non-Javadoc)
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
if (nowProcessing == null) {
if (!resultIterator.hasNext()) return false;
nowProcessing = (InterimCompilationResult) resultIterator.next();
classFileIndex = 0;
}
while (nowProcessing.unwovenClassFiles().length == 0 ) {
if (!resultIterator.hasNext()) return false;
nowProcessing = (InterimCompilationResult) resultIterator.next();
}
if (classFileIndex < nowProcessing.unwovenClassFiles().length) {
return true;
} else {
classFileIndex = 0;
if (!resultIterator.hasNext()) return false;
nowProcessing = (InterimCompilationResult) resultIterator.next();
while (nowProcessing.unwovenClassFiles().length == 0 ) {
if (!resultIterator.hasNext()) return false;
nowProcessing = (InterimCompilationResult) resultIterator.next();
}
}
return true;
}
/* (non-Javadoc)
* @see java.util.Iterator#next()
*/
public Object next() {
if (!hasNext()) return null; // sets up indices correctly
if (finalPhase) {
if ((lastReturnedResult != null) && (lastReturnedResult != nowProcessing)) {
// we're done with the lastReturnedResult
finishedWith(lastReturnedResult);
}
}
lastReturnedResult = nowProcessing;
weaverMessageHandler.setCurrentResult(nowProcessing.result());
return nowProcessing.unwovenClassFiles()[classFileIndex++];
}
/* (non-Javadoc)
* @see java.util.Iterator#remove()
*/
public void remove() {
throw new UnsupportedOperationException();
}
// IWeaveRequestor
// =====================================================================================
// weave phases as indicated by bcelWeaver...
public void processingReweavableState() {}
public void addingTypeMungers() {}
public void weavingAspects() {}
public void weavingClasses() {finalPhase = true;}
public void weaveCompleted() {
if ((lastReturnedResult != null) && (!lastReturnedResult.result().hasBeenAccepted)) {
finishedWith(lastReturnedResult);
}
}
/* (non-Javadoc)
* @see org.aspectj.weaver.IWeaveRequestor#acceptResult(org.aspectj.weaver.bcel.UnwovenClassFile)
*/
public void acceptResult(UnwovenClassFile result) {
char[] key = result.getClassName().replace('.','/').toCharArray();
removeFromHashtable(lastReturnedResult.result().compiledTypes,key);
String className = result.getClassName().replace('.', '/');
AjClassFile ajcf = new AjClassFile(className.toCharArray(),
result.getBytes());
lastReturnedResult.result().record(ajcf.fileName(),ajcf);
}
// helpers...
// =================================================================
private void finishedWith(InterimCompilationResult result) {
compilerAdapter.acceptResult(result.result());
}
private void removeFromHashtable(Hashtable table, char[] key) {
// jdt uses char[] as a key in the hashtable, which is not very useful as equality is based on being
// the same array, not having the same content.
String skey = new String(key);
char[] victim = null;
for (Enumeration iter = table.keys(); iter.hasMoreElements();) {
char[] thisKey = (char[]) iter.nextElement();
if (skey.equals(new String(thisKey))) {
victim = thisKey;
break;
}
}
if (victim != null) {
table.remove(victim);
}
}
}
|
40,192
|
Bug 40192 build cancel during weaving
|
The build can not be cancelled during the bytecode weaving stage.
|
resolved fixed
|
183fc23
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-18T13:00:01Z
| 2003-07-16T10:06: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.IIntermediateResultsRequestor;
import org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider;
import org.aspectj.ajdt.internal.compiler.InterimCompilationResult;
import org.aspectj.ajdt.internal.compiler.lookup.*;
import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter;
import org.aspectj.asm.*;
//import org.aspectj.asm.internal.*;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.*;
import org.aspectj.util.FileUtil;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.*;
import org.eclipse.jdt.core.compiler.*;
import org.eclipse.jdt.internal.compiler.*;
import org.eclipse.jdt.internal.compiler.batch.*;
import org.eclipse.jdt.internal.compiler.batch.FileSystem;
import org.eclipse.jdt.internal.compiler.env.*;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.parser.Parser;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
//import org.eclipse.jdt.internal.compiler.util.HashtableOfObject;
public class AjBuildManager implements IOutputClassFileNameProvider,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 IProgressListener progressListener = null;
private int compiledCount;
private int sourceFileCount;
private JarOutputStream zos;
private boolean batchCompile = true;
private INameEnvironment environment;
private IHierarchy structureModel;
public AjBuildConfig buildConfig;
AjState state = new AjState(this);
BcelWeaver bcelWeaver;
public BcelWorld bcelWorld;
public CountingMessageHandler handler;
public AjBuildManager(IMessageHandler holder) {
super();
this.handler = CountingMessageHandler.makeCountingMessageHandler(holder);
}
/** @return true if we should generate a model as a side-effect */
public boolean doGenerateModel() {
return buildConfig.isGenerateModelMode();
}
public boolean batchBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler)
throws IOException, AbortException {
return doBuild(buildConfig, baseHandler, true);
}
public boolean incrementalBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler)
throws IOException, AbortException {
return doBuild(buildConfig, baseHandler, false);
}
/** @throws AbortException if check for runtime fails */
protected boolean doBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler,
boolean batch) throws IOException, AbortException {
boolean ret = true;
batchCompile = batch;
try {
if (batch) {
this.state = new AjState(this);
}
boolean canIncremental = state.prepareForNextBuild(buildConfig);
if (!canIncremental && !batch) { // retry as batch?
return doBuild(buildConfig, baseHandler, true);
}
this.handler =
CountingMessageHandler.makeCountingMessageHandler(baseHandler);
// XXX duplicate, no? remove?
String check = checkRtJar(buildConfig);
if (check != null) {
if (FAIL_IF_RUNTIME_NOT_FOUND) {
MessageUtil.error(handler, check);
return false;
} else {
MessageUtil.warn(handler, check);
}
}
// if (batch) {
setBuildConfig(buildConfig);
//}
// if (batch) {
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
setupModel();
// }
// }
if (batch) {
initBcelWorld(handler);
}
if (handler.hasErrors()) {
return false;
}
if (buildConfig.getOutputJar() != null) {
if (!openOutputStream(buildConfig.getOutputJar())) return false;
}
if (batch) {
// System.err.println("XXXX batch: " + buildConfig.getFiles());
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
bcelWorld.setModel(AsmManager.getDefault().getHierarchy());
// in incremental build, only get updated model?
}
performCompilation(buildConfig.getFiles());
if (handler.hasErrors()) {
return false;
}
} else {
// done already?
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
// bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel());
// }
// System.err.println("XXXX start inc ");
List files = state.getFilesToCompile(true);
for (int i = 0; (i < 5) && !files.isEmpty(); i++) {
// System.err.println("XXXX inc: " + files);
performCompilation(files);
if (handler.hasErrors()) {
return false;
}
files = state.getFilesToCompile(false);
}
if (!files.isEmpty()) {
return batchBuild(buildConfig, baseHandler);
}
}
// XXX not in Mik's incremental
if (buildConfig.isEmacsSymMode()) {
new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel();
}
// have to tell state we succeeded or next is not incremental
state.successfulCompile(buildConfig);
copyResourcesToDestination();
/*boolean weaved = *///weaveAndGenerateClassFiles();
// if not weaved, then no-op build, no model changes
// but always returns true
// XXX weaved not in Mik's incremental
if (buildConfig.isGenerateModelMode()) {
AsmManager.getDefault().fireModelUpdated();
}
} finally {
if (zos != null) {
closeOutputStream();
}
ret = !handler.hasErrors();
handler = null;
}
return ret;
}
private boolean openOutputStream(File outJar) {
try {
OutputStream os = FileUtil.makeOutputStream(buildConfig.getOutputJar());
zos = new JarOutputStream(os,bcelWeaver.getManifest(true));
} catch (IOException ex) {
IMessage message =
new Message("Unable to open outjar "
+ outJar.getPath()
+ "(" + ex.getMessage()
+ ")",
new SourceLocation(outJar,0),
true);
handler.handleMessage(message);
return false;
}
return true;
}
private void closeOutputStream() {
try {
if (zos != null) zos.close();
zos = null;
} catch (IOException ex) {
IMessage message =
new Message("Unable to write outjar "
+ buildConfig.getOutputJar().getPath()
+ "(" + ex.getMessage()
+ ")",
new SourceLocation(buildConfig.getOutputJar(),0),
true);
handler.handleMessage(message);
}
}
private void copyResourcesToDestination() throws IOException {
// resources that we need to copy are contained in the injars and inpath only
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File inJar = (File)i.next();
copyResourcesFromJarFile(inJar);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (inPathElement.isDirectory()) {
copyResourcesFromDirectory(inPathElement);
} else {
copyResourcesFromJarFile(inPathElement);
}
}
if (buildConfig.getSourcePathResources() != null) {
for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) {
String resource = (String)i.next();
File from = (File)buildConfig.getSourcePathResources().get(resource);
copyResourcesFromFile(from,resource,from);
}
}
writeManifest();
}
private void copyResourcesFromJarFile(File jarFile) throws IOException {
JarInputStream inStream = null;
try {
inStream = new JarInputStream(new FileInputStream(jarFile));
while (true) {
ZipEntry entry = inStream.getNextEntry();
if (entry == null) break;
String filename = entry.getName();
if (!entry.isDirectory() && acceptResource(filename)) {
byte[] bytes = FileUtil.readAsByteArray(inStream);
writeResource(filename,bytes,jarFile);
}
inStream.closeEntry();
}
} finally {
if (inStream != null) inStream.close();
}
}
private void copyResourcesFromDirectory(File dir) throws IOException {
if (!COPY_INPATH_DIR_RESOURCES) return;
// Get a list of all files (i.e. everything that isnt a directory)
File[] files = FileUtil.listFiles(dir,new FileFilter() {
public boolean accept(File f) {
boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")) ;
return accept;
}
});
// For each file, add it either as a real .class file or as a resource
for (int i = 0; i < files.length; i++) {
// ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
// or we are in trouble...
String filename = files[i].getAbsolutePath().substring(
dir.getAbsolutePath().length()+1);
copyResourcesFromFile(files[i],filename,dir);
}
}
private void copyResourcesFromFile(File f,String filename,File src) throws IOException {
if (!acceptResource(filename)) return;
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
byte[] bytes = FileUtil.readAsByteArray(fis);
// String relativePath = files[i].getPath();
writeResource(filename,bytes,src);
} finally {
if (fis != null) fis.close();
}
}
private void writeResource(String filename, byte[] content, File srcLocation) throws IOException {
if (state.resources.contains(filename)) {
IMessage msg = new Message("duplicate resource: '" + filename + "'",
IMessage.WARNING,
null,
new SourceLocation(srcLocation,0));
handler.handleMessage(msg);
return;
}
if (zos != null) {
ZipEntry newEntry = new ZipEntry(filename); //??? get compression scheme right
zos.putNextEntry(newEntry);
zos.write(content);
zos.closeEntry();
} else {
OutputStream fos =
FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),filename));
fos.write(content);
fos.close();
}
state.resources.add(filename);
}
/*
* If we are writing to an output directory copy the manifest but only
* if we already have one
*/
private void writeManifest () throws IOException {
Manifest manifest = bcelWeaver.getManifest(false);
if (manifest != null && zos == null) {
OutputStream fos =
FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),MANIFEST_NAME));
manifest.write(fos);
fos.close();
}
}
private boolean acceptResource(String resourceName) {
if (
(resourceName.startsWith("CVS/")) ||
(resourceName.indexOf("/CVS/") != -1) ||
(resourceName.endsWith("/CVS")) ||
(resourceName.endsWith(".class"))
)
{
return false;
} else {
return true;
}
}
/**
* Responsible for managing the ASM model between builds. Contains the policy for
* maintaining the persistance of elements in the model.
*
* TODO: implement incremental policy.
*/
private void setupModel() {
String rootLabel = "<root>";
IHierarchy model = AsmManager.getDefault().getHierarchy();
AsmManager.getDefault().getRelationshipMap().clear();
IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA;
if (buildConfig.getConfigFile() != null) {
rootLabel = buildConfig.getConfigFile().getName();
model.setConfigFile(
buildConfig.getConfigFile().getAbsolutePath()
);
kind = IProgramElement.Kind.FILE_LST;
}
model.setRoot(new ProgramElement(rootLabel, kind, new ArrayList()));
model.setFileMap(new HashMap());
setStructureModel(model);
}
/** init only on initial batch compile? no file-specific options */
private void initBcelWorld(IMessageHandler handler) throws IOException {
bcelWorld = new BcelWorld(buildConfig.getClasspath(), handler, null);
bcelWorld.setXnoInline(buildConfig.isXnoInline());
bcelWorld.setXlazyTjp(buildConfig.isXlazyTjp());
bcelWeaver = new BcelWeaver(bcelWorld);
state.binarySourceFiles = new HashMap();
for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext();) {
File f = (File) i.next();
bcelWeaver.addLibraryJarFile(f);
}
// String lintMode = buildConfig.getLintMode();
if (buildConfig.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT)) {
bcelWorld.getLint().loadDefaultProperties();
} else {
bcelWorld.getLint().setAll(buildConfig.getLintMode());
}
if (buildConfig.getLintSpecFile() != null) {
bcelWorld.getLint().setFromProperties(buildConfig.getLintSpecFile());
}
//??? incremental issues
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File inJar = (File)i.next();
List unwovenClasses = bcelWeaver.addJarFile(inJar, buildConfig.getOutputDir(),false);
state.binarySourceFiles.put(inJar.getPath(), unwovenClasses);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
List unwovenClasses = bcelWeaver.addJarFile(inPathElement,buildConfig.getOutputDir(),true);
state.binarySourceFiles.put(inPathElement.getPath(),unwovenClasses); // good enough for ajc to lump these together
}
// if (buildConfig.getSourcePathResources() != null) {
// // XXX buildConfig.getSourcePathResources always returns null (CompileCommand.java)
// for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) {
// // File resource = (File)i.next();
// String resource = (String)i.next();
// bcelWeaver.addResource(resource, (File)buildConfig.getSourcePathResources().get(resource), buildConfig.getOutputDir());
// // bcelWeaver.addResource(resource, buildConfig.getOutputDir());
// }
// }
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 = (String) buildConfig.getJavaOptions().get(CompilerOptions.OPTION_Encoding);
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 = (String) buildConfig.getJavaOptions().get(CompilerOptions.OPTION_Encoding);
if ("".equals(defaultEncoding)) //$NON-NLS-1$
defaultEncoding = null; //$NON-NLS-1$
for (int i = 0; i < fileCount; i++) {
String encoding = encodings[i];
if (encoding == null)
encoding = defaultEncoding;
units[i] = new CompilationUnit(null, filenames[i], encoding);
}
return units;
}
public String extractDestinationPathFromSourceFile(CompilationResult result) {
ICompilationUnit compilationUnit = result.compilationUnit;
if (compilationUnit != null) {
char[] fileName = compilationUnit.getFileName();
int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName);
if (lastIndex == -1) {
return System.getProperty("user.dir"); //$NON-NLS-1$
}
return new String(CharOperation.subarray(fileName, 0, lastIndex));
}
return System.getProperty("user.dir"); //$NON-NLS-1$
}
public void performCompilation(List files) {
if (progressListener != null) {
compiledCount = 0;
sourceFileCount = files.size();
progressListener.setText("compiling source files");
}
//System.err.println("got files: " + files);
String[] filenames = new String[files.size()];
String[] encodings = new String[files.size()];
//System.err.println("filename: " + this.filenames);
for (int i=0; i < files.size(); i++) {
filenames[i] = ((File)files.get(i)).getPath();
}
List cps = buildConfig.getFullClasspath();
String[] classpaths = new String[cps.size()];
for (int i=0; i < cps.size(); i++) {
classpaths[i] = (String)cps.get(i);
}
//System.out.println("compiling");
environment = getLibraryAccess(classpaths, filenames);
if (!state.classesFromName.isEmpty()) {
environment = new StatefulNameEnvironment(environment, state.classesFromName);
}
org.eclipse.jdt.internal.compiler.Compiler.setCompilerAdapterFactory(this);
org.eclipse.jdt.internal.compiler.Compiler compiler =
new org.eclipse.jdt.internal.compiler.Compiler(environment,
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
buildConfig.getJavaOptions(),
getBatchRequestor(),
getProblemFactory());
CompilerOptions options = compiler.options;
options.produceReferenceInfo(true); //TODO turn off when not needed
compiler.compile(getCompilationUnits(filenames, encodings));
// 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);
}
};
}
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(
unitResult.compilationUnit,
CANT_WRITE_RESULT,
ex);
handler.handleMessage(message);
}
}
}
if (unitResult.hasProblems() || unitResult.hasTasks()) {
IProblem[] problems = unitResult.getAllProblems();
for (int i=0; i < problems.length; i++) {
IMessage message =
EclipseAdapterUtils.makeMessage(unitResult.compilationUnit, problems[i]);
handler.handleMessage(message);
}
}
}
private void writeDirectoryEntry(
CompilationResult unitResult,
ClassFile classFile,
String filename)
throws IOException {
File destinationPath = buildConfig.getOutputDir();
String outFile;
if (destinationPath == null) {
outFile = new File(filename).getName();
outFile = new File(extractDestinationPathFromSourceFile(unitResult), outFile).getPath();
} else {
outFile = new File(destinationPath, filename).getPath();
}
BufferedOutputStream os =
FileUtil.makeOutputStream(new File(outFile));
os.write(classFile.getBytes());
os.close();
}
private void writeZipEntry(ClassFile classFile, String name)
throws IOException {
name = name.replace(File.separatorChar,'/');
ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right
zos.putNextEntry(newEntry);
zos.write(classFile.getBytes());
zos.closeEntry();
}
};
}
protected boolean proceedOnError() {
return true; //???
}
// public void noteClassFiles(AjCompiler.InterimResult result) {
// if (result == null) return;
// CompilationResult unitResult = result.result;
// String sourceFileName = result.fileName();
// if (!(unitResult.hasErrors() && !proceedOnError())) {
// List unwovenClassFiles = new ArrayList();
// Enumeration classFiles = unitResult.compiledTypes.elements();
// while (classFiles.hasMoreElements()) {
// ClassFile classFile = (ClassFile) classFiles.nextElement();
// String filename = new String(classFile.fileName());
// filename = filename.replace('/', File.separatorChar) + ".class";
//
// File destinationPath = buildConfig.getOutputDir();
// if (destinationPath == null) {
// filename = new File(filename).getName();
// filename = new File(extractDestinationPathFromSourceFile(unitResult), filename).getPath();
// } else {
// filename = new File(destinationPath, filename).getPath();
// }
//
// //System.out.println("classfile: " + filename);
// unwovenClassFiles.add(new UnwovenClassFile(filename, classFile.getBytes()));
// }
// state.noteClassesFromFile(unitResult, sourceFileName, unwovenClassFiles);
//// System.out.println("file: " + sourceFileName);
//// for (int i=0; i < unitResult.simpleNameReferences.length; i++) {
//// System.out.println("simple: " + new String(unitResult.simpleNameReferences[i]));
//// }
//// for (int i=0; i < unitResult.qualifiedReferences.length; i++) {
//// System.out.println("qualified: " +
//// new String(CharOperation.concatWith(unitResult.qualifiedReferences[i], '/')));
//// }
// } else {
// state.noteClassesFromFile(null, sourceFileName, Collections.EMPTY_LIST);
// }
// }
//
private void setBuildConfig(AjBuildConfig buildConfig) {
this.buildConfig = buildConfig;
handler.reset();
}
String makeClasspathString() {
if (buildConfig == null || buildConfig.getClasspath() == null) return "";
StringBuffer buf = new StringBuffer();
boolean first = true;
for (Iterator it = buildConfig.getClasspath().iterator(); it.hasNext(); ) {
if (first) { first = false; }
else { buf.append(File.pathSeparator); }
buf.append(it.next().toString());
}
return buf.toString();
}
/**
* This will return null if aspectjrt.jar is present and has the correct version.
* Otherwise it will return a string message indicating the problem.
*/
public String checkRtJar(AjBuildConfig buildConfig) {
// omitting dev info
if (Version.text.equals(Version.DEVELOPMENT)) {
// in the development version we can't do this test usefully
// MessageUtil.info(holder, "running development version of aspectj compiler");
return null;
}
if (buildConfig == null || buildConfig.getClasspath() == null) return "no classpath specified";
for (Iterator it = buildConfig.getClasspath().iterator(); it.hasNext(); ) {
File p = new File( (String)it.next() );
if (p.isFile() && p.getName().equals("aspectjrt.jar")) {
try {
String version = null;
Manifest manifest = new JarFile(p).getManifest();
if (manifest == null) {
return "no manifest found in " + p.getAbsolutePath() +
", expected " + Version.text;
}
Attributes attr = manifest.getAttributes("org/aspectj/lang/");
if (null != attr) {
version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
if (null != version) {
version = version.trim();
}
}
// assume that users of development aspectjrt.jar know what they're doing
if (Version.DEVELOPMENT.equals(version)) {
// MessageUtil.info(holder,
// "running with development version of aspectjrt.jar in " +
// p.getAbsolutePath());
return null;
} else if (!Version.text.equals(version)) {
return "bad version number found in " + p.getAbsolutePath() +
" expected " + Version.text + " found " + version;
}
} catch (IOException ioe) {
return "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe;
}
return null;
} else {
// might want to catch other classpath errors
}
}
return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString();
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("AjBuildManager(");
buf.append(")");
return buf.toString();
}
public void setStructureModel(IHierarchy structureModel) {
this.structureModel = structureModel;
}
/**
* Returns null if there is no structure model
*/
public IHierarchy getStructureModel() {
return structureModel;
}
public IProgressListener getProgressListener() {
return progressListener;
}
public void setProgressListener(IProgressListener progressListener) {
this.progressListener = progressListener;
}
/* (non-Javadoc)
* @see org.aspectj.ajdt.internal.compiler.AjCompiler.IOutputClassFileNameProvider#getOutputClassFileName(char[])
*/
public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) {
String filename = new String(eclipseClassFileName);
filename = filename.replace('/', File.separatorChar) + ".class";
File destinationPath = buildConfig.getOutputDir();
String outFile;
if (destinationPath == null) {
outFile = new File(filename).getName();
outFile = new File(extractDestinationPathFromSourceFile(result), outFile).getPath();
} else {
outFile = new File(destinationPath, filename).getPath();
}
return outFile;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler)
*/
public ICompilerAdapter getAdapter(org.eclipse.jdt.internal.compiler.Compiler forCompiler) {
// complete compiler config and return a suitable adapter...
AjProblemReporter pr =
new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(),
forCompiler.options, getProblemFactory());
forCompiler.problemReporter = pr;
AjLookupEnvironment le =
new AjLookupEnvironment(forCompiler, forCompiler.options, pr, environment);
EclipseFactory factory = new EclipseFactory(le);
le.factory = factory;
pr.factory = factory;
le.factory.buildManager = this;
forCompiler.lookupEnvironment = le;
forCompiler.parser =
new Parser(
pr,
forCompiler.options.parseLiteralExpressionsAsConstants);
return new AjCompilerAdapter(forCompiler,batchCompile,bcelWorld,bcelWeaver,
factory,
getInterimResultRequestor(),this,
state.binarySourceFiles,
state.resultsFromFile.values(),
buildConfig.isNoWeave());
}
} // class AjBuildManager
|
55,134
|
Bug 55134 Incremental compilation does not delete weaver-generated class files
|
During incremental compilation, AjState records classes generated from source files following the initial compile phase, but before weaving. (So that these can be passed to the weaver on a subsequent iteration if we need to reweave the world). During weaving of a given class file, the weaver may generate additional class files (for e.g. around closures) that get written to the output. If the orginal source file is deleted, these additional weaver generated classes are not deleted from the output since AjState does not know about them.
|
resolved fixed
|
7d6b500
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-18T14:36:58Z
| 2004-03-17T19:00:00Z
|
tests/incremental/initialTests/classWAroundClosureRemoved/AdviceOnIntroduced.delete.20.java
| |
55,134
|
Bug 55134 Incremental compilation does not delete weaver-generated class files
|
During incremental compilation, AjState records classes generated from source files following the initial compile phase, but before weaving. (So that these can be passed to the weaver on a subsequent iteration if we need to reweave the world). During weaving of a given class file, the weaver may generate additional class files (for e.g. around closures) that get written to the output. If the orginal source file is deleted, these additional weaver generated classes are not deleted from the output since AjState does not know about them.
|
resolved fixed
|
7d6b500
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-18T14:36:58Z
| 2004-03-17T19:00:00Z
|
tests/incremental/initialTests/classWAroundClosureRemoved/AdviceOnIntroduced.java
| |
55,134
|
Bug 55134 Incremental compilation does not delete weaver-generated class files
|
During incremental compilation, AjState records classes generated from source files following the initial compile phase, but before weaving. (So that these can be passed to the weaver on a subsequent iteration if we need to reweave the world). During weaving of a given class file, the weaver may generate additional class files (for e.g. around closures) that get written to the output. If the orginal source file is deleted, these additional weaver generated classes are not deleted from the output since AjState does not know about them.
|
resolved fixed
|
7d6b500
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-18T14:36:58Z
| 2004-03-17T19:00:00Z
|
tests/incremental/initialTests/classWAroundClosureRemoved/Main.java
| |
55,134
|
Bug 55134 Incremental compilation does not delete weaver-generated class files
|
During incremental compilation, AjState records classes generated from source files following the initial compile phase, but before weaving. (So that these can be passed to the weaver on a subsequent iteration if we need to reweave the world). During weaving of a given class file, the weaver may generate additional class files (for e.g. around closures) that get written to the output. If the orginal source file is deleted, these additional weaver generated classes are not deleted from the output since AjState does not know about them.
|
resolved fixed
|
7d6b500
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-18T14:36:58Z
| 2004-03-17T19:00:00Z
|
weaver/src/org/aspectj/weaver/bcel/UnwovenClassFile.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.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.bcel.classfile.JavaClass;
import org.aspectj.util.FileUtil;
public class UnwovenClassFile {
protected String filename;
protected byte[] bytes;
// protected JavaClass javaClass = null;
//protected byte[] writtenBytes = null;
protected List /* ChildClass */ writtenChildClasses = new ArrayList(0);
protected String className = null;
public UnwovenClassFile(String filename, byte[] bytes) {
this.filename = filename;
this.bytes = bytes;
}
public String getFilename() {
return filename;
}
public String makeInnerFileName(String innerName) {
String prefix = filename.substring(0, filename.length()-6); // strip the .class
return prefix + "$" + innerName + ".class";
}
public byte[] getBytes() {
// if (bytes == null) bytes = javaClass.getBytes();
return bytes;
}
public JavaClass getJavaClass() {
//XXX need to know when to make a new class and when not to
//XXX this is an important optimization
if (getBytes() == null) {
System.out.println("no bytes for: " + getFilename());
//Thread.currentThread().dumpStack();
Thread.dumpStack();
}
return Utility.makeJavaClass(filename, getBytes());
// if (javaClass == null) javaClass = Utility.makeJavaClass(filename, getBytes());
// return javaClass;
}
public boolean exists() {
return getBytes() != null;
}
public void writeUnchangedBytes() throws IOException {
writeWovenBytes(getBytes(), Collections.EMPTY_LIST);
}
public void writeWovenBytes(byte[] bytes, List childClasses) throws IOException {
writeChildClasses(childClasses);
//System.err.println("should write: " + getClassName());
//System.err.println("about to write: " + this + ", " + writtenBytes + ", ");
// + writtenBytes != null + " && " + unchanged(bytes, writtenBytes) );
//if (writtenBytes != null && unchanged(bytes, writtenBytes)) return;
//System.err.println(" actually wrote it");
BufferedOutputStream os = FileUtil.makeOutputStream(new File(filename));
os.write(bytes);
os.close();
//writtenBytes = bytes;
}
private void writeChildClasses(List childClasses) throws IOException {
//??? we only really need to delete writtenChildClasses whose
//??? names aren't in childClasses; however, it's unclear
//??? how much that will affect performance
deleteAllChildClasses();
childClasses.removeAll(writtenChildClasses); //XXX is this right
for (Iterator iter = childClasses.iterator(); iter.hasNext();) {
ChildClass childClass = (ChildClass) iter.next();
writeChildClassFile(childClass.name, childClass.bytes);
}
writtenChildClasses = childClasses;
}
private void writeChildClassFile(String innerName, byte[] bytes) throws IOException {
BufferedOutputStream os =
FileUtil.makeOutputStream(new File(makeInnerFileName(innerName)));
os.write(bytes);
os.close();
}
protected void deleteAllChildClasses() {
for (Iterator iter = writtenChildClasses.iterator(); iter.hasNext();) {
ChildClass childClass = (ChildClass) iter.next();
deleteChildClassFile(childClass.name);
}
}
protected void deleteChildClassFile(String innerName) {
File childClassFile = new File(makeInnerFileName(innerName));
childClassFile.delete();
}
/* private */ static boolean unchanged(byte[] b1, byte[] b2) {
int len = b1.length;
if (b2.length != len) return false;
for (int i=0; i < len; i++) {
if (b1[i] != b2[i]) return false;
}
return true;
}
public String getClassName() {
if (className == null) className = getJavaClass().getClassName();
return className;
}
public String toString() {
return "UnwovenClassFile(" + filename + ", " + getClassName() + ")";
}
public void deleteRealFile() throws IOException {
new File(filename).delete();
}
// record
public static class ChildClass {
public final String name;
public final byte[] bytes;
ChildClass(String name, byte[] bytes) {
this.name = name;
this.bytes = bytes;
}
public boolean equals(Object other) {
if (! (other instanceof ChildClass)) return false;
ChildClass o = (ChildClass) other;
return o.name.equals(name) && unchanged(o.bytes, bytes);
}
public int hashCode() {
return name.hashCode();
}
public String toString() {
return "(ChildClass " + name + ")";
}
}
}
|
52,928
|
Bug 52928 Private members introduced via an interface are visible to the class
|
If private members are introduced via an interface to classes, the introduced members are visible inside the classes themselves, although the visibility is supposed to be relative to the aspect. Here's a sample: public class Sample { public static void main(String[] args) { Sample s = new Sample(); s.aMethod(); } public void aMethod() { // x is introduced by the following aspect as private // so it should not be accessible here System.out.println("I have " + x); } } aspect SampleAspect { private interface Tag {}; private int Tag.x = 0; declare parents: Sample implements Tag; }
|
resolved fixed
|
5795b4a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-18T22:31:27Z
| 2004-02-24T13:40:00Z
|
tests/bugs/VisiblePrivateInterfaceITDs.java
| |
53,012
|
Bug 53012 declare precedence on a class should be a compile-time error
|
The compiler silently accepts ---- public class DeclarePrecedence { public static void main(String[] args) { System.out.println("hello"); } } aspect DP { declare precedence: DeclarePrecedence, DP; before() : staticinitialization(DeclarePrecedence) { System.out.println("ok"); } } ---- Since this is likely to be a mistake, an error would be nice. However, that would mean saying (!TargetClass && TargetClass+) to pick out the aspect subtypes of TargetClass.
|
resolved fixed
|
0a01759
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-19T09:28:14Z
| 2004-02-25T00:46:40Z
|
tests/bugs/declarePrecedenceWithClasses/DeclarePrecedenceTestClass.java
| |
53,012
|
Bug 53012 declare precedence on a class should be a compile-time error
|
The compiler silently accepts ---- public class DeclarePrecedence { public static void main(String[] args) { System.out.println("hello"); } } aspect DP { declare precedence: DeclarePrecedence, DP; before() : staticinitialization(DeclarePrecedence) { System.out.println("ok"); } } ---- Since this is likely to be a mistake, an error would be nice. However, that would mean saying (!TargetClass && TargetClass+) to pick out the aspect subtypes of TargetClass.
|
resolved fixed
|
0a01759
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-03-19T09:28:14Z
| 2004-02-25T00: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;
public class DeclarePrecedence extends Declare {
private TypePatternList patterns;
public DeclarePrecedence(List patterns) {
this(new TypePatternList(patterns));
}
private DeclarePrecedence(TypePatternList patterns) {
this.patterns = patterns;
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("declare precedence: ");
buf.append(patterns);
buf.append(";");
return buf.toString();
}
public boolean equals(Object other) {
if (!(other instanceof DeclarePrecedence)) return false;
DeclarePrecedence o = (DeclarePrecedence)other;
return o.patterns.equals(patterns);
}
public int hashCode() {
return patterns.hashCode();
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(Declare.DOMINATES);
patterns.write(s);
writeLocation(s);
}
public static Declare read(DataInputStream s, ISourceContext context) throws IOException {
Declare ret = new DeclarePrecedence(TypePatternList.read(s, context));
ret.readLocation(context, s);
return ret;
}
public void resolve(IScope scope) {
patterns = patterns.resolveBindings(scope, Bindings.NONE, false, false);
boolean seenStar = false;
for (int i=0; i < patterns.size(); i++) {
TypePattern pi = patterns.get(i);
if (pi.isStar()) {
if (seenStar) {
scope.getWorld().showMessage(IMessage.ERROR,
"circularity in declare precedence, '*' occurs more than once",
pi.getSourceLocation(), null);
}
seenStar = true;
continue;
}
ResolvedTypeX exactType = pi.getExactType().resolve(scope.getWorld());
if (exactType == ResolvedTypeX.MISSING) continue;
for (int j=0; j < patterns.size(); j++) {
if (j == i) continue;
TypePattern pj = patterns.get(j);
if (pj.isStar()) continue;
if (pj.matchesStatically(exactType)) {
scope.getWorld().showMessage(IMessage.ERROR,
"circularity in declare precedence, '" + exactType.getName() +
"' matches two patterns", pi.getSourceLocation(), pj.getSourceLocation());
}
}
}
}
public TypePatternList getPatterns() {
return patterns;
}
private int matchingIndex(ResolvedTypeX a) {
int knownMatch = -1;
int starMatch = -1;
for (int i=0, len=patterns.size(); i < len; i++) {
TypePattern p = patterns.get(i);
if (p.isStar()) {
starMatch = i;
} else if (p.matchesStatically(a)) {
if (knownMatch != -1) {
a.getWorld().showMessage(IMessage.ERROR, "multiple matches for " + a +
", matches both " + patterns.get(knownMatch) + " and " + p,
patterns.get(knownMatch).getSourceLocation(), p.getSourceLocation());
return -1;
} else {
knownMatch = i;
}
}
}
if (knownMatch == -1) return starMatch;
else return knownMatch;
}
public int compare(ResolvedTypeX aspect1, ResolvedTypeX aspect2) {
int index1 = matchingIndex(aspect1);
int index2 = matchingIndex(aspect2);
//System.out.println("a1: " + aspect1 + ", " + aspect2 + " = " + index1 + ", " + index2);
if (index1 == -1 || index2 == -1) return 0;
if (index1 == index2) return 0;
else if (index1 > index2) return -1;
else return +1;
}
public boolean isAdviceLike() {
return false;
}
}
|
31,460
|
Bug 31460 Weaving class loader
|
Hi! As discussed on the mailing list a few days ago I implemented a weaving class loader to enable bytecode based weaving at class loading time. The class loader is based on the URLClassLoader and can be used like any other URLClassLoader. In addition to that you can add aspects to the weaving loader. These aspects got woven into each class that is loaded. The test cases for the class loader aren't implemented yet, I am still thinking about how to implement them. I will contribute them later, okay? -Martin
|
resolved fixed
|
33d8ee9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-04-02T12:03:40Z
| 2003-02-10T15:13:20Z
|
org.aspectj.ajdt.core/testdata/src1/LTWHelloWorld.java
| |
31,460
|
Bug 31460 Weaving class loader
|
Hi! As discussed on the mailing list a few days ago I implemented a weaving class loader to enable bytecode based weaving at class loading time. The class loader is based on the URLClassLoader and can be used like any other URLClassLoader. In addition to that you can add aspects to the weaving loader. These aspects got woven into each class that is loaded. The test cases for the class loader aren't implemented yet, I am still thinking about how to implement them. I will contribute them later, okay? -Martin
|
resolved fixed
|
33d8ee9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-04-02T12:03:40Z
| 2003-02-10T15:13:20Z
|
org.aspectj.ajdt.core/testdata/src1/ltw/LTWPackageTest.java
| |
31,460
|
Bug 31460 Weaving class loader
|
Hi! As discussed on the mailing list a few days ago I implemented a weaving class loader to enable bytecode based weaving at class loading time. The class loader is based on the URLClassLoader and can be used like any other URLClassLoader. In addition to that you can add aspects to the weaving loader. These aspects got woven into each class that is loaded. The test cases for the class loader aren't implemented yet, I am still thinking about how to implement them. I will contribute them later, okay? -Martin
|
resolved fixed
|
33d8ee9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-04-02T12:03:40Z
| 2003-02-10T15:13:20Z
|
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/BcweaverJarMaker.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.batch;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.ArrayList;
import org.aspectj.ajdt.ajc.AjdtAjcTests;
public class BcweaverJarMaker {
public BcweaverJarMaker() {
super();
}
public static void main(String[] args) throws IOException {
makeJar0();
makeJar1();
makeJar1a();
makeJar2();
makeJarObviousNothing();
makeJarHardNothing();
makeTestJars();
}
public static void makeJar0() throws IOException {
List args = new ArrayList();
args.add("-outjar");
args.add("../weaver/testdata/tracing.jar");
args.add("-classpath");
args.add("../runtime/bin" + File.pathSeparator +
System.getProperty("aspectjrt.path"));
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/Trace.java");
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/MyTrace.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
}
public static void makeJar1() throws IOException {
List args = new ArrayList();
args.add("-outjar");
args.add("../weaver/testdata/megatrace.jar");
args.add("-classpath");
args.add("../runtime/bin" + File.pathSeparator +
System.getProperty("aspectjrt.path"));
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/MegaTrace.java");
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/ExecTrace.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
}
public static void makeJarObviousNothing() throws IOException {
List args = new ArrayList();
args.add("-outjar");
args.add("../weaver/testdata/megatrace0easy.jar");
args.add("-classpath");
args.add("../runtime/bin" + File.pathSeparator +
System.getProperty("aspectjrt.path"));
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/MegaTrace.java");
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/ObviousTraceNothing.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
}
public static void makeJarHardNothing() throws IOException {
List args = new ArrayList();
args.add("-outjar");
args.add("../weaver/testdata/megatrace0hard.jar");
args.add("-classpath");
args.add("../runtime/bin" + File.pathSeparator +
System.getProperty("aspectjrt.path"));
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/MegaTrace.java");
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/HardTraceNothing.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
}
public static void makeJar1a() throws IOException {
List args = new ArrayList();
args.add("-outjar");
args.add("../weaver/testdata/megatraceNoweave.jar");
args.add("-noweave");
args.add("-classpath");
args.add("../runtime/bin" + File.pathSeparator +
System.getProperty("aspectjrt.path"));
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/MegaTrace.java");
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/ExecTrace.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
}
public static void makeJar2() throws IOException {
List args = new ArrayList();
args.add("-outjar");
args.add("../weaver/testdata/dummyAspect.jar");
args.add("-classpath");
args.add("../runtime/bin" + File.pathSeparator +
System.getProperty("aspectjrt.path"));
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/DummyAspect.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
}
public static void makeTestJars() throws IOException {
List args = new ArrayList();
args.add("-classpath");
args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" +
File.pathSeparator + System.getProperty("aspectjrt.path"));
args.add("-outjar");
args.add("../tests/new/options11/aspectlib1.jar");
args.add("../tests/new/options11/library1/*.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
args = new ArrayList();
args.add("-classpath");
args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" +
File.pathSeparator + System.getProperty("aspectjrt.path"));
args.add("-outjar");
args.add("../tests/new/options11/aspectlib2.jar");
args.add("../tests/new/options11/library2/*.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
args = new ArrayList();
args.add("-classpath");
args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" +
File.pathSeparator + System.getProperty("aspectjrt.path"));
args.add("-outjar");
args.add("../tests/new/options11/injar.jar");
args.add("../tests/new/options11/injar/*.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
args = new ArrayList();
args.add("-classpath");
args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" +
File.pathSeparator + System.getProperty("aspectjrt.path"));
args.add("-outjar");
args.add("../tests/bugs/serialVersionUID/injar.jar");
args.add("../tests/bugs/serialVersionUID/Test.java");
args.add("../tests/bugs/serialVersionUID/Util.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
}
}
|
31,460
|
Bug 31460 Weaving class loader
|
Hi! As discussed on the mailing list a few days ago I implemented a weaving class loader to enable bytecode based weaving at class loading time. The class loader is based on the URLClassLoader and can be used like any other URLClassLoader. In addition to that you can add aspects to the weaving loader. These aspects got woven into each class that is loaded. The test cases for the class loader aren't implemented yet, I am still thinking about how to implement them. I will contribute them later, okay? -Martin
|
resolved fixed
|
33d8ee9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-04-02T12:03:40Z
| 2003-02-10T15:13:20Z
|
util/src/org/aspectj/util/FileUtil.java
|
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.util;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.zip.*;
import java.util.zip.ZipFile;
/**
*
*/
public class FileUtil {
/** default parent directory File when a file has a null parent */
public static final File DEFAULT_PARENT = new File("."); // XXX user.dir?
/** unmodifiable List of String source file suffixes (including leading ".") */
public static final List SOURCE_SUFFIXES
= Collections.unmodifiableList(Arrays.asList(new String[] { ".java", ".aj"}));
public static final FileFilter ZIP_FILTER = new FileFilter() {
public boolean accept(File file) {
return hasZipSuffix(file);
}
public String toString() {
return "ZIP_FILTER";
}
};
public static final FileFilter SOURCE_FILTER = new FileFilter() {
public boolean accept(File file) {
return hasSourceSuffix(file);
}
public String toString() {
return "SOURCE_FILTER";
}
};
final static int[] INT_RA = new int[0];
/** accept all files */
public static final FileFilter ALL = new FileFilter() {
public boolean accept(File f) { return true; }
};
public static final FileFilter DIRS_AND_WRITABLE_CLASSES
= new FileFilter() {
public boolean accept(File file) {
return ((null != file)
&& (file.isDirectory()
|| (file.canWrite()
&& file.getName().toLowerCase().endsWith(".class"))));
}
};
/** @return true if file path has a zip/jar suffix */
public static boolean hasZipSuffix(File file) {
return ((null != file) && hasZipSuffix(file.getPath()));
}
/** @return true if path ends with .zip or .jar */
public static boolean hasZipSuffix(String path) {
return ((null != path) && (0 != zipSuffixLength(path)));
}
/** @return 0 if file has no zip/jar suffix or 4 otherwise */
public static int zipSuffixLength(File file) {
return (null == file ? 0 : zipSuffixLength(file.getPath()));
}
/** @return 0 if no zip/jar suffix or 4 otherwise */
public static int zipSuffixLength(String path) {
if ((null != path) && (4 < path.length())){
String test = path.substring(path.length()-4).toLowerCase();
if (".zip".equals(test) || ".jar".equals(test)) {
return 4;
}
}
return 0;
}
/** @return true if file path has a source suffix */
public static boolean hasSourceSuffix(File file) {
return ((null != file) && hasSourceSuffix(file.getPath()));
}
/** @return true if path ends with .java or .aj */
public static boolean hasSourceSuffix(String path) {
return ((null != path) && (0 != sourceSuffixLength(path)));
}
/** @return 0 if file has no source suffix or the length of the suffix otherwise */
public static int sourceSuffixLength(File file) {
return (null == file ? 0 : sourceSuffixLength(file.getPath()));
}
/** @return 0 if no source suffix or the length of the suffix otherwise */
public static int sourceSuffixLength(String path) {
if (LangUtil.isEmpty(path)) {
return 0;
}
for (Iterator iter = SOURCE_SUFFIXES.iterator(); iter.hasNext();) {
String suffix = (String) iter.next();
if (path.endsWith(suffix)
|| path.toLowerCase().endsWith(suffix)) {
return suffix.length();
}
}
return 0;
}
/** @return true if this is a readable directory */
public static boolean canReadDir(File dir) {
return ((null != dir) && dir.canRead() && dir.isDirectory());
}
/** @return true if this is a readable file */
public static boolean canReadFile(File file) {
return ((null != file) && file.canRead() && file.isFile());
}
/** @return true if dir is a writable directory */
public static boolean canWriteDir(File dir) {
return ((null != dir) && dir.canWrite() && dir.isDirectory());
}
/** @return true if this is a writable file */
public static boolean canWriteFile(File file) {
return ((null != file) && file.canWrite() && file.isFile());
}
/** @throws IllegalArgumentException unless file is readable and not a directory */
public static void throwIaxUnlessCanReadFile(File file, String label) {
if (!canReadFile(file)) {
throw new IllegalArgumentException(label + " not readable file: " + file);
}
}
/** @throws IllegalArgumentException unless dir is a readable directory */
public static void throwIaxUnlessCanReadDir(File dir, String label) {
if (!canReadDir(dir)) {
throw new IllegalArgumentException(label + " not readable dir: " + dir);
}
}
/** @throws IllegalArgumentException unless file is readable and not a directory */
public static void throwIaxUnlessCanWriteFile(File file, String label) {
if (!canWriteFile(file)) {
throw new IllegalArgumentException(label + " not writable file: " + file);
}
}
/** @throws IllegalArgumentException unless dir is a readable directory */
public static void throwIaxUnlessCanWriteDir(File dir, String label) {
if (!canWriteDir(dir)) {
throw new IllegalArgumentException(label + " not writable dir: " + dir);
}
}
/** @return array same length as input, with String paths */
public static String[] getPaths(File[] files) {
if ((null == files) || (0 == files.length)) {
return new String[0];
}
String[] result = new String[files.length];
for (int i = 0; i < result.length; i++) {
if (null != files[i]) {
result[i] = files[i].getPath();
}
}
return result;
}
/** @return array same length as input, with String paths */
public static String[] getPaths(List files) {
final int size = (null == files ? 0 : files.size());
if (0 == size) {
return new String[0];
}
String[] result = new String[size];
for (int i = 0; i < size; i++) {
File file = (File) files.get(i);
if (null != file) {
result[i] = file.getPath();
}
}
return result;
}
/**
* Extract the name of a class from the path to its file.
* If the basedir is null, then the class is assumed to be in
* the default package unless the classFile has one of the
* top-level suffixes { com, org, java, javax } as a parent directory.
* @param basedir the File of the base directory (prefix of classFile)
* @param classFile the File of the class to extract the name for
* @throws IllegalArgumentException if classFile is null or does not end with
* ".class" or a non-null basedir is not a prefix of classFile
*/
public static String fileToClassName(File basedir, File classFile) {
LangUtil.throwIaxIfNull(classFile, "classFile");
String classFilePath = normalizedPath(classFile);
if (!classFilePath.endsWith(".class")) {
String m = classFile + " does not end with .class";
throw new IllegalArgumentException(m);
}
classFilePath = classFilePath.substring(0, classFilePath.length()-6);
if (null != basedir) {
String basePath = normalizedPath(basedir);
if (!classFilePath.startsWith(basePath)) {
String m = classFile + " does not start with " + basedir;
throw new IllegalArgumentException(m);
}
classFilePath = classFilePath.substring(basePath.length()+1);
} else {
final String[] suffixes = new String[] { "com", "org", "java", "javax"};
boolean found = false;
for (int i = 0; !found && (i < suffixes.length); i++) {
int loc = classFilePath.indexOf(suffixes[i] + "/");
if ((0 == loc)
|| ((-1 != loc) && ('/' == classFilePath.charAt(loc-1)))) {
classFilePath = classFilePath.substring(loc);
found = true;
}
}
if (!found) {
int loc = classFilePath.lastIndexOf("/");
if (-1 != loc) { // treat as default package
classFilePath = classFilePath.substring(loc+1);
}
}
}
return classFilePath.replace('/', '.');
}
/**
* Normalize path for comparisons by rendering absolute,
* clipping basedir prefix,
* trimming and changing '\\' to '/'
* @param file the File with the path to normalize
* @param basedir the File for the prefix of the file to normalize - ignored if null
* @return "" if null or normalized path otherwise
* @throws IllegalArgumentException if basedir is not a prefix of file
*/
public static String normalizedPath(File file, File basedir) {
String filePath = normalizedPath(file);
if (null != basedir) {
String basePath = normalizedPath(basedir);
if (filePath.startsWith(basePath)) {
filePath = filePath.substring(basePath.length());
if (filePath.startsWith("/")) {
filePath = filePath.substring(1);
}
}
}
return filePath;
}
/**
* Render a set of files to String as a path by getting absolute
* paths of each and delimiting with infix.
* @param files the File[] to flatten - may be null or empty
* @param infix the String delimiter internally between entries
* (if null, then use File.pathSeparator).
* (alias to <code>flatten(getAbsolutePaths(files), infix)</code>
* @return String with absolute paths to entries in order,
* delimited with infix
*/
public static String flatten(File[] files, String infix) {
if (LangUtil.isEmpty(files)) {
return "";
}
return flatten(getPaths(files), infix);
}
/**
* Flatten File[] to String.
* @param files the File[] of paths to flatten - null ignored
* @param infix the String infix to use - null treated as File.pathSeparator
*/
public static String flatten(String[] paths, String infix) {
if (null == infix) {
infix = File.pathSeparator;
}
StringBuffer result = new StringBuffer();
boolean first = true;
for (int i = 0; i < paths.length; i++) {
String path = paths[i];
if (null == path) {
continue;
}
if (first) {
first = false;
} else {
result.append(infix);
}
result.append(path);
}
return result.toString();
}
/**
* Normalize path for comparisons by rendering absolute
* trimming and changing '\\' to '/'
* @return "" if null or normalized path otherwise
*/
public static String normalizedPath(File file) {
return (null == file ? "" : weakNormalize(file.getAbsolutePath()));
}
/**
* Weakly normalize path for comparisons by
* trimming and changing '\\' to '/'
*/
public static String weakNormalize(String path) {
if (null != path) {
path = path.replace('\\', '/').trim();
}
return path;
}
/**
* Render as best path, canonical or absolute.
* @param file the File to get the path for (not null)
* @return String of the best-available path
* @throws IllegalArgumentException if file is null
*/
public static String getBestPath(File file) {
LangUtil.throwIaxIfNull(file, "file");
if (file.exists()) {
try {
return file.getCanonicalPath();
} catch (IOException e) {
return file.getAbsolutePath();
}
} else {
return file.getPath();
}
}
/** @return array same length as input, with String absolute paths */
public static String[] getAbsolutePaths(File[] files) {
if ((null == files) || (0 == files.length)) {
return new String[0];
}
String[] result = new String[files.length];
for (int i = 0; i < result.length; i++) {
if (null != files[i]) {
result[i] = files[i].getAbsolutePath();
}
}
return result;
}
/**
* Recursively delete the contents of dir, but not the dir itself
* @return the total number of files deleted
*/
public static int deleteContents(File dir) {
return deleteContents(dir, ALL);
}
/**
* Recursively delete some contents of dir, but not the dir itself.
* This deletes any subdirectory which is empty after its files
* are deleted.
* @return the total number of files deleted
*/
public static int deleteContents(File dir, FileFilter filter) {
return deleteContents(dir, filter, true);
}
/**
* Recursively delete some contents of dir, but not the dir itself.
* If deleteEmptyDirs is true, this deletes any subdirectory
* which is empty after its files are deleted.
* @param dir the File directory (if a file, the the file is deleted)
* @return the total number of files deleted
*/
public static int deleteContents(File dir, FileFilter filter,
boolean deleteEmptyDirs) {
if (null == dir) {
throw new IllegalArgumentException("null dir");
}
if ((!dir.exists()) || (!dir.canWrite())) {
return 0;
}
if (!dir.isDirectory()) {
dir.delete();
return 1;
}
String[] fromFiles = dir.list();
int result = 0;
for (int i = 0; i < fromFiles.length; i++) {
String string = fromFiles[i];
File file = new File(dir, string);
if ((null == filter) || filter.accept(file)) {
if (file.isDirectory()) {
result += deleteContents(file, filter, deleteEmptyDirs);
if (deleteEmptyDirs && (0 == file.list().length)) {
file.delete();
}
} else {
/*boolean ret = */file.delete();
result++;
}
}
}
return result;
}
/**
* Copy contents of fromDir into toDir
* @param fromDir must exist and be readable
* @param toDir must exist or be creatable and be writable
* @return the total number of files copied
*/
public static int copyDir(File fromDir, File toDir) throws IOException {
return copyDir(fromDir, toDir, null, null);
}
/**
* Recursively copy files in fromDir (with any fromSuffix) to toDir,
* replacing fromSuffix with toSuffix if any.
* This silently ignores dirs and files that are not readable
* but throw IOException for directories that are not writable.
* This does not clean out the original contents of toDir.
* (subdirectories are not renamed per directory rules)
* @param fromSuffix select files with this suffix - select all if null or empty
* @param toSuffix replace fromSuffix with toSuffix in the destination file
* name - ignored if null or empty,
* appended to name if fromSuffix is null or empty
* @return the total number of files copied
*/
public static int copyDir(File fromDir, File toDir,
final String fromSuffix, String toSuffix) throws IOException {
return copyDir(fromDir, toDir, fromSuffix, toSuffix, (FileFilter) null);
}
/**
* Recursively copy files in fromDir (with any fromSuffix) to toDir,
* replacing fromSuffix with toSuffix if any,
* and adding the destination file to any collector.
* This silently ignores dirs and files that are not readable
* but throw IOException for directories that are not writable.
* This does not clean out the original contents of toDir.
* (subdirectories are not renamed per directory rules)
* This calls any delegate FilenameFilter to collect any selected file.
* @param fromSuffix select files with this suffix - select all if null or empty
* @param toSuffix replace fromSuffix with toSuffix in the destination file
* name - ignored if null or empty,
* appended to name if fromSuffix is null or empty
* @param collector the List sink for destination files - ignored if null
* @return the total number of files copied
*/
public static int copyDir(File fromDir, File toDir, final String fromSuffix,
final String toSuffix, final List collector) throws IOException {
//int before = collector.size();
if (null == collector) {
return copyDir(fromDir, toDir, fromSuffix, toSuffix);
} else {
FileFilter collect = new FileFilter() {
public boolean accept(File pathname) {
return collector.add(pathname);
}
};
return copyDir(fromDir, toDir, fromSuffix, toSuffix, collect);
}
}
/**
* Recursively copy files in fromDir (with any fromSuffix) to toDir,
* replacing fromSuffix with toSuffix if any.
* This silently ignores dirs and files that are not readable
* but throw IOException for directories that are not writable.
* This does not clean out the original contents of toDir.
* (subdirectories are not renamed per directory rules)
* This calls any delegate FilenameFilter to collect any selected file.
* @param fromSuffix select files with this suffix - select all if null or empty
* @param toSuffix replace fromSuffix with toSuffix in the destination file
* name - ignored if null or empty,
* appended to name if fromSuffix is null or empty
* @return the total number of files copied
*/
public static int copyDir(File fromDir, File toDir, final String fromSuffix,
final String toSuffix, final FileFilter delegate) throws IOException {
if ((null == fromDir) || (!fromDir.canRead())) {
return 0;
}
final boolean haveSuffix = ((null != fromSuffix) && (0 < fromSuffix.length()));
final int slen = (!haveSuffix ? 0 : fromSuffix.length());
if (!toDir.exists()) {
toDir.mkdirs();
}
final String[] fromFiles;
if (!haveSuffix) {
fromFiles = fromDir.list();
} else {
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return (new File(dir, name).isDirectory()
|| (name.endsWith(fromSuffix)));
}
};
fromFiles = fromDir.list(filter);
}
int result = 0;
final int MAX = (null == fromFiles ? 0 : fromFiles.length);
for (int i = 0; i < MAX; i++) {
String filename = fromFiles[i];
File fromFile = new File(fromDir, filename);
if (fromFile.canRead()) {
if (fromFile.isDirectory()) {
result += copyDir(fromFile, new File(toDir, filename), fromSuffix, toSuffix, delegate);
} else if (fromFile.isFile()) {
if (haveSuffix) {
filename = filename.substring(0, filename.length()-slen);
}
if (null != toSuffix) {
filename = filename + toSuffix;
}
File targetFile = new File(toDir, filename);
if ((null == delegate) || delegate.accept(targetFile)) {
copyFile(fromFile, targetFile);
}
result++;
}
}
}
return result;
}
/**
* Recursively list files in srcDir.
* @return ArrayList with String paths of File under srcDir (relative to srcDir)
*/
public static String[] listFiles(File srcDir) {
ArrayList result = new ArrayList();
if ((null != srcDir) && srcDir.canRead()) {
listFiles(srcDir, null, result);
}
return (String[]) result.toArray(new String[0]);
}
public static final FileFilter aspectjSourceFileFilter = new FileFilter() {
public boolean accept(File pathname) {
String name = pathname.getName().toLowerCase();
return name.endsWith(".java") || name.endsWith(".aj");
}
};
/**
* Recursively list files in srcDir.
* @return ArrayList with String paths of File under srcDir (relative to srcDir)
*/
public static File[] listFiles(File srcDir, FileFilter fileFilter) {
ArrayList result = new ArrayList();
if ((null != srcDir) && srcDir.canRead()) {
listFiles(srcDir, result, fileFilter);
}
return (File[]) result.toArray(new File[result.size()]);
}
/**
* Convert String[] paths to File[] as offset of base directory
* @param basedir the non-null File base directory for File to create with paths
* @param paths the String[] of paths to create
* @return File[] with same length as paths
*/
public static File[] getBaseDirFiles(
File basedir,
String[] paths) {
return getBaseDirFiles(basedir, paths, (String[]) null);
}
/**
* Convert String[] paths to File[] as offset of base directory
* @param basedir the non-null File base directory for File to create with paths
* @param paths the String[] of paths to create
* @param suffixes the String[] of suffixes to limit sources to - ignored if null
* @return File[] with same length as paths
*/
public static File[] getBaseDirFiles(
File basedir,
String[] paths,
String[] suffixes) {
LangUtil.throwIaxIfNull(basedir, "basedir");
LangUtil.throwIaxIfNull(paths, "paths");
File[] result = null;
if (!LangUtil.isEmpty(suffixes)) {
ArrayList list = new ArrayList();
for (int i = 0; i < paths.length; i++) {
boolean listed = false;
String path = paths[i];
for (int j = 0; !listed && (j < suffixes.length); j++) {
String suffix = suffixes[j];
if (listed = path.endsWith(suffix)) {
list.add(new File(basedir, paths[i]));
}
}
}
result = (File[]) list.toArray(new File[0]);
} else {
result = new File[paths.length];
for (int i = 0; i < result.length; i++) {
result[i] = newFile(basedir, paths[i]);
}
}
return result;
}
/**
* Create a new File, resolving paths ".." and "." specially.
* @param dir the File for the parent directory of the file
* @param path the path in the parent directory (filename only?)
* @return File for the new file.
*/
private static File newFile(File dir, String path) {
if (".".equals(path)) {
return dir;
} else if ("..".equals(path)) {
File parentDir = dir.getParentFile();
if (null != parentDir) {
return parentDir;
} else {
return new File(dir, "..");
}
} else {
return new File(dir, path);
}
}
/**
* Copy files from source dir into destination directory,
* creating any needed directories. This differs from copyDir in not
* being recursive; each input with the source dir creates a full path.
* However, if the source is a directory, it is copied as such.
* @param srcDir an existing, readable directory containing relativePaths files
* @param relativePaths a set of paths relative to srcDir to readable File to copy
* @param destDir an existing, writable directory to copy files to
* @throws IllegalArgumentException if input invalid, IOException if operations fail
*/
public static File[] copyFiles(File srcDir, String[] relativePaths, File destDir)
throws IllegalArgumentException, IOException {
final String[] paths = relativePaths;
throwIaxUnlessCanReadDir(srcDir, "srcDir");
throwIaxUnlessCanWriteDir(destDir, "destDir");
LangUtil.throwIaxIfNull(paths, "relativePaths");
File[] result = new File[paths.length];
for (int i = 0; i < paths.length; i++) {
String path = paths[i];
LangUtil.throwIaxIfNull(path, "relativePaths-entry");
File src = newFile(srcDir, paths[i]);
File dest = newFile(destDir, path);
File destParent = dest.getParentFile();
if (!destParent.exists()) {
destParent.mkdirs();
}
LangUtil.throwIaxIfFalse(canWriteDir(destParent), "dest-entry-parent");
copyFile(src, dest); // both file-dir and dir-dir copies
result[i] = dest;
}
return result;
}
/**
* Copy fromFile to toFile, handling file-file, dir-dir, and file-dir
* copies.
* @param fromFile the File path of the file or directory to copy - must be
* readable
* @param toFile the File path of the target file or directory - must be
* writable (will be created if it does not exist)
*/
public static void copyFile(File fromFile, File toFile) throws IOException {
LangUtil.throwIaxIfNull(fromFile, "fromFile");
LangUtil.throwIaxIfNull(toFile, "toFile");
LangUtil.throwIaxIfFalse(!toFile.equals(fromFile), "same file");
if (toFile.isDirectory()) { // existing directory
throwIaxUnlessCanWriteDir(toFile, "toFile");
if (fromFile.isFile()) { // file-dir
File targFile = new File(toFile, fromFile.getName());
copyValidFiles(fromFile, targFile);
} else if (fromFile.isDirectory()) { // dir-dir
copyDir(fromFile, toFile);
} else {
LangUtil.throwIaxIfFalse(false, "not dir or file: " + fromFile);
}
} else if (toFile.isFile()) { // target file exists
if (fromFile.isDirectory()) {
LangUtil.throwIaxIfFalse(false, "can't copy to file dir: " + fromFile);
}
copyValidFiles(fromFile, toFile); // file-file
} else { // target file is a non-existent path -- could be file or dir
/*File toFileParent = */ensureParentWritable(toFile);
if (fromFile.isFile()) {
copyValidFiles(fromFile, toFile);
} else if (fromFile.isDirectory()) {
toFile.mkdirs();
throwIaxUnlessCanWriteDir(toFile, "toFile");
copyDir(fromFile, toFile);
} else {
LangUtil.throwIaxIfFalse(false, "not dir or file: " + fromFile);
}
}
}
/**
* Ensure that the parent directory to path can be written.
* If the path has a null parent, DEFAULT_PARENT is tested.
* If the path parent does not exist, this tries to create it.
* @param path the File path whose parent should be writable
* @return the File path of the writable parent directory
* @throws IllegalArgumentException if parent cannot be written
* or path is null.
*/
public static File ensureParentWritable(File path) {
LangUtil.throwIaxIfNull(path, "path");
File pathParent = path.getParentFile();
if (null == pathParent) {
pathParent = DEFAULT_PARENT;
}
if (!pathParent.canWrite()) {
pathParent.mkdirs();
}
throwIaxUnlessCanWriteDir(pathParent, "pathParent");
return pathParent;
}
/**
* Copy file to file.
* @param fromFile the File to copy (readable, non-null file)
* @param toFile the File to copy to (non-null, parent dir exists)
* @throws IOException
*/
public static void copyValidFiles(File fromFile, File toFile) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(fromFile);
out = new FileOutputStream(toFile);
copyStream(in, out);
} finally {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
}
}
/** do line-based copying */
public static void copyStream(DataInputStream in, PrintStream out) throws IOException {
LangUtil.throwIaxIfNull(in, "in");
LangUtil.throwIaxIfNull(in, "out");
String s;
while (null != (s = in.readLine())) {
out.println(s);
}
}
public static void copyStream(InputStream in, OutputStream out) throws IOException {
final int MAX = 4096;
byte[] buf = new byte[MAX];
for (int bytesRead = in.read(buf, 0, MAX);
bytesRead != -1;
bytesRead = in.read(buf, 0, MAX)) {
out.write(buf, 0, bytesRead);
}
}
public static void copyStream(Reader in, Writer out) throws IOException {
final int MAX = 4096;
char[] buf = new char[MAX];
for (int bytesRead = in.read(buf, 0, MAX);
bytesRead != -1;
bytesRead = in.read(buf, 0, MAX)) {
out.write(buf, 0, bytesRead);
}
}
/**
* Make a new child directory of parent
* @param parent a File for the parent (writable)
* @param child a prefix for the child directory
* @return a File dir that exists with parentDir as the parent file or null
*/
public static File makeNewChildDir(File parent, String child) {
if (null == parent || ! parent.canWrite() || !parent.isDirectory()) {
throw new IllegalArgumentException("bad parent: " + parent);
} else if (null == child) {
child = "makeNewChildDir";
} else if (!isValidFileName(child)) {
throw new IllegalArgumentException("bad child: " + child);
}
File result = new File(parent, child);
int safety = 1000;
for (String suffix = FileUtil.randomFileString();
((0 < --safety) && result.exists());
suffix = FileUtil.randomFileString()) {
result = new File(parent, child+suffix);
}
if ((null == result) || result.exists()) {
System.err.println("exhausted files for child dir in " + parent);
return null;
}
return ((result.mkdirs() && result.exists()) ? result : null);
}
/**
* Make a new temporary directory in the same directory
* that the system uses for temporary files, or if
* that files, in the current directory.
* @param name the preferred (simple) name of the directory - may be null.
* @return File of an existing new temp dir, or null if unable to create
*/
public static File getTempDir(String name) {
if (null == name) {
name = "FileUtil_getTempDir";
} else if (!isValidFileName(name)) {
throw new IllegalArgumentException(" invalid: " + name);
}
File result = null;
File tempFile = null;
try {
tempFile = File.createTempFile("ignoreMe", ".txt");
File tempParent = tempFile.getParentFile();
result = makeNewChildDir(tempParent, name);
} catch (IOException t) {
result = makeNewChildDir(new File("."), name);
} finally {
if (null != tempFile) {
tempFile.delete();
}
}
return result;
}
public static URL[] getFileURLs(File[] files) {
if ((null == files) || (0 == files.length)) {
return new URL[0];
}
URL[] result = new URL[files.length]; // XXX dangerous non-copy...
for (int i = 0; i < result.length; i++) {
result[i] = getFileURL(files[i]);
}
return result;
}
/**
* Get URL for a File.
* This appends "/" for directories.
* prints errors to System.err
* @param file the File to convert to URL (not null)
*/
public static URL getFileURL(File file) {
LangUtil.throwIaxIfNull(file, "file");
URL result = null;
try {
String url = "file:" + file.getAbsolutePath().replace('\\', '/');
result = new URL(url + (file.isDirectory() ? "/" : ""));
} catch (MalformedURLException e) {
String m = "Util.makeURL(\"" + file.getPath() + "\" MUE " + e.getMessage();
System.err.println(m);
}
return result;
}
/**
* Write contents to file, returning null on success or error message otherwise.
* This tries to make any necessary parent directories first.
* @param file the File to write (not null)
* @param contents the String to write (use "" if null)
* @return String null on no error, error otherwise
*/
public static String writeAsString(File file, String contents) {
LangUtil.throwIaxIfNull(file, "file");
if (null == contents) {
contents = "";
}
Writer out = null;
try {
File parentDir = file.getParentFile();
if (!parentDir.exists() && !parentDir.mkdirs()) {
return "unable to make parent dir for " + file;
}
Reader in = new StringReader(contents);
out = new FileWriter(file);
FileUtil.copyStream(in, out);
return null;
} catch (IOException e) {
return LangUtil.unqualifiedClassName(e) + " writing " + file
+ ": " + e.getMessage();
} finally {
if (null != out) {
try { out.close(); }
catch (IOException e) {} // ignored
}
}
}
/**
* Reads a boolean array with our encoding
*/
public static boolean[] readBooleanArray(DataInputStream s) throws IOException {
int len = s.readInt();
boolean[] ret = new boolean[len];
for (int i=0; i < len; i++) ret[i] = s.readBoolean();
return ret;
}
/**
* Writes a boolean array with our encoding
*/
public static void writeBooleanArray(boolean[] a, DataOutputStream s) throws IOException {
int len = a.length;
s.writeInt(len);
for (int i=0; i < len; i++) s.writeBoolean(a[i]);
}
/**
* Reads an int array with our encoding
*/
public static int[] readIntArray(DataInputStream s) throws IOException {
int len = s.readInt();
int[] ret = new int[len];
for (int i=0; i < len; i++) ret[i] = s.readInt();
return ret;
}
/**
* Writes an int array with our encoding
*/
public static void writeIntArray(int[] a, DataOutputStream s) throws IOException {
int len = a.length;
s.writeInt(len);
for (int i=0; i < len; i++) s.writeInt(a[i]);
}
/**
* Reads an int array with our encoding
*/
public static String[] readStringArray(DataInputStream s) throws IOException {
int len = s.readInt();
String[] ret = new String[len];
for (int i=0; i < len; i++) ret[i] = s.readUTF();
return ret;
}
/**
* Writes an int array with our encoding
*/
public static void writeStringArray(String[] a, DataOutputStream s) throws IOException {
if (a == null) {
s.writeInt(0);
return;
}
int len = a.length;
s.writeInt(len);
for (int i=0; i < len; i++) s.writeUTF(a[i]);
}
/**
* Returns the contents of this file as a String
*/
public static String readAsString(File file) throws IOException {
BufferedReader r = new BufferedReader(new FileReader(file));
StringBuffer b = new StringBuffer();
while (true) {
int ch = r.read();
if (ch == -1) break;
b.append((char)ch);
}
r.close();
return b.toString();
}
/**
* Returns the contents of this stream as a String
*/
public static String readAsString(InputStream in) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuffer b = new StringBuffer();
while (true) {
int ch = r.read();
if (ch == -1) break;
b.append((char)ch);
}
in.close();
r.close();
return b.toString();
}
/**
* Returns the contents of this file as a byte[]
*/
public static byte[] readAsByteArray(File file) throws IOException {
FileInputStream in = new FileInputStream(file);
byte[] ret = FileUtil.readAsByteArray(in);
in.close();
return ret;
}
/**
* Reads this input stream and returns contents as a byte[]
*/
public static byte[] readAsByteArray(InputStream inStream) throws IOException {
int size = 1024;
byte[] ba = new byte[size];
int readSoFar = 0;
while (true) {
int nRead = inStream.read(ba, readSoFar, size-readSoFar);
if (nRead == -1) break;
readSoFar += nRead;
if (readSoFar == size) {
int newSize = size * 2;
byte[] newBa = new byte[newSize];
System.arraycopy(ba, 0, newBa, 0, size);
ba = newBa;
size = newSize;
}
}
byte[] newBa = new byte[readSoFar];
System.arraycopy(ba, 0, newBa, 0, readSoFar);
return newBa;
}
final static String FILECHARS = "abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
/** @return semi-random String of length 6 usable as filename suffix */
static String randomFileString() {
final double FILECHARS_length = FILECHARS.length();
final int LEN = 6;
final char[] result = new char[LEN];
int index = (int) (Math.random() * 6d);
for (int i = 0; i < LEN; i++) {
if (index >= LEN) {
index = 0;
}
result[index++] = FILECHARS.charAt((int) (Math.random() * FILECHARS_length));
}
return new String(result);
}
public static InputStream getStreamFromZip(String zipFile, String name) {
try {
ZipFile zf = new ZipFile(zipFile);
try {
ZipEntry entry = zf.getEntry(name);
return zf.getInputStream(entry);
} finally {
//??? is it safe not to close this zf.close();
}
} catch (IOException ioe) {
return null;
}
}
public static void extractJar(String zipFile, String outDir) throws IOException {
ZipInputStream zs = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry entry;
while ( (entry = zs.getNextEntry()) != null) {
if (entry.isDirectory()) continue;
byte[] in = readAsByteArray(zs);
File outFile = new File(outDir + "/" + entry.getName());
//if (!outFile.getParentFile().exists())
//System.err.println("parent: " + outFile.getParentFile());
//System.err.println("parent: " + outFile.getParentFile());
outFile.getParentFile().mkdirs();
FileOutputStream os = new FileOutputStream(outFile);
os.write(in);
os.close();
zs.closeEntry();
}
zs.close();
}
/**
* Do line-based search for literal text in source files,
* returning file:line where found.
* @param sought the String text to seek in the file
* @param sources the List of String paths to the source files
* @param listAll if false, only list first match in file
* @param errorSink the PrintStream to print any errors to (one per line)
* (use null to silently ignore errors)
* @return List of String of the form file:line for each found entry
* (never null, might be empty)
*/
public static List lineSeek(String sought, List sources, boolean listAll,
PrintStream errorSink) {
if (LangUtil.isEmpty(sought) || LangUtil.isEmpty(sources)) {
return Collections.EMPTY_LIST;
}
ArrayList result = new ArrayList();
for (Iterator iter = sources.iterator(); iter.hasNext();) {
String path = (String) iter.next();
String error = lineSeek(sought, path, listAll, result);
if ((null != error) && (null != errorSink)) {
errorSink.println(error);
}
}
return result;
}
/**
* Do line-based search for literal text in source file,
* returning line where found as a String
* in the form {sourcePath}:line:column submitted to the
* collecting parameter sink.
* Any error is rendered to String and returned as the result.
*
* @param sought the String text to seek in the file
* @param sources the List of String paths to the source files
* @param listAll if false, only list first match in file
* @param List sink the List for String entries of the form {sourcePath}:line:column
* @return String error if any, or add String entries to sink
*/
public static String lineSeek(String sought, String sourcePath, boolean listAll,
ArrayList sink) {
if (LangUtil.isEmpty(sought) || LangUtil.isEmpty(sourcePath)) {
return "nothing sought";
}
if (LangUtil.isEmpty(sourcePath)) {
return "no sourcePath";
}
final File file = new File(sourcePath);
if (!file.canRead() || !file.isFile()) {
return "sourcePath not a readable file";
}
int lineNum = 0;
FileReader fin = null;
try {
fin = new FileReader(file);
BufferedReader reader = new BufferedReader(fin);
String line;
while (null != (line = reader.readLine())) {
lineNum++;
int loc = line.indexOf(sought);
if (-1 != loc) {
sink.add(sourcePath + ":" + lineNum + ":" + loc);
if (!listAll) {
break;
}
}
}
} catch (IOException e) {
return LangUtil.unqualifiedClassName(e) + " reading " + sourcePath
+ ":" + lineNum;
} finally {
try { if (null != fin) fin.close(); }
catch (IOException e) {} // ignore
}
return null;
}
public static BufferedOutputStream makeOutputStream(File file) throws FileNotFoundException {
File parent = file.getParentFile();
if (parent != null) parent.mkdirs();
return new BufferedOutputStream(new FileOutputStream(file));
}
/**
* Sleep until after the last last-modified stamp from the files.
* @param files the File[] of files to inspect for last modified times
* (this ignores null or empty files array
* and null or non-existing components of files array)
* @return true if succeeded without 100 interrupts
*/
public static boolean sleepPastFinalModifiedTime(File[] files) {
if ((null == files) || (0 == files.length)) {
return true;
}
long delayUntil = System.currentTimeMillis();
for (int i = 0; i < files.length; i++) {
File file = files[i];
if ((null == file) || !file.exists()) {
continue;
}
long nextModTime = file.lastModified();
if (nextModTime > delayUntil) {
delayUntil = nextModTime;
}
}
return LangUtil.sleepUntil(++delayUntil);
}
// /** map name to result, removing any fromSuffix and adding any toSuffix */
// private static String map(String name, String fromSuffix, String toSuffix) {
// if (null != name) {
// if (null != fromSuffix) {
// name = name.substring(0, name.length()-fromSuffix.length());
// }
// if (null != toSuffix) {
// name = name + toSuffix;
// }
// }
// return name;
// }
private static void listFiles(final File baseDir, ArrayList result, FileFilter filter) {
File[] files = baseDir.listFiles();
for (int i = 0; i < files.length; i++) {
File f = files[i];
if (f.isDirectory()) {
listFiles(f, result, filter);
} else {
if (filter.accept(f)) result.add(f);
}
}
}
/** @return true if input is not null and contains no path separator */
private static boolean isValidFileName(String input) {
return ((null != input) && (-1 == input.indexOf(File.pathSeparator)));
}
private static void listFiles(final File baseDir, String dir, ArrayList result) {
final String dirPrefix = (null == dir ? "" : dir + "/");
final File dirFile = (null == dir ? baseDir : new File(baseDir.getPath() + "/" + dir));
final String[] files = dirFile.list();
for (int i = 0; i < files.length; i++) {
File f = new File(dirFile, files[i]);
String path = dirPrefix + files[i];
if (f.isDirectory()) {
listFiles(baseDir, path, result);
} else {
result.add(path);
}
}
}
private FileUtil() { throw new Error("utility class"); }
/**
* A pipe when run reads from an input stream to an output stream,
* optionally sleeping between reads.
* @see #copyStream(InputStream, OutputStream)
*/
public static class Pipe implements Runnable {
private final InputStream in;
private final OutputStream out;
private final long sleep;
private ByteArrayOutputStream snoop;
private long totalWritten;
private Throwable thrown;
private boolean halt;
/**
* Seem to be unable to detect erroroneous closing of System.out...
*/
private final boolean closeInput;
private final boolean closeOutput;
/**
* If true, then continue processing stream until
* no characters are returned when halting.
*/
private boolean finishStream;
private boolean done; // true after completing() completes
/**
* alias for <code>Pipe(in, out, 100l, false, false)</code>
* @param in the InputStream source to read
* @param out the OutputStream sink to write
*/
Pipe(
InputStream in,
OutputStream out) {
this(in, out, 100l, false, false);
}
/**
* @param in the InputStream source to read
* @param out the OutputStream sink to write
* @param tryClosingStreams if true, then try closing both streams when done
* @param sleep milliseconds to delay between reads (pinned to 0..1 minute)
*/
Pipe(
InputStream in,
OutputStream out,
long sleep,
boolean closeInput,
boolean closeOutput) {
LangUtil.throwIaxIfNull(in, "in");
LangUtil.throwIaxIfNull(out, "out");
this.in = in;
this.out = out;
this.closeInput = closeInput;
this.closeOutput = closeOutput;
this.sleep = Math.min(0l, Math.max(60l*1000l, sleep));
}
public void setSnoop(ByteArrayOutputStream snoop) {
this.snoop = snoop;
}
/**
* Run the pipe.
* This halts on the first Throwable thrown or when a read returns
* -1 (for end-of-file) or on demand.
*/
public void run() {
totalWritten = 0;
if (halt) {
return;
}
try {
final int MAX = 4096;
byte[] buf = new byte[MAX];
int count = in.read(buf, 0, MAX);
ByteArrayOutputStream mySnoop;
while ((halt && finishStream && (0 < count))
|| (!halt && (-1 != count))) {
out.write(buf, 0, count);
mySnoop = snoop;
if (null != mySnoop) {
mySnoop.write(buf, 0, count);
}
totalWritten += count;
if (halt && !finishStream) {
break;
}
if (!halt && (0 < sleep)) {
Thread.sleep(sleep);
}
if (halt && !finishStream) {
break;
}
count = in.read(buf, 0, MAX);
}
} catch (Throwable e) {
thrown = e;
} finally {
halt = true;
if (closeInput) {
try {
in.close();
} catch (IOException e) {
// ignore
}
}
if (closeOutput) {
try {
out.close();
} catch (IOException e) {
// ignore
}
}
done = true;
completing(totalWritten, thrown);
}
}
/**
* Tell the pipe to halt the next time it gains control.
* @param wait if true, this waits synchronously until pipe is done
* @param finishStream if true, then continue until
* a read from the input stream returns no bytes, then halt.
* @return true if <code>run()</code> will return the next time it gains control
*/
public boolean halt(boolean wait, boolean finishStream) {
if (!halt) {
halt = true;
}
if (wait) {
while (!done) {
synchronized (this) {
notifyAll();
}
if (!done) {
try {
Thread.sleep(5l);
} catch (InterruptedException e) {
break;
}
}
}
}
return halt;
}
/** @return the total number of bytes written */
public long totalWritten() {
return totalWritten;
}
/** @return any exception thrown when reading/writing */
public Throwable getThrown() {
return thrown;
}
/**
* This is called when the pipe is completing.
* This implementation does nothing.
* Subclasses implement this to get notice.
* Note that halt(true, true) might or might not have completed
* before this method is called.
*/
protected void completing(long totalWritten, Throwable thrown) {
}
}
}
|
31,460
|
Bug 31460 Weaving class loader
|
Hi! As discussed on the mailing list a few days ago I implemented a weaving class loader to enable bytecode based weaving at class loading time. The class loader is based on the URLClassLoader and can be used like any other URLClassLoader. In addition to that you can add aspects to the weaving loader. These aspects got woven into each class that is loaded. The test cases for the class loader aren't implemented yet, I am still thinking about how to implement them. I will contribute them later, okay? -Martin
|
resolved fixed
|
33d8ee9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-04-02T12:03:40Z
| 2003-02-10T15:13:20Z
|
weaver/src/org/aspectj/weaver/ExtensibleURLClassLoader.java
| |
31,460
|
Bug 31460 Weaving class loader
|
Hi! As discussed on the mailing list a few days ago I implemented a weaving class loader to enable bytecode based weaving at class loading time. The class loader is based on the URLClassLoader and can be used like any other URLClassLoader. In addition to that you can add aspects to the weaving loader. These aspects got woven into each class that is loaded. The test cases for the class loader aren't implemented yet, I am still thinking about how to implement them. I will contribute them later, okay? -Martin
|
resolved fixed
|
33d8ee9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-04-02T12:03:40Z
| 2003-02-10T15:13:20Z
|
weaver/src/org/aspectj/weaver/WeavingURLClassLoader.java
| |
31,460
|
Bug 31460 Weaving class loader
|
Hi! As discussed on the mailing list a few days ago I implemented a weaving class loader to enable bytecode based weaving at class loading time. The class loader is based on the URLClassLoader and can be used like any other URLClassLoader. In addition to that you can add aspects to the weaving loader. These aspects got woven into each class that is loaded. The test cases for the class loader aren't implemented yet, I am still thinking about how to implement them. I will contribute them later, okay? -Martin
|
resolved fixed
|
33d8ee9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-04-02T12:03:40Z
| 2003-02-10T15:13:20Z
|
weaver/src/org/aspectj/weaver/tools/GeneratedClassHandler.java
| |
31,460
|
Bug 31460 Weaving class loader
|
Hi! As discussed on the mailing list a few days ago I implemented a weaving class loader to enable bytecode based weaving at class loading time. The class loader is based on the URLClassLoader and can be used like any other URLClassLoader. In addition to that you can add aspects to the weaving loader. These aspects got woven into each class that is loaded. The test cases for the class loader aren't implemented yet, I am still thinking about how to implement them. I will contribute them later, okay? -Martin
|
resolved fixed
|
33d8ee9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-04-02T12:03:40Z
| 2003-02-10T15:13:20Z
|
weaver/src/org/aspectj/weaver/tools/WeavingAdaptor.java
| |
31,460
|
Bug 31460 Weaving class loader
|
Hi! As discussed on the mailing list a few days ago I implemented a weaving class loader to enable bytecode based weaving at class loading time. The class loader is based on the URLClassLoader and can be used like any other URLClassLoader. In addition to that you can add aspects to the weaving loader. These aspects got woven into each class that is loaded. The test cases for the class loader aren't implemented yet, I am still thinking about how to implement them. I will contribute them later, okay? -Martin
|
resolved fixed
|
33d8ee9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-04-02T12:03:40Z
| 2003-02-10T15:13:20Z
|
weaver/src/org/aspectj/weaver/tools/WeavingClassLoader.java
| |
31,460
|
Bug 31460 Weaving class loader
|
Hi! As discussed on the mailing list a few days ago I implemented a weaving class loader to enable bytecode based weaving at class loading time. The class loader is based on the URLClassLoader and can be used like any other URLClassLoader. In addition to that you can add aspects to the weaving loader. These aspects got woven into each class that is loaded. The test cases for the class loader aren't implemented yet, I am still thinking about how to implement them. I will contribute them later, okay? -Martin
|
resolved fixed
|
33d8ee9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-04-02T12:03:40Z
| 2003-02-10T15:13:20Z
|
weaver/testsrc/BcweaverModuleTests.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
* ******************************************************************/
// default package
import junit.framework.*;
import junit.framework.Test;
public class BcweaverModuleTests extends TestCase {
public static Test suite() {
TestSuite suite = new TestSuite(BcweaverModuleTests.class.getName());
suite.addTest(org.aspectj.weaver.bcel.BcelTests.suite());
suite.addTest(org.aspectj.weaver.BcweaverTests.suite());
suite.addTest(org.aspectj.weaver.patterns.PatternsTests.suite());
suite.addTestSuite(LocaleTest.class);
return suite;
}
public BcweaverModuleTests(String name) { super(name); }
}
|
31,460
|
Bug 31460 Weaving class loader
|
Hi! As discussed on the mailing list a few days ago I implemented a weaving class loader to enable bytecode based weaving at class loading time. The class loader is based on the URLClassLoader and can be used like any other URLClassLoader. In addition to that you can add aspects to the weaving loader. These aspects got woven into each class that is loaded. The test cases for the class loader aren't implemented yet, I am still thinking about how to implement them. I will contribute them later, okay? -Martin
|
resolved fixed
|
33d8ee9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-04-02T12:03:40Z
| 2003-02-10T15:13:20Z
|
weaver/testsrc/org/aspectj/weaver/BcweaverTests.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.File;
import org.aspectj.util.FileUtil;
import junit.framework.*;
public class BcweaverTests extends TestCase {
public static final String TESTDATA_PATH = "../weaver/testdata";
public static final String OUTDIR_PATH = "../weaver/out";
/** @return File outDir (writable) or null if unable to write */
public static File getOutdir() {
File result = new File(OUTDIR_PATH);
if (result.mkdirs()
|| (result.canWrite() && result.isDirectory())) {
return result;
}
return null;
}
/** best efforts to delete the output directory and any contents */
public static void removeOutDir() {
File outDir = getOutdir();
if (null != outDir) {
FileUtil.deleteContents(outDir);
outDir.delete();
}
}
public static Test suite() {
TestSuite suite = new TestSuite(BcweaverTests.class.getName());
// abstract
//suite.addTestSuite(AbstractWorldTestCase.class);
//$JUnit-BEGIN$
suite.addTestSuite(MemberTestCase.class);
suite.addTestSuite(TypeXTestCase.class);
//$JUnit-END$
return suite;
}
public BcweaverTests(String name) { super(name); }
}
|
31,460
|
Bug 31460 Weaving class loader
|
Hi! As discussed on the mailing list a few days ago I implemented a weaving class loader to enable bytecode based weaving at class loading time. The class loader is based on the URLClassLoader and can be used like any other URLClassLoader. In addition to that you can add aspects to the weaving loader. These aspects got woven into each class that is loaded. The test cases for the class loader aren't implemented yet, I am still thinking about how to implement them. I will contribute them later, okay? -Martin
|
resolved fixed
|
33d8ee9
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-04-02T12:03:40Z
| 2003-02-10T15:13:20Z
|
weaver/testsrc/org/aspectj/weaver/WeavingURLClassLoaderTest.java
| |
55,341
|
Bug 55341 error Type mismatch: cannot convert from java.lang.String to java.lang.String
|
When compiling a binary concrete aspect library (for later LTW) consisting of more than one aspect that performs an ITD on a target class not exposed to the weaver I get the following error: error Type mismatch: cannot convert from java.lang.String to java.lang.String The error does not oocur if a complete build & weave is performed. Testcase attached.
|
resolved fixed
|
0521e79
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-04-02T12:45:13Z
| 2004-03-19T09:53:20Z
|
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/InterTypeMemberFinder.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.Arrays;
import java.util.List;
import org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.IMemberFinder;
import org.eclipse.jdt.internal.compiler.lookup.InvocationSite;
import org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.eclipse.jdt.internal.compiler.lookup.ProblemFieldBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
import org.eclipse.jdt.core.compiler.CharOperation;
public class InterTypeMemberFinder implements IMemberFinder {
private List interTypeFields = new ArrayList();
private List interTypeMethods = new ArrayList();
public SourceTypeBinding sourceTypeBinding;
public FieldBinding getField(
SourceTypeBinding sourceTypeBinding,
char[] fieldName,
InvocationSite site,
Scope scope)
{
FieldBinding retField = sourceTypeBinding.getFieldBase(fieldName, false); // XXX may need to get the correct value for second parameter in the future
if (interTypeFields.isEmpty()) return retField;
int fieldLength = fieldName.length;
for (int i=0, len=interTypeFields.size(); i < len; i++) {
FieldBinding field = (FieldBinding)interTypeFields.get(i);
if (field.name.length == fieldLength && CharOperation.prefixEquals(field.name, fieldName)) {
retField = resolveConflicts(sourceTypeBinding, retField, field, site, scope);
}
}
return retField;
}
private FieldBinding resolveConflicts(
SourceTypeBinding sourceTypeBinding,
FieldBinding retField,
FieldBinding field,
InvocationSite site,
Scope scope)
{
if (retField == null) return field;
if (site != null) {
if (!field.canBeSeenBy(sourceTypeBinding, site, scope)) return retField;
if (!retField.canBeSeenBy(sourceTypeBinding, site, scope)) return field;
}
//XXX need dominates check on aspects
return new ProblemFieldBinding(retField.declaringClass, retField.name, ProblemReporter.Ambiguous);
}
// private void reportConflicts(SourceTypeBinding sourceTypeBinding,
// MethodBinding m1, MethodBinding m2)
// {
// if (m1 == m2) {
// System.err.println("odd that we're ecomparing the same: " + m1);
// return;
// }
//
// if (!m1.areParametersEqual(m2)) return;
// if (m1 instanceof InterTypeMethodBinding) {
// if (m2 instanceof InterTypeMethodBinding) {
// reportConflictsBoth(sourceTypeBinding,
// (InterTypeMethodBinding)m1,
// (InterTypeMethodBinding)m2);
// } else {
// reportConflictsOne(sourceTypeBinding,
// (InterTypeMethodBinding)m1,
// m2);
// }
// } else if (m2 instanceof InterTypeMethodBinding) {
// reportConflictsOne(sourceTypeBinding,
// (InterTypeMethodBinding)m2,
// m1);
// } else {
// reportConflictsNone(sourceTypeBinding,
// m2,
// m1);
// }
// }
// private void reportConflicts(
// SourceTypeBinding sourceTypeBinding,
// MethodBinding m1,
// MethodBinding m2)
// {
// //System.err.println("compare: " + m1 + " with " + m2);
//
// if (m1 == m2) {
// System.err.println("odd that we're ecomparing the same: " + m1);
// return;
// }
//
// if (!m1.areParametersEqual(m2)) return;
//
// //System.err.println("t1: " + getTargetType(m1) + ", " + getTargetType(m2));
//
// if (getTargetType(m1) != getTargetType(m2)) return;
//
// if (m1.declaringClass == m2.declaringClass) {
// duplicateMethodBinding(m1, m2);
// return;
// }
//
//
// if (m1.isPublic() || m2.isPublic()) {
// duplicateMethodBinding(m1, m2);
// return;
// }
//
// // handle the wierd case where the aspect is a subtype of the target
// if (m2.isProtected()) {
// if (m2.declaringClass.isSuperclassOf(m1.declaringClass)) {
// duplicateMethodBinding(m1, m2);
// }
// // don't return because we also want to do the package test
// }
//
// if (!m1.isPrivate() || !m2.isPrivate()) {
// // at least package visible
// if (m1.declaringClass.getPackage() == m2.declaringClass.getPackage()) {
// duplicateMethodBinding(m1, m2);
// }
// return;
// }
//
// //XXX think about inner types some day
// }
////
private boolean isVisible(MethodBinding m1, ReferenceBinding s) {
if (m1.declaringClass == s) return true;
if (m1.isPublic()) return true;
//don't need to handle protected
//if (m1.isProtected()) {
if (!m1.isPrivate()) {
// at least package visible
return (m1.declaringClass.getPackage() == s.getPackage());
}
return false;
}
//
// private void duplicateMethodBinding(MethodBinding m1, MethodBinding m2) {
// ReferenceBinding t1 = m1.declaringClass;
// ReferenceBinding t2 = m2.declaringClass;
//
//
//
//
//
//
// if (!(t1 instanceof SourceTypeBinding) || !(t2 instanceof SourceTypeBinding)) {
// throw new RuntimeException("unimplemented");
// }
//
// SourceTypeBinding s1 = (SourceTypeBinding)t1;
// SourceTypeBinding s2 = (SourceTypeBinding)t2;
//
// if (m1.sourceMethod() != null) {
// s1.scope.problemReporter().duplicateMethodInType(s2, m1.sourceMethod());
// }
// if (m2.sourceMethod() != null) {
// s2.scope.problemReporter().duplicateMethodInType(s1, m2.sourceMethod());
// }
// }
// private void reportConflictsNone(
// SourceTypeBinding sourceTypeBinding,
// MethodBinding m2,
// MethodBinding m1)
// {
// throw new RuntimeException("not possible");
// }
// ReferenceBinding t1 = getDeclaringClass(m1);
// //.declaringClass;
// ReferenceBinding t2 = getDeclaringClass(m2);
// //.declaringClass;
//
// if (t1 == t2) {
// AbstractMethodDeclaration methodDecl = m2.sourceMethod(); // cannot be retrieved after binding is lost
// System.err.println("duplicate: " + t1 + ", " + t2);
// sourceTypeBinding.scope.problemReporter().duplicateMethodInType(sourceTypeBinding, methodDecl);
// methodDecl.binding = null;
// //methods[m] = null; //XXX duplicate problem reports
// return;
// }
//
// if (!(t1 instanceof SourceTypeBinding) || !(t2 instanceof SourceTypeBinding)) {
// throw new RuntimeException("unimplemented");
// }
//
// SourceTypeBinding s1 = (SourceTypeBinding)t1;
// SourceTypeBinding s2 = (SourceTypeBinding)t2;
//
//
// if (m1.canBeSeenBy(s1, null, s2.scope) || m2.canBeSeenBy(s2, null, s1.scope)) {
// s1.scope.problemReporter().duplicateMethodInType(s2, m1.sourceMethod());
// s2.scope.problemReporter().duplicateMethodInType(s1, m2.sourceMethod());
// }
// }
// private ReferenceBinding getTargetType(MethodBinding m2) {
// if (m2 instanceof InterTypeMethodBinding) {
// return ((InterTypeMethodBinding)m2).getTargetType();
// }
//
// return m2.declaringClass;
// }
//XXX conflicts
public MethodBinding[] getMethods(
SourceTypeBinding sourceTypeBinding,
char[] selector) {
// System.err.println("getMethods: " + new String(sourceTypeBinding.signature()) +
// ", " + new String(selector));
MethodBinding[] orig = sourceTypeBinding.getMethodsBase(selector);
if (interTypeMethods.isEmpty()) return orig;
List ret = new ArrayList(Arrays.asList(orig));
// System.err.println("declared method: " + ret + " inters = " + interTypeMethods);
for (int i=0, len=interTypeMethods.size(); i < len; i++) {
MethodBinding method = (MethodBinding)interTypeMethods.get(i);
if (CharOperation.equals(selector, method.selector)) {
ret.add(method);
}
}
if (ret.isEmpty()) return SourceTypeBinding.NoMethods;
// System.err.println("method: " + ret);
// check for conflicts
// int len = ret.size();
// if (len > 1) {
// for (int i=0; i <len; i++) {
// MethodBinding m1 = (MethodBinding)ret.get(i);
// for (int j=i+1; j < len; j++) {
// MethodBinding m2 = (MethodBinding)ret.get(j);
// //reportConflicts(sourceTypeBinding, m1, m2);
// }
// }
// }
//System.err.println("got methods: " + ret + " on " + sourceTypeBinding);
return (MethodBinding[])ret.toArray(new MethodBinding[ret.size()]);
}
public MethodBinding getExactMethod(
SourceTypeBinding sourceTypeBinding,
char[] selector,
TypeBinding[] argumentTypes)
{
MethodBinding ret = sourceTypeBinding.getExactMethodBase(selector, argumentTypes);
// An intertype declaration may override an inherited member (Bug#50776)
for (int i=0, len=interTypeMethods.size(); i < len; i++) {
MethodBinding im =
(MethodBinding)interTypeMethods.get(i);
if (matches(im, selector, argumentTypes)) {
return im;
}
}
return ret;
}
// if (isVisible(im, sourceTypeBinding)) {
// if (ret == null) {
// ret = im;
// } else {
// ret = resolveOverride(ret, im);
// }
// }
// }
// }
// return ret;
// }
// private MethodBinding resolveOverride(MethodBinding m1, MethodBinding m2) {
// ReferenceBinding t1 = getTargetType(m1);
// ReferenceBinding t2 = getTargetType(m2);
// if (t1 == t2) {
// //XXX also need a test for completely matching sigs
// if (m1.isAbstract()) return m2;
// else if (m2.isAbstract()) return m1;
//
//
// if (m1 instanceof InterTypeMethodBinding) {
// //XXX need to handle dominates here
// EclipseWorld world = EclipseWorld.fromScopeLookupEnvironment(sourceTypeBinding.scope);
// int cmp = compareAspectPrecedence(world.fromEclipse(m1.declaringClass),
// world.fromEclipse(m2.declaringClass));
// if (cmp < 0) return m2;
// else if (cmp > 0) return m1;
// }
//
// duplicateMethodBinding(m1, m2);
// return null;
// }
// if (t1.isSuperclassOf(t2)) {
// return m2;
// }
// if (t2.isSuperclassOf(t1)) {
// return m1;
// }
//
// duplicateMethodBinding(m1, m2);
// return null;
// }
// private int compareAspectPrecedence(ResolvedTypeX a1, ResolvedTypeX a2) {
// World world = a1.getWorld();
// int ret = world.compareByDominates(a1, a2);
// if (ret == 0) {
// if (a1.isAssignableFrom(a2)) return -1;
// if (a2.isAssignableFrom(a1)) return +1;
// }
// return ret;
// }
//
private boolean matches(MethodBinding m1, MethodBinding m2) {
return matches(m1, m2.selector, m2.parameters);
// &&
// (isVisible(m1, m2.declaringClass) || isVisible(m2, m1.declaringClass));
}
private boolean matches(MethodBinding method, char[] selector, TypeBinding[] argumentTypes) {
if (!CharOperation.equals(selector, method.selector)) return false;
int argCount = argumentTypes.length;
if (method.parameters.length != argCount) return false;
TypeBinding[] toMatch = method.parameters;
for (int p = 0; p < argCount; p++) {
if (toMatch[p] != argumentTypes[p]) return false;
}
return true;
}
public void addInterTypeField(FieldBinding binding) {
//System.err.println("adding: " + binding + " to " + this);
interTypeFields.add(binding);
}
public void addInterTypeMethod(MethodBinding binding) {
// check for conflicts with existing methods, should really check type as well...
//System.err.println("adding: " + binding + " to " + sourceTypeBinding);
if (isVisible(binding, sourceTypeBinding)) {
MethodBinding[] baseMethods = sourceTypeBinding.methods;
for (int i=0, len=baseMethods.length; i < len; i++) {
MethodBinding b = baseMethods[i];
if (matches(binding, b)) {
// this always means we should remove the existing method
if (b.sourceMethod() != null) {
b.sourceMethod().binding = null;
}
sourceTypeBinding.removeMethod(i);
//System.err.println(" left: " + Arrays.asList(sourceTypeBinding.methods));
break;
}
}
}
interTypeMethods.add(binding);
}
}
|
55,341
|
Bug 55341 error Type mismatch: cannot convert from java.lang.String to java.lang.String
|
When compiling a binary concrete aspect library (for later LTW) consisting of more than one aspect that performs an ITD on a target class not exposed to the weaver I get the following error: error Type mismatch: cannot convert from java.lang.String to java.lang.String The error does not oocur if a complete build & weave is performed. Testcase attached.
|
resolved fixed
|
0521e79
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-04-02T12:45:13Z
| 2004-03-19T09:53:20Z
|
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/BcweaverJarMaker.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.batch;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.ArrayList;
import org.aspectj.ajdt.ajc.AjdtAjcTests;
public class BcweaverJarMaker {
public BcweaverJarMaker() {
super();
}
public static void main(String[] args) throws IOException {
makeJar0();
makeJar1();
makeJar1a();
makeJar2();
makeJarObviousNothing();
makeJarHardNothing();
makeTestJars();
makeURLWeavingClassLoaderJars();
}
public static void makeJar0() throws IOException {
List args = new ArrayList();
args.add("-outjar");
args.add("../weaver/testdata/tracing.jar");
args.add("-classpath");
args.add("../runtime/bin" + File.pathSeparator +
System.getProperty("aspectjrt.path"));
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/Trace.java");
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/MyTrace.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
}
public static void makeJar1() throws IOException {
List args = new ArrayList();
args.add("-outjar");
args.add("../weaver/testdata/megatrace.jar");
args.add("-classpath");
args.add("../runtime/bin" + File.pathSeparator +
System.getProperty("aspectjrt.path"));
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/MegaTrace.java");
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/ExecTrace.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
}
public static void makeJarObviousNothing() throws IOException {
List args = new ArrayList();
args.add("-outjar");
args.add("../weaver/testdata/megatrace0easy.jar");
args.add("-classpath");
args.add("../runtime/bin" + File.pathSeparator +
System.getProperty("aspectjrt.path"));
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/MegaTrace.java");
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/ObviousTraceNothing.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
}
public static void makeJarHardNothing() throws IOException {
List args = new ArrayList();
args.add("-outjar");
args.add("../weaver/testdata/megatrace0hard.jar");
args.add("-classpath");
args.add("../runtime/bin" + File.pathSeparator +
System.getProperty("aspectjrt.path"));
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/MegaTrace.java");
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/HardTraceNothing.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
}
public static void makeJar1a() throws IOException {
List args = new ArrayList();
args.add("-outjar");
args.add("../weaver/testdata/megatraceNoweave.jar");
args.add("-noweave");
args.add("-classpath");
args.add("../runtime/bin" + File.pathSeparator +
System.getProperty("aspectjrt.path"));
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/MegaTrace.java");
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/trace/ExecTrace.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
}
public static void makeJar2() throws IOException {
List args = new ArrayList();
args.add("-outjar");
args.add("../weaver/testdata/dummyAspect.jar");
args.add("-classpath");
args.add("../runtime/bin" + File.pathSeparator +
System.getProperty("aspectjrt.path"));
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/DummyAspect.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
}
public static void makeTestJars() throws IOException {
List args = new ArrayList();
args.add("-classpath");
args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" +
File.pathSeparator + System.getProperty("aspectjrt.path"));
args.add("-outjar");
args.add("../tests/new/options11/aspectlib1.jar");
args.add("../tests/new/options11/library1/*.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
args = new ArrayList();
args.add("-classpath");
args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" +
File.pathSeparator + System.getProperty("aspectjrt.path"));
args.add("-outjar");
args.add("../tests/new/options11/aspectlib2.jar");
args.add("../tests/new/options11/library2/*.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
args = new ArrayList();
args.add("-classpath");
args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" +
File.pathSeparator + System.getProperty("aspectjrt.path"));
args.add("-outjar");
args.add("../tests/new/options11/injar.jar");
args.add("../tests/new/options11/injar/*.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
args = new ArrayList();
args.add("-classpath");
args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" +
File.pathSeparator + System.getProperty("aspectjrt.path"));
args.add("-outjar");
args.add("../tests/bugs/serialVersionUID/injar.jar");
args.add("../tests/bugs/serialVersionUID/Test.java");
args.add("../tests/bugs/serialVersionUID/Util.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
}
public static void makeURLWeavingClassLoaderJars() throws IOException {
List args = new ArrayList();
/*
* Vanilla classes
*/
args.add("-classpath");
args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar" +
File.pathSeparator + System.getProperty("aspectjrt.path"));
args.add("-outjar");
args.add("../weaver/testdata/ltw-classes.jar");
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWHelloWorld.java");
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/ltw/LTWPackageTest.java");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
/*
* Woven classes
*/
args = new ArrayList();
args.add("-classpath");
args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" +
File.pathSeparator + System.getProperty("aspectjrt.path"));
args.add("-outjar");
args.add("../weaver/testdata/ltw-woven.jar");
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWHelloWorld.java");
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWAspect.aj");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
/*
* Advice
*/
args = new ArrayList();
args.add("-classpath");
args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" +
File.pathSeparator + System.getProperty("aspectjrt.path"));
args.add("-outjar");
args.add("../weaver/testdata/ltw-aspects.jar");
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWAspect.aj");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
/*
* Around closure advice
*/
args = new ArrayList();
args.add("-classpath");
args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" +
File.pathSeparator + System.getProperty("aspectjrt.path"));
args.add("-outjar");
args.add("../weaver/testdata/ltw-acaspects.jar");
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWAroundClosure.aj");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
/*
* ITD
*/
args = new ArrayList();
args.add("-Xlint:ignore");
args.add("-classpath");
args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" +
File.pathSeparator + System.getProperty("aspectjrt.path"));
args.add("-outjar");
args.add("../weaver/testdata/ltw-itdaspects.jar");
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWInterfaceITD.aj");
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWFieldITD.aj");
/* Uncomment when bug #55341 fixed */
// args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWMethodITD.aj");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
/*
* perXXX()
*/
args = new ArrayList();
args.add("-classpath");
args.add("../lib/test/aspectjrt.jar;../lib/test/testing-client.jar;../weaver/testdata/ltw-classes.jar" +
File.pathSeparator + System.getProperty("aspectjrt.path"));
args.add("-outjar");
args.add("../weaver/testdata/ltw-peraspects.jar");
args.add(AjdtAjcTests.TESTDATA_PATH + "/src1/LTWPerthis.aj");
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
}
}
|
55,341
|
Bug 55341 error Type mismatch: cannot convert from java.lang.String to java.lang.String
|
When compiling a binary concrete aspect library (for later LTW) consisting of more than one aspect that performs an ITD on a target class not exposed to the weaver I get the following error: error Type mismatch: cannot convert from java.lang.String to java.lang.String The error does not oocur if a complete build & weave is performed. Testcase attached.
|
resolved fixed
|
0521e79
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2004-04-02T12:45:13Z
| 2004-03-19T09:53:20Z
|
tests/bugs/StringToString/HW.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.