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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
101,411 |
Bug 101411 SerialVersionUID handling
|
from emails - needs a decision --------------- Hi Andy is there a way for the weaver to add to weaved classes the serial ver uid field based on the pre-weaved bytecode computation. Right now it issues lint warning when a Serializable class without serial ver uid is encountered and due to evil #75442 this is very annoying for LTW. A first step would be to at least deal with that when we had the perObbjectTypeMunger (then should not change any kind previous stuff). Alex ------------ Andy, Generating the suid sounds like a nice idea but the code the JVM used is private inside ObjectStreamClass. Also we need to take care with ITD fields to ensure correct behaviour when sending and receiving from non-woven classes. Basically the programmer needs to be engaged, it only affects serializable classes and in 1.5 there is a warning if you don't declare the field so there is a strong hint to the programmer to solve the problem. For LTW we should make an enhancement to allow the user to configure Lint and other things. For example they may or may not be interested in advice not matching. Matthew Webster ---------------------- Alex, We should make a distinction between benign changes to suid and those that affect members. Generating suid when we add a static initializer (to support thisJoinPoint or the staticinitialization join point), accessor methods for privileged aspects or transient per-fields is OK. Doing for ITDs is more problematic. Matthew Webster
|
resolved fixed
|
6e6658a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-09T17:24:19Z | 2005-06-23T07:00:00Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/BuildArgParser.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.ajc;
import java.io.*;
import java.util.*;
import org.aspectj.ajdt.internal.core.builder.*;
import org.aspectj.bridge.*;
import org.aspectj.util.*;
import org.aspectj.weaver.Constants;
import org.aspectj.weaver.Dump;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.org.eclipse.jdt.core.compiler.InvalidInputException;
import org.aspectj.org.eclipse.jdt.internal.compiler.batch.Main;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
public class BuildArgParser extends Main {
private static final String BUNDLE_NAME = "org.aspectj.ajdt.ajc.messages";
private static boolean LOADED_BUNDLE = false;
static {
bundle = ResourceBundle.getBundle(BUNDLE_NAME);
if (!LOADED_BUNDLE) {
LOADED_BUNDLE = true;
}
}
/** to initialize super's PrintWriter but refer to underlying StringWriter */
private static class StringPrintWriter extends PrintWriter {
public final StringWriter stringWriter;
StringPrintWriter(StringWriter sw) {
super(sw);
this.stringWriter = sw;
}
}
/** @return multi-line String usage for the compiler */
public static String getUsage() {
return Main.bind("misc.usage",Main.bind("compiler.name"));
}
public static String getXOptionUsage() {
return Main.bind("xoption.usage",Main.bind("compiler.name"));
}
/**
* StringWriter sink for some errors.
* This only captures errors not handled by any IMessageHandler parameter
* and only when no PrintWriter is set in the constructor.
* XXX This relies on (Sun's) implementation of StringWriter,
* which returns the actual (not copy) internal StringBuffer.
*/
private final StringBuffer errorSink;
private IMessageHandler handler;
/**
* Overrides super's bundle.
*/
public BuildArgParser(PrintWriter writer, IMessageHandler handler) {
super(writer, writer, false);
if (writer instanceof StringPrintWriter) {
errorSink = ((StringPrintWriter) writer).stringWriter.getBuffer();
} else {
errorSink = null;
}
this.handler = handler;
}
/** Set up to capture messages using getOtherMessages(boolean) */
public BuildArgParser(IMessageHandler handler) {
this(new StringPrintWriter(new StringWriter()),handler);
}
/**
* Generate build configuration for the input args,
* passing to handler any error messages.
* @param args the String[] arguments for the build configuration
* @return AjBuildConfig per args,
* which will be invalid unless there are no handler errors.
*/
public AjBuildConfig genBuildConfig(String[] args) {
AjBuildConfig config = new AjBuildConfig();
populateBuildConfig(config, args, true, null);
return config;
}
/**
* Generate build configuration for the input args,
* passing to handler any error messages.
* @param args the String[] arguments for the build configuration
* @param setClasspath determines if the classpath should be parsed and set on the build configuration
* @param configFile can be null
* @return AjBuildConfig per args,
* which will be invalid unless there are no handler errors.
*/
public AjBuildConfig populateBuildConfig(AjBuildConfig buildConfig, String[] args, boolean setClasspath, File configFile) {
Dump.saveCommandLine(args);
buildConfig.setConfigFile(configFile);
try {
// sets filenames to be non-null in order to make sure that file paramters are ignored
super.filenames = new String[] { "" };
AjcConfigParser parser = new AjcConfigParser(buildConfig, handler);
parser.parseCommandLine(args);
boolean swi = buildConfig.getShowWeavingInformation();
// Now jump through firey hoops to turn them on/off
if (handler instanceof CountingMessageHandler) {
IMessageHandler delegate = ((CountingMessageHandler)handler).delegate;
// Without dontIgnore() on the IMessageHandler interface, we have to do this *blurgh*
if (delegate instanceof MessageHandler) {
if (swi)
((MessageHandler)delegate).dontIgnore(IMessage.WEAVEINFO);
else
((MessageHandler)delegate).ignore(IMessage.WEAVEINFO);
}
}
boolean incrementalMode = buildConfig.isIncrementalMode()
|| buildConfig.isIncrementalFileMode();
List fileList = new ArrayList();
List files = parser.getFiles();
if (!LangUtil.isEmpty(files)) {
if (incrementalMode) {
MessageUtil.error(handler, "incremental mode only handles source files using -sourceroots");
} else {
fileList.addAll(files);
}
}
List javaArgList = new ArrayList();
// disable all special eclipse warnings by default - why???
//??? might want to instead override getDefaultOptions()
javaArgList.add("-warn:none");
// these next four lines are some nonsense to fool the eclipse batch compiler
// without these it will go searching for reasonable values from properties
//TODO fix org.eclipse.jdt.internal.compiler.batch.Main so this hack isn't needed
javaArgList.add("-classpath");
javaArgList.add(System.getProperty("user.dir"));
javaArgList.add("-bootclasspath");
javaArgList.add(System.getProperty("user.dir"));
javaArgList.addAll(parser.getUnparsedArgs());
super.configure((String[])javaArgList.toArray(new String[javaArgList.size()]));
if (!proceed) {
buildConfig.doNotProceed();
return buildConfig;
}
if (buildConfig.getSourceRoots() != null) {
for (Iterator i = buildConfig.getSourceRoots().iterator(); i.hasNext(); ) {
fileList.addAll(collectSourceRootFiles((File)i.next()));
}
}
buildConfig.setFiles(fileList);
if (destinationPath != null) { // XXX ?? unparsed but set?
buildConfig.setOutputDir(new File(destinationPath));
}
if (setClasspath) {
buildConfig.setClasspath(getClasspath(parser));
buildConfig.setBootclasspath(getBootclasspath(parser));
}
if (incrementalMode
&& (0 == buildConfig.getSourceRoots().size())) {
MessageUtil.error(handler, "specify a source root when in incremental mode");
}
/*
* Ensure we don't overwrite injars, inpath or aspectpath with outjar
* bug-71339
*/
File outjar = buildConfig.getOutputJar();
if (outjar != null) {
/* Search injars */
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File injar = (File)i.next();
if (injar.equals(outjar)) {
String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH);
MessageUtil.error(handler,message);
}
}
/* Search inpath */
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (!inPathElement.isDirectory() && inPathElement.equals(outjar)) {
String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH);
MessageUtil.error(handler,message);
}
}
/* Search aspectpath */
for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext(); ) {
File pathElement = (File)i.next();
if (!pathElement.isDirectory() && pathElement.equals(outjar)) {
String message = WeaverMessages.format(WeaverMessages.OUTJAR_IN_INPUT_PATH);
MessageUtil.error(handler,message);
}
}
}
setDebugOptions();
buildConfig.getOptions().set(options);
} catch (InvalidInputException iie) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
location = new SourceLocation(buildConfig.getConfigFile(), 0);
}
IMessage m = new Message(iie.getMessage(), IMessage.ERROR, null, location);
handler.handleMessage(m);
}
return buildConfig;
}
// from super...
public void printVersion() {
System.err.println("AspectJ Compiler " + Version.text + " built on " + Version.time_text); //$NON-NLS-1$
System.err.flush();
}
public void printUsage() {
System.out.println(bind("misc.usage")); //$NON-NLS-1$
System.out.flush();
}
/**
* Get messages not dumped to handler or any PrintWriter.
* @param flush if true, empty errors
* @return null if none, String otherwise
* @see BuildArgParser()
*/
public String getOtherMessages(boolean flush) {
if (null == errorSink) {
return null;
}
String result = errorSink.toString().trim();
if (0 == result.length()) {
result = null;
}
if (flush) {
errorSink.setLength(0);
}
return result;
}
private void setDebugOptions() {
options.put(
CompilerOptions.OPTION_LocalVariableAttribute,
CompilerOptions.GENERATE);
options.put(
CompilerOptions.OPTION_LineNumberAttribute,
CompilerOptions.GENERATE);
options.put(
CompilerOptions.OPTION_SourceFileAttribute,
CompilerOptions.GENERATE);
}
private Collection collectSourceRootFiles(File dir) {
return Arrays.asList(FileUtil.listFiles(dir, FileUtil.aspectjSourceFileFilter));
}
public List getBootclasspath(AjcConfigParser parser) {
List ret = new ArrayList();
if (parser.bootclasspath == null) {
addClasspath(System.getProperty("sun.boot.class.path", ""), ret);
} else {
addClasspath(parser.bootclasspath, ret);
}
return ret;
}
/**
* If the classpath is not set, we use the environment's java.class.path, but remove
* the aspectjtools.jar entry from that list in order to prevent wierd bootstrap issues
* (refer to bug#39959).
*/
public List getClasspath(AjcConfigParser parser) {
List ret = new ArrayList();
// if (parser.bootclasspath == null) {
// addClasspath(System.getProperty("sun.boot.class.path", ""), ret);
// } else {
// addClasspath(parser.bootclasspath, ret);
// }
String extdirs = parser.extdirs;
if (extdirs == null) {
extdirs = System.getProperty("java.ext.dirs", "");
}
addExtDirs(extdirs, ret);
if (parser.classpath == null) {
addClasspath(System.getProperty("java.class.path", ""), ret);
List fixedList = new ArrayList();
for (Iterator it = ret.iterator(); it.hasNext(); ) {
String entry = (String)it.next();
if (!entry.endsWith("aspectjtools.jar")) {
fixedList.add(entry);
}
}
ret = fixedList;
} else {
addClasspath(parser.classpath, ret);
}
//??? eclipse seems to put outdir on the classpath
//??? we're brave and believe we don't need it
return ret;
}
private void addExtDirs(String extdirs, List classpathCollector) {
StringTokenizer tokenizer = new StringTokenizer(extdirs, File.pathSeparator);
while (tokenizer.hasMoreTokens()) {
// classpathCollector.add(tokenizer.nextToken());
File dirFile = new File((String)tokenizer.nextToken());
if (dirFile.canRead() && dirFile.isDirectory()) {
File[] files = dirFile.listFiles(FileUtil.ZIP_FILTER);
for (int i = 0; i < files.length; i++) {
classpathCollector.add(files[i].getAbsolutePath());
}
} else {
// XXX alert on invalid -extdirs entries
}
}
}
private void addClasspath(String classpath, List classpathCollector) {
StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator);
while (tokenizer.hasMoreTokens()) {
classpathCollector.add(tokenizer.nextToken());
}
}
private class AjcConfigParser extends ConfigParser {
private String bootclasspath = null;
private String classpath = null;
private String extdirs = null;
private List unparsedArgs = new ArrayList();
private AjBuildConfig buildConfig;
private IMessageHandler handler;
public AjcConfigParser(AjBuildConfig buildConfig, IMessageHandler handler) {
this.buildConfig = buildConfig;
this.handler = handler;
}
public List getUnparsedArgs() {
return unparsedArgs;
}
/**
* Extract AspectJ-specific options (except for argfiles).
* Caller should warn when sourceroots is empty but in
* incremental mode.
* Signals warnings or errors through handler set in constructor.
*/
public void parseOption(String arg, LinkedList args) { // XXX use ListIterator.remove()
int nextArgIndex = args.indexOf(arg)+1; // XXX assumes unique
// trim arg?
buildConfig.setXlazyTjp(true); // now default - MINOR could be pushed down and made default at a lower level
if (LangUtil.isEmpty(arg)) {
showWarning("empty arg found");
} else if (arg.equals("-inpath")) {;
if (args.size() > nextArgIndex) {
// buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_Inpath, CompilerOptions.PRESERVE);
List inPath = buildConfig.getInpath();
StringTokenizer st = new StringTokenizer(
((ConfigParser.Arg)args.get(nextArgIndex)).getValue(),
File.pathSeparator);
while (st.hasMoreTokens()) {
String filename = st.nextToken();
File file = makeFile(filename);
if (file.exists() && FileUtil.hasZipSuffix(filename)) {
inPath.add(file);
} else {
if (file.isDirectory()) {
inPath.add(file);
} else
showError("bad inpath component: " + filename);
}
}
buildConfig.setInPath(inPath);
args.remove(args.get(nextArgIndex));
}
} else if (arg.equals("-injars")) {;
if (args.size() > nextArgIndex) {
// buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_InJARs, CompilerOptions.PRESERVE);
StringTokenizer st = new StringTokenizer(
((ConfigParser.Arg)args.get(nextArgIndex)).getValue(),
File.pathSeparator);
while (st.hasMoreTokens()) {
String filename = st.nextToken();
File jarFile = makeFile(filename);
if (jarFile.exists() && FileUtil.hasZipSuffix(filename)) {
buildConfig.getInJars().add(jarFile);
} else {
File dirFile = makeFile(filename);
if (dirFile.isDirectory()) {
buildConfig.getInJars().add(dirFile);
} else
showError("bad injar: " + filename);
}
}
args.remove(args.get(nextArgIndex));
}
} else if (arg.equals("-aspectpath")) {;
if (args.size() > nextArgIndex) {
StringTokenizer st = new StringTokenizer(
((ConfigParser.Arg)args.get(nextArgIndex)).getValue(),
File.pathSeparator);
while (st.hasMoreTokens()) {
String filename = st.nextToken();
File jarFile = makeFile(filename);
if (jarFile.exists() && (FileUtil.hasZipSuffix(filename) || jarFile.isDirectory())) {
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("-outxml")) {
buildConfig.setOutxmlName("META-INF/aop.xml");
} else if (arg.equals("-outxmlfile")) {
if (args.size() > nextArgIndex) {
String name = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
buildConfig.setOutxmlName(name);
args.remove(args.get(nextArgIndex));
} else {
showError("-outxmlfile requires file name argument");
}
} else if (arg.equals("-log")){
// remove it as it's already been handled in org.aspectj.tools.ajc.Main
args.remove(args.get(nextArgIndex));
} else if (arg.equals("-messageHolder")) {
// remove it as it's already been handled in org.aspectj.tools.ajc.Main
args.remove(args.get(nextArgIndex));
}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("-crossrefs")) {
buildConfig.setGenerateCrossRefsMode(true);
buildConfig.setGenerateModelMode(true);
} else if (arg.equals("-emacssym")) {
buildConfig.setEmacsSymMode(true);
buildConfig.setGenerateModelMode(true);
} else if (arg.equals("-XjavadocsInModel")) {
buildConfig.setGenerateModelMode(true);
buildConfig.setGenerateJavadocsInModelMode(true);
} else if (arg.equals("-Xdev:NoAtAspectJProcessing")) {
buildConfig.setNoAtAspectJAnnotationProcessing(true);
} else if (arg.equals("-Xdev:Pinpoint")) {
buildConfig.setXdevPinpointMode(true);
} else if (arg.equals("-Xjoinpoints:arrayconstruction")) {
buildConfig.setXJoinpoints("arrayconstruction");
} else if (arg.equals("-noWeave") || arg.equals( "-XnoWeave")) {
showWarning("the noweave option is no longer required and is being ignored");
} else if (arg.equals( "-XterminateAfterCompilation")) {
buildConfig.setTerminateAfterCompilation(true);
} else if (arg.equals("-XserializableAspects")) {
buildConfig.setXserializableAspects(true);
} else if (arg.equals("-XlazyTjp")) {
// do nothing as this is now on by default
showWarning("-XlazyTjp should no longer be used, build tjps lazily is now the default");
} else if (arg.startsWith("-Xreweavable")) {
showWarning("-Xreweavable is on by default");
if (arg.endsWith(":compress")) {
showWarning("-Xreweavable:compress is no longer available - reweavable is now default");
}
} else if (arg.startsWith("-Xset:")) {
buildConfig.setXconfigurationInfo(arg.substring(6));
} else if (arg.startsWith("-XnotReweavable")) {
buildConfig.setXnotReweavable(true);
} else if (arg.equals("-XnoInline")) {
buildConfig.setXnoInline(true);
} else if (arg.equals("-XhasMember")) {
buildConfig.setXHasMemberSupport(true);
} else if (arg.startsWith("-showWeaveInfo")) {
buildConfig.setShowWeavingInformation(true);
} else if (arg.equals("-Xlintfile")) {
if (args.size() > nextArgIndex) {
File lintSpecFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue());
// XXX relax restriction on props file suffix?
if (lintSpecFile.canRead() && lintSpecFile.getName().endsWith(".properties")) {
buildConfig.setLintSpecFile(lintSpecFile);
} else {
showError("bad -Xlintfile file: " + lintSpecFile);
buildConfig.setLintSpecFile(null);
}
args.remove(args.get(nextArgIndex));
} else {
showError("-Xlintfile requires .properties file argument");
}
} else if (arg.equals("-Xlint")) {
// buildConfig.getAjOptions().put(
// AjCompilerOptions.OPTION_Xlint,
// CompilerOptions.GENERATE);
buildConfig.setLintMode(AjBuildConfig.AJLINT_DEFAULT);
} else if (arg.startsWith("-Xlint:")) {
if (7 < arg.length()) {
buildConfig.setLintMode(arg.substring(7));
} else {
showError("invalid lint option " + arg);
}
} else if (arg.equals("-bootclasspath")) {
if (args.size() > nextArgIndex) {
String bcpArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
StringBuffer bcp = new StringBuffer();
StringTokenizer strTok = new StringTokenizer(bcpArg,File.pathSeparator);
while (strTok.hasMoreTokens()) {
bcp.append(makeFile(strTok.nextToken()));
if (strTok.hasMoreTokens()) {
bcp.append(File.pathSeparator);
}
}
bootclasspath = bcp.toString();
args.remove(args.get(nextArgIndex));
} else {
showError("-bootclasspath requires classpath entries");
}
} else if (arg.equals("-classpath") || arg.equals("-cp")) {
if (args.size() > nextArgIndex) {
String cpArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
StringBuffer cp = new StringBuffer();
StringTokenizer strTok = new StringTokenizer(cpArg,File.pathSeparator);
while (strTok.hasMoreTokens()) {
cp.append(makeFile(strTok.nextToken()));
if (strTok.hasMoreTokens()) {
cp.append(File.pathSeparator);
}
}
classpath = cp.toString();
args.remove(args.get(nextArgIndex));
} else {
showError("-classpath requires classpath entries");
}
} else if (arg.equals("-extdirs")) {
if (args.size() > nextArgIndex) {
String extdirsArg = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
StringBuffer ed = new StringBuffer();
StringTokenizer strTok = new StringTokenizer(extdirsArg,File.pathSeparator);
while (strTok.hasMoreTokens()) {
ed.append(makeFile(strTok.nextToken()));
if (strTok.hasMoreTokens()) {
ed.append(File.pathSeparator);
}
}
extdirs = ed.toString();
args.remove(args.get(nextArgIndex));
} else {
showError("-extdirs requires list of external directories");
}
// error on directory unless -d, -{boot}classpath, or -extdirs
} else if (arg.equals("-d")) {
dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-classpath")) {
// dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-bootclasspath")) {
// dirLookahead(arg, args, nextArgIndex);
// } else if (arg.equals("-extdirs")) {
// dirLookahead(arg, args, nextArgIndex);
} else if (arg.equals("-proceedOnError")) {
buildConfig.setProceedOnError(true);
} else if (new File(arg).isDirectory()) {
showError("dir arg not permitted: " + arg);
} else if (arg.startsWith("-Xajruntimetarget")) {
if (arg.endsWith(":1.2")) {
buildConfig.setTargetAspectjRuntimeLevel(Constants.RUNTIME_LEVEL_12);
} else if (arg.endsWith(":1.5")) {
buildConfig.setTargetAspectjRuntimeLevel(Constants.RUNTIME_LEVEL_15);
} else {
showError("-Xajruntimetarget:<level> only supports a target level of 1.2 or 1.5");
}
} else if (arg.equals("-1.5")) {
buildConfig.setBehaveInJava5Way(true);
unparsedArgs.add("-1.5");
// this would enable the '-source 1.5' to do the same as '-1.5' but doesnt sound quite right as
// as an option right now as it doesnt mean we support 1.5 source code - people will get confused...
} else if (arg.equals("-source")) {
if (args.size() > nextArgIndex) {
String level = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
if (level.equals("1.5")){
buildConfig.setBehaveInJava5Way(true);
}
unparsedArgs.add("-source");
unparsedArgs.add(level);
args.remove(args.get(nextArgIndex));
}
} 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,
// -g:[...], -preserveAllLocals,
// -referenceInfo, -encoding, -verbose, -log, -time
// -noExit, -repeat
// (Actually, -noExit grabbed by Main)
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);
}
}
}
|
101,411 |
Bug 101411 SerialVersionUID handling
|
from emails - needs a decision --------------- Hi Andy is there a way for the weaver to add to weaved classes the serial ver uid field based on the pre-weaved bytecode computation. Right now it issues lint warning when a Serializable class without serial ver uid is encountered and due to evil #75442 this is very annoying for LTW. A first step would be to at least deal with that when we had the perObbjectTypeMunger (then should not change any kind previous stuff). Alex ------------ Andy, Generating the suid sounds like a nice idea but the code the JVM used is private inside ObjectStreamClass. Also we need to take care with ITD fields to ensure correct behaviour when sending and receiving from non-woven classes. Basically the programmer needs to be engaged, it only affects serializable classes and in 1.5 there is a warning if you don't declare the field so there is a strong hint to the programmer to solve the problem. For LTW we should make an enhancement to allow the user to configure Lint and other things. For example they may or may not be interested in advice not matching. Matthew Webster ---------------------- Alex, We should make a distinction between benign changes to suid and those that affect members. Generating suid when we add a static initializer (to support thisJoinPoint or the staticinitialization join point), accessor methods for privileged aspects or transient per-fields is OK. Doing for ITDs is more problematic. Matthew Webster
|
resolved fixed
|
6e6658a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-09T17:24:19Z | 2005-06-23T07:00:00Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildConfig.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Adrian Colyer added constructor to populate javaOptions with
* default settings - 01.20.2003
* Bugzilla #29768, 29769
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.util.FileUtil;
/**
* All configuration information needed to run the AspectJ compiler.
* Compiler options (as opposed to path information) are held in an AjCompilerOptions instance
*/
public class AjBuildConfig {
private boolean shouldProceed = true;
public static final String AJLINT_IGNORE = "ignore";
public static final String AJLINT_WARN = "warn";
public static final String AJLINT_ERROR = "error";
public static final String AJLINT_DEFAULT = "default";
private File outputDir;
private File outputJar;
private String outxmlName;
private List/*File*/ sourceRoots = new ArrayList();
private List/*File*/ files = new ArrayList();
private List /*File*/ binaryFiles = new ArrayList(); // .class files in indirs...
private List/*File*/ inJars = new ArrayList();
private List/*File*/ inPath = new ArrayList();
private Map/*String->File*/ sourcePathResources = new HashMap();
private List/*File*/ aspectpath = new ArrayList();
private List/*String*/ classpath = new ArrayList();
private List/*String*/ bootclasspath = new ArrayList();
private File configFile;
private String lintMode = AJLINT_DEFAULT;
private File lintSpecFile = null;
private AjCompilerOptions options;
/** if true, then global values override local when joining */
private boolean override = true;
// incremental variants handled by the compiler client, but parsed here
private boolean incrementalMode;
private File incrementalFile;
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("BuildConfig["+(configFile==null?"null":configFile.getAbsoluteFile().toString())+"] #Files="+files.size());
return sb.toString();
}
public static class BinarySourceFile {
public BinarySourceFile(File dir, File src) {
this.fromInPathDirectory = dir;
this.binSrc = src;
}
public File fromInPathDirectory;
public File binSrc;
public boolean equals(Object obj) {
if ((obj instanceof BinarySourceFile) &&
(obj != null)) {
BinarySourceFile other = (BinarySourceFile)obj;
return(binSrc.equals(other.binSrc));
}
return false;
}
public int hashCode() {
return binSrc != null ? binSrc.hashCode() : 0;
}
}
/**
* Intialises the javaOptions Map to hold the default
* JDT Compiler settings. Added by AMC 01.20.2003 in reponse
* to bug #29768 and enh. 29769.
* The settings here are duplicated from those set in
* org.eclipse.jdt.internal.compiler.batch.Main, but I've elected to
* copy them rather than refactor the JDT class since this keeps
* integration with future JDT releases easier (?).
*/
public AjBuildConfig( ) {
options = new AjCompilerOptions();
}
/**
* returned files includes <ul>
* <li>files explicitly listed on command-line</li>
* <li>files listed by reference in argument list files</li>
* <li>files contained in sourceRootDir if that exists</li>
* </ul>
*
* @return all source files that should be compiled.
*/
public List/*File*/ getFiles() {
return files;
}
/**
* returned files includes all .class files found in
* a directory on the inpath, but does not include
* .class files contained within jars.
*/
public List/*BinarySourceFile*/ getBinaryFiles() {
return binaryFiles;
}
public File getOutputDir() {
return outputDir;
}
public void setFiles(List files) {
this.files = files;
}
public void setOutputDir(File outputDir) {
this.outputDir = outputDir;
}
public AjCompilerOptions getOptions() {
return options;
}
/**
* This does not include -bootclasspath but includes -extdirs and -classpath
*/
public List getClasspath() { // XXX setters don't respect javadoc contract...
return classpath;
}
public void setClasspath(List classpath) {
this.classpath = classpath;
}
public List getBootclasspath() {
return bootclasspath;
}
public void setBootclasspath(List bootclasspath) {
this.bootclasspath = bootclasspath;
}
public File getOutputJar() {
return outputJar;
}
public String getOutxmlName() {
return outxmlName;
}
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 setOutxmlName(String name) {
this.outxmlName = name;
}
public void setInJars(List sourceJars) {
this.inJars = sourceJars;
}
public void setInPath(List dirsOrJars) {
inPath = dirsOrJars;
// remember all the class files in directories on the inpath
binaryFiles = new ArrayList();
FileFilter filter = new FileFilter() {
public boolean accept(File pathname) {
return pathname.getPath().endsWith(".class");
}};
for (Iterator iter = dirsOrJars.iterator(); iter.hasNext();) {
File inpathElement = (File) iter.next();
if (inpathElement.isDirectory()) {
File[] files = FileUtil.listFiles(inpathElement, filter);
for (int i = 0; i < files.length; i++) {
binaryFiles.add(new BinarySourceFile(inpathElement,files[i]));
}
}
}
}
public List getSourceRoots() {
return sourceRoots;
}
public void setSourceRoots(List sourceRootDir) {
this.sourceRoots = sourceRootDir;
}
public File getConfigFile() {
return configFile;
}
public void setConfigFile(File configFile) {
this.configFile = configFile;
}
public void setIncrementalMode(boolean incrementalMode) {
this.incrementalMode = incrementalMode;
}
public boolean isIncrementalMode() {
return incrementalMode;
}
public void setIncrementalFile(File incrementalFile) {
this.incrementalFile = incrementalFile;
}
public boolean isIncrementalFileMode() {
return (null != incrementalFile);
}
/**
* @return List (String) classpath of bootclasspath, injars, inpath, aspectpath
* entries, specified classpath (extdirs, and classpath), and output dir or jar
*/
public List getFullClasspath() {
List full = new ArrayList();
full.addAll(getBootclasspath()); // XXX Is it OK that boot classpath overrides inpath/injars/aspectpath?
for (Iterator i = inJars.iterator(); i.hasNext(); ) {
full.add(((File)i.next()).getAbsolutePath());
}
for (Iterator i = inPath.iterator();i.hasNext();) {
full.add(((File)i.next()).getAbsolutePath());
}
for (Iterator i = aspectpath.iterator(); i.hasNext(); ) {
full.add(((File)i.next()).getAbsolutePath());
}
full.addAll(getClasspath());
// if (null != outputDir) {
// full.add(outputDir.getAbsolutePath());
// } else if (null != outputJar) {
// full.add(outputJar.getAbsolutePath());
// }
return full;
}
public File getLintSpecFile() {
return lintSpecFile;
}
public void setLintSpecFile(File lintSpecFile) {
this.lintSpecFile = lintSpecFile;
}
public List getAspectpath() {
return aspectpath;
}
public void setAspectpath(List aspectpath) {
this.aspectpath = aspectpath;
}
/** @return true if any config file, sourceroots, sourcefiles, injars or inpath */
public boolean hasSources() {
return ((null != configFile)
|| (0 < sourceRoots.size())
|| (0 < files.size())
|| (0 < inJars.size())
|| (0 < inPath.size())
);
}
// /** @return null if no errors, String errors otherwise */
// public String configErrors() {
// StringBuffer result = new StringBuffer();
// // ok, permit both. sigh.
//// if ((null != outputDir) && (null != outputJar)) {
//// result.append("specified both outputDir and outputJar");
//// }
// // incremental => only sourceroots
// //
// return (0 == result.length() ? null : result.toString());
// }
/**
* Install global values into local config
* unless values conflict:
* <ul>
* <li>Collections are unioned</li>
* <li>values takes local value unless default and global set</li>
* <li>this only sets one of outputDir and outputJar as needed</li>
* <ul>
* This also configures super if javaOptions change.
* @param global the AjBuildConfig to read globals from
*/
public void installGlobals(AjBuildConfig global) { // XXX relies on default values
// don't join the options - they already have defaults taken care of.
// Map optionsMap = options.getMap();
// join(optionsMap,global.getOptions().getMap());
// options.set(optionsMap);
join(aspectpath, global.aspectpath);
join(classpath, global.classpath);
if (null == configFile) {
configFile = global.configFile; // XXX correct?
}
if (!isEmacsSymMode() && global.isEmacsSymMode()) {
setEmacsSymMode(true);
}
join(files, global.files);
if (!isGenerateModelMode() && global.isGenerateModelMode()) {
setGenerateModelMode(true);
}
if (null == incrementalFile) {
incrementalFile = global.incrementalFile;
}
if (!incrementalMode && global.incrementalMode) {
incrementalMode = true;
}
join(inJars, global.inJars);
join(inPath, global.inPath);
if ((null == lintMode)
|| (AJLINT_DEFAULT.equals(lintMode))) {
setLintMode(global.lintMode);
}
if (null == lintSpecFile) {
lintSpecFile = global.lintSpecFile;
}
if (!isTerminateAfterCompilation() && global.isTerminateAfterCompilation()) {
setTerminateAfterCompilation(true);
}
if ((null == outputDir) && (null == outputJar)) {
if (null != global.outputDir) {
outputDir = global.outputDir;
}
if (null != global.outputJar) {
outputJar = global.outputJar;
}
}
join(sourceRoots, global.sourceRoots);
if (!isXnoInline() && global.isXnoInline()) {
setXnoInline(true);
}
if (!isXserializableAspects() && global.isXserializableAspects()) {
setXserializableAspects(true);
}
if (!isXlazyTjp() && global.isXlazyTjp()) {
setXlazyTjp(true);
}
if (!getProceedOnError() && global.getProceedOnError()) {
setProceedOnError(true);
}
setTargetAspectjRuntimeLevel(global.getTargetAspectjRuntimeLevel());
setXJoinpoints(global.getXJoinpoints());
if (!isXHasMemberEnabled() && global.isXHasMemberEnabled()) {
setXHasMemberSupport(true);
}
if (!isXNotReweavable() && global.isXNotReweavable()) {
setXnotReweavable(true);
}
setOutxmlName(global.getOutxmlName());
setXconfigurationInfo(global.getXconfigurationInfo());
}
void join(Collection local, Collection global) {
for (Iterator iter = global.iterator(); iter.hasNext();) {
Object next = iter.next();
if (!local.contains(next)) {
local.add(next);
}
}
}
void join(Map local, Map global) {
for (Iterator iter = global.keySet().iterator(); iter.hasNext();) {
Object key = iter.next();
if (override || (null == local.get(key))) { //
Object value = global.get(key);
if (null != value) {
local.put(key, value);
}
}
}
}
public void setSourcePathResources(Map map) {
sourcePathResources = map;
}
/**
* used to indicate whether to proceed after parsing config
*/
public boolean shouldProceed() {
return shouldProceed;
}
public void doNotProceed() {
shouldProceed = false;
}
public String getLintMode() {
return lintMode;
}
// options...
public void setLintMode(String lintMode) {
this.lintMode = lintMode;
String lintValue = null;
if (AJLINT_IGNORE.equals(lintMode)) {
lintValue = AjCompilerOptions.IGNORE;
} else if (AJLINT_WARN.equals(lintMode)) {
lintValue = AjCompilerOptions.WARNING;
} else if (AJLINT_ERROR.equals(lintMode)) {
lintValue = AjCompilerOptions.ERROR;
}
if (lintValue != null) {
Map lintOptions = new HashMap();
lintOptions.put(AjCompilerOptions.OPTION_ReportInvalidAbsoluteTypeName,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportInvalidWildcardTypeName,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportUnresolvableMember,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportTypeNotExposedToWeaver,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportShadowNotInStructure,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportUnmatchedSuperTypeInCall,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportCannotImplementLazyTJP,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportNeedSerialVersionUIDField,lintValue);
lintOptions.put(AjCompilerOptions.OPTION_ReportIncompatibleSerialVersion,lintValue);
options.set(lintOptions);
}
}
public boolean isTerminateAfterCompilation() {
return options.terminateAfterCompilation;
}
public void setTerminateAfterCompilation(boolean b) {
options.terminateAfterCompilation = b;
}
public boolean isXserializableAspects() {
return options.xSerializableAspects;
}
public void setXserializableAspects(boolean xserializableAspects) {
options.xSerializableAspects = xserializableAspects;
}
public void setXJoinpoints(String jps) {
options.xOptionalJoinpoints = jps;
}
public String getXJoinpoints() {
return options.xOptionalJoinpoints;
}
public boolean isXnoInline() {
return options.xNoInline;
}
public void setXnoInline(boolean xnoInline) {
options.xNoInline = xnoInline;
}
public boolean isXlazyTjp() {
return options.xLazyThisJoinPoint;
}
public void setXlazyTjp(boolean b) {
options.xLazyThisJoinPoint = b;
}
public void setXnotReweavable(boolean b) {
options.xNotReweavable = b;
}
public void setXconfigurationInfo(String info) {
options.xConfigurationInfo = info;
}
public String getXconfigurationInfo() {
return options.xConfigurationInfo;
}
public void setXHasMemberSupport(boolean enabled) {
options.xHasMember = enabled;
}
public boolean isXHasMemberEnabled() {
return options.xHasMember;
}
public void setXdevPinpointMode(boolean enabled) {
options.xdevPinpoint = enabled;
}
public boolean isXdevPinpoint() {
return options.xdevPinpoint;
}
public boolean isXNotReweavable() {
return options.xNotReweavable;
}
public boolean isGenerateJavadocsInModelMode() {
return options.generateJavaDocsInModel;
}
public void setGenerateJavadocsInModelMode(
boolean generateJavadocsInModelMode) {
options.generateJavaDocsInModel = generateJavadocsInModelMode;
}
public boolean isGenerateCrossRefsMode() {
return options.generateCrossRefs;
}
public void setGenerateCrossRefsMode(boolean on) {
options.generateCrossRefs = on;
}
public boolean isEmacsSymMode() {
return options.generateEmacsSymFiles;
}
public void setEmacsSymMode(boolean emacsSymMode) {
options.generateEmacsSymFiles = emacsSymMode;
}
public boolean isGenerateModelMode() {
return options.generateModel;
}
public void setGenerateModelMode(boolean structureModelMode) {
options.generateModel = structureModelMode;
}
public boolean isNoAtAspectJAnnotationProcessing() {
return options.noAtAspectJProcessing;
}
public void setNoAtAspectJAnnotationProcessing(boolean noProcess) {
options.noAtAspectJProcessing = noProcess;
}
public void setShowWeavingInformation(boolean b) {
options.showWeavingInformation = true;
}
public boolean getShowWeavingInformation() {
return options.showWeavingInformation;
}
public void setProceedOnError(boolean b) {
options.proceedOnError = b;
}
public boolean getProceedOnError() {
return options.proceedOnError;
}
public void setBehaveInJava5Way(boolean b) {
options.behaveInJava5Way = b;
}
public boolean getBehaveInJava5Way() {
return options.behaveInJava5Way;
}
public void setTargetAspectjRuntimeLevel(String level) {
options.targetAspectjRuntimeLevel = level;
}
public String getTargetAspectjRuntimeLevel() {
return options.targetAspectjRuntimeLevel;
}
}
|
101,411 |
Bug 101411 SerialVersionUID handling
|
from emails - needs a decision --------------- Hi Andy is there a way for the weaver to add to weaved classes the serial ver uid field based on the pre-weaved bytecode computation. Right now it issues lint warning when a Serializable class without serial ver uid is encountered and due to evil #75442 this is very annoying for LTW. A first step would be to at least deal with that when we had the perObbjectTypeMunger (then should not change any kind previous stuff). Alex ------------ Andy, Generating the suid sounds like a nice idea but the code the JVM used is private inside ObjectStreamClass. Also we need to take care with ITD fields to ensure correct behaviour when sending and receiving from non-woven classes. Basically the programmer needs to be engaged, it only affects serializable classes and in 1.5 there is a warning if you don't declare the field so there is a strong hint to the programmer to solve the problem. For LTW we should make an enhancement to allow the user to configure Lint and other things. For example they may or may not be interested in advice not matching. Matthew Webster ---------------------- Alex, We should make a distinction between benign changes to suid and those that affect members. Generating suid when we add a static initializer (to support thisJoinPoint or the staticinitialization join point), accessor methods for privileged aspects or transient per-fields is OK. Doing for ITDs is more problematic. Matthew Webster
|
resolved fixed
|
6e6658a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-09T17:24:19Z | 2005-06-23T07:00:00Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import org.aspectj.ajdt.internal.compiler.AjCompilerAdapter;
import org.aspectj.ajdt.internal.compiler.IBinarySourceProvider;
import org.aspectj.ajdt.internal.compiler.ICompilerAdapter;
import org.aspectj.ajdt.internal.compiler.ICompilerAdapterFactory;
import org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor;
import org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider;
import org.aspectj.ajdt.internal.compiler.InterimCompilationResult;
import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment;
import org.aspectj.ajdt.internal.compiler.lookup.AnonymousClassPublisher;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.CountingMessageHandler;
import org.aspectj.bridge.ILifecycleAware;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.IProgressListener;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.bridge.Version;
import org.aspectj.bridge.context.CompilationAndWeavingContext;
import org.aspectj.bridge.context.ContextFormatter;
import org.aspectj.bridge.context.ContextToken;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.core.compiler.IProblem;
import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile;
import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
import org.aspectj.org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
import org.aspectj.org.eclipse.jdt.internal.compiler.ICompilerRequestor;
import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory;
import org.aspectj.org.eclipse.jdt.internal.compiler.batch.ClasspathDirectory;
import org.aspectj.org.eclipse.jdt.internal.compiler.batch.CompilationUnit;
import org.aspectj.org.eclipse.jdt.internal.compiler.batch.FileSystem;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser;
import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
import org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
import org.aspectj.util.FileUtil;
import org.aspectj.weaver.Dump;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.UnwovenClassFile;
import org.eclipse.core.runtime.OperationCanceledException;
//import org.aspectj.org.eclipse.jdt.internal.compiler.util.HashtableOfObject;
public class AjBuildManager implements IOutputClassFileNameProvider,IBinarySourceProvider,ICompilerAdapterFactory {
private static final String CROSSREFS_FILE_NAME = "build.lst";
private static final String CANT_WRITE_RESULT = "unable to write compilation result";
private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF";
static final boolean COPY_INPATH_DIR_RESOURCES = false;
static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false;
private static final FileFilter binarySourceFilter =
new FileFilter() {
public boolean accept(File f) {
return f.getName().endsWith(".class");
}};
/**
* This builder is static so that it can be subclassed and reset. However, note
* that there is only one builder present, so if two extendsion reset it, only
* the latter will get used.
*/
public static AsmHierarchyBuilder asmHierarchyBuilder = new AsmHierarchyBuilder();
static {
CompilationAndWeavingContext.registerFormatter(
CompilationAndWeavingContext.BATCH_BUILD, new AjBuildContexFormatter());
CompilationAndWeavingContext.registerFormatter(
CompilationAndWeavingContext.INCREMENTAL_BUILD, new AjBuildContexFormatter());
}
private IProgressListener progressListener = null;
private boolean environmentSupportsIncrementalCompilation = false;
private int compiledCount;
private int sourceFileCount;
private JarOutputStream zos;
private boolean batchCompile = true;
private INameEnvironment environment;
private Map /* String -> List<UCF>*/ binarySourcesForTheNextCompile = new HashMap();
// FIXME asc should this really be in here?
private IHierarchy structureModel;
public AjBuildConfig buildConfig;
private List aspectNames = new LinkedList();
AjState state = new AjState(this);
public BcelWeaver getWeaver() { return state.getWeaver();}
public BcelWorld getBcelWorld() { return state.getBcelWorld();}
public CountingMessageHandler handler;
public AjBuildManager(IMessageHandler holder) {
super();
this.handler = CountingMessageHandler.makeCountingMessageHandler(holder);
}
public void environmentSupportsIncrementalCompilation(boolean itDoes) {
this.environmentSupportsIncrementalCompilation = itDoes;
}
/** @return true if we should generate a model as a side-effect */
public boolean doGenerateModel() {
return buildConfig.isGenerateModelMode();
}
public boolean batchBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler)
throws IOException, AbortException {
return doBuild(buildConfig, baseHandler, true);
}
public boolean incrementalBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler)
throws IOException, AbortException {
return doBuild(buildConfig, baseHandler, false);
}
/** @throws AbortException if check for runtime fails */
protected boolean doBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler,
boolean batch) throws IOException, AbortException {
boolean ret = true;
batchCompile = batch;
if (baseHandler instanceof ILifecycleAware) {
((ILifecycleAware)baseHandler).buildStarting(!batch);
}
CompilationAndWeavingContext.reset();
int phase = batch ? CompilationAndWeavingContext.BATCH_BUILD : CompilationAndWeavingContext.INCREMENTAL_BUILD;
ContextToken ct = CompilationAndWeavingContext.enteringPhase(phase ,buildConfig);
try {
if (batch) {
this.state = new AjState(this);
}
this.state.setCouldBeSubsequentIncrementalBuild(this.environmentSupportsIncrementalCompilation);
boolean canIncremental = state.prepareForNextBuild(buildConfig);
if (!canIncremental && !batch) { // retry as batch?
CompilationAndWeavingContext.leavingPhase(ct);
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);
CompilationAndWeavingContext.leavingPhase(ct);
return false;
} else {
MessageUtil.warn(handler, check);
}
}
// if (batch) {
setBuildConfig(buildConfig);
//}
if (batch || !AsmManager.attemptIncrementalModelRepairs) {
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
setupModel(buildConfig);
// }
}
if (batch) {
initBcelWorld(handler);
}
if (handler.hasErrors()) {
CompilationAndWeavingContext.leavingPhase(ct);
return false;
}
if (buildConfig.getOutputJar() != null) {
if (!openOutputStream(buildConfig.getOutputJar())) {
CompilationAndWeavingContext.leavingPhase(ct);
return false;
}
}
if (batch) {
// System.err.println("XXXX batch: " + buildConfig.getFiles());
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
getWorld().setModel(AsmManager.getDefault().getHierarchy());
// in incremental build, only get updated model?
}
binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true);
performCompilation(buildConfig.getFiles());
state.clearBinarySourceFiles(); // we don't want these hanging around...
if (handler.hasErrors()) {
CompilationAndWeavingContext.leavingPhase(ct);
return false;
}
if (AsmManager.isReporting())
AsmManager.getDefault().reportModelInfo("After a batch build");
} else {
// done already?
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
// bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel());
// }
// System.err.println("XXXX start inc ");
binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true);
List files = state.getFilesToCompile(true);
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode())
if (AsmManager.attemptIncrementalModelRepairs)
AsmManager.getDefault().processDelta(files,state.getAddedFiles(),state.getDeletedFiles());
boolean hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty());
for (int i = 0; (i < 5) && hereWeGoAgain; i++) {
// System.err.println("XXXX inc: " + files);
performCompilation(files);
if (handler.hasErrors() || (progressListener!=null && progressListener.isCancelledRequested())) {
CompilationAndWeavingContext.leavingPhase(ct);
return false;
}
if (state.requiresFullBatchBuild()) {
return batchBuild(buildConfig, baseHandler);
}
binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(false);
files = state.getFilesToCompile(false);
hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty());
// TODO Andy - Needs some thought here...
// I think here we might want to pass empty addedFiles/deletedFiles as they were
// dealt with on the first call to processDelta - we are going through this loop
// again because in compiling something we found something else we needed to
// rebuild. But what case causes this?
if (hereWeGoAgain) {
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode())
if (AsmManager.attemptIncrementalModelRepairs)
AsmManager.getDefault().processDelta(files,state.getAddedFiles(),state.getDeletedFiles());
}
}
if (!files.isEmpty()) {
CompilationAndWeavingContext.leavingPhase(ct);
return batchBuild(buildConfig, baseHandler);
} else {
if (AsmManager.isReporting())
AsmManager.getDefault().reportModelInfo("After an incremental build");
}
}
// XXX not in Mik's incremental
if (buildConfig.isEmacsSymMode()) {
new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel();
}
// for bug 113554: support ajsym file generation for command line builds
if (buildConfig.isGenerateCrossRefsMode()) {
String configFileProxy = buildConfig.getOutputDir().getAbsolutePath()
+ File.separator
+ CROSSREFS_FILE_NAME;
AsmManager.getDefault().writeStructureModel(configFileProxy);
}
// have to tell state we succeeded or next is not incremental
state.successfulCompile(buildConfig,batch);
copyResourcesToDestination();
if (buildConfig.getOutxmlName() != null) {
writeOutxmlFile();
}
/*boolean weaved = *///weaveAndGenerateClassFiles();
// if not weaved, then no-op build, no model changes
// but always returns true
// XXX weaved not in Mik's incremental
if (buildConfig.isGenerateModelMode()) {
AsmManager.getDefault().fireModelUpdated();
}
CompilationAndWeavingContext.leavingPhase(ct);
} finally {
if (baseHandler instanceof ILifecycleAware) {
((ILifecycleAware)baseHandler).buildFinished(!batch);
}
if (zos != null) {
closeOutputStream(buildConfig.getOutputJar());
}
ret = !handler.hasErrors();
if (getBcelWorld()!=null) getBcelWorld().tidyUp();
// bug 59895, don't release reference to handler as may be needed by a nested call
//handler = null;
}
return ret;
}
private boolean openOutputStream(File outJar) {
try {
OutputStream os = FileUtil.makeOutputStream(buildConfig.getOutputJar());
zos = new JarOutputStream(os,getWeaver().getManifest(true));
} catch (IOException ex) {
IMessage message =
new Message("Unable to open outjar "
+ outJar.getPath()
+ "(" + ex.getMessage()
+ ")",
new SourceLocation(outJar,0),
true);
handler.handleMessage(message);
return false;
}
return true;
}
private void closeOutputStream(File outJar) {
try {
if (zos != null) zos.close();
zos = null;
/* Ensure we don't write an incomplete JAR bug-71339 */
if (handler.hasErrors()) {
outJar.delete();
}
} catch (IOException ex) {
IMessage message =
new Message("Unable to write outjar "
+ outJar.getPath()
+ "(" + ex.getMessage()
+ ")",
new SourceLocation(outJar,0),
true);
handler.handleMessage(message);
}
}
private void copyResourcesToDestination() throws IOException {
// resources that we need to copy are contained in the injars and inpath only
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File inJar = (File)i.next();
copyResourcesFromJarFile(inJar);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (inPathElement.isDirectory()) {
copyResourcesFromDirectory(inPathElement);
} else {
copyResourcesFromJarFile(inPathElement);
}
}
if (buildConfig.getSourcePathResources() != null) {
for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) {
String resource = (String)i.next();
File from = (File)buildConfig.getSourcePathResources().get(resource);
copyResourcesFromFile(from,resource,from);
}
}
writeManifest();
}
private void copyResourcesFromJarFile(File jarFile) throws IOException {
JarInputStream inStream = null;
try {
inStream = new JarInputStream(new FileInputStream(jarFile));
while (true) {
ZipEntry entry = inStream.getNextEntry();
if (entry == null) break;
String filename = entry.getName();
// System.out.println("? copyResourcesFromJarFile() filename='" + filename +"'");
if (!entry.isDirectory() && acceptResource(filename)) {
byte[] bytes = FileUtil.readAsByteArray(inStream);
writeResource(filename,bytes,jarFile);
}
inStream.closeEntry();
}
} finally {
if (inStream != null) inStream.close();
}
}
private void copyResourcesFromDirectory(File dir) throws IOException {
if (!COPY_INPATH_DIR_RESOURCES) return;
// Get a list of all files (i.e. everything that isnt a directory)
File[] files = FileUtil.listFiles(dir,new FileFilter() {
public boolean accept(File f) {
boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")) ;
return accept;
}
});
// For each file, add it either as a real .class file or as a resource
for (int i = 0; i < files.length; i++) {
// ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
// or we are in trouble...
String filename = files[i].getAbsolutePath().substring(
dir.getAbsolutePath().length()+1);
copyResourcesFromFile(files[i],filename,dir);
}
}
private void copyResourcesFromFile(File f,String filename,File src) throws IOException {
if (!acceptResource(filename)) return;
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
byte[] bytes = FileUtil.readAsByteArray(fis);
// String relativePath = files[i].getPath();
writeResource(filename,bytes,src);
} finally {
if (fis != null) fis.close();
}
}
private void writeResource(String filename, byte[] content, File srcLocation) throws IOException {
if (state.hasResource(filename)) {
IMessage msg = new Message("duplicate resource: '" + filename + "'",
IMessage.WARNING,
null,
new SourceLocation(srcLocation,0));
handler.handleMessage(msg);
return;
}
if (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.recordResource(filename);
}
/*
* If we are writing to an output directory copy the manifest but only
* if we already have one
*/
private void writeManifest () throws IOException {
Manifest manifest = getWeaver().getManifest(false);
if (manifest != null && zos == null) {
OutputStream fos =
FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),MANIFEST_NAME));
manifest.write(fos);
fos.close();
}
}
private boolean acceptResource(String resourceName) {
if (
(resourceName.startsWith("CVS/")) ||
(resourceName.indexOf("/CVS/") != -1) ||
(resourceName.endsWith("/CVS")) ||
(resourceName.endsWith(".class")) ||
(resourceName.startsWith(".svn/")) ||
(resourceName.indexOf("/.svn/")!=-1) ||
(resourceName.endsWith("/.svn")) ||
(resourceName.toUpperCase().equals(MANIFEST_NAME))
)
{
return false;
} else {
return true;
}
}
private void writeOutxmlFile () throws IOException {
String filename = buildConfig.getOutxmlName();
// System.err.println("? AjBuildManager.writeOutxmlFile() outxml=" + filename);
// System.err.println("? AjBuildManager.writeOutxmlFile() outputDir=" + buildConfig.getOutputDir());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
ps.println("<aspectj>");
ps.println("<aspects>");
for (Iterator i = aspectNames.iterator(); i.hasNext();) {
String name = (String)i.next();
ps.println("<aspect name=\"" + name + "\"/>");
}
ps.println("</aspects>");
ps.println("</aspectj>");
ps.println();
ps.close();
if (zos != null) {
ZipEntry newEntry = new ZipEntry(filename);
zos.putNextEntry(newEntry);
zos.write(baos.toByteArray());
zos.closeEntry();
} else {
OutputStream fos =
FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),filename));
fos.write(baos.toByteArray());
fos.close();
}
}
// public static void dumprels() {
// IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap();
// int ctr = 1;
// Set entries = irm.getEntries();
// for (Iterator iter = entries.iterator(); iter.hasNext();) {
// String hid = (String) iter.next();
// List rels = irm.get(hid);
// for (Iterator iterator = rels.iterator(); iterator.hasNext();) {
// IRelationship ir = (IRelationship) iterator.next();
// List targets = ir.getTargets();
// for (Iterator iterator2 = targets.iterator();
// iterator2.hasNext();
// ) {
// String thid = (String) iterator2.next();
// System.err.println("Hid:"+(ctr++)+":(targets="+targets.size()+") "+hid+" ("+ir.getName()+") "+thid);
// }
// }
// }
// }
/**
* Responsible for managing the ASM model between builds. Contains the policy for
* maintaining the persistance of elements in the model.
*
* This code is driven before each 'fresh' (batch) build to create
* a new model.
*/
private void setupModel(AjBuildConfig config) {
AsmManager.setCreatingModel(config.isEmacsSymMode() || config.isGenerateModelMode());
if (!AsmManager.isCreatingModel()) return;
AsmManager.getDefault().createNewASM();
// AsmManager.getDefault().getRelationshipMap().clear();
IHierarchy model = AsmManager.getDefault().getHierarchy();
String rootLabel = "<root>";
IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA;
if (buildConfig.getConfigFile() != null) {
rootLabel = buildConfig.getConfigFile().getName();
model.setConfigFile(buildConfig.getConfigFile().getAbsolutePath());
kind = IProgramElement.Kind.FILE_LST;
}
model.setRoot(new ProgramElement(rootLabel, kind, new ArrayList()));
model.setFileMap(new HashMap());
setStructureModel(model);
state.setStructureModel(model);
state.setRelationshipMap(AsmManager.getDefault().getRelationshipMap());
}
//
// private void dumplist(List l) {
// System.err.println("---- "+l.size());
// for (int i =0 ;i<l.size();i++) System.err.println(i+"\t "+l.get(i));
// }
// private void accumulateFileNodes(IProgramElement ipe,List store) {
// if (ipe.getKind()==IProgramElement.Kind.FILE_JAVA ||
// ipe.getKind()==IProgramElement.Kind.FILE_ASPECTJ) {
// if (!ipe.getName().equals("<root>")) {
// store.add(ipe);
// return;
// }
// }
// for (Iterator i = ipe.getChildren().iterator();i.hasNext();) {
// accumulateFileNodes((IProgramElement)i.next(),store);
// }
// }
/** init only on initial batch compile? no file-specific options */
private void initBcelWorld(IMessageHandler handler) throws IOException {
List cp = buildConfig.getBootclasspath();
cp.addAll(buildConfig.getClasspath());
BcelWorld bcelWorld = new BcelWorld(cp, handler, null);
bcelWorld.setBehaveInJava5Way(buildConfig.getBehaveInJava5Way());
bcelWorld.performExtraConfiguration(buildConfig.getXconfigurationInfo());
bcelWorld.setTargetAspectjRuntimeLevel(buildConfig.getTargetAspectjRuntimeLevel());
bcelWorld.setOptionalJoinpoints(buildConfig.getXJoinpoints());
bcelWorld.setXnoInline(buildConfig.isXnoInline());
bcelWorld.setXlazyTjp(buildConfig.isXlazyTjp());
bcelWorld.setXHasMemberSupportEnabled(buildConfig.isXHasMemberEnabled());
bcelWorld.setPinpointMode(buildConfig.isXdevPinpoint());
BcelWeaver bcelWeaver = new BcelWeaver(bcelWorld);
state.setWorld(bcelWorld);
state.setWeaver(bcelWeaver);
state.clearBinarySourceFiles();
for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext();) {
File f = (File) i.next();
if (!f.exists()) {
IMessage message = new Message("invalid aspectpath entry: "+f.getName(),null,true);
handler.handleMessage(message);
} else {
bcelWeaver.addLibraryJarFile(f);
}
}
// String lintMode = buildConfig.getLintMode();
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.recordBinarySource(inJar.getPath(), unwovenClasses);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (!inPathElement.isDirectory()) {
// its a jar file on the inpath
// the weaver method can actually handle dirs, but we don't call it, see next block
List unwovenClasses = bcelWeaver.addJarFile(inPathElement,buildConfig.getOutputDir(),true);
state.recordBinarySource(inPathElement.getPath(),unwovenClasses);
} else {
// add each class file in an in-dir individually, this gives us the best error reporting
// (they are like 'source' files then), and enables a cleaner incremental treatment of
// class file changes in indirs.
File[] binSrcs = FileUtil.listFiles(inPathElement, binarySourceFilter);
for (int j = 0; j < binSrcs.length; j++) {
UnwovenClassFile ucf =
bcelWeaver.addClassFile(binSrcs[j], inPathElement, buildConfig.getOutputDir());
List ucfl = new ArrayList();
ucfl.add(ucf);
state.recordBinarySource(binSrcs[j].getPath(),ucfl);
}
}
}
bcelWeaver.setReweavableMode(buildConfig.isXNotReweavable());
//check for org.aspectj.runtime.JoinPoint
ResolvedType joinPoint = bcelWorld.resolve("org.aspectj.lang.JoinPoint");
if (joinPoint.isMissing()) {
IMessage message =
new Message("classpath error: unable to find org.aspectj.lang.JoinPoint (check that aspectjrt.jar is in your classpath)",
null,
true);
handler.handleMessage(message);
}
}
public World getWorld() {
return getBcelWorld();
}
void addAspectClassFilesToWeaver(List addedClassFiles) throws IOException {
for (Iterator i = addedClassFiles.iterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile) i.next();
getWeaver().addClassFile(classFile);
}
}
// public boolean weaveAndGenerateClassFiles() throws IOException {
// handler.handleMessage(MessageUtil.info("weaving"));
// if (progressListener != null) progressListener.setText("weaving aspects");
// bcelWeaver.setProgressListener(progressListener, 0.5, 0.5/state.addedClassFiles.size());
// //!!! doesn't provide intermediate progress during weaving
// // XXX add all aspects even during incremental builds?
// addAspectClassFilesToWeaver(state.addedClassFiles);
// if (buildConfig.isNoWeave()) {
// if (buildConfig.getOutputJar() != null) {
// bcelWeaver.dumpUnwoven(buildConfig.getOutputJar());
// } else {
// bcelWeaver.dumpUnwoven();
// bcelWeaver.dumpResourcesToOutPath();
// }
// } else {
// if (buildConfig.getOutputJar() != null) {
// bcelWeaver.weave(buildConfig.getOutputJar());
// } else {
// bcelWeaver.weave();
// bcelWeaver.dumpResourcesToOutPath();
// }
// }
// if (progressListener != null) progressListener.setProgress(1.0);
// return true;
// //return messageAdapter.getErrorCount() == 0; //!javaBuilder.notifier.anyErrors();
// }
public FileSystem getLibraryAccess(String[] classpaths, String[] filenames) {
String defaultEncoding = buildConfig.getOptions().defaultEncoding;
if ("".equals(defaultEncoding)) //$NON-NLS-1$
defaultEncoding = null; //$NON-NLS-1$
// Bug 46671: We need an array as long as the number of elements in the classpath - *even though* not every
// element of the classpath is likely to be a directory. If we ensure every element of the array is set to
// only look for BINARY, then we make sure that for any classpath element that is a directory, we won't build
// a classpathDirectory object that will attempt to look for source when it can't find binary.
int[] classpathModes = new int[classpaths.length];
for (int i =0 ;i<classpaths.length;i++) classpathModes[i]=ClasspathDirectory.BINARY;
return new FileSystem(classpaths, filenames, defaultEncoding,classpathModes);
}
public IProblemFactory getProblemFactory() {
return new DefaultProblemFactory(Locale.getDefault());
}
/*
* Build the set of compilation source units
*/
public CompilationUnit[] getCompilationUnits(String[] filenames, String[] encodings) {
int fileCount = filenames.length;
CompilationUnit[] units = new CompilationUnit[fileCount];
// HashtableOfObject knownFileNames = new HashtableOfObject(fileCount);
String defaultEncoding = buildConfig.getOptions().defaultEncoding;
if ("".equals(defaultEncoding)) //$NON-NLS-1$
defaultEncoding = null; //$NON-NLS-1$
for (int i = 0; i < fileCount; i++) {
String encoding = encodings[i];
if (encoding == null)
encoding = defaultEncoding;
units[i] = new CompilationUnit(null, filenames[i], encoding);
}
return units;
}
public String extractDestinationPathFromSourceFile(CompilationResult result) {
ICompilationUnit compilationUnit = result.compilationUnit;
if (compilationUnit != null) {
char[] fileName = compilationUnit.getFileName();
int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName);
if (lastIndex == -1) {
return System.getProperty("user.dir"); //$NON-NLS-1$
}
return new String(CharOperation.subarray(fileName, 0, lastIndex));
}
return System.getProperty("user.dir"); //$NON-NLS-1$
}
public void performCompilation(List files) {
if (progressListener != null) {
compiledCount=0;
sourceFileCount = files.size();
progressListener.setText("compiling source files");
}
//System.err.println("got files: " + files);
String[] filenames = new String[files.size()];
String[] encodings = new String[files.size()];
//System.err.println("filename: " + this.filenames);
for (int i=0; i < files.size(); i++) {
filenames[i] = ((File)files.get(i)).getPath();
}
List cps = buildConfig.getFullClasspath();
Dump.saveFullClasspath(cps);
String[] classpaths = new String[cps.size()];
for (int i=0; i < cps.size(); i++) {
classpaths[i] = (String)cps.get(i);
}
//System.out.println("compiling");
environment = getLibraryAccess(classpaths, filenames);
if (!state.getClassNameToFileMap().isEmpty()) {
environment = new StatefulNameEnvironment(environment, state.getClassNameToFileMap());
}
org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(this);
org.aspectj.org.eclipse.jdt.internal.compiler.Compiler compiler =
new org.aspectj.org.eclipse.jdt.internal.compiler.Compiler(environment,
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
buildConfig.getOptions().getMap(),
getBatchRequestor(),
getProblemFactory());
CompilerOptions options = compiler.options;
options.produceReferenceInfo = true; //TODO turn off when not needed
try {
compiler.compile(getCompilationUnits(filenames, encodings));
} catch (OperationCanceledException oce) {
handler.handleMessage(new Message("build cancelled:"+oce.getMessage(),IMessage.WARNING,null,null));
}
// cleanup
org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(null);
AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(null);
environment.cleanup();
environment = null;
}
/*
* Answer the component to which will be handed back compilation results from the compiler
*/
public IIntermediateResultsRequestor getInterimResultRequestor() {
return new IIntermediateResultsRequestor() {
public void acceptResult(InterimCompilationResult result) {
if (progressListener != null) {
compiledCount++;
progressListener.setProgress((compiledCount/2.0)/sourceFileCount);
progressListener.setText("compiled: " + result.fileName());
}
state.noteResult(result);
if (progressListener!=null && progressListener.isCancelledRequested()) {
throw new AbortCompilation(true,
new OperationCanceledException("Compilation cancelled as requested"));
}
}
};
}
public ICompilerRequestor getBatchRequestor() {
return new ICompilerRequestor() {
public void acceptResult(CompilationResult unitResult) {
// end of compile, must now write the results to the output destination
// this is either a jar file or a file in a directory
if (!(unitResult.hasErrors() && !proceedOnError())) {
Collection classFiles = unitResult.compiledTypes.values();
boolean shouldAddAspectName = (buildConfig.getOutxmlName() != null);
for (Iterator iter = classFiles.iterator(); iter.hasNext();) {
ClassFile classFile = (ClassFile) iter.next();
String filename = new String(classFile.fileName());
String classname = filename.replace('/', '.');
filename = filename.replace('/', File.separatorChar) + ".class";
try {
if (buildConfig.getOutputJar() == null) {
writeDirectoryEntry(unitResult, classFile,filename);
} else {
writeZipEntry(classFile,filename);
}
if (shouldAddAspectName) addAspectName(classname);
} catch (IOException ex) {
IMessage message = EclipseAdapterUtils.makeErrorMessage(
new String(unitResult.fileName),
CANT_WRITE_RESULT,
ex);
handler.handleMessage(message);
}
}
}
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();
}
private void addAspectName (String name) {
BcelWorld world = getBcelWorld();
ResolvedType type = world.resolve(name);
// System.err.println("? writeAspectName() type=" + type);
if (type.isAspect()) {
aspectNames.add(name);
}
}
};
}
protected boolean proceedOnError() {
return buildConfig.getProceedOnError();
}
// public void noteClassFiles(AjCompiler.InterimResult result) {
// if (result == null) return;
// CompilationResult unitResult = result.result;
// String sourceFileName = result.fileName();
// if (!(unitResult.hasErrors() && !proceedOnError())) {
// List unwovenClassFiles = new ArrayList();
// Enumeration classFiles = unitResult.compiledTypes.elements();
// while (classFiles.hasMoreElements()) {
// ClassFile classFile = (ClassFile) classFiles.nextElement();
// String filename = new String(classFile.fileName());
// filename = filename.replace('/', File.separatorChar) + ".class";
//
// File destinationPath = buildConfig.getOutputDir();
// if (destinationPath == null) {
// filename = new File(filename).getName();
// filename = new File(extractDestinationPathFromSourceFile(unitResult), filename).getPath();
// } else {
// filename = new File(destinationPath, filename).getPath();
// }
//
// //System.out.println("classfile: " + filename);
// unwovenClassFiles.add(new UnwovenClassFile(filename, classFile.getBytes()));
// }
// state.noteClassesFromFile(unitResult, sourceFileName, unwovenClassFiles);
//// System.out.println("file: " + sourceFileName);
//// for (int i=0; i < unitResult.simpleNameReferences.length; i++) {
//// System.out.println("simple: " + new String(unitResult.simpleNameReferences[i]));
//// }
//// for (int i=0; i < unitResult.qualifiedReferences.length; i++) {
//// System.out.println("qualified: " +
//// new String(CharOperation.concatWith(unitResult.qualifiedReferences[i], '/')));
//// }
// } else {
// state.noteClassesFromFile(null, sourceFileName, Collections.EMPTY_LIST);
// }
// }
//
private void setBuildConfig(AjBuildConfig buildConfig) {
this.buildConfig = buildConfig;
if (!this.environmentSupportsIncrementalCompilation) {
this.environmentSupportsIncrementalCompilation =
(buildConfig.isIncrementalMode() || buildConfig.isIncrementalFileMode());
}
handler.reset();
}
String makeClasspathString(AjBuildConfig buildConfig) {
if (buildConfig == null || buildConfig.getFullClasspath() == null) return "";
StringBuffer buf = new StringBuffer();
boolean first = true;
for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) {
if (first) { first = false; }
else { buf.append(File.pathSeparator); }
buf.append(it.next().toString());
}
return buf.toString();
}
/**
* This will return null if aspectjrt.jar is present and has the correct version.
* Otherwise it will return a string message indicating the problem.
*/
public String checkRtJar(AjBuildConfig buildConfig) {
// omitting dev info
if (Version.text.equals(Version.DEVELOPMENT)) {
// in the development version we can't do this test usefully
// MessageUtil.info(holder, "running development version of aspectj compiler");
return null;
}
if (buildConfig == null || buildConfig.getFullClasspath() == null) return "no classpath specified";
String ret = null;
for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) {
File p = new File( (String)it.next() );
// pr112830, allow variations on aspectjrt.jar of the form aspectjrtXXXXXX.jar
if (p.isFile() && p.getName().startsWith("aspectjrt") && p.getName().endsWith(".jar")) {
try {
String version = null;
Manifest manifest = new JarFile(p).getManifest();
if (manifest == null) {
ret = "no manifest found in " + p.getAbsolutePath() +
", expected " + Version.text;
continue;
}
Attributes attr = manifest.getAttributes("org/aspectj/lang/");
if (null != attr) {
version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
if (null != version) {
version = version.trim();
}
}
// assume that users of development aspectjrt.jar know what they're doing
if (Version.DEVELOPMENT.equals(version)) {
// MessageUtil.info(holder,
// "running with development version of aspectjrt.jar in " +
// p.getAbsolutePath());
return null;
} else if (!Version.text.equals(version)) {
ret = "bad version number found in " + p.getAbsolutePath() +
" expected " + Version.text + " found " + version;
continue;
}
} catch (IOException ioe) {
ret = "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe;
}
return null; // this is the "OK" return value!
} else {
// might want to catch other classpath errors
}
}
if (ret != null) return ret; // last error found in potentially matching jars...
return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString(buildConfig);
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("AjBuildManager(");
buf.append(")");
return buf.toString();
}
public void setStructureModel(IHierarchy structureModel) {
this.structureModel = structureModel;
}
/**
* Returns null if there is no structure model
*/
public IHierarchy getStructureModel() {
return structureModel;
}
public IProgressListener getProgressListener() {
return progressListener;
}
public void setProgressListener(IProgressListener progressListener) {
this.progressListener = progressListener;
}
/* (non-Javadoc)
* @see org.aspectj.ajdt.internal.compiler.AjCompiler.IOutputClassFileNameProvider#getOutputClassFileName(char[])
*/
public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) {
String filename = new String(eclipseClassFileName);
filename = filename.replace('/', File.separatorChar) + ".class";
File destinationPath = buildConfig.getOutputDir();
String outFile;
if (destinationPath == null) {
outFile = new File(filename).getName();
outFile = new File(extractDestinationPathFromSourceFile(result), outFile).getPath();
} else {
outFile = new File(destinationPath, filename).getPath();
}
return outFile;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler)
*/
public ICompilerAdapter getAdapter(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) {
// complete compiler config and return a suitable adapter...
populateCompilerOptionsFromLintSettings(forCompiler);
AjProblemReporter pr =
new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(),
forCompiler.options, getProblemFactory());
forCompiler.problemReporter = pr;
AjLookupEnvironment le =
new AjLookupEnvironment(forCompiler, forCompiler.options, pr, environment);
EclipseFactory factory = new EclipseFactory(le,this);
le.factory = factory;
pr.factory = factory;
forCompiler.lookupEnvironment = le;
forCompiler.parser =
new Parser(
pr,
forCompiler.options.parseLiteralExpressionsAsConstants);
return new AjCompilerAdapter(forCompiler,batchCompile,getBcelWorld(),getWeaver(),
factory,
getInterimResultRequestor(),
progressListener,
this, // IOutputFilenameProvider
this, // IBinarySourceProvider
state.getBinarySourceMap(),
buildConfig.isTerminateAfterCompilation(),
buildConfig.getProceedOnError(),
buildConfig.isNoAtAspectJAnnotationProcessing(),
state);
}
/**
* Some AspectJ lint options need to be known about in the compiler. This is
* how we pass them over...
* @param forCompiler
*/
private void populateCompilerOptionsFromLintSettings(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) {
BcelWorld world = this.state.getBcelWorld();
IMessage.Kind swallowedExceptionKind = world.getLint().swallowedExceptionInCatchBlock.getKind();
Map optionsMap = new HashMap();
optionsMap.put(CompilerOptions.OPTION_ReportSwallowedExceptionInCatchBlock,
swallowedExceptionKind == null ? "ignore" : swallowedExceptionKind.toString());
forCompiler.options.set(optionsMap);
}
/* (non-Javadoc)
* @see org.aspectj.ajdt.internal.compiler.IBinarySourceProvider#getBinarySourcesForThisWeave()
*/
public Map getBinarySourcesForThisWeave() {
return binarySourcesForTheNextCompile;
}
public static AsmHierarchyBuilder getAsmHierarchyBuilder() {
return asmHierarchyBuilder;
}
/**
* Override the the default hierarchy builder.
*/
public static void setAsmHierarchyBuilder(AsmHierarchyBuilder newBuilder) {
asmHierarchyBuilder = newBuilder;
}
public AjState getState() {
return state;
}
public void setState(AjState buildState) {
state = buildState;
}
private static class AjBuildContexFormatter implements ContextFormatter {
public String formatEntry(int phaseId, Object data) {
StringBuffer sb = new StringBuffer();
if (phaseId == CompilationAndWeavingContext.BATCH_BUILD) {
sb.append("batch building ");
} else {
sb.append("incrementally building ");
}
AjBuildConfig config = (AjBuildConfig) data;
List classpath = config.getClasspath();
sb.append("with classpath: ");
for (Iterator iter = classpath.iterator(); iter.hasNext();) {
sb.append(iter.next().toString());
sb.append(File.pathSeparator);
}
return sb.toString();
}
}
}
|
101,411 |
Bug 101411 SerialVersionUID handling
|
from emails - needs a decision --------------- Hi Andy is there a way for the weaver to add to weaved classes the serial ver uid field based on the pre-weaved bytecode computation. Right now it issues lint warning when a Serializable class without serial ver uid is encountered and due to evil #75442 this is very annoying for LTW. A first step would be to at least deal with that when we had the perObbjectTypeMunger (then should not change any kind previous stuff). Alex ------------ Andy, Generating the suid sounds like a nice idea but the code the JVM used is private inside ObjectStreamClass. Also we need to take care with ITD fields to ensure correct behaviour when sending and receiving from non-woven classes. Basically the programmer needs to be engaged, it only affects serializable classes and in 1.5 there is a warning if you don't declare the field so there is a strong hint to the programmer to solve the problem. For LTW we should make an enhancement to allow the user to configure Lint and other things. For example they may or may not be interested in advice not matching. Matthew Webster ---------------------- Alex, We should make a distinction between benign changes to suid and those that affect members. Generating suid when we add a static initializer (to support thisJoinPoint or the staticinitialization join point), accessor methods for privileged aspects or transient per-fields is OK. Doing for ITDs is more problematic. Matthew Webster
|
resolved fixed
|
6e6658a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-09T17:24:19Z | 2005-06-23T07:00:00Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjCompilerOptions.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.util.Map;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.aspectj.weaver.Constants;
/**
* Compiler options used by Eclipse integration (AJDT)
*/
public class AjCompilerOptions extends CompilerOptions {
// AspectJ Lint options
public static final String OPTION_ReportInvalidAbsoluteTypeName = "org.aspectj.ajdt.core.compiler.lint.InvalidAbsoluteTypeName";
public static final String OPTION_ReportInvalidWildcardTypeName = "org.aspectj.ajdt.core.compiler.lint.WildcardTypeName";
public static final String OPTION_ReportUnresolvableMember = "org.aspectj.ajdt.core.compiler.lint.UnresolvableMember";
public static final String OPTION_ReportTypeNotExposedToWeaver = "org.aspectj.ajdt.core.compiler.lint.TypeNotExposedToWeaver";
public static final String OPTION_ReportShadowNotInStructure = "org.aspectj.ajdt.core.compiler.lint.ShadowNotInStructure";
public static final String OPTION_ReportUnmatchedSuperTypeInCall = "org.aspectj.ajdt.core.compiler.list.UnmatchedSuperTypeInCall";
public static final String OPTION_ReportCannotImplementLazyTJP = "org.aspectj.ajdt.core.compiler.lint.CannotImplementLazyTJP";
public static final String OPTION_ReportNeedSerialVersionUIDField = "org.aspectj.ajdt.core.compiler.lint.NeedSerialVersionUIDField";
public static final String OPTION_ReportIncompatibleSerialVersion = "org.aspectj.ajdt.core.compiler.lint.BrokeSerialVersionCompatibility";
// General AspectJ Compiler options (excludes paths etc, these are handled separately)
public static final String OPTION_TerminateAfterCompilation = "org.aspectj.ajdt.core.compiler.weaver.TerminateAfterCompilation";
public static final String OPTION_XSerializableAspects = "org.aspectj.ajdt.core.compiler.weaver.XSerializableAspects";
public static final String OPTION_XLazyThisJoinPoint = "org.aspectj.ajdt.core.compiler.weaver.XLazyThisJoinPoint";
public static final String OPTION_XNoInline = "org.aspectj.ajdt.core.compiler.weaver.XNoInline";
public static final String OPTION_XNotReweavable = "org.aspectj.ajdt.core.compiler.weaver.XNotReweavable";
public static final String OPTION_XHasMember = "org.aspectj.ajdt.core.compiler.weaver.XHasMember";
public static final String OPTION_XdevPinpoint = "org.aspectj.ajdt.core.compiler.weaver.XdevPinpoint";
// these next four not exposed by IDEs
public static final String OPTION_XDevNoAtAspectJProcessing = "org.aspectj.ajdt.core.compiler.ast.NoAtAspectJProcessing";
public static final String OPTION_GenerateModel = "org.aspectj.ajdt.core.compiler.model.GenerateModel";
public static final String OPTION_GenerateJavaDocsInModel = "org.aspectj.ajdt.core.compiler.model.GenerateJavaDocsInModel";
public static final String OPTION_Emacssym = "org.aspectj.ajdt.core.compiler.model.Emacssym";
// constants for irritant levels
public static final long InvalidAbsoluteTypeName = ASTNode.Bit47L;
public static final long InvalidWildCardTypeName = ASTNode.Bit48L;
public static final long UnresolvableMember = ASTNode.Bit49L;
public static final long TypeNotExposedToWeaver = ASTNode.Bit50L;
public static final long ShadowNotInStructure = ASTNode.Bit51L;
public static final long UnmatchedSuperTypeInCall = ASTNode.Bit52L;
public static final long CannotImplementLazyTJP = ASTNode.Bit53L;
public static final long NeedSerialVersionUIDField = ASTNode.Bit54L;
public static final long IncompatibleSerialVersion = ASTNode.Bit55L;
public boolean terminateAfterCompilation = false;
public boolean xSerializableAspects = false;
public boolean xLazyThisJoinPoint = false;
public boolean xNoInline = false;
public boolean xNotReweavable = false;
public boolean xHasMember = false;
public boolean xdevPinpoint = false;
public boolean showWeavingInformation = false;
public String xOptionalJoinpoints = null;
// If true - autoboxing behaves differently ...
public boolean behaveInJava5Way = false;
// Specifies the level of the aspectjrt.jar we are targetting
public String targetAspectjRuntimeLevel = Constants.RUNTIME_LEVEL_DEFAULT;
public String xConfigurationInfo;
// these next four not exposed by IDEs
public boolean generateModel = false;
public boolean generateJavaDocsInModel = false;
public boolean generateEmacsSymFiles = false;
public boolean noAtAspectJProcessing = false;
/**
* Generates a map of cross references based on information
* in the structure model.
*/
public boolean generateCrossRefs = false;
public boolean proceedOnError = false;
/**
* Initializing the compiler options with defaults
*/
public AjCompilerOptions(){
super();
setAspectJWarningDefaults();
}
/**
* Initializing the compiler options with external settings
* @param settings
*/
public AjCompilerOptions(Map settings){
setAspectJWarningDefaults();
if (settings == null) return;
set(settings);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.impl.CompilerOptions#getMap()
*/
public Map getMap() {
Map map = super.getMap();
// now add AspectJ additional options
map.put(OPTION_ReportInvalidAbsoluteTypeName,getSeverityString(InvalidAbsoluteTypeName));
map.put(OPTION_ReportInvalidWildcardTypeName,getSeverityString(InvalidWildCardTypeName));
map.put(OPTION_ReportUnresolvableMember,getSeverityString(UnresolvableMember));
map.put(OPTION_ReportTypeNotExposedToWeaver,getSeverityString(TypeNotExposedToWeaver));
map.put(OPTION_ReportShadowNotInStructure,getSeverityString(ShadowNotInStructure));
map.put(OPTION_ReportUnmatchedSuperTypeInCall,getSeverityString(UnmatchedSuperTypeInCall));
map.put(OPTION_ReportCannotImplementLazyTJP,getSeverityString(CannotImplementLazyTJP));
map.put(OPTION_ReportNeedSerialVersionUIDField,getSeverityString(NeedSerialVersionUIDField));
map.put(OPTION_ReportIncompatibleSerialVersion,getSeverityString(IncompatibleSerialVersion));
map.put(CompilerOptions.OPTION_ReportSwallowedExceptionInCatchBlock,getSeverityString(CompilerOptions.SwallowedExceptionInCatchBlock));
map.put(OPTION_TerminateAfterCompilation, this.terminateAfterCompilation ? ENABLED : DISABLED);
map.put(OPTION_XSerializableAspects,this.xSerializableAspects ? ENABLED : DISABLED);
map.put(OPTION_XLazyThisJoinPoint,this.xLazyThisJoinPoint ? ENABLED : DISABLED);
map.put(OPTION_XNoInline,this.xNoInline ? ENABLED : DISABLED);
map.put(OPTION_XNotReweavable,this.xNotReweavable ? ENABLED : DISABLED);
map.put(OPTION_XHasMember, this.xHasMember ? ENABLED : DISABLED);
map.put(OPTION_XdevPinpoint, this.xdevPinpoint ? ENABLED : DISABLED);
map.put(OPTION_GenerateModel,this.generateModel ? ENABLED : DISABLED);
map.put(OPTION_GenerateJavaDocsInModel,this.generateJavaDocsInModel ? ENABLED : DISABLED);
map.put(OPTION_Emacssym,this.generateEmacsSymFiles ? ENABLED : DISABLED);
map.put(OPTION_XDevNoAtAspectJProcessing,this.noAtAspectJProcessing ? ENABLED : DISABLED);
return map;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.impl.CompilerOptions#set(java.util.Map)
*/
public void set(Map optionsMap) {
super.set(optionsMap);
Object optionValue;
if ((optionValue = optionsMap.get(OPTION_ReportInvalidAbsoluteTypeName)) != null) updateSeverity(InvalidAbsoluteTypeName, optionValue);
if ((optionValue = optionsMap.get(OPTION_ReportInvalidWildcardTypeName)) != null) updateSeverity(InvalidWildCardTypeName, optionValue);
if ((optionValue = optionsMap.get(OPTION_ReportUnresolvableMember)) != null) updateSeverity(UnresolvableMember, optionValue);
if ((optionValue = optionsMap.get(OPTION_ReportTypeNotExposedToWeaver)) != null) updateSeverity(TypeNotExposedToWeaver, optionValue);
if ((optionValue = optionsMap.get(OPTION_ReportShadowNotInStructure)) != null) updateSeverity(ShadowNotInStructure, optionValue);
if ((optionValue = optionsMap.get(OPTION_ReportUnmatchedSuperTypeInCall)) != null) updateSeverity(UnmatchedSuperTypeInCall, optionValue);
if ((optionValue = optionsMap.get(OPTION_ReportCannotImplementLazyTJP)) != null) updateSeverity(CannotImplementLazyTJP, optionValue);
if ((optionValue = optionsMap.get(OPTION_ReportNeedSerialVersionUIDField)) != null) updateSeverity(NeedSerialVersionUIDField, optionValue);
if ((optionValue = optionsMap.get(OPTION_ReportIncompatibleSerialVersion)) != null) updateSeverity(IncompatibleSerialVersion, optionValue);
if ((optionValue = optionsMap.get(CompilerOptions.OPTION_ReportSwallowedExceptionInCatchBlock)) != null) updateSeverity(CompilerOptions.SwallowedExceptionInCatchBlock, optionValue);
if ((optionValue = optionsMap.get(OPTION_TerminateAfterCompilation)) != null) {
if (ENABLED.equals(optionValue)) {
this.terminateAfterCompilation = true;
} else if (DISABLED.equals(optionValue)) {
this.terminateAfterCompilation = false;
}
}
if ((optionValue = optionsMap.get(OPTION_XSerializableAspects)) != null) {
if (ENABLED.equals(optionValue)) {
this.xSerializableAspects = true;
} else if (DISABLED.equals(optionValue)) {
this.xSerializableAspects = false;
}
}
if ((optionValue = optionsMap.get(OPTION_XLazyThisJoinPoint)) != null) {
if (ENABLED.equals(optionValue)) {
this.xLazyThisJoinPoint = true;
} else if (DISABLED.equals(optionValue)) {
this.xLazyThisJoinPoint = false;
}
}
if ((optionValue = optionsMap.get(OPTION_XNoInline)) != null) {
if (ENABLED.equals(optionValue)) {
this.xNoInline = true;
} else if (DISABLED.equals(optionValue)) {
this.xNoInline = false;
}
}
if ((optionValue = optionsMap.get(OPTION_XNotReweavable)) != null) {
if (ENABLED.equals(optionValue)) {
this.xNotReweavable = true;
} else if (DISABLED.equals(optionValue)) {
this.xNotReweavable = false;
}
}
/*
if ((optionValue = optionsMap.get(OPTION_XReweavableCompress)) != null) {
if (ENABLED.equals(optionValue)) {
this.xReweavableCompress = true;
} else if (DISABLED.equals(optionValue)) {
this.xReweavableCompress = false;
}
}
*/
if ((optionValue = optionsMap.get(OPTION_XHasMember)) != null) {
if (ENABLED.equals(optionValue)) {
this.xHasMember = true;
} else if (DISABLED.equals(optionValue)) {
this.xHasMember = false;
}
}
if ((optionValue = optionsMap.get(OPTION_XdevPinpoint)) != null) {
if (ENABLED.equals(optionValue)) {
this.xdevPinpoint = true;
} else if (DISABLED.equals(optionValue)) {
this.xdevPinpoint = false;
}
}
if ((optionValue = optionsMap.get(OPTION_GenerateModel)) != null) {
if (ENABLED.equals(optionValue)) {
this.generateModel = true;
} else if (DISABLED.equals(optionValue)) {
this.generateModel = false;
}
}
if ((optionValue = optionsMap.get(OPTION_GenerateJavaDocsInModel)) != null) {
if (ENABLED.equals(optionValue)) {
this.generateJavaDocsInModel = true;
} else if (DISABLED.equals(optionValue)) {
this.generateJavaDocsInModel = false;
}
}
if ((optionValue = optionsMap.get(OPTION_Emacssym)) != null) {
if (ENABLED.equals(optionValue)) {
this.generateEmacsSymFiles = true;
} else if (DISABLED.equals(optionValue)) {
this.generateEmacsSymFiles = false;
}
}
if ((optionValue = optionsMap.get(OPTION_XDevNoAtAspectJProcessing)) != null) {
if (ENABLED.equals(optionValue)) {
this.noAtAspectJProcessing = true;
} else if (DISABLED.equals(optionValue)) {
this.noAtAspectJProcessing = false;
}
}
}
/**
* Add these warnings to the default set...
*/
private void setAspectJWarningDefaults() {
super.warningThreshold =
super.warningThreshold |
InvalidAbsoluteTypeName |
UnresolvableMember |
TypeNotExposedToWeaver |
UnmatchedSuperTypeInCall |
CannotImplementLazyTJP |
CompilerOptions.SwallowedExceptionInCatchBlock;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuffer buf = new StringBuffer( super.toString() );
// now add AspectJ additional options
buf.append("\n\tAspectJ Specific Options:");
buf.append("\n\t- terminate after compilation: ").append(this.terminateAfterCompilation ? ENABLED : DISABLED); //$NON-NLS-1$
buf.append("\n\t- no inline (X option): ").append(this.xNoInline ? ENABLED : DISABLED); //$NON-NLS-1$
buf.append("\n\t- generate serializable aspects (X option): ").append(this.xSerializableAspects ? ENABLED : DISABLED); //$NON-NLS-1$
buf.append("\n\t- lazy thisJoinPoint (X option): ").append(this.xLazyThisJoinPoint ? ENABLED : DISABLED); //$NON-NLS-1$
buf.append("\n\t- generate non-reweavable class files (X option): ").append(this.xNotReweavable ? ENABLED : DISABLED); //$NON-NLS-1$
buf.append("\n\t- has member support (X option): ").append(this.xHasMember ? ENABLED : DISABLED); //$NON-NLS-1$
buf.append("\n\t- generate AJDE model: ").append(this.generateModel ? ENABLED : DISABLED); //$NON-NLS-1$
buf.append("\n\t- generate Javadocs in AJDE model: ").append(this.generateJavaDocsInModel ? ENABLED : DISABLED); //$NON-NLS-1$
buf.append("\n\t- generate Emacs symbol files: ").append(this.generateEmacsSymFiles ? ENABLED : DISABLED); //$NON-NLS-1$
buf.append("\n\t- suppress @AspectJ processing: ").append(this.noAtAspectJProcessing ? ENABLED : DISABLED); //$NON-NLS-1$
buf.append("\n\t- invalid absolute type name (XLint): ").append(getSeverityString(InvalidAbsoluteTypeName)); //$NON-NLS-1$
buf.append("\n\t- invalid wildcard type name (XLint): ").append(getSeverityString(InvalidWildCardTypeName)); //$NON-NLS-1$
buf.append("\n\t- unresolvable member (XLint): ").append(getSeverityString(UnresolvableMember)); //$NON-NLS-1$
buf.append("\n\t- type not exposed to weaver (XLint): ").append(getSeverityString(TypeNotExposedToWeaver)); //$NON-NLS-1$
buf.append("\n\t- shadow not in structure (XLint): ").append(getSeverityString(ShadowNotInStructure)); //$NON-NLS-1$
buf.append("\n\t- unmatched super type in call (XLint): ").append(getSeverityString(UnmatchedSuperTypeInCall)); //$NON-NLS-1$
buf.append("\n\t- cannot implement lazy thisJoinPoint (XLint): ").append(getSeverityString(CannotImplementLazyTJP)); //$NON-NLS-1$
buf.append("\n\t- need serialVersionUID field (XLint): ").append(getSeverityString(NeedSerialVersionUIDField)); //$NON-NLS-1$
buf.append("\n\t- incompatible serial version (XLint): ").append(getSeverityString(IncompatibleSerialVersion)); //$NON-NLS-1$
buf.append("\n\t- swallowed exception in catch block (XLint): ").append(getSeverityString(CompilerOptions.SwallowedExceptionInCatchBlock)); //$NON-NLS-1$
return buf.toString();
}
}
|
101,411 |
Bug 101411 SerialVersionUID handling
|
from emails - needs a decision --------------- Hi Andy is there a way for the weaver to add to weaved classes the serial ver uid field based on the pre-weaved bytecode computation. Right now it issues lint warning when a Serializable class without serial ver uid is encountered and due to evil #75442 this is very annoying for LTW. A first step would be to at least deal with that when we had the perObbjectTypeMunger (then should not change any kind previous stuff). Alex ------------ Andy, Generating the suid sounds like a nice idea but the code the JVM used is private inside ObjectStreamClass. Also we need to take care with ITD fields to ensure correct behaviour when sending and receiving from non-woven classes. Basically the programmer needs to be engaged, it only affects serializable classes and in 1.5 there is a warning if you don't declare the field so there is a strong hint to the programmer to solve the problem. For LTW we should make an enhancement to allow the user to configure Lint and other things. For example they may or may not be interested in advice not matching. Matthew Webster ---------------------- Alex, We should make a distinction between benign changes to suid and those that affect members. Generating suid when we add a static initializer (to support thisJoinPoint or the staticinitialization join point), accessor methods for privileged aspects or transient per-fields is OK. Doing for ITDs is more problematic. Matthew Webster
|
resolved fixed
|
6e6658a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-09T17:24:19Z | 2005-06-23T07:00:00Z |
tests/features151/serialveruid/AnAspect.java
| |
101,411 |
Bug 101411 SerialVersionUID handling
|
from emails - needs a decision --------------- Hi Andy is there a way for the weaver to add to weaved classes the serial ver uid field based on the pre-weaved bytecode computation. Right now it issues lint warning when a Serializable class without serial ver uid is encountered and due to evil #75442 this is very annoying for LTW. A first step would be to at least deal with that when we had the perObbjectTypeMunger (then should not change any kind previous stuff). Alex ------------ Andy, Generating the suid sounds like a nice idea but the code the JVM used is private inside ObjectStreamClass. Also we need to take care with ITD fields to ensure correct behaviour when sending and receiving from non-woven classes. Basically the programmer needs to be engaged, it only affects serializable classes and in 1.5 there is a warning if you don't declare the field so there is a strong hint to the programmer to solve the problem. For LTW we should make an enhancement to allow the user to configure Lint and other things. For example they may or may not be interested in advice not matching. Matthew Webster ---------------------- Alex, We should make a distinction between benign changes to suid and those that affect members. Generating suid when we add a static initializer (to support thisJoinPoint or the staticinitialization join point), accessor methods for privileged aspects or transient per-fields is OK. Doing for ITDs is more problematic. Matthew Webster
|
resolved fixed
|
6e6658a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-09T17:24:19Z | 2005-06-23T07:00:00Z |
tests/features151/serialveruid/Basic.java
| |
101,411 |
Bug 101411 SerialVersionUID handling
|
from emails - needs a decision --------------- Hi Andy is there a way for the weaver to add to weaved classes the serial ver uid field based on the pre-weaved bytecode computation. Right now it issues lint warning when a Serializable class without serial ver uid is encountered and due to evil #75442 this is very annoying for LTW. A first step would be to at least deal with that when we had the perObbjectTypeMunger (then should not change any kind previous stuff). Alex ------------ Andy, Generating the suid sounds like a nice idea but the code the JVM used is private inside ObjectStreamClass. Also we need to take care with ITD fields to ensure correct behaviour when sending and receiving from non-woven classes. Basically the programmer needs to be engaged, it only affects serializable classes and in 1.5 there is a warning if you don't declare the field so there is a strong hint to the programmer to solve the problem. For LTW we should make an enhancement to allow the user to configure Lint and other things. For example they may or may not be interested in advice not matching. Matthew Webster ---------------------- Alex, We should make a distinction between benign changes to suid and those that affect members. Generating suid when we add a static initializer (to support thisJoinPoint or the staticinitialization join point), accessor methods for privileged aspects or transient per-fields is OK. Doing for ITDs is more problematic. Matthew Webster
|
resolved fixed
|
6e6658a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-09T17:24:19Z | 2005-06-23T07:00:00Z |
tests/features151/serialveruid/BigHorribleClass.java
| |
101,411 |
Bug 101411 SerialVersionUID handling
|
from emails - needs a decision --------------- Hi Andy is there a way for the weaver to add to weaved classes the serial ver uid field based on the pre-weaved bytecode computation. Right now it issues lint warning when a Serializable class without serial ver uid is encountered and due to evil #75442 this is very annoying for LTW. A first step would be to at least deal with that when we had the perObbjectTypeMunger (then should not change any kind previous stuff). Alex ------------ Andy, Generating the suid sounds like a nice idea but the code the JVM used is private inside ObjectStreamClass. Also we need to take care with ITD fields to ensure correct behaviour when sending and receiving from non-woven classes. Basically the programmer needs to be engaged, it only affects serializable classes and in 1.5 there is a warning if you don't declare the field so there is a strong hint to the programmer to solve the problem. For LTW we should make an enhancement to allow the user to configure Lint and other things. For example they may or may not be interested in advice not matching. Matthew Webster ---------------------- Alex, We should make a distinction between benign changes to suid and those that affect members. Generating suid when we add a static initializer (to support thisJoinPoint or the staticinitialization join point), accessor methods for privileged aspects or transient per-fields is OK. Doing for ITDs is more problematic. Matthew Webster
|
resolved fixed
|
6e6658a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-09T17:24:19Z | 2005-06-23T07:00:00Z |
tests/src/org/aspectj/systemtest/ajc151/AllTestsAspectJ151.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc151;
import junit.framework.Test;
import junit.framework.TestSuite;
public class AllTestsAspectJ151 {
public static Test suite() {
TestSuite suite = new TestSuite("AspectJ 1.5.1 tests");
//$JUnit-BEGIN$
suite.addTest(Ajc151Tests.suite());
suite.addTest(NewarrayJoinpointTests.suite());
suite.addTest(AtAroundTests.suite());
//$JUnit-END$
return suite;
}
}
|
101,411 |
Bug 101411 SerialVersionUID handling
|
from emails - needs a decision --------------- Hi Andy is there a way for the weaver to add to weaved classes the serial ver uid field based on the pre-weaved bytecode computation. Right now it issues lint warning when a Serializable class without serial ver uid is encountered and due to evil #75442 this is very annoying for LTW. A first step would be to at least deal with that when we had the perObbjectTypeMunger (then should not change any kind previous stuff). Alex ------------ Andy, Generating the suid sounds like a nice idea but the code the JVM used is private inside ObjectStreamClass. Also we need to take care with ITD fields to ensure correct behaviour when sending and receiving from non-woven classes. Basically the programmer needs to be engaged, it only affects serializable classes and in 1.5 there is a warning if you don't declare the field so there is a strong hint to the programmer to solve the problem. For LTW we should make an enhancement to allow the user to configure Lint and other things. For example they may or may not be interested in advice not matching. Matthew Webster ---------------------- Alex, We should make a distinction between benign changes to suid and those that affect members. Generating suid when we add a static initializer (to support thisJoinPoint or the staticinitialization join point), accessor methods for privileged aspects or transient per-fields is OK. Doing for ITDs is more problematic. Matthew Webster
|
resolved fixed
|
6e6658a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-09T17:24:19Z | 2005-06-23T07:00:00Z |
tests/src/org/aspectj/systemtest/ajc151/SerialVersionUIDTests.java
| |
101,411 |
Bug 101411 SerialVersionUID handling
|
from emails - needs a decision --------------- Hi Andy is there a way for the weaver to add to weaved classes the serial ver uid field based on the pre-weaved bytecode computation. Right now it issues lint warning when a Serializable class without serial ver uid is encountered and due to evil #75442 this is very annoying for LTW. A first step would be to at least deal with that when we had the perObbjectTypeMunger (then should not change any kind previous stuff). Alex ------------ Andy, Generating the suid sounds like a nice idea but the code the JVM used is private inside ObjectStreamClass. Also we need to take care with ITD fields to ensure correct behaviour when sending and receiving from non-woven classes. Basically the programmer needs to be engaged, it only affects serializable classes and in 1.5 there is a warning if you don't declare the field so there is a strong hint to the programmer to solve the problem. For LTW we should make an enhancement to allow the user to configure Lint and other things. For example they may or may not be interested in advice not matching. Matthew Webster ---------------------- Alex, We should make a distinction between benign changes to suid and those that affect members. Generating suid when we add a static initializer (to support thisJoinPoint or the staticinitialization join point), accessor methods for privileged aspects or transient per-fields is OK. Doing for ITDs is more problematic. Matthew Webster
|
resolved fixed
|
6e6658a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-09T17:24:19Z | 2005-06-23T07:00:00Z |
weaver/src/org/aspectj/weaver/Lint.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
public class Lint {
/* private */ Map kinds = new HashMap();
/* private */ World world;
public final Kind invalidAbsoluteTypeName =
new Kind("invalidAbsoluteTypeName", "no match for this type name: {0}");
public final Kind invalidWildcardTypeName =
new Kind("invalidWildcardTypeName", "no match for this type pattern: {0}");
public final Kind unresolvableMember =
new Kind("unresolvableMember", "can not resolve this member: {0}");
public final Kind typeNotExposedToWeaver =
new Kind("typeNotExposedToWeaver", "this affected type is not exposed to the weaver: {0}");
public final Kind shadowNotInStructure =
new Kind("shadowNotInStructure", "the shadow for this join point is not exposed in the structure model: {0}");
public final Kind unmatchedSuperTypeInCall =
new Kind("unmatchedSuperTypeInCall", "does not match because declaring type is {0}, if match desired use target({1})");
public final Kind unmatchedTargetKind =
new Kind("unmatchedTargetKind", "does not match because annotation {0} has @Target{1}");
public final Kind canNotImplementLazyTjp =
new Kind("canNotImplementLazyTjp", "can not implement lazyTjp on this joinpoint {0} because around advice is used");
public final Kind multipleAdviceStoppingLazyTjp =
new Kind("multipleAdviceStoppingLazyTjp", "can not implement lazyTjp at joinpoint {0} because of advice conflicts, see secondary locations to find conflicting advice");
public final Kind needsSerialVersionUIDField =
new Kind("needsSerialVersionUIDField", "serialVersionUID of type {0} needs to be set because of {1}");
public final Kind serialVersionUIDBroken =
new Kind("brokeSerialVersionCompatibility", "serialVersionUID of type {0} is broken because of added field {1}");
public final Kind noInterfaceCtorJoinpoint =
new Kind("noInterfaceCtorJoinpoint","no interface constructor-execution join point - use {0}+ for implementing classes");
public final Kind noJoinpointsForBridgeMethods =
new Kind("noJoinpointsForBridgeMethods","pointcut did not match on the method call to a bridge method. Bridge methods are generated by the compiler and have no join points");
public final Kind enumAsTargetForDecpIgnored =
new Kind("enumAsTargetForDecpIgnored","enum type {0} matches a declare parents type pattern but is being ignored");
public final Kind annotationAsTargetForDecpIgnored =
new Kind("annotationAsTargetForDecpIgnored","annotation type {0} matches a declare parents type pattern but is being ignored");
public final Kind cantMatchArrayTypeOnVarargs =
new Kind("cantMatchArrayTypeOnVarargs","an array type as the last parameter in a signature does not match on the varargs declared method: {0}");
public final Kind adviceDidNotMatch =
new Kind("adviceDidNotMatch","advice defined in {0} has not been applied");
public final Kind invalidTargetForAnnotation =
new Kind("invalidTargetForAnnotation","{0} is not a valid target for annotation {1}, this annotation can only be applied to {2}");
public final Kind elementAlreadyAnnotated =
new Kind("elementAlreadyAnnotated","{0} - already has an annotation of type {1}, cannot add a second instance");
public final Kind runtimeExceptionNotSoftened =
new Kind("runtimeExceptionNotSoftened","{0} will not be softened as it is already a RuntimeException");
public final Kind uncheckedArgument =
new Kind("uncheckedArgument","unchecked match of {0} with {1} when argument is an instance of {2} at join point {3}");
public final Kind uncheckedAdviceConversion =
new Kind("uncheckedAdviceConversion","unchecked conversion when advice applied at shadow {0}, expected {1} but advice uses {2}");
public final Kind noGuardForLazyTjp =
new Kind("noGuardForLazyTjp","can not build thisJoinPoint lazily for this advice since it has no suitable guard. The advice applies at {0}");
public final Kind noExplicitConstructorCall =
new Kind("noExplicitConstructorCall","inter-type constructor does not contain explicit constructor call: field initializers in the target type will not be executed");
public final Kind aspectExcludedByConfiguration =
new Kind("aspectExcludedByConfiguration","aspect {0} exluded for class loader {1}");
public final Kind unorderedAdviceAtShadow =
new Kind("unorderedAdviceAtShadow","at this shadow {0} no precedence is specified between advice applying from aspect {1} and aspect {2}");
public final Kind swallowedExceptionInCatchBlock =
new Kind("swallowedExceptionInCatchBlock","exception swallowed in catch block");
// there are a lot of messages in the cant find type family - I'm defining an umbrella lint warning that
// allows a user to control their severity (for e.g. ltw or binary weaving)
public final Kind cantFindType =
new Kind("cantFindType","{0}");
public final Kind cantFindTypeAffectingJoinPointMatch = new Kind("cantFindTypeAffectingJPMatch","{0}");
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(),
WeaverMessages.format(WeaverMessages.XLINT_LOAD_ERROR,file.getPath(),ioe.getMessage()));
}
}
public void loadDefaultProperties() {
InputStream s = getClass().getResourceAsStream("XlintDefault.properties");
if (s == null) {
MessageUtil.warn(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINTDEFAULT_LOAD_ERROR));
return;
}
try {
setFromProperties(s);
} catch (IOException ioe) {
MessageUtil.error(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINTDEFAULT_LOAD_PROBLEM,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(),
WeaverMessages.format(WeaverMessages.XLINT_KEY_ERROR,entry.getKey()));
} else {
kind.setKind(getMessageKind((String)entry.getValue()));
}
}
}
public Collection allKinds() {
return kinds.values();
}
public Kind getLintKind(String name) {
return (Kind) kinds.get(name);
}
// temporarily suppress the given lint messages
public void suppressKinds(Collection lintKind) {
if (lintKind.isEmpty()) return;
for (Iterator iter = lintKind.iterator(); iter.hasNext();) {
Kind k = (Kind) iter.next();
k.setSuppressed(true);
}
}
// remove any suppression of lint warnings in place
public void clearAllSuppressions() {
for (Iterator iter = kinds.values().iterator(); iter.hasNext();) {
Kind k = (Kind) iter.next();
k.setSuppressed(false);
}
}
public void clearSuppressions(Collection lintKind) {
if (lintKind.isEmpty()) return;
for (Iterator iter = lintKind.iterator(); iter.hasNext();) {
Kind k = (Kind) iter.next();
k.setSuppressed(false);
}
}
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(),
WeaverMessages.format(WeaverMessages.XLINT_VALUE_ERROR,v));
return null;
}
public class Kind {
private String name;
private String message;
private IMessage.Kind kind = IMessage.WARNING;
private boolean isSupressed = false; // by SuppressAjWarnings
public Kind(String name, String message) {
this.name = name;
this.message = message;
kinds.put(this.name, this);
}
public void setSuppressed(boolean shouldBeSuppressed) {
this.isSupressed = shouldBeSuppressed;
}
public boolean isEnabled() {
return (kind != null) && !isSupressed();
}
private boolean isSupressed() {
// can't suppress errors!
return isSupressed && (kind != IMessage.ERROR);
}
public String getName() {
return name;
}
public IMessage.Kind getKind() {
return kind;
}
public void setKind(IMessage.Kind kind) {
this.kind = kind;
}
public void signal(String info, ISourceLocation location) {
if (kind == null) return;
String text = MessageFormat.format(message, new Object[] {info} );
text += " [Xlint:" + name + "]";
world.getMessageHandler().handleMessage(new Message(text, kind, null, location));
}
public void signal(String[] infos, ISourceLocation location, ISourceLocation[] extraLocations) {
if (kind == null) return;
String text = MessageFormat.format(message, infos );
text += " [Xlint:" + name + "]";
world.getMessageHandler().handleMessage(
new Message(text, "", kind, location, null, extraLocations));
}
}
}
|
101,411 |
Bug 101411 SerialVersionUID handling
|
from emails - needs a decision --------------- Hi Andy is there a way for the weaver to add to weaved classes the serial ver uid field based on the pre-weaved bytecode computation. Right now it issues lint warning when a Serializable class without serial ver uid is encountered and due to evil #75442 this is very annoying for LTW. A first step would be to at least deal with that when we had the perObbjectTypeMunger (then should not change any kind previous stuff). Alex ------------ Andy, Generating the suid sounds like a nice idea but the code the JVM used is private inside ObjectStreamClass. Also we need to take care with ITD fields to ensure correct behaviour when sending and receiving from non-woven classes. Basically the programmer needs to be engaged, it only affects serializable classes and in 1.5 there is a warning if you don't declare the field so there is a strong hint to the programmer to solve the problem. For LTW we should make an enhancement to allow the user to configure Lint and other things. For example they may or may not be interested in advice not matching. Matthew Webster ---------------------- Alex, We should make a distinction between benign changes to suid and those that affect members. Generating suid when we add a static initializer (to support thisJoinPoint or the staticinitialization join point), accessor methods for privileged aspects or transient per-fields is OK. Doing for ITDs is more problematic. Matthew Webster
|
resolved fixed
|
6e6658a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-09T17:24:19Z | 2005-06-23T07:00:00Z |
weaver/src/org/aspectj/weaver/World.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* 2005 Contributors
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the 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, Andy Clement, overhaul for generics
* ******************************************************************/
package org.aspectj.weaver;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.WeakHashMap;
import org.aspectj.asm.IHierarchy;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.bridge.context.PinpointingMessageHandler;
import org.aspectj.weaver.UnresolvedType.TypeKind;
import org.aspectj.weaver.bcel.BcelObjectType;
import org.aspectj.weaver.patterns.DeclarePrecedence;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.reflect.ReflectionBasedReferenceTypeDelegate;
/**
* A World is a collection of known types and crosscutting members.
*/
public abstract class World implements Dump.INode {
/** handler for any messages produced during resolution etc. */
private IMessageHandler messageHandler = IMessageHandler.SYSTEM_ERR;
/** handler for cross-reference information produced during the weaving process */
private ICrossReferenceHandler xrefHandler = null;
/** Currently 'active' scope in which to lookup (resolve) typevariable references */
private TypeVariableDeclaringElement typeVariableLookupScope;
/** The heart of the world, a map from type signatures to resolved types */
protected TypeMap typeMap = new TypeMap(this); // Signature to ResolvedType
/** Calculator for working out aspect precedence */
private AspectPrecedenceCalculator precedenceCalculator;
/** All of the type and shadow mungers known to us */
private CrosscuttingMembersSet crosscuttingMembersSet =
new CrosscuttingMembersSet(this);
/** Model holds ASM relationships */
private IHierarchy model = null;
/** for processing Xlint messages */
private Lint lint = new Lint(this);
/** XnoInline option setting passed down to weaver */
private boolean XnoInline;
/** XlazyTjp option setting passed down to weaver */
private boolean XlazyTjp;
/** XhasMember option setting passed down to weaver */
private boolean XhasMember = false;
/** Xpinpoint controls whether we put out developer info showing the source of messages */
private boolean Xpinpoint = false;
/** When behaving in a Java 5 way autoboxing is considered */
private boolean behaveInJava5Way = false;
/** The level of the aspectjrt.jar the code we generate needs to run on */
private String targetAspectjRuntimeLevel = Constants.RUNTIME_LEVEL_DEFAULT;
/** Flags for the new joinpoints that are 'optional' */
private boolean optionalJoinpoint_ArrayConstruction = false; // Command line flag: "arrayconstruction"
private Properties extraConfiguration = null;
// Records whether ASM is around ... so we might use it for delegates
protected static boolean isASMAround;
static {
try {
Class c = Class.forName("org.aspectj.org.objectweb.asm.ClassVisitor");
isASMAround = true;
} catch (ClassNotFoundException cnfe) {
isASMAround = false;
}
}
/**
* A list of RuntimeExceptions containing full stack information for every
* type we couldn't find.
*/
private List dumpState_cantFindTypeExceptions = null;
/**
* Play God.
* On the first day, God created the primitive types and put them in the type
* map.
*/
protected World() {
super();
Dump.registerNode(this.getClass(),this);
typeMap.put("B", ResolvedType.BYTE);
typeMap.put("S", ResolvedType.SHORT);
typeMap.put("I", ResolvedType.INT);
typeMap.put("J", ResolvedType.LONG);
typeMap.put("F", ResolvedType.FLOAT);
typeMap.put("D", ResolvedType.DOUBLE);
typeMap.put("C", ResolvedType.CHAR);
typeMap.put("Z", ResolvedType.BOOLEAN);
typeMap.put("V", ResolvedType.VOID);
precedenceCalculator = new AspectPrecedenceCalculator(this);
}
/**
* Dump processing when a fatal error occurs
*/
public void accept (Dump.IVisitor visitor) {
visitor.visitString("Shadow mungers:");
visitor.visitList(crosscuttingMembersSet.getShadowMungers());
visitor.visitString("Type mungers:");
visitor.visitList(crosscuttingMembersSet.getTypeMungers());
visitor.visitString("Late Type mungers:");
visitor.visitList(crosscuttingMembersSet.getLateTypeMungers());
if (dumpState_cantFindTypeExceptions!=null) {
visitor.visitString("Cant find type problems:");
visitor.visitList(dumpState_cantFindTypeExceptions);
dumpState_cantFindTypeExceptions = null;
}
}
// =============================================================================
// T Y P E R E S O L U T I O N
// =============================================================================
/**
* Resolve a type that we require to be present in the world
*/
public ResolvedType resolve(UnresolvedType ty) {
return resolve(ty, false);
}
/**
* Attempt to resolve a type - the source location gives you some context in which
* resolution is taking place. In the case of an error where we can't find the
* type - we can then at least report why (source location) we were trying to resolve it.
*/
public ResolvedType resolve(UnresolvedType ty,ISourceLocation isl) {
ResolvedType ret = resolve(ty,true);
if (ResolvedType.isMissing(ty)) {
//IMessage msg = null;
getLint().cantFindType.signal(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()),isl);
//if (isl!=null) {
//msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()),isl);
//} else {
//msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()));
//}
//messageHandler.handleMessage(msg);
}
return ret;
}
/**
* Convenience method for resolving an array of unresolved types
* in one hit. Useful for e.g. resolving type parameters in signatures.
*/
public ResolvedType[] resolve(UnresolvedType[] types) {
if (types == null) return new ResolvedType[0];
ResolvedType[] ret = new ResolvedType[types.length];
for (int i=0; i<types.length; i++) {
ret[i] = resolve(types[i]);
}
return ret;
}
/**
* Resolve a type. This the hub of type resolution. The resolved type is added
* to the type map by signature.
*/
public ResolvedType resolve(UnresolvedType ty, boolean allowMissing) {
// special resolution processing for already resolved types.
if (ty instanceof ResolvedType) {
ResolvedType rty = (ResolvedType) ty;
rty = resolve(rty);
return rty;
}
// dispatch back to the type variable reference to resolve its constituent parts
// don't do this for other unresolved types otherwise you'll end up in a loop
if (ty.isTypeVariableReference()) {
return ty.resolve(this);
}
// if we've already got a resolved type for the signature, just return it
// after updating the world
String signature = ty.getSignature();
ResolvedType ret = typeMap.get(signature);
if (ret != null) {
ret.world = this; // Set the world for the RTX
return ret;
} else if ( signature.equals("?") || signature.equals("*")) {
// might be a problem here, not sure '?' should make it to here as a signature, the
// proper signature for wildcard '?' is '*'
// fault in generic wildcard, can't be done earlier because of init issues
ResolvedType something = new BoundedReferenceType("?","Ljava/lang/Object",this);
typeMap.put("?",something);
return something;
}
// no existing resolved type, create one
if (ty.isArray()) {
ResolvedType componentType = resolve(ty.getComponentType(),allowMissing);
//String brackets = signature.substring(0,signature.lastIndexOf("[")+1);
ret = new ResolvedType.Array(signature, "["+componentType.getErasureSignature(),
this,
componentType);
} else {
ret = resolveToReferenceType(ty);
if (!allowMissing && ret.isMissing()) {
ret = handleRequiredMissingTypeDuringResolution(ty);
}
}
// Pulling in the type may have already put the right entry in the map
if (typeMap.get(signature)==null && !ret.isMissing()) {
typeMap.put(signature, ret);
}
return ret;
}
/**
* We tried to resolve a type and couldn't find it...
*/
private ResolvedType handleRequiredMissingTypeDuringResolution(UnresolvedType ty) {
// defer the message until someone asks a question of the type that we can't answer
// just from the signature.
// MessageUtil.error(messageHandler,
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()));
if (dumpState_cantFindTypeExceptions==null) {
dumpState_cantFindTypeExceptions = new ArrayList();
}
dumpState_cantFindTypeExceptions.add(new RuntimeException("Can't find type "+ty.getName()));
return new MissingResolvedTypeWithKnownSignature(ty.getSignature(),this);
}
/**
* Some TypeFactory operations create resolved types directly, but these won't be
* in the typeMap - this resolution process puts them there. Resolved types are
* also told their world which is needed for the special autoboxing resolved types.
*/
public ResolvedType resolve(ResolvedType ty) {
if (ty.isTypeVariableReference()) return ty; // until type variables have proper sigs...
ResolvedType resolved = typeMap.get(ty.getSignature());
if (resolved == null) {
typeMap.put(ty.getSignature(), ty);
resolved = ty;
}
resolved.world = this;
return resolved;
}
/**
* Convenience method for finding a type by name and resolving it in one step.
*/
public ResolvedType resolve(String name) {
return resolve(UnresolvedType.forName(name));
}
public ResolvedType resolve(String name,boolean allowMissing) {
return resolve(UnresolvedType.forName(name),allowMissing);
}
private ResolvedType currentlyResolvingBaseType;
/**
* Resolve to a ReferenceType - simple, raw, parameterized, or generic.
* Raw, parameterized, and generic versions of a type share a delegate.
*/
private final ResolvedType resolveToReferenceType(UnresolvedType ty) {
if (ty.isParameterizedType()) {
// ======= parameterized types ================
ReferenceType genericType = (ReferenceType)resolveGenericTypeFor(ty,false);
currentlyResolvingBaseType = genericType;
ReferenceType parameterizedType =
TypeFactory.createParameterizedType(genericType, ty.typeParameters, this);
currentlyResolvingBaseType = null;
return parameterizedType;
} else if (ty.isGenericType()) {
// ======= generic types ======================
ReferenceType genericType = (ReferenceType)resolveGenericTypeFor(ty,false);
return genericType;
} else if (ty.isGenericWildcard()) {
// ======= generic wildcard types =============
return resolveGenericWildcardFor(ty);
} else {
// ======= simple and raw types ===============
String erasedSignature = ty.getErasureSignature();
ReferenceType simpleOrRawType = new ReferenceType(erasedSignature, this);
if (ty.needsModifiableDelegate()) simpleOrRawType.setNeedsModifiableDelegate(true);
ReferenceTypeDelegate delegate = resolveDelegate(simpleOrRawType);
// 117854
// if (delegate == null) return ResolvedType.MISSING;
if (delegate == null) return new MissingResolvedTypeWithKnownSignature(ty.getSignature(),erasedSignature,this);//ResolvedType.MISSING;
if (delegate.isGeneric() && behaveInJava5Way) {
// ======== raw type ===========
simpleOrRawType.typeKind = TypeKind.RAW;
ReferenceType genericType = makeGenericTypeFrom(delegate,simpleOrRawType);
// name = ReferenceType.fromTypeX(UnresolvedType.forRawTypeNames(ty.getName()),this);
simpleOrRawType.setDelegate(delegate);
genericType.setDelegate(delegate);
simpleOrRawType.setGenericType(genericType);
return simpleOrRawType;
} else {
// ======== simple type =========
simpleOrRawType.setDelegate(delegate);
return simpleOrRawType;
}
}
}
/**
* Attempt to resolve a type that should be a generic type.
*/
public ResolvedType resolveGenericTypeFor(UnresolvedType anUnresolvedType, boolean allowMissing) {
// Look up the raw type by signature
String rawSignature = anUnresolvedType.getRawType().getSignature();
ResolvedType rawType = (ResolvedType) typeMap.get(rawSignature);
if (rawType==null) {
rawType = resolve(UnresolvedType.forSignature(rawSignature),false);
typeMap.put(rawSignature,rawType);
}
// Does the raw type know its generic form? (It will if we created the
// raw type from a source type, it won't if its been created just through
// being referenced, e.g. java.util.List
ResolvedType genericType = rawType.getGenericType();
// There is a special case to consider here (testGenericsBang_pr95993 highlights it)
// You may have an unresolvedType for a parameterized type but it
// is backed by a simple type rather than a generic type. This occurs for
// inner types of generic types that inherit their enclosing types
// type variables.
if (rawType.isSimpleType() && (anUnresolvedType.typeParameters==null || anUnresolvedType.typeParameters.length==0)) {
rawType.world = this;
return rawType;
}
if (genericType != null) {
genericType.world = this;
return genericType;
} else {
// Fault in the generic that underpins the raw type ;)
ReferenceTypeDelegate delegate = resolveDelegate((ReferenceType)rawType);
ReferenceType genericRefType = makeGenericTypeFrom(delegate,((ReferenceType)rawType));
((ReferenceType)rawType).setGenericType(genericRefType);
genericRefType.setDelegate(delegate);
((ReferenceType)rawType).setDelegate(delegate);
return genericRefType;
}
}
private ReferenceType makeGenericTypeFrom(ReferenceTypeDelegate delegate, ReferenceType rawType) {
String genericSig = delegate.getDeclaredGenericSignature();
if (genericSig != null) {
return new ReferenceType(
UnresolvedType.forGenericTypeSignature(rawType.getSignature(),delegate.getDeclaredGenericSignature()),this);
} else {
return new ReferenceType(
UnresolvedType.forGenericTypeVariables(rawType.getSignature(), delegate.getTypeVariables()),this);
}
}
/**
* Go from an unresolved generic wildcard (represented by UnresolvedType) to a resolved version (BoundedReferenceType).
*/
private ReferenceType resolveGenericWildcardFor(UnresolvedType aType) {
BoundedReferenceType ret = null;
// FIXME asc doesnt take account of additional interface bounds (e.g. ? super R & Serializable - can you do that?)
if (aType.isExtends()) {
ReferenceType upperBound = (ReferenceType)resolve(aType.getUpperBound());
ret = new BoundedReferenceType(upperBound,true,this);
} else if (aType.isSuper()) {
ReferenceType lowerBound = (ReferenceType) resolve(aType.getLowerBound());
ret = new BoundedReferenceType(lowerBound,false,this);
} else {
// must be ? on its own!
}
return ret;
}
/**
* Find the ReferenceTypeDelegate behind this reference type so that it can
* fulfill its contract.
*/
protected abstract ReferenceTypeDelegate resolveDelegate(ReferenceType ty);
/**
* Special resolution for "core" types like OBJECT. These are resolved just like
* any other type, but if they are not found it is more serious and we issue an
* error message immediately.
*/
public ResolvedType getCoreType(UnresolvedType tx) {
ResolvedType coreTy = resolve(tx,true);
if (coreTy.isMissing()) {
MessageUtil.error(messageHandler,
WeaverMessages.format(WeaverMessages.CANT_FIND_CORE_TYPE,tx.getName()));
}
return coreTy;
}
/**
* Lookup a type by signature, if not found then build one and put it in the
* map.
*/
public ReferenceType lookupOrCreateName(UnresolvedType ty) {
String signature = ty.getSignature();
ReferenceType ret = lookupBySignature(signature);
if (ret == null) {
ret = ReferenceType.fromTypeX(ty, this);
typeMap.put(signature, ret);
}
return ret;
}
/**
* Lookup a reference type in the world by its signature. Returns
* null if not found.
*/
public ReferenceType lookupBySignature(String signature) {
return (ReferenceType) typeMap.get(signature);
}
// =============================================================================
// T Y P E R E S O L U T I O N -- E N D
// =============================================================================
/**
* Member resolution is achieved by resolving the declaring type and then
* looking up the member in the resolved declaring type.
*/
public ResolvedMember resolve(Member member) {
ResolvedType declaring = member.getDeclaringType().resolve(this);
if (declaring.isRawType()) declaring = declaring.getGenericType();
ResolvedMember ret;
if (member.getKind() == Member.FIELD) {
ret = declaring.lookupField(member);
} else {
ret = declaring.lookupMethod(member);
}
if (ret != null) return ret;
return declaring.lookupSyntheticMember(member);
}
// Methods for creating various cross-cutting members...
// ===========================================================
/**
* Create an advice shadow munger from the given advice attribute
*/
public abstract Advice createAdviceMunger(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature);
/**
* Create an advice shadow munger for the given advice kind
*/
public final Advice createAdviceMunger(
AdviceKind kind,
Pointcut p,
Member signature,
int extraParameterFlags,
IHasSourceLocation loc)
{
AjAttribute.AdviceAttribute attribute =
new AjAttribute.AdviceAttribute(kind, p, extraParameterFlags, loc.getStart(), loc.getEnd(), loc.getSourceContext());
return createAdviceMunger(attribute, p, signature);
}
public abstract ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField);
public abstract ConcreteTypeMunger makeCflowCounterFieldAdder(ResolvedMember cflowField);
/**
* Register a munger for perclause @AJ aspect so that we add aspectOf(..) to them as needed
* @see org.aspectj.weaver.bcel.BcelWorld#makePerClauseAspect(ResolvedType, org.aspectj.weaver.patterns.PerClause.Kind)
*/
public abstract ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, PerClause.Kind kind);
public abstract ConcreteTypeMunger concreteTypeMunger(ResolvedTypeMunger munger, ResolvedType aspectType);
/**
* Same signature as org.aspectj.util.PartialOrder.PartialComparable.compareTo
*/
public int compareByPrecedence(ResolvedType aspect1, ResolvedType aspect2) {
return precedenceCalculator.compareByPrecedence(aspect1, aspect2);
}
public Integer getPrecedenceIfAny(ResolvedType aspect1, ResolvedType aspect2) {
return precedenceCalculator.getPrecedenceIfAny(aspect1, aspect2);
}
/**
* compares by precedence with the additional rule that a super-aspect is
* sorted before its sub-aspects
*/
public int compareByPrecedenceAndHierarchy(ResolvedType aspect1, ResolvedType aspect2) {
return precedenceCalculator.compareByPrecedenceAndHierarchy(aspect1, aspect2);
}
// simple property getter and setters
// ===========================================================
/**
* Nobody should hold onto a copy of this message handler, or setMessageHandler won't
* work right.
*/
public IMessageHandler getMessageHandler() {
return messageHandler;
}
public void setMessageHandler(IMessageHandler messageHandler) {
if (this.isInPinpointMode()) {
this.messageHandler = new PinpointingMessageHandler(messageHandler);
} else {
this.messageHandler = messageHandler;
}
}
/**
* convenenience method for creating and issuing messages via the message handler -
* if you supply two locations you will get two messages.
*/
public void showMessage(
Kind kind,
String message,
ISourceLocation loc1,
ISourceLocation loc2)
{
if (loc1 != null) {
messageHandler.handleMessage(new Message(message, kind, null, loc1));
if (loc2 != null) {
messageHandler.handleMessage(new Message(message, kind, null, loc2));
}
} else {
messageHandler.handleMessage(new Message(message, kind, null, loc2));
}
}
public void setCrossReferenceHandler(ICrossReferenceHandler xrefHandler) {
this.xrefHandler = xrefHandler;
}
/**
* Get the cross-reference handler for the world, may be null.
*/
public ICrossReferenceHandler getCrossReferenceHandler() {
return this.xrefHandler;
}
public void setTypeVariableLookupScope(TypeVariableDeclaringElement scope) {
this.typeVariableLookupScope = scope;
}
public TypeVariableDeclaringElement getTypeVariableLookupScope() {
return typeVariableLookupScope;
}
public List getDeclareParents() {
return crosscuttingMembersSet.getDeclareParents();
}
public List getDeclareAnnotationOnTypes() {
return crosscuttingMembersSet.getDeclareAnnotationOnTypes();
}
public List getDeclareAnnotationOnFields() {
return crosscuttingMembersSet.getDeclareAnnotationOnFields();
}
public List getDeclareAnnotationOnMethods() {
return crosscuttingMembersSet.getDeclareAnnotationOnMethods();
}
public List getDeclareSoft() {
return crosscuttingMembersSet.getDeclareSofts();
}
public CrosscuttingMembersSet getCrosscuttingMembersSet() {
return crosscuttingMembersSet;
}
public IHierarchy getModel() {
return model;
}
public void setModel(IHierarchy model) {
this.model = model;
}
public Lint getLint() {
return lint;
}
public void setLint(Lint lint) {
this.lint = lint;
}
public boolean isXnoInline() {
return XnoInline;
}
public void setXnoInline(boolean xnoInline) {
XnoInline = xnoInline;
}
public boolean isXlazyTjp() {
return XlazyTjp;
}
public void setXlazyTjp(boolean b) {
XlazyTjp = b;
}
public boolean isHasMemberSupportEnabled() {
return XhasMember;
}
public void setXHasMemberSupportEnabled(boolean b) {
XhasMember = b;
}
public boolean isInPinpointMode() {
return Xpinpoint;
}
public void setPinpointMode(boolean b) {
this.Xpinpoint = b;
}
public void setBehaveInJava5Way(boolean b) {
behaveInJava5Way = b;
}
public void performExtraConfiguration(String config) {
if (config==null) return;
// Bunch of name value pairs to split
extraConfiguration = new Properties();
int pos =-1;
while ((pos=config.indexOf(","))!=-1) {
String nvpair = config.substring(0,pos);
int pos2 = nvpair.indexOf("=");
if (pos2!=-1) {
String n = nvpair.substring(0,pos2);
String v = nvpair.substring(pos2+1);
extraConfiguration.setProperty(n,v);
}
config = config.substring(pos+1);
}
if (config.length()>0) {
int pos2 = config.indexOf("=");
if (pos2!=-1) {
String n = config.substring(0,pos2);
String v = config.substring(pos2+1);
extraConfiguration.setProperty(n,v);
}
}
}
/**
* may return null
*/
public Properties getExtraConfiguration() {
return extraConfiguration;
}
public final static String xsetCAPTURE_ALL_CONTEXT = "captureAllContext"; // default false
public boolean isInJava5Mode() {
return behaveInJava5Way;
}
public void setTargetAspectjRuntimeLevel(String s) {
targetAspectjRuntimeLevel = s;
}
public void setOptionalJoinpoints(String jps) {
if (jps==null) return;
if (jps.indexOf("arrayconstruction")!=-1) {
optionalJoinpoint_ArrayConstruction = true;
}
}
public boolean isJoinpointArrayConstructionEnabled() {
return optionalJoinpoint_ArrayConstruction;
}
public String getTargetAspectjRuntimeLevel() {
return targetAspectjRuntimeLevel;
}
public boolean isTargettingAspectJRuntime12() {
boolean b = false; // pr116679
if (!isInJava5Mode()) b=true;
else b = getTargetAspectjRuntimeLevel().equals(org.aspectj.weaver.Constants.RUNTIME_LEVEL_12);
//System.err.println("Asked if targetting runtime 1.2 , returning: "+b);
return b;
}
/*
* Map of types in the world, can have 'references' to expendable ones which
* can be garbage collected to recover memory.
* An expendable type is a reference type that is not exposed to the weaver (ie
* just pulled in for type resolution purposes).
*/
protected static class TypeMap {
private static boolean debug = false;
// Strategy for entries in the expendable map
public static int DONT_USE_REFS = 0; // Hang around forever
public static int USE_WEAK_REFS = 1; // Collected asap
public static int USE_SOFT_REFS = 2; // Collected when short on memory
// SECRETAPI - Can switch to a policy of choice ;)
public static int policy = USE_SOFT_REFS;
// Map of types that never get thrown away
private Map tMap = new HashMap();
// Map of types that may be ejected from the cache if we need space
private Map expendableMap = new WeakHashMap();
private World w;
// profiling tools...
private boolean memoryProfiling = false;
private int maxExpendableMapSize = -1;
private int collectedTypes = 0;
private ReferenceQueue rq = new ReferenceQueue();
TypeMap(World w) {
this.w = w;
memoryProfiling = false;// !w.getMessageHandler().isIgnoring(Message.INFO);
}
/**
* Add a new type into the map, the key is the type signature.
* Some types do *not* go in the map, these are ones involving
* *member* type variables. The reason is that when all you have is the
* signature which gives you a type variable name, you cannot
* guarantee you are using the type variable in the same way
* as someone previously working with a similarly
* named type variable. So, these do not go into the map:
* - TypeVariableReferenceType.
* - ParameterizedType where a member type variable is involved.
* - BoundedReferenceType when one of the bounds is a type variable.
*
* definition: "member type variables" - a tvar declared on a generic
* method/ctor as opposed to those you see declared on a generic type.
*/
public ResolvedType put(String key, ResolvedType type) {
if (type.isParameterizedType() && type.isParameterizedWithAMemberTypeVariable()) {
if (debug)
System.err.println("Not putting a parameterized type that utilises member declared type variables into the typemap: key="+key+" type="+type);
return type;
}
if (type.isTypeVariableReference()) {
if (debug)
System.err.println("Not putting a type variable reference type into the typemap: key="+key+" type="+type);
return type;
}
// this test should be improved - only avoid putting them in if one of the
// bounds is a member type variable
if (type instanceof BoundedReferenceType) {
if (debug)
System.err.println("Not putting a bounded reference type into the typemap: key="+key+" type="+type);
return type;
}
if (type instanceof MissingResolvedTypeWithKnownSignature) {
if (debug)
System.err.println("Not putting a missing type into the typemap: key="+key+" type="+type);
return type;
}
if ((type instanceof ReferenceType) && (((ReferenceType)type).getDelegate()==null) && w.isExpendable(type)) {
if (debug)
System.err.println("Not putting expendable ref type with null delegate into typemap: key="+key+" type="+type);
return type;
}
if (w.isExpendable(type)) {
// Dont use reference queue for tracking if not profiling...
if (policy==USE_WEAK_REFS) {
if (memoryProfiling) expendableMap.put(key,new WeakReference(type,rq));
else expendableMap.put(key,new WeakReference(type));
} else if (policy==USE_SOFT_REFS) {
if (memoryProfiling) expendableMap.put(key,new SoftReference(type,rq));
else expendableMap.put(key,new SoftReference(type));
} else {
expendableMap.put(key,type);
}
if (memoryProfiling && expendableMap.size()>maxExpendableMapSize) {
maxExpendableMapSize = expendableMap.size();
}
return type;
} else {
return (ResolvedType) tMap.put(key,type);
}
}
public void report() {
if (!memoryProfiling) return;
checkq();
w.getMessageHandler().handleMessage(MessageUtil.info("MEMORY: world expendable type map reached maximum size of #"+maxExpendableMapSize+" entries"));
w.getMessageHandler().handleMessage(MessageUtil.info("MEMORY: types collected through garbage collection #"+collectedTypes+" entries"));
}
public void checkq() {
if (!memoryProfiling) return;
while (rq.poll()!=null) collectedTypes++;
}
/** Lookup a type by its signature */
public ResolvedType get(String key) {
checkq();
ResolvedType ret = (ResolvedType) tMap.get(key);
if (ret == null) {
if (policy==USE_WEAK_REFS) {
WeakReference ref = (WeakReference)expendableMap.get(key);
if (ref != null) {
ret = (ResolvedType) ref.get();
}
} else if (policy==USE_SOFT_REFS) {
SoftReference ref = (SoftReference)expendableMap.get(key);
if (ref != null) {
ret = (ResolvedType) ref.get();
}
} else {
return (ResolvedType)expendableMap.get(key);
}
}
return ret;
}
/** Remove a type from the map */
public ResolvedType remove(String key) {
ResolvedType ret = (ResolvedType) tMap.remove(key);
if (ret == null) {
if (policy==USE_WEAK_REFS) {
WeakReference wref = (WeakReference)expendableMap.remove(key);
if (wref!=null) ret = (ResolvedType)wref.get();
return ret;
} else if (policy==USE_SOFT_REFS) {
SoftReference wref = (SoftReference)expendableMap.remove(key);
if (wref!=null) ret = (ResolvedType)wref.get();
return ret;
} else {
ret = (ResolvedType)expendableMap.remove(key);
return ret;
}
}
return ret;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("types:\n");
sb.append(dumpthem(tMap));
sb.append("expendables:\n");
sb.append(dumpthem(expendableMap));
return sb.toString();
}
private String dumpthem(Map m) {
StringBuffer sb = new StringBuffer();
int otherTypes = 0;
int bcelDel = 0;
int refDel = 0;
for (Iterator iter = m.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
Object val = entry.getValue();
if (val instanceof WeakReference) {
val = ((WeakReference)val).get();
} else
if (val instanceof SoftReference) {
val = ((SoftReference)val).get();
}
sb.append(entry.getKey()+"="+val).append("\n");
if (val instanceof ReferenceType) {
ReferenceType refType = (ReferenceType)val;
if (refType.getDelegate() instanceof BcelObjectType) {
bcelDel++;
} else if (refType.getDelegate() instanceof ReflectionBasedReferenceTypeDelegate) {
refDel++;
} else {
otherTypes++;
}
} else {
otherTypes++;
}
}
sb.append("# BCEL = "+bcelDel+", # REF = "+refDel+", # Other = "+otherTypes);
return sb.toString();
}
public int totalSize() {
return tMap.size()+expendableMap.size();
}
public int hardSize() {
return tMap.size();
}
}
/** Reference types we don't intend to weave may be ejected from
* the cache if we need the space.
*/
protected boolean isExpendable(ResolvedType type) {
return (
!type.equals(UnresolvedType.OBJECT) &&
(type != null) &&
(!type.isExposedToWeaver()) &&
(!type.isPrimitiveType())
);
}
/**
* This class is used to compute and store precedence relationships between
* aspects.
*/
private static class AspectPrecedenceCalculator {
private World world;
private Map cachedResults;
public AspectPrecedenceCalculator(World forSomeWorld) {
this.world = forSomeWorld;
this.cachedResults = new HashMap();
}
/**
* Ask every declare precedence in the world to order the two aspects.
* If more than one declare precedence gives an ordering, and the orderings
* conflict, then that's an error.
*/
public int compareByPrecedence(ResolvedType firstAspect, ResolvedType secondAspect) {
PrecedenceCacheKey key = new PrecedenceCacheKey(firstAspect,secondAspect);
if (cachedResults.containsKey(key)) {
return ((Integer) cachedResults.get(key)).intValue();
} else {
int order = 0;
DeclarePrecedence orderer = null; // Records the declare precedence statement that gives the first ordering
for (Iterator i = world.getCrosscuttingMembersSet().getDeclareDominates().iterator(); i.hasNext(); ) {
DeclarePrecedence d = (DeclarePrecedence)i.next();
int thisOrder = d.compare(firstAspect, secondAspect);
if (thisOrder != 0) {
if (orderer==null) orderer = d;
if (order != 0 && order != thisOrder) {
ISourceLocation[] isls = new ISourceLocation[2];
isls[0]=orderer.getSourceLocation();
isls[1]=d.getSourceLocation();
Message m =
new Message("conflicting declare precedence orderings for aspects: "+
firstAspect.getName()+" and "+secondAspect.getName(),null,true,isls);
world.getMessageHandler().handleMessage(m);
} else {
order = thisOrder;
}
}
}
cachedResults.put(key, new Integer(order));
return order;
}
}
public Integer getPrecedenceIfAny(ResolvedType aspect1,ResolvedType aspect2) {
return (Integer)cachedResults.get(new PrecedenceCacheKey(aspect1,aspect2));
}
public int compareByPrecedenceAndHierarchy(ResolvedType firstAspect, ResolvedType secondAspect) {
if (firstAspect.equals(secondAspect)) return 0;
int ret = compareByPrecedence(firstAspect, secondAspect);
if (ret != 0) return ret;
if (firstAspect.isAssignableFrom(secondAspect)) return -1;
else if (secondAspect.isAssignableFrom(firstAspect)) return +1;
return 0;
}
private static class PrecedenceCacheKey {
public ResolvedType aspect1;
public ResolvedType aspect2;
public PrecedenceCacheKey(ResolvedType a1, ResolvedType a2) {
this.aspect1 = a1;
this.aspect2 = a2;
}
public boolean equals(Object obj) {
if (!(obj instanceof PrecedenceCacheKey)) return false;
PrecedenceCacheKey other = (PrecedenceCacheKey) obj;
return (aspect1 == other.aspect1 && aspect2 == other.aspect2);
}
public int hashCode() {
return aspect1.hashCode() + aspect2.hashCode();
}
}
}
public void validateType(UnresolvedType type) { }
// --- with java5 we can get into a recursive mess if we aren't careful when resolving types (*cough* java.lang.Enum) ---
// --- this first map is for java15 delegates which may try and recursively access the same type variables.
// --- I would rather stash this against a reference type - but we don't guarantee referencetypes are unique for
// so we can't :(
private Map workInProgress1 = new HashMap();
public TypeVariable[] getTypeVariablesCurrentlyBeingProcessed(Class baseClass) {
return (TypeVariable[])workInProgress1.get(baseClass);
}
public void recordTypeVariablesCurrentlyBeingProcessed(Class baseClass, TypeVariable[] typeVariables) {
workInProgress1.put(baseClass,typeVariables);
}
public void forgetTypeVariablesCurrentlyBeingProcessed(Class baseClass) {
workInProgress1.remove(baseClass);
}
public void flush() {
// System.err.println("BEFORE FLUSHING");
// System.err.println(typeMap.toString());
typeMap.expendableMap.clear();
// System.err.println("AFTER FLUSHING");
// System.err.println(typeMap.toString());
// System.gc();
System.gc();
}
// ---
}
|
101,411 |
Bug 101411 SerialVersionUID handling
|
from emails - needs a decision --------------- Hi Andy is there a way for the weaver to add to weaved classes the serial ver uid field based on the pre-weaved bytecode computation. Right now it issues lint warning when a Serializable class without serial ver uid is encountered and due to evil #75442 this is very annoying for LTW. A first step would be to at least deal with that when we had the perObbjectTypeMunger (then should not change any kind previous stuff). Alex ------------ Andy, Generating the suid sounds like a nice idea but the code the JVM used is private inside ObjectStreamClass. Also we need to take care with ITD fields to ensure correct behaviour when sending and receiving from non-woven classes. Basically the programmer needs to be engaged, it only affects serializable classes and in 1.5 there is a warning if you don't declare the field so there is a strong hint to the programmer to solve the problem. For LTW we should make an enhancement to allow the user to configure Lint and other things. For example they may or may not be interested in advice not matching. Matthew Webster ---------------------- Alex, We should make a distinction between benign changes to suid and those that affect members. Generating suid when we add a static initializer (to support thisJoinPoint or the staticinitialization join point), accessor methods for privileged aspects or transient per-fields is OK. Doing for ITDs is more problematic. Matthew Webster
|
resolved fixed
|
6e6658a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-09T17:24:19Z | 2005-06-23T07:00:00Z |
weaver/src/org/aspectj/weaver/bcel/LazyClassGen.java
|
/* *******************************************************************
* Copyright (c) 2002 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:
* PARC initial implementation
* Andy Clement 6Jul05 generics - signature attribute
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.Attribute;
import org.aspectj.apache.bcel.classfile.ConstantUtf8;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.classfile.Unknown;
import org.aspectj.apache.bcel.classfile.annotation.Annotation;
import org.aspectj.apache.bcel.generic.ClassGen;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.FieldGen;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.PUSH;
import org.aspectj.apache.bcel.generic.RETURN;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.apache.bcel.generic.annotation.AnnotationGen;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.util.CollectionUtil;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.World;
import org.aspectj.weaver.AjAttribute.WeaverVersionInfo;
/**
* Lazy lazy lazy.
* We don't unpack the underlying class unless necessary. Things
* like new methods and annotations accumulate in here until they
* must be written out, don't add them to the underlying MethodGen!
* Things are slightly different if this represents an Aspect.
*/
public final class LazyClassGen {
int highestLineNumber = 0; // ---- JSR 45 info
private SortedMap /* <String, InlinedSourceFileInfo> */ inlinedFiles = new TreeMap();
private boolean regenerateGenericSignatureAttribute = false;
private BcelObjectType myType; // XXX is not set for types we create
private ClassGen myGen;
private ConstantPoolGen constantPoolGen;
private World world;
private String packageName = null;
private List /*LazyMethodGen*/ methodGens = new ArrayList();
private List /*LazyClassGen*/ classGens = new ArrayList();
private List /*AnnotationGen*/ annotations = new ArrayList();
private int childCounter = 0;
private InstructionFactory fact;
private boolean isSerializable = false;
private boolean hasSerialVersionUIDField = false;
private boolean hasClinit = false;
// ---
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);
UnresolvedType ut = UnresolvedType.forName(name);
ut.setNeedsModifiableDelegate(true);
LazyClassGen clazz = new LazyClassGen(BcelWorld.getBcelObjectType(world.resolve(ut)));
clazz.print(out);
out.println();
}
public int getNewGeneratedNameTag() {
return childCounter++;
}
// ----
public LazyClassGen(
String class_name,
String super_class_name,
String file_name,
int access_flags,
String[] interfaces,
World world)
{
myGen = new ClassGen(class_name, super_class_name, file_name, access_flags, interfaces);
constantPoolGen = myGen.getConstantPool();
fact = new InstructionFactory(myGen, constantPoolGen);
regenerateGenericSignatureAttribute = true;
this.world = world;
}
//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;
this.world = myType.getResolvedTypeX().getWorld();
/* Does this class support serialization */
if (implementsSerializable(getType())) {
isSerializable = true;
// ResolvedMember[] fields = getType().getDeclaredFields();
// for (int i = 0; i < fields.length; i++) {
// ResolvedMember field = fields[i];
// if (field.getName().equals("serialVersionUID")
// && field.isStatic() && field.getType().equals(ResolvedType.LONG)) {
// hasSerialVersionUIDField = true;
// }
// }
hasSerialVersionUIDField = hasSerialVersionUIDField(getType());
ResolvedMember[] methods = getType().getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
ResolvedMember method = methods[i];
if (method.getName().equals("<clinit>")) {
hasClinit = true;
}
}
}
Method[] methods = myGen.getMethods();
for (int i = 0; i < methods.length; i++) {
addMethodGen(new LazyMethodGen(methods[i], this));
}
}
public static boolean hasSerialVersionUIDField (ResolvedType type) {
ResolvedMember[] fields = type.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
ResolvedMember field = fields[i];
if (field.getName().equals("serialVersionUID")
&& field.isStatic() && field.getType().equals(ResolvedType.LONG)) {
return true;
}
}
return false;
}
// public void addAttribute(Attribute i) {
// myGen.addAttribute(i);
// }
// ----
public String getInternalClassName() {
return getConstantPoolGen().getConstantPool().getConstantString(
myGen.getClassNameIndex(),
Constants.CONSTANT_Class);
}
public String getInternalFileName() {
String str = getInternalClassName();
int index = str.lastIndexOf('/');
if (index == -1) {
return getFileName();
} else {
return str.substring(0, index + 1) + getFileName();
}
}
public File getPackagePath(File root) {
String str = getInternalClassName();
int index = str.lastIndexOf('/');
if (index == -1)
return root;
return new File(root, str.substring(0, index));
}
/** Returns the packagename - if its the default package we return an empty string
*/
public String getPackageName() {
if (packageName!=null) return packageName;
String str = getInternalClassName();
int index = str.indexOf("<");
if (index!=-1) str = str.substring(0,index); // strip off the generics guff
index= str.lastIndexOf("/");
if (index==-1) return "";
return str.substring(0,index).replace('/','.');
}
public String getClassId() {
String str = getInternalClassName();
int index = str.lastIndexOf('/');
if (index == -1)
return str;
return str.substring(index + 1);
}
public void addMethodGen(LazyMethodGen gen) {
//assert gen.getClassName() == super.getClassName();
methodGens.add(gen);
if (highestLineNumber < gen.highestLineNumber) highestLineNumber = gen.highestLineNumber;
}
public void addMethodGen(LazyMethodGen gen, ISourceLocation sourceLocation) {
addMethodGen(gen);
if (!gen.getMethod().isPrivate()) {
warnOnAddedMethod(gen.getMethod(),sourceLocation);
}
}
public void errorOnAddedField (Field field, ISourceLocation sourceLocation) {
if (isSerializable && !hasSerialVersionUIDField) {
getWorld().getLint().serialVersionUIDBroken.signal(
new String[] {
myType.getResolvedTypeX().getName().toString(),
field.getName()
},
sourceLocation,
null);
}
}
public void warnOnAddedInterface (String name, ISourceLocation sourceLocation) {
warnOnModifiedSerialVersionUID(sourceLocation,"added interface " + name);
}
public void warnOnAddedMethod (Method method, ISourceLocation sourceLocation) {
warnOnModifiedSerialVersionUID(sourceLocation,"added non-private method " + method.getName());
}
public void warnOnAddedStaticInitializer (Shadow shadow, ISourceLocation sourceLocation) {
if (!hasClinit) {
warnOnModifiedSerialVersionUID(sourceLocation,"added static initializer");
}
}
public void warnOnModifiedSerialVersionUID (ISourceLocation sourceLocation, String reason) {
if (isSerializable && !hasSerialVersionUIDField)
getWorld().getLint().needsSerialVersionUIDField.signal(
new String[] {
myType.getResolvedTypeX().getName().toString(),
reason
},
sourceLocation,
null);
}
public World getWorld () {
return world;
}
public List getMethodGens() {
return methodGens; //???Collections.unmodifiableList(methodGens);
}
// FIXME asc Should be collection returned here
public Field[] getFieldGens() {
return myGen.getFields();
}
public Field getField(String name) {
Field[] allFields = myGen.getFields();
if (allFields==null) return null;
for (int i = 0; i < allFields.length; i++) {
Field field = allFields[i];
if (field.getName().equals(name)) return field;
}
return null;
}
// FIXME asc How do the ones on the underlying class surface if this just returns new ones added?
// FIXME asc ...although no one calls this right now !
public List getAnnotations() {
return annotations;
}
private void writeBack(BcelWorld world) {
if (getConstantPoolGen().getSize() > Short.MAX_VALUE) {
reportClassTooBigProblem();
return;
}
if (annotations.size()>0) {
for (Iterator iter = annotations.iterator(); iter.hasNext();) {
AnnotationGen element = (AnnotationGen) iter.next();
myGen.addAnnotation(element);
}
// Attribute[] annAttributes = org.aspectj.apache.bcel.classfile.Utility.getAnnotationAttributes(getConstantPoolGen(),annotations);
// for (int i = 0; i < annAttributes.length; i++) {
// Attribute attribute = annAttributes[i];
// System.err.println("Adding attribute for "+attribute);
// myGen.addAttribute(attribute);
// }
}
// Add a weaver version attribute to the file being produced (if necessary...)
boolean hasVersionAttribute = false;
Attribute[] attrs = myGen.getAttributes();
for (int i = 0; i < attrs.length && !hasVersionAttribute; i++) {
Attribute attribute = attrs[i];
if (attribute.getName().equals("org.aspectj.weaver.WeaverVersion")) hasVersionAttribute=true;
}
if (!hasVersionAttribute)
myGen.addAttribute(BcelAttributes.bcelAttribute(new AjAttribute.WeaverVersionInfo(),getConstantPoolGen()));
if (myType != null && myType.getWeaverState() != null) {
myGen.addAttribute(BcelAttributes.bcelAttribute(
new AjAttribute.WeaverState(myType.getWeaverState()),
getConstantPoolGen()));
}
//FIXME ATAJ needed only for slow Aspects.aspectOf() - keep or remove
//make a lot of test fail since the test compare weaved class file
// based on some test data as text files...
// if (!myGen.isInterface()) {
// addAjClassField();
// }
addAjcInitializers();
int len = methodGens.size();
myGen.setMethods(new Method[0]);
calculateSourceDebugExtensionOffsets();
for (int i = 0; i < len; i++) {
LazyMethodGen gen = (LazyMethodGen) methodGens.get(i);
// we skip empty clinits
if (isEmptyClinit(gen)) continue;
myGen.addMethod(gen.getMethod());
}
if (inlinedFiles.size() != 0) {
if (hasSourceDebugExtensionAttribute(myGen)) {
world.showMessage(
IMessage.WARNING,
WeaverMessages.format(WeaverMessages.OVERWRITE_JSR45,getFileName()),
null,
null);
}
// 17Feb05 - ASC - Skip this for now - it crashes IBM 1.4.2 jvms (pr80430). Will be revisited when contents
// of attribute are confirmed to be correct.
// myGen.addAttribute(getSourceDebugExtensionAttribute());
}
fixupGenericSignatureAttribute();
}
/**
* When working with 1.5 generics, a signature attribute is attached to the type which indicates
* how it was declared. This routine ensures the signature attribute for what we are about
* to write out is correct. Basically its responsibilities are:
* 1. Checking whether the attribute needs changing (i.e. did weaving change the type hierarchy)
* 2. If it did, removing the old attribute
* 3. Check if we need an attribute at all, are we generic? are our supertypes parameterized/generic?
* 4. Build the new attribute which includes all typevariable, supertype and superinterface information
*/
private void fixupGenericSignatureAttribute () {
if (getWorld() != null && !getWorld().isInJava5Mode()) return;
// TODO asc generics Temporarily assume that types we generate dont need a signature attribute (closure/etc).. will need revisiting no doubt...
if (myType==null) return;
// 1. Has anything changed that would require us to modify this attribute?
if (!regenerateGenericSignatureAttribute) return;
// 2. Find the old attribute
Signature sigAttr = null;
if (myType!=null) { // if null, this is a type built from scratch, it won't already have a sig attribute
Attribute[] as = myGen.getAttributes();
for (int i = 0; i < as.length; i++) {
Attribute attribute = as[i];
if (attribute.getName().equals("Signature")) sigAttr = (Signature)attribute;
}
}
// 3. Do we need an attribute?
boolean needAttribute = false;
if (sigAttr!=null) needAttribute = true; // If we had one before, we definetly still need one as types can't be 'removed' from the hierarchy
// check the interfaces
if (!needAttribute) {
if (myType==null) {
boolean stop = true;
}
ResolvedType[] interfaceRTXs = myType.getDeclaredInterfaces();
for (int i = 0; i < interfaceRTXs.length; i++) {
ResolvedType typeX = interfaceRTXs[i];
if (typeX.isGenericType() || typeX.isParameterizedType()) needAttribute = true;
}
// check the supertype
ResolvedType superclassRTX = myType.getSuperclass();
if (superclassRTX.isGenericType() || superclassRTX.isParameterizedType()) needAttribute = true;
}
if (needAttribute) {
StringBuffer signature = new StringBuffer();
// first, the type variables...
TypeVariable[] tVars = myType.getTypeVariables();
if (tVars.length>0) {
signature.append("<");
for (int i = 0; i < tVars.length; i++) {
TypeVariable variable = tVars[i];
if (i!=0) signature.append(",");
signature.append(variable.getSignature());
}
signature.append(">");
}
// now the supertype
String supersig = myType.getSuperclass().getSignatureForAttribute();
signature.append(supersig);
ResolvedType[] interfaceRTXs = myType.getDeclaredInterfaces();
for (int i = 0; i < interfaceRTXs.length; i++) {
String s = interfaceRTXs[i].getSignatureForAttribute();
signature.append(s);
}
if (sigAttr!=null) myGen.removeAttribute(sigAttr);
myGen.addAttribute(createSignatureAttribute(signature.toString()));
}
}
/**
* Helper method to create a signature attribute based on a string signature:
* e.g. "Ljava/lang/Object;LI<Ljava/lang/Double;>;"
*/
private Signature createSignatureAttribute(String signature) {
int nameIndex = constantPoolGen.addUtf8("Signature");
int sigIndex = constantPoolGen.addUtf8(signature);
return new Signature(nameIndex,2,sigIndex,constantPoolGen.getConstantPool());
}
/**
*
*/
private void reportClassTooBigProblem() {
// PR 59208
// we've generated a class that is just toooooooooo big (you've been generating programs
// again haven't you? come on, admit it, no-one writes classes this big by hand).
// create an empty myGen so that we can give back a return value that doesn't upset the
// rest of the process.
myGen = new ClassGen(myGen.getClassName(), myGen.getSuperclassName(),
myGen.getFileName(), myGen.getAccessFlags(), myGen.getInterfaceNames());
// raise an error against this compilation unit.
getWorld().showMessage(
IMessage.ERROR,
WeaverMessages.format(WeaverMessages.CLASS_TOO_BIG,
this.getClassName()),
new SourceLocation(new File(myGen.getFileName()),0), null
);
}
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 byte [] getJavaClassBytesIncludingReweavable(BcelWorld world){
writeBack(world);
byte [] wovenClassFileData = myGen.getJavaClass().getBytes();
WeaverStateInfo wsi = myType.getWeaverState();//getOrCreateWeaverStateInfo();
if(wsi != null && wsi.isReweavable()){ // && !reweavableDataInserted
//reweavableDataInserted = true;
return wsi.replaceKeyWithDiff(wovenClassFileData);
} else{
return wovenClassFileData;
}
}
public void addGeneratedInner(LazyClassGen newClass) {
classGens.add(newClass);
}
public void addInterface(UnresolvedType typeX, ISourceLocation sourceLocation) {
regenerateGenericSignatureAttribute = true;
myGen.addInterface(typeX.getRawName());
if (!typeX.equals(UnresolvedType.SERIALIZABLE))
warnOnAddedInterface(typeX.getName(),sourceLocation);
}
public void setSuperClass(ResolvedType typeX) {
regenerateGenericSignatureAttribute = true;
myType.addParent(typeX); // used for the attribute
if (typeX.getGenericType()!=null) typeX = typeX.getGenericType();
myGen.setSuperclassName(typeX.getName()); // used in the real class data
}
public String getSuperClassname() {
return myGen.getSuperclassName();
}
// FIXME asc not great that some of these ask the gen and some ask the type ! (see the related setters too)
public ResolvedType getSuperClass() {
return myType.getSuperclass();
}
public String[] getInterfaceNames() {
return myGen.getInterfaceNames();
}
// non-recursive, may be a bug, ha ha.
private List getClassGens() {
List ret = new ArrayList();
ret.add(this);
ret.addAll(classGens);
return ret;
}
public List getChildClasses(BcelWorld world) {
if (classGens.isEmpty()) return Collections.EMPTY_LIST;
List ret = new ArrayList();
for (Iterator i = classGens.iterator(); i.hasNext();) {
LazyClassGen clazz = (LazyClassGen) i.next();
byte[] bytes = clazz.getJavaClass(world).getBytes();
String name = clazz.getName();
int index = name.lastIndexOf('$');
// XXX this could be bad, check use of dollar signs.
name = name.substring(index+1);
ret.add(new UnwovenClassFile.ChildClass(name, bytes));
}
return ret;
}
public String toString() {
return toShortString();
}
public String toShortString() {
String s =
org.aspectj.apache.bcel.classfile.Utility.accessToString(myGen.getAccessFlags(), true);
if (s != "")
s += " ";
s += org.aspectj.apache.bcel.classfile.Utility.classOrInterface(myGen.getAccessFlags());
s += " ";
s += myGen.getClassName();
return s;
}
public String toLongString() {
ByteArrayOutputStream s = new ByteArrayOutputStream();
print(new PrintStream(s));
return new String(s.toByteArray());
}
public void print() { print(System.out); }
public void print(PrintStream out) {
List classGens = getClassGens();
for (Iterator iter = classGens.iterator(); iter.hasNext();) {
LazyClassGen element = (LazyClassGen) iter.next();
element.printOne(out);
if (iter.hasNext()) out.println();
}
}
private void printOne(PrintStream out) {
out.print(toShortString());
out.print(" extends ");
out.print(
org.aspectj.apache.bcel.classfile.Utility.compactClassName(
myGen.getSuperclassName(),
false));
int size = myGen.getInterfaces().length;
if (size > 0) {
out.print(" implements ");
for (int i = 0; i < size; i++) {
out.print(myGen.getInterfaceNames()[i]);
if (i < size - 1)
out.print(", ");
}
}
out.print(":");
out.println();
// XXX make sure to pass types correctly around, so this doesn't happen.
if (myType != null) {
myType.printWackyStuff(out);
}
Field[] fields = myGen.getFields();
for (int i = 0, len = fields.length; i < len; i++) {
out.print(" ");
out.println(fields[i]);
}
List methodGens = getMethodGens();
for (Iterator iter = methodGens.iterator(); iter.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) iter.next();
// we skip empty clinits
if (isEmptyClinit(gen)) continue;
gen.print(out, (myType != null ? myType.getWeaverVersionAttribute() : WeaverVersionInfo.UNKNOWN));
if (iter.hasNext()) out.println();
}
// out.println(" ATTRIBS: " + Arrays.asList(myGen.getAttributes()));
out.println("end " + toShortString());
}
private boolean isEmptyClinit(LazyMethodGen gen) {
if (!gen.getName().equals("<clinit>")) return false;
//System.err.println("checking clinig: " + gen);
InstructionHandle start = gen.getBody().getStart();
while (start != null) {
if (Range.isRangeHandle(start) || (start.getInstruction() instanceof RETURN)) {
start = start.getNext();
} else {
return false;
}
}
return true;
}
public ConstantPoolGen getConstantPoolGen() {
return constantPoolGen;
}
public String getName() {
return myGen.getClassName();
}
public boolean isWoven() {
return myType.getWeaverState() != null;
}
public boolean isReweavable() {
if (myType.getWeaverState()==null) return true;
return myType.getWeaverState().isReweavable();
}
public Set getAspectsAffectingType() {
if (myType.getWeaverState()==null) return null;
return myType.getWeaverState().getAspectsAffectingType();
}
public WeaverStateInfo getOrCreateWeaverStateInfo(boolean inReweavableMode) {
WeaverStateInfo ret = myType.getWeaverState();
if (ret != null) return ret;
ret = new WeaverStateInfo(inReweavableMode);
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 proceedingTjpType =
new ObjectType("org.aspectj.lang.ProceedingJoinPoint");
public static final ObjectType tjpType =
new ObjectType("org.aspectj.lang.JoinPoint");
public static final ObjectType staticTjpType =
new ObjectType("org.aspectj.lang.JoinPoint$StaticPart");
public static final ObjectType enclosingStaticTjpType =
new ObjectType("org.aspectj.lang.JoinPoint$EnclosingStaticPart");
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, final boolean isEnclosingJp) {
Field ret = (Field)tjpFields.get(shadow);
if (ret != null) return ret;
int modifiers = Modifier.STATIC | Modifier.FINAL;
// XXX - Do we ever inline before or after advice? If we do, then we
// better include them in the check below. (or just change it to
// shadow.getEnclosingMethod().getCanInline())
// If the enclosing method is around advice, we could inline the join point
// that has led to this shadow. If we do that then the TJP we are creating
// here must be PUBLIC so it is visible to the type in which the
// advice is inlined. (PR71377)
LazyMethodGen encMethod = shadow.getEnclosingMethod();
boolean shadowIsInAroundAdvice = false;
if (encMethod!=null && encMethod.getName().startsWith(NameMangler.PREFIX+"around")) {
shadowIsInAroundAdvice = true;
}
if (getType().isInterface() || shadowIsInAroundAdvice) {
modifiers |= Modifier.PUBLIC;
}
else {
modifiers |= Modifier.PRIVATE;
}
ObjectType jpType = null;
if (world.isTargettingAspectJRuntime12()) { // TAG:SUPPORTING12: We didn't have different staticjp types in 1.2
jpType = staticTjpType;
} else {
jpType = isEnclosingJp?enclosingStaticTjpType:staticTjpType;
}
ret = new FieldGen(modifiers,jpType,"ajc$tjp_" + tjpFields.size(),getConstantPoolGen()).getField();
addField(ret);
tjpFields.put(shadow, ret);
return ret;
}
//FIXME ATAJ needed only for slow Aspects.aspectOf - keep or remove
// private void addAjClassField() {
// // Andy: Why build it again??
// Field ajClassField = new FieldGen(
// Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC,
// classType,
// "aj$class",
// getConstantPoolGen()).getField();
// addField(ajClassField);
//
// InstructionList il = new InstructionList();
// il.append(new PUSH(getConstantPoolGen(), getClassName()));
// il.append(fact.createInvoke("java.lang.Class", "forName", classType,
// new Type[] {Type.STRING}, Constants.INVOKESTATIC));
// il.append(fact.createFieldAccess(getClassName(), ajClassField.getName(),
// classType, Constants.PUTSTATIC));
//
// getStaticInitializer().getBody().insert(il);
// }
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));
if (world.isTargettingAspectJRuntime12()) { // TAG:SUPPORTING12: We didn't have optimized factory methods in 1.2
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));
} else if (sig.getKind().equals(Member.METHOD)) {
BcelWorld w = shadow.getWorld();
// For methods, push the parts of the signature on.
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w))));
list.append(new PUSH(getConstantPoolGen(),sig.getName()));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterNames(w))));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getExceptions(w))));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getReturnType())));
// And generate a call to the variant of makeMethodSig() that takes 7 strings
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING,Type.STRING,Type.STRING,Type.STRING,Type.STRING,Type.STRING,Type.STRING },
Constants.INVOKEVIRTUAL));
} else if (sig.getKind().equals(Member.HANDLER)) {
BcelWorld w = shadow.getWorld();
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterNames(w))));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING, Type.STRING, Type.STRING },
Constants.INVOKEVIRTUAL));
} else if(sig.getKind().equals(Member.CONSTRUCTOR)) {
BcelWorld w = shadow.getWorld();
if (w.isJoinpointArrayConstructionEnabled() && sig.getDeclaringType().isArray()) {
// its the magical new jp
list.append(new PUSH(getConstantPoolGen(),makeString(Modifier.PUBLIC)));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes())));
list.append(new PUSH(getConstantPoolGen(),""));//makeString("")));//sig.getParameterNames(w))));
list.append(new PUSH(getConstantPoolGen(),""));//makeString("")));//sig.getExceptions(w))));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING },
Constants.INVOKEVIRTUAL));
} else {
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w))));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterNames(w))));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getExceptions(w))));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING },
Constants.INVOKEVIRTUAL));
}
} else if(sig.getKind().equals(Member.FIELD)) {
BcelWorld w = shadow.getWorld();
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w))));
list.append(new PUSH(getConstantPoolGen(),sig.getName()));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getReturnType())));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING, Type.STRING, Type.STRING, Type.STRING },
Constants.INVOKEVIRTUAL));
} else if(sig.getKind().equals(Member.ADVICE)) {
BcelWorld w = shadow.getWorld();
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w))));
list.append(new PUSH(getConstantPoolGen(),sig.getName()));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterTypes())));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getParameterNames(w))));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getExceptions(w))));
list.append(new PUSH(getConstantPoolGen(),makeString((sig.getReturnType()))));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING, Type.STRING },
Constants.INVOKEVIRTUAL));
} else if(sig.getKind().equals(Member.STATIC_INITIALIZATION)) {
BcelWorld w = shadow.getWorld();
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getModifiers(w))));
list.append(new PUSH(getConstantPoolGen(),makeString(sig.getDeclaringType())));
list.append(fact.createInvoke(factoryType.getClassName(),
sig.getSignatureMakerName(),
new ObjectType(sig.getSignatureType()),
new Type[] { Type.STRING, Type.STRING },
Constants.INVOKEVIRTUAL));
} else {
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()));
final String factoryMethod;
if (world.isTargettingAspectJRuntime12()) { // TAG:SUPPORTING12: We didn't have makeESJP() in 1.2
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));
} else {
if (staticTjpType.equals(field.getType())) {
factoryMethod = "makeSJP";
} else if (enclosingStaticTjpType.equals(field.getType())) {
factoryMethod = "makeESJP";
} else {
throw new Error("should not happen");
}
list.append(fact.createInvoke(factoryType.getClassName(),
factoryMethod, field.getType(),
new Type[] { Type.STRING, sigType, Type.INT},
Constants.INVOKEVIRTUAL));
// put it in the field
list.append(fact.createFieldAccess(getClassName(), field.getName(), field.getType(), Constants.PUTSTATIC));
}
}
protected String makeString(int i) {
return Integer.toString(i, 16); //??? expensive
}
protected String makeString(UnresolvedType t) {
// this is the inverse of the odd behavior for Class.forName w/ arrays
if (t.isArray()) {
// this behavior matches the string used by the eclipse compiler for Foo.class literals
return t.getSignature().replace('/', '.');
} else {
return t.getName();
}
}
protected String makeString(UnresolvedType[] types) {
if (types == null) return "";
StringBuffer buf = new StringBuffer();
for (int i = 0, len=types.length; i < len; i++) {
buf.append(makeString(types[i]));
buf.append(':');
}
return buf.toString();
}
protected String makeString(String[] names) {
if (names == null) return "";
StringBuffer buf = new StringBuffer();
for (int i = 0, len=names.length; i < len; i++) {
buf.append(names[i]);
buf.append(':');
}
return buf.toString();
}
public ResolvedType getType() {
if (myType == null) return null;
return myType.getResolvedTypeX();
}
public BcelObjectType getBcelObjectType() {
return myType;
}
public String getFileName() {
return myGen.getFileName();
}
private void addField(Field field) {
myGen.addField(field);
}
public void replaceField(Field oldF, Field newF){
myGen.removeField(oldF);
myGen.addField(newF);
}
public void addField(Field field, ISourceLocation sourceLocation) {
addField(field);
if (!(field.isPrivate()
&& (field.isStatic() || field.isTransient()))) {
errorOnAddedField(field,sourceLocation);
}
}
public String getClassName() {
return myGen.getClassName();
}
public boolean isInterface() {
return myGen.isInterface();
}
public boolean isAbstract() {
return myGen.isAbstract();
}
public LazyMethodGen getLazyMethodGen(Member m) {
return getLazyMethodGen(m.getName(), m.getSignature(),false);
}
public LazyMethodGen getLazyMethodGen(String name, String signature) {
return getLazyMethodGen(name,signature,false);
}
public LazyMethodGen getLazyMethodGen(String name, String signature,boolean allowMissing) {
for (Iterator i = methodGens.iterator(); i.hasNext();) {
LazyMethodGen gen = (LazyMethodGen) i.next();
if (gen.getName().equals(name) && gen.getSignature().equals(signature))
return gen;
}
if (!allowMissing) {
throw new BCException("Class " + this.getName() + " does not have a method "
+ name + " with signature " + signature);
}
return null;
}
public void forcePublic() {
myGen.setAccessFlags(Utility.makePublic(myGen.getAccessFlags()));
}
public boolean hasAnnotation(UnresolvedType t) {
// annotations on the real thing
AnnotationGen agens[] = myGen.getAnnotations();
if (agens==null) return false;
for (int i = 0; i < agens.length; i++) {
AnnotationGen gen = agens[i];
if (t.equals(UnresolvedType.forSignature(gen.getTypeSignature()))) return true;
}
// annotations added during this weave
return false;
}
public void addAnnotation(Annotation a) {
if (!hasAnnotation(UnresolvedType.forSignature(a.getTypeSignature()))) {
annotations.add(new AnnotationGen(a,getConstantPoolGen(),true));
}
}
// this test is like asking:
// if (UnresolvedType.SERIALIZABLE.resolve(getType().getWorld()).isAssignableFrom(getType())) {
// only we don't do that because this forces us to find all the supertypes of the type,
// and if one of them is missing we fail, and it's not worth failing just to put out
// a warning message!
private boolean implementsSerializable(ResolvedType aType) {
ResolvedType[] interfaces = aType.getDeclaredInterfaces();
for (int i = 0; i < interfaces.length; i++) {
if (interfaces[i].getSignature().equals(UnresolvedType.SERIALIZABLE.getSignature())) {
return true;
} else {
if (interfaces[i].isMissing()) continue;
ResolvedType superInterface = interfaces[i].getSuperclass();
if (superInterface != null && !superInterface.isMissing()) {
if (implementsSerializable(superInterface)) return true;
}
}
}
ResolvedType superType = aType.getSuperclass();
if (superType != null && !superType.isMissing()) {
return implementsSerializable(superType);
}
return false;
}
}
|
131,505 |
Bug 131505 Generated aop.xml files contain aspects for all the projects ever built
|
Using the -outxml option in AJDT the generated aop.xml files are not correct after the first build and contain all the aspects that have ever been built (including those in different projects and duplicates if an aspect has been built twice). It seems that there is a global list of aspects (aspectNames in AjBuildManager) that is never cleared.
|
resolved fixed
|
b3cd01d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-15T12:34:48Z | 2006-03-13T11:40:00Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the 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.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import org.aspectj.ajdt.internal.compiler.AjCompilerAdapter;
import org.aspectj.ajdt.internal.compiler.IBinarySourceProvider;
import org.aspectj.ajdt.internal.compiler.ICompilerAdapter;
import org.aspectj.ajdt.internal.compiler.ICompilerAdapterFactory;
import org.aspectj.ajdt.internal.compiler.IIntermediateResultsRequestor;
import org.aspectj.ajdt.internal.compiler.IOutputClassFileNameProvider;
import org.aspectj.ajdt.internal.compiler.InterimCompilationResult;
import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment;
import org.aspectj.ajdt.internal.compiler.lookup.AnonymousClassPublisher;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.CountingMessageHandler;
import org.aspectj.bridge.ILifecycleAware;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.IProgressListener;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.bridge.Version;
import org.aspectj.bridge.context.CompilationAndWeavingContext;
import org.aspectj.bridge.context.ContextFormatter;
import org.aspectj.bridge.context.ContextToken;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.core.compiler.IProblem;
import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile;
import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
import org.aspectj.org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
import org.aspectj.org.eclipse.jdt.internal.compiler.ICompilerRequestor;
import org.aspectj.org.eclipse.jdt.internal.compiler.IProblemFactory;
import org.aspectj.org.eclipse.jdt.internal.compiler.batch.ClasspathDirectory;
import org.aspectj.org.eclipse.jdt.internal.compiler.batch.CompilationUnit;
import org.aspectj.org.eclipse.jdt.internal.compiler.batch.FileSystem;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser;
import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
import org.aspectj.org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
import org.aspectj.util.FileUtil;
import org.aspectj.weaver.Dump;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.UnwovenClassFile;
import org.eclipse.core.runtime.OperationCanceledException;
//import org.aspectj.org.eclipse.jdt.internal.compiler.util.HashtableOfObject;
public class AjBuildManager implements IOutputClassFileNameProvider,IBinarySourceProvider,ICompilerAdapterFactory {
private static final String CROSSREFS_FILE_NAME = "build.lst";
private static final String CANT_WRITE_RESULT = "unable to write compilation result";
private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF";
static final boolean COPY_INPATH_DIR_RESOURCES = false;
static final boolean FAIL_IF_RUNTIME_NOT_FOUND = false;
private static final FileFilter binarySourceFilter =
new FileFilter() {
public boolean accept(File f) {
return f.getName().endsWith(".class");
}};
/**
* This builder is static so that it can be subclassed and reset. However, note
* that there is only one builder present, so if two extendsion reset it, only
* the latter will get used.
*/
public static AsmHierarchyBuilder asmHierarchyBuilder = new AsmHierarchyBuilder();
static {
CompilationAndWeavingContext.registerFormatter(
CompilationAndWeavingContext.BATCH_BUILD, new AjBuildContexFormatter());
CompilationAndWeavingContext.registerFormatter(
CompilationAndWeavingContext.INCREMENTAL_BUILD, new AjBuildContexFormatter());
}
private IProgressListener progressListener = null;
private boolean environmentSupportsIncrementalCompilation = false;
private int compiledCount;
private int sourceFileCount;
private JarOutputStream zos;
private boolean batchCompile = true;
private INameEnvironment environment;
private Map /* String -> List<UCF>*/ binarySourcesForTheNextCompile = new HashMap();
// FIXME asc should this really be in here?
private IHierarchy structureModel;
public AjBuildConfig buildConfig;
private List aspectNames = new LinkedList();
AjState state = new AjState(this);
public BcelWeaver getWeaver() { return state.getWeaver();}
public BcelWorld getBcelWorld() { return state.getBcelWorld();}
public CountingMessageHandler handler;
public AjBuildManager(IMessageHandler holder) {
super();
this.handler = CountingMessageHandler.makeCountingMessageHandler(holder);
}
public void environmentSupportsIncrementalCompilation(boolean itDoes) {
this.environmentSupportsIncrementalCompilation = itDoes;
}
/** @return true if we should generate a model as a side-effect */
public boolean doGenerateModel() {
return buildConfig.isGenerateModelMode();
}
public boolean batchBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler)
throws IOException, AbortException {
return doBuild(buildConfig, baseHandler, true);
}
public boolean incrementalBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler)
throws IOException, AbortException {
return doBuild(buildConfig, baseHandler, false);
}
/** @throws AbortException if check for runtime fails */
protected boolean doBuild(
AjBuildConfig buildConfig,
IMessageHandler baseHandler,
boolean batch) throws IOException, AbortException {
boolean ret = true;
batchCompile = batch;
if (baseHandler instanceof ILifecycleAware) {
((ILifecycleAware)baseHandler).buildStarting(!batch);
}
CompilationAndWeavingContext.reset();
int phase = batch ? CompilationAndWeavingContext.BATCH_BUILD : CompilationAndWeavingContext.INCREMENTAL_BUILD;
ContextToken ct = CompilationAndWeavingContext.enteringPhase(phase ,buildConfig);
try {
if (batch) {
this.state = new AjState(this);
}
this.state.setCouldBeSubsequentIncrementalBuild(this.environmentSupportsIncrementalCompilation);
boolean canIncremental = state.prepareForNextBuild(buildConfig);
if (!canIncremental && !batch) { // retry as batch?
CompilationAndWeavingContext.leavingPhase(ct);
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);
CompilationAndWeavingContext.leavingPhase(ct);
return false;
} else {
MessageUtil.warn(handler, check);
}
}
// if (batch) {
setBuildConfig(buildConfig);
//}
if (batch || !AsmManager.attemptIncrementalModelRepairs) {
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
setupModel(buildConfig);
// }
}
if (batch) {
initBcelWorld(handler);
}
if (handler.hasErrors()) {
CompilationAndWeavingContext.leavingPhase(ct);
return false;
}
if (buildConfig.getOutputJar() != null) {
if (!openOutputStream(buildConfig.getOutputJar())) {
CompilationAndWeavingContext.leavingPhase(ct);
return false;
}
}
if (batch) {
// System.err.println("XXXX batch: " + buildConfig.getFiles());
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
getWorld().setModel(AsmManager.getDefault().getHierarchy());
// in incremental build, only get updated model?
}
binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true);
performCompilation(buildConfig.getFiles());
state.clearBinarySourceFiles(); // we don't want these hanging around...
if (handler.hasErrors()) {
CompilationAndWeavingContext.leavingPhase(ct);
return false;
}
if (AsmManager.isReporting())
AsmManager.getDefault().reportModelInfo("After a batch build");
} else {
// done already?
// if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode()) {
// bcelWorld.setModel(StructureModelManager.INSTANCE.getStructureModel());
// }
// System.err.println("XXXX start inc ");
binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(true);
List files = state.getFilesToCompile(true);
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode())
if (AsmManager.attemptIncrementalModelRepairs)
AsmManager.getDefault().processDelta(files,state.getAddedFiles(),state.getDeletedFiles());
boolean hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty());
for (int i = 0; (i < 5) && hereWeGoAgain; i++) {
// System.err.println("XXXX inc: " + files);
performCompilation(files);
if (handler.hasErrors() || (progressListener!=null && progressListener.isCancelledRequested())) {
CompilationAndWeavingContext.leavingPhase(ct);
return false;
}
if (state.requiresFullBatchBuild()) {
return batchBuild(buildConfig, baseHandler);
}
binarySourcesForTheNextCompile = state.getBinaryFilesToCompile(false);
files = state.getFilesToCompile(false);
hereWeGoAgain = !(files.isEmpty() && binarySourcesForTheNextCompile.isEmpty());
// TODO Andy - Needs some thought here...
// I think here we might want to pass empty addedFiles/deletedFiles as they were
// dealt with on the first call to processDelta - we are going through this loop
// again because in compiling something we found something else we needed to
// rebuild. But what case causes this?
if (hereWeGoAgain) {
if (buildConfig.isEmacsSymMode() || buildConfig.isGenerateModelMode())
if (AsmManager.attemptIncrementalModelRepairs)
AsmManager.getDefault().processDelta(files,state.getAddedFiles(),state.getDeletedFiles());
}
}
if (!files.isEmpty()) {
CompilationAndWeavingContext.leavingPhase(ct);
return batchBuild(buildConfig, baseHandler);
} else {
if (AsmManager.isReporting())
AsmManager.getDefault().reportModelInfo("After an incremental build");
}
}
// XXX not in Mik's incremental
if (buildConfig.isEmacsSymMode()) {
new org.aspectj.ajdt.internal.core.builder.EmacsStructureModelManager().externalizeModel();
}
// for bug 113554: support ajsym file generation for command line builds
if (buildConfig.isGenerateCrossRefsMode()) {
String configFileProxy = buildConfig.getOutputDir().getAbsolutePath()
+ File.separator
+ CROSSREFS_FILE_NAME;
AsmManager.getDefault().writeStructureModel(configFileProxy);
}
// have to tell state we succeeded or next is not incremental
state.successfulCompile(buildConfig,batch);
copyResourcesToDestination();
if (buildConfig.getOutxmlName() != null) {
writeOutxmlFile();
}
/*boolean weaved = *///weaveAndGenerateClassFiles();
// if not weaved, then no-op build, no model changes
// but always returns true
// XXX weaved not in Mik's incremental
if (buildConfig.isGenerateModelMode()) {
AsmManager.getDefault().fireModelUpdated();
}
CompilationAndWeavingContext.leavingPhase(ct);
} finally {
if (baseHandler instanceof ILifecycleAware) {
((ILifecycleAware)baseHandler).buildFinished(!batch);
}
if (zos != null) {
closeOutputStream(buildConfig.getOutputJar());
}
ret = !handler.hasErrors();
if (getBcelWorld()!=null) getBcelWorld().tidyUp();
getWeaver().tidyUp();
// bug 59895, don't release reference to handler as may be needed by a nested call
//handler = null;
}
return ret;
}
private boolean openOutputStream(File outJar) {
try {
OutputStream os = FileUtil.makeOutputStream(buildConfig.getOutputJar());
zos = new JarOutputStream(os,getWeaver().getManifest(true));
} catch (IOException ex) {
IMessage message =
new Message("Unable to open outjar "
+ outJar.getPath()
+ "(" + ex.getMessage()
+ ")",
new SourceLocation(outJar,0),
true);
handler.handleMessage(message);
return false;
}
return true;
}
private void closeOutputStream(File outJar) {
try {
if (zos != null) zos.close();
zos = null;
/* Ensure we don't write an incomplete JAR bug-71339 */
if (handler.hasErrors()) {
outJar.delete();
}
} catch (IOException ex) {
IMessage message =
new Message("Unable to write outjar "
+ outJar.getPath()
+ "(" + ex.getMessage()
+ ")",
new SourceLocation(outJar,0),
true);
handler.handleMessage(message);
}
}
private void copyResourcesToDestination() throws IOException {
// resources that we need to copy are contained in the injars and inpath only
for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext(); ) {
File inJar = (File)i.next();
copyResourcesFromJarFile(inJar);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (inPathElement.isDirectory()) {
copyResourcesFromDirectory(inPathElement);
} else {
copyResourcesFromJarFile(inPathElement);
}
}
if (buildConfig.getSourcePathResources() != null) {
for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) {
String resource = (String)i.next();
File from = (File)buildConfig.getSourcePathResources().get(resource);
copyResourcesFromFile(from,resource,from);
}
}
writeManifest();
}
private void copyResourcesFromJarFile(File jarFile) throws IOException {
JarInputStream inStream = null;
try {
inStream = new JarInputStream(new FileInputStream(jarFile));
while (true) {
ZipEntry entry = inStream.getNextEntry();
if (entry == null) break;
String filename = entry.getName();
// System.out.println("? copyResourcesFromJarFile() filename='" + filename +"'");
if (!entry.isDirectory() && acceptResource(filename)) {
byte[] bytes = FileUtil.readAsByteArray(inStream);
writeResource(filename,bytes,jarFile);
}
inStream.closeEntry();
}
} finally {
if (inStream != null) inStream.close();
}
}
private void copyResourcesFromDirectory(File dir) throws IOException {
if (!COPY_INPATH_DIR_RESOURCES) return;
// Get a list of all files (i.e. everything that isnt a directory)
File[] files = FileUtil.listFiles(dir,new FileFilter() {
public boolean accept(File f) {
boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")) ;
return accept;
}
});
// For each file, add it either as a real .class file or as a resource
for (int i = 0; i < files.length; i++) {
// ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
// or we are in trouble...
String filename = files[i].getAbsolutePath().substring(
dir.getAbsolutePath().length()+1);
copyResourcesFromFile(files[i],filename,dir);
}
}
private void copyResourcesFromFile(File f,String filename,File src) throws IOException {
if (!acceptResource(filename)) return;
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
byte[] bytes = FileUtil.readAsByteArray(fis);
// String relativePath = files[i].getPath();
writeResource(filename,bytes,src);
} finally {
if (fis != null) fis.close();
}
}
private void writeResource(String filename, byte[] content, File srcLocation) throws IOException {
if (state.hasResource(filename)) {
IMessage msg = new Message("duplicate resource: '" + filename + "'",
IMessage.WARNING,
null,
new SourceLocation(srcLocation,0));
handler.handleMessage(msg);
return;
}
if (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.recordResource(filename);
}
/*
* If we are writing to an output directory copy the manifest but only
* if we already have one
*/
private void writeManifest () throws IOException {
Manifest manifest = getWeaver().getManifest(false);
if (manifest != null && zos == null) {
OutputStream fos =
FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),MANIFEST_NAME));
manifest.write(fos);
fos.close();
}
}
private boolean acceptResource(String resourceName) {
if (
(resourceName.startsWith("CVS/")) ||
(resourceName.indexOf("/CVS/") != -1) ||
(resourceName.endsWith("/CVS")) ||
(resourceName.endsWith(".class")) ||
(resourceName.startsWith(".svn/")) ||
(resourceName.indexOf("/.svn/")!=-1) ||
(resourceName.endsWith("/.svn")) ||
(resourceName.toUpperCase().equals(MANIFEST_NAME))
)
{
return false;
} else {
return true;
}
}
private void writeOutxmlFile () throws IOException {
String filename = buildConfig.getOutxmlName();
// System.err.println("? AjBuildManager.writeOutxmlFile() outxml=" + filename);
// System.err.println("? AjBuildManager.writeOutxmlFile() outputDir=" + buildConfig.getOutputDir());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
ps.println("<aspectj>");
ps.println("<aspects>");
for (Iterator i = aspectNames.iterator(); i.hasNext();) {
String name = (String)i.next();
ps.println("<aspect name=\"" + name + "\"/>");
}
ps.println("</aspects>");
ps.println("</aspectj>");
ps.println();
ps.close();
if (zos != null) {
ZipEntry newEntry = new ZipEntry(filename);
zos.putNextEntry(newEntry);
zos.write(baos.toByteArray());
zos.closeEntry();
} else {
OutputStream fos =
FileUtil.makeOutputStream(new File(buildConfig.getOutputDir(),filename));
fos.write(baos.toByteArray());
fos.close();
}
}
// public static void dumprels() {
// IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap();
// int ctr = 1;
// Set entries = irm.getEntries();
// for (Iterator iter = entries.iterator(); iter.hasNext();) {
// String hid = (String) iter.next();
// List rels = irm.get(hid);
// for (Iterator iterator = rels.iterator(); iterator.hasNext();) {
// IRelationship ir = (IRelationship) iterator.next();
// List targets = ir.getTargets();
// for (Iterator iterator2 = targets.iterator();
// iterator2.hasNext();
// ) {
// String thid = (String) iterator2.next();
// System.err.println("Hid:"+(ctr++)+":(targets="+targets.size()+") "+hid+" ("+ir.getName()+") "+thid);
// }
// }
// }
// }
/**
* Responsible for managing the ASM model between builds. Contains the policy for
* maintaining the persistance of elements in the model.
*
* This code is driven before each 'fresh' (batch) build to create
* a new model.
*/
private void setupModel(AjBuildConfig config) {
AsmManager.setCreatingModel(config.isEmacsSymMode() || config.isGenerateModelMode());
if (!AsmManager.isCreatingModel()) return;
AsmManager.getDefault().createNewASM();
// AsmManager.getDefault().getRelationshipMap().clear();
IHierarchy model = AsmManager.getDefault().getHierarchy();
String rootLabel = "<root>";
IProgramElement.Kind kind = IProgramElement.Kind.FILE_JAVA;
if (buildConfig.getConfigFile() != null) {
rootLabel = buildConfig.getConfigFile().getName();
model.setConfigFile(buildConfig.getConfigFile().getAbsolutePath());
kind = IProgramElement.Kind.FILE_LST;
}
model.setRoot(new ProgramElement(rootLabel, kind, new ArrayList()));
model.setFileMap(new HashMap());
setStructureModel(model);
state.setStructureModel(model);
state.setRelationshipMap(AsmManager.getDefault().getRelationshipMap());
}
//
// private void dumplist(List l) {
// System.err.println("---- "+l.size());
// for (int i =0 ;i<l.size();i++) System.err.println(i+"\t "+l.get(i));
// }
// private void accumulateFileNodes(IProgramElement ipe,List store) {
// if (ipe.getKind()==IProgramElement.Kind.FILE_JAVA ||
// ipe.getKind()==IProgramElement.Kind.FILE_ASPECTJ) {
// if (!ipe.getName().equals("<root>")) {
// store.add(ipe);
// return;
// }
// }
// for (Iterator i = ipe.getChildren().iterator();i.hasNext();) {
// accumulateFileNodes((IProgramElement)i.next(),store);
// }
// }
/** init only on initial batch compile? no file-specific options */
private void initBcelWorld(IMessageHandler handler) throws IOException {
List cp = buildConfig.getBootclasspath();
cp.addAll(buildConfig.getClasspath());
BcelWorld bcelWorld = new BcelWorld(cp, handler, null);
bcelWorld.setBehaveInJava5Way(buildConfig.getBehaveInJava5Way());
bcelWorld.setAddSerialVerUID(buildConfig.isAddSerialVerUID());
bcelWorld.performExtraConfiguration(buildConfig.getXconfigurationInfo());
bcelWorld.setTargetAspectjRuntimeLevel(buildConfig.getTargetAspectjRuntimeLevel());
bcelWorld.setOptionalJoinpoints(buildConfig.getXJoinpoints());
bcelWorld.setXnoInline(buildConfig.isXnoInline());
bcelWorld.setXlazyTjp(buildConfig.isXlazyTjp());
bcelWorld.setXHasMemberSupportEnabled(buildConfig.isXHasMemberEnabled());
bcelWorld.setPinpointMode(buildConfig.isXdevPinpoint());
BcelWeaver bcelWeaver = new BcelWeaver(bcelWorld);
state.setWorld(bcelWorld);
state.setWeaver(bcelWeaver);
state.clearBinarySourceFiles();
for (Iterator i = buildConfig.getAspectpath().iterator(); i.hasNext();) {
File f = (File) i.next();
if (!f.exists()) {
IMessage message = new Message("invalid aspectpath entry: "+f.getName(),null,true);
handler.handleMessage(message);
} else {
bcelWeaver.addLibraryJarFile(f);
}
}
// String lintMode = buildConfig.getLintMode();
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.recordBinarySource(inJar.getPath(), unwovenClasses);
}
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (!inPathElement.isDirectory()) {
// its a jar file on the inpath
// the weaver method can actually handle dirs, but we don't call it, see next block
List unwovenClasses = bcelWeaver.addJarFile(inPathElement,buildConfig.getOutputDir(),true);
state.recordBinarySource(inPathElement.getPath(),unwovenClasses);
} else {
// add each class file in an in-dir individually, this gives us the best error reporting
// (they are like 'source' files then), and enables a cleaner incremental treatment of
// class file changes in indirs.
File[] binSrcs = FileUtil.listFiles(inPathElement, binarySourceFilter);
for (int j = 0; j < binSrcs.length; j++) {
UnwovenClassFile ucf =
bcelWeaver.addClassFile(binSrcs[j], inPathElement, buildConfig.getOutputDir());
List ucfl = new ArrayList();
ucfl.add(ucf);
state.recordBinarySource(binSrcs[j].getPath(),ucfl);
}
}
}
bcelWeaver.setReweavableMode(buildConfig.isXNotReweavable());
//check for org.aspectj.runtime.JoinPoint
ResolvedType joinPoint = bcelWorld.resolve("org.aspectj.lang.JoinPoint");
if (joinPoint.isMissing()) {
IMessage message =
new Message("classpath error: unable to find org.aspectj.lang.JoinPoint (check that aspectjrt.jar is in your classpath)",
null,
true);
handler.handleMessage(message);
}
}
public World getWorld() {
return getBcelWorld();
}
void addAspectClassFilesToWeaver(List addedClassFiles) throws IOException {
for (Iterator i = addedClassFiles.iterator(); i.hasNext(); ) {
UnwovenClassFile classFile = (UnwovenClassFile) i.next();
getWeaver().addClassFile(classFile);
}
}
// public boolean weaveAndGenerateClassFiles() throws IOException {
// handler.handleMessage(MessageUtil.info("weaving"));
// if (progressListener != null) progressListener.setText("weaving aspects");
// bcelWeaver.setProgressListener(progressListener, 0.5, 0.5/state.addedClassFiles.size());
// //!!! doesn't provide intermediate progress during weaving
// // XXX add all aspects even during incremental builds?
// addAspectClassFilesToWeaver(state.addedClassFiles);
// if (buildConfig.isNoWeave()) {
// if (buildConfig.getOutputJar() != null) {
// bcelWeaver.dumpUnwoven(buildConfig.getOutputJar());
// } else {
// bcelWeaver.dumpUnwoven();
// bcelWeaver.dumpResourcesToOutPath();
// }
// } else {
// if (buildConfig.getOutputJar() != null) {
// bcelWeaver.weave(buildConfig.getOutputJar());
// } else {
// bcelWeaver.weave();
// bcelWeaver.dumpResourcesToOutPath();
// }
// }
// if (progressListener != null) progressListener.setProgress(1.0);
// return true;
// //return messageAdapter.getErrorCount() == 0; //!javaBuilder.notifier.anyErrors();
// }
public FileSystem getLibraryAccess(String[] classpaths, String[] filenames) {
String defaultEncoding = buildConfig.getOptions().defaultEncoding;
if ("".equals(defaultEncoding)) //$NON-NLS-1$
defaultEncoding = null; //$NON-NLS-1$
// Bug 46671: We need an array as long as the number of elements in the classpath - *even though* not every
// element of the classpath is likely to be a directory. If we ensure every element of the array is set to
// only look for BINARY, then we make sure that for any classpath element that is a directory, we won't build
// a classpathDirectory object that will attempt to look for source when it can't find binary.
int[] classpathModes = new int[classpaths.length];
for (int i =0 ;i<classpaths.length;i++) classpathModes[i]=ClasspathDirectory.BINARY;
return new FileSystem(classpaths, filenames, defaultEncoding,classpathModes);
}
public IProblemFactory getProblemFactory() {
return new DefaultProblemFactory(Locale.getDefault());
}
/*
* Build the set of compilation source units
*/
public CompilationUnit[] getCompilationUnits(String[] filenames, String[] encodings) {
int fileCount = filenames.length;
CompilationUnit[] units = new CompilationUnit[fileCount];
// HashtableOfObject knownFileNames = new HashtableOfObject(fileCount);
String defaultEncoding = buildConfig.getOptions().defaultEncoding;
if ("".equals(defaultEncoding)) //$NON-NLS-1$
defaultEncoding = null; //$NON-NLS-1$
for (int i = 0; i < fileCount; i++) {
String encoding = encodings[i];
if (encoding == null)
encoding = defaultEncoding;
units[i] = new CompilationUnit(null, filenames[i], encoding);
}
return units;
}
public String extractDestinationPathFromSourceFile(CompilationResult result) {
ICompilationUnit compilationUnit = result.compilationUnit;
if (compilationUnit != null) {
char[] fileName = compilationUnit.getFileName();
int lastIndex = CharOperation.lastIndexOf(java.io.File.separatorChar, fileName);
if (lastIndex == -1) {
return System.getProperty("user.dir"); //$NON-NLS-1$
}
return new String(CharOperation.subarray(fileName, 0, lastIndex));
}
return System.getProperty("user.dir"); //$NON-NLS-1$
}
public void performCompilation(List files) {
if (progressListener != null) {
compiledCount=0;
sourceFileCount = files.size();
progressListener.setText("compiling source files");
}
//System.err.println("got files: " + files);
String[] filenames = new String[files.size()];
String[] encodings = new String[files.size()];
//System.err.println("filename: " + this.filenames);
for (int i=0; i < files.size(); i++) {
filenames[i] = ((File)files.get(i)).getPath();
}
List cps = buildConfig.getFullClasspath();
Dump.saveFullClasspath(cps);
String[] classpaths = new String[cps.size()];
for (int i=0; i < cps.size(); i++) {
classpaths[i] = (String)cps.get(i);
}
//System.out.println("compiling");
environment = getLibraryAccess(classpaths, filenames);
if (!state.getClassNameToFileMap().isEmpty()) {
environment = new StatefulNameEnvironment(environment, state.getClassNameToFileMap());
}
org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(this);
org.aspectj.org.eclipse.jdt.internal.compiler.Compiler compiler =
new org.aspectj.org.eclipse.jdt.internal.compiler.Compiler(environment,
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
buildConfig.getOptions().getMap(),
getBatchRequestor(),
getProblemFactory());
CompilerOptions options = compiler.options;
options.produceReferenceInfo = true; //TODO turn off when not needed
try {
compiler.compile(getCompilationUnits(filenames, encodings));
} catch (OperationCanceledException oce) {
handler.handleMessage(new Message("build cancelled:"+oce.getMessage(),IMessage.WARNING,null,null));
}
// cleanup
org.aspectj.ajdt.internal.compiler.CompilerAdapter.setCompilerAdapterFactory(null);
AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(null);
environment.cleanup();
environment = null;
}
/*
* Answer the component to which will be handed back compilation results from the compiler
*/
public IIntermediateResultsRequestor getInterimResultRequestor() {
return new IIntermediateResultsRequestor() {
public void acceptResult(InterimCompilationResult result) {
if (progressListener != null) {
compiledCount++;
progressListener.setProgress((compiledCount/2.0)/sourceFileCount);
progressListener.setText("compiled: " + result.fileName());
}
state.noteResult(result);
if (progressListener!=null && progressListener.isCancelledRequested()) {
throw new AbortCompilation(true,
new OperationCanceledException("Compilation cancelled as requested"));
}
}
};
}
public ICompilerRequestor getBatchRequestor() {
return new ICompilerRequestor() {
public void acceptResult(CompilationResult unitResult) {
// end of compile, must now write the results to the output destination
// this is either a jar file or a file in a directory
if (!(unitResult.hasErrors() && !proceedOnError())) {
Collection classFiles = unitResult.compiledTypes.values();
boolean shouldAddAspectName = (buildConfig.getOutxmlName() != null);
for (Iterator iter = classFiles.iterator(); iter.hasNext();) {
ClassFile classFile = (ClassFile) iter.next();
String filename = new String(classFile.fileName());
String classname = filename.replace('/', '.');
filename = filename.replace('/', File.separatorChar) + ".class";
try {
if (buildConfig.getOutputJar() == null) {
writeDirectoryEntry(unitResult, classFile,filename);
} else {
writeZipEntry(classFile,filename);
}
if (shouldAddAspectName) addAspectName(classname);
} catch (IOException ex) {
IMessage message = EclipseAdapterUtils.makeErrorMessage(
new String(unitResult.fileName),
CANT_WRITE_RESULT,
ex);
handler.handleMessage(message);
}
}
}
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();
}
private void addAspectName (String name) {
BcelWorld world = getBcelWorld();
ResolvedType type = world.resolve(name);
// System.err.println("? writeAspectName() type=" + type);
if (type.isAspect()) {
aspectNames.add(name);
}
}
};
}
protected boolean proceedOnError() {
return buildConfig.getProceedOnError();
}
// public void noteClassFiles(AjCompiler.InterimResult result) {
// if (result == null) return;
// CompilationResult unitResult = result.result;
// String sourceFileName = result.fileName();
// if (!(unitResult.hasErrors() && !proceedOnError())) {
// List unwovenClassFiles = new ArrayList();
// Enumeration classFiles = unitResult.compiledTypes.elements();
// while (classFiles.hasMoreElements()) {
// ClassFile classFile = (ClassFile) classFiles.nextElement();
// String filename = new String(classFile.fileName());
// filename = filename.replace('/', File.separatorChar) + ".class";
//
// File destinationPath = buildConfig.getOutputDir();
// if (destinationPath == null) {
// filename = new File(filename).getName();
// filename = new File(extractDestinationPathFromSourceFile(unitResult), filename).getPath();
// } else {
// filename = new File(destinationPath, filename).getPath();
// }
//
// //System.out.println("classfile: " + filename);
// unwovenClassFiles.add(new UnwovenClassFile(filename, classFile.getBytes()));
// }
// state.noteClassesFromFile(unitResult, sourceFileName, unwovenClassFiles);
//// System.out.println("file: " + sourceFileName);
//// for (int i=0; i < unitResult.simpleNameReferences.length; i++) {
//// System.out.println("simple: " + new String(unitResult.simpleNameReferences[i]));
//// }
//// for (int i=0; i < unitResult.qualifiedReferences.length; i++) {
//// System.out.println("qualified: " +
//// new String(CharOperation.concatWith(unitResult.qualifiedReferences[i], '/')));
//// }
// } else {
// state.noteClassesFromFile(null, sourceFileName, Collections.EMPTY_LIST);
// }
// }
//
private void setBuildConfig(AjBuildConfig buildConfig) {
this.buildConfig = buildConfig;
if (!this.environmentSupportsIncrementalCompilation) {
this.environmentSupportsIncrementalCompilation =
(buildConfig.isIncrementalMode() || buildConfig.isIncrementalFileMode());
}
handler.reset();
}
String makeClasspathString(AjBuildConfig buildConfig) {
if (buildConfig == null || buildConfig.getFullClasspath() == null) return "";
StringBuffer buf = new StringBuffer();
boolean first = true;
for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) {
if (first) { first = false; }
else { buf.append(File.pathSeparator); }
buf.append(it.next().toString());
}
return buf.toString();
}
/**
* This will return null if aspectjrt.jar is present and has the correct version.
* Otherwise it will return a string message indicating the problem.
*/
public String checkRtJar(AjBuildConfig buildConfig) {
// omitting dev info
if (Version.text.equals(Version.DEVELOPMENT)) {
// in the development version we can't do this test usefully
// MessageUtil.info(holder, "running development version of aspectj compiler");
return null;
}
if (buildConfig == null || buildConfig.getFullClasspath() == null) return "no classpath specified";
String ret = null;
for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext(); ) {
File p = new File( (String)it.next() );
// pr112830, allow variations on aspectjrt.jar of the form aspectjrtXXXXXX.jar
if (p.isFile() && p.getName().startsWith("aspectjrt") && p.getName().endsWith(".jar")) {
try {
String version = null;
Manifest manifest = new JarFile(p).getManifest();
if (manifest == null) {
ret = "no manifest found in " + p.getAbsolutePath() +
", expected " + Version.text;
continue;
}
Attributes attr = manifest.getAttributes("org/aspectj/lang/");
if (null != attr) {
version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
if (null != version) {
version = version.trim();
}
}
// assume that users of development aspectjrt.jar know what they're doing
if (Version.DEVELOPMENT.equals(version)) {
// MessageUtil.info(holder,
// "running with development version of aspectjrt.jar in " +
// p.getAbsolutePath());
return null;
} else if (!Version.text.equals(version)) {
ret = "bad version number found in " + p.getAbsolutePath() +
" expected " + Version.text + " found " + version;
continue;
}
} catch (IOException ioe) {
ret = "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe;
}
return null; // this is the "OK" return value!
} else {
// might want to catch other classpath errors
}
}
if (ret != null) return ret; // last error found in potentially matching jars...
return "couldn't find aspectjrt.jar on classpath, checked: " + makeClasspathString(buildConfig);
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("AjBuildManager(");
buf.append(")");
return buf.toString();
}
public void setStructureModel(IHierarchy structureModel) {
this.structureModel = structureModel;
}
/**
* Returns null if there is no structure model
*/
public IHierarchy getStructureModel() {
return structureModel;
}
public IProgressListener getProgressListener() {
return progressListener;
}
public void setProgressListener(IProgressListener progressListener) {
this.progressListener = progressListener;
}
/* (non-Javadoc)
* @see org.aspectj.ajdt.internal.compiler.AjCompiler.IOutputClassFileNameProvider#getOutputClassFileName(char[])
*/
public String getOutputClassFileName(char[] eclipseClassFileName, CompilationResult result) {
String filename = new String(eclipseClassFileName);
filename = filename.replace('/', File.separatorChar) + ".class";
File destinationPath = buildConfig.getOutputDir();
String outFile;
if (destinationPath == null) {
outFile = new File(filename).getName();
outFile = new File(extractDestinationPathFromSourceFile(result), outFile).getPath();
} else {
outFile = new File(destinationPath, filename).getPath();
}
return outFile;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.compiler.ICompilerAdapterFactory#getAdapter(org.eclipse.jdt.internal.compiler.Compiler)
*/
public ICompilerAdapter getAdapter(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) {
// complete compiler config and return a suitable adapter...
populateCompilerOptionsFromLintSettings(forCompiler);
AjProblemReporter pr =
new AjProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(),
forCompiler.options, getProblemFactory());
forCompiler.problemReporter = pr;
AjLookupEnvironment le =
new AjLookupEnvironment(forCompiler, forCompiler.options, pr, environment);
EclipseFactory factory = new EclipseFactory(le,this);
le.factory = factory;
pr.factory = factory;
forCompiler.lookupEnvironment = le;
forCompiler.parser =
new Parser(
pr,
forCompiler.options.parseLiteralExpressionsAsConstants);
return new AjCompilerAdapter(forCompiler,batchCompile,getBcelWorld(),getWeaver(),
factory,
getInterimResultRequestor(),
progressListener,
this, // IOutputFilenameProvider
this, // IBinarySourceProvider
state.getBinarySourceMap(),
buildConfig.isTerminateAfterCompilation(),
buildConfig.getProceedOnError(),
buildConfig.isNoAtAspectJAnnotationProcessing(),
state);
}
/**
* Some AspectJ lint options need to be known about in the compiler. This is
* how we pass them over...
* @param forCompiler
*/
private void populateCompilerOptionsFromLintSettings(org.aspectj.org.eclipse.jdt.internal.compiler.Compiler forCompiler) {
BcelWorld world = this.state.getBcelWorld();
IMessage.Kind swallowedExceptionKind = world.getLint().swallowedExceptionInCatchBlock.getKind();
Map optionsMap = new HashMap();
optionsMap.put(CompilerOptions.OPTION_ReportSwallowedExceptionInCatchBlock,
swallowedExceptionKind == null ? "ignore" : swallowedExceptionKind.toString());
forCompiler.options.set(optionsMap);
}
/* (non-Javadoc)
* @see org.aspectj.ajdt.internal.compiler.IBinarySourceProvider#getBinarySourcesForThisWeave()
*/
public Map getBinarySourcesForThisWeave() {
return binarySourcesForTheNextCompile;
}
public static AsmHierarchyBuilder getAsmHierarchyBuilder() {
return asmHierarchyBuilder;
}
/**
* Override the the default hierarchy builder.
*/
public static void setAsmHierarchyBuilder(AsmHierarchyBuilder newBuilder) {
asmHierarchyBuilder = newBuilder;
}
public AjState getState() {
return state;
}
public void setState(AjState buildState) {
state = buildState;
}
private static class AjBuildContexFormatter implements ContextFormatter {
public String formatEntry(int phaseId, Object data) {
StringBuffer sb = new StringBuffer();
if (phaseId == CompilationAndWeavingContext.BATCH_BUILD) {
sb.append("batch building ");
} else {
sb.append("incrementally building ");
}
AjBuildConfig config = (AjBuildConfig) data;
List classpath = config.getClasspath();
sb.append("with classpath: ");
for (Iterator iter = classpath.iterator(); iter.hasNext();) {
sb.append(iter.next().toString());
sb.append(File.pathSeparator);
}
return sb.toString();
}
}
}
|
131,505 |
Bug 131505 Generated aop.xml files contain aspects for all the projects ever built
|
Using the -outxml option in AJDT the generated aop.xml files are not correct after the first build and contain all the aspects that have ever been built (including those in different projects and duplicates if an aspect has been built twice). It seems that there is a global list of aspects (aspectNames in AjBuildManager) that is never cleared.
|
resolved fixed
|
b3cd01d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-15T12:34:48Z | 2006-03-13T11:40:00Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjState.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.ajdt.internal.compiler.InterimCompilationResult;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IRelationshipMap;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryField;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryMethod;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilerModifiers;
import org.aspectj.org.eclipse.jdt.internal.core.builder.ReferenceCollection;
import org.aspectj.org.eclipse.jdt.internal.core.builder.StringSet;
import org.aspectj.util.FileUtil;
import org.aspectj.weaver.IWeaver;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.UnwovenClassFile;
/**
* Holds state needed for incremental compilation
*/
public class AjState {
private AjBuildManager buildManager;
private boolean couldBeSubsequentIncrementalBuild = false;
// SECRETAPI static so beware of multi-threading bugs...
public static IStateListener stateListener = null;
public static boolean FORCE_INCREMENTAL_DURING_TESTING = false;
private IHierarchy structureModel;
private IRelationshipMap relmap;
private long lastSuccessfulFullBuildTime = -1;
private Hashtable /* File, long */ structuralChangesSinceLastFullBuild = new Hashtable();
private long lastSuccessfulBuildTime = -1;
private long currentBuildTime = -1;
private AjBuildConfig buildConfig;
private boolean batchBuildRequiredThisTime = false;
/**
* Keeps a list of (FQN,Filename) pairs (as ClassFile objects)
* for types that resulted from the compilation of the given
* File. Note :- the ClassFile objects contain no byte code,
* they are simply a Filename,typename pair.
*
* Populated in noteResult and used in addDependentsOf(File)
*
* Added by AMC during state refactoring, 1Q06.
*/
private Map/*<File, List<ClassFile>*/ fullyQualifiedTypeNamesResultingFromCompilationUnit = new HashMap();
/**
* Source files defining aspects
*
* Populated in noteResult and used in processDeletedFiles
*
* Added by AMC during state refactoring, 1Q06.
*/
private Set/*<File>*/ sourceFilesDefiningAspects = new HashSet();
/**
* Populated in noteResult to record the set of types that should be recompiled if
* the given file is modified or deleted.
*
* Refered to during addAffectedSourceFiles when calculating incremental compilation set.
*/
private Map/*<File, ReferenceCollection>*/ references = new HashMap();
/**
* Holds UnwovenClassFiles (byte[]s) originating from the given file source. This
* could be a jar file, a directory, or an individual .class file. This is an
* *expensive* map. It is cleared immediately following a batch build, and the
* cheaper inputClassFilesBySource map is kept for processing of any subsequent
* incremental builds.
*
* Populated during AjBuildManager.initBcelWorld().
*
* Passed into AjCompiler adapter as the set of binary input files to reweave if the
* weaver determines a full weave is required.
*
* Cleared during initBcelWorld prior to repopulation.
*
* Used when a file is deleted during incremental compilation to delete all of the
* class files in the output directory that resulted from the weaving of File.
*
* Used during getBinaryFilesToCompile when compiling incrementally to determine
* which files should be recompiled if a given input file has changed.
*
*/
private Map/*File, List<UnwovenClassFile>*/ binarySourceFiles = new HashMap();
/**
* Initially a duplicate of the information held in binarySourceFiles, with the
* key difference that the values are ClassFiles (type name, File) not UnwovenClassFiles
* (which also have all the byte code in them). After a batch build, binarySourceFiles
* is cleared, leaving just this much lighter weight map to use in processing
* subsequent incremental builds.
*/
private Map/*<File,List<ClassFile>*/ inputClassFilesBySource = new HashMap();
/**
* Holds structure information on types as they were at the end of the last
* build. It would be nice to get rid of this too, but can't see an easy way to do
* that right now.
*/
private Map/*FQN,CompactStructureRepresentation*/ resolvedTypeStructuresFromLastBuild = new HashMap();
/**
* Populated in noteResult to record the set of UnwovenClassFiles (intermediate results)
* that originated from compilation of the class with the given fully-qualified name.
*
* Used in removeAllResultsOfLastBuild to remove .class files from output directory.
*
* Passed into StatefulNameEnvironment during incremental compilation to support
* findType lookups.
*/
private Map/*<String, File>*/ classesFromName = new HashMap();
private List/*File*/ compiledSourceFiles = new ArrayList();
private List/*String*/ resources = new ArrayList();
private ArrayList/*<String>*/ qualifiedStrings;
private ArrayList/*<String>*/ simpleStrings;
private Set addedFiles;
private Set deletedFiles;
private Set /*BinarySourceFile*/addedBinaryFiles;
private Set /*BinarySourceFile*/deletedBinaryFiles;
private BcelWeaver weaver;
private BcelWorld world;
public AjState(AjBuildManager buildManager) {
this.buildManager = buildManager;
}
public void setCouldBeSubsequentIncrementalBuild(boolean yesThereCould) {
this.couldBeSubsequentIncrementalBuild = yesThereCould;
}
void successfulCompile(AjBuildConfig config,boolean wasFullBuild) {
buildConfig = config;
lastSuccessfulBuildTime = currentBuildTime;
if (stateListener!=null) stateListener.buildSuccessful(wasFullBuild);
if (wasFullBuild) lastSuccessfulFullBuildTime = currentBuildTime;
}
/**
* Returns false if a batch build is needed.
*/
boolean prepareForNextBuild(AjBuildConfig newBuildConfig) {
currentBuildTime = System.currentTimeMillis();
if (!maybeIncremental()) {
return false;
}
if (this.batchBuildRequiredThisTime) {
this.batchBuildRequiredThisTime = false;
return false;
}
if (lastSuccessfulBuildTime == -1 || buildConfig == null) {
structuralChangesSinceLastFullBuild.clear();
return false;
}
// we don't support incremental with an outjar yet
if (newBuildConfig.getOutputJar() != null) {
structuralChangesSinceLastFullBuild.clear();
return false;
}
// we can't do an incremental build if one of our paths
// has changed, or a jar on a path has been modified
if (pathChange(buildConfig,newBuildConfig)) {
// last time we built, .class files and resource files from jars on the
// inpath will have been copied to the output directory.
// these all need to be deleted in preparation for the clean build that is
// coming - otherwise a file that has been deleted from an inpath jar
// since the last build will not be deleted from the output directory.
removeAllResultsOfLastBuild();
if (stateListener!=null) stateListener.pathChangeDetected();
structuralChangesSinceLastFullBuild.clear();
return false;
}
simpleStrings = new ArrayList();
qualifiedStrings = new ArrayList();
Set oldFiles = new HashSet(buildConfig.getFiles());
Set newFiles = new HashSet(newBuildConfig.getFiles());
addedFiles = new HashSet(newFiles);
addedFiles.removeAll(oldFiles);
deletedFiles = new HashSet(oldFiles);
deletedFiles.removeAll(newFiles);
Set oldBinaryFiles = new HashSet(buildConfig.getBinaryFiles());
Set newBinaryFiles = new HashSet(newBuildConfig.getBinaryFiles());
addedBinaryFiles = new HashSet(newBinaryFiles);
addedBinaryFiles.removeAll(oldBinaryFiles);
deletedBinaryFiles = new HashSet(oldBinaryFiles);
deletedBinaryFiles.removeAll(newBinaryFiles);
boolean couldStillBeIncremental = processDeletedFiles(deletedFiles);
if (!couldStillBeIncremental) return false;
return true;
}
/**
* Checks if any of the files in the set passed in contains an aspect declaration. If one is found
* then we start the process of batch building, i.e. we remove all the results of the last build,
* call any registered listener to tell them whats happened and return false.
*
* @return false if we discovered an aspect declaration
*/
private boolean processDeletedFiles(Set deletedFiles) {
for (Iterator iter = deletedFiles.iterator(); iter.hasNext();) {
File aDeletedFile = (File ) iter.next();
if (this.sourceFilesDefiningAspects.contains(aDeletedFile)) {
removeAllResultsOfLastBuild();
if (stateListener!=null) stateListener.detectedAspectDeleted(aDeletedFile);
return false;
}
}
return true;
}
private Collection getModifiedFiles() {
return getModifiedFiles(lastSuccessfulBuildTime);
}
Collection getModifiedFiles(long lastBuildTime) {
List ret = new ArrayList();
//not our job to account for new and deleted files
for (Iterator i = buildConfig.getFiles().iterator(); i.hasNext(); ) {
File file = (File)i.next();
if (!file.exists()) continue;
long modTime = file.lastModified();
// System.out.println("check: " + file + " mod " + modTime + " build " + lastBuildTime);
// need to add 1000 since lastModTime is only accurate to a second on some (all?) platforms
if (modTime + 1000 > lastBuildTime) {
ret.add(file);
}
}
return ret;
}
private Collection getModifiedBinaryFiles() {
return getModifiedBinaryFiles(lastSuccessfulBuildTime);
}
Collection getModifiedBinaryFiles(long lastBuildTime) {
List ret = new ArrayList();
//not our job to account for new and deleted files
for (Iterator i = buildConfig.getBinaryFiles().iterator(); i.hasNext(); ) {
AjBuildConfig.BinarySourceFile bsfile = (AjBuildConfig.BinarySourceFile)i.next();
File file = bsfile.binSrc;
if (!file.exists()) continue;
long modTime = file.lastModified();
//System.out.println("check: " + file + " mod " + modTime + " build " + lastBuildTime);
// need to add 1000 since lastModTime is only accurate to a second on some (all?) platforms
if (modTime + 1000 >= lastBuildTime) {
ret.add(bsfile);
}
}
return ret;
}
private boolean classFileChangedInDirSinceLastBuild(File dir) {
// Is another process building into that directory?
AjState state = IncrementalStateManager.findStateManagingOutputLocation(dir);
File[] classFiles = FileUtil.listFiles(dir, new FileFilter() {
public boolean accept(File pathname) {
return pathname.getName().endsWith(".class");
}
});
for (int i = 0; i < classFiles.length; i++) {
long modTime = classFiles[i].lastModified();
if ((modTime+1000)>=lastSuccessfulBuildTime) {
// so the class on disk has changed since our last successful build
// To work out if it is a real change we should ask any state
// object managing this output location whether the file has
// structurally changed or not
if (state!=null) {
boolean realChange = state.hasStructuralChangedSince(classFiles[i],lastSuccessfulBuildTime);
if (realChange) return true;
} else {
// FIXME asc you should ask Eclipse project state here...
return true; // no state object to ask so it must have changed
}
}
}
return false;
}
/**
* Determine if a file has changed since a given time, using the local information
* recorded in the structural changes data structure.
*
* file is the file we are wondering about
* lastSBT is the last build time for the state asking the question
*/
private boolean hasStructuralChangedSince(File file,long lastSuccessfulBuildTime) {
//long lastModTime = file.lastModified();
Long l = (Long)structuralChangesSinceLastFullBuild.get(file.getAbsolutePath());
long strucModTime = -1;
if (l!=null) strucModTime = l.longValue();
else strucModTime = this.lastSuccessfulFullBuildTime;
// we now have:
// 'strucModTime'-> the last time the class was structurally changed
return (strucModTime>lastSuccessfulBuildTime);
}
private boolean pathChange(AjBuildConfig oldConfig, AjBuildConfig newConfig) {
boolean changed = false;
List oldClasspath = oldConfig.getClasspath();
List newClasspath = newConfig.getClasspath();
if (stateListener!=null) stateListener.aboutToCompareClasspaths(oldClasspath,newClasspath);
if (changed(oldClasspath,newClasspath,true,oldConfig.getOutputDir())) return true;
List oldAspectpath = oldConfig.getAspectpath();
List newAspectpath = newConfig.getAspectpath();
if (changed(oldAspectpath,newAspectpath,true,oldConfig.getOutputDir())) return true;
List oldInJars = oldConfig.getInJars();
List newInJars = newConfig.getInJars();
if (changed(oldInJars,newInJars,false,oldConfig.getOutputDir())) return true;
List oldInPath = oldConfig.getInpath();
List newInPath = newConfig.getInpath();
if (changed(oldInPath, newInPath,false,oldConfig.getOutputDir())) return true;
return changed;
}
private boolean changed(List oldPath, List newPath, boolean checkClassFiles, File oldOutputLocation) {
if (oldPath == null) oldPath = new ArrayList();
if (newPath == null) newPath = new ArrayList();
try {
if (oldOutputLocation != null) {
oldOutputLocation = oldOutputLocation.getCanonicalFile();
}
} catch(IOException ex) { /* we did our best...*/ }
if (oldPath.size() != newPath.size()) {
return true;
}
for (int i = 0; i < oldPath.size(); i++) {
if (!oldPath.get(i).equals(newPath.get(i))) {
return true;
}
Object o = oldPath.get(i); // String on classpath, File on other paths
File f = null;
if (o instanceof String) {
f = new File((String)o);
} else {
f = (File) o;
}
if (f.exists() && !f.isDirectory() && (f.lastModified() >= lastSuccessfulBuildTime)) {
return true;
}
if (f.exists() && f.isDirectory() && checkClassFiles && !(f.equals(oldOutputLocation))) {
boolean b= classFileChangedInDirSinceLastBuild(f);
if (b && stateListener!=null) stateListener.detectedClassChangeInThisDir(f);
if (b) return true;
}
}
return false;
}
public List getFilesToCompile(boolean firstPass) {
List thisTime = new ArrayList();
if (firstPass) {
compiledSourceFiles = new ArrayList();
Collection modifiedFiles = getModifiedFiles();
//System.out.println("modified: " + modifiedFiles);
thisTime.addAll(modifiedFiles);
//??? eclipse IncrementalImageBuilder appears to do this
// for (Iterator i = modifiedFiles.iterator(); i.hasNext();) {
// File file = (File) i.next();
// addDependentsOf(file);
// }
thisTime.addAll(addedFiles);
deleteClassFiles();
deleteResources();
addAffectedSourceFiles(thisTime,thisTime);
} else {
addAffectedSourceFiles(thisTime,compiledSourceFiles);
}
compiledSourceFiles = thisTime;
return thisTime;
}
private boolean maybeIncremental() {
return (FORCE_INCREMENTAL_DURING_TESTING || this.couldBeSubsequentIncrementalBuild);
}
public Map /* String -> List<ucf> */ getBinaryFilesToCompile(boolean firstTime) {
if (lastSuccessfulBuildTime == -1 || buildConfig == null || !maybeIncremental()) {
return binarySourceFiles;
}
// else incremental...
Map toWeave = new HashMap();
if (firstTime) {
List addedOrModified = new ArrayList();
addedOrModified.addAll(addedBinaryFiles);
addedOrModified.addAll(getModifiedBinaryFiles());
for (Iterator iter = addedOrModified.iterator(); iter.hasNext();) {
AjBuildConfig.BinarySourceFile bsf = (AjBuildConfig.BinarySourceFile) iter.next();
UnwovenClassFile ucf = createUnwovenClassFile(bsf);
if (ucf == null) continue;
List ucfs = new ArrayList();
ucfs.add(ucf);
addDependentsOf(ucf.getClassName());
binarySourceFiles.put(bsf.binSrc.getPath(),ucfs);
List cfs = new ArrayList(1);
cfs.add(getClassFileFor(ucf));
this.inputClassFilesBySource.put(bsf.binSrc.getPath(), cfs);
toWeave.put(bsf.binSrc.getPath(),ucfs);
}
deleteBinaryClassFiles();
} else {
// return empty set... we've already done our bit.
}
return toWeave;
}
/**
* Called when a path change is about to trigger a full build, but
* we haven't cleaned up from the last incremental build...
*/
private void removeAllResultsOfLastBuild() {
// remove all binarySourceFiles, and all classesFromName...
for (Iterator iter = this.inputClassFilesBySource.values().iterator(); iter.hasNext();) {
List cfs = (List) iter.next();
for (Iterator iterator = cfs.iterator(); iterator.hasNext();) {
ClassFile cf = (ClassFile) iterator.next();
cf.deleteFromFileSystem();
}
}
for (Iterator iterator = classesFromName.values().iterator(); iterator.hasNext();) {
File f = (File) iterator.next();
new ClassFile("",f).deleteFromFileSystem();
}
for (Iterator iter = resources.iterator(); iter.hasNext();) {
String resource = (String) iter.next();
new File(buildConfig.getOutputDir(),resource).delete();
}
}
private void deleteClassFiles() {
for (Iterator i = deletedFiles.iterator(); i.hasNext(); ) {
File deletedFile = (File)i.next();
addDependentsOf(deletedFile);
List cfs = (List) this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(deletedFile);
this.fullyQualifiedTypeNamesResultingFromCompilationUnit.remove(deletedFile);
if (cfs != null) {
for (Iterator iter = cfs.iterator(); iter.hasNext();) {
ClassFile cf = (ClassFile) iter.next();
deleteClassFile(cf);
}
}
}
}
private void deleteBinaryClassFiles() {
// range of bsf is ucfs, domain is files (.class and jars) in inpath/jars
for (Iterator iter = deletedBinaryFiles.iterator(); iter.hasNext();) {
AjBuildConfig.BinarySourceFile deletedFile = (AjBuildConfig.BinarySourceFile) iter.next();
List cfs = (List) this.inputClassFilesBySource.get(deletedFile.binSrc.getPath());
for (Iterator iterator = cfs.iterator(); iterator.hasNext();) {
deleteClassFile((ClassFile)iterator.next());
}
this.inputClassFilesBySource.remove(deletedFile.binSrc.getPath());
}
}
private void deleteResources() {
List oldResources = new ArrayList();
oldResources.addAll(resources);
// note - this deliberately ignores resources in jars as we don't yet handle jar changes
// with incremental compilation
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (inPathElement.isDirectory() && AjBuildManager.COPY_INPATH_DIR_RESOURCES) {
deleteResourcesFromDirectory(inPathElement,oldResources);
}
}
if (buildConfig.getSourcePathResources() != null) {
for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) {
String resource = (String)i.next();
maybeDeleteResource(resource, oldResources);
}
}
// oldResources need to be deleted...
for (Iterator iter = oldResources.iterator(); iter.hasNext();) {
String victim = (String) iter.next();
File f = new File(buildConfig.getOutputDir(),victim);
if (f.exists()) {
f.delete();
}
resources.remove(victim);
}
}
private void maybeDeleteResource(String resName, List oldResources) {
if (resources.contains(resName)) {
oldResources.remove(resName);
File source = new File(buildConfig.getOutputDir(),resName);
if ((source != null) && (source.exists()) &&
(source.lastModified() >= lastSuccessfulBuildTime)) {
resources.remove(resName); // will ensure it is re-copied
}
}
}
private void deleteResourcesFromDirectory(File dir, List oldResources) {
File[] files = FileUtil.listFiles(dir,new FileFilter() {
public boolean accept(File f) {
boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")) ;
return accept;
}
});
// For each file, add it either as a real .class file or as a resource
for (int i = 0; i < files.length; i++) {
// ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
// or we are in trouble...
String filename = files[i].getAbsolutePath().substring(
dir.getAbsolutePath().length()+1);
maybeDeleteResource(filename, oldResources);
}
}
private void deleteClassFile(ClassFile cf) {
classesFromName.remove(cf.fullyQualifiedTypeName);
weaver.deleteClassFile(cf.fullyQualifiedTypeName);
cf.deleteFromFileSystem();
}
private UnwovenClassFile createUnwovenClassFile(AjBuildConfig.BinarySourceFile bsf) {
UnwovenClassFile ucf = null;
try {
ucf = weaver.addClassFile(bsf.binSrc, bsf.fromInPathDirectory, buildConfig.getOutputDir());
} catch(IOException ex) {
IMessage msg = new Message("can't read class file " + bsf.binSrc.getPath(),
new SourceLocation(bsf.binSrc,0),false);
buildManager.handler.handleMessage(msg);
}
return ucf;
}
public void noteResult(InterimCompilationResult result) {
if (!maybeIncremental()) {
return;
}
File sourceFile = new File(result.fileName());
CompilationResult cr = result.result();
if (result != null) {
references.put(sourceFile, new ReferenceCollection(cr.qualifiedReferences, cr.simpleNameReferences));
}
UnwovenClassFile[] unwovenClassFiles = result.unwovenClassFiles();
for (int i = 0; i < unwovenClassFiles.length; i++) {
File lastTimeRound = (File) classesFromName.get(unwovenClassFiles[i].getClassName());
recordClassFile(unwovenClassFiles[i],lastTimeRound);
classesFromName.put(unwovenClassFiles[i].getClassName(),new File(unwovenClassFiles[i].getFilename()));
}
// need to do this before types are deleted from the World...
recordWhetherCompilationUnitDefinedAspect(sourceFile,cr);
deleteTypesThatWereInThisCompilationUnitLastTimeRoundButHaveBeenDeletedInThisIncrement(sourceFile, unwovenClassFiles);
recordFQNsResultingFromCompilationUnit(sourceFile,result);
}
/**
* Currently unused, if we ditch classesFromName, we might need this.... (in noteResult)
* @param file
* @return
*/
private UnwovenClassFile maybeGetExistingClassFileFor(UnwovenClassFile classFile) {
File existing = new File(classFile.getFilename());
if (!existing.exists()) {
return null;
}
else {
try {
return new UnwovenClassFile(classFile.getFilename(),FileUtil.readAsByteArray(existing));
}
catch (IOException ex) {
throw new IllegalStateException("Unable to read contents of '" + classFile.getFilename() + "' " +
"from last compile cycle");
}
}
}
/**
* @param sourceFile
* @param unwovenClassFiles
*/
private void deleteTypesThatWereInThisCompilationUnitLastTimeRoundButHaveBeenDeletedInThisIncrement(File sourceFile, UnwovenClassFile[] unwovenClassFiles) {
List classFiles = (List) this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(sourceFile);
if (classFiles != null) {
for (int i = 0; i < unwovenClassFiles.length; i++) {
// deleting also deletes types from the weaver... don't do this if they are
// still present this time around...
removeFromClassFilesIfPresent(unwovenClassFiles[i].getClassName(),classFiles);
}
for (Iterator iter = classFiles.iterator(); iter.hasNext();) {
ClassFile cf = (ClassFile) iter.next();
deleteClassFile(cf);
}
}
}
private void removeFromClassFilesIfPresent(String className, List classFiles) {
ClassFile victim = null;
for (Iterator iter = classFiles.iterator(); iter.hasNext();) {
ClassFile cf = (ClassFile) iter.next();
if (cf.fullyQualifiedTypeName.equals(className)) {
victim = cf;
break;
}
}
if (victim != null) {
classFiles.remove(victim);
}
}
/**
* Record the fully-qualified names of the types that were declared in the given
* source file.
*
* @param sourceFile, the compilation unit
* @param icr, the CompilationResult from compiling it
*/
private void recordFQNsResultingFromCompilationUnit(File sourceFile, InterimCompilationResult icr) {
List classFiles = new ArrayList();
UnwovenClassFile[] types = icr.unwovenClassFiles();
for (int i = 0; i < types.length; i++) {
classFiles.add(new ClassFile(types[i].getClassName(),new File(types[i].getFilename())));
}
this.fullyQualifiedTypeNamesResultingFromCompilationUnit.put(sourceFile,classFiles);
}
/**
* If this compilation unit defined an aspect, we need to know in case it is
* modified in a future increment.
*
* @param sourceFile
* @param cr
*/
private void recordWhetherCompilationUnitDefinedAspect(File sourceFile, CompilationResult cr) {
this.sourceFilesDefiningAspects.remove(sourceFile);
if (cr!=null) {
Map compiledTypes = cr.compiledTypes;
if (compiledTypes!=null) {
for (Iterator iterator = compiledTypes.keySet().iterator(); iterator.hasNext();) {
char[] className = (char[])iterator.next();
String typeName = new String(className).replace('/','.');
if (typeName.indexOf(IWeaver.SYNTHETIC_CLASS_POSTFIX) == -1) {
ResolvedType rt = world.resolve(typeName);
if (rt.isMissing()) {
throw new IllegalStateException("Type '" + rt.getSignature() + "' not found in world!");
}
if (rt.isAspect()) {
this.sourceFilesDefiningAspects.add(sourceFile);
break;
}
}
}
}
}
}
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, File lastTime) {
if (simpleStrings == null) {
// batch build
// record resolved type for structural comparisions in future increments
// this records a second reference to a structure already held in memory
// by the world.
ResolvedType rType = world.resolve(thisTime.getClassName());
if (!rType.isMissing()) {
this.resolvedTypeStructuresFromLastBuild.put(thisTime.getClassName(),new CompactStructureRepresentation(rType));
}
return;
}
CompactStructureRepresentation existingStructure = (CompactStructureRepresentation) this.resolvedTypeStructuresFromLastBuild.get(thisTime.getClassName());
ReferenceType newResolvedType = (ReferenceType) world.resolve(thisTime.getClassName());
if (!newResolvedType.isMissing()) {
this.resolvedTypeStructuresFromLastBuild.put(thisTime.getClassName(),new CompactStructureRepresentation(newResolvedType));
}
if (lastTime == null) {
addDependentsOf(thisTime.getClassName());
return;
}
if (newResolvedType.isMissing()) {
return;
}
byte[] newBytes = thisTime.getBytes();
try {
ClassFileReader reader = new ClassFileReader(newBytes, lastTime.getAbsolutePath().toCharArray());
// ignore local types since they're only visible inside a single method
if (!(reader.isLocal() || reader.isAnonymous())) {
if (hasStructuralChanges(reader,existingStructure)) {
structuralChangesSinceLastFullBuild.put(thisTime.getFilename(),new Long(currentBuildTime));
addDependentsOf(new String(reader.getName()).replace('/','.'));
}
}
} catch (ClassFormatException e) {
addDependentsOf(thisTime.getClassName());
}
}
/**
* Compare the class structure of the new intermediate (unwoven) class with the
* existingResolvedType of the same class that we have in the world, looking for
* any structural differences (and ignoring aj members resulting from weaving....)
*
* Warning : long but boring method implementation...
* @param reader
* @param existingType
* @return
*/
private boolean hasStructuralChanges(ClassFileReader reader, CompactStructureRepresentation existingType) {
// mirrors the checks in ClassFileReader.hasStructuralChanges, but compares against
// ref type delegate instead of old bytes
if (existingType == null) {
return true;
}
// modifiers
if (!modifiersEqual(reader.getModifiers(),existingType.modifiers)) {
return true;
}
// generic signature
if (!CharOperation.equals(reader.getGenericSignature(),existingType.genericSignature)) {
return true;
}
// superclass name
if (!CharOperation.equals(reader.getSuperclassName(),existingType.superclassName)) {
return true;
}
// interfaces
char[][] existingIfs = existingType.interfaces;
char[][] newIfsAsChars = reader.getInterfaceNames();
if (newIfsAsChars == null) { newIfsAsChars = new char[0][]; }
char[][] newIfs = new char[newIfsAsChars.length][];
if (existingIfs.length != newIfs.length) {
return true;
}
new_interface_loop: for (int i = 0; i < newIfs.length; i++) {
for (int j = 0; j < existingIfs.length; j++) {
if (CharOperation.equals(existingIfs[j],newIfs[i])) {
continue new_interface_loop;
}
}
return true;
}
// fields
MemberStructure[] existingFields = existingType.fields;
IBinaryField[] newFields = reader.getFields();
if (newFields == null) { newFields = new IBinaryField[0]; }
// remove any ajc$XXX fields from those we compare with
// the existing fields - bug 129163
List nonGenFields = new ArrayList();
for (int i = 0; i < newFields.length; i++) {
IBinaryField field = newFields[i];
if (!CharOperation.prefixEquals(NameMangler.AJC_DOLLAR_PREFIX,field.getName())) {
nonGenFields.add(field);
}
}
if (nonGenFields.size() != existingFields.length) {
return true;
}
new_field_loop: for (Iterator iter = nonGenFields.iterator(); iter.hasNext();) {
IBinaryField field = (IBinaryField) iter.next();
char[] fieldName = field.getName();
for (int j = 0; j < existingFields.length; j++) {
if (CharOperation.equals(existingFields[j].name,fieldName)) {
if (!modifiersEqual(field.getModifiers(),existingFields[j].modifiers)) {
return true;
}
if (!CharOperation.equals(existingFields[j].signature,field.getTypeName())) {
return true;
}
continue new_field_loop;
}
}
return true;
}
// methods
MemberStructure[] existingMethods = existingType.methods;
IBinaryMethod[] newMethods = reader.getMethods();
if (newMethods == null) { newMethods = new IBinaryMethod[0]; }
// remove the aspectOf, hasAspect, clinit and ajc$XXX methods
// from those we compare with the existing methods - bug 129163
List nonGenMethods = new ArrayList();
for (int i = 0; i < newMethods.length; i++) {
IBinaryMethod method = newMethods[i];
char[] methodName = method.getSelector();
if (!CharOperation.equals(methodName,NameMangler.METHOD_ASPECTOF) &&
!CharOperation.equals(methodName,NameMangler.METHOD_HASASPECT) &&
!CharOperation.equals(methodName,NameMangler.STATIC_INITIALIZER) &&
!CharOperation.prefixEquals(NameMangler.AJC_DOLLAR_PREFIX,methodName)) {
nonGenMethods.add(method);
}
}
if (nonGenMethods.size() != existingMethods.length) {
return true;
}
new_method_loop: for (Iterator iter = nonGenMethods.iterator(); iter.hasNext();) {
IBinaryMethod method = (IBinaryMethod) iter.next();
char[] methodName = method.getSelector();
for (int j = 0; j < existingMethods.length; j++) {
if (CharOperation.equals(existingMethods[j].name,methodName)) {
// candidate match
if (!CharOperation.equals(method.getMethodDescriptor(),existingMethods[j].signature)) {
continue; // might be overloading
}
else {
// matching sigs
if (!modifiersEqual(method.getModifiers(),existingMethods[j].modifiers)) {
return true;
}
continue new_method_loop;
}
}
}
return true; // (no match found)
}
return false;
}
private boolean modifiersEqual(int eclipseModifiers, int resolvedTypeModifiers) {
resolvedTypeModifiers = resolvedTypeModifiers & CompilerModifiers.AccJustFlag;
eclipseModifiers = eclipseModifiers & CompilerModifiers.AccJustFlag;
if ((eclipseModifiers & CompilerModifiers.AccSuper) != 0) {
eclipseModifiers -= CompilerModifiers.AccSuper;
}
return (eclipseModifiers == resolvedTypeModifiers);
}
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) {
List cfs = (List) this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(sourceFile);
if (cfs != null) {
for (Iterator iter = cfs.iterator(); iter.hasNext();) {
ClassFile cf = (ClassFile) iter.next();
addDependentsOf(cf.fullyQualifiedTypeName);
}
}
}
public void setStructureModel(IHierarchy model) {
structureModel = model;
}
public IHierarchy getStructureModel() {
return structureModel;
}
public void setWeaver(BcelWeaver bw) { weaver=bw;}
public BcelWeaver getWeaver() {return weaver;}
public void setWorld(BcelWorld bw) {world=bw;}
public BcelWorld getBcelWorld() {return world; }
public void setRelationshipMap(IRelationshipMap irm) { relmap = irm;}
public IRelationshipMap getRelationshipMap() { return relmap;}
public int getNumberOfStructuralChangesSinceLastFullBuild() {
return structuralChangesSinceLastFullBuild.size();
}
/** Returns last time we did a full or incremental build. */
public long getLastBuildTime() {
return lastSuccessfulBuildTime;
}
/** Returns last time we did a full build */
public long getLastFullBuildTime() {
return lastSuccessfulFullBuildTime;
}
/**
* @return Returns the buildConfig.
*/
public AjBuildConfig getBuildConfig() {
return this.buildConfig;
}
public void clearBinarySourceFiles() {
this.binarySourceFiles = new HashMap();
}
public void recordBinarySource(String fromPathName, List unwovenClassFiles) {
this.binarySourceFiles.put(fromPathName,unwovenClassFiles);
if (this.maybeIncremental()) {
List simpleClassFiles = new LinkedList();
for (Iterator iter = unwovenClassFiles.iterator(); iter.hasNext();) {
UnwovenClassFile ucf = (UnwovenClassFile) iter.next();
ClassFile cf = getClassFileFor(ucf);
simpleClassFiles.add(cf);
}
this.inputClassFilesBySource.put(fromPathName,simpleClassFiles);
}
}
/**
* @param ucf
* @return
*/
private ClassFile getClassFileFor(UnwovenClassFile ucf) {
return new ClassFile(ucf.getClassName(),new File(ucf.getFilename()));
}
public Map getBinarySourceMap() {
return this.binarySourceFiles;
}
public Map getClassNameToFileMap() {
return this.classesFromName;
}
public boolean hasResource(String resourceName) {
return this.resources.contains(resourceName);
}
public void recordResource(String resourceName) {
this.resources.add(resourceName);
}
/**
* @return Returns the addedFiles.
*/
public Set getAddedFiles() {
return this.addedFiles;
}
/**
* @return Returns the deletedFiles.
*/
public Set getDeletedFiles() {
return this.deletedFiles;
}
public void forceBatchBuildNextTimeAround() {
this.batchBuildRequiredThisTime = true;
}
public boolean requiresFullBatchBuild() {
return this.batchBuildRequiredThisTime;
}
private static class ClassFile {
public String fullyQualifiedTypeName;
public File locationOnDisk;
public ClassFile(String fqn, File location) {
this.fullyQualifiedTypeName = fqn;
this.locationOnDisk = location;
}
public void deleteFromFileSystem() {
String namePrefix = locationOnDisk.getName();
namePrefix = namePrefix.substring(0,namePrefix.lastIndexOf('.'));
final String targetPrefix = namePrefix + IWeaver.CLOSURE_CLASS_PREFIX;
File dir = locationOnDisk.getParentFile();
if (dir != null) {
File[] weaverGenerated = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(targetPrefix);
}});
if (weaverGenerated!=null) {
for (int i = 0; i < weaverGenerated.length; i++) {
weaverGenerated[i].delete();
}
}
}
locationOnDisk.delete();
}
}
private static class CompactStructureRepresentation {
public CompactStructureRepresentation(ResolvedType forType) {
this.className = forType.getName().replace('.','/').toCharArray();
this.modifiers = forType.getModifiers();
this.genericSignature = forType.getGenericSignature().toCharArray();
if (this.genericSignature.length == 0) {
this.genericSignature = null;
}
this.superclassName = forType.getSuperclass().getName().replace('.','/').toCharArray();
ResolvedType[] rTypes = forType.getDeclaredInterfaces();
this.interfaces = new char[rTypes.length][];
for (int i = 0; i < rTypes.length; i++) {
this.interfaces[i] = rTypes[i].getName().replace('.','/').toCharArray();
}
ResolvedMember[] rFields = forType.getDeclaredFields();
this.fields = new MemberStructure[rFields.length];
for (int i = 0; i < rFields.length; i++) {
this.fields[i] = new MemberStructure();
this.fields[i].name = rFields[i].getName().toCharArray();
this.fields[i].modifiers = rFields[i].getModifiers();
this.fields[i].signature = rFields[i].getReturnType().getSignature().toCharArray();
}
ResolvedMember[] rMethods = forType.getDeclaredMethods();
this.methods = new MemberStructure[rMethods.length];
for (int i = 0; i < rMethods.length; i++) {
this.methods[i] = new MemberStructure();
this.methods[i].name = rMethods[i].getName().toCharArray();
this.methods[i].modifiers = rMethods[i].getModifiers();
StringBuffer sig = new StringBuffer();
sig.append("(");
UnresolvedType[] pTypes = rMethods[i].getParameterTypes();
for (int j = 0; j < pTypes.length; j++) {
sig.append(pTypes[j].getSignature());
}
sig.append(")");
sig.append(rMethods[i].getReturnType().getSignature());
this.methods[i].signature = sig.toString().toCharArray();
}
}
char[] className;
int modifiers;
char[] genericSignature;
char[] superclassName;
char[][] interfaces;
MemberStructure[] fields;
MemberStructure[] methods;
}
private static class MemberStructure {
char[] name;
int modifiers;
char[] signature;
}
public void wipeAllKnowledge() {
buildManager.state = null;
buildManager.setStructureModel(null);
}
}
|
131,505 |
Bug 131505 Generated aop.xml files contain aspects for all the projects ever built
|
Using the -outxml option in AJDT the generated aop.xml files are not correct after the first build and contain all the aspects that have ever been built (including those in different projects and duplicates if an aspect has been built twice). It seems that there is a global list of aspects (aspectNames in AjBuildManager) that is never cleared.
|
resolved fixed
|
b3cd01d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-15T12:34:48Z | 2006-03-13T11:40:00Z |
tests/multiIncremental/PR131505/base/C.java
| |
131,505 |
Bug 131505 Generated aop.xml files contain aspects for all the projects ever built
|
Using the -outxml option in AJDT the generated aop.xml files are not correct after the first build and contain all the aspects that have ever been built (including those in different projects and duplicates if an aspect has been built twice). It seems that there is a global list of aspects (aspectNames in AjBuildManager) that is never cleared.
|
resolved fixed
|
b3cd01d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-15T12:34:48Z | 2006-03-13T11:40:00Z |
tests/multiIncremental/PR131505/inc2/C.java
| |
131,505 |
Bug 131505 Generated aop.xml files contain aspects for all the projects ever built
|
Using the -outxml option in AJDT the generated aop.xml files are not correct after the first build and contain all the aspects that have ever been built (including those in different projects and duplicates if an aspect has been built twice). It seems that there is a global list of aspects (aspectNames in AjBuildManager) that is never cleared.
|
resolved fixed
|
b3cd01d
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-15T12:34:48Z | 2006-03-13T11:40:00Z |
tests/src/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement initial implementation
* ******************************************************************/
package org.aspectj.systemtest.incremental.tools;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.aspectj.ajdt.internal.core.builder.AjState;
import org.aspectj.ajdt.internal.core.builder.IncrementalStateManager;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IProgramElement;
import org.aspectj.bridge.IMessage;
import org.aspectj.testing.util.FileUtil;
/**
* The superclass knows all about talking through Ajde to the compiler.
* The superclass isn't in charge of knowing how to simulate overlays
* for incremental builds, that is in here. As is the ability to
* generate valid build configs based on a directory structure. To
* support this we just need access to a sandbox directory - this
* sandbox is managed by the superclass (it only assumes all builds occur
* in <sandboxDir>/<projectName>/ )
*
* The idea is you can initialize multiple projects in the sandbox and
* they can all be built independently, hopefully exploiting
* incremental compilation. Between builds you can alter the contents
* of a project using the alter() method that overlays some set of
* new files onto the current set (adding new files/changing existing
* ones) - you can then drive a new build and check it behaves as
* expected.
*/
public class MultiProjectIncrementalTests extends AjdeInteractionTestbed {
public static boolean VERBOSE = false;
protected void setUp() throws Exception {
super.setUp();
AjdeInteractionTestbed.VERBOSE = VERBOSE;
AjState.FORCE_INCREMENTAL_DURING_TESTING = true;
}
protected void tearDown() throws Exception {
super.tearDown();
AjState.FORCE_INCREMENTAL_DURING_TESTING = false;
}
// Compile a single simple project
public void testTheBasics() {
initialiseProject("P1");
build("P1"); // This first build will be batch
build("P1");
checkWasntFullBuild();
checkCompileWeaveCount(0,0);
}
// source code doesnt matter, we are checking invalid path handling
public void testInvalidAspectpath_pr121395() {
initialiseProject("P1");
File f = new File("foo.jar");
Set s = new HashSet();
s.add(f);
configureAspectPath(s);
build("P1"); // This first build will be batch
checkForError("invalid aspectpath entry");
}
// Make simple changes to a project, adding a class
public void testSimpleChanges() {
initialiseProject("P1");
build("P1"); // This first build will be batch
alter("P1","inc1"); // adds a single class
build("P1");
checkCompileWeaveCount(1,-1);
build("P1");
checkCompileWeaveCount(0,-1);
}
// Make simple changes to a project, adding a class and an aspect
public void testAddingAnAspect() {
initialiseProject("P1");
build("P1"); // build 1, weave 1
alter("P1","inc1"); // adds a class
alter("P1","inc2"); // adds an aspect
build("P1"); // build 1,
long timeTakenForFullBuildAndWeave = getTimeTakenForBuild();
checkWasFullBuild(); // it *will* be a full build under the new
// "back-to-the-source strategy
checkCompileWeaveCount(5,3); // we compile X and A (the delta) find out that
// an aspect has changed, go back to the source
// and compile X,A,C, then weave them all.
build("P1");
long timeTakenForSimpleIncBuild = getTimeTakenForBuild();
// I don't think this test will have timing issues as the times should be *RADICALLY* different
// On my config, first build time is 2093ms and the second is 30ms
assertTrue("Should not take longer for the trivial incremental build! first="+timeTakenForFullBuildAndWeave+
"ms second="+timeTakenForSimpleIncBuild+"ms",
timeTakenForSimpleIncBuild<timeTakenForFullBuildAndWeave);
}
public void testBuildingTwoProjectsInTurns() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
build("P2");
build("P1");
checkWasntFullBuild();
build("P2");
checkWasntFullBuild();
}
/**
* In order for this next test to run, I had to move the weaver/world pair we keep in the
* AjBuildManager instance down into the state object - this makes perfect sense - otherwise
* when reusing the state for another project we'd not be switching to the right weaver/world
* for that project.
*/
public void testBuildingTwoProjectsMakingSmallChanges() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
build("P2");
build("P1");
checkWasntFullBuild();
build("P2");
checkWasntFullBuild();
alter("P1","inc1"); // adds a class
alter("P1","inc2"); // adds an aspect
build("P1");
checkWasFullBuild(); // adding an aspect makes us go back to the source
}
/**
* Setup up two simple projects and build them in turn - check the
* structure model is right after each build
*/
public void testBuildingTwoProjectsAndVerifyingModel() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
}
// Setup up two simple projects and build them in turn - check the
// structure model is right after each build
public void testBuildingTwoProjectsAndVerifyingStuff() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
}
/**
* Complex. Here we are testing that a state object records structural changes since
* the last full build correctly. We build a simple project from scratch - this will
* be a full build and so the structural changes since last build count should be 0.
* We then alter a class, adding a new method and check structural changes is 1.
*/
public void testStateManagement1() {
File binDirectoryForP1 = new File(getFile("P1","bin"));
initialiseProject("P1");
build("P1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1);
assertTrue("There should be a state object for project P1",ajs!=null);
assertTrue("Should be no structural changes as it was a full build but found: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("P1","inc3"); // adds a method to the class C.java
build("P1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin")));
assertTrue("There should be state for project P1",ajs!=null);
checkWasntFullBuild();
assertTrue("Should be one structural changes as it was a full build but found: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==1);
}
/**
* Complex. Here we are testing that a state object records structural changes since
* the last full build correctly. We build a simple project from scratch - this will
* be a full build and so the structural changes since last build count should be 0.
* We then alter a class, changing body of a method, not the structure and
* check struc changes is still 0.
*/
public void testStateManagement2() {
File binDirectoryForP1 = new File(getFile("P1","bin"));
initialiseProject("P1");
alter("P1","inc3"); // need this change in here so 'inc4' can be applied without making
// it a structural change
build("P1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1);
assertTrue("There should be state for project P1",ajs!=null);
assertTrue("Should be no struc changes as its a full build: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("P1","inc4"); // changes body of main() method but does *not* change the structure of C.java
build("P1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin")));
assertTrue("There should be state for project P1",ajs!=null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
}
/**
* Now the most complex test. Create a dependancy between two projects. Building
* one may affect whether the other does an incremental or full build. The
* structural information recorded in the state object should be getting used
* to control whether a full build is necessary...
*/
public void testBuildingDependantProjects() {
initialiseProject("P1");
initialiseProject("P2");
configureNewProjectDependency("P2","P1");
build("P1");
build("P2"); // now everything is consistent and compiled
alter("P1","inc1"); // adds a second class
build("P1");
build("P2"); // although a second class was added - P2 can't be using it, so we don't full build here :)
checkWasntFullBuild();
alter("P1","inc3"); // structurally changes one of the classes
build("P1");
build("P2"); // build notices the structural change
checkWasFullBuild();
alter("P1","inc4");
build("P1");
build("P2"); // build sees a change but works out its not structural
checkWasntFullBuild();
}
public void testPr85132() {
initialiseProject("PR85132");
build("PR85132");
alter("PR85132","inc1");
build("PR85132");
}
// parameterization of generic aspects
public void testPr125405() {
initialiseProject("PR125405");
build("PR125405");
checkCompileWeaveCount(1,1);
alter("PR125405","inc1");
build("PR125405");
// "only abstract aspects can have type parameters"
checkForError("only abstract aspects can have type parameters");
alter("PR125405","inc2");
build("PR125405");
checkCompileWeaveCount(1,1);
assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0);
}
public void testPr128618() {
initialiseProject("PR128618_1");
initialiseProject("PR128618_2");
configureNewProjectDependency("PR128618_2","PR128618_1");
assertTrue("there should be no warning messages before we start",
MyTaskListManager.getWarningMessages().isEmpty());
build("PR128618_1");
build("PR128618_2");
List warnings = MyTaskListManager.getWarningMessages();
assertTrue("Should be one warning, but there are #"+warnings.size(),warnings.size()==1);
IMessage msg = (IMessage)(MyTaskListManager.getWarningMessages().get(0));
assertEquals("warning should be against the FFDC.aj resource","FFDC.aj",msg.getSourceLocation().getSourceFile().getName());
alter("PR128618_2","inc1");
build("PR128618_2");
checkWasntFullBuild();
IMessage msg2 = (IMessage)(MyTaskListManager.getWarningMessages().get(0));
assertEquals("warning should be against the FFDC.aj resource","FFDC.aj",msg2.getSourceLocation().getSourceFile().getName());
assertFalse("a new warning message should have been generated", msg.equals(msg2));
}
public void testPr92837() {
initialiseProject("PR92837");
build("PR92837");
alter("PR92837","inc1");
build("PR92837");
}
public void testPr119570() {
initialiseProject("PR119570");
build("PR119570");
assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0);
}
public void testPr119570_2() {
initialiseProject("PR119570_2");
build("PR119570_2");
List l = MyTaskListManager.getWarningMessages();
assertTrue("Should be no warnings, but got "+l,l.size()==0);
}
// If you fiddle with the compiler options - you must manually reset the options at the end of the test
public void testPr117209() {
try {
initialiseProject("pr117209");
configureNonStandardCompileOptions("-proceedOnError");
build("pr117209");
checkCompileWeaveCount(6,6);
} finally {
MyBuildOptionsAdapter.reset();
}
}
public void testPr114875() {
initialiseProject("pr114875");
build("pr114875");
alter("pr114875","inc1");
build("pr114875");
checkWasFullBuild();
alter("pr114875","inc2");
build("pr114875");
checkWasFullBuild(); // back to the source for an aspect change
}
public void testPr117882() {
// AjdeInteractionTestbed.VERBOSE=true;
// AjdeInteractionTestbed.configureBuildStructureModel(true);
initialiseProject("PR117882");
build("PR117882");
checkWasFullBuild();
alter("PR117882","inc1");
build("PR117882");
checkWasFullBuild(); // back to the source for an aspect
// AjdeInteractionTestbed.VERBOSE=false;
// AjdeInteractionTestbed.configureBuildStructureModel(false);
}
public void testPr117882_2() {
// AjdeInteractionTestbed.VERBOSE=true;
// AjdeInteractionTestbed.configureBuildStructureModel(true);
initialiseProject("PR117882_2");
build("PR117882_2");
checkWasFullBuild();
alter("PR117882_2","inc1");
build("PR117882_2");
checkWasFullBuild(); // back to the source...
//checkCompileWeaveCount(1,4);
//fullBuild("PR117882_2");
//checkWasFullBuild();
// AjdeInteractionTestbed.VERBOSE=false;
// AjdeInteractionTestbed.configureBuildStructureModel(false);
}
public void testPr115251() {
//AjdeInteractionTestbed.VERBOSE=true;
initialiseProject("PR115251");
build("PR115251");
checkWasFullBuild();
alter("PR115251","inc1");
build("PR115251");
checkWasFullBuild(); // back to the source
}
// public void testPr124399() {
// AjdeInteractionTestbed.VERBOSE=true;
// configureBuildStructureModel(true);
// initialiseProject("PR124399");
// build("PR124399");
// checkWasFullBuild();
// alter("PR124399","inc1");
// build("PR124399");
// checkWasntFullBuild();
// }
public void testPr121384() {
// AjdeInteractionTestbed.VERBOSE=true;
// AsmManager.setReporting("c:/foo.txt",true,true,true,false);
MyBuildOptionsAdapter.setNonStandardOptions("-showWeaveInfo");
configureBuildStructureModel(true);
initialiseProject("pr121384");
build("pr121384");
checkWasFullBuild();
alter("pr121384","inc1");
build("pr121384");
checkWasntFullBuild();
}
/* public void testPr111779() {
super.VERBOSE=true;
initialiseProject("PR111779");
build("PR111779");
alter("PR111779","inc1");
build("PR111779");
}
*/
public void testPr93310_1() {
initialiseProject("PR93310_1");
build("PR93310_1");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_1" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java";
(new File(fileC2)).delete();
alter("PR93310_1","inc1");
build("PR93310_1");
checkWasFullBuild();
int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size();
assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1);
String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0);
assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java"));
}
public void testPr93310_2() {
initialiseProject("PR93310_2");
build("PR93310_2");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_2" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java";
(new File(fileC2)).delete();
alter("PR93310_2","inc1");
build("PR93310_2");
checkWasFullBuild();
int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size();
assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1);
String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0);
assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java"));
}
// Stage1: Compile two files, pack.A and pack.A1 - A1 sets a protected field in A.
// Stage2: make the field private in class A > gives compile error
// Stage3: Add a new aspect whilst there is a compile error !
public void testPr113531() {
initialiseProject("PR113531");
build("PR113531");
assertFalse("build should have compiled ok",
MyTaskListManager.hasErrorMessages());
alter("PR113531","inc1");
build("PR113531");
assertEquals("error message should be 'foo cannot be resolved' ",
"foo cannot be resolved",
((IMessage)MyTaskListManager.getErrorMessages().get(0))
.getMessage());
alter("PR113531","inc2");
build("PR113531");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
assertEquals("error message should be 'foo cannot be resolved' ",
"foo cannot be resolved",
((IMessage)MyTaskListManager.getErrorMessages().get(0))
.getMessage());
}
// Stage 1: Compile the 4 files, pack.A2 extends pack.A1 (aspects) where
// A2 uses a protected field in A1 and pack.C2 extends pack.C1 (classes)
// where C2 uses a protected field in C1
// Stage 2: make the field private in class C1 ==> compile errors in C2
// Stage 3: make the field private in aspect A1 whilst there's the compile
// error.
// There shouldn't be a BCExcpetion saying can't find delegate for pack.C2
public void testPr119882() {
initialiseProject("PR119882");
build("PR119882");
assertFalse("build should have compiled ok",MyTaskListManager.hasErrorMessages());
alter("PR119882","inc1");
build("PR119882");
//fullBuild("PR119882");
assertEquals("error message should be 'i cannot be resolved' ",
"i cannot be resolved",
((IMessage)MyTaskListManager.getErrorMessages().get(0))
.getMessage());
alter("PR119882","inc2");
build("PR119882");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
assertEquals("error message should be 'i cannot be resolved' ",
"i cannot be resolved",
((IMessage)MyTaskListManager.getErrorMessages().get(0))
.getMessage());
}
public void testPr112736() {
// AjdeInteractionTestbed.VERBOSE = true;
initialiseProject("PR112736");
build("PR112736");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR112736" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "A.java";
(new File(fileC2)).delete();
alter("PR112736","inc1");
build("PR112736");
checkWasFullBuild();
}
/**
* We have problems with multiple rewrites of a pointcut across incremental builds.
*/
public void testPr113257() {
initialiseProject("PR113257");
build("PR113257");
alter("PR113257","inc1");
build("PR113257");
checkWasFullBuild(); // back to the source
alter("PR113257","inc1");
build("PR113257");
}
public void testPr123612() {
initialiseProject("PR123612");
build("PR123612");
alter("PR123612","inc1");
build("PR123612");
checkWasFullBuild(); // back to the source
}
public void testPr128655() {
configureNonStandardCompileOptions("-showWeaveInfo");
initialiseProject("pr128655");
build("pr128655");
List firstBuildMessages = MyTaskListManager.getWeavingMessages();
assertTrue("Should be at least one message about the dec @type, but there were none",firstBuildMessages.size()>0);
alter("pr128655","inc1");
build("pr128655");
checkWasntFullBuild(); // back to the source
List secondBuildMessages = MyTaskListManager.getWeavingMessages();
// check they are the same
for (int i = 0; i < firstBuildMessages.size(); i++) {
IMessage m1 = (IMessage)firstBuildMessages.get(i);
IMessage m2 = (IMessage)secondBuildMessages.get(i);
if (!m1.toString().equals(m2.toString())) {
System.err.println("Message during first build was: "+m1);
System.err.println("Message during second build was: "+m1);
fail("The two messages should be the same, but are not: \n"+m1+"!="+m2);
}
}
}
// Similar to above, but now the annotation is in the default package
public void testPr128655_2() {
configureNonStandardCompileOptions("-showWeaveInfo");
initialiseProject("pr128655_2");
build("pr128655_2");
List firstBuildMessages = MyTaskListManager.getWeavingMessages();
assertTrue("Should be at least one message about the dec @type, but there were none",firstBuildMessages.size()>0);
alter("pr128655_2","inc1");
build("pr128655_2");
checkWasntFullBuild(); // back to the source
List secondBuildMessages = MyTaskListManager.getWeavingMessages();
// check they are the same
for (int i = 0; i < firstBuildMessages.size(); i++) {
IMessage m1 = (IMessage)firstBuildMessages.get(i);
IMessage m2 = (IMessage)secondBuildMessages.get(i);
if (!m1.toString().equals(m2.toString())) {
System.err.println("Message during first build was: "+m1);
System.err.println("Message during second build was: "+m1);
fail("The two messages should be the same, but are not: \n"+m1+"!="+m2);
}
}
}
// test for comment #31 - NPE
public void testPr129163() {
configureBuildStructureModel(true);
initialiseProject("PR129613");
build("PR129613");
alter("PR129613","inc1");
build("PR129613");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
assertEquals("warning message should be 'no match for this type name: File [Xlint:invalidAbsoluteTypeName]' ",
"no match for this type name: File [Xlint:invalidAbsoluteTypeName]",
((IMessage)MyTaskListManager.getWarningMessages().get(0))
.getMessage());
configureBuildStructureModel(false);
}
// test for comment #0 - adding a comment to a class file shouldn't
// cause us to go back to source and recompile everything. To force this
// to behave like AJDT we need to include the aspect in 'inc1' so that
// when AjState looks at its timestamp it thinks the aspect has been modified.
// The logic within CrosscuttingMembers should then work out correctly
// that there haven't really been any changes within the aspect and so
// we shouldn't go back to source.
public void testPr129163_2() {
// want to behave like AJDT
configureBuildStructureModel(true);
initialiseProject("pr129163_2");
build("pr129163_2");
checkWasFullBuild();
alter("pr129163_2","inc1");
build("pr129163_2");
checkWasntFullBuild(); // shouldn't be a full build because the
// aspect hasn't changed
configureBuildStructureModel(false);
}
// test for comment #6 - simulates AJDT core builder test testBug99133a -
// changing the contents of a method within a class shouldn't force a
// full build of a dependant project. To force this to behave like AJDT
// 'inc1' of the dependant project should just be a copy of 'base' so that
// AjState thinks somethings changed within the dependant project and
// we do a build. Similarly, 'inc1' of the project depended on should
// include the aspect even though nothing's changed within it. This causes
// AjState to think that the aspect has changed. Together its then up to
// logic within CrosscuttingMembers and various equals methods to decide
// correctly that we don't have to go back to source.
public void testPr129163_3() {
configureBuildStructureModel(true);
initialiseProject("PR129163_4");
build("PR129163_4");
checkWasFullBuild(); // should be a full build because initializing project
initialiseProject("PR129163_3");
configureNewProjectDependency("PR129163_3","PR129163_4");
build("PR129163_3");
checkWasFullBuild(); // should be a full build because initializing project
alter("PR129163_4","inc1");
build("PR129163_4");
checkWasntFullBuild(); // should be an incremental build because although
// "inc1" includes the aspect A1.aj, it actually hasn't
// changed so we shouldn't go back to source
alter("PR129163_3","inc1");
build("PR129163_3");
checkWasntFullBuild(); // should be an incremental build because nothing has
// changed within the class and no aspects have changed
// within the running of the test
configureBuildStructureModel(false);
}
// other possible tests:
// - memory usage (freemem calls?)
// - relationship map
// ---------------------------------------------------------------------------------------------------
/**
* Check we compiled/wove the right number of files, passing '-1' indicates you don't care about
* that number.
*/
private void checkCompileWeaveCount(int expCompile,int expWoven) {
if (expCompile!=-1 && getCompiledFiles().size()!=expCompile)
fail("Expected compilation of "+expCompile+" files but compiled "+getCompiledFiles().size()+
"\n"+printCompiledAndWovenFiles());
if (expWoven!=-1 && getWovenClasses().size()!=expWoven)
fail("Expected weaving of "+expWoven+" files but wove "+getWovenClasses().size()+
"\n"+printCompiledAndWovenFiles());
}
private void checkWasntFullBuild() {
assertTrue("Shouldn't have been a full (batch) build",!wasFullBuild());
}
private void checkWasFullBuild() {
assertTrue("Should have been a full (batch) build",wasFullBuild());
}
private void checkForNode(String packageName,String typeName,boolean shouldBeFound) {
IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForType(packageName,typeName);
if (shouldBeFound) {
if (ipe==null) printModel();
assertTrue("Should have been able to find '"+packageName+"."+typeName+"' in the asm",ipe!=null);
} else {
if (ipe!=null) printModel();
assertTrue("Should have NOT been able to find '"+packageName+"."+typeName+"' in the asm",ipe==null);
}
}
private void printModel() {
try {
AsmManager.dumptree(AsmManager.getDefault().getHierarchy().getRoot(),0);
} catch (IOException e) {
e.printStackTrace();
}
}
public void build(String projectName) {
constructUpToDateLstFile(projectName,"build.lst");
build(projectName,"build.lst");
if (AjdeInteractionTestbed.VERBOSE) printBuildReport();
}
public void fullBuild(String projectName) {
constructUpToDateLstFile(projectName,"build.lst");
fullBuild(projectName,"build.lst");
if (AjdeInteractionTestbed.VERBOSE) printBuildReport();
}
private void constructUpToDateLstFile(String pname,String configname) {
File projectBase = new File(sandboxDir,pname);
File toConstruct = new File(projectBase,configname);
List filesForCompilation = new ArrayList();
collectUpFiles(projectBase,projectBase,filesForCompilation);
try {
FileOutputStream fos = new FileOutputStream(toConstruct);
DataOutputStream dos = new DataOutputStream(fos);
for (Iterator iter = filesForCompilation.iterator(); iter.hasNext();) {
String file = (String) iter.next();
dos.writeBytes(file+"\n");
}
dos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void checkForError(String anError) {
List messages = MyTaskListManager.getErrorMessages();
for (Iterator iter = messages.iterator(); iter.hasNext();) {
IMessage element = (IMessage) iter.next();
if (element.getMessage().indexOf(anError)!=-1) return;
}
fail("Didn't find the error message:\n'"+anError+"'.\nErrors that occurred:\n"+MyTaskListManager.getErrorMessages());
}
private void collectUpFiles(File location,File base,List collectionPoint) {
String contents[] = location.list();
if (contents==null) return;
for (int i = 0; i < contents.length; i++) {
String string = contents[i];
File f = new File(location,string);
if (f.isDirectory()) {
collectUpFiles(f,base,collectionPoint);
} else if (f.isFile() && (f.getName().endsWith(".aj") || f.getName().endsWith(".java"))) {
String fileFound;
try {
fileFound = f.getCanonicalPath();
String toRemove = base.getCanonicalPath();
if (!fileFound.startsWith(toRemove)) throw new RuntimeException("eh? "+fileFound+" "+toRemove);
collectionPoint.add(fileFound.substring(toRemove.length()+1));//+1 captures extra separator
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Fill in the working directory with the project base files,
* from the 'base' folder.
*/
protected void initialiseProject(String p) {
File projectSrc=new File(testdataSrcDir+File.separatorChar+p+File.separatorChar+"base");
File destination=new File(getWorkingDir(),p);
if (!destination.exists()) {destination.mkdir();}
copy(projectSrc,destination);//,false);
}
/*
* Applies an overlay onto the project being tested - copying
* the contents of the specified overlay directory.
*/
private void alter(String projectName,String overlayDirectory) {
File projectSrc =new File(testdataSrcDir+File.separatorChar+projectName+
File.separatorChar+overlayDirectory);
File destination=new File(getWorkingDir(),projectName);
copy(projectSrc,destination);
}
/**
* Copy the contents of some directory to another location - the
* copy is recursive.
*/
private void copy(File from, File to) {
String contents[] = from.list();
if (contents==null) return;
for (int i = 0; i < contents.length; i++) {
String string = contents[i];
File f = new File(from,string);
File t = new File(to,string);
if (f.isDirectory() && !f.getName().startsWith("inc")) {
t.mkdir();
copy(f,t);
} else if (f.isFile()) {
StringBuffer sb = new StringBuffer();
//if (VERBOSE) System.err.println("Copying "+f+" to "+t);
FileUtil.copyFile(f,t,sb);
if (sb.length()!=0) { System.err.println(sb.toString());}
}
}
}
private static void log(String msg) {
if (VERBOSE) System.out.println(msg);
}
}
|
131,933 |
Bug 131933 grotty ClassCastException on referring to pointcut in generic type
|
import java.util.List; public aspect Slide71 { before(): GenericType<String>.foo() {} before(): GenericType<MyList>.foo() {} //before(): GenericType.foo() {} } class GenericType<T> { public pointcut foo(): execution(* T.*(..)); } that programs gives: (because MyList is not a known type) java.lang.ClassCastException at org.aspectj.weaver.patterns.TypePattern.resolveExactType(TypePattern.java:193) at org.aspectj.weaver.patterns.ReferencePointcut.resolveBindings(ReferencePointcut.java:130) at org.aspectj.weaver.patterns.Pointcut.resolve(Pointcut.java:194) at org.aspectj.ajdt.internal.compiler.ast.PointcutDesignator.finishResolveTypes(PointcutDesignator.java:84) at org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration.resolveStatements(AdviceDeclaration.java:118) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:400) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1088) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.resolve(AspectDeclaration.java:116) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1137) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:305) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:514) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:843) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:268) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:170) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) ClassCastException thrown: org.aspectj.weaver.patterns.WildTypePattern
|
resolved fixed
|
f2cd94f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-16T11:01:54Z | 2006-03-15T13:40:00Z |
tests/src/org/aspectj/systemtest/ajc151/Ajc151Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc151;
import java.io.File;
import java.util.List;
import junit.framework.Test;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.systemtest.ajc150.GenericsTests;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc151Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public void testGenericAdviceParameters_pr123553() { runTest("generic advice parameters");}
public void testMemberTypesInGenericTypes_pr122458() { runTest("member types in generic types");}
public void testMemberTypesInGenericTypes_pr122458_2() { runTest("member types in generic types - 2");}
public void testNPEOnDeclareAnnotation_pr123695() { runTest("Internal nullptr exception with complex declare annotation");}
public void testHasMemberPackageProblem_pr124105() { runTest("hasMember problems with packages");}
public void testDifferentNumbersofTVars_pr124803() { runTest("generics and different numbers of type variables");}
public void testDifferentNumbersofTVars_pr124803_2() { runTest("generics and different numbers of type variables - classes");}
public void testParameterizedCollectionFieldMatching_pr124808() { runTest("parameterized collection fields matched via pointcut");}
public void testGenericAspectsAndAnnotations_pr124654() { runTest("generic aspects and annotations");}
public void testCallInheritedGenericMethod_pr124999() { runTest("calling inherited generic method from around advice");}
public void testIncorrectlyReferencingPointcuts_pr122452() { runTest("incorrectly referencing pointcuts");}
public void testIncorrectlyReferencingPointcuts_pr122452_2() { runTest("incorrectly referencing pointcuts - 2");}
public void testInlinevisitorNPE_pr123901() { runTest("inlinevisitor NPE");}
//public void testExposingWithintype_enh123423() { runTest("exposing withintype");}
//public void testMissingImport_pr127299() { runTest("missing import gives funny message");}
public void testUnusedInterfaceMessage_pr120527() { runTest("incorrect unused interface message");}
public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () { runTest("inherit advice with this() and thisJoinPoint"); }
public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699_2 () {runTest("inherit advice with this() and thisJoinPoint - 2"); }
public void testBrokenLTW_pr128744() { runTest("broken ltw"); }
public void testArrayindexoutofbounds_pr129566() {
runTest("arrayindexoutofbounds");
// public class SkipList<T extends Comparable> extends Object implements Set<T>, Iterable<T>
GenericsTests.verifyClassSignature(ajc,"common.SkipList","<T::Ljava/lang/Comparable;>Ljava/lang/Object;Ljava/util/Set<TT;>;Ljava/lang/Iterable<TT;>;");
// protected class SkipListElement<E> extends Object
GenericsTests.verifyClassSignature(ajc,"common.SkipList$SkipListElement","<E:Ljava/lang/Object;>Ljava/lang/Object;");
// protected class SkipListIterator<E> implements Iterator<T>
GenericsTests.verifyClassSignature(ajc,"common.SkipList$SkipListIterator","<E:Ljava/lang/Object;>Ljava/lang/Object;Ljava/util/Iterator<TT;>;");
}
public void testMixingNumbersOfTypeParameters_pr125080() {
runTest("mixing numbers of type parameters");
GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;");
GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;");
GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<Ljava/lang/String;>;");
}
public void testMixingNumbersOfTypeParameters_pr125080_2() {
runTest("mixing numbers of type parameters - 2");
GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Number;>Ljava/lang/Object;");
GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;");
GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<LStudent;>;");
}
public void testIProgramElementMethods_pr125295() {
runTest("new IProgramElement methods");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForType("pkg","foo");
assertNotNull("Couldn't find 'foo' element in the tree",pe);
// check that the defaults return the fully qualified arg
assertEquals("foo(int, java.lang.Object)",pe.toLabelString());
assertEquals("C.foo(int, java.lang.Object)",pe.toLinkLabelString());
assertEquals("foo(int, java.lang.Object)",pe.toSignatureString());
// check that can get hold of the non qualified args
assertEquals("foo(int, Object)",pe.toLabelString(false));
assertEquals("C.foo(int, Object)",pe.toLinkLabelString(false));
assertEquals("foo(int, Object)",pe.toSignatureString(false));
IProgramElement pe2 = top.findElementForType("pkg","printParameters");
assertNotNull("Couldn't find 'printParameters' element in the tree",pe2);
// the argument is org.aspectj.lang.JoinPoint, check that this is added
assertFalse("printParameters method should have arguments",pe2.getParameterTypes().isEmpty());
}
public void testParameterizedEnum_pr126316() {
runTest("E extends Enum(E) again");
}
public void testSwallowedException() {
runTest("swallowed exceptions");
}
public void testAtAspectVerifyErrorWithAfterThrowingAndthisJoinPoint_pr122742() {
runTest("@AJ VerifyError with @AfterThrowing and thisJoinPoint argument");
}
public void testAtAspectVerifyErrorWithAfterReturningAndthisJoinPoint_pr122742() {
runTest("@AJ VerifyError with @AfterReturning and thisJoinPoint argument");
}
public void testSwallowedExceptionIgnored() {
runTest("swallowed exceptions with xlint");
}
/*
* @AspectJ bugs and enhancements
*/
// public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () {
// runTest("inherit adivce with this() and thisJoinPoint");
// }
public void testAtAspectInheritsAbstractPointcut_pr125810 () {
runTest("warning when inherited pointcut not made concrete");
}
public void testAtAspectDEOWInStructureModel_pr120356() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("@AJ deow appear correctly when structure model is generated");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the @DeclareWarning statement
// and the method it matches.
IProgramElement warningMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"warningMethod()");
assertNotNull("Couldn't find 'warningMethod()' element in the tree",warningMethodIPE);
IProgramElement atDeclareWarningIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.FIELD,"warning");
assertNotNull("Couldn't find @DeclareWarning element in the tree",atDeclareWarningIPE);
// check that the method has a matches declare relationship with @DeclareWarning
List matches = AsmManager.getDefault().getRelationshipMap().get(warningMethodIPE);
assertNotNull("warningMethod should have some relationships but does not",matches);
assertTrue("warningMethod should have one relationships but has " + matches.size(),matches.size()==1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("warningMethod should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the @DeclareWarning 'warning' but is IPE with label "
+ target.toLabelString(),atDeclareWarningIPE,target);
// check that the @DeclareWarning has a matches relationship with the warningMethod
List matchedBy = AsmManager.getDefault().getRelationshipMap().get(atDeclareWarningIPE);
assertNotNull("@DeclareWarning should have some relationships but does not",matchedBy);
assertTrue("@DeclareWarning should have one relationship but has " + matchedBy.size(), matchedBy.size() == 1);
List matchedByTargets = ((Relationship)matchedBy.get(0)).getTargets();
assertTrue("@DeclareWarning 'matched by' relationship should have one target " +
"but has " + matchedByTargets.size(), matchedByTargets.size() == 1);
IProgramElement matchedByTarget = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargets.get(0));
assertEquals("target of relationship should be the warningMethod but is IPE with label "
+ matchedByTarget.toLabelString(),warningMethodIPE,matchedByTarget);
// get the IProgramElements corresponding to the @DeclareError statement
// and the method it matches.
IProgramElement errorMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"badMethod()");
assertNotNull("Couldn't find 'badMethod()' element in the tree",errorMethodIPE);
IProgramElement atDeclarErrorIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.FIELD,"error");
assertNotNull("Couldn't find @DeclareError element in the tree",atDeclarErrorIPE);
// check that the @DeclareError has a matches relationship with the badMethod
List matchedByE = AsmManager.getDefault().getRelationshipMap().get(atDeclarErrorIPE);
assertNotNull("@DeclareError should have some relationships but does not",matchedByE);
assertTrue("@DeclareError should have one relationship but has " + matchedByE.size(), matchedByE.size() == 1);
List matchedByTargetsE = ((Relationship)matchedByE.get(0)).getTargets();
assertTrue("@DeclareError 'matched by' relationship should have one target " +
"but has " + matchedByTargetsE.size(), matchedByTargetsE.size() == 1);
IProgramElement matchedByTargetE = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargetsE.get(0));
assertEquals("target of relationship should be the badMethod but is IPE with label "
+ matchedByTargetE.toLabelString(),errorMethodIPE,matchedByTargetE);
}
public void testAtAspectNoNPEWithDEOWWithoutStructureModel_pr120356() {
runTest("@AJ no NPE with deow when structure model isn't generated");
}
public void testAtAspectWithoutJoinPointImport_pr121616() {
runTest("@AJ without JoinPoint import");
}
public void testAtAspectDeclareParentsRetainsFieldState_pr122370() {
runTest("@AJ declare parents retains field state");
}
public void testAtAspectNoNPEWithPcdContainingOrThisAndWildcard_pr128237() {
runTest("@AJ no npe with pointcut containing or, this and a wildcard");
}
/*
* Load-time weaving bugs and enhancements
*/
public void testEmptyPointcutInAtAspectJ_pr125475 () {
runTest("define empty pointcut using an annotation");
}
public void testEmptyPointcutInAtAspectJ_pr125475_2() {
runTest("define empty pointcut using an annotation - 2");
}
public void testEmptyPointcutInAtAspectJWithLTW_pr125475 () {
runTest("define empty pointcut using aop.xml");
}
public void testLTWGeneratedAspectWithAbstractMethod_pr125480 () {
runTest("aop.xml aspect inherits abstract method that has concrete implementation in parent");
}
public void testGenericAspectsWithAnnotationTypeParameters() {
runTest("Generic aspects with annotation type parameters");
}
public void testPointcutInterfaces_pr130869() {
runTest("Pointcut interfaces");
}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc151Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc151/ajc151.xml");
}
}
|
131,933 |
Bug 131933 grotty ClassCastException on referring to pointcut in generic type
|
import java.util.List; public aspect Slide71 { before(): GenericType<String>.foo() {} before(): GenericType<MyList>.foo() {} //before(): GenericType.foo() {} } class GenericType<T> { public pointcut foo(): execution(* T.*(..)); } that programs gives: (because MyList is not a known type) java.lang.ClassCastException at org.aspectj.weaver.patterns.TypePattern.resolveExactType(TypePattern.java:193) at org.aspectj.weaver.patterns.ReferencePointcut.resolveBindings(ReferencePointcut.java:130) at org.aspectj.weaver.patterns.Pointcut.resolve(Pointcut.java:194) at org.aspectj.ajdt.internal.compiler.ast.PointcutDesignator.finishResolveTypes(PointcutDesignator.java:84) at org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration.resolveStatements(AdviceDeclaration.java:118) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration.resolve(AbstractMethodDeclaration.java:400) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1088) at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.resolve(AspectDeclaration.java:116) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.resolve(TypeDeclaration.java:1137) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.resolve(CompilationUnitDeclaration.java:305) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:514) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:843) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:268) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:170) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) ClassCastException thrown: org.aspectj.weaver.patterns.WildTypePattern
|
resolved fixed
|
f2cd94f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-16T11:01:54Z | 2006-03-15T13:40:00Z |
weaver/src/org/aspectj/weaver/patterns/TypePattern.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.Iterator;
import java.util.Map;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.TypeVariableReference;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
/**
* On creation, type pattern only contains WildTypePattern nodes, not BindingType or ExactType.
*
* <p>Then we call resolveBindings() during compilation
* During concretization of enclosing pointcuts, we call remapAdviceFormals
*
* @author Erik Hilsdale
* @author Jim Hugunin
*/
public abstract class TypePattern extends PatternNode {
public static class MatchKind {
private String name;
public MatchKind(String name) { this.name = name; }
public String toString() { return name; }
}
public static final MatchKind STATIC = new MatchKind("STATIC");
public static final MatchKind DYNAMIC = new MatchKind("DYNAMIC");
public static final TypePattern ELLIPSIS = new EllipsisTypePattern();
public static final TypePattern ANY = new AnyTypePattern();
public static final TypePattern NO = new NoTypePattern();
protected boolean includeSubtypes;
protected boolean isVarArgs = false;
protected AnnotationTypePattern annotationPattern = AnnotationTypePattern.ANY;
protected TypePatternList typeParameters = TypePatternList.EMPTY;
protected TypePattern(boolean includeSubtypes,boolean isVarArgs,TypePatternList typeParams) {
this.includeSubtypes = includeSubtypes;
this.isVarArgs = isVarArgs;
this.typeParameters = (typeParams == null ? TypePatternList.EMPTY : typeParams);
}
protected TypePattern(boolean includeSubtypes, boolean isVarArgs) {
this(includeSubtypes,isVarArgs,null);
}
public AnnotationTypePattern getAnnotationPattern() {
return annotationPattern;
}
public boolean isVarArgs() {
return isVarArgs;
}
public boolean isStarAnnotation() {
return annotationPattern == AnnotationTypePattern.ANY;
}
public boolean isArray() {
return false;
}
protected TypePattern(boolean includeSubtypes) {
this(includeSubtypes,false);
}
public void setAnnotationTypePattern(AnnotationTypePattern annPatt) {
this.annotationPattern = annPatt;
}
public void setTypeParameters(TypePatternList typeParams) {
this.typeParameters = typeParams;
}
public TypePatternList getTypeParameters() {
return this.typeParameters;
}
public void setIsVarArgs(boolean isVarArgs) {
this.isVarArgs = isVarArgs;
}
// answer conservatively...
protected boolean couldEverMatchSameTypesAs(TypePattern other) {
if (this.includeSubtypes || other.includeSubtypes) return true;
if (this.annotationPattern != AnnotationTypePattern.ANY) return true;
if (other.annotationPattern != AnnotationTypePattern.ANY) return true;
return false;
}
//XXX non-final for Not, && and ||
public boolean matchesStatically(ResolvedType type) {
if (includeSubtypes) {
return matchesSubtypes(type);
} else {
return matchesExactly(type);
}
}
public abstract FuzzyBoolean matchesInstanceof(ResolvedType type);
public final FuzzyBoolean matches(ResolvedType type, MatchKind kind) {
FuzzyBoolean typeMatch = null;
//??? This is part of gracefully handling missing references
if (type.isMissing()) return FuzzyBoolean.NO;
if (kind == STATIC) {
// typeMatch = FuzzyBoolean.fromBoolean(matchesStatically(type));
// return typeMatch.and(annotationPattern.matches(type));
return FuzzyBoolean.fromBoolean(matchesStatically(type));
} else if (kind == DYNAMIC) {
//System.err.println("matching: " + this + " with " + type);
// typeMatch = matchesInstanceof(type);
//System.err.println(" got: " + ret);
// return typeMatch.and(annotationPattern.matches(type));
return matchesInstanceof(type);
} else {
throw new IllegalArgumentException("kind must be DYNAMIC or STATIC");
}
}
protected abstract boolean matchesExactly(ResolvedType type);
protected abstract boolean matchesExactly(ResolvedType type, ResolvedType annotatedType);
protected boolean matchesSubtypes(ResolvedType type) {
//System.out.println("matching: " + this + " to " + type);
if (matchesExactly(type)) {
//System.out.println(" true");
return true;
}
// pr124808
Iterator typesIterator = null;
if (type.isTypeVariableReference()) {
typesIterator = ((TypeVariableReference)type).getTypeVariable().getFirstBound().resolve(type.getWorld()).getDirectSupertypes();
} else {
typesIterator = type.getDirectSupertypes();
}
// FuzzyBoolean ret = FuzzyBoolean.NO; // ??? -eh
for (Iterator i = typesIterator; i.hasNext(); ) {
ResolvedType superType = (ResolvedType)i.next();
// TODO asc generics, temporary whilst matching isnt aware..
//if (superType.isParameterizedType()) superType = superType.getRawType().resolve(superType.getWorld());
if (matchesSubtypes(superType,type)) return true;
}
return false;
}
protected boolean matchesSubtypes(ResolvedType superType, ResolvedType annotatedType) {
//System.out.println("matching: " + this + " to " + type);
if (matchesExactly(superType,annotatedType)) {
//System.out.println(" true");
return true;
}
// FuzzyBoolean ret = FuzzyBoolean.NO; // ??? -eh
for (Iterator i = superType.getDirectSupertypes(); i.hasNext(); ) {
ResolvedType superSuperType = (ResolvedType)i.next();
if (matchesSubtypes(superSuperType,annotatedType)) return true;
}
return false;
}
public UnresolvedType resolveExactType(IScope scope, Bindings bindings) {
TypePattern p = resolveBindings(scope, bindings, false, true);
if (p == NO) return ResolvedType.MISSING;
return ((ExactTypePattern)p).getType();
}
public UnresolvedType getExactType() {
if (this instanceof ExactTypePattern) return ((ExactTypePattern)this).getType();
else return ResolvedType.MISSING;
}
protected TypePattern notExactType(IScope s) {
s.getMessageHandler().handleMessage(MessageUtil.error(
WeaverMessages.format(WeaverMessages.EXACT_TYPE_PATTERN_REQD), getSourceLocation()));
return NO;
}
// public boolean assertExactType(IMessageHandler m) {
// if (this instanceof ExactTypePattern) return true;
//
// //XXX should try harder to avoid multiple errors for one problem
// m.handleMessage(MessageUtil.error("exact type pattern required", getSourceLocation()));
// return false;
// }
/**
* This can modify in place, or return a new TypePattern if the type changes.
*/
public TypePattern resolveBindings(IScope scope, Bindings bindings,
boolean allowBinding, boolean requireExactType)
{
annotationPattern = annotationPattern.resolveBindings(scope,bindings,allowBinding);
return this;
}
public void resolve(World world) {
annotationPattern.resolve(world);
}
/**
* return a version of this type pattern in which all type variable references have been
* replaced by their corresponding entry in the map.
*/
public abstract TypePattern parameterizeWith(Map typeVariableMap);
public void postRead(ResolvedType enclosingType) {
}
public boolean isStar() {
return false;
}
/**
* This is called during concretization of pointcuts, it is used by BindingTypePattern
* to return a new BindingTypePattern with a formal index appropiate for the advice,
* rather than for the lexical declaration, i.e. this handles transforamtions through
* named pointcuts.
* <pre>
* pointcut foo(String name): args(name);
* --> This makes a BindingTypePattern(0) pointing to the 0th formal
*
* before(Foo f, String n): this(f) && foo(n) { ... }
* --> when resolveReferences is called on the args from the above, it
* will return a BindingTypePattern(1)
*
* before(Foo f): this(f) && foo(*) { ... }
* --> when resolveReferences is called on the args from the above, it
* will return an ExactTypePattern(String)
* </pre>
*/
public TypePattern remapAdviceFormals(IntMap bindings) {
return this;
}
public static final byte WILD = 1;
public static final byte EXACT = 2;
public static final byte BINDING = 3;
public static final byte ELLIPSIS_KEY = 4;
public static final byte ANY_KEY = 5;
public static final byte NOT = 6;
public static final byte OR = 7;
public static final byte AND = 8;
public static final byte NO_KEY = 9;
public static final byte ANY_WITH_ANNO = 10;
public static final byte HAS_MEMBER = 11;
public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException {
byte key = s.readByte();
switch(key) {
case WILD: return WildTypePattern.read(s, context);
case EXACT: return ExactTypePattern.read(s, context);
case BINDING: return BindingTypePattern.read(s, context);
case ELLIPSIS_KEY: return ELLIPSIS;
case ANY_KEY: return ANY;
case NO_KEY: return NO;
case NOT: return NotTypePattern.read(s, context);
case OR: return OrTypePattern.read(s, context);
case AND: return AndTypePattern.read(s, context);
case ANY_WITH_ANNO: return AnyWithAnnotationTypePattern.read(s,context);
case HAS_MEMBER: return HasMemberTypePattern.read(s,context);
}
throw new BCException("unknown TypePattern kind: " + key);
}
public boolean isIncludeSubtypes() {
return includeSubtypes;
}
}
class EllipsisTypePattern extends TypePattern {
/**
* Constructor for EllipsisTypePattern.
* @param includeSubtypes
*/
public EllipsisTypePattern() {
super(false,false,new TypePatternList());
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern)
*/
protected boolean couldEverMatchSameTypesAs(TypePattern other) {
return true;
}
/**
* @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType)
*/
protected boolean matchesExactly(ResolvedType type) {
return false;
}
protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) {
return false;
}
/**
* @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType)
*/
public FuzzyBoolean matchesInstanceof(ResolvedType type) {
return FuzzyBoolean.NO;
}
/**
* @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream)
*/
public void write(DataOutputStream s) throws IOException {
s.writeByte(ELLIPSIS_KEY);
}
public String toString() { return ".."; }
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
return (obj instanceof EllipsisTypePattern);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return 17 * 37;
}
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
public TypePattern parameterizeWith(Map typeVariableMap) {
return this;
}
}
class AnyTypePattern extends TypePattern {
/**
* Constructor for EllipsisTypePattern.
* @param includeSubtypes
*/
public AnyTypePattern() {
super(false,false,new TypePatternList());
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern)
*/
protected boolean couldEverMatchSameTypesAs(TypePattern other) {
return true;
}
/**
* @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType)
*/
protected boolean matchesExactly(ResolvedType type) {
return true;
}
protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) {
return true;
}
/**
* @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType)
*/
public FuzzyBoolean matchesInstanceof(ResolvedType type) {
return FuzzyBoolean.YES;
}
/**
* @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream)
*/
public void write(DataOutputStream s) throws IOException {
s.writeByte(ANY_KEY);
}
/**
* @see org.aspectj.weaver.patterns.TypePattern#matches(IType, MatchKind)
*/
// public FuzzyBoolean matches(IType type, MatchKind kind) {
// return FuzzyBoolean.YES;
// }
/**
* @see org.aspectj.weaver.patterns.TypePattern#matchesSubtypes(IType)
*/
protected boolean matchesSubtypes(ResolvedType type) {
return true;
}
public boolean isStar() {
return true;
}
public String toString() { return "*"; }
public boolean equals(Object obj) {
return (obj instanceof AnyTypePattern);
}
public int hashCode() {
return 37;
}
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
public TypePattern parameterizeWith(Map arg0) {
return this;
}
}
/**
* This type represents a type pattern of '*' but with an annotation specified,
* e.g. '@Color *'
*/
class AnyWithAnnotationTypePattern extends TypePattern {
public AnyWithAnnotationTypePattern(AnnotationTypePattern atp) {
super(false,false);
annotationPattern = atp;
}
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this,data);
}
protected boolean couldEverMatchSameTypesAs(TypePattern other) {
return true;
}
protected boolean matchesExactly(ResolvedType type) {
annotationPattern.resolve(type.getWorld());
return annotationPattern.matches(type).alwaysTrue();
}
protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) {
annotationPattern.resolve(type.getWorld());
return annotationPattern.matches(annotatedType).alwaysTrue();
}
public FuzzyBoolean matchesInstanceof(ResolvedType type) {
if (Modifier.isFinal(type.getModifiers())) {
return FuzzyBoolean.fromBoolean(matchesExactly(type));
}
return FuzzyBoolean.MAYBE;
}
public TypePattern parameterizeWith(Map typeVariableMap) {
AnyWithAnnotationTypePattern ret = new AnyWithAnnotationTypePattern(this.annotationPattern.parameterizeWith(typeVariableMap));
ret.copyLocationFrom(this);
return ret;
}
public void write(DataOutputStream s) throws IOException {
s.writeByte(TypePattern.ANY_WITH_ANNO);
annotationPattern.write(s);
writeLocation(s);
}
public static TypePattern read(VersionedDataInputStream s,ISourceContext c) throws IOException {
AnnotationTypePattern annPatt = AnnotationTypePattern.read(s,c);
AnyWithAnnotationTypePattern ret = new AnyWithAnnotationTypePattern(annPatt);
ret.readLocation(c, s);
return ret;
}
// public FuzzyBoolean matches(IType type, MatchKind kind) {
// return FuzzyBoolean.YES;
// }
protected boolean matchesSubtypes(ResolvedType type) {
return true;
}
public boolean isStar() {
return false;
}
public String toString() { return annotationPattern+" *"; }
public boolean equals(Object obj) {
if (!(obj instanceof AnyWithAnnotationTypePattern)) return false;
AnyWithAnnotationTypePattern awatp = (AnyWithAnnotationTypePattern) obj;
return (annotationPattern.equals(awatp.annotationPattern));
}
public int hashCode() {
return annotationPattern.hashCode();
}
}
class NoTypePattern extends TypePattern {
public NoTypePattern() {
super(false,false,new TypePatternList());
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern)
*/
protected boolean couldEverMatchSameTypesAs(TypePattern other) {
return false;
}
/**
* @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType)
*/
protected boolean matchesExactly(ResolvedType type) {
return false;
}
protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) {
return false;
}
/**
* @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType)
*/
public FuzzyBoolean matchesInstanceof(ResolvedType type) {
return FuzzyBoolean.NO;
}
/**
* @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream)
*/
public void write(DataOutputStream s) throws IOException {
s.writeByte(NO_KEY);
}
/**
* @see org.aspectj.weaver.patterns.TypePattern#matches(IType, MatchKind)
*/
// public FuzzyBoolean matches(IType type, MatchKind kind) {
// return FuzzyBoolean.YES;
// }
/**
* @see org.aspectj.weaver.patterns.TypePattern#matchesSubtypes(IType)
*/
protected boolean matchesSubtypes(ResolvedType type) {
return false;
}
public boolean isStar() {
return false;
}
public String toString() { return "<nothing>"; }//FIXME AV - bad! toString() cannot be parsed back (not idempotent)
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
return (obj instanceof NoTypePattern);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return 17 * 37 * 37;
}
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
public TypePattern parameterizeWith(Map arg0) {
return this;
}
}
|
131,932 |
Bug 131932 structure model bug: generic method ITD
|
import java.util.List; public aspect Slide74 { public X Bar<X>.getFirst() { return lts.get(0); } static class Bar<T> { List<T> lts; } } in AJDT, this program incorrectly shows the relationship from the TYPE to the Bar class rather than from the ITD to the Bar class.
|
resolved fixed
|
e2703cf
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-16T15:34:26Z | 2006-03-15T13:40:00Z |
tests/src/org/aspectj/systemtest/ajc151/Ajc151Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc151;
import java.io.File;
import java.util.List;
import junit.framework.Test;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.systemtest.ajc150.GenericsTests;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc151Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public void testGenericAdviceParameters_pr123553() { runTest("generic advice parameters");}
public void testMemberTypesInGenericTypes_pr122458() { runTest("member types in generic types");}
public void testMemberTypesInGenericTypes_pr122458_2() { runTest("member types in generic types - 2");}
public void testNPEOnDeclareAnnotation_pr123695() { runTest("Internal nullptr exception with complex declare annotation");}
public void testHasMemberPackageProblem_pr124105() { runTest("hasMember problems with packages");}
public void testDifferentNumbersofTVars_pr124803() { runTest("generics and different numbers of type variables");}
public void testDifferentNumbersofTVars_pr124803_2() { runTest("generics and different numbers of type variables - classes");}
public void testParameterizedCollectionFieldMatching_pr124808() { runTest("parameterized collection fields matched via pointcut");}
public void testGenericAspectsAndAnnotations_pr124654() { runTest("generic aspects and annotations");}
public void testCallInheritedGenericMethod_pr124999() { runTest("calling inherited generic method from around advice");}
public void testIncorrectlyReferencingPointcuts_pr122452() { runTest("incorrectly referencing pointcuts");}
public void testIncorrectlyReferencingPointcuts_pr122452_2() { runTest("incorrectly referencing pointcuts - 2");}
public void testInlinevisitorNPE_pr123901() { runTest("inlinevisitor NPE");}
//public void testExposingWithintype_enh123423() { runTest("exposing withintype");}
//public void testMissingImport_pr127299() { runTest("missing import gives funny message");}
public void testUnusedInterfaceMessage_pr120527() { runTest("incorrect unused interface message");}
public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () { runTest("inherit advice with this() and thisJoinPoint"); }
public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699_2 () {runTest("inherit advice with this() and thisJoinPoint - 2"); }
public void testBrokenLTW_pr128744() { runTest("broken ltw"); }
public void testArrayindexoutofbounds_pr129566() {
runTest("arrayindexoutofbounds");
// public class SkipList<T extends Comparable> extends Object implements Set<T>, Iterable<T>
GenericsTests.verifyClassSignature(ajc,"common.SkipList","<T::Ljava/lang/Comparable;>Ljava/lang/Object;Ljava/util/Set<TT;>;Ljava/lang/Iterable<TT;>;");
// protected class SkipListElement<E> extends Object
GenericsTests.verifyClassSignature(ajc,"common.SkipList$SkipListElement","<E:Ljava/lang/Object;>Ljava/lang/Object;");
// protected class SkipListIterator<E> implements Iterator<T>
GenericsTests.verifyClassSignature(ajc,"common.SkipList$SkipListIterator","<E:Ljava/lang/Object;>Ljava/lang/Object;Ljava/util/Iterator<TT;>;");
}
public void testMixingNumbersOfTypeParameters_pr125080() {
runTest("mixing numbers of type parameters");
GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;");
GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;");
GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<Ljava/lang/String;>;");
}
public void testMixingNumbersOfTypeParameters_pr125080_2() {
runTest("mixing numbers of type parameters - 2");
GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Number;>Ljava/lang/Object;");
GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;");
GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<LStudent;>;");
}
public void testIProgramElementMethods_pr125295() {
runTest("new IProgramElement methods");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForType("pkg","foo");
assertNotNull("Couldn't find 'foo' element in the tree",pe);
// check that the defaults return the fully qualified arg
assertEquals("foo(int, java.lang.Object)",pe.toLabelString());
assertEquals("C.foo(int, java.lang.Object)",pe.toLinkLabelString());
assertEquals("foo(int, java.lang.Object)",pe.toSignatureString());
// check that can get hold of the non qualified args
assertEquals("foo(int, Object)",pe.toLabelString(false));
assertEquals("C.foo(int, Object)",pe.toLinkLabelString(false));
assertEquals("foo(int, Object)",pe.toSignatureString(false));
IProgramElement pe2 = top.findElementForType("pkg","printParameters");
assertNotNull("Couldn't find 'printParameters' element in the tree",pe2);
// the argument is org.aspectj.lang.JoinPoint, check that this is added
assertFalse("printParameters method should have arguments",pe2.getParameterTypes().isEmpty());
}
public void testParameterizedEnum_pr126316() {
runTest("E extends Enum(E) again");
}
public void testSwallowedException() {
runTest("swallowed exceptions");
}
public void testAtAspectVerifyErrorWithAfterThrowingAndthisJoinPoint_pr122742() {
runTest("@AJ VerifyError with @AfterThrowing and thisJoinPoint argument");
}
public void testAtAspectVerifyErrorWithAfterReturningAndthisJoinPoint_pr122742() {
runTest("@AJ VerifyError with @AfterReturning and thisJoinPoint argument");
}
public void testSwallowedExceptionIgnored() {
runTest("swallowed exceptions with xlint");
}
public void testGenericAspectWithUnknownType_pr131933() {
runTest("no ClassCastException with generic aspect and unknown type");
}
/*
* @AspectJ bugs and enhancements
*/
// public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () {
// runTest("inherit adivce with this() and thisJoinPoint");
// }
public void testAtAspectInheritsAbstractPointcut_pr125810 () {
runTest("warning when inherited pointcut not made concrete");
}
public void testAtAspectDEOWInStructureModel_pr120356() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("@AJ deow appear correctly when structure model is generated");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the @DeclareWarning statement
// and the method it matches.
IProgramElement warningMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"warningMethod()");
assertNotNull("Couldn't find 'warningMethod()' element in the tree",warningMethodIPE);
IProgramElement atDeclareWarningIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.FIELD,"warning");
assertNotNull("Couldn't find @DeclareWarning element in the tree",atDeclareWarningIPE);
// check that the method has a matches declare relationship with @DeclareWarning
List matches = AsmManager.getDefault().getRelationshipMap().get(warningMethodIPE);
assertNotNull("warningMethod should have some relationships but does not",matches);
assertTrue("warningMethod should have one relationships but has " + matches.size(),matches.size()==1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("warningMethod should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the @DeclareWarning 'warning' but is IPE with label "
+ target.toLabelString(),atDeclareWarningIPE,target);
// check that the @DeclareWarning has a matches relationship with the warningMethod
List matchedBy = AsmManager.getDefault().getRelationshipMap().get(atDeclareWarningIPE);
assertNotNull("@DeclareWarning should have some relationships but does not",matchedBy);
assertTrue("@DeclareWarning should have one relationship but has " + matchedBy.size(), matchedBy.size() == 1);
List matchedByTargets = ((Relationship)matchedBy.get(0)).getTargets();
assertTrue("@DeclareWarning 'matched by' relationship should have one target " +
"but has " + matchedByTargets.size(), matchedByTargets.size() == 1);
IProgramElement matchedByTarget = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargets.get(0));
assertEquals("target of relationship should be the warningMethod but is IPE with label "
+ matchedByTarget.toLabelString(),warningMethodIPE,matchedByTarget);
// get the IProgramElements corresponding to the @DeclareError statement
// and the method it matches.
IProgramElement errorMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"badMethod()");
assertNotNull("Couldn't find 'badMethod()' element in the tree",errorMethodIPE);
IProgramElement atDeclarErrorIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.FIELD,"error");
assertNotNull("Couldn't find @DeclareError element in the tree",atDeclarErrorIPE);
// check that the @DeclareError has a matches relationship with the badMethod
List matchedByE = AsmManager.getDefault().getRelationshipMap().get(atDeclarErrorIPE);
assertNotNull("@DeclareError should have some relationships but does not",matchedByE);
assertTrue("@DeclareError should have one relationship but has " + matchedByE.size(), matchedByE.size() == 1);
List matchedByTargetsE = ((Relationship)matchedByE.get(0)).getTargets();
assertTrue("@DeclareError 'matched by' relationship should have one target " +
"but has " + matchedByTargetsE.size(), matchedByTargetsE.size() == 1);
IProgramElement matchedByTargetE = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargetsE.get(0));
assertEquals("target of relationship should be the badMethod but is IPE with label "
+ matchedByTargetE.toLabelString(),errorMethodIPE,matchedByTargetE);
}
public void testAtAspectNoNPEWithDEOWWithoutStructureModel_pr120356() {
runTest("@AJ no NPE with deow when structure model isn't generated");
}
public void testAtAspectWithoutJoinPointImport_pr121616() {
runTest("@AJ without JoinPoint import");
}
public void testAtAspectDeclareParentsRetainsFieldState_pr122370() {
runTest("@AJ declare parents retains field state");
}
public void testAtAspectNoNPEWithPcdContainingOrThisAndWildcard_pr128237() {
runTest("@AJ no npe with pointcut containing or, this and a wildcard");
}
/*
* Load-time weaving bugs and enhancements
*/
public void testEmptyPointcutInAtAspectJ_pr125475 () {
runTest("define empty pointcut using an annotation");
}
public void testEmptyPointcutInAtAspectJ_pr125475_2() {
runTest("define empty pointcut using an annotation - 2");
}
public void testEmptyPointcutInAtAspectJWithLTW_pr125475 () {
runTest("define empty pointcut using aop.xml");
}
public void testLTWGeneratedAspectWithAbstractMethod_pr125480 () {
runTest("aop.xml aspect inherits abstract method that has concrete implementation in parent");
}
public void testGenericAspectsWithAnnotationTypeParameters() {
runTest("Generic aspects with annotation type parameters");
}
public void testPointcutInterfaces_pr130869() {
runTest("Pointcut interfaces");
}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc151Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc151/ajc151.xml");
}
}
|
131,932 |
Bug 131932 structure model bug: generic method ITD
|
import java.util.List; public aspect Slide74 { public X Bar<X>.getFirst() { return lts.get(0); } static class Bar<T> { List<T> lts; } } in AJDT, this program incorrectly shows the relationship from the TYPE to the Bar class rather than from the ITD to the Bar class.
|
resolved fixed
|
e2703cf
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-16T15:34:26Z | 2006-03-15T13:40:00Z |
weaver/src/org/aspectj/weaver/NewConstructorTypeMunger.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
public class NewConstructorTypeMunger extends ResolvedTypeMunger {
private ResolvedMember syntheticConstructor;
private ResolvedMember explicitConstructor;
public NewConstructorTypeMunger(
ResolvedMember signature,
ResolvedMember syntheticConstructor,
ResolvedMember explicitConstructor,
Set superMethodsCalled,
List typeVariableAliases) {
super(Constructor, signature);
this.syntheticConstructor = syntheticConstructor;
this.typeVariableAliases = typeVariableAliases;
this.explicitConstructor = explicitConstructor;
this.setSuperMethodsCalled(superMethodsCalled);
}
public boolean equals(Object other) {
if (!(other instanceof NewConstructorTypeMunger)) return false;
NewConstructorTypeMunger o = (NewConstructorTypeMunger)other;
return ((o.syntheticConstructor == null) ? (syntheticConstructor == null )
: syntheticConstructor.equals(o.syntheticConstructor))
& ((o.explicitConstructor == null) ? (explicitConstructor == null )
: explicitConstructor.equals(o.explicitConstructor));
}
private volatile int hashCode = 0;
public int hashCode() {
if (hashCode == 0) {
int result = 17;
result = 37*result + ((syntheticConstructor == null) ? 0 : syntheticConstructor.hashCode());
result = 37*result + ((explicitConstructor == null) ? 0 : explicitConstructor.hashCode());
hashCode = result;
}
return hashCode;
}
// doesnt seem required....
// public ResolvedMember getDispatchMethod(UnresolvedType aspectType) {
// return AjcMemberMaker.interMethodBody(signature, aspectType);
// }
public void write(DataOutputStream s) throws IOException {
kind.write(s);
signature.write(s);
syntheticConstructor.write(s);
explicitConstructor.write(s);
writeSuperMethodsCalled(s);
writeSourceLocation(s);
writeOutTypeAliases(s);
}
public static ResolvedTypeMunger readConstructor(VersionedDataInputStream s, ISourceContext context) throws IOException {
ISourceLocation sloc = null;
ResolvedMember sig = ResolvedMemberImpl.readResolvedMember(s, context);
ResolvedMember syntheticCtor = ResolvedMemberImpl.readResolvedMember(s, context);
ResolvedMember explicitCtor = ResolvedMemberImpl.readResolvedMember(s, context);
Set superMethodsCalled = readSuperMethodsCalled(s);
sloc = readSourceLocation(s);
List typeVarAliases = readInTypeAliases(s);
ResolvedTypeMunger munger = new NewConstructorTypeMunger(sig,syntheticCtor,explicitCtor,superMethodsCalled,typeVarAliases);
if (sloc!=null) munger.setSourceLocation(sloc);
return munger;
}
public ResolvedMember getExplicitConstructor() {
return explicitConstructor;
}
public ResolvedMember getSyntheticConstructor() {
return syntheticConstructor;
}
public void setExplicitConstructor(ResolvedMember explicitConstructor) {
this.explicitConstructor = explicitConstructor;
// reset hashCode so that its recalculated with new value
hashCode = 0;
}
public ResolvedMember getMatchingSyntheticMember(Member member, ResolvedType aspectType) {
ResolvedMember ret = getSyntheticConstructor();
if (ResolvedType.matches(ret, member)) return getSignature();
return super.getMatchingSyntheticMember(member, aspectType);
}
public void check(World world) {
if (getSignature().getDeclaringType().resolve(world).isAspect()) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_CONS_ON_ASPECT),
getSignature().getSourceLocation(), null);
}
}
/**
* see ResolvedTypeMunger.parameterizedFor(ResolvedType)
*/
public ResolvedTypeMunger parameterizedFor(ResolvedType target) {
ResolvedType genericType = target;
if (target.isRawType() || target.isParameterizedType()) genericType = genericType.getGenericType();
ResolvedMember parameterizedSignature = null;
// If we are parameterizing it for a generic type, we just need to 'swap the letters' from the ones used
// in the original ITD declaration to the ones used in the actual target type declaration.
if (target.isGenericType()) {
TypeVariable vars[] = target.getTypeVariables();
UnresolvedTypeVariableReferenceType[] varRefs = new UnresolvedTypeVariableReferenceType[vars.length];
for (int i = 0; i < vars.length; i++) {
varRefs[i] = new UnresolvedTypeVariableReferenceType(vars[i]);
}
parameterizedSignature = getSignature().parameterizedWith(varRefs,genericType,true,typeVariableAliases);
} else {
// For raw and 'normal' parameterized targets (e.g. Interface, Interface<String>)
parameterizedSignature = getSignature().parameterizedWith(target.getTypeParameters(),genericType,target.isParameterizedType(),typeVariableAliases);
}
return new NewConstructorTypeMunger(parameterizedSignature,syntheticConstructor,explicitConstructor,getSuperMethodsCalled(),typeVariableAliases);
}
}
|
131,932 |
Bug 131932 structure model bug: generic method ITD
|
import java.util.List; public aspect Slide74 { public X Bar<X>.getFirst() { return lts.get(0); } static class Bar<T> { List<T> lts; } } in AJDT, this program incorrectly shows the relationship from the TYPE to the Bar class rather than from the ITD to the Bar class.
|
resolved fixed
|
e2703cf
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-16T15:34:26Z | 2006-03-15T13:40:00Z |
weaver/src/org/aspectj/weaver/NewFieldTypeMunger.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.DataOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import org.aspectj.bridge.ISourceLocation;
public class NewFieldTypeMunger extends ResolvedTypeMunger {
public NewFieldTypeMunger(ResolvedMember signature, Set superMethodsCalled, List typeVariableAliases) {
super(Field, signature);
this.typeVariableAliases = typeVariableAliases;
signature.setAnnotatedElsewhere(true);
this.setSuperMethodsCalled(superMethodsCalled);
}
public ResolvedMember getInitMethod(UnresolvedType aspectType) {
return AjcMemberMaker.interFieldInitializer(signature, aspectType);
}
public void write(DataOutputStream s) throws IOException {
kind.write(s);
signature.write(s);
writeSuperMethodsCalled(s);
writeSourceLocation(s);
writeOutTypeAliases(s);
}
public static ResolvedTypeMunger readField(VersionedDataInputStream s, ISourceContext context) throws IOException {
ISourceLocation sloc = null;
ResolvedMember fieldSignature = ResolvedMemberImpl.readResolvedMember(s, context);
Set superMethodsCalled = readSuperMethodsCalled(s);
sloc = readSourceLocation(s);
List aliases = readInTypeAliases(s);
ResolvedTypeMunger munger = new NewFieldTypeMunger(fieldSignature,superMethodsCalled,aliases);
if (sloc!=null) munger.setSourceLocation(sloc);
return munger;
}
public ResolvedMember getMatchingSyntheticMember(Member member, ResolvedType aspectType) {
//??? might give a field where a method is expected
ResolvedType onType = aspectType.getWorld().resolve(getSignature().getDeclaringType());
if (onType.isRawType()) onType = onType.getGenericType();
ResolvedMember ret = AjcMemberMaker.interFieldGetDispatcher(getSignature(), aspectType);
if (ResolvedType.matches(ret, member)) return getSignature();
ret = AjcMemberMaker.interFieldSetDispatcher(getSignature(), aspectType);
if (ResolvedType.matches(ret, member)) return getSignature();
ret = AjcMemberMaker.interFieldInterfaceGetter(getSignature(), onType, aspectType);
if (ResolvedType.matches(ret, member)) return getSignature();
ret = AjcMemberMaker.interFieldInterfaceSetter(getSignature(), onType, aspectType);
if (ResolvedType.matches(ret, member)) return getSignature();
return super.getMatchingSyntheticMember(member, aspectType);
}
/**
* see ResolvedTypeMunger.parameterizedFor(ResolvedType)
*/
public ResolvedTypeMunger parameterizedFor(ResolvedType target) {
ResolvedType genericType = target;
if (target.isRawType() || target.isParameterizedType()) genericType = genericType.getGenericType();
ResolvedMember parameterizedSignature = null;
// If we are parameterizing it for a generic type, we just need to 'swap the letters' from the ones used
// in the original ITD declaration to the ones used in the actual target type declaration.
if (target.isGenericType()) {
TypeVariable vars[] = target.getTypeVariables();
UnresolvedTypeVariableReferenceType[] varRefs = new UnresolvedTypeVariableReferenceType[vars.length];
for (int i = 0; i < vars.length; i++) {
varRefs[i] = new UnresolvedTypeVariableReferenceType(vars[i]);
}
parameterizedSignature = getSignature().parameterizedWith(varRefs,genericType,true,typeVariableAliases);
} else {
// For raw and 'normal' parameterized targets (e.g. Interface, Interface<String>)
parameterizedSignature = getSignature().parameterizedWith(target.getTypeParameters(),genericType,target.isParameterizedType(),typeVariableAliases);
}
NewFieldTypeMunger nftm = new NewFieldTypeMunger(parameterizedSignature,getSuperMethodsCalled(),typeVariableAliases);
nftm.setDeclaredSignature(getSignature());
return nftm;
}
public boolean equals(Object other) {
if (! (other instanceof NewFieldTypeMunger)) return false;
NewFieldTypeMunger o = (NewFieldTypeMunger) other;
return kind.equals(o.kind)
&& ((o.signature == null) ? (signature == null ) : signature.equals(o.signature))
&& ((o.declaredSignature == null) ? (declaredSignature == null ) : declaredSignature.equals(o.declaredSignature))
&& ((o.typeVariableAliases == null) ? (typeVariableAliases == null ) : typeVariableAliases.equals(o.typeVariableAliases));
}
public int hashCode() {
int result = 17;
result = 37*result + kind.hashCode();
result = 37*result + ((signature == null) ? 0 : signature.hashCode());
result = 37*result + ((declaredSignature == null) ? 0 : declaredSignature.hashCode());
result = 37*result + ((typeVariableAliases == null) ? 0 : typeVariableAliases.hashCode());
return result;
}
}
|
131,932 |
Bug 131932 structure model bug: generic method ITD
|
import java.util.List; public aspect Slide74 { public X Bar<X>.getFirst() { return lts.get(0); } static class Bar<T> { List<T> lts; } } in AJDT, this program incorrectly shows the relationship from the TYPE to the Bar class rather than from the ITD to the Bar class.
|
resolved fixed
|
e2703cf
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-16T15:34:26Z | 2006-03-15T13:40:00Z |
weaver/src/org/aspectj/weaver/NewMethodTypeMunger.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.DataOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import org.aspectj.bridge.ISourceLocation;
public class NewMethodTypeMunger extends ResolvedTypeMunger {
public NewMethodTypeMunger(
ResolvedMember signature,
Set superMethodsCalled,
List typeVariableAliases) {
super(Method, signature);
this.typeVariableAliases = typeVariableAliases;
this.setSuperMethodsCalled(superMethodsCalled);
}
public ResolvedMember getInterMethodBody(UnresolvedType aspectType) {
return AjcMemberMaker.interMethodBody(signature, aspectType);
}
/**
* If the munger has a declared signature
*/
public ResolvedMember getDeclaredInterMethodBody(UnresolvedType aspectType,World w) {
if (declaredSignature!=null) {
ResolvedMember rm = declaredSignature.parameterizedWith(null,signature.getDeclaringType().resolve(w),false,getTypeVariableAliases());
return AjcMemberMaker.interMethodBody(rm, aspectType);
} else {
return AjcMemberMaker.interMethodBody(signature,aspectType);
}
}
public ResolvedMember getInterMethodDispatcher(UnresolvedType aspectType) {
return AjcMemberMaker.interMethodDispatcher(signature, aspectType);
}
public ResolvedMember getDeclaredInterMethodDispatcher(UnresolvedType aspectType,World w) {
if (declaredSignature!=null) {
ResolvedMember rm = declaredSignature.parameterizedWith(null,signature.getDeclaringType().resolve(w),false,getTypeVariableAliases());
return AjcMemberMaker.interMethodDispatcher(rm, aspectType);
} else {
return AjcMemberMaker.interMethodDispatcher(signature,aspectType);
}
}
public void write(DataOutputStream s) throws IOException {
kind.write(s);
signature.write(s);
writeSuperMethodsCalled(s);
writeSourceLocation(s);
writeOutTypeAliases(s);
}
public static ResolvedTypeMunger readMethod(VersionedDataInputStream s, ISourceContext context) throws IOException {
ISourceLocation sloc = null;
ResolvedMemberImpl rmImpl = ResolvedMemberImpl.readResolvedMember(s, context);
Set superMethodsCalled = readSuperMethodsCalled(s);
sloc = readSourceLocation(s);
List typeVarAliases = readInTypeAliases(s);
ResolvedTypeMunger munger = new NewMethodTypeMunger(rmImpl,superMethodsCalled,typeVarAliases);
if (sloc!=null) munger.setSourceLocation(sloc);
return munger;
}
public ResolvedMember getMatchingSyntheticMember(Member member, ResolvedType aspectType) {
ResolvedMember ret = AjcMemberMaker.interMethodDispatcher(getSignature(), aspectType);
if (ResolvedType.matches(ret, member)) return getSignature();
return super.getMatchingSyntheticMember(member, aspectType);
}
/**
* see ResolvedTypeMunger.parameterizedFor(ResolvedType)
*/
public ResolvedTypeMunger parameterizedFor(ResolvedType target) {
ResolvedType genericType = target;
if (target.isRawType() || target.isParameterizedType()) genericType = genericType.getGenericType();
ResolvedMember parameterizedSignature = null;
// If we are parameterizing it for a generic type, we just need to 'swap the letters' from the ones used
// in the original ITD declaration to the ones used in the actual target type declaration.
if (target.isGenericType()) {
TypeVariable vars[] = target.getTypeVariables();
UnresolvedTypeVariableReferenceType[] varRefs = new UnresolvedTypeVariableReferenceType[vars.length];
for (int i = 0; i < vars.length; i++) {
varRefs[i] = new UnresolvedTypeVariableReferenceType(vars[i]);
}
parameterizedSignature = getSignature().parameterizedWith(varRefs,genericType,true,typeVariableAliases);
} else {
// For raw and 'normal' parameterized targets (e.g. Interface, Interface<String>)
parameterizedSignature = getSignature().parameterizedWith(target.getTypeParameters(),genericType,target.isParameterizedType(),typeVariableAliases);
}
NewMethodTypeMunger nmtm = new NewMethodTypeMunger(parameterizedSignature,getSuperMethodsCalled(),typeVariableAliases);
nmtm.setDeclaredSignature(getSignature());
return nmtm;
}
public boolean equals(Object other) {
if (! (other instanceof NewMethodTypeMunger)) return false;
NewMethodTypeMunger o = (NewMethodTypeMunger) other;
return kind.equals(o.kind)
&& ((o.signature == null) ? (signature == null ) : signature.equals(o.signature))
&& ((o.declaredSignature == null) ? (declaredSignature == null ) : declaredSignature.equals(o.declaredSignature))
&& ((o.typeVariableAliases == null) ? (typeVariableAliases == null ) : typeVariableAliases.equals(o.typeVariableAliases));
}
public int hashCode() {
int result = 17;
result = 37*result + kind.hashCode();
result = 37*result + ((signature == null) ? 0 : signature.hashCode());
result = 37*result + ((declaredSignature == null) ? 0 : declaredSignature.hashCode());
result = 37*result + ((typeVariableAliases == null) ? 0 : typeVariableAliases.hashCode());
return result;
}
}
|
132,130 |
Bug 132130 Missing relationship for declare @method when annotating a co-located method
|
For this program (when all entered into *one* file) I don't see a marker from the declare to the annotated method. If the annotated method is in another file, I do... (not sure if fields/ctors/types are also a problem..) public aspect basic { declare @method: * debit(..): @Secured(role="supervisor"); } class BankAccount { public void debit(long accId,long amount) { } } @interface Secured { String role(); }
|
resolved fixed
|
9dca72e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-17T16:47:06Z | 2006-03-16T11:53:20Z |
ajde/testsrc/org/aspectj/ajde/AsmDeclarationsTest.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
*
* ******************************************************************/
package org.aspectj.ajde;
import org.aspectj.asm.*;
/**
* @author Mik Kersten
*/
public class AsmDeclarationsTest extends AjdeTestCase {
private IHierarchy model = null;
// TODO-path
private static final String CONFIG_FILE_PATH = "../examples/coverage/coverage.lst";
public AsmDeclarationsTest(String name) {
super(name);
}
public void testRoot() {
IProgramElement root = (IProgramElement)model.getRoot();
assertNotNull(root);
assertEquals(root.toLabelString(), "coverage.lst");
}
public void testAspectAccessibility() {
IProgramElement packageAspect = AsmManager.getDefault().getHierarchy().findElementForType(null, "AdviceNamingCoverage");
assertNotNull(packageAspect);
assertEquals(IProgramElement.Accessibility.PACKAGE, packageAspect.getAccessibility());
assertEquals("aspect should not have public in it's signature","aspect AdviceNamingCoverage",packageAspect.getSourceSignature());
}
public void testStaticModifiers() {
IProgramElement aspect = AsmManager.getDefault().getHierarchy().findElementForType(null, "ModifiersCoverage");
assertNotNull(aspect);
IProgramElement staticA = model.findElementForSignature(aspect, IProgramElement.Kind.FIELD, "staticA");
assertTrue(staticA.getModifiers().contains(IProgramElement.Modifiers.STATIC));
IProgramElement finalA = model.findElementForSignature(aspect, IProgramElement.Kind.FIELD, "finalA");
assertTrue(!finalA.getModifiers().contains(IProgramElement.Modifiers.STATIC));
assertTrue(finalA.getModifiers().contains(IProgramElement.Modifiers.FINAL));
}
public void testFileInPackageAndDefaultPackage() {
IProgramElement root = model.getRoot();
assertEquals(root.toLabelString(), "coverage.lst");
IProgramElement pkg = (IProgramElement)root.getChildren().get(1);
assertEquals(pkg.toLabelString(), "pkg");
assertEquals(((IProgramElement)pkg.getChildren().get(0)).toLabelString(), "InPackage.java");
assertEquals(((IProgramElement)root.getChildren().get(0)).toLabelString(), "ModelCoverage.java");
}
public void testDeclares() {
IProgramElement node = (IProgramElement)model.getRoot();
assertNotNull(node);
IProgramElement aspect = AsmManager.getDefault().getHierarchy().findElementForType(null, "DeclareCoverage");
assertNotNull(aspect);
String label = "declare error: \"Illegal construct..\"";
IProgramElement decErrNode = model.findElementForSignature(aspect, IProgramElement.Kind.DECLARE_ERROR, "declare error");
assertNotNull(decErrNode);
assertEquals(decErrNode.toLabelString(), label);
String decWarnMessage = "declare warning: \"Illegal call.\"";
IProgramElement decWarnNode = model.findElementForSignature(aspect, IProgramElement.Kind.DECLARE_WARNING, "declare warning");
assertNotNull(decWarnNode);
assertEquals(decWarnNode.toLabelString(), decWarnMessage);
String decParentsMessage = "declare parents: implements Serializable";
IProgramElement decParentsNode = model.findElementForSignature(aspect, IProgramElement.Kind.DECLARE_PARENTS, "declare parents");
assertNotNull(decParentsNode);
assertEquals(decParentsNode.toLabelString(), decParentsMessage);
// check the next two relative to this one
int declareIndex = decParentsNode.getParent().getChildren().indexOf(decParentsNode);
String decParentsPtnMessage = "declare parents: extends Observable";
assertEquals(decParentsPtnMessage,((IProgramElement)aspect.getChildren().get(declareIndex+1)).toLabelString());
String decParentsTPMessage = "declare parents: extends Observable";
assertEquals(decParentsTPMessage,((IProgramElement)aspect.getChildren().get(declareIndex+2)).toLabelString());
String decSoftMessage = "declare soft: SizeException";
IProgramElement decSoftNode = model.findElementForSignature(aspect, IProgramElement.Kind.DECLARE_SOFT, "declare soft");
assertNotNull(decSoftNode);
assertEquals(decSoftNode.toLabelString(), decSoftMessage);
String decPrecMessage = "declare precedence: AdviceCoverage, InterTypeDecCoverage, <type pattern>";
IProgramElement decPrecNode = model.findElementForSignature(aspect, IProgramElement.Kind.DECLARE_PRECEDENCE, "declare precedence");
assertNotNull(decPrecNode);
assertEquals(decPrecNode.toLabelString(), decPrecMessage);
}
public void testInterTypeMemberDeclares() {
IProgramElement node = (IProgramElement)model.getRoot();
assertNotNull(node);
IProgramElement aspect = AsmManager.getDefault().getHierarchy().findElementForType(null, "InterTypeDecCoverage");
assertNotNull(aspect);
String fieldMsg = "Point.xxx";
IProgramElement fieldNode = model.findElementForLabel(aspect, IProgramElement.Kind.INTER_TYPE_FIELD, fieldMsg);
assertNotNull(fieldNode);
assertEquals(fieldNode.toLabelString(), fieldMsg);
String methodMsg = "Point.check(int, Line)";
IProgramElement methodNode = model.findElementForLabel(aspect, IProgramElement.Kind.INTER_TYPE_METHOD, methodMsg);
assertNotNull(methodNode);
assertEquals(methodNode.toLabelString(), methodMsg);
// TODO: enable
// String constructorMsg = "Point.new(int, int, int)";
// ProgramElementNode constructorNode = model.findNode(aspect, ProgramElementNode.Kind.INTER_TYPE_CONSTRUCTOR, constructorMsg);
// assertNotNull(constructorNode);
// assertEquals(constructorNode.toLabelString(), constructorMsg);
}
public void testPointcuts() {
IProgramElement node = (IProgramElement)model.getRoot();
assertNotNull(node);
IProgramElement aspect = AsmManager.getDefault().getHierarchy().findElementForType(null, "AdviceNamingCoverage");
assertNotNull(aspect);
String ptct = "named()";
IProgramElement ptctNode = model.findElementForSignature(aspect, IProgramElement.Kind.POINTCUT, ptct);
assertNotNull(ptctNode);
assertEquals(ptctNode.toLabelString(), ptct);
String params = "namedWithArgs(int, int)";
IProgramElement paramsNode = model.findElementForSignature(aspect, IProgramElement.Kind.POINTCUT, params);
assertNotNull(paramsNode);
assertEquals(paramsNode.toLabelString(), params);
}
public void testAbstract() {
IProgramElement node = (IProgramElement)model.getRoot();
assertNotNull(node);
IProgramElement aspect = AsmManager.getDefault().getHierarchy().findElementForType(null, "AbstractAspect");
assertNotNull(aspect);
String abst = "abPtct()";
IProgramElement abstNode = model.findElementForSignature(aspect, IProgramElement.Kind.POINTCUT, abst);
assertNotNull(abstNode);
assertEquals(abstNode.toLabelString(), abst);
}
public void testAdvice() {
IProgramElement node = (IProgramElement)model.getRoot();
assertNotNull(node);
IProgramElement aspect = AsmManager.getDefault().getHierarchy().findElementForType(null, "AdviceNamingCoverage");
assertNotNull(aspect);
String anon = "before(): <anonymous pointcut>";
IProgramElement anonNode = model.findElementForLabel(aspect, IProgramElement.Kind.ADVICE, anon);
assertNotNull(anonNode);
assertEquals(anonNode.toLabelString(), anon);
String named = "before(): named..";
IProgramElement namedNode = model.findElementForLabel(aspect, IProgramElement.Kind.ADVICE, named);
assertNotNull(namedNode);
assertEquals(namedNode.toLabelString(), named);
String namedWithOneArg = "around(int): namedWithOneArg..";
IProgramElement namedWithOneArgNode = model.findElementForLabel(aspect, IProgramElement.Kind.ADVICE, namedWithOneArg);
assertNotNull(namedWithOneArgNode);
assertEquals(namedWithOneArgNode.toLabelString(), namedWithOneArg);
String afterReturning = "afterReturning(int, int): namedWithArgs..";
IProgramElement afterReturningNode = model.findElementForLabel(aspect, IProgramElement.Kind.ADVICE, afterReturning);
assertNotNull(afterReturningNode);
assertEquals(afterReturningNode.toLabelString(), afterReturning);
String around = "around(int): namedWithOneArg..";
IProgramElement aroundNode = model.findElementForLabel(aspect, IProgramElement.Kind.ADVICE, around);
assertNotNull(aroundNode);
assertEquals(aroundNode.toLabelString(), around);
String compAnon = "before(int): <anonymous pointcut>..";
IProgramElement compAnonNode = model.findElementForLabel(aspect, IProgramElement.Kind.ADVICE, compAnon);
assertNotNull(compAnonNode);
assertEquals(compAnonNode.toLabelString(), compAnon);
String compNamed = "before(int): named()..";
IProgramElement compNamedNode = model.findElementForLabel(aspect, IProgramElement.Kind.ADVICE, compNamed);
assertNotNull(compNamedNode);
assertEquals(compNamedNode.toLabelString(), compNamed);
}
protected void setUp() throws Exception {
super.setUp("examples");
assertTrue("build success", doSynchronousBuild(CONFIG_FILE_PATH));
model = AsmManager.getDefault().getHierarchy();
}
protected void tearDown() throws Exception {
super.tearDown();
}
}
|
132,130 |
Bug 132130 Missing relationship for declare @method when annotating a co-located method
|
For this program (when all entered into *one* file) I don't see a marker from the declare to the annotated method. If the annotated method is in another file, I do... (not sure if fields/ctors/types are also a problem..) public aspect basic { declare @method: * debit(..): @Secured(role="supervisor"); } class BankAccount { public void debit(long accId,long amount) { } } @interface Secured { String role(); }
|
resolved fixed
|
9dca72e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-17T16:47:06Z | 2006-03-16T11:53:20Z |
ajde/testsrc/org/aspectj/ajde/AsmRelationshipsTest.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
*
* ******************************************************************/
package org.aspectj.ajde;
import java.util.Iterator;
import java.util.List;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
/**
* @author Mik Kersten
*/
public class AsmRelationshipsTest extends AjdeTestCase {
private AsmManager manager = null;
// TODO-path
private static final String CONFIG_FILE_PATH = "../examples/coverage/coverage.lst";
public AsmRelationshipsTest(String name) {
super(name);
}
public void testUsesPointcut() {
IProgramElement ptUsage = AsmManager.getDefault().getHierarchy().findElementForType(null, "PointcutUsage");
assertNotNull(ptUsage);
IProgramElement pts = AsmManager.getDefault().getHierarchy().findElementForType(null, "Pointcuts");
assertNotNull(pts);
IProgramElement pUsesA = manager.getHierarchy().findElementForLabel(
ptUsage,
IProgramElement.Kind.POINTCUT,
"usesA()"/*Point"*/);
assertNotNull(pUsesA);
IProgramElement ptsA = manager.getHierarchy().findElementForLabel(
pts,
IProgramElement.Kind.POINTCUT,
"a()"/*Point"*/);
assertNotNull(ptsA);
assertTrue(AsmManager.getDefault().getRelationshipMap().get(pUsesA).size()>0);
assertTrue(AsmManager.getDefault().getRelationshipMap().get(ptsA).size()>0);
}
public void testDeclareParents() {
IProgramElement aspect = AsmManager.getDefault().getHierarchy().findElementForType(null, "DeclareCoverage");
IProgramElement dp = manager.getHierarchy().findElementForLabel(
aspect,
IProgramElement.Kind.DECLARE_PARENTS,
"declare parents: implements Serializable"/*Point"*/);
assertNotNull(dp);
/*List relations = */manager.getRelationshipMap().get(dp);
List rels = AsmManager.getDefault().getRelationshipMap().get(dp);
assertTrue(rels.size()>0);
// assertTrue(rel.getTargets().size() > 0);
//
// checkDeclareMapping("DeclareCoverage", "Point", ,
// "Point", "matched by", "matches declare",
// IProgramElement.Kind.DECLARE_PARENTS);
}
public void testDeclareWarningAndError() {
checkDeclareMapping("DeclareCoverage", "Point", "declare warning: \"Illegal call.\"",
"method-call(void Point.setX(int))", "matched by", "matches declare", IProgramElement.Kind.DECLARE_WARNING);
}
public void testInterTypeDeclarations() {
checkInterTypeMapping("InterTypeDecCoverage", "Point", "Point.xxx", "Point",
"declared on", "aspect declarations", IProgramElement.Kind.INTER_TYPE_FIELD);
checkInterTypeMapping("InterTypeDecCoverage", "Point", "Point.check(int, Line)",
"Point", "declared on", "aspect declarations", IProgramElement.Kind.INTER_TYPE_METHOD);
}
public void testAdvice() {
checkMapping("AdvisesRelationshipCoverage", "Point", "before(): methodExecutionP..",
"setX(int)", "advises", "advised by");
checkUniDirectionalMapping("AdvisesRelationshipCoverage", "Point", "before(): getP..",
"field-get(int Point.x)", "advises");
checkUniDirectionalMapping("AdvisesRelationshipCoverage", "Point", "before(): setP..",
"field-set(int Point.x)", "advises");
}
private void checkDeclareMapping(String fromType, String toType, String from, String to,
String forwardRelName, String backRelName, IProgramElement.Kind kind) {
IProgramElement aspect = AsmManager.getDefault().getHierarchy().findElementForType(null, fromType);
assertNotNull(aspect);
String beforeExec = from;
IProgramElement beforeExecNode = manager.getHierarchy().findElementForLabel(aspect, kind, beforeExec);
assertNotNull(beforeExecNode);
IRelationship rel = manager.getRelationshipMap().get(beforeExecNode, IRelationship.Kind.DECLARE, forwardRelName);
assertTrue(rel.getTargets().size() > 0);
String handle = (String)rel.getTargets().get(0);
assertEquals(manager.getHierarchy().findElementForHandle(handle).toString(), to);
IProgramElement clazz = AsmManager.getDefault().getHierarchy().findElementForType(null, toType);
assertNotNull(clazz);
String set = to;
IProgramElement setNode = manager.getHierarchy().findElementForLabel(clazz, IProgramElement.Kind.CODE, set);
assertNotNull(setNode);
IRelationship rel2 = manager.getRelationshipMap().get(setNode, IRelationship.Kind.DECLARE, backRelName);
String handle2 = (String)rel2.getTargets().get(0);
assertEquals(manager.getHierarchy().findElementForHandle(handle2).toString(), from);
}
private void checkUniDirectionalMapping(String fromType, String toType, String from,
String to, String relName) {
IProgramElement aspect = AsmManager.getDefault().getHierarchy().findElementForType(null, fromType);
assertNotNull(aspect);
String beforeExec = from;
IProgramElement beforeExecNode = manager.getHierarchy().findElementForLabel(aspect, IProgramElement.Kind.ADVICE, beforeExec);
assertNotNull(beforeExecNode);
IRelationship rel = manager.getRelationshipMap().get(beforeExecNode, IRelationship.Kind.ADVICE, relName);
for (Iterator it = rel.getTargets().iterator(); it.hasNext(); ) {
String currHandle = (String)it.next();
if (manager.getHierarchy().findElementForHandle(currHandle).toLabelString().equals(to)) return;
}
fail(); // didn't find it
}
private void checkMapping(String fromType, String toType, String from, String to,
String forwardRelName, String backRelName) {
IProgramElement aspect = AsmManager.getDefault().getHierarchy().findElementForType(null, fromType);
assertNotNull(aspect);
String beforeExec = from;
IProgramElement beforeExecNode = manager.getHierarchy().findElementForLabel(aspect, IProgramElement.Kind.ADVICE, beforeExec);
assertNotNull(beforeExecNode);
IRelationship rel = manager.getRelationshipMap().get(beforeExecNode, IRelationship.Kind.ADVICE, forwardRelName);
String handle = (String)rel.getTargets().get(0);
assertEquals(manager.getHierarchy().findElementForHandle(handle).toString(), to);
IProgramElement clazz = AsmManager.getDefault().getHierarchy().findElementForType(null, toType);
assertNotNull(clazz);
String set = to;
IProgramElement setNode = manager.getHierarchy().findElementForLabel(clazz, IProgramElement.Kind.METHOD, set);
assertNotNull(setNode);
IRelationship rel2 = manager.getRelationshipMap().get(setNode, IRelationship.Kind.ADVICE, backRelName);
String handle2 = (String)rel2.getTargets().get(0);
assertEquals(manager.getHierarchy().findElementForHandle(handle2).toString(), from);
}
private void checkInterTypeMapping(String fromType, String toType, String from,
String to, String forwardRelName, String backRelName, IProgramElement.Kind declareKind) {
IProgramElement aspect = AsmManager.getDefault().getHierarchy().findElementForType(null, fromType);
assertNotNull(aspect);
String beforeExec = from;
IProgramElement fromNode = manager.getHierarchy().findElementForLabel(aspect, declareKind, beforeExec);
assertNotNull(fromNode);
IRelationship rel = manager.getRelationshipMap().get(fromNode, IRelationship.Kind.DECLARE_INTER_TYPE, forwardRelName);
String handle = (String)rel.getTargets().get(0);
assertEquals(manager.getHierarchy().findElementForHandle(handle).toString(), to);
IProgramElement clazz = AsmManager.getDefault().getHierarchy().findElementForType(null, toType);
assertNotNull(clazz);
// String set = to;
IRelationship rel2 = manager.getRelationshipMap().get(clazz, IRelationship.Kind.DECLARE_INTER_TYPE, backRelName);
// String handle2 = (String)rel2.getTargets().get(0);
for (Iterator it = rel2.getTargets().iterator(); it.hasNext(); ) {
String currHandle = (String)it.next();
if (manager.getHierarchy().findElementForHandle(currHandle).toLabelString().equals(from)) return;
}
fail(); // didn't find it
}
protected void setUp() throws Exception {
super.setUp("examples");
assertTrue("build success", doSynchronousBuild(CONFIG_FILE_PATH));
manager = AsmManager.getDefault();
}
protected void tearDown() throws Exception {
super.tearDown();
}
}
|
132,130 |
Bug 132130 Missing relationship for declare @method when annotating a co-located method
|
For this program (when all entered into *one* file) I don't see a marker from the declare to the annotated method. If the annotated method is in another file, I do... (not sure if fields/ctors/types are also a problem..) public aspect basic { declare @method: * debit(..): @Secured(role="supervisor"); } class BankAccount { public void debit(long accId,long amount) { } } @interface Secured { String role(); }
|
resolved fixed
|
9dca72e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-17T16:47:06Z | 2006-03-16T11:53:20Z |
ajdoc/testsrc/org/aspectj/tools/ajdoc/CoverageTestCase.java
|
/* *******************************************************************
* Copyright (c) 2003 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Mik Kersten initial implementation
* ******************************************************************/
package org.aspectj.tools.ajdoc;
import java.io.File;
import java.util.List;
/**
* A long way to go until full coverage, but this is the place to add more.
*
* @author Mik Kersten
*/
public class CoverageTestCase extends AjdocTestCase {
protected File file0,file1,aspect1,file2,file3,file4,file5,file6,file7,file8,file9,file10;
protected void setUp() throws Exception {
super.setUp();
initialiseProject("coverage");
createFiles();
}
public void testOptions() {
String[] args = {
"-private",
"-encoding",
"EUCJIS",
"-docencoding",
"EUCJIS",
"-charset",
"UTF-8",
"-classpath",
AjdocTests.ASPECTJRT_PATH.getPath(),
"-d",
getAbsolutePathOutdir(),
file0.getAbsolutePath(),
};
org.aspectj.tools.ajdoc.Main.main(args);
assertTrue(true);
}
/**
* Test the "-public" argument
*/
public void testCoveragePublicMode() throws Exception {
File[] files = {file3,file9};
runAjdoc("public","1.4",files);
// have passed the "public" modifier as well as
// one public and one package visible class. There
// should only be ajdoc for the public class
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/PkgVisibleClass.html");
assertFalse("ajdoc for PkgVisibleClass shouldn't exist because passed" +
" the 'public' flag to ajdoc",htmlFile.exists());
htmlFile = new File(getAbsolutePathOutdir() + "/foo/PlainJava.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath()
+ " - were there compilation errors?");
}
// check there's no private fields within the file, that
// the file contains the getI() method but doesn't contain
// the private ClassBar, Bazz and Jazz classes.
String[] strings = { "private", "getI()","ClassBar", "Bazz", "Jazz"};
List missing = AjdocOutputChecker.getMissingStringsInFile(htmlFile,strings);
assertEquals("There should be 4 missing strings",4,missing.size());
assertTrue(htmlFile.getName() + " should not contain the private modifier",missing.contains("private"));
assertTrue(htmlFile.getName() + " should not contain the private ClassBar class",missing.contains("ClassBar"));
assertTrue(htmlFile.getName() + " should not contain the private Bazz class",missing.contains("Bazz"));
assertTrue(htmlFile.getName() + " should not contain the private Jazz class",missing.contains("Jazz"));
}
/**
* Test that the ajdoc for an aspect has the title "Aspect"
*/
public void testAJdocHasAspectTitle() throws Exception {
File[] files = {new File(getAbsoluteProjectDir() + "/pkg/A.aj")};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/pkg/A.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath()+ " - were there compilation errors?");
}
assertTrue(htmlFile.getAbsolutePath() + " should have Aspect A as it's title",
AjdocOutputChecker.containsString(htmlFile,"Aspect A"));
}
/**
* Test that the ajdoc for a class has the title "Class"
*/
public void testAJdocHasClassTitle() throws Exception {
File[] files = {new File(getAbsoluteProjectDir() + "/pkg/C.java")};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/pkg/C.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath()+ " - were there compilation errors?");
}
assertTrue(htmlFile.getAbsolutePath() + " should have Class C as it's title",
AjdocOutputChecker.containsString(htmlFile,"Class C"));
}
/**
* Test that the ajdoc for an inner aspect is entitled "Aspect" rather
* than "Class", but that the enclosing class is still "Class"
*/
public void testInnerAspect() throws Exception {
File[] files = {file1, file2};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/ClassA.InnerAspect.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath()
+ " - were there compilation errors?");
}
// ensure that the file is entitled "Aspect ClassA.InnerAspect" rather
// than "Class ClassA.InnerAspect"
String[] strings = { "Aspect ClassA.InnerAspect",
"<PRE>static aspect <B>ClassA.InnerAspect</B><DT>extends java.lang.Object</DL>",
"Class ClassA.InnerAspect",
"<PRE>static class <B>ClassA.InnerAspect</B><DT>extends java.lang.Object</DL>"};
List missing = AjdocOutputChecker.getMissingStringsInFile(htmlFile,strings);
assertEquals("There should be 2 missing strings",2,missing.size());
assertTrue(htmlFile.getName() + " should not have Class as it's title",missing.contains("Class ClassA.InnerAspect"));
assertTrue(htmlFile.getName() + " should not have class in its subtitle",missing.contains("<PRE>static class <B>ClassA.InnerAspect</B><DT>extends java.lang.Object</DL>"));
// get the html file for the enclosing class
File htmlFileClass = new File(getAbsolutePathOutdir() + "/foo/ClassA.html");
if (htmlFileClass == null || !htmlFileClass.exists()) {
fail("couldn't find " + htmlFileClass.getAbsolutePath()
+ " - were there compilation errors?");
}
// ensure that the file is entitled "Class ClassA" and
// has not been changed to "Aspect ClassA"
String[] classStrings = { "Class ClassA</H2>",
"public abstract class <B>ClassA</B><DT>extends java.lang.Object<DT>",
"Aspect ClassA</H2>",
"public abstract aspect <B>ClassA</B><DT>extends java.lang.Object<DT>"};
List classMissing = AjdocOutputChecker.getMissingStringsInFile(htmlFileClass,classStrings);
assertEquals("There should be 2 missing strings",2,classMissing.size());
assertTrue(htmlFileClass.getName() + " should not have Aspect as it's title",classMissing.contains("Aspect ClassA</H2>"));
assertTrue(htmlFileClass.getName() + " should not have aspect in its subtitle",classMissing.contains("public abstract aspect <B>ClassA</B><DT>extends java.lang.Object<DT>"));
}
/**
* Test that all the different types of advice appear
* with the named pointcut in it's description
*/
public void testAdviceNamingCoverage() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/AdviceNamingCoverage.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath()
+ " - were there compilation errors?");
}
String[] strings = {
"after(): named..",
"afterReturning(int, int): namedWithArgs..",
"afterThrowing(): named..",
"before(): named..",
"around(int): namedWithOneArg..",
"before(int):",
"before(int): named()..",
"before():"};
List missing = AjdocOutputChecker.getMissingStringsInSection(
htmlFile, strings,"ADVICE DETAIL SUMMARY");
assertTrue(htmlFile.getName() + " should contain all advice in the Advice Detail section",missing.isEmpty());
missing = AjdocOutputChecker.getMissingStringsInSection(
htmlFile,strings,"ADVICE SUMMARY");
assertTrue(htmlFile.getName() + " should contain all advice in the Advice Summary section",missing.isEmpty());
}
/**
* Test that all the advises relationships appear in the
* Advice Detail and Advice Summary sections and that
* the links are correct
*/
public void testAdvisesRelationshipCoverage() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/AdvisesRelationshipCoverage.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String[] strings = {
"before(): methodExecutionP..",
"HREF=\"../foo/Point.html#setX(int)\"",
"before(): constructorExecutionP..",
"HREF=\"../foo/Point.html#Point()\"",
"before(): callMethodP..",
"HREF=\"../foo/Point.html#changeX(int)\"",
"before(): callConstructorP..",
"HREF=\"../foo/Point.html#doIt()\"",
"before(): getP..",
"HREF=\"../foo/Point.html#getX()\"",
"before(): setP..",
"HREF=\"../foo/Point.html\"><tt>foo.Point</tt></A>, <A HREF=\"../foo/Point.html#Point()\"><tt>foo.Point.Point()</tt></A>, <A HREF=\"../foo/Point.html#setX(int)\"",
"before(): initializationP..",
"HREF=\"../foo/Point.html#Point()\"",
"before(): staticinitializationP..",
"HREF=\"../foo/Point.html\"",
"before(): handlerP..",
"HREF=\"../foo/Point.html#doIt()\""
};
for (int i = 0; i < strings.length - 1; i = i+2) {
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"ADVICE DETAIL SUMMARY",strings[i],
HtmlDecorator.HtmlRelationshipKind.ADVISES,
strings[i+1]);
assertTrue(strings[i] + " should advise " + strings[i+1] +
" in the Advice Detail section", b);
}
for (int i = 0; i < strings.length - 1; i = i+2) {
boolean b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"ADVICE SUMMARY",strings[i],
HtmlDecorator.HtmlRelationshipKind.ADVISES,
strings[i+1]);
assertTrue(strings[i] + " should advise " + strings[i+1] +
" in the Advice Summary section", b);
}
}
/**
* Test that the advised by relationship appears in the ajdoc when the
* advice is associated with a method execution pointcut
*/
public void testAdvisedByMethodExecution() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/Point.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String[] strings = {
"setX(int)",
"HREF=\"../foo/AdvisesRelationshipCoverage.html#before(): methodExecutionP..\""};
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD DETAIL",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Detail should have " + strings[0]+" advised by " + strings[1],b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== METHOD SUMMARY",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Summary should have " + strings[0]+" advised by " + strings[1],b);
}
/**
* Test that the advised by relationship appears in the ajdoc when the
* advice is associated with a constructor execution pointcut
*/
public void testAdvisedByConstructorExecution() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/Point.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String[] strings = {
"Point()",
"HREF=\"../foo/AdvisesRelationshipCoverage.html#before(): constructorExecutionP..\""};
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== CONSTRUCTOR DETAIL",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Constructor Detail should have " + strings[0]+" advised by " + strings[1],b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== CONSTRUCTOR SUMMARY",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Constructor Summary should have " + strings[0]+" advised by " + strings[1],b);
}
/**
* Test that the advised by relationship appears in the ajdoc when the
* advice is associated with a method call pointcut
*/
public void testAdvisedByMethodCall() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/Point.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String[] strings = {
"changeX(int)",
"HREF=\"../foo/AdvisesRelationshipCoverage.html#before(): callMethodP..\""};
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD DETAIL",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Detail should have " + strings[0]+" advised by " + strings[1],b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== METHOD SUMMARY",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Summary should have " + strings[0]+" advised by " + strings[1],b);
}
/**
* Test that the advised by relationship appears in the ajdoc when the
* advice is associated with a constructor call pointcut
*/
public void testAdvisedByConstructorCall() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/Point.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String[] strings = {
"doIt()",
"HREF=\"../foo/AdvisesRelationshipCoverage.html#before(): callConstructorP..\""};
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD DETAIL",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Detail should have " + strings[0]+" advised by " + strings[1],b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== METHOD SUMMARY",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Summary should have " + strings[0]+" advised by " + strings[1],b);
}
/**
* Test that the advised by relationship appears in the ajdoc when the
* advice is associated with a get pointcut
*/
public void testAdvisedByGet() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/Point.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String[] strings = {
"getX()",
"HREF=\"../foo/AdvisesRelationshipCoverage.html#before(): getP..\""};
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD DETAIL",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Detail should have " + strings[0]+" advised by " + strings[1],b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== METHOD SUMMARY",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Summary should have " + strings[0]+" advised by " + strings[1],b);
}
/**
* Test that the advised by relationship appears in the ajdoc when the
* advice is associated with a set pointcut
*/
public void testAdvisedBySet() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/Point.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String href = "HREF=\"../foo/AdvisesRelationshipCoverage.html#before(): setP..\"";
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD DETAIL",
"setX(int)",
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
href);
assertTrue("the Method Detail should have setX(int) advised by " + href,b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== METHOD SUMMARY",
"setX(int)",
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
href);
assertTrue("the Method Summary should have setX(int) advised by " + href,b);
b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== CONSTRUCTOR DETAIL",
"Point()",
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
href);
assertTrue("the Constructor Detail should have advised by " + href,b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== CONSTRUCTOR SUMMARY",
"Point()",
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
href);
assertTrue("the Constructor Summary should have advised by " + href,b);
b = AjdocOutputChecker.classDataSectionContainsRel(
htmlFile,
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
href);
assertTrue("The class data section should have 'advised by " + href + "'",b);
}
/**
* Test that the advised by relationship appears in the ajdoc when the
* advice is associated with an initialization pointcut
*/
public void testAdvisedByInitialization() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/Point.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String[] strings = {
"Point()",
"HREF=\"../foo/AdvisesRelationshipCoverage.html#before(): initializationP..\""};
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== CONSTRUCTOR DETAIL",strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Detail should have 'setX(int) advised by ... before()'",b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== CONSTRUCTOR SUMMARY",strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Summary should have 'setX(int) advised by ... before()'",b);
}
/**
* Test that the advised by relationship appears in the ajdoc when the
* advice is associated with a staticinitialization pointcut
*/
public void testAdvisedByStaticInitialization() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/Point.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String href = "HREF=\"../foo/AdvisesRelationshipCoverage.html#before(): staticinitializationP..\"";
boolean b = AjdocOutputChecker.classDataSectionContainsRel(
htmlFile,
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
href);
assertTrue("The class data section should have 'advised by " + href + "'",b);
}
/**
* Test that the advised by relationship appears in the ajdoc when the
* advice is associated with a handler pointcut
*/
public void testAdvisedByHandler() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/Point.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String[] strings = {
"doIt()",
"HREF=\"../foo/AdvisesRelationshipCoverage.html#before(): handlerP..\""};
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD DETAIL",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Detail should have " + strings[0]+" advised by " + strings[1],b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== METHOD SUMMARY",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Summary should have " + strings[0]+" advised by " + strings[1],b);
}
/**
* Test that if have two before advice blocks from the same
* aspect affect the same method, then both appear in the ajdoc
*/
public void testTwoBeforeAdvice() throws Exception {
File[] files = {new File(getAbsoluteProjectDir() + "/pkg/A2.aj")};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/pkg/C2.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String[] strings = {
"amethod()",
"HREF=\"../pkg/A2.html#before(): p..\"",
"HREF=\"../pkg/A2.html#before(): p2..\""};
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD DETAIL",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Detail should have " + strings[0]+" advised by " + strings[1],b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== METHOD SUMMARY",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[1]);
assertTrue("the Method Summary should have " + strings[0]+" advised by " + strings[1],b);
b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD DETAIL",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[2]);
assertTrue("the Method Detail should have " + strings[0]+" advised by " + strings[2],b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== METHOD SUMMARY",
strings[0],
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
strings[2]);
assertTrue("the Method Summary should have " + strings[0]+" advised by " + strings[2],b);
}
/**
* Test that there are no spurious "advised by" entries
* against the aspect in the ajdoc
*/
public void testNoSpuriousAdvisedByRels() throws Exception {
File[] files = {file4};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/foo/AdvisesRelationshipCoverage.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath() + " - were there compilation errors?");
}
String href = "foo.Point.setX(int)";
boolean b = AjdocOutputChecker.classDataSectionContainsRel(
htmlFile,
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
href);
assertFalse("The class data section should not have 'advised by " + href + "'",b);
}
public void testCoverage() {
File[] files = {aspect1,file0,file1,file2,file3,file4,file5,file6,
file7,file8,file9,file10};
runAjdoc("private","1.4",files);
}
/**
* Test that nested aspects appear with "aspect" in their title
* when the ajdoc file is written slightly differently (when it's
* written for this apsect, it's different than for testInnerAspect())
*/
public void testNestedAspect() throws Exception {
File[] files = {file9};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/PkgVisibleClass.NestedAspect.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath()
+ " - were there compilation errors?");
}
// ensure that the file is entitled "Aspect PkgVisibleClass.NestedAspect" rather
// than "Class PkgVisibleClass.NestedAspect"
String[] strings = { "Aspect PkgVisibleClass.NestedAspect",
"<PRE>static aspect <B>PkgVisibleClass.NestedAspect</B><DT>extends java.lang.Object</DL>",
"Class PkgVisibleClass.NestedAspect",
"<PRE>static class <B>PkgVisibleClass.NestedAspect</B><DT>extends java.lang.Object</DL>"};
List missing = AjdocOutputChecker.getMissingStringsInFile(htmlFile,strings);
assertEquals("There should be 2 missing strings",2,missing.size());
assertTrue(htmlFile.getName() + " should not have Class as it's title",missing.contains("Class PkgVisibleClass.NestedAspect"));
assertTrue(htmlFile.getName() + " should not have class in its subtitle",missing.contains("<PRE>static class <B>PkgVisibleClass.NestedAspect</B><DT>extends java.lang.Object</DL>"));
// get the html file for the enclosing class
File htmlFileClass = new File(getAbsolutePathOutdir() + "/PkgVisibleClass.html");
if (htmlFileClass == null || !htmlFileClass.exists()) {
fail("couldn't find " + htmlFileClass.getAbsolutePath()
+ " - were there compilation errors?");
}
// ensure that the file is entitled "Class PkgVisibleClass" and
// has not been changed to "Aspect PkgVisibleClass"
String[] classStrings = { "Class PkgVisibleClass</H2>",
"class <B>PkgVisibleClass</B><DT>extends java.lang.Object</DL>",
"Aspect PkgVisibleClass</H2>",
"aspect <B>PkgVisibleClass</B><DT>extends java.lang.Object<DT>"};
List classMissing = AjdocOutputChecker.getMissingStringsInFile(htmlFileClass,classStrings);
assertEquals("There should be 2 missing strings",2,classMissing.size());
assertTrue(htmlFileClass.getName() + " should not have Aspect as it's title",classMissing.contains("Aspect PkgVisibleClass</H2>"));
assertTrue(htmlFileClass.getName() + " should not have aspect in its subtitle",classMissing.contains("aspect <B>PkgVisibleClass</B><DT>extends java.lang.Object<DT>"));
}
/**
* Test that in the case when you have a nested aspect whose
* name is part of the enclosing class, for example a class called
* ClassWithNestedAspect has nested aspect called NestedAspect,
* that the titles for the ajdoc are correct.
*/
public void testNestedAspectWithSimilarName() throws Exception {
File[] files = {new File(getAbsoluteProjectDir() + "/pkg/ClassWithNestedAspect.java")};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/pkg/ClassWithNestedAspect.NestedAspect.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath()
+ " - were there compilation errors?");
}
// ensure that the file is entitled "Aspect ClassWithNestedAspect.NestedAspect"
// rather than "Class ClassWithNestedAspect.NestedAspect"
String[] strings = { "Aspect ClassWithNestedAspect.NestedAspect",
"<PRE>static aspect <B>ClassWithNestedAspect.NestedAspect</B><DT>extends java.lang.Object</DL>",
"Class ClassWithNestedAspect.NestedAspect",
"<PRE>static class <B>ClassWithNestedAspect.NestedAspect</B><DT>extends java.lang.Object</DL>"};
List missing = AjdocOutputChecker.getMissingStringsInFile(htmlFile,strings);
assertEquals("There should be 2 missing strings",2,missing.size());
assertTrue(htmlFile.getName() + " should not have Class as it's title",missing.contains("Class ClassWithNestedAspect.NestedAspect"));
assertTrue(htmlFile.getName() + " should not have class in its subtitle",missing.contains("<PRE>static class <B>ClassWithNestedAspect.NestedAspect</B><DT>extends java.lang.Object</DL>"));
// get the html file for the enclosing class
File htmlFileClass = new File(getAbsolutePathOutdir() + "/pkg/ClassWithNestedAspect.html");
if (htmlFileClass == null || !htmlFileClass.exists()) {
fail("couldn't find " + htmlFileClass.getAbsolutePath()
+ " - were there compilation errors?");
}
// ensure that the file is entitled "Class ClassWithNestedAspect" and
// has not been changed to "Aspect ClassWithNestedAspect"
String[] classStrings = { "Class ClassWithNestedAspect</H2>",
"public class <B>ClassWithNestedAspect</B><DT>extends java.lang.Object</DL>",
"Aspect ClassWithNestedAspect</H2>",
"public aspect <B>ClassWithNestedAspect</B><DT>extends java.lang.Object</DL>"};
List classMissing = AjdocOutputChecker.getMissingStringsInFile(htmlFileClass,classStrings);
assertEquals("There should be 2 missing strings",2,classMissing.size());
assertTrue(htmlFileClass.getName() + " should not have Aspect as it's title",
classMissing.contains("Aspect ClassWithNestedAspect</H2>"));
assertTrue(htmlFileClass.getName() + " should not have aspect in its subtitle",
classMissing.contains("public aspect <B>ClassWithNestedAspect</B><DT>extends java.lang.Object</DL>"));
}
/**
* Test that everythings being decorated correctly within the ajdoc
* for the aspect when the aspect is a nested aspect
*/
public void testAdviceInNestedAspect() throws Exception {
File[] files = {new File(getAbsoluteProjectDir() + "/pkg/ClassWithNestedAspect.java")};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/pkg/ClassWithNestedAspect.NestedAspect.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath()
+ " - were there compilation errors?");
}
boolean b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"ADVICE DETAIL SUMMARY",
"before(): p..",
HtmlDecorator.HtmlRelationshipKind.ADVISES,
"HREF=\"../pkg/ClassWithNestedAspect.html#amethod()\"");
assertTrue("Should have 'before(): p.. advises HREF=\"../pkg/ClassWithNestedAspect.html#amethod()\"" +
"' in the Advice Detail section", b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"ADVICE SUMMARY",
"before(): p..",
HtmlDecorator.HtmlRelationshipKind.ADVISES,
"HREF=\"../pkg/ClassWithNestedAspect.html#amethod()\"");
assertTrue("Should have 'before(): p.. advises HREF=\"../pkg/ClassWithNestedAspect.html#amethod()\"" +
"' in the Advice Summary section", b);
}
/**
* Test that everythings being decorated correctly within the ajdoc
* for the advised class when the aspect is a nested aspect
*/
public void testAdvisedByInNestedAspect() throws Exception {
File[] files = {new File(getAbsoluteProjectDir() + "/pkg/ClassWithNestedAspect.java")};
runAjdoc("private","1.4",files);
File htmlFile = new File(getAbsolutePathOutdir() + "/pkg/ClassWithNestedAspect.html");
if (htmlFile == null || !htmlFile.exists()) {
fail("couldn't find " + htmlFile.getAbsolutePath()
+ " - were there compilation errors?");
}
boolean b = AjdocOutputChecker.containsString(htmlFile,"POINTCUT SUMMARY ");
assertFalse(htmlFile.getName() + " should not contain a pointcut summary section",b);
b = AjdocOutputChecker.containsString(htmlFile,"ADVICE SUMMARY ");
assertFalse(htmlFile.getName() + " should not contain an adivce summary section",b);
b = AjdocOutputChecker.containsString(htmlFile,"POINTCUT DETAIL ");
assertFalse(htmlFile.getName() + " should not contain a pointcut detail section",b);
b = AjdocOutputChecker.containsString(htmlFile,"ADVICE DETAIL ");
assertFalse(htmlFile.getName() + " should not contain an advice detail section",b);
b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD DETAIL",
"amethod()",
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
"HREF=\"../pkg/ClassWithNestedAspect.NestedAspect.html#before(): p..\"");
assertTrue("Should have 'amethod() advised by " +
"HREF=\"../pkg/ClassWithNestedAspect.NestedAspect.html#before(): p..\"" +
"' in the Method Detail section", b);
b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD DETAIL",
"amethod()",
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
"pkg.ClassWithNestedAspect.NestedAspect.NestedAspect.before(): p..");
assertFalse("Should not have the label " +
"pkg.ClassWithNestedAspect.NestedAspect.NestedAspect.before(): p.." +
" in the Method Detail section", b);
b = AjdocOutputChecker.summarySectionContainsRel(
htmlFile,"=== METHOD SUMMARY",
"amethod()",
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
"HREF=\"../pkg/ClassWithNestedAspect.NestedAspect.html#before(): p..\"");
assertTrue("Should have 'amethod() advised by " +
"HREF=\"../pkg/ClassWithNestedAspect.NestedAspect.html#before(): p..\"" +
"' in the Method Summary section", b);
b = AjdocOutputChecker.detailSectionContainsRel(
htmlFile,"=== METHOD SUMMARY",
"amethod()",
HtmlDecorator.HtmlRelationshipKind.ADVISED_BY,
"pkg.ClassWithNestedAspect.NestedAspect.NestedAspect.before(): p..");
assertFalse("Should not have the label " +
"pkg.ClassWithNestedAspect.NestedAspect.NestedAspect.before(): p.." +
" in the Method Summary section", b);
}
private void createFiles() {
file0 = new File(getAbsoluteProjectDir() + "/InDefaultPackage.java");
file1 = new File(getAbsoluteProjectDir() + "/foo/ClassA.java");
aspect1 = new File(getAbsoluteProjectDir() + "/foo/UseThisAspectForLinkCheck.aj");
file2 = new File(getAbsoluteProjectDir() + "/foo/InterfaceI.java");
file3 = new File(getAbsoluteProjectDir() + "/foo/PlainJava.java");
file4 = new File(getAbsoluteProjectDir() + "/foo/ModelCoverage.java");
file5 = new File(getAbsoluteProjectDir() + "/fluffy/Fluffy.java");
file6 = new File(getAbsoluteProjectDir() + "/fluffy/bunny/Bunny.java");
file7 = new File(getAbsoluteProjectDir() + "/fluffy/bunny/rocks/Rocks.java");
file8 = new File(getAbsoluteProjectDir() + "/fluffy/bunny/rocks/UseThisAspectForLinkCheckToo.java");
file9 = new File(getAbsoluteProjectDir() + "/foo/PkgVisibleClass.java");
file10 = new File(getAbsoluteProjectDir() + "/foo/NoMembers.java");
}
// public void testPlainJava() {
// String[] args = { "-d",
// getAbsolutePathOutdir(),
// file3.getAbsolutePath() };
// org.aspectj.tools.ajdoc.Main.main(args);
// }
}
|
132,130 |
Bug 132130 Missing relationship for declare @method when annotating a co-located method
|
For this program (when all entered into *one* file) I don't see a marker from the declare to the annotated method. If the annotated method is in another file, I do... (not sure if fields/ctors/types are also a problem..) public aspect basic { declare @method: * debit(..): @Secured(role="supervisor"); } class BankAccount { public void debit(long accId,long amount) { } } @interface Secured { String role(); }
|
resolved fixed
|
9dca72e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-17T16:47:06Z | 2006-03-16T11:53:20Z |
asm/src/org/aspectj/asm/internal/ProgramElement.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 Extensions for better IDE representation
* ******************************************************************/
package org.aspectj.asm.internal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.HierarchyWalker;
import org.aspectj.asm.IProgramElement;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
/**
* @author Mik Kersten
*/
public class ProgramElement implements IProgramElement {
private static final long serialVersionUID = 171673495267384449L;
public static boolean shortITDNames = true;
private final static String UNDEFINED = "<undefined>";
private static int AccPublic = 0x0001;
private static int AccPrivate = 0x0002;
private static int AccProtected = 0x0004;
private static int AccPrivileged = 0x0006; // XXX is this right?
private static int AccStatic = 0x0008;
private static int AccFinal = 0x0010;
private static int AccSynchronized = 0x0020;
private static int AccVolatile = 0x0040;
private static int AccTransient = 0x0080;
private static int AccNative = 0x0100;
private static int AccInterface = 0x0200;
private static int AccAbstract = 0x0400;
private static int AccStrictfp = 0x0800;
protected String name;
private Kind kind;
protected IProgramElement parent = null;
protected List children = Collections.EMPTY_LIST;
private Map kvpairs = Collections.EMPTY_MAP;
protected ISourceLocation sourceLocation = null;
private int modifiers;
private String handle = null;
// --- ctors
/** Used during de-externalization */
public ProgramElement() { }
/** Use to create program element nodes that do not correspond to source locations */
public ProgramElement (String name,Kind kind,List children) {
this.name = name;
this.kind = kind;
if (children!=null) setChildren(children);
}
public ProgramElement (String name, IProgramElement.Kind kind, ISourceLocation sourceLocation,
int modifiers, String comment, List children) {
this(name, kind, children);
this.sourceLocation = //ISourceLocation.EMPTY;
sourceLocation;
setFormalComment(comment);
// if (comment!=null && comment.length()>0) formalComment = comment;
this.modifiers = modifiers;
// this.accessibility = genAccessibility(modifiers);
cacheByHandle();
}
/**
* Use to create program element nodes that correspond to source locations.
*/
public ProgramElement(
String name,
Kind kind,
int modifiers,
//Accessibility accessibility,
String declaringType,
String packageName,
String comment,
ISourceLocation sourceLocation,
List relations,
List children,
boolean member) {
this(name, kind, children);
this.sourceLocation =
//ISourceLocation.EMPTY;
sourceLocation;
this.kind = kind;
this.modifiers = modifiers;
// this.accessibility = accessibility;
setDeclaringType(declaringType);//this.declaringType = declaringType;
//this.packageName = packageName;
setFormalComment(comment);
// if (comment!=null && comment.length()>0) formalComment = comment;
if (relations!=null && relations.size()!=0) setRelations(relations);
// this.relations = relations;
cacheByHandle();
}
public List getModifiers() {
return genModifiers(modifiers);
}
public Accessibility getAccessibility() {
return genAccessibility(modifiers); // accessibility
}
// public void setAccessibility(Accessibility a) {
//
// //accessibility=a;
// }
public void setDeclaringType(String t) {
if (t!=null && t.length()>0) {
if (kvpairs==Collections.EMPTY_MAP) kvpairs = new HashMap();
kvpairs.put("declaringType",t);
}
}
public String getDeclaringType() {
String dt = (String)kvpairs.get("declaringType");
if (dt==null) return ""; // assumption that not having one means "" is at HtmlDecorator line 111
return dt;
}
public String getPackageName() {
if (kind == Kind.PACKAGE) return getName();
if (getParent() == null || !(getParent() instanceof IProgramElement)) {
return "";
}
return ((IProgramElement)getParent()).getPackageName();
}
public Kind getKind() {
return kind;
}
public boolean isCode() {
return kind.equals(Kind.CODE);
}
public ISourceLocation getSourceLocation() {
return sourceLocation;
}
public void setSourceLocation(ISourceLocation sourceLocation) {
//this.sourceLocation = sourceLocation;
}
public IMessage getMessage() {
return (IMessage)kvpairs.get("message");
// return message;
}
public void setMessage(IMessage message) {
if (kvpairs==Collections.EMPTY_MAP) kvpairs = new HashMap();
kvpairs.put("message",message);
// this.message = message;
}
public IProgramElement getParent() {
return parent;
}
public void setParent(IProgramElement parent) {
this.parent = parent;
}
public boolean isMemberKind() {
return kind.isMember();
}
public void setRunnable(boolean value) {
if (kvpairs==Collections.EMPTY_MAP) kvpairs = new HashMap();
if (value) kvpairs.put("isRunnable","true");
else kvpairs.remove("isRunnable");
// this.runnable = value;
}
public boolean isRunnable() {
return kvpairs.get("isRunnable")!=null;
// return runnable;
}
public boolean isImplementor() {
return kvpairs.get("isImplementor")!=null;
// return implementor;
}
public void setImplementor(boolean value) {
if (kvpairs==Collections.EMPTY_MAP) kvpairs = new HashMap();
if (value) kvpairs.put("isImplementor","true");
else kvpairs.remove("isImplementor");
// this.implementor = value;
}
public boolean isOverrider() {
return kvpairs.get("isOverrider")!=null;
// return overrider;
}
public void setOverrider(boolean value) {
if (kvpairs==Collections.EMPTY_MAP) kvpairs = new HashMap();
if (value) kvpairs.put("isOverrider","true");
else kvpairs.remove("isOverrider");
// this.overrider = value;
}
public List getRelations() {
return (List)kvpairs.get("relations");
// return relations;
}
public void setRelations(List relations) {
if (relations.size() > 0) {
if (kvpairs==Collections.EMPTY_MAP) kvpairs = new HashMap();
kvpairs.put("relations",relations);
// this.relations = relations;
}
}
public String getFormalComment() {
return (String)kvpairs.get("formalComment");
// return formalComment;
}
public String toString() {
return toLabelString();
}
private static List genModifiers(int modifiers) {
List modifiersList = new ArrayList();
if ((modifiers & AccStatic) != 0) modifiersList.add(IProgramElement.Modifiers.STATIC);
if ((modifiers & AccFinal) != 0) modifiersList.add(IProgramElement.Modifiers.FINAL);
if ((modifiers & AccSynchronized) != 0) modifiersList.add(IProgramElement.Modifiers.SYNCHRONIZED);
if ((modifiers & AccVolatile) != 0) modifiersList.add(IProgramElement.Modifiers.VOLATILE);
if ((modifiers & AccTransient) != 0) modifiersList.add(IProgramElement.Modifiers.TRANSIENT);
if ((modifiers & AccNative) != 0) modifiersList.add(IProgramElement.Modifiers.NATIVE);
if ((modifiers & AccAbstract) != 0) modifiersList.add(IProgramElement.Modifiers.ABSTRACT);
return modifiersList;
}
public static IProgramElement.Accessibility genAccessibility(int modifiers) {
if ((modifiers & AccPublic) != 0) return IProgramElement.Accessibility.PUBLIC;
if ((modifiers & AccPrivate) != 0) return IProgramElement.Accessibility.PRIVATE;
if ((modifiers & AccProtected) != 0) return IProgramElement.Accessibility.PROTECTED;
if ((modifiers & AccPrivileged) != 0) return IProgramElement.Accessibility.PRIVILEGED;
else return IProgramElement.Accessibility.PACKAGE;
}
public String getBytecodeName() {
String s = (String)kvpairs.get("bytecodeName");
if (s==null) return UNDEFINED;
return s;
}
public String getBytecodeSignature() {
String s = (String)kvpairs.get("bytecodeSignature");
// if (s==null) return UNDEFINED;
return s;
}
public void setBytecodeName(String s) {
if (kvpairs==Collections.EMPTY_MAP) kvpairs = new HashMap();
kvpairs.put("bytecodeName",s);
}
public void setBytecodeSignature(String s) {
if (kvpairs==Collections.EMPTY_MAP) kvpairs = new HashMap();
kvpairs.put("bytecodeSignature",s);
}
public String getSourceSignature() {
return (String)kvpairs.get("sourceSignature");
}
public void setSourceSignature(String string) {
if (kvpairs==Collections.EMPTY_MAP) kvpairs = new HashMap();
// System.err.println(name+" SourceSig=>"+string);
kvpairs.put("sourceSignature",string);
// sourceSignature = string;
}
public void setKind(Kind kind) {
this.kind = kind;
}
public void setCorrespondingType(String s) {
if (kvpairs==Collections.EMPTY_MAP) kvpairs = new HashMap();
kvpairs.put("returnType",s);
// this.returnType = s;
}
public String getCorrespondingType() {
return getCorrespondingType(false);
}
public String getCorrespondingType(boolean getFullyQualifiedType) {
String returnType = (String)kvpairs.get("returnType");
if (returnType==null) returnType="";
if (getFullyQualifiedType) {
return returnType;
}
int index = returnType.lastIndexOf(".");
if (index != -1) {
return returnType.substring(index);
}
return returnType;
}
public String getName() {
return name;
}
public List getChildren() {
return children;
}
public void setChildren(List children) {
this.children = children;
if (children == null) return;
for (Iterator it = children.iterator(); it.hasNext(); ) {
((IProgramElement)it.next()).setParent(this);
}
}
public void addChild(IProgramElement child) {
if (children == null || children==Collections.EMPTY_LIST) children = new ArrayList();
children.add(child);
child.setParent(this);
}
public void addChild(int position, IProgramElement child) {
if (children == null || children==Collections.EMPTY_LIST) children = new ArrayList();
children.add(position, child);
child.setParent(this);
}
public boolean removeChild(IProgramElement child) {
child.setParent(null);
return children.remove(child);
}
public void setName(String string) {
name = string;
}
public IProgramElement walk(HierarchyWalker walker) {
if (children!=null) {
for (Iterator it = children.iterator(); it.hasNext(); ) {
IProgramElement child = (IProgramElement)it.next();
walker.process(child);
}
}
return this;
}
public String toLongString() {
final StringBuffer buffer = new StringBuffer();
HierarchyWalker walker = new HierarchyWalker() {
private int depth = 0;
public void preProcess(IProgramElement node) {
for (int i = 0; i < depth; i++) buffer.append(' ');
buffer.append(node.toString());
buffer.append('\n');
depth += 2;
}
public void postProcess(IProgramElement node) {
depth -= 2;
}
};
walker.process(this);
return buffer.toString();
}
public void setModifiers(int i) {
this.modifiers = i;
}
public String toSignatureString() {
return toSignatureString(true);
}
public String toSignatureString(boolean getFullyQualifiedArgTypes) {
StringBuffer sb = new StringBuffer();
sb.append(name);
List ptypes = getParameterTypes();
if (ptypes != null) {
sb.append('(');
for (Iterator it = ptypes.iterator(); it.hasNext(); ) {
String arg = (String)it.next();
if (getFullyQualifiedArgTypes) {
sb.append(arg);
} else {
int index = arg.lastIndexOf(".");
if (index != -1) {
sb.append(arg.substring(index + 1));
} else {
sb.append(arg);
}
}
if (it.hasNext()) sb.append(", ");
}
sb.append(')');
}
return sb.toString();
}
/**
* TODO: move the "parent != null"==>injar heuristic to more explicit
*/
public String toLinkLabelString() {
return toLinkLabelString(true);
}
public String toLinkLabelString(boolean getFullyQualifiedArgTypes) {
String label;
if (kind == Kind.CODE || kind == Kind.INITIALIZER) {
label = parent.getParent().getName() + ": ";
} else if (kind.isInterTypeMember()) {
if (shortITDNames) {
// if (name.indexOf('.')!=-1) return toLabelString().substring(name.indexOf('.')+1);
label="";
} else {
int dotIndex = name.indexOf('.');
if (dotIndex != -1) {
return parent.getName() + ": " + toLabelString().substring(dotIndex+1);
} else {
label = parent.getName() + '.';
}
}
} else if (kind == Kind.CLASS || kind == Kind.ASPECT || kind == Kind.INTERFACE) {
label = "";
} else if (kind.equals(Kind.DECLARE_PARENTS)) {
label = "";
} else {
if (parent != null) {
label = parent.getName() + '.';
} else {
label = "injar aspect: ";
}
}
label += toLabelString(getFullyQualifiedArgTypes);
return label;
}
public String toLabelString() {
return toLabelString(true);
}
public String toLabelString(boolean getFullyQualifiedArgTypes) {
String label = toSignatureString(getFullyQualifiedArgTypes);
String details = getDetails();
if (details != null) {
label += ": " + details;
}
return label;
}
public String getHandleIdentifier() {
if (null == handle) {
if (sourceLocation != null) {
handle = AsmManager.getDefault().getHandleProvider().createHandleIdentifier(sourceLocation);
// return genHandleIdentifier(sourceLocation);
}
}
return handle;
}
public List getParameterNames() {
List parameterNames = (List)kvpairs.get("parameterNames");
return parameterNames;
}
public void setParameterNames(List list) {
if (list==null || list.size()==0) return;
if (kvpairs==Collections.EMPTY_MAP) kvpairs = new HashMap();
kvpairs.put("parameterNames",list);
//parameterNames = list;
}
public List getParameterTypes() {
List parameterTypes = (List)kvpairs.get("parameterTypes");
return parameterTypes;
}
public void setParameterTypes(List list) {
if (kvpairs==Collections.EMPTY_MAP) kvpairs = new HashMap();
if (list==null || list.size()==0) kvpairs.put("parameterTypes",Collections.EMPTY_LIST);
else kvpairs.put("parameterTypes",list);
// parameterTypes = list;
}
public String getDetails() {
String details = (String)kvpairs.get("details");
return details;
}
public void setDetails(String string) {
if (kvpairs==Collections.EMPTY_MAP) kvpairs = new HashMap();
kvpairs.put("details",string);
}
public void setFormalComment(String txt) {
if (txt!=null && txt.length()>0) {
if (kvpairs==Collections.EMPTY_MAP) kvpairs = new HashMap();
kvpairs.put("formalComment",txt);
}
}
/** AMC added to speed up findByHandle lookups in AspectJElementHierarchy */
private void cacheByHandle() {
String handle = getHandleIdentifier();
if (handle != null) {
AspectJElementHierarchy hierarchy = (AspectJElementHierarchy)
AsmManager.getDefault().getHierarchy();
hierarchy.cache(handle,this);
//System.err.println("Cache size now "+hierarchy.handleMap.size());
}
}
public void setExtraInfo(ExtraInformation info) {
if (kvpairs==Collections.EMPTY_MAP) kvpairs = new HashMap();
kvpairs.put("ExtraInformation",info);
}
public ExtraInformation getExtraInfo() {
return (ExtraInformation)kvpairs.get("ExtraInformation");
}
}
|
132,130 |
Bug 132130 Missing relationship for declare @method when annotating a co-located method
|
For this program (when all entered into *one* file) I don't see a marker from the declare to the annotated method. If the annotated method is in another file, I do... (not sure if fields/ctors/types are also a problem..) public aspect basic { declare @method: * debit(..): @Secured(role="supervisor"); } class BankAccount { public void debit(long accId,long amount) { } } @interface Secured { String role(); }
|
resolved fixed
|
9dca72e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-17T16:47:06Z | 2006-03-16T11:53:20Z |
tests/src/org/aspectj/systemtest/ajc151/Ajc151Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc151;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.systemtest.ajc150.GenericsTests;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc151Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public void testGenericAdviceParameters_pr123553() { runTest("generic advice parameters");}
public void testMemberTypesInGenericTypes_pr122458() { runTest("member types in generic types");}
public void testMemberTypesInGenericTypes_pr122458_2() { runTest("member types in generic types - 2");}
public void testNPEOnDeclareAnnotation_pr123695() { runTest("Internal nullptr exception with complex declare annotation");}
public void testHasMemberPackageProblem_pr124105() { runTest("hasMember problems with packages");}
public void testDifferentNumbersofTVars_pr124803() { runTest("generics and different numbers of type variables");}
public void testDifferentNumbersofTVars_pr124803_2() { runTest("generics and different numbers of type variables - classes");}
public void testParameterizedCollectionFieldMatching_pr124808() { runTest("parameterized collection fields matched via pointcut");}
public void testGenericAspectsAndAnnotations_pr124654() { runTest("generic aspects and annotations");}
public void testCallInheritedGenericMethod_pr124999() { runTest("calling inherited generic method from around advice");}
public void testIncorrectlyReferencingPointcuts_pr122452() { runTest("incorrectly referencing pointcuts");}
public void testIncorrectlyReferencingPointcuts_pr122452_2() { runTest("incorrectly referencing pointcuts - 2");}
public void testInlinevisitorNPE_pr123901() { runTest("inlinevisitor NPE");}
//public void testExposingWithintype_enh123423() { runTest("exposing withintype");}
//public void testMissingImport_pr127299() { runTest("missing import gives funny message");}
public void testUnusedInterfaceMessage_pr120527() { runTest("incorrect unused interface message");}
public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () { runTest("inherit advice with this() and thisJoinPoint"); }
public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699_2 () {runTest("inherit advice with this() and thisJoinPoint - 2"); }
public void testBrokenLTW_pr128744() { runTest("broken ltw"); }
public void testArrayindexoutofbounds_pr129566() {
runTest("arrayindexoutofbounds");
// public class SkipList<T extends Comparable> extends Object implements Set<T>, Iterable<T>
GenericsTests.verifyClassSignature(ajc,"common.SkipList","<T::Ljava/lang/Comparable;>Ljava/lang/Object;Ljava/util/Set<TT;>;Ljava/lang/Iterable<TT;>;");
// protected class SkipListElement<E> extends Object
GenericsTests.verifyClassSignature(ajc,"common.SkipList$SkipListElement","<E:Ljava/lang/Object;>Ljava/lang/Object;");
// protected class SkipListIterator<E> implements Iterator<T>
GenericsTests.verifyClassSignature(ajc,"common.SkipList$SkipListIterator","<E:Ljava/lang/Object;>Ljava/lang/Object;Ljava/util/Iterator<TT;>;");
}
public void testMixingNumbersOfTypeParameters_pr125080() {
runTest("mixing numbers of type parameters");
GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;");
GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;");
GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<Ljava/lang/String;>;");
}
public void testMixingNumbersOfTypeParameters_pr125080_2() {
runTest("mixing numbers of type parameters - 2");
GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Number;>Ljava/lang/Object;");
GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;");
GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<LStudent;>;");
}
public void testIProgramElementMethods_pr125295() {
runTest("new IProgramElement methods");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForType("pkg","foo");
assertNotNull("Couldn't find 'foo' element in the tree",pe);
// check that the defaults return the fully qualified arg
assertEquals("foo(int, java.lang.Object)",pe.toLabelString());
assertEquals("C.foo(int, java.lang.Object)",pe.toLinkLabelString());
assertEquals("foo(int, java.lang.Object)",pe.toSignatureString());
// check that can get hold of the non qualified args
assertEquals("foo(int, Object)",pe.toLabelString(false));
assertEquals("C.foo(int, Object)",pe.toLinkLabelString(false));
assertEquals("foo(int, Object)",pe.toSignatureString(false));
IProgramElement pe2 = top.findElementForType("pkg","printParameters");
assertNotNull("Couldn't find 'printParameters' element in the tree",pe2);
// the argument is org.aspectj.lang.JoinPoint, check that this is added
assertFalse("printParameters method should have arguments",pe2.getParameterTypes().isEmpty());
}
public void testParameterizedEnum_pr126316() {
runTest("E extends Enum(E) again");
}
public void testSwallowedException() {
runTest("swallowed exceptions");
}
public void testAtAspectVerifyErrorWithAfterThrowingAndthisJoinPoint_pr122742() {
runTest("@AJ VerifyError with @AfterThrowing and thisJoinPoint argument");
}
public void testAtAspectVerifyErrorWithAfterReturningAndthisJoinPoint_pr122742() {
runTest("@AJ VerifyError with @AfterReturning and thisJoinPoint argument");
}
public void testSwallowedExceptionIgnored() {
runTest("swallowed exceptions with xlint");
}
public void testGenericAspectWithUnknownType_pr131933() {
runTest("no ClassCastException with generic aspect and unknown type");
}
public void testStructureModelForGenericITD_pr131932() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("structure model for generic itd");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the ITDs and classes
IProgramElement foo = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.CLASS,"Foo");
assertNotNull("Couldn't find Foo element in the tree",foo);
IProgramElement bar = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.CLASS,"Bar");
assertNotNull("Couldn't find Bar element in the tree",bar);
IProgramElement method = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.INTER_TYPE_METHOD,"Bar.getFirst()");
assertNotNull("Couldn't find 'Bar.getFirst()' element in the tree",method);
IProgramElement field = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.INTER_TYPE_FIELD,"Bar.children");
assertNotNull("Couldn't find 'Bar.children' element in the tree",field);
IProgramElement constructor = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR,"Foo.Foo(List<T>)");
assertNotNull("Couldn't find 'Foo.Foo(List<T>)' element in the tree",constructor);
// check that the relationship map has 'itd method declared on bar'
List matches = AsmManager.getDefault().getRelationshipMap().get(method);
assertNotNull("itd Bar.getFirst() should have some relationships but does not",matches);
assertTrue("method itd should have one relationship but has " + matches.size(), matches.size() == 1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("itd Bar.getFirst() should have one target but has " + matchesTargets.size(),matchesTargets.size() == 1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the Bar class but is IPE with label "
+ target.toLabelString(),bar,target);
// check that the relationship map has 'itd field declared on bar'
matches = AsmManager.getDefault().getRelationshipMap().get(field);
assertNotNull("itd Bar.children should have some relationships but does not",matches);
assertTrue("field itd should have one relationship but has " + matches.size(), matches.size() == 1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("itd Bar.children should have one target but has " + matchesTargets.size(),matchesTargets.size() == 1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the Bar class but is IPE with label "
+ target.toLabelString(),bar,target);
// check that the relationship map has 'itd constructor declared on foo'
matches = AsmManager.getDefault().getRelationshipMap().get(constructor);
assertNotNull("itd Foo.Foo(List<T>) should have some relationships but does not",matches);
assertTrue("constructor itd should have one relationship but has " + matches.size(), matches.size() == 1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("itd Foo.Foo(List<T>) should have one target but has " + matchesTargets.size(),matchesTargets.size() == 1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the Foo class but is IPE with label "
+ target.toLabelString(),foo,target);
// check that the relationship map has 'bar aspect declarations method and field itd'
matches = AsmManager.getDefault().getRelationshipMap().get(bar);
assertNotNull("Bar should have some relationships but does not",matches);
assertTrue("Bar should have one relationship but has " + matches.size(), matches.size() == 1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("Bar should have two targets but has " + matchesTargets.size(),matchesTargets.size() == 2);
for (Iterator iter = matchesTargets.iterator(); iter.hasNext();) {
String element = (String) iter.next();
target = AsmManager.getDefault().getHierarchy().findElementForHandle(element);
if (!target.equals(method) && !target.equals(field)) {
fail("Expected rel target to be " + method.toLabelString() + " or " + field.toLabelString()
+ ", found " + target.toLabelString());
}
}
// check that the relationship map has 'foo aspect declarations constructor itd'
matches = AsmManager.getDefault().getRelationshipMap().get(foo);
assertNotNull("Foo should have some relationships but does not",matches);
assertTrue("Foo should have one relationship but has " + matches.size(), matches.size() == 1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("Foo should have one target but has " + matchesTargets.size(),matchesTargets.size() == 1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the Foo.Foo(List<T>) itd but is IPE with label "
+ target.toLabelString(),constructor,target);
}
/*
* @AspectJ bugs and enhancements
*/
// public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () {
// runTest("inherit adivce with this() and thisJoinPoint");
// }
public void testAtAspectInheritsAbstractPointcut_pr125810 () {
runTest("warning when inherited pointcut not made concrete");
}
public void testAtAspectDEOWInStructureModel_pr120356() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("@AJ deow appear correctly when structure model is generated");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the @DeclareWarning statement
// and the method it matches.
IProgramElement warningMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"warningMethod()");
assertNotNull("Couldn't find 'warningMethod()' element in the tree",warningMethodIPE);
IProgramElement atDeclareWarningIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.FIELD,"warning");
assertNotNull("Couldn't find @DeclareWarning element in the tree",atDeclareWarningIPE);
// check that the method has a matches declare relationship with @DeclareWarning
List matches = AsmManager.getDefault().getRelationshipMap().get(warningMethodIPE);
assertNotNull("warningMethod should have some relationships but does not",matches);
assertTrue("warningMethod should have one relationships but has " + matches.size(),matches.size()==1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("warningMethod should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the @DeclareWarning 'warning' but is IPE with label "
+ target.toLabelString(),atDeclareWarningIPE,target);
// check that the @DeclareWarning has a matches relationship with the warningMethod
List matchedBy = AsmManager.getDefault().getRelationshipMap().get(atDeclareWarningIPE);
assertNotNull("@DeclareWarning should have some relationships but does not",matchedBy);
assertTrue("@DeclareWarning should have one relationship but has " + matchedBy.size(), matchedBy.size() == 1);
List matchedByTargets = ((Relationship)matchedBy.get(0)).getTargets();
assertTrue("@DeclareWarning 'matched by' relationship should have one target " +
"but has " + matchedByTargets.size(), matchedByTargets.size() == 1);
IProgramElement matchedByTarget = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargets.get(0));
assertEquals("target of relationship should be the warningMethod but is IPE with label "
+ matchedByTarget.toLabelString(),warningMethodIPE,matchedByTarget);
// get the IProgramElements corresponding to the @DeclareError statement
// and the method it matches.
IProgramElement errorMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"badMethod()");
assertNotNull("Couldn't find 'badMethod()' element in the tree",errorMethodIPE);
IProgramElement atDeclarErrorIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.FIELD,"error");
assertNotNull("Couldn't find @DeclareError element in the tree",atDeclarErrorIPE);
// check that the @DeclareError has a matches relationship with the badMethod
List matchedByE = AsmManager.getDefault().getRelationshipMap().get(atDeclarErrorIPE);
assertNotNull("@DeclareError should have some relationships but does not",matchedByE);
assertTrue("@DeclareError should have one relationship but has " + matchedByE.size(), matchedByE.size() == 1);
List matchedByTargetsE = ((Relationship)matchedByE.get(0)).getTargets();
assertTrue("@DeclareError 'matched by' relationship should have one target " +
"but has " + matchedByTargetsE.size(), matchedByTargetsE.size() == 1);
IProgramElement matchedByTargetE = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargetsE.get(0));
assertEquals("target of relationship should be the badMethod but is IPE with label "
+ matchedByTargetE.toLabelString(),errorMethodIPE,matchedByTargetE);
}
public void testAtAspectNoNPEWithDEOWWithoutStructureModel_pr120356() {
runTest("@AJ no NPE with deow when structure model isn't generated");
}
public void testAtAspectWithoutJoinPointImport_pr121616() {
runTest("@AJ without JoinPoint import");
}
public void testAtAspectDeclareParentsRetainsFieldState_pr122370() {
runTest("@AJ declare parents retains field state");
}
public void testAtAspectNoNPEWithPcdContainingOrThisAndWildcard_pr128237() {
runTest("@AJ no npe with pointcut containing or, this and a wildcard");
}
/*
* Load-time weaving bugs and enhancements
*/
public void testEmptyPointcutInAtAspectJ_pr125475 () {
runTest("define empty pointcut using an annotation");
}
public void testEmptyPointcutInAtAspectJ_pr125475_2() {
runTest("define empty pointcut using an annotation - 2");
}
public void testEmptyPointcutInAtAspectJWithLTW_pr125475 () {
runTest("define empty pointcut using aop.xml");
}
public void testLTWGeneratedAspectWithAbstractMethod_pr125480 () {
runTest("aop.xml aspect inherits abstract method that has concrete implementation in parent");
}
public void testGenericAspectsWithAnnotationTypeParameters() {
runTest("Generic aspects with annotation type parameters");
}
public void testPointcutInterfaces_pr130869() {
runTest("Pointcut interfaces");
}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc151Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc151/ajc151.xml");
}
}
|
132,926 |
Bug 132926 Compiler crashes processing annotations
|
Just upgraded to latest AJDT (Version: 1.3.1, Build id: 20060322082516 AspectJ version: 1.5.1.20060320075953) and the compiler crashed while rebulding the project (which used to work fine using using the March 16th version). Retrying with 'clean' build produced the same crash. java.lang.NullPointerException at org.aspectj.weaver.AnnotationX.ensureAtTargetInitialized(AnnotationX.java:158) at org.aspectj.weaver.AnnotationX.specifiesTarget(AnnotationX.java:98) at org.aspectj.weaver.bcel.BcelWeaver.verifyTargetIsOK(BcelWeaver.java:1450) at org.aspectj.weaver.bcel.BcelWeaver.applyDeclareAtType(BcelWeaver.java:1417) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentTypeMungers(BcelWeaver.java:1366) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentsFor(BcelWeaver.java:1223) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentsFor(BcelWeaver.java:1211) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1058) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:311) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:183) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:845) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:241) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:161) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
|
resolved fixed
|
2fb86fe
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-24T10:10:02Z | 2006-03-23T02:13:20Z |
tests/bugs151/Deca/DecA.java
| |
132,926 |
Bug 132926 Compiler crashes processing annotations
|
Just upgraded to latest AJDT (Version: 1.3.1, Build id: 20060322082516 AspectJ version: 1.5.1.20060320075953) and the compiler crashed while rebulding the project (which used to work fine using using the March 16th version). Retrying with 'clean' build produced the same crash. java.lang.NullPointerException at org.aspectj.weaver.AnnotationX.ensureAtTargetInitialized(AnnotationX.java:158) at org.aspectj.weaver.AnnotationX.specifiesTarget(AnnotationX.java:98) at org.aspectj.weaver.bcel.BcelWeaver.verifyTargetIsOK(BcelWeaver.java:1450) at org.aspectj.weaver.bcel.BcelWeaver.applyDeclareAtType(BcelWeaver.java:1417) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentTypeMungers(BcelWeaver.java:1366) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentsFor(BcelWeaver.java:1223) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentsFor(BcelWeaver.java:1211) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1058) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:311) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:183) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:845) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:241) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:161) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
|
resolved fixed
|
2fb86fe
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-24T10:10:02Z | 2006-03-23T02:13:20Z |
tests/bugs151/pr132926/AffectedType.java
| |
132,926 |
Bug 132926 Compiler crashes processing annotations
|
Just upgraded to latest AJDT (Version: 1.3.1, Build id: 20060322082516 AspectJ version: 1.5.1.20060320075953) and the compiler crashed while rebulding the project (which used to work fine using using the March 16th version). Retrying with 'clean' build produced the same crash. java.lang.NullPointerException at org.aspectj.weaver.AnnotationX.ensureAtTargetInitialized(AnnotationX.java:158) at org.aspectj.weaver.AnnotationX.specifiesTarget(AnnotationX.java:98) at org.aspectj.weaver.bcel.BcelWeaver.verifyTargetIsOK(BcelWeaver.java:1450) at org.aspectj.weaver.bcel.BcelWeaver.applyDeclareAtType(BcelWeaver.java:1417) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentTypeMungers(BcelWeaver.java:1366) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentsFor(BcelWeaver.java:1223) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentsFor(BcelWeaver.java:1211) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1058) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:311) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:183) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:845) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:241) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:161) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
|
resolved fixed
|
2fb86fe
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-24T10:10:02Z | 2006-03-23T02:13:20Z |
tests/bugs151/pr132926/InputAnnotation.java
| |
132,926 |
Bug 132926 Compiler crashes processing annotations
|
Just upgraded to latest AJDT (Version: 1.3.1, Build id: 20060322082516 AspectJ version: 1.5.1.20060320075953) and the compiler crashed while rebulding the project (which used to work fine using using the March 16th version). Retrying with 'clean' build produced the same crash. java.lang.NullPointerException at org.aspectj.weaver.AnnotationX.ensureAtTargetInitialized(AnnotationX.java:158) at org.aspectj.weaver.AnnotationX.specifiesTarget(AnnotationX.java:98) at org.aspectj.weaver.bcel.BcelWeaver.verifyTargetIsOK(BcelWeaver.java:1450) at org.aspectj.weaver.bcel.BcelWeaver.applyDeclareAtType(BcelWeaver.java:1417) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentTypeMungers(BcelWeaver.java:1366) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentsFor(BcelWeaver.java:1223) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentsFor(BcelWeaver.java:1211) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1058) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:311) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:183) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:845) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:241) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:161) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
|
resolved fixed
|
2fb86fe
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-24T10:10:02Z | 2006-03-23T02:13:20Z |
tests/bugs151/pr132926/InputAnnotation2.java
| |
132,926 |
Bug 132926 Compiler crashes processing annotations
|
Just upgraded to latest AJDT (Version: 1.3.1, Build id: 20060322082516 AspectJ version: 1.5.1.20060320075953) and the compiler crashed while rebulding the project (which used to work fine using using the March 16th version). Retrying with 'clean' build produced the same crash. java.lang.NullPointerException at org.aspectj.weaver.AnnotationX.ensureAtTargetInitialized(AnnotationX.java:158) at org.aspectj.weaver.AnnotationX.specifiesTarget(AnnotationX.java:98) at org.aspectj.weaver.bcel.BcelWeaver.verifyTargetIsOK(BcelWeaver.java:1450) at org.aspectj.weaver.bcel.BcelWeaver.applyDeclareAtType(BcelWeaver.java:1417) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentTypeMungers(BcelWeaver.java:1366) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentsFor(BcelWeaver.java:1223) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentsFor(BcelWeaver.java:1211) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1058) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:311) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:183) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:845) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:241) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:161) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
|
resolved fixed
|
2fb86fe
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-24T10:10:02Z | 2006-03-23T02:13:20Z |
tests/src/org/aspectj/systemtest/ajc151/Ajc151Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc151;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.systemtest.ajc150.GenericsTests;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc151Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public void testGenericAdviceParameters_pr123553() { runTest("generic advice parameters");}
public void testMemberTypesInGenericTypes_pr122458() { runTest("member types in generic types");}
public void testMemberTypesInGenericTypes_pr122458_2() { runTest("member types in generic types - 2");}
public void testNPEOnDeclareAnnotation_pr123695() { runTest("Internal nullptr exception with complex declare annotation");}
public void testHasMemberPackageProblem_pr124105() { runTest("hasMember problems with packages");}
public void testDifferentNumbersofTVars_pr124803() { runTest("generics and different numbers of type variables");}
public void testDifferentNumbersofTVars_pr124803_2() { runTest("generics and different numbers of type variables - classes");}
public void testParameterizedCollectionFieldMatching_pr124808() { runTest("parameterized collection fields matched via pointcut");}
public void testGenericAspectsAndAnnotations_pr124654() { runTest("generic aspects and annotations");}
public void testCallInheritedGenericMethod_pr124999() { runTest("calling inherited generic method from around advice");}
public void testIncorrectlyReferencingPointcuts_pr122452() { runTest("incorrectly referencing pointcuts");}
public void testIncorrectlyReferencingPointcuts_pr122452_2() { runTest("incorrectly referencing pointcuts - 2");}
public void testInlinevisitorNPE_pr123901() { runTest("inlinevisitor NPE");}
//public void testExposingWithintype_enh123423() { runTest("exposing withintype");}
//public void testMissingImport_pr127299() { runTest("missing import gives funny message");}
public void testUnusedInterfaceMessage_pr120527() { runTest("incorrect unused interface message");}
public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () { runTest("inherit advice with this() and thisJoinPoint"); }
public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699_2 () {runTest("inherit advice with this() and thisJoinPoint - 2"); }
public void testBrokenLTW_pr128744() { runTest("broken ltw"); }
public void testArrayindexoutofbounds_pr129566() {
runTest("arrayindexoutofbounds");
// public class SkipList<T extends Comparable> extends Object implements Set<T>, Iterable<T>
GenericsTests.verifyClassSignature(ajc,"common.SkipList","<T::Ljava/lang/Comparable;>Ljava/lang/Object;Ljava/util/Set<TT;>;Ljava/lang/Iterable<TT;>;");
// protected class SkipListElement<E> extends Object
GenericsTests.verifyClassSignature(ajc,"common.SkipList$SkipListElement","<E:Ljava/lang/Object;>Ljava/lang/Object;");
// protected class SkipListIterator<E> implements Iterator<T>
GenericsTests.verifyClassSignature(ajc,"common.SkipList$SkipListIterator","<E:Ljava/lang/Object;>Ljava/lang/Object;Ljava/util/Iterator<TT;>;");
}
public void testMixingNumbersOfTypeParameters_pr125080() {
runTest("mixing numbers of type parameters");
GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;");
GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;");
GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<Ljava/lang/String;>;");
}
public void testMixingNumbersOfTypeParameters_pr125080_2() {
runTest("mixing numbers of type parameters - 2");
GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Number;>Ljava/lang/Object;");
GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;");
GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<LStudent;>;");
}
public void testIProgramElementMethods_pr125295() {
runTest("new IProgramElement methods");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForType("pkg","foo");
assertNotNull("Couldn't find 'foo' element in the tree",pe);
// check that the defaults return the fully qualified arg
assertEquals("foo(int,java.lang.Object)",pe.toLabelString());
assertEquals("C.foo(int,java.lang.Object)",pe.toLinkLabelString());
assertEquals("foo(int,java.lang.Object)",pe.toSignatureString());
// check that can get hold of the non qualified args
assertEquals("foo(int,Object)",pe.toLabelString(false));
assertEquals("C.foo(int,Object)",pe.toLinkLabelString(false));
assertEquals("foo(int,Object)",pe.toSignatureString(false));
IProgramElement pe2 = top.findElementForType("pkg","printParameters");
assertNotNull("Couldn't find 'printParameters' element in the tree",pe2);
// the argument is org.aspectj.lang.JoinPoint, check that this is added
assertFalse("printParameters method should have arguments",pe2.getParameterTypes().isEmpty());
}
public void testParameterizedEnum_pr126316() {
runTest("E extends Enum(E) again");
}
public void testSwallowedException() {
runTest("swallowed exceptions");
}
public void testAtAspectVerifyErrorWithAfterThrowingAndthisJoinPoint_pr122742() {
runTest("@AJ VerifyError with @AfterThrowing and thisJoinPoint argument");
}
public void testAtAspectVerifyErrorWithAfterReturningAndthisJoinPoint_pr122742() {
runTest("@AJ VerifyError with @AfterReturning and thisJoinPoint argument");
}
public void testSwallowedExceptionIgnored() {
runTest("swallowed exceptions with xlint");
}
public void testGenericAspectWithUnknownType_pr131933() {
runTest("no ClassCastException with generic aspect and unknown type");
}
public void testStructureModelForGenericITD_pr131932() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("structure model for generic itd");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the ITDs and classes
IProgramElement foo = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.CLASS,"Foo");
assertNotNull("Couldn't find Foo element in the tree",foo);
IProgramElement bar = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.CLASS,"Bar");
assertNotNull("Couldn't find Bar element in the tree",bar);
IProgramElement method = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.INTER_TYPE_METHOD,"Bar.getFirst()");
assertNotNull("Couldn't find 'Bar.getFirst()' element in the tree",method);
IProgramElement field = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.INTER_TYPE_FIELD,"Bar.children");
assertNotNull("Couldn't find 'Bar.children' element in the tree",field);
IProgramElement constructor = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR,"Foo.Foo(List<T>)");
assertNotNull("Couldn't find 'Foo.Foo(List<T>)' element in the tree",constructor);
// check that the relationship map has 'itd method declared on bar'
List matches = AsmManager.getDefault().getRelationshipMap().get(method);
assertNotNull("itd Bar.getFirst() should have some relationships but does not",matches);
assertTrue("method itd should have one relationship but has " + matches.size(), matches.size() == 1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("itd Bar.getFirst() should have one target but has " + matchesTargets.size(),matchesTargets.size() == 1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the Bar class but is IPE with label "
+ target.toLabelString(),bar,target);
// check that the relationship map has 'itd field declared on bar'
matches = AsmManager.getDefault().getRelationshipMap().get(field);
assertNotNull("itd Bar.children should have some relationships but does not",matches);
assertTrue("field itd should have one relationship but has " + matches.size(), matches.size() == 1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("itd Bar.children should have one target but has " + matchesTargets.size(),matchesTargets.size() == 1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the Bar class but is IPE with label "
+ target.toLabelString(),bar,target);
// check that the relationship map has 'itd constructor declared on foo'
matches = AsmManager.getDefault().getRelationshipMap().get(constructor);
assertNotNull("itd Foo.Foo(List<T>) should have some relationships but does not",matches);
assertTrue("constructor itd should have one relationship but has " + matches.size(), matches.size() == 1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("itd Foo.Foo(List<T>) should have one target but has " + matchesTargets.size(),matchesTargets.size() == 1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the Foo class but is IPE with label "
+ target.toLabelString(),foo,target);
// check that the relationship map has 'bar aspect declarations method and field itd'
matches = AsmManager.getDefault().getRelationshipMap().get(bar);
assertNotNull("Bar should have some relationships but does not",matches);
assertTrue("Bar should have one relationship but has " + matches.size(), matches.size() == 1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("Bar should have two targets but has " + matchesTargets.size(),matchesTargets.size() == 2);
for (Iterator iter = matchesTargets.iterator(); iter.hasNext();) {
String element = (String) iter.next();
target = AsmManager.getDefault().getHierarchy().findElementForHandle(element);
if (!target.equals(method) && !target.equals(field)) {
fail("Expected rel target to be " + method.toLabelString() + " or " + field.toLabelString()
+ ", found " + target.toLabelString());
}
}
// check that the relationship map has 'foo aspect declarations constructor itd'
matches = AsmManager.getDefault().getRelationshipMap().get(foo);
assertNotNull("Foo should have some relationships but does not",matches);
assertTrue("Foo should have one relationship but has " + matches.size(), matches.size() == 1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("Foo should have one target but has " + matchesTargets.size(),matchesTargets.size() == 1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the Foo.Foo(List<T>) itd but is IPE with label "
+ target.toLabelString(),constructor,target);
}
public void testDeclareAnnotationAppearsInStructureModel_pr132130() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare annotation appears in structure model when in same file");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the different code entries
IProgramElement decam = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_METHOD,"declare @method: * debit(..) : @Secured(role = \"supervisor\")");
assertNotNull("Couldn't find 'declare @method' element in the tree",decam);
IProgramElement method = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"debit(long,long)");
assertNotNull("Couldn't find the 'debit(long,long)' method element in the tree",method);
IProgramElement decac = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_CONSTRUCTOR,"declare @constructor: BankAccount+.new(..) : @Secured(role = \"supervisor\")");
assertNotNull("Couldn't find 'declare @constructor' element in the tree",decac);
IProgramElement ctr = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.CONSTRUCTOR,"BankAccount(String,int)");
assertNotNull("Couldn't find the 'BankAccount(String,int)' constructor element in the tree",ctr);
// check that decam has a annotates relationship with the debit method
List matches = AsmManager.getDefault().getRelationshipMap().get(decam);
assertNotNull("'declare @method' should have some relationships but does not",matches);
assertTrue("'declare @method' should have one relationships but has " + matches.size(),matches.size()==1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'declare @method' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'debit(long,long)' method but is IPE with label "
+ target.toLabelString(),method,target);
// check that the debit method has an annotated by relationship with the declare @method
matches = AsmManager.getDefault().getRelationshipMap().get(method);
assertNotNull("'debit(long,long)' should have some relationships but does not",matches);
assertTrue("'debit(long,long)' should have one relationships but has " + matches.size(),matches.size()==1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'debit(long,long)' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'declare @method' ipe but is IPE with label "
+ target.toLabelString(),decam,target);
// check that decac has a annotates relationship with the constructor
matches = AsmManager.getDefault().getRelationshipMap().get(decac);
assertNotNull("'declare @method' should have some relationships but does not",matches);
assertTrue("'declare @method' should have one relationships but has " + matches.size(),matches.size()==1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'declare @method' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'debit(long, long)' method but is IPE with label "
+ target.toLabelString(),ctr,target);
// check that the constructor has an annotated by relationship with the declare @constructor
matches = AsmManager.getDefault().getRelationshipMap().get(ctr);
assertNotNull("'debit(long, long)' should have some relationships but does not",matches);
assertTrue("'debit(long, long)' should have one relationships but has " + matches.size(),matches.size()==1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'debit(long, long)' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'declare @method' ipe but is IPE with label "
+ target.toLabelString(),decac,target);
}
/*
* @AspectJ bugs and enhancements
*/
// public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () {
// runTest("inherit adivce with this() and thisJoinPoint");
// }
public void testAtAspectInheritsAbstractPointcut_pr125810 () {
runTest("warning when inherited pointcut not made concrete");
}
public void testAtAspectDEOWInStructureModel_pr120356() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("@AJ deow appear correctly when structure model is generated");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the @DeclareWarning statement
// and the method it matches.
IProgramElement warningMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"warningMethod()");
assertNotNull("Couldn't find 'warningMethod()' element in the tree",warningMethodIPE);
IProgramElement atDeclareWarningIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.FIELD,"warning");
assertNotNull("Couldn't find @DeclareWarning element in the tree",atDeclareWarningIPE);
// check that the method has a matches declare relationship with @DeclareWarning
List matches = AsmManager.getDefault().getRelationshipMap().get(warningMethodIPE);
assertNotNull("warningMethod should have some relationships but does not",matches);
assertTrue("warningMethod should have one relationships but has " + matches.size(),matches.size()==1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("warningMethod should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the @DeclareWarning 'warning' but is IPE with label "
+ target.toLabelString(),atDeclareWarningIPE,target);
// check that the @DeclareWarning has a matches relationship with the warningMethod
List matchedBy = AsmManager.getDefault().getRelationshipMap().get(atDeclareWarningIPE);
assertNotNull("@DeclareWarning should have some relationships but does not",matchedBy);
assertTrue("@DeclareWarning should have one relationship but has " + matchedBy.size(), matchedBy.size() == 1);
List matchedByTargets = ((Relationship)matchedBy.get(0)).getTargets();
assertTrue("@DeclareWarning 'matched by' relationship should have one target " +
"but has " + matchedByTargets.size(), matchedByTargets.size() == 1);
IProgramElement matchedByTarget = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargets.get(0));
assertEquals("target of relationship should be the warningMethod but is IPE with label "
+ matchedByTarget.toLabelString(),warningMethodIPE,matchedByTarget);
// get the IProgramElements corresponding to the @DeclareError statement
// and the method it matches.
IProgramElement errorMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"badMethod()");
assertNotNull("Couldn't find 'badMethod()' element in the tree",errorMethodIPE);
IProgramElement atDeclarErrorIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.FIELD,"error");
assertNotNull("Couldn't find @DeclareError element in the tree",atDeclarErrorIPE);
// check that the @DeclareError has a matches relationship with the badMethod
List matchedByE = AsmManager.getDefault().getRelationshipMap().get(atDeclarErrorIPE);
assertNotNull("@DeclareError should have some relationships but does not",matchedByE);
assertTrue("@DeclareError should have one relationship but has " + matchedByE.size(), matchedByE.size() == 1);
List matchedByTargetsE = ((Relationship)matchedByE.get(0)).getTargets();
assertTrue("@DeclareError 'matched by' relationship should have one target " +
"but has " + matchedByTargetsE.size(), matchedByTargetsE.size() == 1);
IProgramElement matchedByTargetE = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargetsE.get(0));
assertEquals("target of relationship should be the badMethod but is IPE with label "
+ matchedByTargetE.toLabelString(),errorMethodIPE,matchedByTargetE);
}
public void testAtAspectNoNPEWithDEOWWithoutStructureModel_pr120356() {
runTest("@AJ no NPE with deow when structure model isn't generated");
}
public void testAtAspectWithoutJoinPointImport_pr121616() {
runTest("@AJ without JoinPoint import");
}
public void testAtAspectDeclareParentsRetainsFieldState_pr122370() {
runTest("@AJ declare parents retains field state");
}
public void testAtAspectNoNPEWithPcdContainingOrThisAndWildcard_pr128237() {
runTest("@AJ no npe with pointcut containing or, this and a wildcard");
}
/*
* Load-time weaving bugs and enhancements
*/
public void testEmptyPointcutInAtAspectJ_pr125475 () {
runTest("define empty pointcut using an annotation");
}
public void testEmptyPointcutInAtAspectJ_pr125475_2() {
runTest("define empty pointcut using an annotation - 2");
}
public void testEmptyPointcutInAtAspectJWithLTW_pr125475 () {
runTest("define empty pointcut using aop.xml");
}
public void testLTWGeneratedAspectWithAbstractMethod_pr125480 () {
runTest("aop.xml aspect inherits abstract method that has concrete implementation in parent");
}
public void testGenericAspectsWithAnnotationTypeParameters() {
runTest("Generic aspects with annotation type parameters");
}
public void testPointcutInterfaces_pr130869() {
runTest("Pointcut interfaces");
}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc151Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc151/ajc151.xml");
}
}
|
132,926 |
Bug 132926 Compiler crashes processing annotations
|
Just upgraded to latest AJDT (Version: 1.3.1, Build id: 20060322082516 AspectJ version: 1.5.1.20060320075953) and the compiler crashed while rebulding the project (which used to work fine using using the March 16th version). Retrying with 'clean' build produced the same crash. java.lang.NullPointerException at org.aspectj.weaver.AnnotationX.ensureAtTargetInitialized(AnnotationX.java:158) at org.aspectj.weaver.AnnotationX.specifiesTarget(AnnotationX.java:98) at org.aspectj.weaver.bcel.BcelWeaver.verifyTargetIsOK(BcelWeaver.java:1450) at org.aspectj.weaver.bcel.BcelWeaver.applyDeclareAtType(BcelWeaver.java:1417) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentTypeMungers(BcelWeaver.java:1366) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentsFor(BcelWeaver.java:1223) at org.aspectj.weaver.bcel.BcelWeaver.weaveParentsFor(BcelWeaver.java:1211) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1058) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:311) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:183) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:845) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:241) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:161) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
|
resolved fixed
|
2fb86fe
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-24T10:10:02Z | 2006-03-23T02:13:20Z |
weaver/src/org/aspectj/weaver/AnnotationX.java
|
/*******************************************************************************
* Copyright (c) 2005 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement initial API and implementation
*******************************************************************************/
package org.aspectj.weaver;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.aspectj.apache.bcel.classfile.annotation.Annotation;
import org.aspectj.apache.bcel.classfile.annotation.ArrayElementValue;
import org.aspectj.apache.bcel.classfile.annotation.ElementNameValuePair;
import org.aspectj.apache.bcel.classfile.annotation.ElementValue;
import org.aspectj.apache.bcel.classfile.annotation.EnumElementValue;
import org.aspectj.apache.bcel.classfile.Utility;
/**
* AnnotationX instances are holders for an annotation from either Bcel or
* ASM. We have this holder so that types about the bcel weaver package
* can work with something not bytecode toolkit specific.
*/
public class AnnotationX {
public static final AnnotationX[] NONE = new AnnotationX[0];
private Annotation theRealBcelAnnotation;
private AnnotationAJ theRealASMAnnotation;
private int mode = -1;
private final static int MODE_ASM = 1;
private final static int MODE_BCEL = 2;
private ResolvedType signature = null;
// @target meta-annotation related stuff, built lazily
private boolean lookedForAtTargetAnnotation = false;
private AnnotationX atTargetAnnotation = null;
private Set supportedTargets = null;
public AnnotationX(Annotation a,World world) {
theRealBcelAnnotation = a;
signature = UnresolvedType.forSignature(theRealBcelAnnotation.getTypeSignature()).resolve(world);
mode = MODE_BCEL;
}
public AnnotationX(AnnotationAJ a,World world) {
theRealASMAnnotation = a;
signature = UnresolvedType.forSignature(theRealASMAnnotation.getTypeSignature()).resolve(world);
mode= MODE_ASM;
}
public Annotation getBcelAnnotation() {
return theRealBcelAnnotation;
}
public UnresolvedType getSignature() {
return signature;
}
public String toString() {
if (mode==MODE_BCEL) return theRealBcelAnnotation.toString();
else return theRealASMAnnotation.toString();
}
public String getTypeName() {
if (mode==MODE_BCEL) return theRealBcelAnnotation.getTypeName();
else return Utility.signatureToString(theRealASMAnnotation.getTypeSignature());
}
public String getTypeSignature() {
if (mode==MODE_BCEL) return theRealBcelAnnotation.getTypeSignature();
else return theRealASMAnnotation.getTypeSignature();
}
// @target related helpers
/**
* return true if this annotation can target an annotation type
*/
public boolean allowedOnAnnotationType() {
ensureAtTargetInitialized();
if (atTargetAnnotation == null) return true; // if no target specified, then return true
return supportedTargets.contains("ANNOTATION_TYPE");
}
/**
* return true if this annotation is marked with @target()
*/
public boolean specifiesTarget() {
ensureAtTargetInitialized();
return atTargetAnnotation!=null;
}
/**
* return true if this annotation can target a 'regular' type.
* A 'regular' type is enum/class/interface - it is *not* annotation.
*/
public boolean allowedOnRegularType() {
ensureAtTargetInitialized();
if (atTargetAnnotation == null) return true; // if no target specified, then return true
return supportedTargets.contains("TYPE");
}
/**
* Use in messages about this annotation
*/
public String stringify() {
return signature.getName();
}
public String getValidTargets() {
StringBuffer sb = new StringBuffer();
sb.append("{");
for (Iterator iter = supportedTargets.iterator(); iter.hasNext();) {
String evalue = (String) iter.next();
sb.append(evalue);
if (iter.hasNext()) sb.append(",");
}
sb.append("}");
return sb.toString();
}
// privates
/**
* Helper method to retrieve an annotation on an annotation e.g.
* retrieveAnnotationOnAnnotation(UnresolvedType.AT_TARGET)
*/
private AnnotationX retrieveAnnotationOnAnnotation(UnresolvedType requiredAnnotationSignature) {
AnnotationX[] annos = signature.getAnnotations();
for (int i = 0; i < annos.length; i++) {
AnnotationX annotationX = annos[i];
if (annotationX.getSignature().equals(requiredAnnotationSignature)) return annos[i];
}
return null;
}
/**
* Makes sure we have looked for the @target() annotation on this annotation.
* Calling this method initializes (and caches) the information for later use.
*/
private void ensureAtTargetInitialized() {
if (!lookedForAtTargetAnnotation) {
lookedForAtTargetAnnotation = true;
atTargetAnnotation = retrieveAnnotationOnAnnotation(UnresolvedType.AT_TARGET);
if (atTargetAnnotation != null) {
supportedTargets = new HashSet();
List values = atTargetAnnotation.getBcelAnnotation().getValues();
ElementNameValuePair envp = (ElementNameValuePair)values.get(0);
ArrayElementValue aev = (ArrayElementValue)envp.getValue();
ElementValue[] evs = aev.getElementValuesArray();
for (int i = 0; i < evs.length; i++) {
EnumElementValue ev = (EnumElementValue)evs[i];
supportedTargets.add(ev.getEnumValueString());
}
}
}
}
/**
* @return true if this annotation can be put on a field
*/
public boolean allowedOnField() {
ensureAtTargetInitialized();
if (atTargetAnnotation == null) return true; // if no target specified, then return true
return supportedTargets.contains("FIELD");
}
public boolean isRuntimeVisible() {
return theRealBcelAnnotation.isRuntimeVisible();
}
}
|
133,307 |
Bug 133307 declare parents implementing generic interface referencing same type
|
I have the following construct: public interface TestIF<T extends TestIF> {} public class TestClass {} public aspect TestAspect { declare parents: TestClass implements TestIF<TestClass>; } The later aspect does not compile, although public class TestClass implements TestIF<TestClass> { } is a valid class.
|
resolved fixed
|
c9a60e5
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-27T13:42:23Z | 2006-03-27T03:26:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/AjLookupEnvironment.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration;
import org.aspectj.asm.AsmManager;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.WeaveMessage;
import org.aspectj.bridge.context.CompilationAndWeavingContext;
import org.aspectj.bridge.context.ContextToken;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.NormalAnnotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.AccessRestriction;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryType;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ITypeRequestor;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.PackageBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
import org.aspectj.weaver.AnnotationX;
import org.aspectj.weaver.AsmRelationshipProvider;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.FakeAnnotation;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.LazyClassGen;
import org.aspectj.weaver.patterns.DeclareAnnotation;
import org.aspectj.weaver.patterns.DeclareParents;
/**
* Overrides the default eclipse LookupEnvironment for two purposes.
*
* 1. To provide some additional phases to <code>completeTypeBindings</code>
* that weave declare parents and inter-type declarations at the correct time.
*
* 2. To intercept the loading of new binary types to ensure the they will have
* declare parents and inter-type declarations woven when appropriate.
*
* @author Jim Hugunin
*/
public class AjLookupEnvironment extends LookupEnvironment implements AnonymousClassCreationListener {
public EclipseFactory factory = null;
// private boolean builtInterTypesAndPerClauses = false;
private List pendingTypesToWeave = new ArrayList();
// Q: What are dangerousInterfaces?
// A: An interface is considered dangerous if an ITD has been made upon it and that ITD
// requires the top most implementors of the interface to be woven *and yet* the aspect
// responsible for the ITD is not in the 'world'.
// Q: Err, how can that happen?
// A: When a type is on the inpath, it is 'processed' when completing type bindings. At this
// point we look at any type mungers it was affected by previously (stored in the weaver
// state info attribute). Effectively we are working with a type munger and yet may not have its
// originating aspect in the world. This is a problem if, for example, the aspect supplied
// a 'body' for a method targetting an interface - since the top most implementors should
// be woven by the munger from the aspect. When this happens we store the interface name here
// in the map - if we later process a type that is the topMostImplementor of a dangerous
// interface then we put out an error message.
/** interfaces targetted by ITDs that have to be implemented by accessing the topMostImplementor
* of the interface, yet the aspect where the ITD originated is not in the world */
private Map dangerousInterfaces = new HashMap();
public AjLookupEnvironment(
ITypeRequestor typeRequestor,
CompilerOptions options,
ProblemReporter problemReporter,
INameEnvironment nameEnvironment) {
super(typeRequestor, options, problemReporter, nameEnvironment);
}
//??? duplicates some of super's code
public void completeTypeBindings() {
AsmManager.setCompletingTypeBindings(true);
ContextToken completeTypeBindingsToken = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.COMPLETING_TYPE_BINDINGS, "");
// builtInterTypesAndPerClauses = false;
//pendingTypesToWeave = new ArrayList();
stepCompleted = BUILD_TYPE_HIERARCHY;
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.CHECK_AND_SET_IMPORTS, units[i].compilationResult.fileName);
units[i].scope.checkAndSetImports();
CompilationAndWeavingContext.leavingPhase(tok);
}
stepCompleted = CHECK_AND_SET_IMPORTS;
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.CONNECTING_TYPE_HIERARCHY, units[i].compilationResult.fileName);
units[i].scope.connectTypeHierarchy();
CompilationAndWeavingContext.leavingPhase(tok);
}
stepCompleted = CONNECT_TYPE_HIERARCHY;
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.BUILDING_FIELDS_AND_METHODS, units[i].compilationResult.fileName);
units[i].scope.buildFieldsAndMethods();
CompilationAndWeavingContext.leavingPhase(tok);
}
// would like to gather up all TypeDeclarations at this point and put them in the factory
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
SourceTypeBinding[] b = units[i].scope.topLevelTypes;
for (int j = 0; j < b.length; j++) {
factory.addSourceTypeBinding(b[j],units[i]);
}
}
// We won't find out about anonymous types until later though, so register to be
// told about them when they turn up.
AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(this);
// need to build inter-type declarations for all AspectDeclarations at this point
// this MUST be done in order from super-types to subtypes
List typesToProcess = new ArrayList();
for (int i=lastCompletedUnitIndex+1; i<=lastUnitIndex; i++) {
CompilationUnitScope cus = units[i].scope;
SourceTypeBinding[] stbs = cus.topLevelTypes;
for (int j=0; j<stbs.length; j++) {
SourceTypeBinding stb = stbs[j];
typesToProcess.add(stb);
}
}
factory.getWorld().getCrosscuttingMembersSet().reset();
while (typesToProcess.size()>0) {
// removes types from the list as they are processed...
collectAllITDsAndDeclares((SourceTypeBinding)typesToProcess.get(0),typesToProcess);
}
factory.finishTypeMungers();
// now do weaving
Collection typeMungers = factory.getTypeMungers();
Collection declareParents = factory.getDeclareParents();
Collection declareAnnotationOnTypes = factory.getDeclareAnnotationOnTypes();
doPendingWeaves();
// We now have some list of types to process, and we are about to apply the type mungers.
// There can be situations where the order of types passed to the compiler causes the
// output from the compiler to vary - THIS IS BAD. For example, if we have class A
// and class B extends A. Also, an aspect that 'declare parents: A+ implements Serializable'
// then depending on whether we see A first, we may or may not make B serializable.
// The fix is to process them in the right order, ensuring that for a type we process its
// supertypes and superinterfaces first. This algorithm may have problems with:
// - partial hierarchies (e.g. suppose types A,B,C are in a hierarchy and A and C are to be woven but not B)
// - weaving that brings new types in for processing (see pendingTypesToWeave.add() calls) after we thought
// we had the full list.
//
// but these aren't common cases (he bravely said...)
boolean typeProcessingOrderIsImportant = declareParents.size()>0 || declareAnnotationOnTypes.size()>0; //DECAT
if (typeProcessingOrderIsImportant) {
typesToProcess = new ArrayList();
for (int i=lastCompletedUnitIndex+1; i<=lastUnitIndex; i++) {
CompilationUnitScope cus = units[i].scope;
SourceTypeBinding[] stbs = cus.topLevelTypes;
for (int j=0; j<stbs.length; j++) {
SourceTypeBinding stb = stbs[j];
typesToProcess.add(stb);
}
}
while (typesToProcess.size()>0) {
// A side effect of weaveIntertypes() is that the processed type is removed from the collection
weaveIntertypes(typesToProcess,(SourceTypeBinding)typesToProcess.get(0),typeMungers,declareParents,declareAnnotationOnTypes);
}
} else {
// Order isn't important
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
//System.err.println("Working on "+new String(units[i].getFileName()));
weaveInterTypeDeclarations(units[i].scope, typeMungers, declareParents,declareAnnotationOnTypes);
}
}
for (int i = lastCompletedUnitIndex +1; i<=lastUnitIndex; i++) {
SourceTypeBinding[] b = units[i].scope.topLevelTypes;
for (int j = 0; j < b.length; j++) {
verifyAnyTypeParametersMeetBounds(b[j]);
}
}
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
SourceTypeBinding[] b = units[i].scope.topLevelTypes;
for (int j = 0; j < b.length; j++) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.RESOLVING_POINTCUT_DECLARATIONS, b[j].sourceName);
resolvePointcutDeclarations(b[j].scope);
CompilationAndWeavingContext.leavingPhase(tok);
}
}
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
SourceTypeBinding[] b = units[i].scope.topLevelTypes;
for (int j = 0; j < b.length; j++) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.ADDING_DECLARE_WARNINGS_AND_ERRORS, b[j].sourceName);
addAdviceLikeDeclares(b[j].scope);
CompilationAndWeavingContext.leavingPhase(tok);
}
}
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
units[i] = null; // release unnecessary reference to the parsed unit
}
stepCompleted = BUILD_FIELDS_AND_METHODS;
lastCompletedUnitIndex = lastUnitIndex;
AsmManager.setCompletingTypeBindings(false);
CompilationAndWeavingContext.leavingPhase(completeTypeBindingsToken);
}
/**
* For any given sourcetypebinding, this method checks that if it is a parameterized aspect that
* the type parameters specified for any supertypes meet the bounds for the generic type
* variables.
*/
private void verifyAnyTypeParametersMeetBounds(SourceTypeBinding sourceType) {
ResolvedType onType = factory.fromEclipse(sourceType);
if (onType.isAspect()) {
ResolvedType superType = factory.fromEclipse(sourceType.superclass);
// Don't need to check if it was used in its RAW form or isnt generic
if (superType.isGenericType() || superType.isParameterizedType()) {
TypeVariable[] typeVariables = superType.getTypeVariables();
UnresolvedType[] typeParams = superType.getTypeParameters();
if (typeVariables!=null && typeParams!=null) {
for (int i = 0; i < typeVariables.length; i++) {
boolean ok = typeVariables[i].canBeBoundTo(typeParams[i].resolve(factory.getWorld()));
if (!ok) { // the supplied parameter violates the bounds
// Type {0} does not meet the specification for type parameter {1} ({2}) in generic type {3}
String msg =
WeaverMessages.format(
WeaverMessages.VIOLATES_TYPE_VARIABLE_BOUNDS,
typeParams[i],
new Integer(i+1),
typeVariables[i].getDisplayName(),
superType.getGenericType().getName());
factory.getWorld().getMessageHandler().handleMessage(MessageUtil.error(msg,onType.getSourceLocation()));
}
}
}
}
}
}
public void doSupertypesFirst(ReferenceBinding rb,Collection yetToProcess) {
if (rb instanceof SourceTypeBinding) {
if (yetToProcess.contains(rb)) {
collectAllITDsAndDeclares((SourceTypeBinding)rb, yetToProcess);
}
} else if (rb instanceof ParameterizedTypeBinding) {
// If its a PTB we need to pull the SourceTypeBinding out of it.
ParameterizedTypeBinding ptb = (ParameterizedTypeBinding)rb;
if (ptb.type instanceof SourceTypeBinding && yetToProcess.contains(ptb.type)) {
collectAllITDsAndDeclares((SourceTypeBinding)ptb.type, yetToProcess);
}
}
}
/**
* Find all the ITDs and Declares, but it is important we do this from the supertypes
* down to the subtypes.
* @param sourceType
* @param yetToProcess
*/
private void collectAllITDsAndDeclares(SourceTypeBinding sourceType, Collection yetToProcess) {
// Look at the supertype first
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.COLLECTING_ITDS_AND_DECLARES, sourceType.sourceName);
// look out our direct supertype
doSupertypesFirst(sourceType.superclass(),yetToProcess);
// now check our membertypes (pr119570)
ReferenceBinding[] memberTypes = sourceType.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
SourceTypeBinding rb = (SourceTypeBinding)memberTypes[i];
if (!rb.superclass().equals(sourceType))
doSupertypesFirst(rb.superclass(),yetToProcess);
}
buildInterTypeAndPerClause(sourceType.scope);
addCrosscuttingStructures(sourceType.scope);
yetToProcess.remove(sourceType);
CompilationAndWeavingContext.leavingPhase(tok);
}
/**
* Weave the parents and intertype decls into a given type. This method looks at the
* supertype and superinterfaces for the specified type and recurses to weave those first
* if they are in the full list of types we are going to process during this compile... it stops recursing
* the first time it hits a type we aren't going to process during this compile. This could cause problems
* if you supply 'pieces' of a hierarchy, i.e. the bottom and the top, but not the middle - but what the hell
* are you doing if you do that?
*/
private void weaveIntertypes(List typesToProcess,SourceTypeBinding typeToWeave,Collection typeMungers,
Collection declareParents,Collection declareAnnotationOnTypes) {
// Look at the supertype first
ReferenceBinding superType = typeToWeave.superclass();
if (typesToProcess.contains(superType) && superType instanceof SourceTypeBinding) {
//System.err.println("Recursing to supertype "+new String(superType.getFileName()));
weaveIntertypes(typesToProcess,(SourceTypeBinding)superType,typeMungers,declareParents,declareAnnotationOnTypes);
}
// Then look at the superinterface list
ReferenceBinding[] interfaceTypes = typeToWeave.superInterfaces();
for (int i = 0; i < interfaceTypes.length; i++) {
ReferenceBinding binding = interfaceTypes[i];
if (typesToProcess.contains(binding) && binding instanceof SourceTypeBinding) {
//System.err.println("Recursing to superinterface "+new String(binding.getFileName()));
weaveIntertypes(typesToProcess,(SourceTypeBinding)binding,typeMungers,declareParents,declareAnnotationOnTypes);
}
}
weaveInterTypeDeclarations(typeToWeave,typeMungers,declareParents,declareAnnotationOnTypes,false);
typesToProcess.remove(typeToWeave);
}
private void doPendingWeaves() {
for (Iterator i = pendingTypesToWeave.iterator(); i.hasNext(); ) {
SourceTypeBinding t = (SourceTypeBinding)i.next();
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_INTERTYPE_DECLARATIONS, t.sourceName);
weaveInterTypeDeclarations(t);
CompilationAndWeavingContext.leavingPhase(tok);
}
pendingTypesToWeave.clear();
}
private void addAdviceLikeDeclares(ClassScope s) {
TypeDeclaration dec = s.referenceContext;
if (dec instanceof AspectDeclaration) {
ResolvedType typeX = factory.fromEclipse(dec.binding);
factory.getWorld().getCrosscuttingMembersSet().addAdviceLikeDeclares(typeX);
}
SourceTypeBinding sourceType = s.referenceContext.binding;
ReferenceBinding[] memberTypes = sourceType.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
addAdviceLikeDeclares(((SourceTypeBinding) memberTypes[i]).scope);
}
}
private void addCrosscuttingStructures(ClassScope s) {
TypeDeclaration dec = s.referenceContext;
if (dec instanceof AspectDeclaration) {
ResolvedType typeX = factory.fromEclipse(dec.binding);
factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX,false);
if (typeX.getSuperclass().isAspect() && !typeX.getSuperclass().isExposedToWeaver()) {
factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX.getSuperclass(),false);
}
}
SourceTypeBinding sourceType = s.referenceContext.binding;
ReferenceBinding[] memberTypes = sourceType.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
addCrosscuttingStructures(((SourceTypeBinding) memberTypes[i]).scope);
}
}
private void resolvePointcutDeclarations(ClassScope s) {
TypeDeclaration dec = s.referenceContext;
SourceTypeBinding sourceType = s.referenceContext.binding;
boolean hasPointcuts = false;
AbstractMethodDeclaration[] methods = dec.methods;
boolean initializedMethods = false;
if (methods != null) {
for (int i=0; i < methods.length; i++) {
if (methods[i] instanceof PointcutDeclaration) {
hasPointcuts = true;
if (!initializedMethods) {
sourceType.methods(); //force initialization
initializedMethods = true;
}
((PointcutDeclaration)methods[i]).resolvePointcut(s);
}
}
}
if (hasPointcuts || dec instanceof AspectDeclaration || couldBeAnnotationStyleAspectDeclaration(dec)) {
ReferenceType name = (ReferenceType)factory.fromEclipse(sourceType);
EclipseSourceType eclipseSourceType = (EclipseSourceType)name.getDelegate();
eclipseSourceType.checkPointcutDeclarations();
}
ReferenceBinding[] memberTypes = sourceType.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
resolvePointcutDeclarations(((SourceTypeBinding) memberTypes[i]).scope);
}
}
/**
* Return true if the declaration has @Aspect annotation. Called 'couldBe' rather than
* 'is' because someone else may have defined an annotation called Aspect - we can't
* verify the full name (including package name) because it may not have been resolved
* just yet and rather going through expensive resolution when we dont have to, this
* gives us a cheap check that tells us whether to bother.
*/
private boolean couldBeAnnotationStyleAspectDeclaration(TypeDeclaration dec) {
Annotation[] annotations = dec.annotations;
boolean couldBeAtAspect = false;
if (annotations != null) {
for (int i = 0; i < annotations.length && !couldBeAtAspect; i++) {
if (annotations[i].toString().equals("@Aspect")) couldBeAtAspect=true;
}
}
return couldBeAtAspect;
}
private void buildInterTypeAndPerClause(ClassScope s) {
TypeDeclaration dec = s.referenceContext;
if (dec instanceof AspectDeclaration) {
((AspectDeclaration)dec).buildInterTypeAndPerClause(s);
}
SourceTypeBinding sourceType = s.referenceContext.binding;
// test classes don't extend aspects
if (sourceType.superclass != null) {
ResolvedType parent = factory.fromEclipse(sourceType.superclass);
if (parent.isAspect() && !isAspect(dec)) {
factory.showMessage(IMessage.ERROR, "class \'" + new String(sourceType.sourceName) +
"\' can not extend aspect \'" + parent.getName() + "\'",
factory.fromEclipse(sourceType).getSourceLocation(), null);
}
}
ReferenceBinding[] memberTypes = sourceType.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
buildInterTypeAndPerClause(((SourceTypeBinding) memberTypes[i]).scope);
}
}
private boolean isAspect(TypeDeclaration decl) {
if ((decl instanceof AspectDeclaration)) {
return true;
} else if (decl.annotations == null) {
return false;
} else {
for (int i = 0; i < decl.annotations.length; i++) {
Annotation ann = decl.annotations[i];
if (ann.type instanceof SingleTypeReference) {
if (CharOperation.equals("Aspect".toCharArray(),((SingleTypeReference)ann.type).token)) return true;
} else if (ann.type instanceof QualifiedTypeReference) {
QualifiedTypeReference qtr = (QualifiedTypeReference) ann.type;
if (qtr.tokens.length != 5) return false;
if (!CharOperation.equals("org".toCharArray(),qtr.tokens[0])) return false;
if (!CharOperation.equals("aspectj".toCharArray(),qtr.tokens[1])) return false;
if (!CharOperation.equals("lang".toCharArray(),qtr.tokens[2])) return false;
if (!CharOperation.equals("annotation".toCharArray(),qtr.tokens[3])) return false;
if (!CharOperation.equals("Aspect".toCharArray(),qtr.tokens[4])) return false;
return true;
}
}
}
return false;
}
private void weaveInterTypeDeclarations(CompilationUnitScope unit, Collection typeMungers,
Collection declareParents, Collection declareAnnotationOnTypes) {
for (int i = 0, length = unit.topLevelTypes.length; i < length; i++) {
weaveInterTypeDeclarations(unit.topLevelTypes[i], typeMungers, declareParents, declareAnnotationOnTypes,false);
}
}
private void weaveInterTypeDeclarations(SourceTypeBinding sourceType) {
if (!factory.areTypeMungersFinished()) {
if (!pendingTypesToWeave.contains(sourceType)) pendingTypesToWeave.add(sourceType);
} else {
weaveInterTypeDeclarations(sourceType, factory.getTypeMungers(), factory.getDeclareParents(), factory.getDeclareAnnotationOnTypes(),true);
}
}
private void weaveInterTypeDeclarations(SourceTypeBinding sourceType, Collection typeMungers,
Collection declareParents, Collection declareAnnotationOnTypes, boolean skipInners) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_INTERTYPE_DECLARATIONS, sourceType.sourceName);
ResolvedType onType = factory.fromEclipse(sourceType);
// AMC we shouldn't need this when generic sigs are fixed??
if (onType.isRawType()) onType = onType.getGenericType();
WeaverStateInfo info = onType.getWeaverState();
// this test isnt quite right - there will be a case where we fail to flag a problem
// with a 'dangerous interface' because the type is reweavable when we should have
// because the type wasn't going to be rewoven... if that happens, we should perhaps
// move this test and dangerous interface processing to the end of this method and
// make it conditional on whether any of the typeMungers passed into here actually
// matched this type.
if (info != null && !info.isOldStyle() && !info.isReweavable()) {
processTypeMungersFromExistingWeaverState(sourceType,onType);
CompilationAndWeavingContext.leavingPhase(tok);
return;
}
// Check if the type we are looking at is the topMostImplementor of a dangerous interface -
// report a problem if it is.
for (Iterator i = dangerousInterfaces.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
ResolvedType interfaceType = (ResolvedType)entry.getKey();
if (onType.isTopmostImplementor(interfaceType)) {
factory.showMessage(IMessage.ERROR,
onType + ": " + entry.getValue(),
onType.getSourceLocation(), null);
}
}
boolean needOldStyleWarning = (info != null && info.isOldStyle());
onType.clearInterTypeMungers();
// FIXME asc perf Could optimize here, after processing the expected set of types we may bring
// binary types that are not exposed to the weaver, there is no need to attempt declare parents
// or declare annotation really - unless we want to report the not-exposed to weaver
// messages...
List decpToRepeat = new ArrayList();
List decaToRepeat = new ArrayList();
boolean anyNewParents = false;
boolean anyNewAnnotations = false;
// first pass
// try and apply all decps - if they match, then great. If they don't then
// check if they are starred-annotation patterns. If they are not starred
// annotation patterns then they might match later...remember that...
for (Iterator i = declareParents.iterator(); i.hasNext();) {
DeclareParents decp = (DeclareParents)i.next();
boolean didSomething = doDeclareParents(decp, sourceType);
if (didSomething) {
anyNewParents = true;
} else {
if (!decp.getChild().isStarAnnotation()) decpToRepeat.add(decp);
}
}
for (Iterator i = declareAnnotationOnTypes.iterator(); i.hasNext();) {
DeclareAnnotation deca = (DeclareAnnotation)i.next();
boolean didSomething = doDeclareAnnotations(deca, sourceType,true);
if (didSomething) {
anyNewAnnotations = true;
} else {
if (!deca.getTypePattern().isStar()) decaToRepeat.add(deca);
}
}
// now lets loop over and over until we have done all we can
while ((anyNewAnnotations || anyNewParents) &&
(!decpToRepeat.isEmpty() || !decaToRepeat.isEmpty())) {
anyNewParents = anyNewAnnotations = false;
List forRemoval = new ArrayList();
for (Iterator i = decpToRepeat.iterator(); i.hasNext();) {
DeclareParents decp = (DeclareParents)i.next();
boolean didSomething = doDeclareParents(decp, sourceType);
if (didSomething) {
anyNewParents = true;
forRemoval.add(decp);
}
}
decpToRepeat.removeAll(forRemoval);
forRemoval = new ArrayList();
for (Iterator i = declareAnnotationOnTypes.iterator(); i.hasNext();) {
DeclareAnnotation deca = (DeclareAnnotation)i.next();
boolean didSomething = doDeclareAnnotations(deca, sourceType,false);
if (didSomething) {
anyNewAnnotations = true;
forRemoval.add(deca);
}
}
decaToRepeat.removeAll(forRemoval);
}
for (Iterator i = typeMungers.iterator(); i.hasNext();) {
EclipseTypeMunger munger = (EclipseTypeMunger) i.next();
if (munger.matches(onType)) {
if (needOldStyleWarning) {
factory.showMessage(IMessage.WARNING,
"The class for " + onType + " should be recompiled with ajc-1.1.1 for best results",
onType.getSourceLocation(), null);
needOldStyleWarning = false;
}
onType.addInterTypeMunger(munger);
}
}
onType.checkInterTypeMungers();
for (Iterator i = onType.getInterTypeMungers().iterator(); i.hasNext();) {
EclipseTypeMunger munger = (EclipseTypeMunger) i.next();
//System.out.println("applying: " + munger + " to " + new String(sourceType.sourceName));
munger.munge(sourceType,onType);
}
// Call if you would like to do source weaving of declare @method/@constructor
// at source time... no need to do this as it can't impact anything, but left here for
// future generations to enjoy. Method source is commented out at the end of this module
// doDeclareAnnotationOnMethods();
// Call if you would like to do source weaving of declare @field
// at source time... no need to do this as it can't impact anything, but left here for
// future generations to enjoy. Method source is commented out at the end of this module
// doDeclareAnnotationOnFields();
if (skipInners) {
CompilationAndWeavingContext.leavingPhase(tok);
return;
}
ReferenceBinding[] memberTypes = sourceType.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
if (memberTypes[i] instanceof SourceTypeBinding) {
weaveInterTypeDeclarations((SourceTypeBinding) memberTypes[i], typeMungers, declareParents,declareAnnotationOnTypes, false);
}
}
CompilationAndWeavingContext.leavingPhase(tok);
}
/**
* Called when we discover we are weaving intertype declarations on some type that has
* an existing 'WeaverStateInfo' object - this is typically some previously woven type
* that has been passed on the inpath.
*
* sourceType and onType are the 'same type' - the former is the 'Eclipse' version and
* the latter is the 'Weaver' version.
*/
private void processTypeMungersFromExistingWeaverState(SourceTypeBinding sourceType,ResolvedType onType) {
Collection previouslyAppliedMungers = onType.getWeaverState().getTypeMungers(onType);
for (Iterator i = previouslyAppliedMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger m = (ConcreteTypeMunger)i.next();
EclipseTypeMunger munger = factory.makeEclipseTypeMunger(m);
if (munger.munge(sourceType,onType)) {
if (onType.isInterface() && munger.getMunger().needsAccessToTopmostImplementor()) {
if (!onType.getWorld().getCrosscuttingMembersSet().containsAspect(munger.getAspectType())) {
dangerousInterfaces.put(onType, "implementors of "+onType+" must be woven by "+munger.getAspectType());
}
}
}
}
}
private boolean doDeclareParents(DeclareParents declareParents, SourceTypeBinding sourceType) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS, sourceType.sourceName);
List newParents = declareParents.findMatchingNewParents(factory.fromEclipse(sourceType),false);
if (!newParents.isEmpty()) {
for (Iterator i = newParents.iterator(); i.hasNext(); ) {
ResolvedType parent = (ResolvedType)i.next();
if (dangerousInterfaces.containsKey(parent)) {
ResolvedType onType = factory.fromEclipse(sourceType);
factory.showMessage(IMessage.ERROR,
onType + ": " + dangerousInterfaces.get(parent),
onType.getSourceLocation(), null);
}
if (Modifier.isFinal(parent.getModifiers())) {
factory.showMessage(IMessage.ERROR,"cannot extend final class " + parent.getClassName(),declareParents.getSourceLocation(),null);
} else {
AsmRelationshipProvider.getDefault().addDeclareParentsRelationship(declareParents.getSourceLocation(),factory.fromEclipse(sourceType), newParents);
addParent(sourceType, parent);
}
}
CompilationAndWeavingContext.leavingPhase(tok);
return true;
}
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
private String stringifyTargets(long bits) {
if ((bits & TagBits.AnnotationTargetMASK)==0) return "";
Set s = new HashSet();
if ((bits&TagBits.AnnotationForAnnotationType)!=0) s.add("ANNOTATION_TYPE");
if ((bits&TagBits.AnnotationForConstructor)!=0) s.add("CONSTRUCTOR");
if ((bits&TagBits.AnnotationForField)!=0) s.add("FIELD");
if ((bits&TagBits.AnnotationForLocalVariable)!=0) s.add("LOCAL_VARIABLE");
if ((bits&TagBits.AnnotationForMethod)!=0) s.add("METHOD");
if ((bits&TagBits.AnnotationForPackage)!=0) s.add("PACKAGE");
if ((bits&TagBits.AnnotationForParameter)!=0) s.add("PARAMETER");
if ((bits&TagBits.AnnotationForType)!=0) s.add("TYPE");
StringBuffer sb = new StringBuffer();
sb.append("{");
for (Iterator iter = s.iterator(); iter.hasNext();) {
String element = (String) iter.next();
sb.append(element);
if (iter.hasNext()) sb.append(",");
}
sb.append("}");
return sb.toString();
}
private boolean doDeclareAnnotations(DeclareAnnotation decA, SourceTypeBinding sourceType,boolean reportProblems) {
ResolvedType rtx = factory.fromEclipse(sourceType);
if (!decA.matches(rtx)) return false;
if (!rtx.isExposedToWeaver()) return false;
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_ANNOTATIONS, sourceType.sourceName);
// Get the annotation specified in the declare
UnresolvedType aspectType = decA.getAspect();
if (aspectType instanceof ReferenceType) {
ReferenceType rt = (ReferenceType) aspectType;
if (rt.isParameterizedType() || rt.isRawType()) {
aspectType = rt.getGenericType();
}
}
TypeBinding tb = factory.makeTypeBinding(aspectType);
// Hideousness follows:
// There are multiple situations to consider here and they relate to the combinations of
// where the annotation is coming from and where the annotation is going to be put:
//
// 1. Straight full build, all from source - the annotation is from a dec@type and
// is being put on some type. Both types are real SourceTypeBindings. WORKS
// 2. Incremental build, changing the affected type - the annotation is from a
// dec@type in a BinaryTypeBinding (so has to be accessed via bcel) and the
// affected type is a real SourceTypeBinding. Mostly works (pr128665)
// 3. ?
SourceTypeBinding stb = (SourceTypeBinding)tb;
Annotation[] toAdd = null;
long abits = 0;
// Might have to retrieve the annotation through BCEL and construct an eclipse one for it.
if (stb instanceof BinaryTypeBinding) {
ReferenceType rt = (ReferenceType)factory.fromEclipse(stb);
ResolvedMember[] methods = rt.getDeclaredMethods();
ResolvedMember decaMethod = null;
String nameToLookFor = decA.getAnnotationMethod();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals(nameToLookFor)) {decaMethod = methods[i];break;}
}
if (decaMethod!=null) { // could assert this ...
AnnotationX[] axs = decaMethod.getAnnotations();
toAdd = new Annotation[1];
toAdd[0] = createAnnotationFromBcelAnnotation(axs[0],decaMethod.getSourceLocation().getOffset(),factory);
// BUG BUG BUG - We dont test these abits are correct, in fact we'll be very lucky if they are.
// What does that mean? It means on an incremental compile you might get away with an
// annotation that isn't allowed on a type being put on a type.
abits = toAdd[0].resolvedType.getAnnotationTagBits();
}
} else {
// much nicer, its a real SourceTypeBinding so we can stay in eclipse land
MethodBinding[] mbs = stb.getMethods(decA.getAnnotationMethod().toCharArray());
abits = mbs[0].getAnnotationTagBits(); // ensure resolved
TypeDeclaration typeDecl = ((SourceTypeBinding)mbs[0].declaringClass).scope.referenceContext;
AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(mbs[0]);
toAdd = methodDecl.annotations; // this is what to add
abits = toAdd[0].resolvedType.getAnnotationTagBits();
}
if (sourceType instanceof BinaryTypeBinding) {
// In this case we can't access the source type binding to add a new annotation, so let's put something
// on the weaver type temporarily
ResolvedType theTargetType = factory.fromEclipse(sourceType);
TypeBinding theAnnotationType = toAdd[0].resolvedType;
String name = new String(theAnnotationType.qualifiedPackageName())+"."+new String(theAnnotationType.sourceName());
String sig = new String(theAnnotationType.signature());
if (theTargetType.hasAnnotation(UnresolvedType.forSignature(sig))) {
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
// FIXME asc tidy up this code that duplicates whats below!
// Simple checks on the bits
boolean giveupnow = false;
if (((abits & TagBits.AnnotationTargetMASK)!=0)) {
if ( isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(abits)) {
// error will have been already reported
giveupnow = true;
} else if ( (sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType)==0) ||
(!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType)==0) ) {
if (reportProblems) {
if (decA.isExactPattern()) {
factory.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION,rtx.getName(),toAdd[0].type,stringifyTargets(abits)),
decA.getSourceLocation(), null);
}
// dont put out the lint - the weaving process will do that
// else {
// if (factory.getWorld().getLint().invalidTargetForAnnotation.isEnabled()) {
// factory.getWorld().getLint().invalidTargetForAnnotation.signal(new String[]{rtx.getName(),toAdd[0].type.toString(),stringifyTargets(abits)},decA.getSourceLocation(),null);
// }
// }
}
giveupnow=true;
}
}
if (giveupnow) {
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
theTargetType.addAnnotation(new AnnotationX(new FakeAnnotation(name,sig,(abits & TagBits.AnnotationRuntimeRetention)!=0),factory.getWorld()));
CompilationAndWeavingContext.leavingPhase(tok);
return true;
}
Annotation currentAnnotations[] = sourceType.scope.referenceContext.annotations;
if (currentAnnotations!=null)
for (int i = 0; i < currentAnnotations.length; i++) {
Annotation annotation = currentAnnotations[i];
String a = CharOperation.toString(annotation.type.getTypeName());
String b = CharOperation.toString(toAdd[0].type.getTypeName());
// FIXME asc we have a lint for attempting to add an annotation twice to a method,
// we could put it out here *if* we can resolve the problem of errors coming out
// multiple times if we have cause to loop through here
if (a.equals(b)) {
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
}
if (((abits & TagBits.AnnotationTargetMASK)!=0)) {
if ( (abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType))==0) {
// this means it specifies something other than annotation or normal type - error will have been already reported, just resolution process above
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
if ( (sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType)==0) ||
(!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType)==0) ) {
if (reportProblems) {
if (decA.isExactPattern()) {
factory.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION,rtx.getName(),toAdd[0].type,stringifyTargets(abits)),
decA.getSourceLocation(), null);
}
// dont put out the lint - the weaving process will do that
// else {
// if (factory.getWorld().getLint().invalidTargetForAnnotation.isEnabled()) {
// factory.getWorld().getLint().invalidTargetForAnnotation.signal(new String[]{rtx.getName(),toAdd[0].type.toString(),stringifyTargets(abits)},decA.getSourceLocation(),null);
// }
// }
}
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
}
// Build a new array of annotations
// remember the current set (rememberAnnotations only does something the first time it is called for a type)
sourceType.scope.referenceContext.rememberAnnotations();
AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(decA.getSourceLocation(),rtx.getSourceLocation());
Annotation abefore[] = sourceType.scope.referenceContext.annotations;
Annotation[] newset = new Annotation[toAdd.length+(abefore==null?0:abefore.length)];
System.arraycopy(toAdd,0,newset,0,toAdd.length);
if (abefore!=null) {
System.arraycopy(abefore,0,newset,toAdd.length,abefore.length);
}
sourceType.scope.referenceContext.annotations = newset;
CompilationAndWeavingContext.leavingPhase(tok);
return true;
}
/**
* Transform an annotation from its AJ form to an eclipse form. We *DONT* care about the
* values of the annotation. that is because it is only being stuck on a type during
* type completion to allow for other constructs (decps, decas) that might be looking for it -
* when the class actually gets to disk it wont have this new annotation on it and during
* weave time we will do the right thing copying across values too.
*/
private static Annotation createAnnotationFromBcelAnnotation(AnnotationX annX,int pos, EclipseFactory factory) {
String name = annX.getTypeName();
TypeBinding tb = factory.makeTypeBinding(annX.getSignature());
char[][] typeName = CharOperation.splitOn('.',name.toCharArray());
long[] positions = new long[] {pos};
TypeReference annType = new QualifiedTypeReference(typeName,positions);
NormalAnnotation ann = new NormalAnnotation(annType,pos);
ann.resolvedType=tb; // yuck - is this OK in all cases?
// We don't need membervalues...
// Expression pcExpr = new StringLiteral(pointcutExpression.toCharArray(),pos,pos);
// MemberValuePair[] mvps = new MemberValuePair[2];
// mvps[0] = new MemberValuePair("value".toCharArray(),pos,pos,pcExpr);
// Expression argNamesExpr = new StringLiteral(argNames.toCharArray(),pos,pos);
// mvps[1] = new MemberValuePair("argNames".toCharArray(),pos,pos,argNamesExpr);
// ann.memberValuePairs = mvps;
return ann;
}
private boolean isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(long abits) {
return (abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType))==0;
}
private void reportDeclareParentsMessage(WeaveMessage.WeaveMessageKind wmk,SourceTypeBinding sourceType,ResolvedType parent) {
if (!factory.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
String filename = new String(sourceType.getFileName());
int takefrom = filename.lastIndexOf('/');
if (takefrom == -1 ) takefrom = filename.lastIndexOf('\\');
filename = filename.substring(takefrom+1);
factory.getWorld().getMessageHandler().handleMessage(
WeaveMessage.constructWeavingMessage(wmk,
new String[]{CharOperation.toString(sourceType.compoundName),
filename,
parent.getClassName(),
getShortname(parent.getSourceLocation().getSourceFile().getPath())}));
}
}
private String getShortname(String path) {
int takefrom = path.lastIndexOf('/');
if (takefrom == -1) {
takefrom = path.lastIndexOf('\\');
}
return path.substring(takefrom+1);
}
private void addParent(SourceTypeBinding sourceType, ResolvedType parent) {
ReferenceBinding parentBinding = (ReferenceBinding)factory.makeTypeBinding(parent);
if (parentBinding == null) return; // The parent is missing, it will be reported elsewhere.
sourceType.rememberTypeHierarchy();
if (parentBinding.isClass()) {
sourceType.superclass = parentBinding;
// this used to be true, but I think I've fixed it now, decp is done at weave time!
// TAG: WeavingMessage DECLARE PARENTS: EXTENDS
// Compiler restriction: Can't do EXTENDS at weave time
// So, only see this message if doing a source compilation
// reportDeclareParentsMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent);
} else {
ReferenceBinding[] oldI = sourceType.superInterfaces;
ReferenceBinding[] newI;
if (oldI == null) {
newI = new ReferenceBinding[1];
newI[0] = parentBinding;
} else {
int n = oldI.length;
newI = new ReferenceBinding[n+1];
System.arraycopy(oldI, 0, newI, 0, n);
newI[n] = parentBinding;
}
sourceType.superInterfaces = newI;
// warnOnAddedInterface(factory.fromEclipse(sourceType),parent); // now reported at weave time...
// this used to be true, but I think I've fixed it now, decp is done at weave time!
// TAG: WeavingMessage DECLARE PARENTS: IMPLEMENTS
// This message will come out of BcelTypeMunger.munge if doing a binary weave
// reportDeclareParentsMessage(WeaveMessage.WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS,sourceType,parent);
}
}
public void warnOnAddedInterface (ResolvedType type, ResolvedType parent) {
World world = factory.getWorld();
ResolvedType serializable = world.getCoreType(UnresolvedType.SERIALIZABLE);
if (serializable.isAssignableFrom(type)
&& !serializable.isAssignableFrom(parent)
&& !LazyClassGen.hasSerialVersionUIDField(type)) {
world.getLint().needsSerialVersionUIDField.signal(
new String[] {
type.getName().toString(),
"added interface " + parent.getName().toString()
},
null,
null);
}
}
private List pendingTypesToFinish = new ArrayList();
boolean inBinaryTypeCreationAndWeaving = false;
boolean processingTheQueue = false;
public BinaryTypeBinding createBinaryTypeFrom(
IBinaryType binaryType,
PackageBinding packageBinding,
boolean needFieldsAndMethods,
AccessRestriction accessRestriction)
{
if (inBinaryTypeCreationAndWeaving) {
BinaryTypeBinding ret = super.createBinaryTypeFrom(
binaryType,
packageBinding,
needFieldsAndMethods,
accessRestriction);
pendingTypesToFinish.add(ret);
return ret;
}
inBinaryTypeCreationAndWeaving = true;
try {
BinaryTypeBinding ret = super.createBinaryTypeFrom(
binaryType,
packageBinding,
needFieldsAndMethods,
accessRestriction);
factory.getWorld().validateType(factory.fromBinding(ret));
// if you need the bytes to pass to validate, here they are:((ClassFileReader)binaryType).getReferenceBytes()
weaveInterTypeDeclarations(ret);
return ret;
} finally {
inBinaryTypeCreationAndWeaving = false;
// Start processing the list...
if (pendingTypesToFinish.size()>0) {
processingTheQueue = true;
while (!pendingTypesToFinish.isEmpty()) {
BinaryTypeBinding nextVictim = (BinaryTypeBinding)pendingTypesToFinish.remove(0);
// During this call we may recurse into this method and add
// more entries to the pendingTypesToFinish list.
weaveInterTypeDeclarations(nextVictim);
}
processingTheQueue = false;
}
}
}
/**
* Callback driven when the compiler detects an anonymous type during block resolution.
* We need to add it to the weaver so that we don't trip up later.
* @param aBinding
*/
public void anonymousTypeBindingCreated(LocalTypeBinding aBinding) {
factory.addSourceTypeBinding(aBinding,null);
}
}
// commented out, supplied as info on how to manipulate annotations in an eclipse world
//
// public void doDeclareAnnotationOnMethods() {
// Do the declare annotation on fields/methods/ctors
//Collection daoms = factory.getDeclareAnnotationOnMethods();
//if (daoms!=null && daoms.size()>0 && !(sourceType instanceof BinaryTypeBinding)) {
// System.err.println("Going through the methods on "+sourceType.debugName()+" looking for DECA matches");
// // We better take a look through them...
// for (Iterator iter = daoms.iterator(); iter.hasNext();) {
// DeclareAnnotation element = (DeclareAnnotation) iter.next();
// System.err.println("Looking for anything that might match "+element+" on "+sourceType.debugName()+" "+getType(sourceType.compoundName).debugName()+" "+(sourceType instanceof BinaryTypeBinding));
//
// ReferenceBinding rbb = getType(sourceType.compoundName);
// // fix me if we ever uncomment this code... should iterate the other way round, over the methods then over the decas
// sourceType.methods();
// MethodBinding sourceMbs[] = sourceType.methods;
// for (int i = 0; i < sourceMbs.length; i++) {
// MethodBinding sourceMb = sourceMbs[i];
// MethodBinding mbbbb = ((SourceTypeBinding)rbb).getExactMethod(sourceMb.selector,sourceMb.parameters);
// boolean isCtor = sourceMb.selector[0]=='<';
//
// if ((element.isDeclareAtConstuctor() ^ !isCtor)) {
// System.err.println("Checking "+sourceMb+" ... declaringclass="+sourceMb.declaringClass.debugName()+" rbb="+rbb.debugName()+" "+sourceMb.declaringClass.equals(rbb));
//
// ResolvedMember rm = null;
// rm = EclipseFactory.makeResolvedMember(mbbbb);
// if (element.matches(rm,factory.getWorld())) {
// System.err.println("MATCH");
//
// // Determine the set of annotations that are currently on the method
// ReferenceBinding rb = getType(sourceType.compoundName);
//// TypeBinding tb = factory.makeTypeBinding(decA.getAspect());
// MethodBinding mb = ((SourceTypeBinding)rb).getExactMethod(sourceMb.selector,sourceMb.parameters);
// //long abits = mbs[0].getAnnotationTagBits(); // ensure resolved
// TypeDeclaration typeDecl = ((SourceTypeBinding)sourceMb.declaringClass).scope.referenceContext;
// AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(sourceMb);
// Annotation[] currentlyHas = methodDecl.annotations; // this is what to add
// //abits = toAdd[0].resolvedType.getAnnotationTagBits();
//
// // Determine the annotations to add to that method
// TypeBinding tb = factory.makeTypeBinding(element.getAspect());
// MethodBinding[] aspectMbs = ((SourceTypeBinding)tb).getMethods(element.getAnnotationMethod().toCharArray());
// long abits = aspectMbs[0].getAnnotationTagBits(); // ensure resolved
// TypeDeclaration typeDecl2 = ((SourceTypeBinding)aspectMbs[0].declaringClass).scope.referenceContext;
// AbstractMethodDeclaration methodDecl2 = typeDecl2.declarationOf(aspectMbs[0]);
// Annotation[] toAdd = methodDecl2.annotations; // this is what to add
// // abits = toAdd[0].resolvedType.getAnnotationTagBits();
//System.err.println("Has: "+currentlyHas+" toAdd: "+toAdd);
//
// // fix me? should check if it already has the annotation
// //Annotation abefore[] = sourceType.scope.referenceContext.annotations;
// Annotation[] newset = new Annotation[(currentlyHas==null?0:currentlyHas.length)+1];
// System.arraycopy(toAdd,0,newset,0,toAdd.length);
// if (currentlyHas!=null) {
// System.arraycopy(currentlyHas,0,newset,1,currentlyHas.length);
// }
// methodDecl.annotations = newset;
// System.err.println("New set on "+CharOperation.charToString(sourceMb.selector)+" is "+newset);
// } else
// System.err.println("NO MATCH");
// }
// }
// }
//}
//}
// commented out, supplied as info on how to manipulate annotations in an eclipse world
//
// public void doDeclareAnnotationOnFields() {
// Collection daofs = factory.getDeclareAnnotationOnFields();
// if (daofs!=null && daofs.size()>0 && !(sourceType instanceof BinaryTypeBinding)) {
// System.err.println("Going through the fields on "+sourceType.debugName()+" looking for DECA matches");
// // We better take a look through them...
// for (Iterator iter = daofs.iterator(); iter.hasNext();) {
// DeclareAnnotation element = (DeclareAnnotation) iter.next();
// System.err.println("Processing deca "+element+" on "+sourceType.debugName()+" "+getType(sourceType.compoundName).debugName()+" "+(sourceType instanceof BinaryTypeBinding));
//
// ReferenceBinding rbb = getType(sourceType.compoundName);
// // fix me? should iterate the other way round, over the methods then over the decas
// sourceType.fields(); // resolve the bloody things
// FieldBinding sourceFbs[] = sourceType.fields;
// for (int i = 0; i < sourceFbs.length; i++) {
// FieldBinding sourceFb = sourceFbs[i];
// //FieldBinding fbbbb = ((SourceTypeBinding)rbb).getgetExactMethod(sourceMb.selector,sourceMb.parameters);
//
// System.err.println("Checking "+sourceFb+" ... declaringclass="+sourceFb.declaringClass.debugName()+" rbb="+rbb.debugName());
//
// ResolvedMember rm = null;
// rm = EclipseFactory.makeResolvedMember(sourceFb);
// if (element.matches(rm,factory.getWorld())) {
// System.err.println("MATCH");
//
// // Determine the set of annotations that are currently on the field
// ReferenceBinding rb = getType(sourceType.compoundName);
//// TypeBinding tb = factory.makeTypeBinding(decA.getAspect());
// FieldBinding fb = ((SourceTypeBinding)rb).getField(sourceFb.name,true);
// //long abits = mbs[0].getAnnotationTagBits(); // ensure resolved
// TypeDeclaration typeDecl = ((SourceTypeBinding)sourceFb.declaringClass).scope.referenceContext;
// FieldDeclaration fd = typeDecl.declarationOf(sourceFb);
// //AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(sourceMb);
// Annotation[] currentlyHas = fd.annotations; // this is what to add
// //abits = toAdd[0].resolvedType.getAnnotationTagBits();
//
// // Determine the annotations to add to that method
// TypeBinding tb = factory.makeTypeBinding(element.getAspect());
// MethodBinding[] aspectMbs = ((SourceTypeBinding)tb).getMethods(element.getAnnotationMethod().toCharArray());
// long abits = aspectMbs[0].getAnnotationTagBits(); // ensure resolved
// TypeDeclaration typeDecl2 = ((SourceTypeBinding)aspectMbs[0].declaringClass).scope.referenceContext;
// AbstractMethodDeclaration methodDecl2 = typeDecl2.declarationOf(aspectMbs[0]);
// Annotation[] toAdd = methodDecl2.annotations; // this is what to add
// // abits = toAdd[0].resolvedType.getAnnotationTagBits();
//System.err.println("Has: "+currentlyHas+" toAdd: "+toAdd);
//
// // fix me? check if it already has the annotation
//
//
// //Annotation abefore[] = sourceType.scope.referenceContext.annotations;
// Annotation[] newset = new Annotation[(currentlyHas==null?0:currentlyHas.length)+1];
// System.arraycopy(toAdd,0,newset,0,toAdd.length);
// if (currentlyHas!=null) {
// System.arraycopy(currentlyHas,0,newset,1,currentlyHas.length);
// }
// fd.annotations = newset;
// System.err.println("New set on "+CharOperation.charToString(sourceFb.name)+" is "+newset);
// } else
// System.err.println("NO MATCH");
// }
//
// }
// }
|
133,307 |
Bug 133307 declare parents implementing generic interface referencing same type
|
I have the following construct: public interface TestIF<T extends TestIF> {} public class TestClass {} public aspect TestAspect { declare parents: TestClass implements TestIF<TestClass>; } The later aspect does not compile, although public class TestClass implements TestIF<TestClass> { } is a valid class.
|
resolved fixed
|
c9a60e5
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-27T13:42:23Z | 2006-03-27T03:26:40Z |
tests/src/org/aspectj/systemtest/ajc151/Ajc151Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc151;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.systemtest.ajc150.GenericsTests;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc151Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
// public void testDeca() { runTest("doubly annotating a method with declare");}
// public void testDeca2() { runTest("doubly annotating a method with declare - 2");}
public void testCrashingWithASM_pr132926_1() { runTest("crashing on annotation type resolving with asm - 1");}
public void testCrashingWithASM_pr132926_2() { runTest("crashing on annotation type resolving with asm - 2");}
public void testCrashingWithASM_pr132926_3() { runTest("crashing on annotation type resolving with asm - 3");}
public void testGenericAdviceParameters_pr123553() { runTest("generic advice parameters");}
public void testMemberTypesInGenericTypes_pr122458() { runTest("member types in generic types");}
public void testMemberTypesInGenericTypes_pr122458_2() { runTest("member types in generic types - 2");}
public void testNPEOnDeclareAnnotation_pr123695() { runTest("Internal nullptr exception with complex declare annotation");}
public void testHasMemberPackageProblem_pr124105() { runTest("hasMember problems with packages");}
public void testDifferentNumbersofTVars_pr124803() { runTest("generics and different numbers of type variables");}
public void testDifferentNumbersofTVars_pr124803_2() { runTest("generics and different numbers of type variables - classes");}
public void testParameterizedCollectionFieldMatching_pr124808() { runTest("parameterized collection fields matched via pointcut");}
public void testGenericAspectsAndAnnotations_pr124654() { runTest("generic aspects and annotations");}
public void testCallInheritedGenericMethod_pr124999() { runTest("calling inherited generic method from around advice");}
public void testIncorrectlyReferencingPointcuts_pr122452() { runTest("incorrectly referencing pointcuts");}
public void testIncorrectlyReferencingPointcuts_pr122452_2() { runTest("incorrectly referencing pointcuts - 2");}
public void testInlinevisitorNPE_pr123901() { runTest("inlinevisitor NPE");}
//public void testExposingWithintype_enh123423() { runTest("exposing withintype");}
//public void testMissingImport_pr127299() { runTest("missing import gives funny message");}
public void testUnusedInterfaceMessage_pr120527() { runTest("incorrect unused interface message");}
public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () { runTest("inherit advice with this() and thisJoinPoint"); }
public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699_2 () {runTest("inherit advice with this() and thisJoinPoint - 2"); }
public void testBrokenLTW_pr128744() { runTest("broken ltw"); }
public void testArrayindexoutofbounds_pr129566() {
runTest("arrayindexoutofbounds");
// public class SkipList<T extends Comparable> extends Object implements Set<T>, Iterable<T>
GenericsTests.verifyClassSignature(ajc,"common.SkipList","<T::Ljava/lang/Comparable;>Ljava/lang/Object;Ljava/util/Set<TT;>;Ljava/lang/Iterable<TT;>;");
// protected class SkipListElement<E> extends Object
GenericsTests.verifyClassSignature(ajc,"common.SkipList$SkipListElement","<E:Ljava/lang/Object;>Ljava/lang/Object;");
// protected class SkipListIterator<E> implements Iterator<T>
GenericsTests.verifyClassSignature(ajc,"common.SkipList$SkipListIterator","<E:Ljava/lang/Object;>Ljava/lang/Object;Ljava/util/Iterator<TT;>;");
}
public void testMixingNumbersOfTypeParameters_pr125080() {
runTest("mixing numbers of type parameters");
GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Object;>Ljava/lang/Object;");
GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;");
GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<Ljava/lang/String;>;");
}
public void testMixingNumbersOfTypeParameters_pr125080_2() {
runTest("mixing numbers of type parameters - 2");
GenericsTests.verifyClassSignature(ajc,"AspectInterface","<T:Ljava/lang/Object;S:Ljava/lang/Number;>Ljava/lang/Object;");
GenericsTests.verifyClassSignature(ajc,"AbstractAspect","<T:Ljava/lang/Object;>Ljava/lang/Object;LAspectInterface<TT;Ljava/lang/Integer;>;");
GenericsTests.verifyClassSignature(ajc,"ConcreteAspect","LAbstractAspect<LStudent;>;");
}
public void testIProgramElementMethods_pr125295() {
runTest("new IProgramElement methods");
IHierarchy top = AsmManager.getDefault().getHierarchy();
IProgramElement pe = top.findElementForType("pkg","foo");
assertNotNull("Couldn't find 'foo' element in the tree",pe);
// check that the defaults return the fully qualified arg
assertEquals("foo(int,java.lang.Object)",pe.toLabelString());
assertEquals("C.foo(int,java.lang.Object)",pe.toLinkLabelString());
assertEquals("foo(int,java.lang.Object)",pe.toSignatureString());
// check that can get hold of the non qualified args
assertEquals("foo(int,Object)",pe.toLabelString(false));
assertEquals("C.foo(int,Object)",pe.toLinkLabelString(false));
assertEquals("foo(int,Object)",pe.toSignatureString(false));
IProgramElement pe2 = top.findElementForType("pkg","printParameters");
assertNotNull("Couldn't find 'printParameters' element in the tree",pe2);
// the argument is org.aspectj.lang.JoinPoint, check that this is added
assertFalse("printParameters method should have arguments",pe2.getParameterTypes().isEmpty());
}
public void testParameterizedEnum_pr126316() {
runTest("E extends Enum(E) again");
}
public void testSwallowedException() {
runTest("swallowed exceptions");
}
public void testAtAspectVerifyErrorWithAfterThrowingAndthisJoinPoint_pr122742() {
runTest("@AJ VerifyError with @AfterThrowing and thisJoinPoint argument");
}
public void testAtAspectVerifyErrorWithAfterReturningAndthisJoinPoint_pr122742() {
runTest("@AJ VerifyError with @AfterReturning and thisJoinPoint argument");
}
public void testSwallowedExceptionIgnored() {
runTest("swallowed exceptions with xlint");
}
public void testGenericAspectWithUnknownType_pr131933() {
runTest("no ClassCastException with generic aspect and unknown type");
}
public void testStructureModelForGenericITD_pr131932() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("structure model for generic itd");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the ITDs and classes
IProgramElement foo = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.CLASS,"Foo");
assertNotNull("Couldn't find Foo element in the tree",foo);
IProgramElement bar = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.CLASS,"Bar");
assertNotNull("Couldn't find Bar element in the tree",bar);
IProgramElement method = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.INTER_TYPE_METHOD,"Bar.getFirst()");
assertNotNull("Couldn't find 'Bar.getFirst()' element in the tree",method);
IProgramElement field = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.INTER_TYPE_FIELD,"Bar.children");
assertNotNull("Couldn't find 'Bar.children' element in the tree",field);
IProgramElement constructor = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR,"Foo.Foo(List<T>)");
assertNotNull("Couldn't find 'Foo.Foo(List<T>)' element in the tree",constructor);
// check that the relationship map has 'itd method declared on bar'
List matches = AsmManager.getDefault().getRelationshipMap().get(method);
assertNotNull("itd Bar.getFirst() should have some relationships but does not",matches);
assertTrue("method itd should have one relationship but has " + matches.size(), matches.size() == 1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("itd Bar.getFirst() should have one target but has " + matchesTargets.size(),matchesTargets.size() == 1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the Bar class but is IPE with label "
+ target.toLabelString(),bar,target);
// check that the relationship map has 'itd field declared on bar'
matches = AsmManager.getDefault().getRelationshipMap().get(field);
assertNotNull("itd Bar.children should have some relationships but does not",matches);
assertTrue("field itd should have one relationship but has " + matches.size(), matches.size() == 1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("itd Bar.children should have one target but has " + matchesTargets.size(),matchesTargets.size() == 1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the Bar class but is IPE with label "
+ target.toLabelString(),bar,target);
// check that the relationship map has 'itd constructor declared on foo'
matches = AsmManager.getDefault().getRelationshipMap().get(constructor);
assertNotNull("itd Foo.Foo(List<T>) should have some relationships but does not",matches);
assertTrue("constructor itd should have one relationship but has " + matches.size(), matches.size() == 1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("itd Foo.Foo(List<T>) should have one target but has " + matchesTargets.size(),matchesTargets.size() == 1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the Foo class but is IPE with label "
+ target.toLabelString(),foo,target);
// check that the relationship map has 'bar aspect declarations method and field itd'
matches = AsmManager.getDefault().getRelationshipMap().get(bar);
assertNotNull("Bar should have some relationships but does not",matches);
assertTrue("Bar should have one relationship but has " + matches.size(), matches.size() == 1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("Bar should have two targets but has " + matchesTargets.size(),matchesTargets.size() == 2);
for (Iterator iter = matchesTargets.iterator(); iter.hasNext();) {
String element = (String) iter.next();
target = AsmManager.getDefault().getHierarchy().findElementForHandle(element);
if (!target.equals(method) && !target.equals(field)) {
fail("Expected rel target to be " + method.toLabelString() + " or " + field.toLabelString()
+ ", found " + target.toLabelString());
}
}
// check that the relationship map has 'foo aspect declarations constructor itd'
matches = AsmManager.getDefault().getRelationshipMap().get(foo);
assertNotNull("Foo should have some relationships but does not",matches);
assertTrue("Foo should have one relationship but has " + matches.size(), matches.size() == 1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("Foo should have one target but has " + matchesTargets.size(),matchesTargets.size() == 1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the Foo.Foo(List<T>) itd but is IPE with label "
+ target.toLabelString(),constructor,target);
}
public void testDeclareAnnotationAppearsInStructureModel_pr132130() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("declare annotation appears in structure model when in same file");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the different code entries
IProgramElement decam = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_METHOD,"declare @method: * debit(..) : @Secured(role = \"supervisor\")");
assertNotNull("Couldn't find 'declare @method' element in the tree",decam);
IProgramElement method = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"debit(long,long)");
assertNotNull("Couldn't find the 'debit(long,long)' method element in the tree",method);
IProgramElement decac = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.DECLARE_ANNOTATION_AT_CONSTRUCTOR,"declare @constructor: BankAccount+.new(..) : @Secured(role = \"supervisor\")");
assertNotNull("Couldn't find 'declare @constructor' element in the tree",decac);
IProgramElement ctr = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.CONSTRUCTOR,"BankAccount(String,int)");
assertNotNull("Couldn't find the 'BankAccount(String,int)' constructor element in the tree",ctr);
// check that decam has a annotates relationship with the debit method
List matches = AsmManager.getDefault().getRelationshipMap().get(decam);
assertNotNull("'declare @method' should have some relationships but does not",matches);
assertTrue("'declare @method' should have one relationships but has " + matches.size(),matches.size()==1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'declare @method' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'debit(long,long)' method but is IPE with label "
+ target.toLabelString(),method,target);
// check that the debit method has an annotated by relationship with the declare @method
matches = AsmManager.getDefault().getRelationshipMap().get(method);
assertNotNull("'debit(long,long)' should have some relationships but does not",matches);
assertTrue("'debit(long,long)' should have one relationships but has " + matches.size(),matches.size()==1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'debit(long,long)' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'declare @method' ipe but is IPE with label "
+ target.toLabelString(),decam,target);
// check that decac has a annotates relationship with the constructor
matches = AsmManager.getDefault().getRelationshipMap().get(decac);
assertNotNull("'declare @method' should have some relationships but does not",matches);
assertTrue("'declare @method' should have one relationships but has " + matches.size(),matches.size()==1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'declare @method' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'debit(long, long)' method but is IPE with label "
+ target.toLabelString(),ctr,target);
// check that the constructor has an annotated by relationship with the declare @constructor
matches = AsmManager.getDefault().getRelationshipMap().get(ctr);
assertNotNull("'debit(long, long)' should have some relationships but does not",matches);
assertTrue("'debit(long, long)' should have one relationships but has " + matches.size(),matches.size()==1);
matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("'debit(long, long)' should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the 'declare @method' ipe but is IPE with label "
+ target.toLabelString(),decac,target);
}
/*
* @AspectJ bugs and enhancements
*/
// public void testAtAspectInheritsAdviceWithTJPAndThis_pr125699 () {
// runTest("inherit adivce with this() and thisJoinPoint");
// }
public void testAtAspectInheritsAbstractPointcut_pr125810 () {
runTest("warning when inherited pointcut not made concrete");
}
public void testAtAspectDEOWInStructureModel_pr120356() {
//AsmManager.setReporting("c:/debug.txt",true,true,true,true);
runTest("@AJ deow appear correctly when structure model is generated");
IHierarchy top = AsmManager.getDefault().getHierarchy();
// get the IProgramElements corresponding to the @DeclareWarning statement
// and the method it matches.
IProgramElement warningMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"warningMethod()");
assertNotNull("Couldn't find 'warningMethod()' element in the tree",warningMethodIPE);
IProgramElement atDeclareWarningIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.FIELD,"warning");
assertNotNull("Couldn't find @DeclareWarning element in the tree",atDeclareWarningIPE);
// check that the method has a matches declare relationship with @DeclareWarning
List matches = AsmManager.getDefault().getRelationshipMap().get(warningMethodIPE);
assertNotNull("warningMethod should have some relationships but does not",matches);
assertTrue("warningMethod should have one relationships but has " + matches.size(),matches.size()==1);
List matchesTargets = ((Relationship)matches.get(0)).getTargets();
assertTrue("warningMethod should have one targets but has" + matchesTargets.size(),matchesTargets.size()==1);
IProgramElement target = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchesTargets.get(0));
assertEquals("target of relationship should be the @DeclareWarning 'warning' but is IPE with label "
+ target.toLabelString(),atDeclareWarningIPE,target);
// check that the @DeclareWarning has a matches relationship with the warningMethod
List matchedBy = AsmManager.getDefault().getRelationshipMap().get(atDeclareWarningIPE);
assertNotNull("@DeclareWarning should have some relationships but does not",matchedBy);
assertTrue("@DeclareWarning should have one relationship but has " + matchedBy.size(), matchedBy.size() == 1);
List matchedByTargets = ((Relationship)matchedBy.get(0)).getTargets();
assertTrue("@DeclareWarning 'matched by' relationship should have one target " +
"but has " + matchedByTargets.size(), matchedByTargets.size() == 1);
IProgramElement matchedByTarget = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargets.get(0));
assertEquals("target of relationship should be the warningMethod but is IPE with label "
+ matchedByTarget.toLabelString(),warningMethodIPE,matchedByTarget);
// get the IProgramElements corresponding to the @DeclareError statement
// and the method it matches.
IProgramElement errorMethodIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.METHOD,"badMethod()");
assertNotNull("Couldn't find 'badMethod()' element in the tree",errorMethodIPE);
IProgramElement atDeclarErrorIPE = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.FIELD,"error");
assertNotNull("Couldn't find @DeclareError element in the tree",atDeclarErrorIPE);
// check that the @DeclareError has a matches relationship with the badMethod
List matchedByE = AsmManager.getDefault().getRelationshipMap().get(atDeclarErrorIPE);
assertNotNull("@DeclareError should have some relationships but does not",matchedByE);
assertTrue("@DeclareError should have one relationship but has " + matchedByE.size(), matchedByE.size() == 1);
List matchedByTargetsE = ((Relationship)matchedByE.get(0)).getTargets();
assertTrue("@DeclareError 'matched by' relationship should have one target " +
"but has " + matchedByTargetsE.size(), matchedByTargetsE.size() == 1);
IProgramElement matchedByTargetE = AsmManager.getDefault().getHierarchy().findElementForHandle((String)matchedByTargetsE.get(0));
assertEquals("target of relationship should be the badMethod but is IPE with label "
+ matchedByTargetE.toLabelString(),errorMethodIPE,matchedByTargetE);
}
public void testAtAspectNoNPEWithDEOWWithoutStructureModel_pr120356() {
runTest("@AJ no NPE with deow when structure model isn't generated");
}
public void testAtAspectWithoutJoinPointImport_pr121616() {
runTest("@AJ without JoinPoint import");
}
public void testAtAspectDeclareParentsRetainsFieldState_pr122370() {
runTest("@AJ declare parents retains field state");
}
public void testAtAspectNoNPEWithPcdContainingOrThisAndWildcard_pr128237() {
runTest("@AJ no npe with pointcut containing or, this and a wildcard");
}
/*
* Load-time weaving bugs and enhancements
*/
public void testEmptyPointcutInAtAspectJ_pr125475 () {
runTest("define empty pointcut using an annotation");
}
public void testEmptyPointcutInAtAspectJ_pr125475_2() {
runTest("define empty pointcut using an annotation - 2");
}
public void testEmptyPointcutInAtAspectJWithLTW_pr125475 () {
runTest("define empty pointcut using aop.xml");
}
public void testLTWGeneratedAspectWithAbstractMethod_pr125480 () {
runTest("aop.xml aspect inherits abstract method that has concrete implementation in parent");
}
public void testGenericAspectsWithAnnotationTypeParameters() {
runTest("Generic aspects with annotation type parameters");
}
public void testPointcutInterfaces_pr130869() {
runTest("Pointcut interfaces");
}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc151Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc151/ajc151.xml");
}
}
|
133,307 |
Bug 133307 declare parents implementing generic interface referencing same type
|
I have the following construct: public interface TestIF<T extends TestIF> {} public class TestClass {} public aspect TestAspect { declare parents: TestClass implements TestIF<TestClass>; } The later aspect does not compile, although public class TestClass implements TestIF<TestClass> { } is a valid class.
|
resolved fixed
|
c9a60e5
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-27T13:42:23Z | 2006-03-27T03:26: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.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.weaver.patterns.CflowPointcut;
import org.aspectj.weaver.patterns.DeclareParents;
/**
* This holds on to all CrosscuttingMembers for a world. It handles
* management of change.
*
* @author Jim Hugunin
*/
public class CrosscuttingMembersSet {
private World world;
//FIXME AV - ? we may need a sequencedHashMap there to ensure source based precedence for @AJ advice
private Map /* ResolvedType (the aspect) > CrosscuttingMembers */members = new HashMap();
private List shadowMungers = null;
private List typeMungers = null;
private List lateTypeMungers = null;
private List declareSofts = null;
private List declareParents = null;
private List declareAnnotationOnTypes = null;
private List declareAnnotationOnFields = null;
private List declareAnnotationOnMethods= null; // includes ctors
private List declareDominates = null;
private boolean changedSinceLastReset = false;
public CrosscuttingMembersSet(World world) {
this.world = world;
}
public boolean addOrReplaceAspect(ResolvedType aspectType) {
return addOrReplaceAspect(aspectType,true);
}
/**
* @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(ResolvedType aspectType,boolean careAboutShadowMungers) {
boolean change = false;
CrosscuttingMembers xcut = (CrosscuttingMembers)members.get(aspectType);
if (xcut == null) {
members.put(aspectType, aspectType.collectCrosscuttingMembers());
clearCaches();
CflowPointcut.clearCaches(aspectType);
change = true;
} else {
if (xcut.replaceWith(aspectType.collectCrosscuttingMembers(),careAboutShadowMungers)) {
clearCaches();
CflowPointcut.clearCaches(aspectType);
change = true;
} else {
change = false;
}
}
if (aspectType.isAbstract()) {
// we might have sub-aspects that need to re-collect their crosscutting members from us
boolean ancestorChange = addOrReplaceDescendantsOf(aspectType,careAboutShadowMungers);
change = change || ancestorChange;
}
changedSinceLastReset = changedSinceLastReset || change;
return change;
}
private boolean addOrReplaceDescendantsOf(ResolvedType aspectType,boolean careAboutShadowMungers) {
//System.err.println("Looking at descendants of "+aspectType.getName());
Set knownAspects = members.keySet();
Set toBeReplaced = new HashSet();
for(Iterator it = knownAspects.iterator(); it.hasNext(); ) {
ResolvedType candidateDescendant = (ResolvedType)it.next();
if ((candidateDescendant != aspectType) && (aspectType.isAssignableFrom(candidateDescendant))) {
toBeReplaced.add(candidateDescendant);
}
}
boolean change = false;
for (Iterator it = toBeReplaced.iterator(); it.hasNext(); ) {
ResolvedType next = (ResolvedType)it.next();
boolean thisChange = addOrReplaceAspect(next,careAboutShadowMungers);
change = change || thisChange;
}
return change;
}
public void addAdviceLikeDeclares(ResolvedType aspectType) {
CrosscuttingMembers xcut = (CrosscuttingMembers)members.get(aspectType);
xcut.addDeclares(aspectType.collectDeclares(true));
}
public boolean deleteAspect(UnresolvedType aspectType) {
boolean isAspect = members.remove(aspectType) != null;
clearCaches();
return isAspect;
}
public boolean containsAspect(UnresolvedType aspectType) {
return members.containsKey(aspectType);
}
//XXX only for testing
public void addFixedCrosscuttingMembers(ResolvedType aspectType) {
members.put(aspectType, aspectType.crosscuttingMembers);
clearCaches();
}
private void clearCaches() {
shadowMungers = null;
typeMungers = null;
lateTypeMungers = null;
declareSofts = null;
declareParents = null;
declareAnnotationOnFields=null;
declareAnnotationOnMethods=null;
declareAnnotationOnTypes=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 getLateTypeMungers() {
if (lateTypeMungers == null) {
ArrayList ret = new ArrayList();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getLateTypeMungers());
}
lateTypeMungers = ret;
}
return lateTypeMungers;
}
public List getDeclareSofts() {
if (declareSofts == null) {
Set ret = new HashSet();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareSofts());
}
declareSofts = new ArrayList();
declareSofts.addAll(ret);
}
return declareSofts;
}
public List getDeclareParents() {
if (declareParents == null) {
Set ret = new HashSet();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareParents());
}
declareParents = new ArrayList();
declareParents.addAll(ret);
}
return declareParents;
}
// DECAT Merge multiple together
public List getDeclareAnnotationOnTypes() {
if (declareAnnotationOnTypes == null) {
Set ret = new HashSet();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareAnnotationOnTypes());
}
declareAnnotationOnTypes = new ArrayList();
declareAnnotationOnTypes.addAll(ret);
}
return declareAnnotationOnTypes;
}
public List getDeclareAnnotationOnFields() {
if (declareAnnotationOnFields == null) {
Set ret = new HashSet();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareAnnotationOnFields());
}
declareAnnotationOnFields = new ArrayList();
declareAnnotationOnFields.addAll(ret);
}
return declareAnnotationOnFields;
}
/**
* Return an amalgamation of the declare @method/@constructor statements.
*/
public List getDeclareAnnotationOnMethods() {
if (declareAnnotationOnMethods == null) {
Set ret = new HashSet();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareAnnotationOnMethods());
}
declareAnnotationOnMethods = new ArrayList();
declareAnnotationOnMethods.addAll(ret);
}
return declareAnnotationOnMethods;
}
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;
}
public ResolvedType findAspectDeclaringParents(DeclareParents p) {
Set keys = this.members.keySet();
for (Iterator iter = keys.iterator(); iter.hasNext();) {
ResolvedType element = (ResolvedType) iter.next();
for (Iterator i = ((CrosscuttingMembers)members.get(element)).getDeclareParents().iterator(); i.hasNext(); ) {
DeclareParents dp = (DeclareParents)i.next();
if (dp.equals(p)) return element;
}
}
return null;
}
public void reset() {
changedSinceLastReset = false;
}
public boolean hasChangedSinceLastReset() {
return changedSinceLastReset;
}
}
|
133,307 |
Bug 133307 declare parents implementing generic interface referencing same type
|
I have the following construct: public interface TestIF<T extends TestIF> {} public class TestClass {} public aspect TestAspect { declare parents: TestClass implements TestIF<TestClass>; } The later aspect does not compile, although public class TestClass implements TestIF<TestClass> { } is a valid class.
|
resolved fixed
|
c9a60e5
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-27T13:42:23Z | 2006-03-27T03:26:40Z |
weaver/src/org/aspectj/weaver/patterns/IVerificationRequired.java
| |
133,307 |
Bug 133307 declare parents implementing generic interface referencing same type
|
I have the following construct: public interface TestIF<T extends TestIF> {} public class TestClass {} public aspect TestAspect { declare parents: TestClass implements TestIF<TestClass>; } The later aspect does not compile, although public class TestClass implements TestIF<TestClass> { } is a valid class.
|
resolved fixed
|
c9a60e5
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-27T13:42:23Z | 2006-03-27T03:26:40Z |
weaver/src/org/aspectj/weaver/patterns/WildTypePattern.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FileUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.BoundedReferenceType;
import org.aspectj.weaver.IHasPosition;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.TypeFactory;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.TypeVariableReference;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.UnresolvedTypeVariableReferenceType;
import org.aspectj.weaver.VersionedDataInputStream;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
/**
* The PatternParser always creates WildTypePatterns for type patterns in pointcut
* expressions (apart from *, which is sometimes directly turned into TypePattern.ANY).
* resolveBindings() tries to work out what we've really got and turn it into a type
* pattern that we can use for matching. This will normally be either an ExactTypePattern
* or a WildTypePattern.
*
* Here's how the process pans out for various generic and parameterized patterns:
* (see GenericsWildTypePatternResolvingTestCase)
*
* Foo where Foo exists and is generic
* Parser creates WildTypePattern namePatterns={Foo}
* resolveBindings resolves Foo to RT(Foo - raw)
* return ExactTypePattern(LFoo;)
*
* Foo<String> where Foo exists and String meets the bounds
* Parser creates WildTypePattern namePatterns = {Foo}, typeParameters=WTP{String}
* resolveBindings resolves typeParameters to ExactTypePattern(String)
* resolves Foo to RT(Foo)
* returns ExactTypePattern(PFoo<String>; - parameterized)
*
* Foo<Str*> where Foo exists and takes one bound
* Parser creates WildTypePattern namePatterns = {Foo}, typeParameters=WTP{Str*}
* resolveBindings resolves typeParameters to WTP{Str*}
* resolves Foo to RT(Foo)
* returns WildTypePattern(name = Foo, typeParameters = WTP{Str*} isGeneric=false)
*
* Fo*<String>
* Parser creates WildTypePattern namePatterns = {Fo*}, typeParameters=WTP{String}
* resolveBindings resolves typeParameters to ETP{String}
* returns WildTypePattern(name = Fo*, typeParameters = ETP{String} isGeneric=false)
*
*
* Foo<?>
*
* Foo<? extends Number>
*
* Foo<? extends Number+>
*
* Foo<? super Number>
*
*/
public class WildTypePattern extends TypePattern {
private static final String GENERIC_WILDCARD_CHARACTER = "?";
private NamePattern[] namePatterns;
int ellipsisCount;
String[] importedPrefixes;
String[] knownMatches;
int dim;
// SECRETAPI - just for testing, turns off boundschecking temporarily...
public static boolean boundscheckingoff = false;
// these next three are set if the type pattern is constrained by extends or super clauses, in which case the
// namePatterns must have length 1
// TODO AMC: read/write/resolve of these fields
TypePattern upperBound; // extends Foo
TypePattern[] additionalInterfaceBounds; // extends Foo & A,B,C
TypePattern lowerBound; // super Foo
// if we have type parameters, these fields indicate whether we should be a generic type pattern or a parameterized
// type pattern. We can only tell during resolve bindings.
private boolean isGeneric = true;
WildTypePattern(NamePattern[] namePatterns, boolean includeSubtypes, int dim, boolean isVarArgs, TypePatternList typeParams) {
super(includeSubtypes,isVarArgs,typeParams);
this.namePatterns = namePatterns;
this.dim = dim;
ellipsisCount = 0;
for (int i=0; i<namePatterns.length; i++) {
if (namePatterns[i] == NamePattern.ELLIPSIS) ellipsisCount++;
}
setLocation(namePatterns[0].getSourceContext(), namePatterns[0].getStart(), namePatterns[namePatterns.length-1].getEnd());
}
public WildTypePattern(List names, boolean includeSubtypes, int dim) {
this((NamePattern[])names.toArray(new NamePattern[names.size()]), includeSubtypes, dim,false,TypePatternList.EMPTY);
}
public WildTypePattern(List names, boolean includeSubtypes, int dim, int endPos) {
this(names, includeSubtypes, dim);
this.end = endPos;
}
public WildTypePattern(List names, boolean includeSubtypes, int dim, int endPos, boolean isVarArg) {
this(names, includeSubtypes, dim);
this.end = endPos;
this.isVarArgs = isVarArg;
}
public WildTypePattern(
List names,
boolean includeSubtypes,
int dim,
int endPos,
boolean isVarArg,
TypePatternList typeParams,
TypePattern upperBound,
TypePattern[] additionalInterfaceBounds,
TypePattern lowerBound) {
this((NamePattern[])names.toArray(new NamePattern[names.size()]),includeSubtypes,dim,isVarArg,typeParams);
this.end = endPos;
this.upperBound = upperBound;
this.lowerBound = lowerBound;
this.additionalInterfaceBounds = additionalInterfaceBounds;
}
public WildTypePattern(
List names,
boolean includeSubtypes,
int dim,
int endPos,
boolean isVarArg,
TypePatternList typeParams)
{
this((NamePattern[])names.toArray(new NamePattern[names.size()]),includeSubtypes,dim,isVarArg,typeParams);
this.end = endPos;
}
public NamePattern[] getNamePatterns() {
return namePatterns;
}
public TypePattern getUpperBound() { return upperBound; }
public TypePattern getLowerBound() { return lowerBound; }
public TypePattern[] getAdditionalIntefaceBounds() { return additionalInterfaceBounds; }
// called by parser after parsing a type pattern, must bump dim as well as setting flag
public void setIsVarArgs(boolean isVarArgs) {
this.isVarArgs = isVarArgs;
if (isVarArgs) this.dim += 1;
}
/* (non-Javadoc)
* @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern)
*/
protected boolean couldEverMatchSameTypesAs(TypePattern other) {
if (super.couldEverMatchSameTypesAs(other)) return true;
// false is necessary but not sufficient
UnresolvedType otherType = other.getExactType();
if (!ResolvedType.isMissing(otherType)) {
if (namePatterns.length > 0) {
if (!namePatterns[0].matches(otherType.getName())) return false;
}
}
if (other instanceof WildTypePattern) {
WildTypePattern owtp = (WildTypePattern) other;
String mySimpleName = namePatterns[0].maybeGetSimpleName();
String yourSimpleName = owtp.namePatterns[0].maybeGetSimpleName();
if (mySimpleName != null && yourSimpleName != null) {
return (mySimpleName.startsWith(yourSimpleName) ||
yourSimpleName.startsWith(mySimpleName));
}
}
return true;
}
//XXX inefficient implementation
// we don't know whether $ characters are from nested types, or were
// part of the declared type name (generated code often uses $s in type
// names). More work required on our part to get this right...
public static char[][] splitNames(String s, boolean convertDollar) {
List ret = new ArrayList();
int startIndex = 0;
while (true) {
int breakIndex = s.indexOf('.', startIndex); // what about /
if (convertDollar && (breakIndex == -1)) breakIndex = s.indexOf('$', startIndex); // we treat $ like . here
if (breakIndex == -1) break;
char[] name = s.substring(startIndex, breakIndex).toCharArray();
ret.add(name);
startIndex = breakIndex+1;
}
ret.add(s.substring(startIndex).toCharArray());
return (char[][])ret.toArray(new char[ret.size()][]);
}
/**
* @see org.aspectj.weaver.TypePattern#matchesExactly(IType)
*/
protected boolean matchesExactly(ResolvedType type) {
return matchesExactly(type,type);
}
protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) {
String targetTypeName = type.getName();
//System.err.println("match: " + targetTypeName + ", " + knownMatches); //Arrays.asList(importedPrefixes));
// Ensure the annotation pattern is resolved
annotationPattern.resolve(type.getWorld());
return matchesExactlyByName(targetTypeName,type.isAnonymous(),type.isNested()) &&
matchesParameters(type,STATIC) &&
matchesBounds(type,STATIC) &&
annotationPattern.matches(annotatedType).alwaysTrue();
}
// we've matched against the base (or raw) type, but if this type pattern specifies parameters or
// type variables we need to make sure we match against them too
private boolean matchesParameters(ResolvedType aType, MatchKind staticOrDynamic) {
if (!isGeneric && typeParameters.size() > 0) {
if(!aType.isParameterizedType()) return false;
// we have to match type parameters
return typeParameters.matches(aType.getResolvedTypeParameters(), staticOrDynamic).alwaysTrue();
}
return true;
}
// we've matched against the base (or raw) type, but if this type pattern specifies bounds because
// it is a ? extends or ? super deal then we have to match them too.
private boolean matchesBounds(ResolvedType aType, MatchKind staticOrDynamic) {
if (upperBound == null && aType.getUpperBound() != null) {
// for upper bound, null can also match against Object - but anything else and we're out.
if (!aType.getUpperBound().getName().equals(UnresolvedType.OBJECT.getName())) {
return false;
}
}
if (lowerBound == null && aType.getLowerBound() != null) return false;
if (upperBound != null) {
// match ? extends
if (aType.isGenericWildcard() && aType.isSuper()) return false;
if (aType.getUpperBound() == null) return false;
return upperBound.matches((ResolvedType)aType.getUpperBound(),staticOrDynamic).alwaysTrue();
}
if (lowerBound != null) {
// match ? super
if (!(aType.isGenericWildcard() && aType.isSuper())) return false;
return lowerBound.matches((ResolvedType)aType.getLowerBound(),staticOrDynamic).alwaysTrue();
}
return true;
}
/**
* Used in conjunction with checks on 'isStar()' to tell you if this pattern represents '*' or '*[]' which are
* different !
*/
public int getDimensions() {
return dim;
}
public boolean isArray() {
return dim > 1;
}
/**
* @param targetTypeName
* @return
*/
private boolean matchesExactlyByName(String targetTypeName, boolean isAnonymous, boolean isNested) {
// we deal with parameter matching separately...
if (targetTypeName.indexOf('<') != -1) {
targetTypeName = targetTypeName.substring(0,targetTypeName.indexOf('<'));
}
// we deal with bounds matching separately too...
if (targetTypeName.startsWith(GENERIC_WILDCARD_CHARACTER)) {
targetTypeName = GENERIC_WILDCARD_CHARACTER;
}
//XXX hack
if (knownMatches == null && importedPrefixes == null) {
return innerMatchesExactly(targetTypeName,isAnonymous, isNested);
}
if (isNamePatternStar()) {
// we match if the dimensions match
int numDimensionsInTargetType = 0;
if (dim > 0) {
int index;
while((index = targetTypeName.indexOf('[')) != -1) {
numDimensionsInTargetType++;
targetTypeName = targetTypeName.substring(index+1);
}
if (numDimensionsInTargetType == dim) {
return true;
} else {
return false;
}
}
}
// if our pattern is length 1, then known matches are exact matches
// if it's longer than that, then known matches are prefixes of a sort
if (namePatterns.length == 1) {
if (isAnonymous) {
// we've already ruled out "*", and no other name pattern should match an anonymous type
return false;
}
for (int i=0, len=knownMatches.length; i < len; i++) {
if (knownMatches[i].equals(targetTypeName)) return true;
}
} else {
for (int i=0, len=knownMatches.length; i < len; i++) {
String knownPrefix = knownMatches[i] + "$";
if (targetTypeName.startsWith(knownPrefix)) {
int pos = lastIndexOfDotOrDollar(knownMatches[i]);
if (innerMatchesExactly(targetTypeName.substring(pos+1),isAnonymous,isNested)) {
return true;
}
}
}
}
// if any prefixes match, strip the prefix and check that the rest matches
// assumes that prefixes have a dot at the end
for (int i=0, len=importedPrefixes.length; i < len; i++) {
String prefix = importedPrefixes[i];
//System.err.println("prefix match? " + prefix + " to " + targetTypeName);
if (targetTypeName.startsWith(prefix)) {
if (innerMatchesExactly(targetTypeName.substring(prefix.length()),isAnonymous,isNested)) {
return true;
}
}
}
return innerMatchesExactly(targetTypeName,isAnonymous,isNested);
}
private int lastIndexOfDotOrDollar(String string) {
int dot = string.lastIndexOf('.');
int dollar = string.lastIndexOf('$');
return Math.max(dot, dollar);
}
private boolean innerMatchesExactly(String targetTypeName, boolean isAnonymous, boolean isNested) {
//??? doing this everytime is not very efficient
char[][] names = splitNames(targetTypeName,isNested);
return innerMatchesExactly(names, isAnonymous);
}
private boolean innerMatchesExactly(char[][] names, boolean isAnonymous) {
int namesLength = names.length;
int patternsLength = namePatterns.length;
int namesIndex = 0;
int patternsIndex = 0;
if ((!namePatterns[patternsLength-1].isAny()) && isAnonymous) return false;
if (ellipsisCount == 0) {
if (namesLength != patternsLength) return false;
while (patternsIndex < patternsLength) {
if (!namePatterns[patternsIndex++].matches(names[namesIndex++])) {
return false;
}
}
return true;
} else if (ellipsisCount == 1) {
if (namesLength < patternsLength-1) return false;
while (patternsIndex < patternsLength) {
NamePattern p = namePatterns[patternsIndex++];
if (p == NamePattern.ELLIPSIS) {
namesIndex = namesLength - (patternsLength-patternsIndex);
} else {
if (!p.matches(names[namesIndex++])) {
return false;
}
}
}
return true;
} else {
// System.err.print("match(\"" + Arrays.asList(namePatterns) + "\", \"" + Arrays.asList(names) + "\") -> ");
boolean b = outOfStar(namePatterns, names, 0, 0, patternsLength - ellipsisCount, namesLength, ellipsisCount);
// System.err.println(b);
return b;
}
}
private static boolean outOfStar(final NamePattern[] pattern, final char[][] target,
int pi, int ti,
int pLeft, int tLeft,
final int starsLeft) {
if (pLeft > tLeft) return false;
while (true) {
// invariant: if (tLeft > 0) then (ti < target.length && pi < pattern.length)
if (tLeft == 0) return true;
if (pLeft == 0) {
return (starsLeft > 0);
}
if (pattern[pi] == NamePattern.ELLIPSIS) {
return inStar(pattern, target, pi+1, ti, pLeft, tLeft, starsLeft-1);
}
if (! pattern[pi].matches(target[ti])) {
return false;
}
pi++; ti++; pLeft--; tLeft--;
}
}
private static boolean inStar(final NamePattern[] pattern, final char[][] target,
int pi, int ti,
final int pLeft, int tLeft,
int starsLeft) {
// invariant: pLeft > 0, so we know we'll run out of stars and find a real char in pattern
// of course, we probably can't parse multiple ..'s in a row, but this keeps the algorithm
// exactly parallel with that in NamePattern
NamePattern patternChar = pattern[pi];
while (patternChar == NamePattern.ELLIPSIS) {
starsLeft--;
patternChar = pattern[++pi];
}
while (true) {
// invariant: if (tLeft > 0) then (ti < target.length)
if (pLeft > tLeft) return false;
if (patternChar.matches(target[ti])) {
if (outOfStar(pattern, target, pi+1, ti+1, pLeft-1, tLeft-1, starsLeft)) return true;
}
ti++; tLeft--;
}
}
/**
* @see org.aspectj.weaver.TypePattern#matchesInstanceof(IType)
*/
public FuzzyBoolean matchesInstanceof(ResolvedType type) {
//XXX hack to let unmatched types just silently remain so
if (maybeGetSimpleName() != null) return
FuzzyBoolean.NO;
type.getWorld().getMessageHandler().handleMessage(
new Message("can't do instanceof matching on patterns with wildcards",
IMessage.ERROR, null, getSourceLocation()));
return FuzzyBoolean.NO;
}
public NamePattern extractName() {
if (isIncludeSubtypes() || isVarArgs() || isArray() || (typeParameters.size() > 0)) {
// we can't extract a name, the pattern is something like Foo+ and therefore
// it is not ok to treat Foo as a method name!
return null;
}
//System.err.println("extract from : " + Arrays.asList(namePatterns));
int len = namePatterns.length;
if (len ==1 && !annotationPattern.isAny()) return null; // can't extract
NamePattern ret = namePatterns[len-1];
NamePattern[] newNames = new NamePattern[len-1];
System.arraycopy(namePatterns, 0, newNames, 0, len-1);
namePatterns = newNames;
//System.err.println(" left : " + Arrays.asList(namePatterns));
return ret;
}
/**
* Method maybeExtractName.
* @param string
* @return boolean
*/
public boolean maybeExtractName(String string) {
int len = namePatterns.length;
NamePattern ret = namePatterns[len-1];
String simple = ret.maybeGetSimpleName();
if (simple != null && simple.equals(string)) {
extractName();
return true;
}
return false;
}
/**
* If this type pattern has no '.' or '*' in it, then
* return a simple string
*
* otherwise, this will return null;
*/
public String maybeGetSimpleName() {
if (namePatterns.length == 1) {
return namePatterns[0].maybeGetSimpleName();
}
return null;
}
/**
* If this type pattern has no '*' or '..' in it
*/
public String maybeGetCleanName() {
if (namePatterns.length == 0) {
throw new RuntimeException("bad name: " + namePatterns);
}
//System.out.println("get clean: " + this);
StringBuffer buf = new StringBuffer();
for (int i=0, len=namePatterns.length; i < len; i++) {
NamePattern p = namePatterns[i];
String simpleName = p.maybeGetSimpleName();
if (simpleName == null) return null;
if (i > 0) buf.append(".");
buf.append(simpleName);
}
//System.out.println(buf);
return buf.toString();
}
public TypePattern parameterizeWith(Map typeVariableMap) {
NamePattern[] newNamePatterns = new NamePattern[namePatterns.length];
for(int i=0; i<namePatterns.length;i++) { newNamePatterns[i] = namePatterns[i]; }
if (newNamePatterns.length == 1) {
String simpleName = newNamePatterns[0].maybeGetSimpleName();
if (simpleName != null) {
if (typeVariableMap.containsKey(simpleName)) {
String newName = ((ReferenceType)typeVariableMap.get(simpleName)).getName().replace('$','.');
StringTokenizer strTok = new StringTokenizer(newName,".");
newNamePatterns = new NamePattern[strTok.countTokens()];
int index = 0;
while(strTok.hasMoreTokens()) {
newNamePatterns[index++] = new NamePattern(strTok.nextToken());
}
}
}
}
WildTypePattern ret = new WildTypePattern(
newNamePatterns,
includeSubtypes,
dim,
isVarArgs,
typeParameters.parameterizeWith(typeVariableMap)
);
ret.annotationPattern = this.annotationPattern.parameterizeWith(typeVariableMap);
if (additionalInterfaceBounds == null) {
ret.additionalInterfaceBounds = null;
} else {
ret.additionalInterfaceBounds = new TypePattern[additionalInterfaceBounds.length];
for (int i = 0; i < additionalInterfaceBounds.length; i++) {
ret.additionalInterfaceBounds[i] = additionalInterfaceBounds[i].parameterizeWith(typeVariableMap);
}
}
ret.upperBound = upperBound != null ? upperBound.parameterizeWith(typeVariableMap) : null;
ret.lowerBound = lowerBound != null ? lowerBound.parameterizeWith(typeVariableMap) : null;
ret.isGeneric = isGeneric;
ret.knownMatches = knownMatches;
ret.importedPrefixes = importedPrefixes;
ret.copyLocationFrom(this);
return ret;
}
/**
* Need to determine if I'm really a pattern or a reference to a formal
*
* We may wish to further optimize the case of pattern vs. non-pattern
*
* We will be replaced by what we return
*/
public TypePattern resolveBindings(IScope scope, Bindings bindings,
boolean allowBinding, boolean requireExactType)
{
if (isNamePatternStar()) {
TypePattern anyPattern = maybeResolveToAnyPattern(scope, bindings, allowBinding, requireExactType);
if (anyPattern != null) {
if (requireExactType) {
scope.getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.WILDCARD_NOT_ALLOWED),
getSourceLocation()));
return NO;
} else {
return anyPattern;
}
}
}
TypePattern bindingTypePattern = maybeResolveToBindingTypePattern(scope, bindings, allowBinding, requireExactType);
if (bindingTypePattern != null) return bindingTypePattern;
annotationPattern = annotationPattern.resolveBindings(scope,bindings,allowBinding);
// resolve any type parameters
if (typeParameters!=null && typeParameters.size()>0) {
typeParameters.resolveBindings(scope,bindings,allowBinding,requireExactType);
isGeneric = false;
}
// resolve any bounds
if (upperBound != null) upperBound = upperBound.resolveBindings(scope, bindings, allowBinding, requireExactType);
if (lowerBound != null) lowerBound = lowerBound.resolveBindings(scope, bindings, allowBinding, requireExactType);
// amc - additional interface bounds only needed if we support type vars again.
String fullyQualifiedName = maybeGetCleanName();
if (fullyQualifiedName != null) {
return resolveBindingsFromFullyQualifiedTypeName(fullyQualifiedName, scope, bindings, allowBinding, requireExactType);
} else {
if (requireExactType) {
scope.getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.WILDCARD_NOT_ALLOWED),
getSourceLocation()));
return NO;
}
importedPrefixes = scope.getImportedPrefixes();
knownMatches = preMatch(scope.getImportedNames());
return this; // pattern contains wildcards so can't be resolved to an ExactTypePattern...
//XXX need to implement behavior for Lint.invalidWildcardTypeName
}
}
private TypePattern maybeResolveToAnyPattern(IScope scope, Bindings bindings,
boolean allowBinding, boolean requireExactType) {
// If there is an annotation specified we have to
// use a special variant of Any TypePattern called
// AnyWithAnnotation
if (annotationPattern == AnnotationTypePattern.ANY) {
if (dim == 0 && !isVarArgs && upperBound == null && lowerBound == null && (additionalInterfaceBounds == null || additionalInterfaceBounds.length==0)) { // pr72531
return TypePattern.ANY; //??? loses source location
}
} else {
annotationPattern = annotationPattern.resolveBindings(scope,bindings,allowBinding);
AnyWithAnnotationTypePattern ret = new AnyWithAnnotationTypePattern(annotationPattern);
ret.setLocation(sourceContext,start,end);
return ret;
}
return null; // can't resolve to a simple "any" pattern
}
private TypePattern maybeResolveToBindingTypePattern(IScope scope, Bindings bindings,
boolean allowBinding, boolean requireExactType) {
String simpleName = maybeGetSimpleName();
if (simpleName != null) {
FormalBinding formalBinding = scope.lookupFormal(simpleName);
if (formalBinding != null) {
if (bindings == null) {
scope.message(IMessage.ERROR, this, "negation doesn't allow binding");
return this;
}
if (!allowBinding) {
scope.message(IMessage.ERROR, this,
"name binding only allowed in target, this, and args pcds");
return this;
}
BindingTypePattern binding = new BindingTypePattern(formalBinding,isVarArgs);
binding.copyLocationFrom(this);
bindings.register(binding, scope);
return binding;
}
}
return null; // not possible to resolve to a binding type pattern
}
private TypePattern resolveBindingsFromFullyQualifiedTypeName(String fullyQualifiedName, IScope scope, Bindings bindings,
boolean allowBinding, boolean requireExactType) {
String originalName = fullyQualifiedName;
ResolvedType resolvedTypeInTheWorld = null;
UnresolvedType type;
//System.out.println("resolve: " + cleanName);
//??? this loop has too many inefficiencies to count
resolvedTypeInTheWorld = lookupTypeInWorld(scope.getWorld(), fullyQualifiedName);
if (resolvedTypeInTheWorld.isGenericWildcard()) {
type = resolvedTypeInTheWorld;
} else {
type = lookupTypeInScope(scope, fullyQualifiedName, this);
}
if ((type instanceof ResolvedType) && ((ResolvedType)type).isMissing()) {
return resolveBindingsForMissingType(resolvedTypeInTheWorld, originalName, scope, bindings, allowBinding, requireExactType);
} else {
return resolveBindingsForExactType(scope,type,fullyQualifiedName,requireExactType);
}
}
private UnresolvedType lookupTypeInScope(IScope scope, String typeName, IHasPosition location) {
UnresolvedType type = null;
while (ResolvedType.isMissing(type = scope.lookupType(typeName, location))) {
int lastDot = typeName.lastIndexOf('.');
if (lastDot == -1) break;
typeName = typeName.substring(0, lastDot) + '$' + typeName.substring(lastDot+1);
}
return type;
}
private ResolvedType lookupTypeInWorld(World world, String typeName) {
ResolvedType ret = world.resolve(UnresolvedType.forName(typeName),true);
while (ret.isMissing()) {
int lastDot = typeName.lastIndexOf('.');
if (lastDot == -1) break;
typeName = typeName.substring(0, lastDot) + '$' + typeName.substring(lastDot+1);
ret = world.resolve(UnresolvedType.forName(typeName),true);
}
return ret;
}
private TypePattern resolveBindingsForExactType(IScope scope, UnresolvedType aType, String fullyQualifiedName,boolean requireExactType) {
TypePattern ret = null;
if (aType.isTypeVariableReference()) {
// we have to set the bounds on it based on the bounds of this pattern
ret = resolveBindingsForTypeVariable(scope, (UnresolvedTypeVariableReferenceType) aType);
} else if (typeParameters.size()>0) {
ret = resolveParameterizedType(scope, aType, requireExactType);
} else if (upperBound != null || lowerBound != null) {
// this must be a generic wildcard with bounds
ret = resolveGenericWildcard(scope, aType);
} else {
if (dim != 0) aType = UnresolvedType.makeArray(aType, dim);
ret = new ExactTypePattern(aType,includeSubtypes,isVarArgs);
}
ret.setAnnotationTypePattern(annotationPattern);
ret.copyLocationFrom(this);
return ret;
}
private TypePattern resolveGenericWildcard(IScope scope, UnresolvedType aType) {
if (!aType.getSignature().equals(GENERIC_WILDCARD_CHARACTER)) throw new IllegalStateException("Can only have bounds for a generic wildcard");
boolean canBeExact = true;
if ((upperBound != null) && ResolvedType.isMissing(upperBound.getExactType())) canBeExact = false;
if ((lowerBound != null) && ResolvedType.isMissing(lowerBound.getExactType())) canBeExact = false;
if (canBeExact) {
ResolvedType type = null;
if (upperBound != null) {
if (upperBound.isIncludeSubtypes()) {
canBeExact = false;
} else {
ReferenceType upper = (ReferenceType) upperBound.getExactType().resolve(scope.getWorld());
type = new BoundedReferenceType(upper,true,scope.getWorld());
}
} else {
if (lowerBound.isIncludeSubtypes()) {
canBeExact = false;
} else {
ReferenceType lower = (ReferenceType) lowerBound.getExactType().resolve(scope.getWorld());
type = new BoundedReferenceType(lower,false,scope.getWorld());
}
}
if (canBeExact) {
// might have changed if we find out include subtypes is set on one of the bounds...
return new ExactTypePattern(type,includeSubtypes,isVarArgs);
}
}
// we weren't able to resolve to an exact type pattern...
// leave as wild type pattern
importedPrefixes = scope.getImportedPrefixes();
knownMatches = preMatch(scope.getImportedNames());
return this;
}
private TypePattern resolveParameterizedType(IScope scope, UnresolvedType aType, boolean requireExactType) {
if (!verifyTypeParameters(aType.resolve(scope.getWorld()),scope,requireExactType)) return TypePattern.NO; // messages already isued
// Only if the type is exact *and* the type parameters are exact should we create an
// ExactTypePattern for this WildTypePattern
if (typeParameters.areAllExactWithNoSubtypesAllowed()) {
TypePattern[] typePats = typeParameters.getTypePatterns();
UnresolvedType[] typeParameterTypes = new UnresolvedType[typePats.length];
for (int i = 0; i < typeParameterTypes.length; i++) {
typeParameterTypes[i] = ((ExactTypePattern)typePats[i]).getExactType();
}
ResolvedType type = TypeFactory.createParameterizedType(aType.resolve(scope.getWorld()), typeParameterTypes, scope.getWorld());
if (isGeneric) type = type.getGenericType();
// UnresolvedType tx = UnresolvedType.forParameterizedTypes(aType,typeParameterTypes);
// UnresolvedType type = scope.getWorld().resolve(tx,true);
if (dim != 0) type = ResolvedType.makeArray(type, dim);
return new ExactTypePattern(type,includeSubtypes,isVarArgs);
} else {
// AMC... just leave it as a wild type pattern then?
importedPrefixes = scope.getImportedPrefixes();
knownMatches = preMatch(scope.getImportedNames());
return this;
}
}
private TypePattern resolveBindingsForMissingType(ResolvedType typeFoundInWholeWorldSearch, String nameWeLookedFor, IScope scope, Bindings bindings,
boolean allowBinding, boolean requireExactType) {
if (requireExactType) {
if (!allowBinding) {
scope.getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.CANT_BIND_TYPE,nameWeLookedFor),
getSourceLocation()));
} else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) {
scope.getWorld().getLint().invalidAbsoluteTypeName.signal(nameWeLookedFor, getSourceLocation());
}
return NO;
} else if (scope.getWorld().getLint().invalidAbsoluteTypeName.isEnabled()) {
// Only put the lint warning out if we can't find it in the world
if (typeFoundInWholeWorldSearch.isMissing()) {
scope.getWorld().getLint().invalidAbsoluteTypeName.signal(nameWeLookedFor, getSourceLocation());
}
}
importedPrefixes = scope.getImportedPrefixes();
knownMatches = preMatch(scope.getImportedNames());
return this;
}
/**
* We resolved the type to a type variable declared in the pointcut designator.
* Now we have to create either an exact type pattern or a wild type pattern for it,
* with upper and lower bounds set accordingly.
* XXX none of this stuff gets serialized yet
* @param scope
* @param tvrType
* @return
*/
private TypePattern resolveBindingsForTypeVariable(IScope scope, UnresolvedTypeVariableReferenceType tvrType) {
Bindings emptyBindings = new Bindings(0);
if (upperBound != null) {
upperBound = upperBound.resolveBindings(scope, emptyBindings, false, false);
}
if (lowerBound != null) {
lowerBound = lowerBound.resolveBindings(scope, emptyBindings, false, false);
}
if (additionalInterfaceBounds != null) {
TypePattern[] resolvedIfBounds = new TypePattern[additionalInterfaceBounds.length];
for (int i = 0; i < resolvedIfBounds.length; i++) {
resolvedIfBounds[i] = additionalInterfaceBounds[i].resolveBindings(scope, emptyBindings, false, false);
}
additionalInterfaceBounds = resolvedIfBounds;
}
if ( upperBound == null && lowerBound == null && additionalInterfaceBounds == null) {
// no bounds to worry about...
ResolvedType rType = tvrType.resolve(scope.getWorld());
if (dim != 0) rType = ResolvedType.makeArray(rType, dim);
return new ExactTypePattern(rType,includeSubtypes,isVarArgs);
} else {
// we have to set bounds on the TypeVariable held by tvrType before resolving it
boolean canCreateExactTypePattern = true;
if (upperBound != null && ResolvedType.isMissing(upperBound.getExactType())) canCreateExactTypePattern = false;
if (lowerBound != null && ResolvedType.isMissing(lowerBound.getExactType())) canCreateExactTypePattern = false;
if (additionalInterfaceBounds != null) {
for (int i = 0; i < additionalInterfaceBounds.length; i++) {
if (ResolvedType.isMissing(additionalInterfaceBounds[i].getExactType())) canCreateExactTypePattern = false;
}
}
if (canCreateExactTypePattern) {
TypeVariable tv = tvrType.getTypeVariable();
if (upperBound != null) tv.setUpperBound(upperBound.getExactType());
if (lowerBound != null) tv.setLowerBound(lowerBound.getExactType());
if (additionalInterfaceBounds != null) {
UnresolvedType[] ifBounds = new UnresolvedType[additionalInterfaceBounds.length];
for (int i = 0; i < ifBounds.length; i++) {
ifBounds[i] = additionalInterfaceBounds[i].getExactType();
}
tv.setAdditionalInterfaceBounds(ifBounds);
}
ResolvedType rType = tvrType.resolve(scope.getWorld());
if (dim != 0) rType = ResolvedType.makeArray(rType, dim);
return new ExactTypePattern(rType,includeSubtypes,isVarArgs);
}
return this; // leave as wild type pattern then
}
}
/**
* When this method is called, we have resolved the base type to an exact type.
* We also have a set of type patterns for the parameters.
* Time to perform some basic checks:
* - can the base type be parameterized? (is it generic)
* - can the type parameter pattern list match the number of parameters on the base type
* - do all parameter patterns meet the bounds of the respective type variables
* If any of these checks fail, a warning message is issued and we return false.
* @return
*/
private boolean verifyTypeParameters(ResolvedType baseType,IScope scope, boolean requireExactType) {
ResolvedType genericType = baseType.getGenericType();
if (genericType == null) {
// issue message "does not match because baseType.getName() is not generic"
scope.message(MessageUtil.warn(
WeaverMessages.format(WeaverMessages.NOT_A_GENERIC_TYPE,baseType.getName()),
getSourceLocation()));
return false;
}
int minRequiredTypeParameters = typeParameters.size();
boolean foundEllipsis = false;
TypePattern[] typeParamPatterns = typeParameters.getTypePatterns();
for (int i = 0; i < typeParamPatterns.length; i++) {
if (typeParamPatterns[i] instanceof WildTypePattern) {
WildTypePattern wtp = (WildTypePattern) typeParamPatterns[i];
if (wtp.ellipsisCount > 0) {
foundEllipsis = true;
minRequiredTypeParameters--;
}
}
}
TypeVariable[] tvs = genericType.getTypeVariables();
if ((tvs.length < minRequiredTypeParameters) ||
(!foundEllipsis && minRequiredTypeParameters != tvs.length))
{
// issue message "does not match because wrong no of type params"
String msg = WeaverMessages.format(WeaverMessages.INCORRECT_NUMBER_OF_TYPE_ARGUMENTS,
genericType.getName(),new Integer(tvs.length));
if (requireExactType) scope.message(MessageUtil.error(msg,getSourceLocation()));
else scope.message(MessageUtil.warn(msg,getSourceLocation()));
return false;
}
// now check that each typeParameter pattern, if exact, matches the bounds
// of the type variable.
return checkBoundsOK(scope,genericType,requireExactType);
// return true;
}
public boolean checkBoundsOK(IScope scope,ResolvedType genericType,boolean requireExactType) {
if (boundscheckingoff) return true;
TypeVariable[] tvs = genericType.getTypeVariables();
TypePattern[] typeParamPatterns = typeParameters.getTypePatterns();
if (typeParameters.areAllExactWithNoSubtypesAllowed()) {
for (int i = 0; i < tvs.length; i++) {
UnresolvedType ut = typeParamPatterns[i].getExactType();
boolean continueCheck = true;
// FIXME asc dont like this but ok temporary measure. If the type parameter
// is itself a type variable (from the generic aspect) then assume it'll be
// ok... (see pr112105) Want to break this? Run GenericAspectK test.
if (ut.isTypeVariableReference()) {
continueCheck = false;
}
if (continueCheck &&
!tvs[i].canBeBoundTo(ut.resolve(scope.getWorld()))) {
// issue message that type parameter does not meet specification
String parameterName = ut.getName();
if (ut.isTypeVariableReference()) parameterName = ((TypeVariableReference)ut).getTypeVariable().getDisplayName();
String msg =
WeaverMessages.format(
WeaverMessages.VIOLATES_TYPE_VARIABLE_BOUNDS,
parameterName,
new Integer(i+1),
tvs[i].getDisplayName(),
genericType.getName());
if (requireExactType) scope.message(MessageUtil.error(msg,getSourceLocation()));
else scope.message(MessageUtil.warn(msg,getSourceLocation()));
return false;
}
}
}
return true;
}
public boolean isStar() {
boolean annPatternStar = annotationPattern == AnnotationTypePattern.ANY;
return (isNamePatternStar() && annPatternStar);
}
private boolean isNamePatternStar() {
return namePatterns.length == 1 && namePatterns[0].isAny();
}
/**
* returns those possible matches which I match exactly the last element of
*/
private String[] preMatch(String[] possibleMatches) {
//if (namePatterns.length != 1) return CollectionUtil.NO_STRINGS;
List ret = new ArrayList();
for (int i=0, len=possibleMatches.length; i < len; i++) {
char[][] names = splitNames(possibleMatches[i],true); //??? not most efficient
if (namePatterns[0].matches(names[names.length-1])) {
ret.add(possibleMatches[i]);
continue;
}
if (possibleMatches[i].indexOf("$") != -1) {
names = splitNames(possibleMatches[i],false); //??? not most efficient
if (namePatterns[0].matches(names[names.length-1])) {
ret.add(possibleMatches[i]);
}
}
}
return (String[])ret.toArray(new String[ret.size()]);
}
// public void postRead(ResolvedType enclosingType) {
// this.importedPrefixes = enclosingType.getImportedPrefixes();
// this.knownNames = prematch(enclosingType.getImportedNames());
// }
public String toString() {
StringBuffer buf = new StringBuffer();
if (annotationPattern != AnnotationTypePattern.ANY) {
buf.append('(');
buf.append(annotationPattern.toString());
buf.append(' ');
}
for (int i=0, len=namePatterns.length; i < len; i++) {
NamePattern name = namePatterns[i];
if (name == null) {
buf.append(".");
} else {
if (i > 0) buf.append(".");
buf.append(name.toString());
}
}
if (upperBound != null) {
buf.append(" extends ");
buf.append(upperBound.toString());
}
if (lowerBound != null) {
buf.append(" super ");
buf.append(lowerBound.toString());
}
if (typeParameters!=null && typeParameters.size()!=0) {
buf.append("<");
buf.append(typeParameters.toString());
buf.append(">");
}
if (includeSubtypes) buf.append('+');
if (isVarArgs) buf.append("...");
if (annotationPattern != AnnotationTypePattern.ANY) {
buf.append(')');
}
return buf.toString();
}
public boolean equals(Object other) {
if (!(other instanceof WildTypePattern)) return false;
WildTypePattern o = (WildTypePattern)other;
int len = o.namePatterns.length;
if (len != this.namePatterns.length) return false;
if (this.includeSubtypes != o.includeSubtypes) return false;
if (this.dim != o.dim) return false;
if (this.isVarArgs != o.isVarArgs) return false;
if (this.upperBound != null) {
if (o.upperBound == null) return false;
if (!this.upperBound.equals(o.upperBound)) return false;
} else {
if (o.upperBound != null) return false;
}
if (this.lowerBound != null) {
if (o.lowerBound == null) return false;
if (!this.lowerBound.equals(o.lowerBound)) return false;
} else {
if (o.lowerBound != null) return false;
}
if (!typeParameters.equals(o.typeParameters)) return false;
for (int i=0; i < len; i++) {
if (!o.namePatterns[i].equals(this.namePatterns[i])) return false;
}
return (o.annotationPattern.equals(this.annotationPattern));
}
public int hashCode() {
int result = 17;
for (int i = 0, len = namePatterns.length; i < len; i++) {
result = 37*result + namePatterns[i].hashCode();
}
result = 37*result + annotationPattern.hashCode();
if (upperBound != null) result = 37*result + upperBound.hashCode();
if (lowerBound != null) result = 37*result + lowerBound.hashCode();
return result;
}
private static final byte VERSION = 1; // rev on change
/**
* @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream)
*/
public void write(DataOutputStream s) throws IOException {
s.writeByte(TypePattern.WILD);
s.writeByte(VERSION);
s.writeShort(namePatterns.length);
for (int i = 0; i < namePatterns.length; i++) {
namePatterns[i].write(s);
}
s.writeBoolean(includeSubtypes);
s.writeInt(dim);
s.writeBoolean(isVarArgs);
typeParameters.write(s); // ! change from M2
//??? storing this information with every type pattern is wasteful of .class
// file size. Storing it on enclosing types would be more efficient
FileUtil.writeStringArray(knownMatches, s);
FileUtil.writeStringArray(importedPrefixes, s);
writeLocation(s);
annotationPattern.write(s);
// generics info, new in M3
s.writeBoolean(isGeneric);
s.writeBoolean(upperBound != null);
if (upperBound != null) upperBound.write(s);
s.writeBoolean(lowerBound != null);
if (lowerBound != null) lowerBound.write(s);
s.writeInt(additionalInterfaceBounds == null ? 0 : additionalInterfaceBounds.length);
if (additionalInterfaceBounds != null) {
for (int i = 0; i < additionalInterfaceBounds.length; i++) {
additionalInterfaceBounds[i].write(s);
}
}
}
public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException {
if (s.getMajorVersion()>=AjAttribute.WeaverVersionInfo.WEAVER_VERSION_MAJOR_AJ150) {
return readTypePattern150(s,context);
} else {
return readTypePatternOldStyle(s,context);
}
}
public static TypePattern readTypePattern150(VersionedDataInputStream s, ISourceContext context) throws IOException {
byte version = s.readByte();
if (version > VERSION) {
throw new BCException("WildTypePattern was written by a more recent version of AspectJ, cannot read");
}
int len = s.readShort();
NamePattern[] namePatterns = new NamePattern[len];
for (int i=0; i < len; i++) {
namePatterns[i] = NamePattern.read(s);
}
boolean includeSubtypes = s.readBoolean();
int dim = s.readInt();
boolean varArg = s.readBoolean();
TypePatternList typeParams = TypePatternList.read(s, context);
WildTypePattern ret = new WildTypePattern(namePatterns, includeSubtypes, dim, varArg,typeParams);
ret.knownMatches = FileUtil.readStringArray(s);
ret.importedPrefixes = FileUtil.readStringArray(s);
ret.readLocation(context, s);
ret.setAnnotationTypePattern(AnnotationTypePattern.read(s,context));
// generics info, new in M3
ret.isGeneric = s.readBoolean();
if (s.readBoolean()) {
ret.upperBound = TypePattern.read(s,context);
}
if (s.readBoolean()) {
ret.lowerBound = TypePattern.read(s,context);
}
int numIfBounds = s.readInt();
if (numIfBounds > 0) {
ret.additionalInterfaceBounds = new TypePattern[numIfBounds];
for (int i = 0; i < numIfBounds; i++) {
ret.additionalInterfaceBounds[i] = TypePattern.read(s,context);
}
}
return ret;
}
public static TypePattern readTypePatternOldStyle(VersionedDataInputStream s, ISourceContext context) throws IOException {
int len = s.readShort();
NamePattern[] namePatterns = new NamePattern[len];
for (int i=0; i < len; i++) {
namePatterns[i] = NamePattern.read(s);
}
boolean includeSubtypes = s.readBoolean();
int dim = s.readInt();
WildTypePattern ret = new WildTypePattern(namePatterns, includeSubtypes, dim, false,null);
ret.knownMatches = FileUtil.readStringArray(s);
ret.importedPrefixes = FileUtil.readStringArray(s);
ret.readLocation(context, s);
return ret;
}
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
}
|
132,160 |
Bug 132160 NPE in SingleTypeReference
|
I was C&P'ing the guts of another aspect into a new file (from another project that I'm porting over). There are a number of errors in the aspect (as most of the references point to the other project). I just changed an object from one type (in the other project) to a type in the project that the file is in. Eclipse SDK Version: 3.1.2 Build id: M20060118-1600 Version: 1.3.0 Build id: 20051220093604 AspectJ version: 1.5.0 ---------------------------------------------------------------- java.lang.NullPointerException at org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference.getTypeBinding(SingleTypeReference.java:39) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference.getTypeBindingPublic(TypeReference.java:98) at org.aspectj.ajdt.internal.core.builder.AsmElementFormatter.genLabelAndKind(AsmElementFormatter.java:230) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.visit(AsmHierarchyBuilder.java:399) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.traverse(MethodDeclaration.java:185) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.traverse(TypeDeclaration.java:1250) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedAllocationExpression.traverse(QualifiedAllocationExpression.java:392) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration.traverse(LocalDeclaration.java:242) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.traverse(MethodDeclaration.java:212) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.traverse(TypeDeclaration.java:1195) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.traverse(CompilationUnitDeclaration.java:339) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.internalBuild(AsmHierarchyBuilder.java:142) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.buildStructureForCompilationUnit(AsmHierarchyBuilder.java:82) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.finishedCompilationUnit(EclipseFactory.java:926) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterProcessing(AjCompilerAdapter.java:195) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$4$6b855184(CompilerAdapter.aj:89) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:528) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:811) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:230) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:185) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
|
resolved fixed
|
91473b3
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-27T19:11:57Z | 2006-03-16T14:40:00Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmElementFormatter.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur support for @AJ style
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.DeclareDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeConstructorDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeFieldDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.InterTypeMethodDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration;
import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment;
import org.aspectj.asm.IProgramElement;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.patterns.AndPointcut;
import org.aspectj.weaver.patterns.DeclareAnnotation;
import org.aspectj.weaver.patterns.DeclareErrorOrWarning;
import org.aspectj.weaver.patterns.DeclareParents;
import org.aspectj.weaver.patterns.DeclarePrecedence;
import org.aspectj.weaver.patterns.DeclareSoft;
import org.aspectj.weaver.patterns.OrPointcut;
import org.aspectj.weaver.patterns.ReferencePointcut;
import org.aspectj.weaver.patterns.TypePattern;
import org.aspectj.weaver.patterns.TypePatternList;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation;
/**
* @author Mik Kersten
*/
public class AsmElementFormatter {
public static final String UNDEFINED="<undefined>";
public static final String DECLARE_PRECEDENCE = "precedence";
public static final String DECLARE_SOFT = "soft";
public static final String DECLARE_PARENTS = "parents";
public static final String DECLARE_WARNING = "warning";
public static final String DECLARE_ERROR = "error";
public static final String DECLARE_UNKNONWN = "<unknown declare>";
public static final String POINTCUT_ABSTRACT = "<abstract pointcut>";
public static final String POINTCUT_ANONYMOUS = "<anonymous pointcut>";
public static final String DOUBLE_DOTS = "..";
public static final int MAX_MESSAGE_LENGTH = 18;
public static final String DEC_LABEL = "declare";
public void genLabelAndKind(MethodDeclaration methodDeclaration, IProgramElement node) {
if (methodDeclaration instanceof AdviceDeclaration) {
AdviceDeclaration ad = (AdviceDeclaration)methodDeclaration;
node.setKind(IProgramElement.Kind.ADVICE);
if (ad.kind == AdviceKind.Around) {
node.setCorrespondingType(ad.returnType.toString()); //returnTypeToString(0));
}
StringBuffer details = new StringBuffer();
if (ad.pointcutDesignator != null) {
if (ad.pointcutDesignator.getPointcut() instanceof ReferencePointcut) {
ReferencePointcut rp = (ReferencePointcut)ad.pointcutDesignator.getPointcut();
details.append(rp.name).append("..");
} else if (ad.pointcutDesignator.getPointcut() instanceof AndPointcut) {
AndPointcut ap = (AndPointcut)ad.pointcutDesignator.getPointcut();
if (ap.getLeft() instanceof ReferencePointcut) {
details.append(ap.getLeft().toString()).append(DOUBLE_DOTS);
} else {
details.append(POINTCUT_ANONYMOUS).append(DOUBLE_DOTS);
}
} else if (ad.pointcutDesignator.getPointcut() instanceof OrPointcut) {
OrPointcut op = (OrPointcut)ad.pointcutDesignator.getPointcut();
if (op.getLeft() instanceof ReferencePointcut) {
details.append(op.getLeft().toString()).append(DOUBLE_DOTS);
} else {
details.append(POINTCUT_ANONYMOUS).append(DOUBLE_DOTS);
}
} else {
details.append(POINTCUT_ANONYMOUS);
}
} else {
details.append(POINTCUT_ABSTRACT);
}
node.setName(ad.kind.toString());
//if (details.length()!=0)
node.setDetails(details.toString());
setParameters(methodDeclaration, node);
} else if (methodDeclaration instanceof PointcutDeclaration) {
PointcutDeclaration pd = (PointcutDeclaration)methodDeclaration;
node.setKind(IProgramElement.Kind.POINTCUT);
node.setName(translatePointcutName(new String(methodDeclaration.selector)));
setParameters(methodDeclaration, node);
} else if (methodDeclaration instanceof DeclareDeclaration) {
DeclareDeclaration declare = (DeclareDeclaration)methodDeclaration;
String name = DEC_LABEL + " ";
if (declare.declareDecl instanceof DeclareErrorOrWarning) {
DeclareErrorOrWarning deow = (DeclareErrorOrWarning)declare.declareDecl;
if (deow.isError()) {
node.setKind( IProgramElement.Kind.DECLARE_ERROR);
name += DECLARE_ERROR;
} else {
node.setKind( IProgramElement.Kind.DECLARE_WARNING);
name += DECLARE_WARNING;
}
node.setName(name) ;
node.setDetails("\"" + genDeclareMessage(deow.getMessage()) + "\"");
} else if (declare.declareDecl instanceof DeclareParents) {
node.setKind( IProgramElement.Kind.DECLARE_PARENTS);
DeclareParents dp = (DeclareParents)declare.declareDecl;
node.setName(name + DECLARE_PARENTS);
String kindOfDP = null;
StringBuffer details = new StringBuffer("");
TypePattern[] newParents = dp.getParents().getTypePatterns();
for (int i = 0; i < newParents.length; i++) {
TypePattern tp = newParents[i];
UnresolvedType tx = tp.getExactType();
if (kindOfDP == null) {
kindOfDP = "implements ";
try {
ResolvedType rtx = tx.resolve(((AjLookupEnvironment)declare.scope.environment()).factory.getWorld());
if (!rtx.isInterface()) kindOfDP = "extends ";
} catch (Throwable t) {
// What can go wrong???? who knows!
}
}
String typename= tp.toString();
if (typename.lastIndexOf(".")!=-1) {
typename=typename.substring(typename.lastIndexOf(".")+1);
}
details.append(typename);
if ((i+1)<newParents.length) details.append(",");
}
node.setDetails(kindOfDP+details.toString());
} else if (declare.declareDecl instanceof DeclareSoft) {
node.setKind( IProgramElement.Kind.DECLARE_SOFT);
DeclareSoft ds = (DeclareSoft)declare.declareDecl;
node.setName(name + DECLARE_SOFT);
node.setDetails(genTypePatternLabel(ds.getException()));
} else if (declare.declareDecl instanceof DeclarePrecedence) {
node.setKind( IProgramElement.Kind.DECLARE_PRECEDENCE);
DeclarePrecedence ds = (DeclarePrecedence)declare.declareDecl;
node.setName(name + DECLARE_PRECEDENCE);
node.setDetails(genPrecedenceListLabel(ds.getPatterns()));
} else if (declare.declareDecl instanceof DeclareAnnotation) {
DeclareAnnotation deca = (DeclareAnnotation)declare.declareDecl;
String thekind = deca.getKind().toString();
node.setName(name+"@"+thekind.substring(3));
if (deca.getKind()==DeclareAnnotation.AT_CONSTRUCTOR) {
node.setKind(IProgramElement.Kind.DECLARE_ANNOTATION_AT_CONSTRUCTOR);
} else if (deca.getKind()==DeclareAnnotation.AT_FIELD) {
node.setKind(IProgramElement.Kind.DECLARE_ANNOTATION_AT_FIELD);
} else if (deca.getKind()==DeclareAnnotation.AT_METHOD) {
node.setKind(IProgramElement.Kind.DECLARE_ANNOTATION_AT_METHOD);
} else if (deca.getKind()==DeclareAnnotation.AT_TYPE) {
node.setKind(IProgramElement.Kind.DECLARE_ANNOTATION_AT_TYPE);
}
node.setDetails(genDecaLabel(deca));
} else {
node.setKind(IProgramElement.Kind.ERROR);
node.setName(DECLARE_UNKNONWN);
}
} else if (methodDeclaration instanceof InterTypeDeclaration) {
InterTypeDeclaration itd = (InterTypeDeclaration)methodDeclaration;
String name = itd.getOnType().toString() + "." + new String(itd.getDeclaredSelector());
if (methodDeclaration instanceof InterTypeFieldDeclaration) {
node.setKind(IProgramElement.Kind.INTER_TYPE_FIELD);
node.setName(name);
} else if (methodDeclaration instanceof InterTypeMethodDeclaration) {
node.setKind(IProgramElement.Kind.INTER_TYPE_METHOD);
node.setName(name);
} else if (methodDeclaration instanceof InterTypeConstructorDeclaration) {
node.setKind(IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR);
// StringBuffer argumentsSignature = new StringBuffer("fubar");
// argumentsSignature.append("(");
// if (methodDeclaration.arguments!=null && methodDeclaration.arguments.length>1) {
//
// for (int i = 1;i<methodDeclaration.arguments.length;i++) {
// argumentsSignature.append(methodDeclaration.arguments[i]);
// if (i+1<methodDeclaration.arguments.length) argumentsSignature.append(",");
// }
// }
// argumentsSignature.append(")");
// InterTypeConstructorDeclaration itcd = (InterTypeConstructorDeclaration)methodDeclaration;
node.setName(itd.getOnType().toString() + "." + itd.getOnType().toString()/*+argumentsSignature.toString()*/);
} else {
node.setKind(IProgramElement.Kind.ERROR);
node.setName(name);
}
node.setCorrespondingType(itd.returnType.toString());
if (node.getKind() != IProgramElement.Kind.INTER_TYPE_FIELD) {
setParameters(methodDeclaration, node);
}
} else {
if (methodDeclaration.isConstructor()) {
node.setKind(IProgramElement.Kind.CONSTRUCTOR);
} else {
node.setKind(IProgramElement.Kind.METHOD);
//TODO AV - could speed up if we could dig only for @Aspect declaring types (or aspect if mixed style allowed)
//??? how to : node.getParent().getKind().equals(IProgramElement.Kind.ASPECT)) {
if (true && methodDeclaration!=null && methodDeclaration.annotations != null) {
for (int i = 0; i < methodDeclaration.annotations.length; i++) {
//Note: AV: implicit single advice type support here (should be enforced somewhere as well (APT etc))
Annotation annotation = methodDeclaration.annotations[i];
String annotationSig = new String(annotation.type.getTypeBindingPublic(methodDeclaration.scope).signature());
if (annotationSig!=null && annotationSig.charAt(1)=='o') {
if ("Lorg/aspectj/lang/annotation/Pointcut;".equals(annotationSig)) {
node.setKind(IProgramElement.Kind.POINTCUT);
break;
} else if ("Lorg/aspectj/lang/annotation/Before;".equals(annotationSig)
|| "Lorg/aspectj/lang/annotation/After;".equals(annotationSig)
|| "Lorg/aspectj/lang/annotation/AfterReturning;".equals(annotationSig)
|| "Lorg/aspectj/lang/annotation/AfterThrowing;".equals(annotationSig)
|| "Lorg/aspectj/lang/annotation/Around;".equals(annotationSig)) {
node.setKind(IProgramElement.Kind.ADVICE);
//TODO AV - all are considered anonymous - is that ok?
node.setDetails(POINTCUT_ANONYMOUS);
break;
}
}
}
}
}
node.setName(new String(methodDeclaration.selector));
setParameters(methodDeclaration, node);
}
}
private String genDecaLabel(DeclareAnnotation deca) {
StringBuffer sb = new StringBuffer("");
sb.append(deca.getPatternAsString());
sb.append(" : ");
sb.append(deca.getAnnotationString());
return sb.toString();
}
private String genPrecedenceListLabel(TypePatternList list) {
String tpList = "";
for (int i = 0; i < list.size(); i++) {
tpList += genTypePatternLabel(list.get(i));
if (i < list.size()-1) tpList += ", ";
}
return tpList;
}
// private String genArguments(MethodDeclaration md) {
// String args = "";
// Argument[] argArray = md.arguments;
// if (argArray == null) return args;
// for (int i = 0; i < argArray.length; i++) {
// String argName = new String(argArray[i].name);
// String argType = argArray[i].type.toString();
// if (acceptArgument(argName, argType)) {
// args += argType + ", ";
// }
// }
// int lastSepIndex = args.lastIndexOf(',');
// if (lastSepIndex != -1 && args.endsWith(", ")) args = args.substring(0, lastSepIndex);
// return args;
// }
private void setParameters(MethodDeclaration md, IProgramElement pe) {
Argument[] argArray = md.arguments;
if (argArray == null) {
pe.setParameterNames(Collections.EMPTY_LIST);
pe.setParameterTypes(Collections.EMPTY_LIST);
} else {
List names = new ArrayList();
List types = new ArrayList();
for (int i = 0; i < argArray.length; i++) {
String argName = new String(argArray[i].name);
String argType = argArray[i].type.resolvedType.debugName();
if (acceptArgument(argName, argArray[i].type.toString())) {
names.add(argName);
types.add(argType);
}
}
pe.setParameterNames(names);
pe.setParameterTypes(types);
}
}
// TODO: fix this way of determing ajc-added arguments, make subtype of Argument with extra info
private boolean acceptArgument(String name, String type) {
if (name.charAt(0)!='a' && type.charAt(0)!='o') return true;
return !name.startsWith("ajc$this_")
&& !type.equals("org.aspectj.lang.JoinPoint.StaticPart")
&& !type.equals("org.aspectj.lang.JoinPoint")
&& !type.equals("org.aspectj.runtime.internal.AroundClosure");
}
public String genTypePatternLabel(TypePattern tp) {
final String TYPE_PATTERN_LITERAL = "<type pattern>";
String label;
UnresolvedType typeX = tp.getExactType();
if (!ResolvedType.isMissing(typeX)) {
label = typeX.getName();
if (tp.isIncludeSubtypes()) label += "+";
} else {
label = TYPE_PATTERN_LITERAL;
}
return label;
}
public String genDeclareMessage(String message) {
int length = message.length();
if (length < MAX_MESSAGE_LENGTH) {
return message;
} else {
return message.substring(0, MAX_MESSAGE_LENGTH-1) + "..";
}
}
// // TODO:
// private String translateAdviceName(String label) {
// if (label.indexOf("before") != -1) return "before";
// if (label.indexOf("returning") != -1) return "after returning";
// if (label.indexOf("after") != -1) return "after";
// if (label.indexOf("around") != -1) return "around";
// else return "<advice>";
// }
// // !!! move or replace
// private String translateDeclareName(String name) {
// int colonIndex = name.indexOf(":");
// if (colonIndex != -1) {
// return name.substring(0, colonIndex);
// } else {
// return name;
// }
// }
// !!! move or replace
// private String translateInterTypeDecName(String name) {
// int index = name.lastIndexOf('$');
// if (index != -1) {
// return name.substring(index+1);
// } else {
// return name;
// }
// }
// !!! move or replace
private String translatePointcutName(String name) {
int index = name.indexOf("$$")+2;
int endIndex = name.lastIndexOf('$');
if (index != -1 && endIndex != -1) {
return name.substring(index, endIndex);
} else {
return name;
}
}
}
|
132,087 |
Bug 132087 NPE from unbound variable in advice
|
I get this error from having an unbound reference to a variable in an aspect. See attached AJDT project for an example. java.lang.NullPointerException at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.visit(AsmHierarchyBuilder.java:412) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.traverse(MethodDeclaration.java:185) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.traverse(TypeDeclaration.java:1250) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedAllocationExpression.traverse(QualifiedAllocationExpression.java:392) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration.traverse(LocalDeclaration.java:242) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.traverse(MethodDeclaration.java:212) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.traverse(TypeDeclaration.java:1195) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.traverse(CompilationUnitDeclaration.java:339) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.internalBuild(AsmHierarchyBuilder.java:143) at org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder.buildStructureForCompilationUnit(AsmHierarchyBuilder.java:82) at org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory.finishedCompilationUnit(EclipseFactory.java:927) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterProcessing(AjCompilerAdapter.java:201) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$4$6b855184(CompilerAdapter.aj:90) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:528) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:843) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:243) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:163) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
|
resolved fixed
|
fa2ed1b
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-27T21:39:46Z | 2006-03-16T03:33:20Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmHierarchyBuilder.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the 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
* Mik Kersten revisions, added additional relationships
* Alexandre Vasseur support for @AJ style
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.File;
import java.io.IOException;
import java.util.*;
import org.aspectj.ajdt.internal.compiler.ast.*;
import org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.asm.*;
import org.aspectj.asm.internal.ProgramElement;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ASTVisitor;
import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.*;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IGenericType;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.*;
import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemHandler;
import org.aspectj.util.LangUtil;
import org.aspectj.weaver.*;
import org.aspectj.weaver.patterns.*;
/**
* At each iteration of <CODE>processCompilationUnit</CODE> the declarations for a
* particular compilation unit are added to the hierarchy passed as a a parameter.
* <p>
* Clients who extend this class need to ensure that they do not override any of the existing
* behavior. If they do, the structure model will not be built properly and tools such as IDE
* structure views and ajdoc will fail.
* <p>
* <b>Note:</b> this class is not considered public API and the overridable
* methods are subject to change.
*
* @author Mik Kersten
*/
public class AsmHierarchyBuilder extends ASTVisitor {
protected AsmElementFormatter formatter = new AsmElementFormatter();
/**
* Reset for every compilation unit.
*/
protected AjBuildConfig buildConfig;
/**
* Reset for every compilation unit.
*/
protected Stack stack;
/**
* Reset for every compilation unit.
*/
private CompilationResult currCompilationResult;
private String filename;
int[] lineseps;
/**
*
* @param cuDeclaration
* @param buildConfig
* @param structureModel hiearchy to add this unit's declarations to
*/
public void buildStructureForCompilationUnit(CompilationUnitDeclaration cuDeclaration, IHierarchy structureModel, AjBuildConfig buildConfig) {
currCompilationResult = cuDeclaration.compilationResult();
filename = new String(currCompilationResult.fileName);
lineseps = currCompilationResult.lineSeparatorPositions;
LangUtil.throwIaxIfNull(currCompilationResult, "result");
stack = new Stack();
this.buildConfig = buildConfig;
internalBuild(cuDeclaration, structureModel);
this.buildConfig = null; // clear reference since this structure is anchored in static
currCompilationResult=null;
stack.clear();
// throw new RuntimeException("not implemented");
}
private void internalBuild(CompilationUnitDeclaration unit, IHierarchy structureModel) {
LangUtil.throwIaxIfNull(structureModel, "structureModel");
// if (!currCompilationResult.equals(unit.compilationResult())) {
// throw new IllegalArgumentException("invalid unit: " + unit);
// }
// ---- summary
// add unit to package (or root if no package),
// first removing any duplicate (XXX? removes children if 3 classes in same file?)
// push the node on the stack
// and traverse
// -- create node to add
final File file = new File(new String(unit.getFileName()));
final IProgramElement cuNode;
{
// AMC - use the source start and end from the compilation unit decl
int startLine = getStartLine(unit);
int endLine = getEndLine(unit);
SourceLocation sourceLocation
= new SourceLocation(file, startLine, endLine);
sourceLocation.setOffset(unit.sourceStart);
cuNode = new ProgramElement(
new String(file.getName()),
IProgramElement.Kind.FILE_JAVA,
sourceLocation,
0,null,null);
}
cuNode.addChild(new ProgramElement(
"import declarations",
IProgramElement.Kind.IMPORT_REFERENCE,
null,0,null,null));
final IProgramElement addToNode = genAddToNode(unit, structureModel);
// -- remove duplicates before adding (XXX use them instead?)
if (addToNode!=null && addToNode.getChildren()!=null) {
for (ListIterator itt = addToNode.getChildren().listIterator(); itt.hasNext(); ) {
IProgramElement child = (IProgramElement)itt.next();
ISourceLocation childLoc = child.getSourceLocation();
if (null == childLoc) {
// XXX ok, packages have null source locations
// signal others?
} else if (childLoc.getSourceFile().equals(file)) {
itt.remove();
}
}
}
// -- add and traverse
addToNode.addChild(cuNode);
stack.push(cuNode);
unit.traverse(this, unit.scope);
// -- update file map (XXX do this before traversal?)
try {
structureModel.addToFileMap(file.getCanonicalPath(), cuNode);
} catch (IOException e) {
System.err.println("IOException " + e.getMessage()
+ " creating path for " + file );
// XXX signal IOException when canonicalizing file path
}
}
/**
* Get/create the node (package or root) to add to.
*/
private IProgramElement genAddToNode(
CompilationUnitDeclaration unit,
IHierarchy structureModel) {
final IProgramElement addToNode;
{
ImportReference currentPackage = unit.currentPackage;
if (null == currentPackage) {
addToNode = structureModel.getRoot();
} else {
String pkgName;
{
StringBuffer nameBuffer = new StringBuffer();
final char[][] importName = currentPackage.getImportName();
final int last = importName.length-1;
for (int i = 0; i < importName.length; i++) {
nameBuffer.append(new String(importName[i]));
if (i < last) {
nameBuffer.append('.');
}
}
pkgName = nameBuffer.toString();
}
IProgramElement pkgNode = null;
if (structureModel!=null && structureModel.getRoot()!=null && structureModel.getRoot().getChildren()!=null) {
for (Iterator it = structureModel.getRoot().getChildren().iterator();
it.hasNext(); ) {
IProgramElement currNode = (IProgramElement)it.next();
if (pkgName.equals(currNode.getName())) {
pkgNode = currNode;
break;
}
}
}
if (pkgNode == null) {
// note packages themselves have no source location
pkgNode = new ProgramElement(
pkgName,
IProgramElement.Kind.PACKAGE,
new ArrayList()
);
structureModel.getRoot().addChild(pkgNode);
}
addToNode = pkgNode;
}
}
return addToNode;
}
public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
String name = new String(typeDeclaration.name);
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (typeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT;
else if (typeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE;
else if (typeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM;
else if (typeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION;
//@AJ support
if (typeDeclaration.annotations != null) {
for (int i = 0; i < typeDeclaration.annotations.length; i++) {
Annotation annotation = typeDeclaration.annotations[i];
if (Arrays.equals(annotation.type.getTypeBindingPublic(scope).signature(),
"Lorg/aspectj/lang/annotation/Aspect;".toCharArray())) {
kind = IProgramElement.Kind.ASPECT;
}
}
}
int typeModifiers = typeDeclaration.modifiers;
if (typeDeclaration instanceof AspectDeclaration) {
typeModifiers = ((AspectDeclaration)typeDeclaration).getDeclaredModifiers();
}
IProgramElement peNode = new ProgramElement(
name,
kind,
makeLocation(typeDeclaration),
typeModifiers, null,null);
peNode.setSourceSignature(genSourceSignature(typeDeclaration));
peNode.setFormalComment(generateJavadocComment(typeDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
stack.pop();
}
// ??? share impl with visit(TypeDeclaration, ..) ?
public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
String name = new String(memberTypeDeclaration.name);
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (memberTypeDeclaration instanceof AspectDeclaration) kind = IProgramElement.Kind.ASPECT;
else if (memberTypeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE;
else if (memberTypeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM;
else if (memberTypeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION;
//@AJ support
if (memberTypeDeclaration.annotations != null) {
for (int i = 0; i < memberTypeDeclaration.annotations.length; i++) {
Annotation annotation = memberTypeDeclaration.annotations[i];
if (Arrays.equals(annotation.type.getTypeBindingPublic(scope).signature(),
"Lorg/aspectj/lang/annotation/Aspect;".toCharArray())) {
kind = IProgramElement.Kind.ASPECT;
}
}
}
int typeModifiers = memberTypeDeclaration.modifiers;
if (memberTypeDeclaration instanceof AspectDeclaration) {
typeModifiers = ((AspectDeclaration)memberTypeDeclaration).getDeclaredModifiers();
}
IProgramElement peNode = new ProgramElement(
name,
kind,
makeLocation(memberTypeDeclaration),
typeModifiers,null,null);
peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration));
peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration memberTypeDeclaration, ClassScope scope) {
stack.pop();
}
public boolean visit(TypeDeclaration memberTypeDeclaration, BlockScope scope) {
String fullName = "<undefined>";
if (memberTypeDeclaration.allocation != null
&& memberTypeDeclaration.allocation.type != null) {
// Create a name something like 'new Runnable() {..}'
fullName = "new "+memberTypeDeclaration.allocation.type.toString()+"() {..}";
} else if (memberTypeDeclaration.binding != null
&& memberTypeDeclaration.binding.constantPoolName() != null) {
// If we couldn't find a nice name like 'new Runnable() {..}' then use the number after the $
fullName = new String(memberTypeDeclaration.binding.constantPoolName());
int dollar = fullName.indexOf('$');
fullName = fullName.substring(dollar+1);
}
IProgramElement.Kind kind = IProgramElement.Kind.CLASS;
if (memberTypeDeclaration.kind() == IGenericType.INTERFACE_DECL) kind = IProgramElement.Kind.INTERFACE;
else if (memberTypeDeclaration.kind() == IGenericType.ENUM_DECL) kind = IProgramElement.Kind.ENUM;
else if (memberTypeDeclaration.kind() == IGenericType.ANNOTATION_TYPE_DECL) kind = IProgramElement.Kind.ANNOTATION;
//@AJ support
if (memberTypeDeclaration.annotations != null) {
for (int i = 0; i < memberTypeDeclaration.annotations.length; i++) {
Annotation annotation = memberTypeDeclaration.annotations[i];
if (Arrays.equals(annotation.type.getTypeBindingPublic(scope).signature(),
"Lorg/aspectj/lang/annotation/Aspect;".toCharArray())) {
kind = IProgramElement.Kind.ASPECT;
break;
}
}
}
IProgramElement peNode = new ProgramElement(
fullName,
kind,
makeLocation(memberTypeDeclaration),
memberTypeDeclaration.modifiers,null,null);
peNode.setSourceSignature(genSourceSignature(memberTypeDeclaration));
peNode.setFormalComment(generateJavadocComment(memberTypeDeclaration));
// if we're something like 'new Runnable(){..}' then set the
// bytecodeSignature to be the typename so we can match it later
// when creating the structure model
if (peNode.getBytecodeSignature() == null
&& memberTypeDeclaration.binding != null
&& memberTypeDeclaration.binding.constantPoolName() != null) {
StringTokenizer st = new StringTokenizer(
new String(memberTypeDeclaration.binding.constantPoolName()),"/");
while(st.hasMoreTokens()) {
String s = st.nextToken();
if (!st.hasMoreTokens()) {
peNode.setBytecodeSignature(s);
}
}
}
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(TypeDeclaration memberTypeDeclaration, BlockScope scope) {
stack.pop();
}
private String genSourceSignature(TypeDeclaration typeDeclaration) {
StringBuffer output = new StringBuffer();
typeDeclaration.printHeader(0, output);
return output.toString();
}
private IProgramElement findEnclosingClass(Stack stack) {
for (int i = stack.size()-1; i >= 0; i--) {
IProgramElement pe = (IProgramElement)stack.get(i);
if (pe.getKind() == IProgramElement.Kind.CLASS) {
return pe;
}
}
return (IProgramElement)stack.peek();
}
public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) {
IProgramElement peNode = null;
// For intertype decls, use the modifiers from the original signature, not the generated method
if (methodDeclaration instanceof InterTypeDeclaration) {
InterTypeDeclaration itd = (InterTypeDeclaration) methodDeclaration;
ResolvedMember sig = itd.getSignature();
peNode = new ProgramElement(
null,
IProgramElement.Kind.ERROR,
makeLocation(methodDeclaration),
(sig!=null?sig.getModifiers():0),null,null);
} else {
peNode = new ProgramElement(
null,
IProgramElement.Kind.ERROR,
makeLocation(methodDeclaration),
methodDeclaration.modifiers,null,null);
}
formatter.genLabelAndKind(methodDeclaration, peNode); // will set the name
genBytecodeInfo(methodDeclaration, peNode);
List namedPointcuts = genNamedPointcuts(methodDeclaration);
addUsesPointcutRelationsForNode(peNode, namedPointcuts, methodDeclaration);
if (methodDeclaration.returnType!=null) {
// if we don't make the distinction between ITD fields and other
// methods, then we loose the type, for example int, for the field
// and instead get "void".
if (peNode.getKind().equals(IProgramElement.Kind.INTER_TYPE_FIELD)) {
peNode.setCorrespondingType(methodDeclaration.returnType.toString());
} else {
peNode.setCorrespondingType(methodDeclaration.returnType.resolvedType.debugName());
}
} else {
peNode.setCorrespondingType(null);
}
peNode.setSourceSignature(genSourceSignature(methodDeclaration));
peNode.setFormalComment(generateJavadocComment(methodDeclaration));
// TODO: add return type test
if (peNode.getKind().equals(IProgramElement.Kind.METHOD)) {
if ((peNode.getName().charAt(0)=='m') &&
(peNode.toLabelString().equals("main(String[])")
|| peNode.toLabelString().equals("main(java.lang.String[])"))
&& peNode.getModifiers().contains(IProgramElement.Modifiers.STATIC)
&& peNode.getAccessibility().equals(IProgramElement.Accessibility.PUBLIC)) {
((IProgramElement)stack.peek()).setRunnable(true);
}
}
stack.push(peNode);
return true;
}
private void addUsesPointcutRelationsForNode(IProgramElement peNode, List namedPointcuts, MethodDeclaration declaration) {
for (Iterator it = namedPointcuts.iterator(); it.hasNext();) {
ReferencePointcut rp = (ReferencePointcut) it.next();
ResolvedMember member = getPointcutDeclaration(rp, declaration);
if (member != null) {
IRelationship foreward = AsmManager.getDefault().getRelationshipMap().get(peNode.getHandleIdentifier(), IRelationship.Kind.USES_POINTCUT, "uses pointcut", false, true);
foreward.addTarget(AsmManager.getDefault().getHandleProvider().createHandleIdentifier(member.getSourceLocation()));
IRelationship back = AsmManager.getDefault().getRelationshipMap().get(AsmManager.getDefault().getHandleProvider().createHandleIdentifier(member.getSourceLocation()), IRelationship.Kind.USES_POINTCUT, "pointcut used by", false, true);
back.addTarget(peNode.getHandleIdentifier());
}
}
}
private ResolvedMember getPointcutDeclaration(ReferencePointcut rp, MethodDeclaration declaration) {
EclipseFactory factory = ((AjLookupEnvironment)declaration.scope.environment()).factory;
World world = factory.getWorld();
UnresolvedType onType = rp.onType;
if (onType == null) {
if (declaration.binding != null) {
Member member = factory.makeResolvedMember(declaration.binding);
onType = member.getDeclaringType();
} else {
return null;
}
}
ResolvedMember[] members = onType.resolve(world).getDeclaredPointcuts();
if (members != null) {
for (int i = 0; i < members.length; i++) {
if (members[i].getName().equals(rp.name)) {
return members[i];
}
}
}
return null;
}
/**
* @param methodDeclaration
* @return all of the named pointcuts referenced by the PCD of this declaration
*/
private List genNamedPointcuts(MethodDeclaration methodDeclaration) {
List pointcuts = new ArrayList();
if (methodDeclaration instanceof AdviceDeclaration) {
if (((AdviceDeclaration)methodDeclaration).pointcutDesignator != null)
addAllNamed(((AdviceDeclaration)methodDeclaration).pointcutDesignator.getPointcut(), pointcuts);
} else if (methodDeclaration instanceof PointcutDeclaration) {
if (((PointcutDeclaration)methodDeclaration).pointcutDesignator != null)
addAllNamed(((PointcutDeclaration)methodDeclaration).pointcutDesignator.getPointcut(), pointcuts);
}
return pointcuts;
}
/**
* @param left
* @param pointcuts accumulator for named pointcuts
*/
private void addAllNamed(Pointcut pointcut, List pointcuts) {
if (pointcut == null) return;
if (pointcut instanceof ReferencePointcut) {
ReferencePointcut rp = (ReferencePointcut)pointcut;
pointcuts.add(rp);
} else if (pointcut instanceof AndPointcut) {
AndPointcut ap = (AndPointcut)pointcut;
addAllNamed(ap.getLeft(), pointcuts);
addAllNamed(ap.getRight(), pointcuts);
} else if (pointcut instanceof OrPointcut) {
OrPointcut op = (OrPointcut)pointcut;
addAllNamed(op.getLeft(), pointcuts);
addAllNamed(op.getRight(), pointcuts);
}
}
private String genSourceSignature(MethodDeclaration methodDeclaration) {
StringBuffer output = new StringBuffer();
ASTNode.printModifiers(methodDeclaration.modifiers, output);
methodDeclaration.printReturnType(0, output).append(methodDeclaration.selector).append('(');
if (methodDeclaration.arguments != null) {
for (int i = 0; i < methodDeclaration.arguments.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
methodDeclaration.arguments[i].print(0, output);
}
}
output.append(')');
if (methodDeclaration.thrownExceptions != null) {
output.append(" throws "); //$NON-NLS-1$
for (int i = 0; i < methodDeclaration.thrownExceptions.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
methodDeclaration.thrownExceptions[i].print(0, output);
}
}
return output.toString();
}
// protected void genBytecodeInfo(MethodDeclaration methodDeclaration, IProgramElement peNode) {
// if (methodDeclaration.binding != null) {
// String memberName = "";
// String memberBytecodeSignature = "";
// try {
// EclipseFactory factory = ((AjLookupEnvironment)methodDeclaration.scope.environment()).factory;
// Member member = factory.makeResolvedMember(methodDeclaration.binding);
// memberName = member.getName();
// memberBytecodeSignature = member.getSignature();
// } catch (BCException bce) { // bad type name
// memberName = "<undefined>";
// } catch (NullPointerException npe) {
// memberName = "<undefined>";
// }
//
// peNode.setBytecodeName(memberName);
// peNode.setBytecodeSignature(memberBytecodeSignature);
// }
// ((IProgramElement)stack.peek()).addChild(peNode);
// }
protected void genBytecodeInfo(MethodDeclaration methodDeclaration, IProgramElement peNode) {
if (methodDeclaration.binding != null) {
try {
EclipseFactory factory = ((AjLookupEnvironment)methodDeclaration.scope.environment()).factory;
Member member = factory.makeResolvedMember(methodDeclaration.binding);
peNode.setBytecodeName(member.getName());
peNode.setBytecodeSignature(member.getSignature());
} catch (BCException bce) { // bad type name
bce.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
}
((IProgramElement)stack.peek()).addChild(peNode);
}
public void endVisit(MethodDeclaration methodDeclaration, ClassScope scope) {
stack.pop();
}
public boolean visit(ImportReference importRef, CompilationUnitScope scope) {
int dotIndex = importRef.toString().lastIndexOf('.');
String currPackageImport = "";
if (dotIndex != -1) {
currPackageImport = importRef.toString().substring(0, dotIndex);
}
if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) {
IProgramElement peNode = new ProgramElement(
new String(importRef.toString()),
IProgramElement.Kind.IMPORT_REFERENCE,
makeLocation(importRef),
0,
null,null);
ProgramElement imports = (ProgramElement)((ProgramElement)stack.peek()).getChildren().get(0);
imports.addChild(0, peNode);
stack.push(peNode);
}
return true;
}
public void endVisit(ImportReference importRef, CompilationUnitScope scope) {
int dotIndex = importRef.toString().lastIndexOf('.');
String currPackageImport = "";
if (dotIndex != -1) {
currPackageImport = importRef.toString().substring(0, dotIndex);
}
if (!((ProgramElement)stack.peek()).getPackageName().equals(currPackageImport)) {
stack.pop();
}
}
public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) {
IProgramElement peNode = null;
if (fieldDeclaration.type == null) { // The field represents an enum value
peNode = new ProgramElement(
new String(fieldDeclaration.name),IProgramElement.Kind.ENUM_VALUE,
makeLocation(fieldDeclaration), fieldDeclaration.modifiers,
null,null);
peNode.setCorrespondingType(fieldDeclaration.binding.type.debugName());
} else {
peNode = new ProgramElement(
new String(fieldDeclaration.name),IProgramElement.Kind.FIELD,
makeLocation(fieldDeclaration), fieldDeclaration.modifiers,
null,null);
peNode.setCorrespondingType(fieldDeclaration.type.toString());
}
peNode.setSourceSignature(genSourceSignature(fieldDeclaration));
peNode.setFormalComment(generateJavadocComment(fieldDeclaration));
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(FieldDeclaration fieldDeclaration, MethodScope scope) {
stack.pop();
}
/**
* Checks if comments should be added to the model before generating.
*/
protected String generateJavadocComment(ASTNode astNode) {
if (buildConfig != null && !buildConfig.isGenerateJavadocsInModelMode()) return null;
StringBuffer sb = new StringBuffer(); // !!! specify length?
boolean completed = false;
int startIndex = -1;
if (astNode instanceof MethodDeclaration) {
startIndex = ((MethodDeclaration)astNode).declarationSourceStart;
} else if (astNode instanceof FieldDeclaration) {
startIndex = ((FieldDeclaration)astNode).declarationSourceStart;
} else if (astNode instanceof TypeDeclaration) {
startIndex = ((TypeDeclaration)astNode).declarationSourceStart;
}
if (startIndex == -1) {
return null;
} else if (currCompilationResult.compilationUnit.getContents()[startIndex] == '/' // look for /**
&& currCompilationResult.compilationUnit.getContents()[startIndex+1] == '*'
&& currCompilationResult.compilationUnit.getContents()[startIndex+2] == '*') {
for (int i = startIndex; i < astNode.sourceStart && !completed; i++) {
char curr = currCompilationResult.compilationUnit.getContents()[i];
if (curr == '/' && sb.length() > 2 && sb.charAt(sb.length()-1) == '*') completed = true; // found */
sb.append(currCompilationResult.compilationUnit.getContents()[i]);
}
return sb.toString();
} else {
return null;
}
}
/**
* Doesn't print qualified allocation expressions.
*/
protected String genSourceSignature(FieldDeclaration fieldDeclaration) {
StringBuffer output = new StringBuffer();
if (fieldDeclaration.type == null) { // This is an enum value
output.append(fieldDeclaration.name); // the "," or ";" has to be put on by whatever uses the sourceSignature
return output.toString();
} else {
FieldDeclaration.printModifiers(fieldDeclaration.modifiers, output);
fieldDeclaration.type.print(0, output).append(' ').append(fieldDeclaration.name);
}
if (fieldDeclaration.initialization != null
&& !(fieldDeclaration.initialization instanceof QualifiedAllocationExpression)) {
output.append(" = "); //$NON-NLS-1$
if (fieldDeclaration.initialization instanceof ExtendedStringLiteral) {
output.append("\"<extended string literal>\"");
} else {
fieldDeclaration.initialization.printExpression(0, output);
}
}
output.append(';');
return output.toString();
}
// public boolean visit(ImportReference importRef, CompilationUnitScope scope) {
// ProgramElementNode peNode = new ProgramElementNode(
// new String(importRef.toString()),
// ProgramElementNode.Kind.,
// makeLocation(importRef),
// 0,
// "",
// new ArrayList());
// ((IProgramElement)stack.peek()).addChild(0, peNode);
// stack.push(peNode);
// return true;
// }
// public void endVisit(ImportReference importRef,CompilationUnitScope scope) {
// stack.pop();
// }
public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
if (constructorDeclaration.isDefaultConstructor) {
stack.push(null); // a little wierd but does the job
return true;
}
StringBuffer argumentsSignature = new StringBuffer();
argumentsSignature.append("(");
if (constructorDeclaration.arguments!=null) {
for (int i = 0;i<constructorDeclaration.arguments.length;i++) {
argumentsSignature.append(constructorDeclaration.arguments[i].type);
if (i+1<constructorDeclaration.arguments.length) argumentsSignature.append(",");
}
}
argumentsSignature.append(")");
IProgramElement peNode = new ProgramElement(
new String(constructorDeclaration.selector)+argumentsSignature,
IProgramElement.Kind.CONSTRUCTOR,
makeLocation(constructorDeclaration),
constructorDeclaration.modifiers,
null,null);
peNode.setModifiers(constructorDeclaration.modifiers);
peNode.setSourceSignature(genSourceSignature(constructorDeclaration));
// Fix to enable us to anchor things from ctor nodes
if (constructorDeclaration.binding != null) {
String memberName = "";
String memberBytecodeSignature = "";
try {
EclipseFactory factory = ((AjLookupEnvironment)constructorDeclaration.scope.environment()).factory;
Member member = factory.makeResolvedMember(constructorDeclaration.binding);
memberName = member.getName();
memberBytecodeSignature = member.getSignature();
} catch (BCException bce) { // bad type name
memberName = "<undefined>";
} catch (NullPointerException npe) {
memberName = "<undefined>";
}
peNode.setBytecodeName(memberName);
peNode.setBytecodeSignature(memberBytecodeSignature);
}
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
return true;
}
public void endVisit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
stack.pop();
}
private String genSourceSignature(ConstructorDeclaration constructorDeclaration) {
StringBuffer output = new StringBuffer();
ASTNode.printModifiers(constructorDeclaration.modifiers, output);
output.append(constructorDeclaration.selector).append('(');
if (constructorDeclaration.arguments != null) {
for (int i = 0; i < constructorDeclaration.arguments.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
constructorDeclaration.arguments[i].print(0, output);
}
}
output.append(')');
if (constructorDeclaration.thrownExceptions != null) {
output.append(" throws "); //$NON-NLS-1$
for (int i = 0; i < constructorDeclaration.thrownExceptions.length; i++) {
if (i > 0) output.append(", "); //$NON-NLS-1$
constructorDeclaration.thrownExceptions[i].print(0, output);
}
}
return output.toString();
}
// public boolean visit(Clinit clinit, ClassScope scope) {
// ProgramElementNode peNode = new ProgramElementNode(
// "<clinit>",
// ProgramElementNode.Kind.INITIALIZER,
// makeLocation(clinit),
// clinit.modifiers,
// "",
// new ArrayList());
// ((IProgramElement)stack.peek()).addChild(peNode);
// stack.push(peNode);
// return false;
// }
// public void endVisit(Clinit clinit, ClassScope scope) {
// stack.pop();
// }
/** This method works-around an odd traverse implementation on Initializer
*/
private Initializer inInitializer = null;
public boolean visit(Initializer initializer, MethodScope scope) {
if (initializer == inInitializer) return false;
inInitializer = initializer;
IProgramElement peNode = new ProgramElement(
"...",
IProgramElement.Kind.INITIALIZER,
makeLocation(initializer),
initializer.modifiers,null,null);
// "",
// new ArrayList());
((IProgramElement)stack.peek()).addChild(peNode);
stack.push(peNode);
initializer.block.traverse(this, scope);
stack.pop();
inInitializer=null;
return false;
}
// ??? handle non-existant files
protected ISourceLocation makeLocation(ASTNode node) {
String fileName = "";
if (filename != null) {
fileName = this.filename;
}
// AMC - different strategies based on node kind
int startLine = getStartLine(node);
int endLine = getEndLine(node);
SourceLocation loc = null;
if ( startLine <= endLine ) {
// found a valid end line for this node...
loc = new SourceLocation(new File(fileName), startLine, endLine);
loc.setOffset(node.sourceStart);
} else {
loc = new SourceLocation(new File(fileName), startLine);
loc.setOffset(node.sourceStart);
}
return loc;
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
protected int getStartLine( ASTNode n){
// if ( n instanceof AbstractVariableDeclaration ) return getStartLine( (AbstractVariableDeclaration)n);
// if ( n instanceof AbstractMethodDeclaration ) return getStartLine( (AbstractMethodDeclaration)n);
// if ( n instanceof TypeDeclaration ) return getStartLine( (TypeDeclaration)n);
return ProblemHandler.searchLineNumber(lineseps,
// currCompilationResult.lineSeparatorPositions,
n.sourceStart);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
protected int getEndLine( ASTNode n){
if ( n instanceof AbstractVariableDeclaration ) return getEndLine( (AbstractVariableDeclaration)n);
if ( n instanceof AbstractMethodDeclaration ) return getEndLine( (AbstractMethodDeclaration)n);
if ( n instanceof TypeDeclaration ) return getEndLine( (TypeDeclaration)n);
return ProblemHandler.searchLineNumber(lineseps,
// currCompilationResult.lineSeparatorPositions,
n.sourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( AbstractVariableDeclaration avd ) {
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// avd.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( AbstractVariableDeclaration avd ){
return ProblemHandler.searchLineNumber(lineseps,
// currCompilationResult.lineSeparatorPositions,
avd.declarationSourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( AbstractMethodDeclaration amd ){
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// amd.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( AbstractMethodDeclaration amd) {
return ProblemHandler.searchLineNumber(lineseps,
// currCompilationResult.lineSeparatorPositions,
amd.declarationSourceEnd);
}
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
// private int getStartLine( TypeDeclaration td ){
// return ProblemHandler.searchLineNumber(
// currCompilationResult.lineSeparatorPositions,
// td.declarationSourceStart);
// }
// AMC - overloaded set of methods to get start and end lines for
// various ASTNode types. They have no common ancestor in the
// hierarchy!!
private int getEndLine( TypeDeclaration td){
return ProblemHandler.searchLineNumber(lineseps,
// currCompilationResult.lineSeparatorPositions,
td.declarationSourceEnd);
}
}
|
130,837 |
Bug 130837 Exception while trying to edit Annotation based Aspect Class (normal Java class)
|
java.lang.NullPointerException at org.aspectj.ajdt.internal.compiler.ast.ValidateAtAspectJAnnotationsVisitor.buildFormalAdviceBindingsFrom(ValidateAtAspectJAnnotationsVisitor.java:417) at org.aspectj.ajdt.internal.compiler.ast.ValidateAtAspectJAnnotationsVisitor.resolveAndSetPointcut(ValidateAtAspectJAnnotationsVisitor.java:364) at org.aspectj.ajdt.internal.compiler.ast.ValidateAtAspectJAnnotationsVisitor.validateAdvice(ValidateAtAspectJAnnotationsVisitor.java:336) at org.aspectj.ajdt.internal.compiler.ast.ValidateAtAspectJAnnotationsVisitor.visit(ValidateAtAspectJAnnotationsVisitor.java:186) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration.traverse(MethodDeclaration.java:185) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration.traverse(TypeDeclaration.java:1195) at org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration.traverse(CompilationUnitDeclaration.java:339) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.beforeAnalysing(AjCompilerAdapter.java:154) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$before$org_aspectj_ajdt_internal_compiler_CompilerAdapter$7$db78446d(CompilerAdapter.aj:101) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:517) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:824) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:234) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:189) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:164) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
|
resolved fixed
|
41f1f3a
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-03-28T08:09:10Z | 2006-03-08T01:06:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/ValidateAtAspectJAnnotationsVisitor.java
|
/* *******************************************************************
* Copyright (c) 2005 IBM Corporation Ltd
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import java.lang.reflect.Modifier;
import java.util.Stack;
import java.util.ArrayList;
import java.util.List;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseScope;
import org.aspectj.ajdt.internal.core.builder.EclipseSourceContext;
import org.aspectj.bridge.context.CompilationAndWeavingContext;
import org.aspectj.bridge.context.ContextToken;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ASTVisitor;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MemberValuePair;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.NormalAnnotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.StringLiteral;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.patterns.AbstractPatternNodeVisitor;
import org.aspectj.weaver.patterns.FormalBinding;
import org.aspectj.weaver.patterns.IfPointcut;
import org.aspectj.weaver.patterns.ParserException;
import org.aspectj.weaver.patterns.PatternParser;
import org.aspectj.weaver.patterns.Pointcut;
public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor {
private static final char[] beforeAdviceSig = "Lorg/aspectj/lang/annotation/Before;".toCharArray();
private static final char[] afterAdviceSig = "Lorg/aspectj/lang/annotation/After;".toCharArray();
private static final char[] afterReturningAdviceSig = "Lorg/aspectj/lang/annotation/AfterReturning;".toCharArray();
private static final char[] afterThrowingAdviceSig = "Lorg/aspectj/lang/annotation/AfterThrowing;".toCharArray();
private static final char[] aroundAdviceSig = "Lorg/aspectj/lang/annotation/Around;".toCharArray();
private static final char[] pointcutSig = "Lorg/aspectj/lang/annotation/Pointcut;".toCharArray();
private static final char[] aspectSig = "Lorg/aspectj/lang/annotation/Aspect;".toCharArray();
private static final char[] adviceNameSig = "Lorg/aspectj/lang/annotation/AdviceName;".toCharArray();
private static final char[] orgAspectJLangAnnotation = "org/aspectj/lang/annotation/".toCharArray();
private static final char[] voidType = "void".toCharArray();
private static final char[] booleanType = "boolean".toCharArray();
private static final char[] joinPoint = "Lorg/aspectj/lang/JoinPoint;".toCharArray();
private static final char[] joinPointStaticPart = "Lorg/aspectj/lang/JoinPoint$StaticPart;".toCharArray();
private static final char[] joinPointEnclosingStaticPart = "Lorg/aspectj/lang/JoinPoint$EnclosingStaticPart;".toCharArray();
private static final char[] proceedingJoinPoint = "Lorg/aspectj/lang/ProceedingJoinPoint;".toCharArray();
private static final char[][] adviceSigs = new char[][] {beforeAdviceSig,afterAdviceSig,afterReturningAdviceSig,afterThrowingAdviceSig,aroundAdviceSig};
private CompilationUnitDeclaration unit;
private Stack typeStack = new Stack();
private AspectJAnnotations ajAnnotations;
public ValidateAtAspectJAnnotationsVisitor(CompilationUnitDeclaration unit) {
this.unit = unit;
}
public boolean visit(TypeDeclaration localTypeDeclaration, BlockScope scope) {
typeStack.push(localTypeDeclaration);
ajAnnotations = new AspectJAnnotations(localTypeDeclaration.annotations);
checkTypeDeclaration(localTypeDeclaration);
return true;
}
public void endVisit(TypeDeclaration localTypeDeclaration,BlockScope scope) {
typeStack.pop();
}
public boolean visit(TypeDeclaration memberTypeDeclaration,ClassScope scope) {
typeStack.push(memberTypeDeclaration);
ajAnnotations = new AspectJAnnotations(memberTypeDeclaration.annotations);
checkTypeDeclaration(memberTypeDeclaration);
return true;
}
public void endVisit(TypeDeclaration memberTypeDeclaration,ClassScope scope) {
typeStack.pop();
}
public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
typeStack.push(typeDeclaration);
ajAnnotations = new AspectJAnnotations(typeDeclaration.annotations);
checkTypeDeclaration(typeDeclaration);
return true;
}
public void endVisit(TypeDeclaration typeDeclaration,CompilationUnitScope scope) {
typeStack.pop();
}
private void checkTypeDeclaration(TypeDeclaration typeDecl) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.VALIDATING_AT_ASPECTJ_ANNOTATIONS, typeDecl.name);
if (!(typeDecl instanceof AspectDeclaration)) {
if (ajAnnotations.hasAspectAnnotation) {
validateAspectDeclaration(typeDecl);
} else {
// check that class doesn't extend aspect
TypeReference parentRef = typeDecl.superclass;
if (parentRef != null) {
TypeBinding parentBinding = parentRef.resolvedType;
if (parentBinding instanceof SourceTypeBinding) {
SourceTypeBinding parentSTB = (SourceTypeBinding) parentBinding;
if (parentSTB.scope != null) {
TypeDeclaration parentDecl = parentSTB.scope.referenceContext;
if (isAspect(parentDecl)) {
typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart,typeDecl.sourceEnd,"a class cannot extend an aspect");
}
}
}
}
}
} else {
// check that aspect doesn't have @Aspect annotation, we've already added on ourselves.
if (ajAnnotations.hasMultipleAspectAnnotations) {
typeDecl.scope.problemReporter().signalError(
typeDecl.sourceStart,
typeDecl.sourceEnd,
"aspects cannot have @Aspect annotation"
);
}
}
CompilationAndWeavingContext.leavingPhase(tok);
}
public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) {
if (methodDeclaration.hasErrors()) {
return false;
}
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.VALIDATING_AT_ASPECTJ_ANNOTATIONS, methodDeclaration.selector);
ajAnnotations = new AspectJAnnotations(methodDeclaration.annotations);
if (!methodDeclaration.getClass().equals(AjMethodDeclaration.class)) {
// simply test for innapropriate use of annotations on code-style members
if (methodDeclaration instanceof PointcutDeclaration) {
if (ajAnnotations.hasMultiplePointcutAnnotations ||
ajAnnotations.hasAdviceAnnotation ||
ajAnnotations.hasAspectAnnotation ||
ajAnnotations.hasAdviceNameAnnotation) {
methodDeclaration.scope.problemReporter().signalError(
methodDeclaration.sourceStart,
methodDeclaration.sourceEnd,
"@AspectJ annotations cannot be declared on this aspect member");
}
} else if (methodDeclaration instanceof AdviceDeclaration) {
if (ajAnnotations.hasMultipleAdviceAnnotations ||
ajAnnotations.hasAspectAnnotation ||
ajAnnotations.hasPointcutAnnotation) {
methodDeclaration.scope.problemReporter().signalError(
methodDeclaration.sourceStart,
methodDeclaration.sourceEnd,
"Only @AdviceName AspectJ annotation allowed on advice");
}
} else {
if (ajAnnotations.hasAspectJAnnotations()) {
methodDeclaration.scope.problemReporter().signalError(
methodDeclaration.sourceStart,
methodDeclaration.sourceEnd,
"@AspectJ annotations cannot be declared on this aspect member");
}
}
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
if (ajAnnotations.hasAdviceAnnotation) {
validateAdvice(methodDeclaration);
} else if (ajAnnotations.hasPointcutAnnotation) {
convertToPointcutDeclaration(methodDeclaration,scope);
}
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
private boolean isAspectJAnnotation(Annotation ann) {
if (ann.resolvedType == null) return false;
char[] sig = ann.resolvedType.signature();
return CharOperation.contains(orgAspectJLangAnnotation, sig);
}
private boolean insideAspect() {
if (typeStack.empty()) return false;
TypeDeclaration typeDecl = (TypeDeclaration) typeStack.peek();
return isAspect(typeDecl);
}
private boolean isAspect(TypeDeclaration typeDecl) {
if (typeDecl instanceof AspectDeclaration) return true;
return new AspectJAnnotations(typeDecl.annotations).hasAspectAnnotation;
}
/**
* aspect must be public
* nested aspect must be static
* cannot extend a concrete aspect
* pointcut in perclause must be good.
*/
private void validateAspectDeclaration(TypeDeclaration typeDecl) {
if (typeStack.size() > 1) {
// it's a nested aspect
if (!Modifier.isStatic(typeDecl.modifiers)) {
typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart, typeDecl.sourceEnd, "inner aspects must be static");
return;
}
}
SourceTypeBinding binding = typeDecl.binding;
if (binding != null) {
if (binding.isEnum() || binding.isInterface() || binding.isAnnotationType()) {
typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart,typeDecl.sourceEnd,"only classes can have an @Aspect annotation");
}
}
//FIXME AV - do we really want that
// if (!Modifier.isPublic(typeDecl.modifiers)) {
// typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart,typeDecl.sourceEnd,"@Aspect class must be public");
// }
TypeReference parentRef = typeDecl.superclass;
if (parentRef != null) {
TypeBinding parentBinding = parentRef.resolvedType;
if (parentBinding instanceof SourceTypeBinding) {
SourceTypeBinding parentSTB = (SourceTypeBinding) parentBinding;
if (parentSTB.scope!=null) { // scope is null if its a binarytypebinding (in AJ world, thats a subclass of SourceTypeBinding)
TypeDeclaration parentDecl = parentSTB.scope.referenceContext;
if (isAspect(parentDecl) && !Modifier.isAbstract(parentDecl.modifiers)) {
typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart,typeDecl.sourceEnd,"cannot extend a concrete aspect");
}
}
}
}
Annotation aspectAnnotation = ajAnnotations.aspectAnnotation;
int[] pcLoc = new int[2];
String perClause = getStringLiteralFor("value", aspectAnnotation, pcLoc);
AspectDeclaration aspectDecl = new AspectDeclaration(typeDecl.compilationResult);
try {
if (perClause != null && !perClause.equals("")) {
ISourceContext context = new EclipseSourceContext(unit.compilationResult,pcLoc[0]);
Pointcut pc = new PatternParser(perClause,context).maybeParsePerClause();
FormalBinding[] bindings = new FormalBinding[0];
if (pc != null) pc.resolve(new EclipseScope(bindings,typeDecl.scope));
}
} catch(ParserException pEx) {
typeDecl.scope.problemReporter().parseError(
pcLoc[0] + pEx.getLocation().getStart(),
pcLoc[0] + pEx.getLocation().getEnd() ,
-1,
perClause.toCharArray(),
perClause,
new String[] {pEx.getMessage()});
}
}
/**
* 1) Advice must be public
* 2) Advice must have a void return type if not around advice
* 3) Advice must not have any other @AspectJ annotations
* 4) After throwing advice must declare the thrown formal
* 5) After returning advice must declare the returning formal
*/
private void validateAdvice(MethodDeclaration methodDeclaration) {
if (!insideAspect()) {
methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart,
methodDeclaration.sourceEnd,
"Advice must be declared inside an aspect type");
}
if (!Modifier.isPublic(methodDeclaration.modifiers)) {
methodDeclaration.scope.problemReporter()
.signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"advice must be public");
}
if (ajAnnotations.hasMultipleAdviceAnnotations) {
methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.duplicateAdviceAnnotation);
}
if (ajAnnotations.hasPointcutAnnotation) {
methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.pointcutAnnotation);
}
if (ajAnnotations.hasAspectAnnotation) {
methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.aspectAnnotation);
}
if (ajAnnotations.hasAdviceNameAnnotation) {
methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.adviceNameAnnotation);
}
if (ajAnnotations.adviceKind != AdviceKind.Around) {
ensureVoidReturnType(methodDeclaration);
}
if (ajAnnotations.adviceKind == AdviceKind.AfterThrowing) {
int[] throwingLocation = new int[2];
String thrownFormal = getStringLiteralFor("throwing",ajAnnotations.adviceAnnotation,throwingLocation);
if (thrownFormal != null) {
Argument[] arguments = methodDeclaration.arguments;
if (!toArgumentNames(methodDeclaration.arguments).contains(thrownFormal)) {
methodDeclaration.scope.problemReporter()
.signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"throwing formal '" + thrownFormal + "' must be declared as a parameter in the advice signature");
}
}
}
if (ajAnnotations.adviceKind == AdviceKind.AfterReturning) {
int[] throwingLocation = new int[2];
String returningFormal = getStringLiteralFor("returning",ajAnnotations.adviceAnnotation,throwingLocation);
if (returningFormal != null) {
if (!toArgumentNames(methodDeclaration.arguments).contains(returningFormal)) {
methodDeclaration.scope.problemReporter()
.signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"returning formal '" + returningFormal + "' must be declared as a parameter in the advice signature");
}
}
}
resolveAndSetPointcut(methodDeclaration, ajAnnotations.adviceAnnotation);
}
/**
* Get the argument names as a string list
* @param arguments
* @return argument names (possibly empty)
*/
private List toArgumentNames(Argument[] arguments) {
List names = new ArrayList();
if (arguments == null) {
return names;
} else {
for (int i = 0; i < arguments.length; i++) {
names.add(new String(arguments[i].name));
}
return names;
}
}
private void resolveAndSetPointcut(MethodDeclaration methodDeclaration, Annotation adviceAnn) {
int[] pcLocation = new int[2];
String pointcutExpression = getStringLiteralFor("pointcut",adviceAnn,pcLocation);
if (pointcutExpression == null) pointcutExpression = getStringLiteralFor("value",adviceAnn,pcLocation);
try {
ISourceContext context = new EclipseSourceContext(unit.compilationResult,pcLocation[0]);
Pointcut pc = new PatternParser(pointcutExpression,context).parsePointcut();
FormalBinding[] bindings = buildFormalAdviceBindingsFrom(methodDeclaration);
pc.resolve(new EclipseScope(bindings,methodDeclaration.scope));
EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(methodDeclaration.scope);
// now create a ResolvedPointcutDefinition,make an attribute out of it, and add it to the method
UnresolvedType[] paramTypes = new UnresolvedType[bindings.length];
for (int i = 0; i < paramTypes.length; i++) paramTypes[i] = bindings[i].getType();
ResolvedPointcutDefinition resPcutDef =
new ResolvedPointcutDefinition(
factory.fromBinding(((TypeDeclaration)typeStack.peek()).binding),
methodDeclaration.modifiers,
"anonymous",
paramTypes,
pc
);
AjAttribute attr = new AjAttribute.PointcutDeclarationAttribute(resPcutDef);
((AjMethodDeclaration)methodDeclaration).addAttribute(new EclipseAttributeAdapter(attr));
} catch(ParserException pEx) {
methodDeclaration.scope.problemReporter().parseError(
pcLocation[0] + pEx.getLocation().getStart(),
pcLocation[0] + pEx.getLocation().getEnd() ,
-1,
pointcutExpression.toCharArray(),
pointcutExpression,
new String[] {pEx.getMessage()});
}
}
private void ensureVoidReturnType(MethodDeclaration methodDeclaration) {
boolean returnsVoid = true;
if ((methodDeclaration.returnType instanceof SingleTypeReference)) {
SingleTypeReference retType = (SingleTypeReference) methodDeclaration.returnType;
if (!CharOperation.equals(voidType,retType.token)) {
returnsVoid = false;
}
} else {
returnsVoid = false;
}
if (!returnsVoid) {
methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart,
methodDeclaration.returnType.sourceEnd,
"This advice must return void");
}
}
private FormalBinding[] buildFormalAdviceBindingsFrom(MethodDeclaration mDecl) {
if (mDecl.arguments == null) return new FormalBinding[0];
EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(mDecl.scope);
String extraArgName = maybeGetExtraArgName();
if (extraArgName == null) extraArgName = "";
FormalBinding[] ret = new FormalBinding[mDecl.arguments.length];
for (int i = 0; i < mDecl.arguments.length; i++) {
Argument arg = mDecl.arguments[i];
String name = new String(arg.name);
TypeBinding argTypeBinding = mDecl.binding.parameters[i];
UnresolvedType type = factory.fromBinding(argTypeBinding);
if (CharOperation.equals(joinPoint,argTypeBinding.signature()) ||
CharOperation.equals(joinPointStaticPart,argTypeBinding.signature()) ||
CharOperation.equals(joinPointEnclosingStaticPart,argTypeBinding.signature()) ||
CharOperation.equals(proceedingJoinPoint,argTypeBinding.signature()) ||
name.equals(extraArgName)) {
ret[i] = new FormalBinding.ImplicitFormalBinding(type,name,i);
} else {
ret[i] = new FormalBinding(type, name, i, arg.sourceStart, arg.sourceEnd, "unknown");
}
}
return ret;
}
private String maybeGetExtraArgName() {
String argName = null;
if (ajAnnotations.adviceKind == AdviceKind.AfterReturning) {
argName = getStringLiteralFor("returning",ajAnnotations.adviceAnnotation,new int[2]);
} else if (ajAnnotations.adviceKind == AdviceKind.AfterThrowing) {
argName = getStringLiteralFor("throwing",ajAnnotations.adviceAnnotation,new int[2]);
}
return argName;
}
private String getStringLiteralFor(String memberName, Annotation inAnnotation, int[] location) {
if (inAnnotation instanceof SingleMemberAnnotation && memberName.equals("value")) {
SingleMemberAnnotation sma = (SingleMemberAnnotation) inAnnotation;
if (sma.memberValue instanceof StringLiteral) {
StringLiteral sv = (StringLiteral) sma.memberValue;
location[0] = sv.sourceStart;
location[1] = sv.sourceEnd;
return new String(sv.source());
}
}
if (! (inAnnotation instanceof NormalAnnotation)) return null;
NormalAnnotation ann = (NormalAnnotation) inAnnotation;
MemberValuePair[] mvps = ann.memberValuePairs;
if (mvps == null) return null;
for (int i = 0; i < mvps.length; i++) {
if (CharOperation.equals(memberName.toCharArray(),mvps[i].name)) {
if (mvps[i].value instanceof StringLiteral) {
StringLiteral sv = (StringLiteral) mvps[i].value;
location[0] = sv.sourceStart;
location[1] = sv.sourceEnd;
return new String(sv.source());
}
}
}
return null;
}
private void convertToPointcutDeclaration(MethodDeclaration methodDeclaration, ClassScope scope) {
TypeDeclaration typeDecl = (TypeDeclaration) typeStack.peek();
if (typeDecl.binding != null) {
if (!typeDecl.binding.isClass()) {
methodDeclaration.scope.problemReporter()
.signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"pointcuts can only be declared in a class or an aspect");
}
}
if (methodDeclaration.thrownExceptions != null && methodDeclaration.thrownExceptions.length > 0) {
methodDeclaration.scope.problemReporter()
.signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"pointcuts cannot throw exceptions!");
}
PointcutDeclaration pcDecl = new PointcutDeclaration(unit.compilationResult);
copyAllFields(methodDeclaration,pcDecl);
if (ajAnnotations.hasAdviceAnnotation) {
methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.adviceAnnotation);
}
if (ajAnnotations.hasAspectAnnotation) {
methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.aspectAnnotation);
}
if (ajAnnotations.hasAdviceNameAnnotation) {
methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.adviceNameAnnotation);
}
boolean noValueSupplied=true;
boolean containsIfPcd = false;
int[] pcLocation = new int[2];
String pointcutExpression = getStringLiteralFor("value",ajAnnotations.pointcutAnnotation,pcLocation);
try {
ISourceContext context = new EclipseSourceContext(unit.compilationResult,pcLocation[0]);
Pointcut pc = null;//abstract
if (pointcutExpression == null || pointcutExpression.length() == 0) {
noValueSupplied=true; // matches nothing pointcut
} else {
noValueSupplied=false;
pc = new PatternParser(pointcutExpression,context).parsePointcut();
}
pcDecl.pointcutDesignator = (pc==null)?null:new PointcutDesignator(pc);
pcDecl.setGenerateSyntheticPointcutMethod();
TypeDeclaration onType = (TypeDeclaration) typeStack.peek();
pcDecl.postParse(onType);
// EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(methodDeclaration.scope);
// int argsLength = methodDeclaration.arguments == null ? 0 : methodDeclaration.arguments.length;
FormalBinding[] bindings = buildFormalAdviceBindingsFrom(methodDeclaration);
// FormalBinding[] bindings = new FormalBinding[argsLength];
// for (int i = 0, len = bindings.length; i < len; i++) {
// Argument arg = methodDeclaration.arguments[i];
// String name = new String(arg.name);
// UnresolvedType type = factory.fromBinding(methodDeclaration.binding.parameters[i]);
// bindings[i] = new FormalBinding(type, name, i, arg.sourceStart, arg.sourceEnd, "unknown");
// }
swap(onType,methodDeclaration,pcDecl);
if (pc != null) {
// has an expression
pc.resolve(new EclipseScope(bindings,methodDeclaration.scope));
HasIfPCDVisitor ifFinder = new HasIfPCDVisitor();
pc.traverse(ifFinder, null);
containsIfPcd = ifFinder.containsIfPcd;
}
} catch(ParserException pEx) {
methodDeclaration.scope.problemReporter().parseError(
pcLocation[0] + pEx.getLocation().getStart(),
pcLocation[0] + pEx.getLocation().getEnd() ,
-1,
pointcutExpression.toCharArray(),
pointcutExpression,
new String[] {pEx.getMessage()});
}
boolean returnsVoid = false;
boolean returnsBoolean = false;
if ((methodDeclaration.returnType instanceof SingleTypeReference)) {
SingleTypeReference retType = (SingleTypeReference) methodDeclaration.returnType;
if (CharOperation.equals(voidType,retType.token)) returnsVoid = true;
if (CharOperation.equals(booleanType,retType.token)) returnsBoolean = true;
}
if (!returnsVoid && !containsIfPcd) {
methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart,
methodDeclaration.returnType.sourceEnd,
"Methods annotated with @Pointcut must return void unless the pointcut contains an if() expression");
}
if (!returnsBoolean && containsIfPcd) {
methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart,
methodDeclaration.returnType.sourceEnd,
"Methods annotated with @Pointcut must return boolean when the pointcut contains an if() expression");
}
if (methodDeclaration.statements != null && methodDeclaration.statements.length > 0 && !containsIfPcd) {
methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart,
methodDeclaration.returnType.sourceEnd,
"Pointcuts without an if() expression should have an empty method body");
}
if (pcDecl.pointcutDesignator == null) {
if (Modifier.isAbstract(methodDeclaration.modifiers)
|| noValueSupplied // this is a matches nothing pointcut
//those 2 checks makes sense for aop.xml concretization but NOT for regular abstraction of pointcut
//&& returnsVoid
//&& (methodDeclaration.arguments == null || methodDeclaration.arguments.length == 0)) {
) {
;//fine
} else {
methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart,
methodDeclaration.returnType.sourceEnd,
"Method annotated with @Pointcut() for abstract pointcut must be abstract");
}
} else if (Modifier.isAbstract(methodDeclaration.modifiers)) {
methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart,
methodDeclaration.returnType.sourceEnd,
"Method annotated with non abstract @Pointcut(\""+pointcutExpression+"\") is abstract");
}
}
private void copyAllFields(MethodDeclaration from, MethodDeclaration to) {
to.annotations = from.annotations;
to.arguments = from.arguments;
to.binding = from.binding;
to.bits = from.bits;
to.bodyEnd = from.bodyEnd;
to.bodyStart = from.bodyStart;
to.declarationSourceEnd = from.declarationSourceEnd;
to.declarationSourceStart = from.declarationSourceStart;
to.errorInSignature = from.errorInSignature;
to.explicitDeclarations = from.explicitDeclarations;
to.ignoreFurtherInvestigation = from.ignoreFurtherInvestigation;
to.javadoc = from.javadoc;
to.modifiers = from.modifiers;
to.modifiersSourceStart = from.modifiersSourceStart;
to.needFreeReturn = from.needFreeReturn;
to.returnType = from.returnType;
to.scope = from.scope;
to.selector = from.selector;
to.sourceEnd = from.sourceEnd;
to.sourceStart = from.sourceStart;
to.statements = from.statements;
to.thrownExceptions = from.thrownExceptions;
to.typeParameters = from.typeParameters;
}
private void swap(TypeDeclaration inType, MethodDeclaration thisDeclaration, MethodDeclaration forThatDeclaration) {
for (int i = 0; i < inType.methods.length; i++) {
if (inType.methods[i] == thisDeclaration) {
inType.methods[i] = forThatDeclaration;
break;
}
}
}
private static class AspectJAnnotations {
boolean hasAdviceAnnotation = false;
boolean hasPointcutAnnotation = false;
boolean hasAspectAnnotation = false;
boolean hasAdviceNameAnnotation = false;
boolean hasMultipleAdviceAnnotations = false;
boolean hasMultiplePointcutAnnotations = false;
boolean hasMultipleAspectAnnotations = false;
AdviceKind adviceKind = null;
Annotation adviceAnnotation = null;
Annotation pointcutAnnotation = null;
Annotation aspectAnnotation = null;
Annotation adviceNameAnnotation = null;
Annotation duplicateAdviceAnnotation = null;
Annotation duplicatePointcutAnnotation = null;
Annotation duplicateAspectAnnotation = null;
public AspectJAnnotations(Annotation[] annotations) {
if (annotations == null) return;
for (int i = 0; i < annotations.length; i++) {
if (annotations[i].resolvedType == null) continue; // user messed up annotation declaration
char[] sig = annotations[i].resolvedType.signature();
if (CharOperation.equals(afterAdviceSig,sig)) {
adviceKind = AdviceKind.After;
addAdviceAnnotation(annotations[i]);
} else if (CharOperation.equals(afterReturningAdviceSig,sig)) {
adviceKind = AdviceKind.AfterReturning;
addAdviceAnnotation(annotations[i]);
} else if (CharOperation.equals(afterThrowingAdviceSig,sig)) {
adviceKind = AdviceKind.AfterThrowing;
addAdviceAnnotation(annotations[i]);
} else if (CharOperation.equals(beforeAdviceSig,sig)) {
adviceKind = AdviceKind.Before;
addAdviceAnnotation(annotations[i]);
} else if (CharOperation.equals(aroundAdviceSig,sig)) {
adviceKind = AdviceKind.Around;
addAdviceAnnotation(annotations[i]);
} else if (CharOperation.equals(adviceNameSig,sig)) {
hasAdviceNameAnnotation = true;
adviceNameAnnotation = annotations[i];
} else if (CharOperation.equals(aspectSig,sig)) {
if (hasAspectAnnotation) {
hasMultipleAspectAnnotations = true;
duplicateAspectAnnotation = annotations[i];
} else {
hasAspectAnnotation = true;
aspectAnnotation = annotations[i];
}
} else if (CharOperation.equals(pointcutSig,sig)) {
if (hasPointcutAnnotation) {
hasMultiplePointcutAnnotations = true;
duplicatePointcutAnnotation = annotations[i];
} else {
hasPointcutAnnotation = true;
pointcutAnnotation = annotations[i];
}
}
}
}
public boolean hasAspectJAnnotations() {
return hasAdviceAnnotation || hasPointcutAnnotation || hasAdviceNameAnnotation || hasAspectAnnotation;
}
private void addAdviceAnnotation(Annotation annotation) {
if (!hasAdviceAnnotation) {
hasAdviceAnnotation = true;
adviceAnnotation = annotation;
} else {
hasMultipleAdviceAnnotations = true;
duplicateAdviceAnnotation = annotation;
}
}
}
private static class HasIfPCDVisitor extends AbstractPatternNodeVisitor {
public boolean containsIfPcd = false;
public Object visit(IfPointcut node, Object data) {
containsIfPcd = true;
return data;
}
}
}
|
134,541 |
Bug 134541 adviceDidNotMatch's line number doesn't keep up with line number of advice
|
When advice doesn't match in a 1.5.0 enabled project, there is an adviceDidNotMatch warning against the line number of the advice. If you insert a line before this advice and save then the warning stays associated with the original line and not the new one. Full building puts the warning against the new line. This is a regression and didn't happen in AJ 1.5.0.
|
resolved fixed
|
94d8b82
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-04-06T10:44:14Z | 2006-04-03T16:00:00Z |
tests/src/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement initial implementation
* ******************************************************************/
package org.aspectj.systemtest.incremental.tools;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.aspectj.ajdt.internal.core.builder.AjState;
import org.aspectj.ajdt.internal.core.builder.IncrementalStateManager;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IProgramElement;
import org.aspectj.bridge.IMessage;
import org.aspectj.testing.util.FileUtil;
/**
* The superclass knows all about talking through Ajde to the compiler.
* The superclass isn't in charge of knowing how to simulate overlays
* for incremental builds, that is in here. As is the ability to
* generate valid build configs based on a directory structure. To
* support this we just need access to a sandbox directory - this
* sandbox is managed by the superclass (it only assumes all builds occur
* in <sandboxDir>/<projectName>/ )
*
* The idea is you can initialize multiple projects in the sandbox and
* they can all be built independently, hopefully exploiting
* incremental compilation. Between builds you can alter the contents
* of a project using the alter() method that overlays some set of
* new files onto the current set (adding new files/changing existing
* ones) - you can then drive a new build and check it behaves as
* expected.
*/
public class MultiProjectIncrementalTests extends AjdeInteractionTestbed {
public static boolean VERBOSE = false;
protected void setUp() throws Exception {
super.setUp();
AjdeInteractionTestbed.VERBOSE = VERBOSE;
AjState.FORCE_INCREMENTAL_DURING_TESTING = true;
}
protected void tearDown() throws Exception {
super.tearDown();
AjState.FORCE_INCREMENTAL_DURING_TESTING = false;
}
// Compile a single simple project
public void testTheBasics() {
initialiseProject("P1");
build("P1"); // This first build will be batch
build("P1");
checkWasntFullBuild();
checkCompileWeaveCount(0,0);
}
// source code doesnt matter, we are checking invalid path handling
public void testInvalidAspectpath_pr121395() {
initialiseProject("P1");
File f = new File("foo.jar");
Set s = new HashSet();
s.add(f);
configureAspectPath(s);
build("P1"); // This first build will be batch
checkForError("invalid aspectpath entry");
}
// Make simple changes to a project, adding a class
public void testSimpleChanges() {
initialiseProject("P1");
build("P1"); // This first build will be batch
alter("P1","inc1"); // adds a single class
build("P1");
checkCompileWeaveCount(1,-1);
build("P1");
checkCompileWeaveCount(0,-1);
}
// Make simple changes to a project, adding a class and an aspect
public void testAddingAnAspect() {
initialiseProject("P1");
build("P1"); // build 1, weave 1
alter("P1","inc1"); // adds a class
alter("P1","inc2"); // adds an aspect
build("P1"); // build 1,
long timeTakenForFullBuildAndWeave = getTimeTakenForBuild();
checkWasFullBuild(); // it *will* be a full build under the new
// "back-to-the-source strategy
checkCompileWeaveCount(5,3); // we compile X and A (the delta) find out that
// an aspect has changed, go back to the source
// and compile X,A,C, then weave them all.
build("P1");
long timeTakenForSimpleIncBuild = getTimeTakenForBuild();
// I don't think this test will have timing issues as the times should be *RADICALLY* different
// On my config, first build time is 2093ms and the second is 30ms
assertTrue("Should not take longer for the trivial incremental build! first="+timeTakenForFullBuildAndWeave+
"ms second="+timeTakenForSimpleIncBuild+"ms",
timeTakenForSimpleIncBuild<timeTakenForFullBuildAndWeave);
}
public void testBuildingTwoProjectsInTurns() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
build("P2");
build("P1");
checkWasntFullBuild();
build("P2");
checkWasntFullBuild();
}
/**
* In order for this next test to run, I had to move the weaver/world pair we keep in the
* AjBuildManager instance down into the state object - this makes perfect sense - otherwise
* when reusing the state for another project we'd not be switching to the right weaver/world
* for that project.
*/
public void testBuildingTwoProjectsMakingSmallChanges() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
build("P2");
build("P1");
checkWasntFullBuild();
build("P2");
checkWasntFullBuild();
alter("P1","inc1"); // adds a class
alter("P1","inc2"); // adds an aspect
build("P1");
checkWasFullBuild(); // adding an aspect makes us go back to the source
}
/**
* Setup up two simple projects and build them in turn - check the
* structure model is right after each build
*/
public void testBuildingTwoProjectsAndVerifyingModel() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
}
// Setup up two simple projects and build them in turn - check the
// structure model is right after each build
public void testBuildingTwoProjectsAndVerifyingStuff() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
}
/**
* Complex. Here we are testing that a state object records structural changes since
* the last full build correctly. We build a simple project from scratch - this will
* be a full build and so the structural changes since last build count should be 0.
* We then alter a class, adding a new method and check structural changes is 1.
*/
public void testStateManagement1() {
File binDirectoryForP1 = new File(getFile("P1","bin"));
initialiseProject("P1");
build("P1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1);
assertTrue("There should be a state object for project P1",ajs!=null);
assertTrue("Should be no structural changes as it was a full build but found: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("P1","inc3"); // adds a method to the class C.java
build("P1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin")));
assertTrue("There should be state for project P1",ajs!=null);
checkWasntFullBuild();
assertTrue("Should be one structural changes as it was a full build but found: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==1);
}
/**
* Complex. Here we are testing that a state object records structural changes since
* the last full build correctly. We build a simple project from scratch - this will
* be a full build and so the structural changes since last build count should be 0.
* We then alter a class, changing body of a method, not the structure and
* check struc changes is still 0.
*/
public void testStateManagement2() {
File binDirectoryForP1 = new File(getFile("P1","bin"));
initialiseProject("P1");
alter("P1","inc3"); // need this change in here so 'inc4' can be applied without making
// it a structural change
build("P1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1);
assertTrue("There should be state for project P1",ajs!=null);
assertTrue("Should be no struc changes as its a full build: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("P1","inc4"); // changes body of main() method but does *not* change the structure of C.java
build("P1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin")));
assertTrue("There should be state for project P1",ajs!=null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
}
/**
* The C.java file modified in this test has an inner class - this means the inner class
* has a this$0 field and <init>(C) ctor to watch out for when checking for structural changes
*
*/
public void testStateManagement3() {
File binDirForInterproject1 = new File(getFile("interprojectdeps1","bin"));
initialiseProject("interprojectdeps1");
build("interprojectdeps1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject1);
assertTrue("There should be state for project P1",ajs!=null);
assertTrue("Should be no struc changes as its a full build: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("interprojectdeps1","inc1"); // adds a space to C.java
build("interprojectdeps1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps1","bin")));
assertTrue("There should be state for project interprojectdeps1",ajs!=null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
}
/**
* The C.java file modified in this test has an inner class - which has two ctors - this checks
* how they are mangled with an instance of C.
*
*/
public void testStateManagement4() {
File binDirForInterproject2 = new File(getFile("interprojectdeps2","bin"));
initialiseProject("interprojectdeps2");
build("interprojectdeps2"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject2);
assertTrue("There should be state for project interprojectdeps2",ajs!=null);
assertTrue("Should be no struc changes as its a full build: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("interprojectdeps2","inc1"); // minor change to C.java
build("interprojectdeps2");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps2","bin")));
assertTrue("There should be state for project interprojectdeps1",ajs!=null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
}
/**
* The C.java file modified in this test has an inner class - it has two ctors but
* also a reference to C.this in it - which will give rise to an accessor being
* created in C
*
*/
public void testStateManagement5() {
File binDirForInterproject3 = new File(getFile("interprojectdeps3","bin"));
initialiseProject("interprojectdeps3");
build("interprojectdeps3"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject3);
assertTrue("There should be state for project interprojectdeps3",ajs!=null);
assertTrue("Should be no struc changes as its a full build: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("interprojectdeps3","inc1"); // minor change to C.java
build("interprojectdeps3");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps3","bin")));
assertTrue("There should be state for project interprojectdeps1",ajs!=null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
}
/**
* Now the most complex test. Create a dependancy between two projects. Building
* one may affect whether the other does an incremental or full build. The
* structural information recorded in the state object should be getting used
* to control whether a full build is necessary...
*/
public void testBuildingDependantProjects() {
initialiseProject("P1");
initialiseProject("P2");
configureNewProjectDependency("P2","P1");
build("P1");
build("P2"); // now everything is consistent and compiled
alter("P1","inc1"); // adds a second class
build("P1");
build("P2"); // although a second class was added - P2 can't be using it, so we don't full build here :)
checkWasntFullBuild();
alter("P1","inc3"); // structurally changes one of the classes
build("P1");
build("P2"); // build notices the structural change
checkWasFullBuild();
alter("P1","inc4");
build("P1");
build("P2"); // build sees a change but works out its not structural
checkWasntFullBuild();
}
public void testPr85132() {
initialiseProject("PR85132");
build("PR85132");
alter("PR85132","inc1");
build("PR85132");
}
// parameterization of generic aspects
public void testPr125405() {
initialiseProject("PR125405");
build("PR125405");
checkCompileWeaveCount(1,1);
alter("PR125405","inc1");
build("PR125405");
// "only abstract aspects can have type parameters"
checkForError("only abstract aspects can have type parameters");
alter("PR125405","inc2");
build("PR125405");
checkCompileWeaveCount(1,1);
assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0);
}
public void testPr128618() {
initialiseProject("PR128618_1");
initialiseProject("PR128618_2");
configureNewProjectDependency("PR128618_2","PR128618_1");
assertTrue("there should be no warning messages before we start",
MyTaskListManager.getWarningMessages().isEmpty());
build("PR128618_1");
build("PR128618_2");
List warnings = MyTaskListManager.getWarningMessages();
assertTrue("Should be one warning, but there are #"+warnings.size(),warnings.size()==1);
IMessage msg = (IMessage)(MyTaskListManager.getWarningMessages().get(0));
assertEquals("warning should be against the FFDC.aj resource","FFDC.aj",msg.getSourceLocation().getSourceFile().getName());
alter("PR128618_2","inc1");
build("PR128618_2");
checkWasntFullBuild();
IMessage msg2 = (IMessage)(MyTaskListManager.getWarningMessages().get(0));
assertEquals("warning should be against the FFDC.aj resource","FFDC.aj",msg2.getSourceLocation().getSourceFile().getName());
assertFalse("a new warning message should have been generated", msg.equals(msg2));
}
public void testPr92837() {
initialiseProject("PR92837");
build("PR92837");
alter("PR92837","inc1");
build("PR92837");
}
public void testPr119570() {
initialiseProject("PR119570");
build("PR119570");
assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0);
}
public void testPr119570_2() {
initialiseProject("PR119570_2");
build("PR119570_2");
List l = MyTaskListManager.getWarningMessages();
assertTrue("Should be no warnings, but got "+l,l.size()==0);
}
// If you fiddle with the compiler options - you must manually reset the options at the end of the test
public void testPr117209() {
try {
initialiseProject("pr117209");
configureNonStandardCompileOptions("-proceedOnError");
build("pr117209");
checkCompileWeaveCount(6,6);
} finally {
MyBuildOptionsAdapter.reset();
}
}
public void testPr114875() {
initialiseProject("pr114875");
build("pr114875");
alter("pr114875","inc1");
build("pr114875");
checkWasFullBuild();
alter("pr114875","inc2");
build("pr114875");
checkWasFullBuild(); // back to the source for an aspect change
}
public void testPr117882() {
// AjdeInteractionTestbed.VERBOSE=true;
// AjdeInteractionTestbed.configureBuildStructureModel(true);
initialiseProject("PR117882");
build("PR117882");
checkWasFullBuild();
alter("PR117882","inc1");
build("PR117882");
checkWasFullBuild(); // back to the source for an aspect
// AjdeInteractionTestbed.VERBOSE=false;
// AjdeInteractionTestbed.configureBuildStructureModel(false);
}
public void testPr117882_2() {
// AjdeInteractionTestbed.VERBOSE=true;
// AjdeInteractionTestbed.configureBuildStructureModel(true);
initialiseProject("PR117882_2");
build("PR117882_2");
checkWasFullBuild();
alter("PR117882_2","inc1");
build("PR117882_2");
checkWasFullBuild(); // back to the source...
//checkCompileWeaveCount(1,4);
//fullBuild("PR117882_2");
//checkWasFullBuild();
// AjdeInteractionTestbed.VERBOSE=false;
// AjdeInteractionTestbed.configureBuildStructureModel(false);
}
public void testPr115251() {
//AjdeInteractionTestbed.VERBOSE=true;
initialiseProject("PR115251");
build("PR115251");
checkWasFullBuild();
alter("PR115251","inc1");
build("PR115251");
checkWasFullBuild(); // back to the source
}
// public void testPr124399() {
// AjdeInteractionTestbed.VERBOSE=true;
// configureBuildStructureModel(true);
// initialiseProject("PR124399");
// build("PR124399");
// checkWasFullBuild();
// alter("PR124399","inc1");
// build("PR124399");
// checkWasntFullBuild();
// }
public void testPr121384() {
// AjdeInteractionTestbed.VERBOSE=true;
// AsmManager.setReporting("c:/foo.txt",true,true,true,false);
MyBuildOptionsAdapter.setNonStandardOptions("-showWeaveInfo");
configureBuildStructureModel(true);
initialiseProject("pr121384");
build("pr121384");
checkWasFullBuild();
alter("pr121384","inc1");
build("pr121384");
checkWasntFullBuild();
}
/* public void testPr111779() {
super.VERBOSE=true;
initialiseProject("PR111779");
build("PR111779");
alter("PR111779","inc1");
build("PR111779");
}
*/
public void testPr93310_1() {
initialiseProject("PR93310_1");
build("PR93310_1");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_1" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java";
(new File(fileC2)).delete();
alter("PR93310_1","inc1");
build("PR93310_1");
checkWasFullBuild();
int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size();
assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1);
String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0);
assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java"));
}
public void testPr93310_2() {
initialiseProject("PR93310_2");
build("PR93310_2");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_2" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java";
(new File(fileC2)).delete();
alter("PR93310_2","inc1");
build("PR93310_2");
checkWasFullBuild();
int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size();
assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1);
String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0);
assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java"));
}
// Stage1: Compile two files, pack.A and pack.A1 - A1 sets a protected field in A.
// Stage2: make the field private in class A > gives compile error
// Stage3: Add a new aspect whilst there is a compile error !
public void testPr113531() {
initialiseProject("PR113531");
build("PR113531");
assertFalse("build should have compiled ok",
MyTaskListManager.hasErrorMessages());
alter("PR113531","inc1");
build("PR113531");
assertEquals("error message should be 'foo cannot be resolved' ",
"foo cannot be resolved",
((IMessage)MyTaskListManager.getErrorMessages().get(0))
.getMessage());
alter("PR113531","inc2");
build("PR113531");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
assertEquals("error message should be 'foo cannot be resolved' ",
"foo cannot be resolved",
((IMessage)MyTaskListManager.getErrorMessages().get(0))
.getMessage());
}
// Stage 1: Compile the 4 files, pack.A2 extends pack.A1 (aspects) where
// A2 uses a protected field in A1 and pack.C2 extends pack.C1 (classes)
// where C2 uses a protected field in C1
// Stage 2: make the field private in class C1 ==> compile errors in C2
// Stage 3: make the field private in aspect A1 whilst there's the compile
// error.
// There shouldn't be a BCExcpetion saying can't find delegate for pack.C2
public void testPr119882() {
initialiseProject("PR119882");
build("PR119882");
assertFalse("build should have compiled ok",MyTaskListManager.hasErrorMessages());
alter("PR119882","inc1");
build("PR119882");
//fullBuild("PR119882");
List errors = MyTaskListManager.getErrorMessages();
assertTrue("Should be at least one error, but got none",errors.size()==1);
assertEquals("error message should be 'i cannot be resolved' ",
"i cannot be resolved",
((IMessage)errors.get(0))
.getMessage());
alter("PR119882","inc2");
build("PR119882");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
assertEquals("error message should be 'i cannot be resolved' ",
"i cannot be resolved",
((IMessage)errors.get(0))
.getMessage());
}
public void testPr112736() {
// AjdeInteractionTestbed.VERBOSE = true;
initialiseProject("PR112736");
build("PR112736");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR112736" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "A.java";
(new File(fileC2)).delete();
alter("PR112736","inc1");
build("PR112736");
checkWasFullBuild();
}
/**
* We have problems with multiple rewrites of a pointcut across incremental builds.
*/
public void testPr113257() {
initialiseProject("PR113257");
build("PR113257");
alter("PR113257","inc1");
build("PR113257");
checkWasFullBuild(); // back to the source
alter("PR113257","inc1");
build("PR113257");
}
public void testPr123612() {
initialiseProject("PR123612");
build("PR123612");
alter("PR123612","inc1");
build("PR123612");
checkWasFullBuild(); // back to the source
}
public void testPr128655() {
configureNonStandardCompileOptions("-showWeaveInfo");
initialiseProject("pr128655");
build("pr128655");
List firstBuildMessages = MyTaskListManager.getWeavingMessages();
assertTrue("Should be at least one message about the dec @type, but there were none",firstBuildMessages.size()>0);
alter("pr128655","inc1");
build("pr128655");
checkWasntFullBuild(); // back to the source
List secondBuildMessages = MyTaskListManager.getWeavingMessages();
// check they are the same
for (int i = 0; i < firstBuildMessages.size(); i++) {
IMessage m1 = (IMessage)firstBuildMessages.get(i);
IMessage m2 = (IMessage)secondBuildMessages.get(i);
if (!m1.toString().equals(m2.toString())) {
System.err.println("Message during first build was: "+m1);
System.err.println("Message during second build was: "+m1);
fail("The two messages should be the same, but are not: \n"+m1+"!="+m2);
}
}
}
// Similar to above, but now the annotation is in the default package
public void testPr128655_2() {
configureNonStandardCompileOptions("-showWeaveInfo");
initialiseProject("pr128655_2");
build("pr128655_2");
List firstBuildMessages = MyTaskListManager.getWeavingMessages();
assertTrue("Should be at least one message about the dec @type, but there were none",firstBuildMessages.size()>0);
alter("pr128655_2","inc1");
build("pr128655_2");
checkWasntFullBuild(); // back to the source
List secondBuildMessages = MyTaskListManager.getWeavingMessages();
// check they are the same
for (int i = 0; i < firstBuildMessages.size(); i++) {
IMessage m1 = (IMessage)firstBuildMessages.get(i);
IMessage m2 = (IMessage)secondBuildMessages.get(i);
if (!m1.toString().equals(m2.toString())) {
System.err.println("Message during first build was: "+m1);
System.err.println("Message during second build was: "+m1);
fail("The two messages should be the same, but are not: \n"+m1+"!="+m2);
}
}
}
// test for comment #31 - NPE
public void testPr129163() {
configureBuildStructureModel(true);
initialiseProject("PR129613");
build("PR129613");
alter("PR129613","inc1");
build("PR129613");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
assertEquals("warning message should be 'no match for this type name: File [Xlint:invalidAbsoluteTypeName]' ",
"no match for this type name: File [Xlint:invalidAbsoluteTypeName]",
((IMessage)MyTaskListManager.getWarningMessages().get(0))
.getMessage());
configureBuildStructureModel(false);
}
// test for comment #0 - adding a comment to a class file shouldn't
// cause us to go back to source and recompile everything. To force this
// to behave like AJDT we need to include the aspect in 'inc1' so that
// when AjState looks at its timestamp it thinks the aspect has been modified.
// The logic within CrosscuttingMembers should then work out correctly
// that there haven't really been any changes within the aspect and so
// we shouldn't go back to source.
public void testPr129163_2() {
// want to behave like AJDT
configureBuildStructureModel(true);
initialiseProject("pr129163_2");
build("pr129163_2");
checkWasFullBuild();
alter("pr129163_2","inc1");
build("pr129163_2");
checkWasntFullBuild(); // shouldn't be a full build because the
// aspect hasn't changed
configureBuildStructureModel(false);
}
// test for comment #6 - simulates AJDT core builder test testBug99133a -
// changing the contents of a method within a class shouldn't force a
// full build of a dependant project. To force this to behave like AJDT
// 'inc1' of the dependant project should just be a copy of 'base' so that
// AjState thinks somethings changed within the dependant project and
// we do a build. Similarly, 'inc1' of the project depended on should
// include the aspect even though nothing's changed within it. This causes
// AjState to think that the aspect has changed. Together its then up to
// logic within CrosscuttingMembers and various equals methods to decide
// correctly that we don't have to go back to source.
public void testPr129163_3() {
configureBuildStructureModel(true);
initialiseProject("PR129163_4");
build("PR129163_4");
checkWasFullBuild(); // should be a full build because initializing project
initialiseProject("PR129163_3");
configureNewProjectDependency("PR129163_3","PR129163_4");
build("PR129163_3");
checkWasFullBuild(); // should be a full build because initializing project
alter("PR129163_4","inc1");
build("PR129163_4");
checkWasntFullBuild(); // should be an incremental build because although
// "inc1" includes the aspect A1.aj, it actually hasn't
// changed so we shouldn't go back to source
alter("PR129163_3","inc1");
build("PR129163_3");
checkWasntFullBuild(); // should be an incremental build because nothing has
// changed within the class and no aspects have changed
// within the running of the test
configureBuildStructureModel(false);
}
public void testPr131505() {
configureNonStandardCompileOptions("-outxml");
initialiseProject("PR131505");
build("PR131505");
checkWasFullBuild();
// aop.xml file shouldn't contain any aspects
checkXMLAspectCount("PR131505","",0);
// add a new aspect A which should be included in the aop.xml file
alter("PR131505","inc1");
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",1);
checkXMLAspectCount("PR131505","A",1);
// make changes to the class file which shouldn't affect the contents
// of the aop.xml file
alter("PR131505","inc2");
build("PR131505");
checkWasntFullBuild();
checkXMLAspectCount("PR131505","",1);
checkXMLAspectCount("PR131505","A",1);
// add another new aspect A1 which should also be included in the aop.xml file
// ...there should be no duplicate entries in the file
alter("PR131505","inc3");
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",2);
checkXMLAspectCount("PR131505","A1",1);
checkXMLAspectCount("PR131505","A",1);
// delete aspect A1 which meanss that aop.xml file should only contain A
File a1 = new File(getWorkingDir().getAbsolutePath()
+ File.separatorChar + "PR131505" + File.separatorChar + "A1.aj");
a1.delete();
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",1);
checkXMLAspectCount("PR131505","A1",0);
checkXMLAspectCount("PR131505","A",1);
// add another aspect called A which is in a different package, both A
// and pkg.A should be included in the aop.xml file
alter("PR131505","inc4");
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",2);
checkXMLAspectCount("PR131505","A",1);
checkXMLAspectCount("PR131505","pkg.A",1);
}
public void testPr133532() {
initialiseProject("PR133532");
build("PR133532");
alter("PR133532","inc1");
build("PR133532");
alter("PR133532","inc2");
build("PR133532");
assertTrue("There should be no errors reported:\n"+MyTaskListManager.getErrorMessages(),
MyTaskListManager.getErrorMessages().isEmpty());
}
public void testPr133532_2() {
initialiseProject("pr133532_2");
build("pr133532_2");
alter("pr133532_2","inc2");
build("pr133532_2");
assertTrue("There should be no errors reported:\n"+MyTaskListManager.getErrorMessages(),
MyTaskListManager.getErrorMessages().isEmpty());
String decisions = AjdeInteractionTestbed.MyStateListener.getDecisions();
String expect="Need to recompile 'A.aj'";
assertTrue("Couldn't find build decision: '"+expect+"' in the list of decisions made:\n"+decisions,
decisions.indexOf(expect)!=-1);
}
// other possible tests:
// - memory usage (freemem calls?)
// - relationship map
// ---------------------------------------------------------------------------------------------------
/**
* Check we compiled/wove the right number of files, passing '-1' indicates you don't care about
* that number.
*/
private void checkCompileWeaveCount(int expCompile,int expWoven) {
if (expCompile!=-1 && getCompiledFiles().size()!=expCompile)
fail("Expected compilation of "+expCompile+" files but compiled "+getCompiledFiles().size()+
"\n"+printCompiledAndWovenFiles());
if (expWoven!=-1 && getWovenClasses().size()!=expWoven)
fail("Expected weaving of "+expWoven+" files but wove "+getWovenClasses().size()+
"\n"+printCompiledAndWovenFiles());
}
private void checkWasntFullBuild() {
assertTrue("Shouldn't have been a full (batch) build",!wasFullBuild());
}
private void checkWasFullBuild() {
assertTrue("Should have been a full (batch) build",wasFullBuild());
}
private void checkForNode(String packageName,String typeName,boolean shouldBeFound) {
IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForType(packageName,typeName);
if (shouldBeFound) {
if (ipe==null) printModel();
assertTrue("Should have been able to find '"+packageName+"."+typeName+"' in the asm",ipe!=null);
} else {
if (ipe!=null) printModel();
assertTrue("Should have NOT been able to find '"+packageName+"."+typeName+"' in the asm",ipe==null);
}
}
private void printModel() {
try {
AsmManager.dumptree(AsmManager.getDefault().getHierarchy().getRoot(),0);
} catch (IOException e) {
e.printStackTrace();
}
}
public void build(String projectName) {
constructUpToDateLstFile(projectName,"build.lst");
build(projectName,"build.lst");
if (AjdeInteractionTestbed.VERBOSE) printBuildReport();
}
public void fullBuild(String projectName) {
constructUpToDateLstFile(projectName,"build.lst");
fullBuild(projectName,"build.lst");
if (AjdeInteractionTestbed.VERBOSE) printBuildReport();
}
private void constructUpToDateLstFile(String pname,String configname) {
File projectBase = new File(sandboxDir,pname);
File toConstruct = new File(projectBase,configname);
List filesForCompilation = new ArrayList();
collectUpFiles(projectBase,projectBase,filesForCompilation);
try {
FileOutputStream fos = new FileOutputStream(toConstruct);
DataOutputStream dos = new DataOutputStream(fos);
for (Iterator iter = filesForCompilation.iterator(); iter.hasNext();) {
String file = (String) iter.next();
dos.writeBytes(file+"\n");
}
dos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void checkForError(String anError) {
List messages = MyTaskListManager.getErrorMessages();
for (Iterator iter = messages.iterator(); iter.hasNext();) {
IMessage element = (IMessage) iter.next();
if (element.getMessage().indexOf(anError)!=-1) return;
}
fail("Didn't find the error message:\n'"+anError+"'.\nErrors that occurred:\n"+MyTaskListManager.getErrorMessages());
}
private void collectUpFiles(File location,File base,List collectionPoint) {
String contents[] = location.list();
if (contents==null) return;
for (int i = 0; i < contents.length; i++) {
String string = contents[i];
File f = new File(location,string);
if (f.isDirectory()) {
collectUpFiles(f,base,collectionPoint);
} else if (f.isFile() && (f.getName().endsWith(".aj") || f.getName().endsWith(".java"))) {
String fileFound;
try {
fileFound = f.getCanonicalPath();
String toRemove = base.getCanonicalPath();
if (!fileFound.startsWith(toRemove)) throw new RuntimeException("eh? "+fileFound+" "+toRemove);
collectionPoint.add(fileFound.substring(toRemove.length()+1));//+1 captures extra separator
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Fill in the working directory with the project base files,
* from the 'base' folder.
*/
protected void initialiseProject(String p) {
File projectSrc=new File(testdataSrcDir+File.separatorChar+p+File.separatorChar+"base");
File destination=new File(getWorkingDir(),p);
if (!destination.exists()) {destination.mkdir();}
copy(projectSrc,destination);//,false);
}
/*
* Applies an overlay onto the project being tested - copying
* the contents of the specified overlay directory.
*/
private void alter(String projectName,String overlayDirectory) {
File projectSrc =new File(testdataSrcDir+File.separatorChar+projectName+
File.separatorChar+overlayDirectory);
File destination=new File(getWorkingDir(),projectName);
copy(projectSrc,destination);
}
/**
* Copy the contents of some directory to another location - the
* copy is recursive.
*/
private void copy(File from, File to) {
String contents[] = from.list();
if (contents==null) return;
for (int i = 0; i < contents.length; i++) {
String string = contents[i];
File f = new File(from,string);
File t = new File(to,string);
if (f.isDirectory() && !f.getName().startsWith("inc")) {
t.mkdir();
copy(f,t);
} else if (f.isFile()) {
StringBuffer sb = new StringBuffer();
//if (VERBOSE) System.err.println("Copying "+f+" to "+t);
FileUtil.copyFile(f,t,sb);
if (sb.length()!=0) { System.err.println(sb.toString());}
}
}
}
private static void log(String msg) {
if (VERBOSE) System.out.println(msg);
}
/**
* Count the number of times a specified aspectName appears in the default
* aop.xml file and compare with the expected number of occurrences. If just
* want to count the number of aspects mentioned within the file then
* pass "" for the aspectName, otherwise, specify the name of the
* aspect interested in.
*/
private void checkXMLAspectCount(String projectName, String aspectName, int expectedOccurrences) {
int aspectCount = 0;
File aopXML = new File(getWorkingDir().getAbsolutePath()
+ File.separatorChar + projectName + File.separatorChar
+ "bin" + File.separatorChar + "META-INF" + File.separatorChar + "aop.xml");
if (!aopXML.exists()) {
fail("Expected file " + aopXML.getAbsolutePath() + " to exist but it doesn't");
}
try {
BufferedReader reader = new BufferedReader(new FileReader(aopXML));
String line = reader.readLine();
while (line != null) {
if (aspectName.equals("") && line.indexOf("aspect name=\"") != -1) {
aspectCount++;
} else if (line.indexOf("aspect name=\""+aspectName+"\"") != -1) {
aspectCount++;
}
line = reader.readLine();
}
reader.close();
} catch (IOException ie) {
ie.printStackTrace();
}
if (aspectCount != expectedOccurrences) {
fail("Expected aspect " + aspectName + " to appear " + expectedOccurrences + " times" +
" in the aop.xml file but found " + aspectCount + " occurrences");
}
}
}
|
134,541 |
Bug 134541 adviceDidNotMatch's line number doesn't keep up with line number of advice
|
When advice doesn't match in a 1.5.0 enabled project, there is an adviceDidNotMatch warning against the line number of the advice. If you insert a line before this advice and save then the warning stays associated with the original line and not the new one. Full building puts the warning against the new line. This is a regression and didn't happen in AJ 1.5.0.
|
resolved fixed
|
94d8b82
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-04-06T10:44:14Z | 2006-04-03T16:00:00Z |
weaver/src/org/aspectj/weaver/CrosscuttingMembers.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the 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.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.aspectj.weaver.bcel.BcelTypeMunger;
import org.aspectj.weaver.patterns.Declare;
import org.aspectj.weaver.patterns.DeclareAnnotation;
import org.aspectj.weaver.patterns.DeclareErrorOrWarning;
import org.aspectj.weaver.patterns.DeclareParents;
import org.aspectj.weaver.patterns.DeclarePrecedence;
import org.aspectj.weaver.patterns.DeclareSoft;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.PointcutRewriter;
/**
* This holds on to all members that have an invasive effect outside of
* there own compilation unit. These members need to be all gathered up and in
* a world before any weaving can take place.
*
* They are also important in the compilation process and need to be gathered
* up before the inter-type declaration weaving stage (unsurprisingly).
*
* All members are concrete.
*
* @author Jim Hugunin
*/
public class CrosscuttingMembers {
private ResolvedType inAspect;
private World world;
private PerClause perClause;
private List shadowMungers = new ArrayList(4);
private List typeMungers = new ArrayList(4);
private List lateTypeMungers = new ArrayList(0);
private List declareParents = new ArrayList(4);
private List declareSofts = new ArrayList(0);
private List declareDominates = new ArrayList(4);
// These are like declare parents type mungers
private List declareAnnotationsOnType = new ArrayList();
private List declareAnnotationsOnField = new ArrayList();
private List declareAnnotationsOnMethods = new ArrayList(); // includes ctors
public CrosscuttingMembers(ResolvedType 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) throw new Error("FIXME AV - should not happen or what ?");//return; //???
typeMungers.add(m);
}
public void addLateTypeMungers(Collection c) {
lateTypeMungers.addAll(c);
}
public void addLateTypeMunger(ConcreteTypeMunger m) {
lateTypeMungers.add(m);
}
public void addDeclares(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); ) {
addDeclare( (Declare)i.next() );
}
}
public void addDeclare(Declare declare) {
// this is not extensible, oh well
if (declare instanceof DeclareErrorOrWarning) {
ShadowMunger m = new Checker((DeclareErrorOrWarning)declare);
m.setDeclaringType(declare.getDeclaringType());
addShadowMunger(m);
} else if (declare instanceof DeclarePrecedence) {
declareDominates.add(declare);
} else if (declare instanceof DeclareParents) {
DeclareParents dp = (DeclareParents)declare;
exposeTypes(dp.getParents().getExactTypes());
declareParents.add(dp);
} else if (declare instanceof DeclareSoft) {
DeclareSoft d = (DeclareSoft)declare;
// Ordered so that during concretization we can check the related munger
ShadowMunger m = Advice.makeSoftener(world, d.getPointcut(), d.getException(),inAspect,d);
m.setDeclaringType(d.getDeclaringType());
Pointcut concretePointcut = d.getPointcut().concretize(inAspect, d.getDeclaringType(), 0,m);
m.pointcut = concretePointcut;
declareSofts.add(new DeclareSoft(d.getException(), concretePointcut));
addConcreteShadowMunger(m);
} else if (declare instanceof DeclareAnnotation) {
// FIXME asc perf Possible Improvement. Investigate why this is called twice in a weave ?
DeclareAnnotation da = (DeclareAnnotation)declare;
if (da.getAspect() == null) da.setAspect(this.inAspect);
if (da.isDeclareAtType()) {
declareAnnotationsOnType.add(da);
} else if (da.isDeclareAtField()) {
declareAnnotationsOnField.add(da);
} else if (da.isDeclareAtMethod() || da.isDeclareAtConstuctor()) {
declareAnnotationsOnMethods.add(da);
}
} else {
throw new RuntimeException("unimplemented");
}
}
public void exposeTypes(Collection typesToExpose) {
for (Iterator i = typesToExpose.iterator(); i.hasNext(); ) {
exposeType((UnresolvedType)i.next());
}
}
public void exposeType(UnresolvedType typeToExpose) {
if (ResolvedType.isMissing(typeToExpose)) return;
if (typeToExpose.isParameterizedType() || typeToExpose.isRawType()) {
if (typeToExpose instanceof ResolvedType) {
typeToExpose = ((ResolvedType)typeToExpose).getGenericType();
} else {
typeToExpose = UnresolvedType.forSignature(typeToExpose.getErasureSignature());
}
}
ResolvedMember member = new ResolvedMemberImpl(
Member.STATIC_INITIALIZATION, typeToExpose, 0, ResolvedType.VOID, "", UnresolvedType.NONE);
addTypeMunger(world.concreteTypeMunger(
new PrivilegedAccessMunger(member), inAspect));
}
public void addPrivilegedAccesses(Collection accessedMembers) {
for (Iterator i = accessedMembers.iterator(); i.hasNext(); ) {
addPrivilegedAccess( (ResolvedMember)i.next() );
}
}
private void addPrivilegedAccess(ResolvedMember member) {
//System.err.println("add priv access: " + member);
addTypeMunger(world.concreteTypeMunger(new PrivilegedAccessMunger(member), inAspect));
}
public Collection getCflowEntries() {
ArrayList ret = new ArrayList();
for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) {
ShadowMunger m = (ShadowMunger)i.next();
if (m instanceof Advice) {
Advice a = (Advice)m;
if (a.getKind().isCflow()) {
ret.add(a);
}
}
}
return ret;
}
/**
* Updates the records if something has changed. This is called at most twice, firstly
* whilst collecting ITDs and declares. At this point the CrosscuttingMembers we're
* comparing ourselves with doesn't know about shadowmungers. Therefore a straight comparison
* with the existing list of shadowmungers would return that something has changed
* even though it might not have, so in this first round we ignore the shadowMungers.
* The second time this is called is whilst we're preparing to weave. At this point
* we know everything in the system and so we're able to compare the shadowMunger list.
* (see bug 129163)
*
* @param other
* @param careAboutShadowMungers
* @return true if something has changed since the last time this method was
* called, false otherwise
*/
public boolean replaceWith(CrosscuttingMembers other,boolean careAboutShadowMungers) {
boolean changed = false;
if (perClause == null || !perClause.equals(other.perClause)) {
changed = true;
perClause = other.perClause;
}
//XXX all of the below should be set equality rather than list equality
//System.err.println("old: " + shadowMungers + " new: " + other.shadowMungers);
if (careAboutShadowMungers) {
// bug 129163: use set equality rather than list equality
Set theseShadowMungers = new HashSet();
theseShadowMungers.addAll(shadowMungers);
Set otherShadowMungers = new HashSet();
otherShadowMungers.addAll(other.shadowMungers);
PointcutRewriter pr = new PointcutRewriter();
for (Iterator iter = otherShadowMungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
Pointcut p = munger.getPointcut();
Pointcut newP = pr.rewrite(p);
munger.setPointcut(newP);
}
if (!theseShadowMungers.equals(otherShadowMungers)) {
changed = true;
shadowMungers = other.shadowMungers;
}
}
// bug 129163: use set equality rather than list equality and
// if we dont care about shadow mungers then ignore those
// typeMungers which are created to help with the implementation
// of shadowMungers
Set theseTypeMungers = new HashSet();
Set otherTypeMungers = new HashSet();
if (!careAboutShadowMungers) {
for (Iterator iter = typeMungers.iterator(); iter.hasNext();) {
Object o = iter.next();
if (o instanceof BcelTypeMunger) {
BcelTypeMunger typeMunger = (BcelTypeMunger) o;
if (!typeMunger.existsToSupportShadowMunging()) {
theseTypeMungers.add(typeMunger);
}
} else {
theseTypeMungers.add(o);
}
}
for (Iterator iter = other.typeMungers.iterator(); iter.hasNext();) {
Object o = iter.next();
if (o instanceof BcelTypeMunger) {
BcelTypeMunger typeMunger = (BcelTypeMunger) o;
if (!typeMunger.existsToSupportShadowMunging()) {
otherTypeMungers.add(typeMunger);
}
} else {
otherTypeMungers.add(o);
}
}
} else {
theseTypeMungers.addAll(typeMungers);
otherTypeMungers.addAll(other.typeMungers);
}
// initial go at equivalence logic rather than set compare (see pr133532)
// if (theseTypeMungers.size()!=otherTypeMungers.size()) {
// changed = true;
// typeMungers = other.typeMungers;
// } else {
// boolean foundInequality=false;
// for (Iterator iter = theseTypeMungers.iterator(); iter.hasNext() && !foundInequality;) {
// Object thisOne = (Object) iter.next();
// boolean foundInOtherSet = false;
// for (Iterator iterator = otherTypeMungers.iterator(); iterator.hasNext();) {
// Object otherOne = (Object) iterator.next();
// if (thisOne instanceof ConcreteTypeMunger && otherOne instanceof ConcreteTypeMunger) {
// if (((ConcreteTypeMunger)thisOne).equivalentTo(otherOne)) {
// foundInOtherSet=true;
// } else if (thisOne.equals(otherOne)) {
// foundInOtherSet=true;
// }
// } else {
// if (thisOne.equals(otherOne)) {
// foundInOtherSet=true;
// }
// }
// }
// if (!foundInOtherSet) foundInequality=true;
// }
// if (foundInequality) {
// changed = true;
// typeMungers = other.typeMungers;
//// } else {
//// typeMungers = other.typeMungers;
// }
// }
if (!theseTypeMungers.equals(otherTypeMungers)) {
changed = true;
typeMungers = other.typeMungers;
}
if (!lateTypeMungers.equals(other.lateTypeMungers)) {
changed = true;
lateTypeMungers = other.lateTypeMungers;
}
if (!declareDominates.equals(other.declareDominates)) {
changed = true;
declareDominates = other.declareDominates;
}
if (!declareParents.equals(other.declareParents)) {
changed = true;
declareParents = other.declareParents;
}
if (!declareSofts.equals(other.declareSofts)) {
changed = true;
declareSofts = other.declareSofts;
}
// DECAT for when attempting to replace an aspect
if (!declareAnnotationsOnType.equals(other.declareAnnotationsOnType)) {
changed = true;
declareAnnotationsOnType = other.declareAnnotationsOnType;
}
if (!declareAnnotationsOnField.equals(other.declareAnnotationsOnField)) {
changed = true;
declareAnnotationsOnField = other.declareAnnotationsOnField;
}
if (!declareAnnotationsOnMethods.equals(other.declareAnnotationsOnMethods)) {
changed = true;
declareAnnotationsOnMethods = other.declareAnnotationsOnMethods;
}
return changed;
}
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;
}
public List getLateTypeMungers() {
return lateTypeMungers;
}
public List getDeclareAnnotationOnTypes() {
return declareAnnotationsOnType;
}
public List getDeclareAnnotationOnFields() {
return declareAnnotationsOnField;
}
/**
* includes declare @method and @constructor
*/
public List getDeclareAnnotationOnMethods() {
return declareAnnotationsOnMethods;
}
}
|
134,541 |
Bug 134541 adviceDidNotMatch's line number doesn't keep up with line number of advice
|
When advice doesn't match in a 1.5.0 enabled project, there is an adviceDidNotMatch warning against the line number of the advice. If you insert a line before this advice and save then the warning stays associated with the original line and not the new one. Full building puts the warning against the new line. This is a regression and didn't happen in AJ 1.5.0.
|
resolved fixed
|
94d8b82
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-04-06T10:44:14Z | 2006-04-03T16:00:00Z |
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.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.weaver.patterns.CflowPointcut;
import org.aspectj.weaver.patterns.DeclareParents;
import org.aspectj.weaver.patterns.IVerificationRequired;
/**
* This holds on to all CrosscuttingMembers for a world. It handles
* management of change.
*
* @author Jim Hugunin
*/
public class CrosscuttingMembersSet {
private World world;
//FIXME AV - ? we may need a sequencedHashMap there to ensure source based precedence for @AJ advice
private Map /* ResolvedType (the aspect) > CrosscuttingMembers */members = new HashMap();
private List shadowMungers = null;
private List typeMungers = null;
private List lateTypeMungers = null;
private List declareSofts = null;
private List declareParents = null;
private List declareAnnotationOnTypes = null;
private List declareAnnotationOnFields = null;
private List declareAnnotationOnMethods= null; // includes ctors
private List declareDominates = null;
private boolean changedSinceLastReset = false;
private List /*IVerificationRequired*/ verificationList = null; // List of things to be verified once the type system is 'complete'
public CrosscuttingMembersSet(World world) {
this.world = world;
}
public boolean addOrReplaceAspect(ResolvedType aspectType) {
return addOrReplaceAspect(aspectType,true);
}
/**
* @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(ResolvedType aspectType,boolean careAboutShadowMungers) {
boolean change = false;
CrosscuttingMembers xcut = (CrosscuttingMembers)members.get(aspectType);
if (xcut == null) {
members.put(aspectType, aspectType.collectCrosscuttingMembers());
clearCaches();
CflowPointcut.clearCaches(aspectType);
change = true;
} else {
if (xcut.replaceWith(aspectType.collectCrosscuttingMembers(),careAboutShadowMungers)) {
clearCaches();
CflowPointcut.clearCaches(aspectType);
change = true;
} else {
change = false;
}
}
if (aspectType.isAbstract()) {
// we might have sub-aspects that need to re-collect their crosscutting members from us
boolean ancestorChange = addOrReplaceDescendantsOf(aspectType,careAboutShadowMungers);
change = change || ancestorChange;
}
changedSinceLastReset = changedSinceLastReset || change;
return change;
}
private boolean addOrReplaceDescendantsOf(ResolvedType aspectType,boolean careAboutShadowMungers) {
//System.err.println("Looking at descendants of "+aspectType.getName());
Set knownAspects = members.keySet();
Set toBeReplaced = new HashSet();
for(Iterator it = knownAspects.iterator(); it.hasNext(); ) {
ResolvedType candidateDescendant = (ResolvedType)it.next();
if ((candidateDescendant != aspectType) && (aspectType.isAssignableFrom(candidateDescendant))) {
toBeReplaced.add(candidateDescendant);
}
}
boolean change = false;
for (Iterator it = toBeReplaced.iterator(); it.hasNext(); ) {
ResolvedType next = (ResolvedType)it.next();
boolean thisChange = addOrReplaceAspect(next,careAboutShadowMungers);
change = change || thisChange;
}
return change;
}
public void addAdviceLikeDeclares(ResolvedType aspectType) {
CrosscuttingMembers xcut = (CrosscuttingMembers)members.get(aspectType);
xcut.addDeclares(aspectType.collectDeclares(true));
}
public boolean deleteAspect(UnresolvedType aspectType) {
boolean isAspect = members.remove(aspectType) != null;
clearCaches();
return isAspect;
}
public boolean containsAspect(UnresolvedType aspectType) {
return members.containsKey(aspectType);
}
//XXX only for testing
public void addFixedCrosscuttingMembers(ResolvedType aspectType) {
members.put(aspectType, aspectType.crosscuttingMembers);
clearCaches();
}
private void clearCaches() {
shadowMungers = null;
typeMungers = null;
lateTypeMungers = null;
declareSofts = null;
declareParents = null;
declareAnnotationOnFields=null;
declareAnnotationOnMethods=null;
declareAnnotationOnTypes=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 getLateTypeMungers() {
if (lateTypeMungers == null) {
ArrayList ret = new ArrayList();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getLateTypeMungers());
}
lateTypeMungers = ret;
}
return lateTypeMungers;
}
public List getDeclareSofts() {
if (declareSofts == null) {
Set ret = new HashSet();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareSofts());
}
declareSofts = new ArrayList();
declareSofts.addAll(ret);
}
return declareSofts;
}
public List getDeclareParents() {
if (declareParents == null) {
Set ret = new HashSet();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareParents());
}
declareParents = new ArrayList();
declareParents.addAll(ret);
}
return declareParents;
}
// DECAT Merge multiple together
public List getDeclareAnnotationOnTypes() {
if (declareAnnotationOnTypes == null) {
Set ret = new HashSet();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareAnnotationOnTypes());
}
declareAnnotationOnTypes = new ArrayList();
declareAnnotationOnTypes.addAll(ret);
}
return declareAnnotationOnTypes;
}
public List getDeclareAnnotationOnFields() {
if (declareAnnotationOnFields == null) {
Set ret = new HashSet();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareAnnotationOnFields());
}
declareAnnotationOnFields = new ArrayList();
declareAnnotationOnFields.addAll(ret);
}
return declareAnnotationOnFields;
}
/**
* Return an amalgamation of the declare @method/@constructor statements.
*/
public List getDeclareAnnotationOnMethods() {
if (declareAnnotationOnMethods == null) {
Set ret = new HashSet();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareAnnotationOnMethods());
}
declareAnnotationOnMethods = new ArrayList();
declareAnnotationOnMethods.addAll(ret);
}
return declareAnnotationOnMethods;
}
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;
}
public ResolvedType findAspectDeclaringParents(DeclareParents p) {
Set keys = this.members.keySet();
for (Iterator iter = keys.iterator(); iter.hasNext();) {
ResolvedType element = (ResolvedType) iter.next();
for (Iterator i = ((CrosscuttingMembers)members.get(element)).getDeclareParents().iterator(); i.hasNext(); ) {
DeclareParents dp = (DeclareParents)i.next();
if (dp.equals(p)) return element;
}
}
return null;
}
public void reset() {
verificationList=null;
changedSinceLastReset = false;
}
public boolean hasChangedSinceLastReset() {
return changedSinceLastReset;
}
/**
* Record something that needs verifying when we believe the type system is complete.
* Used for things that can't be verified as we go along - for example some
* recursive type variable references (pr133307)
*/
public void recordNecessaryCheck(IVerificationRequired verification) {
if (verificationList==null) verificationList = new ArrayList();
verificationList.add(verification);
}
/**
* Called when type bindings are complete - calls all registered verification
* objects in turn.
*/
public void verify() {
if (verificationList==null) return;
for (Iterator iter = verificationList.iterator(); iter.hasNext();) {
IVerificationRequired element = (IVerificationRequired) iter.next();
element.verify();
}
verificationList = null;
}
}
|
135,001 |
Bug 135001 NPE at at org.aspectj.weaver.bcel.BcelShadow.weaveAroundInline
|
java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelShadow.weaveAroundInline(BcelShadow.java:2109) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:232) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:639) at org.aspectj.weaver.Shadow.implement(Shadow.java:456) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2236) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:491) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:109) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1560) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1511) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1291) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1113) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:311) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:183) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:242) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:161) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191)
|
resolved fixed
|
1a6f695
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-04-06T11:45:02Z | 2006-04-05T12:26:40Z |
tests/bugs152/pr135001/AbstractAspect.java
| |
135,001 |
Bug 135001 NPE at at org.aspectj.weaver.bcel.BcelShadow.weaveAroundInline
|
java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelShadow.weaveAroundInline(BcelShadow.java:2109) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:232) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:639) at org.aspectj.weaver.Shadow.implement(Shadow.java:456) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2236) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:491) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:109) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1560) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1511) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1291) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1113) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:311) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:183) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:242) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:161) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191)
|
resolved fixed
|
1a6f695
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-04-06T11:45:02Z | 2006-04-05T12:26:40Z |
tests/bugs152/pr135001/ConcreteAspect.java
| |
135,001 |
Bug 135001 NPE at at org.aspectj.weaver.bcel.BcelShadow.weaveAroundInline
|
java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelShadow.weaveAroundInline(BcelShadow.java:2109) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:232) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:639) at org.aspectj.weaver.Shadow.implement(Shadow.java:456) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2236) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:491) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:109) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1560) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1511) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1291) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1113) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:311) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:183) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:242) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:161) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191)
|
resolved fixed
|
1a6f695
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-04-06T11:45:02Z | 2006-04-05T12:26:40Z |
tests/bugs152/pr135001/Foo.java
| |
135,001 |
Bug 135001 NPE at at org.aspectj.weaver.bcel.BcelShadow.weaveAroundInline
|
java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelShadow.weaveAroundInline(BcelShadow.java:2109) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:232) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:639) at org.aspectj.weaver.Shadow.implement(Shadow.java:456) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2236) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:491) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:109) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1560) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1511) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1291) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1113) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:311) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:183) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:242) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:161) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191)
|
resolved fixed
|
1a6f695
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-04-06T11:45:02Z | 2006-04-05T12:26:40Z |
tests/src/org/aspectj/systemtest/AllTests15.java
|
/*
* Created on 19-01-2005
*/
package org.aspectj.systemtest;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.aspectj.systemtest.ajc150.AllTestsAspectJ150;
import org.aspectj.systemtest.ajc150.ataspectj.AtAjAnnotationGenTests;
import org.aspectj.systemtest.ajc151.AllTestsAspectJ151;
public class AllTests15 {
public static Test suite() {
TestSuite suite = new TestSuite("AspectJ System Test Suite - JDK 1.5");
//$JUnit-BEGIN$
suite.addTest(AllTests14.suite());
suite.addTest(AllTestsAspectJ150.suite());
suite.addTest(AllTestsAspectJ151.suite());
suite.addTest(AtAjAnnotationGenTests.suite());
//$JUnit-END$
return suite;
}
}
|
135,001 |
Bug 135001 NPE at at org.aspectj.weaver.bcel.BcelShadow.weaveAroundInline
|
java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelShadow.weaveAroundInline(BcelShadow.java:2109) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:232) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:639) at org.aspectj.weaver.Shadow.implement(Shadow.java:456) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2236) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:491) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:109) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1560) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1511) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1291) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1113) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:311) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:183) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:242) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:161) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191)
|
resolved fixed
|
1a6f695
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-04-06T11:45:02Z | 2006-04-05T12:26:40Z |
tests/src/org/aspectj/systemtest/ajc152/Ajc152Tests.java
| |
135,001 |
Bug 135001 NPE at at org.aspectj.weaver.bcel.BcelShadow.weaveAroundInline
|
java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelShadow.weaveAroundInline(BcelShadow.java:2109) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:232) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:639) at org.aspectj.weaver.Shadow.implement(Shadow.java:456) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2236) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:491) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:109) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1560) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1511) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1291) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1113) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:311) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:183) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:242) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:161) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191)
|
resolved fixed
|
1a6f695
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-04-06T11:45:02Z | 2006-04-05T12:26:40Z |
tests/src/org/aspectj/systemtest/ajc152/AllTestsAspectJ152.java
| |
135,001 |
Bug 135001 NPE at at org.aspectj.weaver.bcel.BcelShadow.weaveAroundInline
|
java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelShadow.weaveAroundInline(BcelShadow.java:2109) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:232) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:639) at org.aspectj.weaver.Shadow.implement(Shadow.java:456) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2236) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:491) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:109) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1560) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1511) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1291) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1113) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:311) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:183) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:242) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:161) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191)
|
resolved fixed
|
1a6f695
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-04-06T11:45:02Z | 2006-04-05T12:26:40Z |
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur support for @AJ aspects
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.generic.ACONST_NULL;
import org.aspectj.apache.bcel.generic.ALOAD;
import org.aspectj.apache.bcel.generic.ANEWARRAY;
import org.aspectj.apache.bcel.generic.ArrayType;
import org.aspectj.apache.bcel.generic.BranchInstruction;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.DUP;
import org.aspectj.apache.bcel.generic.DUP_X1;
import org.aspectj.apache.bcel.generic.FieldInstruction;
import org.aspectj.apache.bcel.generic.INVOKEINTERFACE;
import org.aspectj.apache.bcel.generic.INVOKESPECIAL;
import org.aspectj.apache.bcel.generic.INVOKESTATIC;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionTargeter;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.LoadInstruction;
import org.aspectj.apache.bcel.generic.LocalVariableTag;
import org.aspectj.apache.bcel.generic.MULTIANEWARRAY;
import org.aspectj.apache.bcel.generic.NEW;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.PUSH;
import org.aspectj.apache.bcel.generic.ReturnInstruction;
import org.aspectj.apache.bcel.generic.SWAP;
import org.aspectj.apache.bcel.generic.StoreInstruction;
import org.aspectj.apache.bcel.generic.TargetLostException;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.bridge.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.MemberImpl;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewConstructorTypeMunger;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Var;
import org.aspectj.weaver.patterns.AndPointcut;
import org.aspectj.weaver.patterns.IdentityPointcutVisitor;
import org.aspectj.weaver.patterns.NotPointcut;
import org.aspectj.weaver.patterns.OrPointcut;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.ThisOrTargetPointcut;
/*
* 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
// SECRETAPI - for testing, this will tell us if the optimization succeeded *on the last shadow processed*
public static boolean appliedLazyTjpOptimization;
// Some instructions have a target type that will vary
// from the signature (pr109728) (1.4 declaring type issue)
private String actualInstructionTargetType;
// ---- 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);
if (mungers.size()>0) {
List src = mungers;
if (s.mungers==Collections.EMPTY_LIST) s.mungers = new ArrayList();
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 instruction 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);
}
// Now make any jumps to the 'new', the 'dup' or the 'end' now target the nextHandle
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--) {
if (sources[i] instanceof ExceptionRange) {
ExceptionRange it = (ExceptionRange)sources[i];
System.err.println("...");
it.updateTarget(old,fresh,it.getBody());
} else {
sources[i].updateTarget(old, fresh);
}
}
}
}
// records advice that is stopping us doing the lazyTjp optimization
private List badAdvice = null;
public void addAdvicePreventingLazyTjp(BcelAdvice advice) {
if (badAdvice == null) badAdvice = new ArrayList();
badAdvice.add(advice);
}
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) {
if (!world.isJoinpointArrayConstructionEnabled() || !this.getSignature().getDeclaringType().isArray())
deleteNewAndDup(); // no new/dup for new array construction
initializeArgVars();
} else if (getKind() == PreInitialization) { // pr74952
ShadowRange range = getRange();
range.insert(InstructionConstants.NOP,Range.InsideAfter);
} else if (getKind() == ExceptionHandler) {
ShadowRange range = getRange();
InstructionList body = range.getBody();
InstructionHandle start = range.getStart();
// Create a store instruction to put the value from the top of the
// stack into a local variable slot. This is a trimmed version of
// what is in initializeArgVars() (since there is only one argument
// at a handler jp and only before advice is supported) (pr46298)
argVars = new BcelVar[1];
//int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
UnresolvedType tx = getArgType(0);
argVars[0] = genTempVar(tx, "ajc$arg0");
InstructionHandle insertedInstruction =
range.insert(argVars[0].createStore(getFactory()), Range.OutsideBefore);
// Now the exception range starts just after our new instruction.
// The next bit of code changes the exception range to point at
// the store instruction
InstructionTargeter[] targeters = start.getTargeters();
for (int i = 0; i < targeters.length; i++) {
InstructionTargeter t = targeters[i];
if (t instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) t;
er.updateTarget(start, insertedInstruction, body);
}
}
}
// now we ask each munger to request our state
isThisJoinPointLazy = true;//world.isXlazyTjp(); // lazy is default now
badAdvice = null;
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
munger.specializeOn(this);
}
initializeThisJoinPoint();
if (thisJoinPointVar!=null && !isThisJoinPointLazy && badAdvice!=null && badAdvice.size()>1) {
// something stopped us making it a lazy tjp
// can't build tjp lazily, no suitable test...
int valid = 0;
for (Iterator iter = badAdvice.iterator(); iter.hasNext();) {
BcelAdvice element = (BcelAdvice) iter.next();
ISourceLocation sLoc = element.getSourceLocation();
if (sLoc!=null && sLoc.getLine()>0) valid++;
}
if (valid!=0) {
ISourceLocation[] badLocs = new ISourceLocation[valid];
int i = 0;
for (Iterator iter = badAdvice.iterator(); iter.hasNext();) {
BcelAdvice element = (BcelAdvice) iter.next();
ISourceLocation sLoc = element.getSourceLocation();
if (sLoc!=null) badLocs[i++]=sLoc;
}
world.getLint().multipleAdviceStoppingLazyTjp.signal(
new String[] {this.toString()},
getSourceLocation(),badLocs
);
}
}
badAdvice=null;
// If we are an expression kind, we require our target/arguments on the stack
// before we do our actual thing. However, they may have been removed
// from the stack as the shadowMungers have requested state.
// if any of our shadowMungers requested either the arguments or target,
// the munger will have added code
// to pop the target/arguments into temporary variables, represented by
// targetVar and argVars. In such a case, we must make sure to re-push the
// values.
// If we are nonExpressionKind, we don't expect arguments on the stack
// so this is moot. If our argVars happen to be null, then we know that
// no ShadowMunger has squirrelled away our arguments, so they're still
// on the stack.
InstructionFactory fact = getFactory();
if (getKind().argsOnStack() && argVars != null) {
// Special case first (pr46298). If we are an exception handler and the instruction
// just after the shadow is a POP then we should remove the pop. The code
// above which generated the store instruction has already cleared the stack.
// We also don't generate any code for the arguments in this case as it would be
// an incorrect aload.
if (getKind() == ExceptionHandler
&& range.getEnd().getNext().getInstruction().equals(InstructionConstants.POP)) {
// easier than deleting it ...
range.getEnd().getNext().setInstruction(InstructionConstants.NOP);
} else {
range.insert(
BcelRenderer.renderExprs(fact, world, argVars),
Range.InsideBefore);
if (targetVar != null) {
range.insert(
BcelRenderer.renderExpr(fact, world, targetVar),
Range.InsideBefore);
}
if (getKind() == ConstructorCall) {
if (!world.isJoinpointArrayConstructionEnabled() || !this.getSignature().getDeclaringType().isArray()) {
range.insert((Instruction) InstructionFactory.createDup(1), Range.InsideBefore);
range.insert(
fact.createNew(
(ObjectType) BcelWorld.makeBcelType(
getSignature().getDeclaringType())),
Range.InsideBefore);
}
}
}
}
}
// ---- getters
public ShadowRange getRange() {
return range;
}
public void setRange(ShadowRange range) {
this.range = range;
}
public int getSourceLine() {
// if the kind of join point for which we are a shadow represents
// a method or constructor execution, then the best source line is
// the one from the enclosingMethod declarationLineNumber if available.
Kind kind = getKind();
if ( (kind == MethodExecution) ||
(kind == ConstructorExecution) ||
(kind == AdviceExecution) ||
(kind == StaticInitialization) ||
(kind == PreInitialization) ||
(kind == Initialization)) {
if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
return getEnclosingMethod().getDeclarationLineNumber();
}
}
if (range == null) {
if (getEnclosingMethod().hasBody()) {
return Utility.getSourceLine(getEnclosingMethod().getBody().getStart());
} else {
return 0;
}
}
int ret = Utility.getSourceLine(range.getStart());
if (ret < 0) return 0;
return ret;
}
// overrides
public UnresolvedType 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.makeJoinPointSignature(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.makeJoinPointSignature(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();
UnresolvedType catchType = exceptionRange.getCatchType();
UnresolvedType inType = enclosingMethod.getEnclosingClass().getType();
ResolvedMemberImpl sig = MemberImpl.makeExceptionHandlerSignature(inType, catchType);
sig.setParameterNames(new String[] {findHandlerParamName(startOfHandler)});
BcelShadow s =
new BcelShadow(
world,
ExceptionHandler,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
InstructionHandle start = Range.genStart(body, startOfHandler);
InstructionHandle end = Range.genEnd(body, start);
r.associateWithTargets(start, end);
exceptionRange.updateTarget(startOfHandler, start, body);
return s;
}
private static String findHandlerParamName(InstructionHandle startOfHandler) {
if (startOfHandler.getInstruction() instanceof StoreInstruction &&
startOfHandler.getNext() != null)
{
int slot = ((StoreInstruction)startOfHandler.getInstruction()).getIndex();
//System.out.println("got store: " + startOfHandler.getInstruction() + ", " + index);
InstructionTargeter[] targeters = startOfHandler.getNext().getTargeters();
if (targeters!=null) {
for (int i=targeters.length-1; i >= 0; i--) {
if (targeters[i] instanceof LocalVariableTag) {
LocalVariableTag t = (LocalVariableTag)targeters[i];
if (t.getSlot() == slot) {
return t.getName();
}
//System.out.println("tag: " + targeters[i]);
}
}
}
}
return "<missing>";
}
/** create an init join point associated w/ an interface in the body of a constructor */
public static BcelShadow makeIfaceInitialization(
BcelWorld world,
LazyMethodGen constructor,
Member interfaceConstructorSignature)
{
// this call marks the instruction list as changed
constructor.getBody();
// UnresolvedType 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();
// // UnresolvedType 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)
{
BcelShadow ret = new BcelShadow(
world,
Initialization,
world.makeJoinPointSignature(constructor),
constructor,
null);
if (constructor.getEffectiveSignature() != null) {
ret.setMatchingSignature(constructor.getEffectiveSignature().getEffectiveSignature());
}
return ret;
}
public static BcelShadow makeUnfinishedPreinitialization(
BcelWorld world,
LazyMethodGen constructor)
{
BcelShadow ret = new BcelShadow(
world,
PreInitialization,
world.makeJoinPointSignature(constructor),
constructor,
null);
// ret.fallsThrough = true;
if (constructor.getEffectiveSignature() != null) {
ret.setMatchingSignature(constructor.getEffectiveSignature().getEffectiveSignature());
}
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.makeJoinPointSignatureFromMethod(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 = world.makeJoinPointSignatureForMethodInvocation(
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 makeArrayConstructorCall(BcelWorld world,LazyMethodGen enclosingMethod,InstructionHandle arrayInstruction,BcelShadow enclosingShadow) {
final InstructionList body = enclosingMethod.getBody();
Member sig = world.makeJoinPointSignatureForArrayConstruction(enclosingMethod.getEnclosingClass(),arrayInstruction);
BcelShadow s =
new BcelShadow(
world,
ConstructorCall,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, arrayInstruction),
Range.genEnd(body, arrayInstruction));
retargetAllBranches(arrayInstruction, r.getStart());
return s;
}
// see pr77166
// public static BcelShadow makeArrayLoadCall(
// BcelWorld world,
// LazyMethodGen enclosingMethod,
// InstructionHandle arrayInstruction,
// BcelShadow enclosingShadow)
// {
// final InstructionList body = enclosingMethod.getBody();
// Member sig = world.makeJoinPointSignatureForArrayLoad(enclosingMethod.getEnclosingClass(),arrayInstruction);
// BcelShadow s =
// new BcelShadow(
// world,
// MethodCall,
// sig,
// enclosingMethod,
// enclosingShadow);
// ShadowRange r = new ShadowRange(body);
// r.associateWithShadow(s);
// r.associateWithTargets(
// Range.genStart(body, arrayInstruction),
// Range.genEnd(body, arrayInstruction));
// retargetAllBranches(arrayInstruction, 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,
world.makeJoinPointSignatureForMethodInvocation(
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,
ResolvedMember field,
LazyMethodGen enclosingMethod,
InstructionHandle getHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldGet,
field,
// 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.makeFieldJoinPointSignature(
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;
private Map/*<UnresolvedType,BcelVar>*/ kindedAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ thisAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ targetAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/[] argAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ withinAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ withincodeAnnotationVars = null;
public Var getThisVar() {
if (!hasThis()) {
throw new IllegalStateException("no this");
}
initializeThisVar();
return thisVar;
}
public Var getThisAnnotationVar(UnresolvedType forAnnotationType) {
if (!hasThis()) {
throw new IllegalStateException("no this");
}
initializeThisAnnotationVars(); // FIXME asc Why bother with this if we always return one?
// Even if we can't find one, we have to return one as we might have this annotation at runtime
Var v = (Var) thisAnnotationVars.get(forAnnotationType);
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getThisVar());
return v;
}
public Var getTargetVar() {
if (!hasTarget()) {
throw new IllegalStateException("no target");
}
initializeTargetVar();
return targetVar;
}
public Var getTargetAnnotationVar(UnresolvedType forAnnotationType) {
if (!hasTarget()) {
throw new IllegalStateException("no target");
}
initializeTargetAnnotationVars(); // FIXME asc why bother with this if we always return one?
Var v =(Var) targetAnnotationVars.get(forAnnotationType);
// Even if we can't find one, we have to return one as we might have this annotation at runtime
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getTargetVar());
return v;
}
public Var getArgVar(int i) {
initializeArgVars();
return argVars[i];
}
public Var getArgAnnotationVar(int i,UnresolvedType forAnnotationType) {
initializeArgAnnotationVars();
Var v= (Var) argAnnotationVars[i].get(forAnnotationType);
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getArgVar(i));
return v;
}
public Var getKindedAnnotationVar(UnresolvedType forAnnotationType) {
initializeKindedAnnotationVars();
return (Var) kindedAnnotationVars.get(forAnnotationType);
}
public Var getWithinAnnotationVar(UnresolvedType forAnnotationType) {
initializeWithinAnnotationVars();
return (Var) withinAnnotationVars.get(forAnnotationType);
}
public Var getWithinCodeAnnotationVar(UnresolvedType forAnnotationType) {
initializeWithinCodeAnnotationVars();
return (Var) withincodeAnnotationVars.get(forAnnotationType);
}
// 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, boolean isAround) {
if (!isAround){
if (!hasGuardTest) {
isThisJoinPointLazy = false;
} else {
lazyTjpConsumers++;
}
}
// if (!hasGuardTest) {
// isThisJoinPointLazy = false;
// } else {
// lazyTjpConsumers++;
// }
if (thisJoinPointVar == null) {
thisJoinPointVar = genTempVar(UnresolvedType.forName("org.aspectj.lang.JoinPoint"));
}
}
public Var getThisJoinPointVar() {
requireThisJoinPoint(false,false);
return thisJoinPointVar;
}
void initializeThisJoinPoint() {
if (thisJoinPointVar == null) return;
if (isThisJoinPointLazy) {
isThisJoinPointLazy = checkLazyTjp();
}
if (isThisJoinPointLazy) {
appliedLazyTjpOptimization = true;
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 {
appliedLazyTjpOptimization = false;
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) {
if (munger.getSourceLocation()!=null) { // do we know enough to bother reporting?
if (world.getLint().canNotImplementLazyTjp.isEnabled()) {
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) {
// If we're lazy, build the join point right here.
il.append(createThisJoinPoint());
// Does someone else need it? If so, store it for later retrieval
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 {
// If not lazy, its already been built and stored, just retrieve it
thisJoinPointVar.appendLoad(il, fact);
}
return il;
}
InstructionList createThisJoinPoint() {
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
BcelVar staticPart = getThisJoinPointStaticPartBcelVar();
staticPart.appendLoad(il, fact);
if (hasThis()) {
((BcelVar)getThisVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
if (hasTarget()) {
((BcelVar)getTargetVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
switch(getArgCount()) {
case 0:
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 1:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 2:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
((BcelVar)getArgVar(1)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.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;
}
/**
* Get the Var for the jpStaticPart
* @return
*/
public BcelVar getThisJoinPointStaticPartBcelVar() {
return getThisJoinPointStaticPartBcelVar(false);
}
/**
* Get the Var for the xxxxJpStaticPart, xxx = this or enclosing
* @param isEnclosingJp true to have the enclosingJpStaticPart
* @return
*/
public BcelVar getThisJoinPointStaticPartBcelVar(final boolean isEnclosingJp) {
if (thisJoinPointStaticPartVar == null) {
Field field = getEnclosingClass().getTjpField(this, isEnclosingJp);
ResolvedType sjpType = null;
if (world.isTargettingAspectJRuntime12()) { // TAG:SUPPORTING12: We didn't have different jpsp types in 1.2
sjpType = world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$StaticPart"));
} else {
sjpType = isEnclosingJp?
world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$EnclosingStaticPart")):
world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$StaticPart"));
}
thisJoinPointStaticPartVar = new BcelFieldRef(
sjpType,
getEnclosingClass().getClassName(),
field.getName());
// getEnclosingClass().warnOnAddedStaticInitializer(this,munger.getSourceLocation());
}
return thisJoinPointStaticPartVar;
}
/**
* Get the Var for the enclosingJpStaticPart
* @return
*/
public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() {
if (enclosingShadow == null) {
// the enclosing of an execution is itself
return getThisJoinPointStaticPartBcelVar(true);
} else {
return ((BcelShadow)enclosingShadow).getThisJoinPointStaticPartBcelVar(true);
}
}
//??? need to better understand all the enclosing variants
public Member getEnclosingCodeSignature() {
if (getKind().isEnclosingKind()) {
return getSignature();
} else if (getKind() == Shadow.PreInitialization) {
// PreInit doesn't enclose code but its signature
// is correctly the signature of the ctor.
return getSignature();
} else if (enclosingShadow == null) {
return getEnclosingMethod().getMemberView();
} else {
return enclosingShadow.getSignature();
}
}
private InstructionList makeArgsObjectArray() {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(UnresolvedType.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
UnresolvedType type = getTargetType();
type = ensureTargetTypeIsCorrect(type);
targetVar = genTempVar(type, "ajc$target");
range.insert(targetVar.createStore(fact), Range.OutsideBefore);
targetVar.setPositionInAroundState(hasThis() ? 1 : 0);
}
}
/* PR 72528
* This method double checks the target type under certain conditions. The Java 1.4
* compilers seem to take calls to clone methods on array types and create bytecode that
* looks like clone is being called on Object. If we advise a clone call with around
* advice we extract the call into a helper method which we can then refer to. Because the
* type in the bytecode for the call to clone is Object we create a helper method with
* an Object parameter - this is not correct as we have lost the fact that the actual
* type is an array type. If we don't do the check below we will create code that fails
* java verification. This method checks for the peculiar set of conditions and if they
* are true, it has a sneak peek at the code before the call to see what is on the stack.
*/
public UnresolvedType ensureTargetTypeIsCorrect(UnresolvedType tx) {
Member msig = getSignature();
if (msig.getArity()==0 &&
getKind() == MethodCall &&
msig.getName().charAt(0) == 'c' &&
tx.equals(ResolvedType.OBJECT) &&
msig.getReturnType().equals(ResolvedType.OBJECT) &&
msig.getName().equals("clone")) {
// Lets go back through the code from the start of the shadow
InstructionHandle searchPtr = range.getStart().getPrev();
while (Range.isRangeHandle(searchPtr) ||
searchPtr.getInstruction() instanceof StoreInstruction) { // ignore this instruction - it doesnt give us the info we want
searchPtr = searchPtr.getPrev();
}
// A load instruction may tell us the real type of what the clone() call is on
if (searchPtr.getInstruction() instanceof LoadInstruction) {
LoadInstruction li = (LoadInstruction)searchPtr.getInstruction();
li.getIndex();
LocalVariableTag lvt = LazyMethodGen.getLocalVariableTag(searchPtr,li.getIndex());
if (lvt!=null) return UnresolvedType.forSignature(lvt.getType());
}
// A field access instruction may tell us the real type of what the clone() call is on
if (searchPtr.getInstruction() instanceof FieldInstruction) {
FieldInstruction si = (FieldInstruction)searchPtr.getInstruction();
Type t = si.getFieldType(getEnclosingClass().getConstantPoolGen());
return BcelWorld.fromBcel(t);
}
// A new array instruction obviously tells us it is an array type !
if (searchPtr.getInstruction() instanceof ANEWARRAY) {
//ANEWARRAY ana = (ANEWARRAY)searchPoint.getInstruction();
//Type t = ana.getType(getEnclosingClass().getConstantPoolGen());
// Just use a standard java.lang.object array - that will work fine
return BcelWorld.fromBcel(new ArrayType(Type.OBJECT,1));
}
// A multi new array instruction obviously tells us it is an array type !
if (searchPtr.getInstruction() instanceof MULTIANEWARRAY) {
MULTIANEWARRAY ana = (MULTIANEWARRAY)searchPtr.getInstruction();
// Type t = ana.getType(getEnclosingClass().getConstantPoolGen());
// t = new ArrayType(t,ana.getDimensions());
// Just use a standard java.lang.object array - that will work fine
return BcelWorld.fromBcel(new ArrayType(Type.OBJECT,ana.getDimensions()));
}
throw new BCException("Can't determine real target of clone() when processing instruction "+
searchPtr.getInstruction()+". Perhaps avoid selecting clone with your pointcut?");
}
return tx;
}
public void initializeArgVars() {
if (argVars != null) return;
InstructionFactory fact = getFactory();
int len = getArgCount();
argVars = new BcelVar[len];
int positionOffset = (hasTarget() ? 1 : 0) +
((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
if (getKind().argsOnStack()) {
// we move backwards because we're popping off the stack
for (int i = len - 1; i >= 0; i--) {
UnresolvedType 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++) {
UnresolvedType 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);
}
public void initializeThisAnnotationVars() {
if (thisAnnotationVars != null) return;
thisAnnotationVars = new HashMap();
// populate..
}
public void initializeTargetAnnotationVars() {
if (targetAnnotationVars != null) return;
if (getKind().isTargetSameAsThis()) {
if (hasThis()) initializeThisAnnotationVars();
targetAnnotationVars = thisAnnotationVars;
} else {
targetAnnotationVars = new HashMap();
ResolvedType[] rtx = this.getTargetType().resolve(world).getAnnotationTypes(); // what about annotations we havent gotten yet but we will get in subclasses?
for (int i = 0; i < rtx.length; i++) {
ResolvedType typeX = rtx[i];
targetAnnotationVars.put(typeX,new TypeAnnotationAccessVar(typeX,(BcelVar)getTargetVar()));
}
// populate.
}
}
public void initializeArgAnnotationVars() {
if (argAnnotationVars != null) return;
int numArgs = getArgCount();
argAnnotationVars = new Map[numArgs];
for (int i = 0; i < argAnnotationVars.length; i++) {
argAnnotationVars[i] = new HashMap();
//FIXME asc just delete this logic - we always build the Var on demand, as we don't know at weave time
// what the full set of annotations could be (due to static/dynamic type differences...)
}
}
protected Member getRelevantMember(Member foundMember, Member relevantMember, ResolvedType relevantType){
if (foundMember != null){
return foundMember;
}
foundMember = getSignature().resolve(world);
if (foundMember == null && relevantMember != null) {
foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember);
}
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewMethodTypeMunger ||
typeMunger.getMunger() instanceof NewConstructorTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
if (fakerm.getName().equals(getSignature().getName()) &&
fakerm.getParameterSignature().equals(getSignature().getParameterSignature())){
if (foundMember.getKind()==ResolvedMember.CONSTRUCTOR){
foundMember = AjcMemberMaker.interConstructor(
relevantType,
(ResolvedMember)foundMember,
typeMunger.getAspectType());
} else {
foundMember = AjcMemberMaker.interMethod((ResolvedMember)foundMember,
typeMunger.getAspectType(), false);
}
// in the above.. what about if it's on an Interface? Can that happen?
// then the last arg of the above should be true
return foundMember;
}
}
}
return foundMember;
}
protected ResolvedType [] getAnnotations(Member foundMember, Member relevantMember, ResolvedType relevantType){
if (foundMember == null){
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewMethodTypeMunger ||
typeMunger.getMunger() instanceof NewConstructorTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
//if (fakerm.hasAnnotations())
ResolvedMember ajcMethod = (getSignature().getKind()==ResolvedMember.CONSTRUCTOR?
AjcMemberMaker.postIntroducedConstructor(typeMunger.getAspectType(),fakerm.getDeclaringType(),fakerm.getParameterTypes()):
AjcMemberMaker.interMethodDispatcher(fakerm,typeMunger.getAspectType()));
//AjcMemberMaker.interMethodBody(fakerm,typeMunger.getAspectType()));
ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod);
if (fakerm.getName().equals(getSignature().getName()) &&
fakerm.getParameterSignature().equals(getSignature().getParameterSignature())) {
relevantType = typeMunger.getAspectType();
foundMember = rmm;
return foundMember.getAnnotationTypes();
}
}
}
// didn't find in ITDs, look in supers
foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember);
if (foundMember == null) {
throw new IllegalStateException("Couldn't find member " + relevantMember + " for type " + relevantType);
}
}
return foundMember.getAnnotationTypes();
}
public void initializeKindedAnnotationVars() {
if (kindedAnnotationVars != null) return;
kindedAnnotationVars = new HashMap();
// by determining what "kind" of shadow we are, we can find out the
// annotations on the appropriate element (method, field, constructor, type).
// Then create one BcelVar entry in the map for each annotation, keyed by
// annotation type (UnresolvedType).
// FIXME asc Refactor this code, there is duplication
ResolvedType[] annotations = null;
Member relevantMember = getSignature();
ResolvedType relevantType = relevantMember.getDeclaringType().resolve(world);
if (getKind() == Shadow.StaticInitialization) {
annotations = relevantType.resolve(world).getAnnotationTypes();
} else if (getKind() == Shadow.MethodCall || getKind() == Shadow.ConstructorCall) {
Member foundMember = findMethod2(relevantType.resolve(world).getDeclaredMethods(),getSignature());
annotations = getAnnotations(foundMember, relevantMember, relevantType);
relevantMember = getRelevantMember(foundMember,relevantMember,relevantType);
relevantType = relevantMember.getDeclaringType().resolve(world);
} else if (getKind() == Shadow.FieldSet || getKind() == Shadow.FieldGet) {
relevantMember = findField(relevantType.getDeclaredFields(),getSignature());
if (relevantMember==null) {
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewFieldTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
//if (fakerm.hasAnnotations())
ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm,typeMunger.getAspectType());
ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod);
if (fakerm.equals(getSignature())) {
relevantType = typeMunger.getAspectType();
relevantMember = rmm;
}
}
}
}
annotations = relevantMember.getAnnotationTypes();
} else if (getKind() == Shadow.MethodExecution || getKind() == Shadow.ConstructorExecution ||
getKind() == Shadow.AdviceExecution) {
//ResolvedMember rm[] = relevantType.getDeclaredMethods();
Member foundMember = findMethod2(relevantType.getDeclaredMethods(),getSignature());
annotations = getAnnotations(foundMember, relevantMember,relevantType);
relevantMember = foundMember;
relevantMember = getRelevantMember(foundMember, relevantMember,relevantType);
} else if (getKind() == Shadow.ExceptionHandler) {
relevantType = getSignature().getParameterTypes()[0].resolve(world);
annotations = relevantType.getAnnotationTypes();
} else if (getKind() == Shadow.PreInitialization || getKind() == Shadow.Initialization) {
ResolvedMember found = findMethod2(relevantType.getDeclaredMethods(),getSignature());
annotations = found.getAnnotationTypes();
}
if (annotations == null) {
// We can't have recognized the shadow - should blow up now to be on the safe side
throw new BCException("Couldn't discover annotations for shadow: "+getKind());
}
for (int i = 0; i < annotations.length; i++) {
ResolvedType aTX = annotations[i];
KindedAnnotationAccessVar kaav = new KindedAnnotationAccessVar(getKind(),aTX.resolve(world),relevantType,relevantMember);
kindedAnnotationVars.put(aTX,kaav);
}
}
//FIXME asc whats the real diff between this one and the version in findMethod()?
ResolvedMember findMethod2(ResolvedMember rm[], Member sig) {
ResolvedMember found = null;
// String searchString = getSignature().getName()+getSignature().getParameterSignature();
for (int i = 0; i < rm.length && found==null; i++) {
ResolvedMember member = rm[i];
if (member.getName().equals(sig.getName()) && member.getParameterSignature().equals(sig.getParameterSignature()))
found = member;
}
return found;
}
private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) {
ResolvedMember decMethods[] = aspectType.getDeclaredMethods();
for (int i = 0; i < decMethods.length; i++) {
ResolvedMember member = decMethods[i];
if (member.equals(ajcMethod)) return member;
}
return null;
}
private ResolvedMember findField(ResolvedMember[] members,Member lookingFor) {
for (int i = 0; i < members.length; i++) {
ResolvedMember member = members[i];
if ( member.getName().equals(getSignature().getName()) &&
member.getType().equals(getSignature().getType())) {
return member;
}
}
return null;
}
public void initializeWithinAnnotationVars() {
if (withinAnnotationVars != null) return;
withinAnnotationVars = new HashMap();
ResolvedType[] annotations = getEnclosingType().resolve(world).getAnnotationTypes();
for (int i = 0; i < annotations.length; i++) {
ResolvedType ann = annotations[i];
Kind k = Shadow.StaticInitialization;
withinAnnotationVars.put(ann,new KindedAnnotationAccessVar(k,ann,getEnclosingType(),null));
}
}
public void initializeWithinCodeAnnotationVars() {
if (withincodeAnnotationVars != null) return;
withincodeAnnotationVars = new HashMap();
// For some shadow we are interested in annotations on the method containing that shadow.
ResolvedType[] annotations = getEnclosingMethod().getMemberView().getAnnotationTypes();
for (int i = 0; i < annotations.length; i++) {
ResolvedType ann = annotations[i];
Kind k = (getEnclosingMethod().getMemberView().getKind()==Member.CONSTRUCTOR?
Shadow.ConstructorExecution:Shadow.MethodExecution);
withincodeAnnotationVars.put(ann,
new KindedAnnotationAccessVar(k,ann,getEnclosingType(),getEnclosingCodeSignature()));
}
}
// ---- weave methods
void weaveBefore(BcelAdvice munger) {
range.insert(
munger.getAdviceInstructions(this, null, range.getRealStart()),
Range.InsideBefore);
}
public void weaveAfter(BcelAdvice munger) {
weaveAfterThrowing(munger, UnresolvedType.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()) */ {
/*
*
27: getstatic #72; //Field ajc$cflowCounter$0:Lorg/aspectj/runtime/internal/CFlowCounter;
30: invokevirtual #87; //Method org/aspectj/runtime/internal/CFlowCounter.dec:()V
33: aload 6
35: athrow
36: nop
37: getstatic #72; //Field ajc$cflowCounter$0:Lorg/aspectj/runtime/internal/CFlowCounter;
40: invokevirtual #87; //Method org/aspectj/runtime/internal/CFlowCounter.dec:()V
43: d2i
44: invokespecial #23; //Method java/lang/Object."<init>":()V
*/
retList = new InstructionList(InstructionConstants.NOP);
afterAdvice = retList.getStart();
// } else {
// retList = new InstructionList();
// afterAdvice = null;
}
InstructionList advice = new InstructionList();
BcelVar tempVar = null;
if (munger.hasExtraParameter()) {
UnresolvedType tempVarType = getReturnType();
if (tempVarType.equals(ResolvedType.VOID)) {
tempVar = genTempVar(UnresolvedType.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, UnresolvedType catchType) {
// a good optimization would be not to generate anything here
// if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
// a shadow, inside me).
if (getRange().getStart().getNext() == getRange().getEnd()) return;
InstructionFactory fact = getFactory();
InstructionList handler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
exceptionVar.appendStore(handler, fact);
// pr62642
// I will now jump through some firey BCEL hoops to generate a trivial bit of code:
// if (exc instanceof ExceptionInInitializerError)
// throw (ExceptionInInitializerError)exc;
if (this.getEnclosingMethod().getName().equals("<clinit>")) {
ResolvedType eiieType = world.resolve("java.lang.ExceptionInInitializerError");
ObjectType eiieBcelType = (ObjectType)BcelWorld.makeBcelType(eiieType);
InstructionList ih = new InstructionList(InstructionConstants.NOP);
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createInstanceOf(eiieBcelType));
BranchInstruction bi =
InstructionFactory.createBranchInstruction(Constants.IFEQ,ih.getStart());
handler.append(bi);
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createCheckCast(eiieBcelType));
handler.append(InstructionConstants.ATHROW);
handler.append(ih);
}
InstructionList endHandler = new InstructionList(
exceptionVar.createLoad(fact));
handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart()));
handler.append(endHandler);
handler.append(InstructionConstants.ATHROW);
InstructionHandle handlerStart = handler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = handler.append(InstructionConstants.NOP);
handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
InstructionHandle protectedEnd = handler.getStart();
range.insert(handler, Range.InsideAfter);
enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(),
handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), //???Type.THROWABLE,
// high priority if our args are on the stack
getKind().hasHighPriorityExceptions());
}
//??? this shares a lot of code with the above weaveAfterThrowing
//??? would be nice to abstract that to say things only once
public void weaveSoftener(BcelAdvice munger, UnresolvedType 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();
InstructionList rtExHandler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
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);
// ENH 42737
exceptionVar.appendStore(rtExHandler, fact);
// aload_1
rtExHandler.append(exceptionVar.createLoad(fact));
// instanceof class java/lang/RuntimeException
rtExHandler.append(fact.createInstanceOf(new ObjectType("java.lang.RuntimeException")));
// ifeq go to new SOFT_EXCEPTION_TYPE instruction
rtExHandler.append(InstructionFactory.createBranchInstruction(Constants.IFEQ,handler.getStart()));
// aload_1
rtExHandler.append(exceptionVar.createLoad(fact));
// athrow
rtExHandler.append(InstructionFactory.ATHROW);
InstructionHandle handlerStart = rtExHandler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = range.getEnd();//handler.append(fact.NOP);
rtExHandler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
rtExHandler.append(handler);
InstructionHandle protectedEnd = rtExHandler.getStart();
range.insert(rtExHandler, 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);
}
// PTWIMPL Create static initializer to call the aspect factory
/**
* Causes the aspect instance to be *set* for later retrievable through localAspectof()/aspectOf()
*/
public void weavePerTypeWithinAspectInitialization(final BcelAdvice munger,UnresolvedType t) {
if (t.resolve(world).isInterface()) return; // Don't initialize statics in
final InstructionFactory fact = getFactory();
InstructionList entryInstructions = new InstructionList();
InstructionList entrySuccessInstructions = new InstructionList();
BcelWorld.getBcelObjectType(munger.getConcreteAspect());
String aspectname = munger.getConcreteAspect().getName();
String ptwField = NameMangler.perTypeWithinFieldForTarget(munger.getConcreteAspect());
entrySuccessInstructions.append(new PUSH(fact.getConstantPool(),t.getName()));
entrySuccessInstructions.append(fact.createInvoke(aspectname,"ajc$createAspectInstance",new ObjectType(aspectname),
new Type[]{new ObjectType("java.lang.String")},Constants.INVOKESTATIC));
entrySuccessInstructions.append(fact.createPutStatic(t.getName(),ptwField,
new ObjectType(aspectname)));
entryInstructions.append(entrySuccessInstructions);
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveCflowEntry(final BcelAdvice munger, final Member cflowField) {
final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry ||
munger.getKind() == AdviceKind.PerCflowEntry;
final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionFactory fact = getFactory();
final BcelVar testResult = genTempVar(ResolvedType.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(false);
if (cflowStateVars.length == 0) {
// This should be getting managed by a counter - lets make sure.
if (!cflowField.getType().getName().endsWith("CFlowCounter"))
throw new RuntimeException("Incorrectly attempting counter operation on stacked cflow");
entrySuccessInstructions.append(
Utility.createGet(fact, cflowField));
//arrayVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(fact.createInvoke(NameMangler.CFLOW_COUNTER_TYPE,"inc",Type.VOID,new Type[] { },Constants.INVOKEVIRTUAL));
} else {
BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
int alen = cflowStateVars.length;
entrySuccessInstructions.append(Utility.createConstant(fact, alen));
entrySuccessInstructions.append(
(Instruction) fact.createNewArray(Type.OBJECT, (short) 1));
arrayVar.appendStore(entrySuccessInstructions, fact);
for (int i = 0; i < alen; i++) {
arrayVar.appendConvertableArrayStore(
entrySuccessInstructions,
fact,
i,
cflowStateVars[i]);
}
entrySuccessInstructions.append(
Utility.createGet(fact, cflowField));
arrayVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID,
new Type[] { objectArrayType },
Constants.INVOKEVIRTUAL));
}
}
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
}
// this is the same for both per and non-per
weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) {
public InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice) {
InstructionList exitInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
testResult.appendLoad(exitInstructions, fact);
exitInstructions.append(
InstructionFactory.createBranchInstruction(
Constants.IFEQ,
ifNoAdvice));
}
exitInstructions.append(Utility.createGet(fact, cflowField));
if (munger.getKind() != AdviceKind.PerCflowEntry &&
munger.getKind() != AdviceKind.PerCflowBelowEntry &&
munger.getExposedStateAsBcelVars(false).length==0) {
exitInstructions
.append(
fact
.createInvoke(
NameMangler.CFLOW_COUNTER_TYPE,
"dec",
Type.VOID,
new Type[] {
}, Constants.INVOKEVIRTUAL));
} else {
exitInstructions
.append(
fact
.createInvoke(
NameMangler.CFLOW_STACK_TYPE,
"pop",
Type.VOID,
new Type[] {
}, Constants.INVOKEVIRTUAL));
}
return exitInstructions;
}
});
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveAroundInline(
BcelAdvice munger,
boolean hasDynamicTest)
{
/* Implementation notes:
*
* AroundInline still extracts the instructions of the original shadow into
* an extracted method. This allows inlining of even that advice that doesn't
* call proceed or calls proceed more than once.
*
* It extracts the instructions of the original shadow into a method.
*
* Then it extracts the instructions of the advice into a new method defined on
* this enclosing class. This new method can then be specialized as below.
*
* Then it searches in the instructions of the advice for any call to the
* proceed method.
*
* At such a call, there is stuff on the stack representing the arguments to
* proceed. Pop these into the frame.
*
* Now build the stack for the call to the extracted method, taking values
* either from the join point state or from the new frame locs from proceed.
* Now call the extracted method. The right return value should be on the
* stack, so no cast is necessary.
*
* If only one call to proceed is made, we can re-inline the original shadow.
* We are not doing that presently.
*
* If the body of the advice can be determined to not alter the stack, or if
* this shadow doesn't care about the stack, i.e. method-execution, then the
* new method for the advice can also be re-lined. We are not doing that
* presently.
*/
// !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...);
Member mungerSig = munger.getSignature();
//Member originalSig = mungerSig; // If mungerSig is on a parameterized type, originalSig is the member on the generic type
if (mungerSig instanceof ResolvedMember) {
ResolvedMember rm = (ResolvedMember)mungerSig;
if (rm.hasBackingGenericMember()) mungerSig = rm.getBackingGenericMember();
}
ResolvedType declaringType = world.resolve(mungerSig.getDeclaringType(),true);
if (declaringType.isMissing()) {
world.getLint().cantFindType.signal(
new String[] {WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName())},
getSourceLocation(),
new ISourceLocation[]{ munger.getSourceLocation()}
);
// IMessage msg = new Message(
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName()),
// "",IMessage.ERROR,getSourceLocation(),null,
// new ISourceLocation[]{ munger.getSourceLocation()});
// world.getMessageHandler().handleMessage(msg);
}
//??? might want some checks here to give better errors
BcelObjectType ot = BcelWorld.getBcelObjectType((declaringType.isParameterizedType()?declaringType.getGenericType():declaringType));
LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig);
if (!adviceMethod.getCanInline()) {
weaveAroundClosure(munger, hasDynamicTest);
return;
}
// specific test for @AJ proceedInInners
if (munger.getConcreteAspect().isAnnotationStyleAspect()) {
// if we can't find one proceed()
// we suspect that the call is happening in an inner class
// so we don't inline it.
// Note: for code style, this is done at Aspect compilation time.
boolean canSeeProceedPassedToOther = false;
InstructionHandle curr = adviceMethod.getBody().getStart();
InstructionHandle end = adviceMethod.getBody().getEnd();
ConstantPoolGen cpg = adviceMethod.getEnclosingClass().getConstantPoolGen();
while (curr != end) {
InstructionHandle next = curr.getNext();
Instruction inst = curr.getInstruction();
if ((inst instanceof InvokeInstruction)
&& ((InvokeInstruction)inst).getSignature(cpg).indexOf("Lorg/aspectj/lang/ProceedingJoinPoint;") > 0) {
// we may want to refine to exclude stuff returning jp ?
// does code style skip inline if i write dump(thisJoinPoint) ?
canSeeProceedPassedToOther = true;// we see one pjp passed around - dangerous
break;
}
curr = next;
}
if (canSeeProceedPassedToOther) {
// remember this decision to avoid re-analysis
adviceMethod.setCanInline(false);
weaveAroundClosure(munger, hasDynamicTest);
return;
}
}
// We can't inline around methods if they have around advice on them, this
// is because the weaving will extract the body and hence the proceed call.
//??? should consider optimizations to recognize simple cases that don't require body extraction
enclosingMethod.setCanInline(false);
// start by exposing various useful things into the frame
final InstructionFactory fact = getFactory();
// now generate the aroundBody method
LazyMethodGen extractedMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
Modifier.PRIVATE,
munger
);
// now extract the advice into its own method
String adviceMethodName =
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()) + "$advice";
List argVarList = new ArrayList();
List proceedVarList = new ArrayList();
int extraParamOffset = 0;
// Create the extra parameters that are needed for passing to proceed
// This code is very similar to that found in makeCallToCallback and should
// be rationalized in the future
if (thisVar != null) {
argVarList.add(thisVar);
proceedVarList.add(new BcelVar(thisVar.getType(), extraParamOffset));
extraParamOffset += thisVar.getType().getSize();
}
if (targetVar != null && targetVar != thisVar) {
argVarList.add(targetVar);
proceedVarList.add(new BcelVar(targetVar.getType(), extraParamOffset));
extraParamOffset += targetVar.getType().getSize();
}
for (int i = 0, len = getArgCount(); i < len; i++) {
argVarList.add(argVars[i]);
proceedVarList.add(new BcelVar(argVars[i].getType(), extraParamOffset));
extraParamOffset += argVars[i].getType().getSize();
}
if (thisJoinPointVar != null) {
argVarList.add(thisJoinPointVar);
proceedVarList.add(new BcelVar(thisJoinPointVar.getType(), extraParamOffset));
extraParamOffset += thisJoinPointVar.getType().getSize();
}
Type[] adviceParameterTypes = adviceMethod.getArgumentTypes();
Type[] extractedMethodParameterTypes = extractedMethod.getArgumentTypes();
Type[] parameterTypes =
new Type[extractedMethodParameterTypes.length
+ adviceParameterTypes.length
+ 1];
int parameterIndex = 0;
System.arraycopy(
extractedMethodParameterTypes,
0,
parameterTypes,
parameterIndex,
extractedMethodParameterTypes.length);
parameterIndex += extractedMethodParameterTypes.length;
parameterTypes[parameterIndex++] =
BcelWorld.makeBcelType(adviceMethod.getEnclosingClass().getType());
System.arraycopy(
adviceParameterTypes,
0,
parameterTypes,
parameterIndex,
adviceParameterTypes.length);
LazyMethodGen localAdviceMethod =
new LazyMethodGen(
Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC,
BcelWorld.makeBcelType(mungerSig.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,
(munger.getConcreteAspect().isAnnotationStyleAspect() && munger.getDeclaringAspect()!=null && munger.getDeclaringAspect().resolve(world).isAnnotationStyleAspect())?
this.loadThisJoinPoint():
new InstructionList(InstructionConstants.ACONST_NULL)));
// adviceMethodInvocation =
advice.append(
Utility.createInvoke(fact, localAdviceMethod)); //(fact, getWorld(), munger.getSignature()));
advice.append(
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(mungerSig.getReturnType()),
extractedMethod.getReturnType(),world.isInJava5Mode()));
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.
// inlining support for code style aspects
if (!munger.getConcreteAspect().isAnnotationStyleAspect()) {
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.
} else {
//ATAJ inlining support for @AJ aspects
// [TODO document @AJ code rule: don't manipulate 2 jps proceed at the same time.. in an advice body]
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 INVOKEINTERFACE)
&& "proceed".equals(((INVOKEINTERFACE) inst).getMethodName(cpg))) {
final boolean isProceedWithArgs;
if (((INVOKEINTERFACE) inst).getArgumentTypes(cpg).length == 1) {
// proceed with args as a boxed Object[]
isProceedWithArgs = true;
} else {
isProceedWithArgs = false;
}
InstructionList insteadProceedIl = getRedoneProceedCallForAnnotationStyle(
fact,
extractedMethod,
munger,
localAdviceMethod,
proceedVarList,
isProceedWithArgs
);
localAdviceMethod.getBody().append(curr, insteadProceedIl);
Utility.deleteInstruction(curr, localAdviceMethod);
}
curr = next;
}
}
}
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(true);
IntMap proceedMap = makeProceedArgumentMap(adviceVars);
// System.out.println(proceedMap + " for " + this);
// System.out.println(argVarList);
ResolvedType[] proceedParamTypes =
world.resolve(munger.getSignature().getParameterTypes());
// remove this*JoinPoint* as arguments to proceed
if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) {
int len = munger.getBaseParameterCount()+1;
ResolvedType[] newTypes = new ResolvedType[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];
ResolvedType 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;
}
private static boolean bindsThisOrTarget(Pointcut pointcut) {
ThisTargetFinder visitor = new ThisTargetFinder();
pointcut.accept(visitor, null);
return visitor.bindsThisOrTarget;
}
private static class ThisTargetFinder extends IdentityPointcutVisitor {
boolean bindsThisOrTarget = false;
public Object visit(ThisOrTargetPointcut node, Object data) {
if (node.isBinding()) {
bindsThisOrTarget = true;
}
return node;
}
public Object visit(AndPointcut node, Object data) {
if (!bindsThisOrTarget) node.getLeft().accept(this, data);
if (!bindsThisOrTarget) node.getRight().accept(this, data);
return node;
}
public Object visit(NotPointcut node, Object data) {
if (!bindsThisOrTarget) node.getNegatedPointcut().accept(this, data);
return node;
}
public Object visit(OrPointcut node, Object data) {
if (!bindsThisOrTarget) node.getLeft().accept(this, data);
if (!bindsThisOrTarget) node.getRight().accept(this, data);
return node;
}
}
/**
* ATAJ Handle the inlining for @AJ aspects
*
* @param fact
* @param callbackMethod
* @param munger
* @param localAdviceMethod
* @param argVarList
* @param isProceedWithArgs
* @return
*/
private InstructionList getRedoneProceedCallForAnnotationStyle(
InstructionFactory fact,
LazyMethodGen callbackMethod,
BcelAdvice munger,
LazyMethodGen localAdviceMethod,
List argVarList,
boolean isProceedWithArgs)
{
// Notes:
// proceedingjp is on stack (since user was calling pjp.proceed(...)
// the boxed args to proceed() are on stack as well (Object[]) unless
// the call is to pjp.proceed(<noarg>)
// new Object[]{new Integer(argAdvice1-1)};// arg of proceed
// call to proceed(..) is NOT made
// instead we do
// itar callback args i
// get from array i, convert it to the callback arg i
// if ask for JP, push the one we got on the stack
// invoke callback, create conversion back to Object/Integer
// rest of method -- (hence all those conversions)
// intValue() from original code
// int res = .. from original code
//Note: we just don't care about the proceed map etc
InstructionList ret = new InstructionList();
// store the Object[] array on stack if proceed with args
if (isProceedWithArgs) {
Type objectArrayType = Type.getType("[Ljava/lang/Object;");
int localProceedArgArray = localAdviceMethod.allocateLocal(objectArrayType);
ret.append(InstructionFactory.createStore(objectArrayType, localProceedArgArray));
Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;");
int localJp = localAdviceMethod.allocateLocal(proceedingJpType);
ret.append(InstructionFactory.createStore(proceedingJpType, localJp));
// push on stack each element of the object array
// that is assumed to be consistent with the callback argument (ie munger args)
// TODO do we want to try catch ClassCast and AOOBE exception ?
// special logic when withincode is static or not
int startIndex = 0;
if (thisVar != null) {
startIndex = 1;
//TODO this logic is actually depending on target as well - test me
ret.append(new ALOAD(0));//thisVar
}
// if (bindsThisOrTarget(munger.getPointcut())) {
for (int i = startIndex, len=callbackMethod.getArgumentTypes().length; i < len; i++) {
Type stateType = callbackMethod.getArgumentTypes()[i];
BcelWorld.fromBcel(stateType).resolve(world);
if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
ret.append(new ALOAD(localJp));// from localAdvice signature
} else {
ret.append(InstructionFactory.createLoad(objectArrayType, localProceedArgArray));
ret.append(Utility.createConstant(fact, i-startIndex));
ret.append(InstructionFactory.createArrayLoad(Type.OBJECT));
ret.append(Utility.createConversion(
fact,
Type.OBJECT,
stateType
));
}
}
} else {
Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;");
int localJp = localAdviceMethod.allocateLocal(proceedingJpType);
ret.append(InstructionFactory.createStore(proceedingJpType, localJp));
for (int i = 0, len=callbackMethod.getArgumentTypes().length; i < len; i++) {
Type stateType = callbackMethod.getArgumentTypes()[i];
/*ResolvedType stateTypeX =*/
BcelWorld.fromBcel(stateType).resolve(world);
if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
ret.append(new ALOAD(localJp));// from localAdvice signature
// } else if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(stateType.getSignature())) {
// //FIXME ALEX?
// ret.append(new ALOAD(localJp));// from localAdvice signature
//// ret.append(fact.createCheckCast(
//// (ReferenceType) BcelWorld.makeBcelType(stateTypeX)
//// ));
// // cast ?
//
} else {
ret.append(InstructionFactory.createLoad(stateType, i));
}
}
}
// do the callback invoke
ret.append(Utility.createInvoke(fact, callbackMethod));
// box it again. Handles cases where around advice does return something else than Object
if (!UnresolvedType.OBJECT.equals(munger.getSignature().getReturnType())) {
ret.append(Utility.createConversion(
fact,
callbackMethod.getReturnType(),
Type.OBJECT
));
}
ret.append(Utility.createConversion(
fact,
callbackMethod.getReturnType(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType())
));
return ret;
//
//
//
// if (proceedMap.hasKey(i)) {
// ret.append(new ALOAD(i));
// //throw new RuntimeException("unimplemented");
// //proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
// } else {
// //((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
// //ret.append(new ALOAD(i));
// if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
// ret.append(new ALOAD(i));
// } else {
// ret.append(new ALOAD(i));
// }
// }
// }
//
// ret.append(Utility.createInvoke(fact, callbackMethod));
// ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
// BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
//
// //ret.append(new ACONST_NULL());//will be POPed
// if (true) return ret;
//
//
//
// // 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);
//
// ResolvedType[] proceedParamTypes =
// world.resolve(munger.getSignature().getParameterTypes());
// // remove this*JoinPoint* as arguments to proceed
// if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) {
// int len = munger.getBaseParameterCount()+1;
// ResolvedType[] newTypes = new ResolvedType[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];
// ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
// if (proceedMap.hasKey(i)) {
// //throw new RuntimeException("unimplemented");
// proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
// } else {
// ((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
// }
// }
//
// ret.append(Utility.createInvoke(fact, callbackMethod));
// ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
// BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
// return ret;
}
public void weaveAroundClosure(BcelAdvice munger, boolean hasDynamicTest) {
InstructionFactory fact = getFactory();
enclosingMethod.setCanInline(false);
// MOVE OUT ALL THE INSTRUCTIONS IN MY SHADOW INTO ANOTHER METHOD!
LazyMethodGen callbackMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
0,
munger);
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(true);
String closureClassName =
NameMangler.makeClosureClassName(
getEnclosingClass().getType(),
getEnclosingClass().getNewGeneratedNameTag());
Member constructorSig = new MemberImpl(Member.CONSTRUCTOR,
UnresolvedType.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(UnresolvedType.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++) {
UnresolvedType bcelTX = BcelWorld.fromBcel(stateTypes[i]);
ResolvedType stateRTX = world.resolve(bcelTX,true);
if (stateRTX.isMissing()) {
world.getLint().cantFindType.signal(
new String[] {WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName())},
getSourceLocation(),
new ISourceLocation[]{ munger.getSourceLocation()}
);
// IMessage msg = new Message(
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName()),
// "",IMessage.ERROR,getSourceLocation(),null,
// new ISourceLocation[]{ munger.getSourceLocation()});
// world.getMessageHandler().handleMessage(msg);
}
stateTempVar.appendConvertableArrayLoad(
returnConversionCode,
fact,
i,
stateRTX);
}
} else {
returnConversionCode =
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType()),
callbackMethod.getReturnType(),world.isInJava5Mode());
if (!isFallsThrough()) {
returnConversionCode.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
}
}
// ATAJ for @AJ aspect we need to link the closure with the joinpoint instance
if (munger.getConcreteAspect()!=null && munger.getConcreteAspect().isAnnotationStyleAspect()
&& munger.getDeclaringAspect()!=null && munger.getDeclaringAspect().resolve(world).isAnnotationStyleAspect()) {
closureInstantiation.append(Utility.createInvoke(
getFactory(),
getWorld(),
new MemberImpl(
Member.METHOD,
UnresolvedType.forName("org.aspectj.runtime.internal.AroundClosure"),
Modifier.PUBLIC,
"linkClosureAndJoinPoint",
"()Lorg/aspectj/lang/ProceedingJoinPoint;"
)
));
}
InstructionList advice = new InstructionList();
advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation));
// invoke the advice
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(UnresolvedType.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[] {},
getWorld());
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(UnresolvedType.OBJECTARRAY.resolve(world), 1);
// int proceedVarIndex = 1;
BcelVar stateVar =
new BcelVar(UnresolvedType.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];
ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
if (proceedMap.hasKey(i)) {
mbody.append(
proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i),
stateTypeX));
} else {
mbody.append(
stateVar.createConvertableArrayLoad(fact, i,
stateTypeX));
}
}
mbody.append(Utility.createInvoke(fact, callbackMethod));
if (getKind() == PreInitialization) {
mbody.append(Utility.createSet(
fact,
AjcMemberMaker.aroundClosurePreInitializationField()));
mbody.append(InstructionConstants.ACONST_NULL);
} else {
mbody.append(
Utility.createConversion(
fact,
callbackMethod.getReturnType(),
Type.OBJECT));
}
mbody.append(InstructionFactory.createReturn(Type.OBJECT));
closureClass.addMethodGen(runMethod);
// class
getEnclosingClass().addGeneratedInner(closureClass);
return constructor;
}
// ---- extraction methods
public LazyMethodGen extractMethod(String newMethodName, int visibilityModifier, ShadowMunger munger) {
LazyMethodGen.assertGoodBody(range.getBody(), newMethodName);
if (!getKind().allowsExtraction()) throw new BCException("Attempt to extract method from a shadow kind that does not support this operation (" + getKind() + ")");
LazyMethodGen freshMethod = createMethodGen(newMethodName,visibilityModifier);
// System.err.println("******");
// System.err.println("ABOUT TO EXTRACT METHOD for" + this);
// enclosingMethod.print(System.err);
// System.err.println("INTO");
// freshMethod.print(System.err);
// System.err.println("WITH REMAP");
// System.err.println(makeRemap());
range.extractInstructionsInto(freshMethod, makeRemap(),
(getKind() != PreInitialization) &&
isFallsThrough());
if (getKind() == PreInitialization) {
addPreInitializationReturnCode(
freshMethod,
getSuperConstructorParameterTypes());
}
getEnclosingClass().addMethodGen(freshMethod,munger.getSourceLocation());
return freshMethod;
}
private void addPreInitializationReturnCode(
LazyMethodGen extractedMethod,
Type[] superConstructorTypes)
{
InstructionList body = extractedMethod.getBody();
final InstructionFactory fact = getFactory();
BcelVar arrayVar = new BcelVar(
world.getCoreType(UnresolvedType.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++) {
UnresolvedType type = getArgType(i);
ret.put(oldi, newi);
oldi += type.getSize();
newi += type.getSize();
}
}
// System.err.println("making remap for : " + this);
// if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot());
// if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot());
// System.err.println(ret);
return ret;
}
/**
* The new method always static.
* It may take some extra arguments: this, target.
* If it's argsOnStack, then it must take both this/target
* If it's argsOnFrame, it shares this and target.
* ??? rewrite this to do less array munging, please
*/
private LazyMethodGen createMethodGen(String newMethodName, int visibilityModifier) {
Type[] parameterTypes = BcelWorld.makeBcelTypes(getArgTypes());
int modifiers = Modifier.FINAL | visibilityModifier;
// XXX some bug
// if (! isExpressionKind() && getSignature().isStrict(world)) {
// modifiers |= Modifier.STRICT;
// }
modifiers |= Modifier.STATIC;
if (targetVar != null && targetVar != thisVar) {
UnresolvedType targetType = getTargetType();
targetType = ensureTargetTypeIsCorrect(targetType);
// see pr109728 - this fixes the case when the declaring class is sometype 'X' but the getfield
// in the bytecode refers to a subtype of 'X'. This makes sure we use the type originally
// mentioned in the fieldget instruction as the method parameter and *not* the type upon which the
// field is declared because when the instructions are extracted into the new around body,
// they will still refer to the subtype.
if (getKind()==FieldGet && getActualTargetType()!=null &&
!getActualTargetType().equals(targetType.getName())) {
targetType = UnresolvedType.forName(getActualTargetType()).resolve(world);
}
ResolvedMember resolvedMember = getSignature().resolve(world);
if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) &&
!samePackage(targetType.getPackageName(), getEnclosingType().getPackageName()) &&
!resolvedMember.getName().equals("clone"))
{
if (!targetType.resolve(world).isAssignableFrom(getThisType().resolve(world))) {
throw new BCException("bad bytecode");
}
targetType = getThisType();
}
parameterTypes = addType(BcelWorld.makeBcelType(targetType), parameterTypes);
}
if (thisVar != null) {
UnresolvedType 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);
//FIXME ALEX? which one
//parameterTypes = addTypeToEnd(LazyClassGen.proceedingTjpType, parameterTypes);
}
UnresolvedType returnType;
if (getKind() == PreInitialization) {
returnType = UnresolvedType.OBJECTARRAY;
} else {
returnType = getReturnType();
}
return
new LazyMethodGen(
modifiers,
BcelWorld.makeBcelType(returnType),
newMethodName,
parameterTypes,
new String[0],
// XXX again, we need to look up methods!
// UnresolvedType.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(UnresolvedType typeX) {
return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize()));
}
// public static final boolean CREATE_TEMP_NAMES = true;
public BcelVar genTempVar(UnresolvedType typeX, String localName) {
BcelVar tv = genTempVar(typeX);
// if (CREATE_TEMP_NAMES) {
// for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
// if (Range.isRangeHandle(ih)) continue;
// ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot()));
// }
// }
return tv;
}
// eh doesn't think we need to garbage collect these (64K is a big number...)
private int genTempVarIndex(int size) {
return enclosingMethod.allocateLocal(size);
}
public InstructionFactory getFactory() {
return getEnclosingClass().getFactory();
}
public ISourceLocation getSourceLocation() {
int sourceLine = getSourceLine();
if (sourceLine == 0 || sourceLine == -1) {
// Thread.currentThread().dumpStack();
// System.err.println(this + ": " + range);
return getEnclosingClass().getType().getSourceLocation();
} else {
// For staticinitialization, if we have a nice offset, don't build a new source loc
if (getKind()==Shadow.StaticInitialization && getEnclosingClass().getType().getSourceLocation().getOffset()!=0) {
return getEnclosingClass().getType().getSourceLocation();
} else {
int offset = 0;
Kind kind = getKind();
if ( (kind == MethodExecution) ||
(kind == ConstructorExecution) ||
(kind == AdviceExecution) ||
(kind == StaticInitialization) ||
(kind == PreInitialization) ||
(kind == Initialization)) {
if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
offset = getEnclosingMethod().getDeclarationOffset();
}
}
return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine, offset);
}
}
}
public Shadow getEnclosingShadow() {
return enclosingShadow;
}
public LazyMethodGen getEnclosingMethod() {
return enclosingMethod;
}
public boolean isFallsThrough() {
return !terminatesWithReturn(); //fallsThrough;
}
public void setActualTargetType(String className) {
this.actualInstructionTargetType = className;
}
public String getActualTargetType() {
return actualInstructionTargetType;
}
}
|
135,001 |
Bug 135001 NPE at at org.aspectj.weaver.bcel.BcelShadow.weaveAroundInline
|
java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelShadow.weaveAroundInline(BcelShadow.java:2109) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:232) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:639) at org.aspectj.weaver.Shadow.implement(Shadow.java:456) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2236) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:491) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:109) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1560) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1511) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1291) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1113) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:311) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:183) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:242) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:161) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191)
|
resolved fixed
|
1a6f695
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-04-06T11:45:02Z | 2006-04-05T12:26:40Z |
weaver/src/org/aspectj/weaver/bcel/BcelWorld.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur perClause support for @AJ aspects
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import org.aspectj.apache.bcel.classfile.Attribute;
import org.aspectj.apache.bcel.classfile.ClassParser;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.annotation.Annotation;
import org.aspectj.apache.bcel.generic.ANEWARRAY;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.FieldInstruction;
import org.aspectj.apache.bcel.generic.GETSTATIC;
import org.aspectj.apache.bcel.generic.INVOKEINTERFACE;
import org.aspectj.apache.bcel.generic.INVOKESPECIAL;
import org.aspectj.apache.bcel.generic.INVOKESTATIC;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.MULTIANEWARRAY;
import org.aspectj.apache.bcel.generic.NEWARRAY;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.PUTSTATIC;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.apache.bcel.util.ClassLoaderRepository;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.Repository;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.ICrossReferenceHandler;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.MemberImpl;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ReferenceTypeDelegate;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.AjAttribute.Aspect;
import org.aspectj.weaver.asm.AsmDelegate;
import org.aspectj.weaver.patterns.FormalBinding;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.SimpleScope;
public class BcelWorld extends World implements Repository {
private ClassPathManager classPath;
private Repository delegate;
//private ClassPathManager aspectPath = null;
// private List aspectPathEntries;
// ---- constructors
public BcelWorld() {
this("");
}
public BcelWorld(String cp) {
this(makeDefaultClasspath(cp), IMessageHandler.THROW, null);
}
private static List makeDefaultClasspath(String cp) {
List classPath = new ArrayList();
classPath.addAll(getPathEntries(cp));
classPath.addAll(getPathEntries(ClassPath.getClassPath()));
//System.err.println("classpath: " + classPath);
return classPath;
}
private static List getPathEntries(String s) {
List ret = new ArrayList();
StringTokenizer tok = new StringTokenizer(s, File.pathSeparator);
while(tok.hasMoreTokens()) ret.add(tok.nextToken());
return ret;
}
public BcelWorld(List classPath, IMessageHandler handler, ICrossReferenceHandler xrefHandler) {
//this.aspectPath = new ClassPathManager(aspectPath, handler);
this.classPath = new ClassPathManager(classPath, handler);
setMessageHandler(handler);
setCrossReferenceHandler(xrefHandler);
// Tell BCEL to use us for resolving any classes
delegate = this;
// TODO Alex do we need to call org.aspectj.apache.bcel.Repository.setRepository(delegate);
// if so, how can that be safe in J2EE ?? (static stuff in Bcel)
}
public BcelWorld(ClassPathManager cpm, IMessageHandler handler, ICrossReferenceHandler xrefHandler) {
this.classPath = cpm;
setMessageHandler(handler);
setCrossReferenceHandler(xrefHandler);
// Tell BCEL to use us for resolving any classes
delegate = this;
// TODO Alex do we need to call org.aspectj.apache.bcel.Repository.setRepository(delegate);
// if so, how can that be safe in J2EE ?? (static stuff in Bcel)
}
/**
* Build a World from a ClassLoader, for LTW support
*
* @param loader
* @param handler
* @param xrefHandler
*/
public BcelWorld(ClassLoader loader, IMessageHandler handler, ICrossReferenceHandler xrefHandler) {
this.classPath = null;
setMessageHandler(handler);
setCrossReferenceHandler(xrefHandler);
// Tell BCEL to use us for resolving any classes
delegate = new ClassLoaderRepository(loader);
// TODO Alex do we need to call org.aspectj.apache.bcel.Repository.setRepository(delegate);
// if so, how can that be safe in J2EE ?? (static stuff in Bcel)
}
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 = MemberImpl.methodFromString(str.substring(i+2, str.length()).trim());
// now, we resolve
UnresolvedType[] 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(UnresolvedType type) {
return Type.getType(type.getErasureSignature());
}
static Type[] makeBcelTypes(UnresolvedType[] types) {
Type[] ret = new Type[types.length];
for (int i = 0, len = types.length; i < len; i++) {
ret[i] = makeBcelType(types[i]);
}
return ret;
}
static String[] makeBcelTypesAsClassNames(UnresolvedType[] types) {
String[] ret = new String[types.length];
for (int i = 0, len = types.length; i < len; i++) {
ret[i] = types[i].getClassName();//makeBcelType(types[i]);
}
return ret;
}
public static UnresolvedType fromBcel(Type t) {
return UnresolvedType.forSignature(t.getSignature());
}
static UnresolvedType[] fromBcel(Type[] ts) {
UnresolvedType[] ret = new UnresolvedType[ts.length];
for (int i = 0, len = ts.length; i < len; i++) {
ret[i] = fromBcel(ts[i]);
}
return ret;
}
public ResolvedType resolve(Type t) {
return resolve(fromBcel(t));
}
private int packageRestrictionsForFastDelegates = 0; // 0=dontknow 1=no 2=yes
private List packagePrefixRestrictionList = null;
public boolean isNotOnPackageRestrictedList(String s) {
if (packageRestrictionsForFastDelegates==0) {
Properties p = getExtraConfiguration();
String possiblePackageRestrictions = (p==null?null:p.getProperty("fastDelegateRestrictions"));
if (possiblePackageRestrictions==null) {
packageRestrictionsForFastDelegates=1;
} else {
packageRestrictionsForFastDelegates=2;
packagePrefixRestrictionList=new ArrayList();
StringTokenizer st = new StringTokenizer(possiblePackageRestrictions,":");
while (st.hasMoreTokens()) {
packagePrefixRestrictionList.add(st.nextToken());
}
}
}
if (packageRestrictionsForFastDelegates==1) return true;
if (packageRestrictionsForFastDelegates==2) {
for (Iterator iter = packagePrefixRestrictionList.iterator(); iter.hasNext();) {
String element = (String) iter.next();
if (s.startsWith(element)) {
// System.err.println("Not creating fast delegate for "+s);
return false;
}
}
}
return true;
}
protected ReferenceTypeDelegate resolveDelegate(ReferenceType ty) {
String name = ty.getName();
JavaClass jc = null;
ensureAdvancedConfigurationProcessed();
//UnwovenClassFile classFile = (UnwovenClassFile)sourceJavaClasses.get(name);
//if (classFile != null) jc = classFile.getJavaClass();
if (isFastDelegateSupportEnabled() && classPath!=null && !ty.needsModifiableDelegate() && isNotOnPackageRestrictedList(name)) {
ClassPathManager.ClassFile cf = classPath.find(ty);
if (cf==null) {
return null;
} else {
return buildAsmDelegate(ty,cf);
}
} else {
if (jc == null) {
jc = lookupJavaClass(classPath, name);
}
if (jc == null) {
return null;
} else {
return buildBcelDelegate(ty, jc, false);
}
}
}
private ReferenceTypeDelegate buildAsmDelegate(ReferenceType type,ClassPathManager.ClassFile t) {
AsmDelegate asmDelegate;
try {
asmDelegate = new AsmDelegate(type,t.getInputStream());
} catch (IOException e) {
e.printStackTrace();
return null;
}
return asmDelegate;
}
public BcelObjectType buildBcelDelegate(ReferenceType resolvedTypeX, JavaClass jc, boolean exposedToWeaver) {
BcelObjectType ret = new BcelObjectType(resolvedTypeX, jc, exposedToWeaver);
return ret;
}
private JavaClass lookupJavaClass(ClassPathManager classPath, String name) {
if (classPath == null) {
try {
return delegate.loadClass(name);
} catch (ClassNotFoundException e) {
return null;
}
}
try {
ClassPathManager.ClassFile file = classPath.find(UnresolvedType.forName(name));
if (file == null) return null;
ClassParser parser = new ClassParser(file.getInputStream(), file.getPath());
JavaClass jc = parser.parse();
file.close();
return jc;
} catch (IOException ioe) {
return null;
}
}
public BcelObjectType addSourceObjectType(JavaClass jc) {
BcelObjectType ret = null;
String signature = UnresolvedType.forName(jc.getClassName()).getSignature();
Object fromTheMap = typeMap.get(signature);
if (fromTheMap!=null && !(fromTheMap instanceof ReferenceType)) {
// what on earth is it then? See pr 112243
StringBuffer exceptionText = new StringBuffer();
exceptionText.append("Found invalid (not a ReferenceType) entry in the type map. ");
exceptionText.append("Signature=["+signature+"] Found=["+fromTheMap+"] Class=["+fromTheMap.getClass()+"]");
throw new BCException(exceptionText.toString());
}
ReferenceType nameTypeX = (ReferenceType)fromTheMap;
if (nameTypeX == null) {
if (jc.isGeneric() && isInJava5Mode()) {
nameTypeX = ReferenceType.fromTypeX(UnresolvedType.forRawTypeName(jc.getClassName()),this);
ret = buildBcelDelegate(nameTypeX, jc, true);
ReferenceType genericRefType = new ReferenceType(
UnresolvedType.forGenericTypeSignature(signature,ret.getDeclaredGenericSignature()),this);
nameTypeX.setDelegate(ret);
genericRefType.setDelegate(ret);
nameTypeX.setGenericType(genericRefType);
typeMap.put(signature, nameTypeX);
} else {
nameTypeX = new ReferenceType(signature, this);
ret = buildBcelDelegate(nameTypeX, jc, true);
typeMap.put(signature, nameTypeX);
}
} else {
ret = buildBcelDelegate(nameTypeX, jc, true);
}
return ret;
}
void deleteSourceObjectType(UnresolvedType ty) {
typeMap.remove(ty.getSignature());
}
public static Member makeFieldJoinPointSignature(LazyClassGen cg, FieldInstruction fi) {
ConstantPoolGen cpg = cg.getConstantPoolGen();
return
MemberImpl.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
// MemberImpl.field(
// fi.getClassName(cpg),
// (fi instanceof GETSTATIC || fi instanceof PUTSTATIC)
// ? Modifier.STATIC
// : 0,
// fi.getName(cpg),
// "(" + fi.getSignature(cpg) + ")" +fi.getSignature(cpg));
// }
public Member makeJoinPointSignature(LazyMethodGen mg) {
return makeJoinPointSignatureFromMethod(mg, null);
}
public Member makeJoinPointSignatureFromMethod(LazyMethodGen mg, MemberImpl.Kind kind) {
Member 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 ResolvedMemberImpl(kind,
UnresolvedType.forName(mg.getClassName()),
mods,
fromBcel(mg.getReturnType()),
mg.getName(),
fromBcel(mg.getArgumentTypes())
);
} else {
return ret;
}
}
public Member makeJoinPointSignatureForArrayConstruction(LazyClassGen cg, InstructionHandle handle) {
Instruction i = handle.getInstruction();
ConstantPoolGen cpg = cg.getConstantPoolGen();
Member retval = null;
if (i instanceof ANEWARRAY) {
ANEWARRAY arrayInstruction = (ANEWARRAY)i;
ObjectType ot = arrayInstruction.getLoadClassType(cpg);
UnresolvedType ut = fromBcel(ot);
ut = UnresolvedType.makeArray(ut,1);
retval = MemberImpl.method(ut, Modifier.PUBLIC, ResolvedType.VOID, "<init>", new ResolvedType[]{ResolvedType.INT});
} else if (i instanceof MULTIANEWARRAY) {
MULTIANEWARRAY arrayInstruction = (MULTIANEWARRAY)i;
UnresolvedType ut = null;
short dimensions = arrayInstruction.getDimensions();
ObjectType ot = arrayInstruction.getLoadClassType(cpg);
if (ot!=null) {
ut = fromBcel(ot);
ut = UnresolvedType.makeArray(ut,dimensions);
} else {
Type t = arrayInstruction.getType(cpg);
ut = fromBcel(t);
}
ResolvedType[] parms = new ResolvedType[dimensions];
for (int ii=0;ii<dimensions;ii++) parms[ii] = ResolvedType.INT;
retval = MemberImpl.method(ut, Modifier.PUBLIC, ResolvedType.VOID, "<init>", parms);
} else if (i instanceof NEWARRAY) {
NEWARRAY arrayInstruction = (NEWARRAY)i;
Type ot = arrayInstruction.getType();
UnresolvedType ut = fromBcel(ot);
retval = MemberImpl.method(ut, Modifier.PUBLIC, ResolvedType.VOID, "<init>", new ResolvedType[]{ResolvedType.INT});
} else {
throw new BCException("Cannot create array construction signature for this non-array instruction:"+i);
}
return retval;
}
public Member makeJoinPointSignatureForMethodInvocation(LazyClassGen cg, InvokeInstruction ii) {
ConstantPoolGen cpg = cg.getConstantPoolGen();
String name = ii.getName(cpg);
String declaring = ii.getClassName(cpg);
UnresolvedType declaringType = null;
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;
// in Java 1.4 and after, static method call of super class within subclass method appears
// as declared by the subclass in the bytecode - but they are not
// see #104212
if (ii instanceof INVOKESTATIC) {
ResolvedType appearsDeclaredBy = resolve(declaring);
// look for the method there
for (Iterator iterator = appearsDeclaredBy.getMethods(); iterator.hasNext();) {
ResolvedMember method = (ResolvedMember) iterator.next();
if (method.isStatic()) {
if (name.equals(method.getName()) && signature.equals(method.getSignature())) {
// we found it
declaringType = method.getDeclaringType();
break;
}
}
}
}
if (declaringType == null) {
if (declaring.charAt(0)=='[') declaringType = UnresolvedType.forSignature(declaring);
else declaringType = UnresolvedType.forName(declaring);
}
return MemberImpl.method(declaringType, 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 MemberImpl.method(
UnresolvedType.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 createAdviceMunger(
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, ResolvedType aspectType)
{
return new BcelTypeMunger(munger, aspectType);
}
public ConcreteTypeMunger makeCflowStackFieldAdder(ResolvedMember cflowField) {
return new BcelCflowStackFieldAdder(cflowField);
}
public ConcreteTypeMunger makeCflowCounterFieldAdder(ResolvedMember cflowField) {
return new BcelCflowCounterFieldAdder(cflowField);
}
/**
* Register a munger for perclause @AJ aspect so that we add aspectOf(..) to them as needed
*
* @param aspect
* @param kind
* @return munger
*/
public ConcreteTypeMunger makePerClauseAspect(ResolvedType aspect, PerClause.Kind kind) {
return new BcelPerClauseAspectAdder(aspect, kind);
}
/**
* Retrieve a bcel delegate for an aspect - this will return NULL if the
* delegate is an EclipseSourceType and not a BcelObjectType - this happens
* quite often when incrementally compiling.
*/
public static BcelObjectType getBcelObjectType(ResolvedType concreteAspect) {
ReferenceTypeDelegate rtDelegate = ((ReferenceType)concreteAspect).getDelegate();
if (rtDelegate instanceof BcelObjectType) {
return (BcelObjectType)rtDelegate;
} else {
return null;
}
}
public void tidyUp() {
// At end of compile, close any open files so deletion of those archives is possible
classPath.closeArchives();
typeMap.report();
ResolvedType.resetPrimitives();
}
/// The repository interface methods
public JavaClass findClass(String className) {
return lookupJavaClass(classPath,className);
}
public JavaClass loadClass(String className) throws ClassNotFoundException {
return lookupJavaClass(classPath,className);
}
public void storeClass(JavaClass clazz) {
throw new RuntimeException("Not implemented");
}
public void removeClass(JavaClass clazz) {
throw new RuntimeException("Not implemented");
}
public JavaClass loadClass(Class clazz) throws ClassNotFoundException {
throw new RuntimeException("Not implemented");
}
public void clear() {
throw new RuntimeException("Not implemented");
}
// @Override
/**
* The aim of this method is to make sure a particular type is 'ok'. Some
* operations on the delegate for a type modify it and this method is
* intended to undo that... see pr85132
*/
public void validateType(UnresolvedType type) {
ResolvedType result = typeMap.get(type.getSignature());
if (result==null) return; // We haven't heard of it yet
if (!result.isExposedToWeaver()) return; // cant need resetting
ReferenceType rt = (ReferenceType)result;
rt.getDelegate().ensureDelegateConsistent();
// If we want to rebuild it 'from scratch' then:
// ClassParser cp = new ClassParser(new ByteArrayInputStream(newbytes),new String(cs));
// try {
// rt.setDelegate(makeBcelObjectType(rt,cp.parse(),true));
// } catch (ClassFormatException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
}
/**
* Checks if given bytecode is an @AspectJ aspect
*
* @param name
* @param bytes
* @return true if so
*/
public boolean isAnnotationStyleAspect(String name, byte[] bytes) {
try {
ClassParser cp = new ClassParser(new ByteArrayInputStream(bytes), null);
JavaClass jc = cp.parse();
if (!jc.isClass()) {
return false;
}
Annotation anns[] = jc.getAnnotations();
if (anns.length == 0) {
return false;
}
boolean couldBeAtAspectJStyle = false;
for (int i = 0; i < anns.length; i++) {
Annotation ann = anns[i];
if ("Lorg/aspectj/lang/annotation/Aspect;".equals(ann.getTypeSignature())) {
couldBeAtAspectJStyle = true;
}
}
if (!couldBeAtAspectJStyle) return false;
// ok, so it has the annotation, but it could have been put
// on a code style aspect by the annotation visitor
Attribute[] attributes = jc.getAttributes();
for (int i = 0; i < attributes.length; i++) {
if (attributes[i].getName().equals(Aspect.AttributeName)) {
return false;
}
}
return true;
} catch (IOException e) {
// assume it is one as a best effort
return true;
}
}
}
|
135,001 |
Bug 135001 NPE at at org.aspectj.weaver.bcel.BcelShadow.weaveAroundInline
|
java.lang.NullPointerException at org.aspectj.weaver.bcel.BcelShadow.weaveAroundInline(BcelShadow.java:2109) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:232) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:639) at org.aspectj.weaver.Shadow.implement(Shadow.java:456) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2236) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:491) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:109) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1560) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1511) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1291) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1113) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:311) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:183) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:242) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:161) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191)
|
resolved fixed
|
1a6f695
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-04-06T11:45:02Z | 2006-04-05T12:26:40Z |
weaver/testsrc/org/aspectj/weaver/bcel/AsmDelegateTests.java
|
/* *******************************************************************
* Copyright (c) 2006 Contributors
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.aspectj.weaver.AbstractReferenceTypeDelegate;
import org.aspectj.weaver.AbstractWorldTestCase;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AnnotationX;
import org.aspectj.weaver.BcweaverTests;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ReferenceTypeDelegate;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.AjAttribute.EffectiveSignatureAttribute;
import org.aspectj.weaver.asm.AsmDelegate;
import org.aspectj.weaver.asm.AsmField;
import org.aspectj.weaver.asm.AsmMethod;
/**
* This is a test case for the nameType parts of worlds.
*/
public class AsmDelegateTests extends AbstractWorldTestCase {
private final BcelWorld world = new BcelWorld(BcweaverTests.TESTDATA_PATH+"/forAsmDelegateTesting/stuff.jar");
public AsmDelegateTests(String name) {
super(name);
}
protected World getWorld() {
return world;
}
// --- testcode
public void testWeDontGoBang() {
ResolvedType rt = world.resolve("SimpleAspect");
ReferenceTypeDelegate delegate = ((ReferenceType)rt).getDelegate();
assertTrue("Should be an ASM delegate but is "+delegate.getClass(),
delegate.getClass().toString().equals("class org.aspectj.weaver.asm.AsmDelegate"));
}
public void testDifferentiatingBetweenAspectAndClass() {
ReferenceType rtAspect = (ReferenceType)world.resolve("SimpleAspect");
ReferenceType rtString = (ReferenceType)world.resolve("java.lang.String");
assertTrue("SimpleAspect should be an aspect",rtAspect.isAspect());
assertTrue("String should not be an aspect",!rtString.isAspect());
assertTrue("Should be a persingleton "+rtAspect.getPerClause(),rtAspect.getPerClause().toString().startsWith("persingleton"));
}
public void testRecognizingDifferentTypes() {
ResolvedType rtAnnotation = world.resolve("SimpleAnnotation");
ResolvedType rtEnum = world.resolve("SimpleEnum");
ResolvedType rtString = world.resolve("java.lang.String");
assertTrue("Should be an annotation type",rtAnnotation.isAnnotation());
assertTrue("Should be an enum type",rtEnum.isEnum());
assertTrue("Should not be an annotation or enum type",!(rtString.isAnnotation() || rtString.isEnum()));
}
public void testAnnotationsBehaving() {
ReferenceType rtAnnotation = (ReferenceType)world.resolve("SimpleAnnotation");
assertTrue("Should be SOURCE but is "+rtAnnotation.getRetentionPolicy(),rtAnnotation.getRetentionPolicy().equals("SOURCE"));
ReferenceType rtAnnotation2 = (ReferenceType)world.resolve("SimpleAnnotation2");
assertTrue("Should be CLASS but is "+rtAnnotation2.getRetentionPolicy(),rtAnnotation2.getRetentionPolicy().equals("CLASS"));
ReferenceType rtAnnotation3 = (ReferenceType)world.resolve("SimpleAnnotation3");
assertTrue("Should be RUNTIME but is "+rtAnnotation3.getRetentionPolicy(),rtAnnotation3.getRetentionPolicy().equals("RUNTIME"));
ReferenceType rtAnnotation4 = (ReferenceType)world.resolve("SimpleAnnotation4");
assertTrue("Should be CLASS but is "+rtAnnotation4.getRetentionPolicy(),rtAnnotation4.getRetentionPolicy().equals("CLASS"));
}
public void testInterfaceflag() {
ReferenceType rtString = (ReferenceType)world.resolve("java.lang.String");
assertTrue("String should not be an interface",!rtString.isInterface());
ReferenceType rtSerializable = (ReferenceType)world.resolve("java.io.Serializable");
assertTrue("Serializable should be an interface",rtSerializable.isInterface());
}
public void testCompareDelegates() {
BcelWorld slowWorld = new BcelWorld(BcweaverTests.TESTDATA_PATH+"/forAsmDelegateTesting/stuff.jar");
slowWorld.setFastDelegateSupport(false);
BcelWorld fastWorld = new BcelWorld(BcweaverTests.TESTDATA_PATH+"/forAsmDelegateTesting/stuff.jar");
ReferenceType bcelList = (ReferenceType)slowWorld.resolve("java.util.List");
ReferenceType asmList = (ReferenceType)fastWorld.resolve("java.util.List");
assertTrue("Should be a bcel delegate? "+bcelList.getDelegate().getClass(),
bcelList.getDelegate().getClass().toString().equals("class org.aspectj.weaver.bcel.BcelObjectType"));
assertTrue("Should be an asm delegate? "+asmList.getDelegate().getClass(),
asmList.getDelegate().getClass().toString().equals("class org.aspectj.weaver.asm.AsmDelegate"));
TypeVariable[] bcelTVars = bcelList.getTypeVariables();
TypeVariable[] asmTVars = asmList.getTypeVariables();
for (int i = 0; i < asmTVars.length; i++) {
TypeVariable variable = asmTVars[i];
}
String bcelsig = bcelList.getSignature();
String asmsig = asmList.getSignature();
assertTrue("Signatures should be the same but "+bcelsig+"!="+asmsig,bcelsig.equals(asmsig));
String bcelerasuresig = bcelList.getErasureSignature();
String asmerasuresig = asmList.getErasureSignature();
assertTrue("Erasure Signatures should be the same but "+bcelerasuresig+"!="+asmerasuresig,bcelerasuresig.equals(asmerasuresig));
ResolvedMember[] bcelfields = bcelList.getDeclaredFields();
ResolvedMember[] asmfields = asmList.getDeclaredFields();
if (bcelfields.length!=asmfields.length) {
fail("Dont have the same number of fields? bcel="+bcelfields.length+" asm="+asmfields.length);
}
for (int i = 0; i < asmfields.length; i++) {
ResolvedMember member = asmfields[i];
if (!bcelfields[i].equals(asmfields[i])) {
fail("Differing fields: "+bcelfields[i]+" and "+asmfields[i]);
}
}
}
public void testCompareDelegatesComplex() {
BcelWorld slowWorld = new BcelWorld(BcweaverTests.TESTDATA_PATH+"/forAsmDelegateTesting/stuff.jar");
slowWorld.setFastDelegateSupport(false);
BcelWorld fastWorld = new BcelWorld(BcweaverTests.TESTDATA_PATH+"/forAsmDelegateTesting/stuff.jar");
ReferenceType bComplex = (ReferenceType)slowWorld.resolve("Complex");
ReferenceType aComplex = (ReferenceType)fastWorld.resolve("Complex");
checkEquivalent("",(AbstractReferenceTypeDelegate)aComplex.getDelegate(),(AbstractReferenceTypeDelegate)bComplex.getDelegate());
}
/**
* Methods are transformed according to generic signatures - this checks
* that some of the generic methods in java.lang.Class appear the same
* whether viewed through an ASM or a BCEL delegate.
*/
public void testCompareGenericMethods() {
BcelWorld slowWorld = new BcelWorld();
slowWorld.setFastDelegateSupport(false);
slowWorld.setBehaveInJava5Way(true);
BcelWorld fastWorld = new BcelWorld();
fastWorld.setBehaveInJava5Way(true);
ResolvedType bcelJavaLangClass = slowWorld.resolve(UnresolvedType.forName("java.lang.Class"));
ResolvedType asmJavaLangClass = fastWorld.resolve(UnresolvedType.forName("java.lang.Class"));
bcelJavaLangClass = bcelJavaLangClass.getGenericType();
asmJavaLangClass = asmJavaLangClass.getGenericType();
//if (bcelJavaLangClass == null) return; // for < 1.5
ResolvedMember[] bcelMethods = bcelJavaLangClass.getDeclaredMethods();
ResolvedMember[] asmMethods = asmJavaLangClass.getDeclaredMethods();
for (int i = 0; i < bcelMethods.length; i++) {
bcelMethods[i].setParameterNames(null); // forget them, asm delegates dont currently know them
String one = bcelMethods[i].toDebugString();
String two = asmMethods[i].toDebugString();
if (!one.equals(two)) {
fail("These methods look different when viewed through ASM or BCEL\nBCEL='"+bcelMethods[i].toDebugString()+
"'\n ASM='"+asmMethods[i].toDebugString()+"'");
}
// If one is parameterized, check the other is...
if (bcelMethods[i].canBeParameterized()) {
assertTrue("ASM method '"+asmMethods[i].toDebugString()+"' can't be parameterized whereas its' BCEL variant could",
asmMethods[i].canBeParameterized());
}
}
// Let's take a special look at:
// public <U> Class<? extends U> asSubclass(Class<U> clazz)
ResolvedMember bcelSubclassMethod = null;
for (int i = 0; i < bcelMethods.length; i++) {
if (bcelMethods[i].getName().equals("asSubclass")) { bcelSubclassMethod = bcelMethods[i]; break; }
}
ResolvedMember asmSubclassMethod = null;
for (int i = 0; i < asmMethods.length; i++) {
if (asmMethods[i].getName().equals("asSubclass")) { asmSubclassMethod = asmMethods[i];break; }
}
TypeVariable[] tvs = bcelSubclassMethod.getTypeVariables();
assertTrue("should have one type variable on the bcel version but found: "+format(tvs),tvs!=null && tvs.length==1);
tvs = asmSubclassMethod.getTypeVariables();
assertTrue("should have one type variable on the asm version but found: "+format(tvs),tvs!=null && tvs.length==1);
}
private String format(TypeVariable[] tvs) {
if (tvs==null) return "null";
StringBuffer s = new StringBuffer();
s.append("[");
for (int i = 0; i < tvs.length; i++) {
s.append(tvs[i]);
if ((i+1)<tvs.length) s.append(",");
}
s.append("]");
return s.toString();
}
public void testCompareGenericFields() {
BcelWorld slowWorld = new BcelWorld();
slowWorld.setFastDelegateSupport(false);
slowWorld.setBehaveInJava5Way(true);
BcelWorld fastWorld = new BcelWorld();
fastWorld.setBehaveInJava5Way(true);
ResolvedType bcelJavaLangClass = slowWorld.resolve(UnresolvedType.forName("java.lang.Class"));
ResolvedType asmJavaLangClass = fastWorld.resolve(UnresolvedType.forName("java.lang.Class"));
bcelJavaLangClass = bcelJavaLangClass.getGenericType();
asmJavaLangClass = asmJavaLangClass.getGenericType();
if (bcelJavaLangClass == null) return; // for < 1.5
ResolvedMember[] bcelFields = bcelJavaLangClass.getDeclaredFields();
ResolvedMember[] asmFields = asmJavaLangClass.getDeclaredFields();
for (int i = 0; i < bcelFields.length; i++) {
UnresolvedType bcelFieldType = bcelFields[i].getGenericReturnType();
UnresolvedType asmFieldType = asmFields[i].getGenericReturnType();
if (!bcelFields[i].getGenericReturnType().toDebugString().equals(asmFields[i].getGenericReturnType().toDebugString())) {
fail("These fields look different when viewed through ASM or BCEL\nBCEL='"+bcelFieldType.toDebugString()+
"'\n ASM='"+asmFieldType.toDebugString()+"'");
}
}
}
public void testCompareDelegatesMonster() {
BcelWorld slowWorld = new BcelWorld("../lib/aspectj/lib/aspectjtools.jar");slowWorld.setFastDelegateSupport(false);
BcelWorld fastWorld = new BcelWorld("../lib/aspectj/lib/aspectjtools.jar");
ResolvedMemberImpl.showParameterNames=false;
try {
File f = new File("../lib/aspectj/lib/aspectjtools.jar");
assertTrue("Couldnt find aspectjtools to test. Tried: "+f.getAbsolutePath(),f.exists());
ZipFile zf = new ZipFile(f);
int i = 0;
Enumeration entries = zf.entries();
while (entries.hasMoreElements()) {
ZipEntry zfe = (ZipEntry)entries.nextElement();
String classfileName = zfe.getName();
if (classfileName.endsWith(".class")) {
String clazzname = classfileName.substring(0,classfileName.length()-6).replace('/','.');
ReferenceType b = (ReferenceType)slowWorld.resolve(clazzname);
ReferenceType a = (ReferenceType)fastWorld.resolve(clazzname);
checkEquivalent("Comparison number #"+(i++)+" ",(AbstractReferenceTypeDelegate)a.getDelegate(),(AbstractReferenceTypeDelegate)b.getDelegate());
}
}
//System.err.println();("Successfully compared "+i+" entries!!");
} catch (IOException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
public void testCompareDelegatesLoadingPerformance() {
BcelWorld slowWorld = new BcelWorld("../lib/aspectj/lib/aspectjtools.jar");slowWorld.setFastDelegateSupport(false);
BcelWorld fastWorld = new BcelWorld("../lib/aspectj/lib/aspectjtools.jar");
ResolvedMemberImpl.showParameterNames=false;
try {
File f = new File("../lib/aspectj/lib/aspectjtools.jar");
assertTrue("Couldnt find aspectjtools to test. Tried: "+f.getAbsolutePath(),f.exists());
ZipFile zf = new ZipFile(f);
int i = 0;
long stime = System.currentTimeMillis();
Enumeration entries = zf.entries();
while (entries.hasMoreElements()) {
ZipEntry zfe = (ZipEntry)entries.nextElement();
String classfileName = zfe.getName();
if (classfileName.endsWith(".class")) {
String clazzname = classfileName.substring(0,classfileName.length()-6).replace('/','.');
ReferenceType b = (ReferenceType)slowWorld.resolve(clazzname);
i++;
}
}
long etime = System.currentTimeMillis();
System.err.println("Time taken to load "+i+" entries with BCEL="+(etime-stime)+"ms");
//System.err.println();("Successfully compared "+i+" entries!!");
} catch (IOException e) {
e.printStackTrace();
fail(e.getMessage());
}
try {
File f = new File("../lib/aspectj/lib/aspectjtools.jar");
assertTrue("Couldnt find aspectjtools to test. Tried: "+f.getAbsolutePath(),f.exists());
ZipFile zf = new ZipFile(f);
int i = 0;
long stime = System.currentTimeMillis();
Enumeration entries = zf.entries();
while (entries.hasMoreElements()) {
ZipEntry zfe = (ZipEntry)entries.nextElement();
String classfileName = zfe.getName();
if (classfileName.endsWith(".class")) {
String clazzname = classfileName.substring(0,classfileName.length()-6).replace('/','.');
ReferenceType b = (ReferenceType)fastWorld.resolve(clazzname);
i++;
}
}
long etime = System.currentTimeMillis();
System.err.println("Time taken to load "+i+" entries with ASM="+(etime-stime)+"ms");
//System.err.println();("Successfully compared "+i+" entries!!");
} catch (IOException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
private void checkEquivalent(String prefix,AbstractReferenceTypeDelegate asmType,AbstractReferenceTypeDelegate bcelType) {
assertTrue("Should be a bcel delegate? "+bcelType.getClass(),
bcelType.getClass().toString().equals("class org.aspectj.weaver.bcel.BcelObjectType"));
assertTrue("Should be an asm delegate? "+asmType.getClass(),
asmType.getClass().toString().equals("class org.aspectj.weaver.asm.AsmDelegate"));
String asmString = asmType.stringifyDelegate();
String bcelString= bcelType.stringifyDelegate();
if (!asmString.equals(bcelString)) {
fail(prefix+"Delegates don't match for "+bcelType.getResolvedTypeX()+"\n ASM=\n"+asmString+"\n BCEL=\n"+bcelString);
}
}
private void compareAnnotations(String n,World bcelWorld,World asmWorld) {
ReferenceType bcelT = (ReferenceType)bcelWorld.resolve(n);
ReferenceType asmT = (ReferenceType)asmWorld.resolve(n);
ensureTheSame(bcelT.getAnnotations(),asmT.getAnnotations());
}
private void ensureTheSame(AnnotationX[] bcelSet,AnnotationX[] asmSet) {
String bcelString = stringify(bcelSet);
String asmString = stringify(asmSet);
if (bcelSet.length!=asmSet.length) {
fail("Lengths are different!!! Not a good start. \nBcel reports: \n"+bcelString+" Asm reports: \n"+asmString);
}
assertTrue("Different answers. \nBcel reports: \n"+bcelString+" Asm reports: \n"+asmString,bcelString.equals(asmString));
}
public String stringify(AnnotationX[] annotations) {
if (annotations==null) return "";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < annotations.length; i++) {
AnnotationX annotationX = annotations[i];
sb.append(i+") "+annotationX.toString());
sb.append("\n");
}
return sb.toString();
}
public void testDifferentAnnotationKinds() {
BcelWorld slowWorld = new BcelWorld(BcweaverTests.TESTDATA_PATH+"/forAsmDelegateTesting/stuff.jar");slowWorld.setFastDelegateSupport(false);
BcelWorld fastWorld = new BcelWorld(BcweaverTests.TESTDATA_PATH+"/forAsmDelegateTesting/stuff.jar");
compareAnnotations("AnnotatedClass",slowWorld,fastWorld);
compareAnnotations("AnnotatedFields",slowWorld,fastWorld);
compareAnnotations("AnnotatedMethods",slowWorld,fastWorld);
compareAnnotations("AnnotatedWithClassClass",slowWorld,fastWorld);
compareAnnotations("AnnotatedWithCombinedAnnotation",slowWorld,fastWorld);
compareAnnotations("AnnotatedWithEnumClass",slowWorld,fastWorld);
compareAnnotations("AnnotationClassElement",slowWorld,fastWorld);
compareAnnotations("AnnotationEnumElement",slowWorld,fastWorld);
compareAnnotations("ComplexAnnotation",slowWorld,fastWorld);
compareAnnotations("CombinedAnnotation",slowWorld,fastWorld);
compareAnnotations("ComplexAnnotatedClass",slowWorld,fastWorld);
}
/**
* Load up the AspectFromHell and take it apart...
*/
public void testLoadingAttributesForTypes() {
BcelWorld slowWorld = new BcelWorld(BcweaverTests.TESTDATA_PATH+"/forAsmDelegateTesting/stuff.jar");slowWorld.setFastDelegateSupport(false);
BcelWorld fastWorld = new BcelWorld(BcweaverTests.TESTDATA_PATH+"/forAsmDelegateTesting/stuff.jar");
ReferenceType bcelT = (ReferenceType)slowWorld.resolve("AspectFromHell");
ReferenceType asmT = (ReferenceType)fastWorld.resolve("AspectFromHell");
AsmDelegate asmD = (AsmDelegate)asmT.getDelegate();
String [] asmAttributeNames = asmD.getAttributeNames();
BcelObjectType bcelD = (BcelObjectType)bcelT.getDelegate();
String [] bcelAttributeNames = bcelD.getAttributeNames();
// Won't be exactly the same number as ASM currently processes some and then discards them - effectively those stored in the delegate
// are the 'not yet processed' ones
// should be 6 type mungers
AjAttribute[] asmTypeMungers = asmD.getAttributes("org.aspectj.weaver.TypeMunger");
AjAttribute[] bcelTypeMungers = bcelD.getAttributes("org.aspectj.weaver.TypeMunger");
assertTrue("Should be 6 type mungers but asm="+asmTypeMungers.length+" bcel="+bcelTypeMungers.length,asmTypeMungers.length==6 && bcelTypeMungers.length==6);
}
public void testLoadingAttributesForMethods() {
boolean debug = false;
BcelWorld slowWorld = new BcelWorld(BcweaverTests.TESTDATA_PATH+"/forAsmDelegateTesting/stuff.jar");slowWorld.setFastDelegateSupport(false);
BcelWorld fastWorld = new BcelWorld(BcweaverTests.TESTDATA_PATH+"/forAsmDelegateTesting/stuff.jar");
ReferenceType bcelT = (ReferenceType)slowWorld.resolve("AspectFromHell");
ReferenceType asmT = (ReferenceType)fastWorld.resolve("AspectFromHell");
ResolvedMember[] bcelMethods = bcelT.getDeclaredMethods();
ResolvedMember[] asmMethods = asmT.getDeclaredMethods();
for (int i = 0; i < bcelMethods.length; i++) {
BcelMethod bmember = (BcelMethod)bcelMethods[i];
AsmMethod amember = (AsmMethod)asmMethods[i];
assertTrue("Seem to be in a muddle. a="+amember.getName()+" b="+bmember.getName(),
amember.getName().equals(bmember.getName()));
if (debug) System.err.println("Looking at "+bmember);
String[] bcelMemberAttributes = bmember.getAttributeNames(true);
String[] asmMemberAttributes = amember.getAttributeNames(true);
// System.err.println("BCEL=>\n"+stringifyStringArray(bcelMemberAttributes));
// System.err.println(" ASM=>\n"+stringifyStringArray(asmMemberAttributes));
compareAttributeNames(bcelMemberAttributes,asmMemberAttributes);
// Let's check the member ones of interest:
// org.aspectj.weaver.AjSynthetic
if (bmember.isAjSynthetic()) {
assertTrue("Why isnt the ASM method ajsynthetic? "+amember.toDebugString(),amember.isAjSynthetic());
} else {
assertTrue("Why is the ASM method ajsynthetic? "+amember.toDebugString(),!amember.isAjSynthetic());
}
// org.aspectj.weaver.EffectiveSignature
EffectiveSignatureAttribute bcelEsa = bmember.getEffectiveSignature();
EffectiveSignatureAttribute asmEsa = amember.getEffectiveSignature();
if (bcelEsa==null) {
assertTrue("Why isnt the ASM effective signature null? "+asmEsa,asmEsa==null);
} else {
if (asmEsa==null) fail("ASM effective signature is null, when BCEL effective signature is "+bcelEsa.toString());
assertTrue("Should be the same?? b="+bcelEsa.toString()+" a="+asmEsa.toString(),bcelEsa.toString().equals(asmEsa.toString()));
}
// org.aspectj.weaver.MethodDeclarationLineNumber
int bLine = bmember.getDeclarationLineNumber();
int aLine = amember.getDeclarationLineNumber();
assertTrue("Should be the same number: "+bLine+" "+aLine,bLine==aLine);
// org.aspectj.weaver.Advice
ShadowMunger bcelSM = bmember.getAssociatedShadowMunger();
ShadowMunger asmSM = amember.getAssociatedShadowMunger();
if (bcelSM==null) {
assertTrue("Why isnt the ASM effective signature null? "+asmSM,asmSM==null);
} else {
if (asmSM==null) fail("ASM effective signature is null, when BCEL effective signature is "+bcelSM.toString());
assertTrue("Should be the same?? b="+bcelSM.toString()+" a="+asmSM.toString(),bcelSM.toString().equals(asmSM.toString()));
}
// new AjASMAttribute("org.aspectj.weaver.SourceContext"),
}
}
// @SimpleAnnotation(id=1) int i;
// @SimpleAnnotation(id=2) String s;
public void testLoadingAnnotationsForFields() {
boolean debug = false;
BcelWorld slowWorld = new BcelWorld(BcweaverTests.TESTDATA_PATH+"/forAsmDelegateTesting/stuff.jar");slowWorld.setFastDelegateSupport(false);
BcelWorld fastWorld = new BcelWorld(BcweaverTests.TESTDATA_PATH+"/forAsmDelegateTesting/stuff.jar");
ReferenceType bcelT = (ReferenceType)slowWorld.resolve("AnnotatedFields");
ReferenceType asmT = (ReferenceType)fastWorld.resolve("AnnotatedFields");
ResolvedMember[] bcelFields = bcelT.getDeclaredFields();
ResolvedMember[] asmFields = asmT.getDeclaredFields();
for (int i = 0; i < bcelFields.length; i++) {
BcelField bmember = (BcelField)bcelFields[i];
AsmField amember = (AsmField)asmFields[i];
assertTrue("Seem to be in a muddle. a="+amember.getName()+" b="+bmember.getName(),
amember.getName().equals(bmember.getName()));
if (debug) System.err.println("Looking at "+bmember);
ResolvedType[] bAnns = bmember.getAnnotationTypes();
ResolvedType[] aAnns = amember.getAnnotationTypes();
assertTrue("Should have found an annotation on the bcel field?",bAnns!=null && bAnns.length==1);
assertTrue("Should have found an annotation on the asm field?",aAnns!=null && aAnns.length==1);
assertTrue("BCEL annotation should be 'SimpleAnnotation3' but is "+bAnns[0].toString(),bAnns[0].toString().equals("SimpleAnnotation3"));
assertTrue("ASM annotation should be 'SimpleAnnotation3' but is "+aAnns[0].toString(),aAnns[0].toString().equals("SimpleAnnotation3"));
AnnotationX[] bXs = bmember.getAnnotations();
AnnotationX[] aXs = amember.getAnnotations();
assertTrue("Should have found an annotation on the bcel field?",bXs!=null && bXs.length==1);
assertTrue("Should have found an annotation on the asm field?",aXs!=null && aXs.length==1);
String exp = null;
if (i==0) exp = "ANNOTATION [LSimpleAnnotation3;] [runtimeVisible] [id=1]";
else if (i==1) exp="ANNOTATION [LSimpleAnnotation3;] [runtimeVisible] [id=2]";
assertTrue("BCEL annotation should be '"+exp+"' but is "+bXs[0].toString(),bXs[0].toString().equals(exp));
assertTrue("ASM annotation should be '"+exp+"' but is "+aXs[0].toString(),aXs[0].toString().equals(exp));
}
}
// @SimpleAnnotation(id=1)
// public void method1() { }
//
// @SimpleAnnotation(id=2)
// public void method2() { }
public void testLoadingAnnotationsForMethods() {
boolean debug = false;
BcelWorld slowWorld = new BcelWorld(BcweaverTests.TESTDATA_PATH+"/forAsmDelegateTesting/stuff.jar");slowWorld.setFastDelegateSupport(false);
BcelWorld fastWorld = new BcelWorld(BcweaverTests.TESTDATA_PATH+"/forAsmDelegateTesting/stuff.jar");
ReferenceType bcelT = (ReferenceType)slowWorld.resolve("AnnotatedMethods");
ReferenceType asmT = (ReferenceType)fastWorld.resolve("AnnotatedMethods");
ResolvedMember[] bcelMethods = bcelT.getDeclaredMethods();
ResolvedMember[] asmMethods = asmT.getDeclaredMethods();
for (int i = 0; i < bcelMethods.length; i++) {
BcelMethod bmember = (BcelMethod)bcelMethods[i];
AsmMethod amember = (AsmMethod)asmMethods[i];
if (!bmember.getName().startsWith("method")) continue;
assertTrue("Seem to be in a muddle. a="+amember.getName()+" b="+bmember.getName(),
amember.getName().equals(bmember.getName()));
if (debug) System.err.println("Looking at "+bmember);
ResolvedType[] bAnns = bmember.getAnnotationTypes();
ResolvedType[] aAnns = amember.getAnnotationTypes();
assertTrue("Should have found an annotation on the bcel method?",bAnns!=null && bAnns.length==1);
assertTrue("Should have found an annotation on the asm method?",aAnns!=null && aAnns.length==1);
assertTrue("BCEL annotation should be 'SimpleAnnotation3' but is "+bAnns[0].toString(),bAnns[0].toString().equals("SimpleAnnotation3"));
assertTrue("ASM annotation should be 'SimpleAnnotation3' but is "+aAnns[0].toString(),aAnns[0].toString().equals("SimpleAnnotation3"));
AnnotationX[] bXs = bmember.getAnnotations();
AnnotationX[] aXs = amember.getAnnotations();
assertTrue("Should have found an annotation on the bcel method?",bXs!=null && bXs.length==1);
assertTrue("Should have found an annotation on the asm method?",aXs!=null && aXs.length==1);
String exp = null;
if (i==1) exp = "ANNOTATION [LSimpleAnnotation3;] [runtimeVisible] [id=1]";
else if (i==2) exp="ANNOTATION [LSimpleAnnotation3;] [runtimeVisible] [id=2]";
assertTrue("BCEL annotation should be '"+exp+"' but is "+bXs[0].toString(),bXs[0].toString().equals(exp));
assertTrue("ASM annotation should be '"+exp+"' but is "+aXs[0].toString(),aXs[0].toString().equals(exp));
}
}
private void compareAttributeNames(String[] asmlist,String[] bcellist) {
String astring = stringifyStringArray(asmlist);
String bstring = stringifyStringArray(bcellist);
if (asmlist.length!=bcellist.length) {
fail("Differing lengths.\nBCEL=>\n"+bstring+" ASM=>\n"+astring);
}
}
private String stringifyStringArray(String[] s) {
StringBuffer r = new StringBuffer();
for (int i = 0; i < s.length; i++) {
r.append(s[i]).append("\n");
}
return r.toString();
}
}
|
136,665 |
Bug 136665 Bug: ajc fails on missing classpath entries with fix
|
[iajc] error at (no source information available) [iajc] File.aj:0::0 Internal compiler error [iajc] org.aspectj.weaver.BCException: Can't open archive: missingjar [iajc] when resolving types defined in compilation unit File.aj [iajc] when processing compilation unit File.aj [iajc] when batch building BuildConfig[null] #Files=14 [iajc] [iajc] at org.aspectj.weaver.bcel.ClassPathManager$ZipFileEntry.ensureO pen(ClassPathManager.java:258) [iajc] at org.aspectj.weaver.bcel.ClassPathManager$ZipFileEntry.find(Cl assPathManager.java:225) [iajc] at org.aspectj.weaver.bcel.ClassPathManager.find(ClassPathManage r.java:92) [iajc] at org.aspectj.weaver.bcel.BcelWorld.resolveDelegate(BcelWorld.j ava:287) [iajc] at org.aspectj.weaver.World.resolveToReferenceType(World.java:33 5) [iajc] at org.aspectj.weaver.World.resolve(World.java:251) [iajc] at org.aspectj.weaver.patterns.WildTypePattern.lookupTypeInWorld (WildTypePattern.java:716) [iajc] at org.aspectj.weaver.patterns.WildTypePattern.resolveBindingsFr omFullyQualifiedTypeName(WildTypePattern.java:690) [iajc] at org.aspectj.weaver.patterns.WildTypePattern.resolveBindings(W ildTypePattern.java:623) [iajc] at org.aspectj.weaver.patterns.SignaturePattern.resolveBindings( SignaturePattern.java:82) [iajc] at org.aspectj.weaver.patterns.KindedPointcut.resolveBindings(Ki ndedPointcut.java:259) [iajc] at org.aspectj.weaver.patterns.AndPointcut.resolveBindings(AndPo intcut.java:74) [iajc] at org.aspectj.weaver.patterns.Pointcut.resolve(Pointcut.java:19 4) [iajc] at org.aspectj.ajdt.internal.compiler.ast.PointcutDesignator.fin ishResolveTypes(PointcutDesignator.java:84) [iajc] at org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration.reso lveStatements(AdviceDeclaration.java:118) [iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMet hodDeclaration.resolve(AbstractMethodDeclaration.java:400) [iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclara tion.resolve(TypeDeclaration.java:1088) [iajc] at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.reso lve(AspectDeclaration.java:116) [iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclara tion.resolve(TypeDeclaration.java:1137) [iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.Compilation UnitDeclaration.resolve(CompilationUnitDeclaration.java:305) [iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.proces s(Compiler.java:514) [iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compil e(Compiler.java:329) [iajc] at org.aspectj.ajdt.internal.core.builder.AjBuildManager.perform Compilation(AjBuildManager.java:845) [iajc] at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:241) [iajc] at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBu ild(AjBuildManager.java:161) [iajc] at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:1 12) [iajc] at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java: 60) [iajc] at org.aspectj.tools.ajc.Main.run(Main.java:356) [iajc] at org.aspectj.tools.ajc.Main.runMain(Main.java:246) [iajc] at org.aspectj.tools.ant.taskdefs.AjcTask.executeInSameVM(AjcTas k.java:1262) [iajc] at org.aspectj.tools.ant.taskdefs.AjcTask.execute(AjcTask.java:1 056) [iajc] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.ja va:275) [iajc] at org.apache.tools.ant.Task.perform(Task.java:364) [iajc] at org.apache.tools.ant.Target.execute(Target.java:341) [iajc] at org.apache.tools.ant.Target.performTasks(Target.java:369) [iajc] at org.apache.tools.ant.Project.executeTarget(Project.java:1214) [iajc] at org.apache.tools.ant.taskdefs.Ant.execute(Ant.java:386) [iajc] at org.apache.tools.ant.taskdefs.CallTarget.execute(CallTarget.j ava:106) [iajc] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.ja va:275) [iajc] at org.apache.tools.ant.Task.perform(Task.java:364) [iajc] at org.apache.tools.ant.Target.execute(Target.java:341) [iajc] at org.apache.tools.ant.Target.performTasks(Target.java:369) [iajc] at org.apache.tools.ant.Project.executeTarget(Project.java:1214) [iajc] at org.apache.tools.ant.Project.executeTargets(Project.java:1062 ) [iajc] at org.apache.tools.ant.Main.runBuild(Main.java:673) [iajc] at org.apache.tools.ant.Main.startAnt(Main.java:188) [iajc] at org.apache.tools.ant.launch.Launcher.run(Launcher.java:196) [iajc] at org.apache.tools.ant.launch.Launcher.main(Launcher.java:55) [iajc] Caused by: java.util.zip.ZipException: error in opening zip file [iajc] java.util.zip.ZipException: error in opening zip file [iajc] at java.util.zip.ZipFile.open(Native Method) [iajc] at java.util.zip.ZipFile.<init>(ZipFile.java:111) [iajc] at java.util.zip.ZipFile.<init>(ZipFile.java:127) [iajc] at org.aspectj.weaver.bcel.ClassPathManager$ZipFileEntry.ensureO pen(ClassPathManager.java:252) [iajc] at org.aspectj.weaver.bcel.ClassPathManager$ZipFileEntry.find(Cl assPathManager.java:225) [iajc] at org.aspectj.weaver.bcel.ClassPathManager.find(ClassPathManage r.java:92) [iajc] at org.aspectj.weaver.bcel.BcelWorld.resolveDelegate(BcelWorld.j ava:287) [iajc] at org.aspectj.weaver.World.resolveToReferenceType(World.java:33 5) [iajc] at org.aspectj.weaver.World.resolve(World.java:251) [iajc] at org.aspectj.weaver.patterns.WildTypePattern.lookupTypeInWorld (WildTypePattern.java:716) [iajc] at org.aspectj.weaver.patterns.WildTypePattern.resolveBindingsFr omFullyQualifiedTypeName(WildTypePattern.java:690) [iajc] at org.aspectj.weaver.patterns.WildTypePattern.resolveBindings(W ildTypePattern.java:623) [iajc] at org.aspectj.weaver.patterns.SignaturePattern.resolveBindings( SignaturePattern.java:82) [iajc] at org.aspectj.weaver.patterns.KindedPointcut.resolveBindings(Ki ndedPointcut.java:259) [iajc] at org.aspectj.weaver.patterns.AndPointcut.resolveBindings(AndPo intcut.java:74) [iajc] at org.aspectj.weaver.patterns.Pointcut.resolve(Pointcut.java:19 4) [iajc] at org.aspectj.ajdt.internal.compiler.ast.PointcutDesignator.fin ishResolveTypes(PointcutDesignator.java:84) [iajc] at org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration.reso lveStatements(AdviceDeclaration.java:118) [iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMet hodDeclaration.resolve(AbstractMethodDeclaration.java:400) [iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclara tion.resolve(TypeDeclaration.java:1088) [iajc] at org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration.reso lve(AspectDeclaration.java:116) [iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclara tion.resolve(TypeDeclaration.java:1137) [iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.ast.Compilation UnitDeclaration.resolve(CompilationUnitDeclaration.java:305) [iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.proces s(Compiler.java:514) [iajc] at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compil e(Compiler.java:329) [iajc] at org.aspectj.ajdt.internal.core.builder.AjBuildManager.perform Compilation(AjBuildManager.java:845) [iajc] at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild (AjBuildManager.java:241) [iajc] at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBu ild(AjBuildManager.java:161) [iajc] at org.aspectj.ajdt.ajc.AjdtCommand.doCommand(AjdtCommand.java:1 12) [iajc] at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(AjdtCommand.java: 60) [iajc] at org.aspectj.tools.ajc.Main.run(Main.java:356) [iajc] at org.aspectj.tools.ajc.Main.runMain(Main.java:246) [iajc] at org.aspectj.tools.ant.taskdefs.AjcTask.executeInSameVM(AjcTas k.java:1262) [iajc] at org.aspectj.tools.ant.taskdefs.AjcTask.execute(AjcTask.java:1 056) [iajc] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.ja va:275) [iajc] at org.apache.tools.ant.Task.perform(Task.java:364) [iajc] at org.apache.tools.ant.Target.execute(Target.java:341) [iajc] at org.apache.tools.ant.Target.performTasks(Target.java:369) [iajc] at org.apache.tools.ant.Project.executeTarget(Project.java:1214) [iajc] at org.apache.tools.ant.taskdefs.Ant.execute(Ant.java:386) [iajc] at org.apache.tools.ant.taskdefs.CallTarget.execute(CallTarget.j ava:106) [iajc] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.ja va:275) [iajc] at org.apache.tools.ant.Task.perform(Task.java:364) [iajc] at org.apache.tools.ant.Target.execute(Target.java:341) [iajc] at org.apache.tools.ant.Target.performTasks(Target.java:369) [iajc] at org.apache.tools.ant.Project.executeTarget(Project.java:1214) [iajc] at org.apache.tools.ant.Project.executeTargets(Project.java:1062 ) [iajc] at org.apache.tools.ant.Main.runBuild(Main.java:673) [iajc] at org.apache.tools.ant.Main.startAnt(Main.java:188) [iajc] at org.apache.tools.ant.launch.Launcher.run(Launcher.java:196) [iajc] at org.apache.tools.ant.launch.Launcher.main(Launcher.java:55) [iajc] abort ABORT -- (BCException) Can't open archive: wissing.jar [iajc] when resolving types defined in compilation unit File.aj [iajc] when processing compilation unit File.aj [iajc] when batch building BuildConfig[null] #Files=14
|
resolved fixed
|
d1a252e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-04-18T10:51:38Z | 2006-04-13T14:53:20Z |
weaver/src/org/aspectj/weaver/bcel/ClassPathManager.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
public class ClassPathManager {
private List entries;
// In order to control how many open files we have, we maintain a list.
// The max number is configured through the property:
// org.aspectj.weaver.openarchives
// and it defaults to 1000
private List openArchives = new ArrayList();
private static int maxOpenArchives = -1;
private static final int MAXOPEN_DEFAULT = 1000;
static {
String openzipsString = getSystemPropertyWithoutSecurityException("org.aspectj.weaver.openarchives",Integer.toString(MAXOPEN_DEFAULT));
maxOpenArchives=Integer.parseInt(openzipsString);
if (maxOpenArchives<20) maxOpenArchives=1000;
}
public ClassPathManager(List classpath, IMessageHandler handler) {
entries = new ArrayList();
for (Iterator i = classpath.iterator(); i.hasNext();) {
String name = (String) i.next();
addPath(name, handler);
}
}
protected ClassPathManager() {};
public void addPath (String name, IMessageHandler handler) {
File f = new File(name);
String lc = name.toLowerCase();
if (lc.endsWith(".jar") || lc.endsWith(".zip")) {
if (!f.isFile()) {
MessageUtil.info(handler, WeaverMessages.format(WeaverMessages.ZIPFILE_ENTRY_MISSING,name));
return;
}
try {
entries.add(new ZipFileEntry(f));
} catch (IOException ioe) {
MessageUtil.warn(handler, WeaverMessages.format(WeaverMessages.ZIPFILE_ENTRY_INVALID,name,ioe.getMessage()));
return;
}
} else {
if (!f.isDirectory()) {
MessageUtil.info(handler, WeaverMessages.format(WeaverMessages.DIRECTORY_ENTRY_MISSING,name));
return;
}
entries.add(new DirEntry(f));
}
}
public ClassFile find(UnresolvedType type) {
String name = type.getName();
for (Iterator i = entries.iterator(); i.hasNext(); ) {
Entry entry = (Entry)i.next();
ClassFile ret = entry.find(name);
if (ret != null) return ret;
}
return null;
}
public String toString() {
StringBuffer buf = new StringBuffer();
boolean start = true;
for (Iterator i = entries.iterator(); i.hasNext(); ) {
if (start) { start = false; }
else {buf.append(File.pathSeparator); }
buf.append(i.next());
}
return buf.toString();
}
/**
* This method is extremely expensive and should only be called rarely
*/
public List getAllClassFiles() {
List ret = new ArrayList();
for (Iterator i = entries.iterator(); i.hasNext(); ) {
Entry entry = (Entry)i.next();
ret.addAll(entry.getAllClassFiles());
}
return ret;
}
public abstract static class ClassFile {
public abstract InputStream getInputStream() throws IOException;
public abstract String getPath();
public abstract void close();
}
public abstract static class Entry {
public abstract ClassFile find(String name);
public abstract List getAllClassFiles();
}
private static class FileClassFile extends ClassFile {
private File file;
private FileInputStream fis;
public FileClassFile(File file) {
this.file = file;
}
public InputStream getInputStream() throws IOException {
fis = new FileInputStream(file);
return fis;
}
public void close() {
try {
if (fis!=null) fis.close();
} catch (IOException ioe) {
throw new BCException("Can't close class file : "+file.getName(),ioe);
} finally {
fis = null;
}
}
public String getPath() { return file.getPath(); }
}
public class DirEntry extends Entry {
private String dirPath;
public DirEntry(File dir) { this.dirPath = dir.getPath(); }
public DirEntry(String dirPath) { this.dirPath = dirPath; }
public ClassFile find(String name) {
File f = new File(dirPath + File.separator + name.replace('.', File.separatorChar) + ".class");
if (f.isFile()) return new FileClassFile(f);
else return null;
}
public List getAllClassFiles() {
throw new RuntimeException("unimplemented");
}
public String toString() { return dirPath; }
}
private static class ZipEntryClassFile extends ClassFile {
private ZipEntry entry;
private ZipFileEntry zipFile;
private InputStream is;
public ZipEntryClassFile(ZipFileEntry zipFile, ZipEntry entry) {
this.zipFile = zipFile;
this.entry = entry;
}
public InputStream getInputStream() throws IOException {
is = zipFile.getZipFile().getInputStream(entry);
return is;
}
public void close() {
try {
if (is!=null) is.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
is = null;
}
}
public String getPath() { return entry.getName(); }
}
public class ZipFileEntry extends Entry {
private File file;
private ZipFile zipFile;
public ZipFileEntry(File file) throws IOException {
this.file = file;
}
public ZipFileEntry(ZipFile zipFile) {
this.zipFile = zipFile;
}
public ZipFile getZipFile() {
return zipFile;
}
public ClassFile find(String name) {
ensureOpen();
String key = name.replace('.', '/') + ".class";
ZipEntry entry = zipFile.getEntry(key);
if (entry != null) return new ZipEntryClassFile(this, entry);
else return null; // This zip will be closed when necessary...
}
public List getAllClassFiles() {
ensureOpen();
List ret = new ArrayList();
for (Enumeration e = zipFile.entries(); e.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry)e.nextElement();
String name = entry.getName();
if (hasClassExtension(name)) ret.add(new ZipEntryClassFile(this, entry));
}
// if (ret.isEmpty()) close();
return ret;
}
private void ensureOpen() {
if (zipFile != null && openArchives.contains(zipFile)) {
if (isReallyOpen()) return;
}
try {
if (openArchives.size()>=maxOpenArchives) {
closeSomeArchives(openArchives.size()/10); // Close 10% of those open
}
zipFile = new ZipFile(file);
if (!isReallyOpen()) {
throw new BCException("Can't open archive: "+file.getName()+" (size() check failed)");
}
openArchives.add(zipFile);
} catch (IOException ioe) {
throw new BCException("Can't open archive: "+file.getName(),ioe);
}
}
private boolean isReallyOpen() {
try {
zipFile.size(); // this will fail if the file has been closed for
// some reason;
return true;
} catch (IllegalStateException ex) {
// this means the zip file is closed...
return false;
}
}
public void closeSomeArchives(int n) {
for (int i=n-1;i>=0;i--) {
ZipFile zf = (ZipFile)openArchives.get(i);
try {
zf.close();
} catch (IOException e) {
e.printStackTrace();
}
openArchives.remove(i);
}
}
public void close() {
if (zipFile == null) return;
try {
openArchives.remove(zipFile);
zipFile.close();
} catch (IOException ioe) {
throw new BCException("Can't close archive: "+file.getName(),ioe);
} finally {
zipFile = null;
}
}
public String toString() { return file.getName(); }
}
/* private */ static boolean hasClassExtension(String name) {
return name.toLowerCase().endsWith((".class"));
}
public void closeArchives() {
for (Iterator i = entries.iterator(); i.hasNext(); ) {
Entry entry = (Entry)i.next();
if (entry instanceof ZipFileEntry) {
((ZipFileEntry)entry).close();
}
openArchives.clear();
}
}
// Copes with the security manager
private static String getSystemPropertyWithoutSecurityException (String aPropertyName, String aDefaultValue) {
try {
return System.getProperty(aPropertyName, aDefaultValue);
} catch (SecurityException ex) {
return aDefaultValue;
}
}
}
|
136,585 |
Bug 136585 NullPointerException in PerObjectInterfaceTypeMunger.java:33
|
AspectJ 1.5.1a + AJDT 1.4.0-dev on Eclipse 3.2M6 Using the Sapcewar example, open Game.java and add: public void foo() {} save and an incremental build will fail with: java.lang.NullPointerException at org.aspectj.weaver.PerObjectInterfaceTypeMunger.equals(PerObjectInterfaceTypeMunger.java:33) at org.aspectj.weaver.bcel.BcelTypeMunger.equals(BcelTypeMunger.java:1672) at java.util.AbstractList.equals(AbstractList.java:610) at org.aspectj.weaver.CrosscuttingMembers.replaceWith(CrosscuttingMembers.java:321) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect(CrosscuttingMembersSet.java:73) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.addCrosscuttingStructures(AjLookupEnvironment.java:397) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.collectAllITDsAndDeclares(AjLookupEnvironment.java:333) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:173) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:301) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:315) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:269) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:168) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
|
resolved fixed
|
1535ee7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-04-19T13:36:39Z | 2006-04-13T09:20:00Z |
tests/multiIncremental/PR136585/base/Hello.java
| |
136,585 |
Bug 136585 NullPointerException in PerObjectInterfaceTypeMunger.java:33
|
AspectJ 1.5.1a + AJDT 1.4.0-dev on Eclipse 3.2M6 Using the Sapcewar example, open Game.java and add: public void foo() {} save and an incremental build will fail with: java.lang.NullPointerException at org.aspectj.weaver.PerObjectInterfaceTypeMunger.equals(PerObjectInterfaceTypeMunger.java:33) at org.aspectj.weaver.bcel.BcelTypeMunger.equals(BcelTypeMunger.java:1672) at java.util.AbstractList.equals(AbstractList.java:610) at org.aspectj.weaver.CrosscuttingMembers.replaceWith(CrosscuttingMembers.java:321) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect(CrosscuttingMembersSet.java:73) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.addCrosscuttingStructures(AjLookupEnvironment.java:397) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.collectAllITDsAndDeclares(AjLookupEnvironment.java:333) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:173) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:301) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:315) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:269) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:168) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
|
resolved fixed
|
1535ee7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-04-19T13:36:39Z | 2006-04-13T09:20:00Z |
tests/src/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement initial implementation
* ******************************************************************/
package org.aspectj.systemtest.incremental.tools;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.aspectj.ajdt.internal.core.builder.AjState;
import org.aspectj.ajdt.internal.core.builder.IncrementalStateManager;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IProgramElement;
import org.aspectj.bridge.IMessage;
import org.aspectj.testing.util.FileUtil;
/**
* The superclass knows all about talking through Ajde to the compiler.
* The superclass isn't in charge of knowing how to simulate overlays
* for incremental builds, that is in here. As is the ability to
* generate valid build configs based on a directory structure. To
* support this we just need access to a sandbox directory - this
* sandbox is managed by the superclass (it only assumes all builds occur
* in <sandboxDir>/<projectName>/ )
*
* The idea is you can initialize multiple projects in the sandbox and
* they can all be built independently, hopefully exploiting
* incremental compilation. Between builds you can alter the contents
* of a project using the alter() method that overlays some set of
* new files onto the current set (adding new files/changing existing
* ones) - you can then drive a new build and check it behaves as
* expected.
*/
public class MultiProjectIncrementalTests extends AjdeInteractionTestbed {
public static boolean VERBOSE = false;
protected void setUp() throws Exception {
super.setUp();
AjdeInteractionTestbed.VERBOSE = VERBOSE;
AjState.FORCE_INCREMENTAL_DURING_TESTING = true;
}
protected void tearDown() throws Exception {
super.tearDown();
AjState.FORCE_INCREMENTAL_DURING_TESTING = false;
}
// Compile a single simple project
public void testTheBasics() {
initialiseProject("P1");
build("P1"); // This first build will be batch
build("P1");
checkWasntFullBuild();
checkCompileWeaveCount(0,0);
}
// source code doesnt matter, we are checking invalid path handling
public void testInvalidAspectpath_pr121395() {
initialiseProject("P1");
File f = new File("foo.jar");
Set s = new HashSet();
s.add(f);
configureAspectPath(s);
build("P1"); // This first build will be batch
checkForError("invalid aspectpath entry");
}
// Make simple changes to a project, adding a class
public void testSimpleChanges() {
initialiseProject("P1");
build("P1"); // This first build will be batch
alter("P1","inc1"); // adds a single class
build("P1");
checkCompileWeaveCount(1,-1);
build("P1");
checkCompileWeaveCount(0,-1);
}
// Make simple changes to a project, adding a class and an aspect
public void testAddingAnAspect() {
initialiseProject("P1");
build("P1"); // build 1, weave 1
alter("P1","inc1"); // adds a class
alter("P1","inc2"); // adds an aspect
build("P1"); // build 1,
long timeTakenForFullBuildAndWeave = getTimeTakenForBuild();
checkWasFullBuild(); // it *will* be a full build under the new
// "back-to-the-source strategy
checkCompileWeaveCount(5,3); // we compile X and A (the delta) find out that
// an aspect has changed, go back to the source
// and compile X,A,C, then weave them all.
build("P1");
long timeTakenForSimpleIncBuild = getTimeTakenForBuild();
// I don't think this test will have timing issues as the times should be *RADICALLY* different
// On my config, first build time is 2093ms and the second is 30ms
assertTrue("Should not take longer for the trivial incremental build! first="+timeTakenForFullBuildAndWeave+
"ms second="+timeTakenForSimpleIncBuild+"ms",
timeTakenForSimpleIncBuild<timeTakenForFullBuildAndWeave);
}
public void testBuildingTwoProjectsInTurns() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
build("P2");
build("P1");
checkWasntFullBuild();
build("P2");
checkWasntFullBuild();
}
/**
* In order for this next test to run, I had to move the weaver/world pair we keep in the
* AjBuildManager instance down into the state object - this makes perfect sense - otherwise
* when reusing the state for another project we'd not be switching to the right weaver/world
* for that project.
*/
public void testBuildingTwoProjectsMakingSmallChanges() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
build("P2");
build("P1");
checkWasntFullBuild();
build("P2");
checkWasntFullBuild();
alter("P1","inc1"); // adds a class
alter("P1","inc2"); // adds an aspect
build("P1");
checkWasFullBuild(); // adding an aspect makes us go back to the source
}
/**
* Setup up two simple projects and build them in turn - check the
* structure model is right after each build
*/
public void testBuildingTwoProjectsAndVerifyingModel() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
}
// Setup up two simple projects and build them in turn - check the
// structure model is right after each build
public void testBuildingTwoProjectsAndVerifyingStuff() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
}
/**
* Complex. Here we are testing that a state object records structural changes since
* the last full build correctly. We build a simple project from scratch - this will
* be a full build and so the structural changes since last build count should be 0.
* We then alter a class, adding a new method and check structural changes is 1.
*/
public void testStateManagement1() {
File binDirectoryForP1 = new File(getFile("P1","bin"));
initialiseProject("P1");
build("P1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1);
assertTrue("There should be a state object for project P1",ajs!=null);
assertTrue("Should be no structural changes as it was a full build but found: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("P1","inc3"); // adds a method to the class C.java
build("P1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin")));
assertTrue("There should be state for project P1",ajs!=null);
checkWasntFullBuild();
assertTrue("Should be one structural changes as it was a full build but found: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==1);
}
/**
* Complex. Here we are testing that a state object records structural changes since
* the last full build correctly. We build a simple project from scratch - this will
* be a full build and so the structural changes since last build count should be 0.
* We then alter a class, changing body of a method, not the structure and
* check struc changes is still 0.
*/
public void testStateManagement2() {
File binDirectoryForP1 = new File(getFile("P1","bin"));
initialiseProject("P1");
alter("P1","inc3"); // need this change in here so 'inc4' can be applied without making
// it a structural change
build("P1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1);
assertTrue("There should be state for project P1",ajs!=null);
assertTrue("Should be no struc changes as its a full build: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("P1","inc4"); // changes body of main() method but does *not* change the structure of C.java
build("P1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin")));
assertTrue("There should be state for project P1",ajs!=null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
}
/**
* The C.java file modified in this test has an inner class - this means the inner class
* has a this$0 field and <init>(C) ctor to watch out for when checking for structural changes
*
*/
public void testStateManagement3() {
File binDirForInterproject1 = new File(getFile("interprojectdeps1","bin"));
initialiseProject("interprojectdeps1");
build("interprojectdeps1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject1);
assertTrue("There should be state for project P1",ajs!=null);
assertTrue("Should be no struc changes as its a full build: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("interprojectdeps1","inc1"); // adds a space to C.java
build("interprojectdeps1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps1","bin")));
assertTrue("There should be state for project interprojectdeps1",ajs!=null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
}
/**
* The C.java file modified in this test has an inner class - which has two ctors - this checks
* how they are mangled with an instance of C.
*
*/
public void testStateManagement4() {
File binDirForInterproject2 = new File(getFile("interprojectdeps2","bin"));
initialiseProject("interprojectdeps2");
build("interprojectdeps2"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject2);
assertTrue("There should be state for project interprojectdeps2",ajs!=null);
assertTrue("Should be no struc changes as its a full build: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("interprojectdeps2","inc1"); // minor change to C.java
build("interprojectdeps2");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps2","bin")));
assertTrue("There should be state for project interprojectdeps1",ajs!=null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
}
/**
* The C.java file modified in this test has an inner class - it has two ctors but
* also a reference to C.this in it - which will give rise to an accessor being
* created in C
*
*/
public void testStateManagement5() {
File binDirForInterproject3 = new File(getFile("interprojectdeps3","bin"));
initialiseProject("interprojectdeps3");
build("interprojectdeps3"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject3);
assertTrue("There should be state for project interprojectdeps3",ajs!=null);
assertTrue("Should be no struc changes as its a full build: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("interprojectdeps3","inc1"); // minor change to C.java
build("interprojectdeps3");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps3","bin")));
assertTrue("There should be state for project interprojectdeps1",ajs!=null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
}
/**
* Now the most complex test. Create a dependancy between two projects. Building
* one may affect whether the other does an incremental or full build. The
* structural information recorded in the state object should be getting used
* to control whether a full build is necessary...
*/
public void testBuildingDependantProjects() {
initialiseProject("P1");
initialiseProject("P2");
configureNewProjectDependency("P2","P1");
build("P1");
build("P2"); // now everything is consistent and compiled
alter("P1","inc1"); // adds a second class
build("P1");
build("P2"); // although a second class was added - P2 can't be using it, so we don't full build here :)
checkWasntFullBuild();
alter("P1","inc3"); // structurally changes one of the classes
build("P1");
build("P2"); // build notices the structural change
checkWasFullBuild();
alter("P1","inc4");
build("P1");
build("P2"); // build sees a change but works out its not structural
checkWasntFullBuild();
}
public void testPr85132() {
initialiseProject("PR85132");
build("PR85132");
alter("PR85132","inc1");
build("PR85132");
}
// parameterization of generic aspects
public void testPr125405() {
initialiseProject("PR125405");
build("PR125405");
checkCompileWeaveCount(1,1);
alter("PR125405","inc1");
build("PR125405");
// "only abstract aspects can have type parameters"
checkForError("only abstract aspects can have type parameters");
alter("PR125405","inc2");
build("PR125405");
checkCompileWeaveCount(1,1);
assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0);
}
public void testPr128618() {
initialiseProject("PR128618_1");
initialiseProject("PR128618_2");
configureNewProjectDependency("PR128618_2","PR128618_1");
assertTrue("there should be no warning messages before we start",
MyTaskListManager.getWarningMessages().isEmpty());
build("PR128618_1");
build("PR128618_2");
List warnings = MyTaskListManager.getWarningMessages();
assertTrue("Should be one warning, but there are #"+warnings.size(),warnings.size()==1);
IMessage msg = (IMessage)(MyTaskListManager.getWarningMessages().get(0));
assertEquals("warning should be against the FFDC.aj resource","FFDC.aj",msg.getSourceLocation().getSourceFile().getName());
alter("PR128618_2","inc1");
build("PR128618_2");
checkWasntFullBuild();
IMessage msg2 = (IMessage)(MyTaskListManager.getWarningMessages().get(0));
assertEquals("warning should be against the FFDC.aj resource","FFDC.aj",msg2.getSourceLocation().getSourceFile().getName());
assertFalse("a new warning message should have been generated", msg.equals(msg2));
}
public void testPr92837() {
initialiseProject("PR92837");
build("PR92837");
alter("PR92837","inc1");
build("PR92837");
}
public void testPr119570() {
initialiseProject("PR119570");
build("PR119570");
assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0);
}
public void testPr119570_2() {
initialiseProject("PR119570_2");
build("PR119570_2");
List l = MyTaskListManager.getWarningMessages();
assertTrue("Should be no warnings, but got "+l,l.size()==0);
}
// If you fiddle with the compiler options - you must manually reset the options at the end of the test
public void testPr117209() {
try {
initialiseProject("pr117209");
configureNonStandardCompileOptions("-proceedOnError");
build("pr117209");
checkCompileWeaveCount(6,6);
} finally {
MyBuildOptionsAdapter.reset();
}
}
public void testPr114875() {
initialiseProject("pr114875");
build("pr114875");
alter("pr114875","inc1");
build("pr114875");
checkWasFullBuild();
alter("pr114875","inc2");
build("pr114875");
checkWasFullBuild(); // back to the source for an aspect change
}
public void testPr117882() {
// AjdeInteractionTestbed.VERBOSE=true;
// AjdeInteractionTestbed.configureBuildStructureModel(true);
initialiseProject("PR117882");
build("PR117882");
checkWasFullBuild();
alter("PR117882","inc1");
build("PR117882");
checkWasFullBuild(); // back to the source for an aspect
// AjdeInteractionTestbed.VERBOSE=false;
// AjdeInteractionTestbed.configureBuildStructureModel(false);
}
public void testPr117882_2() {
// AjdeInteractionTestbed.VERBOSE=true;
// AjdeInteractionTestbed.configureBuildStructureModel(true);
initialiseProject("PR117882_2");
build("PR117882_2");
checkWasFullBuild();
alter("PR117882_2","inc1");
build("PR117882_2");
checkWasFullBuild(); // back to the source...
//checkCompileWeaveCount(1,4);
//fullBuild("PR117882_2");
//checkWasFullBuild();
// AjdeInteractionTestbed.VERBOSE=false;
// AjdeInteractionTestbed.configureBuildStructureModel(false);
}
public void testPr115251() {
//AjdeInteractionTestbed.VERBOSE=true;
initialiseProject("PR115251");
build("PR115251");
checkWasFullBuild();
alter("PR115251","inc1");
build("PR115251");
checkWasFullBuild(); // back to the source
}
// public void testPr124399() {
// AjdeInteractionTestbed.VERBOSE=true;
// configureBuildStructureModel(true);
// initialiseProject("PR124399");
// build("PR124399");
// checkWasFullBuild();
// alter("PR124399","inc1");
// build("PR124399");
// checkWasntFullBuild();
// }
public void testPr121384() {
// AjdeInteractionTestbed.VERBOSE=true;
// AsmManager.setReporting("c:/foo.txt",true,true,true,false);
MyBuildOptionsAdapter.setNonStandardOptions("-showWeaveInfo");
configureBuildStructureModel(true);
initialiseProject("pr121384");
build("pr121384");
checkWasFullBuild();
alter("pr121384","inc1");
build("pr121384");
checkWasntFullBuild();
}
/* public void testPr111779() {
super.VERBOSE=true;
initialiseProject("PR111779");
build("PR111779");
alter("PR111779","inc1");
build("PR111779");
}
*/
public void testPr93310_1() {
initialiseProject("PR93310_1");
build("PR93310_1");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_1" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java";
(new File(fileC2)).delete();
alter("PR93310_1","inc1");
build("PR93310_1");
checkWasFullBuild();
int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size();
assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1);
String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0);
assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java"));
}
public void testPr93310_2() {
initialiseProject("PR93310_2");
build("PR93310_2");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_2" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java";
(new File(fileC2)).delete();
alter("PR93310_2","inc1");
build("PR93310_2");
checkWasFullBuild();
int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size();
assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1);
String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0);
assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java"));
}
// Stage1: Compile two files, pack.A and pack.A1 - A1 sets a protected field in A.
// Stage2: make the field private in class A > gives compile error
// Stage3: Add a new aspect whilst there is a compile error !
public void testPr113531() {
initialiseProject("PR113531");
build("PR113531");
assertFalse("build should have compiled ok",
MyTaskListManager.hasErrorMessages());
alter("PR113531","inc1");
build("PR113531");
assertEquals("error message should be 'foo cannot be resolved' ",
"foo cannot be resolved",
((IMessage)MyTaskListManager.getErrorMessages().get(0))
.getMessage());
alter("PR113531","inc2");
build("PR113531");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
assertEquals("error message should be 'foo cannot be resolved' ",
"foo cannot be resolved",
((IMessage)MyTaskListManager.getErrorMessages().get(0))
.getMessage());
}
// Stage 1: Compile the 4 files, pack.A2 extends pack.A1 (aspects) where
// A2 uses a protected field in A1 and pack.C2 extends pack.C1 (classes)
// where C2 uses a protected field in C1
// Stage 2: make the field private in class C1 ==> compile errors in C2
// Stage 3: make the field private in aspect A1 whilst there's the compile
// error.
// There shouldn't be a BCExcpetion saying can't find delegate for pack.C2
public void testPr119882() {
initialiseProject("PR119882");
build("PR119882");
assertFalse("build should have compiled ok",MyTaskListManager.hasErrorMessages());
alter("PR119882","inc1");
build("PR119882");
//fullBuild("PR119882");
List errors = MyTaskListManager.getErrorMessages();
assertTrue("Should be at least one error, but got none",errors.size()==1);
assertEquals("error message should be 'i cannot be resolved' ",
"i cannot be resolved",
((IMessage)errors.get(0))
.getMessage());
alter("PR119882","inc2");
build("PR119882");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
assertEquals("error message should be 'i cannot be resolved' ",
"i cannot be resolved",
((IMessage)errors.get(0))
.getMessage());
}
public void testPr112736() {
// AjdeInteractionTestbed.VERBOSE = true;
initialiseProject("PR112736");
build("PR112736");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR112736" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "A.java";
(new File(fileC2)).delete();
alter("PR112736","inc1");
build("PR112736");
checkWasFullBuild();
}
/**
* We have problems with multiple rewrites of a pointcut across incremental builds.
*/
public void testPr113257() {
initialiseProject("PR113257");
build("PR113257");
alter("PR113257","inc1");
build("PR113257");
checkWasFullBuild(); // back to the source
alter("PR113257","inc1");
build("PR113257");
}
public void testPr123612() {
initialiseProject("PR123612");
build("PR123612");
alter("PR123612","inc1");
build("PR123612");
checkWasFullBuild(); // back to the source
}
public void testPr128655() {
configureNonStandardCompileOptions("-showWeaveInfo");
initialiseProject("pr128655");
build("pr128655");
List firstBuildMessages = MyTaskListManager.getWeavingMessages();
assertTrue("Should be at least one message about the dec @type, but there were none",firstBuildMessages.size()>0);
alter("pr128655","inc1");
build("pr128655");
checkWasntFullBuild(); // back to the source
List secondBuildMessages = MyTaskListManager.getWeavingMessages();
// check they are the same
for (int i = 0; i < firstBuildMessages.size(); i++) {
IMessage m1 = (IMessage)firstBuildMessages.get(i);
IMessage m2 = (IMessage)secondBuildMessages.get(i);
if (!m1.toString().equals(m2.toString())) {
System.err.println("Message during first build was: "+m1);
System.err.println("Message during second build was: "+m1);
fail("The two messages should be the same, but are not: \n"+m1+"!="+m2);
}
}
}
// Similar to above, but now the annotation is in the default package
public void testPr128655_2() {
configureNonStandardCompileOptions("-showWeaveInfo");
initialiseProject("pr128655_2");
build("pr128655_2");
List firstBuildMessages = MyTaskListManager.getWeavingMessages();
assertTrue("Should be at least one message about the dec @type, but there were none",firstBuildMessages.size()>0);
alter("pr128655_2","inc1");
build("pr128655_2");
checkWasntFullBuild(); // back to the source
List secondBuildMessages = MyTaskListManager.getWeavingMessages();
// check they are the same
for (int i = 0; i < firstBuildMessages.size(); i++) {
IMessage m1 = (IMessage)firstBuildMessages.get(i);
IMessage m2 = (IMessage)secondBuildMessages.get(i);
if (!m1.toString().equals(m2.toString())) {
System.err.println("Message during first build was: "+m1);
System.err.println("Message during second build was: "+m1);
fail("The two messages should be the same, but are not: \n"+m1+"!="+m2);
}
}
}
// test for comment #31 - NPE
public void testPr129163() {
configureBuildStructureModel(true);
initialiseProject("PR129613");
build("PR129613");
alter("PR129613","inc1");
build("PR129613");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
assertEquals("warning message should be 'no match for this type name: File [Xlint:invalidAbsoluteTypeName]' ",
"no match for this type name: File [Xlint:invalidAbsoluteTypeName]",
((IMessage)MyTaskListManager.getWarningMessages().get(0))
.getMessage());
configureBuildStructureModel(false);
}
// test for comment #0 - adding a comment to a class file shouldn't
// cause us to go back to source and recompile everything. To force this
// to behave like AJDT we need to include the aspect in 'inc1' so that
// when AjState looks at its timestamp it thinks the aspect has been modified.
// The logic within CrosscuttingMembers should then work out correctly
// that there haven't really been any changes within the aspect and so
// we shouldn't go back to source.
public void testPr129163_2() {
// want to behave like AJDT
configureBuildStructureModel(true);
initialiseProject("pr129163_2");
build("pr129163_2");
checkWasFullBuild();
alter("pr129163_2","inc1");
build("pr129163_2");
checkWasntFullBuild(); // shouldn't be a full build because the
// aspect hasn't changed
configureBuildStructureModel(false);
}
// test for comment #6 - simulates AJDT core builder test testBug99133a -
// changing the contents of a method within a class shouldn't force a
// full build of a dependant project. To force this to behave like AJDT
// 'inc1' of the dependant project should just be a copy of 'base' so that
// AjState thinks somethings changed within the dependant project and
// we do a build. Similarly, 'inc1' of the project depended on should
// include the aspect even though nothing's changed within it. This causes
// AjState to think that the aspect has changed. Together its then up to
// logic within CrosscuttingMembers and various equals methods to decide
// correctly that we don't have to go back to source.
public void testPr129163_3() {
configureBuildStructureModel(true);
initialiseProject("PR129163_4");
build("PR129163_4");
checkWasFullBuild(); // should be a full build because initializing project
initialiseProject("PR129163_3");
configureNewProjectDependency("PR129163_3","PR129163_4");
build("PR129163_3");
checkWasFullBuild(); // should be a full build because initializing project
alter("PR129163_4","inc1");
build("PR129163_4");
checkWasntFullBuild(); // should be an incremental build because although
// "inc1" includes the aspect A1.aj, it actually hasn't
// changed so we shouldn't go back to source
alter("PR129163_3","inc1");
build("PR129163_3");
checkWasntFullBuild(); // should be an incremental build because nothing has
// changed within the class and no aspects have changed
// within the running of the test
configureBuildStructureModel(false);
}
public void testPr131505() {
configureNonStandardCompileOptions("-outxml");
initialiseProject("PR131505");
build("PR131505");
checkWasFullBuild();
// aop.xml file shouldn't contain any aspects
checkXMLAspectCount("PR131505","",0);
// add a new aspect A which should be included in the aop.xml file
alter("PR131505","inc1");
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",1);
checkXMLAspectCount("PR131505","A",1);
// make changes to the class file which shouldn't affect the contents
// of the aop.xml file
alter("PR131505","inc2");
build("PR131505");
checkWasntFullBuild();
checkXMLAspectCount("PR131505","",1);
checkXMLAspectCount("PR131505","A",1);
// add another new aspect A1 which should also be included in the aop.xml file
// ...there should be no duplicate entries in the file
alter("PR131505","inc3");
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",2);
checkXMLAspectCount("PR131505","A1",1);
checkXMLAspectCount("PR131505","A",1);
// delete aspect A1 which meanss that aop.xml file should only contain A
File a1 = new File(getWorkingDir().getAbsolutePath()
+ File.separatorChar + "PR131505" + File.separatorChar + "A1.aj");
a1.delete();
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",1);
checkXMLAspectCount("PR131505","A1",0);
checkXMLAspectCount("PR131505","A",1);
// add another aspect called A which is in a different package, both A
// and pkg.A should be included in the aop.xml file
alter("PR131505","inc4");
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",2);
checkXMLAspectCount("PR131505","A",1);
checkXMLAspectCount("PR131505","pkg.A",1);
}
public void testPr133532() {
initialiseProject("PR133532");
build("PR133532");
alter("PR133532","inc1");
build("PR133532");
alter("PR133532","inc2");
build("PR133532");
assertTrue("There should be no errors reported:\n"+MyTaskListManager.getErrorMessages(),
MyTaskListManager.getErrorMessages().isEmpty());
}
public void testPr133532_2() {
initialiseProject("pr133532_2");
build("pr133532_2");
alter("pr133532_2","inc2");
build("pr133532_2");
assertTrue("There should be no errors reported:\n"+MyTaskListManager.getErrorMessages(),
MyTaskListManager.getErrorMessages().isEmpty());
String decisions = AjdeInteractionTestbed.MyStateListener.getDecisions();
String expect="Need to recompile 'A.aj'";
assertTrue("Couldn't find build decision: '"+expect+"' in the list of decisions made:\n"+decisions,
decisions.indexOf(expect)!=-1);
}
public void testPr134541() {
initialiseProject("PR134541");
build("PR134541");
assertEquals("[Xlint:adviceDidNotMatch] should be associated with line 5",5,
((IMessage)MyTaskListManager.getWarningMessages().get(0)).getSourceLocation().getLine());
alter("PR134541","inc1");
build("PR134541");
checkWasntFullBuild(); // we've only added a white space therefore we
// shouldn't be doing a full build
assertEquals("[Xlint:adviceDidNotMatch] should now be associated with line 7",7,
((IMessage)MyTaskListManager.getWarningMessages().get(0)).getSourceLocation().getLine());
}
// other possible tests:
// - memory usage (freemem calls?)
// - relationship map
// ---------------------------------------------------------------------------------------------------
/**
* Check we compiled/wove the right number of files, passing '-1' indicates you don't care about
* that number.
*/
private void checkCompileWeaveCount(int expCompile,int expWoven) {
if (expCompile!=-1 && getCompiledFiles().size()!=expCompile)
fail("Expected compilation of "+expCompile+" files but compiled "+getCompiledFiles().size()+
"\n"+printCompiledAndWovenFiles());
if (expWoven!=-1 && getWovenClasses().size()!=expWoven)
fail("Expected weaving of "+expWoven+" files but wove "+getWovenClasses().size()+
"\n"+printCompiledAndWovenFiles());
}
private void checkWasntFullBuild() {
assertTrue("Shouldn't have been a full (batch) build",!wasFullBuild());
}
private void checkWasFullBuild() {
assertTrue("Should have been a full (batch) build",wasFullBuild());
}
private void checkForNode(String packageName,String typeName,boolean shouldBeFound) {
IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForType(packageName,typeName);
if (shouldBeFound) {
if (ipe==null) printModel();
assertTrue("Should have been able to find '"+packageName+"."+typeName+"' in the asm",ipe!=null);
} else {
if (ipe!=null) printModel();
assertTrue("Should have NOT been able to find '"+packageName+"."+typeName+"' in the asm",ipe==null);
}
}
private void printModel() {
try {
AsmManager.dumptree(AsmManager.getDefault().getHierarchy().getRoot(),0);
} catch (IOException e) {
e.printStackTrace();
}
}
public void build(String projectName) {
constructUpToDateLstFile(projectName,"build.lst");
build(projectName,"build.lst");
if (AjdeInteractionTestbed.VERBOSE) printBuildReport();
}
public void fullBuild(String projectName) {
constructUpToDateLstFile(projectName,"build.lst");
fullBuild(projectName,"build.lst");
if (AjdeInteractionTestbed.VERBOSE) printBuildReport();
}
private void constructUpToDateLstFile(String pname,String configname) {
File projectBase = new File(sandboxDir,pname);
File toConstruct = new File(projectBase,configname);
List filesForCompilation = new ArrayList();
collectUpFiles(projectBase,projectBase,filesForCompilation);
try {
FileOutputStream fos = new FileOutputStream(toConstruct);
DataOutputStream dos = new DataOutputStream(fos);
for (Iterator iter = filesForCompilation.iterator(); iter.hasNext();) {
String file = (String) iter.next();
dos.writeBytes(file+"\n");
}
dos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void checkForError(String anError) {
List messages = MyTaskListManager.getErrorMessages();
for (Iterator iter = messages.iterator(); iter.hasNext();) {
IMessage element = (IMessage) iter.next();
if (element.getMessage().indexOf(anError)!=-1) return;
}
fail("Didn't find the error message:\n'"+anError+"'.\nErrors that occurred:\n"+MyTaskListManager.getErrorMessages());
}
private void collectUpFiles(File location,File base,List collectionPoint) {
String contents[] = location.list();
if (contents==null) return;
for (int i = 0; i < contents.length; i++) {
String string = contents[i];
File f = new File(location,string);
if (f.isDirectory()) {
collectUpFiles(f,base,collectionPoint);
} else if (f.isFile() && (f.getName().endsWith(".aj") || f.getName().endsWith(".java"))) {
String fileFound;
try {
fileFound = f.getCanonicalPath();
String toRemove = base.getCanonicalPath();
if (!fileFound.startsWith(toRemove)) throw new RuntimeException("eh? "+fileFound+" "+toRemove);
collectionPoint.add(fileFound.substring(toRemove.length()+1));//+1 captures extra separator
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Fill in the working directory with the project base files,
* from the 'base' folder.
*/
protected void initialiseProject(String p) {
File projectSrc=new File(testdataSrcDir+File.separatorChar+p+File.separatorChar+"base");
File destination=new File(getWorkingDir(),p);
if (!destination.exists()) {destination.mkdir();}
copy(projectSrc,destination);//,false);
}
/*
* Applies an overlay onto the project being tested - copying
* the contents of the specified overlay directory.
*/
private void alter(String projectName,String overlayDirectory) {
File projectSrc =new File(testdataSrcDir+File.separatorChar+projectName+
File.separatorChar+overlayDirectory);
File destination=new File(getWorkingDir(),projectName);
copy(projectSrc,destination);
}
/**
* Copy the contents of some directory to another location - the
* copy is recursive.
*/
private void copy(File from, File to) {
String contents[] = from.list();
if (contents==null) return;
for (int i = 0; i < contents.length; i++) {
String string = contents[i];
File f = new File(from,string);
File t = new File(to,string);
if (f.isDirectory() && !f.getName().startsWith("inc")) {
t.mkdir();
copy(f,t);
} else if (f.isFile()) {
StringBuffer sb = new StringBuffer();
//if (VERBOSE) System.err.println("Copying "+f+" to "+t);
FileUtil.copyFile(f,t,sb);
if (sb.length()!=0) { System.err.println(sb.toString());}
}
}
}
private static void log(String msg) {
if (VERBOSE) System.out.println(msg);
}
/**
* Count the number of times a specified aspectName appears in the default
* aop.xml file and compare with the expected number of occurrences. If just
* want to count the number of aspects mentioned within the file then
* pass "" for the aspectName, otherwise, specify the name of the
* aspect interested in.
*/
private void checkXMLAspectCount(String projectName, String aspectName, int expectedOccurrences) {
int aspectCount = 0;
File aopXML = new File(getWorkingDir().getAbsolutePath()
+ File.separatorChar + projectName + File.separatorChar
+ "bin" + File.separatorChar + "META-INF" + File.separatorChar + "aop.xml");
if (!aopXML.exists()) {
fail("Expected file " + aopXML.getAbsolutePath() + " to exist but it doesn't");
}
try {
BufferedReader reader = new BufferedReader(new FileReader(aopXML));
String line = reader.readLine();
while (line != null) {
if (aspectName.equals("") && line.indexOf("aspect name=\"") != -1) {
aspectCount++;
} else if (line.indexOf("aspect name=\""+aspectName+"\"") != -1) {
aspectCount++;
}
line = reader.readLine();
}
reader.close();
} catch (IOException ie) {
ie.printStackTrace();
}
if (aspectCount != expectedOccurrences) {
fail("Expected aspect " + aspectName + " to appear " + expectedOccurrences + " times" +
" in the aop.xml file but found " + aspectCount + " occurrences");
}
}
}
|
136,585 |
Bug 136585 NullPointerException in PerObjectInterfaceTypeMunger.java:33
|
AspectJ 1.5.1a + AJDT 1.4.0-dev on Eclipse 3.2M6 Using the Sapcewar example, open Game.java and add: public void foo() {} save and an incremental build will fail with: java.lang.NullPointerException at org.aspectj.weaver.PerObjectInterfaceTypeMunger.equals(PerObjectInterfaceTypeMunger.java:33) at org.aspectj.weaver.bcel.BcelTypeMunger.equals(BcelTypeMunger.java:1672) at java.util.AbstractList.equals(AbstractList.java:610) at org.aspectj.weaver.CrosscuttingMembers.replaceWith(CrosscuttingMembers.java:321) at org.aspectj.weaver.CrosscuttingMembersSet.addOrReplaceAspect(CrosscuttingMembersSet.java:73) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.addCrosscuttingStructures(AjLookupEnvironment.java:397) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.collectAllITDsAndDeclares(AjLookupEnvironment.java:333) at org.aspectj.ajdt.internal.compiler.lookup.AjLookupEnvironment.completeTypeBindings(AjLookupEnvironment.java:173) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:301) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:315) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:269) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:168) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) NullPointerException thrown: null
|
resolved fixed
|
1535ee7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-04-19T13:36:39Z | 2006-04-13T09:20:00Z |
weaver/src/org/aspectj/weaver/PerObjectInterfaceTypeMunger.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
* Alexandre Vasseur rearchitected for #75442 finer grained matching
* ******************************************************************/
package org.aspectj.weaver;
import org.aspectj.weaver.patterns.PerFromSuper;
import org.aspectj.weaver.patterns.PerObject;
import org.aspectj.weaver.patterns.PerThisOrTargetPointcutVisitor;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.TypePattern;
import java.io.DataOutputStream;
import java.io.IOException;
public class PerObjectInterfaceTypeMunger extends ResolvedTypeMunger {
private final UnresolvedType interfaceType;
private final Pointcut testPointcut;
private TypePattern lazyTestTypePattern;
public boolean equals(Object other) {
if (!(other instanceof PerObjectInterfaceTypeMunger)) return false;
PerObjectInterfaceTypeMunger o = (PerObjectInterfaceTypeMunger)other;
return ((o.testPointcut == null) ? (testPointcut == null ) : testPointcut.equals(o.testPointcut))
&& ((o.lazyTestTypePattern == null) ? (lazyTestTypePattern == null ) : lazyTestTypePattern.equals(o.lazyTestTypePattern));
}
private volatile int hashCode = 0;
public int hashCode() {
if (hashCode == 0) {
int result = 17;
result = 37*result + ((testPointcut == null) ? 0 : testPointcut.hashCode());
result = 37*result + ((lazyTestTypePattern == null) ? 0 : lazyTestTypePattern.hashCode());
hashCode = result;
}
return hashCode;
}
public PerObjectInterfaceTypeMunger(UnresolvedType aspectType, Pointcut testPointcut) {
super(PerObjectInterface, null);
this.testPointcut = testPointcut;
this.interfaceType = AjcMemberMaker.perObjectInterfaceType(aspectType);
}
private TypePattern getTestTypePattern(ResolvedType aspectType) {
if (lazyTestTypePattern == null) {
final boolean isPerThis;
if (aspectType.getPerClause() instanceof PerFromSuper) {
PerFromSuper ps = (PerFromSuper) aspectType.getPerClause();
isPerThis = ((PerObject) ps.lookupConcretePerClause(aspectType)).isThis();
} else {
isPerThis = ((PerObject) aspectType.getPerClause()).isThis();
}
PerThisOrTargetPointcutVisitor v = new PerThisOrTargetPointcutVisitor(!isPerThis, aspectType);
lazyTestTypePattern = v.getPerTypePointcut(testPointcut);
// reset hashCode so that its recalculated with the new lazyTestTypePattern
hashCode = 0;
}
return lazyTestTypePattern;
}
public void write(DataOutputStream s) throws IOException {
throw new RuntimeException("shouldn't be serialized");
}
public UnresolvedType getInterfaceType() {
return interfaceType;
}
public Pointcut getTestPointcut() {
return testPointcut;
}
public boolean matches(ResolvedType matchType, ResolvedType aspectType) {
if (matchType.isInterface()) return false;
return getTestTypePattern(aspectType).matchesStatically(matchType);
}
public boolean isLateMunger() {
return true;
}
}
|
138,540 |
Bug 138540 Patch to add support for -Xset: options
|
I needed to add X="set:activateLightweightDelegates=false to my ant build configuration, to troubleshoot the out of memory permgen condition. However, the ant task support doesn't currently support adding the new -Xset style options Andy added. Here is a small patch to pass any -Xset: options through, that worked for me.
|
resolved fixed
|
99882cb
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-04-26T07:25:49Z | 2006-04-26T00:06: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.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.tools.ant.AntClassLoader;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Location;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.tools.ant.taskdefs.Delete;
import org.apache.tools.ant.taskdefs.Execute;
import org.apache.tools.ant.taskdefs.Expand;
import org.apache.tools.ant.taskdefs.Javac;
import org.apache.tools.ant.taskdefs.LogStreamHandler;
import org.apache.tools.ant.taskdefs.MatchingTask;
import org.apache.tools.ant.taskdefs.Mkdir;
import org.apache.tools.ant.taskdefs.PumpStreamHandler;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.taskdefs.compilers.DefaultCompilerAdapter;
import org.apache.tools.ant.types.Commandline;
import org.apache.tools.ant.types.CommandlineJava;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.PatternSet;
import org.apache.tools.ant.types.Reference;
import org.apache.tools.ant.types.ZipFileSet;
import org.apache.tools.ant.util.TaskLogger;
import org.aspectj.bridge.AbortException;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.IMessageHolder;
import org.aspectj.bridge.MessageHandler;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.tools.ajc.Main;
import org.aspectj.util.FileUtil;
import org.aspectj.util.LangUtil;
/**
* This runs the AspectJ 1.1 compiler,
* supporting all the command-line options.
* In 1.1.1, ajc copies resources from input jars,
* but you can copy resources from the source directories
* using sourceRootCopyFilter.
* When not forking, things will be copied as needed
* for each iterative compile,
* but when forking things are only copied at the
* completion of a successful compile.
* <p>
* See the development environment guide for
* usage documentation.
*
* @since AspectJ 1.1, Ant 1.5
*/
public class AjcTask extends MatchingTask {
/*
* This task mainly converts ant specification for ajc,
* verbosely ignoring improper input.
* It also has some special features for non-obvious clients:
* (1) Javac compiler adapter supported in
* <code>setupAjc(AjcTask, Javac, File)</code>
* and
* <code>readArguments(String[])</code>;
* (2) testing is supported by
* (a) permitting the same specification to be re-run
* with added flags (settings once made cannot be
* removed); and
* (b) permitting recycling the task with
* <code>reset()</code> (untested).
*
* The parts that do more than convert ant specs are
* (a) code for forking;
* (b) code for copying resources.
*
* If you maintain/upgrade this task, keep in mind:
* (1) changes to the semantics of ajc (new options, new
* values permitted, etc.) will have to be reflected here.
* (2) the clients:
* the iajc ant script, Javac compiler adapter,
* maven clients of iajc, and testing code.
*/
// XXX move static methods after static initializer
/**
* This method extracts javac arguments to ajc,
* and add arguments to make ajc behave more like javac
* in copying resources.
* <p>
* Pass ajc-specific options using compilerarg sub-element:
* <pre>
* <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", "1.5" };
static final String[] SOURCE_INPUTS = new String []
{ "1.3", "1.4", "1.5" };
static final String[] COMPLIANCE_INPUTS = new String []
{ "-1.3", "-1.4", "-1.5" };
private static final ICommandEditor COMMAND_EDITOR;
static {
// many now deprecated: reweavable*
String[] xs = new String[]
{ "serializableAspects", "incrementalFile", "lazyTjp",
"reweavable", "reweavable:compress", "notReweavable", "noInline",
"terminateAfterCompilation","hasMember",
"ajruntimetarget:1.2", "ajruntimetarget:1.5",
//, "targetNearSource", "OcodeSize",
};
VALID_XOPTIONS = Collections.unmodifiableList(Arrays.asList(xs));
xs = new String[]
{"constructorName", "packageDefaultMethod", "deprecation",
"maskedCatchBlocks", "unusedLocals", "unusedArguments",
"unusedImports", "syntheticAccess", "assertIdentifier", "none" };
VALID_WARNINGS = Collections.unmodifiableList(Arrays.asList(xs));
xs = new String[] {"none", "lines", "vars", "source" };
VALID_DEBUG = Collections.unmodifiableList(Arrays.asList(xs));
xs = new String[] { "error", "warning", "ignore"};
VALID_XLINT = Collections.unmodifiableList(Arrays.asList(xs));
ICommandEditor editor = null;
try {
String editorClassName = System.getProperty(COMMAND_EDITOR_NAME);
if (null != editorClassName) {
ClassLoader cl = AjcTask.class.getClassLoader();
Class editorClass = cl.loadClass(editorClassName);
editor = (ICommandEditor) editorClass.newInstance();
}
} catch (Throwable t) {
System.err.println("Warning: unable to load command editor");
t.printStackTrace(System.err);
}
COMMAND_EDITOR = editor;
}
// ---------------------------- state and Ant interface thereto
private boolean verbose;
private boolean listFileArgs;
private boolean failonerror;
private boolean fork;
private String maxMem;
private TaskLogger logger;
// ------- single entries dumped into cmd
protected GuardedCommand cmd;
// ------- lists resolved in addListArgs() at execute() time
private Path srcdir;
private Path injars;
private Path inpath;
private Path classpath;
private Path bootclasspath;
private Path forkclasspath;
private Path extdirs;
private Path aspectpath;
private Path argfiles;
private List ignored;
private Path sourceRoots;
private File xweaveDir;
private String xdoneSignal;
// ----- added by adapter - integrate better?
private List /* File */ adapterFiles;
private String[] adapterArguments;
private IMessageHolder messageHolder;
private ICommandEditor commandEditor;
// -------- resource-copying
/** true if copying injar non-.class files to the output jar */
private boolean copyInjars;
private boolean copyInpath;
/** non-null if copying all source root files but the filtered ones */
private String sourceRootCopyFilter;
/** non-null if copying all inpath dir files but the filtered ones */
private String inpathDirCopyFilter;
/** directory sink for classes */
private File destDir;
/** zip file sink for classes */
private File outjar;
/** track whether we've supplied any temp outjar */
private boolean outjarFixedup;
/**
* When possibly copying resources to the output jar,
* pass ajc a fake output jar to copy from,
* so we don't change the modification time of the output jar
* when copying injars/inpath into the actual outjar.
*/
private File tmpOutjar;
private boolean executing;
/** non-null only while executing in same vm */
private Main main;
/** true only when executing in other vm */
private boolean executingInOtherVM;
/** true if -incremental */
private boolean inIncrementalMode;
/** true if -XincrementalFile (i.e, setTagFile)*/
private boolean inIncrementalFileMode;
/** used when forking */
private CommandlineJava javaCmd = new CommandlineJava();
// also note MatchingTask grabs source files...
public AjcTask() {
reset();
}
/** to use this same Task more than once (testing) */
public void reset() { // XXX possible to reset MatchingTask?
// need declare for "all fields initialized in ..."
adapterArguments = null;
adapterFiles = new ArrayList();
argfiles = null;
executing = false;
aspectpath = null;
bootclasspath = null;
classpath = null;
cmd = new GuardedCommand();
copyInjars = false;
copyInpath = false;
destDir = DEFAULT_DESTDIR;
executing = false;
executingInOtherVM = false;
extdirs = null;
failonerror = true; // non-standard default
forkclasspath = null;
inIncrementalMode = false;
inIncrementalFileMode = false;
ignored = new ArrayList();
injars = null;
inpath = null;
listFileArgs = false;
maxMem = null;
messageHolder = null;
outjar = null;
sourceRootCopyFilter = null;
inpathDirCopyFilter = null;
sourceRoots = null;
srcdir = null;
tmpOutjar = null;
verbose = false;
xweaveDir = null;
xdoneSignal = null;
javaCmd = new CommandlineJava();
}
protected void ignore(String ignored) {
this.ignored.add(ignored + " at " + getLocation());
}
//---------------------- option values
// used by entries with internal commas
protected String validCommaList(String list, List valid, String label) {
return validCommaList(list, valid, label, valid.size());
}
protected String validCommaList(String list, List valid, String label, int max) {
StringBuffer result = new StringBuffer();
StringTokenizer st = new StringTokenizer(list, ",");
int num = 0;
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
num++;
if (num > max) {
ignore("too many entries for -"
+ label
+ ": "
+ token);
break;
}
if (!valid.contains(token)) {
ignore("bad commaList entry for -"
+ label
+ ": "
+ token);
} else {
if (0 < result.length()) {
result.append(",");
}
result.append(token);
}
}
return (0 == result.length() ? null : result.toString());
}
public void setIncremental(boolean incremental) {
cmd.addFlag("-incremental", incremental);
inIncrementalMode = incremental;
}
public void setHelp(boolean help) {
cmd.addFlag("-help", help);
}
public void setVersion(boolean version) {
cmd.addFlag("-version", version);
}
public void setXTerminateAfterCompilation(boolean b) {
cmd.addFlag("-XterminateAfterCompilation", b);
}
public void setXReweavable(boolean reweavable) {
cmd.addFlag("-Xreweavable",reweavable);
}
public void setXNoWeave(boolean b) {
if (logger!=null) logger.warning("the noweave option is no longer required and is being ignored");
}
public void setNoWeave(boolean b) {
if (logger!=null) logger.warning("the noweave option is no longer required and is being ignored");
}
public void setXNotReweavable(boolean notReweavable) {
cmd.addFlag("-XnotReweavable",notReweavable);
}
public void setXNoInline(boolean noInline) {
cmd.addFlag("-XnoInline",noInline);
}
public void setShowWeaveInfo(boolean showweaveinfo) {
cmd.addFlag("-showWeaveInfo",showweaveinfo);
}
public void setNowarn(boolean nowarn) {
cmd.addFlag("-nowarn", nowarn);
}
public void setDeprecation(boolean deprecation) {
cmd.addFlag("-deprecation", deprecation);
}
public void setWarn(String warnings) {
warnings = validCommaList(warnings, VALID_WARNINGS, "warn");
cmd.addFlag("-warn:" + warnings, (null != warnings));
}
public void setDebug(boolean debug) {
cmd.addFlag("-g", debug);
}
public void setDebugLevel(String level) {
level = validCommaList(level, VALID_DEBUG, "g");
cmd.addFlag("-g:" + level, (null != level));
}
public void setEmacssym(boolean emacssym) {
cmd.addFlag("-emacssym", emacssym);
}
public void setCrossrefs(boolean on) {
cmd.addFlag("-crossrefs", on);
}
/**
* -Xlint - set default level of -Xlint messages to warning
* (same as </code>-Xlint:warning</code>)
*/
public void setXlintwarnings(boolean xlintwarnings) {
cmd.addFlag("-Xlint", xlintwarnings);
}
/** -Xlint:{error|warning|info} - set default level for -Xlint messages
* @param xlint the String with one of error, warning, ignored
*/
public void setXlint(String xlint) {
xlint = validCommaList(xlint, VALID_XLINT, "Xlint", 1);
cmd.addFlag("-Xlint:" + xlint, (null != xlint));
}
/**
* -Xlintfile {lint.properties} - enable or disable specific forms
* of -Xlint messages based on a lint properties file
* (default is
* <code>org/aspectj/weaver/XLintDefault.properties</code>)
* @param xlintFile the File with lint properties
*/
public void setXlintfile(File xlintFile) {
cmd.addFlagged("-Xlintfile", xlintFile.getAbsolutePath());
}
public void setPreserveAllLocals(boolean preserveAllLocals) {
cmd.addFlag("-preserveAllLocals", preserveAllLocals);
}
public void setNoImportError(boolean noImportError) {
cmd.addFlag("-warn:-unusedImport", noImportError);
}
public void setEncoding(String encoding) {
cmd.addFlagged("-encoding", encoding);
}
public void setLog(File file) {
cmd.addFlagged("-log", file.getAbsolutePath());
}
public void setProceedOnError(boolean proceedOnError) {
cmd.addFlag("-proceedOnError", proceedOnError);
}
public void setVerbose(boolean verbose) {
cmd.addFlag("-verbose", verbose);
this.verbose = verbose;
}
public void setListFileArgs(boolean listFileArgs) {
this.listFileArgs = listFileArgs;
}
public void setReferenceInfo(boolean referenceInfo) {
cmd.addFlag("-referenceInfo", referenceInfo);
}
public void setTime(boolean time) {
cmd.addFlag("-time", time);
}
public void setNoExit(boolean noExit) {
cmd.addFlag("-noExit", noExit);
}
public void setFailonerror(boolean failonerror) {
this.failonerror = failonerror;
}
/**
* @return true if fork was set
*/
public boolean isForked() {
return fork;
}
public void setFork(boolean fork) {
this.fork = fork;
}
public void setMaxmem(String maxMem) {
this.maxMem = maxMem;
}
/** support for nested <jvmarg> elements */
public Commandline.Argument createJvmarg() {
return this.javaCmd.createVmArgument();
}
// ----------------
public void setTagFile(File file) {
inIncrementalMode = true;
cmd.addFlagged(Main.CommandController.TAG_FILE_OPTION,
file.getAbsolutePath());
inIncrementalFileMode = true;
}
public void setOutjar(File file) {
if (DEFAULT_DESTDIR != destDir) {
String e = "specifying both output jar ("
+ file
+ ") and destination dir ("
+ destDir
+ ")";
throw new BuildException(e);
}
outjar = file;
outjarFixedup = false;
tmpOutjar = null;
}
public void setOutxml(boolean outxml) {
cmd.addFlag("-outxml",outxml);
}
public void setOutxmlfile(String name) {
cmd.addFlagged("-outxmlfile", name);
}
public void setDestdir(File dir) {
if (null != outjar) {
String e = "specifying both output jar ("
+ outjar
+ ") and destination dir ("
+ dir
+ ")";
throw new BuildException(e);
}
cmd.addFlagged("-d", dir.getAbsolutePath());
destDir = dir;
}
/**
* @param input a String in TARGET_INPUTS
*/
public void setTarget(String input) {
String ignore = cmd.addOption("-target", TARGET_INPUTS, input);
if (null != ignore) {
ignore(ignore);
}
}
/**
* Language compliance level.
* If not set explicitly, eclipse default holds.
* @param input a String in COMPLIANCE_INPUTS
*/
public void setCompliance(String input) {
String ignore = cmd.addOption(null, COMPLIANCE_INPUTS, input);
if (null != ignore) {
ignore(ignore);
}
}
/**
* Source compliance level.
* If not set explicitly, eclipse default holds.
* @param input a String in SOURCE_INPUTS
*/
public void setSource(String input) {
String ignore = cmd.addOption("-source", SOURCE_INPUTS, input);
if (null != ignore) {
ignore(ignore);
}
}
/**
* Flag to copy all non-.class contents of injars
* to outjar after compile completes.
* Requires both injars and outjar.
* @param doCopy
*/
public void setCopyInjars(boolean doCopy){
ignore("copyInJars");
log("copyInjars not required since 1.1.1.\n", Project.MSG_WARN);
//this.copyInjars = doCopy;
}
/**
* Option to copy all files from
* all source root directories
* except those specified here.
* If this is specified and sourceroots are specified,
* then this will copy all files except
* those specified in the filter pattern.
* Requires sourceroots.
*
* @param filter a String acceptable as an excludes
* filter for an Ant Zip fileset.
*/
public void setSourceRootCopyFilter(String filter){
this.sourceRootCopyFilter = filter;
}
/**
* Option to copy all files from
* all inpath directories
* except the files specified here.
* If this is specified and inpath directories are specified,
* then this will copy all files except
* those specified in the filter pattern.
* Requires inpath.
* If the input does not contain "**\/*.class", then
* this prepends it, to avoid overwriting woven classes
* with unwoven input.
* @param filter a String acceptable as an excludes
* filter for an Ant Zip fileset.
*/
public void setInpathDirCopyFilter(String filter){
if (null != filter) {
if (-1 == filter.indexOf("**/*.class")) {
filter = "**/*.class," + filter;
}
}
this.inpathDirCopyFilter = filter;
}
public void setX(String input) { // ajc-only eajc-also docDone
StringTokenizer tokens = new StringTokenizer(input, ",", false);
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken().trim();
if (1 < token.length()) {
if (VALID_XOPTIONS.contains(token)) {
cmd.addFlag("-X" + token, true);
} else {
ignore("-X" + token);
}
}
}
}
public void setXDoneSignal(String doneSignal) {
this.xdoneSignal = doneSignal;
}
/** direct API for testing */
public void setMessageHolder(IMessageHolder holder) {
this.messageHolder = holder;
}
/**
* Setup custom message handling.
* @param className the String fully-qualified-name of a class
* reachable from this object's class loader,
* implementing IMessageHolder, and
* having a public no-argument constructor.
* @throws BuildException if unable to create instance of className
*/
public void setMessageHolderClass(String className) {
try {
Class mclass = Class.forName(className);
IMessageHolder holder = (IMessageHolder) mclass.newInstance();
setMessageHolder(holder);
} catch (Throwable t) {
String m = "unable to instantiate message holder: " + className;
throw new BuildException(m, t);
}
}
/** direct API for testing */
public void setCommandEditor(ICommandEditor editor) {
this.commandEditor = editor;
}
/**
* Setup command-line filter.
* To do this staticly, define the environment variable
* <code>org.aspectj.tools.ant.taskdefs.AjcTask.COMMAND_EDITOR</code>
* with the <code>className</code> parameter.
* @param className the String fully-qualified-name of a class
* reachable from this object's class loader,
* implementing ICommandEditor, and
* having a public no-argument constructor.
* @throws BuildException if unable to create instance of className
*/
public void setCommandEditorClass(String className) { // skip Ant interface?
try {
Class mclass = Class.forName(className);
setCommandEditor((ICommandEditor) mclass.newInstance());
} catch (Throwable t) {
String m = "unable to instantiate command editor: " + className;
throw new BuildException(m, t);
}
}
//---------------------- Path lists
/**
* Add path elements to source path and return result.
* Elements are added even if they do not exist.
* @param source the Path to add to - may be null
* @param toAdd the Path to add - may be null
* @return the (never-null) Path that results
*/
protected Path incPath(Path source, Path toAdd) {
if (null == source) {
source = new Path(project);
}
if (null != toAdd) {
source.append(toAdd);
}
return source;
}
public void setSourcerootsref(Reference ref) {
createSourceRoots().setRefid(ref);
}
public void setSourceRoots(Path roots) {
sourceRoots = incPath(sourceRoots, roots);
}
public Path createSourceRoots() {
if (sourceRoots == null) {
sourceRoots = new Path(project);
}
return sourceRoots.createPath();
}
public void setXWeaveDir(File file) {
if ((null != file) && file.isDirectory()
&& file.canRead()) {
xweaveDir = file;
}
}
public void setInjarsref(Reference ref) {
createInjars().setRefid(ref);
}
public void setInpathref(Reference ref) {
createInpath().setRefid(ref);
}
public void setInjars(Path path) {
injars = incPath(injars, path);
}
public void setInpath(Path path) {
inpath = incPath(inpath,path);
}
public Path createInjars() {
if (injars == null) {
injars = new Path(project);
}
return injars.createPath();
}
public Path createInpath() {
if (inpath == null) {
inpath = new Path(project);
}
return inpath.createPath();
}
public void setClasspath(Path path) {
classpath = incPath(classpath, path);
}
public void setClasspathref(Reference classpathref) {
createClasspath().setRefid(classpathref);
}
public Path createClasspath() {
if (classpath == null) {
classpath = new Path(project);
}
return classpath.createPath();
}
public void setBootclasspath(Path path) {
bootclasspath = incPath(bootclasspath, path);
}
public void setBootclasspathref(Reference bootclasspathref) {
createBootclasspath().setRefid(bootclasspathref);
}
public Path createBootclasspath() {
if (bootclasspath == null) {
bootclasspath = new Path(project);
}
return bootclasspath.createPath();
}
public void setForkclasspath(Path path) {
forkclasspath = incPath(forkclasspath, path);
}
public void setForkclasspathref(Reference forkclasspathref) {
createForkclasspath().setRefid(forkclasspathref);
}
public Path createForkclasspath() {
if (forkclasspath == null) {
forkclasspath = new Path(project);
}
return forkclasspath.createPath();
}
public void setExtdirs(Path path) {
extdirs = incPath(extdirs, path);
}
public void setExtdirsref(Reference ref) {
createExtdirs().setRefid(ref);
}
public Path createExtdirs() {
if (extdirs == null) {
extdirs = new Path(project);
}
return extdirs.createPath();
}
public void setAspectpathref(Reference ref) {
createAspectpath().setRefid(ref);
}
public void setAspectpath(Path path) {
aspectpath = incPath(aspectpath, path);
}
public Path createAspectpath() {
if (aspectpath == null) {
aspectpath = new Path(project);
}
return aspectpath.createPath();
}
public void setSrcDir(Path path) {
srcdir = incPath(srcdir, path);
}
public Path createSrc() {
return createSrcdir();
}
public Path createSrcdir() {
if (srcdir == null) {
srcdir = new Path(project);
}
return srcdir.createPath();
}
/** @return true if in incremental mode (command-line or file) */
public boolean isInIncrementalMode() {
return inIncrementalMode;
}
/** @return true if in incremental file mode */
public boolean isInIncrementalFileMode() {
return inIncrementalFileMode;
}
public void setArgfilesref(Reference ref) {
createArgfiles().setRefid(ref);
}
public void setArgfiles(Path path) { // ajc-only eajc-also docDone
argfiles = incPath(argfiles, path);
}
public Path createArgfiles() {
if (argfiles == null) {
argfiles = new Path(project);
}
return argfiles.createPath();
}
// ------------------------------ run
/**
* Compile using ajc per settings.
* @exception BuildException if the compilation has problems
* or if there were compiler errors and failonerror is true.
*/
public void execute() throws BuildException {
this.logger = new TaskLogger(this);
if (executing) {
throw new IllegalStateException("already executing");
} else {
executing = true;
}
setupOptions();
verifyOptions();
try {
String[] args = makeCommand();
logVerbose("ajc " + Arrays.asList(args));
if (!fork) {
executeInSameVM(args);
} else { // when forking, Adapter handles failonerror
executeInOtherVM(args);
}
} catch (BuildException e) {
throw e;
} catch (Throwable x) {
this.logger.error(Main.renderExceptionForUser(x));
throw new BuildException("IGNORE -- See "
+ LangUtil.unqualifiedClassName(x)
+ " rendered to ant logger");
} finally {
executing = false;
if (null != tmpOutjar) {
tmpOutjar.delete();
}
}
}
/**
* Halt processing.
* This tells main in the same vm to quit.
* It fails when running in forked mode.
* @return true if not in forked mode
* and main has quit or been told to quit
*/
public boolean quit() {
if (executingInOtherVM) {
return false;
}
Main me = main;
if (null != me) {
me.quit();
}
return true;
}
// package-private for testing
String[] makeCommand() {
ArrayList result = new ArrayList();
if (0 < ignored.size()) {
for (Iterator iter = ignored.iterator(); iter.hasNext();) {
logVerbose("ignored: " + iter.next());
}
}
// when copying resources, use temp jar for class output
// then copy temp jar contents and resources to output jar
if ((null != outjar) && !outjarFixedup) {
if (copyInjars || copyInpath || (null != sourceRootCopyFilter)
|| (null != inpathDirCopyFilter)) {
String path = outjar.getAbsolutePath();
int len = FileUtil.zipSuffixLength(path);
if (len < 1) {
this.logger.info("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 != inpathDirCopyFilter) || (null != sourceRootCopyFilter))
&& (null == outjar) && (DEFAULT_DESTDIR == destDir)) {
final String REQ = " requires dest dir or output jar.\n";
if (null == inpathDirCopyFilter) {
sb.append("sourceRootCopyFilter");
} else if (null == sourceRootCopyFilter) {
sb.append("inpathDirCopyFilter");
} else {
sb.append("sourceRootCopyFilter and inpathDirCopyFilter");
}
sb.append(REQ);
}
if (0 < sb.length()) {
throw new BuildException(sb.toString());
}
}
/**
* Run the compile in the same VM by
* loading the compiler (Main),
* setting up any message holders,
* doing the compile,
* and converting abort/failure and error messages
* to BuildException, as appropriate.
* @throws BuildException if abort or failure messages
* or if errors and failonerror.
*
*/
protected void executeInSameVM(String[] args) {
if (null != maxMem) {
log("maxMem ignored unless forked: " + maxMem, Project.MSG_WARN);
}
IMessageHolder holder = messageHolder;
int numPreviousErrors;
if (null == holder) {
MessageHandler mhandler = new MessageHandler(true);
final IMessageHandler delegate;
delegate = new AntMessageHandler(this.logger,this.verbose, false);
mhandler.setInterceptor(delegate);
holder = mhandler;
numPreviousErrors = 0;
} else {
numPreviousErrors = holder.numMessages(IMessage.ERROR, true);
}
{
Main newmain = new Main();
newmain.setHolder(holder);
newmain.setCompletionRunner(new Runnable() {
public void run() {
doCompletionTasks();
}
});
if (null != main) {
MessageUtil.fail(holder, "still running prior main");
return;
}
main = newmain;
}
main.runMain(args, false);
if (failonerror) {
int errs = holder.numMessages(IMessage.ERROR, false);
errs -= numPreviousErrors;
if (0 < errs) {
String m = errs + " errors";
MessageUtil.print(System.err, holder, "", MessageUtil.MESSAGE_ALL, MessageUtil.PICK_ERROR, true);
throw new BuildException(m);
}
}
// Throw BuildException if there are any fail or abort
// messages.
// The BuildException message text has a list of class names
// for the exceptions found in the messages, or the
// number of fail/abort messages found if there were
// no exceptions for any of the fail/abort messages.
// The interceptor message handler should have already
// printed the messages, including any stack traces.
// HACK: this ignores the Usage message
{
IMessage[] fails = holder.getMessages(IMessage.FAIL, true);
if (!LangUtil.isEmpty(fails)) {
StringBuffer sb = new StringBuffer();
String prefix = "fail due to ";
int numThrown = 0;
for (int i = 0; i < fails.length; i++) {
String message = fails[i].getMessage();
if (LangUtil.isEmpty(message)) {
message = "<no message>";
} else if (-1 != message.indexOf(USAGE_SUBSTRING)) {
continue;
}
Throwable t = fails[i].getThrown();
if (null != t) {
numThrown++;
sb.append(prefix);
sb.append(LangUtil.unqualifiedClassName(t.getClass()));
String thrownMessage = t.getMessage();
if (!LangUtil.isEmpty(thrownMessage)) {
sb.append(" \"" + thrownMessage + "\"");
}
}
sb.append("\"" + message + "\"");
prefix = ", ";
}
if (0 < sb.length()) {
sb.append(" (" + numThrown + " exceptions)");
throw new BuildException(sb.toString());
}
}
}
}
/**
* Execute in a separate VM.
* Differences from normal same-VM execution:
* <ul>
* <li>ignores any message holder {class} set</li>
* <li>No resource-copying between interative runs</li>
* <li>failonerror fails when process interface fails
* to return negative values</li>
* </ul>
* @param args String[] of the complete compiler command to execute
*
* @see DefaultCompilerAdapter#executeExternalCompile(String[], int)
* @throws BuildException if ajc aborts (negative value)
* or if failonerror and there were compile errors.
*/
protected void executeInOtherVM(String[] args) {
javaCmd.setClassname(org.aspectj.tools.ajc.Main.class.getName());
final Path vmClasspath = javaCmd.createClasspath(getProject());
{
File aspectjtools = null;
int vmClasspathSize = vmClasspath.size();
if ((null != forkclasspath)
&& (0 != forkclasspath.size())) {
vmClasspath.addExisting(forkclasspath);
} else {
aspectjtools = findAspectjtoolsJar();
if (null != aspectjtools) {
vmClasspath.createPathElement().setLocation(aspectjtools);
}
}
int newVmClasspathSize = vmClasspath.size();
if (vmClasspathSize == newVmClasspathSize) {
String m = "unable to find aspectjtools to fork - ";
if (null != aspectjtools) {
m += "tried " + aspectjtools.toString();
} else if (null != forkclasspath) {
m += "tried " + forkclasspath.toString();
} else {
m += "define forkclasspath or put aspectjtools on classpath";
}
throw new BuildException(m);
}
}
if (null != maxMem) {
javaCmd.setMaxmemory(maxMem);
}
File tempFile = null;
int numArgs = args.length;
args = GuardedCommand.limitTo(args, MAX_COMMANDLINE, getLocation());
if (args.length != numArgs) {
tempFile = new File(args[1]);
}
try {
boolean setMessageHolderOnForking = (this.messageHolder != null);
String[] javaArgs = javaCmd.getCommandline();
String[] both = new String[javaArgs.length + args.length + (setMessageHolderOnForking ? 2 : 0)];
System.arraycopy(javaArgs,0,both,0,javaArgs.length);
System.arraycopy(args,0,both,javaArgs.length,args.length);
if (setMessageHolderOnForking) {
both[both.length - 2] = "-messageHolder";
both[both.length - 1] = this.messageHolder.getClass().getName();
}
// try to use javaw instead on windows
if (both[0].endsWith("java.exe")) {
String path = both[0];
path = path.substring(0, path.length()-4);
path = path + "w.exe";
File javaw = new File(path);
if (javaw.canRead() && javaw.isFile()) {
both[0] = path;
}
}
logVerbose("forking " + Arrays.asList(both));
int result = execInOtherVM(both);
if (0 > result) {
throw new BuildException("failure[" + result + "] running ajc");
} else if (failonerror && (0 < result)) {
throw new BuildException("compile errors: " + result);
}
// when forking, do completion only at end and when successful
doCompletionTasks();
} finally {
if (null != tempFile) {
tempFile.delete();
}
}
}
/**
* Execute in another process using the same JDK
* and the base directory of the project. XXX correct?
* @param args
* @return
*/
protected int execInOtherVM(String[] args) {
try {
Project project = getProject();
PumpStreamHandler handler = new LogStreamHandler(this,
verbose ? Project.MSG_VERBOSE : Project.MSG_INFO,
Project.MSG_WARN);
// replace above two lines with what follows as an aid to debugging when running the unit tests....
// LogStreamHandler handler = new LogStreamHandler(this,
// Project.MSG_INFO, Project.MSG_WARN) {
//
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// /* (non-Javadoc)
// * @see org.apache.tools.ant.taskdefs.PumpStreamHandler#createProcessOutputPump(java.io.InputStream, java.io.OutputStream)
// */
// protected void createProcessErrorPump(InputStream is,
// OutputStream os) {
// super.createProcessErrorPump(is, baos);
// }
//
// /* (non-Javadoc)
// * @see org.apache.tools.ant.taskdefs.LogStreamHandler#stop()
// */
// public void stop() {
// byte[] written = baos.toByteArray();
// System.err.print(new String(written));
// super.stop();
// }
// };
Execute exe = new Execute(handler);
exe.setAntRun(project);
exe.setWorkingDirectory(project.getBaseDir());
exe.setCommandline(args);
try {
if (executingInOtherVM) {
String s = "already running in other vm?";
throw new BuildException(s, location);
}
executingInOtherVM = true;
exe.execute();
} finally {
executingInOtherVM = false;
}
return exe.getExitValue();
} catch (IOException e) {
String m = "Error executing command " + Arrays.asList(args);
throw new BuildException(m, e, location);
}
}
// ------------------------------ setup and reporting
/** @return null if path null or empty, String rendition otherwise */
protected static void addFlaggedPath(String flag, Path path, List list) {
if (!LangUtil.isEmpty(flag)
&& ((null != path) && (0 < path.size()))) {
list.add(flag);
list.add(path.toString());
}
}
/**
* Add to list any path or plural arguments.
*/
protected void addListArgs(List list) throws BuildException {
addFlaggedPath("-classpath", classpath, list);
addFlaggedPath("-bootclasspath", bootclasspath, list);
addFlaggedPath("-extdirs", extdirs, list);
addFlaggedPath("-aspectpath", aspectpath, list);
addFlaggedPath("-injars", injars, list);
addFlaggedPath("-inpath", inpath, list);
addFlaggedPath("-sourceroots", sourceRoots, list);
if (argfiles != null) {
String[] files = argfiles.list();
for (int i = 0; i < files.length; i++) {
File argfile = project.resolveFile(files[i]);
if (check(argfile, files[i], false, location)) {
list.add("-argfile");
list.add(argfile.getAbsolutePath());
}
}
}
if (srcdir != null) {
// todo: ignore any srcdir if any argfiles and no explicit includes
String[] dirs = srcdir.list();
for (int i = 0; i < dirs.length; i++) {
File dir = project.resolveFile(dirs[i]);
check(dir, dirs[i], true, location);
// relies on compiler to prune non-source files
String[] files = getDirectoryScanner(dir).getIncludedFiles();
for (int j = 0; j < files.length; j++) {
File file = new File(dir, files[j]);
if (FileUtil.hasSourceSuffix(file)) {
list.add(file.getAbsolutePath());
}
}
}
}
if (0 < adapterFiles.size()) {
for (Iterator iter = adapterFiles.iterator(); iter.hasNext();) {
File file = (File) iter.next();
if (file.canRead() && FileUtil.hasSourceSuffix(file)) {
list.add(file.getAbsolutePath());
} else {
this.logger.warning("skipping file: " + file);
}
}
}
}
/**
* Throw BuildException unless file is valid.
* @param file the File to check
* @param name the symbolic name to print on error
* @param isDir if true, verify file is a directory
* @param loc the Location used to create sensible BuildException
* @return
* @throws BuildException unless file valid
*/
protected final boolean check(File file, String name,
boolean isDir, Location loc) {
loc = loc != null ? loc : location;
if (file == null) {
throw new BuildException(name + " is null!", loc);
}
if (!file.exists()) {
throw new BuildException(file + " doesn't exist!", loc);
}
if (isDir ^ file.isDirectory()) {
String e = file + " should" + (isDir ? "" : "n't") +
" be a directory!";
throw new BuildException(e, loc);
}
return true;
}
/**
* Called when compile or incremental compile is completing,
* this completes the output jar or directory
* by copying resources if requested.
* Note: this is a callback run synchronously by the compiler.
* That means exceptions thrown here are caught by Main.run(..)
* and passed to the message handler.
*/
protected void doCompletionTasks() {
if (!executing) {
throw new IllegalStateException("should be executing");
}
if (null != outjar) {
completeOutjar();
} else {
completeDestdir();
}
if (null != xdoneSignal) {
MessageUtil.info(messageHolder, xdoneSignal);
}
}
/**
* Complete the destination directory
* by copying resources from the source root directories
* (if the filter is specified)
* and non-.class files from the input jars
* (if XCopyInjars is enabled).
*/
private void completeDestdir() {
if (!copyInjars && (null == sourceRootCopyFilter)
&& (null == inpathDirCopyFilter)) {
return;
} else if ((destDir == DEFAULT_DESTDIR)
|| !destDir.canWrite()) {
String s = "unable to copy resources to destDir: " + destDir;
throw new BuildException(s);
}
final Project project = getProject();
if (copyInjars) { // XXXX remove as unused since 1.1.1
if (null != inpath) {
log("copyInjars does not support inpath.\n", Project.MSG_WARN);
}
String taskName = getTaskName() + " - unzip";
String[] paths = injars.list();
if (!LangUtil.isEmpty(paths)) {
PatternSet patternSet = new PatternSet();
patternSet.setProject(project);
patternSet.setIncludes("**/*");
patternSet.setExcludes("**/*.class");
for (int i = 0; i < paths.length; i++) {
Expand unzip = new Expand();
unzip.setProject(project);
unzip.setTaskName(taskName);
unzip.setDest(destDir);
unzip.setSrc(new File(paths[i]));
unzip.addPatternset(patternSet);
unzip.execute();
}
}
}
if ((null != sourceRootCopyFilter) && (null != sourceRoots)) {
String[] paths = sourceRoots.list();
if (!LangUtil.isEmpty(paths)) {
Copy copy = new Copy();
copy.setProject(project);
copy.setTodir(destDir);
for (int i = 0; i < paths.length; i++) {
FileSet fileSet = new FileSet();
fileSet.setDir(new File(paths[i]));
fileSet.setIncludes("**/*");
fileSet.setExcludes(sourceRootCopyFilter);
copy.addFileset(fileSet);
}
copy.execute();
}
}
if ((null != inpathDirCopyFilter) && (null != inpath)) {
String[] paths = inpath.list();
if (!LangUtil.isEmpty(paths)) {
Copy copy = new Copy();
copy.setProject(project);
copy.setTodir(destDir);
boolean gotDir = false;
for (int i = 0; i < paths.length; i++) {
File inpathDir = new File(paths[i]);
if (inpathDir.isDirectory() && inpathDir.canRead()) {
if (!gotDir) {
gotDir = true;
}
FileSet fileSet = new FileSet();
fileSet.setDir(inpathDir);
fileSet.setIncludes("**/*");
fileSet.setExcludes(inpathDirCopyFilter);
copy.addFileset(fileSet);
}
}
if (gotDir) {
copy.execute();
}
}
}
}
/**
* Complete the output jar
* by copying resources from the source root directories
* if the filter is specified.
* and non-.class files from the input jars if enabled.
*/
private void completeOutjar() {
if (((null == tmpOutjar) || !tmpOutjar.canRead())
|| (!copyInjars && (null == sourceRootCopyFilter)
&& (null == inpathDirCopyFilter))) {
return;
}
Zip zip = new Zip();
Project project = getProject();
zip.setProject(project);
zip.setTaskName(getTaskName() + " - zip");
zip.setDestFile(outjar);
ZipFileSet zipfileset = new ZipFileSet();
zipfileset.setProject(project);
zipfileset.setSrc(tmpOutjar);
zipfileset.setIncludes("**/*.class");
zip.addZipfileset(zipfileset);
if (copyInjars) {
String[] paths = injars.list();
if (!LangUtil.isEmpty(paths)) {
for (int i = 0; i < paths.length; i++) {
File jarFile = new File(paths[i]);
zipfileset = new ZipFileSet();
zipfileset.setProject(project);
zipfileset.setSrc(jarFile);
zipfileset.setIncludes("**/*");
zipfileset.setExcludes("**/*.class");
zip.addZipfileset(zipfileset);
}
}
}
if ((null != sourceRootCopyFilter) && (null != sourceRoots)) {
String[] paths = sourceRoots.list();
if (!LangUtil.isEmpty(paths)) {
for (int i = 0; i < paths.length; i++) {
File srcRoot = new File(paths[i]);
FileSet fileset = new FileSet();
fileset.setProject(project);
fileset.setDir(srcRoot);
fileset.setIncludes("**/*");
fileset.setExcludes(sourceRootCopyFilter);
zip.addFileset(fileset);
}
}
}
if ((null != inpathDirCopyFilter) && (null != inpath)) {
String[] paths = inpath.list();
if (!LangUtil.isEmpty(paths)) {
for (int i = 0; i < paths.length; i++) {
File inpathDir = new File(paths[i]);
if (inpathDir.isDirectory() && inpathDir.canRead()) {
FileSet fileset = new FileSet();
fileset.setProject(project);
fileset.setDir(inpathDir);
fileset.setIncludes("**/*");
fileset.setExcludes(inpathDirCopyFilter);
zip.addFileset(fileset);
}
}
}
}
zip.execute();
}
// -------------------------- compiler adapter interface extras
/**
* Add specified source files.
*/
void addFiles(File[] paths) {
for (int i = 0; i < paths.length; i++) {
addFile(paths[i]);
}
}
/**
* Add specified source file.
*/
void addFile(File path) {
if (null != path) {
adapterFiles.add(path);
}
}
/**
* Read arguments in as if from a command line,
* mainly to support compiler adapter compilerarg subelement.
*
* @param args the String[] of arguments to read
*/
public void readArguments(String[] args) { // XXX slow, stupid, unmaintainable
if ((null == args) || (0 == args.length)) {
return;
}
/** String[] wrapper with increment, error reporting */
class Args {
final String[] args;
int index = 0;
Args(String[] args) {
this.args = args; // not null or empty
}
boolean hasNext() {
return index < args.length;
}
String next() {
String err = null;
if (!hasNext()) {
err = "need arg for flag " + args[args.length-1];
} else {
String s = args[index++];
if (null == s) {
err = "null value";
} else {
s = s.trim();
if (0 == s.trim().length()) {
err = "no value";
} else {
return s;
}
}
}
err += " at [" + index + "] of " + Arrays.asList(args);
throw new BuildException(err);
}
} // class Args
Args in = new Args(args);
String flag;
while (in.hasNext()) {
flag = in.next();
if ("-1.3".equals(flag)) {
setCompliance(flag);
} else if ("-1.4".equals(flag)) {
setCompliance(flag);
} else if ("-1.5".equals(flag)) {
setCompliance("1.5");
} else if ("-argfile".equals(flag)) {
setArgfiles(new Path(project, in.next()));
} else if ("-aspectpath".equals(flag)) {
setAspectpath(new Path(project, in.next()));
} else if ("-classpath".equals(flag)) {
setClasspath(new Path(project, in.next()));
} else if ("-extdirs".equals(flag)) {
setExtdirs(new Path(project, in.next()));
} else if ("-Xcopyinjars".equals(flag)) {
setCopyInjars(true); // ignored - will be flagged by setter
} else if ("-g".equals(flag)) {
setDebug(true);
} else if (flag.startsWith("-g:")) {
setDebugLevel(flag.substring(2));
} else if ("-deprecation".equals(flag)) {
setDeprecation(true);
} else if ("-d".equals(flag)) {
setDestdir(new File(in.next()));
} else if ("-crossrefs".equals(flag)) {
setCrossrefs(true);
} else if ("-emacssym".equals(flag)) {
setEmacssym(true);
} else if ("-encoding".equals(flag)) {
setEncoding(in.next());
} else if ("-Xfailonerror".equals(flag)) {
setFailonerror(true);
} else if ("-fork".equals(flag)) {
setFork(true);
} else if ("-forkclasspath".equals(flag)) {
setForkclasspath(new Path(project, in.next()));
} else if ("-help".equals(flag)) {
setHelp(true);
} else if ("-incremental".equals(flag)) {
setIncremental(true);
} else if ("-injars".equals(flag)) {
setInjars(new Path(project, in.next()));
} else if ("-inpath".equals(flag)) {
setInpath(new Path(project,in.next()));
} else if ("-Xlistfileargs".equals(flag)) {
setListFileArgs(true);
} else if ("-Xmaxmem".equals(flag)) {
setMaxmem(in.next());
} else if ("-Xmessageholderclass".equals(flag)) {
setMessageHolderClass(in.next());
} else if ("-noexit".equals(flag)) {
setNoExit(true);
} else if ("-noimport".equals(flag)) {
setNoExit(true);
} else if ("-noExit".equals(flag)) {
setNoExit(true);
} else if ("-noImportError".equals(flag)) {
setNoImportError(true);
} else if ("-noWarn".equals(flag)) {
setNowarn(true);
} else if ("-noexit".equals(flag)) {
setNoExit(true);
} else if ("-outjar".equals(flag)) {
setOutjar(new File(in.next()));
} else if ("-outxml".equals(flag)) {
setOutxml(true);
} else if ("-outxmlfile".equals(flag)) {
setOutxmlfile(in.next());
} else if ("-preserveAllLocals".equals(flag)) {
setPreserveAllLocals(true);
} else if ("-proceedOnError".equals(flag)) {
setProceedOnError(true);
} else if ("-referenceInfo".equals(flag)) {
setReferenceInfo(true);
} else if ("-source".equals(flag)) {
setSource(in.next());
} else if ("-Xsourcerootcopyfilter".equals(flag)) {
setSourceRootCopyFilter(in.next());
} else if ("-sourceroots".equals(flag)) {
setSourceRoots(new Path(project, in.next()));
} else if ("-Xsrcdir".equals(flag)) {
setSrcDir(new Path(project, in.next()));
} else if ("-Xtagfile".equals(flag)) {
setTagFile(new File(in.next()));
} else if ("-target".equals(flag)) {
setTarget(in.next());
} else if ("-time".equals(flag)) {
setTime(true);
} else if ("-time".equals(flag)) {
setTime(true);
} else if ("-verbose".equals(flag)) {
setVerbose(true);
} else if ("-showWeaveInfo".equals(flag)) {
setShowWeaveInfo(true);
} else if ("-version".equals(flag)) {
setVersion(true);
} else if ("-warn".equals(flag)) {
setWarn(in.next());
} else if (flag.startsWith("-warn:")) {
setWarn(flag.substring(6));
} else if ("-Xlint".equals(flag)) {
setXlintwarnings(true);
} else if (flag.startsWith("-Xlint:")) {
setXlint(flag.substring(7));
} else if ("-Xlintfile".equals(flag)) {
setXlintfile(new File(in.next()));
} else if ("-XterminateAfterCompilation".equals(flag)) {
setXTerminateAfterCompilation(true);
} else if ("-Xreweavable".equals(flag)) {
setXReweavable(true);
} else if ("-XnotReweavable".equals(flag)) {
setXNotReweavable(true);
} else if (flag.startsWith("@")) {
File file = new File(flag.substring(1));
if (file.canRead()) {
setArgfiles(new Path(project, file.getPath()));
} else {
ignore(flag);
}
} else {
File file = new File(flag);
if (file.isFile()
&& file.canRead()
&& FileUtil.hasSourceSuffix(file)) {
addFile(file);
} else {
ignore(flag);
}
}
}
}
protected void logVerbose(String text) {
if (this.verbose) {
this.logger.info(text);
} else {
this.logger.verbose(text);
}
}
/**
* Commandline wrapper that
* only permits addition of non-empty values
* and converts to argfile form if necessary.
*/
public static class GuardedCommand {
Commandline command;
//int size;
static boolean isEmpty(String s) {
return ((null == s) || (0 == s.trim().length()));
}
GuardedCommand() {
command = new Commandline();
}
void addFlag(String flag, boolean doAdd) {
if (doAdd && !isEmpty(flag)) {
command.createArgument().setValue(flag);
//size += 1 + flag.length();
}
}
/** @return null if added or ignoreString otherwise */
String addOption(String prefix, String[] validOptions, String input) {
if (isEmpty(input)) {
return null;
}
for (int i = 0; i < validOptions.length; i++) {
if (input.equals(validOptions[i])) {
if (isEmpty(prefix)) {
addFlag(input, true);
} else {
addFlagged(prefix, input);
}
return null;
}
}
return (null == prefix ? input : prefix + " " + input);
}
void addFlagged(String flag, String argument) {
if (!isEmpty(flag) && !isEmpty(argument)) {
command.addArguments(new String[] {flag, argument});
//size += 1 + flag.length() + argument.length();
}
}
// private void addFile(File file) {
// if (null != file) {
// String path = file.getAbsolutePath();
// addFlag(path, true);
// }
// }
List extractArguments() {
ArrayList result = new ArrayList();
String[] cmds = command.getArguments();
if (!LangUtil.isEmpty(cmds)) {
result.addAll(Arrays.asList(cmds));
}
return result;
}
/**
* Adjust args for size if necessary by creating
* an argument file, which should be deleted by the client
* after the compiler run has completed.
* @param max the int maximum length of the command line (in char)
* @return the temp File for the arguments (if generated),
* for deletion when done.
* @throws IllegalArgumentException if max is negative
*/
static String[] limitTo(String[] args, int max,
Location location) {
if (max < 0) {
throw new IllegalArgumentException("negative max: " + max);
}
// sigh - have to count anyway for now
int size = 0;
for (int i = 0; (i < args.length) && (size < max); i++) {
size += 1 + (null == args[i] ? 0 : args[i].length());
}
if (size <= max) {
return args;
}
File tmpFile = null;
PrintWriter out = null;
// adapted from DefaultCompilerAdapter.executeExternalCompile
try {
String userDirName = System.getProperty("user.dir");
File userDir = new File(userDirName);
tmpFile = File.createTempFile("argfile", "", userDir);
out = new PrintWriter(new FileWriter(tmpFile));
for (int i = 0; i < args.length; i++) {
out.println(args[i]);
}
out.flush();
return new String[] {"-argfile", tmpFile.getAbsolutePath()};
} catch (IOException e) {
throw new BuildException("Error creating temporary file",
e, location);
} finally {
if (out != null) {
try {out.close();} catch (Throwable t) {}
}
}
}
}
private static class AntMessageHandler implements IMessageHandler {
private TaskLogger logger;
private final boolean taskLevelVerbose;
private final boolean handledMessage;
public AntMessageHandler(TaskLogger logger, boolean taskVerbose, boolean handledMessage) {
this.logger = logger;
this.taskLevelVerbose = taskVerbose;
this.handledMessage = handledMessage;
}
/* (non-Javadoc)
* @see org.aspectj.bridge.IMessageHandler#handleMessage(org.aspectj.bridge.IMessage)
*/
public boolean handleMessage(IMessage message) throws AbortException {
Kind messageKind = message.getKind();
String messageText = message.toString();
if (messageKind == IMessage.ABORT) {
this.logger.error(messageText);
} else if (messageKind == IMessage.DEBUG) {
this.logger.debug(messageText);
} else if (messageKind == IMessage.ERROR) {
this.logger.error(messageText);
} else if (messageKind == IMessage.FAIL){
this.logger.error(messageText);
} else if (messageKind == IMessage.INFO) {
if (this.taskLevelVerbose) {
this.logger.info(messageText);
}
else {
this.logger.verbose(messageText);
}
} else if (messageKind == IMessage.WARNING) {
this.logger.warning(messageText);
} else if (messageKind == IMessage.WEAVEINFO) {
this.logger.info(messageText);
} else if (messageKind == IMessage.TASKTAG) {
// ignore
} else {
throw new BuildException("Unknown message kind from AspectJ compiler: " + messageKind.toString());
}
return handledMessage;
}
/* (non-Javadoc)
* @see org.aspectj.bridge.IMessageHandler#isIgnoring(org.aspectj.bridge.IMessage.Kind)
*/
public boolean isIgnoring(Kind kind) {
return false;
}
/* (non-Javadoc)
* @see org.aspectj.bridge.IMessageHandler#dontIgnore(org.aspectj.bridge.IMessage.Kind)
*/
public void dontIgnore(Kind kind) {
}
}
}
|
138,286 |
Bug 138286 perthis() causes ClassCastException
|
When using perthis() with an aspect, I see the following Internal Compiler AJDT 1.3.1 / AspectJ 1.5.1a Build 20060406092046 Eclipse 3.1.2, Windows XP, JDK 1.5 Error: java.lang.ClassCastException at org.aspectj.weaver.patterns.PerThisOrTargetPointcutVisitor.getPerTypePointcut(PerThisOrTargetPointcutVisitor.java:41) at org.aspectj.weaver.patterns.PerThisOrTargetPointcutVisitor.visit(PerThisOrTargetPointcutVisitor.java:108) at org.aspectj.weaver.patterns.AndPointcut.accept(AndPointcut.java:119) at org.aspectj.weaver.patterns.PerThisOrTargetPointcutVisitor.getPerTypePointcut(PerThisOrTargetPointcutVisitor.java:41) at org.aspectj.weaver.PerObjectInterfaceTypeMunger.getTestTypePattern(PerObjectInterfaceTypeMunger.java:64) at org.aspectj.weaver.PerObjectInterfaceTypeMunger.matches(PerObjectInterfaceTypeMunger.java:85) at org.aspectj.weaver.ConcreteTypeMunger.matches(ConcreteTypeMunger.java:65) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:508) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:109) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1560) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1511) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1291) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1089) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:311) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:183) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:242) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:161) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:278) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:168) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) trouble in: public abstract class org.apache.tapestry.internal.aspects.AbstractClassTargetting extends java.lang.Object: public void <init>(): ALOAD_0 // Lorg/apache/tapestry/internal/aspects/AbstractClassTargetting; this (line 10) INVOKESPECIAL java.lang.Object.<init> ()V initialization(void org.apache.tapestry.internal.aspects.AbstractClassTargetting.<init>()) | ALOAD_0 | INVOKEVIRTUAL java.lang.Object.getClass ()Ljava/lang/Class; | LDC org.apache.tapestry.internal.annotations.Synchronized | INVOKEVIRTUAL java.lang.Class.isAnnotationPresent (Ljava/lang/Class;)Z | IFEQ L0 | ALOAD_0 | INVOKESTATIC org.apache.tapestry.internal.aspects.InternalSynchronization.ajc$perObjectBind (Ljava/lang/Object;)V | constructor-execution(void org.apache.tapestry.internal.aspects.AbstractClassTargetting.<init>()) | | L0: ALOAD_0 | | INVOKEVIRTUAL java.lang.Object.getClass ()Ljava/lang/Class; | | LDC org.apache.tapestry.internal.annotations.Synchronized | | INVOKEVIRTUAL java.lang.Class.isAnnotationPresent (Ljava/lang/Class;)Z | | IFEQ L1 | | ALOAD_0 | | INVOKESTATIC org.apache.tapestry.internal.aspects.InternalSynchronization.ajc$perObjectBind (Ljava/lang/Object;)V | | L1: RETURN | constructor-execution(void org.apache.tapestry.internal.aspects.AbstractClassTargetting.<init>()) initialization(void org.apache.tapestry.internal.aspects.AbstractClassTargetting.<init>()) end public void <init>() abstract void ajc$pointcut$$targetClasses$274() org.aspectj.weaver.MethodDeclarationLineNumber: 16:628 ; end public abstract class org.apache.tapestry.internal.aspects.AbstractClassTargetting when weaving type org.apache.tapestry.internal.aspects.AbstractClassTargetting when weaving aspects when weaving when batch building BuildConfig[C:\workspace\.metadata\.plugins\org.eclipse.ajdt.core\tapestry5.generated.lst] #Files=70 I'll attach the corresponding files.
|
resolved fixed
|
c667bcb
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-04-26T16:45:17Z | 2006-04-24T23:06:40Z |
tests/src/org/aspectj/systemtest/ajc152/Ajc152Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc152;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc152Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public void testNotAtWithincode_pr138158_1() { runTest("not at withincode - 1");}
public void testNotAtWithincode_pr138158_2() { runTest("not at withincode - 2");}
public void testNotAtWithincode_pr138158_3() { runTest("not at within - 3");}
// public void testComplexGenericDecl_pr137568() { runTest("complicated generics declaration");}
public void testNpeOnDup_pr138143() { runTest("npe on duplicate method with ataj");}
public void testPointcutsAndGenerics_pr137496_1() { runTest("pointcuts and generics - B");}
public void testPointcutsAndGenerics_pr137496_2() { runTest("pointcuts and generics - D");}
public void testPointcutsAndGenerics_pr137496_3() { runTest("pointcuts and generics - E");}
public void testPointcutsAndGenerics_pr137496_4() { runTest("pointcuts and generics - F");}
public void testPointcutsAndGenerics_pr137496_5() { runTest("pointcuts and generics - G");}
public void testPointcutsAndGenerics_pr137496_6() { runTest("pointcuts and generics - H");}
public void testAspectLibrariesAndASM_pr135001() { runTest("aspect libraries and asm");}
public void testStackOverflow_pr136258() { runTest("stack overflow");}
public void testIncorrectOverridesEvaluation13() { runTest("incorrect overrides evaluation - 1.3"); }
public void testIncorrectOverridesEvaluation15() { runTest("incorrect overrides evaluation - 1.5"); }
// known failures, uncomment when working.
public void testReferencePCutInDeclareWarning_pr138215() { runTest("Reference pointcut fails inside @DeclareWarning");}
// public void testReferencePCutInPerClause_pr138219() { runTest("Can't use a FQ Reference pointcut in any pointcut expression referenced by a per-clause");}
// public void testDoubleAnnotationMatching_pr138223() { runTest("Double at annotation matching (no binding)");}
// this next one reported as a bug by Rob Harrop, but I can't reproduce the failure yet...
//public void testAtAspectWithReferencePCPerClause_pr138220() { runTest("@Aspect with reference pointcut in perclause");}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc152Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc152/ajc152.xml");
}
}
|
138,286 |
Bug 138286 perthis() causes ClassCastException
|
When using perthis() with an aspect, I see the following Internal Compiler AJDT 1.3.1 / AspectJ 1.5.1a Build 20060406092046 Eclipse 3.1.2, Windows XP, JDK 1.5 Error: java.lang.ClassCastException at org.aspectj.weaver.patterns.PerThisOrTargetPointcutVisitor.getPerTypePointcut(PerThisOrTargetPointcutVisitor.java:41) at org.aspectj.weaver.patterns.PerThisOrTargetPointcutVisitor.visit(PerThisOrTargetPointcutVisitor.java:108) at org.aspectj.weaver.patterns.AndPointcut.accept(AndPointcut.java:119) at org.aspectj.weaver.patterns.PerThisOrTargetPointcutVisitor.getPerTypePointcut(PerThisOrTargetPointcutVisitor.java:41) at org.aspectj.weaver.PerObjectInterfaceTypeMunger.getTestTypePattern(PerObjectInterfaceTypeMunger.java:64) at org.aspectj.weaver.PerObjectInterfaceTypeMunger.matches(PerObjectInterfaceTypeMunger.java:85) at org.aspectj.weaver.ConcreteTypeMunger.matches(ConcreteTypeMunger.java:65) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:508) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:109) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1560) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1511) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1291) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1089) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:311) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:183) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:242) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:161) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:278) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:168) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) trouble in: public abstract class org.apache.tapestry.internal.aspects.AbstractClassTargetting extends java.lang.Object: public void <init>(): ALOAD_0 // Lorg/apache/tapestry/internal/aspects/AbstractClassTargetting; this (line 10) INVOKESPECIAL java.lang.Object.<init> ()V initialization(void org.apache.tapestry.internal.aspects.AbstractClassTargetting.<init>()) | ALOAD_0 | INVOKEVIRTUAL java.lang.Object.getClass ()Ljava/lang/Class; | LDC org.apache.tapestry.internal.annotations.Synchronized | INVOKEVIRTUAL java.lang.Class.isAnnotationPresent (Ljava/lang/Class;)Z | IFEQ L0 | ALOAD_0 | INVOKESTATIC org.apache.tapestry.internal.aspects.InternalSynchronization.ajc$perObjectBind (Ljava/lang/Object;)V | constructor-execution(void org.apache.tapestry.internal.aspects.AbstractClassTargetting.<init>()) | | L0: ALOAD_0 | | INVOKEVIRTUAL java.lang.Object.getClass ()Ljava/lang/Class; | | LDC org.apache.tapestry.internal.annotations.Synchronized | | INVOKEVIRTUAL java.lang.Class.isAnnotationPresent (Ljava/lang/Class;)Z | | IFEQ L1 | | ALOAD_0 | | INVOKESTATIC org.apache.tapestry.internal.aspects.InternalSynchronization.ajc$perObjectBind (Ljava/lang/Object;)V | | L1: RETURN | constructor-execution(void org.apache.tapestry.internal.aspects.AbstractClassTargetting.<init>()) initialization(void org.apache.tapestry.internal.aspects.AbstractClassTargetting.<init>()) end public void <init>() abstract void ajc$pointcut$$targetClasses$274() org.aspectj.weaver.MethodDeclarationLineNumber: 16:628 ; end public abstract class org.apache.tapestry.internal.aspects.AbstractClassTargetting when weaving type org.apache.tapestry.internal.aspects.AbstractClassTargetting when weaving aspects when weaving when batch building BuildConfig[C:\workspace\.metadata\.plugins\org.eclipse.ajdt.core\tapestry5.generated.lst] #Files=70 I'll attach the corresponding files.
|
resolved fixed
|
c667bcb
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-04-26T16:45:17Z | 2006-04-24T23:06:40Z |
weaver/src/org/aspectj/weaver/patterns/PerThisOrTargetPointcutVisitor.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
*******************************************************************************/
package org.aspectj.weaver.patterns;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedType;
/**
* A visitor that turns a pointcut into a type pattern equivalent for a perthis or pertarget matching:
* - pertarget(target(Foo)) => Foo+ (this one is a special case..)
* - pertarget(execution(* Foo.do()) => Foo
* - perthis(call(* Foo.do()) => *
* - perthis(!call(* Foo.do()) => * (see how the ! has been absorbed here..)
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class PerThisOrTargetPointcutVisitor extends IdentityPointcutVisitor {
/** A maybe marker */
private final static TypePattern MAYBE = new TypePatternMayBe();
private final boolean m_isTarget;
private final ResolvedType m_fromAspectType;
public PerThisOrTargetPointcutVisitor(boolean isTarget, ResolvedType fromAspectType) {
m_isTarget = isTarget;
m_fromAspectType = fromAspectType;
}
public TypePattern getPerTypePointcut(Pointcut perClausePointcut) {
return (TypePattern) perClausePointcut.accept(this, perClausePointcut);
}
//-- visitor methods, all is like Identity visitor except when it comes to transform pointcuts
public Object visit(WithinPointcut node, Object data) {
if (m_isTarget) {
//pertarget(.. && within(Foo)) => true
//pertarget(.. && !within(Foo)) => true as well !
return MAYBE;
} else {
return node.getTypePattern();
}
}
public Object visit(WithincodePointcut node, Object data) {
if (m_isTarget) {
//pertarget(.. && withincode(* Foo.do())) => true
//pertarget(.. && !withincode(* Foo.do())) => true as well !
return MAYBE;
} else {
return node.getSignature().getDeclaringType();
}
}
public Object visit(WithinAnnotationPointcut node, Object data) {
if (m_isTarget) {
return MAYBE;
} else {
return node.getAnnotationTypePattern();
}
}
public Object visit(WithinCodeAnnotationPointcut node, Object data) {
if (m_isTarget) {
return MAYBE;
} else {
return MAYBE;//FIXME AV - can we optimize ? perthis(@withincode(Foo)) = hasmethod(..)
}
}
public Object visit(KindedPointcut node, Object data) {
if (node.getKind().equals(Shadow.AdviceExecution)) {
return MAYBE;//TODO AV - can we do better ?
} else if (node.getKind().equals(Shadow.ConstructorExecution)
|| node.getKind().equals(Shadow.Initialization)
|| node.getKind().equals(Shadow.MethodExecution)
|| node.getKind().equals(Shadow.PreInitialization)
|| node.getKind().equals(Shadow.StaticInitialization)) {
return node.getSignature().getDeclaringType();
} else if (node.getKind().equals(Shadow.ConstructorCall)
|| node.getKind().equals(Shadow.FieldGet)
|| node.getKind().equals(Shadow.FieldSet)
|| node.getKind().equals(Shadow.MethodCall)) {
if (m_isTarget) {
return node.getSignature().getDeclaringType();
} else {
return MAYBE;
}
} else if (node.getKind().equals(Shadow.ExceptionHandler)) {
return MAYBE;
} else {
throw new ParserException("Undetermined - should not happen: " + node.getKind().getSimpleName(), null);
}
}
public Object visit(AndPointcut node, Object data) {
return new AndTypePattern(getPerTypePointcut(node.left), getPerTypePointcut(node.right));
}
public Object visit(OrPointcut node, Object data) {
return new OrTypePattern(getPerTypePointcut(node.left), getPerTypePointcut(node.right));
}
public Object visit(NotPointcut node, Object data) {
// TypePattern negated = getPerTypePointcut(node.getNegatedPointcut());
// if (MAYBE.equals(negated)) {
// return MAYBE;
// }
// return new NotTypePattern(negated);
// AMC - the only safe thing to return here is maybe...
// see for example pr114054
return MAYBE;
}
public Object visit(ThisOrTargetAnnotationPointcut node, Object data) {
if (m_isTarget && !node.isThis()) {
return node.getAnnotationTypePattern();
} else if (!m_isTarget && node.isThis()) {
return node.getAnnotationTypePattern();
} else {
// perthis(@target(Foo))
return MAYBE;
}
}
public Object visit(ThisOrTargetPointcut node, Object data) {
if ((m_isTarget && !node.isThis())
|| (!m_isTarget && node.isThis())) {
String pointcutString = node.getType().toString();
// see pr115788 "<nothing>" means there was a problem resolving types - that will be reported so dont blow up
// the parser here..
if (pointcutString.equals("<nothing>")) {
return new NoTypePattern();
}
//pertarget(target(Foo)) => Foo+ for type pattern matching
//perthis(this(Foo)) => Foo+ for type pattern matching
// TODO AV - we do like a deep copy by parsing it again.. quite dirty, would need a clean deep copy
TypePattern copy = new PatternParser(pointcutString.replace('$', '.')).parseTypePattern();
// TODO AV - see dirty replace from $ to . here as inner classes are with $ instead (#108488)
copy.includeSubtypes = true;
return copy;
} else {
// perthis(target(Foo)) => maybe
return MAYBE;
}
}
public Object visit(ReferencePointcut node, Object data) {
// && pc_ref()
// we know there is no support for binding in perClause: perthis(pc_ref(java.lang.String))
// TODO AV - may need some work for generics..
ResolvedPointcutDefinition pointcutDec;
ResolvedType searchStart = m_fromAspectType;
if (node.onType != null) {
searchStart = node.onType.resolve(m_fromAspectType.getWorld());
if (searchStart.isMissing()) {
return MAYBE;// this should not happen since concretize will fails but just in case..
}
}
pointcutDec = searchStart.findPointcut(node.name);
return getPerTypePointcut(pointcutDec.getPointcut());
}
public Object visit(IfPointcut node, Object data) {
return TypePattern.ANY;
}
public Object visit(HandlerPointcut node, Object data) {
// quiet unexpected since a KindedPointcut but do as if...
return MAYBE;
}
public Object visit(CflowPointcut node, Object data) {
return MAYBE;
}
public Object visit(ConcreteCflowPointcut node, Object data) {
return MAYBE;
}
public Object visit(ArgsPointcut node, Object data) {
return MAYBE;
}
public Object visit(ArgsAnnotationPointcut node, Object data) {
return MAYBE;
}
public Object visit(AnnotationPointcut node, Object data) {
return MAYBE;
}
public Object visit(Pointcut.MatchesNothingPointcut node, Object data) {
// a small hack since the usual MatchNothing has its toString = "<nothing>" which is not parseable back
// while I use back parsing for check purpose.
return new NoTypePattern() {
public String toString() {
return "false";
}
};
}
/**
* A MayBe type pattern that acts as ANY except that !MAYBE = MAYBE
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
private static class TypePatternMayBe extends AnyTypePattern {
}
}
|
138,798 |
Bug 138798 BCException on invalid annotation match
|
This unfortunately invalid code: before(Throwable throwable, NormalException normalException) : handler(*) && args(throwable) && @withincode(normalException) { ... Generates this exception in AJDT with post-1.5.1a AspectJ org.aspectj.weaver.BCException at org.aspectj.weaver.bcel.BcelRenderer.visit(BcelRenderer.java:237) at org.aspectj.weaver.ast.Literal.accept(Literal.java:29) at org.aspectj.weaver.bcel.BcelRenderer.recur(BcelRenderer.java:153) at org.aspectj.weaver.bcel.BcelRenderer.renderTest(BcelRenderer.java:119) at org.aspectj.weaver.bcel.BcelAdvice.getTestInstructions(BcelAdvice.java:537) at org.aspectj.weaver.bcel.BcelAdvice.getAdviceInstructions(BcelAdvice.java:376) at org.aspectj.weaver.bcel.BcelShadow.weaveBefore(BcelShadow.java:1690) at org.aspectj.weaver.bcel.BcelAdvice.implementOn(BcelAdvice.java:208) at org.aspectj.weaver.Shadow.implementMungers(Shadow.java:639) at org.aspectj.weaver.Shadow.implement(Shadow.java:456) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2236) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:491) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:109) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1560) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1511) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1291) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1113) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:311) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:183) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:862) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:242) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:161) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) trouble in: public class glassbox.client.ConnectionManager extends java.lang.Object: public static String propnameNum public static String propnameDefault public static String propnameViewed public static String propnameNickPrefix public static String propnameUrlPrefix public static String propnameViewedPrefix private static String propFilename private static String localhostNickname public static String localhostURL private java.util.List connectionList [Signature(Ljava/util/List<Lglassbox/client/ConnectionManager$AgentConnection;>;)] private int defaultConnectionIndex private static final org.aspectj.lang.JoinPoint$StaticPart ajc$tjp_0 static void <clinit>(): staticinitialization(void glassbox.client.ConnectionManager.<clinit>()) | LDC "glassbox.connections.num" (line 13) | PUTSTATIC glassbox.client.ConnectionManager.propnameNum Ljava/lang/String; | LDC "glassbox.connections.default" (line 14) | PUTSTATIC glassbox.client.ConnectionManager.propnameDefault Ljava/lang/String; | LDC "glassbox.connections.viewed" (line 15) | PUTSTATIC glassbox.client.ConnectionManager.propnameViewed Ljava/lang/String; | LDC "glassbox.connections.nickname_" (line 16) | PUTSTATIC glassbox.client.ConnectionManager.propnameNickPrefix Ljava/lang/String; | LDC "glassbox.connections.url_" (line 17) | PUTSTATIC glassbox.client.ConnectionManager.propnameUrlPrefix Ljava/lang/String; | LDC "glassbox.connections.viewed_" (line 18) | PUTSTATIC glassbox.client.ConnectionManager.propnameViewedPrefix Ljava/lang/String; | LDC "connection.properties" (line 20) | PUTSTATIC glassbox.client.ConnectionManager.propFilename Ljava/lang/String; | LDC "localhost" (line 21) | PUTSTATIC glassbox.client.ConnectionManager.localhostNickname Ljava/lang/String; | LDC "service:jmx:rmi://localhost:7131/jndi/rmi://localhost:7132/GlassboxTroubleshooter" (line 22) | PUTSTATIC glassbox.client.ConnectionManager.localhostURL Ljava/lang/String; | RETURN (line 11) staticinitialization(void glassbox.client.ConnectionManager.<clinit>()) end static void <clinit>() public void <init>() org.aspectj.weaver.MethodDeclarationLineNumber: 23:966 : ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 23) INVOKESPECIAL java.lang.Object.<init> ()V constructor-execution(void glassbox.client.ConnectionManager.<init>()) | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 24) | INVOKEVIRTUAL glassbox.client.ConnectionManager.init ()V | RETURN (line 25) constructor-execution(void glassbox.client.ConnectionManager.<init>()) end public void <init>() public void init() org.aspectj.weaver.MethodDeclarationLineNumber: 67:1992 : method-execution(void glassbox.client.ConnectionManager.init()) | catch java.lang.RuntimeException -> E0 | | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 69) | | INVOKEVIRTUAL glassbox.client.ConnectionManager.readFromFile ()V | | GOTO L0 | catch java.lang.RuntimeException -> E0 | E0: ASTORE_2 | exception-handler(void glassbox.client.ConnectionManager.<catch>(java.lang.RuntimeException)) | | ALOAD_2 | exception-handler(void glassbox.client.ConnectionManager.<catch>(java.lang.RuntimeException)) | ASTORE_1 (line 70) | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 71) | INVOKEVIRTUAL glassbox.client.ConnectionManager.createDefaultList ()V | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 72) | INVOKEVIRTUAL glassbox.client.ConnectionManager.writeToFile ()V | L0: RETURN (line 74) method-execution(void glassbox.client.ConnectionManager.init()) end public void init() public void createDefaultList() org.aspectj.weaver.MethodDeclarationLineNumber: 76:2134 : method-execution(void glassbox.client.ConnectionManager.createDefaultList()) | NEW glassbox.client.ConnectionManager$AgentConnection (line 77) | DUP | ALOAD_0 // Lglassbox/client/ConnectionManager; this | GETSTATIC glassbox.client.ConnectionManager.localhostNickname Ljava/lang/String; | GETSTATIC glassbox.client.ConnectionManager.localhostURL Ljava/lang/String; | ICONST_1 | INVOKESPECIAL glassbox.client.ConnectionManager$AgentConnection.<init> (Lglassbox/client/ConnectionManager;Ljava/lang/String;Ljava/lang/String;Z)V | ASTORE_1 | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 78) | NEW java.util.ArrayList | DUP | INVOKESPECIAL java.util.ArrayList.<init> ()V | PUTFIELD glassbox.client.ConnectionManager.connectionList Ljava/util/List; | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 79) | GETFIELD glassbox.client.ConnectionManager.connectionList Ljava/util/List; | ALOAD_1 // Lglassbox/client/ConnectionManager$AgentConnection; localhost | INVOKEINTERFACE java.util.List.add (Ljava/lang/Object;)Z | POP | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 80) | ICONST_0 | PUTFIELD glassbox.client.ConnectionManager.defaultConnectionIndex I | RETURN (line 81) method-execution(void glassbox.client.ConnectionManager.createDefaultList()) end public void createDefaultList() public void writeToFile() org.aspectj.weaver.MethodDeclarationLineNumber: 84:2433 : method-execution(void glassbox.client.ConnectionManager.writeToFile()) | NEW java.util.Properties (line 85) | DUP | INVOKESPECIAL java.util.Properties.<init> ()V | ASTORE_1 | ALOAD_1 // Ljava/util/Properties; properties (line 86) | GETSTATIC glassbox.client.ConnectionManager.propnameNum Ljava/lang/String; | ALOAD_0 // Lglassbox/client/ConnectionManager; this | GETFIELD glassbox.client.ConnectionManager.connectionList Ljava/util/List; | INVOKEINTERFACE java.util.List.size ()I | INVOKESTATIC java.lang.String.valueOf (I)Ljava/lang/String; | INVOKEVIRTUAL java.util.Properties.setProperty (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object; | POP | ALOAD_1 // Ljava/util/Properties; properties (line 87) | GETSTATIC glassbox.client.ConnectionManager.propnameDefault Ljava/lang/String; | ALOAD_0 // Lglassbox/client/ConnectionManager; this | GETFIELD glassbox.client.ConnectionManager.connectionList Ljava/util/List; | ALOAD_0 // Lglassbox/client/ConnectionManager; this | GETFIELD glassbox.client.ConnectionManager.defaultConnectionIndex I | INVOKEINTERFACE java.util.List.get (I)Ljava/lang/Object; | CHECKCAST glassbox.client.ConnectionManager$AgentConnection | INVOKEVIRTUAL glassbox.client.ConnectionManager$AgentConnection.getNickname ()Ljava/lang/String; | INVOKEVIRTUAL java.util.Properties.setProperty (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object; | POP | ICONST_0 (line 88) | ISTORE_2 | GOTO L1 | L0: ALOAD_1 // Ljava/util/Properties; properties (line 89) | NEW java.lang.StringBuilder | DUP | GETSTATIC glassbox.client.ConnectionManager.propnameNickPrefix Ljava/lang/String; | INVOKESTATIC java.lang.String.valueOf (Ljava/lang/Object;)Ljava/lang/String; | INVOKESPECIAL java.lang.StringBuilder.<init> (Ljava/lang/String;)V | ILOAD_2 // I i | INVOKEVIRTUAL java.lang.StringBuilder.append (I)Ljava/lang/StringBuilder; | INVOKEVIRTUAL java.lang.StringBuilder.toString ()Ljava/lang/String; | ALOAD_0 // Lglassbox/client/ConnectionManager; this | GETFIELD glassbox.client.ConnectionManager.connectionList Ljava/util/List; | ILOAD_2 // I i | INVOKEINTERFACE java.util.List.get (I)Ljava/lang/Object; | CHECKCAST glassbox.client.ConnectionManager$AgentConnection | INVOKEVIRTUAL glassbox.client.ConnectionManager$AgentConnection.getNickname ()Ljava/lang/String; | INVOKEVIRTUAL java.util.Properties.setProperty (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object; | POP | ALOAD_1 // Ljava/util/Properties; properties (line 90) | NEW java.lang.StringBuilder | DUP | GETSTATIC glassbox.client.ConnectionManager.propnameUrlPrefix Ljava/lang/String; | INVOKESTATIC java.lang.String.valueOf (Ljava/lang/Object;)Ljava/lang/String; | INVOKESPECIAL java.lang.StringBuilder.<init> (Ljava/lang/String;)V | ILOAD_2 // I i | INVOKEVIRTUAL java.lang.StringBuilder.append (I)Ljava/lang/StringBuilder; | INVOKEVIRTUAL java.lang.StringBuilder.toString ()Ljava/lang/String; | ALOAD_0 // Lglassbox/client/ConnectionManager; this | GETFIELD glassbox.client.ConnectionManager.connectionList Ljava/util/List; | ILOAD_2 // I i | INVOKEINTERFACE java.util.List.get (I)Ljava/lang/Object; | CHECKCAST glassbox.client.ConnectionManager$AgentConnection | INVOKEVIRTUAL glassbox.client.ConnectionManager$AgentConnection.getUrl ()Ljava/lang/String; | INVOKEVIRTUAL java.util.Properties.setProperty (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object; | POP | ALOAD_1 // Ljava/util/Properties; properties (line 91) | NEW java.lang.StringBuilder | DUP | GETSTATIC glassbox.client.ConnectionManager.propnameViewedPrefix Ljava/lang/String; | INVOKESTATIC java.lang.String.valueOf (Ljava/lang/Object;)Ljava/lang/String; | INVOKESPECIAL java.lang.StringBuilder.<init> (Ljava/lang/String;)V | ILOAD_2 // I i | INVOKEVIRTUAL java.lang.StringBuilder.append (I)Ljava/lang/StringBuilder; | INVOKEVIRTUAL java.lang.StringBuilder.toString ()Ljava/lang/String; | ALOAD_0 // Lglassbox/client/ConnectionManager; this | GETFIELD glassbox.client.ConnectionManager.connectionList Ljava/util/List; | ILOAD_2 // I i | INVOKEINTERFACE java.util.List.get (I)Ljava/lang/Object; | CHECKCAST glassbox.client.ConnectionManager$AgentConnection | INVOKEVIRTUAL glassbox.client.ConnectionManager$AgentConnection.isViewed ()Z | INVOKESTATIC java.lang.String.valueOf (Z)Ljava/lang/String; | INVOKEVIRTUAL java.util.Properties.setProperty (Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object; | POP | IINC 2 1 // I i (line 88) | L1: ILOAD_2 // I i | ALOAD_0 // Lglassbox/client/ConnectionManager; this | GETFIELD glassbox.client.ConnectionManager.connectionList Ljava/util/List; | INVOKEINTERFACE java.util.List.size ()I | IF_ICMPLT L0 | catch java.io.IOException -> E0 | | NEW java.io.File (line 94) | | DUP | | GETSTATIC glassbox.client.ConnectionManager.propFilename Ljava/lang/String; | | INVOKESPECIAL java.io.File.<init> (Ljava/lang/String;)V | | ASTORE_2 | | NEW java.io.FileOutputStream (line 95) | | DUP | | ALOAD_2 // Ljava/io/File; f | | ICONST_0 | | INVOKESPECIAL java.io.FileOutputStream.<init> (Ljava/io/File;Z)V | | ASTORE_3 | | ALOAD_1 // Ljava/util/Properties; properties (line 96) | | ALOAD_3 // Ljava/io/FileOutputStream; fos | | ACONST_NULL | | INVOKEVIRTUAL java.util.Properties.store (Ljava/io/OutputStream;Ljava/lang/String;)V | | ALOAD_3 // Ljava/io/FileOutputStream; fos (line 97) | | INVOKEVIRTUAL java.io.FileOutputStream.close ()V | | GOTO L2 | catch java.io.IOException -> E0 | E0: ASTORE_2 (line 98) | GETSTATIC java.lang.System.err Ljava/io/PrintStream; (line 99) | LDC "Failed to write connection.properties file" | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | GETSTATIC java.lang.System.err Ljava/io/PrintStream; (line 100) | ALOAD_2 // Ljava/io/IOException; e | INVOKEVIRTUAL java.io.IOException.toString ()Ljava/lang/String; | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | L2: RETURN (line 102) method-execution(void glassbox.client.ConnectionManager.writeToFile()) end public void writeToFile() public void readFromFile() org.aspectj.weaver.MethodDeclarationLineNumber: 105:3495 : method-execution(void glassbox.client.ConnectionManager.readFromFile()) | NEW java.util.ArrayList (line 107) | DUP | INVOKESPECIAL java.util.ArrayList.<init> ()V | ASTORE_1 | NEW java.util.Properties (line 108) | DUP | INVOKESPECIAL java.util.Properties.<init> ()V | ASTORE_2 | NEW java.io.File (line 110) | DUP | GETSTATIC glassbox.client.ConnectionManager.propFilename Ljava/lang/String; | INVOKESPECIAL java.io.File.<init> (Ljava/lang/String;)V | ASTORE 4 | catch java.io.IOException -> E0 | | ALOAD_2 // Ljava/util/Properties; properties (line 112) | | NEW java.io.FileInputStream | | DUP | | ALOAD 4 // Ljava/io/File; f | | INVOKESPECIAL java.io.FileInputStream.<init> (Ljava/io/File;)V | | INVOKEVIRTUAL java.util.Properties.load (Ljava/io/InputStream;)V | | GOTO L0 | catch java.io.IOException -> E0 | E0: ASTORE 5 (line 113) | NEW java.lang.RuntimeException (line 116) | DUP | NEW java.lang.StringBuilder | DUP | LDC "Can't open " | INVOKESPECIAL java.lang.StringBuilder.<init> (Ljava/lang/String;)V | ALOAD 4 // Ljava/io/File; f | INVOKEVIRTUAL java.io.File.getAbsolutePath ()Ljava/lang/String; | INVOKEVIRTUAL java.lang.StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder; | INVOKEVIRTUAL java.lang.StringBuilder.toString ()Ljava/lang/String; | INVOKESPECIAL java.lang.RuntimeException.<init> (Ljava/lang/String;)V | ATHROW | catch java.lang.Exception -> E1 | | L0: ALOAD_2 // Ljava/util/Properties; properties (line 119) | | GETSTATIC glassbox.client.ConnectionManager.propnameNum Ljava/lang/String; | | INVOKEVIRTUAL java.util.Properties.getProperty (Ljava/lang/String;)Ljava/lang/String; | | INVOKESTATIC java.lang.Integer.valueOf (Ljava/lang/String;)Ljava/lang/Integer; | | INVOKEVIRTUAL java.lang.Integer.intValue ()I | | ISTORE 5 | | ALOAD_2 // Ljava/util/Properties; properties (line 120) | | GETSTATIC glassbox.client.ConnectionManager.propnameDefault Ljava/lang/String; | | INVOKEVIRTUAL java.util.Properties.getProperty (Ljava/lang/String;)Ljava/lang/String; | | ASTORE 6 | | ALOAD 6 // Ljava/lang/String; defNickname (line 121) | | IFNONNULL L1 | | NEW java.lang.RuntimeException | | DUP | | NEW java.lang.StringBuilder | | DUP | | LDC "missing " | | INVOKESPECIAL java.lang.StringBuilder.<init> (Ljava/lang/String;)V | | GETSTATIC glassbox.client.ConnectionManager.propnameDefault Ljava/lang/String; | | INVOKEVIRTUAL java.lang.StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder; | | INVOKEVIRTUAL java.lang.StringBuilder.toString ()Ljava/lang/String; | | INVOKESPECIAL java.lang.RuntimeException.<init> (Ljava/lang/String;)V | | ATHROW | | L1: ILOAD 5 // I num (line 122) | | ICONST_1 | | IF_ICMPGE L2 | | NEW java.lang.RuntimeException | | DUP | | NEW java.lang.StringBuilder | | DUP | | LDC "Bad " | | INVOKESPECIAL java.lang.StringBuilder.<init> (Ljava/lang/String;)V | | GETSTATIC glassbox.client.ConnectionManager.propnameNum Ljava/lang/String; | | INVOKEVIRTUAL java.lang.StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder; | | LDC "=" | | INVOKEVIRTUAL java.lang.StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder; | | ILOAD 5 // I num | | INVOKEVIRTUAL java.lang.StringBuilder.append (I)Ljava/lang/StringBuilder; | | INVOKEVIRTUAL java.lang.StringBuilder.toString ()Ljava/lang/String; | | INVOKESPECIAL java.lang.RuntimeException.<init> (Ljava/lang/String;)V | | ATHROW | | L2: ICONST_0 (line 123) | | ISTORE 7 | | GOTO L9 | | L3: ALOAD_2 // Ljava/util/Properties; properties (line 124) | | NEW java.lang.StringBuilder | | DUP | | GETSTATIC glassbox.client.ConnectionManager.propnameNickPrefix Ljava/lang/String; | | INVOKESTATIC java.lang.String.valueOf (Ljava/lang/Object;)Ljava/lang/String; | | INVOKESPECIAL java.lang.StringBuilder.<init> (Ljava/lang/String;)V | | ILOAD 7 // I i | | INVOKEVIRTUAL java.lang.StringBuilder.append (I)Ljava/lang/StringBuilder; | | INVOKEVIRTUAL java.lang.StringBuilder.toString ()Ljava/lang/String; | | INVOKEVIRTUAL java.util.Properties.getProperty (Ljava/lang/String;)Ljava/lang/String; | | ASTORE 8 | | ALOAD 8 // Ljava/lang/String; nickname (line 125) | | IFNONNULL L4 | | NEW java.lang.RuntimeException | | DUP | | NEW java.lang.StringBuilder | | DUP | | LDC "missing " | | INVOKESPECIAL java.lang.StringBuilder.<init> (Ljava/lang/String;)V | | GETSTATIC glassbox.client.ConnectionManager.propnameNickPrefix Ljava/lang/String; | | INVOKEVIRTUAL java.lang.StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder; | | ILOAD 7 // I i | | INVOKEVIRTUAL java.lang.StringBuilder.append (I)Ljava/lang/StringBuilder; | | INVOKEVIRTUAL java.lang.StringBuilder.toString ()Ljava/lang/String; | | INVOKESPECIAL java.lang.RuntimeException.<init> (Ljava/lang/String;)V | | ATHROW | | L4: ALOAD_2 // Ljava/util/Properties; properties (line 126) | | NEW java.lang.StringBuilder | | DUP | | GETSTATIC glassbox.client.ConnectionManager.propnameUrlPrefix Ljava/lang/String; | | INVOKESTATIC java.lang.String.valueOf (Ljava/lang/Object;)Ljava/lang/String; | | INVOKESPECIAL java.lang.StringBuilder.<init> (Ljava/lang/String;)V | | ILOAD 7 // I i | | INVOKEVIRTUAL java.lang.StringBuilder.append (I)Ljava/lang/StringBuilder; | | INVOKEVIRTUAL java.lang.StringBuilder.toString ()Ljava/lang/String; | | INVOKEVIRTUAL java.util.Properties.getProperty (Ljava/lang/String;)Ljava/lang/String; | | ASTORE 9 | | ALOAD 9 // Ljava/lang/String; url (line 127) | | IFNONNULL L5 | | NEW java.lang.RuntimeException | | DUP | | NEW java.lang.StringBuilder | | DUP | | LDC "missing " | | INVOKESPECIAL java.lang.StringBuilder.<init> (Ljava/lang/String;)V | | GETSTATIC glassbox.client.ConnectionManager.propnameUrlPrefix Ljava/lang/String; | | INVOKEVIRTUAL java.lang.StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder; | | ILOAD 7 // I i | | INVOKEVIRTUAL java.lang.StringBuilder.append (I)Ljava/lang/StringBuilder; | | INVOKEVIRTUAL java.lang.StringBuilder.toString ()Ljava/lang/String; | | INVOKESPECIAL java.lang.RuntimeException.<init> (Ljava/lang/String;)V | | ATHROW | | L5: ALOAD_2 // Ljava/util/Properties; properties (line 128) | | NEW java.lang.StringBuilder | | DUP | | GETSTATIC glassbox.client.ConnectionManager.propnameViewedPrefix Ljava/lang/String; | | INVOKESTATIC java.lang.String.valueOf (Ljava/lang/Object;)Ljava/lang/String; | | INVOKESPECIAL java.lang.StringBuilder.<init> (Ljava/lang/String;)V | | ILOAD 7 // I i | | INVOKEVIRTUAL java.lang.StringBuilder.append (I)Ljava/lang/StringBuilder; | | INVOKEVIRTUAL java.lang.StringBuilder.toString ()Ljava/lang/String; | | INVOKEVIRTUAL java.util.Properties.getProperty (Ljava/lang/String;)Ljava/lang/String; | | ASTORE 10 | | ALOAD 10 // Ljava/lang/String; viewedStr (line 129) | | LDC "true" | | INVOKEVIRTUAL java.lang.String.contentEquals (Ljava/lang/CharSequence;)Z | | IFEQ L6 | | ICONST_1 | | GOTO L7 | | L6: ICONST_0 | | L7: ISTORE_3 | | ALOAD 9 // Ljava/lang/String; url (line 130) | | IFNONNULL L8 | | NEW java.lang.RuntimeException | | DUP | | NEW java.lang.StringBuilder | | DUP | | LDC "missing " | | INVOKESPECIAL java.lang.StringBuilder.<init> (Ljava/lang/String;)V | | GETSTATIC glassbox.client.ConnectionManager.propnameViewedPrefix Ljava/lang/String; | | INVOKEVIRTUAL java.lang.StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder; | | ILOAD 7 // I i | | INVOKEVIRTUAL java.lang.StringBuilder.append (I)Ljava/lang/StringBuilder; | | INVOKEVIRTUAL java.lang.StringBuilder.toString ()Ljava/lang/String; | | INVOKESPECIAL java.lang.RuntimeException.<init> (Ljava/lang/String;)V | | ATHROW | | L8: ALOAD_1 // Ljava/util/List; agcon (line 131) | | NEW glassbox.client.ConnectionManager$AgentConnection | | DUP | | ALOAD_0 // Lglassbox/client/ConnectionManager; this | | ALOAD 8 // Ljava/lang/String; nickname | | ALOAD 9 // Ljava/lang/String; url | | ILOAD_3 // Z viewed | | INVOKESPECIAL glassbox.client.ConnectionManager$AgentConnection.<init> (Lglassbox/client/ConnectionManager;Ljava/lang/String;Ljava/lang/String;Z)V | | INVOKEINTERFACE java.util.List.add (Ljava/lang/Object;)Z | | POP | | IINC 7 1 // I i (line 123) | | L9: ILOAD 7 // I i | | ILOAD 5 // I num | | IF_ICMPLT L3 | | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 133) | | ICONST_M1 | | PUTFIELD glassbox.client.ConnectionManager.defaultConnectionIndex I | | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 134) | | ALOAD_1 // Ljava/util/List; agcon | | PUTFIELD glassbox.client.ConnectionManager.connectionList Ljava/util/List; | | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 135) | | ALOAD 6 // Ljava/lang/String; defNickname | | INVOKEVIRTUAL glassbox.client.ConnectionManager.setAsDefault (Ljava/lang/String;)V | | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 136) | | GETFIELD glassbox.client.ConnectionManager.defaultConnectionIndex I | | ICONST_M1 | | IF_ICMPNE L10 | | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 137) | | ICONST_0 | | PUTFIELD glassbox.client.ConnectionManager.defaultConnectionIndex I | | GOTO L10 | catch java.lang.Exception -> E1 | E1: ASTORE 5 (line 140) | GETSTATIC java.lang.System.err Ljava/io/PrintStream; (line 141) | LDC "Failed to read connection.properties file" | INVOKEVIRTUAL java.io.PrintStream.println (Ljava/lang/String;)V | ALOAD 5 // Ljava/lang/Exception; e2 (line 142) | INVOKEVIRTUAL java.lang.Exception.printStackTrace ()V | NEW java.lang.RuntimeException (line 143) | DUP | ALOAD 5 // Ljava/lang/Exception; e2 | INVOKESPECIAL java.lang.RuntimeException.<init> (Ljava/lang/Throwable;)V | ATHROW | L10: RETURN (line 145) method-execution(void glassbox.client.ConnectionManager.readFromFile()) end public void readFromFile() public void delete(String) org.aspectj.weaver.MethodDeclarationLineNumber: 147:5452 : method-execution(void glassbox.client.ConnectionManager.delete(java.lang.String)) | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 148) | GETFIELD glassbox.client.ConnectionManager.connectionList Ljava/util/List; | INVOKEINTERFACE java.util.List.size ()I | ICONST_1 | IF_ICMPGT L0 | RETURN | L0: ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 149) | GETFIELD glassbox.client.ConnectionManager.connectionList Ljava/util/List; | INVOKEINTERFACE java.util.List.iterator ()Ljava/util/Iterator; | ASTORE_3 | GOTO L3 | L1: ALOAD_3 | INVOKEINTERFACE java.util.Iterator.next ()Ljava/lang/Object; | CHECKCAST glassbox.client.ConnectionManager$AgentConnection | ASTORE_2 | ALOAD_2 // Lglassbox/client/ConnectionManager$AgentConnection; con (line 151) | INVOKEVIRTUAL glassbox.client.ConnectionManager$AgentConnection.getNickname ()Ljava/lang/String; | ALOAD_1 // Ljava/lang/String; nickname | INVOKEVIRTUAL java.lang.String.equals (Ljava/lang/Object;)Z | IFEQ L3 | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 152) | GETFIELD glassbox.client.ConnectionManager.connectionList Ljava/util/List; | ALOAD_2 // Lglassbox/client/ConnectionManager$AgentConnection; con | INVOKEINTERFACE java.util.List.lastIndexOf (Ljava/lang/Object;)I | ALOAD_0 // Lglassbox/client/ConnectionManager; this | GETFIELD glassbox.client.ConnectionManager.defaultConnectionIndex I | IF_ICMPNE L2 | ALOAD_0 // Lglassbox/client/ConnectionManager; this | ICONST_0 | PUTFIELD glassbox.client.ConnectionManager.defaultConnectionIndex I | L2: ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 154) | GETFIELD glassbox.client.ConnectionManager.connectionList Ljava/util/List; | ALOAD_2 // Lglassbox/client/ConnectionManager$AgentConnection; con | INVOKEINTERFACE java.util.List.remove (Ljava/lang/Object;)Z | POP | GOTO L4 (line 155) | L3: ALOAD_3 (line 149) | INVOKEINTERFACE java.util.Iterator.hasNext ()Z | IFNE L1 | L4: RETURN (line 158) method-execution(void glassbox.client.ConnectionManager.delete(java.lang.String)) end public void delete(String) public void setAsDefault(String) org.aspectj.weaver.MethodDeclarationLineNumber: 160:5880 : method-execution(void glassbox.client.ConnectionManager.setAsDefault(java.lang.String)) | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 161) | GETFIELD glassbox.client.ConnectionManager.connectionList Ljava/util/List; | INVOKEINTERFACE java.util.List.iterator ()Ljava/util/Iterator; | ASTORE_3 | GOTO L1 | L0: ALOAD_3 | INVOKEINTERFACE java.util.Iterator.next ()Ljava/lang/Object; | CHECKCAST glassbox.client.ConnectionManager$AgentConnection | ASTORE_2 | ALOAD_2 // Lglassbox/client/ConnectionManager$AgentConnection; con (line 162) | INVOKEVIRTUAL glassbox.client.ConnectionManager$AgentConnection.getNickname ()Ljava/lang/String; | ALOAD_1 // Ljava/lang/String; nickname | INVOKEVIRTUAL java.lang.String.equals (Ljava/lang/Object;)Z | IFEQ L1 | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 163) | ALOAD_0 // Lglassbox/client/ConnectionManager; this | GETFIELD glassbox.client.ConnectionManager.connectionList Ljava/util/List; | ALOAD_2 // Lglassbox/client/ConnectionManager$AgentConnection; con | INVOKEINTERFACE java.util.List.lastIndexOf (Ljava/lang/Object;)I | PUTFIELD glassbox.client.ConnectionManager.defaultConnectionIndex I | ALOAD_2 // Lglassbox/client/ConnectionManager$AgentConnection; con (line 164) | ICONST_1 | INVOKEVIRTUAL glassbox.client.ConnectionManager$AgentConnection.setViewed (Z)V | GOTO L2 (line 165) | L1: ALOAD_3 (line 161) | INVOKEINTERFACE java.util.Iterator.hasNext ()Z | IFNE L0 | L2: RETURN (line 168) method-execution(void glassbox.client.ConnectionManager.setAsDefault(java.lang.String)) end public void setAsDefault(String) public void setSelectViewed(String, boolean) org.aspectj.weaver.MethodDeclarationLineNumber: 170:6156 : method-execution(void glassbox.client.ConnectionManager.setSelectViewed(java.lang.String, boolean)) | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 171) | INVOKEVIRTUAL glassbox.client.ConnectionManager.getDefaultNick ()Ljava/lang/String; | ASTORE_3 | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 172) | GETFIELD glassbox.client.ConnectionManager.connectionList Ljava/util/List; | INVOKEINTERFACE java.util.List.iterator ()Ljava/util/Iterator; | ASTORE 5 | GOTO L2 | L0: ALOAD 5 | INVOKEINTERFACE java.util.Iterator.next ()Ljava/lang/Object; | CHECKCAST glassbox.client.ConnectionManager$AgentConnection | ASTORE 4 | ALOAD 4 // Lglassbox/client/ConnectionManager$AgentConnection; con (line 173) | INVOKEVIRTUAL glassbox.client.ConnectionManager$AgentConnection.getNickname ()Ljava/lang/String; | ALOAD_1 // Ljava/lang/String; nickname | INVOKEVIRTUAL java.lang.String.equals (Ljava/lang/Object;)Z | IFEQ L2 | ILOAD_2 // Z val (line 174) | IFNE L1 | ALOAD_3 // Ljava/lang/String; defNick | ALOAD 4 // Lglassbox/client/ConnectionManager$AgentConnection; con | INVOKEVIRTUAL glassbox.client.ConnectionManager$AgentConnection.getNickname ()Ljava/lang/String; | IF_ACMPEQ L2 | L1: ALOAD 4 // Lglassbox/client/ConnectionManager$AgentConnection; con (line 177) | ILOAD_2 // Z val | INVOKEVIRTUAL glassbox.client.ConnectionManager$AgentConnection.setViewed (Z)V | GOTO L3 (line 178) | L2: ALOAD 5 (line 172) | INVOKEINTERFACE java.util.Iterator.hasNext ()Z | IFNE L0 | L3: RETURN (line 182) method-execution(void glassbox.client.ConnectionManager.setSelectViewed(java.lang.String, boolean)) end public void setSelectViewed(String, boolean) public boolean getSelectViewed(String) org.aspectj.weaver.MethodDeclarationLineNumber: 184:6636 : method-execution(boolean glassbox.client.ConnectionManager.getSelectViewed(java.lang.String)) | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 185) | GETFIELD glassbox.client.ConnectionManager.connectionList Ljava/util/List; | INVOKEINTERFACE java.util.List.iterator ()Ljava/util/Iterator; | ASTORE_3 | GOTO L1 | L0: ALOAD_3 | INVOKEINTERFACE java.util.Iterator.next ()Ljava/lang/Object; | CHECKCAST glassbox.client.ConnectionManager$AgentConnection | ASTORE_2 | ALOAD_2 // Lglassbox/client/ConnectionManager$AgentConnection; con (line 186) | INVOKEVIRTUAL glassbox.client.ConnectionManager$AgentConnection.getNickname ()Ljava/lang/String; | ALOAD_1 // Ljava/lang/String; nickname | INVOKEVIRTUAL java.lang.String.equals (Ljava/lang/Object;)Z | IFEQ L1 | ALOAD_2 // Lglassbox/client/ConnectionManager$AgentConnection; con (line 187) | INVOKEVIRTUAL glassbox.client.ConnectionManager$AgentConnection.isViewed ()Z | IRETURN | L1: ALOAD_3 (line 185) | INVOKEINTERFACE java.util.Iterator.hasNext ()Z | IFNE L0 | ICONST_0 (line 190) | IRETURN method-execution(boolean glassbox.client.ConnectionManager.getSelectViewed(java.lang.String)) end public boolean getSelectViewed(String) public String getNicknameFromURL(String) org.aspectj.weaver.MethodDeclarationLineNumber: 193:6903 : method-execution(java.lang.String glassbox.client.ConnectionManager.getNicknameFromURL(java.lang.String)) | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 194) | GETFIELD glassbox.client.ConnectionManager.connectionList Ljava/util/List; | INVOKEINTERFACE java.util.List.iterator ()Ljava/util/Iterator; | ASTORE_3 | GOTO L1 | L0: ALOAD_3 | INVOKEINTERFACE java.util.Iterator.next ()Ljava/lang/Object; | CHECKCAST glassbox.client.ConnectionManager$AgentConnection | ASTORE_2 | ALOAD_2 // Lglassbox/client/ConnectionManager$AgentConnection; con (line 195) | INVOKEVIRTUAL glassbox.client.ConnectionManager$AgentConnection.getUrl ()Ljava/lang/String; | ALOAD_1 // Ljava/lang/String; url | INVOKEVIRTUAL java.lang.String.equals (Ljava/lang/Object;)Z | IFEQ L1 | ALOAD_2 // Lglassbox/client/ConnectionManager$AgentConnection; con (line 196) | INVOKEVIRTUAL glassbox.client.ConnectionManager$AgentConnection.getNickname ()Ljava/lang/String; | ARETURN | L1: ALOAD_3 (line 194) | INVOKEINTERFACE java.util.Iterator.hasNext ()Z | IFNE L0 | LDC_W " " (line 199) | ARETURN method-execution(java.lang.String glassbox.client.ConnectionManager.getNicknameFromURL(java.lang.String)) end public String getNicknameFromURL(String) public glassbox.client.ConnectionManager$AgentConnection getAgentConnectionFromURL(String) org.aspectj.weaver.MethodDeclarationLineNumber: 202:7168 : method-execution(glassbox.client.ConnectionManager$AgentConnection glassbox.client.ConnectionManager.getAgentConnectionFromURL(java.lang.String)) | ALOAD_0 // Lglassbox/client/ConnectionManager; this (line 203) | GETFIELD glassbox.client.ConnectionManager.connectionList Ljava/util/List; | INVOKEINTERFACE java.util.List.iterator ()Ljava/util/Iterator; | ASTORE_3 | GOTO L1 | L0: ALOAD_3 | INVOKEINTERFACE java.util.Iterator.next ()Ljava/lang/Object; | CHECKCAST glassbox.client.ConnectionManager$AgentConnection | ASTORE_2 | ALOAD_2 // Lglassbox/client/ConnectionManager$AgentConnection; con (line 204) | INVOKEVIRTUAL glassbox.client.ConnectionManager$AgentConnection.getUrl ()Ljava/lang/String; | ALOAD_1 // Ljava/lang/String; url | INVOKEVIRTUAL java.lang.String.equals (Ljava/lang/Object;)Z | IFEQ L1 | ALOAD_2 // Lglassbox/client/ConnectionManager$AgentConnection; con (line 205) | ARETURN | L1: ALOAD_3 (line 203) | INVOKEINTERFACE java.util.Iterator.hasNext ()Z | IFNE L0 | ACONST_NULL (line 209) | ARETURN method-execution(glassbox.client.ConnectionManager$AgentConnection glassbox.client.ConnectionManager.getAgentConnectionFromURL(java.lang.String)) end public glassbox.client.ConnectionManager$AgentConnection getAgentConnectionFromURL(String) public glassbox.client.ConnectionManager$AgentConnection getAgentConnectionFromNick(String) org.aspectj.weaver.MethodDeclarationLineNumber: 212:7429 : method-execution(glassbox.client.C
|
resolved fixed
|
c5c18aa
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-04-27T07:06:30Z | 2006-04-27T01:06:40Z |
tests/src/org/aspectj/systemtest/ajc152/Ajc152Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc152;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc152Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public void testNotAtWithincode_pr138158_1() { runTest("not at withincode - 1");}
public void testNotAtWithincode_pr138158_2() { runTest("not at withincode - 2");}
public void testNotAtWithincode_pr138158_3() { runTest("not at within - 3");}
// public void testComplexGenericDecl_pr137568() { runTest("complicated generics declaration");}
public void testNpeOnDup_pr138143() { runTest("npe on duplicate method with ataj");}
public void testPointcutsAndGenerics_pr137496_1() { runTest("pointcuts and generics - B");}
public void testPointcutsAndGenerics_pr137496_2() { runTest("pointcuts and generics - D");}
public void testPointcutsAndGenerics_pr137496_3() { runTest("pointcuts and generics - E");}
public void testPointcutsAndGenerics_pr137496_4() { runTest("pointcuts and generics - F");}
public void testPointcutsAndGenerics_pr137496_5() { runTest("pointcuts and generics - G");}
public void testPointcutsAndGenerics_pr137496_6() { runTest("pointcuts and generics - H");}
public void testAspectLibrariesAndASM_pr135001() { runTest("aspect libraries and asm");}
public void testStackOverflow_pr136258() { runTest("stack overflow");}
public void testIncorrectOverridesEvaluation13() { runTest("incorrect overrides evaluation - 1.3"); }
public void testIncorrectOverridesEvaluation15() { runTest("incorrect overrides evaluation - 1.5"); }
// known failures, uncomment when working.
public void testReferencePCutInDeclareWarning_pr138215() { runTest("Reference pointcut fails inside @DeclareWarning");}
// public void testReferencePCutInPerClause_pr138219() { runTest("Can't use a FQ Reference pointcut in any pointcut expression referenced by a per-clause");}
// public void testDoubleAnnotationMatching_pr138223() { runTest("Double at annotation matching (no binding)");}
public void testNoClassCastExceptionWithPerThis_pr138286() { runTest("No ClassCastException with perThis");}
// this next one reported as a bug by Rob Harrop, but I can't reproduce the failure yet...
//public void testAtAspectWithReferencePCPerClause_pr138220() { runTest("@Aspect with reference pointcut in perclause");}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc152Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc152/ajc152.xml");
}
}
|
135,780 |
Bug 135780 Java 1.2 dependency in aspectjrt.jar bug with fix
| null |
resolved fixed
|
cb5dfe7
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-03T16:18:25Z | 2006-04-10T03:33:20Z |
runtime/src/org/aspectj/runtime/reflect/SignatureImpl.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.Signature;
import java.lang.ref.SoftReference;
import java.util.StringTokenizer;
abstract class SignatureImpl implements Signature {
private static boolean useCache = true;
int modifiers = -1;
String name;
String declaringTypeName;
Class declaringType;
SoftReference toStringCacheRef;
SignatureImpl(int modifiers, String name, Class declaringType) {
this.modifiers = modifiers;
this.name = name;
this.declaringType = declaringType;
}
protected abstract String createToString (StringMaker sm);
/* Use a soft cache for the short, middle and long String representations */
String toString (StringMaker sm) {
String[] toStringCache = null;
if (toStringCacheRef == null || toStringCacheRef.get() == null) {
toStringCache = new String[3];
if (useCache) toStringCacheRef = new SoftReference(toStringCache);
}
else {
toStringCache = (String[])toStringCacheRef.get();
}
if (toStringCache[sm.cacheOffset] == null) {
toStringCache[sm.cacheOffset] = createToString(sm);
}
return toStringCache[sm.cacheOffset];
}
public final String toString() { return toString(StringMaker.middleStringMaker); }
public final String toShortString() { return toString(StringMaker.shortStringMaker); }
public final String toLongString() { return toString(StringMaker.longStringMaker); }
public int getModifiers() {
if (modifiers == -1) modifiers = extractInt(0);
return modifiers;
}
public String getName() {
if (name == null) name = extractString(1);
return name;
}
public Class getDeclaringType() {
if (declaringType == null) declaringType = extractType(2);
return declaringType;
}
public String getDeclaringTypeName() {
if (declaringTypeName == null) {
declaringTypeName = getDeclaringType().getName();
}
return declaringTypeName;
}
String fullTypeName(Class type) {
if (type == null) return "ANONYMOUS";
if (type.isArray()) return fullTypeName(type.getComponentType()) + "[]";
return type.getName().replace('$', '.');
}
String stripPackageName(String name) {
int dot = name.lastIndexOf('.');
if (dot == -1) return name;
return name.substring(dot+1);
}
String shortTypeName(Class type) {
if (type == null) return "ANONYMOUS";
if (type.isArray()) return shortTypeName(type.getComponentType()) + "[]";
return stripPackageName(type.getName()).replace('$', '.');
}
void addFullTypeNames(StringBuffer buf, Class[] types) {
for (int i = 0; i < types.length; i++) {
if (i > 0) buf.append(", ");
buf.append(fullTypeName(types[i]));
}
}
void addShortTypeNames(StringBuffer buf, Class[] types) {
for (int i = 0; i < types.length; i++) {
if (i > 0) buf.append(", ");
buf.append(shortTypeName(types[i]));
}
}
void addTypeArray(StringBuffer buf, Class[] types) {
addFullTypeNames(buf, types);
}
// lazy version
private String stringRep;
ClassLoader lookupClassLoader = null;
public void setLookupClassLoader(ClassLoader loader) {
this.lookupClassLoader = loader;
}
private ClassLoader getLookupClassLoader() {
if (lookupClassLoader == null) lookupClassLoader = this.getClass().getClassLoader();
return lookupClassLoader;
}
public SignatureImpl(String stringRep) {
this.stringRep = stringRep;
}
static final char SEP = '-';
String extractString(int n) {
//System.out.println(n + ": from " + stringRep);
int startIndex = 0;
int endIndex = stringRep.indexOf(SEP);
while (n-- > 0) {
startIndex = endIndex+1;
endIndex = stringRep.indexOf(SEP, startIndex);
}
if (endIndex == -1) endIndex = stringRep.length();
//System.out.println(" " + stringRep.substring(startIndex, endIndex));
return stringRep.substring(startIndex, endIndex);
}
int extractInt(int n) {
String s = extractString(n);
return Integer.parseInt(s, 16);
}
Class extractType(int n) {
String s = extractString(n);
return Factory.makeClass(s,getLookupClassLoader());
}
static String[] EMPTY_STRING_ARRAY = new String[0];
static Class[] EMPTY_CLASS_ARRAY = new Class[0];
static final String INNER_SEP = ":";
String[] extractStrings(int n) {
String s = extractString(n);
StringTokenizer st = new StringTokenizer(s, INNER_SEP);
final int N = st.countTokens();
String[] ret = new String[N];
for (int i = 0; i < N; i++) ret[i]= st.nextToken();
return ret;
}
Class[] extractTypes(int n) {
String s = extractString(n);
StringTokenizer st = new StringTokenizer(s, INNER_SEP);
final int N = st.countTokens();
Class[] ret = new Class[N];
for (int i = 0; i < N; i++) ret[i]= Factory.makeClass(st.nextToken(),getLookupClassLoader());
return ret;
}
/*
* Used for testing
*/
static void setUseCache (boolean b) {
useCache = b;
}
static boolean getUseCache () {
return useCache;
}
}
|
134,371 |
Bug 134371 ClassCastException in AjState.recordClassFile()
|
I got this exception while working on a static inner aspect. A full rebuild avoided the problem. java.lang.ClassCastException: org.aspectj.weaver.MissingResolvedTypeWithKnownSignature at org.aspectj.ajdt.internal.core.builder.AjState.recordClassFile(AjState.java:774) at org.aspectj.ajdt.internal.core.builder.AjState.noteResult(AjState.java:627) at org.aspectj.ajdt.internal.core.builder.AjBuildManager$3.acceptResult(AjBuildManager.java:867) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterProcessing(AjCompilerAdapter.java:206) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$4$6b855184(CompilerAdapter.aj:90) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:528) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:845) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:266) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:168) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191)
|
resolved fixed
|
299c3a4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-05T09:46:43Z | 2006-04-01T16:46:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AspectDeclaration.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseScope;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceType;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseTypeMunger;
import org.aspectj.ajdt.internal.compiler.lookup.HelperInterfaceBinding;
import org.aspectj.ajdt.internal.compiler.lookup.InlineAccessFieldBinding;
import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedHandler;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile;
import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Clinit;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.ExceptionLabel;
import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.Label;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IGenericType;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BaseTypes;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Binding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.InvocationSite;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.patterns.Declare;
import org.aspectj.weaver.patterns.FormalBinding;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.PerFromSuper;
import org.aspectj.weaver.patterns.PerSingleton;
import org.aspectj.weaver.patterns.TypePattern;
//import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser;
// (we used to...) making all aspects member types avoids a nasty hierarchy pain
// switched from MemberTypeDeclaration to TypeDeclaration
public class AspectDeclaration extends TypeDeclaration {
//public IAjDeclaration[] ajDeclarations;
private AjAttribute.Aspect aspectAttribute;
public PerClause perClause;
public ResolvedMember aspectOfMethod;
//public ResolvedMember ptwGetWithinTypeMethod;
public ResolvedMember hasAspectMethod;
public Map accessForInline = new HashMap();
public Map superAccessForInline = new HashMap();
public boolean isPrivileged;
private int declaredModifiers;
public EclipseSourceType concreteName;
public ReferenceType typeX;
public EclipseFactory factory; //??? should use this consistently
public int adviceCounter = 1; // Used as a part of the generated name for advice methods
public int declareCounter= 1; // Used as a part of the generated name for methods representing declares
// for better error messages in 1.0 to 1.1 transition
public TypePattern dominatesPattern;
public AspectDeclaration(CompilationResult compilationResult) {
super(compilationResult);
//perClause = new PerSingleton();
}
public boolean isAbstract() {
return (modifiers & AccAbstract) != 0;
}
public void resolve() {
declaredModifiers = modifiers; // remember our modifiers, we're going to be public in generateCode
if (binding == null) {
ignoreFurtherInvestigation = true;
return;
}
super.resolve();
}
public void checkSpec(ClassScope scope) {
if (ignoreFurtherInvestigation) return;
if (dominatesPattern != null) {
scope.problemReporter().signalError(
dominatesPattern.getStart(), dominatesPattern.getEnd(),
"dominates has changed for 1.1, use 'declare precedence: " +
new String(this.name) + ", " + dominatesPattern.toString() + ";' " +
"in the body of the aspect instead");
}
if (!isAbstract()) {
MethodBinding[] methods = binding.methods();
for (int i=0, len = methods.length; i < len; i++) {
MethodBinding m = methods[i];
if (m.isConstructor()) {
// this make all constructors in aspects invisible and thus uncallable
//XXX this only works for aspects that come from source
methods[i] = new MethodBinding(m, binding) {
public boolean canBeSeenBy(
InvocationSite invocationSite,
Scope scope) {
return false;
}
};
if (m.parameters != null && m.parameters.length != 0) {
scope.problemReporter().signalError(m.sourceStart(), m.sourceEnd(),
"only zero-argument constructors allowed in concrete aspect");
}
}
}
// check the aspect was not declared generic, only abstract aspects can have type params
if (typeParameters != null && typeParameters.length > 0) {
scope.problemReporter().signalError(sourceStart(), sourceEnd(),
"only abstract aspects can have type parameters");
}
}
if (this.enclosingType != null) {
if (!Modifier.isStatic(modifiers)) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"inner aspects must be static");
ignoreFurtherInvestigation = true;
return;
}
}
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope);
ResolvedType myType = typeX;
//if (myType == null) System.err.println("bad myType for: " + this);
ResolvedType superType = myType.getSuperclass();
// can't be Serializable/Cloneable unless -XserializableAspects
if (!world.isXSerializableAspects()) {
if (world.getWorld().getCoreType(UnresolvedType.SERIALIZABLE).isAssignableFrom(myType)) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"aspects may not implement Serializable");
ignoreFurtherInvestigation = true;
return;
}
if (world.getWorld().getCoreType(UnresolvedType.CLONEABLE).isAssignableFrom(myType)) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"aspects may not implement Cloneable");
ignoreFurtherInvestigation = true;
return;
}
}
if (superType.isAspect()) {
if (!superType.isAbstract()) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"can not extend a concrete aspect");
ignoreFurtherInvestigation = true;
return;
}
// if super type is generic, check that we have fully parameterized it
if (superType.isRawType()) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"a generic super-aspect must be fully parameterized in an extends clause");
ignoreFurtherInvestigation = true;
return;
}
}
}
private FieldBinding initFailureField= null;
/**
* AMC - this method is called by the AtAspectJVisitor during beforeCompilation processing in
* the AjCompiler adapter. We use this hook to add in the @AspectJ annotations.
*/
public void addAtAspectJAnnotations() {
Annotation atAspectAnnotation = AtAspectJAnnotationFactory.createAspectAnnotation(perClause.toDeclarationString(), declarationSourceStart);
Annotation privilegedAnnotation = null;
if (isPrivileged) privilegedAnnotation = AtAspectJAnnotationFactory.createPrivilegedAnnotation(declarationSourceStart);
Annotation[] toAdd = new Annotation[isPrivileged ? 2 : 1];
toAdd[0] = atAspectAnnotation;
if (isPrivileged) toAdd[1] = privilegedAnnotation;
if (annotations == null) {
annotations = toAdd;
} else {
Annotation[] old = annotations;
annotations = new Annotation[annotations.length + toAdd.length];
System.arraycopy(old,0,annotations,0,old.length);
System.arraycopy(toAdd,0,annotations,old.length,toAdd.length);
}
}
public void generateCode(ClassFile enclosingClassFile) {
if (ignoreFurtherInvestigation) {
if (binding == null)
return;
ClassFile.createProblemType(
this,
scope.referenceCompilationUnit().compilationResult);
return;
}
// make me and my binding public
this.modifiers = AstUtil.makePublic(this.modifiers);
this.binding.modifiers = AstUtil.makePublic(this.binding.modifiers);
if (!isAbstract()) {
initFailureField = factory.makeFieldBinding(AjcMemberMaker.initFailureCauseField(typeX));
binding.addField(initFailureField);
if (perClause == null) {
// we've already produced an error for this
} else if (perClause.getKind() == PerClause.SINGLETON) {
binding.addField(factory.makeFieldBinding(AjcMemberMaker.perSingletonField(
typeX)));
methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, false, true, initFailureField);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
binding.addField(
factory.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, true, false, null);
} else if (perClause.getKind() == PerClause.PEROBJECT) {
// binding.addField(
// world.makeFieldBinding(
// AjcMemberMaker.perCflowField(
// typeX)));
} else if (perClause.getKind() == PerClause.PERTYPEWITHIN) {
//PTWIMPL Add field for storing typename in aspect for which the aspect instance exists
binding.addField(factory.makeFieldBinding(AjcMemberMaker.perTypeWithinWithinTypeField(typeX,typeX)));
} else {
throw new RuntimeException("unimplemented");
}
}
if (EclipseFactory.DEBUG) System.out.println(toString());
super.generateCode(enclosingClassFile);
}
public boolean needClassInitMethod() {
return true;
}
protected void generateAttributes(ClassFile classFile) {
if (!isAbstract()) generatePerSupportMembers(classFile);
generateInlineAccessMembers(classFile);
addVersionAttributeIfNecessary(classFile);
classFile.extraAttributes.add(
new EclipseAttributeAdapter(new AjAttribute.Aspect(perClause)));
if (binding.privilegedHandler != null) {
ResolvedMember[] members = ((PrivilegedHandler)binding.privilegedHandler).getMembers();
classFile.extraAttributes.add(
new EclipseAttributeAdapter(new AjAttribute.PrivilegedAttribute(members)));
}
//XXX need to get this attribute on anyone with a pointcut for good errors
classFile.extraAttributes.add(
new EclipseAttributeAdapter(new AjAttribute.SourceContextAttribute(
new String(compilationResult().getFileName()),
compilationResult().lineSeparatorPositions)));
super.generateAttributes(classFile);
}
/**
* A pointcut might have already added the attribute, let's not add it again.
*/
private void addVersionAttributeIfNecessary(ClassFile classFile) {
for (Iterator iter = classFile.extraAttributes.iterator(); iter.hasNext();) {
EclipseAttributeAdapter element = (EclipseAttributeAdapter) iter.next();
if (CharOperation.equals(element.getNameChars(),weaverVersionChars)) return;
}
classFile.extraAttributes.add(new EclipseAttributeAdapter(new AjAttribute.WeaverVersionInfo()));
}
private static char[] weaverVersionChars = "org.aspectj.weaver.WeaverVersion".toCharArray();
private void generateInlineAccessMembers(ClassFile classFile) {
for (Iterator i = superAccessForInline.values().iterator(); i.hasNext(); ) {
AccessForInlineVisitor.SuperAccessMethodPair pair = (AccessForInlineVisitor.SuperAccessMethodPair)i.next();
generateSuperAccessMethod(classFile, pair.accessMethod, pair.originalMethod);
}
for (Iterator i = accessForInline.entrySet().iterator(); i.hasNext(); ) {
Map.Entry e = (Map.Entry)i.next();
generateInlineAccessMethod(classFile, (Binding)e.getValue(), (ResolvedMember)e.getKey());
}
}
private void generatePerSupportMembers(ClassFile classFile) {
if (isAbstract()) return;
//XXX otherwise we need to have this (error handling?)
if (aspectOfMethod == null) return;
if (perClause == null) {
System.err.println("has null perClause: " + this);
return;
}
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
if (perClause.getKind() == PerClause.SINGLETON) {
generatePerSingletonAspectOfMethod(classFile);
generatePerSingletonHasAspectMethod(classFile);
generatePerSingletonAjcClinitMethod(classFile);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
generatePerCflowAspectOfMethod(classFile);
generatePerCflowHasAspectMethod(classFile);
generatePerCflowPushMethod(classFile);
generatePerCflowAjcClinitMethod(classFile);
} else if (perClause.getKind() == PerClause.PEROBJECT) {
TypeBinding interfaceType =
generatePerObjectInterface(classFile);
world.addTypeBinding(interfaceType);
generatePerObjectAspectOfMethod(classFile, interfaceType);
generatePerObjectHasAspectMethod(classFile, interfaceType);
generatePerObjectBindMethod(classFile, interfaceType);
} else if (perClause.getKind() == PerClause.PERTYPEWITHIN) {
//PTWIMPL Generate the methods required *in the aspect*
generatePerTypeWithinAspectOfMethod(classFile); // public static <aspecttype> aspectOf(java.lang.Class)
generatePerTypeWithinGetInstanceMethod(classFile); // private static <aspecttype> ajc$getInstance(Class c) throws Exception
generatePerTypeWithinHasAspectMethod(classFile);
generatePerTypeWithinCreateAspectInstanceMethod(classFile); // generate public static X ajc$createAspectInstance(Class forClass) {
// PTWIMPL getWithinType() would need this...
//generatePerTypeWithinGetWithinTypeMethod(classFile); // generate public Class getWithinType() {
} else {
throw new RuntimeException("unimplemented");
}
}
private static interface BodyGenerator {
public void generate(CodeStream codeStream);
}
private void generateMethod(ClassFile classFile, ResolvedMember member, BodyGenerator gen) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(member), gen);
}
private void generateMethod(ClassFile classFile, MethodBinding methodBinding, BodyGenerator gen) {
generateMethod(classFile,methodBinding,null,gen);
}
protected List makeEffectiveSignatureAttribute(ResolvedMember sig,Shadow.Kind kind,boolean weaveBody) {
List l = new ArrayList(1);
l.add(new EclipseAttributeAdapter(
new AjAttribute.EffectiveSignatureAttribute(sig, kind, weaveBody)));
return l;
}
/*
* additionalAttributes allows us to pass some optional attributes we want to attach to the method we generate.
* Currently this is used for inline accessor methods that have been generated to allow private field references or
* private method calls to be inlined (PR71377). In these cases the optional attribute is an effective signature
* attribute which means calls to these methods are able to masquerade as any join point (a field set, field get or
* method call). The effective signature attribute is 'unwrapped' in BcelClassWeaver.matchInvokeInstruction()
*/
private void generateMethod(ClassFile classFile, MethodBinding methodBinding, List additionalAttributes/*ResolvedMember realMember*/, BodyGenerator gen) {
// EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
classFile.generateMethodInfoHeader(methodBinding);
int methodAttributeOffset = classFile.contentsOffset;
int attributeNumber;
if (additionalAttributes!=null) { // mini optimization
List attrs = new ArrayList();
attrs.addAll(AstUtil.getAjSyntheticAttribute());
attrs.addAll(additionalAttributes);
attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, false, attrs);
} else {
attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, false, AstUtil.getAjSyntheticAttribute());
}
int codeAttributeOffset = classFile.contentsOffset;
classFile.generateCodeAttributeHeader();
CodeStream codeStream = classFile.codeStream;
// Use reset() rather than init()
// XXX We need a scope to keep reset happy, initializerScope is *not* the right one, but it works !
// codeStream.init(classFile);
// codeStream.initializeMaxLocals(methodBinding);
MethodDeclaration md = AstUtil.makeMethodDeclaration(methodBinding);
md.scope = initializerScope;
codeStream.reset(md,classFile);
// body starts here
gen.generate(codeStream);
// body ends here
classFile.completeCodeAttribute(codeAttributeOffset);
attributeNumber++;
classFile.completeMethodInfo(methodAttributeOffset, attributeNumber);
}
private void generatePerCflowAspectOfMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackPeekInstance()));
codeStream.checkcast(binding);
codeStream.areturn();
// body ends here
}});
}
private void generatePerCflowHasAspectMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackIsValid()));
codeStream.ireturn();
// body ends here
}});
}
private void generatePerCflowPushMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.perCflowPush(
factory.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackPushInstance()));
codeStream.return_();
// body ends here
}});
}
private void generatePerCflowAjcClinitMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPreClinitMethod(
world.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.CFLOW_STACK_TYPE));
codeStream.dup();
codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.cflowStackInit()));
codeStream.putstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.return_();
// body ends here
}});
}
private TypeBinding generatePerObjectInterface(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
UnresolvedType interfaceTypeX =
AjcMemberMaker.perObjectInterfaceType(typeX);
HelperInterfaceBinding interfaceType =
new HelperInterfaceBinding(this.binding, interfaceTypeX);
world.addTypeBinding(interfaceType);
interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceGet(typeX));
interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceSet(typeX));
interfaceType.generateClass(compilationResult, classFile);
return interfaceType;
}
/*private void generatePerTypeWithinGetWithinTypeMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile,ptwGetWithinTypeMethod,new BodyGenerator() {
public void generate(CodeStream codeStream) {
codeStream.aload_0();
codeStream.getfield(world.makeFieldBinding(AjcMemberMaker.perTypeWithinWithinTypeField(typeX,typeX)));
codeStream.areturn();
}});
}*/
// PTWIMPL Generate aspectOf() method
private void generatePerTypeWithinAspectOfMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
Label instanceFound = new Label(codeStream);
ExceptionLabel anythingGoesWrong = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION));
codeStream.aload_0();
codeStream.invokestatic(world.makeMethodBindingForCall(AjcMemberMaker.perTypeWithinGetInstance(typeX)));
codeStream.astore_1();
codeStream.aload_1();
codeStream.ifnonnull(instanceFound);
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
codeStream.ldc(typeX.getName());
codeStream.aconst_null();
codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.noAspectBoundExceptionInit2()));
codeStream.athrow();
instanceFound.place();
codeStream.aload_1();
codeStream.areturn();
anythingGoesWrong.placeEnd();
anythingGoesWrong.place();
codeStream.astore_1();
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
// Run the simple ctor for NABE
codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.noAspectBoundExceptionInit()));
codeStream.athrow();
}});
}
private void generatePerObjectAspectOfMethod(
ClassFile classFile,
final TypeBinding interfaceType)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
Label popWrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
codeStream.dup();
codeStream.ifnull(popWrongType);
codeStream.areturn();
popWrongType.place();
codeStream.pop();
wrongType.place();
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
codeStream.invokespecial(world.makeMethodBindingForCall(
AjcMemberMaker.noAspectBoundExceptionInit()
));
codeStream.athrow();
// body ends here
}});
}
private void generatePerObjectHasAspectMethod(ClassFile classFile,
final TypeBinding interfaceType) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
codeStream.ifnull(wrongType);
codeStream.iconst_1();
codeStream.ireturn();
wrongType.place();
codeStream.iconst_0();
codeStream.ireturn();
// body ends here
}});
}
// PTWIMPL Generate hasAspect() method
private void generatePerTypeWithinHasAspectMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
ExceptionLabel goneBang = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION));
Label noInstanceExists = new Label(codeStream);
Label leave = new Label(codeStream);
goneBang.placeStart();
codeStream.aload_0();
codeStream.invokestatic(world.makeMethodBinding(AjcMemberMaker.perTypeWithinGetInstance(typeX)));
codeStream.ifnull(noInstanceExists);
codeStream.iconst_1();
codeStream.goto_(leave);
noInstanceExists.place();
codeStream.iconst_0();
leave.place();
goneBang.placeEnd();
codeStream.ireturn();
goneBang.place();
codeStream.astore_1();
codeStream.iconst_0();
codeStream.ireturn();
}});
}
private void generatePerObjectBindMethod(
ClassFile classFile,
final TypeBinding interfaceType)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, AjcMemberMaker.perObjectBind(world.fromBinding(binding)),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType); //XXX this case might call for screaming
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
//XXX should do a check for null here and throw a NoAspectBound
codeStream.ifnonnull(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceSet(typeX)));
wrongType.place();
codeStream.return_();
// body ends here
}});
}
// PTWIMPL Generate getInstance method
private void generatePerTypeWithinGetInstanceMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, AjcMemberMaker.perTypeWithinGetInstance(world.fromBinding(binding)),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
ExceptionLabel exc = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION));
exc.placeStart();
codeStream.aload_0();
codeStream.ldc(NameMangler.perTypeWithinLocalAspectOf(typeX));
codeStream.aconst_null();
codeStream.invokevirtual(
new MethodBinding(
0,
"getDeclaredMethod".toCharArray(),
world.makeTypeBinding(UnresolvedType.forSignature("Ljava/lang/reflect/Method;")), // return type
new TypeBinding[]{world.makeTypeBinding(UnresolvedType.forSignature("Ljava/lang/String;")),
world.makeTypeBinding(UnresolvedType.forSignature("[Ljava/lang/Class;"))},
new ReferenceBinding[0],
(ReferenceBinding)world.makeTypeBinding(UnresolvedType.JAVA_LANG_CLASS)));
codeStream.astore_1();
codeStream.aload_1();
codeStream.aconst_null();
codeStream.aconst_null();
codeStream.invokevirtual(
new MethodBinding(
0,
"invoke".toCharArray(),
world.makeTypeBinding(UnresolvedType.OBJECT),
new TypeBinding[]{world.makeTypeBinding(UnresolvedType.OBJECT),world.makeTypeBinding(UnresolvedType.forSignature("[Ljava/lang/Object;"))},
new ReferenceBinding[0],
(ReferenceBinding)world.makeTypeBinding(UnresolvedType.JAVA_LANG_REFLECT_METHOD)));
codeStream.checkcast(world.makeTypeBinding(typeX));
codeStream.astore_2();
codeStream.aload_2();
exc.placeEnd();
codeStream.areturn();
exc.place();
codeStream.astore_1();
// this just returns null now - the old version used to throw the caught exception!
codeStream.aconst_null();
codeStream.areturn();
}});
}
private void generatePerTypeWithinCreateAspectInstanceMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, AjcMemberMaker.perTypeWithinCreateAspectInstance(world.fromBinding(binding)),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
codeStream.new_(world.makeTypeBinding(typeX));
codeStream.dup();
codeStream.invokespecial(new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.astore_1();
codeStream.aload_1();
codeStream.aload_0();
codeStream.putfield(world.makeFieldBinding(AjcMemberMaker.perTypeWithinWithinTypeField(typeX,typeX)));
codeStream.aload_1();
codeStream.areturn();
}});
}
private void generatePerSingletonAspectOfMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// Old style aspectOf() method which confused decompilers
// // body starts here
// codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField(
// typeX)));
// Label isNull = new Label(codeStream);
// codeStream.dup();
// codeStream.ifnull(isNull);
// codeStream.areturn();
// isNull.place();
//
// codeStream.incrStackSize(+1); // the dup trick above confuses the stack counter
// codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
// codeStream.dup();
// codeStream.ldc(typeX.getNameAsIdentifier());
// codeStream.getstatic(initFailureField);
// codeStream.invokespecial(world.makeMethodBindingForCall(
// AjcMemberMaker.noAspectBoundExceptionInitWithCause()
// ));
// codeStream.athrow();
// // body ends here
// The stuff below generates code that looks like this:
/*
* if (ajc$perSingletonInstance == null)
* throw new NoAspectBoundException("A", ajc$initFailureCause);
* else
* return ajc$perSingletonInstance;
*/
// body starts here (see end of each line for what it is doing!)
FieldBinding fb = world.makeFieldBinding(AjcMemberMaker.perSingletonField(typeX));
codeStream.getstatic(fb); // GETSTATIC
Label isNonNull = new Label(codeStream);
codeStream.ifnonnull(isNonNull); // IFNONNULL
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); // NEW
codeStream.dup(); // DUP
codeStream.ldc(typeX.getNameAsIdentifier()); // LDC
codeStream.getstatic(initFailureField); // GETSTATIC
codeStream.invokespecial(world.makeMethodBindingForCall(
AjcMemberMaker.noAspectBoundExceptionInitWithCause())); // INVOKESPECIAL
codeStream.athrow(); // ATHROW
isNonNull.place();
codeStream.getstatic(fb); // GETSTATIC
codeStream.areturn(); // ARETURN
// body ends here
}});
}
private void generatePerSingletonHasAspectMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField(
typeX)));
Label isNull = new Label(codeStream);
codeStream.ifnull(isNull);
codeStream.iconst_1();
codeStream.ireturn();
isNull.place();
codeStream.iconst_0();
codeStream.ireturn();
// body ends here
}});
}
private void generatePerSingletonAjcClinitMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPostClinitMethod(
world.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.putstatic(
world.makeFieldBinding(
AjcMemberMaker.perSingletonField(
typeX)));
codeStream.return_();
// body ends here
}});
}
private void generateSuperAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) {
generateMethod(classFile, accessMethod,
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.aload_0();
AstUtil.generateParameterLoads(accessMethod.parameters, codeStream);
codeStream.invokespecial(
factory.makeMethodBinding(method));
AstUtil.generateReturn(accessMethod.returnType, codeStream);
// body ends here
}});
}
private void generateInlineAccessMethod(ClassFile classFile, final Binding binding, final ResolvedMember member) {
if (binding instanceof InlineAccessFieldBinding) {
generateInlineAccessors(classFile, (InlineAccessFieldBinding)binding, member);
} else {
generateInlineAccessMethod(classFile, (MethodBinding)binding, member);
}
}
private void generateInlineAccessors(ClassFile classFile, final InlineAccessFieldBinding accessField, final ResolvedMember field) {
final FieldBinding fieldBinding = factory.makeFieldBinding(field);
generateMethod(classFile, accessField.reader,
makeEffectiveSignatureAttribute(field,Shadow.FieldGet,false),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
if (field.isStatic()) {
codeStream.getstatic(fieldBinding);
} else {
codeStream.aload_0();
codeStream.getfield(fieldBinding);
}
AstUtil.generateReturn(accessField.reader.returnType, codeStream);
// body ends here
}});
generateMethod(classFile, accessField.writer,
makeEffectiveSignatureAttribute(field,Shadow.FieldSet,false),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
if (field.isStatic()) {
codeStream.load(fieldBinding.type, 0);
codeStream.putstatic(fieldBinding);
} else {
codeStream.aload_0();
codeStream.load(fieldBinding.type, 1);
codeStream.putfield(fieldBinding);
}
codeStream.return_();
// body ends here
}});
}
private void generateInlineAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) {
generateMethod(classFile, accessMethod,
makeEffectiveSignatureAttribute(method, Shadow.MethodCall, false),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
AstUtil.generateParameterLoads(accessMethod.parameters, codeStream);
if (method.isStatic()) {
codeStream.invokestatic(factory.makeMethodBinding(method));
} else {
codeStream.invokevirtual(factory.makeMethodBinding(method));
}
AstUtil.generateReturn(accessMethod.returnType, codeStream);
// body ends here
}});
}
private PerClause.Kind lookupPerClauseKind(ReferenceBinding binding) {
PerClause perClause;
if (binding instanceof BinaryTypeBinding) {
ResolvedType superTypeX = factory.fromEclipse(binding);
perClause = superTypeX.getPerClause();
} else if (binding instanceof SourceTypeBinding ) {
SourceTypeBinding sourceSc = (SourceTypeBinding)binding;
if (sourceSc.scope.referenceContext instanceof AspectDeclaration) {
perClause = ((AspectDeclaration)sourceSc.scope.referenceContext).perClause;
} else {
return null;
}
} else if (binding instanceof ParameterizedTypeBinding) {
ParameterizedTypeBinding pBinding = (ParameterizedTypeBinding)binding;
if (pBinding.type instanceof SourceTypeBinding) {
SourceTypeBinding sourceSc = (SourceTypeBinding)pBinding.type;
if (sourceSc.scope != null && sourceSc.scope.referenceContext instanceof AspectDeclaration) {
perClause = ((AspectDeclaration)sourceSc.scope.referenceContext).perClause;
} else {
return null;
}
} else {
perClause=null;
}
} else {
//XXX need to handle this too
return null;
}
if (perClause == null) {
return lookupPerClauseKind(binding.superclass());
} else {
return perClause.getKind();
}
}
private void buildPerClause(ClassScope scope) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope);
if (perClause == null) {
PerClause.Kind kind = lookupPerClauseKind(binding.superclass);
if (kind == null) {
perClause = new PerSingleton();
} else {
perClause = new PerFromSuper(kind);
}
}
aspectAttribute = new AjAttribute.Aspect(perClause);
if (ignoreFurtherInvestigation) return; //???
if (!isAbstract()) {
if (perClause.getKind() == PerClause.SINGLETON) {
aspectOfMethod = AjcMemberMaker.perSingletonAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perSingletonHasAspectMethod(typeX);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
aspectOfMethod = AjcMemberMaker.perCflowAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perCflowHasAspectMethod(typeX);
} else if (perClause.getKind() == PerClause.PEROBJECT) {
aspectOfMethod = AjcMemberMaker.perObjectAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perObjectHasAspectMethod(typeX);
} else if (perClause.getKind() == PerClause.PERTYPEWITHIN) {
// PTWIMPL Use these variants of aspectOf()/hasAspect()
aspectOfMethod = AjcMemberMaker.perTypeWithinAspectOfMethod(typeX,world.getWorld().isInJava5Mode());
hasAspectMethod = AjcMemberMaker.perTypeWithinHasAspectMethod(typeX,world.getWorld().isInJava5Mode());
//ptwGetWithinTypeMethod = AjcMemberMaker.perTypeWithinGetWithinTypeMethod(typeX,world.getWorld().isInJava5Mode());
//binding.addMethod(world.makeMethodBinding(ptwGetWithinTypeMethod));
} else {
throw new RuntimeException("bad per clause: " + perClause);
}
binding.addMethod(world.makeMethodBinding(aspectOfMethod));
binding.addMethod(world.makeMethodBinding(hasAspectMethod));
}
resolvePerClause(); //XXX might be too soon for some error checking
}
private PerClause resolvePerClause() {
EclipseScope iscope = new EclipseScope(new FormalBinding[0], scope);
perClause.resolve(iscope);
return perClause;
}
public void buildInterTypeAndPerClause(ClassScope classScope) {
factory = EclipseFactory.fromScopeLookupEnvironment(scope);
if (isPrivileged) {
binding.privilegedHandler = new PrivilegedHandler(this);
}
checkSpec(classScope);
if (ignoreFurtherInvestigation) return;
buildPerClause(scope);
if (methods != null) {
for (int i = 0; i < methods.length; i++) {
if (methods[i] instanceof InterTypeDeclaration) {
EclipseTypeMunger m = ((InterTypeDeclaration)methods[i]).build(classScope);
if (m != null) concreteName.typeMungers.add(m);
} else if (methods[i] instanceof DeclareDeclaration) {
Declare d = ((DeclareDeclaration)methods[i]).build(classScope);
if (d != null) concreteName.declares.add(d);
}
}
}
concreteName.getDeclaredPointcuts();
}
// public String toString(int tab) {
// return tabString(tab) + toStringHeader() + toStringBody(tab);
// }
//
// public String toStringBody(int tab) {
//
// String s = " {"; //$NON-NLS-1$
//
//
// if (memberTypes != null) {
// for (int i = 0; i < memberTypes.length; i++) {
// if (memberTypes[i] != null) {
// s += "\n" + memberTypes[i].toString(tab + 1); //$NON-NLS-1$
// }
// }
// }
// if (fields != null) {
// for (int fieldI = 0; fieldI < fields.length; fieldI++) {
// if (fields[fieldI] != null) {
// s += "\n" + fields[fieldI].toString(tab + 1); //$NON-NLS-1$
// if (fields[fieldI].isField())
// s += ";"; //$NON-NLS-1$
// }
// }
// }
// if (methods != null) {
// for (int i = 0; i < methods.length; i++) {
// if (methods[i] != null) {
// s += "\n" + methods[i].toString(tab + 1); //$NON-NLS-1$
// }
// }
// }
// s += "\n" + tabString(tab) + "}"; //$NON-NLS-2$ //$NON-NLS-1$
// return s;
// }
public StringBuffer printHeader(int indent, StringBuffer output) {
// since all aspects are made public we want to print the
// modifiers that were supplied in the original source code
printModifiers(this.declaredModifiers,output);
output.append("aspect " );
output.append(name);
if (superclass != null) {
output.append(" extends "); //$NON-NLS-1$
superclass.print(0, output);
}
if (superInterfaces != null && superInterfaces.length > 0) {
output.append((kind() == IGenericType.INTERFACE_DECL) ? " extends " : " implements ");//$NON-NLS-2$ //$NON-NLS-1$
for (int i = 0; i < superInterfaces.length; i++) {
if (i > 0) output.append( ", "); //$NON-NLS-1$
superInterfaces[i].print(0, output);
}
}
return output;
//XXX we should append the per-clause
}
/**
* All aspects are made public after type checking etc. and before generating code
* (so that the advice can be called!).
* This method returns the modifiers as specified in the original source code declaration
* so that the structure model sees the right thing.
*/
public int getDeclaredModifiers() {
return declaredModifiers;
}
}
|
134,371 |
Bug 134371 ClassCastException in AjState.recordClassFile()
|
I got this exception while working on a static inner aspect. A full rebuild avoided the problem. java.lang.ClassCastException: org.aspectj.weaver.MissingResolvedTypeWithKnownSignature at org.aspectj.ajdt.internal.core.builder.AjState.recordClassFile(AjState.java:774) at org.aspectj.ajdt.internal.core.builder.AjState.noteResult(AjState.java:627) at org.aspectj.ajdt.internal.core.builder.AjBuildManager$3.acceptResult(AjBuildManager.java:867) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterProcessing(AjCompilerAdapter.java:206) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$4$6b855184(CompilerAdapter.aj:90) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:528) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:845) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:266) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:168) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191)
|
resolved fixed
|
299c3a4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-05T09:46:43Z | 2006-04-01T16:46:40Z |
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
* Mik Kersten 2004-07-26 extended to allow overloading of
* hierarchy builder
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.AstUtil;
import org.aspectj.ajdt.internal.core.builder.AjBuildManager;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.EmptyStatement;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Wildcard;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.Constant;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BaseTypes;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Binding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.RawTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.WildcardBinding;
import org.aspectj.weaver.BoundedReferenceType;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.IHasPosition;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeFactory;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.TypeVariableDeclaringElement;
import org.aspectj.weaver.TypeVariableReference;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.UnresolvedTypeVariableReferenceType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.UnresolvedType.TypeKind;
/**
* @author Jim Hugunin
*/
public class EclipseFactory {
public static boolean DEBUG = false;
private AjBuildManager buildManager;
private LookupEnvironment lookupEnvironment;
private boolean xSerializableAspects;
private World world;
public Collection finishedTypeMungers = null;
// We can get clashes if we don't treat raw types differently - we end up looking
// up a raw and getting the generic type (pr115788)
private Map/*UnresolvedType, TypeBinding*/ typexToBinding = new HashMap();
private Map/*UnresolvedType, TypeBinding*/ rawTypeXToBinding = new HashMap();
//XXX currently unused
// private Map/*TypeBinding, ResolvedType*/ 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,AjBuildManager buildManager) {
this.lookupEnvironment = lookupEnvironment;
this.buildManager = buildManager;
this.world = buildManager.getWorld();
this.xSerializableAspects = buildManager.buildConfig.isXserializableAspects();
}
public EclipseFactory(LookupEnvironment lookupEnvironment, World world, boolean xSer) {
this.lookupEnvironment = lookupEnvironment;
this.world = world;
this.xSerializableAspects = xSer;
this.buildManager = null;
}
public World getWorld() {
return world;
}
public void showMessage(
Kind kind,
String message,
ISourceLocation loc1,
ISourceLocation loc2)
{
getWorld().showMessage(kind, message, loc1, loc2);
}
public ResolvedType fromEclipse(ReferenceBinding binding) {
if (binding == null) return ResolvedType.MISSING;
//??? this seems terribly inefficient
//System.err.println("resolving: " + binding.getClass() + ", name = " + getName(binding));
ResolvedType ret = getWorld().resolve(fromBinding(binding));
//System.err.println(" got: " + ret);
return ret;
}
public ResolvedType fromTypeBindingToRTX(TypeBinding tb) {
if (tb == null) return ResolvedType.MISSING;
ResolvedType ret = getWorld().resolve(fromBinding(tb));
return ret;
}
public ResolvedType[] fromEclipse(ReferenceBinding[] bindings) {
if (bindings == null) {
return ResolvedType.NONE;
}
int len = bindings.length;
ResolvedType[] ret = new ResolvedType[len];
for (int i=0; i < len; i++) {
ret[i] = fromEclipse(bindings[i]);
}
return ret;
}
public static String getName(TypeBinding binding) {
if (binding instanceof TypeVariableBinding) {
// The first bound may be null - so default to object?
TypeVariableBinding tvb = (TypeVariableBinding)binding;
if (tvb.firstBound!=null) {
return getName(tvb.firstBound);
} else {
return getName(tvb.superclass);
}
}
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);
}
/**
* Some generics notes:
*
* Andy 6-May-05
* We were having trouble with parameterized types in a couple of places - due to TypeVariableBindings. When we
* see a TypeVariableBinding now we default to either the firstBound if it is specified or java.lang.Object. Not
* sure when/if this gets us unstuck? It does mean we forget that it is a type variable when going back
* the other way from the UnresolvedType and that would seem a bad thing - but I've yet to see the reason we need to
* remember the type variable.
* Adrian 10-July-05
* When we forget it's a type variable we come unstuck when getting the declared members of a parameterized
* type - since we don't know it's a type variable we can't replace it with the type parameter.
*/
//??? going back and forth between strings and bindings is a waste of cycles
public UnresolvedType fromBinding(TypeBinding binding) {
if (binding instanceof HelperInterfaceBinding) {
return ((HelperInterfaceBinding) binding).getTypeX();
}
if (binding == null || binding.qualifiedSourceName() == null) {
return ResolvedType.MISSING;
}
// first piece of generics support!
if (binding instanceof TypeVariableBinding) {
TypeVariableBinding tb = (TypeVariableBinding) binding;
UnresolvedTypeVariableReferenceType utvrt = (UnresolvedTypeVariableReferenceType) fromTypeVariableBinding(tb);
return utvrt;
}
// handle arrays since the component type may need special treatment too...
if (binding instanceof ArrayBinding) {
ArrayBinding aBinding = (ArrayBinding) binding;
UnresolvedType componentType = fromBinding(aBinding.leafComponentType);
return UnresolvedType.makeArray(componentType, aBinding.dimensions);
}
if (binding instanceof WildcardBinding) {
WildcardBinding eWB = (WildcardBinding) binding;
UnresolvedType theType = TypeFactory.createTypeFromSignature(CharOperation.charToString(eWB.genericTypeSignature()));
// Repair the bound
// e.g. If the bound for the wildcard is a typevariable, e.g. '? extends E' then
// the type variable in the unresolvedtype will be correct only in name. In that
// case let's set it correctly based on the one in the eclipse WildcardBinding
UnresolvedType theBound = null;
if (eWB.bound instanceof TypeVariableBinding) {
theBound = fromTypeVariableBinding((TypeVariableBinding)eWB.bound);
} else {
theBound = fromBinding(eWB.bound);
}
if (theType.isGenericWildcard() && theType.isSuper()) theType.setLowerBound(theBound);
if (theType.isGenericWildcard() && theType.isExtends()) theType.setUpperBound(theBound);
return theType;
}
if (binding instanceof ParameterizedTypeBinding) {
if (binding instanceof RawTypeBinding) {
// special case where no parameters are specified!
return UnresolvedType.forRawTypeName(getName(binding));
}
ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) binding;
UnresolvedType[] arguments = null;
if (ptb.arguments!=null) { // null can mean this is an inner type of a Parameterized Type with no bounds of its own (pr100227)
arguments = new UnresolvedType[ptb.arguments.length];
for (int i = 0; i < arguments.length; i++) {
arguments[i] = fromBinding(ptb.arguments[i]);
}
}
String baseTypeSignature = null;
ResolvedType baseType = getWorld().resolve(UnresolvedType.forName(getName(binding)),true);
if (!baseType.isMissing()) {
// can legitimately be missing if a bound refers to a type we haven't added to the world yet...
if (!baseType.isGenericType() && arguments!=null) baseType = baseType.getGenericType();
baseTypeSignature = baseType.getErasureSignature();
} else {
baseTypeSignature = UnresolvedType.forName(getName(binding)).getSignature();
}
// Create an unresolved parameterized type. We can't create a resolved one as the
// act of resolution here may cause recursion problems since the parameters may
// be type variables that we haven't fixed up yet.
if (arguments==null) arguments=new UnresolvedType[0];
String parameterizedSig = ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER+CharOperation.charToString(binding.genericTypeSignature()).substring(1);
return TypeFactory.createUnresolvedParameterizedType(parameterizedSig,baseTypeSignature,arguments);
}
// Convert the source type binding for a generic type into a generic UnresolvedType
// notice we can easily determine the type variables from the eclipse object
// and we can recover the generic signature from it too - so we pass those
// to the forGenericType() method.
if (binding.isGenericType() &&
!binding.isParameterizedType() &&
!binding.isRawType()) {
TypeVariableBinding[] tvbs = binding.typeVariables();
TypeVariable[] tVars = new TypeVariable[tvbs.length];
for (int i = 0; i < tvbs.length; i++) {
TypeVariableBinding eclipseV = tvbs[i];
tVars[i] = ((TypeVariableReference)fromTypeVariableBinding(eclipseV)).getTypeVariable();
}
//TODO asc generics - temporary guard....
if (!(binding instanceof SourceTypeBinding))
throw new RuntimeException("Cant get the generic sig for "+binding.debugName());
return UnresolvedType.forGenericType(getName(binding),tVars,
CharOperation.charToString(((SourceTypeBinding)binding).genericSignature()));
}
// LocalTypeBinding have a name $Local$, we can get the real name by using the signature....
if (binding instanceof LocalTypeBinding) {
LocalTypeBinding ltb = (LocalTypeBinding) binding;
if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) {
return UnresolvedType.forSignature(new String(binding.signature()));
} else {
// we're reporting a problem and don't have a resolved name for an
// anonymous local type yet, report the issue on the enclosing type
return UnresolvedType.forSignature(new String(ltb.enclosingType.signature()));
}
}
return UnresolvedType.forName(getName(binding));
}
/**
* Some type variables refer to themselves recursively, this enables us to avoid
* recursion problems.
*/
private static Map typeVariableBindingsInProgress = new HashMap();
/**
* Convert from the eclipse form of type variable (TypeVariableBinding) to the AspectJ
* form (TypeVariable).
*/
private UnresolvedType fromTypeVariableBinding(TypeVariableBinding aTypeVariableBinding) {
// first, check for recursive call to this method for the same tvBinding
if (typeVariableBindingsInProgress.containsKey(aTypeVariableBinding)) {
return (UnresolvedType) typeVariableBindingsInProgress.get(aTypeVariableBinding);
}
// Check if its a type variable binding that we need to recover to an alias...
if (typeVariablesForAliasRecovery!=null) {
String aliasname = (String)typeVariablesForAliasRecovery.get(aTypeVariableBinding);
if (aliasname!=null) {
UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType();
ret.setTypeVariable(new TypeVariable(aliasname));
return ret;
}
}
if (typeVariablesForThisMember.containsKey(new String(aTypeVariableBinding.sourceName))) {
return (UnresolvedType)typeVariablesForThisMember.get(new String(aTypeVariableBinding.sourceName));
}
// Create the UnresolvedTypeVariableReferenceType for the type variable
String name = CharOperation.charToString(aTypeVariableBinding.sourceName());
UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType();
typeVariableBindingsInProgress.put(aTypeVariableBinding,ret);
TypeVariable tv = new TypeVariable(name);
ret.setTypeVariable(tv);
// Dont set any bounds here, you'll get in a recursive mess
// TODO -- what about lower bounds??
UnresolvedType superclassType = fromBinding(aTypeVariableBinding.superclass());
UnresolvedType[] superinterfaces = new UnresolvedType[aTypeVariableBinding.superInterfaces.length];
for (int i = 0; i < superinterfaces.length; i++) {
superinterfaces[i] = fromBinding(aTypeVariableBinding.superInterfaces[i]);
}
tv.setUpperBound(superclassType);
tv.setAdditionalInterfaceBounds(superinterfaces);
tv.setRank(aTypeVariableBinding.rank);
if (aTypeVariableBinding.declaringElement instanceof MethodBinding) {
tv.setDeclaringElementKind(TypeVariable.METHOD);
// tv.setDeclaringElement(fromBinding((MethodBinding)aTypeVariableBinding.declaringElement);
} else {
tv.setDeclaringElementKind(TypeVariable.TYPE);
// // tv.setDeclaringElement(fromBinding(aTypeVariableBinding.declaringElement));
}
if (aTypeVariableBinding.declaringElement instanceof MethodBinding)
typeVariablesForThisMember.put(new String(aTypeVariableBinding.sourceName),ret);
typeVariableBindingsInProgress.remove(aTypeVariableBinding);
return ret;
}
public UnresolvedType[] fromBindings(TypeBinding[] bindings) {
if (bindings == null) return UnresolvedType.NONE;
int len = bindings.length;
UnresolvedType[] ret = new UnresolvedType[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 getDeclareAnnotationOnTypes() {
return getWorld().getDeclareAnnotationOnTypes();
}
public Collection getDeclareAnnotationOnFields() {
return getWorld().getDeclareAnnotationOnFields();
}
public Collection getDeclareAnnotationOnMethods() {
return getWorld().getDeclareAnnotationOnMethods();
}
public boolean areTypeMungersFinished() {
return finishedTypeMungers != null;
}
public void finishTypeMungers() {
// make sure that type mungers are
Collection ret = new ArrayList();
Collection baseTypeMungers = getWorld().getCrosscuttingMembersSet().getTypeMungers();
// XXX by Andy: why do we mix up the mungers here? it means later we know about two sets
// and the late ones are a subset of the complete set? (see pr114436)
baseTypeMungers.addAll(getWorld().getCrosscuttingMembersSet().getLateTypeMungers());
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 ResolvedMember makeResolvedMember(MethodBinding binding) {
return makeResolvedMember(binding, binding.declaringClass);
}
public ResolvedMember makeResolvedMember(MethodBinding binding, Shadow.Kind shadowKind) {
Member.Kind memberKind = binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD;
if (shadowKind == Shadow.AdviceExecution) memberKind = Member.ADVICE;
return makeResolvedMember(binding,binding.declaringClass,memberKind);
}
/**
* Conversion from a methodbinding (eclipse) to a resolvedmember (aspectj) is now done
* in the scope of some type variables. Before converting the parts of a methodbinding
* (params, return type) we store the type variables in this structure, then should any
* component of the method binding refer to them, we grab them from the map.
*/
private Map typeVariablesForThisMember = new HashMap();
/**
* This is a map from typevariablebindings (eclipsey things) to the names the user
* originally specified in their ITD. For example if the target is 'interface I<N extends Number> {}'
* and the ITD was 'public void I<X>.m(List<X> lxs) {}' then this map would contain a pointer
* from the eclipse type 'N extends Number' to the letter 'X'.
*/
private Map typeVariablesForAliasRecovery;
/**
* Construct a resolvedmember from a methodbinding. The supplied map tells us about any
* typevariablebindings that replaced typevariables whilst the compiler was resolving types -
* this only happens if it is a generic itd that shares type variables with its target type.
*/
public ResolvedMember makeResolvedMemberForITD(MethodBinding binding,TypeBinding declaringType,
Map /*TypeVariableBinding > original alias name*/ recoveryAliases) {
ResolvedMember result = null;
try {
typeVariablesForAliasRecovery = recoveryAliases;
result = makeResolvedMember(binding,declaringType);
} finally {
typeVariablesForAliasRecovery = null;
}
return result;
}
public ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType) {
return makeResolvedMember(binding,declaringType,
binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD);
}
public ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType, Member.Kind memberKind) {
//System.err.println("member for: " + binding + ", " + new String(binding.declaringClass.sourceName));
// Convert the type variables and store them
UnresolvedType[] ajTypeRefs = null;
typeVariablesForThisMember.clear();
// This is the set of type variables available whilst building the resolved member...
if (binding.typeVariables!=null) {
ajTypeRefs = new UnresolvedType[binding.typeVariables.length];
for (int i = 0; i < binding.typeVariables.length; i++) {
ajTypeRefs[i] = fromBinding(binding.typeVariables[i]);
typeVariablesForThisMember.put(new String(binding.typeVariables[i].sourceName),/*new Integer(binding.typeVariables[i].rank),*/ajTypeRefs[i]);
}
}
// AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map
ResolvedType realDeclaringType = world.resolve(fromBinding(declaringType));
if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType();
ResolvedMemberImpl ret = new ResolvedMemberImpl(
memberKind,
realDeclaringType,
binding.modifiers,
fromBinding(binding.returnType),
new String(binding.selector),
fromBindings(binding.parameters),
fromBindings(binding.thrownExceptions)
);
if (binding.isVarargs()) {
ret.setVarargsMethod();
}
if (ajTypeRefs!=null) {
TypeVariable[] tVars = new TypeVariable[ajTypeRefs.length];
for (int i=0;i<ajTypeRefs.length;i++) {
tVars[i]=((TypeVariableReference)ajTypeRefs[i]).getTypeVariable();
}
ret.setTypeVariables(tVars);
}
typeVariablesForThisMember.clear();
ret.resolve(world);
return ret;
}
public ResolvedMember makeResolvedMember(FieldBinding binding) {
return makeResolvedMember(binding, binding.declaringClass);
}
public ResolvedMember makeResolvedMember(FieldBinding binding, TypeBinding receiverType) {
// AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map
ResolvedType realDeclaringType = world.resolve(fromBinding(receiverType));
if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType();
return new ResolvedMemberImpl(
Member.FIELD,
realDeclaringType,
binding.modifiers,
world.resolve(fromBinding(binding.type)),
new String(binding.name),
UnresolvedType.NONE);
}
public TypeBinding makeTypeBinding(UnresolvedType typeX) {
TypeBinding ret = null;
// looking up type variables can get us into trouble
if (!typeX.isTypeVariableReference()) {
if (typeX.isRawType()) {
ret = (TypeBinding)rawTypeXToBinding.get(typeX);
} else {
ret = (TypeBinding)typexToBinding.get(typeX);
}
}
if (ret == null) {
ret = makeTypeBinding1(typeX);
if (!(typeX instanceof BoundedReferenceType) &&
!(typeX instanceof UnresolvedTypeVariableReferenceType)
) {
if (typeX.isRawType()) {
rawTypeXToBinding.put(typeX,ret);
} else {
typexToBinding.put(typeX, ret);
}
}
}
if (ret == null) {
System.out.println("can't find: " + typeX);
}
return ret;
}
// When converting a parameterized type from our world to the eclipse world, these get set so that
// resolution of the type parameters may known in what context it is occurring (pr114744)
private ReferenceBinding baseTypeForParameterizedType;
private int indexOfTypeParameterBeingConverted;
private TypeBinding makeTypeBinding1(UnresolvedType typeX) {
if (typeX.isPrimitiveType()) {
if (typeX == ResolvedType.BOOLEAN) return BaseTypes.BooleanBinding;
if (typeX == ResolvedType.BYTE) return BaseTypes.ByteBinding;
if (typeX == ResolvedType.CHAR) return BaseTypes.CharBinding;
if (typeX == ResolvedType.DOUBLE) return BaseTypes.DoubleBinding;
if (typeX == ResolvedType.FLOAT) return BaseTypes.FloatBinding;
if (typeX == ResolvedType.INT) return BaseTypes.IntBinding;
if (typeX == ResolvedType.LONG) return BaseTypes.LongBinding;
if (typeX == ResolvedType.SHORT) return BaseTypes.ShortBinding;
if (typeX == ResolvedType.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 if (typeX.isParameterizedType()) {
// Converting back to a binding from a UnresolvedType
UnresolvedType[] typeParameters = typeX.getTypeParameters();
ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName());
TypeBinding[] argumentBindings = new TypeBinding[typeParameters.length];
baseTypeForParameterizedType = baseTypeBinding;
for (int i = 0; i < argumentBindings.length; i++) {
indexOfTypeParameterBeingConverted = i;
argumentBindings[i] = makeTypeBinding(typeParameters[i]);
}
indexOfTypeParameterBeingConverted = 0;
baseTypeForParameterizedType = null;
ParameterizedTypeBinding ptb =
lookupEnvironment.createParameterizedType(baseTypeBinding,argumentBindings,baseTypeBinding.enclosingType());
return ptb;
} else if (typeX.isTypeVariableReference()) {
// return makeTypeVariableBinding((TypeVariableReference)typeX);
return makeTypeVariableBindingFromAJTypeVariable(((TypeVariableReference)typeX).getTypeVariable());
} else if (typeX.isRawType()) {
ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName());
RawTypeBinding rtb = lookupEnvironment.createRawType(baseTypeBinding,baseTypeBinding.enclosingType());
return rtb;
} else if (typeX.isGenericWildcard()) {
// translate from boundedreferencetype to WildcardBinding
BoundedReferenceType brt = (BoundedReferenceType)typeX;
// Work out 'kind' for the WildcardBinding
int boundkind = Wildcard.UNBOUND;
TypeBinding bound = null;
if (brt.isExtends()) {
boundkind = Wildcard.EXTENDS;
bound = makeTypeBinding(brt.getUpperBound());
} else if (brt.isSuper()) {
boundkind = Wildcard.SUPER;
bound = makeTypeBinding(brt.getLowerBound());
}
TypeBinding[] otherBounds = null;
if (brt.getAdditionalBounds()!=null && brt.getAdditionalBounds().length!=0) otherBounds = makeTypeBindings(brt.getAdditionalBounds());
WildcardBinding wb = lookupEnvironment.createWildcard(baseTypeForParameterizedType,indexOfTypeParameterBeingConverted,bound,otherBounds,boundkind);
return wb;
} else {
return lookupBinding(typeX.getName());
}
}
private ReferenceBinding lookupBinding(String sname) {
char[][] name = CharOperation.splitOn('.', sname.toCharArray());
ReferenceBinding rb = lookupEnvironment.getType(name);
return rb;
}
public TypeBinding[] makeTypeBindings(UnresolvedType[] 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(UnresolvedType[] 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;
}
// field related
public FieldBinding makeFieldBinding(NewFieldTypeMunger nftm) {
return internalMakeFieldBinding(nftm.getSignature(),nftm.getTypeVariableAliases());
}
/**
* Convert a resolvedmember into an eclipse field binding
*/
public FieldBinding makeFieldBinding(ResolvedMember member,List aliases) {
return internalMakeFieldBinding(member,aliases);
}
/**
* Convert a resolvedmember into an eclipse field binding
*/
public FieldBinding makeFieldBinding(ResolvedMember member) {
return internalMakeFieldBinding(member,null);
}
/**
* Take a normal AJ member and convert it into an eclipse fieldBinding.
* Taking into account any aliases that it may include due to being
* a generic itd. Any aliases are put into the typeVariableToBinding
* map so that they will be substituted as appropriate in the returned
* fieldbinding.
*/
public FieldBinding internalMakeFieldBinding(ResolvedMember member,List aliases) {
typeVariableToTypeBinding.clear();
TypeVariableBinding[] tvbs = null;
ReferenceBinding declaringType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType());
// If there are aliases, place them in the map
if (aliases!=null && aliases.size()>0) {
int i =0;
for (Iterator iter = aliases.iterator(); iter.hasNext();) {
String element = (String) iter.next();
typeVariableToTypeBinding.put(element,declaringType.typeVariables()[i++]);
}
}
currentType = declaringType;
FieldBinding fb = new FieldBinding(member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
member.getModifiers(),
currentType,
Constant.NotAConstant);
typeVariableToTypeBinding.clear();
currentType = null;
return fb;
}
private ReferenceBinding currentType = null;
// method binding related
public MethodBinding makeMethodBinding(NewMethodTypeMunger nmtm) {
return internalMakeMethodBinding(nmtm.getSignature(),nmtm.getTypeVariableAliases());
}
/**
* Convert a resolvedmember into an eclipse method binding.
*/
public MethodBinding makeMethodBinding(ResolvedMember member,List aliases) {
return internalMakeMethodBinding(member,aliases);
}
/**
* Creates a method binding for a resolvedmember taking into account type variable aliases -
* this variant can take an aliasTargetType and should be used when the alias target type
* cannot be retrieved from the resolvedmember.
*/
public MethodBinding makeMethodBinding(ResolvedMember member,List aliases,UnresolvedType aliasTargetType) {
return internalMakeMethodBinding(member,aliases,aliasTargetType);
}
/**
* Convert a resolvedmember into an eclipse method binding.
*/
public MethodBinding makeMethodBinding(ResolvedMember member) {
return internalMakeMethodBinding(member,null); // there are no aliases
}
public MethodBinding internalMakeMethodBinding(ResolvedMember member,List aliases) {
return internalMakeMethodBinding(member,aliases,member.getDeclaringType());
}
/**
* Take a normal AJ member and convert it into an eclipse methodBinding.
* Taking into account any aliases that it may include due to being a
* generic ITD. Any aliases are put into the typeVariableToBinding
* map so that they will be substituted as appropriate in the returned
* methodbinding
*/
public MethodBinding internalMakeMethodBinding(ResolvedMember member,List aliases,UnresolvedType aliasTargetType) {
typeVariableToTypeBinding.clear();
TypeVariableBinding[] tvbs = null;
if (member.getTypeVariables()!=null) {
if (member.getTypeVariables().length==0) {
tvbs = MethodBinding.NoTypeVariables;
} else {
tvbs = makeTypeVariableBindingsFromAJTypeVariables(member.getTypeVariables());
// QQQ do we need to bother fixing up the declaring element here?
}
}
ReferenceBinding declaringType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType());
// If there are aliases, place them in the map
if (aliases!=null && aliases.size()!=0) {
int i=0;
ReferenceBinding aliasTarget = (ReferenceBinding)makeTypeBinding(aliasTargetType);
for (Iterator iter = aliases.iterator(); iter.hasNext();) {
String element = (String) iter.next();
typeVariableToTypeBinding.put(element,aliasTarget.typeVariables()[i++]);
}
}
currentType = declaringType;
MethodBinding mb = new MethodBinding(member.getModifiers(),
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
makeReferenceBindings(member.getExceptions()),
declaringType);
if (tvbs!=null) mb.typeVariables = tvbs;
typeVariableToTypeBinding.clear();
currentType = null;
return mb;
}
/**
* Convert a bunch of type variables in one go, from AspectJ form to Eclipse form.
*/
// private TypeVariableBinding[] makeTypeVariableBindings(UnresolvedType[] typeVariables) {
// int len = typeVariables.length;
// TypeVariableBinding[] ret = new TypeVariableBinding[len];
// for (int i = 0; i < len; i++) {
// ret[i] = makeTypeVariableBinding((TypeVariableReference)typeVariables[i]);
// }
// return ret;
// }
private TypeVariableBinding[] makeTypeVariableBindingsFromAJTypeVariables(TypeVariable[] typeVariables) {
int len = typeVariables.length;
TypeVariableBinding[] ret = new TypeVariableBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = makeTypeVariableBindingFromAJTypeVariable(typeVariables[i]);
}
return ret;
}
// only accessed through private methods in this class. Ensures all type variables we encounter
// map back to the same type binding - this is important later when Eclipse code is processing
// a methodbinding trying to come up with possible bindings for the type variables.
// key is currently the name of the type variable...is that ok?
private Map typeVariableToTypeBinding = new HashMap();
/**
* Converts from an TypeVariableReference to a TypeVariableBinding. A TypeVariableReference
* in AspectJ world holds a TypeVariable and it is this type variable that is converted
* to the TypeVariableBinding.
*/
private TypeVariableBinding makeTypeVariableBinding(TypeVariableReference tvReference) {
TypeVariable tv = tvReference.getTypeVariable();
TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tv.getName());
if (currentType!=null) {
TypeVariableBinding tvb = currentType.getTypeVariable(tv.getName().toCharArray());
if (tvb!=null) return tvb;
}
if (tvBinding==null) {
Binding declaringElement = null;
// this will cause an infinite loop or NPE... not required yet luckily.
// if (tVar.getDeclaringElement() instanceof Member) {
// declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement());
// } else {
// declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement());
// }
tvBinding = new TypeVariableBinding(tv.getName().toCharArray(),declaringElement,tv.getRank());
typeVariableToTypeBinding.put(tv.getName(),tvBinding);
tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tv.getUpperBound());
tvBinding.firstBound=(ReferenceBinding)makeTypeBinding(tv.getFirstBound());
if (tv.getAdditionalInterfaceBounds()==null) {
tvBinding.superInterfaces=TypeVariableBinding.NoSuperInterfaces;
} else {
TypeBinding tbs[] = makeTypeBindings(tv.getAdditionalInterfaceBounds());
ReferenceBinding[] rbs= new ReferenceBinding[tbs.length];
for (int i = 0; i < tbs.length; i++) {
rbs[i] = (ReferenceBinding)tbs[i];
}
tvBinding.superInterfaces=rbs;
}
}
return tvBinding;
}
private TypeVariableBinding makeTypeVariableBindingFromAJTypeVariable(TypeVariable tv) {
TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tv.getName());
if (currentType!=null) {
TypeVariableBinding tvb = currentType.getTypeVariable(tv.getName().toCharArray());
if (tvb!=null) return tvb;
}
if (tvBinding==null) {
Binding declaringElement = null;
// this will cause an infinite loop or NPE... not required yet luckily.
// if (tVar.getDeclaringElement() instanceof Member) {
// declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement());
// } else {
// declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement());
// }
tvBinding = new TypeVariableBinding(tv.getName().toCharArray(),declaringElement,tv.getRank());
typeVariableToTypeBinding.put(tv.getName(),tvBinding);
tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tv.getUpperBound());
tvBinding.firstBound=(ReferenceBinding)makeTypeBinding(tv.getFirstBound());
if (tv.getAdditionalInterfaceBounds()==null) {
tvBinding.superInterfaces=TypeVariableBinding.NoSuperInterfaces;
} else {
TypeBinding tbs[] = makeTypeBindings(tv.getAdditionalInterfaceBounds());
ReferenceBinding[] rbs= new ReferenceBinding[tbs.length];
for (int i = 0; i < tbs.length; i++) {
rbs[i] = (ReferenceBinding)tbs[i];
}
tvBinding.superInterfaces=rbs;
}
}
return tvBinding;
}
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 != null) && buildManager.doGenerateModel()) {
AjBuildManager.getAsmHierarchyBuilder().buildStructureForCompilationUnit(unit, buildManager.getStructureModel(), buildManager.buildConfig);
}
}
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, CompilationUnitDeclaration unit) {
TypeDeclaration decl = binding.scope.referenceContext;
// Deal with the raw/basic type to give us an entry in the world type map
UnresolvedType simpleTx = null;
if (binding.isGenericType()) {
simpleTx = UnresolvedType.forRawTypeName(getName(binding));
} else if (binding.isLocalType()) {
LocalTypeBinding ltb = (LocalTypeBinding) binding;
if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) {
simpleTx = UnresolvedType.forSignature(new String(binding.signature()));
} else {
simpleTx = UnresolvedType.forName(getName(binding));
}
}else {
simpleTx = UnresolvedType.forName(getName(binding));
}
ReferenceType name = getWorld().lookupOrCreateName(simpleTx);
// A type can change from simple > generic > simple across a set of compiles. We need
// to ensure the entry in the typemap is promoted and demoted correctly. The call
// to setGenericType() below promotes a simple to a raw. This call demotes it back
// to simple
// pr125405
if (!binding.isRawType() && !binding.isGenericType() && name.getTypekind()==TypeKind.RAW) {
name.demoteToSimpleType();
}
EclipseSourceType t = new EclipseSourceType(name, this, binding, decl, unit);
// For generics, go a bit further - build a typex for the generic type
// give it the same delegate and link it to the raw type
if (binding.isGenericType()) {
UnresolvedType complexTx = fromBinding(binding); // fully aware of any generics info
ResolvedType cName = world.resolve(complexTx,true);
ReferenceType complexName = null;
if (!cName.isMissing()) {
complexName = (ReferenceType) cName;
complexName = (ReferenceType) complexName.getGenericType();
if (complexName == null) complexName = new ReferenceType(complexTx,world);
} else {
complexName = new ReferenceType(complexTx,world);
}
name.setGenericType(complexName);
complexName.setDelegate(t);
}
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], unit);
}
}
// XXX this doesn't feel like it belongs here, but it breaks a hard dependency on
// exposing AjBuildManager (needed by AspectDeclaration).
public boolean isXSerializableAspects() {
return xSerializableAspects;
}
public ResolvedMember fromBinding(MethodBinding binding) {
return new ResolvedMemberImpl(Member.METHOD,fromBinding(binding.declaringClass),binding.modifiers,
fromBinding(binding.returnType),CharOperation.charToString(binding.selector),fromBindings(binding.parameters));
}
public TypeVariableDeclaringElement fromBinding(Binding declaringElement) {
if (declaringElement instanceof TypeBinding) {
return fromBinding(((TypeBinding)declaringElement));
} else {
return fromBinding((MethodBinding)declaringElement);
}
}
public void cleanup() {
this.typexToBinding.clear();
this.rawTypeXToBinding.clear();
this.finishedTypeMungers = null;
}
}
|
134,371 |
Bug 134371 ClassCastException in AjState.recordClassFile()
|
I got this exception while working on a static inner aspect. A full rebuild avoided the problem. java.lang.ClassCastException: org.aspectj.weaver.MissingResolvedTypeWithKnownSignature at org.aspectj.ajdt.internal.core.builder.AjState.recordClassFile(AjState.java:774) at org.aspectj.ajdt.internal.core.builder.AjState.noteResult(AjState.java:627) at org.aspectj.ajdt.internal.core.builder.AjBuildManager$3.acceptResult(AjBuildManager.java:867) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterProcessing(AjCompilerAdapter.java:206) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$4$6b855184(CompilerAdapter.aj:90) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:528) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:845) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:266) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:168) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191)
|
resolved fixed
|
299c3a4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-05T09:46:43Z | 2006-04-01T16:46:40Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjState.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.core.builder;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.ajdt.internal.compiler.InterimCompilationResult;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IRelationshipMap;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryField;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryMethod;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilerModifiers;
import org.aspectj.org.eclipse.jdt.internal.core.builder.ReferenceCollection;
import org.aspectj.org.eclipse.jdt.internal.core.builder.StringSet;
import org.aspectj.util.FileUtil;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.IWeaver;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.UnwovenClassFile;
/**
* Holds state needed for incremental compilation
*/
public class AjState {
private AjBuildManager buildManager;
private boolean couldBeSubsequentIncrementalBuild = false;
// SECRETAPI static so beware of multi-threading bugs...
public static IStateListener stateListener = null;
public static boolean FORCE_INCREMENTAL_DURING_TESTING = false;
private IHierarchy structureModel;
private IRelationshipMap relmap;
private long lastSuccessfulFullBuildTime = -1;
private Hashtable /* File, long */ structuralChangesSinceLastFullBuild = new Hashtable();
private long lastSuccessfulBuildTime = -1;
private long currentBuildTime = -1;
private AjBuildConfig buildConfig;
private boolean batchBuildRequiredThisTime = false;
/**
* Keeps a list of (FQN,Filename) pairs (as ClassFile objects)
* for types that resulted from the compilation of the given
* File. Note :- the ClassFile objects contain no byte code,
* they are simply a Filename,typename pair.
*
* Populated in noteResult and used in addDependentsOf(File)
*
* Added by AMC during state refactoring, 1Q06.
*/
private Map/*<File, List<ClassFile>*/ fullyQualifiedTypeNamesResultingFromCompilationUnit = new HashMap();
/**
* Source files defining aspects
*
* Populated in noteResult and used in processDeletedFiles
*
* Added by AMC during state refactoring, 1Q06.
*/
private Set/*<File>*/ sourceFilesDefiningAspects = new HashSet();
/**
* Populated in noteResult to record the set of types that should be recompiled if
* the given file is modified or deleted.
*
* Refered to during addAffectedSourceFiles when calculating incremental compilation set.
*/
private Map/*<File, ReferenceCollection>*/ references = new HashMap();
/**
* Holds UnwovenClassFiles (byte[]s) originating from the given file source. This
* could be a jar file, a directory, or an individual .class file. This is an
* *expensive* map. It is cleared immediately following a batch build, and the
* cheaper inputClassFilesBySource map is kept for processing of any subsequent
* incremental builds.
*
* Populated during AjBuildManager.initBcelWorld().
*
* Passed into AjCompiler adapter as the set of binary input files to reweave if the
* weaver determines a full weave is required.
*
* Cleared during initBcelWorld prior to repopulation.
*
* Used when a file is deleted during incremental compilation to delete all of the
* class files in the output directory that resulted from the weaving of File.
*
* Used during getBinaryFilesToCompile when compiling incrementally to determine
* which files should be recompiled if a given input file has changed.
*
*/
private Map/*File, List<UnwovenClassFile>*/ binarySourceFiles = new HashMap();
/**
* Initially a duplicate of the information held in binarySourceFiles, with the
* key difference that the values are ClassFiles (type name, File) not UnwovenClassFiles
* (which also have all the byte code in them). After a batch build, binarySourceFiles
* is cleared, leaving just this much lighter weight map to use in processing
* subsequent incremental builds.
*/
private Map/*<File,List<ClassFile>*/ inputClassFilesBySource = new HashMap();
/**
* Holds structure information on types as they were at the end of the last
* build. It would be nice to get rid of this too, but can't see an easy way to do
* that right now.
*/
private Map/*FQN,CompactStructureRepresentation*/ resolvedTypeStructuresFromLastBuild = new HashMap();
/**
* Populated in noteResult to record the set of UnwovenClassFiles (intermediate results)
* that originated from compilation of the class with the given fully-qualified name.
*
* Used in removeAllResultsOfLastBuild to remove .class files from output directory.
*
* Passed into StatefulNameEnvironment during incremental compilation to support
* findType lookups.
*/
private Map/*<String, File>*/ classesFromName = new HashMap();
private List/*File*/ compiledSourceFiles = new ArrayList();
private List/*String*/ resources = new ArrayList();
private List/*String*/ aspectNames;
private ArrayList/*<String>*/ qualifiedStrings;
private ArrayList/*<String>*/ simpleStrings;
private Set addedFiles;
private Set deletedFiles;
private Set /*BinarySourceFile*/addedBinaryFiles;
private Set /*BinarySourceFile*/deletedBinaryFiles;
private BcelWeaver weaver;
private BcelWorld world;
public AjState(AjBuildManager buildManager) {
this.buildManager = buildManager;
}
public void setCouldBeSubsequentIncrementalBuild(boolean yesThereCould) {
this.couldBeSubsequentIncrementalBuild = yesThereCould;
}
void successfulCompile(AjBuildConfig config,boolean wasFullBuild) {
buildConfig = config;
lastSuccessfulBuildTime = currentBuildTime;
if (stateListener!=null) stateListener.buildSuccessful(wasFullBuild);
if (wasFullBuild) lastSuccessfulFullBuildTime = currentBuildTime;
}
/**
* Returns false if a batch build is needed.
*/
boolean prepareForNextBuild(AjBuildConfig newBuildConfig) {
currentBuildTime = System.currentTimeMillis();
if (!maybeIncremental()) {
if (listenerDefined()) getListener().recordDecision("Preparing for build: not going to be incremental because either not in AJDT or incremental deactivated");
return false;
}
if (this.batchBuildRequiredThisTime) {
this.batchBuildRequiredThisTime = false;
if (listenerDefined()) getListener().recordDecision("Preparing for build: not going to be incremental this time because batch build explicitly forced");
return false;
}
if (lastSuccessfulBuildTime == -1 || buildConfig == null) {
structuralChangesSinceLastFullBuild.clear();
if (listenerDefined()) getListener().recordDecision("Preparing for build: not going to be incremental because no successful previous full build");
return false;
}
// we don't support incremental with an outjar yet
if (newBuildConfig.getOutputJar() != null) {
structuralChangesSinceLastFullBuild.clear();
if (listenerDefined()) getListener().recordDecision("Preparing for build: not going to be incremental because outjar being used");
return false;
}
// we can't do an incremental build if one of our paths
// has changed, or a jar on a path has been modified
if (pathChange(buildConfig,newBuildConfig)) {
// last time we built, .class files and resource files from jars on the
// inpath will have been copied to the output directory.
// these all need to be deleted in preparation for the clean build that is
// coming - otherwise a file that has been deleted from an inpath jar
// since the last build will not be deleted from the output directory.
removeAllResultsOfLastBuild();
if (stateListener!=null) stateListener.pathChangeDetected();
structuralChangesSinceLastFullBuild.clear();
if (listenerDefined()) getListener().recordDecision("Preparing for build: not going to be incremental because path change detected (one of classpath/aspectpath/inpath/injars)");
return false;
}
simpleStrings = new ArrayList();
qualifiedStrings = new ArrayList();
Set oldFiles = new HashSet(buildConfig.getFiles());
Set newFiles = new HashSet(newBuildConfig.getFiles());
addedFiles = new HashSet(newFiles);
addedFiles.removeAll(oldFiles);
deletedFiles = new HashSet(oldFiles);
deletedFiles.removeAll(newFiles);
Set oldBinaryFiles = new HashSet(buildConfig.getBinaryFiles());
Set newBinaryFiles = new HashSet(newBuildConfig.getBinaryFiles());
addedBinaryFiles = new HashSet(newBinaryFiles);
addedBinaryFiles.removeAll(oldBinaryFiles);
deletedBinaryFiles = new HashSet(oldBinaryFiles);
deletedBinaryFiles.removeAll(newBinaryFiles);
boolean couldStillBeIncremental = processDeletedFiles(deletedFiles);
if (!couldStillBeIncremental) {
if (listenerDefined()) getListener().recordDecision("Preparing for build: not going to be incremental because an aspect was deleted");
return false;
}
if (listenerDefined()) getListener().recordDecision("Preparing for build: planning to be an incremental build");
return true;
}
/**
* Checks if any of the files in the set passed in contains an aspect declaration. If one is found
* then we start the process of batch building, i.e. we remove all the results of the last build,
* call any registered listener to tell them whats happened and return false.
*
* @return false if we discovered an aspect declaration
*/
private boolean processDeletedFiles(Set deletedFiles) {
for (Iterator iter = deletedFiles.iterator(); iter.hasNext();) {
File aDeletedFile = (File ) iter.next();
if (this.sourceFilesDefiningAspects.contains(aDeletedFile)) {
removeAllResultsOfLastBuild();
if (stateListener!=null) stateListener.detectedAspectDeleted(aDeletedFile);
return false;
}
}
return true;
}
private Collection getModifiedFiles() {
return getModifiedFiles(lastSuccessfulBuildTime);
}
Collection getModifiedFiles(long lastBuildTime) {
List ret = new ArrayList();
//not our job to account for new and deleted files
for (Iterator i = buildConfig.getFiles().iterator(); i.hasNext(); ) {
File file = (File)i.next();
if (!file.exists()) continue;
long modTime = file.lastModified();
// System.out.println("check: " + file + " mod " + modTime + " build " + lastBuildTime);
// need to add 1000 since lastModTime is only accurate to a second on some (all?) platforms
if (modTime + 1000 > lastBuildTime) {
ret.add(file);
}
}
return ret;
}
private Collection getModifiedBinaryFiles() {
return getModifiedBinaryFiles(lastSuccessfulBuildTime);
}
Collection getModifiedBinaryFiles(long lastBuildTime) {
List ret = new ArrayList();
//not our job to account for new and deleted files
for (Iterator i = buildConfig.getBinaryFiles().iterator(); i.hasNext(); ) {
AjBuildConfig.BinarySourceFile bsfile = (AjBuildConfig.BinarySourceFile)i.next();
File file = bsfile.binSrc;
if (!file.exists()) continue;
long modTime = file.lastModified();
//System.out.println("check: " + file + " mod " + modTime + " build " + lastBuildTime);
// need to add 1000 since lastModTime is only accurate to a second on some (all?) platforms
if (modTime + 1000 >= lastBuildTime) {
ret.add(bsfile);
}
}
return ret;
}
private boolean classFileChangedInDirSinceLastBuild(File dir) {
// Is another process building into that directory?
AjState state = IncrementalStateManager.findStateManagingOutputLocation(dir);
File[] classFiles = FileUtil.listFiles(dir, new FileFilter() {
public boolean accept(File pathname) {
return pathname.getName().endsWith(".class");
}
});
for (int i = 0; i < classFiles.length; i++) {
long modTime = classFiles[i].lastModified();
if ((modTime+1000)>=lastSuccessfulBuildTime) {
// so the class on disk has changed since our last successful build
// To work out if it is a real change we should ask any state
// object managing this output location whether the file has
// structurally changed or not
if (state!=null) {
boolean realChange = state.hasStructuralChangedSince(classFiles[i],lastSuccessfulBuildTime);
if (realChange) return true;
} else {
// FIXME asc you should ask Eclipse project state here...
return true; // no state object to ask so it must have changed
}
}
}
return false;
}
/**
* Determine if a file has changed since a given time, using the local information
* recorded in the structural changes data structure.
*
* file is the file we are wondering about
* lastSBT is the last build time for the state asking the question
*/
private boolean hasStructuralChangedSince(File file,long lastSuccessfulBuildTime) {
//long lastModTime = file.lastModified();
Long l = (Long)structuralChangesSinceLastFullBuild.get(file.getAbsolutePath());
long strucModTime = -1;
if (l!=null) strucModTime = l.longValue();
else strucModTime = this.lastSuccessfulFullBuildTime;
// we now have:
// 'strucModTime'-> the last time the class was structurally changed
return (strucModTime>lastSuccessfulBuildTime);
}
private boolean pathChange(AjBuildConfig oldConfig, AjBuildConfig newConfig) {
boolean changed = false;
List oldClasspath = oldConfig.getClasspath();
List newClasspath = newConfig.getClasspath();
if (stateListener!=null) stateListener.aboutToCompareClasspaths(oldClasspath,newClasspath);
if (changed(oldClasspath,newClasspath,true,oldConfig.getOutputDir())) return true;
List oldAspectpath = oldConfig.getAspectpath();
List newAspectpath = newConfig.getAspectpath();
if (changed(oldAspectpath,newAspectpath,true,oldConfig.getOutputDir())) return true;
List oldInJars = oldConfig.getInJars();
List newInJars = newConfig.getInJars();
if (changed(oldInJars,newInJars,false,oldConfig.getOutputDir())) return true;
List oldInPath = oldConfig.getInpath();
List newInPath = newConfig.getInpath();
if (changed(oldInPath, newInPath,false,oldConfig.getOutputDir())) return true;
return changed;
}
private boolean changed(List oldPath, List newPath, boolean checkClassFiles, File oldOutputLocation) {
if (oldPath == null) oldPath = new ArrayList();
if (newPath == null) newPath = new ArrayList();
try {
if (oldOutputLocation != null) {
oldOutputLocation = oldOutputLocation.getCanonicalFile();
}
} catch(IOException ex) { /* we did our best...*/ }
if (oldPath.size() != newPath.size()) {
return true;
}
for (int i = 0; i < oldPath.size(); i++) {
if (!oldPath.get(i).equals(newPath.get(i))) {
return true;
}
Object o = oldPath.get(i); // String on classpath, File on other paths
File f = null;
if (o instanceof String) {
f = new File((String)o);
} else {
f = (File) o;
}
if (f.exists() && !f.isDirectory() && (f.lastModified() >= lastSuccessfulBuildTime)) {
return true;
}
if (f.exists() && f.isDirectory() && checkClassFiles && !(f.equals(oldOutputLocation))) {
boolean b= classFileChangedInDirSinceLastBuild(f);
if (b && stateListener!=null) stateListener.detectedClassChangeInThisDir(f);
if (b) return true;
}
}
return false;
}
public List getFilesToCompile(boolean firstPass) {
List thisTime = new ArrayList();
if (firstPass) {
compiledSourceFiles = new ArrayList();
Collection modifiedFiles = getModifiedFiles();
//System.out.println("modified: " + modifiedFiles);
thisTime.addAll(modifiedFiles);
//??? eclipse IncrementalImageBuilder appears to do this
// for (Iterator i = modifiedFiles.iterator(); i.hasNext();) {
// File file = (File) i.next();
// addDependentsOf(file);
// }
thisTime.addAll(addedFiles);
deleteClassFiles();
deleteResources();
addAffectedSourceFiles(thisTime,thisTime);
} else {
addAffectedSourceFiles(thisTime,compiledSourceFiles);
}
compiledSourceFiles = thisTime;
return thisTime;
}
private boolean maybeIncremental() {
return (FORCE_INCREMENTAL_DURING_TESTING || this.couldBeSubsequentIncrementalBuild);
}
public Map /* String -> List<ucf> */ getBinaryFilesToCompile(boolean firstTime) {
if (lastSuccessfulBuildTime == -1 || buildConfig == null || !maybeIncremental()) {
return binarySourceFiles;
}
// else incremental...
Map toWeave = new HashMap();
if (firstTime) {
List addedOrModified = new ArrayList();
addedOrModified.addAll(addedBinaryFiles);
addedOrModified.addAll(getModifiedBinaryFiles());
for (Iterator iter = addedOrModified.iterator(); iter.hasNext();) {
AjBuildConfig.BinarySourceFile bsf = (AjBuildConfig.BinarySourceFile) iter.next();
UnwovenClassFile ucf = createUnwovenClassFile(bsf);
if (ucf == null) continue;
List ucfs = new ArrayList();
ucfs.add(ucf);
addDependentsOf(ucf.getClassName());
binarySourceFiles.put(bsf.binSrc.getPath(),ucfs);
List cfs = new ArrayList(1);
cfs.add(getClassFileFor(ucf));
this.inputClassFilesBySource.put(bsf.binSrc.getPath(), cfs);
toWeave.put(bsf.binSrc.getPath(),ucfs);
}
deleteBinaryClassFiles();
} else {
// return empty set... we've already done our bit.
}
return toWeave;
}
/**
* Called when a path change is about to trigger a full build, but
* we haven't cleaned up from the last incremental build...
*/
private void removeAllResultsOfLastBuild() {
// remove all binarySourceFiles, and all classesFromName...
for (Iterator iter = this.inputClassFilesBySource.values().iterator(); iter.hasNext();) {
List cfs = (List) iter.next();
for (Iterator iterator = cfs.iterator(); iterator.hasNext();) {
ClassFile cf = (ClassFile) iterator.next();
cf.deleteFromFileSystem();
}
}
for (Iterator iterator = classesFromName.values().iterator(); iterator.hasNext();) {
File f = (File) iterator.next();
new ClassFile("",f).deleteFromFileSystem();
}
for (Iterator iter = resources.iterator(); iter.hasNext();) {
String resource = (String) iter.next();
new File(buildConfig.getOutputDir(),resource).delete();
}
}
private void deleteClassFiles() {
for (Iterator i = deletedFiles.iterator(); i.hasNext(); ) {
File deletedFile = (File)i.next();
addDependentsOf(deletedFile);
List cfs = (List) this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(deletedFile);
this.fullyQualifiedTypeNamesResultingFromCompilationUnit.remove(deletedFile);
if (cfs != null) {
for (Iterator iter = cfs.iterator(); iter.hasNext();) {
ClassFile cf = (ClassFile) iter.next();
deleteClassFile(cf);
}
}
}
}
private void deleteBinaryClassFiles() {
// range of bsf is ucfs, domain is files (.class and jars) in inpath/jars
for (Iterator iter = deletedBinaryFiles.iterator(); iter.hasNext();) {
AjBuildConfig.BinarySourceFile deletedFile = (AjBuildConfig.BinarySourceFile) iter.next();
List cfs = (List) this.inputClassFilesBySource.get(deletedFile.binSrc.getPath());
for (Iterator iterator = cfs.iterator(); iterator.hasNext();) {
deleteClassFile((ClassFile)iterator.next());
}
this.inputClassFilesBySource.remove(deletedFile.binSrc.getPath());
}
}
private void deleteResources() {
List oldResources = new ArrayList();
oldResources.addAll(resources);
// note - this deliberately ignores resources in jars as we don't yet handle jar changes
// with incremental compilation
for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext(); ) {
File inPathElement = (File)i.next();
if (inPathElement.isDirectory() && AjBuildManager.COPY_INPATH_DIR_RESOURCES) {
deleteResourcesFromDirectory(inPathElement,oldResources);
}
}
if (buildConfig.getSourcePathResources() != null) {
for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) {
String resource = (String)i.next();
maybeDeleteResource(resource, oldResources);
}
}
// oldResources need to be deleted...
for (Iterator iter = oldResources.iterator(); iter.hasNext();) {
String victim = (String) iter.next();
File f = new File(buildConfig.getOutputDir(),victim);
if (f.exists()) {
f.delete();
}
resources.remove(victim);
}
}
private void maybeDeleteResource(String resName, List oldResources) {
if (resources.contains(resName)) {
oldResources.remove(resName);
File source = new File(buildConfig.getOutputDir(),resName);
if ((source != null) && (source.exists()) &&
(source.lastModified() >= lastSuccessfulBuildTime)) {
resources.remove(resName); // will ensure it is re-copied
}
}
}
private void deleteResourcesFromDirectory(File dir, List oldResources) {
File[] files = FileUtil.listFiles(dir,new FileFilter() {
public boolean accept(File f) {
boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")) ;
return accept;
}
});
// For each file, add it either as a real .class file or as a resource
for (int i = 0; i < files.length; i++) {
// ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
// or we are in trouble...
String filename = files[i].getAbsolutePath().substring(
dir.getAbsolutePath().length()+1);
maybeDeleteResource(filename, oldResources);
}
}
private void deleteClassFile(ClassFile cf) {
classesFromName.remove(cf.fullyQualifiedTypeName);
weaver.deleteClassFile(cf.fullyQualifiedTypeName);
cf.deleteFromFileSystem();
}
private UnwovenClassFile createUnwovenClassFile(AjBuildConfig.BinarySourceFile bsf) {
UnwovenClassFile ucf = null;
try {
ucf = weaver.addClassFile(bsf.binSrc, bsf.fromInPathDirectory, buildConfig.getOutputDir());
} catch(IOException ex) {
IMessage msg = new Message("can't read class file " + bsf.binSrc.getPath(),
new SourceLocation(bsf.binSrc,0),false);
buildManager.handler.handleMessage(msg);
}
return ucf;
}
public void noteResult(InterimCompilationResult result) {
if (!maybeIncremental()) {
return;
}
File sourceFile = new File(result.fileName());
CompilationResult cr = result.result();
if (result != null) {
references.put(sourceFile, new ReferenceCollection(cr.qualifiedReferences, cr.simpleNameReferences));
}
UnwovenClassFile[] unwovenClassFiles = result.unwovenClassFiles();
for (int i = 0; i < unwovenClassFiles.length; i++) {
File lastTimeRound = (File) classesFromName.get(unwovenClassFiles[i].getClassName());
recordClassFile(unwovenClassFiles[i],lastTimeRound);
classesFromName.put(unwovenClassFiles[i].getClassName(),new File(unwovenClassFiles[i].getFilename()));
}
// need to do this before types are deleted from the World...
recordWhetherCompilationUnitDefinedAspect(sourceFile,cr);
deleteTypesThatWereInThisCompilationUnitLastTimeRoundButHaveBeenDeletedInThisIncrement(sourceFile, unwovenClassFiles);
recordFQNsResultingFromCompilationUnit(sourceFile,result);
}
/**
* Currently unused, if we ditch classesFromName, we might need this.... (in noteResult)
* @param file
* @return
*/
private UnwovenClassFile maybeGetExistingClassFileFor(UnwovenClassFile classFile) {
File existing = new File(classFile.getFilename());
if (!existing.exists()) {
return null;
}
else {
try {
return new UnwovenClassFile(classFile.getFilename(),FileUtil.readAsByteArray(existing));
}
catch (IOException ex) {
throw new IllegalStateException("Unable to read contents of '" + classFile.getFilename() + "' " +
"from last compile cycle");
}
}
}
/**
* @param sourceFile
* @param unwovenClassFiles
*/
private void deleteTypesThatWereInThisCompilationUnitLastTimeRoundButHaveBeenDeletedInThisIncrement(File sourceFile, UnwovenClassFile[] unwovenClassFiles) {
List classFiles = (List) this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(sourceFile);
if (classFiles != null) {
for (int i = 0; i < unwovenClassFiles.length; i++) {
// deleting also deletes types from the weaver... don't do this if they are
// still present this time around...
removeFromClassFilesIfPresent(unwovenClassFiles[i].getClassName(),classFiles);
}
for (Iterator iter = classFiles.iterator(); iter.hasNext();) {
ClassFile cf = (ClassFile) iter.next();
deleteClassFile(cf);
}
}
}
private void removeFromClassFilesIfPresent(String className, List classFiles) {
ClassFile victim = null;
for (Iterator iter = classFiles.iterator(); iter.hasNext();) {
ClassFile cf = (ClassFile) iter.next();
if (cf.fullyQualifiedTypeName.equals(className)) {
victim = cf;
break;
}
}
if (victim != null) {
classFiles.remove(victim);
}
}
/**
* Record the fully-qualified names of the types that were declared in the given
* source file.
*
* @param sourceFile, the compilation unit
* @param icr, the CompilationResult from compiling it
*/
private void recordFQNsResultingFromCompilationUnit(File sourceFile, InterimCompilationResult icr) {
List classFiles = new ArrayList();
UnwovenClassFile[] types = icr.unwovenClassFiles();
for (int i = 0; i < types.length; i++) {
classFiles.add(new ClassFile(types[i].getClassName(),new File(types[i].getFilename())));
}
this.fullyQualifiedTypeNamesResultingFromCompilationUnit.put(sourceFile,classFiles);
}
/**
* If this compilation unit defined an aspect, we need to know in case it is
* modified in a future increment.
*
* @param sourceFile
* @param cr
*/
private void recordWhetherCompilationUnitDefinedAspect(File sourceFile, CompilationResult cr) {
this.sourceFilesDefiningAspects.remove(sourceFile);
if (cr!=null) {
Map compiledTypes = cr.compiledTypes;
if (compiledTypes!=null) {
for (Iterator iterator = compiledTypes.keySet().iterator(); iterator.hasNext();) {
char[] className = (char[])iterator.next();
String typeName = new String(className).replace('/','.');
if (typeName.indexOf(IWeaver.SYNTHETIC_CLASS_POSTFIX) == -1) {
ResolvedType rt = world.resolve(typeName);
if (rt.isMissing()) {
throw new IllegalStateException("Type '" + rt.getSignature() + "' not found in world!");
}
if (rt.isAspect()) {
this.sourceFilesDefiningAspects.add(sourceFile);
break;
}
}
}
}
}
}
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, File lastTime) {
if (simpleStrings == null) {
// batch build
// record resolved type for structural comparisions in future increments
// this records a second reference to a structure already held in memory
// by the world.
ResolvedType rType = world.resolve(thisTime.getClassName());
if (!rType.isMissing()) {
try {
ClassFileReader reader = new ClassFileReader(thisTime.getBytes(), null);
this.resolvedTypeStructuresFromLastBuild.put(thisTime.getClassName(),new CompactStructureRepresentation(reader));
} catch (ClassFormatException cfe) {
throw new BCException("Unexpected problem processing class",cfe);
}
}
return;
}
CompactStructureRepresentation existingStructure = (CompactStructureRepresentation) this.resolvedTypeStructuresFromLastBuild.get(thisTime.getClassName());
ReferenceType newResolvedType = (ReferenceType) world.resolve(thisTime.getClassName());
if (!newResolvedType.isMissing()) {
try {
ClassFileReader reader = new ClassFileReader(thisTime.getBytes(), null);
this.resolvedTypeStructuresFromLastBuild.put(thisTime.getClassName(),new CompactStructureRepresentation(reader));
} catch (ClassFormatException cfe) {
throw new BCException("Unexpected problem processing class",cfe);
}
}
if (lastTime == null) {
addDependentsOf(thisTime.getClassName());
return;
}
if (newResolvedType.isMissing()) {
return;
}
world.ensureAdvancedConfigurationProcessed();
byte[] newBytes = thisTime.getBytes();
try {
ClassFileReader reader = new ClassFileReader(newBytes, lastTime.getAbsolutePath().toCharArray());
// ignore local types since they're only visible inside a single method
if (!(reader.isLocal() || reader.isAnonymous())) {
if (hasStructuralChanges(reader,existingStructure)) {
if (world.forDEBUG_structuralChangesCode)
System.err.println("Detected a structural change in "+thisTime.getFilename());
structuralChangesSinceLastFullBuild.put(thisTime.getFilename(),new Long(currentBuildTime));
addDependentsOf(new String(reader.getName()).replace('/','.'));
}
}
} catch (ClassFormatException e) {
addDependentsOf(thisTime.getClassName());
}
}
private static final char[][] EMPTY_CHAR_ARRAY = new char[0][];
private static final char[] BRACKET_V = {')','V'};
/**
* Compare the class structure of the new intermediate (unwoven) class with the
* existingResolvedType of the same class that we have in the world, looking for
* any structural differences (and ignoring aj members resulting from weaving....)
*
* Some notes from Andy... lot of problems here, which I've eventually resolved
* by building the compactstructure based on a classfilereader, rather than on a
* ResolvedType. There are accessors for inner types and funky fields that the
* compiler creates to support the language - for non-static inner types it
* also mangles ctors to be prefixed with an instance of the surrounding type.
*
* Warning : long but boring method implementation...
* @param reader
* @param existingType
* @return
*/
private boolean hasStructuralChanges(ClassFileReader reader, CompactStructureRepresentation existingType) {
if (existingType == null) {
return true;
}
// modifiers
if (!modifiersEqual(reader.getModifiers(),existingType.modifiers)) {
return true;
}
// generic signature
if (!CharOperation.equals(reader.getGenericSignature(),existingType.genericSignature)) {
return true;
}
// superclass name
if (!CharOperation.equals(reader.getSuperclassName(),existingType.superclassName)) {
return true;
}
// interfaces
char[][] existingIfs = existingType.interfaces;
char[][] newIfsAsChars = reader.getInterfaceNames();
if (newIfsAsChars == null) { newIfsAsChars = EMPTY_CHAR_ARRAY; } // damn I'm lazy...
if (existingIfs == null) { existingIfs = EMPTY_CHAR_ARRAY; }
if (existingIfs.length != newIfsAsChars.length) return true;
new_interface_loop: for (int i = 0; i < newIfsAsChars.length; i++) {
for (int j = 0; j < existingIfs.length; j++) {
if (CharOperation.equals(existingIfs[j],newIfsAsChars[i])) {
continue new_interface_loop;
}
}
return true;
}
// fields
MemberStructure[] existingFields = existingType.fields;
IBinaryField[] newFields = reader.getFields();
if (newFields == null) { newFields = new IBinaryField[0]; }
// all redundant for now ... could be an optimization at some point...
// remove any ajc$XXX fields from those we compare with
// the existing fields - bug 129163
// List nonGenFields = new ArrayList();
// for (int i = 0; i < newFields.length; i++) {
// IBinaryField field = newFields[i];
// //if (!CharOperation.prefixEquals(NameMangler.AJC_DOLLAR_PREFIX,field.getName())) { // this would skip ajc$ fields
// //if ((field.getModifiers()&0x1000)==0) // 0x1000 => synthetic - this will skip synthetic fields (eg. this$0)
// nonGenFields.add(field);
// //}
// }
if (newFields.length != existingFields.length) return true;
new_field_loop:
for (int i = 0; i < newFields.length; i++) {
IBinaryField field = newFields[i];
char[] fieldName = field.getName();
for (int j = 0; j < existingFields.length; j++) {
if (CharOperation.equals(existingFields[j].name,fieldName)) {
if (!modifiersEqual(field.getModifiers(),existingFields[j].modifiers)) {
return true;
}
if (!CharOperation.equals(existingFields[j].signature,field.getTypeName())) {
return true;
}
continue new_field_loop;
}
}
return true;
}
// methods
MemberStructure[] existingMethods = existingType.methods;
IBinaryMethod[] newMethods = reader.getMethods();
if (newMethods == null) { newMethods = new IBinaryMethod[0]; }
// all redundant for now ... could be an optimization at some point...
// Ctors in a non-static inner type have an 'extra parameter' of the enclosing type.
// If skippableDescriptorPrefix gets set here then it is set to the descriptor portion
// for this 'extra parameter'. For an inner class of pkg.Foo the skippable descriptor
// prefix will be '(Lpkg/Foo;' - so later when comparing <init> methods we know what to
// compare.
// IF THIS CODE NEEDS TO GET MORE COMPLICATED, I THINK ITS WORTH RIPPING IT ALL OUT AND
// CREATING THE STRUCTURAL CHANGES OBJECT BASED ON CLASSREADER OUTPUT RATHER THAN
// THE RESOLVEDTYPE - THEN THERE WOULD BE NO NEED TO TREAT SOME METHODS IN A PECULIAR
// WAY.
// char[] skippableDescriptorPrefix = null;
// char[] enclosingTypeName = reader.getEnclosingTypeName();
// boolean isStaticType = Modifier.isStatic(reader.getModifiers());
// if (!isStaticType && enclosingTypeName!=null) {
// StringBuffer sb = new StringBuffer();
// sb.append("(L").append(new String(enclosingTypeName)).append(";");
// skippableDescriptorPrefix = sb.toString().toCharArray();
// }
//
//
// // remove the aspectOf, hasAspect, clinit and ajc$XXX methods
// // from those we compare with the existing methods - bug 129163
// List nonGenMethods = new ArrayList();
// for (int i = 0; i < newMethods.length; i++) {
// IBinaryMethod method = newMethods[i];
//// if ((method.getModifiers() & 0x1000)!=0) continue; // 0x1000 => synthetic - will cause us to skip access$0 - is this always safe?
// char[] methodName = method.getSelector();
//// if (!CharOperation.equals(methodName,NameMangler.METHOD_ASPECTOF) &&
//// !CharOperation.equals(methodName,NameMangler.METHOD_HASASPECT) &&
//// !CharOperation.equals(methodName,NameMangler.STATIC_INITIALIZER) &&
//// !CharOperation.prefixEquals(NameMangler.AJC_DOLLAR_PREFIX,methodName) &&
//// !CharOperation.prefixEquals(NameMangler.CLINIT,methodName)) {
// nonGenMethods.add(method);
//// }
// }
if (newMethods.length != existingMethods.length) return true;
new_method_loop:
for (int i = 0; i < newMethods.length; i++) {
IBinaryMethod method = newMethods[i];
char[] methodName = method.getSelector();
for (int j = 0; j < existingMethods.length; j++) {
if (CharOperation.equals(existingMethods[j].name,methodName)) {
// candidate match
if (!CharOperation.equals(method.getMethodDescriptor(),existingMethods[j].signature)) {
// ok, the descriptors don't match, but is this a funky ctor on a non-static inner
// type?
// boolean mightBeOK =
// skippableDescriptorPrefix!=null && // set for inner types
// CharOperation.equals(methodName,NameMangler.INIT) && // ctor
// CharOperation.prefixEquals(skippableDescriptorPrefix,method.getMethodDescriptor()); // checking for prefix on the descriptor
// if (mightBeOK) {
// // OK, so the descriptor starts something like '(Lpkg/Foo;' - we now may need to look at the rest of the
// // descriptor if it takes >1 parameter.
// // eg. could be (Lpkg/C;Ljava/lang/String;) where the skippablePrefix is (Lpkg/C;
// char [] md = method.getMethodDescriptor();
// char[] remainder = CharOperation.subarray(md, skippableDescriptorPrefix.length, md.length);
// if (CharOperation.equals(remainder,BRACKET_V)) continue new_method_loop; // no other parameters to worry about
// char[] comparableSig = CharOperation.subarray(existingMethods[j].signature, 1, existingMethods[j].signature.length);
// boolean match = CharOperation.equals(comparableSig, remainder);
// if (match) continue new_method_loop;
// }
continue; // might be overloading
} else {
// matching sigs
if (!modifiersEqual(method.getModifiers(),existingMethods[j].modifiers)) {
return true;
}
continue new_method_loop;
}
}
}
return true; // (no match found)
}
return false;
}
private boolean modifiersEqual(int eclipseModifiers, int resolvedTypeModifiers) {
resolvedTypeModifiers = resolvedTypeModifiers & CompilerModifiers.AccJustFlag;
eclipseModifiers = eclipseModifiers & CompilerModifiers.AccJustFlag;
// if ((eclipseModifiers & CompilerModifiers.AccSuper) != 0) {
// eclipseModifiers -= CompilerModifiers.AccSuper;
// }
return (eclipseModifiers == resolvedTypeModifiers);
}
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;
}
private String stringifyList(List l) {
StringBuffer sb = new StringBuffer();
sb.append("{");
for (Iterator iter = l.iterator(); iter.hasNext();) {
Object el = (Object) iter.next();
sb.append(el);
if (iter.hasNext()) sb.append(",");
}
sb.append("}");
return sb.toString();
}
protected void addAffectedSourceFiles(List addTo, List lastTimeSources) {
if (qualifiedStrings.isEmpty() && simpleStrings.isEmpty()) return;
if (listenerDefined()) getListener().recordDecision("Examining whether any other files now need compilation based just compiling: '"+stringifyList(lastTimeSources)+"'");
// 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)
if (listenerDefined()) {
getListener().recordDecision("Need to recompile '"+file.getName().toString()+"'");
}
addTo.add(file);
}
}
}
}
// add in the things we compiled previously - I know that seems crap but otherwise we may pull woven
// stuff off disk (since we no longer have UnwovenClassFile objects) in order to satisfy references
// in the new files we are about to compile (see pr133532)
// XXX Promote addTo to a Set - then we don't need this rubbish? but does it need to be ordered?
if (addTo.size()>0) {
for (Iterator iter = lastTimeSources.iterator(); iter.hasNext();) {
Object element = (Object) iter.next();
if (!addTo.contains(element)) addTo.add(element);
}
}
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) {
List cfs = (List) this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(sourceFile);
if (cfs != null) {
for (Iterator iter = cfs.iterator(); iter.hasNext();) {
ClassFile cf = (ClassFile) iter.next();
addDependentsOf(cf.fullyQualifiedTypeName);
}
}
}
public void setStructureModel(IHierarchy model) {
structureModel = model;
}
public IHierarchy getStructureModel() {
return structureModel;
}
public void setWeaver(BcelWeaver bw) { weaver=bw;}
public BcelWeaver getWeaver() {return weaver;}
public void setWorld(BcelWorld bw) {world=bw;}
public BcelWorld getBcelWorld() {return world; }
public void setRelationshipMap(IRelationshipMap irm) { relmap = irm;}
public IRelationshipMap getRelationshipMap() { return relmap;}
public int getNumberOfStructuralChangesSinceLastFullBuild() {
return structuralChangesSinceLastFullBuild.size();
}
/** Returns last time we did a full or incremental build. */
public long getLastBuildTime() {
return lastSuccessfulBuildTime;
}
/** Returns last time we did a full build */
public long getLastFullBuildTime() {
return lastSuccessfulFullBuildTime;
}
/**
* @return Returns the buildConfig.
*/
public AjBuildConfig getBuildConfig() {
return this.buildConfig;
}
public void clearBinarySourceFiles() {
this.binarySourceFiles = new HashMap();
}
public void recordBinarySource(String fromPathName, List unwovenClassFiles) {
this.binarySourceFiles.put(fromPathName,unwovenClassFiles);
if (this.maybeIncremental()) {
List simpleClassFiles = new LinkedList();
for (Iterator iter = unwovenClassFiles.iterator(); iter.hasNext();) {
UnwovenClassFile ucf = (UnwovenClassFile) iter.next();
ClassFile cf = getClassFileFor(ucf);
simpleClassFiles.add(cf);
}
this.inputClassFilesBySource.put(fromPathName,simpleClassFiles);
}
}
/**
* @param ucf
* @return
*/
private ClassFile getClassFileFor(UnwovenClassFile ucf) {
return new ClassFile(ucf.getClassName(),new File(ucf.getFilename()));
}
public Map getBinarySourceMap() {
return this.binarySourceFiles;
}
public Map getClassNameToFileMap() {
return this.classesFromName;
}
public boolean hasResource(String resourceName) {
return this.resources.contains(resourceName);
}
public void recordResource(String resourceName) {
this.resources.add(resourceName);
}
/**
* @return Returns the addedFiles.
*/
public Set getAddedFiles() {
return this.addedFiles;
}
/**
* @return Returns the deletedFiles.
*/
public Set getDeletedFiles() {
return this.deletedFiles;
}
public void forceBatchBuildNextTimeAround() {
this.batchBuildRequiredThisTime = true;
}
public boolean requiresFullBatchBuild() {
return this.batchBuildRequiredThisTime;
}
private static class ClassFile {
public String fullyQualifiedTypeName;
public File locationOnDisk;
public ClassFile(String fqn, File location) {
this.fullyQualifiedTypeName = fqn;
this.locationOnDisk = location;
}
public void deleteFromFileSystem() {
String namePrefix = locationOnDisk.getName();
namePrefix = namePrefix.substring(0,namePrefix.lastIndexOf('.'));
final String targetPrefix = namePrefix + IWeaver.CLOSURE_CLASS_PREFIX;
File dir = locationOnDisk.getParentFile();
if (dir != null) {
File[] weaverGenerated = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(targetPrefix);
}});
if (weaverGenerated!=null) {
for (int i = 0; i < weaverGenerated.length; i++) {
weaverGenerated[i].delete();
}
}
}
locationOnDisk.delete();
}
}
private static class CompactStructureRepresentation {
char[] className;
int modifiers;
char[] genericSignature;
char[] superclassName;
char[][] interfaces;
MemberStructure[] fields;
MemberStructure[] methods;
public CompactStructureRepresentation(ClassFileReader cfr) {
this.className = cfr.getName(); // slashes...
this.modifiers = cfr.getModifiers();
this.genericSignature = cfr.getGenericSignature();
// if (this.genericSignature.length == 0) {
// this.genericSignature = null;
// }
this.superclassName = cfr.getSuperclassName(); // slashes...
interfaces = cfr.getInterfaceNames();
IBinaryField[] rFields = cfr.getFields();
this.fields = new MemberStructure[rFields==null?0:rFields.length];
if (rFields!=null) {
for (int i = 0; i < rFields.length; i++) {
this.fields[i] = new MemberStructure();
this.fields[i].name = rFields[i].getName();
this.fields[i].modifiers = rFields[i].getModifiers();
this.fields[i].signature = rFields[i].getTypeName();
}
}
IBinaryMethod[] rMethods = cfr.getMethods();
this.methods = new MemberStructure[rMethods==null?0:rMethods.length];
if (rMethods!=null) {
for (int i = 0; i < rMethods.length; i++) {
this.methods[i] = new MemberStructure();
this.methods[i].name = rMethods[i].getSelector();
this.methods[i].modifiers = rMethods[i].getModifiers();
// StringBuffer sig = new StringBuffer();
// sig.append("(");
// UnresolvedType[] pTypes = rMethods[i].getMethodDescriptor();
// for (int j = 0; j < pTypes.length; j++) {
// sig.append(pTypes[j].getSignature());
// }
// sig.append(")");
// sig.append(rMethods[i].getReturnType().getSignature());
this.methods[i].signature =rMethods[i].getMethodDescriptor();// sig.toString().toCharArray();
}
}
}
public CompactStructureRepresentation(ResolvedType forType) {
this.className = forType.getName().replace('.','/').toCharArray();
this.modifiers = forType.getModifiers();
this.genericSignature = forType.getGenericSignature().toCharArray();
if (this.genericSignature.length == 0) {
this.genericSignature = null;
}
this.superclassName = forType.getSuperclass().getName().replace('.','/').toCharArray();
ResolvedType[] rTypes = forType.getDeclaredInterfaces();
this.interfaces = new char[rTypes.length][];
for (int i = 0; i < rTypes.length; i++) {
this.interfaces[i] = rTypes[i].getName().replace('.','/').toCharArray();
}
ResolvedMember[] rFields = forType.getDeclaredFields();
this.fields = new MemberStructure[rFields.length];
for (int i = 0; i < rFields.length; i++) {
this.fields[i] = new MemberStructure();
this.fields[i].name = rFields[i].getName().toCharArray();
this.fields[i].modifiers = rFields[i].getModifiers();
this.fields[i].signature = rFields[i].getReturnType().getSignature().toCharArray();
}
ResolvedMember[] rMethods = forType.getDeclaredMethods();
this.methods = new MemberStructure[rMethods.length];
for (int i = 0; i < rMethods.length; i++) {
this.methods[i] = new MemberStructure();
this.methods[i].name = rMethods[i].getName().toCharArray();
this.methods[i].modifiers = rMethods[i].getModifiers();
StringBuffer sig = new StringBuffer();
sig.append("(");
UnresolvedType[] pTypes = rMethods[i].getParameterTypes();
for (int j = 0; j < pTypes.length; j++) {
sig.append(pTypes[j].getSignature());
}
sig.append(")");
sig.append(rMethods[i].getReturnType().getSignature());
this.methods[i].signature = sig.toString().toCharArray();
}
}
}
private static class MemberStructure {
char[] name;
int modifiers;
char[] signature;
}
public void wipeAllKnowledge() {
buildManager.state = null;
buildManager.setStructureModel(null);
}
public List getAspectNames() {
return aspectNames;
}
public void initializeAspectNamesList() {
this.aspectNames = new LinkedList();
}
// Will allow us to record decisions made during incremental processing, hopefully aid in debugging
public boolean listenerDefined() {
return stateListener!=null;
}
public IStateListener getListener() {
return stateListener;
}
}
|
134,371 |
Bug 134371 ClassCastException in AjState.recordClassFile()
|
I got this exception while working on a static inner aspect. A full rebuild avoided the problem. java.lang.ClassCastException: org.aspectj.weaver.MissingResolvedTypeWithKnownSignature at org.aspectj.ajdt.internal.core.builder.AjState.recordClassFile(AjState.java:774) at org.aspectj.ajdt.internal.core.builder.AjState.noteResult(AjState.java:627) at org.aspectj.ajdt.internal.core.builder.AjBuildManager$3.acceptResult(AjBuildManager.java:867) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterProcessing(AjCompilerAdapter.java:206) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$4$6b855184(CompilerAdapter.aj:90) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:528) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:329) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:845) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:266) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.incrementalBuild(AjBuildManager.java:168) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:117) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191)
|
resolved fixed
|
299c3a4
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-05T09:46:43Z | 2006-04-01T16:46:40Z |
tests/src/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement initial implementation
* ******************************************************************/
package org.aspectj.systemtest.incremental.tools;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.aspectj.ajdt.internal.core.builder.AjState;
import org.aspectj.ajdt.internal.core.builder.IncrementalStateManager;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.IRelationshipMap;
import org.aspectj.bridge.IMessage;
import org.aspectj.testing.util.FileUtil;
/**
* The superclass knows all about talking through Ajde to the compiler.
* The superclass isn't in charge of knowing how to simulate overlays
* for incremental builds, that is in here. As is the ability to
* generate valid build configs based on a directory structure. To
* support this we just need access to a sandbox directory - this
* sandbox is managed by the superclass (it only assumes all builds occur
* in <sandboxDir>/<projectName>/ )
*
* The idea is you can initialize multiple projects in the sandbox and
* they can all be built independently, hopefully exploiting
* incremental compilation. Between builds you can alter the contents
* of a project using the alter() method that overlays some set of
* new files onto the current set (adding new files/changing existing
* ones) - you can then drive a new build and check it behaves as
* expected.
*/
public class MultiProjectIncrementalTests extends AjdeInteractionTestbed {
public static boolean VERBOSE = false;
protected void setUp() throws Exception {
super.setUp();
AjdeInteractionTestbed.VERBOSE = VERBOSE;
AjState.FORCE_INCREMENTAL_DURING_TESTING = true;
}
protected void tearDown() throws Exception {
super.tearDown();
AjState.FORCE_INCREMENTAL_DURING_TESTING = false;
}
// Compile a single simple project
public void testTheBasics() {
initialiseProject("P1");
build("P1"); // This first build will be batch
build("P1");
checkWasntFullBuild();
checkCompileWeaveCount(0,0);
}
// source code doesnt matter, we are checking invalid path handling
public void testInvalidAspectpath_pr121395() {
initialiseProject("P1");
File f = new File("foo.jar");
Set s = new HashSet();
s.add(f);
configureAspectPath(s);
build("P1"); // This first build will be batch
checkForError("invalid aspectpath entry");
}
// Make simple changes to a project, adding a class
public void testSimpleChanges() {
initialiseProject("P1");
build("P1"); // This first build will be batch
alter("P1","inc1"); // adds a single class
build("P1");
checkCompileWeaveCount(1,-1);
build("P1");
checkCompileWeaveCount(0,-1);
}
// Make simple changes to a project, adding a class and an aspect
public void testAddingAnAspect() {
initialiseProject("P1");
build("P1"); // build 1, weave 1
alter("P1","inc1"); // adds a class
alter("P1","inc2"); // adds an aspect
build("P1"); // build 1,
long timeTakenForFullBuildAndWeave = getTimeTakenForBuild();
checkWasFullBuild(); // it *will* be a full build under the new
// "back-to-the-source strategy
checkCompileWeaveCount(5,3); // we compile X and A (the delta) find out that
// an aspect has changed, go back to the source
// and compile X,A,C, then weave them all.
build("P1");
long timeTakenForSimpleIncBuild = getTimeTakenForBuild();
// I don't think this test will have timing issues as the times should be *RADICALLY* different
// On my config, first build time is 2093ms and the second is 30ms
assertTrue("Should not take longer for the trivial incremental build! first="+timeTakenForFullBuildAndWeave+
"ms second="+timeTakenForSimpleIncBuild+"ms",
timeTakenForSimpleIncBuild<timeTakenForFullBuildAndWeave);
}
public void testBuildingTwoProjectsInTurns() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
build("P2");
build("P1");
checkWasntFullBuild();
build("P2");
checkWasntFullBuild();
}
/**
* In order for this next test to run, I had to move the weaver/world pair we keep in the
* AjBuildManager instance down into the state object - this makes perfect sense - otherwise
* when reusing the state for another project we'd not be switching to the right weaver/world
* for that project.
*/
public void testBuildingTwoProjectsMakingSmallChanges() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
build("P2");
build("P1");
checkWasntFullBuild();
build("P2");
checkWasntFullBuild();
alter("P1","inc1"); // adds a class
alter("P1","inc2"); // adds an aspect
build("P1");
checkWasFullBuild(); // adding an aspect makes us go back to the source
}
/**
* Setup up two simple projects and build them in turn - check the
* structure model is right after each build
*/
public void testBuildingTwoProjectsAndVerifyingModel() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
}
// Setup up two simple projects and build them in turn - check the
// structure model is right after each build
public void testBuildingTwoProjectsAndVerifyingStuff() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
}
/**
* Complex. Here we are testing that a state object records structural changes since
* the last full build correctly. We build a simple project from scratch - this will
* be a full build and so the structural changes since last build count should be 0.
* We then alter a class, adding a new method and check structural changes is 1.
*/
public void testStateManagement1() {
File binDirectoryForP1 = new File(getFile("P1","bin"));
initialiseProject("P1");
build("P1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1);
assertTrue("There should be a state object for project P1",ajs!=null);
assertTrue("Should be no structural changes as it was a full build but found: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("P1","inc3"); // adds a method to the class C.java
build("P1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin")));
assertTrue("There should be state for project P1",ajs!=null);
checkWasntFullBuild();
assertTrue("Should be one structural changes as it was a full build but found: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==1);
}
/**
* Complex. Here we are testing that a state object records structural changes since
* the last full build correctly. We build a simple project from scratch - this will
* be a full build and so the structural changes since last build count should be 0.
* We then alter a class, changing body of a method, not the structure and
* check struc changes is still 0.
*/
public void testStateManagement2() {
File binDirectoryForP1 = new File(getFile("P1","bin"));
initialiseProject("P1");
alter("P1","inc3"); // need this change in here so 'inc4' can be applied without making
// it a structural change
build("P1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1);
assertTrue("There should be state for project P1",ajs!=null);
assertTrue("Should be no struc changes as its a full build: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("P1","inc4"); // changes body of main() method but does *not* change the structure of C.java
build("P1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin")));
assertTrue("There should be state for project P1",ajs!=null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
}
/**
* The C.java file modified in this test has an inner class - this means the inner class
* has a this$0 field and <init>(C) ctor to watch out for when checking for structural changes
*
*/
public void testStateManagement3() {
File binDirForInterproject1 = new File(getFile("interprojectdeps1","bin"));
initialiseProject("interprojectdeps1");
build("interprojectdeps1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject1);
assertTrue("There should be state for project P1",ajs!=null);
assertTrue("Should be no struc changes as its a full build: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("interprojectdeps1","inc1"); // adds a space to C.java
build("interprojectdeps1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps1","bin")));
assertTrue("There should be state for project interprojectdeps1",ajs!=null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
}
/**
* The C.java file modified in this test has an inner class - which has two ctors - this checks
* how they are mangled with an instance of C.
*
*/
public void testStateManagement4() {
File binDirForInterproject2 = new File(getFile("interprojectdeps2","bin"));
initialiseProject("interprojectdeps2");
build("interprojectdeps2"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject2);
assertTrue("There should be state for project interprojectdeps2",ajs!=null);
assertTrue("Should be no struc changes as its a full build: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("interprojectdeps2","inc1"); // minor change to C.java
build("interprojectdeps2");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps2","bin")));
assertTrue("There should be state for project interprojectdeps1",ajs!=null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
}
/**
* The C.java file modified in this test has an inner class - it has two ctors but
* also a reference to C.this in it - which will give rise to an accessor being
* created in C
*
*/
public void testStateManagement5() {
File binDirForInterproject3 = new File(getFile("interprojectdeps3","bin"));
initialiseProject("interprojectdeps3");
build("interprojectdeps3"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject3);
assertTrue("There should be state for project interprojectdeps3",ajs!=null);
assertTrue("Should be no struc changes as its a full build: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("interprojectdeps3","inc1"); // minor change to C.java
build("interprojectdeps3");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps3","bin")));
assertTrue("There should be state for project interprojectdeps1",ajs!=null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
}
/**
* Now the most complex test. Create a dependancy between two projects. Building
* one may affect whether the other does an incremental or full build. The
* structural information recorded in the state object should be getting used
* to control whether a full build is necessary...
*/
public void testBuildingDependantProjects() {
initialiseProject("P1");
initialiseProject("P2");
configureNewProjectDependency("P2","P1");
build("P1");
build("P2"); // now everything is consistent and compiled
alter("P1","inc1"); // adds a second class
build("P1");
build("P2"); // although a second class was added - P2 can't be using it, so we don't full build here :)
checkWasntFullBuild();
alter("P1","inc3"); // structurally changes one of the classes
build("P1");
build("P2"); // build notices the structural change
checkWasFullBuild();
alter("P1","inc4");
build("P1");
build("P2"); // build sees a change but works out its not structural
checkWasntFullBuild();
}
public void testPr85132() {
initialiseProject("PR85132");
build("PR85132");
alter("PR85132","inc1");
build("PR85132");
}
// parameterization of generic aspects
public void xpr134471_testPr125405() {
initialiseProject("PR125405");
build("PR125405");
checkCompileWeaveCount(1,1);
alter("PR125405","inc1");
build("PR125405");
// "only abstract aspects can have type parameters"
checkForError("only abstract aspects can have type parameters");
alter("PR125405","inc2");
build("PR125405");
checkCompileWeaveCount(1,1);
assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0);
}
public void testPr128618() {
initialiseProject("PR128618_1");
initialiseProject("PR128618_2");
configureNewProjectDependency("PR128618_2","PR128618_1");
assertTrue("there should be no warning messages before we start",
MyTaskListManager.getWarningMessages().isEmpty());
build("PR128618_1");
build("PR128618_2");
List warnings = MyTaskListManager.getWarningMessages();
assertTrue("Should be one warning, but there are #"+warnings.size(),warnings.size()==1);
IMessage msg = (IMessage)(MyTaskListManager.getWarningMessages().get(0));
assertEquals("warning should be against the FFDC.aj resource","FFDC.aj",msg.getSourceLocation().getSourceFile().getName());
alter("PR128618_2","inc1");
build("PR128618_2");
checkWasntFullBuild();
IMessage msg2 = (IMessage)(MyTaskListManager.getWarningMessages().get(0));
assertEquals("warning should be against the FFDC.aj resource","FFDC.aj",msg2.getSourceLocation().getSourceFile().getName());
assertFalse("a new warning message should have been generated", msg.equals(msg2));
}
public void testPr92837() {
initialiseProject("PR92837");
build("PR92837");
alter("PR92837","inc1");
build("PR92837");
}
public void testPr119570() {
initialiseProject("PR119570");
build("PR119570");
assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0);
}
public void testPr119570_2() {
initialiseProject("PR119570_2");
build("PR119570_2");
List l = MyTaskListManager.getWarningMessages();
assertTrue("Should be no warnings, but got "+l,l.size()==0);
}
// If you fiddle with the compiler options - you must manually reset the options at the end of the test
public void testPr117209() {
try {
initialiseProject("pr117209");
configureNonStandardCompileOptions("-proceedOnError");
build("pr117209");
checkCompileWeaveCount(6,6);
} finally {
MyBuildOptionsAdapter.reset();
}
}
public void testPr114875() {
initialiseProject("pr114875");
build("pr114875");
alter("pr114875","inc1");
build("pr114875");
checkWasFullBuild();
alter("pr114875","inc2");
build("pr114875");
checkWasFullBuild(); // back to the source for an aspect change
}
public void testPr117882() {
// AjdeInteractionTestbed.VERBOSE=true;
// AjdeInteractionTestbed.configureBuildStructureModel(true);
initialiseProject("PR117882");
build("PR117882");
checkWasFullBuild();
alter("PR117882","inc1");
build("PR117882");
checkWasFullBuild(); // back to the source for an aspect
// AjdeInteractionTestbed.VERBOSE=false;
// AjdeInteractionTestbed.configureBuildStructureModel(false);
}
public void testPr117882_2() {
// AjdeInteractionTestbed.VERBOSE=true;
// AjdeInteractionTestbed.configureBuildStructureModel(true);
initialiseProject("PR117882_2");
build("PR117882_2");
checkWasFullBuild();
alter("PR117882_2","inc1");
build("PR117882_2");
checkWasFullBuild(); // back to the source...
//checkCompileWeaveCount(1,4);
//fullBuild("PR117882_2");
//checkWasFullBuild();
// AjdeInteractionTestbed.VERBOSE=false;
// AjdeInteractionTestbed.configureBuildStructureModel(false);
}
public void testPr115251() {
//AjdeInteractionTestbed.VERBOSE=true;
initialiseProject("PR115251");
build("PR115251");
checkWasFullBuild();
alter("PR115251","inc1");
build("PR115251");
checkWasFullBuild(); // back to the source
}
// public void testPr124399() {
// AjdeInteractionTestbed.VERBOSE=true;
// configureBuildStructureModel(true);
// initialiseProject("PR124399");
// build("PR124399");
// checkWasFullBuild();
// alter("PR124399","inc1");
// build("PR124399");
// checkWasntFullBuild();
// }
public void testPr121384() {
// AjdeInteractionTestbed.VERBOSE=true;
// AsmManager.setReporting("c:/foo.txt",true,true,true,false);
MyBuildOptionsAdapter.setNonStandardOptions("-showWeaveInfo");
configureBuildStructureModel(true);
initialiseProject("pr121384");
build("pr121384");
checkWasFullBuild();
alter("pr121384","inc1");
build("pr121384");
checkWasntFullBuild();
}
/* public void testPr111779() {
super.VERBOSE=true;
initialiseProject("PR111779");
build("PR111779");
alter("PR111779","inc1");
build("PR111779");
}
*/
public void testPr93310_1() {
initialiseProject("PR93310_1");
build("PR93310_1");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_1" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java";
(new File(fileC2)).delete();
alter("PR93310_1","inc1");
build("PR93310_1");
checkWasFullBuild();
int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size();
assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1);
String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0);
assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java"));
}
public void testPr93310_2() {
initialiseProject("PR93310_2");
build("PR93310_2");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_2" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java";
(new File(fileC2)).delete();
alter("PR93310_2","inc1");
build("PR93310_2");
checkWasFullBuild();
int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size();
assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1);
String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0);
assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java"));
}
// Stage1: Compile two files, pack.A and pack.A1 - A1 sets a protected field in A.
// Stage2: make the field private in class A > gives compile error
// Stage3: Add a new aspect whilst there is a compile error !
public void testPr113531() {
initialiseProject("PR113531");
build("PR113531");
assertFalse("build should have compiled ok",
MyTaskListManager.hasErrorMessages());
alter("PR113531","inc1");
build("PR113531");
assertEquals("error message should be 'foo cannot be resolved' ",
"foo cannot be resolved",
((IMessage)MyTaskListManager.getErrorMessages().get(0))
.getMessage());
alter("PR113531","inc2");
build("PR113531");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
assertEquals("error message should be 'foo cannot be resolved' ",
"foo cannot be resolved",
((IMessage)MyTaskListManager.getErrorMessages().get(0))
.getMessage());
}
// Stage 1: Compile the 4 files, pack.A2 extends pack.A1 (aspects) where
// A2 uses a protected field in A1 and pack.C2 extends pack.C1 (classes)
// where C2 uses a protected field in C1
// Stage 2: make the field private in class C1 ==> compile errors in C2
// Stage 3: make the field private in aspect A1 whilst there's the compile
// error.
// There shouldn't be a BCExcpetion saying can't find delegate for pack.C2
public void testPr119882() {
initialiseProject("PR119882");
build("PR119882");
assertFalse("build should have compiled ok",MyTaskListManager.hasErrorMessages());
alter("PR119882","inc1");
build("PR119882");
//fullBuild("PR119882");
List errors = MyTaskListManager.getErrorMessages();
assertTrue("Should be at least one error, but got none",errors.size()==1);
assertEquals("error message should be 'i cannot be resolved' ",
"i cannot be resolved",
((IMessage)errors.get(0))
.getMessage());
alter("PR119882","inc2");
build("PR119882");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
assertEquals("error message should be 'i cannot be resolved' ",
"i cannot be resolved",
((IMessage)errors.get(0))
.getMessage());
}
public void testPr112736() {
// AjdeInteractionTestbed.VERBOSE = true;
initialiseProject("PR112736");
build("PR112736");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR112736" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "A.java";
(new File(fileC2)).delete();
alter("PR112736","inc1");
build("PR112736");
checkWasFullBuild();
}
/**
* We have problems with multiple rewrites of a pointcut across incremental builds.
*/
public void testPr113257() {
initialiseProject("PR113257");
build("PR113257");
alter("PR113257","inc1");
build("PR113257");
checkWasFullBuild(); // back to the source
alter("PR113257","inc1");
build("PR113257");
}
public void testPr123612() {
initialiseProject("PR123612");
build("PR123612");
alter("PR123612","inc1");
build("PR123612");
checkWasFullBuild(); // back to the source
}
public void testPr128655() {
configureNonStandardCompileOptions("-showWeaveInfo");
initialiseProject("pr128655");
build("pr128655");
List firstBuildMessages = MyTaskListManager.getWeavingMessages();
assertTrue("Should be at least one message about the dec @type, but there were none",firstBuildMessages.size()>0);
alter("pr128655","inc1");
build("pr128655");
checkWasntFullBuild(); // back to the source
List secondBuildMessages = MyTaskListManager.getWeavingMessages();
// check they are the same
for (int i = 0; i < firstBuildMessages.size(); i++) {
IMessage m1 = (IMessage)firstBuildMessages.get(i);
IMessage m2 = (IMessage)secondBuildMessages.get(i);
if (!m1.toString().equals(m2.toString())) {
System.err.println("Message during first build was: "+m1);
System.err.println("Message during second build was: "+m1);
fail("The two messages should be the same, but are not: \n"+m1+"!="+m2);
}
}
}
// Similar to above, but now the annotation is in the default package
public void testPr128655_2() {
configureNonStandardCompileOptions("-showWeaveInfo");
initialiseProject("pr128655_2");
build("pr128655_2");
List firstBuildMessages = MyTaskListManager.getWeavingMessages();
assertTrue("Should be at least one message about the dec @type, but there were none",firstBuildMessages.size()>0);
alter("pr128655_2","inc1");
build("pr128655_2");
checkWasntFullBuild(); // back to the source
List secondBuildMessages = MyTaskListManager.getWeavingMessages();
// check they are the same
for (int i = 0; i < firstBuildMessages.size(); i++) {
IMessage m1 = (IMessage)firstBuildMessages.get(i);
IMessage m2 = (IMessage)secondBuildMessages.get(i);
if (!m1.toString().equals(m2.toString())) {
System.err.println("Message during first build was: "+m1);
System.err.println("Message during second build was: "+m1);
fail("The two messages should be the same, but are not: \n"+m1+"!="+m2);
}
}
}
// test for comment #31 - NPE
public void testPr129163() {
configureBuildStructureModel(true);
initialiseProject("PR129613");
build("PR129613");
alter("PR129613","inc1");
build("PR129613");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
assertEquals("warning message should be 'no match for this type name: File [Xlint:invalidAbsoluteTypeName]' ",
"no match for this type name: File [Xlint:invalidAbsoluteTypeName]",
((IMessage)MyTaskListManager.getWarningMessages().get(0))
.getMessage());
configureBuildStructureModel(false);
}
// test for comment #0 - adding a comment to a class file shouldn't
// cause us to go back to source and recompile everything. To force this
// to behave like AJDT we need to include the aspect in 'inc1' so that
// when AjState looks at its timestamp it thinks the aspect has been modified.
// The logic within CrosscuttingMembers should then work out correctly
// that there haven't really been any changes within the aspect and so
// we shouldn't go back to source.
public void xpr134471_testPr129163_2() {
// want to behave like AJDT
configureBuildStructureModel(true);
initialiseProject("pr129163_2");
build("pr129163_2");
checkWasFullBuild();
alter("pr129163_2","inc1");
build("pr129163_2");
checkWasntFullBuild(); // shouldn't be a full build because the
// aspect hasn't changed
configureBuildStructureModel(false);
}
// test for comment #6 - simulates AJDT core builder test testBug99133a -
// changing the contents of a method within a class shouldn't force a
// full build of a dependant project. To force this to behave like AJDT
// 'inc1' of the dependant project should just be a copy of 'base' so that
// AjState thinks somethings changed within the dependant project and
// we do a build. Similarly, 'inc1' of the project depended on should
// include the aspect even though nothing's changed within it. This causes
// AjState to think that the aspect has changed. Together its then up to
// logic within CrosscuttingMembers and various equals methods to decide
// correctly that we don't have to go back to source.
public void xpr134471_testPr129163_3() {
configureBuildStructureModel(true);
initialiseProject("PR129163_4");
build("PR129163_4");
checkWasFullBuild(); // should be a full build because initializing project
initialiseProject("PR129163_3");
configureNewProjectDependency("PR129163_3","PR129163_4");
build("PR129163_3");
checkWasFullBuild(); // should be a full build because initializing project
alter("PR129163_4","inc1");
build("PR129163_4");
checkWasntFullBuild(); // should be an incremental build because although
// "inc1" includes the aspect A1.aj, it actually hasn't
// changed so we shouldn't go back to source
alter("PR129163_3","inc1");
build("PR129163_3");
checkWasntFullBuild(); // should be an incremental build because nothing has
// changed within the class and no aspects have changed
// within the running of the test
configureBuildStructureModel(false);
}
public void xpr134471_testPr131505() {
configureNonStandardCompileOptions("-outxml");
initialiseProject("PR131505");
build("PR131505");
checkWasFullBuild();
// aop.xml file shouldn't contain any aspects
checkXMLAspectCount("PR131505","",0);
// add a new aspect A which should be included in the aop.xml file
alter("PR131505","inc1");
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",1);
checkXMLAspectCount("PR131505","A",1);
// make changes to the class file which shouldn't affect the contents
// of the aop.xml file
alter("PR131505","inc2");
build("PR131505");
checkWasntFullBuild();
checkXMLAspectCount("PR131505","",1);
checkXMLAspectCount("PR131505","A",1);
// add another new aspect A1 which should also be included in the aop.xml file
// ...there should be no duplicate entries in the file
alter("PR131505","inc3");
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",2);
checkXMLAspectCount("PR131505","A1",1);
checkXMLAspectCount("PR131505","A",1);
// delete aspect A1 which meanss that aop.xml file should only contain A
File a1 = new File(getWorkingDir().getAbsolutePath()
+ File.separatorChar + "PR131505" + File.separatorChar + "A1.aj");
a1.delete();
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",1);
checkXMLAspectCount("PR131505","A1",0);
checkXMLAspectCount("PR131505","A",1);
// add another aspect called A which is in a different package, both A
// and pkg.A should be included in the aop.xml file
alter("PR131505","inc4");
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",2);
checkXMLAspectCount("PR131505","A",1);
checkXMLAspectCount("PR131505","pkg.A",1);
}
public void testPr136585() {
initialiseProject("PR136585");
build("PR136585");
alter("PR136585","inc1");
build("PR136585");
assertTrue("There should be no errors reported:\n"+MyTaskListManager.getErrorMessages(),
MyTaskListManager.getErrorMessages().isEmpty());
}
public void testPr133532() {
initialiseProject("PR133532");
build("PR133532");
alter("PR133532","inc1");
build("PR133532");
alter("PR133532","inc2");
build("PR133532");
assertTrue("There should be no errors reported:\n"+MyTaskListManager.getErrorMessages(),
MyTaskListManager.getErrorMessages().isEmpty());
}
public void testPr133532_2() {
initialiseProject("pr133532_2");
build("pr133532_2");
alter("pr133532_2","inc2");
build("pr133532_2");
assertTrue("There should be no errors reported:\n"+MyTaskListManager.getErrorMessages(),
MyTaskListManager.getErrorMessages().isEmpty());
String decisions = AjdeInteractionTestbed.MyStateListener.getDecisions();
String expect="Need to recompile 'A.aj'";
assertTrue("Couldn't find build decision: '"+expect+"' in the list of decisions made:\n"+decisions,
decisions.indexOf(expect)!=-1);
}
public void xpr134471_testPr134541() {
initialiseProject("PR134541");
build("PR134541");
assertEquals("[Xlint:adviceDidNotMatch] should be associated with line 5",5,
((IMessage)MyTaskListManager.getWarningMessages().get(0)).getSourceLocation().getLine());
alter("PR134541","inc1");
build("PR134541");
checkWasntFullBuild(); // we've only added a white space therefore we
// shouldn't be doing a full build
assertEquals("[Xlint:adviceDidNotMatch] should now be associated with line 7",7,
((IMessage)MyTaskListManager.getWarningMessages().get(0)).getSourceLocation().getLine());
}
public void testPr134471() {
// super.VERBOSE=true;
configureBuildStructureModel(true);
AsmManager.setReporting("c:/foo.txt",true,true,true,true);
configureNonStandardCompileOptions("-showWeaveInfo -emacssym");
initialiseProject("PR134471");
build("PR134471");
IProgramElement ipe = checkForNode("pkg","A",true);
IProgramElement adviceNode = findAdvice(ipe);
List relatedElements = getRelatedElements(adviceNode);
StringBuffer debugString = new StringBuffer();
if (relatedElements!=null) {
for (Iterator iter = relatedElements.iterator(); iter.hasNext();) {
String element = (String) iter.next();
debugString.append(AsmManager.getDefault().getHierarchy().findElementForHandle(element).toLabelString()).append("\n");
}
}
// debug should be: 'p()' and 'method-call(void pkg.C.method2())' - first is 'uses pointcut' relation, second is 'advises'
assertTrue("Should be 2 elements on the first build, but there are not:\n "+debugString,relatedElements!=null && relatedElements.size()==2);
try {
IProgramElement cNode = checkForNode("pkg","C",true);
IProgramElement mNode = findCode(cNode);
IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap();
List rels = (List)irm.get(mNode);
IRelationship ir = (IRelationship)rels.get(0);
List targs = ir.getTargets();
String t1 = (String)targs.get(0);
int ii = AsmManager.getDefault().getHandleProvider().getLineNumberForHandle(t1);
assertTrue("Advice should be on line 7?? but is on line "+ii,ii==7);
} catch (Exception e) {
e.printStackTrace();
fail("Couldn't determine if the line number for the advice was right?!?");
}
// No change to the aspect at all !
alter("PR134471","inc1");
build("PR134471");
ipe = checkForNode("pkg","A",true);
adviceNode = findAdvice(ipe);
relatedElements = getRelatedElements(adviceNode);
debugString = new StringBuffer();
if (relatedElements!=null) {
for (Iterator iter = relatedElements.iterator(); iter.hasNext();) {
String element = (String) iter.next();
debugString.append(AsmManager.getDefault().getHierarchy().findElementForHandle(element).toLabelString()).append("\n");
}
}
// debug should be: 'p()' and 'method-call(void pkg.C.method2())' - first is 'uses pointcut' relation, second is 'advises'
assertTrue("Should be 2 elements on the second build, but there are not:\n "+debugString,relatedElements!=null && relatedElements.size()==2);
}
public void testPr134471_2() {
AsmManager.setReporting("c:/foo.txt",true,true,true,true);
configureBuildStructureModel(true);
configureNonStandardCompileOptions("-showWeaveInfo -emacssym");
initialiseProject("PR134471_2");
build("PR134471_2");
IProgramElement ipe = checkForNode("pkg","A",true);
IProgramElement adviceNode = findAdvice(ipe);
List relatedElements = getRelatedElements(adviceNode);
StringBuffer debugString = new StringBuffer();
if (relatedElements!=null) {
for (Iterator iter = relatedElements.iterator(); iter.hasNext();) {
String element = (String) iter.next();
debugString.append(AsmManager.getDefault().getHierarchy().findElementForHandle(element).toLabelString()).append("\n");
}
}
// debug should be: 'p()' and 'method-call(void pkg.C.method2())' - first is 'uses pointcut' relation, second is 'advises'
assertTrue("Should be 2 elements on the first build, but there are not:\n "+debugString,relatedElements!=null && relatedElements.size()==2);
try {
IProgramElement cNode = checkForNode("pkg","C",true);
IProgramElement mNode = findCode(cNode);
IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap();
List rels = (List)irm.get(mNode);
IRelationship ir = (IRelationship)rels.get(0);
List targs = ir.getTargets();
String t1 = (String)targs.get(0);
int ii = AsmManager.getDefault().getHandleProvider().getLineNumberForHandle(t1);
assertTrue("After first build, advice should be on line 7?? but is on line "+ii,ii==7);
} catch (Exception e) {
e.printStackTrace();
fail("Couldn't determine if the line number for the advice was right?!?");
}
//IProgramElement advisedNode = AsmManager.getDefault().getHierarchy().findElementForHandle((String)relatedElements.get(1));
// No structural change but the advice has moved down a few lines.
alter("PR134471_2","inc1");
build("PR134471_2");
ipe = checkForNode("pkg","A",true);
adviceNode = findAdvice(ipe);
relatedElements = getRelatedElements(adviceNode);
debugString = new StringBuffer();
if (relatedElements!=null) {
for (Iterator iter = relatedElements.iterator(); iter.hasNext();) {
String element = (String) iter.next();
debugString.append(AsmManager.getDefault().getHierarchy().findElementForHandle(element).toLabelString()).append("\n");
}
}
// debug should be: 'p()' and 'method-call(void pkg.C.method2())' - first is 'uses pointcut' relation, second is 'advises'
assertTrue("Should be 2 elements on the second build, but there are not:\n "+debugString,relatedElements!=null && relatedElements.size()==2);
try {
IProgramElement cNode = checkForNode("pkg","C",true);
IProgramElement mNode = findCode(cNode);
IRelationshipMap irm = AsmManager.getDefault().getRelationshipMap();
List rels = (List)irm.get(mNode);
IRelationship ir = (IRelationship)rels.get(0);
List targs = ir.getTargets();
String t1 = (String)targs.get(0);
int ii = AsmManager.getDefault().getHandleProvider().getLineNumberForHandle(t1);
assertTrue("After second build, advice should be on line 11?? but is on line "+ii,ii==11);
} catch (Exception e) {
e.printStackTrace();
fail("Couldn't determine if the line number for the advice was right?!?");
}
}
// ---
private List/*IProgramElement*/ getRelatedElements(IProgramElement advice) {
List output = null;
IRelationshipMap map = AsmManager.getDefault().getRelationshipMap();
List/*IRelationship*/ rels = (List)map.get(advice);
for (Iterator iter = rels.iterator(); iter.hasNext();) {
IRelationship element = (IRelationship) iter.next();
List/*String*/ targets = element.getTargets();
if (output==null) output = new ArrayList();
output.addAll(targets);
}
return output;
}
private IProgramElement findAdvice(IProgramElement ipe) {
return findAdvice(ipe,1);
}
private IProgramElement findAdvice(IProgramElement ipe,int whichOne) {
if (ipe.getKind()==IProgramElement.Kind.ADVICE) {
whichOne=whichOne-1;
if (whichOne==0) return ipe;
}
List kids = ipe.getChildren();
for (Iterator iter = kids.iterator(); iter.hasNext();) {
IProgramElement kid = (IProgramElement) iter.next();
IProgramElement found = findAdvice(kid,whichOne);
if (found!=null) return found;
}
return null;
}
private IProgramElement findCode(IProgramElement ipe) {
return findCode(ipe,1);
}
private IProgramElement findCode(IProgramElement ipe,int whichOne) {
if (ipe.getKind()==IProgramElement.Kind.CODE) {
whichOne=whichOne-1;
if (whichOne==0) return ipe;
}
List kids = ipe.getChildren();
for (Iterator iter = kids.iterator(); iter.hasNext();) {
IProgramElement kid = (IProgramElement) iter.next();
IProgramElement found = findCode(kid,whichOne);
if (found!=null) return found;
}
return null;
}
// other possible tests:
// - memory usage (freemem calls?)
// - relationship map
// ---------------------------------------------------------------------------------------------------
/**
* Check we compiled/wove the right number of files, passing '-1' indicates you don't care about
* that number.
*/
private void checkCompileWeaveCount(int expCompile,int expWoven) {
if (expCompile!=-1 && getCompiledFiles().size()!=expCompile)
fail("Expected compilation of "+expCompile+" files but compiled "+getCompiledFiles().size()+
"\n"+printCompiledAndWovenFiles());
if (expWoven!=-1 && getWovenClasses().size()!=expWoven)
fail("Expected weaving of "+expWoven+" files but wove "+getWovenClasses().size()+
"\n"+printCompiledAndWovenFiles());
}
private void checkWasntFullBuild() {
assertTrue("Shouldn't have been a full (batch) build",!wasFullBuild());
}
private void checkWasFullBuild() {
assertTrue("Should have been a full (batch) build",wasFullBuild());
}
private IProgramElement checkForNode(String packageName,String typeName,boolean shouldBeFound) {
IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForType(packageName,typeName);
if (shouldBeFound) {
if (ipe==null) printModel();
assertTrue("Should have been able to find '"+packageName+"."+typeName+"' in the asm",ipe!=null);
} else {
if (ipe!=null) printModel();
assertTrue("Should have NOT been able to find '"+packageName+"."+typeName+"' in the asm",ipe==null);
}
return ipe;
}
private void printModel() {
try {
AsmManager.dumptree(AsmManager.getDefault().getHierarchy().getRoot(),0);
} catch (IOException e) {
e.printStackTrace();
}
}
public void build(String projectName) {
constructUpToDateLstFile(projectName,"build.lst");
build(projectName,"build.lst");
if (AjdeInteractionTestbed.VERBOSE) printBuildReport();
}
public void fullBuild(String projectName) {
constructUpToDateLstFile(projectName,"build.lst");
fullBuild(projectName,"build.lst");
if (AjdeInteractionTestbed.VERBOSE) printBuildReport();
}
private void constructUpToDateLstFile(String pname,String configname) {
File projectBase = new File(sandboxDir,pname);
File toConstruct = new File(projectBase,configname);
List filesForCompilation = new ArrayList();
collectUpFiles(projectBase,projectBase,filesForCompilation);
try {
FileOutputStream fos = new FileOutputStream(toConstruct);
DataOutputStream dos = new DataOutputStream(fos);
for (Iterator iter = filesForCompilation.iterator(); iter.hasNext();) {
String file = (String) iter.next();
dos.writeBytes(file+"\n");
}
dos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void checkForError(String anError) {
List messages = MyTaskListManager.getErrorMessages();
for (Iterator iter = messages.iterator(); iter.hasNext();) {
IMessage element = (IMessage) iter.next();
if (element.getMessage().indexOf(anError)!=-1) return;
}
fail("Didn't find the error message:\n'"+anError+"'.\nErrors that occurred:\n"+MyTaskListManager.getErrorMessages());
}
private void collectUpFiles(File location,File base,List collectionPoint) {
String contents[] = location.list();
if (contents==null) return;
for (int i = 0; i < contents.length; i++) {
String string = contents[i];
File f = new File(location,string);
if (f.isDirectory()) {
collectUpFiles(f,base,collectionPoint);
} else if (f.isFile() && (f.getName().endsWith(".aj") || f.getName().endsWith(".java"))) {
String fileFound;
try {
fileFound = f.getCanonicalPath();
String toRemove = base.getCanonicalPath();
if (!fileFound.startsWith(toRemove)) throw new RuntimeException("eh? "+fileFound+" "+toRemove);
collectionPoint.add(fileFound.substring(toRemove.length()+1));//+1 captures extra separator
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Fill in the working directory with the project base files,
* from the 'base' folder.
*/
protected void initialiseProject(String p) {
File projectSrc=new File(testdataSrcDir+File.separatorChar+p+File.separatorChar+"base");
File destination=new File(getWorkingDir(),p);
if (!destination.exists()) {destination.mkdir();}
copy(projectSrc,destination);//,false);
}
/*
* Applies an overlay onto the project being tested - copying
* the contents of the specified overlay directory.
*/
private void alter(String projectName,String overlayDirectory) {
File projectSrc =new File(testdataSrcDir+File.separatorChar+projectName+
File.separatorChar+overlayDirectory);
File destination=new File(getWorkingDir(),projectName);
copy(projectSrc,destination);
}
/**
* Copy the contents of some directory to another location - the
* copy is recursive.
*/
private void copy(File from, File to) {
String contents[] = from.list();
if (contents==null) return;
for (int i = 0; i < contents.length; i++) {
String string = contents[i];
File f = new File(from,string);
File t = new File(to,string);
if (f.isDirectory() && !f.getName().startsWith("inc")) {
t.mkdir();
copy(f,t);
} else if (f.isFile()) {
StringBuffer sb = new StringBuffer();
//if (VERBOSE) System.err.println("Copying "+f+" to "+t);
FileUtil.copyFile(f,t,sb);
if (sb.length()!=0) { System.err.println(sb.toString());}
}
}
}
private static void log(String msg) {
if (VERBOSE) System.out.println(msg);
}
/**
* Count the number of times a specified aspectName appears in the default
* aop.xml file and compare with the expected number of occurrences. If just
* want to count the number of aspects mentioned within the file then
* pass "" for the aspectName, otherwise, specify the name of the
* aspect interested in.
*/
private void checkXMLAspectCount(String projectName, String aspectName, int expectedOccurrences) {
int aspectCount = 0;
File aopXML = new File(getWorkingDir().getAbsolutePath()
+ File.separatorChar + projectName + File.separatorChar
+ "bin" + File.separatorChar + "META-INF" + File.separatorChar + "aop.xml");
if (!aopXML.exists()) {
fail("Expected file " + aopXML.getAbsolutePath() + " to exist but it doesn't");
}
try {
BufferedReader reader = new BufferedReader(new FileReader(aopXML));
String line = reader.readLine();
while (line != null) {
if (aspectName.equals("") && line.indexOf("aspect name=\"") != -1) {
aspectCount++;
} else if (line.indexOf("aspect name=\""+aspectName+"\"") != -1) {
aspectCount++;
}
line = reader.readLine();
}
reader.close();
} catch (IOException ie) {
ie.printStackTrace();
}
if (aspectCount != expectedOccurrences) {
fail("Expected aspect " + aspectName + " to appear " + expectedOccurrences + " times" +
" in the aop.xml file but found " + aspectCount + " occurrences");
}
}
}
|
140,357 |
Bug 140357 NPE or StackOverflow when resolving reference pointcut in ReflectionWorld
|
Given a type such as : private static class NamedPointcutResolution { @Pointcut("execution(* *(..))") public void a() {} @Pointcut("this(org.aspectj.weaver.tools.Java15PointcutExpressionTest.A)") public void b() {} @Pointcut("a() && b()") public void c() {} } The reflection based delegate is unable to resolve the pointcut c() failing with either (1) an NPE, or (2) a StackOverflow, depending on the order of the pointcut definitions in the type. The problem occurs because in resolving "c()" we get all the pointcuts in the type, which gets a(), b(), and c(), and tries to resolve them...
|
resolved fixed
|
b954b26
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-05T14:08:35Z | 2006-05-05T14:40:00Z |
weaver/src/org/aspectj/weaver/tools/PointcutParser.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.weaver.tools;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.SourceLocation;
import org.aspectj.weaver.IHasPosition;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.IntMap;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.AtAjAttributes;
import org.aspectj.weaver.internal.tools.PointcutExpressionImpl;
import org.aspectj.weaver.internal.tools.TypePatternMatcherImpl;
import org.aspectj.weaver.patterns.AndPointcut;
import org.aspectj.weaver.patterns.CflowPointcut;
import org.aspectj.weaver.patterns.FormalBinding;
import org.aspectj.weaver.patterns.IScope;
import org.aspectj.weaver.patterns.KindedPointcut;
import org.aspectj.weaver.patterns.NotPointcut;
import org.aspectj.weaver.patterns.OrPointcut;
import org.aspectj.weaver.patterns.ParserException;
import org.aspectj.weaver.patterns.PatternParser;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.SimpleScope;
import org.aspectj.weaver.patterns.ThisOrTargetAnnotationPointcut;
import org.aspectj.weaver.patterns.ThisOrTargetPointcut;
import org.aspectj.weaver.patterns.TypePattern;
import org.aspectj.weaver.reflect.PointcutParameterImpl;
import org.aspectj.weaver.reflect.ReflectionWorld;
/**
* A PointcutParser can be used to build PointcutExpressions for a
* user-defined subset of AspectJ's pointcut language
*/
public class PointcutParser {
private ReflectionWorld world;
private ClassLoader classLoader;
private Set supportedPrimitives;
private Set pointcutDesignators = new HashSet();
/**
* @return a Set containing every PointcutPrimitive except
* if, cflow, and cflowbelow (useful for passing to
* PointcutParser constructor).
*/
public static Set getAllSupportedPointcutPrimitives() {
Set primitives = new HashSet();
primitives.add(PointcutPrimitive.ADVICE_EXECUTION);
primitives.add(PointcutPrimitive.ARGS);
primitives.add(PointcutPrimitive.CALL);
primitives.add(PointcutPrimitive.EXECUTION);
primitives.add(PointcutPrimitive.GET);
primitives.add(PointcutPrimitive.HANDLER);
primitives.add(PointcutPrimitive.INITIALIZATION);
primitives.add(PointcutPrimitive.PRE_INITIALIZATION);
primitives.add(PointcutPrimitive.SET);
primitives.add(PointcutPrimitive.STATIC_INITIALIZATION);
primitives.add(PointcutPrimitive.TARGET);
primitives.add(PointcutPrimitive.THIS);
primitives.add(PointcutPrimitive.WITHIN);
primitives.add(PointcutPrimitive.WITHIN_CODE);
primitives.add(PointcutPrimitive.AT_ANNOTATION);
primitives.add(PointcutPrimitive.AT_THIS);
primitives.add(PointcutPrimitive.AT_TARGET);
primitives.add(PointcutPrimitive.AT_ARGS);
primitives.add(PointcutPrimitive.AT_WITHIN);
primitives.add(PointcutPrimitive.AT_WITHINCODE);
primitives.add(PointcutPrimitive.REFERENCE);
return primitives;
}
/**
* Returns a pointcut parser that can parse the full AspectJ pointcut
* language with the following exceptions:
* <ul>
* <li>The <code>if, cflow, and cflowbelow</code> pointcut designators are not supported
* <li>Pointcut expressions must be self-contained :- they cannot contain references
* to other named pointcuts
* <li>The pointcut expression must be anonymous with no formals allowed.
* </ul>
* <p>When resolving types in pointcut expressions, the context classloader is used to find types.</p>
*/
public static PointcutParser getPointcutParserSupportingAllPrimitivesAndUsingContextClassloaderForResolution() {
PointcutParser p = new PointcutParser();
p.setClassLoader(Thread.currentThread().getContextClassLoader());
return p;
}
/**
* Returns a pointcut parser that can parse pointcut expressions built
* from a user-defined subset of AspectJ's supported pointcut primitives.
* The following restrictions apply:
* <ul>
* <li>The <code>if, cflow, and cflowbelow</code> pointcut designators are not supported
* <li>Pointcut expressions must be self-contained :- they cannot contain references
* to other named pointcuts
* <li>The pointcut expression must be anonymous with no formals allowed.
* </ul>
* <p>When resolving types in pointcut expressions, the context classloader is used to find types.</p>
* @param supportedPointcutKinds a set of PointcutPrimitives this parser
* should support
* @throws UnsupportedOperationException if the set contains if, cflow, or
* cflow below
*/
public static PointcutParser getPointcutParserSupportingSpecifiedPrimitivesAndUsingContextClassloaderForResolution(Set supportedPointcutKinds) {
PointcutParser p = new PointcutParser(supportedPointcutKinds);
p.setClassLoader(Thread.currentThread().getContextClassLoader());
return p;
}
/**
* Returns a pointcut parser that can parse the full AspectJ pointcut
* language with the following exceptions:
* <ul>
* <li>The <code>if, cflow, and cflowbelow</code> pointcut designators are not supported
* <li>Pointcut expressions must be self-contained :- they cannot contain references
* to other named pointcuts
* <li>The pointcut expression must be anonymous with no formals allowed.
* </ul>
* <p>When resolving types in pointcut expressions, the given classloader is used to find types.</p>
*/
public static PointcutParser getPointcutParserSupportingAllPrimitivesAndUsingSpecifiedClassloaderForResolution(ClassLoader classLoader) {
PointcutParser p = new PointcutParser();
p.setClassLoader(classLoader);
return p;
}
/**
* Returns a pointcut parser that can parse pointcut expressions built
* from a user-defined subset of AspectJ's supported pointcut primitives.
* The following restrictions apply:
* <ul>
* <li>The <code>if, cflow, and cflowbelow</code> pointcut designators are not supported
* <li>Pointcut expressions must be self-contained :- they cannot contain references
* to other named pointcuts
* <li>The pointcut expression must be anonymous with no formals allowed.
* </ul>
* <p>When resolving types in pointcut expressions, the given classloader is used to find types.</p>
* @param supportedPointcutKinds a set of PointcutPrimitives this parser
* should support
* @throws UnsupportedOperationException if the set contains if, cflow, or
* cflow below
*/
public static PointcutParser getPointcutParserSupportingSpecifiedPrimitivesAndUsingSpecifiedClassLoaderForResolution(Set supportedPointcutKinds, ClassLoader classLoader) {
PointcutParser p = new PointcutParser(supportedPointcutKinds);
p.setClassLoader(classLoader);
return p;
}
/**
* Create a pointcut parser that can parse the full AspectJ pointcut
* language with the following exceptions:
* <ul>
* <li>The <code>if, cflow, and cflowbelow</code> pointcut designators are not supported
* <li>Pointcut expressions must be self-contained :- they cannot contain references
* to other named pointcuts
* <li>The pointcut expression must be anonymous with no formals allowed.
* </ul>
*/
private PointcutParser() {
supportedPrimitives = getAllSupportedPointcutPrimitives();
setClassLoader(PointcutParser.class.getClassLoader());
}
/**
* Create a pointcut parser that can parse pointcut expressions built
* from a user-defined subset of AspectJ's supported pointcut primitives.
* The following restrictions apply:
* <ul>
* <li>The <code>if, cflow, and cflowbelow</code> pointcut designators are not supported
* <li>Pointcut expressions must be self-contained :- they cannot contain references
* to other named pointcuts
* <li>The pointcut expression must be anonymous with no formals allowed.
* </ul>
* @param supportedPointcutKinds a set of PointcutPrimitives this parser
* should support
* @throws UnsupportedOperationException if the set contains if, cflow, or
* cflow below
*/
private PointcutParser(Set/*<PointcutPrimitives>*/ supportedPointcutKinds) {
supportedPrimitives = supportedPointcutKinds;
for (Iterator iter = supportedPointcutKinds.iterator(); iter.hasNext();) {
PointcutPrimitive element = (PointcutPrimitive) iter.next();
if ((element == PointcutPrimitive.IF) ||
(element == PointcutPrimitive.CFLOW) ||
(element == PointcutPrimitive.CFLOW_BELOW)) {
throw new UnsupportedOperationException("Cannot handle if, cflow, and cflowbelow primitives");
}
}
setClassLoader(PointcutParser.class.getClassLoader());
}
public void setWorld(ReflectionWorld aWorld) {
this.world = aWorld;
}
/**
* Set the classloader that this parser should use for
* type resolution.
* @param aLoader
*/
private void setClassLoader(ClassLoader aLoader) {
this.classLoader = aLoader;
world = new ReflectionWorld(this.classLoader);
}
/**
* Set the lint properties for this parser from the
* given resource on the classpath.
* @param resourcePath path to a file containing aspectj
* lint properties
*/
public void setLintProperties(String resourcePath)throws IOException {
URL url = this.classLoader.getResource(resourcePath);
InputStream is = url.openStream();
Properties p = new Properties();
p.load(is);
setLintProperties(p);
}
/**
* Set the lint properties for this parser from the
* given properties set.
* @param properties
*/
public void setLintProperties(Properties properties) {
getWorld().getLint().setFromProperties(properties);
}
/**
* Register a new pointcut designator handler with this parser.
* This provides an extension mechansim for the integration of
* domain-specific pointcut designators with the AspectJ
* pointcut language.
* @param designatorHandler
*/
public void registerPointcutDesignatorHandler(PointcutDesignatorHandler designatorHandler) {
this.pointcutDesignators.add(designatorHandler);
}
/**
* Create a pointcut parameter of the given name and type.
* @param name
* @param type
* @return
*/
public PointcutParameter createPointcutParameter(String name, Class type) {
return new PointcutParameterImpl(name,type);
}
/**
* Parse the given pointcut expression.
* A global scope is assumed for resolving any type references, and the pointcut
* must contain no formals (variables to be bound).
* @throws UnsupportedPointcutPrimitiveException if the parser encounters a
* primitive pointcut expression of a kind not supported by this PointcutParser.
* @throws IllegalArgumentException if the expression is not a well-formed
* pointcut expression
*/
public PointcutExpression parsePointcutExpression(String expression)
throws UnsupportedPointcutPrimitiveException, IllegalArgumentException {
return parsePointcutExpression(expression,null,new PointcutParameter[0]);
}
/**
* Parse the given pointcut expression.
* The pointcut is resolved as if it had been declared inside the inScope class
* (this allows the pointcut to contain unqualified references to other pointcuts
* declared in the same type for example).
* The pointcut may contain zero or more formal parameters to be bound at matched
* join points.
* @throws UnsupportedPointcutPrimitiveException if the parser encounters a
* primitive pointcut expression of a kind not supported by this PointcutParser.
* @throws IllegalArgumentException if the expression is not a well-formed
* pointcut expression
*/
public PointcutExpression parsePointcutExpression(
String expression,
Class inScope,
PointcutParameter[] formalParameters)
throws UnsupportedPointcutPrimitiveException, IllegalArgumentException {
PointcutExpressionImpl pcExpr = null;
try {
PatternParser parser = new PatternParser(expression);
parser.setPointcutDesignatorHandlers(pointcutDesignators, world);
Pointcut pc = parser.parsePointcut();
validateAgainstSupportedPrimitives(pc,expression);
IScope resolutionScope = buildResolutionScope((inScope == null ? Object.class : inScope),formalParameters);
pc = pc.resolve(resolutionScope);
ResolvedType declaringTypeForResolution = null;
if (inScope != null) {
declaringTypeForResolution = getWorld().resolve(inScope.getName());
} else {
declaringTypeForResolution = ResolvedType.OBJECT.resolve(getWorld());
}
IntMap arity = new IntMap(formalParameters.length);
for (int i = 0; i < formalParameters.length; i++) {
arity.put(i, i);
}
pc = pc.concretize(declaringTypeForResolution, declaringTypeForResolution, arity);
validateAgainstSupportedPrimitives(pc,expression); // again, because we have now followed any ref'd pcuts
pcExpr = new PointcutExpressionImpl(pc,expression,formalParameters,getWorld());
} catch (ParserException pEx) {
throw new IllegalArgumentException(buildUserMessageFromParserException(expression,pEx));
} catch (ReflectionWorld.ReflectionWorldException rwEx) {
throw new IllegalArgumentException(rwEx.getMessage());
}
return pcExpr;
}
/**
* Parse the given aspectj type pattern, and return a
* matcher that can be used to match types using it.
* @param typePattern an aspectj type pattern
* @return a type pattern matcher that matches using the given
* pattern
* @throws IllegalArgumentException if the type pattern cannot
* be successfully parsed.
*/
public TypePatternMatcher parseTypePattern(String typePattern)
throws IllegalArgumentException {
try {
TypePattern tp = new PatternParser(typePattern).parseTypePattern();
tp.resolve(world);
return new TypePatternMatcherImpl(tp,world);
} catch (ParserException pEx) {
throw new IllegalArgumentException(buildUserMessageFromParserException(typePattern,pEx));
} catch (ReflectionWorld.ReflectionWorldException rwEx) {
throw new IllegalArgumentException(rwEx.getMessage());
}
}
private World getWorld() {
return world;
}
/* for testing */
Set getSupportedPrimitives() {
return supportedPrimitives;
}
/* for testing */
IMessageHandler setCustomMessageHandler(IMessageHandler aHandler) {
IMessageHandler current = getWorld().getMessageHandler();
getWorld().setMessageHandler(aHandler);
return current;
}
private IScope buildResolutionScope(Class inScope, PointcutParameter[] formalParameters) {
if (formalParameters == null) formalParameters = new PointcutParameter[0];
FormalBinding[] formalBindings = new FormalBinding[formalParameters.length];
for (int i = 0; i < formalBindings.length; i++) {
formalBindings[i] = new FormalBinding(UnresolvedType.forName(formalParameters[i].getType().getName()),formalParameters[i].getName(),i);
}
if (inScope == null) {
return new SimpleScope(getWorld(),formalBindings);
} else {
ResolvedType inType = getWorld().resolve(inScope.getName());
ISourceContext sourceContext = new ISourceContext() {
public ISourceLocation makeSourceLocation(IHasPosition position) {
return new SourceLocation(new File(""),0);
}
public ISourceLocation makeSourceLocation(int line, int offset) {
return new SourceLocation(new File(""),line);
}
public int getOffset() {
return 0;
}
public void tidy() {}
};
return new AtAjAttributes.BindingScope(inType,sourceContext,formalBindings);
}
}
private void validateAgainstSupportedPrimitives(Pointcut pc, String expression) {
switch(pc.getPointcutKind()) {
case Pointcut.AND:
validateAgainstSupportedPrimitives(((AndPointcut)pc).getLeft(),expression);
validateAgainstSupportedPrimitives(((AndPointcut)pc).getRight(),expression);
break;
case Pointcut.ARGS:
if (!supportedPrimitives.contains(PointcutPrimitive.ARGS))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.ARGS);
break;
case Pointcut.CFLOW:
CflowPointcut cfp = (CflowPointcut) pc;
if (cfp.isCflowBelow()) {
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.CFLOW_BELOW);
} else {
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.CFLOW);
}
case Pointcut.HANDLER:
if (!supportedPrimitives.contains(PointcutPrimitive.HANDLER))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.HANDLER);
break;
case Pointcut.IF:
case Pointcut.IF_FALSE:
case Pointcut.IF_TRUE:
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.IF);
case Pointcut.KINDED:
validateKindedPointcut(((KindedPointcut)pc),expression);
break;
case Pointcut.NOT:
validateAgainstSupportedPrimitives(((NotPointcut)pc).getNegatedPointcut(),expression);
break;
case Pointcut.OR:
validateAgainstSupportedPrimitives(((OrPointcut)pc).getLeft(),expression);
validateAgainstSupportedPrimitives(((OrPointcut)pc).getRight(),expression);
break;
case Pointcut.THIS_OR_TARGET:
boolean isThis = ((ThisOrTargetPointcut)pc).isThis();
if (isThis && !supportedPrimitives.contains(PointcutPrimitive.THIS)) {
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.THIS);
} else if (!supportedPrimitives.contains(PointcutPrimitive.TARGET)) {
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.TARGET);
}
break;
case Pointcut.WITHIN:
if (!supportedPrimitives.contains(PointcutPrimitive.WITHIN))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.WITHIN);
break;
case Pointcut.WITHINCODE:
if (!supportedPrimitives.contains(PointcutPrimitive.WITHIN_CODE))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.WITHIN_CODE);
break;
case Pointcut.ATTHIS_OR_TARGET:
isThis = ((ThisOrTargetAnnotationPointcut)pc).isThis();
if (isThis && !supportedPrimitives.contains(PointcutPrimitive.AT_THIS)) {
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.AT_THIS);
} else if (!supportedPrimitives.contains(PointcutPrimitive.AT_TARGET)) {
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.AT_TARGET);
}
break;
case Pointcut.ATARGS:
if (!supportedPrimitives.contains(PointcutPrimitive.AT_ARGS))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.AT_ARGS);
break;
case Pointcut.ANNOTATION:
if (!supportedPrimitives.contains(PointcutPrimitive.AT_ANNOTATION))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.AT_ANNOTATION);
break;
case Pointcut.ATWITHIN:
if (!supportedPrimitives.contains(PointcutPrimitive.AT_WITHIN))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.AT_WITHIN);
break;
case Pointcut.ATWITHINCODE:
if (!supportedPrimitives.contains(PointcutPrimitive.AT_WITHINCODE))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.AT_WITHINCODE);
break;
case Pointcut.REFERENCE:
if (!supportedPrimitives.contains(PointcutPrimitive.REFERENCE))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.REFERENCE);
break;
case Pointcut.USER_EXTENSION:
// always ok...
break;
case Pointcut.NONE: // deliberate fall-through
default:
throw new IllegalArgumentException("Unknown pointcut kind: " + pc.getPointcutKind());
}
}
private void validateKindedPointcut(KindedPointcut pc, String expression) {
Shadow.Kind kind = pc.getKind();
if ((kind == Shadow.MethodCall) || (kind == Shadow.ConstructorCall)) {
if (!supportedPrimitives.contains(PointcutPrimitive.CALL))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.CALL);
} else if ((kind == Shadow.MethodExecution) || (kind == Shadow.ConstructorExecution)) {
if (!supportedPrimitives.contains(PointcutPrimitive.EXECUTION))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.EXECUTION);
} else if (kind == Shadow.AdviceExecution) {
if (!supportedPrimitives.contains(PointcutPrimitive.ADVICE_EXECUTION))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.ADVICE_EXECUTION);
} else if (kind == Shadow.FieldGet) {
if (!supportedPrimitives.contains(PointcutPrimitive.GET))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.GET);
} else if (kind == Shadow.FieldSet) {
if (!supportedPrimitives.contains(PointcutPrimitive.SET))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.SET);
} else if (kind == Shadow.Initialization) {
if (!supportedPrimitives.contains(PointcutPrimitive.INITIALIZATION))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.INITIALIZATION);
} else if (kind == Shadow.PreInitialization) {
if (!supportedPrimitives.contains(PointcutPrimitive.PRE_INITIALIZATION))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.PRE_INITIALIZATION);
} else if (kind == Shadow.StaticInitialization) {
if (!supportedPrimitives.contains(PointcutPrimitive.STATIC_INITIALIZATION))
throw new UnsupportedPointcutPrimitiveException(expression, PointcutPrimitive.STATIC_INITIALIZATION);
}
}
private String buildUserMessageFromParserException(String pc, ParserException ex) {
StringBuffer msg = new StringBuffer();
msg.append("Pointcut is not well-formed: expecting '");
msg.append(ex.getMessage());
msg.append("'");
IHasPosition location = ex.getLocation();
msg.append(" at character position ");
msg.append(location.getStart());
msg.append("\n");
msg.append(pc);
msg.append("\n");
for (int i = 0; i < location.getStart(); i++) {
msg.append(" ");
}
for (int j=location.getStart(); j <= location.getEnd(); j++) {
msg.append("^");
}
msg.append("\n");
return msg.toString();
}
}
|
140,357 |
Bug 140357 NPE or StackOverflow when resolving reference pointcut in ReflectionWorld
|
Given a type such as : private static class NamedPointcutResolution { @Pointcut("execution(* *(..))") public void a() {} @Pointcut("this(org.aspectj.weaver.tools.Java15PointcutExpressionTest.A)") public void b() {} @Pointcut("a() && b()") public void c() {} } The reflection based delegate is unable to resolve the pointcut c() failing with either (1) an NPE, or (2) a StackOverflow, depending on the order of the pointcut definitions in the type. The problem occurs because in resolving "c()" we get all the pointcuts in the type, which gets a(), b(), and c(), and tries to resolve them...
|
resolved fixed
|
b954b26
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-05T14:08:35Z | 2006-05-05T14:40:00Z |
weaver5/java5-src/org/aspectj/weaver/reflect/DeferredResolvedPointcutDefinition.java
| |
140,357 |
Bug 140357 NPE or StackOverflow when resolving reference pointcut in ReflectionWorld
|
Given a type such as : private static class NamedPointcutResolution { @Pointcut("execution(* *(..))") public void a() {} @Pointcut("this(org.aspectj.weaver.tools.Java15PointcutExpressionTest.A)") public void b() {} @Pointcut("a() && b()") public void c() {} } The reflection based delegate is unable to resolve the pointcut c() failing with either (1) an NPE, or (2) a StackOverflow, depending on the order of the pointcut definitions in the type. The problem occurs because in resolving "c()" we get all the pointcuts in the type, which gets a(), b(), and c(), and tries to resolve them...
|
resolved fixed
|
b954b26
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-05T14:08:35Z | 2006-05-05T14:40:00Z |
weaver5/java5-src/org/aspectj/weaver/reflect/InternalUseOnlyPointcutParser.java
| |
140,357 |
Bug 140357 NPE or StackOverflow when resolving reference pointcut in ReflectionWorld
|
Given a type such as : private static class NamedPointcutResolution { @Pointcut("execution(* *(..))") public void a() {} @Pointcut("this(org.aspectj.weaver.tools.Java15PointcutExpressionTest.A)") public void b() {} @Pointcut("a() && b()") public void c() {} } The reflection based delegate is unable to resolve the pointcut c() failing with either (1) an NPE, or (2) a StackOverflow, depending on the order of the pointcut definitions in the type. The problem occurs because in resolving "c()" we get all the pointcuts in the type, which gets a(), b(), and c(), and tries to resolve them...
|
resolved fixed
|
b954b26
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-05T14:08:35Z | 2006-05-05T14:40:00Z |
weaver5/java5-src/org/aspectj/weaver/reflect/Java15ReflectionBasedReferenceTypeDelegate.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer Initial implementation
* ******************************************************************/
package org.aspectj.weaver.reflect;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.AjType;
import org.aspectj.lang.reflect.AjTypeSystem;
import org.aspectj.lang.reflect.Pointcut;
import org.aspectj.weaver.AnnotationX;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.TypeVariableReferenceType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.internal.tools.PointcutExpressionImpl;
import org.aspectj.weaver.tools.PointcutParameter;
import org.aspectj.weaver.tools.PointcutParser;
/**
* @author colyer
* Provides Java 5 behaviour in reflection based delegates (overriding
* 1.4 behaviour from superclass where appropriate)
*/
public class Java15ReflectionBasedReferenceTypeDelegate extends
ReflectionBasedReferenceTypeDelegate {
private AjType<?> myType;
private ResolvedType[] annotations;
private ResolvedMember[] pointcuts;
private ResolvedMember[] methods;
private ResolvedMember[] fields;
private TypeVariable[] typeVariables;
private ResolvedType superclass;
private ResolvedType[] superInterfaces;
private String genericSignature = null;
private JavaLangTypeToResolvedTypeConverter typeConverter;
private Java15AnnotationFinder annotationFinder = null;
private ArgNameFinder argNameFinder = null;
public Java15ReflectionBasedReferenceTypeDelegate() {}
@Override
public void initialize(ReferenceType aType, Class aClass, ClassLoader classLoader, World aWorld) {
super.initialize(aType, aClass, classLoader, aWorld);
myType = AjTypeSystem.getAjType(aClass);
annotationFinder = new Java15AnnotationFinder();
argNameFinder = annotationFinder;
annotationFinder.setClassLoader(classLoader);
this.typeConverter = new JavaLangTypeToResolvedTypeConverter(aWorld);
}
public ReferenceType buildGenericType() {
return (ReferenceType) UnresolvedType.forGenericTypeVariables(
getResolvedTypeX().getSignature(),
getTypeVariables()).resolve(getWorld());
}
public AnnotationX[] getAnnotations() {
// AMC - we seem not to need to implement this method...
//throw new UnsupportedOperationException("getAnnotations on Java15ReflectionBasedReferenceTypeDelegate is not implemented yet");
// FIXME is this the right implementation in the reflective case?
return super.getAnnotations();
}
public ResolvedType[] getAnnotationTypes() {
if (annotations == null) {
annotations = annotationFinder.getAnnotations(getBaseClass(), getWorld());
}
return annotations;
}
public boolean hasAnnotation(UnresolvedType ofType) {
ResolvedType[] myAnns = getAnnotationTypes();
ResolvedType toLookFor = ofType.resolve(getWorld());
for (int i = 0; i < myAnns.length; i++) {
if (myAnns[i] == toLookFor) return true;
}
return false;
}
// use the MAP to ensure that any aj-synthetic fields are filtered out
public ResolvedMember[] getDeclaredFields() {
if (fields == null) {
Field[] reflectFields = this.myType.getDeclaredFields();
this.fields = new ResolvedMember[reflectFields.length];
for (int i = 0; i < reflectFields.length; i++) {
this.fields[i] = createGenericFieldMember(reflectFields[i]);
}
}
return fields;
}
public String getDeclaredGenericSignature() {
if (this.genericSignature == null && isGeneric()) {
}
return genericSignature;
}
public ResolvedType[] getDeclaredInterfaces() {
if (superInterfaces == null) {
Type[] genericInterfaces = getBaseClass().getGenericInterfaces();
this.superInterfaces = typeConverter.fromTypes(genericInterfaces);
}
return superInterfaces;
}
// If the superclass is null, return Object - same as bcel does
public ResolvedType getSuperclass() {
if (superclass == null && getBaseClass()!=Object.class) {// superclass of Object is null
Type t = this.getBaseClass().getGenericSuperclass();
if (t!=null) superclass = typeConverter.fromType(t);
if (t==null) superclass = getWorld().resolve(UnresolvedType.OBJECT);
}
return superclass;
}
public TypeVariable[] getTypeVariables() {
TypeVariable[] workInProgressSetOfVariables = (TypeVariable[])getResolvedTypeX().getWorld().getTypeVariablesCurrentlyBeingProcessed(getBaseClass());
if (workInProgressSetOfVariables!=null) {
return workInProgressSetOfVariables;
}
if (this.typeVariables == null) {
java.lang.reflect.TypeVariable[] tVars = this.getBaseClass().getTypeParameters();
this.typeVariables = new TypeVariable[tVars.length];
// basic initialization
for (int i = 0; i < tVars.length; i++) {
typeVariables[i] = new TypeVariable(tVars[i].getName());
}
// stash it
this.getResolvedTypeX().getWorld().recordTypeVariablesCurrentlyBeingProcessed(getBaseClass(),typeVariables);
// now fill in the details...
for (int i = 0; i < tVars.length; i++) {
TypeVariableReferenceType tvrt = ((TypeVariableReferenceType) typeConverter.fromType(tVars[i]));
TypeVariable tv = tvrt.getTypeVariable();
typeVariables[i].setUpperBound(tv.getUpperBound());
typeVariables[i].setAdditionalInterfaceBounds(tv.getAdditionalInterfaceBounds());
typeVariables[i].setDeclaringElement(tv.getDeclaringElement());
typeVariables[i].setDeclaringElementKind(tv.getDeclaringElementKind());
typeVariables[i].setRank(tv.getRank());
typeVariables[i].setLowerBound(tv.getLowerBound());
}
this.getResolvedTypeX().getWorld().forgetTypeVariablesCurrentlyBeingProcessed(getBaseClass());
}
return this.typeVariables;
}
// overrides super method since by using the MAP we can filter out advice
// methods that really shouldn't be seen in this list
public ResolvedMember[] getDeclaredMethods() {
if (methods == null) {
Method[] reflectMethods = this.myType.getDeclaredMethods();
Constructor[] reflectCons = this.myType.getDeclaredConstructors();
this.methods = new ResolvedMember[reflectMethods.length + reflectCons.length];
for (int i = 0; i < reflectMethods.length; i++) {
this.methods[i] = createGenericMethodMember(reflectMethods[i]);
}
for (int i = 0; i < reflectCons.length; i++) {
this.methods[i + reflectMethods.length] =
createGenericConstructorMember(reflectCons[i]);
}
}
return methods;
}
/**
* Returns the generic type, regardless of the resolvedType we 'know about'
*/
public ResolvedType getGenericResolvedType() {
ResolvedType rt = getResolvedTypeX();
if (rt.isParameterizedType() || rt.isRawType()) return rt.getGenericType();
return rt;
}
private ResolvedMember createGenericMethodMember(Method forMethod) {
ReflectionBasedResolvedMemberImpl ret =
new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.METHOD,
getGenericResolvedType(),
forMethod.getModifiers(),
typeConverter.fromType(forMethod.getReturnType()),
forMethod.getName(),
typeConverter.fromTypes(forMethod.getParameterTypes()),
typeConverter.fromTypes(forMethod.getExceptionTypes()),
forMethod
);
ret.setAnnotationFinder(this.annotationFinder);
ret.setGenericSignatureInformationProvider(new Java15GenericSignatureInformationProvider(this.getWorld()));
return ret;
}
private ResolvedMember createGenericConstructorMember(Constructor forConstructor) {
ReflectionBasedResolvedMemberImpl ret =
new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.METHOD,
getGenericResolvedType(),
forConstructor.getModifiers(),
// to return what BCEL returns the return type is void
ResolvedType.VOID,//getGenericResolvedType(),
"<init>",
typeConverter.fromTypes(forConstructor.getParameterTypes()),
typeConverter.fromTypes(forConstructor.getExceptionTypes()),
forConstructor
);
ret.setAnnotationFinder(this.annotationFinder);
ret.setGenericSignatureInformationProvider(new Java15GenericSignatureInformationProvider(this.getWorld()));
return ret;
}
private ResolvedMember createGenericFieldMember(Field forField) {
ReflectionBasedResolvedMemberImpl ret =
new ReflectionBasedResolvedMemberImpl(
org.aspectj.weaver.Member.FIELD,
getGenericResolvedType(),
forField.getModifiers(),
typeConverter.fromType(forField.getType()),
forField.getName(),
new UnresolvedType[0],
forField);
ret.setAnnotationFinder(this.annotationFinder);
ret.setGenericSignatureInformationProvider(new Java15GenericSignatureInformationProvider(this.getWorld()));
return ret;
}
public ResolvedMember[] getDeclaredPointcuts() {
if (pointcuts == null) {
Pointcut[] pcs = this.myType.getDeclaredPointcuts();
pointcuts = new ResolvedMember[pcs.length];
PointcutParser parser = PointcutParser.getPointcutParserSupportingAllPrimitivesAndUsingSpecifiedClassloaderForResolution(classLoader);
World world = getWorld();
if (world instanceof ReflectionWorld) {
parser.setWorld((ReflectionWorld)getWorld());
}
for (int i = 0; i < pcs.length; i++) {
AjType<?>[] ptypes = pcs[i].getParameterTypes();
String[] pnames = pcs[i].getParameterNames();
if (pnames.length != ptypes.length) {
pnames = tryToDiscoverParameterNames(pcs[i]);
if (pnames == null || (pnames.length != ptypes.length)) {
throw new IllegalStateException("Required parameter names not available when parsing pointcut " + pcs[i].getName() + " in type " + getResolvedTypeX().getName());
}
}
PointcutParameter[] parameters = new PointcutParameter[ptypes.length];
for (int j = 0; j < parameters.length; j++) {
parameters[j] = parser.createPointcutParameter(pnames[j],ptypes[j].getJavaClass());
}
String pcExpr = pcs[i].getPointcutExpression().toString();
PointcutExpressionImpl pEx = (PointcutExpressionImpl) parser.parsePointcutExpression(pcExpr,getBaseClass(),parameters);
org.aspectj.weaver.patterns.Pointcut pc = pEx.getUnderlyingPointcut();
UnresolvedType[] weaverPTypes = new UnresolvedType[ptypes.length];
for (int j = 0; j < weaverPTypes.length; j++) {
weaverPTypes[j] = UnresolvedType.forName(ptypes[j].getName());
}
pointcuts[i] = new ResolvedPointcutDefinition(getResolvedTypeX(),pcs[i].getModifiers(),pcs[i].getName(),weaverPTypes,pc);
}
}
return pointcuts;
}
// for @AspectJ pointcuts compiled by javac only...
private String[] tryToDiscoverParameterNames(Pointcut pcut) {
Method[] ms = pcut.getDeclaringType().getJavaClass().getDeclaredMethods();
for(Method m : ms) {
if (m.getName().equals(pcut.getName())) {
return argNameFinder.getParameterNames(m);
}
}
return null;
}
public boolean isAnnotation() {
return getBaseClass().isAnnotation();
}
public boolean isAnnotationStyleAspect() {
return getBaseClass().isAnnotationPresent(Aspect.class);
}
public boolean isAnnotationWithRuntimeRetention() {
if (!isAnnotation()) return false;
if (getBaseClass().isAnnotationPresent(Retention.class)) {
Retention retention = (Retention) getBaseClass().getAnnotation(Retention.class);
RetentionPolicy policy = retention.value();
return policy == RetentionPolicy.RUNTIME;
} else {
return false;
}
}
public boolean isAspect() {
return this.myType.isAspect();
}
public boolean isEnum() {
return getBaseClass().isEnum();
}
public boolean isGeneric() {
//return false; // for now
return getBaseClass().getTypeParameters().length > 0;
}
@Override
public boolean isAnonymous() {
return this.myClass.isAnonymousClass();
}
}
|
140,357 |
Bug 140357 NPE or StackOverflow when resolving reference pointcut in ReflectionWorld
|
Given a type such as : private static class NamedPointcutResolution { @Pointcut("execution(* *(..))") public void a() {} @Pointcut("this(org.aspectj.weaver.tools.Java15PointcutExpressionTest.A)") public void b() {} @Pointcut("a() && b()") public void c() {} } The reflection based delegate is unable to resolve the pointcut c() failing with either (1) an NPE, or (2) a StackOverflow, depending on the order of the pointcut definitions in the type. The problem occurs because in resolving "c()" we get all the pointcuts in the type, which gets a(), b(), and c(), and tries to resolve them...
|
resolved fixed
|
b954b26
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-05T14:08:35Z | 2006-05-05T14:40:00Z |
weaver5/java5-testsrc/org/aspectj/weaver/tools/Java15PointcutExpressionTest.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer Initial implementation
* ******************************************************************/
package org.aspectj.weaver.tools;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
import java.util.List;
import org.aspectj.lang.annotation.Pointcut;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* @author colyer
*
*/
public class Java15PointcutExpressionTest extends TestCase {
public static Test suite() {
TestSuite suite = new TestSuite("Java15PointcutExpressionTest");
suite.addTestSuite(Java15PointcutExpressionTest.class);
return suite;
}
private PointcutParser parser;
private Method a;
private Method b;
private Method c;
private Method d;
public void testAtThis() {
PointcutExpression atThis = parser.parsePointcutExpression("@this(org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyAnnotation)");
ShadowMatch sMatch1 = atThis.matchesMethodExecution(a);
ShadowMatch sMatch2 = atThis.matchesMethodExecution(b);
assertTrue("maybe matches A",sMatch1.maybeMatches());
assertTrue("maybe matches B",sMatch2.maybeMatches());
JoinPointMatch jp1 = sMatch1.matchesJoinPoint(new A(), new A(), new Object[0]);
assertFalse("does not match",jp1.matches());
JoinPointMatch jp2 = sMatch2.matchesJoinPoint(new B(), new B(), new Object[0]);
assertTrue("matches",jp2.matches());
}
public void testAtTarget() {
PointcutExpression atTarget = parser.parsePointcutExpression("@target(org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyAnnotation)");
ShadowMatch sMatch1 = atTarget.matchesMethodExecution(a);
ShadowMatch sMatch2 = atTarget.matchesMethodExecution(b);
assertTrue("maybe matches A",sMatch1.maybeMatches());
assertTrue("maybe matches B",sMatch2.maybeMatches());
JoinPointMatch jp1 = sMatch1.matchesJoinPoint(new A(), new A(), new Object[0]);
assertFalse("does not match",jp1.matches());
JoinPointMatch jp2 = sMatch2.matchesJoinPoint(new B(), new B(), new Object[0]);
assertTrue("matches",jp2.matches());
}
public void testAtThisWithBinding() {
PointcutParameter param = parser.createPointcutParameter("a",MyAnnotation.class);
B myB = new B();
MyAnnotation bAnnotation = B.class.getAnnotation(MyAnnotation.class);
PointcutExpression atThis = parser.parsePointcutExpression("@this(a)",A.class,new PointcutParameter[] {param});
ShadowMatch sMatch1 = atThis.matchesMethodExecution(a);
ShadowMatch sMatch2 = atThis.matchesMethodExecution(b);
assertTrue("maybe matches A",sMatch1.maybeMatches());
assertTrue("maybe matches B",sMatch2.maybeMatches());
JoinPointMatch jp1 = sMatch1.matchesJoinPoint(new A(), new A(), new Object[0]);
assertFalse("does not match",jp1.matches());
JoinPointMatch jp2 = sMatch2.matchesJoinPoint(myB, myB, new Object[0]);
assertTrue("matches",jp2.matches());
assertEquals(1,jp2.getParameterBindings().length);
assertEquals("should be myB's annotation",bAnnotation,jp2.getParameterBindings()[0].getBinding());
}
public void testAtTargetWithBinding() {
PointcutParameter param = parser.createPointcutParameter("a",MyAnnotation.class);
B myB = new B();
MyAnnotation bAnnotation = B.class.getAnnotation(MyAnnotation.class);
PointcutExpression atThis = parser.parsePointcutExpression("@target(a)",A.class,new PointcutParameter[] {param});
ShadowMatch sMatch1 = atThis.matchesMethodExecution(a);
ShadowMatch sMatch2 = atThis.matchesMethodExecution(b);
assertTrue("maybe matches A",sMatch1.maybeMatches());
assertTrue("maybe matches B",sMatch2.maybeMatches());
JoinPointMatch jp1 = sMatch1.matchesJoinPoint(new A(), new A(), new Object[0]);
assertFalse("does not match",jp1.matches());
JoinPointMatch jp2 = sMatch2.matchesJoinPoint(myB, myB, new Object[0]);
assertTrue("matches",jp2.matches());
assertEquals(1,jp2.getParameterBindings().length);
assertEquals("should be myB's annotation",bAnnotation,jp2.getParameterBindings()[0].getBinding());
}
public void testAtArgs() {
PointcutExpression atArgs = parser.parsePointcutExpression("@args(..,org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyAnnotation)");
ShadowMatch sMatch1 = atArgs.matchesMethodExecution(a);
ShadowMatch sMatch2 = atArgs.matchesMethodExecution(c);
assertTrue("never matches A",sMatch1.neverMatches());
assertTrue("maybe matches C",sMatch2.maybeMatches());
JoinPointMatch jp2 = sMatch2.matchesJoinPoint(new B(), new B(), new Object[]{new A(),new B()});
assertTrue("matches",jp2.matches());
atArgs = parser.parsePointcutExpression("@args(org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyAnnotation,org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyAnnotation)");
sMatch1 = atArgs.matchesMethodExecution(a);
sMatch2 = atArgs.matchesMethodExecution(c);
assertTrue("never matches A",sMatch1.neverMatches());
assertTrue("maybe matches C",sMatch2.maybeMatches());
JoinPointMatch jp1 = sMatch2.matchesJoinPoint(new A(), new A(), new Object[] {new A(), new B()});
assertFalse("does not match",jp1.matches());
jp2 = sMatch2.matchesJoinPoint(new B(), new B(), new Object[] {new B(),new B()});
assertTrue("matches",jp2.matches());
}
public void testAtArgs2() {
PointcutExpression atArgs = parser.parsePointcutExpression("@args(*, org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyAnnotation)");
ShadowMatch sMatch1 = atArgs.matchesMethodExecution(c);
ShadowMatch sMatch2 = atArgs.matchesMethodExecution(d);
assertTrue("maybe matches c",sMatch1.maybeMatches());
assertTrue("maybe matches d",sMatch2.maybeMatches());
JoinPointMatch jp1 = sMatch1.matchesJoinPoint(new B(), new B(), new Object[] {new A(), new B()});
assertTrue("matches",jp1.matches());
JoinPointMatch jp2 = sMatch2.matchesJoinPoint(new B(), new B(), new Object[] {new A(),new A()});
assertFalse("does not match",jp2.matches());
}
public void testAtArgsWithBinding() {
PointcutParameter p1 = parser.createPointcutParameter("a",MyAnnotation.class);
PointcutParameter p2 = parser.createPointcutParameter("b", MyAnnotation.class);
PointcutExpression atArgs = parser.parsePointcutExpression("@args(..,a)",A.class,new PointcutParameter[] {p1});
ShadowMatch sMatch2 = atArgs.matchesMethodExecution(c);
assertTrue("maybe matches C",sMatch2.maybeMatches());
JoinPointMatch jp2 = sMatch2.matchesJoinPoint(new B(), new B(), new Object[]{new A(),new B()});
assertTrue("matches",jp2.matches());
assertEquals(1,jp2.getParameterBindings().length);
MyAnnotation bAnnotation = B.class.getAnnotation(MyAnnotation.class);
assertEquals("annotation on B",bAnnotation,jp2.getParameterBindings()[0].getBinding());
atArgs = parser.parsePointcutExpression("@args(a,b)",A.class,new PointcutParameter[] {p1,p2});
sMatch2 = atArgs.matchesMethodExecution(c);
assertTrue("maybe matches C",sMatch2.maybeMatches());
jp2 = sMatch2.matchesJoinPoint(new B(), new B(), new Object[] {new B(),new B()});
assertTrue("matches",jp2.matches());
assertEquals(2,jp2.getParameterBindings().length);
assertEquals("annotation on B",bAnnotation,jp2.getParameterBindings()[0].getBinding());
assertEquals("annotation on B",bAnnotation,jp2.getParameterBindings()[1].getBinding());
}
public void testAtWithin() {
PointcutExpression atWithin = parser.parsePointcutExpression("@within(org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyAnnotation)");
ShadowMatch sMatch1 = atWithin.matchesMethodExecution(a);
ShadowMatch sMatch2 = atWithin.matchesMethodExecution(b);
assertTrue("does not match a",sMatch1.neverMatches());
assertTrue("matches b",sMatch2.alwaysMatches());
}
public void testAtWithinWithBinding() {
PointcutParameter p1 = parser.createPointcutParameter("x",MyAnnotation.class);
PointcutExpression atWithin = parser.parsePointcutExpression("@within(x)",B.class,new PointcutParameter[] {p1});
ShadowMatch sMatch1 = atWithin.matchesMethodExecution(a);
ShadowMatch sMatch2 = atWithin.matchesMethodExecution(b);
assertTrue("does not match a",sMatch1.neverMatches());
assertTrue("matches b",sMatch2.alwaysMatches());
JoinPointMatch jpm = sMatch2.matchesJoinPoint(new B(), new B(), new Object[0]);
assertTrue(jpm.matches());
assertEquals(1,jpm.getParameterBindings().length);
MyAnnotation bAnnotation = B.class.getAnnotation(MyAnnotation.class);
assertEquals("annotation on B",bAnnotation,jpm.getParameterBindings()[0].getBinding());
}
public void testAtWithinCode() {
PointcutExpression atWithinCode = parser.parsePointcutExpression("@withincode(org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyAnnotation)");
ShadowMatch sMatch1 = atWithinCode.matchesMethodCall(a,b);
ShadowMatch sMatch2 = atWithinCode.matchesMethodCall(a,a);
assertTrue("does not match from b",sMatch1.neverMatches());
assertTrue("matches from a",sMatch2.alwaysMatches());
}
public void testAtWithinCodeWithBinding() {
PointcutParameter p1 = parser.createPointcutParameter("x",MyAnnotation.class);
PointcutExpression atWithinCode = parser.parsePointcutExpression("@withincode(x)",A.class,new PointcutParameter[] {p1});
ShadowMatch sMatch2 = atWithinCode.matchesMethodCall(a,a);
assertTrue("matches from a",sMatch2.alwaysMatches());
JoinPointMatch jpm = sMatch2.matchesJoinPoint(new A(), new A(), new Object[0]);
assertEquals(1,jpm.getParameterBindings().length);
MyAnnotation annOna = a.getAnnotation(MyAnnotation.class);
assertEquals("MyAnnotation on a",annOna,jpm.getParameterBindings()[0].getBinding());
}
public void testAtAnnotation() {
PointcutExpression atAnnotation = parser.parsePointcutExpression("@annotation(org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyAnnotation)");
ShadowMatch sMatch1 = atAnnotation.matchesMethodCall(b,a);
ShadowMatch sMatch2 = atAnnotation.matchesMethodCall(a,a);
assertTrue("does not match call to b",sMatch1.neverMatches());
assertTrue("matches call to a",sMatch2.alwaysMatches());
}
public void testAtAnnotationWithBinding() {
PointcutParameter p1 = parser.createPointcutParameter("x",MyAnnotation.class);
PointcutExpression atAnnotation = parser.parsePointcutExpression("@annotation(x)",A.class,new PointcutParameter[] {p1});
ShadowMatch sMatch2 = atAnnotation.matchesMethodCall(a,a);
assertTrue("matches call to a",sMatch2.alwaysMatches());
JoinPointMatch jpm = sMatch2.matchesJoinPoint(new A(), new A(), new Object[0]);
assertTrue(jpm.matches());
assertEquals(1,jpm.getParameterBindings().length);
MyAnnotation annOna = a.getAnnotation(MyAnnotation.class);
assertEquals("MyAnnotation on a",annOna,jpm.getParameterBindings()[0].getBinding());
}
public void testReferencePointcutNoParams() {
PointcutExpression pc = parser.parsePointcutExpression("foo()",C.class,new PointcutParameter[0]);
ShadowMatch sMatch1 = pc.matchesMethodCall(a,b);
ShadowMatch sMatch2 = pc.matchesMethodExecution(a);
assertTrue("no match on call",sMatch1.neverMatches());
assertTrue("match on execution",sMatch2.alwaysMatches());
pc = parser.parsePointcutExpression("org.aspectj.weaver.tools.Java15PointcutExpressionTest.C.foo()");
sMatch1 = pc.matchesMethodCall(a,b);
sMatch2 = pc.matchesMethodExecution(a);
assertTrue("no match on call",sMatch1.neverMatches());
assertTrue("match on execution",sMatch2.alwaysMatches());
}
public void testReferencePointcutParams() {
PointcutParameter p1 = parser.createPointcutParameter("x",A.class);
PointcutExpression pc = parser.parsePointcutExpression("goo(x)",C.class,new PointcutParameter[] {p1});
ShadowMatch sMatch1 = pc.matchesMethodCall(a,b);
ShadowMatch sMatch2 = pc.matchesMethodExecution(a);
assertTrue("no match on call",sMatch1.neverMatches());
assertTrue("match on execution",sMatch2.maybeMatches());
A anA = new A();
JoinPointMatch jpm = sMatch2.matchesJoinPoint(anA, new A(), new Object[0]);
assertTrue(jpm.matches());
assertEquals("should be bound to anA",anA,jpm.getParameterBindings()[0].getBinding());
}
public void testExecutionWithClassFileRetentionAnnotation() {
PointcutExpression pc1 = parser.parsePointcutExpression("execution(@org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyAnnotation * *(..))");
PointcutExpression pc2 = parser.parsePointcutExpression("execution(@org.aspectj.weaver.tools.Java15PointcutExpressionTest.MyClassFileRetentionAnnotation * *(..))");
ShadowMatch sMatch = pc1.matchesMethodExecution(a);
assertTrue("matches",sMatch.alwaysMatches());
sMatch = pc2.matchesMethodExecution(a);
assertTrue("no match",sMatch.neverMatches());
sMatch = pc1.matchesMethodExecution(b);
assertTrue("no match",sMatch.neverMatches());
sMatch = pc2.matchesMethodExecution(b);
assertTrue("matches",sMatch.alwaysMatches());
}
public void testGenericMethodSignatures() throws Exception{
PointcutExpression ex = parser.parsePointcutExpression("execution(* set*(java.util.List<org.aspectj.weaver.tools.Java15PointcutExpressionTest.C>))");
Method m = TestBean.class.getMethod("setFriends",List.class);
ShadowMatch sm = ex.matchesMethodExecution(m);
assertTrue("should match",sm.alwaysMatches());
}
public void testAnnotationInExecution() throws Exception {
PointcutExpression ex = parser.parsePointcutExpression("execution(@(org.springframework..*) * *(..))");
}
public void testVarArgsMatching() throws Exception {
PointcutExpression ex = parser.parsePointcutExpression("execution(* *(String...))");
Method usesVarArgs = D.class.getMethod("varArgs",String[].class);
Method noVarArgs = D.class.getMethod("nonVarArgs", String[].class);
ShadowMatch sm1 = ex.matchesMethodExecution(usesVarArgs);
assertTrue("should match",sm1.alwaysMatches());
ShadowMatch sm2 = ex.matchesMethodExecution(noVarArgs);
assertFalse("should not match",sm2.alwaysMatches());
}
public void testJavaLangMatching() throws Exception {
PointcutExpression ex = parser.parsePointcutExpression("@within(java.lang.Deprecated)");
Method foo = GoldenOldie.class.getMethod("foo");
ShadowMatch sm1 = ex.matchesMethodExecution(foo);
assertTrue("should match",sm1.alwaysMatches());
}
protected void setUp() throws Exception {
super.setUp();
parser = PointcutParser.getPointcutParserSupportingAllPrimitivesAndUsingSpecifiedClassloaderForResolution(this.getClass().getClassLoader());
a = A.class.getMethod("a");
b = B.class.getMethod("b");
c = B.class.getMethod("c",new Class[] {A.class,B.class});
d = B.class.getMethod("d",new Class[] {A.class,A.class});
}
@Retention(RetentionPolicy.RUNTIME)
private @interface MyAnnotation {}
private @interface MyClassFileRetentionAnnotation {}
private static class A {
@MyAnnotation public void a() {}
}
@MyAnnotation
private static class B {
@MyClassFileRetentionAnnotation public void b() {}
public void c(A anA, B aB) {}
public void d(A anA, A anotherA) {}
}
private static class C {
@Pointcut("execution(* *(..))")
public void foo() {}
@Pointcut(value="execution(* *(..)) && this(x)", argNames="x")
public void goo(A x) {}
}
private static class D {
public void nonVarArgs(String[] strings) {};
public void varArgs(String... strings) {};
}
static class TestBean {
public void setFriends(List<C> friends) {}
}
@Deprecated
static class GoldenOldie {
public void foo() {}
}
}
|
138,384 |
Bug 138384 java.lang.ClassFormatError: Invalid method Code length 83071 in class file org/eclipse/jdt/internal/compiler/impl/Constant
| null |
resolved fixed
|
5d2b5b8
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-12T08:17:43Z | 2006-04-25T15:46:40Z |
bcel-builder/src/org/aspectj/apache/bcel/generic/InstructionList.java
|
package org.aspectj.apache.bcel.generic;
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache BCEL" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* "Apache BCEL", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.Constant;
import org.aspectj.apache.bcel.util.ByteSequence;
import java.io.*;
import java.util.Iterator;
import java.util.HashMap;
import java.util.ArrayList;
/**
* This class is a container for a list of <a
* href="Instruction.html">Instruction</a> objects. Instructions can
* be appended, inserted, moved, deleted, etc.. Instructions are being
* wrapped into <a
* href="InstructionHandle.html">InstructionHandles</a> objects that
* are returned upon append/insert operations. They give the user
* (read only) access to the list structure, such that it can be traversed and
* manipulated in a controlled way.
*
* A list is finally dumped to a byte code array with <a
* href="#getByteCode()">getByteCode</a>.
*
* @version $Id: InstructionList.java,v 1.3 2006/02/14 13:32:07 aclement Exp $
* @author <A HREF="mailto:[email protected]">M. Dahm</A>
* @see Instruction
* @see InstructionHandle
* @see BranchHandle
*/
public class InstructionList implements Serializable {
private InstructionHandle start = null, end = null;
private int length = 0; // number of elements in list
private int[] byte_positions; // byte code offsets corresponding to instructions
/**
* Create (empty) instruction list.
*/
public InstructionList() {}
/**
* Create instruction list containing one instruction.
* @param i initial instruction
*/
public InstructionList(Instruction i) {
append(i);
}
/**
* Create instruction list containing one instruction.
* @param i initial instruction
*/
public InstructionList(BranchInstruction i) {
append(i);
}
/**
* Initialize list with (nonnull) compound instruction. Consumes argument
* list, i.e., it becomes empty.
*
* @param c compound instruction (list)
*/
public InstructionList(CompoundInstruction c) {
append(c.getInstructionList());
}
/**
* Test for empty list.
*/
public boolean isEmpty() { return start == null; } // && end == null
/**
* Find the target instruction (handle) that corresponds to the given target
* position (byte code offset).
*
* @param ihs array of instruction handles, i.e. il.getInstructionHandles()
* @param pos array of positions corresponding to ihs, i.e. il.getInstructionPositions()
* @param count length of arrays
* @param target target position to search for
* @return target position's instruction handle if available
*/
public static InstructionHandle findHandle(InstructionHandle[] ihs,
int[] pos, int count,int target) {
int l=0, r = count - 1;
// Do a binary search since the pos array is ordered
int i,j;
do {
i = (l + r) / 2;
j = pos[i];
if (j == target) return ihs[i]; // found it
else if (target < j) r=i-1; // else constrain search area
else l=i+1; // target > j
} while(l <= r);
return null;
}
/**
* Get instruction handle for instruction at byte code position pos.
* This only works properly, if the list is freshly initialized from a byte array or
* setPositions() has been called before this method.
*
* @param pos byte code position to search for
* @return target position's instruction handle if available
*/
public InstructionHandle findHandle(int pos) {
InstructionHandle[] ihs = getInstructionHandles();
return findHandle(ihs, byte_positions, length, pos);
}
public InstructionHandle[] getInstructionsAsArray() {
return getInstructionHandles();
}
public InstructionHandle findHandle(int pos,InstructionHandle[] instructionArray) {
return findHandle(instructionArray,byte_positions,length,pos);
}
/**
* Initialize instruction list from byte array.
*
* @param code byte array containing the instructions
*/
public InstructionList(byte[] code) {
ByteSequence bytes = new ByteSequence(code);
InstructionHandle[] ihs = new InstructionHandle[code.length];
int[] pos = new int[code.length]; // Can't be more than that
int count = 0; // Contains actual length
/* Pass 1: Create an object for each byte code and append them
* to the list.
*/
try {
while(bytes.available() > 0) {
// Remember byte offset and associate it with the instruction
int off = bytes.getIndex();
pos[count] = off;
/* Read one instruction from the byte stream, the byte position is set
* accordingly.
*/
Instruction i = Instruction.readInstruction(bytes);
InstructionHandle ih;
if(i instanceof BranchInstruction) // Use proper append() method
ih = append((BranchInstruction)i);
else
ih = append(i);
ih.setPosition(off);
ihs[count] = ih;
count++;
}
} catch(IOException e) { throw new ClassGenException(e.toString()); }
byte_positions = new int[count]; // Trim to proper size
System.arraycopy(pos, 0, byte_positions, 0, count);
/* Pass 2: Look for BranchInstruction and update their targets, i.e.,
* convert offsets to instruction handles.
*/
for(int i=0; i < count; i++) {
if(ihs[i] instanceof BranchHandle) {
BranchInstruction bi = (BranchInstruction)ihs[i].instruction;
int target = bi.position + bi.getIndex(); /* Byte code position:
* relative -> absolute. */
// Search for target position
InstructionHandle ih = findHandle(ihs, pos, count, target);
if(ih == null) // Search failed
throw new ClassGenException("Couldn't find target for branch: " + bi);
bi.setTarget(ih); // Update target
// If it is a Select instruction, update all branch targets
if(bi instanceof Select) { // Either LOOKUPSWITCH or TABLESWITCH
Select s = (Select)bi;
int[] indices = s.getIndices();
for(int j=0; j < indices.length; j++) {
target = bi.position + indices[j];
ih = findHandle(ihs, pos, count, target);
if(ih == null) // Search failed
throw new ClassGenException("Couldn't find target for switch: " + bi);
s.setTarget(j, ih); // Update target
}
}
}
}
}
/**
* Append another list after instruction (handle) ih contained in this list.
* Consumes argument list, i.e., it becomes empty.
*
* @param ih where to append the instruction list
* @param il Instruction list to append to this one
* @return instruction handle pointing to the <B>first</B> appended instruction
*/
public InstructionHandle append(InstructionHandle ih, InstructionList il) {
if(il == null)
throw new ClassGenException("Appending null InstructionList");
if(il.isEmpty()) // Nothing to do
return ih;
InstructionHandle next = ih.next, ret = il.start;
ih.next = il.start;
il.start.prev = ih;
il.end.next = next;
if(next != null) // i == end ?
next.prev = il.end;
else
end = il.end; // Update end ...
length += il.length; // Update length
il.clear();
return ret;
}
/**
* Append another list after instruction i contained in this list.
* Consumes argument list, i.e., it becomes empty.
*
* @param i where to append the instruction list
* @param il Instruction list to append to this one
* @return instruction handle pointing to the <B>first</B> appended instruction
*/
public InstructionHandle append(Instruction i, InstructionList il) {
InstructionHandle ih;
if((ih = findInstruction2(i)) == null) // Also applies for empty list
throw new ClassGenException("Instruction " + i +
" is not contained in this list.");
return append(ih, il);
}
/**
* Append another list to this one.
* Consumes argument list, i.e., it becomes empty.
*
* @param il list to append to end of this list
* @return instruction handle of the <B>first</B> appended instruction
*/
public InstructionHandle append(InstructionList il) {
if(il == null)
throw new ClassGenException("Appending null InstructionList");
if(il.isEmpty()) // Nothing to do
return null;
if(isEmpty()) {
start = il.start;
end = il.end;
length = il.length;
il.clear();
return start;
} else
return append(end, il); // was end.instruction
}
/**
* Append an instruction to the end of this list.
*
* @param ih instruction to append
*/
private void append(InstructionHandle ih) {
if(isEmpty()) {
start = end = ih;
ih.next = ih.prev = null;
}
else {
end.next = ih;
ih.prev = end;
ih.next = null;
end = ih;
}
length++; // Update length
}
/**
* Append an instruction to the end of this list.
*
* @param i instruction to append
* @return instruction handle of the appended instruction
*/
public InstructionHandle append(Instruction i) {
InstructionHandle ih = InstructionHandle.getInstructionHandle(i);
append(ih);
return ih;
}
/**
* Append a branch instruction to the end of this list.
*
* @param i branch instruction to append
* @return branch instruction handle of the appended instruction
*/
public BranchHandle append(BranchInstruction i) {
BranchHandle ih = BranchHandle.getBranchHandle(i);
append(ih);
return ih;
}
/**
* Append a single instruction j after another instruction i, which
* must be in this list of course!
*
* @param i Instruction in list
* @param j Instruction to append after i in list
* @return instruction handle of the first appended instruction
*/
public InstructionHandle append(Instruction i, Instruction j) {
return append(i, new InstructionList(j));
}
/**
* Append a compound instruction, after instruction i.
*
* @param i Instruction in list
* @param c The composite instruction (containing an InstructionList)
* @return instruction handle of the first appended instruction
*/
public InstructionHandle append(Instruction i, CompoundInstruction c) {
return append(i, c.getInstructionList());
}
/**
* Append a compound instruction.
*
* @param c The composite instruction (containing an InstructionList)
* @return instruction handle of the first appended instruction
*/
public InstructionHandle append(CompoundInstruction c) {
return append(c.getInstructionList());
}
/**
* Append a compound instruction.
*
* @param ih where to append the instruction list
* @param c The composite instruction (containing an InstructionList)
* @return instruction handle of the first appended instruction
*/
public InstructionHandle append(InstructionHandle ih, CompoundInstruction c) {
return append(ih, c.getInstructionList());
}
/**
* Append an instruction after instruction (handle) ih contained in this list.
*
* @param ih where to append the instruction list
* @param i Instruction to append
* @return instruction handle pointing to the <B>first</B> appended instruction
*/
public InstructionHandle append(InstructionHandle ih, Instruction i) {
return append(ih, new InstructionList(i));
}
/**
* Append an instruction after instruction (handle) ih contained in this list.
*
* @param ih where to append the instruction list
* @param i Instruction to append
* @return instruction handle pointing to the <B>first</B> appended instruction
*/
public BranchHandle append(InstructionHandle ih, BranchInstruction i) {
BranchHandle bh = BranchHandle.getBranchHandle(i);
InstructionList il = new InstructionList();
il.append(bh);
append(ih, il);
return bh;
}
/**
* Insert another list before Instruction handle ih contained in this list.
* Consumes argument list, i.e., it becomes empty.
*
* @param i where to append the instruction list
* @param il Instruction list to insert
* @return instruction handle of the first inserted instruction
*/
public InstructionHandle insert(InstructionHandle ih, InstructionList il) {
if(il == null)
throw new ClassGenException("Inserting null InstructionList");
if(il.isEmpty()) // Nothing to do
return ih;
InstructionHandle prev = ih.prev, ret = il.start;
ih.prev = il.end;
il.end.next = ih;
il.start.prev = prev;
if(prev != null) // ih == start ?
prev.next = il.start;
else
start = il.start; // Update start ...
length += il.length; // Update length
il.clear();
return ret;
}
/**
* Insert another list.
*
* @param il list to insert before start of this list
* @return instruction handle of the first inserted instruction
*/
public InstructionHandle insert(InstructionList il) {
if(isEmpty()) {
append(il); // Code is identical for this case
return start;
}
else
return insert(start, il);
}
/**
* Insert an instruction at start of this list.
*
* @param ih instruction to insert
*/
private void insert(InstructionHandle ih) {
if(isEmpty()) {
start = end = ih;
ih.next = ih.prev = null;
} else {
start.prev = ih;
ih.next = start;
ih.prev = null;
start = ih;
}
length++;
}
/**
* Insert another list before Instruction i contained in this list.
* Consumes argument list, i.e., it becomes empty.
*
* @param i where to append the instruction list
* @param il Instruction list to insert
* @return instruction handle pointing to the first inserted instruction,
* i.e., il.getStart()
*/
public InstructionHandle insert(Instruction i, InstructionList il) {
InstructionHandle ih;
if((ih = findInstruction1(i)) == null)
throw new ClassGenException("Instruction " + i +
" is not contained in this list.");
return insert(ih, il);
}
/**
* Insert an instruction at start of this list.
*
* @param i instruction to insert
* @return instruction handle of the inserted instruction
*/
public InstructionHandle insert(Instruction i) {
InstructionHandle ih = InstructionHandle.getInstructionHandle(i);
insert(ih);
return ih;
}
/**
* Insert a branch instruction at start of this list.
*
* @param i branch instruction to insert
* @return branch instruction handle of the appended instruction
*/
public BranchHandle insert(BranchInstruction i) {
BranchHandle ih = BranchHandle.getBranchHandle(i);
insert(ih);
return ih;
}
/**
* Insert a single instruction j before another instruction i, which
* must be in this list of course!
*
* @param i Instruction in list
* @param j Instruction to insert before i in list
* @return instruction handle of the first inserted instruction
*/
public InstructionHandle insert(Instruction i, Instruction j) {
return insert(i, new InstructionList(j));
}
/**
* Insert a compound instruction before instruction i.
*
* @param i Instruction in list
* @param c The composite instruction (containing an InstructionList)
* @return instruction handle of the first inserted instruction
*/
public InstructionHandle insert(Instruction i, CompoundInstruction c) {
return insert(i, c.getInstructionList());
}
/**
* Insert a compound instruction.
*
* @param c The composite instruction (containing an InstructionList)
* @return instruction handle of the first inserted instruction
*/
public InstructionHandle insert(CompoundInstruction c) {
return insert(c.getInstructionList());
}
/**
* Insert an instruction before instruction (handle) ih contained in this list.
*
* @param ih where to insert to the instruction list
* @param i Instruction to insert
* @return instruction handle of the first inserted instruction
*/
public InstructionHandle insert(InstructionHandle ih, Instruction i) {
return insert(ih, new InstructionList(i));
}
/**
* Insert a compound instruction.
*
* @param ih where to insert the instruction list
* @param c The composite instruction (containing an InstructionList)
* @return instruction handle of the first inserted instruction
*/
public InstructionHandle insert(InstructionHandle ih, CompoundInstruction c) {
return insert(ih, c.getInstructionList());
}
/**
* Insert an instruction before instruction (handle) ih contained in this list.
*
* @param ih where to insert to the instruction list
* @param i Instruction to insert
* @return instruction handle of the first inserted instruction
*/
public BranchHandle insert(InstructionHandle ih, BranchInstruction i) {
BranchHandle bh = BranchHandle.getBranchHandle(i);
InstructionList il = new InstructionList();
il.append(bh);
insert(ih, il);
return bh;
}
/**
* Take all instructions (handles) from "start" to "end" and append them after the
* new location "target". Of course, "end" must be after "start" and target must
* not be located withing this range. If you want to move something to the start of
* the list use null as value for target.<br>
* Any instruction targeters pointing to handles within the block, keep their targets.
*
* @param start of moved block
* @param end of moved block
* @param target of moved block
*/
public void move(InstructionHandle start, InstructionHandle end, InstructionHandle target) {
// Step 1: Check constraints
if((start == null) || (end == null))
throw new ClassGenException("Invalid null handle: From " + start + " to " + end);
if((target == start) || (target == end))
throw new ClassGenException("Invalid range: From " + start + " to " + end +
" contains target " + target);
for(InstructionHandle ih = start; ih != end.next; ih = ih.next) {
if(ih == null) // At end of list, end not found yet
throw new ClassGenException("Invalid range: From " + start + " to " + end);
else if(ih == target) // target may be null
throw new ClassGenException("Invalid range: From " + start + " to " + end +
" contains target " + target);
}
// Step 2: Temporarily remove the given instructions from the list
InstructionHandle prev = start.prev, next = end.next;
if(prev != null)
prev.next = next;
else // start == this.start!
this.start = next;
if(next != null)
next.prev = prev;
else // end == this.end!
this.end = prev;
start.prev = end.next = null;
// Step 3: append after target
if(target == null) { // append to start of list
end.next = this.start;
this.start = start;
} else {
next = target.next;
target.next = start;
start.prev = target;
end.next = next;
if(next != null)
next.prev = end;
}
}
/**
* Move a single instruction (handle) to a new location.
*
* @param ih moved instruction
* @param target new location of moved instruction
*/
public void move(InstructionHandle ih, InstructionHandle target) {
move(ih, ih, target);
}
/**
* Remove from instruction `prev' to instruction `next' both contained
* in this list. Throws TargetLostException when one of the removed instruction handles
* is still being targeted.
*
* @param prev where to start deleting (predecessor, exclusive)
* @param next where to end deleting (successor, exclusive)
*/
private void remove(InstructionHandle prev, InstructionHandle next)
throws TargetLostException
{
InstructionHandle first, last; // First and last deleted instruction
if((prev == null) && (next == null)) { // singleton list
first = last = start;
start = end = null;
} else {
if(prev == null) { // At start of list
first = start;
start = next;
} else {
first = prev.next;
prev.next = next;
}
if(next == null) { // At end of list
last = end;
end = prev;
} else {
last = next.prev;
next.prev = prev;
}
}
first.prev = null; // Completely separated from rest of list
last.next = null;
ArrayList target_vec = new ArrayList();
for(InstructionHandle ih=first; ih != null; ih = ih.next)
ih.getInstruction().dispose(); // e.g. BranchInstructions release their targets
StringBuffer buf = new StringBuffer("{ ");
for(InstructionHandle ih=first; ih != null; ih = next) {
next = ih.next;
length--;
if(ih.hasTargeters()) { // Still got targeters?
target_vec.add(ih);
buf.append(ih.toString(true) + " ");
ih.next = ih.prev = null;
} else
ih.dispose();
}
buf.append("}");
if(!target_vec.isEmpty()) {
InstructionHandle[] targeted = new InstructionHandle[target_vec.size()];
target_vec.toArray(targeted);
throw new TargetLostException(targeted, buf.toString());
}
}
/**
* Remove instruction from this list. The corresponding Instruction
* handles must not be reused!
*
* @param ih instruction (handle) to remove
*/
public void delete(InstructionHandle ih) throws TargetLostException {
remove(ih.prev, ih.next);
}
/**
* Remove instruction from this list. The corresponding Instruction
* handles must not be reused!
*
* @param i instruction to remove
*/
public void delete(Instruction i) throws TargetLostException {
InstructionHandle ih;
if((ih = findInstruction1(i)) == null)
throw new ClassGenException("Instruction " + i +
" is not contained in this list.");
delete(ih);
}
/**
* Remove instructions from instruction `from' to instruction `to' contained
* in this list. The user must ensure that `from' is an instruction before
* `to', or risk havoc. The corresponding Instruction handles must not be reused!
*
* @param from where to start deleting (inclusive)
* @param to where to end deleting (inclusive)
*/
public void delete(InstructionHandle from, InstructionHandle to)
throws TargetLostException
{
remove(from.prev, to.next);
}
/**
* Remove instructions from instruction `from' to instruction `to' contained
* in this list. The user must ensure that `from' is an instruction before
* `to', or risk havoc. The corresponding Instruction handles must not be reused!
*
* @param from where to start deleting (inclusive)
* @param to where to end deleting (inclusive)
*/
public void delete(Instruction from, Instruction to) throws TargetLostException {
InstructionHandle from_ih, to_ih;
if((from_ih = findInstruction1(from)) == null)
throw new ClassGenException("Instruction " + from +
" is not contained in this list.");
if((to_ih = findInstruction2(to)) == null)
throw new ClassGenException("Instruction " + to +
" is not contained in this list.");
delete(from_ih, to_ih);
}
/**
* Search for given Instruction reference, start at beginning of list.
*
* @param i instruction to search for
* @return instruction found on success, null otherwise
*/
private InstructionHandle findInstruction1(Instruction i) {
for(InstructionHandle ih=start; ih != null; ih = ih.next)
if(ih.instruction == i)
return ih;
return null;
}
/**
* Search for given Instruction reference, start at end of list
*
* @param i instruction to search for
* @return instruction found on success, null otherwise
*/
private InstructionHandle findInstruction2(Instruction i) {
for(InstructionHandle ih=end; ih != null; ih = ih.prev)
if(ih.instruction == i)
return ih;
return null;
}
public boolean contains(InstructionHandle i) {
if(i == null)
return false;
for(InstructionHandle ih=start; ih != null; ih = ih.next)
if(ih == i)
return true;
return false;
}
public boolean contains(Instruction i) {
return findInstruction1(i) != null;
}
public void setPositions() {
setPositions(false);
}
/**
* Give all instructions their position number (offset in byte stream), i.e.,
* make the list ready to be dumped.
*
* @param check Perform sanity checks, e.g. if all targeted instructions really belong
* to this list
*/
public void setPositions(boolean check) {
int max_additional_bytes = 0, additional_bytes = 0;
int index = 0, count = 0;
int[] pos = new int[length];
/* Pass 0: Sanity checks
*/
if(check) {
for(InstructionHandle ih=start; ih != null; ih = ih.next) {
Instruction i = ih.instruction;
if(i instanceof BranchInstruction) { // target instruction within list?
Instruction inst = ((BranchInstruction)i).getTarget().instruction;
if(!contains(inst))
throw new ClassGenException("Branch target of " +
Constants.OPCODE_NAMES[i.opcode] + ":" +
inst + " not in instruction list");
if(i instanceof Select) {
InstructionHandle[] targets = ((Select)i).getTargets();
for(int j=0; j < targets.length; j++) {
inst = targets[j].instruction;
if(!contains(inst))
throw new ClassGenException("Branch target of " +
Constants.OPCODE_NAMES[i.opcode] + ":" +
inst + " not in instruction list");
}
}
if(!(ih instanceof BranchHandle))
throw new ClassGenException("Branch instruction " +
Constants.OPCODE_NAMES[i.opcode] + ":" +
inst + " not contained in BranchHandle.");
}
}
}
/* Pass 1: Set position numbers and sum up the maximum number of bytes an
* instruction may be shifted.
*/
for(InstructionHandle ih=start; ih != null; ih = ih.next) {
Instruction i = ih.instruction;
ih.setPosition(index);
pos[count++] = index;
/* Get an estimate about how many additional bytes may be added, because
* BranchInstructions may have variable length depending on the target
* offset (short vs. int) or alignment issues (TABLESWITCH and
* LOOKUPSWITCH).
*/
switch(i.getOpcode()) {
case Constants.JSR: case Constants.GOTO:
max_additional_bytes += 2;
break;
case Constants.TABLESWITCH: case Constants.LOOKUPSWITCH:
max_additional_bytes += 3;
break;
}
index += i.getLength();
}
/* Pass 2: Expand the variable-length (Branch)Instructions depending on
* the target offset (short or int) and ensure that branch targets are
* within this list.
*/
for(InstructionHandle ih=start; ih != null; ih = ih.next)
additional_bytes += ih.updatePosition(additional_bytes, max_additional_bytes);
/* Pass 3: Update position numbers (which may have changed due to the
* preceding expansions), like pass 1.
*/
index=count=0;
for(InstructionHandle ih=start; ih != null; ih = ih.next) {
Instruction i = ih.instruction;
ih.setPosition(index);
pos[count++] = index;
index += i.getLength();
}
byte_positions = new int[count]; // Trim to proper size
System.arraycopy(pos, 0, byte_positions, 0, count);
}
/**
* When everything is finished, use this method to convert the instruction
* list into an array of bytes.
*
* @return the byte code ready to be dumped
*/
public byte[] getByteCode() {
// Update position indices of instructions
setPositions();
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(b);
try {
for(InstructionHandle ih=start; ih != null; ih = ih.next) {
Instruction i = ih.instruction;
i.dump(out); // Traverse list
}
} catch(IOException e) {
System.err.println(e);
return null;
}
return b.toByteArray();
}
/**
* @return an array of instructions without target information for branch instructions.
*/
public Instruction[] getInstructions() {
ByteSequence bytes = new ByteSequence(getByteCode());
ArrayList instructions = new ArrayList();
try {
while(bytes.available() > 0) {
instructions.add(Instruction.readInstruction(bytes));
}
} catch(IOException e) { throw new ClassGenException(e.toString()); }
Instruction[] result = new Instruction[instructions.size()];
instructions.toArray(result);
return result;
}
public String toString() {
return toString(true);
}
/**
* @param verbose toggle output format
* @return String containing all instructions in this list.
*/
public String toString(boolean verbose) {
StringBuffer buf = new StringBuffer();
for(InstructionHandle ih=start; ih != null; ih = ih.next) {
buf.append(ih.toString(verbose) + "\n");
}
return buf.toString();
}
/**
* @return Enumeration that lists all instructions (handles)
*/
public Iterator iterator() {
return new Iterator() {
private InstructionHandle ih = start;
public Object next() {
InstructionHandle i = ih;
ih = ih.next;
return i;
}
public void remove() {
throw new UnsupportedOperationException();
}
public boolean hasNext() { return ih != null; }
};
}
/**
* @return array containing all instructions (handles)
*/
public InstructionHandle[] getInstructionHandles() {
InstructionHandle[] ihs = new InstructionHandle[length];
InstructionHandle ih = start;
for(int i=0; i < length; i++) {
ihs[i] = ih;
ih = ih.next;
}
return ihs;
}
/**
* Get positions (offsets) of all instructions in the list. This relies on that
* the list has been freshly created from an byte code array, or that setPositions()
* has been called. Otherwise this may be inaccurate.
*
* @return array containing all instruction's offset in byte code
*/
public int[] getInstructionPositions() { return byte_positions; }
/**
* @return complete, i.e., deep copy of this list
*/
public InstructionList copy() {
HashMap map = new HashMap();
InstructionList il = new InstructionList();
/* Pass 1: Make copies of all instructions, append them to the new list
* and associate old instruction references with the new ones, i.e.,
* a 1:1 mapping.
*/
for(InstructionHandle ih=start; ih != null; ih = ih.next) {
Instruction i = ih.instruction;
Instruction c = i.copy(); // Use clone for shallow copy
if(c instanceof BranchInstruction)
map.put(ih, il.append((BranchInstruction)c));
else
map.put(ih, il.append(c));
}
/* Pass 2: Update branch targets.
*/
InstructionHandle ih=start;
InstructionHandle ch=il.start;
while(ih != null) {
Instruction i = ih.instruction;
Instruction c = ch.instruction;
if(i instanceof BranchInstruction) {
BranchInstruction bi = (BranchInstruction)i;
BranchInstruction bc = (BranchInstruction)c;
InstructionHandle itarget = bi.getTarget(); // old target
// New target is in hash map
bc.setTarget((InstructionHandle)map.get(itarget));
if(bi instanceof Select) { // Either LOOKUPSWITCH or TABLESWITCH
InstructionHandle[] itargets = ((Select)bi).getTargets();
InstructionHandle[] ctargets = ((Select)bc).getTargets();
for(int j=0; j < itargets.length; j++) { // Update all targets
ctargets[j] = (InstructionHandle)map.get(itargets[j]);
}
}
}
ih = ih.next;
ch = ch.next;
}
return il;
}
/** Replace all references to the old constant pool with references to the new
* constant pool
*/
public void replaceConstantPool(ConstantPoolGen old_cp, ConstantPoolGen new_cp) {
for(InstructionHandle ih=start; ih != null; ih = ih.next) {
Instruction i = ih.instruction;
if(i instanceof CPInstruction) {
CPInstruction ci = (CPInstruction)i;
Constant c = old_cp.getConstant(ci.getIndex());
ci.setIndex(new_cp.addConstant(c, old_cp));
}
}
}
private void clear() {
start = end = null;
length = 0;
}
/**
* Delete contents of list. Provides besser memory utilization,
* because the system then may reuse the instruction handles. This
* method is typically called right after
* <href="MethodGen.html#getMethod()">MethodGen.getMethod()</a>.
*/
public void dispose() {
// Traverse in reverse order, because ih.next is overwritten
for(InstructionHandle ih=end; ih != null; ih = ih.prev)
/* Causes BranchInstructions to release target and targeters, because it
* calls dispose() on the contained instruction.
*/
ih.dispose();
clear();
}
/**
* @return start of list
*/
public InstructionHandle getStart() { return start; }
/**
* @return end of list
*/
public InstructionHandle getEnd() { return end; }
/**
* @return length of list (Number of instructions, not bytes)
*/
public int getLength() { return length; }
/**
* @return length of list (Number of instructions, not bytes)
*/
public int size() { return length; }
/**
* Redirect all references from old_target to new_target, i.e., update targets
* of branch instructions.
*
* @param old_target the old target instruction handle
* @param new_target the new target instruction handle
*/
public void redirectBranches(InstructionHandle old_target,
InstructionHandle new_target) {
for(InstructionHandle ih = start; ih != null; ih = ih.next) {
Instruction i = ih.getInstruction();
if(i instanceof BranchInstruction) {
BranchInstruction b = (BranchInstruction)i;
InstructionHandle target = b.getTarget();
if(target == old_target)
b.setTarget(new_target);
if(b instanceof Select) { // Either LOOKUPSWITCH or TABLESWITCH
InstructionHandle[] targets = ((Select)b).getTargets();
for(int j=0; j < targets.length; j++) // Update targets
if(targets[j] == old_target)
((Select)b).setTarget(j, new_target);
}
}
}
}
/**
* Redirect all references of local variables from old_target to new_target.
*
* @param lg array of local variables
* @param old_target the old target instruction handle
* @param new_target the new target instruction handle
* @see MethodGen
*/
public void redirectLocalVariables(LocalVariableGen[] lg,
InstructionHandle old_target,
InstructionHandle new_target) {
for(int i=0; i < lg.length; i++) {
InstructionHandle start = lg[i].getStart();
InstructionHandle end = lg[i].getEnd();
if(start == old_target)
lg[i].setStart(new_target);
if(end == old_target)
lg[i].setEnd(new_target);
}
}
/**
* Redirect all references of exception handlers from old_target to new_target.
*
* @param exceptions array of exception handlers
* @param old_target the old target instruction handle
* @param new_target the new target instruction handle
* @see MethodGen
*/
public void redirectExceptionHandlers(CodeExceptionGen[] exceptions,
InstructionHandle old_target,
InstructionHandle new_target) {
for(int i=0; i < exceptions.length; i++) {
if(exceptions[i].getStartPC() == old_target)
exceptions[i].setStartPC(new_target);
if(exceptions[i].getEndPC() == old_target)
exceptions[i].setEndPC(new_target);
if(exceptions[i].getHandlerPC() == old_target)
exceptions[i].setHandlerPC(new_target);
}
}
private ArrayList observers;
/** Add observer for this object.
*/
public void addObserver(InstructionListObserver o) {
if(observers == null)
observers = new ArrayList();
observers.add(o);
}
/** Remove observer for this object.
*/
public void removeObserver(InstructionListObserver o) {
if(observers != null)
observers.remove(o);
}
/** Call notify() method on all observers. This method is not called
* automatically whenever the state has changed, but has to be
* called by the user after he has finished editing the object.
*/
public void update() {
if(observers != null)
for(Iterator e = observers.iterator(); e.hasNext(); )
((InstructionListObserver)e.next()).notify(this);
}
}
|
138,384 |
Bug 138384 java.lang.ClassFormatError: Invalid method Code length 83071 in class file org/eclipse/jdt/internal/compiler/impl/Constant
| null |
resolved fixed
|
5d2b5b8
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-12T08:17:43Z | 2006-04-25T15:46:40Z |
tests/bugs152/pr138384/BigMethod.java
| |
138,384 |
Bug 138384 java.lang.ClassFormatError: Invalid method Code length 83071 in class file org/eclipse/jdt/internal/compiler/impl/Constant
| null |
resolved fixed
|
5d2b5b8
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-12T08:17:43Z | 2006-04-25T15:46:40Z |
tests/src/org/aspectj/systemtest/ajc152/Ajc152Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc152;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc152Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public void testNotAtWithincode_pr138158_1() { runTest("not at withincode - 1");}
public void testNotAtWithincode_pr138158_2() { runTest("not at withincode - 2");}
public void testNotAtWithincode_pr138158_3() { runTest("not at within - 3");}
// public void testComplexGenericDecl_pr137568() { runTest("complicated generics declaration");}
public void testNpeOnDup_pr138143() { runTest("npe on duplicate method with ataj");}
public void testPointcutsAndGenerics_pr137496_1() { runTest("pointcuts and generics - B");}
public void testPointcutsAndGenerics_pr137496_2() { runTest("pointcuts and generics - D");}
public void testPointcutsAndGenerics_pr137496_3() { runTest("pointcuts and generics - E");}
public void testPointcutsAndGenerics_pr137496_4() { runTest("pointcuts and generics - F");}
public void testPointcutsAndGenerics_pr137496_5() { runTest("pointcuts and generics - G");}
public void testPointcutsAndGenerics_pr137496_6() { runTest("pointcuts and generics - H");}
public void testAspectLibrariesAndASM_pr135001() { runTest("aspect libraries and asm");}
public void testStackOverflow_pr136258() { runTest("stack overflow");}
public void testIncorrectOverridesEvaluation13() { runTest("incorrect overrides evaluation - 1.3"); }
public void testIncorrectOverridesEvaluation15() { runTest("incorrect overrides evaluation - 1.5"); }
public void testAtWithinCodeBug_pr138798() { runTest("atWithinCodeBug"); }
// known failures, uncomment when working.
public void testReferencePCutInDeclareWarning_pr138215() { runTest("Reference pointcut fails inside @DeclareWarning");}
// public void testReferencePCutInPerClause_pr138219() { runTest("Can't use a FQ Reference pointcut in any pointcut expression referenced by a per-clause");}
// public void testDoubleAnnotationMatching_pr138223() { runTest("Double at annotation matching (no binding)");}
public void testSuperCallsInAtAspectJAdvice_pr139749() { runTest("Super calls in @AspectJ advice");}
public void testNoClassCastExceptionWithPerThis_pr138286() { runTest("No ClassCastException with perThis");}
// this next one reported as a bug by Rob Harrop, but I can't reproduce the failure yet...
//public void testAtAspectWithReferencePCPerClause_pr138220() { runTest("@Aspect with reference pointcut in perclause");}
public void testJarChecking_pr137235_1() { runTest("directory with .jar extension: source and outjar"); }
public void testJarChecking_pr137235_2() { runTest("directory with .jar extension"); }
public void testMakePreMethodNPE_pr136393() { runTest("NPE in makePreMethod");}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc152Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc152/ajc152.xml");
}
}
|
129,704 |
Bug 129704 BCException
|
org.aspectj.weaver.BCException at org.aspectj.weaver.bcel.BcelShadow.initializeKindedAnnotationVars(BcelShadow.java:1553) at org.aspectj.weaver.bcel.BcelShadow.getKindedAnnotationVar(BcelShadow.java:995) at org.aspectj.weaver.patterns.AnnotationPointcut.findResidueInternal(AnnotationPointcut.java:196) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:268) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:97) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:268) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:97) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:268) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:97) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:268) at org.aspectj.weaver.bcel.BcelAdvice.specializeOn(BcelAdvice.java:132) at org.aspectj.weaver.bcel.BcelShadow.prepareForMungers(BcelShadow.java:313) at org.aspectj.weaver.Shadow.implement(Shadow.java:404) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2146) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:467) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:102) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:811) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:230) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:156) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) trouble in: public class com.ytg.bilette.client.core.providers.DomainContentProvider extends java.lang.Object implements com.ytg.bilette.client.core.providers.IRefreshableStructuredContentProvider: private java.util.HashSet listeners [Signature(Ljava/util/HashSet<Lcom/ytg/bilette/client/core/providers/IDomainObjectChangeListener<TT;>;>;)] private com.ytg.bilette.client.core.providers.DomainContentProvider$State state [Signature(Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State;)] private Class clazz [Signature(Ljava/lang/Class<+Lcom/ytg/bilette/model/GenericDomainObject;>;)] private boolean deletable private java.util.List summaries [Signature(Ljava/util/List<TT;>;)] static Class class$0 public void <init>(Class) org.aspectj.weaver.MethodDeclarationLineNumber: 47:1136 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 47) İNVOKESPECİAL java.lang.Object.<init> ()V constructor-execution(void com.ytg.bilette.client.core.providers.DomainContentProvider.<init>(java.lang.Class)) | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 34) | NEW java.util.HashSet | DUP | İNVOKESPECİAL java.util.HashSet.<init> ()V | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.listeners Ljava/util/HashSet; | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 36) | GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.NOT_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 40) | İCONST_0 | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.deletable Z | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 48) | ALOAD_1 // java.lang.Class clazz | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.clazz Ljava/lang/Class; | ALOAD_1 // java.lang.Class clazz (line 50) | İNVOKEVİRTUAL java.lang.Class.getInterfaces ()[Ljava/lang/Class; | ASTORE_2 | İCONST_0 (line 51) | İSTORE_3 | GOTO L2 | L0: ALOAD_2 // java.lang.Class[] interfaces (line 52) | İLOAD_3 // int i | AALOAD | LDC com.ytg.bilette.model.Deletable | İNVOKEVİRTUAL java.lang.Object.equals (Ljava/lang/Object;)Z | İFEQ L1 | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 53) | İCONST_1 | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.deletable Z | GOTO L3 (line 54) | L1: İİNC 3 1 // int i (line 51) | L2: İLOAD_3 // int i | ALOAD_2 // java.lang.Class[] interfaces | ARRAYLENGTH | İF_İCMPLT L0 | L3: RETURN (line 57) constructor-execution(void com.ytg.bilette.client.core.providers.DomainContentProvider.<init>(java.lang.Class)) end public void <init>(Class) public Object[] getElements(Object) org.aspectj.weaver.MethodDeclarationLineNumber: 65:1611 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 66) ALOAD_1 // java.lang.Object input İNVOKESPECİAL com.ytg.bilette.client.core.providers.DomainContentProvider.checkInput (Ljava/lang/Object;)Z İSTORE_2 ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 68) İLOAD_2 // boolean includeDeleted İNVOKEVİRTUAL com.ytg.bilette.client.core.providers.DomainContentProvider.getSummaries (Z)Ljava/util/List; İNVOKEİNTERFACE java.util.List.toArray ()[Ljava/lang/Object; ARETURN end public Object[] getElements(Object) private void checkInitialized(boolean) org.aspectj.weaver.MethodDeclarationLineNumber: 71:1759 : GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.NOT_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; (line 72) ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; İNVOKEVİRTUAL com.ytg.bilette.client.core.providers.DomainContentProvider$State.equals (Ljava/lang/Object;)Z İFNE L0 GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.LIGHT_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; (line 73) ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; İNVOKEVİRTUAL com.ytg.bilette.client.core.providers.DomainContentProvider$State.equals (Ljava/lang/Object;)Z İFEQ L1 İLOAD_1 // boolean includeDeleted İFEQ L1 L0: ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 74) ACONST_NULL ACONST_NULL İLOAD_1 // boolean includeDeleted İNVOKESPECİAL com.ytg.bilette.client.core.providers.DomainContentProvider.getData (Lcom/ytg/bilette/dao/SummaryDAO;Lorg/eclipse/core/runtime/IProgressMonitor;Z)V L1: RETURN (line 75) end private void checkInitialized(boolean) private boolean checkInput(Object) org.aspectj.weaver.MethodDeclarationLineNumber: 83:2060 : ALOAD_1 // java.lang.Object input (line 84) İNSTANCEOF java.lang.Boolean LDC "Input for generic content provider must be Boolean value" (line 85) İNVOKESTATİC org.eclipse.jface.util.Assert.isTrue (ZLjava/lang/String;)Z (line 84) POP ALOAD_1 // java.lang.Object input (line 86) CHECKCAST java.lang.Boolean İNVOKEVİRTUAL java.lang.Boolean.booleanValue ()Z İSTORE_2 ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 87) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.deletable Z İFNE L1 ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 88) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.deletable Z İFNE L0 İLOAD_2 // boolean includeDeleted İFEQ L1 L0: İCONST_0 GOTO L2 L1: İCONST_1 L2: LDC "Nondeletable object yet deleted flag!" (line 89) İNVOKESTATİC org.eclipse.jface.util.Assert.isLegal (ZLjava/lang/String;)Z (line 87) POP İLOAD_2 // boolean includeDeleted (line 91) İRETURN end private boolean checkInput(Object) public void dispose() org.aspectj.weaver.MethodDeclarationLineNumber: 99:2522 : RETURN (line 101) end public void dispose() public void inputChanged(org.eclipse.jface.viewers.Viewer, Object, Object) org.aspectj.weaver.MethodDeclarationLineNumber: 109:2747 : RETURN (line 111) end public void inputChanged(org.eclipse.jface.viewers.Viewer, Object, Object) private void getData(com.ytg.bilette.dao.SummaryDAO, org.eclipse.core.runtime.IProgressMonitor, boolean) org.aspectj.weaver.MethodDeclarationLineNumber: 115:2954 : ALOAD_1 ASTORE 4 ALOAD_2 ASTORE 5 İLOAD_3 İSTORE 6 method-execution(void com.ytg.bilette.client.core.providers.DomainContentProvider.getData(com.ytg.bilette.dao.SummaryDAO, org.eclipse.core.runtime.IProgressMonitor, boolean)) | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 117) | ALOAD_1 // com.ytg.bilette.dao.SummaryDAO dao | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this | GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.clazz Ljava/lang/Class; | İLOAD_3 // boolean includeDeleted | İNVOKEİNTERFACE com.ytg.bilette.dao.SummaryDAO.getSummaries (Ljava/lang/Class;Z)Ljava/util/List; | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.summaries Ljava/util/List; | İLOAD_3 // boolean includeDeleted (line 118) | İFEQ L0 | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 119) | GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.FULL_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; | GOTO L1 | L0: ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 121) | GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.LIGHT_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; | L1: RETURN (line 122) method-execution(void com.ytg.bilette.client.core.providers.DomainContentProvider.getData(com.ytg.bilette.dao.SummaryDAO, org.eclipse.core.runtime.IProgressMonitor, boolean)) end private void getData(com.ytg.bilette.dao.SummaryDAO, org.eclipse.core.runtime.IProgressMonitor, boolean) public java.util.List getSummaries(boolean) org.aspectj.weaver.MethodDeclarationLineNumber: 128:3308 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 129) İLOAD_1 // boolean includeDeleted İNVOKESPECİAL com.ytg.bilette.client.core.providers.DomainContentProvider.checkInitialized (Z)V İLOAD_1 // boolean includeDeleted (line 131) İFNE L0 GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.LIGHT_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; İNVOKEVİRTUAL com.ytg.bilette.client.core.providers.DomainContentProvider$State.equals (Ljava/lang/Object;)Z İFEQ L1 L0: ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 132) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.summaries Ljava/util/List; ARETURN L1: ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 134) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.summaries Ljava/util/List; İNVOKEİNTERFACE java.util.List.iterator ()Ljava/util/Iterator; ASTORE_2 NEW java.util.ArrayList (line 135) DUP İNVOKESPECİAL java.util.ArrayList.<init> ()V ASTORE_3 GOTO L3 (line 136) L2: ALOAD_2 // java.util.Iterator i (line 137) İNVOKEİNTERFACE java.util.Iterator.next ()Ljava/lang/Object; CHECKCAST com.ytg.bilette.model.Deletable CHECKCAST com.ytg.bilette.model.Deletable ASTORE 4 ALOAD 4 // com.ytg.bilette.model.Deletable object (line 138) İNVOKEİNTERFACE com.ytg.bilette.model.Deletable.isDeleted ()Z İFNE L3 ALOAD_3 // java.util.ArrayList list (line 139) ALOAD 4 // com.ytg.bilette.model.Deletable object CHECKCAST com.ytg.bilette.model.GenericDomainObject İNVOKEVİRTUAL java.util.ArrayList.add (Ljava/lang/Object;)Z POP L3: ALOAD_2 // java.util.Iterator i (line 136) İNVOKEİNTERFACE java.util.Iterator.hasNext ()Z İFNE L2 ALOAD_3 // java.util.ArrayList list (line 142) ARETURN end public java.util.List getSummaries(boolean) public synchronized void refresh() org.aspectj.weaver.MethodDeclarationLineNumber: 148:3783 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 149) GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.NOT_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; İCONST_0 (line 150) İSTORE_1 ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 152) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.deletable Z İFEQ L2 ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 153) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.listeners Ljava/util/HashSet; İNVOKEVİRTUAL java.util.HashSet.iterator ()Ljava/util/Iterator; ASTORE_2 GOTO L1 (line 154) L0: ALOAD_2 // java.util.Iterator i (line 155) İNVOKEİNTERFACE java.util.Iterator.next ()Ljava/lang/Object; CHECKCAST com.ytg.bilette.client.core.providers.IDomainObjectChangeListener ASTORE_3 ALOAD_3 // com.ytg.bilette.client.core.providers.IDomainObjectChangeListener listener (line 156) İNVOKEİNTERFACE com.ytg.bilette.client.core.providers.IDomainObjectChangeListener.isIncludeDeleted ()Z İFEQ L1 İCONST_1 (line 157) İSTORE_1 // boolean includeDeleted GOTO L2 (line 158) L1: ALOAD_2 // java.util.Iterator i (line 154) İNVOKEİNTERFACE java.util.Iterator.hasNext ()Z İFNE L0 L2: ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 163) ACONST_NULL ACONST_NULL İLOAD_1 // boolean includeDeleted İNVOKESPECİAL com.ytg.bilette.client.core.providers.DomainContentProvider.getData (Lcom/ytg/bilette/dao/SummaryDAO;Lorg/eclipse/core/runtime/IProgressMonitor;Z)V ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 165) ACONST_NULL ACONST_NULL İNVOKESPECİAL com.ytg.bilette.client.core.providers.DomainContentProvider.notifyAllListeners (Lcom/ytg/bilette/model/GenericDomainObject;Lcom/ytg/bilette/model/GenericDomainObject;)V RETURN (line 166) end public synchronized void refresh() private synchronized void notifyAllListeners(com.ytg.bilette.model.GenericDomainObject, com.ytg.bilette.model.GenericDomainObject) org.aspectj.weaver.MethodDeclarationLineNumber: 174:4356 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 175) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.listeners Ljava/util/HashSet; İNVOKEVİRTUAL java.util.HashSet.iterator ()Ljava/util/Iterator; ASTORE_3 GOTO L2 (line 176) L0: ALOAD_3 // java.util.Iterator i (line 177) İNVOKEİNTERFACE java.util.Iterator.next ()Ljava/lang/Object; CHECKCAST com.ytg.bilette.client.core.providers.IDomainObjectChangeListener ASTORE 4 ALOAD_1 // com.ytg.bilette.model.GenericDomainObject oldObj (line 178) İFNONNULL L1 ALOAD_2 // com.ytg.bilette.model.GenericDomainObject newObj İFNONNULL L1 ALOAD 4 // com.ytg.bilette.client.core.providers.IDomainObjectChangeListener listener (line 179) İNVOKEİNTERFACE com.ytg.bilette.client.core.providers.IDomainObjectChangeListener.fullRefresh ()V GOTO L2 L1: ALOAD 4 // com.ytg.bilette.client.core.providers.IDomainObjectChangeListener listener (line 181) ALOAD_1 // com.ytg.bilette.model.GenericDomainObject oldObj ALOAD_2 // com.ytg.bilette.model.GenericDomainObject newObj İNVOKEİNTERFACE com.ytg.bilette.client.core.providers.IDomainObjectChangeListener.concessionChanged (Lcom/ytg/bilette/model/GenericDomainObject;Lcom/ytg/bilette/model/GenericDomainObject;)V L2: ALOAD_3 // java.util.Iterator i (line 176) İNVOKEİNTERFACE java.util.Iterator.hasNext ()Z İFNE L0 RETURN (line 183) end private synchronized void notifyAllListeners(com.ytg.bilette.model.GenericDomainObject, com.ytg.bilette.model.GenericDomainObject) public synchronized void addListener(com.ytg.bilette.client.core.providers.IDomainObjectChangeListener) org.aspectj.weaver.MethodDeclarationLineNumber: 185:4715 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 186) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.listeners Ljava/util/HashSet; ALOAD_1 // com.ytg.bilette.client.core.providers.IDomainObjectChangeListener listener İNVOKEVİRTUAL java.util.HashSet.add (Ljava/lang/Object;)Z POP RETURN (line 187) end public synchronized void addListener(com.ytg.bilette.client.core.providers.IDomainObjectChangeListener) public synchronized void removeListener(com.ytg.bilette.client.core.providers.IDomainObjectChangeListener) org.aspectj.weaver.MethodDeclarationLineNumber: 189:4831 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 190) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.listeners Ljava/util/HashSet; ALOAD_1 // com.ytg.bilette.client.core.providers.IDomainObjectChangeListener listener İNVOKEVİRTUAL java.util.HashSet.remove (Ljava/lang/Object;)Z POP RETURN (line 191) end public synchronized void removeListener(com.ytg.bilette.client.core.providers.IDomainObjectChangeListener) end public class com.ytg.bilette.client.core.providers.DomainContentProvider when implementing on shadow method-execution(void com.ytg.bilette.client.core.providers.DomainContentProvider.getData(com.ytg.bilette.dao.SummaryDAO, org.eclipse.core.runtime.IProgressMonitor, boolean)) when weaving type com.ytg.bilette.client.core.providers.DomainContentProvider when weaving classes when weaving when batch building BuildConfig[F:\java\Bilette\.metadata\.plugins\org.eclipse.ajdt.core\com.ytg.bilette.client.core.generated.lst] #Files=22
|
resolved fixed
|
3ca976f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-12T10:41:42Z | 2006-02-28T01:26:40Z |
tests/bugs152/pr129704/A.java
| |
129,704 |
Bug 129704 BCException
|
org.aspectj.weaver.BCException at org.aspectj.weaver.bcel.BcelShadow.initializeKindedAnnotationVars(BcelShadow.java:1553) at org.aspectj.weaver.bcel.BcelShadow.getKindedAnnotationVar(BcelShadow.java:995) at org.aspectj.weaver.patterns.AnnotationPointcut.findResidueInternal(AnnotationPointcut.java:196) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:268) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:97) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:268) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:97) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:268) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:97) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:268) at org.aspectj.weaver.bcel.BcelAdvice.specializeOn(BcelAdvice.java:132) at org.aspectj.weaver.bcel.BcelShadow.prepareForMungers(BcelShadow.java:313) at org.aspectj.weaver.Shadow.implement(Shadow.java:404) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2146) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:467) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:102) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:811) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:230) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:156) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) trouble in: public class com.ytg.bilette.client.core.providers.DomainContentProvider extends java.lang.Object implements com.ytg.bilette.client.core.providers.IRefreshableStructuredContentProvider: private java.util.HashSet listeners [Signature(Ljava/util/HashSet<Lcom/ytg/bilette/client/core/providers/IDomainObjectChangeListener<TT;>;>;)] private com.ytg.bilette.client.core.providers.DomainContentProvider$State state [Signature(Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State;)] private Class clazz [Signature(Ljava/lang/Class<+Lcom/ytg/bilette/model/GenericDomainObject;>;)] private boolean deletable private java.util.List summaries [Signature(Ljava/util/List<TT;>;)] static Class class$0 public void <init>(Class) org.aspectj.weaver.MethodDeclarationLineNumber: 47:1136 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 47) İNVOKESPECİAL java.lang.Object.<init> ()V constructor-execution(void com.ytg.bilette.client.core.providers.DomainContentProvider.<init>(java.lang.Class)) | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 34) | NEW java.util.HashSet | DUP | İNVOKESPECİAL java.util.HashSet.<init> ()V | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.listeners Ljava/util/HashSet; | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 36) | GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.NOT_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 40) | İCONST_0 | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.deletable Z | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 48) | ALOAD_1 // java.lang.Class clazz | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.clazz Ljava/lang/Class; | ALOAD_1 // java.lang.Class clazz (line 50) | İNVOKEVİRTUAL java.lang.Class.getInterfaces ()[Ljava/lang/Class; | ASTORE_2 | İCONST_0 (line 51) | İSTORE_3 | GOTO L2 | L0: ALOAD_2 // java.lang.Class[] interfaces (line 52) | İLOAD_3 // int i | AALOAD | LDC com.ytg.bilette.model.Deletable | İNVOKEVİRTUAL java.lang.Object.equals (Ljava/lang/Object;)Z | İFEQ L1 | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 53) | İCONST_1 | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.deletable Z | GOTO L3 (line 54) | L1: İİNC 3 1 // int i (line 51) | L2: İLOAD_3 // int i | ALOAD_2 // java.lang.Class[] interfaces | ARRAYLENGTH | İF_İCMPLT L0 | L3: RETURN (line 57) constructor-execution(void com.ytg.bilette.client.core.providers.DomainContentProvider.<init>(java.lang.Class)) end public void <init>(Class) public Object[] getElements(Object) org.aspectj.weaver.MethodDeclarationLineNumber: 65:1611 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 66) ALOAD_1 // java.lang.Object input İNVOKESPECİAL com.ytg.bilette.client.core.providers.DomainContentProvider.checkInput (Ljava/lang/Object;)Z İSTORE_2 ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 68) İLOAD_2 // boolean includeDeleted İNVOKEVİRTUAL com.ytg.bilette.client.core.providers.DomainContentProvider.getSummaries (Z)Ljava/util/List; İNVOKEİNTERFACE java.util.List.toArray ()[Ljava/lang/Object; ARETURN end public Object[] getElements(Object) private void checkInitialized(boolean) org.aspectj.weaver.MethodDeclarationLineNumber: 71:1759 : GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.NOT_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; (line 72) ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; İNVOKEVİRTUAL com.ytg.bilette.client.core.providers.DomainContentProvider$State.equals (Ljava/lang/Object;)Z İFNE L0 GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.LIGHT_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; (line 73) ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; İNVOKEVİRTUAL com.ytg.bilette.client.core.providers.DomainContentProvider$State.equals (Ljava/lang/Object;)Z İFEQ L1 İLOAD_1 // boolean includeDeleted İFEQ L1 L0: ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 74) ACONST_NULL ACONST_NULL İLOAD_1 // boolean includeDeleted İNVOKESPECİAL com.ytg.bilette.client.core.providers.DomainContentProvider.getData (Lcom/ytg/bilette/dao/SummaryDAO;Lorg/eclipse/core/runtime/IProgressMonitor;Z)V L1: RETURN (line 75) end private void checkInitialized(boolean) private boolean checkInput(Object) org.aspectj.weaver.MethodDeclarationLineNumber: 83:2060 : ALOAD_1 // java.lang.Object input (line 84) İNSTANCEOF java.lang.Boolean LDC "Input for generic content provider must be Boolean value" (line 85) İNVOKESTATİC org.eclipse.jface.util.Assert.isTrue (ZLjava/lang/String;)Z (line 84) POP ALOAD_1 // java.lang.Object input (line 86) CHECKCAST java.lang.Boolean İNVOKEVİRTUAL java.lang.Boolean.booleanValue ()Z İSTORE_2 ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 87) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.deletable Z İFNE L1 ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 88) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.deletable Z İFNE L0 İLOAD_2 // boolean includeDeleted İFEQ L1 L0: İCONST_0 GOTO L2 L1: İCONST_1 L2: LDC "Nondeletable object yet deleted flag!" (line 89) İNVOKESTATİC org.eclipse.jface.util.Assert.isLegal (ZLjava/lang/String;)Z (line 87) POP İLOAD_2 // boolean includeDeleted (line 91) İRETURN end private boolean checkInput(Object) public void dispose() org.aspectj.weaver.MethodDeclarationLineNumber: 99:2522 : RETURN (line 101) end public void dispose() public void inputChanged(org.eclipse.jface.viewers.Viewer, Object, Object) org.aspectj.weaver.MethodDeclarationLineNumber: 109:2747 : RETURN (line 111) end public void inputChanged(org.eclipse.jface.viewers.Viewer, Object, Object) private void getData(com.ytg.bilette.dao.SummaryDAO, org.eclipse.core.runtime.IProgressMonitor, boolean) org.aspectj.weaver.MethodDeclarationLineNumber: 115:2954 : ALOAD_1 ASTORE 4 ALOAD_2 ASTORE 5 İLOAD_3 İSTORE 6 method-execution(void com.ytg.bilette.client.core.providers.DomainContentProvider.getData(com.ytg.bilette.dao.SummaryDAO, org.eclipse.core.runtime.IProgressMonitor, boolean)) | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 117) | ALOAD_1 // com.ytg.bilette.dao.SummaryDAO dao | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this | GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.clazz Ljava/lang/Class; | İLOAD_3 // boolean includeDeleted | İNVOKEİNTERFACE com.ytg.bilette.dao.SummaryDAO.getSummaries (Ljava/lang/Class;Z)Ljava/util/List; | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.summaries Ljava/util/List; | İLOAD_3 // boolean includeDeleted (line 118) | İFEQ L0 | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 119) | GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.FULL_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; | GOTO L1 | L0: ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 121) | GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.LIGHT_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; | L1: RETURN (line 122) method-execution(void com.ytg.bilette.client.core.providers.DomainContentProvider.getData(com.ytg.bilette.dao.SummaryDAO, org.eclipse.core.runtime.IProgressMonitor, boolean)) end private void getData(com.ytg.bilette.dao.SummaryDAO, org.eclipse.core.runtime.IProgressMonitor, boolean) public java.util.List getSummaries(boolean) org.aspectj.weaver.MethodDeclarationLineNumber: 128:3308 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 129) İLOAD_1 // boolean includeDeleted İNVOKESPECİAL com.ytg.bilette.client.core.providers.DomainContentProvider.checkInitialized (Z)V İLOAD_1 // boolean includeDeleted (line 131) İFNE L0 GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.LIGHT_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; İNVOKEVİRTUAL com.ytg.bilette.client.core.providers.DomainContentProvider$State.equals (Ljava/lang/Object;)Z İFEQ L1 L0: ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 132) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.summaries Ljava/util/List; ARETURN L1: ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 134) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.summaries Ljava/util/List; İNVOKEİNTERFACE java.util.List.iterator ()Ljava/util/Iterator; ASTORE_2 NEW java.util.ArrayList (line 135) DUP İNVOKESPECİAL java.util.ArrayList.<init> ()V ASTORE_3 GOTO L3 (line 136) L2: ALOAD_2 // java.util.Iterator i (line 137) İNVOKEİNTERFACE java.util.Iterator.next ()Ljava/lang/Object; CHECKCAST com.ytg.bilette.model.Deletable CHECKCAST com.ytg.bilette.model.Deletable ASTORE 4 ALOAD 4 // com.ytg.bilette.model.Deletable object (line 138) İNVOKEİNTERFACE com.ytg.bilette.model.Deletable.isDeleted ()Z İFNE L3 ALOAD_3 // java.util.ArrayList list (line 139) ALOAD 4 // com.ytg.bilette.model.Deletable object CHECKCAST com.ytg.bilette.model.GenericDomainObject İNVOKEVİRTUAL java.util.ArrayList.add (Ljava/lang/Object;)Z POP L3: ALOAD_2 // java.util.Iterator i (line 136) İNVOKEİNTERFACE java.util.Iterator.hasNext ()Z İFNE L2 ALOAD_3 // java.util.ArrayList list (line 142) ARETURN end public java.util.List getSummaries(boolean) public synchronized void refresh() org.aspectj.weaver.MethodDeclarationLineNumber: 148:3783 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 149) GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.NOT_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; İCONST_0 (line 150) İSTORE_1 ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 152) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.deletable Z İFEQ L2 ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 153) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.listeners Ljava/util/HashSet; İNVOKEVİRTUAL java.util.HashSet.iterator ()Ljava/util/Iterator; ASTORE_2 GOTO L1 (line 154) L0: ALOAD_2 // java.util.Iterator i (line 155) İNVOKEİNTERFACE java.util.Iterator.next ()Ljava/lang/Object; CHECKCAST com.ytg.bilette.client.core.providers.IDomainObjectChangeListener ASTORE_3 ALOAD_3 // com.ytg.bilette.client.core.providers.IDomainObjectChangeListener listener (line 156) İNVOKEİNTERFACE com.ytg.bilette.client.core.providers.IDomainObjectChangeListener.isIncludeDeleted ()Z İFEQ L1 İCONST_1 (line 157) İSTORE_1 // boolean includeDeleted GOTO L2 (line 158) L1: ALOAD_2 // java.util.Iterator i (line 154) İNVOKEİNTERFACE java.util.Iterator.hasNext ()Z İFNE L0 L2: ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 163) ACONST_NULL ACONST_NULL İLOAD_1 // boolean includeDeleted İNVOKESPECİAL com.ytg.bilette.client.core.providers.DomainContentProvider.getData (Lcom/ytg/bilette/dao/SummaryDAO;Lorg/eclipse/core/runtime/IProgressMonitor;Z)V ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 165) ACONST_NULL ACONST_NULL İNVOKESPECİAL com.ytg.bilette.client.core.providers.DomainContentProvider.notifyAllListeners (Lcom/ytg/bilette/model/GenericDomainObject;Lcom/ytg/bilette/model/GenericDomainObject;)V RETURN (line 166) end public synchronized void refresh() private synchronized void notifyAllListeners(com.ytg.bilette.model.GenericDomainObject, com.ytg.bilette.model.GenericDomainObject) org.aspectj.weaver.MethodDeclarationLineNumber: 174:4356 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 175) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.listeners Ljava/util/HashSet; İNVOKEVİRTUAL java.util.HashSet.iterator ()Ljava/util/Iterator; ASTORE_3 GOTO L2 (line 176) L0: ALOAD_3 // java.util.Iterator i (line 177) İNVOKEİNTERFACE java.util.Iterator.next ()Ljava/lang/Object; CHECKCAST com.ytg.bilette.client.core.providers.IDomainObjectChangeListener ASTORE 4 ALOAD_1 // com.ytg.bilette.model.GenericDomainObject oldObj (line 178) İFNONNULL L1 ALOAD_2 // com.ytg.bilette.model.GenericDomainObject newObj İFNONNULL L1 ALOAD 4 // com.ytg.bilette.client.core.providers.IDomainObjectChangeListener listener (line 179) İNVOKEİNTERFACE com.ytg.bilette.client.core.providers.IDomainObjectChangeListener.fullRefresh ()V GOTO L2 L1: ALOAD 4 // com.ytg.bilette.client.core.providers.IDomainObjectChangeListener listener (line 181) ALOAD_1 // com.ytg.bilette.model.GenericDomainObject oldObj ALOAD_2 // com.ytg.bilette.model.GenericDomainObject newObj İNVOKEİNTERFACE com.ytg.bilette.client.core.providers.IDomainObjectChangeListener.concessionChanged (Lcom/ytg/bilette/model/GenericDomainObject;Lcom/ytg/bilette/model/GenericDomainObject;)V L2: ALOAD_3 // java.util.Iterator i (line 176) İNVOKEİNTERFACE java.util.Iterator.hasNext ()Z İFNE L0 RETURN (line 183) end private synchronized void notifyAllListeners(com.ytg.bilette.model.GenericDomainObject, com.ytg.bilette.model.GenericDomainObject) public synchronized void addListener(com.ytg.bilette.client.core.providers.IDomainObjectChangeListener) org.aspectj.weaver.MethodDeclarationLineNumber: 185:4715 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 186) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.listeners Ljava/util/HashSet; ALOAD_1 // com.ytg.bilette.client.core.providers.IDomainObjectChangeListener listener İNVOKEVİRTUAL java.util.HashSet.add (Ljava/lang/Object;)Z POP RETURN (line 187) end public synchronized void addListener(com.ytg.bilette.client.core.providers.IDomainObjectChangeListener) public synchronized void removeListener(com.ytg.bilette.client.core.providers.IDomainObjectChangeListener) org.aspectj.weaver.MethodDeclarationLineNumber: 189:4831 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 190) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.listeners Ljava/util/HashSet; ALOAD_1 // com.ytg.bilette.client.core.providers.IDomainObjectChangeListener listener İNVOKEVİRTUAL java.util.HashSet.remove (Ljava/lang/Object;)Z POP RETURN (line 191) end public synchronized void removeListener(com.ytg.bilette.client.core.providers.IDomainObjectChangeListener) end public class com.ytg.bilette.client.core.providers.DomainContentProvider when implementing on shadow method-execution(void com.ytg.bilette.client.core.providers.DomainContentProvider.getData(com.ytg.bilette.dao.SummaryDAO, org.eclipse.core.runtime.IProgressMonitor, boolean)) when weaving type com.ytg.bilette.client.core.providers.DomainContentProvider when weaving classes when weaving when batch building BuildConfig[F:\java\Bilette\.metadata\.plugins\org.eclipse.ajdt.core\com.ytg.bilette.client.core.generated.lst] #Files=22
|
resolved fixed
|
3ca976f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-12T10:41:42Z | 2006-02-28T01:26:40Z |
tests/src/org/aspectj/systemtest/ajc152/Ajc152Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc152;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc152Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public void testMethodTooBigAfterWeaving_pr138384() { runTest("method too big"); }
public void testNotAtWithincode_pr138158_1() { runTest("not at withincode - 1");}
public void testNotAtWithincode_pr138158_2() { runTest("not at withincode - 2");}
public void testNotAtWithincode_pr138158_3() { runTest("not at within - 3");}
// public void testComplexGenericDecl_pr137568() { runTest("complicated generics declaration");}
public void testNpeOnDup_pr138143() { runTest("npe on duplicate method with ataj");}
public void testPointcutsAndGenerics_pr137496_1() { runTest("pointcuts and generics - B");}
public void testPointcutsAndGenerics_pr137496_2() { runTest("pointcuts and generics - D");}
public void testPointcutsAndGenerics_pr137496_3() { runTest("pointcuts and generics - E");}
public void testPointcutsAndGenerics_pr137496_4() { runTest("pointcuts and generics - F");}
public void testPointcutsAndGenerics_pr137496_5() { runTest("pointcuts and generics - G");}
public void testPointcutsAndGenerics_pr137496_6() { runTest("pointcuts and generics - H");}
public void testAspectLibrariesAndASM_pr135001() { runTest("aspect libraries and asm");}
public void testStackOverflow_pr136258() { runTest("stack overflow");}
public void testIncorrectOverridesEvaluation13() { runTest("incorrect overrides evaluation - 1.3"); }
public void testIncorrectOverridesEvaluation15() { runTest("incorrect overrides evaluation - 1.5"); }
public void testAtWithinCodeBug_pr138798() { runTest("atWithinCodeBug"); }
// known failures, uncomment when working.
public void testReferencePCutInDeclareWarning_pr138215() { runTest("Reference pointcut fails inside @DeclareWarning");}
// public void testReferencePCutInPerClause_pr138219() { runTest("Can't use a FQ Reference pointcut in any pointcut expression referenced by a per-clause");}
// public void testDoubleAnnotationMatching_pr138223() { runTest("Double at annotation matching (no binding)");}
public void testSuperCallsInAtAspectJAdvice_pr139749() { runTest("Super calls in @AspectJ advice");}
public void testNoClassCastExceptionWithPerThis_pr138286() { runTest("No ClassCastException with perThis");}
// this next one reported as a bug by Rob Harrop, but I can't reproduce the failure yet...
//public void testAtAspectWithReferencePCPerClause_pr138220() { runTest("@Aspect with reference pointcut in perclause");}
public void testJarChecking_pr137235_1() { runTest("directory with .jar extension: source and outjar"); }
public void testJarChecking_pr137235_2() { runTest("directory with .jar extension"); }
public void testMakePreMethodNPE_pr136393() { runTest("NPE in makePreMethod");}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc152Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc152/ajc152.xml");
}
}
|
129,704 |
Bug 129704 BCException
|
org.aspectj.weaver.BCException at org.aspectj.weaver.bcel.BcelShadow.initializeKindedAnnotationVars(BcelShadow.java:1553) at org.aspectj.weaver.bcel.BcelShadow.getKindedAnnotationVar(BcelShadow.java:995) at org.aspectj.weaver.patterns.AnnotationPointcut.findResidueInternal(AnnotationPointcut.java:196) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:268) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:97) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:268) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:97) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:268) at org.aspectj.weaver.patterns.AndPointcut.findResidueInternal(AndPointcut.java:97) at org.aspectj.weaver.patterns.Pointcut.findResidue(Pointcut.java:268) at org.aspectj.weaver.bcel.BcelAdvice.specializeOn(BcelAdvice.java:132) at org.aspectj.weaver.bcel.BcelShadow.prepareForMungers(BcelShadow.java:313) at org.aspectj.weaver.Shadow.implement(Shadow.java:404) at org.aspectj.weaver.bcel.BcelClassWeaver.implement(BcelClassWeaver.java:2146) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:467) at org.aspectj.weaver.bcel.BcelClassWeaver.weave(BcelClassWeaver.java:102) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1543) at org.aspectj.weaver.bcel.BcelWeaver.weaveWithoutDump(BcelWeaver.java:1494) at org.aspectj.weaver.bcel.BcelWeaver.weaveAndNotify(BcelWeaver.java:1275) at org.aspectj.weaver.bcel.BcelWeaver.weave(BcelWeaver.java:1097) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.weave(AjCompilerAdapter.java:300) at org.aspectj.ajdt.internal.compiler.AjCompilerAdapter.afterCompiling(AjCompilerAdapter.java:178) at org.aspectj.ajdt.internal.compiler.CompilerAdapter.ajc$afterReturning$org_aspectj_ajdt_internal_compiler_CompilerAdapter$2$f9cc9ca0(CompilerAdapter.aj:70) at org.aspectj.org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:367) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.performCompilation(AjBuildManager.java:811) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.doBuild(AjBuildManager.java:230) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild(AjBuildManager.java:156) at org.aspectj.ajde.internal.CompilerAdapter.compile(CompilerAdapter.java:122) at org.aspectj.ajde.internal.AspectJBuildManager$CompilerThread.run(AspectJBuildManager.java:191) trouble in: public class com.ytg.bilette.client.core.providers.DomainContentProvider extends java.lang.Object implements com.ytg.bilette.client.core.providers.IRefreshableStructuredContentProvider: private java.util.HashSet listeners [Signature(Ljava/util/HashSet<Lcom/ytg/bilette/client/core/providers/IDomainObjectChangeListener<TT;>;>;)] private com.ytg.bilette.client.core.providers.DomainContentProvider$State state [Signature(Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State;)] private Class clazz [Signature(Ljava/lang/Class<+Lcom/ytg/bilette/model/GenericDomainObject;>;)] private boolean deletable private java.util.List summaries [Signature(Ljava/util/List<TT;>;)] static Class class$0 public void <init>(Class) org.aspectj.weaver.MethodDeclarationLineNumber: 47:1136 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 47) İNVOKESPECİAL java.lang.Object.<init> ()V constructor-execution(void com.ytg.bilette.client.core.providers.DomainContentProvider.<init>(java.lang.Class)) | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 34) | NEW java.util.HashSet | DUP | İNVOKESPECİAL java.util.HashSet.<init> ()V | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.listeners Ljava/util/HashSet; | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 36) | GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.NOT_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 40) | İCONST_0 | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.deletable Z | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 48) | ALOAD_1 // java.lang.Class clazz | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.clazz Ljava/lang/Class; | ALOAD_1 // java.lang.Class clazz (line 50) | İNVOKEVİRTUAL java.lang.Class.getInterfaces ()[Ljava/lang/Class; | ASTORE_2 | İCONST_0 (line 51) | İSTORE_3 | GOTO L2 | L0: ALOAD_2 // java.lang.Class[] interfaces (line 52) | İLOAD_3 // int i | AALOAD | LDC com.ytg.bilette.model.Deletable | İNVOKEVİRTUAL java.lang.Object.equals (Ljava/lang/Object;)Z | İFEQ L1 | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 53) | İCONST_1 | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.deletable Z | GOTO L3 (line 54) | L1: İİNC 3 1 // int i (line 51) | L2: İLOAD_3 // int i | ALOAD_2 // java.lang.Class[] interfaces | ARRAYLENGTH | İF_İCMPLT L0 | L3: RETURN (line 57) constructor-execution(void com.ytg.bilette.client.core.providers.DomainContentProvider.<init>(java.lang.Class)) end public void <init>(Class) public Object[] getElements(Object) org.aspectj.weaver.MethodDeclarationLineNumber: 65:1611 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 66) ALOAD_1 // java.lang.Object input İNVOKESPECİAL com.ytg.bilette.client.core.providers.DomainContentProvider.checkInput (Ljava/lang/Object;)Z İSTORE_2 ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 68) İLOAD_2 // boolean includeDeleted İNVOKEVİRTUAL com.ytg.bilette.client.core.providers.DomainContentProvider.getSummaries (Z)Ljava/util/List; İNVOKEİNTERFACE java.util.List.toArray ()[Ljava/lang/Object; ARETURN end public Object[] getElements(Object) private void checkInitialized(boolean) org.aspectj.weaver.MethodDeclarationLineNumber: 71:1759 : GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.NOT_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; (line 72) ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; İNVOKEVİRTUAL com.ytg.bilette.client.core.providers.DomainContentProvider$State.equals (Ljava/lang/Object;)Z İFNE L0 GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.LIGHT_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; (line 73) ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; İNVOKEVİRTUAL com.ytg.bilette.client.core.providers.DomainContentProvider$State.equals (Ljava/lang/Object;)Z İFEQ L1 İLOAD_1 // boolean includeDeleted İFEQ L1 L0: ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 74) ACONST_NULL ACONST_NULL İLOAD_1 // boolean includeDeleted İNVOKESPECİAL com.ytg.bilette.client.core.providers.DomainContentProvider.getData (Lcom/ytg/bilette/dao/SummaryDAO;Lorg/eclipse/core/runtime/IProgressMonitor;Z)V L1: RETURN (line 75) end private void checkInitialized(boolean) private boolean checkInput(Object) org.aspectj.weaver.MethodDeclarationLineNumber: 83:2060 : ALOAD_1 // java.lang.Object input (line 84) İNSTANCEOF java.lang.Boolean LDC "Input for generic content provider must be Boolean value" (line 85) İNVOKESTATİC org.eclipse.jface.util.Assert.isTrue (ZLjava/lang/String;)Z (line 84) POP ALOAD_1 // java.lang.Object input (line 86) CHECKCAST java.lang.Boolean İNVOKEVİRTUAL java.lang.Boolean.booleanValue ()Z İSTORE_2 ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 87) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.deletable Z İFNE L1 ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 88) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.deletable Z İFNE L0 İLOAD_2 // boolean includeDeleted İFEQ L1 L0: İCONST_0 GOTO L2 L1: İCONST_1 L2: LDC "Nondeletable object yet deleted flag!" (line 89) İNVOKESTATİC org.eclipse.jface.util.Assert.isLegal (ZLjava/lang/String;)Z (line 87) POP İLOAD_2 // boolean includeDeleted (line 91) İRETURN end private boolean checkInput(Object) public void dispose() org.aspectj.weaver.MethodDeclarationLineNumber: 99:2522 : RETURN (line 101) end public void dispose() public void inputChanged(org.eclipse.jface.viewers.Viewer, Object, Object) org.aspectj.weaver.MethodDeclarationLineNumber: 109:2747 : RETURN (line 111) end public void inputChanged(org.eclipse.jface.viewers.Viewer, Object, Object) private void getData(com.ytg.bilette.dao.SummaryDAO, org.eclipse.core.runtime.IProgressMonitor, boolean) org.aspectj.weaver.MethodDeclarationLineNumber: 115:2954 : ALOAD_1 ASTORE 4 ALOAD_2 ASTORE 5 İLOAD_3 İSTORE 6 method-execution(void com.ytg.bilette.client.core.providers.DomainContentProvider.getData(com.ytg.bilette.dao.SummaryDAO, org.eclipse.core.runtime.IProgressMonitor, boolean)) | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 117) | ALOAD_1 // com.ytg.bilette.dao.SummaryDAO dao | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this | GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.clazz Ljava/lang/Class; | İLOAD_3 // boolean includeDeleted | İNVOKEİNTERFACE com.ytg.bilette.dao.SummaryDAO.getSummaries (Ljava/lang/Class;Z)Ljava/util/List; | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.summaries Ljava/util/List; | İLOAD_3 // boolean includeDeleted (line 118) | İFEQ L0 | ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 119) | GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.FULL_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; | GOTO L1 | L0: ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 121) | GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.LIGHT_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; | PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; | L1: RETURN (line 122) method-execution(void com.ytg.bilette.client.core.providers.DomainContentProvider.getData(com.ytg.bilette.dao.SummaryDAO, org.eclipse.core.runtime.IProgressMonitor, boolean)) end private void getData(com.ytg.bilette.dao.SummaryDAO, org.eclipse.core.runtime.IProgressMonitor, boolean) public java.util.List getSummaries(boolean) org.aspectj.weaver.MethodDeclarationLineNumber: 128:3308 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 129) İLOAD_1 // boolean includeDeleted İNVOKESPECİAL com.ytg.bilette.client.core.providers.DomainContentProvider.checkInitialized (Z)V İLOAD_1 // boolean includeDeleted (line 131) İFNE L0 GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.LIGHT_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; İNVOKEVİRTUAL com.ytg.bilette.client.core.providers.DomainContentProvider$State.equals (Ljava/lang/Object;)Z İFEQ L1 L0: ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 132) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.summaries Ljava/util/List; ARETURN L1: ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 134) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.summaries Ljava/util/List; İNVOKEİNTERFACE java.util.List.iterator ()Ljava/util/Iterator; ASTORE_2 NEW java.util.ArrayList (line 135) DUP İNVOKESPECİAL java.util.ArrayList.<init> ()V ASTORE_3 GOTO L3 (line 136) L2: ALOAD_2 // java.util.Iterator i (line 137) İNVOKEİNTERFACE java.util.Iterator.next ()Ljava/lang/Object; CHECKCAST com.ytg.bilette.model.Deletable CHECKCAST com.ytg.bilette.model.Deletable ASTORE 4 ALOAD 4 // com.ytg.bilette.model.Deletable object (line 138) İNVOKEİNTERFACE com.ytg.bilette.model.Deletable.isDeleted ()Z İFNE L3 ALOAD_3 // java.util.ArrayList list (line 139) ALOAD 4 // com.ytg.bilette.model.Deletable object CHECKCAST com.ytg.bilette.model.GenericDomainObject İNVOKEVİRTUAL java.util.ArrayList.add (Ljava/lang/Object;)Z POP L3: ALOAD_2 // java.util.Iterator i (line 136) İNVOKEİNTERFACE java.util.Iterator.hasNext ()Z İFNE L2 ALOAD_3 // java.util.ArrayList list (line 142) ARETURN end public java.util.List getSummaries(boolean) public synchronized void refresh() org.aspectj.weaver.MethodDeclarationLineNumber: 148:3783 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 149) GETSTATİC com.ytg.bilette.client.core.providers.DomainContentProvider$State.NOT_INITIALIZED Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; PUTFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.state Lcom/ytg/bilette/client/core/providers/DomainContentProvider$State; İCONST_0 (line 150) İSTORE_1 ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 152) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.deletable Z İFEQ L2 ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 153) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.listeners Ljava/util/HashSet; İNVOKEVİRTUAL java.util.HashSet.iterator ()Ljava/util/Iterator; ASTORE_2 GOTO L1 (line 154) L0: ALOAD_2 // java.util.Iterator i (line 155) İNVOKEİNTERFACE java.util.Iterator.next ()Ljava/lang/Object; CHECKCAST com.ytg.bilette.client.core.providers.IDomainObjectChangeListener ASTORE_3 ALOAD_3 // com.ytg.bilette.client.core.providers.IDomainObjectChangeListener listener (line 156) İNVOKEİNTERFACE com.ytg.bilette.client.core.providers.IDomainObjectChangeListener.isIncludeDeleted ()Z İFEQ L1 İCONST_1 (line 157) İSTORE_1 // boolean includeDeleted GOTO L2 (line 158) L1: ALOAD_2 // java.util.Iterator i (line 154) İNVOKEİNTERFACE java.util.Iterator.hasNext ()Z İFNE L0 L2: ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 163) ACONST_NULL ACONST_NULL İLOAD_1 // boolean includeDeleted İNVOKESPECİAL com.ytg.bilette.client.core.providers.DomainContentProvider.getData (Lcom/ytg/bilette/dao/SummaryDAO;Lorg/eclipse/core/runtime/IProgressMonitor;Z)V ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 165) ACONST_NULL ACONST_NULL İNVOKESPECİAL com.ytg.bilette.client.core.providers.DomainContentProvider.notifyAllListeners (Lcom/ytg/bilette/model/GenericDomainObject;Lcom/ytg/bilette/model/GenericDomainObject;)V RETURN (line 166) end public synchronized void refresh() private synchronized void notifyAllListeners(com.ytg.bilette.model.GenericDomainObject, com.ytg.bilette.model.GenericDomainObject) org.aspectj.weaver.MethodDeclarationLineNumber: 174:4356 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 175) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.listeners Ljava/util/HashSet; İNVOKEVİRTUAL java.util.HashSet.iterator ()Ljava/util/Iterator; ASTORE_3 GOTO L2 (line 176) L0: ALOAD_3 // java.util.Iterator i (line 177) İNVOKEİNTERFACE java.util.Iterator.next ()Ljava/lang/Object; CHECKCAST com.ytg.bilette.client.core.providers.IDomainObjectChangeListener ASTORE 4 ALOAD_1 // com.ytg.bilette.model.GenericDomainObject oldObj (line 178) İFNONNULL L1 ALOAD_2 // com.ytg.bilette.model.GenericDomainObject newObj İFNONNULL L1 ALOAD 4 // com.ytg.bilette.client.core.providers.IDomainObjectChangeListener listener (line 179) İNVOKEİNTERFACE com.ytg.bilette.client.core.providers.IDomainObjectChangeListener.fullRefresh ()V GOTO L2 L1: ALOAD 4 // com.ytg.bilette.client.core.providers.IDomainObjectChangeListener listener (line 181) ALOAD_1 // com.ytg.bilette.model.GenericDomainObject oldObj ALOAD_2 // com.ytg.bilette.model.GenericDomainObject newObj İNVOKEİNTERFACE com.ytg.bilette.client.core.providers.IDomainObjectChangeListener.concessionChanged (Lcom/ytg/bilette/model/GenericDomainObject;Lcom/ytg/bilette/model/GenericDomainObject;)V L2: ALOAD_3 // java.util.Iterator i (line 176) İNVOKEİNTERFACE java.util.Iterator.hasNext ()Z İFNE L0 RETURN (line 183) end private synchronized void notifyAllListeners(com.ytg.bilette.model.GenericDomainObject, com.ytg.bilette.model.GenericDomainObject) public synchronized void addListener(com.ytg.bilette.client.core.providers.IDomainObjectChangeListener) org.aspectj.weaver.MethodDeclarationLineNumber: 185:4715 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 186) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.listeners Ljava/util/HashSet; ALOAD_1 // com.ytg.bilette.client.core.providers.IDomainObjectChangeListener listener İNVOKEVİRTUAL java.util.HashSet.add (Ljava/lang/Object;)Z POP RETURN (line 187) end public synchronized void addListener(com.ytg.bilette.client.core.providers.IDomainObjectChangeListener) public synchronized void removeListener(com.ytg.bilette.client.core.providers.IDomainObjectChangeListener) org.aspectj.weaver.MethodDeclarationLineNumber: 189:4831 : ALOAD_0 // com.ytg.bilette.client.core.providers.DomainContentProvider this (line 190) GETFİELD com.ytg.bilette.client.core.providers.DomainContentProvider.listeners Ljava/util/HashSet; ALOAD_1 // com.ytg.bilette.client.core.providers.IDomainObjectChangeListener listener İNVOKEVİRTUAL java.util.HashSet.remove (Ljava/lang/Object;)Z POP RETURN (line 191) end public synchronized void removeListener(com.ytg.bilette.client.core.providers.IDomainObjectChangeListener) end public class com.ytg.bilette.client.core.providers.DomainContentProvider when implementing on shadow method-execution(void com.ytg.bilette.client.core.providers.DomainContentProvider.getData(com.ytg.bilette.dao.SummaryDAO, org.eclipse.core.runtime.IProgressMonitor, boolean)) when weaving type com.ytg.bilette.client.core.providers.DomainContentProvider when weaving classes when weaving when batch building BuildConfig[F:\java\Bilette\.metadata\.plugins\org.eclipse.ajdt.core\com.ytg.bilette.client.core.generated.lst] #Files=22
|
resolved fixed
|
3ca976f
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-12T10:41:42Z | 2006-02-28T01:26:40Z |
weaver/src/org/aspectj/weaver/bcel/BcelShadow.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* Alexandre Vasseur support for @AJ aspects
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.generic.ACONST_NULL;
import org.aspectj.apache.bcel.generic.ALOAD;
import org.aspectj.apache.bcel.generic.ANEWARRAY;
import org.aspectj.apache.bcel.generic.ArrayType;
import org.aspectj.apache.bcel.generic.BranchInstruction;
import org.aspectj.apache.bcel.generic.ConstantPoolGen;
import org.aspectj.apache.bcel.generic.DUP;
import org.aspectj.apache.bcel.generic.DUP_X1;
import org.aspectj.apache.bcel.generic.FieldInstruction;
import org.aspectj.apache.bcel.generic.INVOKEINTERFACE;
import org.aspectj.apache.bcel.generic.INVOKESPECIAL;
import org.aspectj.apache.bcel.generic.INVOKESTATIC;
import org.aspectj.apache.bcel.generic.Instruction;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.apache.bcel.generic.InstructionTargeter;
import org.aspectj.apache.bcel.generic.InvokeInstruction;
import org.aspectj.apache.bcel.generic.LoadInstruction;
import org.aspectj.apache.bcel.generic.LocalVariableTag;
import org.aspectj.apache.bcel.generic.MULTIANEWARRAY;
import org.aspectj.apache.bcel.generic.NEW;
import org.aspectj.apache.bcel.generic.ObjectType;
import org.aspectj.apache.bcel.generic.PUSH;
import org.aspectj.apache.bcel.generic.ReturnInstruction;
import org.aspectj.apache.bcel.generic.SWAP;
import org.aspectj.apache.bcel.generic.StoreInstruction;
import org.aspectj.apache.bcel.generic.TargetLostException;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.bridge.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.MemberImpl;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewConstructorTypeMunger;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Var;
import org.aspectj.weaver.patterns.AndPointcut;
import org.aspectj.weaver.patterns.IdentityPointcutVisitor;
import org.aspectj.weaver.patterns.NotPointcut;
import org.aspectj.weaver.patterns.OrPointcut;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.ThisOrTargetPointcut;
/*
* 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
// SECRETAPI - for testing, this will tell us if the optimization succeeded *on the last shadow processed*
public static boolean appliedLazyTjpOptimization;
// Some instructions have a target type that will vary
// from the signature (pr109728) (1.4 declaring type issue)
private String actualInstructionTargetType;
// ---- 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);
if (mungers.size()>0) {
List src = mungers;
if (s.mungers==Collections.EMPTY_LIST) s.mungers = new ArrayList();
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 instruction 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);
}
// Now make any jumps to the 'new', the 'dup' or the 'end' now target the nextHandle
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--) {
if (sources[i] instanceof ExceptionRange) {
ExceptionRange it = (ExceptionRange)sources[i];
System.err.println("...");
it.updateTarget(old,fresh,it.getBody());
} else {
sources[i].updateTarget(old, fresh);
}
}
}
}
// records advice that is stopping us doing the lazyTjp optimization
private List badAdvice = null;
public void addAdvicePreventingLazyTjp(BcelAdvice advice) {
if (badAdvice == null) badAdvice = new ArrayList();
badAdvice.add(advice);
}
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) {
if (!world.isJoinpointArrayConstructionEnabled() || !this.getSignature().getDeclaringType().isArray())
deleteNewAndDup(); // no new/dup for new array construction
initializeArgVars();
} else if (getKind() == PreInitialization) { // pr74952
ShadowRange range = getRange();
range.insert(InstructionConstants.NOP,Range.InsideAfter);
} else if (getKind() == ExceptionHandler) {
ShadowRange range = getRange();
InstructionList body = range.getBody();
InstructionHandle start = range.getStart();
// Create a store instruction to put the value from the top of the
// stack into a local variable slot. This is a trimmed version of
// what is in initializeArgVars() (since there is only one argument
// at a handler jp and only before advice is supported) (pr46298)
argVars = new BcelVar[1];
//int positionOffset = (hasTarget() ? 1 : 0) + ((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
UnresolvedType tx = getArgType(0);
argVars[0] = genTempVar(tx, "ajc$arg0");
InstructionHandle insertedInstruction =
range.insert(argVars[0].createStore(getFactory()), Range.OutsideBefore);
// Now the exception range starts just after our new instruction.
// The next bit of code changes the exception range to point at
// the store instruction
InstructionTargeter[] targeters = start.getTargeters();
for (int i = 0; i < targeters.length; i++) {
InstructionTargeter t = targeters[i];
if (t instanceof ExceptionRange) {
ExceptionRange er = (ExceptionRange) t;
er.updateTarget(start, insertedInstruction, body);
}
}
}
// now we ask each munger to request our state
isThisJoinPointLazy = true;//world.isXlazyTjp(); // lazy is default now
badAdvice = null;
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
munger.specializeOn(this);
}
initializeThisJoinPoint();
if (thisJoinPointVar!=null && !isThisJoinPointLazy && badAdvice!=null && badAdvice.size()>1) {
// something stopped us making it a lazy tjp
// can't build tjp lazily, no suitable test...
int valid = 0;
for (Iterator iter = badAdvice.iterator(); iter.hasNext();) {
BcelAdvice element = (BcelAdvice) iter.next();
ISourceLocation sLoc = element.getSourceLocation();
if (sLoc!=null && sLoc.getLine()>0) valid++;
}
if (valid!=0) {
ISourceLocation[] badLocs = new ISourceLocation[valid];
int i = 0;
for (Iterator iter = badAdvice.iterator(); iter.hasNext();) {
BcelAdvice element = (BcelAdvice) iter.next();
ISourceLocation sLoc = element.getSourceLocation();
if (sLoc!=null) badLocs[i++]=sLoc;
}
world.getLint().multipleAdviceStoppingLazyTjp.signal(
new String[] {this.toString()},
getSourceLocation(),badLocs
);
}
}
badAdvice=null;
// If we are an expression kind, we require our target/arguments on the stack
// before we do our actual thing. However, they may have been removed
// from the stack as the shadowMungers have requested state.
// if any of our shadowMungers requested either the arguments or target,
// the munger will have added code
// to pop the target/arguments into temporary variables, represented by
// targetVar and argVars. In such a case, we must make sure to re-push the
// values.
// If we are nonExpressionKind, we don't expect arguments on the stack
// so this is moot. If our argVars happen to be null, then we know that
// no ShadowMunger has squirrelled away our arguments, so they're still
// on the stack.
InstructionFactory fact = getFactory();
if (getKind().argsOnStack() && argVars != null) {
// Special case first (pr46298). If we are an exception handler and the instruction
// just after the shadow is a POP then we should remove the pop. The code
// above which generated the store instruction has already cleared the stack.
// We also don't generate any code for the arguments in this case as it would be
// an incorrect aload.
if (getKind() == ExceptionHandler
&& range.getEnd().getNext().getInstruction().equals(InstructionConstants.POP)) {
// easier than deleting it ...
range.getEnd().getNext().setInstruction(InstructionConstants.NOP);
} else {
range.insert(
BcelRenderer.renderExprs(fact, world, argVars),
Range.InsideBefore);
if (targetVar != null) {
range.insert(
BcelRenderer.renderExpr(fact, world, targetVar),
Range.InsideBefore);
}
if (getKind() == ConstructorCall) {
if (!world.isJoinpointArrayConstructionEnabled() || !this.getSignature().getDeclaringType().isArray()) {
range.insert((Instruction) InstructionFactory.createDup(1), Range.InsideBefore);
range.insert(
fact.createNew(
(ObjectType) BcelWorld.makeBcelType(
getSignature().getDeclaringType())),
Range.InsideBefore);
}
}
}
}
}
// ---- getters
public ShadowRange getRange() {
return range;
}
public void setRange(ShadowRange range) {
this.range = range;
}
public int getSourceLine() {
// if the kind of join point for which we are a shadow represents
// a method or constructor execution, then the best source line is
// the one from the enclosingMethod declarationLineNumber if available.
Kind kind = getKind();
if ( (kind == MethodExecution) ||
(kind == ConstructorExecution) ||
(kind == AdviceExecution) ||
(kind == StaticInitialization) ||
(kind == PreInitialization) ||
(kind == Initialization)) {
if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
return getEnclosingMethod().getDeclarationLineNumber();
}
}
if (range == null) {
if (getEnclosingMethod().hasBody()) {
return Utility.getSourceLine(getEnclosingMethod().getBody().getStart());
} else {
return 0;
}
}
int ret = Utility.getSourceLine(range.getStart());
if (ret < 0) return 0;
return ret;
}
// overrides
public UnresolvedType 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.makeJoinPointSignature(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.makeJoinPointSignature(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();
UnresolvedType catchType = exceptionRange.getCatchType();
UnresolvedType inType = enclosingMethod.getEnclosingClass().getType();
ResolvedMemberImpl sig = MemberImpl.makeExceptionHandlerSignature(inType, catchType);
sig.setParameterNames(new String[] {findHandlerParamName(startOfHandler)});
BcelShadow s =
new BcelShadow(
world,
ExceptionHandler,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
InstructionHandle start = Range.genStart(body, startOfHandler);
InstructionHandle end = Range.genEnd(body, start);
r.associateWithTargets(start, end);
exceptionRange.updateTarget(startOfHandler, start, body);
return s;
}
private static String findHandlerParamName(InstructionHandle startOfHandler) {
if (startOfHandler.getInstruction() instanceof StoreInstruction &&
startOfHandler.getNext() != null)
{
int slot = ((StoreInstruction)startOfHandler.getInstruction()).getIndex();
//System.out.println("got store: " + startOfHandler.getInstruction() + ", " + index);
InstructionTargeter[] targeters = startOfHandler.getNext().getTargeters();
if (targeters!=null) {
for (int i=targeters.length-1; i >= 0; i--) {
if (targeters[i] instanceof LocalVariableTag) {
LocalVariableTag t = (LocalVariableTag)targeters[i];
if (t.getSlot() == slot) {
return t.getName();
}
//System.out.println("tag: " + targeters[i]);
}
}
}
}
return "<missing>";
}
/** create an init join point associated w/ an interface in the body of a constructor */
public static BcelShadow makeIfaceInitialization(
BcelWorld world,
LazyMethodGen constructor,
Member interfaceConstructorSignature)
{
// this call marks the instruction list as changed
constructor.getBody();
// UnresolvedType 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();
// // UnresolvedType 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)
{
BcelShadow ret = new BcelShadow(
world,
Initialization,
world.makeJoinPointSignature(constructor),
constructor,
null);
if (constructor.getEffectiveSignature() != null) {
ret.setMatchingSignature(constructor.getEffectiveSignature().getEffectiveSignature());
}
return ret;
}
public static BcelShadow makeUnfinishedPreinitialization(
BcelWorld world,
LazyMethodGen constructor)
{
BcelShadow ret = new BcelShadow(
world,
PreInitialization,
world.makeJoinPointSignature(constructor),
constructor,
null);
// ret.fallsThrough = true;
if (constructor.getEffectiveSignature() != null) {
ret.setMatchingSignature(constructor.getEffectiveSignature().getEffectiveSignature());
}
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.makeJoinPointSignatureFromMethod(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 = world.makeJoinPointSignatureForMethodInvocation(
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 makeArrayConstructorCall(BcelWorld world,LazyMethodGen enclosingMethod,InstructionHandle arrayInstruction,BcelShadow enclosingShadow) {
final InstructionList body = enclosingMethod.getBody();
Member sig = world.makeJoinPointSignatureForArrayConstruction(enclosingMethod.getEnclosingClass(),arrayInstruction);
BcelShadow s =
new BcelShadow(
world,
ConstructorCall,
sig,
enclosingMethod,
enclosingShadow);
ShadowRange r = new ShadowRange(body);
r.associateWithShadow(s);
r.associateWithTargets(
Range.genStart(body, arrayInstruction),
Range.genEnd(body, arrayInstruction));
retargetAllBranches(arrayInstruction, r.getStart());
return s;
}
// see pr77166
// public static BcelShadow makeArrayLoadCall(
// BcelWorld world,
// LazyMethodGen enclosingMethod,
// InstructionHandle arrayInstruction,
// BcelShadow enclosingShadow)
// {
// final InstructionList body = enclosingMethod.getBody();
// Member sig = world.makeJoinPointSignatureForArrayLoad(enclosingMethod.getEnclosingClass(),arrayInstruction);
// BcelShadow s =
// new BcelShadow(
// world,
// MethodCall,
// sig,
// enclosingMethod,
// enclosingShadow);
// ShadowRange r = new ShadowRange(body);
// r.associateWithShadow(s);
// r.associateWithTargets(
// Range.genStart(body, arrayInstruction),
// Range.genEnd(body, arrayInstruction));
// retargetAllBranches(arrayInstruction, 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,
world.makeJoinPointSignatureForMethodInvocation(
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,
ResolvedMember field,
LazyMethodGen enclosingMethod,
InstructionHandle getHandle,
BcelShadow enclosingShadow)
{
final InstructionList body = enclosingMethod.getBody();
BcelShadow s =
new BcelShadow(
world,
FieldGet,
field,
// 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.makeFieldJoinPointSignature(
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;
private Map/*<UnresolvedType,BcelVar>*/ kindedAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ thisAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ targetAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/[] argAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ withinAnnotationVars = null;
private Map/*<UnresolvedType,BcelVar>*/ withincodeAnnotationVars = null;
public Var getThisVar() {
if (!hasThis()) {
throw new IllegalStateException("no this");
}
initializeThisVar();
return thisVar;
}
public Var getThisAnnotationVar(UnresolvedType forAnnotationType) {
if (!hasThis()) {
throw new IllegalStateException("no this");
}
initializeThisAnnotationVars(); // FIXME asc Why bother with this if we always return one?
// Even if we can't find one, we have to return one as we might have this annotation at runtime
Var v = (Var) thisAnnotationVars.get(forAnnotationType);
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getThisVar());
return v;
}
public Var getTargetVar() {
if (!hasTarget()) {
throw new IllegalStateException("no target");
}
initializeTargetVar();
return targetVar;
}
public Var getTargetAnnotationVar(UnresolvedType forAnnotationType) {
if (!hasTarget()) {
throw new IllegalStateException("no target");
}
initializeTargetAnnotationVars(); // FIXME asc why bother with this if we always return one?
Var v =(Var) targetAnnotationVars.get(forAnnotationType);
// Even if we can't find one, we have to return one as we might have this annotation at runtime
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getTargetVar());
return v;
}
public Var getArgVar(int i) {
initializeArgVars();
return argVars[i];
}
public Var getArgAnnotationVar(int i,UnresolvedType forAnnotationType) {
initializeArgAnnotationVars();
Var v= (Var) argAnnotationVars[i].get(forAnnotationType);
if (v==null)
v = new TypeAnnotationAccessVar(forAnnotationType.resolve(world),(BcelVar)getArgVar(i));
return v;
}
public Var getKindedAnnotationVar(UnresolvedType forAnnotationType) {
initializeKindedAnnotationVars();
return (Var) kindedAnnotationVars.get(forAnnotationType);
}
public Var getWithinAnnotationVar(UnresolvedType forAnnotationType) {
initializeWithinAnnotationVars();
return (Var) withinAnnotationVars.get(forAnnotationType);
}
public Var getWithinCodeAnnotationVar(UnresolvedType forAnnotationType) {
initializeWithinCodeAnnotationVars();
return (Var) withincodeAnnotationVars.get(forAnnotationType);
}
// 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, boolean isAround) {
if (!isAround){
if (!hasGuardTest) {
isThisJoinPointLazy = false;
} else {
lazyTjpConsumers++;
}
}
// if (!hasGuardTest) {
// isThisJoinPointLazy = false;
// } else {
// lazyTjpConsumers++;
// }
if (thisJoinPointVar == null) {
thisJoinPointVar = genTempVar(UnresolvedType.forName("org.aspectj.lang.JoinPoint"));
}
}
public Var getThisJoinPointVar() {
requireThisJoinPoint(false,false);
return thisJoinPointVar;
}
void initializeThisJoinPoint() {
if (thisJoinPointVar == null) return;
if (isThisJoinPointLazy) {
isThisJoinPointLazy = checkLazyTjp();
}
if (isThisJoinPointLazy) {
appliedLazyTjpOptimization = true;
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 {
appliedLazyTjpOptimization = false;
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) {
if (munger.getSourceLocation()!=null) { // do we know enough to bother reporting?
if (world.getLint().canNotImplementLazyTjp.isEnabled()) {
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) {
// If we're lazy, build the join point right here.
il.append(createThisJoinPoint());
// Does someone else need it? If so, store it for later retrieval
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 {
// If not lazy, its already been built and stored, just retrieve it
thisJoinPointVar.appendLoad(il, fact);
}
return il;
}
InstructionList createThisJoinPoint() {
InstructionFactory fact = getFactory();
InstructionList il = new InstructionList();
BcelVar staticPart = getThisJoinPointStaticPartBcelVar();
staticPart.appendLoad(il, fact);
if (hasThis()) {
((BcelVar)getThisVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
if (hasTarget()) {
((BcelVar)getTargetVar()).appendLoad(il, fact);
} else {
il.append(new ACONST_NULL());
}
switch(getArgCount()) {
case 0:
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 1:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
il.append(fact.createInvoke("org.aspectj.runtime.reflect.Factory",
"makeJP", LazyClassGen.tjpType,
new Type[] { LazyClassGen.staticTjpType,
Type.OBJECT, Type.OBJECT, Type.OBJECT},
Constants.INVOKESTATIC));
break;
case 2:
((BcelVar)getArgVar(0)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.OBJECT));
((BcelVar)getArgVar(1)).appendLoadAndConvert(il, fact, world.getCoreType(ResolvedType.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;
}
/**
* Get the Var for the jpStaticPart
* @return
*/
public BcelVar getThisJoinPointStaticPartBcelVar() {
return getThisJoinPointStaticPartBcelVar(false);
}
/**
* Get the Var for the xxxxJpStaticPart, xxx = this or enclosing
* @param isEnclosingJp true to have the enclosingJpStaticPart
* @return
*/
public BcelVar getThisJoinPointStaticPartBcelVar(final boolean isEnclosingJp) {
if (thisJoinPointStaticPartVar == null) {
Field field = getEnclosingClass().getTjpField(this, isEnclosingJp);
ResolvedType sjpType = null;
if (world.isTargettingAspectJRuntime12()) { // TAG:SUPPORTING12: We didn't have different jpsp types in 1.2
sjpType = world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$StaticPart"));
} else {
sjpType = isEnclosingJp?
world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$EnclosingStaticPart")):
world.getCoreType(UnresolvedType.forName("org.aspectj.lang.JoinPoint$StaticPart"));
}
thisJoinPointStaticPartVar = new BcelFieldRef(
sjpType,
getEnclosingClass().getClassName(),
field.getName());
// getEnclosingClass().warnOnAddedStaticInitializer(this,munger.getSourceLocation());
}
return thisJoinPointStaticPartVar;
}
/**
* Get the Var for the enclosingJpStaticPart
* @return
*/
public BcelVar getThisEnclosingJoinPointStaticPartBcelVar() {
if (enclosingShadow == null) {
// the enclosing of an execution is itself
return getThisJoinPointStaticPartBcelVar(true);
} else {
return ((BcelShadow)enclosingShadow).getThisJoinPointStaticPartBcelVar(true);
}
}
//??? need to better understand all the enclosing variants
public Member getEnclosingCodeSignature() {
if (getKind().isEnclosingKind()) {
return getSignature();
} else if (getKind() == Shadow.PreInitialization) {
// PreInit doesn't enclose code but its signature
// is correctly the signature of the ctor.
return getSignature();
} else if (enclosingShadow == null) {
return getEnclosingMethod().getMemberView();
} else {
return enclosingShadow.getSignature();
}
}
private InstructionList makeArgsObjectArray() {
InstructionFactory fact = getFactory();
BcelVar arrayVar = genTempVar(UnresolvedType.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
UnresolvedType type = getTargetType();
type = ensureTargetTypeIsCorrect(type);
targetVar = genTempVar(type, "ajc$target");
range.insert(targetVar.createStore(fact), Range.OutsideBefore);
targetVar.setPositionInAroundState(hasThis() ? 1 : 0);
}
}
/* PR 72528
* This method double checks the target type under certain conditions. The Java 1.4
* compilers seem to take calls to clone methods on array types and create bytecode that
* looks like clone is being called on Object. If we advise a clone call with around
* advice we extract the call into a helper method which we can then refer to. Because the
* type in the bytecode for the call to clone is Object we create a helper method with
* an Object parameter - this is not correct as we have lost the fact that the actual
* type is an array type. If we don't do the check below we will create code that fails
* java verification. This method checks for the peculiar set of conditions and if they
* are true, it has a sneak peek at the code before the call to see what is on the stack.
*/
public UnresolvedType ensureTargetTypeIsCorrect(UnresolvedType tx) {
Member msig = getSignature();
if (msig.getArity()==0 &&
getKind() == MethodCall &&
msig.getName().charAt(0) == 'c' &&
tx.equals(ResolvedType.OBJECT) &&
msig.getReturnType().equals(ResolvedType.OBJECT) &&
msig.getName().equals("clone")) {
// Lets go back through the code from the start of the shadow
InstructionHandle searchPtr = range.getStart().getPrev();
while (Range.isRangeHandle(searchPtr) ||
searchPtr.getInstruction() instanceof StoreInstruction) { // ignore this instruction - it doesnt give us the info we want
searchPtr = searchPtr.getPrev();
}
// A load instruction may tell us the real type of what the clone() call is on
if (searchPtr.getInstruction() instanceof LoadInstruction) {
LoadInstruction li = (LoadInstruction)searchPtr.getInstruction();
li.getIndex();
LocalVariableTag lvt = LazyMethodGen.getLocalVariableTag(searchPtr,li.getIndex());
if (lvt!=null) return UnresolvedType.forSignature(lvt.getType());
}
// A field access instruction may tell us the real type of what the clone() call is on
if (searchPtr.getInstruction() instanceof FieldInstruction) {
FieldInstruction si = (FieldInstruction)searchPtr.getInstruction();
Type t = si.getFieldType(getEnclosingClass().getConstantPoolGen());
return BcelWorld.fromBcel(t);
}
// A new array instruction obviously tells us it is an array type !
if (searchPtr.getInstruction() instanceof ANEWARRAY) {
//ANEWARRAY ana = (ANEWARRAY)searchPoint.getInstruction();
//Type t = ana.getType(getEnclosingClass().getConstantPoolGen());
// Just use a standard java.lang.object array - that will work fine
return BcelWorld.fromBcel(new ArrayType(Type.OBJECT,1));
}
// A multi new array instruction obviously tells us it is an array type !
if (searchPtr.getInstruction() instanceof MULTIANEWARRAY) {
MULTIANEWARRAY ana = (MULTIANEWARRAY)searchPtr.getInstruction();
// Type t = ana.getType(getEnclosingClass().getConstantPoolGen());
// t = new ArrayType(t,ana.getDimensions());
// Just use a standard java.lang.object array - that will work fine
return BcelWorld.fromBcel(new ArrayType(Type.OBJECT,ana.getDimensions()));
}
throw new BCException("Can't determine real target of clone() when processing instruction "+
searchPtr.getInstruction()+". Perhaps avoid selecting clone with your pointcut?");
}
return tx;
}
public void initializeArgVars() {
if (argVars != null) return;
InstructionFactory fact = getFactory();
int len = getArgCount();
argVars = new BcelVar[len];
int positionOffset = (hasTarget() ? 1 : 0) +
((hasThis() && !getKind().isTargetSameAsThis()) ? 1 : 0);
if (getKind().argsOnStack()) {
// we move backwards because we're popping off the stack
for (int i = len - 1; i >= 0; i--) {
UnresolvedType 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++) {
UnresolvedType 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);
}
public void initializeThisAnnotationVars() {
if (thisAnnotationVars != null) return;
thisAnnotationVars = new HashMap();
// populate..
}
public void initializeTargetAnnotationVars() {
if (targetAnnotationVars != null) return;
if (getKind().isTargetSameAsThis()) {
if (hasThis()) initializeThisAnnotationVars();
targetAnnotationVars = thisAnnotationVars;
} else {
targetAnnotationVars = new HashMap();
ResolvedType[] rtx = this.getTargetType().resolve(world).getAnnotationTypes(); // what about annotations we havent gotten yet but we will get in subclasses?
for (int i = 0; i < rtx.length; i++) {
ResolvedType typeX = rtx[i];
targetAnnotationVars.put(typeX,new TypeAnnotationAccessVar(typeX,(BcelVar)getTargetVar()));
}
// populate.
}
}
public void initializeArgAnnotationVars() {
if (argAnnotationVars != null) return;
int numArgs = getArgCount();
argAnnotationVars = new Map[numArgs];
for (int i = 0; i < argAnnotationVars.length; i++) {
argAnnotationVars[i] = new HashMap();
//FIXME asc just delete this logic - we always build the Var on demand, as we don't know at weave time
// what the full set of annotations could be (due to static/dynamic type differences...)
}
}
protected Member getRelevantMember(Member foundMember, Member relevantMember, ResolvedType relevantType){
if (foundMember != null){
return foundMember;
}
foundMember = getSignature().resolve(world);
if (foundMember == null && relevantMember != null) {
foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember);
}
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewMethodTypeMunger ||
typeMunger.getMunger() instanceof NewConstructorTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
if (fakerm.getName().equals(getSignature().getName()) &&
fakerm.getParameterSignature().equals(getSignature().getParameterSignature())){
if (foundMember.getKind()==ResolvedMember.CONSTRUCTOR){
foundMember = AjcMemberMaker.interConstructor(
relevantType,
(ResolvedMember)foundMember,
typeMunger.getAspectType());
} else {
foundMember = AjcMemberMaker.interMethod((ResolvedMember)foundMember,
typeMunger.getAspectType(), false);
}
// in the above.. what about if it's on an Interface? Can that happen?
// then the last arg of the above should be true
return foundMember;
}
}
}
return foundMember;
}
protected ResolvedType [] getAnnotations(Member foundMember, Member relevantMember, ResolvedType relevantType){
if (foundMember == null){
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewMethodTypeMunger ||
typeMunger.getMunger() instanceof NewConstructorTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
//if (fakerm.hasAnnotations())
ResolvedMember ajcMethod = (getSignature().getKind()==ResolvedMember.CONSTRUCTOR?
AjcMemberMaker.postIntroducedConstructor(typeMunger.getAspectType(),fakerm.getDeclaringType(),fakerm.getParameterTypes()):
AjcMemberMaker.interMethodDispatcher(fakerm,typeMunger.getAspectType()));
//AjcMemberMaker.interMethodBody(fakerm,typeMunger.getAspectType()));
ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod);
if (fakerm.getName().equals(getSignature().getName()) &&
fakerm.getParameterSignature().equals(getSignature().getParameterSignature())) {
relevantType = typeMunger.getAspectType();
foundMember = rmm;
return foundMember.getAnnotationTypes();
}
}
}
// didn't find in ITDs, look in supers
foundMember = relevantType.lookupMemberWithSupersAndITDs(relevantMember);
if (foundMember == null) {
throw new IllegalStateException("Couldn't find member " + relevantMember + " for type " + relevantType);
}
}
return foundMember.getAnnotationTypes();
}
public void initializeKindedAnnotationVars() {
if (kindedAnnotationVars != null) return;
kindedAnnotationVars = new HashMap();
// by determining what "kind" of shadow we are, we can find out the
// annotations on the appropriate element (method, field, constructor, type).
// Then create one BcelVar entry in the map for each annotation, keyed by
// annotation type (UnresolvedType).
// FIXME asc Refactor this code, there is duplication
ResolvedType[] annotations = null;
Member relevantMember = getSignature();
ResolvedType relevantType = relevantMember.getDeclaringType().resolve(world);
if (getKind() == Shadow.StaticInitialization) {
annotations = relevantType.resolve(world).getAnnotationTypes();
} else if (getKind() == Shadow.MethodCall || getKind() == Shadow.ConstructorCall) {
Member foundMember = findMethod2(relevantType.resolve(world).getDeclaredMethods(),getSignature());
annotations = getAnnotations(foundMember, relevantMember, relevantType);
relevantMember = getRelevantMember(foundMember,relevantMember,relevantType);
relevantType = relevantMember.getDeclaringType().resolve(world);
} else if (getKind() == Shadow.FieldSet || getKind() == Shadow.FieldGet) {
relevantMember = findField(relevantType.getDeclaredFields(),getSignature());
if (relevantMember==null) {
// check the ITD'd dooberries
List mungers = relevantType.resolve(world).getInterTypeMungers();
for (Iterator iter = mungers.iterator(); iter.hasNext();) {
BcelTypeMunger typeMunger = (BcelTypeMunger) iter.next();
if (typeMunger.getMunger() instanceof NewFieldTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
//if (fakerm.hasAnnotations())
ResolvedMember ajcMethod = AjcMemberMaker.interFieldInitializer(fakerm,typeMunger.getAspectType());
ResolvedMember rmm = findMethod(typeMunger.getAspectType(),ajcMethod);
if (fakerm.equals(getSignature())) {
relevantType = typeMunger.getAspectType();
relevantMember = rmm;
}
}
}
}
annotations = relevantMember.getAnnotationTypes();
} else if (getKind() == Shadow.MethodExecution || getKind() == Shadow.ConstructorExecution ||
getKind() == Shadow.AdviceExecution) {
//ResolvedMember rm[] = relevantType.getDeclaredMethods();
Member foundMember = findMethod2(relevantType.getDeclaredMethods(),getSignature());
annotations = getAnnotations(foundMember, relevantMember,relevantType);
relevantMember = foundMember;
relevantMember = getRelevantMember(foundMember, relevantMember,relevantType);
} else if (getKind() == Shadow.ExceptionHandler) {
relevantType = getSignature().getParameterTypes()[0].resolve(world);
annotations = relevantType.getAnnotationTypes();
} else if (getKind() == Shadow.PreInitialization || getKind() == Shadow.Initialization) {
ResolvedMember found = findMethod2(relevantType.getDeclaredMethods(),getSignature());
annotations = found.getAnnotationTypes();
}
if (annotations == null) {
// We can't have recognized the shadow - should blow up now to be on the safe side
throw new BCException("Couldn't discover annotations for shadow: "+getKind());
}
for (int i = 0; i < annotations.length; i++) {
ResolvedType aTX = annotations[i];
KindedAnnotationAccessVar kaav = new KindedAnnotationAccessVar(getKind(),aTX.resolve(world),relevantType,relevantMember);
kindedAnnotationVars.put(aTX,kaav);
}
}
//FIXME asc whats the real diff between this one and the version in findMethod()?
ResolvedMember findMethod2(ResolvedMember rm[], Member sig) {
ResolvedMember found = null;
// String searchString = getSignature().getName()+getSignature().getParameterSignature();
for (int i = 0; i < rm.length && found==null; i++) {
ResolvedMember member = rm[i];
if (member.getName().equals(sig.getName()) && member.getParameterSignature().equals(sig.getParameterSignature()))
found = member;
}
return found;
}
private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) {
ResolvedMember decMethods[] = aspectType.getDeclaredMethods();
for (int i = 0; i < decMethods.length; i++) {
ResolvedMember member = decMethods[i];
if (member.equals(ajcMethod)) return member;
}
return null;
}
private ResolvedMember findField(ResolvedMember[] members,Member lookingFor) {
for (int i = 0; i < members.length; i++) {
ResolvedMember member = members[i];
if ( member.getName().equals(getSignature().getName()) &&
member.getType().equals(getSignature().getType())) {
return member;
}
}
return null;
}
public void initializeWithinAnnotationVars() {
if (withinAnnotationVars != null) return;
withinAnnotationVars = new HashMap();
ResolvedType[] annotations = getEnclosingType().resolve(world).getAnnotationTypes();
for (int i = 0; i < annotations.length; i++) {
ResolvedType ann = annotations[i];
Kind k = Shadow.StaticInitialization;
withinAnnotationVars.put(ann,new KindedAnnotationAccessVar(k,ann,getEnclosingType(),null));
}
}
public void initializeWithinCodeAnnotationVars() {
if (withincodeAnnotationVars != null) return;
withincodeAnnotationVars = new HashMap();
// For some shadow we are interested in annotations on the method containing that shadow.
ResolvedType[] annotations = getEnclosingMethod().getMemberView().getAnnotationTypes();
for (int i = 0; i < annotations.length; i++) {
ResolvedType ann = annotations[i];
Kind k = (getEnclosingMethod().getMemberView().getKind()==Member.CONSTRUCTOR?
Shadow.ConstructorExecution:Shadow.MethodExecution);
withincodeAnnotationVars.put(ann,
new KindedAnnotationAccessVar(k,ann,getEnclosingType(),getEnclosingCodeSignature()));
}
}
// ---- weave methods
void weaveBefore(BcelAdvice munger) {
range.insert(
munger.getAdviceInstructions(this, null, range.getRealStart()),
Range.InsideBefore);
}
public void weaveAfter(BcelAdvice munger) {
weaveAfterThrowing(munger, UnresolvedType.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()) */ {
/*
*
27: getstatic #72; //Field ajc$cflowCounter$0:Lorg/aspectj/runtime/internal/CFlowCounter;
30: invokevirtual #87; //Method org/aspectj/runtime/internal/CFlowCounter.dec:()V
33: aload 6
35: athrow
36: nop
37: getstatic #72; //Field ajc$cflowCounter$0:Lorg/aspectj/runtime/internal/CFlowCounter;
40: invokevirtual #87; //Method org/aspectj/runtime/internal/CFlowCounter.dec:()V
43: d2i
44: invokespecial #23; //Method java/lang/Object."<init>":()V
*/
retList = new InstructionList(InstructionConstants.NOP);
afterAdvice = retList.getStart();
// } else {
// retList = new InstructionList();
// afterAdvice = null;
}
InstructionList advice = new InstructionList();
BcelVar tempVar = null;
if (munger.hasExtraParameter()) {
UnresolvedType tempVarType = getReturnType();
if (tempVarType.equals(ResolvedType.VOID)) {
tempVar = genTempVar(UnresolvedType.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, UnresolvedType catchType) {
// a good optimization would be not to generate anything here
// if the shadow is GUARANTEED empty (i.e., there's NOTHING, not even
// a shadow, inside me).
if (getRange().getStart().getNext() == getRange().getEnd()) return;
InstructionFactory fact = getFactory();
InstructionList handler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
exceptionVar.appendStore(handler, fact);
// pr62642
// I will now jump through some firey BCEL hoops to generate a trivial bit of code:
// if (exc instanceof ExceptionInInitializerError)
// throw (ExceptionInInitializerError)exc;
if (this.getEnclosingMethod().getName().equals("<clinit>")) {
ResolvedType eiieType = world.resolve("java.lang.ExceptionInInitializerError");
ObjectType eiieBcelType = (ObjectType)BcelWorld.makeBcelType(eiieType);
InstructionList ih = new InstructionList(InstructionConstants.NOP);
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createInstanceOf(eiieBcelType));
BranchInstruction bi =
InstructionFactory.createBranchInstruction(Constants.IFEQ,ih.getStart());
handler.append(bi);
handler.append(exceptionVar.createLoad(fact));
handler.append(fact.createCheckCast(eiieBcelType));
handler.append(InstructionConstants.ATHROW);
handler.append(ih);
}
InstructionList endHandler = new InstructionList(
exceptionVar.createLoad(fact));
handler.append(munger.getAdviceInstructions(this, exceptionVar, endHandler.getStart()));
handler.append(endHandler);
handler.append(InstructionConstants.ATHROW);
InstructionHandle handlerStart = handler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = handler.append(InstructionConstants.NOP);
handler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
InstructionHandle protectedEnd = handler.getStart();
range.insert(handler, Range.InsideAfter);
enclosingMethod.addExceptionHandler(range.getStart().getNext(), protectedEnd.getPrev(),
handlerStart, (ObjectType)BcelWorld.makeBcelType(catchType), //???Type.THROWABLE,
// high priority if our args are on the stack
getKind().hasHighPriorityExceptions());
}
//??? this shares a lot of code with the above weaveAfterThrowing
//??? would be nice to abstract that to say things only once
public void weaveSoftener(BcelAdvice munger, UnresolvedType 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();
InstructionList rtExHandler = new InstructionList();
BcelVar exceptionVar = genTempVar(catchType);
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);
// ENH 42737
exceptionVar.appendStore(rtExHandler, fact);
// aload_1
rtExHandler.append(exceptionVar.createLoad(fact));
// instanceof class java/lang/RuntimeException
rtExHandler.append(fact.createInstanceOf(new ObjectType("java.lang.RuntimeException")));
// ifeq go to new SOFT_EXCEPTION_TYPE instruction
rtExHandler.append(InstructionFactory.createBranchInstruction(Constants.IFEQ,handler.getStart()));
// aload_1
rtExHandler.append(exceptionVar.createLoad(fact));
// athrow
rtExHandler.append(InstructionFactory.ATHROW);
InstructionHandle handlerStart = rtExHandler.getStart();
if (isFallsThrough()) {
InstructionHandle jumpTarget = range.getEnd();//handler.append(fact.NOP);
rtExHandler.insert(InstructionFactory.createBranchInstruction(Constants.GOTO, jumpTarget));
}
rtExHandler.append(handler);
InstructionHandle protectedEnd = rtExHandler.getStart();
range.insert(rtExHandler, 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);
}
// PTWIMPL Create static initializer to call the aspect factory
/**
* Causes the aspect instance to be *set* for later retrievable through localAspectof()/aspectOf()
*/
public void weavePerTypeWithinAspectInitialization(final BcelAdvice munger,UnresolvedType t) {
if (t.resolve(world).isInterface()) return; // Don't initialize statics in
final InstructionFactory fact = getFactory();
InstructionList entryInstructions = new InstructionList();
InstructionList entrySuccessInstructions = new InstructionList();
BcelWorld.getBcelObjectType(munger.getConcreteAspect());
String aspectname = munger.getConcreteAspect().getName();
String ptwField = NameMangler.perTypeWithinFieldForTarget(munger.getConcreteAspect());
entrySuccessInstructions.append(new PUSH(fact.getConstantPool(),t.getName()));
entrySuccessInstructions.append(fact.createInvoke(aspectname,"ajc$createAspectInstance",new ObjectType(aspectname),
new Type[]{new ObjectType("java.lang.String")},Constants.INVOKESTATIC));
entrySuccessInstructions.append(fact.createPutStatic(t.getName(),ptwField,
new ObjectType(aspectname)));
entryInstructions.append(entrySuccessInstructions);
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveCflowEntry(final BcelAdvice munger, final Member cflowField) {
final boolean isPer = munger.getKind() == AdviceKind.PerCflowBelowEntry ||
munger.getKind() == AdviceKind.PerCflowEntry;
final Type objectArrayType = new ArrayType(Type.OBJECT, 1);
final InstructionFactory fact = getFactory();
final BcelVar testResult = genTempVar(ResolvedType.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(false);
if (cflowStateVars.length == 0) {
// This should be getting managed by a counter - lets make sure.
if (!cflowField.getType().getName().endsWith("CFlowCounter"))
throw new RuntimeException("Incorrectly attempting counter operation on stacked cflow");
entrySuccessInstructions.append(
Utility.createGet(fact, cflowField));
//arrayVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(fact.createInvoke(NameMangler.CFLOW_COUNTER_TYPE,"inc",Type.VOID,new Type[] { },Constants.INVOKEVIRTUAL));
} else {
BcelVar arrayVar = genTempVar(UnresolvedType.OBJECTARRAY);
int alen = cflowStateVars.length;
entrySuccessInstructions.append(Utility.createConstant(fact, alen));
entrySuccessInstructions.append(
(Instruction) fact.createNewArray(Type.OBJECT, (short) 1));
arrayVar.appendStore(entrySuccessInstructions, fact);
for (int i = 0; i < alen; i++) {
arrayVar.appendConvertableArrayStore(
entrySuccessInstructions,
fact,
i,
cflowStateVars[i]);
}
entrySuccessInstructions.append(
Utility.createGet(fact, cflowField));
arrayVar.appendLoad(entrySuccessInstructions, fact);
entrySuccessInstructions.append(
fact.createInvoke(NameMangler.CFLOW_STACK_TYPE, "push", Type.VOID,
new Type[] { objectArrayType },
Constants.INVOKEVIRTUAL));
}
}
InstructionList testInstructions =
munger.getTestInstructions(this, entrySuccessInstructions.getStart(),
range.getRealStart(),
entrySuccessInstructions.getStart());
entryInstructions.append(testInstructions);
entryInstructions.append(entrySuccessInstructions);
}
// this is the same for both per and non-per
weaveAfter(new BcelAdvice(null, null, null, 0, 0, 0, null, null) {
public InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice) {
InstructionList exitInstructions = new InstructionList();
if (munger.hasDynamicTests()) {
testResult.appendLoad(exitInstructions, fact);
exitInstructions.append(
InstructionFactory.createBranchInstruction(
Constants.IFEQ,
ifNoAdvice));
}
exitInstructions.append(Utility.createGet(fact, cflowField));
if (munger.getKind() != AdviceKind.PerCflowEntry &&
munger.getKind() != AdviceKind.PerCflowBelowEntry &&
munger.getExposedStateAsBcelVars(false).length==0) {
exitInstructions
.append(
fact
.createInvoke(
NameMangler.CFLOW_COUNTER_TYPE,
"dec",
Type.VOID,
new Type[] {
}, Constants.INVOKEVIRTUAL));
} else {
exitInstructions
.append(
fact
.createInvoke(
NameMangler.CFLOW_STACK_TYPE,
"pop",
Type.VOID,
new Type[] {
}, Constants.INVOKEVIRTUAL));
}
return exitInstructions;
}
});
range.insert(entryInstructions, Range.InsideBefore);
}
public void weaveAroundInline(
BcelAdvice munger,
boolean hasDynamicTest)
{
/* Implementation notes:
*
* AroundInline still extracts the instructions of the original shadow into
* an extracted method. This allows inlining of even that advice that doesn't
* call proceed or calls proceed more than once.
*
* It extracts the instructions of the original shadow into a method.
*
* Then it extracts the instructions of the advice into a new method defined on
* this enclosing class. This new method can then be specialized as below.
*
* Then it searches in the instructions of the advice for any call to the
* proceed method.
*
* At such a call, there is stuff on the stack representing the arguments to
* proceed. Pop these into the frame.
*
* Now build the stack for the call to the extracted method, taking values
* either from the join point state or from the new frame locs from proceed.
* Now call the extracted method. The right return value should be on the
* stack, so no cast is necessary.
*
* If only one call to proceed is made, we can re-inline the original shadow.
* We are not doing that presently.
*
* If the body of the advice can be determined to not alter the stack, or if
* this shadow doesn't care about the stack, i.e. method-execution, then the
* new method for the advice can also be re-lined. We are not doing that
* presently.
*/
// !!! THIS BLOCK OF CODE SHOULD BE IN A METHOD CALLED weaveAround(...);
Member mungerSig = munger.getSignature();
//Member originalSig = mungerSig; // If mungerSig is on a parameterized type, originalSig is the member on the generic type
if (mungerSig instanceof ResolvedMember) {
ResolvedMember rm = (ResolvedMember)mungerSig;
if (rm.hasBackingGenericMember()) mungerSig = rm.getBackingGenericMember();
}
ResolvedType declaringType = world.resolve(mungerSig.getDeclaringType(),true);
if (declaringType.isMissing()) {
world.getLint().cantFindType.signal(
new String[] {WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName())},
getSourceLocation(),
new ISourceLocation[]{ munger.getSourceLocation()}
);
// IMessage msg = new Message(
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE,declaringType.getClassName()),
// "",IMessage.ERROR,getSourceLocation(),null,
// new ISourceLocation[]{ munger.getSourceLocation()});
// world.getMessageHandler().handleMessage(msg);
}
//??? might want some checks here to give better errors
ResolvedType rt = (declaringType.isParameterizedType()?declaringType.getGenericType():declaringType);
BcelObjectType ot = BcelWorld.getBcelObjectType(rt);
// if (ot==null) {
// world.getMessageHandler().handleMessage(
// MessageUtil.warn("Unable to find modifiable delegate for the aspect '"+rt.getName()+"' containing around advice - cannot implement inlining",munger.getSourceLocation()));
// weaveAroundClosure(munger, hasDynamicTest);
// return;
// }
LazyMethodGen adviceMethod = ot.getLazyClassGen().getLazyMethodGen(mungerSig);
if (!adviceMethod.getCanInline()) {
weaveAroundClosure(munger, hasDynamicTest);
return;
}
// specific test for @AJ proceedInInners
if (munger.getConcreteAspect().isAnnotationStyleAspect()) {
// if we can't find one proceed()
// we suspect that the call is happening in an inner class
// so we don't inline it.
// Note: for code style, this is done at Aspect compilation time.
boolean canSeeProceedPassedToOther = false;
InstructionHandle curr = adviceMethod.getBody().getStart();
InstructionHandle end = adviceMethod.getBody().getEnd();
ConstantPoolGen cpg = adviceMethod.getEnclosingClass().getConstantPoolGen();
while (curr != end) {
InstructionHandle next = curr.getNext();
Instruction inst = curr.getInstruction();
if ((inst instanceof InvokeInstruction)
&& ((InvokeInstruction)inst).getSignature(cpg).indexOf("Lorg/aspectj/lang/ProceedingJoinPoint;") > 0) {
// we may want to refine to exclude stuff returning jp ?
// does code style skip inline if i write dump(thisJoinPoint) ?
canSeeProceedPassedToOther = true;// we see one pjp passed around - dangerous
break;
}
curr = next;
}
if (canSeeProceedPassedToOther) {
// remember this decision to avoid re-analysis
adviceMethod.setCanInline(false);
weaveAroundClosure(munger, hasDynamicTest);
return;
}
}
// We can't inline around methods if they have around advice on them, this
// is because the weaving will extract the body and hence the proceed call.
//??? should consider optimizations to recognize simple cases that don't require body extraction
enclosingMethod.setCanInline(false);
// start by exposing various useful things into the frame
final InstructionFactory fact = getFactory();
// now generate the aroundBody method
LazyMethodGen extractedMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
Modifier.PRIVATE,
munger
);
// now extract the advice into its own method
String adviceMethodName =
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()) + "$advice";
List argVarList = new ArrayList();
List proceedVarList = new ArrayList();
int extraParamOffset = 0;
// Create the extra parameters that are needed for passing to proceed
// This code is very similar to that found in makeCallToCallback and should
// be rationalized in the future
if (thisVar != null) {
argVarList.add(thisVar);
proceedVarList.add(new BcelVar(thisVar.getType(), extraParamOffset));
extraParamOffset += thisVar.getType().getSize();
}
if (targetVar != null && targetVar != thisVar) {
argVarList.add(targetVar);
proceedVarList.add(new BcelVar(targetVar.getType(), extraParamOffset));
extraParamOffset += targetVar.getType().getSize();
}
for (int i = 0, len = getArgCount(); i < len; i++) {
argVarList.add(argVars[i]);
proceedVarList.add(new BcelVar(argVars[i].getType(), extraParamOffset));
extraParamOffset += argVars[i].getType().getSize();
}
if (thisJoinPointVar != null) {
argVarList.add(thisJoinPointVar);
proceedVarList.add(new BcelVar(thisJoinPointVar.getType(), extraParamOffset));
extraParamOffset += thisJoinPointVar.getType().getSize();
}
Type[] adviceParameterTypes = adviceMethod.getArgumentTypes();
Type[] extractedMethodParameterTypes = extractedMethod.getArgumentTypes();
Type[] parameterTypes =
new Type[extractedMethodParameterTypes.length
+ adviceParameterTypes.length
+ 1];
int parameterIndex = 0;
System.arraycopy(
extractedMethodParameterTypes,
0,
parameterTypes,
parameterIndex,
extractedMethodParameterTypes.length);
parameterIndex += extractedMethodParameterTypes.length;
parameterTypes[parameterIndex++] =
BcelWorld.makeBcelType(adviceMethod.getEnclosingClass().getType());
System.arraycopy(
adviceParameterTypes,
0,
parameterTypes,
parameterIndex,
adviceParameterTypes.length);
LazyMethodGen localAdviceMethod =
new LazyMethodGen(
Modifier.PRIVATE | Modifier.FINAL | Modifier.STATIC,
BcelWorld.makeBcelType(mungerSig.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,
(munger.getConcreteAspect().isAnnotationStyleAspect() && munger.getDeclaringAspect()!=null && munger.getDeclaringAspect().resolve(world).isAnnotationStyleAspect())?
this.loadThisJoinPoint():
new InstructionList(InstructionConstants.ACONST_NULL)));
// adviceMethodInvocation =
advice.append(
Utility.createInvoke(fact, localAdviceMethod)); //(fact, getWorld(), munger.getSignature()));
advice.append(
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(mungerSig.getReturnType()),
extractedMethod.getReturnType(),world.isInJava5Mode()));
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.
// inlining support for code style aspects
if (!munger.getConcreteAspect().isAnnotationStyleAspect()) {
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.
} else {
//ATAJ inlining support for @AJ aspects
// [TODO document @AJ code rule: don't manipulate 2 jps proceed at the same time.. in an advice body]
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 INVOKEINTERFACE)
&& "proceed".equals(((INVOKEINTERFACE) inst).getMethodName(cpg))) {
final boolean isProceedWithArgs;
if (((INVOKEINTERFACE) inst).getArgumentTypes(cpg).length == 1) {
// proceed with args as a boxed Object[]
isProceedWithArgs = true;
} else {
isProceedWithArgs = false;
}
InstructionList insteadProceedIl = getRedoneProceedCallForAnnotationStyle(
fact,
extractedMethod,
munger,
localAdviceMethod,
proceedVarList,
isProceedWithArgs
);
localAdviceMethod.getBody().append(curr, insteadProceedIl);
Utility.deleteInstruction(curr, localAdviceMethod);
}
curr = next;
}
}
}
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(true);
IntMap proceedMap = makeProceedArgumentMap(adviceVars);
// System.out.println(proceedMap + " for " + this);
// System.out.println(argVarList);
ResolvedType[] proceedParamTypes =
world.resolve(munger.getSignature().getParameterTypes());
// remove this*JoinPoint* as arguments to proceed
if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) {
int len = munger.getBaseParameterCount()+1;
ResolvedType[] newTypes = new ResolvedType[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];
ResolvedType 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;
}
private static boolean bindsThisOrTarget(Pointcut pointcut) {
ThisTargetFinder visitor = new ThisTargetFinder();
pointcut.accept(visitor, null);
return visitor.bindsThisOrTarget;
}
private static class ThisTargetFinder extends IdentityPointcutVisitor {
boolean bindsThisOrTarget = false;
public Object visit(ThisOrTargetPointcut node, Object data) {
if (node.isBinding()) {
bindsThisOrTarget = true;
}
return node;
}
public Object visit(AndPointcut node, Object data) {
if (!bindsThisOrTarget) node.getLeft().accept(this, data);
if (!bindsThisOrTarget) node.getRight().accept(this, data);
return node;
}
public Object visit(NotPointcut node, Object data) {
if (!bindsThisOrTarget) node.getNegatedPointcut().accept(this, data);
return node;
}
public Object visit(OrPointcut node, Object data) {
if (!bindsThisOrTarget) node.getLeft().accept(this, data);
if (!bindsThisOrTarget) node.getRight().accept(this, data);
return node;
}
}
/**
* ATAJ Handle the inlining for @AJ aspects
*
* @param fact
* @param callbackMethod
* @param munger
* @param localAdviceMethod
* @param argVarList
* @param isProceedWithArgs
* @return
*/
private InstructionList getRedoneProceedCallForAnnotationStyle(
InstructionFactory fact,
LazyMethodGen callbackMethod,
BcelAdvice munger,
LazyMethodGen localAdviceMethod,
List argVarList,
boolean isProceedWithArgs)
{
// Notes:
// proceedingjp is on stack (since user was calling pjp.proceed(...)
// the boxed args to proceed() are on stack as well (Object[]) unless
// the call is to pjp.proceed(<noarg>)
// new Object[]{new Integer(argAdvice1-1)};// arg of proceed
// call to proceed(..) is NOT made
// instead we do
// itar callback args i
// get from array i, convert it to the callback arg i
// if ask for JP, push the one we got on the stack
// invoke callback, create conversion back to Object/Integer
// rest of method -- (hence all those conversions)
// intValue() from original code
// int res = .. from original code
//Note: we just don't care about the proceed map etc
InstructionList ret = new InstructionList();
// store the Object[] array on stack if proceed with args
if (isProceedWithArgs) {
Type objectArrayType = Type.getType("[Ljava/lang/Object;");
int localProceedArgArray = localAdviceMethod.allocateLocal(objectArrayType);
ret.append(InstructionFactory.createStore(objectArrayType, localProceedArgArray));
Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;");
int localJp = localAdviceMethod.allocateLocal(proceedingJpType);
ret.append(InstructionFactory.createStore(proceedingJpType, localJp));
// push on stack each element of the object array
// that is assumed to be consistent with the callback argument (ie munger args)
// TODO do we want to try catch ClassCast and AOOBE exception ?
// special logic when withincode is static or not
int startIndex = 0;
if (thisVar != null) {
startIndex = 1;
//TODO this logic is actually depending on target as well - test me
ret.append(new ALOAD(0));//thisVar
}
// if (bindsThisOrTarget(munger.getPointcut())) {
for (int i = startIndex, len=callbackMethod.getArgumentTypes().length; i < len; i++) {
Type stateType = callbackMethod.getArgumentTypes()[i];
BcelWorld.fromBcel(stateType).resolve(world);
if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
ret.append(new ALOAD(localJp));// from localAdvice signature
} else {
ret.append(InstructionFactory.createLoad(objectArrayType, localProceedArgArray));
ret.append(Utility.createConstant(fact, i-startIndex));
ret.append(InstructionFactory.createArrayLoad(Type.OBJECT));
ret.append(Utility.createConversion(
fact,
Type.OBJECT,
stateType
));
}
}
} else {
Type proceedingJpType = Type.getType("Lorg/aspectj/lang/ProceedingJoinPoint;");
int localJp = localAdviceMethod.allocateLocal(proceedingJpType);
ret.append(InstructionFactory.createStore(proceedingJpType, localJp));
for (int i = 0, len=callbackMethod.getArgumentTypes().length; i < len; i++) {
Type stateType = callbackMethod.getArgumentTypes()[i];
/*ResolvedType stateTypeX =*/
BcelWorld.fromBcel(stateType).resolve(world);
if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
ret.append(new ALOAD(localJp));// from localAdvice signature
// } else if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(stateType.getSignature())) {
// //FIXME ALEX?
// ret.append(new ALOAD(localJp));// from localAdvice signature
//// ret.append(fact.createCheckCast(
//// (ReferenceType) BcelWorld.makeBcelType(stateTypeX)
//// ));
// // cast ?
//
} else {
ret.append(InstructionFactory.createLoad(stateType, i));
}
}
}
// do the callback invoke
ret.append(Utility.createInvoke(fact, callbackMethod));
// box it again. Handles cases where around advice does return something else than Object
if (!UnresolvedType.OBJECT.equals(munger.getSignature().getReturnType())) {
ret.append(Utility.createConversion(
fact,
callbackMethod.getReturnType(),
Type.OBJECT
));
}
ret.append(Utility.createConversion(
fact,
callbackMethod.getReturnType(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType())
));
return ret;
//
//
//
// if (proceedMap.hasKey(i)) {
// ret.append(new ALOAD(i));
// //throw new RuntimeException("unimplemented");
// //proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
// } else {
// //((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
// //ret.append(new ALOAD(i));
// if ("Lorg/aspectj/lang/JoinPoint;".equals(stateType.getSignature())) {
// ret.append(new ALOAD(i));
// } else {
// ret.append(new ALOAD(i));
// }
// }
// }
//
// ret.append(Utility.createInvoke(fact, callbackMethod));
// ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
// BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
//
// //ret.append(new ACONST_NULL());//will be POPed
// if (true) return ret;
//
//
//
// // 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);
//
// ResolvedType[] proceedParamTypes =
// world.resolve(munger.getSignature().getParameterTypes());
// // remove this*JoinPoint* as arguments to proceed
// if (munger.getBaseParameterCount()+1 < proceedParamTypes.length) {
// int len = munger.getBaseParameterCount()+1;
// ResolvedType[] newTypes = new ResolvedType[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];
// ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
// if (proceedMap.hasKey(i)) {
// //throw new RuntimeException("unimplemented");
// proceedVars[proceedMap.get(i)].appendLoadAndConvert(ret, fact, stateTypeX);
// } else {
// ((BcelVar) argVarList.get(i)).appendLoad(ret, fact);
// }
// }
//
// ret.append(Utility.createInvoke(fact, callbackMethod));
// ret.append(Utility.createConversion(fact, callbackMethod.getReturnType(),
// BcelWorld.makeBcelType(munger.getSignature().getReturnType())));
// return ret;
}
public void weaveAroundClosure(BcelAdvice munger, boolean hasDynamicTest) {
InstructionFactory fact = getFactory();
enclosingMethod.setCanInline(false);
// MOVE OUT ALL THE INSTRUCTIONS IN MY SHADOW INTO ANOTHER METHOD!
LazyMethodGen callbackMethod =
extractMethod(
NameMangler.aroundCallbackMethodName(
getSignature(),
getEnclosingClass()),
0,
munger);
BcelVar[] adviceVars = munger.getExposedStateAsBcelVars(true);
String closureClassName =
NameMangler.makeClosureClassName(
getEnclosingClass().getType(),
getEnclosingClass().getNewGeneratedNameTag());
Member constructorSig = new MemberImpl(Member.CONSTRUCTOR,
UnresolvedType.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(UnresolvedType.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++) {
UnresolvedType bcelTX = BcelWorld.fromBcel(stateTypes[i]);
ResolvedType stateRTX = world.resolve(bcelTX,true);
if (stateRTX.isMissing()) {
world.getLint().cantFindType.signal(
new String[] {WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName())},
getSourceLocation(),
new ISourceLocation[]{ munger.getSourceLocation()}
);
// IMessage msg = new Message(
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_DURING_AROUND_WEAVE_PREINIT,bcelTX.getClassName()),
// "",IMessage.ERROR,getSourceLocation(),null,
// new ISourceLocation[]{ munger.getSourceLocation()});
// world.getMessageHandler().handleMessage(msg);
}
stateTempVar.appendConvertableArrayLoad(
returnConversionCode,
fact,
i,
stateRTX);
}
} else {
returnConversionCode =
Utility.createConversion(
getFactory(),
BcelWorld.makeBcelType(munger.getSignature().getReturnType()),
callbackMethod.getReturnType(),world.isInJava5Mode());
if (!isFallsThrough()) {
returnConversionCode.append(
InstructionFactory.createReturn(callbackMethod.getReturnType()));
}
}
// ATAJ for @AJ aspect we need to link the closure with the joinpoint instance
if (munger.getConcreteAspect()!=null && munger.getConcreteAspect().isAnnotationStyleAspect()
&& munger.getDeclaringAspect()!=null && munger.getDeclaringAspect().resolve(world).isAnnotationStyleAspect()) {
closureInstantiation.append(Utility.createInvoke(
getFactory(),
getWorld(),
new MemberImpl(
Member.METHOD,
UnresolvedType.forName("org.aspectj.runtime.internal.AroundClosure"),
Modifier.PUBLIC,
"linkClosureAndJoinPoint",
"()Lorg/aspectj/lang/ProceedingJoinPoint;"
)
));
}
InstructionList advice = new InstructionList();
advice.append(munger.getAdviceArgSetup(this, null, closureInstantiation));
// invoke the advice
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(UnresolvedType.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[] {},
getWorld());
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(UnresolvedType.OBJECTARRAY.resolve(world), 1);
// int proceedVarIndex = 1;
BcelVar stateVar =
new BcelVar(UnresolvedType.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];
ResolvedType stateTypeX = BcelWorld.fromBcel(stateType).resolve(world);
if (proceedMap.hasKey(i)) {
mbody.append(
proceedVar.createConvertableArrayLoad(fact, proceedMap.get(i),
stateTypeX));
} else {
mbody.append(
stateVar.createConvertableArrayLoad(fact, i,
stateTypeX));
}
}
mbody.append(Utility.createInvoke(fact, callbackMethod));
if (getKind() == PreInitialization) {
mbody.append(Utility.createSet(
fact,
AjcMemberMaker.aroundClosurePreInitializationField()));
mbody.append(InstructionConstants.ACONST_NULL);
} else {
mbody.append(
Utility.createConversion(
fact,
callbackMethod.getReturnType(),
Type.OBJECT));
}
mbody.append(InstructionFactory.createReturn(Type.OBJECT));
closureClass.addMethodGen(runMethod);
// class
getEnclosingClass().addGeneratedInner(closureClass);
return constructor;
}
// ---- extraction methods
public LazyMethodGen extractMethod(String newMethodName, int visibilityModifier, ShadowMunger munger) {
LazyMethodGen.assertGoodBody(range.getBody(), newMethodName);
if (!getKind().allowsExtraction()) throw new BCException("Attempt to extract method from a shadow kind that does not support this operation (" + getKind() + ")");
LazyMethodGen freshMethod = createMethodGen(newMethodName,visibilityModifier);
// System.err.println("******");
// System.err.println("ABOUT TO EXTRACT METHOD for" + this);
// enclosingMethod.print(System.err);
// System.err.println("INTO");
// freshMethod.print(System.err);
// System.err.println("WITH REMAP");
// System.err.println(makeRemap());
range.extractInstructionsInto(freshMethod, makeRemap(),
(getKind() != PreInitialization) &&
isFallsThrough());
if (getKind() == PreInitialization) {
addPreInitializationReturnCode(
freshMethod,
getSuperConstructorParameterTypes());
}
getEnclosingClass().addMethodGen(freshMethod,munger.getSourceLocation());
return freshMethod;
}
private void addPreInitializationReturnCode(
LazyMethodGen extractedMethod,
Type[] superConstructorTypes)
{
InstructionList body = extractedMethod.getBody();
final InstructionFactory fact = getFactory();
BcelVar arrayVar = new BcelVar(
world.getCoreType(UnresolvedType.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++) {
UnresolvedType type = getArgType(i);
ret.put(oldi, newi);
oldi += type.getSize();
newi += type.getSize();
}
}
// System.err.println("making remap for : " + this);
// if (targetVar != null) System.err.println("target slot : " + targetVar.getSlot());
// if (thisVar != null) System.err.println(" this slot : " + thisVar.getSlot());
// System.err.println(ret);
return ret;
}
/**
* The new method always static.
* It may take some extra arguments: this, target.
* If it's argsOnStack, then it must take both this/target
* If it's argsOnFrame, it shares this and target.
* ??? rewrite this to do less array munging, please
*/
private LazyMethodGen createMethodGen(String newMethodName, int visibilityModifier) {
Type[] parameterTypes = BcelWorld.makeBcelTypes(getArgTypes());
int modifiers = Modifier.FINAL | visibilityModifier;
// XXX some bug
// if (! isExpressionKind() && getSignature().isStrict(world)) {
// modifiers |= Modifier.STRICT;
// }
modifiers |= Modifier.STATIC;
if (targetVar != null && targetVar != thisVar) {
UnresolvedType targetType = getTargetType();
targetType = ensureTargetTypeIsCorrect(targetType);
// see pr109728 - this fixes the case when the declaring class is sometype 'X' but the getfield
// in the bytecode refers to a subtype of 'X'. This makes sure we use the type originally
// mentioned in the fieldget instruction as the method parameter and *not* the type upon which the
// field is declared because when the instructions are extracted into the new around body,
// they will still refer to the subtype.
if (getKind()==FieldGet && getActualTargetType()!=null &&
!getActualTargetType().equals(targetType.getName())) {
targetType = UnresolvedType.forName(getActualTargetType()).resolve(world);
}
ResolvedMember resolvedMember = getSignature().resolve(world);
if (resolvedMember != null && Modifier.isProtected(resolvedMember.getModifiers()) &&
!samePackage(targetType.getPackageName(), getEnclosingType().getPackageName()) &&
!resolvedMember.getName().equals("clone"))
{
if (!targetType.resolve(world).isAssignableFrom(getThisType().resolve(world))) {
throw new BCException("bad bytecode");
}
targetType = getThisType();
}
parameterTypes = addType(BcelWorld.makeBcelType(targetType), parameterTypes);
}
if (thisVar != null) {
UnresolvedType 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);
//FIXME ALEX? which one
//parameterTypes = addTypeToEnd(LazyClassGen.proceedingTjpType, parameterTypes);
}
UnresolvedType returnType;
if (getKind() == PreInitialization) {
returnType = UnresolvedType.OBJECTARRAY;
} else {
if (getKind() == ConstructorCall) returnType = getSignature().getDeclaringType();
else if (getKind() == FieldSet) returnType = ResolvedType.VOID;
else returnType = getSignature().getReturnType().resolve(world);
// returnType = getReturnType(); // for this and above lines, see pr137496
}
return
new LazyMethodGen(
modifiers,
BcelWorld.makeBcelType(returnType),
newMethodName,
parameterTypes,
new String[0],
// XXX again, we need to look up methods!
// UnresolvedType.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(UnresolvedType typeX) {
return new BcelVar(typeX.resolve(world), genTempVarIndex(typeX.getSize()));
}
// public static final boolean CREATE_TEMP_NAMES = true;
public BcelVar genTempVar(UnresolvedType typeX, String localName) {
BcelVar tv = genTempVar(typeX);
// if (CREATE_TEMP_NAMES) {
// for (InstructionHandle ih = range.getStart(); ih != range.getEnd(); ih = ih.getNext()) {
// if (Range.isRangeHandle(ih)) continue;
// ih.addTargeter(new LocalVariableTag(typeX, localName, tv.getSlot()));
// }
// }
return tv;
}
// eh doesn't think we need to garbage collect these (64K is a big number...)
private int genTempVarIndex(int size) {
return enclosingMethod.allocateLocal(size);
}
public InstructionFactory getFactory() {
return getEnclosingClass().getFactory();
}
public ISourceLocation getSourceLocation() {
int sourceLine = getSourceLine();
if (sourceLine == 0 || sourceLine == -1) {
// Thread.currentThread().dumpStack();
// System.err.println(this + ": " + range);
return getEnclosingClass().getType().getSourceLocation();
} else {
// For staticinitialization, if we have a nice offset, don't build a new source loc
if (getKind()==Shadow.StaticInitialization && getEnclosingClass().getType().getSourceLocation().getOffset()!=0) {
return getEnclosingClass().getType().getSourceLocation();
} else {
int offset = 0;
Kind kind = getKind();
if ( (kind == MethodExecution) ||
(kind == ConstructorExecution) ||
(kind == AdviceExecution) ||
(kind == StaticInitialization) ||
(kind == PreInitialization) ||
(kind == Initialization)) {
if (getEnclosingMethod().hasDeclaredLineNumberInfo()) {
offset = getEnclosingMethod().getDeclarationOffset();
}
}
return getEnclosingClass().getType().getSourceContext().makeSourceLocation(sourceLine, offset);
}
}
}
public Shadow getEnclosingShadow() {
return enclosingShadow;
}
public LazyMethodGen getEnclosingMethod() {
return enclosingMethod;
}
public boolean isFallsThrough() {
return !terminatesWithReturn(); //fallsThrough;
}
public void setActualTargetType(String className) {
this.actualInstructionTargetType = className;
}
public String getActualTargetType() {
return actualInstructionTargetType;
}
}
|
133,117 |
Bug 133117 Lots of warnings with noGuardForLazyTjp
|
When the noGuardForLazyTjp compiler option is set to warning or error and a piece of advice causes this warning to show up, you get one warning for every join point matched by the advice. I think just one would probably be enough...
|
resolved fixed
|
3fa4d24
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-12T15:34:39Z | 2006-03-24T08:46:40Z |
tests/src/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java
|
/* *******************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Andy Clement initial implementation
* ******************************************************************/
package org.aspectj.systemtest.incremental.tools;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.aspectj.ajdt.internal.core.builder.AjState;
import org.aspectj.ajdt.internal.core.builder.AsmHierarchyBuilder;
import org.aspectj.ajdt.internal.core.builder.IncrementalStateManager;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IProgramElement;
import org.aspectj.asm.IRelationship;
import org.aspectj.asm.IRelationshipMap;
import org.aspectj.asm.internal.Relationship;
import org.aspectj.bridge.IMessage;
import org.aspectj.testing.util.FileUtil;
import org.aspectj.weaver.World;
/**
* The superclass knows all about talking through Ajde to the compiler.
* The superclass isn't in charge of knowing how to simulate overlays
* for incremental builds, that is in here. As is the ability to
* generate valid build configs based on a directory structure. To
* support this we just need access to a sandbox directory - this
* sandbox is managed by the superclass (it only assumes all builds occur
* in <sandboxDir>/<projectName>/ )
*
* The idea is you can initialize multiple projects in the sandbox and
* they can all be built independently, hopefully exploiting
* incremental compilation. Between builds you can alter the contents
* of a project using the alter() method that overlays some set of
* new files onto the current set (adding new files/changing existing
* ones) - you can then drive a new build and check it behaves as
* expected.
*/
public class MultiProjectIncrementalTests extends AjdeInteractionTestbed {
public static boolean VERBOSE = false;
protected void setUp() throws Exception {
super.setUp();
AjdeInteractionTestbed.VERBOSE = VERBOSE;
AjState.FORCE_INCREMENTAL_DURING_TESTING = true;
}
protected void tearDown() throws Exception {
super.tearDown();
AjState.FORCE_INCREMENTAL_DURING_TESTING = false;
}
/*
A.aj
package pack;
public aspect A {
pointcut p() : call(* C.method
before() : p() { // line 7
}
}
C.java
package pack;
public class C {
public void method1() {
method2(); // line 6
}
public void method2() { }
public void method3() {
method2(); // line 13
}
}*/
public void testDontLoseAdviceMarkers_pr134471() {
try {
AsmHierarchyBuilder.shouldAddUsesPointcut=false;
configureBuildStructureModel(true);
initialiseProject("P4");
build("P4");
dumpAJDEStructureModel("after full build where advice is applying");
// should be 4 relationship entries
// In inc1 the first advised line is 'commented out'
alter("P4","inc1");
build("P4");
checkWasntFullBuild();
dumpAJDEStructureModel("after inc build where first advised line is gone");
// should now be 2 relationship entries
// This will be the line 6 entry in C.java
IProgramElement codeElement = findCode(checkForNode("pack","C",true));
// This will be the line 7 entry in A.java
IProgramElement advice = findAdvice(checkForNode("pack","A",true));
IRelationshipMap asmRelMap = AsmManager.getDefault().getRelationshipMap();
assertEquals("There should be two relationships in the relationship map",
2,asmRelMap.getEntries().size());
for (Iterator iter = asmRelMap.getEntries().iterator(); iter.hasNext();) {
String sourceOfRelationship = (String) iter.next();
IProgramElement ipe = AsmManager.getDefault().getHierarchy()
.findElementForHandle(sourceOfRelationship);
assertNotNull("expected to find IProgramElement with handle "
+ sourceOfRelationship + " but didn't",ipe);
if (ipe.getKind().equals(IProgramElement.Kind.ADVICE)) {
assertEquals("expected source of relationship to be " +
advice.toString() + " but found " +
ipe.toString(),advice,ipe);
} else if (ipe.getKind().equals(IProgramElement.Kind.CODE)) {
assertEquals("expected source of relationship to be " +
codeElement.toString() + " but found " +
ipe.toString(),codeElement,ipe);
} else {
fail("found unexpected relationship source " + ipe
+ " with kind " + ipe.getKind()+" when looking up handle: "+sourceOfRelationship);
}
List relationships = asmRelMap.get(ipe);
assertNotNull("expected " + ipe.getName() +" to have some " +
"relationships",relationships);
for (Iterator iterator = relationships.iterator(); iterator.hasNext();) {
Relationship rel = (Relationship) iterator.next();
List targets = rel.getTargets();
for (Iterator iterator2 = targets.iterator(); iterator2.hasNext();) {
String t = (String) iterator2.next();
IProgramElement link = AsmManager.getDefault().getHierarchy().findElementForHandle(t);
if (ipe.getKind().equals(IProgramElement.Kind.ADVICE)) {
assertEquals("expected target of relationship to be " +
codeElement.toString() + " but found " +
link.toString(),codeElement,link);
} else if (ipe.getKind().equals(IProgramElement.Kind.CODE)) {
assertEquals("expected target of relationship to be " +
advice.toString() + " but found " +
link.toString(),advice,link);
} else {
fail("found unexpected relationship source " + ipe.getName()
+ " with kind " + ipe.getKind());
}
}
}
}
} finally {
AsmHierarchyBuilder.shouldAddUsesPointcut=true;
configureBuildStructureModel(false);
}
}
// Compile a single simple project
public void testTheBasics() {
initialiseProject("P1");
build("P1"); // This first build will be batch
build("P1");
checkWasntFullBuild();
checkCompileWeaveCount(0,0);
}
// source code doesnt matter, we are checking invalid path handling
public void testInvalidAspectpath_pr121395() {
initialiseProject("P1");
File f = new File("foo.jar");
Set s = new HashSet();
s.add(f);
configureAspectPath(s);
build("P1"); // This first build will be batch
checkForError("invalid aspectpath entry");
}
// Make simple changes to a project, adding a class
public void testSimpleChanges() {
initialiseProject("P1");
build("P1"); // This first build will be batch
alter("P1","inc1"); // adds a single class
build("P1");
checkCompileWeaveCount(1,-1);
build("P1");
checkCompileWeaveCount(0,-1);
}
// Make simple changes to a project, adding a class and an aspect
public void testAddingAnAspect() {
initialiseProject("P1");
build("P1"); // build 1, weave 1
alter("P1","inc1"); // adds a class
alter("P1","inc2"); // adds an aspect
build("P1"); // build 1,
long timeTakenForFullBuildAndWeave = getTimeTakenForBuild();
checkWasFullBuild(); // it *will* be a full build under the new
// "back-to-the-source strategy
checkCompileWeaveCount(5,3); // we compile X and A (the delta) find out that
// an aspect has changed, go back to the source
// and compile X,A,C, then weave them all.
build("P1");
long timeTakenForSimpleIncBuild = getTimeTakenForBuild();
// I don't think this test will have timing issues as the times should be *RADICALLY* different
// On my config, first build time is 2093ms and the second is 30ms
assertTrue("Should not take longer for the trivial incremental build! first="+timeTakenForFullBuildAndWeave+
"ms second="+timeTakenForSimpleIncBuild+"ms",
timeTakenForSimpleIncBuild<timeTakenForFullBuildAndWeave);
}
public void testBuildingTwoProjectsInTurns() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
build("P2");
build("P1");
checkWasntFullBuild();
build("P2");
checkWasntFullBuild();
}
/**
* In order for this next test to run, I had to move the weaver/world pair we keep in the
* AjBuildManager instance down into the state object - this makes perfect sense - otherwise
* when reusing the state for another project we'd not be switching to the right weaver/world
* for that project.
*/
public void testBuildingTwoProjectsMakingSmallChanges() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
build("P2");
build("P1");
checkWasntFullBuild();
build("P2");
checkWasntFullBuild();
alter("P1","inc1"); // adds a class
alter("P1","inc2"); // adds an aspect
build("P1");
checkWasFullBuild(); // adding an aspect makes us go back to the source
}
public void testPr134371() {
initialiseProject("PR134371");
build("PR134371");
alter("PR134371","inc1");
build("PR134371");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
}
/**
* Setup up two simple projects and build them in turn - check the
* structure model is right after each build
*/
public void testBuildingTwoProjectsAndVerifyingModel() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
}
// Setup up two simple projects and build them in turn - check the
// structure model is right after each build
public void testBuildingTwoProjectsAndVerifyingStuff() {
configureBuildStructureModel(true);
initialiseProject("P1");
initialiseProject("P2");
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
build("P1");
checkForNode("pkg","C",true);
build("P2");
checkForNode("pkg","C",false);
}
/**
* Complex. Here we are testing that a state object records structural changes since
* the last full build correctly. We build a simple project from scratch - this will
* be a full build and so the structural changes since last build count should be 0.
* We then alter a class, adding a new method and check structural changes is 1.
*/
public void testStateManagement1() {
File binDirectoryForP1 = new File(getFile("P1","bin"));
initialiseProject("P1");
build("P1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1);
assertTrue("There should be a state object for project P1",ajs!=null);
assertTrue("Should be no structural changes as it was a full build but found: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("P1","inc3"); // adds a method to the class C.java
build("P1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin")));
assertTrue("There should be state for project P1",ajs!=null);
checkWasntFullBuild();
assertTrue("Should be one structural changes as it was a full build but found: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==1);
}
/**
* Complex. Here we are testing that a state object records structural changes since
* the last full build correctly. We build a simple project from scratch - this will
* be a full build and so the structural changes since last build count should be 0.
* We then alter a class, changing body of a method, not the structure and
* check struc changes is still 0.
*/
public void testStateManagement2() {
File binDirectoryForP1 = new File(getFile("P1","bin"));
initialiseProject("P1");
alter("P1","inc3"); // need this change in here so 'inc4' can be applied without making
// it a structural change
build("P1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirectoryForP1);
assertTrue("There should be state for project P1",ajs!=null);
assertTrue("Should be no struc changes as its a full build: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("P1","inc4"); // changes body of main() method but does *not* change the structure of C.java
build("P1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("P1","bin")));
assertTrue("There should be state for project P1",ajs!=null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
}
/**
* The C.java file modified in this test has an inner class - this means the inner class
* has a this$0 field and <init>(C) ctor to watch out for when checking for structural changes
*
*/
public void testStateManagement3() {
File binDirForInterproject1 = new File(getFile("interprojectdeps1","bin"));
initialiseProject("interprojectdeps1");
build("interprojectdeps1"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject1);
assertTrue("There should be state for project P1",ajs!=null);
assertTrue("Should be no struc changes as its a full build: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("interprojectdeps1","inc1"); // adds a space to C.java
build("interprojectdeps1");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps1","bin")));
assertTrue("There should be state for project interprojectdeps1",ajs!=null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
}
/**
* The C.java file modified in this test has an inner class - which has two ctors - this checks
* how they are mangled with an instance of C.
*
*/
public void testStateManagement4() {
File binDirForInterproject2 = new File(getFile("interprojectdeps2","bin"));
initialiseProject("interprojectdeps2");
build("interprojectdeps2"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject2);
assertTrue("There should be state for project interprojectdeps2",ajs!=null);
assertTrue("Should be no struc changes as its a full build: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("interprojectdeps2","inc1"); // minor change to C.java
build("interprojectdeps2");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps2","bin")));
assertTrue("There should be state for project interprojectdeps1",ajs!=null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
}
/**
* The C.java file modified in this test has an inner class - it has two ctors but
* also a reference to C.this in it - which will give rise to an accessor being
* created in C
*
*/
public void testStateManagement5() {
File binDirForInterproject3 = new File(getFile("interprojectdeps3","bin"));
initialiseProject("interprojectdeps3");
build("interprojectdeps3"); // full build
AjState ajs = IncrementalStateManager.findStateManagingOutputLocation(binDirForInterproject3);
assertTrue("There should be state for project interprojectdeps3",ajs!=null);
assertTrue("Should be no struc changes as its a full build: "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
alter("interprojectdeps3","inc1"); // minor change to C.java
build("interprojectdeps3");
checkWasntFullBuild();
ajs = IncrementalStateManager.findStateManagingOutputLocation(new File(getFile("interprojectdeps3","bin")));
assertTrue("There should be state for project interprojectdeps1",ajs!=null);
checkWasntFullBuild();
assertTrue("Shouldn't be any structural changes but there were "+
ajs.getNumberOfStructuralChangesSinceLastFullBuild(),
ajs.getNumberOfStructuralChangesSinceLastFullBuild()==0);
}
/**
* Now the most complex test. Create a dependancy between two projects. Building
* one may affect whether the other does an incremental or full build. The
* structural information recorded in the state object should be getting used
* to control whether a full build is necessary...
*/
public void testBuildingDependantProjects() {
initialiseProject("P1");
initialiseProject("P2");
configureNewProjectDependency("P2","P1");
build("P1");
build("P2"); // now everything is consistent and compiled
alter("P1","inc1"); // adds a second class
build("P1");
build("P2"); // although a second class was added - P2 can't be using it, so we don't full build here :)
checkWasntFullBuild();
alter("P1","inc3"); // structurally changes one of the classes
build("P1");
build("P2"); // build notices the structural change
checkWasFullBuild();
alter("P1","inc4");
build("P1");
build("P2"); // build sees a change but works out its not structural
checkWasntFullBuild();
}
public void testPr85132() {
initialiseProject("PR85132");
build("PR85132");
alter("PR85132","inc1");
build("PR85132");
}
// parameterization of generic aspects
public void testPr125405() {
initialiseProject("PR125405");
build("PR125405");
checkCompileWeaveCount(1,1);
alter("PR125405","inc1");
build("PR125405");
// "only abstract aspects can have type parameters"
checkForError("only abstract aspects can have type parameters");
alter("PR125405","inc2");
build("PR125405");
checkCompileWeaveCount(1,1);
assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0);
}
public void testPr128618() {
initialiseProject("PR128618_1");
initialiseProject("PR128618_2");
configureNewProjectDependency("PR128618_2","PR128618_1");
assertTrue("there should be no warning messages before we start",
MyTaskListManager.getWarningMessages().isEmpty());
build("PR128618_1");
build("PR128618_2");
List warnings = MyTaskListManager.getWarningMessages();
assertTrue("Should be one warning, but there are #"+warnings.size(),warnings.size()==1);
IMessage msg = (IMessage)(MyTaskListManager.getWarningMessages().get(0));
assertEquals("warning should be against the FFDC.aj resource","FFDC.aj",msg.getSourceLocation().getSourceFile().getName());
alter("PR128618_2","inc1");
build("PR128618_2");
checkWasntFullBuild();
IMessage msg2 = (IMessage)(MyTaskListManager.getWarningMessages().get(0));
assertEquals("warning should be against the FFDC.aj resource","FFDC.aj",msg2.getSourceLocation().getSourceFile().getName());
assertFalse("a new warning message should have been generated", msg.equals(msg2));
}
public void testPr92837() {
initialiseProject("PR92837");
build("PR92837");
alter("PR92837","inc1");
build("PR92837");
}
public void testPr119570() {
initialiseProject("PR119570");
build("PR119570");
assertTrue("Should be no errors, but got "+MyTaskListManager.getErrorMessages(),MyTaskListManager.getErrorMessages().size()==0);
}
public void testPr119570_2() {
initialiseProject("PR119570_2");
build("PR119570_2");
List l = MyTaskListManager.getWarningMessages();
assertTrue("Should be no warnings, but got "+l,l.size()==0);
}
// If you fiddle with the compiler options - you must manually reset the options at the end of the test
public void testPr117209() {
try {
initialiseProject("pr117209");
configureNonStandardCompileOptions("-proceedOnError");
build("pr117209");
checkCompileWeaveCount(6,6);
} finally {
MyBuildOptionsAdapter.reset();
}
}
public void testPr114875() {
initialiseProject("pr114875");
build("pr114875");
alter("pr114875","inc1");
build("pr114875");
checkWasFullBuild();
alter("pr114875","inc2");
build("pr114875");
checkWasFullBuild(); // back to the source for an aspect change
}
public void testPr117882() {
// AjdeInteractionTestbed.VERBOSE=true;
// AjdeInteractionTestbed.configureBuildStructureModel(true);
initialiseProject("PR117882");
build("PR117882");
checkWasFullBuild();
alter("PR117882","inc1");
build("PR117882");
checkWasFullBuild(); // back to the source for an aspect
// AjdeInteractionTestbed.VERBOSE=false;
// AjdeInteractionTestbed.configureBuildStructureModel(false);
}
public void testPr117882_2() {
// AjdeInteractionTestbed.VERBOSE=true;
// AjdeInteractionTestbed.configureBuildStructureModel(true);
initialiseProject("PR117882_2");
build("PR117882_2");
checkWasFullBuild();
alter("PR117882_2","inc1");
build("PR117882_2");
checkWasFullBuild(); // back to the source...
//checkCompileWeaveCount(1,4);
//fullBuild("PR117882_2");
//checkWasFullBuild();
// AjdeInteractionTestbed.VERBOSE=false;
// AjdeInteractionTestbed.configureBuildStructureModel(false);
}
public void testPr115251() {
//AjdeInteractionTestbed.VERBOSE=true;
initialiseProject("PR115251");
build("PR115251");
checkWasFullBuild();
alter("PR115251","inc1");
build("PR115251");
checkWasFullBuild(); // back to the source
}
// public void testPr124399() {
// AjdeInteractionTestbed.VERBOSE=true;
// configureBuildStructureModel(true);
// initialiseProject("PR124399");
// build("PR124399");
// checkWasFullBuild();
// alter("PR124399","inc1");
// build("PR124399");
// checkWasntFullBuild();
// }
public void testPr121384() {
// AjdeInteractionTestbed.VERBOSE=true;
// AsmManager.setReporting("c:/foo.txt",true,true,true,false);
MyBuildOptionsAdapter.setNonStandardOptions("-showWeaveInfo");
configureBuildStructureModel(true);
initialiseProject("pr121384");
build("pr121384");
checkWasFullBuild();
alter("pr121384","inc1");
build("pr121384");
checkWasntFullBuild();
}
/* public void testPr111779() {
super.VERBOSE=true;
initialiseProject("PR111779");
build("PR111779");
alter("PR111779","inc1");
build("PR111779");
}
*/
public void testPr93310_1() {
initialiseProject("PR93310_1");
build("PR93310_1");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_1" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java";
(new File(fileC2)).delete();
alter("PR93310_1","inc1");
build("PR93310_1");
checkWasFullBuild();
int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size();
assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1);
String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0);
assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java"));
}
public void testPr93310_2() {
initialiseProject("PR93310_2");
build("PR93310_2");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR93310_2" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "C2.java";
(new File(fileC2)).delete();
alter("PR93310_2","inc1");
build("PR93310_2");
checkWasFullBuild();
int l = AjdeInteractionTestbed.MyStateListener.detectedDeletions.size();
assertTrue("Expected one deleted file to be noticed, but detected: "+l,l==1);
String name = (String)AjdeInteractionTestbed.MyStateListener.detectedDeletions.get(0);
assertTrue("Should end with C2.java but is "+name,name.endsWith("C2.java"));
}
// Stage1: Compile two files, pack.A and pack.A1 - A1 sets a protected field in A.
// Stage2: make the field private in class A > gives compile error
// Stage3: Add a new aspect whilst there is a compile error !
public void testPr113531() {
initialiseProject("PR113531");
build("PR113531");
assertFalse("build should have compiled ok",
MyTaskListManager.hasErrorMessages());
alter("PR113531","inc1");
build("PR113531");
assertEquals("error message should be 'foo cannot be resolved' ",
"foo cannot be resolved",
((IMessage)MyTaskListManager.getErrorMessages().get(0))
.getMessage());
alter("PR113531","inc2");
build("PR113531");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
assertEquals("error message should be 'foo cannot be resolved' ",
"foo cannot be resolved",
((IMessage)MyTaskListManager.getErrorMessages().get(0))
.getMessage());
}
// Stage 1: Compile the 4 files, pack.A2 extends pack.A1 (aspects) where
// A2 uses a protected field in A1 and pack.C2 extends pack.C1 (classes)
// where C2 uses a protected field in C1
// Stage 2: make the field private in class C1 ==> compile errors in C2
// Stage 3: make the field private in aspect A1 whilst there's the compile
// error.
// There shouldn't be a BCExcpetion saying can't find delegate for pack.C2
public void testPr119882() {
initialiseProject("PR119882");
build("PR119882");
assertFalse("build should have compiled ok",MyTaskListManager.hasErrorMessages());
alter("PR119882","inc1");
build("PR119882");
//fullBuild("PR119882");
List errors = MyTaskListManager.getErrorMessages();
assertTrue("Should be at least one error, but got none",errors.size()==1);
assertEquals("error message should be 'i cannot be resolved' ",
"i cannot be resolved",
((IMessage)errors.get(0))
.getMessage());
alter("PR119882","inc2");
build("PR119882");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
assertEquals("error message should be 'i cannot be resolved' ",
"i cannot be resolved",
((IMessage)errors.get(0))
.getMessage());
}
public void testPr112736() {
initialiseProject("PR112736");
build("PR112736");
checkWasFullBuild();
String fileC2 = getWorkingDir().getAbsolutePath() + File.separatorChar + "PR112736" + File.separatorChar + "src" + File.separatorChar + "pack" + File.separatorChar + "A.java";
(new File(fileC2)).delete();
alter("PR112736","inc1");
build("PR112736");
checkWasFullBuild();
}
/**
* We have problems with multiple rewrites of a pointcut across incremental builds.
*/
public void testPr113257() {
initialiseProject("PR113257");
build("PR113257");
alter("PR113257","inc1");
build("PR113257");
checkWasFullBuild(); // back to the source
alter("PR113257","inc1");
build("PR113257");
}
public void testPr123612() {
initialiseProject("PR123612");
build("PR123612");
alter("PR123612","inc1");
build("PR123612");
checkWasFullBuild(); // back to the source
}
public void testPr128655() {
configureNonStandardCompileOptions("-showWeaveInfo");
initialiseProject("pr128655");
build("pr128655");
List firstBuildMessages = MyTaskListManager.getWeavingMessages();
assertTrue("Should be at least one message about the dec @type, but there were none",firstBuildMessages.size()>0);
alter("pr128655","inc1");
build("pr128655");
checkWasntFullBuild(); // back to the source
List secondBuildMessages = MyTaskListManager.getWeavingMessages();
// check they are the same
for (int i = 0; i < firstBuildMessages.size(); i++) {
IMessage m1 = (IMessage)firstBuildMessages.get(i);
IMessage m2 = (IMessage)secondBuildMessages.get(i);
if (!m1.toString().equals(m2.toString())) {
System.err.println("Message during first build was: "+m1);
System.err.println("Message during second build was: "+m1);
fail("The two messages should be the same, but are not: \n"+m1+"!="+m2);
}
}
}
// Similar to above, but now the annotation is in the default package
public void testPr128655_2() {
configureNonStandardCompileOptions("-showWeaveInfo");
initialiseProject("pr128655_2");
build("pr128655_2");
List firstBuildMessages = MyTaskListManager.getWeavingMessages();
assertTrue("Should be at least one message about the dec @type, but there were none",firstBuildMessages.size()>0);
alter("pr128655_2","inc1");
build("pr128655_2");
checkWasntFullBuild(); // back to the source
List secondBuildMessages = MyTaskListManager.getWeavingMessages();
// check they are the same
for (int i = 0; i < firstBuildMessages.size(); i++) {
IMessage m1 = (IMessage)firstBuildMessages.get(i);
IMessage m2 = (IMessage)secondBuildMessages.get(i);
if (!m1.toString().equals(m2.toString())) {
System.err.println("Message during first build was: "+m1);
System.err.println("Message during second build was: "+m1);
fail("The two messages should be the same, but are not: \n"+m1+"!="+m2);
}
}
}
// test for comment #31 - NPE
public void testPr129163() {
configureBuildStructureModel(true);
initialiseProject("PR129613");
build("PR129613");
alter("PR129613","inc1");
build("PR129613");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
assertEquals("warning message should be 'no match for this type name: File [Xlint:invalidAbsoluteTypeName]' ",
"no match for this type name: File [Xlint:invalidAbsoluteTypeName]",
((IMessage)MyTaskListManager.getWarningMessages().get(0))
.getMessage());
configureBuildStructureModel(false);
}
// test for comment #0 - adding a comment to a class file shouldn't
// cause us to go back to source and recompile everything. To force this
// to behave like AJDT we need to include the aspect in 'inc1' so that
// when AjState looks at its timestamp it thinks the aspect has been modified.
// The logic within CrosscuttingMembers should then work out correctly
// that there haven't really been any changes within the aspect and so
// we shouldn't go back to source.
public void testPr129163_2() {
// want to behave like AJDT
configureBuildStructureModel(true);
initialiseProject("pr129163_2");
build("pr129163_2");
checkWasFullBuild();
alter("pr129163_2","inc1");
build("pr129163_2");
checkWasntFullBuild(); // shouldn't be a full build because the
// aspect hasn't changed
configureBuildStructureModel(false);
}
// test for comment #6 - simulates AJDT core builder test testBug99133a -
// changing the contents of a method within a class shouldn't force a
// full build of a dependant project. To force this to behave like AJDT
// 'inc1' of the dependant project should just be a copy of 'base' so that
// AjState thinks somethings changed within the dependant project and
// we do a build. Similarly, 'inc1' of the project depended on should
// include the aspect even though nothing's changed within it. This causes
// AjState to think that the aspect has changed. Together its then up to
// logic within CrosscuttingMembers and various equals methods to decide
// correctly that we don't have to go back to source.
public void testPr129163_3() {
configureBuildStructureModel(true);
initialiseProject("PR129163_4");
build("PR129163_4");
checkWasFullBuild(); // should be a full build because initializing project
initialiseProject("PR129163_3");
configureNewProjectDependency("PR129163_3","PR129163_4");
build("PR129163_3");
checkWasFullBuild(); // should be a full build because initializing project
alter("PR129163_4","inc1");
build("PR129163_4");
checkWasntFullBuild(); // should be an incremental build because although
// "inc1" includes the aspect A1.aj, it actually hasn't
// changed so we shouldn't go back to source
alter("PR129163_3","inc1");
build("PR129163_3");
checkWasntFullBuild(); // should be an incremental build because nothing has
// changed within the class and no aspects have changed
// within the running of the test
configureBuildStructureModel(false);
}
public void testPr131505() {
configureNonStandardCompileOptions("-outxml");
initialiseProject("PR131505");
build("PR131505");
checkWasFullBuild();
// aop.xml file shouldn't contain any aspects
checkXMLAspectCount("PR131505","",0);
// add a new aspect A which should be included in the aop.xml file
alter("PR131505","inc1");
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",1);
checkXMLAspectCount("PR131505","A",1);
// make changes to the class file which shouldn't affect the contents
// of the aop.xml file
alter("PR131505","inc2");
build("PR131505");
checkWasntFullBuild();
checkXMLAspectCount("PR131505","",1);
checkXMLAspectCount("PR131505","A",1);
// add another new aspect A1 which should also be included in the aop.xml file
// ...there should be no duplicate entries in the file
alter("PR131505","inc3");
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",2);
checkXMLAspectCount("PR131505","A1",1);
checkXMLAspectCount("PR131505","A",1);
// delete aspect A1 which meanss that aop.xml file should only contain A
File a1 = new File(getWorkingDir().getAbsolutePath()
+ File.separatorChar + "PR131505" + File.separatorChar + "A1.aj");
a1.delete();
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",1);
checkXMLAspectCount("PR131505","A1",0);
checkXMLAspectCount("PR131505","A",1);
// add another aspect called A which is in a different package, both A
// and pkg.A should be included in the aop.xml file
alter("PR131505","inc4");
build("PR131505");
checkWasFullBuild();
checkXMLAspectCount("PR131505","",2);
checkXMLAspectCount("PR131505","A",1);
checkXMLAspectCount("PR131505","pkg.A",1);
}
public void testPr136585() {
initialiseProject("PR136585");
build("PR136585");
alter("PR136585","inc1");
build("PR136585");
assertTrue("There should be no errors reported:\n"+MyTaskListManager.getErrorMessages(),
MyTaskListManager.getErrorMessages().isEmpty());
}
public void testPr133532() {
initialiseProject("PR133532");
build("PR133532");
alter("PR133532","inc1");
build("PR133532");
alter("PR133532","inc2");
build("PR133532");
assertTrue("There should be no errors reported:\n"+MyTaskListManager.getErrorMessages(),
MyTaskListManager.getErrorMessages().isEmpty());
}
public void testPr133532_2() {
initialiseProject("pr133532_2");
build("pr133532_2");
alter("pr133532_2","inc2");
build("pr133532_2");
assertTrue("There should be no errors reported:\n"+MyTaskListManager.getErrorMessages(),
MyTaskListManager.getErrorMessages().isEmpty());
String decisions = AjdeInteractionTestbed.MyStateListener.getDecisions();
String expect="Need to recompile 'A.aj'";
assertTrue("Couldn't find build decision: '"+expect+"' in the list of decisions made:\n"+decisions,
decisions.indexOf(expect)!=-1);
}
public void testPr134541() {
initialiseProject("PR134541");
build("PR134541");
assertEquals("[Xlint:adviceDidNotMatch] should be associated with line 5",5,
((IMessage)MyTaskListManager.getWarningMessages().get(0)).getSourceLocation().getLine());
alter("PR134541","inc1");
build("PR134541");
if (World.compareLocations)
checkWasFullBuild(); // the line number has changed... but nothing structural about the code
else
checkWasntFullBuild(); // the line number has changed... but nothing structural about the code
assertEquals("[Xlint:adviceDidNotMatch] should now be associated with line 7",7,
((IMessage)MyTaskListManager.getWarningMessages().get(0)).getSourceLocation().getLine());
}
// 134471 related tests perform incremental compilation and verify features of the structure model post compile
public void testPr134471_IncrementalCompilationAndModelUpdates() {
try {
AsmHierarchyBuilder.shouldAddUsesPointcut=false;
configureBuildStructureModel(true);
configureNonStandardCompileOptions("-showWeaveInfo -emacssym");
// Step1. Build the code, simple advice from aspect A onto class C
initialiseProject("PR134471");
build("PR134471");
// Step2. Quick check that the advice points to something...
IProgramElement nodeForTypeA = checkForNode("pkg","A",true);
IProgramElement nodeForAdvice = findAdvice(nodeForTypeA);
List relatedElements = getRelatedElements(nodeForAdvice,1);
// Step3. Check the advice applying at the first 'code' join point in pkg.C is from aspect pkg.A, line 7
IProgramElement programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true)));
int line = programElement.getSourceLocation().getLine();
assertTrue("advice should be at line 7 - but is at line "+line,line==7);
// Step4. Simulate the aspect being saved but with no change at all in it
alter("PR134471","inc1");
build("PR134471");
// Step5. Quick check that the advice points to something...
nodeForTypeA = checkForNode("pkg","A",true);
nodeForAdvice = findAdvice(nodeForTypeA);
relatedElements = getRelatedElements(nodeForAdvice,1);
// Step6. Check the advice applying at the first 'code' join point in pkg.C is from aspect pkg.A, line 7
programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true)));
line = programElement.getSourceLocation().getLine();
assertTrue("advice should be at line 7 - but is at line "+line,line==7);
} finally {
AsmHierarchyBuilder.shouldAddUsesPointcut=true;
}
}
// now the advice moves down a few lines - hopefully the model will notice... see discussion in 134471
public void testPr134471_MovingAdvice() {
configureBuildStructureModel(true);
configureNonStandardCompileOptions("-showWeaveInfo -emacssym");
// Step1. build the project
initialiseProject("PR134471_2");
build("PR134471_2");
// Step2. confirm advice is from correct location
IProgramElement programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true)));
int line = programElement.getSourceLocation().getLine();
assertTrue("advice should be at line 7 - but is at line "+line,line==7);
// Step3. No structural change to the aspect but the advice has moved down a few lines... (change in source location)
alter("PR134471_2","inc1");
build("PR134471_2");
checkWasFullBuild(); // this is true whilst we consider sourcelocation in the type/shadow munger equals() method - have to until the handles are independent of location
// Step4. Check we have correctly realised the advice moved to line 11
programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true)));
line = programElement.getSourceLocation().getLine();
assertTrue("advice should be at line 11 - but is at line "+line,line==11);
}
public void testAddingAndRemovingDecwWithStructureModel() {
configureBuildStructureModel(true);
initialiseProject("P3");
build("P3");
alter("P3","inc1");
build("P3");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
alter("P3","inc2");
build("P3");
assertTrue("There should be no exceptions handled:\n"+MyErrorHandler.getErrorMessages(),
MyErrorHandler.getErrorMessages().isEmpty());
configureBuildStructureModel(false);
}
// same as first test with an extra stage that asks for C to be recompiled, it should still be advised...
public void testPr134471_IncrementallyRecompilingTheAffectedClass() {
try {
AsmHierarchyBuilder.shouldAddUsesPointcut=false;
configureBuildStructureModel(true);
configureNonStandardCompileOptions("-showWeaveInfo -emacssym");
// Step1. build the project
initialiseProject("PR134471");
build("PR134471");
// Step2. confirm advice is from correct location
IProgramElement programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true)));
int line = programElement.getSourceLocation().getLine();
assertTrue("advice should be at line 7 - but is at line "+line,line==7);
// Step3. No change to the aspect at all
alter("PR134471","inc1");
build("PR134471");
// Step4. Quick check that the advice points to something...
IProgramElement nodeForTypeA = checkForNode("pkg","A",true);
IProgramElement nodeForAdvice = findAdvice(nodeForTypeA);
List relatedElements = getRelatedElements(nodeForAdvice,1);
// Step5. No change to the file C but it should still be advised afterwards
alter("PR134471","inc2");
build("PR134471");
checkWasntFullBuild();
// Step6. confirm advice is from correct location
programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true)));
line = programElement.getSourceLocation().getLine();
assertTrue("advice should be at line 7 - but is at line "+line,line==7);
} finally {
AsmHierarchyBuilder.shouldAddUsesPointcut=true;
}
}
// similar to previous test but with 'declare warning' as well as advice
public void testPr134471_IncrementallyRecompilingAspectContainingDeclare() {
configureBuildStructureModel(true);
configureNonStandardCompileOptions("-showWeaveInfo -emacssym");
// Step1. build the project
initialiseProject("PR134471_3");
build("PR134471_3");
checkWasFullBuild();
// Step2. confirm declare warning is from correct location, decw matches line 7 in pkg.C
IProgramElement programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true),7));
int line = programElement.getSourceLocation().getLine();
assertTrue("declare warning should be at line 10 - but is at line "+line,line==10);
// Step3. confirm advice is from correct location, advice matches line 6 in pkg.C
programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true),6));
line = programElement.getSourceLocation().getLine();
assertTrue("advice should be at line 7 - but is at line "+line,line==7);
// Step4. Move declare warning in the aspect
alter("PR134471_3","inc1");
build("PR134471_3");
checkWasFullBuild();
// Step5. confirm declare warning is from correct location, decw (now at line 12) in pkg.A matches line 7 in pkg.C
programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true),7));
line = programElement.getSourceLocation().getLine();
assertTrue("declare warning should be at line 12 - but is at line "+line,line==12);
// Step6. Now just simulate 'resave' of the aspect, nothing has changed
alter("PR134471_3","inc2");
build("PR134471_3");
checkWasntFullBuild();
// Step7. confirm declare warning is from correct location, decw (now at line 12) in pkg.A matches line 7 in pkg.C
programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true),7));
line = programElement.getSourceLocation().getLine();
assertTrue("declare warning should be at line 12 - but is at line "+line,line==12);
}
// similar to previous test but with 'declare warning' as well as advice
public void testPr134471_IncrementallyRecompilingTheClassAffectedByDeclare() {
configureBuildStructureModel(true);
configureNonStandardCompileOptions("-showWeaveInfo -emacssym");
// Step1. build the project
initialiseProject("PR134471_3");
build("PR134471_3");
checkWasFullBuild();
// Step2. confirm declare warning is from correct location, decw matches line 7 in pkg.C
IProgramElement programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true),7));
int line = programElement.getSourceLocation().getLine();
assertTrue("declare warning should be at line 10 - but is at line "+line,line==10);
// Step3. confirm advice is from correct location, advice matches line 6 in pkg.C
programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true),6));
line = programElement.getSourceLocation().getLine();
assertTrue("advice should be at line 7 - but is at line "+line,line==7);
// Step4. Move declare warning in the aspect
alter("PR134471_3","inc1");
build("PR134471_3");
checkWasFullBuild();
// Step5. confirm declare warning is from correct location, decw (now at line 12) in pkg.A matches line 7 in pkg.C
programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true),7));
line = programElement.getSourceLocation().getLine();
assertTrue("declare warning should be at line 12 - but is at line "+line,line==12);
// Step6. Now just simulate 'resave' of the aspect, nothing has changed
alter("PR134471_3","inc2");
build("PR134471_3");
checkWasntFullBuild();
// Step7. confirm declare warning is from correct location, decw (now at line 12) in pkg.A matches line 7 in pkg.C
programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true),7));
line = programElement.getSourceLocation().getLine();
assertTrue("declare warning should be at line 12 - but is at line "+line,line==12);
// Step8. Now just simulate resave of the pkg.C type - no change at all... are relationships gonna be repaired OK?
alter("PR134471_3","inc3");
build("PR134471_3");
checkWasntFullBuild();
// Step9. confirm declare warning is from correct location, decw (now at line 12) in pkg.A matches line 7 in pkg.C
programElement = getFirstRelatedElement(findCode(checkForNode("pkg","C",true),7));
line = programElement.getSourceLocation().getLine();
assertTrue("declare warning should be at line 12 - but is at line "+line,line==12);
}
// --- helper code ---
/**
* Retrieve program elements related to this one regardless of the relationship. A JUnit assertion is
* made that the number that the 'expected' number are found.
*
* @param programElement Program element whose related elements are to be found
* @param expected the number of expected related elements
*/
private List/*IProgramElement*/ getRelatedElements(IProgramElement programElement,int expected) {
List relatedElements = getRelatedElements(programElement);
StringBuffer debugString = new StringBuffer();
if (relatedElements!=null) {
for (Iterator iter = relatedElements.iterator(); iter.hasNext();) {
String element = (String) iter.next();
debugString.append(AsmManager.getDefault().getHierarchy().findElementForHandle(element).toLabelString()).append("\n");
}
}
assertTrue("Should be "+expected+" element"+(expected>1?"s":"")+" related to this one '"+programElement+
"' but found :\n "+debugString,relatedElements!=null && relatedElements.size()==1);
return relatedElements;
}
private IProgramElement getFirstRelatedElement(IProgramElement programElement) {
List rels = getRelatedElements(programElement,1);
return AsmManager.getDefault().getHierarchy().findElementForHandle((String)rels.get(0));
}
private List/*IProgramElement*/ getRelatedElements(IProgramElement advice) {
List output = null;
IRelationshipMap map = AsmManager.getDefault().getRelationshipMap();
List/*IRelationship*/ rels = (List)map.get(advice);
if (rels==null) fail("Did not find any related elements!");
for (Iterator iter = rels.iterator(); iter.hasNext();) {
IRelationship element = (IRelationship) iter.next();
List/*String*/ targets = element.getTargets();
if (output==null) output = new ArrayList();
output.addAll(targets);
}
return output;
}
private IProgramElement findAdvice(IProgramElement ipe) {
return findAdvice(ipe,1);
}
private IProgramElement findAdvice(IProgramElement ipe,int whichOne) {
if (ipe.getKind()==IProgramElement.Kind.ADVICE) {
whichOne=whichOne-1;
if (whichOne==0) return ipe;
}
List kids = ipe.getChildren();
for (Iterator iter = kids.iterator(); iter.hasNext();) {
IProgramElement kid = (IProgramElement) iter.next();
IProgramElement found = findAdvice(kid,whichOne);
if (found!=null) return found;
}
return null;
}
/**
* Finds the first 'code' program element below the element supplied - will return null if there aren't any
*/
private IProgramElement findCode(IProgramElement ipe) {
return findCode(ipe,-1);
}
/**
* Searches a hierarchy of program elements for a 'code' element at the specified line number, a line number
* of -1 means just return the first one you find
*/
private IProgramElement findCode(IProgramElement ipe,int linenumber) {
if (ipe.getKind()==IProgramElement.Kind.CODE) {
if (linenumber==-1 || ipe.getSourceLocation().getLine()==linenumber) return ipe;
}
List kids = ipe.getChildren();
for (Iterator iter = kids.iterator(); iter.hasNext();) {
IProgramElement kid = (IProgramElement) iter.next();
IProgramElement found = findCode(kid,linenumber);
if (found!=null) return found;
}
return null;
}
// other possible tests:
// - memory usage (freemem calls?)
// - relationship map
// ---------------------------------------------------------------------------------------------------
/**
* Check we compiled/wove the right number of files, passing '-1' indicates you don't care about
* that number.
*/
private void checkCompileWeaveCount(int expCompile,int expWoven) {
if (expCompile!=-1 && getCompiledFiles().size()!=expCompile)
fail("Expected compilation of "+expCompile+" files but compiled "+getCompiledFiles().size()+
"\n"+printCompiledAndWovenFiles());
if (expWoven!=-1 && getWovenClasses().size()!=expWoven)
fail("Expected weaving of "+expWoven+" files but wove "+getWovenClasses().size()+
"\n"+printCompiledAndWovenFiles());
}
private void checkWasntFullBuild() {
assertTrue("Shouldn't have been a full (batch) build",!wasFullBuild());
}
private void checkWasFullBuild() {
assertTrue("Should have been a full (batch) build",wasFullBuild());
}
private IProgramElement checkForNode(String packageName,String typeName,boolean shouldBeFound) {
IProgramElement ipe = AsmManager.getDefault().getHierarchy().findElementForType(packageName,typeName);
if (shouldBeFound) {
if (ipe==null) printModel();
assertTrue("Should have been able to find '"+packageName+"."+typeName+"' in the asm",ipe!=null);
} else {
if (ipe!=null) printModel();
assertTrue("Should have NOT been able to find '"+packageName+"."+typeName+"' in the asm",ipe==null);
}
return ipe;
}
private void printModel() {
try {
AsmManager.dumptree(AsmManager.getDefault().getHierarchy().getRoot(),0);
} catch (IOException e) {
e.printStackTrace();
}
}
public void build(String projectName) {
constructUpToDateLstFile(projectName,"build.lst");
build(projectName,"build.lst");
if (AjdeInteractionTestbed.VERBOSE) printBuildReport();
}
public void fullBuild(String projectName) {
constructUpToDateLstFile(projectName,"build.lst");
fullBuild(projectName,"build.lst");
if (AjdeInteractionTestbed.VERBOSE) printBuildReport();
}
private void constructUpToDateLstFile(String pname,String configname) {
File projectBase = new File(sandboxDir,pname);
File toConstruct = new File(projectBase,configname);
List filesForCompilation = new ArrayList();
collectUpFiles(projectBase,projectBase,filesForCompilation);
try {
FileOutputStream fos = new FileOutputStream(toConstruct);
DataOutputStream dos = new DataOutputStream(fos);
for (Iterator iter = filesForCompilation.iterator(); iter.hasNext();) {
String file = (String) iter.next();
dos.writeBytes(file+"\n");
}
dos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void checkForError(String anError) {
List messages = MyTaskListManager.getErrorMessages();
for (Iterator iter = messages.iterator(); iter.hasNext();) {
IMessage element = (IMessage) iter.next();
if (element.getMessage().indexOf(anError)!=-1) return;
}
fail("Didn't find the error message:\n'"+anError+"'.\nErrors that occurred:\n"+MyTaskListManager.getErrorMessages());
}
private void collectUpFiles(File location,File base,List collectionPoint) {
String contents[] = location.list();
if (contents==null) return;
for (int i = 0; i < contents.length; i++) {
String string = contents[i];
File f = new File(location,string);
if (f.isDirectory()) {
collectUpFiles(f,base,collectionPoint);
} else if (f.isFile() && (f.getName().endsWith(".aj") || f.getName().endsWith(".java"))) {
String fileFound;
try {
fileFound = f.getCanonicalPath();
String toRemove = base.getCanonicalPath();
if (!fileFound.startsWith(toRemove)) throw new RuntimeException("eh? "+fileFound+" "+toRemove);
collectionPoint.add(fileFound.substring(toRemove.length()+1));//+1 captures extra separator
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Fill in the working directory with the project base files,
* from the 'base' folder.
*/
protected void initialiseProject(String p) {
File projectSrc=new File(testdataSrcDir+File.separatorChar+p+File.separatorChar+"base");
File destination=new File(getWorkingDir(),p);
if (!destination.exists()) {destination.mkdir();}
copy(projectSrc,destination);//,false);
}
/*
* Applies an overlay onto the project being tested - copying
* the contents of the specified overlay directory.
*/
private void alter(String projectName,String overlayDirectory) {
File projectSrc =new File(testdataSrcDir+File.separatorChar+projectName+
File.separatorChar+overlayDirectory);
File destination=new File(getWorkingDir(),projectName);
copy(projectSrc,destination);
}
/**
* Copy the contents of some directory to another location - the
* copy is recursive.
*/
private void copy(File from, File to) {
String contents[] = from.list();
if (contents==null) return;
for (int i = 0; i < contents.length; i++) {
String string = contents[i];
File f = new File(from,string);
File t = new File(to,string);
if (f.isDirectory() && !f.getName().startsWith("inc")) {
t.mkdir();
copy(f,t);
} else if (f.isFile()) {
StringBuffer sb = new StringBuffer();
//if (VERBOSE) System.err.println("Copying "+f+" to "+t);
FileUtil.copyFile(f,t,sb);
if (sb.length()!=0) { System.err.println(sb.toString());}
}
}
}
private static void log(String msg) {
if (VERBOSE) System.out.println(msg);
}
/**
* Count the number of times a specified aspectName appears in the default
* aop.xml file and compare with the expected number of occurrences. If just
* want to count the number of aspects mentioned within the file then
* pass "" for the aspectName, otherwise, specify the name of the
* aspect interested in.
*/
private void checkXMLAspectCount(String projectName, String aspectName, int expectedOccurrences) {
int aspectCount = 0;
File aopXML = new File(getWorkingDir().getAbsolutePath()
+ File.separatorChar + projectName + File.separatorChar
+ "bin" + File.separatorChar + "META-INF" + File.separatorChar + "aop.xml");
if (!aopXML.exists()) {
fail("Expected file " + aopXML.getAbsolutePath() + " to exist but it doesn't");
}
try {
BufferedReader reader = new BufferedReader(new FileReader(aopXML));
String line = reader.readLine();
while (line != null) {
if (aspectName.equals("") && line.indexOf("aspect name=\"") != -1) {
aspectCount++;
} else if (line.indexOf("aspect name=\""+aspectName+"\"") != -1) {
aspectCount++;
}
line = reader.readLine();
}
reader.close();
} catch (IOException ie) {
ie.printStackTrace();
}
if (aspectCount != expectedOccurrences) {
fail("Expected aspect " + aspectName + " to appear " + expectedOccurrences + " times" +
" in the aop.xml file but found " + aspectCount + " occurrences");
}
}
private void dumpAJDEStructureModel(String prefix) {
System.out.println("======================================");//$NON-NLS-1$
System.out.println("start of AJDE structure model:"+prefix); //$NON-NLS-1$
IRelationshipMap asmRelMap = AsmManager.getDefault().getRelationshipMap();
for (Iterator iter = asmRelMap.getEntries().iterator(); iter.hasNext();) {
String sourceOfRelationship = (String) iter.next();
IProgramElement ipe = AsmManager.getDefault().getHierarchy()
.findElementForHandle(sourceOfRelationship);
System.err.println("Examining source relationship handle: "+sourceOfRelationship);
List relationships = asmRelMap.get(ipe);
if (relationships != null) {
for (Iterator iterator = relationships.iterator(); iterator.hasNext();) {
Relationship rel = (Relationship) iterator.next();
List targets = rel.getTargets();
for (Iterator iterator2 = targets.iterator(); iterator2.hasNext();) {
String t = (String) iterator2.next();
IProgramElement link = AsmManager.getDefault().getHierarchy().findElementForHandle(t);
System.out.println(""); //$NON-NLS-1$
System.out.println(" sourceOfRelationship " + sourceOfRelationship); //$NON-NLS-1$
System.out.println(" relationship " + rel.getName()); //$NON-NLS-1$
System.out.println(" target " + link.getName()); //$NON-NLS-1$
}
}
}
}
System.out.println("End of AJDE structure model"); //$NON-NLS-1$
System.out.println("======================================");//$NON-NLS-1$
}
}
|
133,117 |
Bug 133117 Lots of warnings with noGuardForLazyTjp
|
When the noGuardForLazyTjp compiler option is set to warning or error and a piece of advice causes this warning to show up, you get one warning for every join point matched by the advice. I think just one would probably be enough...
|
resolved fixed
|
3fa4d24
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-12T15:34:39Z | 2006-03-24T08: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.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
public class Lint {
/* private */ Map kinds = new HashMap();
/* private */ World world;
public final Kind invalidAbsoluteTypeName =
new Kind("invalidAbsoluteTypeName", "no match for this type name: {0}");
public final Kind invalidWildcardTypeName =
new Kind("invalidWildcardTypeName", "no match for this type pattern: {0}");
public final Kind unresolvableMember =
new Kind("unresolvableMember", "can not resolve this member: {0}");
public final Kind typeNotExposedToWeaver =
new Kind("typeNotExposedToWeaver", "this affected type is not exposed to the weaver: {0}");
public final Kind shadowNotInStructure =
new Kind("shadowNotInStructure", "the shadow for this join point is not exposed in the structure model: {0}");
public final Kind unmatchedSuperTypeInCall =
new Kind("unmatchedSuperTypeInCall", "does not match because declaring type is {0}, if match desired use target({1})");
public final Kind unmatchedTargetKind =
new Kind("unmatchedTargetKind", "does not match because annotation {0} has @Target{1}");
public final Kind canNotImplementLazyTjp =
new Kind("canNotImplementLazyTjp", "can not implement lazyTjp on this joinpoint {0} because around advice is used");
public final Kind multipleAdviceStoppingLazyTjp =
new Kind("multipleAdviceStoppingLazyTjp", "can not implement lazyTjp at joinpoint {0} because of advice conflicts, see secondary locations to find conflicting advice");
public final Kind needsSerialVersionUIDField =
new Kind("needsSerialVersionUIDField", "serialVersionUID of type {0} needs to be set because of {1}");
public final Kind serialVersionUIDBroken =
new Kind("brokeSerialVersionCompatibility", "serialVersionUID of type {0} is broken because of added field {1}");
public final Kind noInterfaceCtorJoinpoint =
new Kind("noInterfaceCtorJoinpoint","no interface constructor-execution join point - use {0}+ for implementing classes");
public final Kind noJoinpointsForBridgeMethods =
new Kind("noJoinpointsForBridgeMethods","pointcut did not match on the method call to a bridge method. Bridge methods are generated by the compiler and have no join points");
public final Kind enumAsTargetForDecpIgnored =
new Kind("enumAsTargetForDecpIgnored","enum type {0} matches a declare parents type pattern but is being ignored");
public final Kind annotationAsTargetForDecpIgnored =
new Kind("annotationAsTargetForDecpIgnored","annotation type {0} matches a declare parents type pattern but is being ignored");
public final Kind cantMatchArrayTypeOnVarargs =
new Kind("cantMatchArrayTypeOnVarargs","an array type as the last parameter in a signature does not match on the varargs declared method: {0}");
public final Kind adviceDidNotMatch =
new Kind("adviceDidNotMatch","advice defined in {0} has not been applied");
public final Kind invalidTargetForAnnotation =
new Kind("invalidTargetForAnnotation","{0} is not a valid target for annotation {1}, this annotation can only be applied to {2}");
public final Kind elementAlreadyAnnotated =
new Kind("elementAlreadyAnnotated","{0} - already has an annotation of type {1}, cannot add a second instance");
public final Kind runtimeExceptionNotSoftened =
new Kind("runtimeExceptionNotSoftened","{0} will not be softened as it is already a RuntimeException");
public final Kind uncheckedArgument =
new Kind("uncheckedArgument","unchecked match of {0} with {1} when argument is an instance of {2} at join point {3}");
public final Kind uncheckedAdviceConversion =
new Kind("uncheckedAdviceConversion","unchecked conversion when advice applied at shadow {0}, expected {1} but advice uses {2}");
public final Kind noGuardForLazyTjp =
new Kind("noGuardForLazyTjp","can not build thisJoinPoint lazily for this advice since it has no suitable guard. The advice applies at {0}");
public final Kind noExplicitConstructorCall =
new Kind("noExplicitConstructorCall","inter-type constructor does not contain explicit constructor call: field initializers in the target type will not be executed");
public final Kind aspectExcludedByConfiguration =
new Kind("aspectExcludedByConfiguration","aspect {0} exluded for class loader {1}");
public final Kind unorderedAdviceAtShadow =
new Kind("unorderedAdviceAtShadow","at this shadow {0} no precedence is specified between advice applying from aspect {1} and aspect {2}");
public final Kind swallowedExceptionInCatchBlock =
new Kind("swallowedExceptionInCatchBlock","exception swallowed in catch block");
public final Kind calculatingSerialVersionUID =
new Kind("calculatingSerialVersionUID","calculated SerialVersionUID for type {0} to be {1}");
// there are a lot of messages in the cant find type family - I'm defining an umbrella lint warning that
// allows a user to control their severity (for e.g. ltw or binary weaving)
public final Kind cantFindType =
new Kind("cantFindType","{0}");
public final Kind cantFindTypeAffectingJoinPointMatch = new Kind("cantFindTypeAffectingJPMatch","{0}");
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(),
WeaverMessages.format(WeaverMessages.XLINT_LOAD_ERROR,file.getPath(),ioe.getMessage()));
}
}
public void loadDefaultProperties() {
InputStream s = getClass().getResourceAsStream("XlintDefault.properties");
if (s == null) {
MessageUtil.warn(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINTDEFAULT_LOAD_ERROR));
return;
}
try {
setFromProperties(s);
} catch (IOException ioe) {
MessageUtil.error(world.getMessageHandler(),
WeaverMessages.format(WeaverMessages.XLINTDEFAULT_LOAD_PROBLEM,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(),
WeaverMessages.format(WeaverMessages.XLINT_KEY_ERROR,entry.getKey()));
} else {
kind.setKind(getMessageKind((String)entry.getValue()));
}
}
}
public Collection allKinds() {
return kinds.values();
}
public Kind getLintKind(String name) {
return (Kind) kinds.get(name);
}
// temporarily suppress the given lint messages
public void suppressKinds(Collection lintKind) {
if (lintKind.isEmpty()) return;
for (Iterator iter = lintKind.iterator(); iter.hasNext();) {
Kind k = (Kind) iter.next();
k.setSuppressed(true);
}
}
// remove any suppression of lint warnings in place
public void clearAllSuppressions() {
for (Iterator iter = kinds.values().iterator(); iter.hasNext();) {
Kind k = (Kind) iter.next();
k.setSuppressed(false);
}
}
public void clearSuppressions(Collection lintKind) {
if (lintKind.isEmpty()) return;
for (Iterator iter = lintKind.iterator(); iter.hasNext();) {
Kind k = (Kind) iter.next();
k.setSuppressed(false);
}
}
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(),
WeaverMessages.format(WeaverMessages.XLINT_VALUE_ERROR,v));
return null;
}
public class Kind {
private String name;
private String message;
private IMessage.Kind kind = IMessage.WARNING;
private boolean isSupressed = false; // by SuppressAjWarnings
public Kind(String name, String message) {
this.name = name;
this.message = message;
kinds.put(this.name, this);
}
public void setSuppressed(boolean shouldBeSuppressed) {
this.isSupressed = shouldBeSuppressed;
}
public boolean isEnabled() {
return (kind != null) && !isSupressed();
}
private boolean isSupressed() {
// can't suppress errors!
return isSupressed && (kind != IMessage.ERROR);
}
public String getName() {
return name;
}
public IMessage.Kind getKind() {
return kind;
}
public void setKind(IMessage.Kind kind) {
this.kind = kind;
}
public void signal(String info, ISourceLocation location) {
if (kind == null) return;
String text = MessageFormat.format(message, new Object[] {info} );
text += " [Xlint:" + name + "]";
world.getMessageHandler().handleMessage(new Message(text, kind, null, location));
}
public void signal(String[] infos, ISourceLocation location, ISourceLocation[] extraLocations) {
if (kind == null) return;
String text = MessageFormat.format(message, infos );
text += " [Xlint:" + name + "]";
world.getMessageHandler().handleMessage(
new Message(text, "", kind, location, null, extraLocations));
}
}
}
|
133,117 |
Bug 133117 Lots of warnings with noGuardForLazyTjp
|
When the noGuardForLazyTjp compiler option is set to warning or error and a piece of advice causes this warning to show up, you get one warning for every join point matched by the advice. I think just one would probably be enough...
|
resolved fixed
|
3fa4d24
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-12T15:34:39Z | 2006-03-24T08: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
* Alexandre Vasseur support for @AJ aspects
* ******************************************************************/
package org.aspectj.weaver.bcel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.aspectj.apache.bcel.generic.InstructionFactory;
import org.aspectj.apache.bcel.generic.InstructionHandle;
import org.aspectj.apache.bcel.generic.InstructionList;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.ShadowMunger;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.World;
import org.aspectj.weaver.ast.Literal;
import org.aspectj.weaver.ast.Test;
import org.aspectj.weaver.patterns.ExactTypePattern;
import org.aspectj.weaver.patterns.ExposedState;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
/**
* Advice implemented for bcel.
*
* @author Erik Hilsdale
* @author Jim Hugunin
*/
public class BcelAdvice extends Advice {
private Test pointcutTest;
private ExposedState exposedState;
private boolean hasMatchedAtLeastOnce = false;
public BcelAdvice(
AjAttribute.AdviceAttribute attribute,
Pointcut pointcut,
Member signature,
ResolvedType concreteAspect)
{
super(attribute, pointcut, signature);
this.concreteAspect = concreteAspect;
}
// !!! must only be used for testing
public BcelAdvice(AdviceKind kind, Pointcut pointcut, Member signature,
int extraArgumentFlags,
int start, int end, ISourceContext sourceContext, ResolvedType concreteAspect)
{
this(new AjAttribute.AdviceAttribute(kind, pointcut, extraArgumentFlags, start, end, sourceContext),
pointcut, signature, concreteAspect);
thrownExceptions = Collections.EMPTY_LIST; //!!! interaction with unit tests
}
// ---- implementations of ShadowMunger's methods
public ShadowMunger concretize(ResolvedType fromType, World world, PerClause clause) {
suppressLintWarnings(world);
ShadowMunger ret = super.concretize(fromType, world, clause);
clearLintSuppressions(world,this.suppressedLintKinds);
return ret;
}
public ShadowMunger parameterizeWith(ResolvedType declaringType,Map typeVariableMap) {
Pointcut pc = getPointcut().parameterizeWith(typeVariableMap);
BcelAdvice ret = null;
Member adviceSignature = signature;
// allows for around advice where the return value is a type variable (see pr115250)
if (signature instanceof ResolvedMember && signature.getDeclaringType().isGenericType()) {
adviceSignature = ((ResolvedMember)signature).parameterizedWith(declaringType.getTypeParameters(),declaringType,declaringType.isParameterizedType());
}
ret = new BcelAdvice(this.attribute,pc,adviceSignature,this.concreteAspect);
return ret;
}
public boolean match(Shadow shadow, World world) {
suppressLintWarnings(world);
boolean ret = super.match(shadow, world);
clearLintSuppressions(world,this.suppressedLintKinds);
return ret;
}
public void specializeOn(Shadow shadow) {
if (getKind() == AdviceKind.Around) {
((BcelShadow)shadow).initializeForAroundClosure();
}
//XXX this case is just here for supporting lazy test code
if (getKind() == null) {
exposedState = new ExposedState(0);
return;
}
if (getKind().isPerEntry()) {
exposedState = new ExposedState(0);
} else if (getKind().isCflow()) {
exposedState = new ExposedState(nFreeVars);
} else if (getSignature() != null) {
exposedState = new ExposedState(getSignature());
} else {
exposedState = new ExposedState(0);
return; //XXX this case is just here for supporting lazy test code
}
World world = shadow.getIWorld();
suppressLintWarnings(world);
pointcutTest = getPointcut().findResidue(shadow, exposedState);
clearLintSuppressions(world,this.suppressedLintKinds);
// these initializations won't be performed by findResidue, but need to be
// so that the joinpoint is primed for weaving
if (getKind() == AdviceKind.PerThisEntry) {
shadow.getThisVar();
} else if (getKind() == AdviceKind.PerTargetEntry) {
shadow.getTargetVar();
}
// make sure thisJoinPoint parameters are initialized
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
((BcelShadow)shadow).getThisJoinPointStaticPartVar();
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
boolean hasGuardTest = pointcutTest != Literal.TRUE && getKind() != AdviceKind.Around;
boolean isAround = getKind() == AdviceKind.Around;
((BcelShadow)shadow).requireThisJoinPoint(hasGuardTest,isAround);
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
if (!hasGuardTest && world.getLint().multipleAdviceStoppingLazyTjp.isEnabled()) {
// collect up the problematic advice
((BcelShadow)shadow).addAdvicePreventingLazyTjp(this);
}
if (!isAround && !hasGuardTest && world.getLint().noGuardForLazyTjp.isEnabled()) {
// can't build tjp lazily, no suitable test...
world.getLint().noGuardForLazyTjp.signal(
new String[] {shadow.toString()},
getSourceLocation(),
new ISourceLocation[] { ((BcelShadow)shadow).getSourceLocation() }
);
}
}
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
((BcelShadow)shadow).getThisEnclosingJoinPointStaticPartVar();
((BcelShadow)shadow).getEnclosingClass().warnOnAddedStaticInitializer(shadow,getSourceLocation());
}
}
private boolean canInline(Shadow s) {
if (attribute.isProceedInInners()) return false;
//XXX this guard seems to only be needed for bad test cases
if (concreteAspect == null || concreteAspect.isMissing()) return false;
if (concreteAspect.getWorld().isXnoInline()) return false;
//System.err.println("isWoven? " + ((BcelObjectType)concreteAspect).getLazyClassGen().getWeaverState());
return BcelWorld.getBcelObjectType(concreteAspect).getLazyClassGen().isWoven();
}
public void implementOn(Shadow s) {
hasMatchedAtLeastOnce=true;
BcelShadow shadow = (BcelShadow) s;
//FIXME AV - see #75442, this logic is not enough so for now comment it out until we fix the bug
// // callback for perObject AJC MightHaveAspect postMunge (#75442)
// if (getConcreteAspect() != null
// && getConcreteAspect().getPerClause() != null
// && PerClause.PEROBJECT.equals(getConcreteAspect().getPerClause().getKind())) {
// final PerObject clause;
// if (getConcreteAspect().getPerClause() instanceof PerFromSuper) {
// clause = (PerObject)((PerFromSuper) getConcreteAspect().getPerClause()).lookupConcretePerClause(getConcreteAspect());
// } else {
// clause = (PerObject) getConcreteAspect().getPerClause();
// }
// if (clause.isThis()) {
// PerObjectInterfaceTypeMunger.registerAsAdvisedBy(s.getThisVar().getType(), getConcreteAspect());
// } else {
// PerObjectInterfaceTypeMunger.registerAsAdvisedBy(s.getTargetVar().getType(), getConcreteAspect());
// }
// }
if (getKind() == AdviceKind.Before) {
shadow.weaveBefore(this);
} else if (getKind() == AdviceKind.AfterReturning) {
shadow.weaveAfterReturning(this);
} else if (getKind() == AdviceKind.AfterThrowing) {
UnresolvedType catchType =
hasExtraParameter()
? getExtraParameterType()
: UnresolvedType.THROWABLE;
shadow.weaveAfterThrowing(this, catchType);
} else if (getKind() == AdviceKind.After) {
shadow.weaveAfter(this);
} else if (getKind() == AdviceKind.Around) {
// Note: under regular LTW the aspect is usually loaded after the first use of any class affecteted by it
// This means that as long as the aspect has not been thru the LTW, it's woven state is unknown
// and thus canInline(s) will return false.
// To force inlining (test), ones can do Class aspect = FQNAspect.class in the clinit of the target class
// FIXME AV : for AJC compiled @AJ aspect (or any code style aspect), the woven state can never be known
// if the aspect belongs to a parent classloader. In that case the aspect will never be inlined.
// It might be dangerous to change that especially for @AJ aspect non compiled with AJC since if those
// are not weaved (f.e. use of some limiteed LTW etc) then they cannot be prepared for inlining.
// One solution would be to flag @AJ aspect with an annotation as "prepared" and query that one.
if (!canInline(s)) {
shadow.weaveAroundClosure(this, hasDynamicTests());
} else {
shadow.weaveAroundInline(this, hasDynamicTests());
}
} else if (getKind() == AdviceKind.InterInitializer) {
shadow.weaveAfterReturning(this);
} else if (getKind().isCflow()) {
shadow.weaveCflowEntry(this, getSignature());
} else if (getKind() == AdviceKind.PerThisEntry) {
shadow.weavePerObjectEntry(this, (BcelVar)shadow.getThisVar());
} else if (getKind() == AdviceKind.PerTargetEntry) {
shadow.weavePerObjectEntry(this, (BcelVar)shadow.getTargetVar());
} else if (getKind() == AdviceKind.Softener) {
shadow.weaveSoftener(this, ((ExactTypePattern)exceptionType).getType());
} else if (getKind() == AdviceKind.PerTypeWithinEntry) {
// PTWIMPL Entry to ptw is the static initialization of a type that matched the ptw type pattern
shadow.weavePerTypeWithinAspectInitialization(this,shadow.getEnclosingType());
} else {
throw new BCException("unimplemented kind: " + getKind());
}
}
// ---- implementations
private Collection collectCheckedExceptions(UnresolvedType[] excs) {
if (excs == null || excs.length == 0) return Collections.EMPTY_LIST;
Collection ret = new ArrayList();
World world = concreteAspect.getWorld();
ResolvedType runtimeException = world.getCoreType(UnresolvedType.RUNTIME_EXCEPTION);
ResolvedType error = world.getCoreType(UnresolvedType.ERROR);
for (int i=0, len=excs.length; i < len; i++) {
ResolvedType t = world.resolve(excs[i],true);
if (t.isMissing()) {
world.getLint().cantFindType.signal(
WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE,excs[i].getName()),
getSourceLocation()
);
// IMessage msg = new Message(
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE,excs[i].getName()),
// "",IMessage.ERROR,getSourceLocation(),null,null);
// world.getMessageHandler().handleMessage(msg);
}
if (!(runtimeException.isAssignableFrom(t) || error.isAssignableFrom(t))) {
ret.add(t);
}
}
return ret;
}
private Collection thrownExceptions = null;
public Collection getThrownExceptions() {
if (thrownExceptions == null) {
//??? can we really lump in Around here, how does this interact with Throwable
if (concreteAspect != null && concreteAspect.getWorld() != null && // null tests for test harness
(getKind().isAfter() || getKind() == AdviceKind.Before || getKind() == AdviceKind.Around))
{
World world = concreteAspect.getWorld();
ResolvedMember m = world.resolve(signature);
if (m == null) {
thrownExceptions = Collections.EMPTY_LIST;
} else {
thrownExceptions = collectCheckedExceptions(m.getExceptions());
}
} else {
thrownExceptions = Collections.EMPTY_LIST;
}
}
return thrownExceptions;
}
/**
* The munger must not check for the advice exceptions to be declared by the shadow in the case
* of @AJ aspects so that around can throws Throwable
*
* @return
*/
public boolean mustCheckExceptions() {
if (getConcreteAspect() == null) {
return true;
}
return !getConcreteAspect().isAnnotationStyleAspect();
}
// only call me after prepare has been called
public boolean hasDynamicTests() {
// if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) {
// UnresolvedType extraParameterType = getExtraParameterType();
// if (! extraParameterType.equals(UnresolvedType.OBJECT)
// && ! extraParameterType.isPrimitive())
// return true;
// }
return pointcutTest != null &&
!(pointcutTest == Literal.TRUE);// || pointcutTest == Literal.NO_TEST);
}
/**
* get the instruction list for the really simple version of this advice.
* Is broken apart
* for other advice, but if you want it in one block, this is the method to call.
*
* @param s The shadow around which these instructions will eventually live.
* @param extraArgVar The var that will hold the return value or thrown exception
* for afterX advice
* @param ifNoAdvice The instructionHandle to jump to if the dynamic
* tests for this munger fails.
*/
InstructionList getAdviceInstructions(
BcelShadow s,
BcelVar extraArgVar,
InstructionHandle ifNoAdvice)
{
BcelShadow shadow = (BcelShadow) s;
InstructionFactory fact = shadow.getFactory();
BcelWorld world = shadow.getWorld();
InstructionList il = new InstructionList();
// we test to see if we have the right kind of thing...
// after throwing does this just by the exception mechanism.
if (hasExtraParameter() && getKind() == AdviceKind.AfterReturning) {
UnresolvedType extraParameterType = getExtraParameterType();
if (! extraParameterType.equals(UnresolvedType.OBJECT)
&& ! extraParameterType.isPrimitiveType()) {
il.append(
BcelRenderer.renderTest(
fact,
world,
Test.makeInstanceof(
extraArgVar, getExtraParameterType().resolve(world)),
null,
ifNoAdvice,
null));
}
}
il.append(getAdviceArgSetup(shadow, extraArgVar, null));
il.append(getNonTestAdviceInstructions(shadow));
InstructionHandle ifYesAdvice = il.getStart();
il.insert(getTestInstructions(shadow, ifYesAdvice, ifNoAdvice, ifYesAdvice));
return il;
}
public InstructionList getAdviceArgSetup(
BcelShadow shadow,
BcelVar extraVar,
InstructionList closureInstantiation)
{
InstructionFactory fact = shadow.getFactory();
BcelWorld world = shadow.getWorld();
InstructionList il = new InstructionList();
// if (targetAspectField != null) {
// il.append(fact.createFieldAccess(
// targetAspectField.getDeclaringType().getName(),
// targetAspectField.getName(),
// BcelWorld.makeBcelType(targetAspectField.getType()),
// Constants.GETSTATIC));
// }
//
//System.err.println("BcelAdvice: " + exposedState);
if (exposedState.getAspectInstance() != null) {
il.append(BcelRenderer.renderExpr(fact, world, exposedState.getAspectInstance()));
}
// pr121385
boolean x = this.getDeclaringAspect().resolve(world).isAnnotationStyleAspect();
final boolean isAnnotationStyleAspect = getConcreteAspect()!=null && getConcreteAspect().isAnnotationStyleAspect() && x;
boolean previousIsClosure = false;
for (int i = 0, len = exposedState.size(); i < len; i++) {
if (exposedState.isErroneousVar(i)) continue; // Erroneous vars have already had error msgs reported!
BcelVar v = (BcelVar) exposedState.get(i);
if (v == null) {
// if not @AJ aspect, go on with the regular binding handling
if (!isAnnotationStyleAspect) {
;
} else {
// ATAJ: for @AJ aspects, handle implicit binding of xxJoinPoint
//if (getKind() == AdviceKind.Around) {
// previousIsClosure = true;
// il.append(closureInstantiation);
if ("Lorg/aspectj/lang/ProceedingJoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) {
//make sure we are in an around, since we deal with the closure, not the arg here
if (getKind() != AdviceKind.Around) {
previousIsClosure = false;
getConcreteAspect().getWorld().getMessageHandler().handleMessage(
new Message(
"use of ProceedingJoinPoint is allowed only on around advice ("
+ "arg " + i + " in " + toString() + ")",
this.getSourceLocation(),
true
)
);
// try to avoid verify error and pass in null
il.append(InstructionConstants.ACONST_NULL);
} else {
if (previousIsClosure) {
il.append(InstructionConstants.DUP);
} else {
previousIsClosure = true;
il.append(closureInstantiation.copy());
}
}
} else if ("Lorg/aspectj/lang/JoinPoint$StaticPart;".equals(getSignature().getParameterTypes()[i].getSignature())) {
previousIsClosure = false;
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
} else if ("Lorg/aspectj/lang/JoinPoint;".equals(getSignature().getParameterTypes()[i].getSignature())) {
previousIsClosure = false;
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
il.append(shadow.loadThisJoinPoint());
}
} else if ("Lorg/aspectj/lang/JoinPoint$EnclosingStaticPart;".equals(getSignature().getParameterTypes()[i].getSignature())) {
previousIsClosure = false;
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
} else if (hasExtraParameter()) {
previousIsClosure = false;
extraVar.appendLoadAndConvert(
il,
fact,
getExtraParameterType().resolve(world));
} else {
previousIsClosure = false;
getConcreteAspect().getWorld().getMessageHandler().handleMessage(
new Message(
"use of ProceedingJoinPoint is allowed only on around advice ("
+ "arg " + i + " in " + toString() + ")",
this.getSourceLocation(),
true
)
);
// try to avoid verify error and pass in null
il.append(InstructionConstants.ACONST_NULL);
}
}
} else {
UnresolvedType desiredTy = getBindingParameterTypes()[i];
v.appendLoadAndConvert(il, fact, desiredTy.resolve(world));
}
}
// ATAJ: for code style aspect, handles the extraFlag as usual ie not
// in the middle of the formal bindings but at the end, in a rock solid ordering
if (!isAnnotationStyleAspect) {
if (getKind() == AdviceKind.Around) {
il.append(closureInstantiation);
} else if (hasExtraParameter()) {
extraVar.appendLoadAndConvert(
il,
fact,
getExtraParameterType().resolve(world));
}
// handle thisJoinPoint parameters
// these need to be in that same order as parameters in
// org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration
if ((getExtraParameterFlags() & ThisJoinPointStaticPart) != 0) {
shadow.getThisJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
if ((getExtraParameterFlags() & ThisJoinPoint) != 0) {
il.append(shadow.loadThisJoinPoint());
}
if ((getExtraParameterFlags() & ThisEnclosingJoinPointStaticPart) != 0) {
shadow.getThisEnclosingJoinPointStaticPartBcelVar().appendLoad(il, fact);
}
}
return il;
}
public InstructionList getNonTestAdviceInstructions(BcelShadow shadow) {
return new InstructionList(
Utility.createInvoke(shadow.getFactory(), shadow.getWorld(), getOriginalSignature()));
}
public Member getOriginalSignature() {
Member sig = getSignature();
if (sig instanceof ResolvedMember) {
ResolvedMember rsig = (ResolvedMember)sig;
if (rsig.hasBackingGenericMember()) return rsig.getBackingGenericMember();
}
return sig;
}
public InstructionList getTestInstructions(
BcelShadow shadow,
InstructionHandle sk,
InstructionHandle fk,
InstructionHandle next)
{
//System.err.println("test: " + pointcutTest);
return BcelRenderer.renderTest(
shadow.getFactory(),
shadow.getWorld(),
pointcutTest,
sk,
fk,
next);
}
public int compareTo(Object other) {
if (!(other instanceof BcelAdvice)) return 0;
BcelAdvice o = (BcelAdvice)other;
//System.err.println("compareTo: " + this + ", " + o);
if (kind.getPrecedence() != o.kind.getPrecedence()) {
if (kind.getPrecedence() > o.kind.getPrecedence()) return +1;
else return -1;
}
if (kind.isCflow()) {
// System.err.println("sort: " + this + " innerCflowEntries " + innerCflowEntries);
// System.err.println(" " + o + " innerCflowEntries " + o.innerCflowEntries);
boolean isBelow = (kind == AdviceKind.CflowBelowEntry);
if (this.innerCflowEntries.contains(o)) return isBelow ? +1 : -1;
else if (o.innerCflowEntries.contains(this)) return isBelow ? -1 : +1;
else return 0;
}
if (kind.isPerEntry() || kind == AdviceKind.Softener) {
return 0;
}
//System.out.println("compare: " + this + " with " + other);
World world = concreteAspect.getWorld();
int ret =
concreteAspect.getWorld().compareByPrecedence(
concreteAspect,
o.concreteAspect);
if (ret != 0) return ret;
ResolvedType declaringAspect = getDeclaringAspect().resolve(world);
ResolvedType o_declaringAspect = o.getDeclaringAspect().resolve(world);
if (declaringAspect == o_declaringAspect) {
if (kind.isAfter() || o.kind.isAfter()) {
return this.getStart() < o.getStart() ? -1: +1;
} else {
return this.getStart()< o.getStart() ? +1: -1;
}
} else if (declaringAspect.isAssignableFrom(o_declaringAspect)) {
return -1;
} else if (o_declaringAspect.isAssignableFrom(declaringAspect)) {
return +1;
} else {
return 0;
}
}
public BcelVar[] getExposedStateAsBcelVars(boolean isAround) {
// ATAJ aspect
if (isAround) {
// the closure instantiation has the same mapping as the extracted method from wich it is called
if (getConcreteAspect()!= null && getConcreteAspect().isAnnotationStyleAspect()) {
return BcelVar.NONE;
}
}
//System.out.println("vars: " + Arrays.asList(exposedState.vars));
if (exposedState == null) return BcelVar.NONE;
int len = exposedState.vars.length;
BcelVar[] ret = new BcelVar[len];
for (int i=0; i < len; i++) {
ret[i] = (BcelVar)exposedState.vars[i];
}
return ret; //(BcelVar[]) exposedState.vars;
}
public boolean hasMatchedSomething() {
return hasMatchedAtLeastOnce;
}
protected void suppressLintWarnings(World inWorld) {
if (suppressedLintKinds == null) {
if (signature instanceof BcelMethod) {
this.suppressedLintKinds = Utility.getSuppressedWarnings(signature.getAnnotations(), inWorld.getLint());
} else {
this.suppressedLintKinds = Collections.EMPTY_LIST;
}
}
inWorld.getLint().suppressKinds(suppressedLintKinds);
}
protected void clearLintSuppressions(World inWorld,Collection toClear) {
inWorld.getLint().clearSuppressions(toClear);
}
}
|
135,068 |
Bug 135068 VerifyError with LTW and @AJ style aspects
|
I get "VerifyError: Incompatible object argument for function call" error when using LTW with @Aspect stype aspects. Interestingly enough, LTW works as expected with equivalent .aj style aspect. Compile time weaving works with both aspect styles. Tested on Linux with AspectJ 1.5.0, 1.5.1 and DEVELOPMENT-20060404163823 and SUN 1.5.0_06 and IBM 1.5.0SR1 JVMs. I will attach example project shortly.
|
resolved fixed
|
9ffc63b
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T07:38:53Z | 2006-04-05T15:13:20Z |
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/ValidateAtAspectJAnnotationsVisitor.java
|
/* *******************************************************************
* Copyright (c) 2005 IBM Corporation Ltd
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Colyer initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import java.lang.reflect.Modifier;
import java.util.Stack;
import java.util.ArrayList;
import java.util.List;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseScope;
import org.aspectj.ajdt.internal.core.builder.EclipseSourceContext;
import org.aspectj.bridge.context.CompilationAndWeavingContext;
import org.aspectj.bridge.context.ContextToken;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ASTVisitor;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MemberValuePair;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.NormalAnnotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.StringLiteral;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.patterns.AbstractPatternNodeVisitor;
import org.aspectj.weaver.patterns.FormalBinding;
import org.aspectj.weaver.patterns.IfPointcut;
import org.aspectj.weaver.patterns.ParserException;
import org.aspectj.weaver.patterns.PatternParser;
import org.aspectj.weaver.patterns.Pointcut;
public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor {
private static final char[] beforeAdviceSig = "Lorg/aspectj/lang/annotation/Before;".toCharArray();
private static final char[] afterAdviceSig = "Lorg/aspectj/lang/annotation/After;".toCharArray();
private static final char[] afterReturningAdviceSig = "Lorg/aspectj/lang/annotation/AfterReturning;".toCharArray();
private static final char[] afterThrowingAdviceSig = "Lorg/aspectj/lang/annotation/AfterThrowing;".toCharArray();
private static final char[] aroundAdviceSig = "Lorg/aspectj/lang/annotation/Around;".toCharArray();
private static final char[] pointcutSig = "Lorg/aspectj/lang/annotation/Pointcut;".toCharArray();
private static final char[] aspectSig = "Lorg/aspectj/lang/annotation/Aspect;".toCharArray();
private static final char[] adviceNameSig = "Lorg/aspectj/lang/annotation/AdviceName;".toCharArray();
private static final char[] orgAspectJLangAnnotation = "org/aspectj/lang/annotation/".toCharArray();
private static final char[] voidType = "void".toCharArray();
private static final char[] booleanType = "boolean".toCharArray();
private static final char[] joinPoint = "Lorg/aspectj/lang/JoinPoint;".toCharArray();
private static final char[] joinPointStaticPart = "Lorg/aspectj/lang/JoinPoint$StaticPart;".toCharArray();
private static final char[] joinPointEnclosingStaticPart = "Lorg/aspectj/lang/JoinPoint$EnclosingStaticPart;".toCharArray();
private static final char[] proceedingJoinPoint = "Lorg/aspectj/lang/ProceedingJoinPoint;".toCharArray();
private static final char[][] adviceSigs = new char[][] {beforeAdviceSig,afterAdviceSig,afterReturningAdviceSig,afterThrowingAdviceSig,aroundAdviceSig};
private CompilationUnitDeclaration unit;
private Stack typeStack = new Stack();
private AspectJAnnotations ajAnnotations;
public ValidateAtAspectJAnnotationsVisitor(CompilationUnitDeclaration unit) {
this.unit = unit;
}
public boolean visit(TypeDeclaration localTypeDeclaration, BlockScope scope) {
typeStack.push(localTypeDeclaration);
ajAnnotations = new AspectJAnnotations(localTypeDeclaration.annotations);
checkTypeDeclaration(localTypeDeclaration);
return true;
}
public void endVisit(TypeDeclaration localTypeDeclaration,BlockScope scope) {
typeStack.pop();
}
public boolean visit(TypeDeclaration memberTypeDeclaration,ClassScope scope) {
typeStack.push(memberTypeDeclaration);
ajAnnotations = new AspectJAnnotations(memberTypeDeclaration.annotations);
checkTypeDeclaration(memberTypeDeclaration);
return true;
}
public void endVisit(TypeDeclaration memberTypeDeclaration,ClassScope scope) {
typeStack.pop();
}
public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) {
typeStack.push(typeDeclaration);
ajAnnotations = new AspectJAnnotations(typeDeclaration.annotations);
checkTypeDeclaration(typeDeclaration);
return true;
}
public void endVisit(TypeDeclaration typeDeclaration,CompilationUnitScope scope) {
typeStack.pop();
}
private void checkTypeDeclaration(TypeDeclaration typeDecl) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.VALIDATING_AT_ASPECTJ_ANNOTATIONS, typeDecl.name);
if (!(typeDecl instanceof AspectDeclaration)) {
if (ajAnnotations.hasAspectAnnotation) {
validateAspectDeclaration(typeDecl);
} else {
// check that class doesn't extend aspect
TypeReference parentRef = typeDecl.superclass;
if (parentRef != null) {
TypeBinding parentBinding = parentRef.resolvedType;
if (parentBinding instanceof SourceTypeBinding) {
SourceTypeBinding parentSTB = (SourceTypeBinding) parentBinding;
if (parentSTB.scope != null) {
TypeDeclaration parentDecl = parentSTB.scope.referenceContext;
if (isAspect(parentDecl)) {
typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart,typeDecl.sourceEnd,"a class cannot extend an aspect");
}
}
}
}
}
} else {
// check that aspect doesn't have @Aspect annotation, we've already added on ourselves.
if (ajAnnotations.hasMultipleAspectAnnotations) {
typeDecl.scope.problemReporter().signalError(
typeDecl.sourceStart,
typeDecl.sourceEnd,
"aspects cannot have @Aspect annotation"
);
}
}
CompilationAndWeavingContext.leavingPhase(tok);
}
public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) {
if (methodDeclaration.hasErrors()) {
return false;
}
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.VALIDATING_AT_ASPECTJ_ANNOTATIONS, methodDeclaration.selector);
ajAnnotations = new AspectJAnnotations(methodDeclaration.annotations);
if (!methodDeclaration.getClass().equals(AjMethodDeclaration.class)) {
// simply test for innapropriate use of annotations on code-style members
if (methodDeclaration instanceof PointcutDeclaration) {
if (ajAnnotations.hasMultiplePointcutAnnotations ||
ajAnnotations.hasAdviceAnnotation ||
ajAnnotations.hasAspectAnnotation ||
ajAnnotations.hasAdviceNameAnnotation) {
methodDeclaration.scope.problemReporter().signalError(
methodDeclaration.sourceStart,
methodDeclaration.sourceEnd,
"@AspectJ annotations cannot be declared on this aspect member");
}
} else if (methodDeclaration instanceof AdviceDeclaration) {
if (ajAnnotations.hasMultipleAdviceAnnotations ||
ajAnnotations.hasAspectAnnotation ||
ajAnnotations.hasPointcutAnnotation) {
methodDeclaration.scope.problemReporter().signalError(
methodDeclaration.sourceStart,
methodDeclaration.sourceEnd,
"Only @AdviceName AspectJ annotation allowed on advice");
}
} else {
if (ajAnnotations.hasAspectJAnnotations()) {
methodDeclaration.scope.problemReporter().signalError(
methodDeclaration.sourceStart,
methodDeclaration.sourceEnd,
"@AspectJ annotations cannot be declared on this aspect member");
}
}
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
if (ajAnnotations.hasAdviceAnnotation) {
validateAdvice(methodDeclaration);
} else if (ajAnnotations.hasPointcutAnnotation) {
convertToPointcutDeclaration(methodDeclaration,scope);
}
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
private boolean isAspectJAnnotation(Annotation ann) {
if (ann.resolvedType == null) return false;
char[] sig = ann.resolvedType.signature();
return CharOperation.contains(orgAspectJLangAnnotation, sig);
}
private boolean insideAspect() {
if (typeStack.empty()) return false;
TypeDeclaration typeDecl = (TypeDeclaration) typeStack.peek();
return isAspect(typeDecl);
}
private boolean isAspect(TypeDeclaration typeDecl) {
if (typeDecl instanceof AspectDeclaration) return true;
return new AspectJAnnotations(typeDecl.annotations).hasAspectAnnotation;
}
/**
* aspect must be public
* nested aspect must be static
* cannot extend a concrete aspect
* pointcut in perclause must be good.
*/
private void validateAspectDeclaration(TypeDeclaration typeDecl) {
if (typeStack.size() > 1) {
// it's a nested aspect
if (!Modifier.isStatic(typeDecl.modifiers)) {
typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart, typeDecl.sourceEnd, "inner aspects must be static");
return;
}
}
SourceTypeBinding binding = typeDecl.binding;
if (binding != null) {
if (binding.isEnum() || binding.isInterface() || binding.isAnnotationType()) {
typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart,typeDecl.sourceEnd,"only classes can have an @Aspect annotation");
}
}
//FIXME AV - do we really want that
// if (!Modifier.isPublic(typeDecl.modifiers)) {
// typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart,typeDecl.sourceEnd,"@Aspect class must be public");
// }
TypeReference parentRef = typeDecl.superclass;
if (parentRef != null) {
TypeBinding parentBinding = parentRef.resolvedType;
if (parentBinding instanceof SourceTypeBinding) {
SourceTypeBinding parentSTB = (SourceTypeBinding) parentBinding;
if (parentSTB.scope!=null) { // scope is null if its a binarytypebinding (in AJ world, thats a subclass of SourceTypeBinding)
TypeDeclaration parentDecl = parentSTB.scope.referenceContext;
if (isAspect(parentDecl) && !Modifier.isAbstract(parentDecl.modifiers)) {
typeDecl.scope.problemReporter().signalError(typeDecl.sourceStart,typeDecl.sourceEnd,"cannot extend a concrete aspect");
}
}
}
}
Annotation aspectAnnotation = ajAnnotations.aspectAnnotation;
int[] pcLoc = new int[2];
String perClause = getStringLiteralFor("value", aspectAnnotation, pcLoc);
AspectDeclaration aspectDecl = new AspectDeclaration(typeDecl.compilationResult);
try {
if (perClause != null && !perClause.equals("")) {
ISourceContext context = new EclipseSourceContext(unit.compilationResult,pcLoc[0]);
Pointcut pc = new PatternParser(perClause,context).maybeParsePerClause();
FormalBinding[] bindings = new FormalBinding[0];
if (pc != null) pc.resolve(new EclipseScope(bindings,typeDecl.scope));
}
} catch(ParserException pEx) {
typeDecl.scope.problemReporter().parseError(
pcLoc[0] + pEx.getLocation().getStart(),
pcLoc[0] + pEx.getLocation().getEnd() ,
-1,
perClause.toCharArray(),
perClause,
new String[] {pEx.getMessage()});
}
}
/**
* 1) Advice must be public
* 2) Advice must have a void return type if not around advice
* 3) Advice must not have any other @AspectJ annotations
* 4) After throwing advice must declare the thrown formal
* 5) After returning advice must declare the returning formal
*/
private void validateAdvice(MethodDeclaration methodDeclaration) {
if (!insideAspect()) {
methodDeclaration.scope.problemReporter().signalError(methodDeclaration.sourceStart,
methodDeclaration.sourceEnd,
"Advice must be declared inside an aspect type");
}
if (!Modifier.isPublic(methodDeclaration.modifiers)) {
methodDeclaration.scope.problemReporter()
.signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"advice must be public");
}
if (ajAnnotations.hasMultipleAdviceAnnotations) {
methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.duplicateAdviceAnnotation);
}
if (ajAnnotations.hasPointcutAnnotation) {
methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.pointcutAnnotation);
}
if (ajAnnotations.hasAspectAnnotation) {
methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.aspectAnnotation);
}
if (ajAnnotations.hasAdviceNameAnnotation) {
methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.adviceNameAnnotation);
}
if (ajAnnotations.adviceKind != AdviceKind.Around) {
ensureVoidReturnType(methodDeclaration);
}
if (ajAnnotations.adviceKind == AdviceKind.AfterThrowing) {
int[] throwingLocation = new int[2];
String thrownFormal = getStringLiteralFor("throwing",ajAnnotations.adviceAnnotation,throwingLocation);
if (thrownFormal != null) {
Argument[] arguments = methodDeclaration.arguments;
if (!toArgumentNames(methodDeclaration.arguments).contains(thrownFormal)) {
methodDeclaration.scope.problemReporter()
.signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"throwing formal '" + thrownFormal + "' must be declared as a parameter in the advice signature");
}
}
}
if (ajAnnotations.adviceKind == AdviceKind.AfterReturning) {
int[] throwingLocation = new int[2];
String returningFormal = getStringLiteralFor("returning",ajAnnotations.adviceAnnotation,throwingLocation);
if (returningFormal != null) {
if (!toArgumentNames(methodDeclaration.arguments).contains(returningFormal)) {
methodDeclaration.scope.problemReporter()
.signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"returning formal '" + returningFormal + "' must be declared as a parameter in the advice signature");
}
}
}
resolveAndSetPointcut(methodDeclaration, ajAnnotations.adviceAnnotation);
}
/**
* Get the argument names as a string list
* @param arguments
* @return argument names (possibly empty)
*/
private List toArgumentNames(Argument[] arguments) {
List names = new ArrayList();
if (arguments == null) {
return names;
} else {
for (int i = 0; i < arguments.length; i++) {
names.add(new String(arguments[i].name));
}
return names;
}
}
private void resolveAndSetPointcut(MethodDeclaration methodDeclaration, Annotation adviceAnn) {
int[] pcLocation = new int[2];
String pointcutExpression = getStringLiteralFor("pointcut",adviceAnn,pcLocation);
if (pointcutExpression == null) pointcutExpression = getStringLiteralFor("value",adviceAnn,pcLocation);
try {
ISourceContext context = new EclipseSourceContext(unit.compilationResult,pcLocation[0]);
Pointcut pc = new PatternParser(pointcutExpression,context).parsePointcut();
FormalBinding[] bindings = buildFormalAdviceBindingsFrom(methodDeclaration);
pc.resolve(new EclipseScope(bindings,methodDeclaration.scope));
EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(methodDeclaration.scope);
// now create a ResolvedPointcutDefinition,make an attribute out of it, and add it to the method
UnresolvedType[] paramTypes = new UnresolvedType[bindings.length];
for (int i = 0; i < paramTypes.length; i++) paramTypes[i] = bindings[i].getType();
ResolvedPointcutDefinition resPcutDef =
new ResolvedPointcutDefinition(
factory.fromBinding(((TypeDeclaration)typeStack.peek()).binding),
methodDeclaration.modifiers,
"anonymous",
paramTypes,
pc
);
AjAttribute attr = new AjAttribute.PointcutDeclarationAttribute(resPcutDef);
((AjMethodDeclaration)methodDeclaration).addAttribute(new EclipseAttributeAdapter(attr));
} catch(ParserException pEx) {
methodDeclaration.scope.problemReporter().parseError(
pcLocation[0] + pEx.getLocation().getStart(),
pcLocation[0] + pEx.getLocation().getEnd() ,
-1,
pointcutExpression.toCharArray(),
pointcutExpression,
new String[] {pEx.getMessage()});
}
}
private void ensureVoidReturnType(MethodDeclaration methodDeclaration) {
boolean returnsVoid = true;
if ((methodDeclaration.returnType instanceof SingleTypeReference)) {
SingleTypeReference retType = (SingleTypeReference) methodDeclaration.returnType;
if (!CharOperation.equals(voidType,retType.token)) {
returnsVoid = false;
}
} else {
returnsVoid = false;
}
if (!returnsVoid) {
methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart,
methodDeclaration.returnType.sourceEnd,
"This advice must return void");
}
}
private FormalBinding[] buildFormalAdviceBindingsFrom(MethodDeclaration mDecl) {
if (mDecl.arguments == null) return new FormalBinding[0];
if (mDecl.binding == null) return new FormalBinding[0];
EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(mDecl.scope);
String extraArgName = maybeGetExtraArgName();
if (extraArgName == null) extraArgName = "";
FormalBinding[] ret = new FormalBinding[mDecl.arguments.length];
for (int i = 0; i < mDecl.arguments.length; i++) {
Argument arg = mDecl.arguments[i];
String name = new String(arg.name);
TypeBinding argTypeBinding = mDecl.binding.parameters[i];
UnresolvedType type = factory.fromBinding(argTypeBinding);
if (CharOperation.equals(joinPoint,argTypeBinding.signature()) ||
CharOperation.equals(joinPointStaticPart,argTypeBinding.signature()) ||
CharOperation.equals(joinPointEnclosingStaticPart,argTypeBinding.signature()) ||
CharOperation.equals(proceedingJoinPoint,argTypeBinding.signature()) ||
name.equals(extraArgName)) {
ret[i] = new FormalBinding.ImplicitFormalBinding(type,name,i);
} else {
ret[i] = new FormalBinding(type, name, i, arg.sourceStart, arg.sourceEnd, "unknown");
}
}
return ret;
}
private String maybeGetExtraArgName() {
String argName = null;
if (ajAnnotations.adviceKind == AdviceKind.AfterReturning) {
argName = getStringLiteralFor("returning",ajAnnotations.adviceAnnotation,new int[2]);
} else if (ajAnnotations.adviceKind == AdviceKind.AfterThrowing) {
argName = getStringLiteralFor("throwing",ajAnnotations.adviceAnnotation,new int[2]);
}
return argName;
}
private String getStringLiteralFor(String memberName, Annotation inAnnotation, int[] location) {
if (inAnnotation instanceof SingleMemberAnnotation && memberName.equals("value")) {
SingleMemberAnnotation sma = (SingleMemberAnnotation) inAnnotation;
if (sma.memberValue instanceof StringLiteral) {
StringLiteral sv = (StringLiteral) sma.memberValue;
location[0] = sv.sourceStart;
location[1] = sv.sourceEnd;
return new String(sv.source());
}
}
if (! (inAnnotation instanceof NormalAnnotation)) return null;
NormalAnnotation ann = (NormalAnnotation) inAnnotation;
MemberValuePair[] mvps = ann.memberValuePairs;
if (mvps == null) return null;
for (int i = 0; i < mvps.length; i++) {
if (CharOperation.equals(memberName.toCharArray(),mvps[i].name)) {
if (mvps[i].value instanceof StringLiteral) {
StringLiteral sv = (StringLiteral) mvps[i].value;
location[0] = sv.sourceStart;
location[1] = sv.sourceEnd;
return new String(sv.source());
}
}
}
return null;
}
private void convertToPointcutDeclaration(MethodDeclaration methodDeclaration, ClassScope scope) {
TypeDeclaration typeDecl = (TypeDeclaration) typeStack.peek();
if (typeDecl.binding != null) {
if (!typeDecl.binding.isClass()) {
methodDeclaration.scope.problemReporter()
.signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"pointcuts can only be declared in a class or an aspect");
}
}
if (methodDeclaration.thrownExceptions != null && methodDeclaration.thrownExceptions.length > 0) {
methodDeclaration.scope.problemReporter()
.signalError(methodDeclaration.sourceStart,methodDeclaration.sourceEnd,"pointcuts cannot throw exceptions!");
}
PointcutDeclaration pcDecl = new PointcutDeclaration(unit.compilationResult);
copyAllFields(methodDeclaration,pcDecl);
if (ajAnnotations.hasAdviceAnnotation) {
methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.adviceAnnotation);
}
if (ajAnnotations.hasAspectAnnotation) {
methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.aspectAnnotation);
}
if (ajAnnotations.hasAdviceNameAnnotation) {
methodDeclaration.scope.problemReporter().disallowedTargetForAnnotation(ajAnnotations.adviceNameAnnotation);
}
boolean noValueSupplied=true;
boolean containsIfPcd = false;
int[] pcLocation = new int[2];
String pointcutExpression = getStringLiteralFor("value",ajAnnotations.pointcutAnnotation,pcLocation);
try {
ISourceContext context = new EclipseSourceContext(unit.compilationResult,pcLocation[0]);
Pointcut pc = null;//abstract
if (pointcutExpression == null || pointcutExpression.length() == 0) {
noValueSupplied=true; // matches nothing pointcut
} else {
noValueSupplied=false;
pc = new PatternParser(pointcutExpression,context).parsePointcut();
}
pcDecl.pointcutDesignator = (pc==null)?null:new PointcutDesignator(pc);
pcDecl.setGenerateSyntheticPointcutMethod();
TypeDeclaration onType = (TypeDeclaration) typeStack.peek();
pcDecl.postParse(onType);
// EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(methodDeclaration.scope);
// int argsLength = methodDeclaration.arguments == null ? 0 : methodDeclaration.arguments.length;
FormalBinding[] bindings = buildFormalAdviceBindingsFrom(methodDeclaration);
// FormalBinding[] bindings = new FormalBinding[argsLength];
// for (int i = 0, len = bindings.length; i < len; i++) {
// Argument arg = methodDeclaration.arguments[i];
// String name = new String(arg.name);
// UnresolvedType type = factory.fromBinding(methodDeclaration.binding.parameters[i]);
// bindings[i] = new FormalBinding(type, name, i, arg.sourceStart, arg.sourceEnd, "unknown");
// }
swap(onType,methodDeclaration,pcDecl);
if (pc != null) {
// has an expression
pc.resolve(new EclipseScope(bindings,methodDeclaration.scope));
HasIfPCDVisitor ifFinder = new HasIfPCDVisitor();
pc.traverse(ifFinder, null);
containsIfPcd = ifFinder.containsIfPcd;
}
} catch(ParserException pEx) {
methodDeclaration.scope.problemReporter().parseError(
pcLocation[0] + pEx.getLocation().getStart(),
pcLocation[0] + pEx.getLocation().getEnd() ,
-1,
pointcutExpression.toCharArray(),
pointcutExpression,
new String[] {pEx.getMessage()});
}
boolean returnsVoid = false;
boolean returnsBoolean = false;
if ((methodDeclaration.returnType instanceof SingleTypeReference)) {
SingleTypeReference retType = (SingleTypeReference) methodDeclaration.returnType;
if (CharOperation.equals(voidType,retType.token)) returnsVoid = true;
if (CharOperation.equals(booleanType,retType.token)) returnsBoolean = true;
}
if (!returnsVoid && !containsIfPcd) {
methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart,
methodDeclaration.returnType.sourceEnd,
"Methods annotated with @Pointcut must return void unless the pointcut contains an if() expression");
}
if (!returnsBoolean && containsIfPcd) {
methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart,
methodDeclaration.returnType.sourceEnd,
"Methods annotated with @Pointcut must return boolean when the pointcut contains an if() expression");
}
if (methodDeclaration.statements != null && methodDeclaration.statements.length > 0 && !containsIfPcd) {
methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart,
methodDeclaration.returnType.sourceEnd,
"Pointcuts without an if() expression should have an empty method body");
}
if (pcDecl.pointcutDesignator == null) {
if (Modifier.isAbstract(methodDeclaration.modifiers)
|| noValueSupplied // this is a matches nothing pointcut
//those 2 checks makes sense for aop.xml concretization but NOT for regular abstraction of pointcut
//&& returnsVoid
//&& (methodDeclaration.arguments == null || methodDeclaration.arguments.length == 0)) {
) {
;//fine
} else {
methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart,
methodDeclaration.returnType.sourceEnd,
"Method annotated with @Pointcut() for abstract pointcut must be abstract");
}
} else if (Modifier.isAbstract(methodDeclaration.modifiers)) {
methodDeclaration.scope.problemReporter().signalError(methodDeclaration.returnType.sourceStart,
methodDeclaration.returnType.sourceEnd,
"Method annotated with non abstract @Pointcut(\""+pointcutExpression+"\") is abstract");
}
}
private void copyAllFields(MethodDeclaration from, MethodDeclaration to) {
to.annotations = from.annotations;
to.arguments = from.arguments;
to.binding = from.binding;
to.bits = from.bits;
to.bodyEnd = from.bodyEnd;
to.bodyStart = from.bodyStart;
to.declarationSourceEnd = from.declarationSourceEnd;
to.declarationSourceStart = from.declarationSourceStart;
to.errorInSignature = from.errorInSignature;
to.explicitDeclarations = from.explicitDeclarations;
to.ignoreFurtherInvestigation = from.ignoreFurtherInvestigation;
to.javadoc = from.javadoc;
to.modifiers = from.modifiers;
to.modifiersSourceStart = from.modifiersSourceStart;
to.needFreeReturn = from.needFreeReturn;
to.returnType = from.returnType;
to.scope = from.scope;
to.selector = from.selector;
to.sourceEnd = from.sourceEnd;
to.sourceStart = from.sourceStart;
to.statements = from.statements;
to.thrownExceptions = from.thrownExceptions;
to.typeParameters = from.typeParameters;
}
private void swap(TypeDeclaration inType, MethodDeclaration thisDeclaration, MethodDeclaration forThatDeclaration) {
for (int i = 0; i < inType.methods.length; i++) {
if (inType.methods[i] == thisDeclaration) {
inType.methods[i] = forThatDeclaration;
break;
}
}
}
private static class AspectJAnnotations {
boolean hasAdviceAnnotation = false;
boolean hasPointcutAnnotation = false;
boolean hasAspectAnnotation = false;
boolean hasAdviceNameAnnotation = false;
boolean hasMultipleAdviceAnnotations = false;
boolean hasMultiplePointcutAnnotations = false;
boolean hasMultipleAspectAnnotations = false;
AdviceKind adviceKind = null;
Annotation adviceAnnotation = null;
Annotation pointcutAnnotation = null;
Annotation aspectAnnotation = null;
Annotation adviceNameAnnotation = null;
Annotation duplicateAdviceAnnotation = null;
Annotation duplicatePointcutAnnotation = null;
Annotation duplicateAspectAnnotation = null;
public AspectJAnnotations(Annotation[] annotations) {
if (annotations == null) return;
for (int i = 0; i < annotations.length; i++) {
if (annotations[i].resolvedType == null) continue; // user messed up annotation declaration
char[] sig = annotations[i].resolvedType.signature();
if (CharOperation.equals(afterAdviceSig,sig)) {
adviceKind = AdviceKind.After;
addAdviceAnnotation(annotations[i]);
} else if (CharOperation.equals(afterReturningAdviceSig,sig)) {
adviceKind = AdviceKind.AfterReturning;
addAdviceAnnotation(annotations[i]);
} else if (CharOperation.equals(afterThrowingAdviceSig,sig)) {
adviceKind = AdviceKind.AfterThrowing;
addAdviceAnnotation(annotations[i]);
} else if (CharOperation.equals(beforeAdviceSig,sig)) {
adviceKind = AdviceKind.Before;
addAdviceAnnotation(annotations[i]);
} else if (CharOperation.equals(aroundAdviceSig,sig)) {
adviceKind = AdviceKind.Around;
addAdviceAnnotation(annotations[i]);
} else if (CharOperation.equals(adviceNameSig,sig)) {
hasAdviceNameAnnotation = true;
adviceNameAnnotation = annotations[i];
} else if (CharOperation.equals(aspectSig,sig)) {
if (hasAspectAnnotation) {
hasMultipleAspectAnnotations = true;
duplicateAspectAnnotation = annotations[i];
} else {
hasAspectAnnotation = true;
aspectAnnotation = annotations[i];
}
} else if (CharOperation.equals(pointcutSig,sig)) {
if (hasPointcutAnnotation) {
hasMultiplePointcutAnnotations = true;
duplicatePointcutAnnotation = annotations[i];
} else {
hasPointcutAnnotation = true;
pointcutAnnotation = annotations[i];
}
}
}
}
public boolean hasAspectJAnnotations() {
return hasAdviceAnnotation || hasPointcutAnnotation || hasAdviceNameAnnotation || hasAspectAnnotation;
}
private void addAdviceAnnotation(Annotation annotation) {
if (!hasAdviceAnnotation) {
hasAdviceAnnotation = true;
adviceAnnotation = annotation;
} else {
hasMultipleAdviceAnnotations = true;
duplicateAdviceAnnotation = annotation;
}
}
}
private static class HasIfPCDVisitor extends AbstractPatternNodeVisitor {
public boolean containsIfPcd = false;
public Object visit(IfPointcut node, Object data) {
containsIfPcd = true;
return data;
}
}
}
|
135,068 |
Bug 135068 VerifyError with LTW and @AJ style aspects
|
I get "VerifyError: Incompatible object argument for function call" error when using LTW with @Aspect stype aspects. Interestingly enough, LTW works as expected with equivalent .aj style aspect. Compile time weaving works with both aspect styles. Tested on Linux with AspectJ 1.5.0, 1.5.1 and DEVELOPMENT-20060404163823 and SUN 1.5.0_06 and IBM 1.5.0SR1 JVMs. I will attach example project shortly.
|
resolved fixed
|
9ffc63b
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T07:38:53Z | 2006-04-05T15:13:20Z |
tests/bugs152/pr135068/A.java
| |
135,068 |
Bug 135068 VerifyError with LTW and @AJ style aspects
|
I get "VerifyError: Incompatible object argument for function call" error when using LTW with @Aspect stype aspects. Interestingly enough, LTW works as expected with equivalent .aj style aspect. Compile time weaving works with both aspect styles. Tested on Linux with AspectJ 1.5.0, 1.5.1 and DEVELOPMENT-20060404163823 and SUN 1.5.0_06 and IBM 1.5.0SR1 JVMs. I will attach example project shortly.
|
resolved fixed
|
9ffc63b
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T07:38:53Z | 2006-04-05T15:13:20Z |
tests/bugs152/pr135068/Ajava.java
| |
135,068 |
Bug 135068 VerifyError with LTW and @AJ style aspects
|
I get "VerifyError: Incompatible object argument for function call" error when using LTW with @Aspect stype aspects. Interestingly enough, LTW works as expected with equivalent .aj style aspect. Compile time weaving works with both aspect styles. Tested on Linux with AspectJ 1.5.0, 1.5.1 and DEVELOPMENT-20060404163823 and SUN 1.5.0_06 and IBM 1.5.0SR1 JVMs. I will attach example project shortly.
|
resolved fixed
|
9ffc63b
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T07:38:53Z | 2006-04-05T15:13:20Z |
tests/bugs152/pr135068/Ajava2.java
| |
135,068 |
Bug 135068 VerifyError with LTW and @AJ style aspects
|
I get "VerifyError: Incompatible object argument for function call" error when using LTW with @Aspect stype aspects. Interestingly enough, LTW works as expected with equivalent .aj style aspect. Compile time weaving works with both aspect styles. Tested on Linux with AspectJ 1.5.0, 1.5.1 and DEVELOPMENT-20060404163823 and SUN 1.5.0_06 and IBM 1.5.0SR1 JVMs. I will attach example project shortly.
|
resolved fixed
|
9ffc63b
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T07:38:53Z | 2006-04-05T15:13:20Z |
tests/bugs152/pr135068/C.java
| |
135,068 |
Bug 135068 VerifyError with LTW and @AJ style aspects
|
I get "VerifyError: Incompatible object argument for function call" error when using LTW with @Aspect stype aspects. Interestingly enough, LTW works as expected with equivalent .aj style aspect. Compile time weaving works with both aspect styles. Tested on Linux with AspectJ 1.5.0, 1.5.1 and DEVELOPMENT-20060404163823 and SUN 1.5.0_06 and IBM 1.5.0SR1 JVMs. I will attach example project shortly.
|
resolved fixed
|
9ffc63b
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T07:38:53Z | 2006-04-05T15:13:20Z |
tests/bugs152/pr135068/C2.java
| |
135,068 |
Bug 135068 VerifyError with LTW and @AJ style aspects
|
I get "VerifyError: Incompatible object argument for function call" error when using LTW with @Aspect stype aspects. Interestingly enough, LTW works as expected with equivalent .aj style aspect. Compile time weaving works with both aspect styles. Tested on Linux with AspectJ 1.5.0, 1.5.1 and DEVELOPMENT-20060404163823 and SUN 1.5.0_06 and IBM 1.5.0SR1 JVMs. I will attach example project shortly.
|
resolved fixed
|
9ffc63b
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T07:38:53Z | 2006-04-05T15:13:20Z |
tests/bugs152/pr135068/t/Ajava.java
| |
135,068 |
Bug 135068 VerifyError with LTW and @AJ style aspects
|
I get "VerifyError: Incompatible object argument for function call" error when using LTW with @Aspect stype aspects. Interestingly enough, LTW works as expected with equivalent .aj style aspect. Compile time weaving works with both aspect styles. Tested on Linux with AspectJ 1.5.0, 1.5.1 and DEVELOPMENT-20060404163823 and SUN 1.5.0_06 and IBM 1.5.0SR1 JVMs. I will attach example project shortly.
|
resolved fixed
|
9ffc63b
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T07:38:53Z | 2006-04-05T15:13:20Z |
tests/bugs152/pr135068/t/Ajava2.java
| |
135,068 |
Bug 135068 VerifyError with LTW and @AJ style aspects
|
I get "VerifyError: Incompatible object argument for function call" error when using LTW with @Aspect stype aspects. Interestingly enough, LTW works as expected with equivalent .aj style aspect. Compile time weaving works with both aspect styles. Tested on Linux with AspectJ 1.5.0, 1.5.1 and DEVELOPMENT-20060404163823 and SUN 1.5.0_06 and IBM 1.5.0SR1 JVMs. I will attach example project shortly.
|
resolved fixed
|
9ffc63b
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T07:38:53Z | 2006-04-05T15:13:20Z |
tests/bugs152/pr135068/t/C.java
| |
135,068 |
Bug 135068 VerifyError with LTW and @AJ style aspects
|
I get "VerifyError: Incompatible object argument for function call" error when using LTW with @Aspect stype aspects. Interestingly enough, LTW works as expected with equivalent .aj style aspect. Compile time weaving works with both aspect styles. Tested on Linux with AspectJ 1.5.0, 1.5.1 and DEVELOPMENT-20060404163823 and SUN 1.5.0_06 and IBM 1.5.0SR1 JVMs. I will attach example project shortly.
|
resolved fixed
|
9ffc63b
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T07:38:53Z | 2006-04-05T15:13:20Z |
tests/bugs152/pr135068/t/C2.java
| |
135,068 |
Bug 135068 VerifyError with LTW and @AJ style aspects
|
I get "VerifyError: Incompatible object argument for function call" error when using LTW with @Aspect stype aspects. Interestingly enough, LTW works as expected with equivalent .aj style aspect. Compile time weaving works with both aspect styles. Tested on Linux with AspectJ 1.5.0, 1.5.1 and DEVELOPMENT-20060404163823 and SUN 1.5.0_06 and IBM 1.5.0SR1 JVMs. I will attach example project shortly.
|
resolved fixed
|
9ffc63b
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T07:38:53Z | 2006-04-05T15:13:20Z |
tests/src/org/aspectj/systemtest/ajc152/Ajc152Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc152;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc152Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public void testVerifyErrorForComplexCflow_pr136026() { runTest("verifyerror");}
public void testVerifyErrorForComplexCflow_pr136026_2() { runTest("verifyerror - 2");}
public void testAnnotationsAndGenericsBCException_pr129704() { runTest("annotations and generics leading to BCException");}
public void testMethodTooBigAfterWeaving_pr138384() { runTest("method too big"); }
public void testNotAtWithincode_pr138158_1() { runTest("not at withincode - 1");}
public void testNotAtWithincode_pr138158_2() { runTest("not at withincode - 2");}
public void testNotAtWithincode_pr138158_3() { runTest("not at within - 3");}
// public void testComplexGenericDecl_pr137568() { runTest("complicated generics declaration");}
public void testNpeOnDup_pr138143() { runTest("npe on duplicate method with ataj");}
public void testPointcutsAndGenerics_pr137496_1() { runTest("pointcuts and generics - B");}
public void testPointcutsAndGenerics_pr137496_2() { runTest("pointcuts and generics - D");}
public void testPointcutsAndGenerics_pr137496_3() { runTest("pointcuts and generics - E");}
public void testPointcutsAndGenerics_pr137496_4() { runTest("pointcuts and generics - F");}
public void testPointcutsAndGenerics_pr137496_5() { runTest("pointcuts and generics - G");}
public void testPointcutsAndGenerics_pr137496_6() { runTest("pointcuts and generics - H");}
public void testAspectLibrariesAndASM_pr135001() { runTest("aspect libraries and asm");}
public void testStackOverflow_pr136258() { runTest("stack overflow");}
public void testIncorrectOverridesEvaluation13() { runTest("incorrect overrides evaluation - 1.3"); }
public void testIncorrectOverridesEvaluation15() { runTest("incorrect overrides evaluation - 1.5"); }
public void testAtWithinCodeBug_pr138798() { runTest("atWithinCodeBug"); }
// known failures, uncomment when working.
public void testReferencePCutInDeclareWarning_pr138215() { runTest("Reference pointcut fails inside @DeclareWarning");}
// public void testReferencePCutInPerClause_pr138219() { runTest("Can't use a FQ Reference pointcut in any pointcut expression referenced by a per-clause");}
// public void testDoubleAnnotationMatching_pr138223() { runTest("Double at annotation matching (no binding)");}
public void testSuperCallsInAtAspectJAdvice_pr139749() { runTest("Super calls in @AspectJ advice");}
public void testNoClassCastExceptionWithPerThis_pr138286() { runTest("No ClassCastException with perThis");}
// this next one reported as a bug by Rob Harrop, but I can't reproduce the failure yet...
//public void testAtAspectWithReferencePCPerClause_pr138220() { runTest("@Aspect with reference pointcut in perclause");}
public void testJarChecking_pr137235_1() { runTest("directory with .jar extension: source and outjar"); }
public void testJarChecking_pr137235_2() { runTest("directory with .jar extension"); }
public void testMakePreMethodNPE_pr136393() { runTest("NPE in makePreMethod");}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc152Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc152/ajc152.xml");
}
}
|
135,068 |
Bug 135068 VerifyError with LTW and @AJ style aspects
|
I get "VerifyError: Incompatible object argument for function call" error when using LTW with @Aspect stype aspects. Interestingly enough, LTW works as expected with equivalent .aj style aspect. Compile time weaving works with both aspect styles. Tested on Linux with AspectJ 1.5.0, 1.5.1 and DEVELOPMENT-20060404163823 and SUN 1.5.0_06 and IBM 1.5.0SR1 JVMs. I will attach example project shortly.
|
resolved fixed
|
9ffc63b
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T07:38:53Z | 2006-04-05T15:13:20Z |
weaver/src/org/aspectj/weaver/bcel/AtAjAttributes.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* initial implementation Alexandre Vasseur
*******************************************************************************/
package org.aspectj.weaver.bcel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.aspectj.apache.bcel.Constants;
import org.aspectj.apache.bcel.classfile.Attribute;
import org.aspectj.apache.bcel.classfile.Constant;
import org.aspectj.apache.bcel.classfile.ConstantUtf8;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.LocalVariable;
import org.aspectj.apache.bcel.classfile.LocalVariableTable;
import org.aspectj.apache.bcel.classfile.Method;
import org.aspectj.apache.bcel.classfile.annotation.Annotation;
import org.aspectj.apache.bcel.classfile.annotation.ClassElementValue;
import org.aspectj.apache.bcel.classfile.annotation.ElementNameValuePair;
import org.aspectj.apache.bcel.classfile.annotation.RuntimeAnnotations;
import org.aspectj.apache.bcel.classfile.annotation.RuntimeVisibleAnnotations;
import org.aspectj.apache.bcel.generic.Type;
import org.aspectj.asm.AsmManager;
import org.aspectj.asm.IHierarchy;
import org.aspectj.asm.IProgramElement;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHandler;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.weaver.Advice;
import org.aspectj.weaver.AdviceKind;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.IHasPosition;
import org.aspectj.weaver.ISourceContext;
import org.aspectj.weaver.MethodDelegateTypeMunger;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedPointcutDefinition;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.patterns.AndPointcut;
import org.aspectj.weaver.patterns.Bindings;
import org.aspectj.weaver.patterns.DeclareErrorOrWarning;
import org.aspectj.weaver.patterns.DeclareParents;
import org.aspectj.weaver.patterns.DeclarePrecedence;
import org.aspectj.weaver.patterns.FormalBinding;
import org.aspectj.weaver.patterns.IScope;
import org.aspectj.weaver.patterns.IdentityPointcutVisitor;
import org.aspectj.weaver.patterns.IfPointcut;
import org.aspectj.weaver.patterns.NotPointcut;
import org.aspectj.weaver.patterns.OrPointcut;
import org.aspectj.weaver.patterns.ParserException;
import org.aspectj.weaver.patterns.PatternParser;
import org.aspectj.weaver.patterns.PerCflow;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.PerFromSuper;
import org.aspectj.weaver.patterns.PerObject;
import org.aspectj.weaver.patterns.PerSingleton;
import org.aspectj.weaver.patterns.PerTypeWithin;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.SimpleScope;
import org.aspectj.weaver.patterns.TypePattern;
/**
* Annotation defined aspect reader.
* <p/>
* It reads the Java 5 annotations and turns them into AjAttributes
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class AtAjAttributes {
private final static List EMPTY_LIST = new ArrayList();
private final static String[] EMPTY_STRINGS = new String[0];
private final static String VALUE = "value";
private final static String POINTCUT = "pointcut";
private final static String THROWING = "throwing";
private final static String RETURNING = "returning";
private final static String STRING_DESC = "Ljava/lang/String;";
/**
* A struct that allows to add extra arguments without always breaking the API
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
private static class AjAttributeStruct {
/**
* The list of AjAttribute.XXX that we are populating from the @AJ read
*/
List ajAttributes = new ArrayList();
/**
* The resolved type (class) for which we are reading @AJ for (be it class, method, field annotations)
*/
final ResolvedType enclosingType;
final ISourceContext context;
final IMessageHandler handler;
public AjAttributeStruct(ResolvedType type, ISourceContext sourceContext, IMessageHandler messageHandler) {
enclosingType = type;
context = sourceContext;
handler = messageHandler;
}
}
/**
* A struct when we read @AJ on method
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
private static class AjAttributeMethodStruct extends AjAttributeStruct {
/**
* Argument names as they appear in the SOURCE code, ordered, and lazyly populated
* Used to do formal binding
*/
private String[] m_argumentNamesLazy = null;
final Method method;
final BcelMethod bMethod;
public AjAttributeMethodStruct(Method method, BcelMethod bMethod, ResolvedType type, ISourceContext sourceContext, IMessageHandler messageHandler) {
super(type, sourceContext, messageHandler);
this.method = method;
this.bMethod = bMethod;
}
public String[] getArgumentNames() {
if (m_argumentNamesLazy == null) {
m_argumentNamesLazy = getMethodArgumentNamesAsInSource(method);
}
return m_argumentNamesLazy;
}
}
/**
* A struct when we read @AJ on field
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
private static class AjAttributeFieldStruct extends AjAttributeStruct {
final Field field;
final BcelField bField;
public AjAttributeFieldStruct(Field field, BcelField bField, ResolvedType type, ISourceContext sourceContext, IMessageHandler messageHandler) {
super(type, sourceContext, messageHandler);
this.field = field;
this.bField = bField;
}
}
/**
* Annotations are RuntimeVisible only. This allow us to not visit RuntimeInvisible ones.
*
* @param attribute
* @return true if runtime visible annotation
*/
public static boolean acceptAttribute(Attribute attribute) {
return (attribute instanceof RuntimeVisibleAnnotations);
}
/**
* Extract class level annotations and turn them into AjAttributes.
*
* @param javaClass
* @param type
* @param context
* @param msgHandler
* @return list of AjAttributes
*/
public static List readAj5ClassAttributes(JavaClass javaClass, ReferenceType type, ISourceContext context, IMessageHandler msgHandler, boolean isCodeStyleAspect) {
//FIXME AV - 1.5 feature limitation, kick after implemented
try {
Constant[] cpool = javaClass.getConstantPool().getConstantPool();
for (int i = 0; i < cpool.length; i++) {
Constant constant = cpool[i];
if (constant != null && constant.getTag() == Constants.CONSTANT_Utf8) {
if (!javaClass.getClassName().startsWith("org.aspectj.lang.annotation")) {
ConstantUtf8 constantUtf8 = (ConstantUtf8) constant;
if ("Lorg/aspectj/lang/annotation/DeclareAnnotation;".equals(constantUtf8.getBytes())) {
msgHandler.handleMessage(
new Message(
"Found @DeclareAnnotation while current release does not support it (see '" + type.getName() + "')",
IMessage.WARNING,
null,
type.getSourceLocation()
)
);
}
}
}
}
} catch (Throwable t) {
;
}
AjAttributeStruct struct = new AjAttributeStruct(type, context, msgHandler);
Attribute[] attributes = javaClass.getAttributes();
boolean hasAtAspectAnnotation = false;
boolean hasAtPrecedenceAnnotation = false;
for (int i = 0; i < attributes.length; i++) {
Attribute attribute = attributes[i];
if (acceptAttribute(attribute)) {
RuntimeAnnotations rvs = (RuntimeAnnotations) attribute;
// we don't need to look for several attribute occurence since it cannot happen as per JSR175
if (!isCodeStyleAspect && !javaClass.isInterface()) {
hasAtAspectAnnotation = handleAspectAnnotation(rvs, struct);
//TODO AV - if put outside the if isCodeStyleAspect then we would enable mix style
hasAtPrecedenceAnnotation = handlePrecedenceAnnotation(rvs, struct);
}
// there can only be one RuntimeVisible bytecode attribute
break;
}
}
// basic semantic check
if (hasAtPrecedenceAnnotation && !hasAtAspectAnnotation) {
msgHandler.handleMessage(
new Message(
"Found @DeclarePrecedence on a non @Aspect type '" + type.getName() + "'",
IMessage.WARNING,
null,
type.getSourceLocation()
)
);
// bypass what we have read
return EMPTY_LIST;
}
// the following block will not detect @Pointcut in non @Aspect types for optimization purpose
if (!hasAtAspectAnnotation) {
return EMPTY_LIST;
}
//FIXME AV - turn on when ajcMightHaveAspect
// if (hasAtAspectAnnotation && type.isInterface()) {
// msgHandler.handleMessage(
// new Message(
// "Found @Aspect on an interface type '" + type.getName() + "'",
// IMessage.WARNING,
// null,
// type.getSourceLocation()
// )
// );
// // bypass what we have read
// return EMPTY_LIST;
// }
// semantic check: @Aspect must be public
// FIXME AV - do we really want to enforce that?
// if (hasAtAspectAnnotation && !javaClass.isPublic()) {
// msgHandler.handleMessage(
// new Message(
// "Found @Aspect annotation on a non public class '" + javaClass.getClassName() + "'",
// IMessage.ERROR,
// null,
// type.getSourceLocation()
// )
// );
// return EMPTY_LIST;
// }
// code style pointcuts are class attributes
// we need to gather the @AJ pointcut right now and not at method level annotation extraction time
// in order to be able to resolve the pointcut references later on
// we don't need to look in super class, the pointcut reference in the grammar will do it
for (int i = 0; i < javaClass.getMethods().length; i++) {
Method method = javaClass.getMethods()[i];
if (method.getName().startsWith(NameMangler.PREFIX)) continue; // already dealt with by ajc...
//FIXME alex optimize, this method struct will gets recreated for advice extraction
AjAttributeMethodStruct mstruct = new AjAttributeMethodStruct(method, null, type, context, msgHandler);//FIXME AVASM
Attribute[] mattributes = method.getAttributes();
for (int j = 0; j < mattributes.length; j++) {
Attribute mattribute = mattributes[j];
if (acceptAttribute(mattribute)) {
RuntimeAnnotations mrvs = (RuntimeAnnotations) mattribute;
handlePointcutAnnotation(mrvs, mstruct);
// there can only be one RuntimeVisible bytecode attribute
break;
}
}
// FIXME asc should check we aren't adding multiple versions... will do once I get the tests passing again...
struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo());
struct.ajAttributes.addAll(mstruct.ajAttributes);
}
// code style declare error / warning / implements / parents are field attributes
for (int i = 0; i < javaClass.getFields().length; i++) {
Field field = javaClass.getFields()[i];
if (field.getName().startsWith(NameMangler.PREFIX)) continue; // already dealt with by ajc...
//FIXME alex optimize, this method struct will gets recreated for advice extraction
AjAttributeFieldStruct fstruct = new AjAttributeFieldStruct(field, null, type, context, msgHandler);
Attribute[] fattributes = field.getAttributes();
for (int j = 0; j < fattributes.length; j++) {
Attribute fattribute = fattributes[j];
if (acceptAttribute(fattribute)) {
RuntimeAnnotations frvs = (RuntimeAnnotations) fattribute;
if (handleDeclareErrorOrWarningAnnotation(frvs, fstruct)
|| handleDeclareParentsAnnotation(frvs, fstruct)) {
// semantic check - must be in an @Aspect [remove if previous block bypassed in advance]
if (!type.isAnnotationStyleAspect()) {
msgHandler.handleMessage(
new Message(
"Found @AspectJ annotations in a non @Aspect type '" + type.getName() + "'",
IMessage.WARNING,
null,
type.getSourceLocation()
)
);
;// go ahead
}
}
// there can only be one RuntimeVisible bytecode attribute
break;
}
}
struct.ajAttributes.addAll(fstruct.ajAttributes);
}
return struct.ajAttributes;
}
/**
* Extract method level annotations and turn them into AjAttributes.
*
* @param method
* @param type
* @param context
* @param msgHandler
* @return list of AjAttributes
*/
public static List readAj5MethodAttributes(Method method, BcelMethod bMethod, ResolvedType type, ResolvedPointcutDefinition preResolvedPointcut, ISourceContext context, IMessageHandler msgHandler) {
if (method.getName().startsWith(NameMangler.PREFIX)) return Collections.EMPTY_LIST; // already dealt with by ajc...
AjAttributeMethodStruct struct = new AjAttributeMethodStruct(method, bMethod, type, context, msgHandler);
Attribute[] attributes = method.getAttributes();
// we remember if we found one @AJ annotation for minimal semantic error reporting
// the real reporting beeing done thru AJDT and the compiler mapping @AJ to AjAtttribute
// or thru APT
//
// Note: we could actually skip the whole thing if type is not itself an @Aspect
// but then we would not see any warning. We do bypass for pointcut but not for advice since it would
// be too silent.
boolean hasAtAspectJAnnotation = false;
boolean hasAtAspectJAnnotationMustReturnVoid = false;
for (int i = 0; i < attributes.length; i++) {
Attribute attribute = attributes[i];
try {
if (acceptAttribute(attribute)) {
RuntimeAnnotations rvs = (RuntimeAnnotations) attribute;
hasAtAspectJAnnotationMustReturnVoid = hasAtAspectJAnnotationMustReturnVoid || handleBeforeAnnotation(
rvs, struct, preResolvedPointcut
);
hasAtAspectJAnnotationMustReturnVoid = hasAtAspectJAnnotationMustReturnVoid || handleAfterAnnotation(
rvs, struct, preResolvedPointcut
);
hasAtAspectJAnnotationMustReturnVoid = hasAtAspectJAnnotationMustReturnVoid || handleAfterReturningAnnotation(
rvs, struct, preResolvedPointcut, bMethod
);
hasAtAspectJAnnotationMustReturnVoid = hasAtAspectJAnnotationMustReturnVoid || handleAfterThrowingAnnotation(
rvs, struct, preResolvedPointcut, bMethod
);
hasAtAspectJAnnotation = hasAtAspectJAnnotation || handleAroundAnnotation(
rvs, struct, preResolvedPointcut
);
// there can only be one RuntimeVisible bytecode attribute
break;
}
} catch (ReturningFormalNotDeclaredInAdviceSignatureException e) {
msgHandler.handleMessage(
new Message(
WeaverMessages.format(WeaverMessages.RETURNING_FORMAL_NOT_DECLARED_IN_ADVICE,e.getFormalName()),
IMessage.ERROR,
null,
bMethod.getSourceLocation())
);
} catch (ThrownFormalNotDeclaredInAdviceSignatureException e) {
msgHandler.handleMessage(
new Message(
WeaverMessages.format(WeaverMessages.THROWN_FORMAL_NOT_DECLARED_IN_ADVICE,e.getFormalName()),
IMessage.ERROR,
null,
bMethod.getSourceLocation())
); }
}
hasAtAspectJAnnotation = hasAtAspectJAnnotation || hasAtAspectJAnnotationMustReturnVoid;
// semantic check - must be in an @Aspect [remove if previous block bypassed in advance]
if (hasAtAspectJAnnotation && !type.isAnnotationStyleAspect()) {
msgHandler.handleMessage(
new Message(
"Found @AspectJ annotations in a non @Aspect type '" + type.getName() + "'",
IMessage.WARNING,
null,
type.getSourceLocation()
)
);
;// go ahead
}
// semantic check - advice must be public
if (hasAtAspectJAnnotation && !struct.method.isPublic()) {
msgHandler.handleMessage(
new Message(
"Found @AspectJ annotation on a non public advice '" + methodToString(struct.method) + "'",
IMessage.ERROR,
null,
type.getSourceLocation()
)
);
;// go ahead
}
// semantic check for non around advice must return void
if (hasAtAspectJAnnotationMustReturnVoid && !Type.VOID.equals(struct.method.getReturnType())) {
msgHandler.handleMessage(
new Message(
"Found @AspectJ annotation on a non around advice not returning void '" + methodToString(
struct.method
) + "'",
IMessage.ERROR,
null,
type.getSourceLocation()
)
);
;// go ahead
}
return struct.ajAttributes;
}
/**
* Extract field level annotations and turn them into AjAttributes.
*
* @param field
* @param type
* @param context
* @param msgHandler
* @return list of AjAttributes, always empty for now
*/
public static List readAj5FieldAttributes(Field field, BcelField bField, ResolvedType type, ISourceContext context, IMessageHandler msgHandler) {
// Note: field annotation are for ITD and DEOW - processed at class level directly
return Collections.EMPTY_LIST;
}
/**
* Read @Aspect
*
* @param runtimeAnnotations
* @param struct
* @return true if found
*/
private static boolean handleAspectAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeStruct struct) {
Annotation aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.ASPECT_ANNOTATION);
if (aspect != null) {
// semantic check for inheritance (only one level up)
boolean extendsAspect = false;
if (!"java.lang.Object".equals(struct.enclosingType.getSuperclass().getName())) {
if (!struct.enclosingType.getSuperclass().isAbstract() && struct.enclosingType.getSuperclass().isAspect()) {
reportError("cannot extend a concrete aspect", struct);
return false;
}
extendsAspect = struct.enclosingType.getSuperclass().isAspect();
}
ElementNameValuePair aspectPerClause = getAnnotationElement(aspect, VALUE);
final PerClause perClause;
if (aspectPerClause == null) {
// empty value means singleton unless inherited
if (!extendsAspect) {
perClause = new PerSingleton();
} else {
perClause = new PerFromSuper(struct.enclosingType.getSuperclass().getPerClause().getKind());
}
} else {
String perX = aspectPerClause.getValue().stringifyValue();
if (perX == null || perX.length() <= 0) {
perClause = new PerSingleton();
} else {
perClause = parsePerClausePointcut(perX, struct);
}
}
if (perClause == null) {
// could not parse it, ignore the aspect
return false;
} else {
perClause.setLocation(struct.context, -1,-1);//struct.context.getOffset(), struct.context.getOffset()+1);//FIXME AVASM
// FIXME asc see related comment way about about the version...
struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo());
AjAttribute.Aspect aspectAttribute = new AjAttribute.Aspect(perClause);
struct.ajAttributes.add(aspectAttribute);
FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0];
final IScope binding;
binding = new BindingScope(
struct.enclosingType,
struct.context,
bindings
);
// // we can't resolve here since the perclause typically refers to pointcuts
// // defined in the aspect that we haven't told the BcelObjectType about yet.
//
// perClause.resolve(binding);
// so we prepare to do it later...
aspectAttribute.setResolutionScope(binding);
return true;
}
}
return false;
}
/**
* Read a perClause, returns null on failure and issue messages
*
* @param perClauseString like "pertarget(.....)"
* @param struct for which we are parsing the per clause
* @return a PerClause instance
*/
private static PerClause parsePerClausePointcut(String perClauseString, AjAttributeStruct struct) {
final String pointcutString;
Pointcut pointcut = null;
TypePattern typePattern = null;
final PerClause perClause;
if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERCFLOW.getName())) {
pointcutString = PerClause.KindAnnotationPrefix.PERCFLOW.extractPointcut(perClauseString);
pointcut = parsePointcut(pointcutString, struct, false);
perClause = new PerCflow(pointcut, false);
} else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERCFLOWBELOW.getName())) {
pointcutString = PerClause.KindAnnotationPrefix.PERCFLOWBELOW.extractPointcut(perClauseString);
pointcut = parsePointcut(pointcutString, struct, false);
perClause = new PerCflow(pointcut, true);
} else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERTARGET.getName())) {
pointcutString = PerClause.KindAnnotationPrefix.PERTARGET.extractPointcut(perClauseString);
pointcut = parsePointcut(pointcutString, struct, false);
perClause = new PerObject(pointcut, false);
} else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERTHIS.getName())) {
pointcutString = PerClause.KindAnnotationPrefix.PERTHIS.extractPointcut(perClauseString);
pointcut = parsePointcut(pointcutString, struct, false);
perClause = new PerObject(pointcut, true);
} else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERTYPEWITHIN.getName())) {
pointcutString = PerClause.KindAnnotationPrefix.PERTYPEWITHIN.extractPointcut(perClauseString);
typePattern = parseTypePattern(pointcutString, struct);
perClause = new PerTypeWithin(typePattern);
} else if (perClauseString.equalsIgnoreCase(PerClause.SINGLETON.getName() + "()")) {
perClause = new PerSingleton();
} else {
// could not parse the @AJ perclause - fallback to singleton and issue an error
reportError("@Aspect per clause cannot be read '" + perClauseString + "'", struct);
return null;
}
if (!PerClause.SINGLETON.equals(perClause.getKind())
&& !PerClause.PERTYPEWITHIN.equals(perClause.getKind())
&& pointcut == null) {
// we could not parse the pointcut
return null;
}
if (PerClause.PERTYPEWITHIN.equals(perClause.getKind()) && typePattern == null) {
// we could not parse the type pattern
return null;
}
return perClause;
}
/**
* Read @DeclarePrecedence
*
* @param runtimeAnnotations
* @param struct
* @return true if found
*/
private static boolean handlePrecedenceAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeStruct struct) {
Annotation aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREPRECEDENCE_ANNOTATION);
if (aspect != null) {
ElementNameValuePair precedence = getAnnotationElement(aspect, VALUE);
if (precedence != null) {
String precedencePattern = precedence.getValue().stringifyValue();
PatternParser parser = new PatternParser(precedencePattern);
DeclarePrecedence ajPrecedence = parser.parseDominates();
struct.ajAttributes.add(new AjAttribute.DeclareAttribute(ajPrecedence));
return true;
}
}
return false;
}
// /**
// * Read @DeclareImplements
// *
// * @param runtimeAnnotations
// * @param struct
// * @return true if found
// */
// private static boolean handleDeclareImplementsAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeFieldStruct struct) {//, ResolvedPointcutDefinition preResolvedPointcut) {
// Annotation deci = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREIMPLEMENTS_ANNOTATION);
// if (deci != null) {
// ElementNameValuePair deciPatternNVP = getAnnotationElement(deci, VALUE);
// String deciPattern = deciPatternNVP.getValue().stringifyValue();
// if (deciPattern != null) {
// TypePattern typePattern = parseTypePattern(deciPattern, struct);
// ResolvedType fieldType = UnresolvedType.forSignature(struct.field.getSignature()).resolve(struct.enclosingType.getWorld());
// if (fieldType.isPrimitiveType()) {
// return false;
// } else if (fieldType.isInterface()) {
// TypePattern parent = new ExactTypePattern(UnresolvedType.forSignature(struct.field.getSignature()), false, false);
// parent.resolve(struct.enclosingType.getWorld());
// List parents = new ArrayList(1);
// parents.add(parent);
// //TODO kick ISourceLocation sl = struct.bField.getSourceLocation(); ??
// struct.ajAttributes.add(
// new AjAttribute.DeclareAttribute(
// new DeclareParents(
// typePattern,
// parents,
// false
// )
// )
// );
// return true;
// } else {
// reportError("@DeclareImplements: can only be used on field whose type is an interface", struct);
// return false;
// }
// }
// }
// return false;
// }
/**
* Read @DeclareParents
*
* @param runtimeAnnotations
* @param struct
* @return true if found
*/
private static boolean handleDeclareParentsAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeFieldStruct struct) {//, ResolvedPointcutDefinition preResolvedPointcut) {
Annotation decp = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREPARENTS_ANNOTATION);
if (decp != null) {
ElementNameValuePair decpPatternNVP = getAnnotationElement(decp, VALUE);
String decpPattern = decpPatternNVP.getValue().stringifyValue();
if (decpPattern != null) {
TypePattern typePattern = parseTypePattern(decpPattern, struct);
ResolvedType fieldType = UnresolvedType.forSignature(struct.field.getSignature()).resolve(struct.enclosingType.getWorld());
if (fieldType.isInterface()) {
TypePattern parent = parseTypePattern(fieldType.getName(),struct);
FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0];
IScope binding = new BindingScope(struct.enclosingType,struct.context,bindings);
// first add the declare implements like
List parents = new ArrayList(1); parents.add(parent);
DeclareParents dp = new DeclareParents(typePattern,parents,false);
dp.resolve(binding); // resolves the parent and child parts of the decp
// resolve this so that we can use it for the MethodDelegateMungers below.
// eg. '@Coloured *' will change from a WildTypePattern to an 'AnyWithAnnotationTypePattern' after this resolution
typePattern = typePattern.resolveBindings(binding, Bindings.NONE, false, false);
//TODO kick ISourceLocation sl = struct.bField.getSourceLocation(); ??
// dp.setLocation(dp.getDeclaringType().getSourceContext(), dp.getDeclaringType().getSourceLocation().getOffset(), dp.getDeclaringType().getSourceLocation().getOffset());
dp.setLocation(struct.context,-1,-1); // not ideal...
struct.ajAttributes.add(new AjAttribute.DeclareAttribute(dp));
// do we have a defaultImpl=xxx.class (ie implementation)
String defaultImplClassName = null;
ElementNameValuePair defaultImplNVP = getAnnotationElement(decp, "defaultImpl");
if (defaultImplNVP != null) {
ClassElementValue defaultImpl = (ClassElementValue) defaultImplNVP.getValue();
defaultImplClassName = UnresolvedType.forSignature(defaultImpl.getClassString()).getName();
if (defaultImplClassName.equals("org.aspectj.lang.annotation.DeclareParents")) {
defaultImplClassName = null;
} else {
// check public no arg ctor
ResolvedType impl = struct.enclosingType.getWorld().resolve(
defaultImplClassName,
false
);
ResolvedMember[] mm = impl.getDeclaredMethods();
boolean hasNoCtorOrANoArgOne = true;
for (int i = 0; i < mm.length; i++) {
ResolvedMember resolvedMember = mm[i];
if (resolvedMember.getName().equals("<init>")) {
hasNoCtorOrANoArgOne = false;
if (resolvedMember.getParameterTypes().length == 0
&& resolvedMember.isPublic()) {
hasNoCtorOrANoArgOne = true;
}
}
if (hasNoCtorOrANoArgOne) {
break;
}
}
if (!hasNoCtorOrANoArgOne) {
reportError("@DeclareParents: defaultImpl=\""
+ defaultImplClassName
+ "\" has no public no-arg constructor", struct);
}
}
}
// then iterate on field interface hierarchy (not object)
boolean hasAtLeastOneMethod = false;
ResolvedMember[] methods = (ResolvedMember[])fieldType.getMethodsWithoutIterator(true, false).toArray(new ResolvedMember[0]);
for (int i = 0; i < methods.length; i++) {
ResolvedMember method = (ResolvedMember)methods[i];
if (method.isAbstract()) {
if (defaultImplClassName == null) {
// non marker interface with no default impl provided
reportError("@DeclareParents: used with a non marker interface and no defaultImpl=\"...\" provided", struct);
return false;
}
hasAtLeastOneMethod = true;
struct.ajAttributes.add(
new AjAttribute.TypeMunger(
new MethodDelegateTypeMunger(
method,
struct.enclosingType,
defaultImplClassName,
typePattern
)
)
);
}
}
// successfull so far, we thus need a bcel type munger to have
// a field hosting the mixin in the target type
if (hasAtLeastOneMethod) {
struct.ajAttributes.add(
new AjAttribute.TypeMunger(
new MethodDelegateTypeMunger.FieldHostTypeMunger(
AjcMemberMaker.itdAtDeclareParentsField(
null,//prototyped
fieldType,
struct.enclosingType
),
struct.enclosingType,
typePattern
)
)
);
}
return true;
} else {
reportError("@DeclareParents: can only be used on a field whose type is an interface", struct);
return false;
}
}
}
return false;
}
/**
* Read @Before
*
* @param runtimeAnnotations
* @param struct
* @return true if found
*/
private static boolean handleBeforeAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeMethodStruct struct, ResolvedPointcutDefinition preResolvedPointcut) {
Annotation before = getAnnotation(runtimeAnnotations, AjcMemberMaker.BEFORE_ANNOTATION);
if (before != null) {
ElementNameValuePair beforeAdvice = getAnnotationElement(before, VALUE);
if (beforeAdvice != null) {
// this/target/args binding
FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0];
try {
bindings = extractBindings(struct);
} catch (UnreadableDebugInfoException unreadableDebugInfoException) {
return false;
}
IScope binding = new BindingScope(
struct.enclosingType,
struct.context,
bindings
);
// joinpoint, staticJoinpoint binding
int extraArgument = extractExtraArgument(struct.method);
Pointcut pc = null;
if (preResolvedPointcut != null) {
pc = preResolvedPointcut.getPointcut();
//pc.resolve(binding);
} else {
pc = parsePointcut(beforeAdvice.getValue().stringifyValue(), struct, false);
if (pc == null) return false;//parse error
pc = pc.resolve(binding);
}
setIgnoreUnboundBindingNames(pc, bindings);
ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(), struct.bMethod.getDeclarationOffset());
struct.ajAttributes.add(
new AjAttribute.AdviceAttribute(
AdviceKind.Before,
pc,
extraArgument,
sl.getOffset(),
sl.getOffset()+1,//FIXME AVASM
struct.context
)
);
return true;
}
}
return false;
}
/**
* Read @After
*
* @param runtimeAnnotations
* @param struct
* @return true if found
*/
private static boolean handleAfterAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeMethodStruct struct, ResolvedPointcutDefinition preResolvedPointcut) {
Annotation after = getAnnotation(runtimeAnnotations, AjcMemberMaker.AFTER_ANNOTATION);
if (after != null) {
ElementNameValuePair afterAdvice = getAnnotationElement(after, VALUE);
if (afterAdvice != null) {
// this/target/args binding
FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0];
try {
bindings = extractBindings(struct);
} catch (UnreadableDebugInfoException unreadableDebugInfoException) {
return false;
}
IScope binding = new BindingScope(
struct.enclosingType,
struct.context,
bindings
);
// joinpoint, staticJoinpoint binding
int extraArgument = extractExtraArgument(struct.method);
Pointcut pc = null;
if (preResolvedPointcut != null) {
pc = preResolvedPointcut.getPointcut();
} else {
pc = parsePointcut(afterAdvice.getValue().stringifyValue(), struct, false);
if (pc == null) return false;//parse error
pc.resolve(binding);
}
setIgnoreUnboundBindingNames(pc, bindings);
ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(), struct.bMethod.getDeclarationOffset());
struct.ajAttributes.add(
new AjAttribute.AdviceAttribute(
AdviceKind.After,
pc,
extraArgument,
sl.getOffset(),
sl.getOffset()+1,//FIXME AVASM
struct.context
)
);
return true;
}
}
return false;
}
/**
* Read @AfterReturning
*
* @param runtimeAnnotations
* @param struct
* @return true if found
*/
private static boolean handleAfterReturningAnnotation(
RuntimeAnnotations runtimeAnnotations,
AjAttributeMethodStruct struct,
ResolvedPointcutDefinition preResolvedPointcut,
BcelMethod owningMethod)
throws ReturningFormalNotDeclaredInAdviceSignatureException
{
Annotation after = getAnnotation(runtimeAnnotations, AjcMemberMaker.AFTERRETURNING_ANNOTATION);
if (after != null) {
ElementNameValuePair annValue = getAnnotationElement(after, VALUE);
ElementNameValuePair annPointcut = getAnnotationElement(after, POINTCUT);
ElementNameValuePair annReturned = getAnnotationElement(after, RETURNING);
// extract the pointcut and returned type/binding - do some checks
String pointcut = null;
String returned = null;
if ((annValue != null && annPointcut != null) || (annValue == null && annPointcut == null)) {
reportError("@AfterReturning: either 'value' or 'poincut' must be provided, not both", struct);
return false;
}
if (annValue != null) {
pointcut = annValue.getValue().stringifyValue();
} else {
pointcut = annPointcut.getValue().stringifyValue();
}
if (isNullOrEmpty(pointcut)) {
reportError("@AfterReturning: either 'value' or 'poincut' must be provided, not both", struct);
return false;
}
if (annReturned != null) {
returned = annReturned.getValue().stringifyValue();
if (isNullOrEmpty(returned)) {
returned = null;
} else {
// check that thrownFormal exists as the last parameter in the advice
String[] pNames = owningMethod.getParameterNames();
if (pNames == null || pNames.length == 0 || !Arrays.asList(pNames).contains(returned)) {
throw new ReturningFormalNotDeclaredInAdviceSignatureException(returned);
}
}
}
// this/target/args binding
// exclude the return binding from the pointcut binding since it is an extraArg binding
FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0];
try {
bindings = (returned == null ? extractBindings(struct) : extractBindings(struct, returned));
} catch (UnreadableDebugInfoException unreadableDebugInfoException) {
return false;
}
IScope binding = new BindingScope(
struct.enclosingType,
struct.context,
bindings
);
// joinpoint, staticJoinpoint binding
int extraArgument = extractExtraArgument(struct.method);
// return binding
if (returned != null) {
extraArgument |= Advice.ExtraArgument;
}
Pointcut pc = null;
if (preResolvedPointcut != null) {
pc = preResolvedPointcut.getPointcut();
} else {
pc = parsePointcut(pointcut, struct, false);
if (pc == null) return false;//parse error
pc.resolve(binding);
}
setIgnoreUnboundBindingNames(pc, bindings);
ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(), struct.bMethod.getDeclarationOffset());
struct.ajAttributes.add(
new AjAttribute.AdviceAttribute(
AdviceKind.AfterReturning,
pc,
extraArgument,
sl.getOffset(),
sl.getOffset()+1,//FIXME AVASM
struct.context
)
);
return true;
}
return false;
}
/**
* Read @AfterThrowing
*
* @param runtimeAnnotations
* @param struct
* @return true if found
*/
private static boolean handleAfterThrowingAnnotation(
RuntimeAnnotations runtimeAnnotations,
AjAttributeMethodStruct struct,
ResolvedPointcutDefinition preResolvedPointcut,
BcelMethod owningMethod)
throws ThrownFormalNotDeclaredInAdviceSignatureException
{
Annotation after = getAnnotation(runtimeAnnotations, AjcMemberMaker.AFTERTHROWING_ANNOTATION);
if (after != null) {
ElementNameValuePair annValue = getAnnotationElement(after, VALUE);
ElementNameValuePair annPointcut = getAnnotationElement(after, POINTCUT);
ElementNameValuePair annThrown = getAnnotationElement(after, THROWING);
// extract the pointcut and throwned type/binding - do some checks
String pointcut = null;
String thrownFormal = null;
if ((annValue != null && annPointcut != null) || (annValue == null && annPointcut == null)) {
reportError("@AfterThrowing: either 'value' or 'poincut' must be provided, not both", struct);
return false;
}
if (annValue != null) {
pointcut = annValue.getValue().stringifyValue();
} else {
pointcut = annPointcut.getValue().stringifyValue();
}
if (isNullOrEmpty(pointcut)) {
reportError("@AfterThrowing: either 'value' or 'poincut' must be provided, not both", struct);
return false;
}
if (annThrown != null) {
thrownFormal = annThrown.getValue().stringifyValue();
if (isNullOrEmpty(thrownFormal)) {
thrownFormal = null;
} else {
// check that thrownFormal exists as the last parameter in the advice
String[] pNames = owningMethod.getParameterNames();
if (pNames == null || pNames.length == 0 || !Arrays.asList(pNames).contains(thrownFormal)) {
throw new ThrownFormalNotDeclaredInAdviceSignatureException(thrownFormal);
}
}
}
// this/target/args binding
// exclude the throwned binding from the pointcut binding since it is an extraArg binding
FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0];
try {
bindings = (thrownFormal == null ? extractBindings(struct) : extractBindings(struct, thrownFormal));
} catch (UnreadableDebugInfoException unreadableDebugInfoException) {
return false;
}
IScope binding = new BindingScope(
struct.enclosingType,
struct.context,
bindings
);
// joinpoint, staticJoinpoint binding
int extraArgument = extractExtraArgument(struct.method);
// return binding
if (thrownFormal != null) {
extraArgument |= Advice.ExtraArgument;
}
Pointcut pc = null;
if (preResolvedPointcut != null) {
pc = preResolvedPointcut.getPointcut();
} else {
pc = parsePointcut(pointcut, struct, false);
if (pc == null) return false;//parse error
pc.resolve(binding);
}
setIgnoreUnboundBindingNames(pc, bindings);
ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(), struct.bMethod.getDeclarationOffset());
struct.ajAttributes.add(
new AjAttribute.AdviceAttribute(
AdviceKind.AfterThrowing,
pc,
extraArgument,
sl.getOffset(),
sl.getOffset()+1,//FIXME AVASM
struct.context
)
);
return true;
}
return false;
}
/**
* Read @Around
*
* @param runtimeAnnotations
* @param struct
* @return true if found
*/
private static boolean handleAroundAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeMethodStruct struct, ResolvedPointcutDefinition preResolvedPointcut) {
Annotation around = getAnnotation(runtimeAnnotations, AjcMemberMaker.AROUND_ANNOTATION);
if (around != null) {
ElementNameValuePair aroundAdvice = getAnnotationElement(around, VALUE);
if (aroundAdvice != null) {
// this/target/args binding
FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0];
try {
bindings = extractBindings(struct);
} catch (UnreadableDebugInfoException unreadableDebugInfoException) {
return false;
}
IScope binding = new BindingScope(
struct.enclosingType,
struct.context,
bindings
);
// joinpoint, staticJoinpoint binding
int extraArgument = extractExtraArgument(struct.method);
Pointcut pc = null;
if (preResolvedPointcut != null) {
pc = preResolvedPointcut.getPointcut();
} else {
pc = parsePointcut(aroundAdvice.getValue().stringifyValue(), struct, false);
if (pc == null) return false;//parse error
pc.resolve(binding);
}
setIgnoreUnboundBindingNames(pc, bindings);
ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(), struct.bMethod.getDeclarationOffset());
struct.ajAttributes.add(
new AjAttribute.AdviceAttribute(
AdviceKind.Around,
pc,
extraArgument,
sl.getOffset(),
sl.getOffset()+1,//FIXME AVASM
struct.context
)
);
return true;
}
}
return false;
}
/**
* Read @Pointcut and handle the resolving in a lazy way to deal with pointcut references
*
* @param runtimeAnnotations
* @param struct
*/
private static void handlePointcutAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeMethodStruct struct) {
Annotation pointcut = getAnnotation(runtimeAnnotations, AjcMemberMaker.POINTCUT_ANNOTATION);
if (pointcut != null) {
ElementNameValuePair pointcutExpr = getAnnotationElement(pointcut, VALUE);
// semantic check: the method must return void, or be "public static boolean" for if() support
if (!(Type.VOID.equals(struct.method.getReturnType())
|| (Type.BOOLEAN.equals(struct.method.getReturnType()) && struct.method.isStatic() && struct.method.isPublic()))) {
reportWarning("Found @Pointcut on a method not returning 'void' or not 'public static boolean'", struct);
;//no need to stop
}
// semantic check: the method must not throw anything
if (struct.method.getExceptionTable() != null) {
reportWarning("Found @Pointcut on a method throwing exception", struct);
;// no need to stop
}
// this/target/args binding
final IScope binding;
try {
binding = new BindingScope(
struct.enclosingType,
struct.context,
extractBindings(struct)
);
} catch (UnreadableDebugInfoException e) {
return;
}
UnresolvedType[] argumentTypes = new UnresolvedType[struct.method.getArgumentTypes().length];
for (int i = 0; i < argumentTypes.length; i++) {
argumentTypes[i] = UnresolvedType.forSignature(struct.method.getArgumentTypes()[i].getSignature());
}
Pointcut pc = null;
if (struct.method.isAbstract()) {
if ((pointcutExpr != null && isNullOrEmpty(pointcutExpr.getValue().stringifyValue()))
|| pointcutExpr == null) {
// abstract pointcut
// leave pc = null
} else {
reportError("Found defined @Pointcut on an abstract method", struct);
return;//stop
}
} else {
if (pointcutExpr==null || (pointcutExpr != null && isNullOrEmpty(pointcutExpr.getValue().stringifyValue()))) {
// the matches nothing pointcut (125475/125480) - perhaps not as cleanly supported as it could be.
} else {
if (pointcutExpr != null) {
// use a LazyResolvedPointcutDefinition so that the pointcut is resolved lazily
// since for it to be resolved, we will need other pointcuts to be registered as well
pc = parsePointcut(pointcutExpr.getValue().stringifyValue(), struct, true);
if (pc == null) return;//parse error
pc.setLocation(struct.context, -1, -1);//FIXME AVASM !! bMethod is null here..
} else {
reportError("Found undefined @Pointcut on a non-abstract method", struct);
return;
}
}
}
// do not resolve binding now but lazily
struct.ajAttributes.add(
new AjAttribute.PointcutDeclarationAttribute(
new LazyResolvedPointcutDefinition(
struct.enclosingType,
struct.method.getModifiers(),
struct.method.getName(),
argumentTypes,
UnresolvedType.forSignature(struct.method.getReturnType().getSignature()),
pc,//can be null for abstract pointcut
binding
)
)
);
}
}
/**
* Read @DeclareError, @DeclareWarning
*
* @param runtimeAnnotations
* @param struct
* @return true if found
*/
private static boolean handleDeclareErrorOrWarningAnnotation(RuntimeAnnotations runtimeAnnotations, AjAttributeFieldStruct struct) {
Annotation error = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREERROR_ANNOTATION);
boolean hasError = false;
if (error != null) {
ElementNameValuePair declareError = getAnnotationElement(error, VALUE);
if (declareError != null) {
if (!STRING_DESC.equals(struct.field.getSignature()) || struct.field.getConstantValue() == null) {
reportError("@DeclareError used on a non String constant field", struct);
return false;
}
Pointcut pc = parsePointcut(declareError.getValue().stringifyValue(), struct, false);
if (pc == null) {
hasError = false;//cannot parse pointcut
} else {
DeclareErrorOrWarning deow = new DeclareErrorOrWarning(true, pc, struct.field.getConstantValue().toString());
setDeclareErrorOrWarningLocation(deow,struct);
struct.ajAttributes.add(new AjAttribute.DeclareAttribute(deow));
hasError = true;
}
}
}
Annotation warning = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREWARNING_ANNOTATION);
boolean hasWarning = false;
if (warning != null) {
ElementNameValuePair declareWarning = getAnnotationElement(warning, VALUE);
if (declareWarning != null) {
if (!STRING_DESC.equals(struct.field.getSignature()) || struct.field.getConstantValue() == null) {
reportError("@DeclareWarning used on a non String constant field", struct);
return false;
}
Pointcut pc = parsePointcut(declareWarning.getValue().stringifyValue(), struct, false);
if (pc == null) {
hasWarning = false;//cannot parse pointcut
} else {
DeclareErrorOrWarning deow = new DeclareErrorOrWarning(false, pc, struct.field.getConstantValue().toString());
setDeclareErrorOrWarningLocation(deow,struct);
struct.ajAttributes.add(new AjAttribute.DeclareAttribute(deow));
return hasWarning = true;
}
}
}
return hasError || hasWarning;
}
/**
* Sets the location for the declare error / warning using the corresponding
* IProgramElement in the structure model. This will only fix bug 120356 if
* compiled with -emacssym, however, it does mean that the cross references
* view in AJDT will show the correct information.
*
* Other possibilities for fix:
* 1. using the information in ajcDeclareSoft (if this is set correctly)
* which will fix the problem if compiled with ajc but not if compiled
* with javac.
* 2. creating an AjAttribute called FieldDeclarationLineNumberAttribute
* (much like MethodDeclarationLineNumberAttribute) which we can ask
* for the offset. This will again only fix bug 120356 when compiled
* with ajc.
*
* @param deow
* @param struct
*/
private static void setDeclareErrorOrWarningLocation(DeclareErrorOrWarning deow, AjAttributeFieldStruct struct) {
IHierarchy top = AsmManager.getDefault().getHierarchy();
if (top.getRoot() != null) {
IProgramElement ipe = top.findElementForLabel(top.getRoot(),
IProgramElement.Kind.FIELD,struct.field.getName());
if (ipe != null && ipe.getSourceLocation() != null) {
ISourceLocation sourceLocation = ipe.getSourceLocation();
int start = sourceLocation.getOffset();
int end = start + struct.field.getName().length();
deow.setLocation(struct.context,start,end);
return;
}
}
deow.setLocation(struct.context, -1, -1);
}
/**
* Returns a readable representation of a method.
* Method.toString() is not suitable.
*
* @param method
* @return a readable representation of a method
*/
private static String methodToString(Method method) {
StringBuffer sb = new StringBuffer();
sb.append(method.getName());
sb.append(method.getSignature());
return sb.toString();
}
/**
* Returns a readable representation of a field.
* Field.toString() is not suitable.
*
* @param field
* @return a readable representation of a field
*/
private static String fieldToString(Field field) {
StringBuffer sb = new StringBuffer();
sb.append(field.getName()).append(' ');
sb.append(field.getSignature());
return sb.toString();
}
/**
* Build the bindings for a given method (pointcut / advice)
*
* @param struct
* @return null if no debug info is available
*/
private static FormalBinding[] extractBindings(AjAttributeMethodStruct struct)
throws UnreadableDebugInfoException {
Method method = struct.method;
String[] argumentNames = struct.getArgumentNames();
// assert debug info was here
if (argumentNames.length != method.getArgumentTypes().length) {
reportError("Cannot read debug info for @Aspect to handle formal binding in pointcuts (please compile with 'javac -g' or '<javac debug='true'.../>' in Ant)", struct);
throw new UnreadableDebugInfoException();
}
List bindings = new ArrayList();
for (int i = 0; i < argumentNames.length; i++) {
String argumentName = argumentNames[i];
UnresolvedType argumentType = UnresolvedType.forSignature(method.getArgumentTypes()[i].getSignature());
// do not bind JoinPoint / StaticJoinPoint / EnclosingStaticJoinPoint
// TODO solve me : this means that the JP/SJP/ESJP cannot appear as binding
// f.e. when applying advice on advice etc
if ((AjcMemberMaker.TYPEX_JOINPOINT.equals(argumentType)
|| AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.equals(argumentType)
|| AjcMemberMaker.TYPEX_STATICJOINPOINT.equals(argumentType)
|| AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.equals(argumentType)
|| AjcMemberMaker.AROUND_CLOSURE_TYPE.equals(argumentType))) {
//continue;// skip
bindings.add(new FormalBinding.ImplicitFormalBinding(argumentType, argumentName, i));
} else {
bindings.add(new FormalBinding(argumentType, argumentName, i));
}
}
return (FormalBinding[]) bindings.toArray(new FormalBinding[]{});
}
//FIXME alex deal with exclude index
private static FormalBinding[] extractBindings(AjAttributeMethodStruct struct, String excludeFormal)
throws UnreadableDebugInfoException {
FormalBinding[] bindings = extractBindings(struct);
int excludeIndex = -1;
for (int i = 0; i < bindings.length; i++) {
FormalBinding binding = bindings[i];
if (binding.getName().equals(excludeFormal)) {
excludeIndex = i;
bindings[i] = new FormalBinding.ImplicitFormalBinding(
binding.getType(), binding.getName(), binding.getIndex()
);
break;
}
}
return bindings;
//
// if (excludeIndex >= 0) {
// FormalBinding[] bindingsFiltered = new FormalBinding[bindings.length-1];
// int k = 0;
// for (int i = 0; i < bindings.length; i++) {
// if (i == excludeIndex) {
// ;
// } else {
// bindingsFiltered[k] = new FormalBinding(bindings[i].getType(), bindings[i].getName(), k);
// k++;
// }
// }
// return bindingsFiltered;
// } else {
// return bindings;
// }
}
/**
* Compute the flag for the xxxJoinPoint extra argument
*
* @param method
* @return extra arg flag
*/
private static int extractExtraArgument(Method method) {
Type[] methodArgs = method.getArgumentTypes();
String[] sigs = new String[methodArgs.length];
for (int i = 0; i < methodArgs.length; i++) {
sigs[i] = methodArgs[i].getSignature();
}
return extractExtraArgument(sigs);
}
/**
* Compute the flag for the xxxJoinPoint extra argument
*
* @param argumentSignatures
* @return extra arg flag
*/
public static int extractExtraArgument(String[] argumentSignatures) {
int extraArgument = 0;
for (int i = 0; i < argumentSignatures.length; i++) {
if (AjcMemberMaker.TYPEX_JOINPOINT.getSignature().equals(argumentSignatures[i])) {
extraArgument |= Advice.ThisJoinPoint;
} else if (AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.getSignature().equals(argumentSignatures[i])) {
extraArgument |= Advice.ThisJoinPoint;
} else if (AjcMemberMaker.TYPEX_STATICJOINPOINT.getSignature().equals(argumentSignatures[i])) {
extraArgument |= Advice.ThisJoinPointStaticPart;
} else if (AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.getSignature().equals(argumentSignatures[i])) {
extraArgument |= Advice.ThisEnclosingJoinPointStaticPart;
}
}
return extraArgument;
}
/**
* Returns the runtime (RV/RIV) annotation of type annotationType or null if no such annotation
*
* @param rvs
* @param annotationType
* @return annotation
*/
private static Annotation getAnnotation(RuntimeAnnotations rvs, UnresolvedType annotationType) {
final String annotationTypeName = annotationType.getName();
for (Iterator iterator = rvs.getAnnotations().iterator(); iterator.hasNext();) {
Annotation rv = (Annotation) iterator.next();
if (annotationTypeName.equals(rv.getTypeName())) {
return rv;
}
}
return null;
}
/**
* Returns the value of a given element of an annotation or null if not found
* Caution: Does not handles default value.
*
* @param annotation
* @param elementName
* @return annotation NVP
*/
private static ElementNameValuePair getAnnotationElement(Annotation annotation, String elementName) {
for (Iterator iterator1 = annotation.getValues().iterator(); iterator1.hasNext();) {
ElementNameValuePair element = (ElementNameValuePair) iterator1.next();
if (elementName.equals(element.getNameString())) {
return element;
}
}
return null;
}
/**
* Extract the method argument names as in source from debug info
* returns an empty array upon inconsistency
*
* @param method
* @return method arg names as in source
*/
private static String[] getMethodArgumentNamesAsInSource(Method method) {
if (method.getArgumentTypes().length == 0) {
return EMPTY_STRINGS;
}
final int startAtStackIndex = method.isStatic() ? 0 : 1;
final List arguments = new ArrayList();
LocalVariableTable lt = (LocalVariableTable) method.getLocalVariableTable();
if (lt != null) {
for (int j = 0; j < lt.getLocalVariableTable().length; j++) {
LocalVariable localVariable = lt.getLocalVariableTable()[j];
if (localVariable.getStartPC() == 0) {
if (localVariable.getIndex() >= startAtStackIndex) {
arguments.add(new MethodArgument(localVariable.getName(), localVariable.getIndex()));
}
}
}
}
if (arguments.size() != method.getArgumentTypes().length) {
return EMPTY_STRINGS;
}
// sort by index
Collections.sort(
arguments, new Comparator() {
public int compare(Object o, Object o1) {
MethodArgument mo = (MethodArgument) o;
MethodArgument mo1 = (MethodArgument) o1;
if (mo.indexOnStack == mo1.indexOnStack) {
return 0;
} else if (mo.indexOnStack > mo1.indexOnStack) {
return 1;
} else {
return -1;
}
}
}
);
String[] argumentNames = new String[arguments.size()];
int i = 0;
for (Iterator iterator = arguments.iterator(); iterator.hasNext(); i++) {
MethodArgument methodArgument = (MethodArgument) iterator.next();
argumentNames[i] = methodArgument.name;
}
return argumentNames;
}
/**
* A method argument, used for sorting by indexOnStack (ie order in signature)
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
private static class MethodArgument {
String name;
int indexOnStack;
public MethodArgument(String name, int indexOnStack) {
this.name = name;
this.indexOnStack = indexOnStack;
}
}
/**
* BindingScope that knows the enclosingType, which is needed for pointcut reference resolution
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public static class BindingScope extends SimpleScope {
private ResolvedType m_enclosingType;
private ISourceContext m_sourceContext;
public BindingScope(ResolvedType type, ISourceContext sourceContext, FormalBinding[] bindings) {
super(type.getWorld(), bindings);
m_enclosingType = type;
m_sourceContext = sourceContext;
}
public ResolvedType getEnclosingType() {
return m_enclosingType;
}
public ISourceLocation makeSourceLocation(IHasPosition location) {
return m_sourceContext.makeSourceLocation(location);
}
public UnresolvedType lookupType(String name, IHasPosition location) {
// bug 126560
if (m_enclosingType != null) {
// add the package we're in to the list of imported
// prefixes so that we can find types in the same package
String pkgName = m_enclosingType.getPackageName();
if (pkgName != null && !pkgName.equals("")) {
String[] currentImports = getImportedPrefixes();
String[] newImports = new String[currentImports.length + 1];
for (int i = 0; i < currentImports.length; i++) {
newImports[i] = currentImports[i];
}
newImports[currentImports.length] = pkgName.concat(".");
setImportedPrefixes(newImports);
}
}
return super.lookupType(name,location);
}
}
/**
* LazyResolvedPointcutDefinition lazyly resolve the pointcut so that we have time to register all
* pointcut referenced before pointcut resolution happens
*
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public static class LazyResolvedPointcutDefinition extends ResolvedPointcutDefinition {
private Pointcut m_pointcutUnresolved;
private IScope m_binding;
private Pointcut m_lazyPointcut = null;
public LazyResolvedPointcutDefinition(ResolvedType declaringType, int modifiers, String name,
UnresolvedType[] parameterTypes, UnresolvedType returnType,
Pointcut pointcut, IScope binding) {
super(declaringType, modifiers, name, parameterTypes, returnType, null);
m_pointcutUnresolved = pointcut;
m_binding = binding;
}
public Pointcut getPointcut() {
if (m_lazyPointcut == null) {
m_lazyPointcut = m_pointcutUnresolved.resolve(m_binding);
m_lazyPointcut.copyLocationFrom(m_pointcutUnresolved);
}
return m_lazyPointcut;
}
}
/**
* Helper to test empty strings
*
* @param s
* @return true if empty or null
*/
private static boolean isNullOrEmpty(String s) {
return (s == null || s.length() <= 0);
}
/**
* Set the pointcut bindings for which to ignore unbound issues, so that we can implicitly bind
* xxxJoinPoint for @AJ advices
*
* @param pointcut
* @param bindings
*/
private static void setIgnoreUnboundBindingNames(Pointcut pointcut, FormalBinding[] bindings) {
// register ImplicitBindings as to be ignored since unbound
// TODO is it likely to fail in a bad way if f.e. this(jp) etc ?
List ignores = new ArrayList();
for (int i = 0; i < bindings.length; i++) {
FormalBinding formalBinding = bindings[i];
if (formalBinding instanceof FormalBinding.ImplicitFormalBinding) {
ignores.add(formalBinding.getName());
}
}
pointcut.m_ignoreUnboundBindingForNames = (String[]) ignores.toArray(new String[ignores.size()]);
}
/**
* A check exception when we cannot read debug info (needed for formal binding)
*/
private static class UnreadableDebugInfoException extends Exception {
}
/**
* Report an error
*
* @param message
* @param location
*/
private static void reportError(String message, AjAttributeStruct location) {
if (!location.handler.isIgnoring(IMessage.ERROR)) {
location.handler.handleMessage(
new Message(
message,
location.enclosingType.getSourceLocation(),
true
)
);
}
}
/**
* Report a warning
*
* @param message
* @param location
*/
private static void reportWarning(String message, AjAttributeStruct location) {
if (!location.handler.isIgnoring(IMessage.WARNING)) {
location.handler.handleMessage(
new Message(
message,
location.enclosingType.getSourceLocation(),
false
)
);
}
}
/**
* Parse the given pointcut, return null on failure and issue an error
*
* @param pointcutString
* @param struct
* @param allowIf
* @return pointcut, unresolved
*/
private static Pointcut parsePointcut(String pointcutString, AjAttributeStruct struct, boolean allowIf) {
try {
Pointcut pointcut = new PatternParser(pointcutString, struct.context).parsePointcut();
if (!allowIf && pointcutString.indexOf("if()") >= 0 && hasIf(pointcut)) {
reportError("if() pointcut is not allowed at this pointcut location '" + pointcutString +"'", struct);
return null;
}
pointcut.setLocation(struct.context, -1, -1);//FIXME -1,-1 is not good enough
return pointcut;
} catch (ParserException e) {
reportError("Invalid pointcut '" + pointcutString + "': " + e.toString(), struct);
return null;
}
}
private static boolean hasIf(Pointcut pointcut) {
IfFinder visitor = new IfFinder();
pointcut.accept(visitor, null);
return visitor.hasIf;
}
/**
* Parse the given type pattern, return null on failure and issue an error
*
* @param patternString
* @param location
* @return type pattern
*/
private static TypePattern parseTypePattern(String patternString, AjAttributeStruct location) {
try {
TypePattern typePattern = new PatternParser(patternString).parseTypePattern();
typePattern.setLocation(location.context, -1, -1);//FIXME -1,-1 is not good enough
return typePattern;
} catch (ParserException e) {
reportError("Invalid type pattern'" + patternString + "' : " + e.getLocation(), location);
return null;
}
}
/**
* Look for an if() pointcut
*/
private static class IfFinder extends IdentityPointcutVisitor {
boolean hasIf = false;
public Object visit(IfPointcut node, Object data) {
if (node.alwaysFalse() || node.alwaysTrue()) {
;//IfFalse / IfTrue
} else {
hasIf = true;
}
return node;
}
public Object visit(AndPointcut node, Object data) {
if (!hasIf) node.getLeft().accept(this, data);
if (!hasIf) node.getRight().accept(this, data);
return node;
}
public Object visit(NotPointcut node, Object data) {
if (!hasIf) node.getNegatedPointcut().accept(this, data);
return node;
}
public Object visit(OrPointcut node, Object data) {
if (!hasIf) node.getLeft().accept(this, data);
if (!hasIf) node.getRight().accept(this, data);
return node;
}
}
static class ThrownFormalNotDeclaredInAdviceSignatureException extends Exception {
private String formalName;
public ThrownFormalNotDeclaredInAdviceSignatureException(String formalName) {
this.formalName = formalName;
}
public String getFormalName() { return formalName; }
}
static class ReturningFormalNotDeclaredInAdviceSignatureException extends Exception {
private String formalName;
public ReturningFormalNotDeclaredInAdviceSignatureException(String formalName) {
this.formalName = formalName;
}
public String getFormalName() { return formalName; }
}
}
|
141,945 |
Bug 141945 Compiler issues message concerning aop.xml even when not doing LTW
|
From the mailing list: ============= I am executing the command as below, COMMAND: ajc -inpath woven_hello1.jar -aspectpath aspect2.jar -outjar woven_hello2.jar I am getting same old error, woven_hello1.jar [error] aspect 'aspect1' woven into 'Hello' must be declared in an aop.xml file. (no source information available) I have placed both aspect1.class and aspect2.class in CLASSPATH system variable. ============== We shouldn't be putting out messages about aop.xml when we are not doing LTW - this message points the user to a solution that will not work in this case!
|
resolved fixed
|
fc7db25
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T12:30:08Z | 2006-05-16T09:00:00Z |
tests/java5/ataspectj/ataspectj/ltwreweavable/MainReweavableLogging.java
|
/*******************************************************************************
* Copyright (c) 2005 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alexandre Vasseur initial implementation
*******************************************************************************/
package ataspectj.ltwreweavable;
import ataspectj.ltwlog.MessageHolder;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Contributed by David Knibb
* @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
*/
public class MainReweavableLogging implements Advisable {
private static List joinPoints = new ArrayList();
public void test1 () {
}
public void test2 () {
}
public void addJoinPoint (String name) {
joinPoints.add(name);
}
public static void main (String[] args) {
String ERROR_STRING = "error aspect 'ataspectj.ltwreweavable.AspectReweavableLogging' woven into 'ataspectj.ltwreweavable.MainReweavableLogging' must be declared in an aop.xml file.";
if(Boolean.getBoolean("aspectDeclared")){
//if the aspect is declared there should not be an error
if (MessageHolder.startsAs( Arrays.asList( new String[]{ ERROR_STRING } )) ) {
MessageHolder.dump();
throw new RuntimeException("Error in MainReweavableLogging - unexpected error message - \"" + ERROR_STRING + "\"");
}
}
else{
//and if the aspect is not declared then there should
if (!MessageHolder.startsAs( Arrays.asList( new String[]{ ERROR_STRING } )) ) {
MessageHolder.dump();
throw new RuntimeException("Error in MainReweavableLogging - missing expected error message - \"" + ERROR_STRING + "\"");
}
}
}
}
|
130,722 |
Bug 130722 poincut references in percflow instantiation model aspects can not be resolved
|
Take these two aspects and this litte class: // source1 package test1; import test.Test; public aspect PointcutProvider { public pointcut test(): execution(* Test.*(..)); } // source2 package test; import test1.PointcutProvider; public aspect PointcutConsumer percflow(flow()) { // compiler issues the following line with // can not find pointcut test on test.PointcutConsumer pointcut mytest(): PointcutProvider.test(); // this also does not work with the same error message pointcut mytest(): test1.PointcutProvider.test(); pointcut flow(): mytest(); } // source3 package test; public class Test { public void foo() { } } Changing the consumer aspect to singleton instantiation model works.
|
resolved fixed
|
b166a7e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T15:43:08Z | 2006-03-07T11:13:20Z |
tests/bugs152/pr130722/test/Test.java
| |
130,722 |
Bug 130722 poincut references in percflow instantiation model aspects can not be resolved
|
Take these two aspects and this litte class: // source1 package test1; import test.Test; public aspect PointcutProvider { public pointcut test(): execution(* Test.*(..)); } // source2 package test; import test1.PointcutProvider; public aspect PointcutConsumer percflow(flow()) { // compiler issues the following line with // can not find pointcut test on test.PointcutConsumer pointcut mytest(): PointcutProvider.test(); // this also does not work with the same error message pointcut mytest(): test1.PointcutProvider.test(); pointcut flow(): mytest(); } // source3 package test; public class Test { public void foo() { } } Changing the consumer aspect to singleton instantiation model works.
|
resolved fixed
|
b166a7e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T15:43:08Z | 2006-03-07T11:13:20Z |
tests/src/org/aspectj/systemtest/ajc150/GenericITDsDesign.java
|
package org.aspectj.systemtest.ajc150;
import java.io.File;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.aspectj.apache.bcel.classfile.Attribute;
import org.aspectj.apache.bcel.classfile.Field;
import org.aspectj.apache.bcel.classfile.JavaClass;
import org.aspectj.apache.bcel.classfile.Signature;
import org.aspectj.apache.bcel.util.ClassPath;
import org.aspectj.apache.bcel.util.SyntheticRepository;
import org.aspectj.testing.XMLBasedAjcTestCase;
import org.aspectj.tools.ajc.Ajc;
import org.aspectj.weaver.CrosscuttingMembers;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.ResolvedTypeMunger;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.TypeVariableReference;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.BcelTypeMunger;
import org.aspectj.weaver.bcel.BcelWorld;
public class GenericITDsDesign extends XMLBasedAjcTestCase {
private World recentWorld;
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(GenericITDsDesign.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc150/ajc150.xml");
}
private void verifyDebugString(ResolvedMember theMember, String string) {
assertTrue("Expected '"+string+"' but found "+theMember.toDebugString(),
theMember.toDebugString().equals(string));
}
public static JavaClass getClassFromDisk(Ajc ajc,String classname) {
try {
ClassPath cp =
new ClassPath(ajc.getSandboxDirectory() + File.pathSeparator + System.getProperty("java.class.path"));
SyntheticRepository sRepos = SyntheticRepository.getInstance(cp);
return sRepos.loadClass(classname);
} catch (ClassNotFoundException e) {
fail("Couldn't find class "+classname+" in the sandbox directory.");
}
return null;
}
public static Signature getClassSignature(Ajc ajc,String classname) {
JavaClass clazz = getClassFromDisk(ajc,classname);
Signature sigAttr = null;
Attribute[] attrs = clazz.getAttributes();
for (int i = 0; i < attrs.length; i++) {
Attribute attribute = attrs[i];
if (attribute.getName().equals("Signature")) sigAttr = (Signature)attribute;
}
return sigAttr;
}
// Check the signature attribute on a class is correct
public static void verifyClassSignature(Ajc ajc,String classname,String sig) {
Signature sigAttr = getClassSignature(ajc,classname);
assertTrue("Failed to find signature attribute for class "+classname,sigAttr!=null);
assertTrue("Expected signature to be '"+sig+"' but was '"+sigAttr.getSignature()+"'",
sigAttr.getSignature().equals(sig));
}
public List /*BcelTypeMunger*/ getTypeMunger(String classname) {
ClassPath cp =
new ClassPath(ajc.getSandboxDirectory() + File.pathSeparator +
System.getProperty("java.class.path"));
recentWorld = new BcelWorld(cp.toString());
ReferenceType resolvedType = (ReferenceType)recentWorld.resolve(classname);
CrosscuttingMembers cmembers = resolvedType.collectCrosscuttingMembers();
List tmungers = cmembers.getTypeMungers();
return tmungers;
}
private BcelTypeMunger getMungerFromLine(String classname,int linenumber) {
List allMungers = getTypeMunger(classname);
for (Iterator iter = allMungers.iterator(); iter.hasNext();) {
BcelTypeMunger element = (BcelTypeMunger) iter.next();
if (element.getMunger().getSourceLocation().getLine()==linenumber) return element;
}
for (Iterator iter = allMungers.iterator(); iter.hasNext();) {
BcelTypeMunger element = (BcelTypeMunger) iter.next();
System.err.println("Line: "+element.getMunger().getSourceLocation().getLine()+" > "+element);
}
fail("Couldn't find a type munger from line "+linenumber+" in class "+classname);
return null;
}
public Hashtable getMeTheFields(String classname) {
JavaClass theClass = getClassFromDisk(ajc,classname);
Hashtable retval = new Hashtable();
org.aspectj.apache.bcel.classfile.Field[] fs = theClass.getFields();
for (int i = 0; i < fs.length; i++) {
Field field = fs[i];
retval.put(field.getName(),field);
}
return retval;
}
/*
test plan:
1. Serializing and recovering 'default bounds' type variable info:
a. methods
b. fields
c. ctors
2. Serializing and recovering 'extends' with a class bounded type variable info:
a. methods
b. fields
c. ctors
3. Serializing and recovering 'extends' with an interface bounded type variable info:
a. methods
b. fields
c. ctors
4. Multiple interface bounds
a. methods
b. fields
c. ctors
5. wildcard bounds '? extends/? super'
a. methods
b. fields
c. ctors
6. using type variables in an ITD from the containing aspect, no bounds
a. methods
b. fields
c. ctors
*/
// Verify: a) After storing it in a class file and recovering it (through deserialization), we can see the type
// variable and that the parameter refers to the type variable.
public void testDesignA() {
runTest("generic itds - design A");
BcelTypeMunger theBcelMunger = getMungerFromLine("X",5);
ResolvedType typeC = recentWorld.resolve("C");
ResolvedTypeMunger rtMunger = theBcelMunger.getMunger();
ResolvedMember theMember = rtMunger.getSignature();
// Let's check all parts of the member
assertTrue("Declaring type should be C: "+theMember,
theMember.getDeclaringType().equals(typeC));
TypeVariable tVar = theMember.getTypeVariables()[0];
TypeVariableReference tvrt = (TypeVariableReference)theMember.getParameterTypes()[0];
theMember.resolve(recentWorld); // resolution will join the type variables together (i.e. make them refer to the same instance)
tVar = theMember.getTypeVariables()[0];
tvrt = (TypeVariableReference)theMember.getParameterTypes()[0];
assertTrue("Post resolution, the type variable in the parameter should be identical to the type variable declared on the member",
tVar==tvrt.getTypeVariable());
}
// Verify: bounds are preserved and accessible after serialization
public void testDesignB() {
runTest("generic itds - design B");
BcelTypeMunger theBcelMunger = getMungerFromLine("X",7);
ResolvedTypeMunger rtMunger = theBcelMunger.getMunger();
ResolvedMember theMember = rtMunger.getSignature();
verifyDebugString(theMember,"<T extends java.lang.Number> void C.m0(T)");
theBcelMunger = getMungerFromLine("X",9);
rtMunger = theBcelMunger.getMunger();
theMember = rtMunger.getSignature();
verifyDebugString(theMember,"<Q extends I> void C.m1(Q)");
theBcelMunger = getMungerFromLine("X",11);
rtMunger = theBcelMunger.getMunger();
theMember = rtMunger.getSignature();
verifyDebugString(theMember,"<R extends java.lang.Number,I> void C.m2(R)");
}
// Verify: a) multiple type variables work.
// b) type variables below the 'top level' (e.g. List<A>) are preserved.
public void testDesignC() {
runTest("generic itds - design C");
BcelTypeMunger theBcelMunger = getMungerFromLine("X",9);
//System.err.println(theBcelMunger.getMunger().getSignature().toDebugString());
verifyDebugString(theBcelMunger.getMunger().getSignature(),"<T extends java.lang.Number,Q extends I> void C.m0(T, Q)");
theBcelMunger = getMungerFromLine("X",11);
System.err.println(theBcelMunger.getMunger().getSignature().toDebugString());
verifyDebugString(theBcelMunger.getMunger().getSignature(),"<A,B,C> java.util.List<A> C.m1(B, java.util.Collection<C>)");
}
// Verify: a) sharing type vars with some target type results in the correct variable names in the serialized form
public void testDesignD() {
runTest("generic itds - design D");
BcelTypeMunger theBcelMunger = getMungerFromLine("X",9);
// System.err.println(theBcelMunger.getMunger().getSignature().toDebugString());
verifyDebugString(theBcelMunger.getMunger().getSignature(),"void C.m0(R)");
theBcelMunger = getMungerFromLine("X",11);
// System.err.println(theBcelMunger.getMunger().getSignature().toDebugString());
verifyDebugString(theBcelMunger.getMunger().getSignature(),"java.util.List<Q> C.m0(Q, int, java.util.List<java.util.List<Q>>)");
}
// Verify: a) for fields, sharing type vars with some target type results in the correct entries in the class file
public void testDesignE() {
runTest("generic itds - design E");
BcelTypeMunger theBcelMunger = getMungerFromLine("X",9);
verifyDebugString(theBcelMunger.getMunger().getSignature(),"java.util.List<Z> C.ln");
assertTrue("Expected to find \"Z\": "+theBcelMunger.getTypeVariableAliases(),theBcelMunger.getTypeVariableAliases().contains("Z"));
theBcelMunger = getMungerFromLine("X",11);
verifyDebugString(theBcelMunger.getMunger().getSignature(),"Q C.n");
assertTrue("Expected to find \"Q\": "+theBcelMunger.getTypeVariableAliases(),theBcelMunger.getTypeVariableAliases().contains("Q"));
}
// Verifying what gets into a class targetted with a field ITD
public void testDesignF() {
runTest("generic itds - design F");
Hashtable fields = getMeTheFields("C");
// Declared in src as: List C.list1; and List<Z> C<Z>.list2;
Field list1 = (Field)fields.get("ajc$interField$$list1");
assertTrue("Field list1 should be of type 'Ljava/util/List;' but is "+list1.getSignature(),
list1.getSignature().equals("Ljava/util/List;"));
Field list2 = (Field)fields.get("ajc$interField$$list1");
assertTrue("Field list2 should be of type 'Ljava/util/List;' but is "+list2.getSignature(),
list2.getSignature().equals("Ljava/util/List;"));
// Declared in src as: String C.field1; and Q C<Q>.field2;
// bound for second field collapses to Object
Field field1 = (Field)fields.get("ajc$interField$$field1");
assertTrue("Field list1 should be of type 'Ljava/lang/String;' but is "+field1.getSignature(),
field1.getSignature().equals("Ljava/lang/String;"));
Field field2 = (Field)fields.get("ajc$interField$$field2");
assertTrue("Field list2 should be of type 'Ljava/lang/Object;' but is "+field2.getSignature(),
field2.getSignature().equals("Ljava/lang/Object;"));
}
// Verifying what gets into a class when an interface it implements was targetted with a field ITD
public void testDesignG() {
runTest("generic itds - design G");
Hashtable fields = getMeTheFields("C");
// The ITDs are targetting an interface. That interface is generic and is parameterized with
// 'String' when implemented in the class C. This means the fields that make it into C should
// be parameterized with String also.
// List<Z> I<Z>.ln; and Q I<Q>.n;
// Field field1 = (Field)fields.get("ajc$interField$X$I$ln");
// assertTrue("Field list1 should be of type 'Ljava/util/List;' but is "+field1.getSignature(),
// field1.getSignature().equals("Ljava/util/List;"));
// Field field2 = (Field)fields.get("ajc$interField$X$I$n");
// assertTrue("Field list2 should be of type 'Ljava/lang/String;' but is "+field2.getSignature(),
// field2.getSignature().equals("Ljava/lang/String;"));
}
// // Verify: a) sharing type vars with some target type results in the correct variable names in the serialized form
// public void testDesignE() {
// runTest("generic itds - design E");
//
// }
}
|
130,722 |
Bug 130722 poincut references in percflow instantiation model aspects can not be resolved
|
Take these two aspects and this litte class: // source1 package test1; import test.Test; public aspect PointcutProvider { public pointcut test(): execution(* Test.*(..)); } // source2 package test; import test1.PointcutProvider; public aspect PointcutConsumer percflow(flow()) { // compiler issues the following line with // can not find pointcut test on test.PointcutConsumer pointcut mytest(): PointcutProvider.test(); // this also does not work with the same error message pointcut mytest(): test1.PointcutProvider.test(); pointcut flow(): mytest(); } // source3 package test; public class Test { public void foo() { } } Changing the consumer aspect to singleton instantiation model works.
|
resolved fixed
|
b166a7e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T15:43:08Z | 2006-03-07T11:13:20Z |
tests/src/org/aspectj/systemtest/ajc152/Ajc152Tests.java
|
/*******************************************************************************
* Copyright (c) 2006 IBM
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Andy Clement - initial API and implementation
*******************************************************************************/
package org.aspectj.systemtest.ajc152;
import java.io.File;
import junit.framework.Test;
import org.aspectj.testing.XMLBasedAjcTestCase;
public class Ajc152Tests extends org.aspectj.testing.XMLBasedAjcTestCase {
public void testVerifyErrorLTW_pr135068() { runTest("ltw verifyerror");}
public void testVerifyErrorLTW_pr135068_2() { runTest("ltw verifyerror - 2");}
public void testVerifyErrorLTW_pr135068_3() { runTest("ltw verifyerror - 3");}
public void testVerifyErrorLTW_pr135068_4() { runTest("ltw verifyerror - 4");}
public void testVerifyErrorForComplexCflow_pr136026() { runTest("verifyerror");}
public void testVerifyErrorForComplexCflow_pr136026_2() { runTest("verifyerror - 2");}
public void testAnnotationsAndGenericsBCException_pr129704() { runTest("annotations and generics leading to BCException");}
public void testMethodTooBigAfterWeaving_pr138384() { runTest("method too big"); }
public void testNotAtWithincode_pr138158_1() { runTest("not at withincode - 1");}
public void testNotAtWithincode_pr138158_2() { runTest("not at withincode - 2");}
public void testNotAtWithincode_pr138158_3() { runTest("not at within - 3");}
// public void testComplexGenericDecl_pr137568() { runTest("complicated generics declaration");}
public void testNpeOnDup_pr138143() { runTest("npe on duplicate method with ataj");}
public void testPointcutsAndGenerics_pr137496_1() { runTest("pointcuts and generics - B");}
public void testPointcutsAndGenerics_pr137496_2() { runTest("pointcuts and generics - D");}
public void testPointcutsAndGenerics_pr137496_3() { runTest("pointcuts and generics - E");}
public void testPointcutsAndGenerics_pr137496_4() { runTest("pointcuts and generics - F");}
public void testPointcutsAndGenerics_pr137496_5() { runTest("pointcuts and generics - G");}
public void testPointcutsAndGenerics_pr137496_6() { runTest("pointcuts and generics - H");}
public void testAspectLibrariesAndASM_pr135001() { runTest("aspect libraries and asm");}
public void testStackOverflow_pr136258() { runTest("stack overflow");}
public void testIncorrectOverridesEvaluation13() { runTest("incorrect overrides evaluation - 1.3"); }
public void testIncorrectOverridesEvaluation15() { runTest("incorrect overrides evaluation - 1.5"); }
public void testAtWithinCodeBug_pr138798() { runTest("atWithinCodeBug"); }
// known failures, uncomment when working.
public void testReferencePCutInDeclareWarning_pr138215() { runTest("Reference pointcut fails inside @DeclareWarning");}
// public void testReferencePCutInPerClause_pr138219() { runTest("Can't use a FQ Reference pointcut in any pointcut expression referenced by a per-clause");}
// public void testDoubleAnnotationMatching_pr138223() { runTest("Double at annotation matching (no binding)");}
public void testSuperCallsInAtAspectJAdvice_pr139749() { runTest("Super calls in @AspectJ advice");}
public void testNoClassCastExceptionWithPerThis_pr138286() { runTest("No ClassCastException with perThis");}
// this next one reported as a bug by Rob Harrop, but I can't reproduce the failure yet...
//public void testAtAspectWithReferencePCPerClause_pr138220() { runTest("@Aspect with reference pointcut in perclause");}
public void testJarChecking_pr137235_1() { runTest("directory with .jar extension: source and outjar"); }
public void testJarChecking_pr137235_2() { runTest("directory with .jar extension"); }
public void testMakePreMethodNPE_pr136393() { runTest("NPE in makePreMethod");}
/////////////////////////////////////////
public static Test suite() {
return XMLBasedAjcTestCase.loadSuite(Ajc152Tests.class);
}
protected File getSpecFile() {
return new File("../tests/src/org/aspectj/systemtest/ajc152/ajc152.xml");
}
}
|
130,722 |
Bug 130722 poincut references in percflow instantiation model aspects can not be resolved
|
Take these two aspects and this litte class: // source1 package test1; import test.Test; public aspect PointcutProvider { public pointcut test(): execution(* Test.*(..)); } // source2 package test; import test1.PointcutProvider; public aspect PointcutConsumer percflow(flow()) { // compiler issues the following line with // can not find pointcut test on test.PointcutConsumer pointcut mytest(): PointcutProvider.test(); // this also does not work with the same error message pointcut mytest(): test1.PointcutProvider.test(); pointcut flow(): mytest(); } // source3 package test; public class Test { public void foo() { } } Changing the consumer aspect to singleton instantiation model works.
|
resolved fixed
|
b166a7e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T15:43:08Z | 2006-03-07T11:13:20Z |
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.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.aspectj.weaver.bcel.BcelTypeMunger;
import org.aspectj.weaver.patterns.Declare;
import org.aspectj.weaver.patterns.DeclareAnnotation;
import org.aspectj.weaver.patterns.DeclareErrorOrWarning;
import org.aspectj.weaver.patterns.DeclareParents;
import org.aspectj.weaver.patterns.DeclarePrecedence;
import org.aspectj.weaver.patterns.DeclareSoft;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.Pointcut;
import org.aspectj.weaver.patterns.PointcutRewriter;
/**
* This holds on to all members that have an invasive effect outside of
* there own compilation unit. These members need to be all gathered up and in
* a world before any weaving can take place.
*
* They are also important in the compilation process and need to be gathered
* up before the inter-type declaration weaving stage (unsurprisingly).
*
* All members are concrete.
*
* @author Jim Hugunin
*/
public class CrosscuttingMembers {
private ResolvedType inAspect;
private World world;
private PerClause perClause;
private List shadowMungers = new ArrayList(4);
private List typeMungers = new ArrayList(4);
private List lateTypeMungers = new ArrayList(0);
private List declareParents = new ArrayList(4);
private List declareSofts = new ArrayList(0);
private List declareDominates = new ArrayList(4);
// These are like declare parents type mungers
private List declareAnnotationsOnType = new ArrayList();
private List declareAnnotationsOnField = new ArrayList();
private List declareAnnotationsOnMethods = new ArrayList(); // includes ctors
public CrosscuttingMembers(ResolvedType 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) throw new Error("FIXME AV - should not happen or what ?");//return; //???
typeMungers.add(m);
}
public void addLateTypeMungers(Collection c) {
lateTypeMungers.addAll(c);
}
public void addLateTypeMunger(ConcreteTypeMunger m) {
lateTypeMungers.add(m);
}
public void addDeclares(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); ) {
addDeclare( (Declare)i.next() );
}
}
public void addDeclare(Declare declare) {
// this is not extensible, oh well
if (declare instanceof DeclareErrorOrWarning) {
ShadowMunger m = new Checker((DeclareErrorOrWarning)declare);
m.setDeclaringType(declare.getDeclaringType());
addShadowMunger(m);
} else if (declare instanceof DeclarePrecedence) {
declareDominates.add(declare);
} else if (declare instanceof DeclareParents) {
DeclareParents dp = (DeclareParents)declare;
exposeTypes(dp.getParents().getExactTypes());
declareParents.add(dp);
} else if (declare instanceof DeclareSoft) {
DeclareSoft d = (DeclareSoft)declare;
// Ordered so that during concretization we can check the related munger
ShadowMunger m = Advice.makeSoftener(world, d.getPointcut(), d.getException(),inAspect,d);
m.setDeclaringType(d.getDeclaringType());
Pointcut concretePointcut = d.getPointcut().concretize(inAspect, d.getDeclaringType(), 0,m);
m.pointcut = concretePointcut;
declareSofts.add(new DeclareSoft(d.getException(), concretePointcut));
addConcreteShadowMunger(m);
} else if (declare instanceof DeclareAnnotation) {
// FIXME asc perf Possible Improvement. Investigate why this is called twice in a weave ?
DeclareAnnotation da = (DeclareAnnotation)declare;
if (da.getAspect() == null) da.setAspect(this.inAspect);
if (da.isDeclareAtType()) {
declareAnnotationsOnType.add(da);
} else if (da.isDeclareAtField()) {
declareAnnotationsOnField.add(da);
} else if (da.isDeclareAtMethod() || da.isDeclareAtConstuctor()) {
declareAnnotationsOnMethods.add(da);
}
} else {
throw new RuntimeException("unimplemented");
}
}
public void exposeTypes(Collection typesToExpose) {
for (Iterator i = typesToExpose.iterator(); i.hasNext(); ) {
exposeType((UnresolvedType)i.next());
}
}
public void exposeType(UnresolvedType typeToExpose) {
if (ResolvedType.isMissing(typeToExpose)) return;
if (typeToExpose.isParameterizedType() || typeToExpose.isRawType()) {
if (typeToExpose instanceof ResolvedType) {
typeToExpose = ((ResolvedType)typeToExpose).getGenericType();
} else {
typeToExpose = UnresolvedType.forSignature(typeToExpose.getErasureSignature());
}
}
ResolvedMember member = new ResolvedMemberImpl(
Member.STATIC_INITIALIZATION, typeToExpose, 0, ResolvedType.VOID, "", UnresolvedType.NONE);
addTypeMunger(world.concreteTypeMunger(
new PrivilegedAccessMunger(member), inAspect));
}
public void addPrivilegedAccesses(Collection accessedMembers) {
for (Iterator i = accessedMembers.iterator(); i.hasNext(); ) {
addPrivilegedAccess( (ResolvedMember)i.next() );
}
}
private void addPrivilegedAccess(ResolvedMember member) {
//System.err.println("add priv access: " + member);
addTypeMunger(world.concreteTypeMunger(new PrivilegedAccessMunger(member), inAspect));
}
public Collection getCflowEntries() {
ArrayList ret = new ArrayList();
for (Iterator i = shadowMungers.iterator(); i.hasNext(); ) {
ShadowMunger m = (ShadowMunger)i.next();
if (m instanceof Advice) {
Advice a = (Advice)m;
if (a.getKind().isCflow()) {
ret.add(a);
}
}
}
return ret;
}
/**
* Updates the records if something has changed. This is called at most twice, firstly
* whilst collecting ITDs and declares. At this point the CrosscuttingMembers we're
* comparing ourselves with doesn't know about shadowmungers. Therefore a straight comparison
* with the existing list of shadowmungers would return that something has changed
* even though it might not have, so in this first round we ignore the shadowMungers.
* The second time this is called is whilst we're preparing to weave. At this point
* we know everything in the system and so we're able to compare the shadowMunger list.
* (see bug 129163)
*
* @param other
* @param careAboutShadowMungers
* @return true if something has changed since the last time this method was
* called, false otherwise
*/
public boolean replaceWith(CrosscuttingMembers other,boolean careAboutShadowMungers) {
boolean changed = false;
if (perClause == null || !perClause.equals(other.perClause)) {
changed = true;
perClause = other.perClause;
}
//XXX all of the below should be set equality rather than list equality
//System.err.println("old: " + shadowMungers + " new: " + other.shadowMungers);
if (careAboutShadowMungers) {
// bug 129163: use set equality rather than list equality
Set theseShadowMungers = new HashSet();
theseShadowMungers.addAll(shadowMungers);
Set otherShadowMungers = new HashSet();
otherShadowMungers.addAll(other.shadowMungers);
PointcutRewriter pr = new PointcutRewriter();
for (Iterator iter = otherShadowMungers.iterator(); iter.hasNext();) {
ShadowMunger munger = (ShadowMunger) iter.next();
Pointcut p = munger.getPointcut();
Pointcut newP = pr.rewrite(p);
munger.setPointcut(newP);
}
if (!theseShadowMungers.equals(otherShadowMungers)) {
changed = true;
}
// replace the existing list of shadowmungers with the
// new ones in case anything like the sourcelocation has
// changed, however, don't want this flagged as a change
// which will force a full build - bug 134541
shadowMungers = other.shadowMungers;
}
// bug 129163: use set equality rather than list equality and
// if we dont care about shadow mungers then ignore those
// typeMungers which are created to help with the implementation
// of shadowMungers
Set theseTypeMungers = new HashSet();
Set otherTypeMungers = new HashSet();
if (!careAboutShadowMungers) {
for (Iterator iter = typeMungers.iterator(); iter.hasNext();) {
Object o = iter.next();
if (o instanceof BcelTypeMunger) {
BcelTypeMunger typeMunger = (BcelTypeMunger) o;
if (!typeMunger.existsToSupportShadowMunging()) {
theseTypeMungers.add(typeMunger);
}
} else {
theseTypeMungers.add(o);
}
}
for (Iterator iter = other.typeMungers.iterator(); iter.hasNext();) {
Object o = iter.next();
if (o instanceof BcelTypeMunger) {
BcelTypeMunger typeMunger = (BcelTypeMunger) o;
if (!typeMunger.existsToSupportShadowMunging()) {
otherTypeMungers.add(typeMunger);
}
} else {
otherTypeMungers.add(o);
}
}
} else {
theseTypeMungers.addAll(typeMungers);
otherTypeMungers.addAll(other.typeMungers);
}
// initial go at equivalence logic rather than set compare (see pr133532)
// if (theseTypeMungers.size()!=otherTypeMungers.size()) {
// changed = true;
// typeMungers = other.typeMungers;
// } else {
// boolean foundInequality=false;
// for (Iterator iter = theseTypeMungers.iterator(); iter.hasNext() && !foundInequality;) {
// Object thisOne = (Object) iter.next();
// boolean foundInOtherSet = false;
// for (Iterator iterator = otherTypeMungers.iterator(); iterator.hasNext();) {
// Object otherOne = (Object) iterator.next();
// if (thisOne instanceof ConcreteTypeMunger && otherOne instanceof ConcreteTypeMunger) {
// if (((ConcreteTypeMunger)thisOne).equivalentTo(otherOne)) {
// foundInOtherSet=true;
// } else if (thisOne.equals(otherOne)) {
// foundInOtherSet=true;
// }
// } else {
// if (thisOne.equals(otherOne)) {
// foundInOtherSet=true;
// }
// }
// }
// if (!foundInOtherSet) foundInequality=true;
// }
// if (foundInequality) {
// changed = true;
// typeMungers = other.typeMungers;
//// } else {
//// typeMungers = other.typeMungers;
// }
// }
if (!theseTypeMungers.equals(otherTypeMungers)) {
changed = true;
typeMungers = other.typeMungers;
}
if (!lateTypeMungers.equals(other.lateTypeMungers)) {
changed = true;
lateTypeMungers = other.lateTypeMungers;
}
if (!declareDominates.equals(other.declareDominates)) {
changed = true;
declareDominates = other.declareDominates;
}
if (!declareParents.equals(other.declareParents)) {
changed = true;
declareParents = other.declareParents;
}
if (!declareSofts.equals(other.declareSofts)) {
changed = true;
declareSofts = other.declareSofts;
}
// DECAT for when attempting to replace an aspect
if (!declareAnnotationsOnType.equals(other.declareAnnotationsOnType)) {
changed = true;
declareAnnotationsOnType = other.declareAnnotationsOnType;
}
if (!declareAnnotationsOnField.equals(other.declareAnnotationsOnField)) {
changed = true;
declareAnnotationsOnField = other.declareAnnotationsOnField;
}
if (!declareAnnotationsOnMethods.equals(other.declareAnnotationsOnMethods)) {
changed = true;
declareAnnotationsOnMethods = other.declareAnnotationsOnMethods;
}
return changed;
}
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;
}
public List getLateTypeMungers() {
return lateTypeMungers;
}
public List getDeclareAnnotationOnTypes() {
return declareAnnotationsOnType;
}
public List getDeclareAnnotationOnFields() {
return declareAnnotationsOnField;
}
/**
* includes declare @method and @constructor
*/
public List getDeclareAnnotationOnMethods() {
return declareAnnotationsOnMethods;
}
}
|
130,722 |
Bug 130722 poincut references in percflow instantiation model aspects can not be resolved
|
Take these two aspects and this litte class: // source1 package test1; import test.Test; public aspect PointcutProvider { public pointcut test(): execution(* Test.*(..)); } // source2 package test; import test1.PointcutProvider; public aspect PointcutConsumer percflow(flow()) { // compiler issues the following line with // can not find pointcut test on test.PointcutConsumer pointcut mytest(): PointcutProvider.test(); // this also does not work with the same error message pointcut mytest(): test1.PointcutProvider.test(); pointcut flow(): mytest(); } // source3 package test; public class Test { public void foo() { } } Changing the consumer aspect to singleton instantiation model works.
|
resolved fixed
|
b166a7e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T15:43:08Z | 2006-03-07T11:13:20Z |
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.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.weaver.patterns.CflowPointcut;
import org.aspectj.weaver.patterns.DeclareParents;
import org.aspectj.weaver.patterns.IVerificationRequired;
/**
* This holds on to all CrosscuttingMembers for a world. It handles
* management of change.
*
* @author Jim Hugunin
*/
public class CrosscuttingMembersSet {
private World world;
//FIXME AV - ? we may need a sequencedHashMap there to ensure source based precedence for @AJ advice
private Map /* ResolvedType (the aspect) > CrosscuttingMembers */members = new HashMap();
private List shadowMungers = null;
private List typeMungers = null;
private List lateTypeMungers = null;
private List declareSofts = null;
private List declareParents = null;
private List declareAnnotationOnTypes = null;
private List declareAnnotationOnFields = null;
private List declareAnnotationOnMethods= null; // includes ctors
private List declareDominates = null;
private boolean changedSinceLastReset = false;
private List /*IVerificationRequired*/ verificationList = null; // List of things to be verified once the type system is 'complete'
public CrosscuttingMembersSet(World world) {
this.world = world;
}
public boolean addOrReplaceAspect(ResolvedType aspectType) {
return addOrReplaceAspect(aspectType,true);
}
/**
* @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(ResolvedType aspectType,boolean careAboutShadowMungers) {
boolean change = false;
CrosscuttingMembers xcut = (CrosscuttingMembers)members.get(aspectType);
if (xcut == null) {
members.put(aspectType, aspectType.collectCrosscuttingMembers());
clearCaches();
CflowPointcut.clearCaches(aspectType);
change = true;
} else {
if (xcut.replaceWith(aspectType.collectCrosscuttingMembers(),careAboutShadowMungers)) {
clearCaches();
CflowPointcut.clearCaches(aspectType);
change = true;
} else {
if (!World.compareLocations && careAboutShadowMungers) {
// bug 134541 - even though we haven't changed we may have updated the
// sourcelocation for the shadowMunger which we need to pick up
shadowMungers = null;
}
change = false;
}
}
if (aspectType.isAbstract()) {
// we might have sub-aspects that need to re-collect their crosscutting members from us
boolean ancestorChange = addOrReplaceDescendantsOf(aspectType,careAboutShadowMungers);
change = change || ancestorChange;
}
changedSinceLastReset = changedSinceLastReset || change;
return change;
}
private boolean addOrReplaceDescendantsOf(ResolvedType aspectType,boolean careAboutShadowMungers) {
//System.err.println("Looking at descendants of "+aspectType.getName());
Set knownAspects = members.keySet();
Set toBeReplaced = new HashSet();
for(Iterator it = knownAspects.iterator(); it.hasNext(); ) {
ResolvedType candidateDescendant = (ResolvedType)it.next();
if ((candidateDescendant != aspectType) && (aspectType.isAssignableFrom(candidateDescendant))) {
toBeReplaced.add(candidateDescendant);
}
}
boolean change = false;
for (Iterator it = toBeReplaced.iterator(); it.hasNext(); ) {
ResolvedType next = (ResolvedType)it.next();
boolean thisChange = addOrReplaceAspect(next,careAboutShadowMungers);
change = change || thisChange;
}
return change;
}
public void addAdviceLikeDeclares(ResolvedType aspectType) {
CrosscuttingMembers xcut = (CrosscuttingMembers)members.get(aspectType);
xcut.addDeclares(aspectType.collectDeclares(true));
}
public boolean deleteAspect(UnresolvedType aspectType) {
boolean isAspect = members.remove(aspectType) != null;
clearCaches();
return isAspect;
}
public boolean containsAspect(UnresolvedType aspectType) {
return members.containsKey(aspectType);
}
//XXX only for testing
public void addFixedCrosscuttingMembers(ResolvedType aspectType) {
members.put(aspectType, aspectType.crosscuttingMembers);
clearCaches();
}
private void clearCaches() {
shadowMungers = null;
typeMungers = null;
lateTypeMungers = null;
declareSofts = null;
declareParents = null;
declareAnnotationOnFields=null;
declareAnnotationOnMethods=null;
declareAnnotationOnTypes=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 getLateTypeMungers() {
if (lateTypeMungers == null) {
ArrayList ret = new ArrayList();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getLateTypeMungers());
}
lateTypeMungers = ret;
}
return lateTypeMungers;
}
public List getDeclareSofts() {
if (declareSofts == null) {
Set ret = new HashSet();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareSofts());
}
declareSofts = new ArrayList();
declareSofts.addAll(ret);
}
return declareSofts;
}
public List getDeclareParents() {
if (declareParents == null) {
Set ret = new HashSet();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareParents());
}
declareParents = new ArrayList();
declareParents.addAll(ret);
}
return declareParents;
}
// DECAT Merge multiple together
public List getDeclareAnnotationOnTypes() {
if (declareAnnotationOnTypes == null) {
Set ret = new HashSet();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareAnnotationOnTypes());
}
declareAnnotationOnTypes = new ArrayList();
declareAnnotationOnTypes.addAll(ret);
}
return declareAnnotationOnTypes;
}
public List getDeclareAnnotationOnFields() {
if (declareAnnotationOnFields == null) {
Set ret = new HashSet();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareAnnotationOnFields());
}
declareAnnotationOnFields = new ArrayList();
declareAnnotationOnFields.addAll(ret);
}
return declareAnnotationOnFields;
}
/**
* Return an amalgamation of the declare @method/@constructor statements.
*/
public List getDeclareAnnotationOnMethods() {
if (declareAnnotationOnMethods == null) {
Set ret = new HashSet();
for (Iterator i = members.values().iterator(); i.hasNext(); ) {
ret.addAll(((CrosscuttingMembers)i.next()).getDeclareAnnotationOnMethods());
}
declareAnnotationOnMethods = new ArrayList();
declareAnnotationOnMethods.addAll(ret);
}
return declareAnnotationOnMethods;
}
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;
}
public ResolvedType findAspectDeclaringParents(DeclareParents p) {
Set keys = this.members.keySet();
for (Iterator iter = keys.iterator(); iter.hasNext();) {
ResolvedType element = (ResolvedType) iter.next();
for (Iterator i = ((CrosscuttingMembers)members.get(element)).getDeclareParents().iterator(); i.hasNext(); ) {
DeclareParents dp = (DeclareParents)i.next();
if (dp.equals(p)) return element;
}
}
return null;
}
public void reset() {
verificationList=null;
changedSinceLastReset = false;
}
public boolean hasChangedSinceLastReset() {
return changedSinceLastReset;
}
/**
* Record something that needs verifying when we believe the type system is complete.
* Used for things that can't be verified as we go along - for example some
* recursive type variable references (pr133307)
*/
public void recordNecessaryCheck(IVerificationRequired verification) {
if (verificationList==null) verificationList = new ArrayList();
verificationList.add(verification);
}
/**
* Called when type bindings are complete - calls all registered verification
* objects in turn.
*/
public void verify() {
if (verificationList==null) return;
for (Iterator iter = verificationList.iterator(); iter.hasNext();) {
IVerificationRequired element = (IVerificationRequired) iter.next();
element.verify();
}
verificationList = null;
}
}
|
130,722 |
Bug 130722 poincut references in percflow instantiation model aspects can not be resolved
|
Take these two aspects and this litte class: // source1 package test1; import test.Test; public aspect PointcutProvider { public pointcut test(): execution(* Test.*(..)); } // source2 package test; import test1.PointcutProvider; public aspect PointcutConsumer percflow(flow()) { // compiler issues the following line with // can not find pointcut test on test.PointcutConsumer pointcut mytest(): PointcutProvider.test(); // this also does not work with the same error message pointcut mytest(): test1.PointcutProvider.test(); pointcut flow(): mytest(); } // source3 package test; public class Test { public void foo() { } } Changing the consumer aspect to singleton instantiation model works.
|
resolved fixed
|
b166a7e
|
AspectJ
|
https://github.com/eclipse/org.aspectj
|
eclipse/org.aspectj
|
java
| null | null | null | 2006-05-16T15:43:08Z | 2006-03-07T11:13:20Z |
weaver/src/org/aspectj/weaver/ResolvedType.java
|
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the 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
* Alexandre Vasseur @AspectJ ITDs
* ******************************************************************/
package org.aspectj.weaver;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.Message;
import org.aspectj.bridge.MessageUtil;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.patterns.Declare;
import org.aspectj.weaver.patterns.PerClause;
public abstract class ResolvedType extends UnresolvedType implements AnnotatedElement {
private static final ResolvedType[] EMPTY_RESOLVED_TYPE_ARRAY = new ResolvedType[0];
public static final String PARAMETERIZED_TYPE_IDENTIFIER = "P";
private ResolvedType[] resolvedTypeParams;
protected World world;
protected ResolvedType(String signature, World world) {
super(signature);
this.world = world;
}
protected ResolvedType(String signature, String signatureErasure, World world) {
super(signature,signatureErasure);
this.world = world;
}
// ---- things that don't require a world
/**
* Returns an iterator through ResolvedType objects representing all the direct
* supertypes of this type. That is, through the superclass, if any, and
* all declared interfaces.
*/
public final Iterator getDirectSupertypes() {
Iterator ifacesIterator = Iterators.array(getDeclaredInterfaces());
ResolvedType superclass = getSuperclass();
if (superclass == null) {
return ifacesIterator;
} else {
return Iterators.snoc(ifacesIterator, superclass);
}
}
public abstract ResolvedMember[] getDeclaredFields();
public abstract ResolvedMember[] getDeclaredMethods();
public abstract ResolvedType[] getDeclaredInterfaces();
public abstract ResolvedMember[] getDeclaredPointcuts();
/**
* Returns a ResolvedType object representing the superclass of this type, or null.
* If this represents a java.lang.Object, a primitive type, or void, this
* method returns null.
*/
public abstract ResolvedType getSuperclass();
/**
* Returns the modifiers for this type.
* <p/>
* See {@link Class#getModifiers()} for a description
* of the weirdness of this methods on primitives and arrays.
*
* @param world the {@link World} in which the lookup is made.
* @return an int representing the modifiers for this type
* @see java.lang.reflect.Modifier
*/
public abstract int getModifiers();
// return true if this resolved type couldn't be found (but we know it's name maybe)
public boolean isMissing() {
return false;
}
// FIXME asc I wonder if in some circumstances MissingWithKnownSignature should not be considered
// 'really' missing as some code can continue based solely on the signature
public static boolean isMissing (UnresolvedType unresolved) {
if (unresolved instanceof ResolvedType) {
ResolvedType resolved = (ResolvedType)unresolved;
return resolved.isMissing();
}
else return (unresolved == MISSING);
}
public ResolvedType[] getAnnotationTypes() {
return EMPTY_RESOLVED_TYPE_ARRAY;
}
public final UnresolvedType getSuperclass(World world) {
return getSuperclass();
}
// This set contains pairs of types whose signatures are concatenated
// together, this means with a fast lookup we can tell if two types
// are equivalent.
static Set validBoxing = new HashSet();
static {
validBoxing.add("Ljava/lang/Byte;B");
validBoxing.add("Ljava/lang/Character;C");
validBoxing.add("Ljava/lang/Double;D");
validBoxing.add("Ljava/lang/Float;F");
validBoxing.add("Ljava/lang/Integer;I");
validBoxing.add("Ljava/lang/Long;J");
validBoxing.add("Ljava/lang/Short;S");
validBoxing.add("Ljava/lang/Boolean;Z");
validBoxing.add("BLjava/lang/Byte;");
validBoxing.add("CLjava/lang/Character;");
validBoxing.add("DLjava/lang/Double;");
validBoxing.add("FLjava/lang/Float;");
validBoxing.add("ILjava/lang/Integer;");
validBoxing.add("JLjava/lang/Long;");
validBoxing.add("SLjava/lang/Short;");
validBoxing.add("ZLjava/lang/Boolean;");
}
// utilities
public ResolvedType getResolvedComponentType() {
return null;
}
public World getWorld() {
return world;
}
// ---- things from object
public final boolean equals(Object other) {
if (other instanceof ResolvedType) {
return this == other;
} else {
return super.equals(other);
}
}
// ---- difficult things
/**
* returns an iterator through all of the fields of this type, in order
* for checking from JVM spec 2ed 5.4.3.2. This means that the order is
* <p/>
* <ul><li> fields from current class </li>
* <li> recur into direct superinterfaces </li>
* <li> recur into superclass </li>
* </ul>
* <p/>
* We keep a hashSet of interfaces that we've visited so we don't spiral
* out into 2^n land.
*/
public Iterator getFields() {
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedType)o).getDirectSupertypes());
}
};
Iterators.Getter fieldGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return Iterators.array(((ResolvedType)o).getDeclaredFields());
}
};
return
Iterators.mapOver(
Iterators.recur(this, typeGetter),
fieldGetter);
}
/**
* returns an iterator through all of the methods of this type, in order
* for checking from JVM spec 2ed 5.4.3.3. This means that the order is
* <p/>
* <ul><li> methods from current class </li>
* <li> recur into superclass, all the way up, not touching interfaces </li>
* <li> recur into all superinterfaces, in some unspecified order </li>
* </ul>
* <p/>
* We keep a hashSet of interfaces that we've visited so we don't spiral
* out into 2^n land.
* NOTE: Take a look at the javadoc on getMethodsWithoutIterator() to see if
* you are sensitive to a quirk in getMethods()
*/
public Iterator getMethods() {
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter ifaceGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
Iterators.array(((ResolvedType)o).getDeclaredInterfaces())
);
}
};
Iterators.Getter methodGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return Iterators.array(((ResolvedType)o).getDeclaredMethods());
}
};
return
Iterators.mapOver(
Iterators.append(
new Iterator() {
ResolvedType curr = ResolvedType.this;
public boolean hasNext() {
return curr != null;
}
public Object next() {
ResolvedType ret = curr;
curr = curr.getSuperclass();
return ret;
}
public void remove() {
throw new UnsupportedOperationException();
}
},
Iterators.recur(this, ifaceGetter)),
methodGetter);
}
/**
* Return a list of methods, first those declared on this class, then those declared on the superclass (recurse) and then those declared
* on the superinterfaces. The getMethods() call above doesn't quite work the same as it will (through the iterator) return methods
* declared on *this* class twice, once at the start and once at the end - I couldn't debug that problem, so created this alternative.
*/
public List getMethodsWithoutIterator(boolean includeITDs, boolean allowMissing) {
List methods = new ArrayList();
Set knowninterfaces = new HashSet();
addAndRecurse(knowninterfaces,methods,this,includeITDs,allowMissing);
return methods;
}
private void addAndRecurse(Set knowninterfaces,List collector, ResolvedType rtx, boolean includeITDs, boolean allowMissing) {
collector.addAll(Arrays.asList(rtx.getDeclaredMethods())); // Add the methods declared on this type
// now add all the inter-typed members too
if (includeITDs && rtx.interTypeMungers != null) {
for (Iterator i = interTypeMungers.iterator(); i.hasNext();) {
ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next();
ResolvedMember rm = tm.getSignature();
if (rm != null) { // new parent type munger can have null signature...
collector.add(tm.getSignature());
}
}
}
if (!rtx.equals(ResolvedType.OBJECT)) {
ResolvedType superType = rtx.getSuperclass();
if (superType != null && !superType.isMissing()) {
addAndRecurse(knowninterfaces,collector,superType,includeITDs,allowMissing); // Recurse if we aren't at the top
}
}
ResolvedType[] interfaces = rtx.getDeclaredInterfaces(); // Go through the interfaces on the way back down
for (int i = 0; i < interfaces.length; i++) {
ResolvedType iface = interfaces[i];
// we need to know if it is an interface from Parent kind munger
// as those are used for @AJ ITD and we precisely want to skip those
boolean shouldSkip = false;
for (int j = 0; j < rtx.interTypeMungers.size(); j++) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) rtx.interTypeMungers.get(j);
if (munger.getMunger().getKind() == ResolvedTypeMunger.Parent) {
shouldSkip = true;
break;
}
}
if (!shouldSkip && !knowninterfaces.contains(iface)) { // Dont do interfaces more than once
knowninterfaces.add(iface);
if (allowMissing && iface.isMissing()) {
if (iface instanceof MissingResolvedTypeWithKnownSignature) {
((MissingResolvedTypeWithKnownSignature)iface).raiseWarningOnMissingInterfaceWhilstFindingMethods();
}
} else {
addAndRecurse(knowninterfaces,collector,iface,includeITDs,allowMissing);
}
}
}
}
public ResolvedType[] getResolvedTypeParameters() {
if (resolvedTypeParams == null) {
resolvedTypeParams = world.resolve(typeParameters);
}
return resolvedTypeParams;
}
/**
* described in JVM spec 2ed 5.4.3.2
*/
public ResolvedMember lookupField(Member m) {
return lookupMember(m, getFields());
}
/**
* described in JVM spec 2ed 5.4.3.3.
* Doesnt check ITDs.
*/
public ResolvedMember lookupMethod(Member m) {
return lookupMember(m, getMethods());
}
public ResolvedMember lookupMethodInITDs(Member m) {
if (interTypeMungers != null) {
for (Iterator i = interTypeMungers.iterator(); i.hasNext();) {
ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next();
if (matches(tm.getSignature(), m)) {
return tm.getSignature();
}
}
}
return null;
}
/**
* return null if not found
*/
private ResolvedMember lookupMember(Member m, Iterator i) {
while (i.hasNext()) {
ResolvedMember f = (ResolvedMember) i.next();
if (matches(f, m)) return f;
if (f.hasBackingGenericMember() && m.getName().equals(f.getName())) { // might be worth checking the method behind the parameterized method (see pr137496)
if (matches(f.getBackingGenericMember(),m)) return f;
}
}
return null; //ResolvedMember.Missing;
//throw new BCException("can't find " + m);
}
/**
* return null if not found
*/
private ResolvedMember lookupMember(Member m, ResolvedMember[] a) {
for (int i = 0; i < a.length; i++) {
ResolvedMember f = a[i];
if (matches(f, m)) return f;
}
return null;
}
/**
* Looks for the first member in the hierarchy matching aMember. This method
* differs from lookupMember(Member) in that it takes into account parameters
* which are type variables - which clearly an unresolved Member cannot do since
* it does not know anything about type variables.
*/
public ResolvedMember lookupResolvedMember(ResolvedMember aMember,boolean allowMissing) {
Iterator toSearch = null;
ResolvedMember found = null;
if ((aMember.getKind() == Member.METHOD) || (aMember.getKind() == Member.CONSTRUCTOR)) {
toSearch = getMethodsWithoutIterator(true,allowMissing).iterator();
} else {
if (aMember.getKind() != Member.FIELD)
throw new IllegalStateException("I didn't know you would look for members of kind " + aMember.getKind());
toSearch = getFields();
}
while(toSearch.hasNext()) {
ResolvedMemberImpl candidate = (ResolvedMemberImpl) toSearch.next();
if (candidate.matches(aMember)) {
found = candidate;
break;
}
}
return found;
}
public static boolean matches(Member m1, Member m2) {
if (m1 == null) return m2 == null;
if (m2 == null) return false;
// Check the names
boolean equalNames = m1.getName().equals(m2.getName());
if (!equalNames) return false;
// Check the signatures
boolean equalSignatures = m1.getSignature().equals(m2.getSignature());
if (equalSignatures) return true;
// If they aren't the same, we need to allow for covariance ... where one sig might be ()LCar; and
// the subsig might be ()LFastCar; - where FastCar is a subclass of Car
boolean equalCovariantSignatures = m1.getParameterSignature().equals(m2.getParameterSignature());
if (equalCovariantSignatures) return true;
return false;
}
public static boolean conflictingSignature(Member m1, Member m2) {
if (m1 == null || m2 == null) return false;
if (!m1.getName().equals(m2.getName())) {
return false;
}
if (m1.getKind() != m2.getKind()) {
return false;
}
if (m1.getKind() == Member.FIELD) {
return m1.getDeclaringType().equals(m2.getDeclaringType());
} else if (m1.getKind() == Member.POINTCUT) {
return true;
}
UnresolvedType[] p1 = m1.getParameterTypes();
UnresolvedType[] p2 = m2.getParameterTypes();
int n = p1.length;
if (n != p2.length) return false;
for (int i=0; i < n; i++) {
if (!p1[i].equals(p2[i])) return false;
}
return true;
}
/**
* returns an iterator through all of the pointcuts of this type, in order
* for checking from JVM spec 2ed 5.4.3.2 (as for fields). This means that the order is
* <p/>
* <ul><li> pointcuts from current class </li>
* <li> recur into direct superinterfaces </li>
* <li> recur into superclass </li>
* </ul>
* <p/>
* We keep a hashSet of interfaces that we've visited so we don't spiral
* out into 2^n land.
*/
public Iterator getPointcuts() {
final Iterators.Filter dupFilter = Iterators.dupFilter();
// same order as fields
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedType)o).getDirectSupertypes());
}
};
Iterators.Getter pointcutGetter = new Iterators.Getter() {
public Iterator get(Object o) {
//System.err.println("getting for " + o);
return Iterators.array(((ResolvedType)o).getDeclaredPointcuts());
}
};
return
Iterators.mapOver(
Iterators.recur(this, typeGetter),
pointcutGetter);
}
public ResolvedPointcutDefinition findPointcut(String name) {
//System.err.println("looking for pointcuts " + this);
for (Iterator i = getPointcuts(); i.hasNext(); ) {
ResolvedPointcutDefinition f = (ResolvedPointcutDefinition) i.next();
//System.err.println(f);
if (name.equals(f.getName())) {
return f;
}
}
// pr120521
if (!getOutermostType().equals(this)) {
ResolvedType outerType = getOutermostType().resolve(world);
ResolvedPointcutDefinition rpd = outerType.findPointcut(name);
return rpd;
}
return null; // should we throw an exception here?
}
// all about collecting CrosscuttingMembers
//??? collecting data-structure, shouldn't really be a field
public CrosscuttingMembers crosscuttingMembers;
public CrosscuttingMembers collectCrosscuttingMembers() {
crosscuttingMembers = new CrosscuttingMembers(this);
crosscuttingMembers.setPerClause(getPerClause());
crosscuttingMembers.addShadowMungers(collectShadowMungers());
crosscuttingMembers.addTypeMungers(getTypeMungers());
//FIXME AV - skip but needed ?? or ?? crosscuttingMembers.addLateTypeMungers(getLateTypeMungers());
crosscuttingMembers.addDeclares(collectDeclares(!this.doesNotExposeShadowMungers()));
crosscuttingMembers.addPrivilegedAccesses(getPrivilegedAccesses());
//System.err.println("collected cc members: " + this + ", " + collectDeclares());
return crosscuttingMembers;
}
public final Collection collectDeclares(boolean includeAdviceLike) {
if (! this.isAspect() ) return Collections.EMPTY_LIST;
ArrayList ret = new ArrayList();
//if (this.isAbstract()) {
// for (Iterator i = getDeclares().iterator(); i.hasNext();) {
// Declare dec = (Declare) i.next();
// if (!dec.isAdviceLike()) ret.add(dec);
// }
//
// if (!includeAdviceLike) return ret;
if (!this.isAbstract()) {
//ret.addAll(getDeclares());
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedType)o).getDirectSupertypes());
}
};
Iterator typeIterator = Iterators.recur(this, typeGetter);
while (typeIterator.hasNext()) {
ResolvedType ty = (ResolvedType) typeIterator.next();
//System.out.println("super: " + ty + ", " + );
for (Iterator i = ty.getDeclares().iterator(); i.hasNext();) {
Declare dec = (Declare) i.next();
if (dec.isAdviceLike()) {
if (includeAdviceLike) ret.add(dec);
} else {
ret.add(dec);
}
}
}
}
return ret;
}
private final Collection collectShadowMungers() {
if (! this.isAspect() || this.isAbstract() || this.doesNotExposeShadowMungers()) return Collections.EMPTY_LIST;
ArrayList acc = new ArrayList();
final Iterators.Filter dupFilter = Iterators.dupFilter();
Iterators.Getter typeGetter = new Iterators.Getter() {
public Iterator get(Object o) {
return
dupFilter.filter(
((ResolvedType)o).getDirectSupertypes());
}
};
Iterator typeIterator = Iterators.recur(this, typeGetter);
while (typeIterator.hasNext()) {
ResolvedType ty = (ResolvedType) typeIterator.next();
acc.addAll(ty.getDeclaredShadowMungers());
}
return acc;
}
protected boolean doesNotExposeShadowMungers() {
return false;
}
public PerClause getPerClause() {
return null;
}
protected Collection getDeclares() {
return Collections.EMPTY_LIST;
}
protected Collection getTypeMungers() {
return Collections.EMPTY_LIST;
}
protected Collection getPrivilegedAccesses() {
return Collections.EMPTY_LIST;
}
// ---- useful things
public final boolean isInterface() {
return Modifier.isInterface(getModifiers());
}
public final boolean isAbstract() {
return Modifier.isAbstract(getModifiers());
}
public boolean isClass() {
return false;
}
public boolean isAspect() {
return false;
}
public boolean isAnnotationStyleAspect() {
return false;
}
/**
* Note: Only overridden by Name subtype.
*/
public boolean isEnum() {
return false;
}
/**
* Note: Only overridden by Name subtype.
*/
public boolean isAnnotation() {
return false;
}
public boolean isAnonymous() {
return false;
}
public boolean isNested() {
return false;
}
/**
* Note: Only overridden by Name subtype
*/
public void addAnnotation(AnnotationX annotationX) {
throw new RuntimeException("ResolvedType.addAnnotation() should never be called");
}
/**
* Note: Only overridden by Name subtype
*/
public AnnotationX[] getAnnotations() {
throw new RuntimeException("ResolvedType.getAnnotations() should never be called");
}
/**
* Note: Only overridden by ReferenceType subtype
*/
public boolean canAnnotationTargetType() {
return false;
}
/**
* Note: Only overridden by ReferenceType subtype
*/
public AnnotationTargetKind[] getAnnotationTargetKinds() {
return null;
}
/**
* Note: Only overridden by Name subtype.
*/
public boolean isAnnotationWithRuntimeRetention() {
return false;
}
public boolean isSynthetic() {
return signature.indexOf("$ajc") != -1;
}
public final boolean isFinal() {
return Modifier.isFinal(getModifiers());
}
protected Map /*Type variable name -> UnresolvedType*/ getMemberParameterizationMap() {
if (!isParameterizedType()) return Collections.EMPTY_MAP;
TypeVariable[] tvs = getGenericType().getTypeVariables();
Map parameterizationMap = new HashMap();
for (int i = 0; i < tvs.length; i++) {
parameterizationMap.put(tvs[i].getName(), typeParameters[i]);
}
return parameterizationMap;
}
public Collection getDeclaredAdvice() {
List l = new ArrayList();
ResolvedMember[] methods = getDeclaredMethods();
if (isParameterizedType()) methods = getGenericType().getDeclaredMethods();
Map typeVariableMap = getAjMemberParameterizationMap();
for (int i=0, len = methods.length; i < len; i++) {
ShadowMunger munger = methods[i].getAssociatedShadowMunger();
if (munger != null) {
if (ajMembersNeedParameterization()) {
//munger.setPointcut(munger.getPointcut().parameterizeWith(typeVariableMap));
munger = munger.parameterizeWith(this,typeVariableMap);
if (munger instanceof Advice) {
Advice advice = (Advice) munger;
// update to use the parameterized signature...
UnresolvedType[] ptypes = methods[i].getGenericParameterTypes() ;
UnresolvedType[] newPTypes = new UnresolvedType[ptypes.length];
for (int j = 0; j < ptypes.length; j++) {
if (ptypes[j] instanceof TypeVariableReferenceType) {
TypeVariableReferenceType tvrt = (TypeVariableReferenceType) ptypes[j];
if (typeVariableMap.containsKey(tvrt.getTypeVariable().getName())) {
newPTypes[j] = (UnresolvedType) typeVariableMap.get(tvrt.getTypeVariable().getName());
} else {
newPTypes[j] = ptypes[j];
}
} else {
newPTypes[j] = ptypes[j];
}
}
advice.setBindingParameterTypes(newPTypes);
}
}
munger.setDeclaringType(this);
l.add(munger);
}
}
return l;
}
public Collection getDeclaredShadowMungers() {
Collection c = getDeclaredAdvice();
return c;
}
// ---- only for testing!
public ResolvedMember[] getDeclaredJavaFields() {
return filterInJavaVisible(getDeclaredFields());
}
public ResolvedMember[] getDeclaredJavaMethods() {
return filterInJavaVisible(getDeclaredMethods());
}
public ShadowMunger[] getDeclaredShadowMungersArray() {
List l = (List) getDeclaredShadowMungers();
return (ShadowMunger[]) l.toArray(new ShadowMunger[l.size()]);
}
private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) {
List l = new ArrayList();
for (int i=0, len = ms.length; i < len; i++) {
if (! ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) {
l.add(ms[i]);
}
}
return (ResolvedMember[]) l.toArray(new ResolvedMember[l.size()]);
}
public abstract ISourceContext getSourceContext();
// ---- fields
public static final ResolvedType[] NONE = new ResolvedType[0];
public static final Primitive BYTE = new Primitive("B", 1, 0);
public static final Primitive CHAR = new Primitive("C", 1, 1);
public static final Primitive DOUBLE = new Primitive("D", 2, 2);
public static final Primitive FLOAT = new Primitive("F", 1, 3);
public static final Primitive INT = new Primitive("I", 1, 4);
public static final Primitive LONG = new Primitive("J", 2, 5);
public static final Primitive SHORT = new Primitive("S", 1, 6);
public static final Primitive VOID = new Primitive("V", 0, 8);
public static final Primitive BOOLEAN = new Primitive("Z", 1, 7);
public static final Missing MISSING = new Missing();
/** Reset the static state in the primitive types */
public static void resetPrimitives() {
BYTE.world=null;
CHAR.world=null;
DOUBLE.world=null;
FLOAT.world=null;
INT.world=null;
LONG.world=null;
SHORT.world=null;
VOID.world=null;
BOOLEAN.world=null;
}
// ---- types
public static ResolvedType makeArray(ResolvedType type, int dim) {
if (dim == 0) return type;
ResolvedType array = new Array("[" + type.getSignature(),"["+type.getErasureSignature(),type.getWorld(),type);
return makeArray(array,dim-1);
}
static class Array extends ResolvedType {
ResolvedType componentType;
// Sometimes the erasure is different, eg. [TT; and [Ljava/lang/Object;
Array(String sig, String erasureSig,World world, ResolvedType componentType) {
super(sig,erasureSig, world);
this.componentType = componentType;
}
public final ResolvedMember[] getDeclaredFields() {
return ResolvedMember.NONE;
}
public final ResolvedMember[] getDeclaredMethods() {
// ??? should this return clone? Probably not...
// If it ever does, here is the code:
// ResolvedMember cloneMethod =
// new ResolvedMember(Member.METHOD,this,Modifier.PUBLIC,UnresolvedType.OBJECT,"clone",new UnresolvedType[]{});
// return new ResolvedMember[]{cloneMethod};
return ResolvedMember.NONE;
}
public final ResolvedType[] getDeclaredInterfaces() {
return
new ResolvedType[] {
world.getCoreType(CLONEABLE),
world.getCoreType(SERIALIZABLE)
};
}
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
public boolean hasAnnotation(UnresolvedType ofType) {
return false;
}
public final ResolvedType getSuperclass() {
return world.getCoreType(OBJECT);
}
public final boolean isAssignableFrom(ResolvedType o) {
if (! o.isArray()) return false;
if (o.getComponentType().isPrimitiveType()) {
return o.equals(this);
} else {
return getComponentType().resolve(world).isAssignableFrom(o.getComponentType().resolve(world));
}
}
public boolean isAssignableFrom(ResolvedType o, boolean allowMissing) {
return isAssignableFrom(o);
}
public final boolean isCoerceableFrom(ResolvedType o) {
if (o.equals(UnresolvedType.OBJECT) ||
o.equals(UnresolvedType.SERIALIZABLE) ||
o.equals(UnresolvedType.CLONEABLE)) {
return true;
}
if (! o.isArray()) return false;
if (o.getComponentType().isPrimitiveType()) {
return o.equals(this);
} else {
return getComponentType().resolve(world).isCoerceableFrom(o.getComponentType().resolve(world));
}
}
public final int getModifiers() {
int mask = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED;
return (componentType.getModifiers() & mask) | Modifier.FINAL;
}
public UnresolvedType getComponentType() {
return componentType;
}
public ResolvedType getResolvedComponentType() {
return componentType;
}
public ISourceContext getSourceContext() {
return getResolvedComponentType().getSourceContext();
}
}
static class Primitive extends ResolvedType {
private int size;
private int index;
Primitive(String signature, int size, int index) {
super(signature, null);
this.size = size;
this.index = index;
this.typeKind=TypeKind.PRIMITIVE;
}
public final int getSize() {
return size;
}
public final int getModifiers() {
return Modifier.PUBLIC | Modifier.FINAL;
}
public final boolean isPrimitiveType() {
return true;
}
public boolean hasAnnotation(UnresolvedType ofType) {
return false;
}
public final boolean isAssignableFrom(ResolvedType other) {
if (!other.isPrimitiveType()) {
if (!world.isInJava5Mode()) return false;
return validBoxing.contains(this.getSignature()+other.getSignature());
}
return assignTable[((Primitive)other).index][index];
}
public final boolean isAssignableFrom(ResolvedType other, boolean allowMissing) {
return isAssignableFrom(other);
}
public final boolean isCoerceableFrom(ResolvedType other) {
if (this == other) return true;
if (! other.isPrimitiveType()) return false;
if (index > 6 || ((Primitive)other).index > 6) return false;
return true;
}
public ResolvedType resolve(World world) {
this.world = world;
return super.resolve(world);
}
public final boolean needsNoConversionFrom(ResolvedType other) {
if (! other.isPrimitiveType()) return false;
return noConvertTable[((Primitive)other).index][index];
}
private static final boolean[][] assignTable =
{// to: B C D F I J S V Z from
{ true , true , true , true , true , true , true , false, false }, // B
{ false, true , true , true , true , true , false, false, false }, // C
{ false, false, true , false, false, false, false, false, false }, // D
{ false, false, true , true , false, false, false, false, false }, // F
{ false, false, true , true , true , true , false, false, false }, // I
{ false, false, true , true , false, true , false, false, false }, // J
{ false, false, true , true , true , true , true , false, false }, // S
{ false, false, false, false, false, false, false, true , false }, // V
{ false, false, false, false, false, false, false, false, true }, // Z
};
private static final boolean[][] noConvertTable =
{// to: B C D F I J S V Z from
{ true , true , false, false, true , false, true , false, false }, // B
{ false, true , false, false, true , false, false, false, false }, // C
{ false, false, true , false, false, false, false, false, false }, // D
{ false, false, false, true , false, false, false, false, false }, // F
{ false, false, false, false, true , false, false, false, false }, // I
{ false, false, false, false, false, true , false, false, false }, // J
{ false, false, false, false, true , false, true , false, false }, // S
{ false, false, false, false, false, false, false, true , false }, // V
{ false, false, false, false, false, false, false, false, true }, // Z
};
// ----
public final ResolvedMember[] getDeclaredFields() {
return ResolvedMember.NONE;
}
public final ResolvedMember[] getDeclaredMethods() {
return ResolvedMember.NONE;
}
public final ResolvedType[] getDeclaredInterfaces() {
return ResolvedType.NONE;
}
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
public final ResolvedType getSuperclass() {
return null;
}
public ISourceContext getSourceContext() {
return null;
}
}
static class Missing extends ResolvedType {
Missing() {
super(MISSING_NAME, null);
}
// public final String toString() {
// return "<missing>";
// }
public final String getName() {
return MISSING_NAME;
}
public final boolean isMissing() {
return true;
}
public boolean hasAnnotation(UnresolvedType ofType) {
return false;
}
public final ResolvedMember[] getDeclaredFields() {
return ResolvedMember.NONE;
}
public final ResolvedMember[] getDeclaredMethods() {
return ResolvedMember.NONE;
}
public final ResolvedType[] getDeclaredInterfaces() {
return ResolvedType.NONE;
}
public final ResolvedMember[] getDeclaredPointcuts() {
return ResolvedMember.NONE;
}
public final ResolvedType getSuperclass() {
return null;
}
public final int getModifiers() {
return 0;
}
public final boolean isAssignableFrom(ResolvedType other) {
return false;
}
public final boolean isAssignableFrom(ResolvedType other, boolean allowMissing) {
return false;
}
public final boolean isCoerceableFrom(ResolvedType other) {
return false;
}
public boolean needsNoConversionFrom(ResolvedType other) {
return false;
}
public ISourceContext getSourceContext() {
return null;
}
}
/**
* Look up a member, takes into account any ITDs on this type.
* return null if not found
*/
public ResolvedMember lookupMemberNoSupers(Member member) {
ResolvedMember ret = lookupDirectlyDeclaredMemberNoSupers(member);
if (ret == null && interTypeMungers != null) {
for (Iterator i = interTypeMungers.iterator(); i.hasNext();) {
ConcreteTypeMunger tm = (ConcreteTypeMunger) i.next();
if (matches(tm.getSignature(), member)) {
return tm.getSignature();
}
}
}
return ret;
}
public ResolvedMember lookupMemberWithSupersAndITDs(Member member) {
ResolvedMember ret = lookupMemberNoSupers(member);
if (ret != null) return ret;
ResolvedType supert = getSuperclass();
if (supert != null) {
ret = supert.lookupMemberNoSupers(member);
}
return ret;
}
/**
* as lookupMemberNoSupers, but does not include ITDs
*
* @param member
* @return
*/
public ResolvedMember lookupDirectlyDeclaredMemberNoSupers(Member member) {
ResolvedMember ret;
if (member.getKind() == Member.FIELD) {
ret = lookupMember(member, getDeclaredFields());
} else {
// assert member.getKind() == Member.METHOD || member.getKind() == Member.CONSTRUCTOR
ret = lookupMember(member, getDeclaredMethods());
}
return ret;
}
/**
* This lookup has specialized behaviour - a null result tells the
* EclipseTypeMunger that it should make a default implementation of a
* method on this type.
*
* @param member
* @return
*/
public ResolvedMember lookupMemberIncludingITDsOnInterfaces(Member member) {
return lookupMemberIncludingITDsOnInterfaces(member, this);
}
private ResolvedMember lookupMemberIncludingITDsOnInterfaces(Member member, ResolvedType onType) {
ResolvedMember ret = onType.lookupMemberNoSupers(member);
if (ret != null) {
return ret;
} else {
ResolvedType superType = onType.getSuperclass();
if (superType != null) {
ret = lookupMemberIncludingITDsOnInterfaces(member,superType);
}
if (ret == null) {
// try interfaces then, but only ITDs now...
ResolvedType[] superInterfaces = onType.getDeclaredInterfaces();
for (int i = 0; i < superInterfaces.length; i++) {
ret = superInterfaces[i].lookupMethodInITDs(member);
if (ret != null) return ret;
}
}
}
return ret;
}
protected List interTypeMungers = new ArrayList(0);
public List getInterTypeMungers() {
return interTypeMungers;
}
public List getInterTypeParentMungers() {
List l = new ArrayList();
for (Iterator iter = interTypeMungers.iterator(); iter.hasNext();) {
ConcreteTypeMunger element = (ConcreteTypeMunger) iter.next();
if (element.getMunger() instanceof NewParentTypeMunger) l.add(element);
}
return l;
}
/**
* ??? This method is O(N*M) where N = number of methods and M is number of
* inter-type declarations in my super
*/
public List getInterTypeMungersIncludingSupers() {
ArrayList ret = new ArrayList();
collectInterTypeMungers(ret);
return ret;
}
public List getInterTypeParentMungersIncludingSupers() {
ArrayList ret = new ArrayList();
collectInterTypeParentMungers(ret);
return ret;
}
private void collectInterTypeParentMungers(List collector) {
for (Iterator iter = getDirectSupertypes(); iter.hasNext();) {
ResolvedType superType = (ResolvedType) iter.next();
superType.collectInterTypeParentMungers(collector);
}
collector.addAll(getInterTypeParentMungers());
}
protected void collectInterTypeMungers(List collector) {
for (Iterator iter = getDirectSupertypes(); iter.hasNext();) {
ResolvedType superType = (ResolvedType) iter.next();
superType.collectInterTypeMungers(collector);
}
outer:
for (Iterator iter1 = collector.iterator(); iter1.hasNext();) {
ConcreteTypeMunger superMunger = (ConcreteTypeMunger) iter1.next();
if ( superMunger.getSignature() == null) continue;
if ( !superMunger.getSignature().isAbstract()) continue;
for (Iterator iter = getInterTypeMungers().iterator(); iter.hasNext();) {
ConcreteTypeMunger myMunger = (ConcreteTypeMunger) iter.next();
if (conflictingSignature(myMunger.getSignature(), superMunger.getSignature())) {
iter1.remove();
continue outer;
}
}
if (!superMunger.getSignature().isPublic()) continue;
for (Iterator iter = getMethods(); iter.hasNext(); ) {
ResolvedMember method = (ResolvedMember)iter.next();
if (conflictingSignature(method, superMunger.getSignature())) {
iter1.remove();
continue outer;
}
}
}
collector.addAll(getInterTypeMungers());
}
/**
* Check:
* 1) That we don't have any abstract type mungers unless this type is abstract.
* 2) That an abstract ITDM on an interface is declared public. (Compiler limitation) (PR70794)
*/
public void checkInterTypeMungers() {
if (isAbstract()) return;
boolean itdProblem = false;
for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next();
itdProblem = checkAbstractDeclaration(munger) || itdProblem; // Rule 2
}
if (itdProblem) return; // If the rules above are broken, return right now
for (Iterator iter = getInterTypeMungersIncludingSupers().iterator(); iter.hasNext();) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) iter.next();
if (munger.getSignature() != null && munger.getSignature().isAbstract()) { // Rule 1
if (munger.getMunger().getKind() == ResolvedTypeMunger.MethodDelegate) {
;//ignore for @AJ ITD as munger.getSignature() is the interface method hence abstract
} else {
world.getMessageHandler().handleMessage(
new Message("must implement abstract inter-type declaration: " + munger.getSignature(),
"", IMessage.ERROR, getSourceLocation(), null,
new ISourceLocation[] { getMungerLocation(munger) }));
}
}
}
}
/**
* See PR70794. This method checks that if an abstract inter-type method declaration is made on
* an interface then it must also be public.
* This is a compiler limitation that could be made to work in the future (if someone
* provides a worthwhile usecase)
*
* @return indicates if the munger failed the check
*/
private boolean checkAbstractDeclaration(ConcreteTypeMunger munger) {
if (munger.getMunger()!=null && (munger.getMunger() instanceof NewMethodTypeMunger)) {
ResolvedMember itdMember = munger.getSignature();
ResolvedType onType = itdMember.getDeclaringType().resolve(world);
if (onType.isInterface() && itdMember.isAbstract() && !itdMember.isPublic()) {
world.getMessageHandler().handleMessage(
new Message(WeaverMessages.format(WeaverMessages.ITD_ABSTRACT_MUST_BE_PUBLIC_ON_INTERFACE,munger.getSignature(),onType),"",
Message.ERROR,getSourceLocation(),null,
new ISourceLocation[]{getMungerLocation(munger)})
);
return true;
}
}
return false;
}
/**
* Get a source location for the munger.
* Until intertype mungers remember where they came from, the source location
* for the munger itself is null. In these cases use the
* source location for the aspect containing the ITD.
*/
private ISourceLocation getMungerLocation(ConcreteTypeMunger munger) {
ISourceLocation sloc = munger.getSourceLocation();
if (sloc == null) {
sloc = munger.getAspectType().getSourceLocation();
}
return sloc;
}
/**
* Returns a ResolvedType object representing the declaring type of this type, or
* null if this type does not represent a non-package-level-type.
* <p/>
* <strong>Warning</strong>: This is guaranteed to work for all member types.
* For anonymous/local types, the only guarantee is given in JLS 13.1, where
* it guarantees that if you call getDeclaringType() repeatedly, you will eventually
* get the top-level class, but it does not say anything about classes in between.
*
* @return the declaring UnresolvedType object, or null.
*/
public ResolvedType getDeclaringType() {
if (isArray()) return null;
String name = getName();
int lastDollar = name.lastIndexOf('$');
while (lastDollar >0) { // allow for classes starting '$' (pr120474)
ResolvedType ret = world.resolve(UnresolvedType.forName(name.substring(0, lastDollar)), true);
if (!ResolvedType.isMissing(ret)) return ret;
lastDollar = name.lastIndexOf('$', lastDollar-1);
}
return null;
}
public static boolean isVisible(int modifiers, ResolvedType targetType, ResolvedType fromType) {
//System.err.println("mod: " + modifiers + ", " + targetType + " and " + fromType);
if (Modifier.isPublic(modifiers)) {
return true;
} else if (Modifier.isPrivate(modifiers)) {
return targetType.getOutermostType().equals(fromType.getOutermostType());
} else if (Modifier.isProtected(modifiers)) {
return samePackage(targetType, fromType) || targetType.isAssignableFrom(fromType);
} else { // package-visible
return samePackage(targetType, fromType);
}
}
public static boolean hasBridgeModifier(int modifiers) {
return (modifiers & Constants.ACC_BRIDGE)!=0;
}
private static boolean samePackage(
ResolvedType targetType,
ResolvedType fromType) {
String p1 = targetType.getPackageName();
String p2 = fromType.getPackageName();
if (p1 == null) return p2 == null;
if (p2 == null) return false;
return p1.equals(p2);
}
/**
* Checks if the generic type for 'this' and the generic type for 'other' are the same -
* it can be passed raw or parameterized versions and will just compare the underlying
* generic type.
*/
private boolean genericTypeEquals(ResolvedType other) {
ResolvedType rt = other;
if (rt.isParameterizedType() || rt.isRawType()) rt.getGenericType();
if (( (isParameterizedType() || isRawType()) && getGenericType().equals(rt)) ||
(this.equals(other))) return true;
return false;
}
/**
* Look up the actual occurence of a particular type in the hierarchy for
* 'this' type. The input is going to be a generic type, and the caller
* wants to know if it was used in its RAW or a PARAMETERIZED form in this
* hierarchy.
*
* returns null if it can't be found.
*/
public ResolvedType discoverActualOccurrenceOfTypeInHierarchy(ResolvedType lookingFor) {
if (!lookingFor.isGenericType())
throw new BCException("assertion failed: method should only be called with generic type, but "+lookingFor+" is "+lookingFor.typeKind);
if (this.equals(ResolvedType.OBJECT)) return null;
if (genericTypeEquals(lookingFor)) return this;
ResolvedType superT = getSuperclass();
if (superT.genericTypeEquals(lookingFor)) return superT;
ResolvedType[] superIs = getDeclaredInterfaces();
for (int i = 0; i < superIs.length; i++) {
ResolvedType superI = superIs[i];
if (superI.genericTypeEquals(lookingFor)) return superI;
ResolvedType checkTheSuperI = superI.discoverActualOccurrenceOfTypeInHierarchy(lookingFor);
if (checkTheSuperI!=null) return checkTheSuperI;
}
return superT.discoverActualOccurrenceOfTypeInHierarchy(lookingFor);
}
/**
* Called for all type mungers but only does something if they share type variables
* with a generic type which they target. When this happens this routine will check
* for the target type in the target hierarchy and 'bind' any type parameters as
* appropriate. For example, for the ITD "List<T> I<T>.x" against a type like this:
* "class A implements I<String>" this routine will return a parameterized form of
* the ITD "List<String> I.x"
*/
public ConcreteTypeMunger fillInAnyTypeParameters(ConcreteTypeMunger munger) {
boolean debug = false;
ResolvedMember member = munger.getSignature();
if (munger.isTargetTypeParameterized()) {
if (debug) System.err.println("Processing attempted parameterization of "+munger+" targetting type "+this);
if (debug) System.err.println(" This type is "+this+" ("+typeKind+")");
// need to tailor this munger instance for the particular target...
if (debug) System.err.println(" Signature that needs parameterizing: "+member);
// Retrieve the generic type
ResolvedType onType = world.resolve(member.getDeclaringType()).getGenericType();
member.resolve(world); // Ensure all parts of the member are resolved
if (debug) System.err.println(" Actual target ontype: "+onType+" ("+onType.typeKind+")");
// quickly find the targettype in the type hierarchy for this type (it will be either RAW or PARAMETERIZED)
ResolvedType actualTarget = discoverActualOccurrenceOfTypeInHierarchy(onType);
if (actualTarget==null)
throw new BCException("assertion failed: asked "+this+" for occurrence of "+onType+" in its hierarchy??");
// only bind the tvars if its a parameterized type or the raw type (in which case they collapse to bounds) - don't do it for generic types ;)
if (!actualTarget.isGenericType()) {
if (debug) System.err.println("Occurrence in "+this+" is actually "+actualTarget+" ("+actualTarget.typeKind+")");
// parameterize the signature
// ResolvedMember newOne = member.parameterizedWith(actualTarget.getTypeParameters(),onType,actualTarget.isParameterizedType());
}
//if (!actualTarget.isRawType())
munger = munger.parameterizedFor(actualTarget);
if (debug) System.err.println("New sig: "+munger.getSignature());
if (debug) System.err.println("=====================================");
}
return munger;
}
public void addInterTypeMunger(ConcreteTypeMunger munger) {
ResolvedMember sig = munger.getSignature();
if (sig == null || munger.getMunger() == null ||
munger.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess)
{
interTypeMungers.add(munger);
return;
}
ConcreteTypeMunger originalMunger = munger;
// we will use the 'parameterized' ITD for all the comparisons but we say the original
// one passed in actually matched as it will be added to the intertype member finder
// for the target type. It is possible we only want to do this if a generic type
// is discovered and the tvar is collapsed to a bound?
munger = fillInAnyTypeParameters(munger);
sig = munger.getSignature(); // possibly changed when type parms filled in
//System.err.println("add: " + munger + " to " + this.getClassName() + " with " + interTypeMungers);
if (sig.getKind() == Member.METHOD) {
if (!compareToExistingMembers(munger, getMethodsWithoutIterator(false,true) /*getMethods()*/)) return;
if (this.isInterface()) {
if (!compareToExistingMembers(munger,
Arrays.asList(world.getCoreType(OBJECT).getDeclaredMethods()).iterator())) return;
}
} else if (sig.getKind() == Member.FIELD) {
if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredFields()).iterator())) return;
} else {
if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredMethods()).iterator())) return;
}
// now compare to existingMungers
for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger existingMunger = (ConcreteTypeMunger)i.next();
if (conflictingSignature(existingMunger.getSignature(), munger.getSignature())) {
//System.err.println("match " + munger + " with " + existingMunger);
if (isVisible(munger.getSignature().getModifiers(),
munger.getAspectType(), existingMunger.getAspectType()))
{
//System.err.println(" is visible");
int c = compareMemberPrecedence(sig, existingMunger.getSignature());
if (c == 0) {
c = getWorld().compareByPrecedenceAndHierarchy(munger.getAspectType(), existingMunger.getAspectType());
}
//System.err.println(" compare: " + c);
if (c < 0) {
// the existing munger dominates the new munger
checkLegalOverride(munger.getSignature(), existingMunger.getSignature());
return;
} else if (c > 0) {
// the new munger dominates the existing one
checkLegalOverride(existingMunger.getSignature(), munger.getSignature());
i.remove();
break;
} else {
interTypeConflictError(munger, existingMunger);
interTypeConflictError(existingMunger, munger);
return;
}
}
}
}
//System.err.println("adding: " + munger + " to " + this);
// we are adding the parameterized form of the ITD to the list of
// mungers. Within it, the munger knows the original declared
// signature for the ITD so it can be retrieved.
interTypeMungers.add(munger);
}
private boolean compareToExistingMembers(ConcreteTypeMunger munger, List existingMembersList) {
return compareToExistingMembers(munger,existingMembersList.iterator());
}
//??? returning too soon
private boolean compareToExistingMembers(ConcreteTypeMunger munger, Iterator existingMembers) {
ResolvedMember sig = munger.getSignature();
while (existingMembers.hasNext()) {
ResolvedMember existingMember = (ResolvedMember)existingMembers.next();
// don't worry about clashing with bridge methods
if (existingMember.isBridgeMethod()) continue;
//System.err.println("Comparing munger: "+sig+" with member "+existingMember);
if (conflictingSignature(existingMember, munger.getSignature())) {
//System.err.println("conflict: existingMember=" + existingMember + " typeMunger=" + munger);
//System.err.println(munger.getSourceLocation() + ", " + munger.getSignature() + ", " + munger.getSignature().getSourceLocation());
if (isVisible(existingMember.getModifiers(), this, munger.getAspectType())) {
int c = compareMemberPrecedence(sig, existingMember);
//System.err.println(" c: " + c);
if (c < 0) {
// existingMember dominates munger
checkLegalOverride(munger.getSignature(), existingMember);
return false;
} else if (c > 0) {
// munger dominates existingMember
checkLegalOverride(existingMember, munger.getSignature());
//interTypeMungers.add(munger);
//??? might need list of these overridden abstracts
continue;
} else {
// bridge methods can differ solely in return type.
// FIXME this whole method seems very hokey - unaware of covariance/varargs/bridging - it
// could do with a rewrite !
boolean sameReturnTypes = (existingMember.getReturnType().equals(sig.getReturnType()));
if (sameReturnTypes)
getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(),
existingMember),
munger.getSourceLocation())
);
}
} else if (isDuplicateMemberWithinTargetType(existingMember,this,sig)) {
getWorld().getMessageHandler().handleMessage(
MessageUtil.error(WeaverMessages.format(WeaverMessages.ITD_MEMBER_CONFLICT,munger.getAspectType().getName(),
existingMember),
munger.getSourceLocation())
);
;
}
//return;
}
}
return true;
}
// we know that the member signature matches, but that the member in the target type is not visible to the aspect.
// this may still be disallowed if it would result in two members within the same declaring type with the same
// signature AND more than one of them is concrete AND they are both visible within the target type.
private boolean isDuplicateMemberWithinTargetType(ResolvedMember existingMember, ResolvedType targetType,ResolvedMember itdMember) {
if ( (existingMember.isAbstract() || itdMember.isAbstract())) return false;
UnresolvedType declaringType = existingMember.getDeclaringType();
if (!targetType.equals(declaringType)) return false;
// now have to test that itdMember is visible from targetType
if (itdMember.isPrivate()) return false;
if (itdMember.isPublic()) return true;
// must be in same package to be visible then...
if (!targetType.getPackageName().equals(itdMember.getDeclaringType().getPackageName())) return false;
// trying to put two members with the same signature into the exact same type..., and both visible in that type.
return true;
}
/**
* @return true if the override is legal
* note: calling showMessage with two locations issues TWO messages, not ONE message
* with an additional source location.
*/
public boolean checkLegalOverride(ResolvedMember parent, ResolvedMember child) {
//System.err.println("check: " + child.getDeclaringType() + " overrides " + parent.getDeclaringType());
if (Modifier.isFinal(parent.getModifiers())) {
world.showMessage(Message.ERROR,
WeaverMessages.format(WeaverMessages.CANT_OVERRIDE_FINAL_MEMBER,parent),
child.getSourceLocation(),null);
return false;
}
boolean incompatibleReturnTypes = false;
// In 1.5 mode, allow for covariance on return type
if (world.isInJava5Mode() && parent.getKind()==Member.METHOD) {
// Look at the generic types when doing this comparison
ResolvedType rtParentReturnType = parent.getGenericReturnType().resolve(world);
ResolvedType rtChildReturnType = child.getGenericReturnType().resolve(world);
incompatibleReturnTypes = !rtParentReturnType.isAssignableFrom(rtChildReturnType);
if (incompatibleReturnTypes) {
incompatibleReturnTypes = !rtParentReturnType.isAssignableFrom(rtChildReturnType);
}
} else {
incompatibleReturnTypes =!parent.getReturnType().equals(child.getReturnType());
}
if (incompatibleReturnTypes) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_RETURN_TYPE_MISMATCH,parent,child),
child.getSourceLocation(), parent.getSourceLocation());
return false;
}
if (parent.getKind() == Member.POINTCUT) {
UnresolvedType[] pTypes = parent.getParameterTypes();
UnresolvedType[] cTypes = child.getParameterTypes();
if (!Arrays.equals(pTypes, cTypes)) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_PARAM_TYPE_MISMATCH,parent,child),
child.getSourceLocation(), parent.getSourceLocation());
return false;
}
}
//System.err.println("check: " + child.getModifiers() + " more visible " + parent.getModifiers());
if (isMoreVisible(parent.getModifiers(), child.getModifiers())) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_VISIBILITY_REDUCTION,parent,child),
child.getSourceLocation(), parent.getSourceLocation());
return false;
}
// check declared exceptions
ResolvedType[] childExceptions = world.resolve(child.getExceptions());
ResolvedType[] parentExceptions = world.resolve(parent.getExceptions());
ResolvedType runtimeException = world.resolve("java.lang.RuntimeException");
ResolvedType error = world.resolve("java.lang.Error");
outer:
for (int i = 0, leni = childExceptions.length; i < leni; i++) {
//System.err.println("checking: " + childExceptions[i]);
if (runtimeException.isAssignableFrom(childExceptions[i])) continue;
if (error.isAssignableFrom(childExceptions[i])) continue;
for (int j = 0, lenj = parentExceptions.length; j < lenj; j++) {
if (parentExceptions[j].isAssignableFrom(childExceptions[i])) continue outer;
}
// this message is now better handled my MethodVerifier in JDT core.
// world.showMessage(IMessage.ERROR,
// WeaverMessages.format(WeaverMessages.ITD_DOESNT_THROW,childExceptions[i].getName()),
// child.getSourceLocation(), null);
return false;
}
if (parent.isStatic() && !child.isStatic()) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_OVERRIDDEN_STATIC,child,parent),
child.getSourceLocation(),null);
return false;
} else if (child.isStatic() && !parent.isStatic()) {
world.showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_OVERIDDING_STATIC,child,parent),
child.getSourceLocation(),null);
return false;
}
return true;
}
private int compareMemberPrecedence(ResolvedMember m1, ResolvedMember m2) {
//if (!m1.getReturnType().equals(m2.getReturnType())) return 0;
// need to allow for the special case of 'clone' - which is like abstract but is
// not marked abstract. The code below this next line seems to make assumptions
// about what will have gotten through the compiler based on the normal
// java rules. clone goes against these...
if (m2.isProtected() && m2.getName().charAt(0)=='c') {
UnresolvedType declaring = m2.getDeclaringType();
if (declaring!=null) {
if (declaring.getName().equals("java.lang.Object") && m2.getName().equals("clone")) return +1;
}
}
if (Modifier.isAbstract(m1.getModifiers())) return -1;
if (Modifier.isAbstract(m2.getModifiers())) return +1;
if (m1.getDeclaringType().equals(m2.getDeclaringType())) return 0;
ResolvedType t1 = m1.getDeclaringType().resolve(world);
ResolvedType t2 = m2.getDeclaringType().resolve(world);
if (t1.isAssignableFrom(t2)) {
return -1;
}
if (t2.isAssignableFrom(t1)) {
return +1;
}
return 0;
}
public static boolean isMoreVisible(int m1, int m2) {
if (Modifier.isPrivate(m1)) return false;
if (isPackage(m1)) return Modifier.isPrivate(m2);
if (Modifier.isProtected(m1)) return /* private package */ (Modifier.isPrivate(m2) || isPackage(m2));
if (Modifier.isPublic(m1)) return /* private package protected */ ! Modifier.isPublic(m2);
throw new RuntimeException("bad modifier: " + m1);
}
private static boolean isPackage(int i) {
return (0 == (i & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED)));
}
private void interTypeConflictError(
ConcreteTypeMunger m1,
ConcreteTypeMunger m2) {
//XXX this works only if we ignore separate compilation issues
//XXX dual errors possible if (this instanceof BcelObjectType) return;
//System.err.println("conflict at " + m2.getSourceLocation());
getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.ITD_CONFLICT,m1.getAspectType().getName(),
m2.getSignature(),m2.getAspectType().getName()),
m2.getSourceLocation(), getSourceLocation());
}
public ResolvedMember lookupSyntheticMember(Member member) {
//??? horribly inefficient
//for (Iterator i =
//System.err.println("lookup " + member + " in " + interTypeMungers);
for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger m = (ConcreteTypeMunger)i.next();
ResolvedMember ret = m.getMatchingSyntheticMember(member);
if (ret != null) {
//System.err.println(" found: " + ret);
return ret;
}
}
// Handling members for the new array join point
if (world.isJoinpointArrayConstructionEnabled() && this.isArray()) {
if (member.getKind()==Member.CONSTRUCTOR) {
ResolvedMemberImpl ret =
new ResolvedMemberImpl(Member.CONSTRUCTOR,this,Modifier.PUBLIC,
ResolvedType.VOID,"<init>",world.resolve(member.getParameterTypes()));
return ret;
}
}
// if (this.getSuperclass() != ResolvedType.OBJECT && this.getSuperclass() != null) {
// return getSuperclass().lookupSyntheticMember(member);
// }
return null;
}
public void clearInterTypeMungers() {
if (isRawType()) getGenericType().clearInterTypeMungers();
interTypeMungers = new ArrayList();
}
public boolean isTopmostImplementor(ResolvedType interfaceType) {
if (isInterface()) return false;
if (!interfaceType.isAssignableFrom(this,true)) return false;
// check that I'm truly the topmost implementor
if (this.getSuperclass().isMissing()) return true; // we don't know anything about supertype, and it can't be exposed to weaver
if (interfaceType.isAssignableFrom(this.getSuperclass(),true)) {
return false;
}
return true;
}
public ResolvedType getTopmostImplementor(ResolvedType interfaceType) {
if (isInterface()) return null;
if (!interfaceType.isAssignableFrom(this)) return null;
// Check if my super class is an implementor?
ResolvedType higherType = this.getSuperclass().getTopmostImplementor(interfaceType);
if (higherType!=null) return higherType;
return this;
}
private ResolvedType findHigher(ResolvedType other) {
if (this == other) return this;
for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) {
ResolvedType rtx = (ResolvedType)i.next();
boolean b = this.isAssignableFrom(rtx);
if (b) return rtx;
}
return null;
}
public List getExposedPointcuts() {
List ret = new ArrayList();
if (getSuperclass() != null) ret.addAll(getSuperclass().getExposedPointcuts());
for (Iterator i = Arrays.asList(getDeclaredInterfaces()).iterator(); i.hasNext(); ) {
ResolvedType t = (ResolvedType)i.next();
addPointcutsResolvingConflicts(ret, Arrays.asList(t.getDeclaredPointcuts()), false);
}
addPointcutsResolvingConflicts(ret, Arrays.asList(getDeclaredPointcuts()), true);
for (Iterator i = ret.iterator(); i.hasNext(); ) {
ResolvedPointcutDefinition inherited = (ResolvedPointcutDefinition)i.next();
// System.err.println("looking at: " + inherited + " in " + this);
// System.err.println(" " + inherited.isAbstract() + " in " + this.isAbstract());
if (inherited.isAbstract()) {
if (!this.isAbstract()) {
getWorld().showMessage(IMessage.ERROR,
WeaverMessages.format(WeaverMessages.POINCUT_NOT_CONCRETE,inherited,this.getName()),
inherited.getSourceLocation(), this.getSourceLocation());
}
}
}
return ret;
}
private void addPointcutsResolvingConflicts(List acc, List added, boolean isOverriding) {
for (Iterator i = added.iterator(); i.hasNext();) {
ResolvedPointcutDefinition toAdd =
(ResolvedPointcutDefinition) i.next();
//System.err.println("adding: " + toAdd);
for (Iterator j = acc.iterator(); j.hasNext();) {
ResolvedPointcutDefinition existing =
(ResolvedPointcutDefinition) j.next();
if (existing == toAdd) continue;
if (!isVisible(existing.getModifiers(),
existing.getDeclaringType().resolve(getWorld()),
this)) {
continue;
}
if (conflictingSignature(existing, toAdd)) {
if (isOverriding) {
checkLegalOverride(existing, toAdd);
j.remove();
} else {
getWorld().showMessage(
IMessage.ERROR,
WeaverMessages.format(WeaverMessages.CONFLICTING_INHERITED_POINTCUTS,this.getName() + toAdd.getSignature()),
existing.getSourceLocation(),
toAdd.getSourceLocation());
j.remove();
}
}
}
acc.add(toAdd);
}
}
public ISourceLocation getSourceLocation() {
return null;
}
public boolean isExposedToWeaver() {
return false;
}
public WeaverStateInfo getWeaverState() {
return null;
}
/**
* Overridden by ReferenceType to return a sensible answer for parameterized and raw types.
*
* @return
*/
public ResolvedType getGenericType() {
if (!(isParameterizedType() || isRawType()))
throw new BCException("The type "+getBaseName()+" is not parameterized or raw - it has no generic type");
return null;
}
/**
* overriden by ReferenceType to return the gsig for a generic type
* @return
*/
public String getGenericSignature() {
return "";
}
public ResolvedType parameterizedWith(UnresolvedType[] typeParameters) {
if (!(isGenericType() || isParameterizedType())) return this;
return TypeFactory.createParameterizedType(this.getGenericType(), typeParameters, getWorld());
}
/**
* Iff I am a parameterized type, and any of my parameters are type variable
* references, return a version with those type parameters replaced in accordance
* with the passed bindings.
*/
public UnresolvedType parameterize(Map typeBindings) {
if (!isParameterizedType()) throw new IllegalStateException("Can't parameterize a type that is not a parameterized type");
boolean workToDo = false;
for (int i = 0; i < typeParameters.length; i++) {
if (typeParameters[i].isTypeVariableReference()) {
workToDo = true;
}
}
if (!workToDo) {
return this;
} else {
UnresolvedType[] newTypeParams = new UnresolvedType[typeParameters.length];
for (int i = 0; i < newTypeParams.length; i++) {
newTypeParams[i] = typeParameters[i];
if (newTypeParams[i].isTypeVariableReference()) {
TypeVariableReferenceType tvrt = (TypeVariableReferenceType) newTypeParams[i];
UnresolvedType binding = (UnresolvedType) typeBindings.get(tvrt.getTypeVariable().getName());
if (binding != null) newTypeParams[i] = binding;
}
}
return TypeFactory.createParameterizedType(getGenericType(), newTypeParams, getWorld());
}
}
public boolean hasParameterizedSuperType() {
getParameterizedSuperTypes();
return parameterizedSuperTypes.length > 0;
}
public boolean hasGenericSuperType() {
ResolvedType[] superTypes = getDeclaredInterfaces();
for (int i = 0; i < superTypes.length; i++) {
if (superTypes[i].isGenericType()) return true;
}
return false;
}
private ResolvedType[] parameterizedSuperTypes = null;
/**
* Similar to the above method, but accumulates the super types
*
* @return
*/
public ResolvedType[] getParameterizedSuperTypes() {
if (parameterizedSuperTypes != null) return parameterizedSuperTypes;
List accumulatedTypes = new ArrayList();
accumulateParameterizedSuperTypes(this,accumulatedTypes);
ResolvedType[] ret = new ResolvedType[accumulatedTypes.size()];
parameterizedSuperTypes = (ResolvedType[]) accumulatedTypes.toArray(ret);
return parameterizedSuperTypes;
}
private void accumulateParameterizedSuperTypes(ResolvedType forType, List parameterizedTypeList) {
if (forType.isParameterizedType()) {
parameterizedTypeList.add(forType);
}
if (forType.getSuperclass() != null) {
accumulateParameterizedSuperTypes(forType.getSuperclass(), parameterizedTypeList);
}
ResolvedType[] interfaces = forType.getDeclaredInterfaces();
for (int i = 0; i < interfaces.length; i++) {
accumulateParameterizedSuperTypes(interfaces[i], parameterizedTypeList);
}
}
/**
* Types may have pointcuts just as they have methods and fields.
*/
public ResolvedPointcutDefinition findPointcut(String name, World world) {
throw new UnsupportedOperationException("Not yet implemenented");
}
/**
* @return true if assignable to java.lang.Exception
*/
public boolean isException() {
return (world.getCoreType(UnresolvedType.JAVA_LANG_EXCEPTION).isAssignableFrom(this));
}
/**
* @return true if it is an exception and it is a checked one, false otherwise.
*/
public boolean isCheckedException() {
if (!isException()) return false;
if (world.getCoreType(UnresolvedType.RUNTIME_EXCEPTION).isAssignableFrom(this)) return false;
return true;
}
/**
* Determines if variables of this type could be assigned values of another
* with lots of help.
* java.lang.Object is convertable from all types.
* A primitive type is convertable from X iff it's assignable from X.
* A reference type is convertable from X iff it's coerceable from X.
* In other words, X isConvertableFrom Y iff the compiler thinks that _some_ value of Y
* could be assignable to a variable of type X without loss of precision.
*
* @param other the other type
* @param world the {@link World} in which the possible assignment should be checked.
* @return true iff variables of this type could be assigned values of other with possible conversion
*/
public final boolean isConvertableFrom(ResolvedType other) {
// // version from TypeX
// if (this.equals(OBJECT)) return true;
// if (this.isPrimitiveType() || other.isPrimitiveType()) return this.isAssignableFrom(other);
// return this.isCoerceableFrom(other);
//
// version from ResolvedTypeX
if (this.equals(OBJECT)) return true;
if (world.isInJava5Mode()) {
if (this.isPrimitiveType()^other.isPrimitiveType()) { // If one is primitive and the other isnt
if (validBoxing.contains(this.getSignature()+other.getSignature())) return true;
}
}
if (this.isPrimitiveType() || other.isPrimitiveType()) return this.isAssignableFrom(other);
return this.isCoerceableFrom(other);
}
/**
* Determines if the variables of this type could be assigned values
* of another type without casting. This still allows for assignment conversion
* as per JLS 2ed 5.2. For object types, this means supertypeOrEqual(THIS, OTHER).
*
* @param other the other type
* @param world the {@link World} in which the possible assignment should be checked.
* @return true iff variables of this type could be assigned values of other without casting
* @throws NullPointerException if other is null
*/
public abstract boolean isAssignableFrom(ResolvedType other);
public abstract boolean isAssignableFrom(ResolvedType other, boolean allowMissing);
/**
* Determines if values of another type could possibly be cast to
* this type. The rules followed are from JLS 2ed 5.5, "Casting Conversion".
* <p/>
* <p> This method should be commutative, i.e., for all UnresolvedType a, b and all World w:
* <p/>
* <blockquote><pre>
* a.isCoerceableFrom(b, w) == b.isCoerceableFrom(a, w)
* </pre></blockquote>
*
* @param other the other type
* @param world the {@link World} in which the possible coersion should be checked.
* @return true iff values of other could possibly be cast to this type.
* @throws NullPointerException if other is null.
*/
public abstract boolean isCoerceableFrom(ResolvedType other);
public boolean needsNoConversionFrom(ResolvedType o) {
return isAssignableFrom(o);
}
/**
* Implemented by ReferenceTypes
*/
public String getSignatureForAttribute() {
throw new RuntimeException("Cannot ask this type "+this+" for a generic sig attribute");
}
private FuzzyBoolean parameterizedWithAMemberTypeVariable = FuzzyBoolean.MAYBE;
/**
* return true if the parameterization of this type includes a member type variable. Member
* type variables occur in generic methods/ctors.
*/
public boolean isParameterizedWithAMemberTypeVariable() {
// MAYBE means we haven't worked it out yet...
if (parameterizedWithAMemberTypeVariable==FuzzyBoolean.MAYBE) {
// if there are no type parameters then we cant be...
if (typeParameters==null || typeParameters.length==0) {
parameterizedWithAMemberTypeVariable = FuzzyBoolean.NO;
return false;
}
for (int i = 0; i < typeParameters.length; i++) {
UnresolvedType aType = (ResolvedType)typeParameters[i];
if (aType.isTypeVariableReference() &&
// assume the worst - if its definetly not a type declared one, it could be anything
((TypeVariableReference)aType).getTypeVariable().getDeclaringElementKind()!=TypeVariable.TYPE) {
parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES;
return true;
}
if (aType.isParameterizedType()) {
boolean b = aType.isParameterizedWithAMemberTypeVariable();
if (b) {
parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES;
return true;
}
}
if (aType.isGenericWildcard()) {
if (aType.isExtends()) {
boolean b = false;
UnresolvedType upperBound = aType.getUpperBound();
if (upperBound.isParameterizedType()) {
b = upperBound.isParameterizedWithAMemberTypeVariable();
} else if (upperBound.isTypeVariableReference() && ((TypeVariableReference)upperBound).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) {
b = true;
}
if (b) {
parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES;
return true;
}
// FIXME asc need to check additional interface bounds
}
if (aType.isSuper()) {
boolean b = false;
UnresolvedType lowerBound = aType.getLowerBound();
if (lowerBound.isParameterizedType()) {
b = lowerBound.isParameterizedWithAMemberTypeVariable();
} else if (lowerBound.isTypeVariableReference() && ((TypeVariableReference)lowerBound).getTypeVariable().getDeclaringElementKind()==TypeVariable.METHOD) {
b = true;
}
if (b) {
parameterizedWithAMemberTypeVariable = FuzzyBoolean.YES;
return true;
}
}
}
}
parameterizedWithAMemberTypeVariable=FuzzyBoolean.NO;
}
return parameterizedWithAMemberTypeVariable.alwaysTrue();
}
protected boolean ajMembersNeedParameterization() {
if (isParameterizedType()) return true;
if (getSuperclass() != null) return getSuperclass().ajMembersNeedParameterization();
return false;
}
protected Map getAjMemberParameterizationMap() {
Map myMap = getMemberParameterizationMap();
if (myMap.size() == 0) {
// might extend a parameterized aspect that we also need to consider...
if (getSuperclass() != null) return getSuperclass().getAjMemberParameterizationMap();
}
return myMap;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.