aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authoraclement <aclement>2008-08-28 02:59:19 +0000
committeraclement <aclement>2008-08-28 02:59:19 +0000
commitaf00617ba35c418cafa385397086acc489ffb0da (patch)
treed315363972dcc0fa2128e34f681b340a720bc562
parent75b4195ec99ece743a5a95484238d0d9dbef55b2 (diff)
downloadaspectj-af00617ba35c418cafa385397086acc489ffb0da.tar.gz
aspectj-af00617ba35c418cafa385397086acc489ffb0da.zip
fixed eclipse warnings
-rw-r--r--org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/BuildArgParser.java871
-rw-r--r--org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseResolvedMember.java129
-rw-r--r--org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/problem/AjProblemReporter.java812
-rw-r--r--org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjState.java1541
-rw-r--r--org.aspectj.ajdt.core/src/org/aspectj/org/eclipse/jdt/core/dom/AjASTConverter.java2
-rw-r--r--org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/ajc/AjdtCommandTestCase.java312
-rw-r--r--org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/CompilerDumpTestCase.java53
-rw-r--r--org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/DeclareParents.java868
-rw-r--r--org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/ProceedOnErrorTestCase.java74
-rw-r--r--org.aspectj.ajdt.core/testsrc/org/aspectj/tools/ajc/AjASTTest.java1205
10 files changed, 2864 insertions, 3003 deletions
diff --git a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/BuildArgParser.java b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/BuildArgParser.java
index dfc31db68..0e51ceecc 100644
--- a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/BuildArgParser.java
+++ b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/BuildArgParser.java
@@ -10,8 +10,6 @@
* PARC initial implementation
* ******************************************************************/
-
-
package org.aspectj.ajdt.ajc;
import java.io.File;
@@ -48,202 +46,196 @@ import org.aspectj.weaver.WeaverMessages;
public class BuildArgParser extends Main {
private static final String BUNDLE_NAME = "org.aspectj.ajdt.ajc.messages";
- private static boolean LOADED_BUNDLE = false;
-
- static {
- Main.bundleName = BUNDLE_NAME;
+ private static boolean LOADED_BUNDLE = false;
+
+ static {
+ Main.bundleName = BUNDLE_NAME;
ResourceBundleFactory.getBundle(Locale.getDefault());
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 _bind("misc.usage",new String[]{_bind("compiler.name",(String[])null)});
- }
-
- public static String getXOptionUsage() {
- return _bind("xoption.usage",new String[]{_bind("compiler.name",(String[])null)});
- }
-
- /**
- * 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;
-
+
+ /** 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 _bind("misc.usage", new String[] { _bind("compiler.name", (String[]) null) });
+ }
+
+ public static String getXOptionUsage() {
+ return _bind("xoption.usage", new String[] { _bind("compiler.name", (String[]) null) });
+ }
+
+ /**
+ * 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;
+ 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);
+ /** 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.
+ * 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.
+ * @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);
+ 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.
- */
+ }
+
+ /**
+ * 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);
+ 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[] { "" };
-
+ 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;
- if (swi)
- delegate.dontIgnore(IMessage.WEAVEINFO);
- else
- delegate.ignore(IMessage.WEAVEINFO);
+ IMessageHandler delegate = ((CountingMessageHandler) handler).delegate;
+ if (swi)
+ delegate.dontIgnore(IMessage.WEAVEINFO);
+ else
+ delegate.ignore(IMessage.WEAVEINFO);
}
-
- boolean incrementalMode = buildConfig.isIncrementalMode()
- || buildConfig.isIncrementalFileMode();
-
+
+ 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 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()
+ // 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
+ // 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()]));
-
+ 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()));
+ 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");
+
+ 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
+ * 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();
+ 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);
+ 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)) {
+ 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);
+ 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)) {
+ 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);
+ 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);
+ location = new SourceLocation(buildConfig.getConfigFile(), 0);
}
- IMessage m = new Message(iie.getMessage(), IMessage.ERROR, null, location);
+ IMessage m = new Message(iie.getMessage(), IMessage.ERROR, null, location);
handler.handleMessage(m);
}
return buildConfig;
@@ -251,259 +243,242 @@ public class BuildArgParser extends Main {
public void printVersion() {
final String version = bind("misc.version", //$NON-NLS-1$
- new String[] {
- bind("compiler.name"), //$NON-NLS-1$
- Version.text+" - Built: "+Version.time_text,
- bind("compiler.version"), //$NON-NLS-1$
- bind("compiler.copyright") //$NON-NLS-1$
- }
- );
+ new String[] { bind("compiler.name"), //$NON-NLS-1$
+ Version.text + " - Built: " + Version.time_text, bind("compiler.version"), //$NON-NLS-1$
+ bind("compiler.copyright") //$NON-NLS-1$
+ });
System.out.println(version);
}
-
+
public void printUsage() {
- System.out.println(bind("misc.usage")); //$NON-NLS-1$
+ 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);
+ /**
+ * 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 (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);
-// }
+
+ /**
+ * 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) {
+ 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();
+ 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;
- }
+ 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());
+ // classpathCollector.add(tokenizer.nextToken());
File dirFile = new File(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());
+ classpathCollector.add(files[i].getAbsolutePath());
}
} else {
- // XXX alert on invalid -extdirs entries
+ // 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 class AjcConfigParser extends ConfigParser {
private String bootclasspath = null;
private String classpath = null;
- private String extdirs = null;
- private List unparsedArgs = new ArrayList();
+ 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?
+
+ 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);
-
+ 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);
+ StringTokenizer st = new StringTokenizer(((ConfigParser.Arg) args.get(nextArgIndex)).getValue(),
+ File.pathSeparator);
while (st.hasMoreTokens()) {
String filename = st.nextToken();
File file = makeFile(filename);
if (FileUtil.isZipFile(file)) {
- inPath.add(file);
+ inPath.add(file);
} else {
if (file.isDirectory()) {
inPath.add(file);
- } else
-
- showWarning("skipping missing, empty or corrupt inpath entry: " + filename);
+ } else
+
+ showWarning("skipping missing, empty or corrupt inpath entry: " + filename);
}
}
buildConfig.setInPath(inPath);
- args.remove(args.get(nextArgIndex));
- }
- } else if (arg.equals("-injars")) {;
+ 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 (FileUtil.isZipFile(jarFile)) {
- buildConfig.getInJars().add(jarFile);
- } else {
- File dirFile = makeFile(filename);
- if (dirFile.isDirectory()) {
- buildConfig.getInJars().add(dirFile);
- } else
-
- showWarning("skipping missing, empty or corrupt injar: " + filename);
- }
- }
-
- args.remove(args.get(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 (FileUtil.isZipFile(jarFile)) {
+ buildConfig.getInJars().add(jarFile);
+ } else {
+ File dirFile = makeFile(filename);
+ if (dirFile.isDirectory()) {
+ buildConfig.getInJars().add(dirFile);
+ } else
+
+ showWarning("skipping missing, empty or corrupt injar: " + filename);
+ }
+ }
+
+ args.remove(args.get(nextArgIndex));
}
- } else if (arg.equals("-aspectpath")) {;
+ } 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 (FileUtil.isZipFile(jarFile) || jarFile.isDirectory()) {
- buildConfig.getAspectpath().add(jarFile);
- } else {
- showWarning("skipping missing, empty or corrupt aspectpath entry: " + filename);
- }
- }
-
- args.remove(args.get(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 (FileUtil.isZipFile(jarFile) || jarFile.isDirectory()) {
+ buildConfig.getAspectpath().add(jarFile);
+ } else {
+ showWarning("skipping missing, empty or corrupt aspectpath entry: " + 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);
+ 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")) {
+ } 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());
+ // buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_OutJAR, CompilerOptions.GENERATE);
+ File jarFile = makeFile(((ConfigParser.Arg) args.get(nextArgIndex)).getValue());
if (!jarFile.isDirectory()) {
try {
if (!jarFile.exists()) {
- jarFile.createNewFile();
- }
- buildConfig.setOutputJar(jarFile);
- } catch (IOException ioe) {
- showError("unable to create outjar file: " + jarFile);
+ jarFile.createNewFile();
+ }
+ buildConfig.setOutputJar(jarFile);
+ } catch (IOException ioe) {
+ showError("unable to create outjar file: " + jarFile);
}
} else {
showError("invalid -outjar file: " + jarFile);
@@ -512,36 +487,36 @@ public class BuildArgParser extends Main {
} else {
showError("-outjar requires jar path argument");
}
- } else if (arg.equals("-outxml")) {
- buildConfig.setOutxmlName(org.aspectj.bridge.Constants.AOP_AJC_XML);
- } else if (arg.equals("-outxmlfile")) {
+ } else if (arg.equals("-outxml")) {
+ buildConfig.setOutxmlName(org.aspectj.bridge.Constants.AOP_AJC_XML);
+ } else if (arg.equals("-outxmlfile")) {
if (args.size() > nextArgIndex) {
- String name = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
- buildConfig.setOutxmlName(name);
+ 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")){
+ } 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")) {
+ } 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");
- }
+ 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);
@@ -560,44 +535,44 @@ public class BuildArgParser extends Main {
} else if (arg.equals("-XjavadocsInModel")) {
buildConfig.setGenerateModelMode(true);
buildConfig.setGenerateJavadocsInModelMode(true);
- } else if (arg.equals("-Xdev:NoAtAspectJProcessing")) {
+ } else if (arg.equals("-Xdev:NoAtAspectJProcessing")) {
buildConfig.setNoAtAspectJAnnotationProcessing(true);
} else if (arg.equals("-XaddSerialVersionUID")) {
buildConfig.setAddSerialVerUID(true);
- } else if (arg.equals("-Xdev:Pinpoint")) {
+ } else if (arg.equals("-Xdev:Pinpoint")) {
buildConfig.setXdevPinpointMode(true);
- } else if (arg.startsWith("-Xjoinpoints:")) {
- buildConfig.setXJoinpoints(arg.substring(13));
- } else if (arg.equals("-noWeave") || arg.equals( "-XnoWeave")) {
+ } else if (arg.startsWith("-Xjoinpoints:")) {
+ buildConfig.setXJoinpoints(arg.substring(13));
+ } 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")) {
+ } 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("-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);
+ 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")) {
+ } 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?
+ 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);
+ buildConfig.setLintSpecFile(lintSpecFile);
} else {
showError("bad -Xlintfile file: " + lintSpecFile);
buildConfig.setLintSpecFile(null);
@@ -606,162 +581,164 @@ public class BuildArgParser extends Main {
} 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("-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();
+ String bcpArg = ((ConfigParser.Arg) args.get(nextArgIndex)).getValue();
StringBuffer bcp = new StringBuffer();
- StringTokenizer strTok = new StringTokenizer(bcpArg,File.pathSeparator);
+ StringTokenizer strTok = new StringTokenizer(bcpArg, File.pathSeparator);
while (strTok.hasMoreTokens()) {
- bcp.append(makeFile(strTok.nextToken()));
- if (strTok.hasMoreTokens()) {
- bcp.append(File.pathSeparator);
- }
+ bcp.append(makeFile(strTok.nextToken()));
+ if (strTok.hasMoreTokens()) {
+ bcp.append(File.pathSeparator);
+ }
}
bootclasspath = bcp.toString();
- args.remove(args.get(nextArgIndex));
+ 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();
+ String cpArg = ((ConfigParser.Arg) args.get(nextArgIndex)).getValue();
StringBuffer cp = new StringBuffer();
- StringTokenizer strTok = new StringTokenizer(cpArg,File.pathSeparator);
+ StringTokenizer strTok = new StringTokenizer(cpArg, File.pathSeparator);
while (strTok.hasMoreTokens()) {
- cp.append(makeFile(strTok.nextToken()));
- if (strTok.hasMoreTokens()) {
- cp.append(File.pathSeparator);
- }
+ cp.append(makeFile(strTok.nextToken()));
+ if (strTok.hasMoreTokens()) {
+ cp.append(File.pathSeparator);
+ }
}
classpath = cp.toString();
- args.remove(args.get(nextArgIndex));
+ 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();
+ String extdirsArg = ((ConfigParser.Arg) args.get(nextArgIndex)).getValue();
StringBuffer ed = new StringBuffer();
- StringTokenizer strTok = new StringTokenizer(extdirsArg,File.pathSeparator);
+ StringTokenizer strTok = new StringTokenizer(extdirsArg, File.pathSeparator);
while (strTok.hasMoreTokens()) {
- ed.append(makeFile(strTok.nextToken()));
- if (strTok.hasMoreTokens()) {
- ed.append(File.pathSeparator);
- }
- }
+ 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("-timers")) {
- // swallow - it is dealt with in Main.runMain()
- } 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("-1.6")) {
- buildConfig.setBehaveInJava5Way(true);
- unparsedArgs.add("-1.6");
- } else if (arg.equals("-source")) {
- if (args.size() > nextArgIndex) {
- String level = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue();
- if (level.equals("1.5") || level.equals("5") ||
- level.equals("1.6") || level.equals("6")) {
- buildConfig.setBehaveInJava5Way(true);
- }
- unparsedArgs.add("-source");
- unparsedArgs.add(level);
- 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("-timers")) {
+ // swallow - it is dealt with in Main.runMain()
+ } 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("-1.6")) {
+ buildConfig.setBehaveInJava5Way(true);
+ unparsedArgs.add("-1.6");
+ } else if (arg.equals("-source")) {
+ if (args.size() > nextArgIndex) {
+ String level = ((ConfigParser.Arg) args.get(nextArgIndex)).getValue();
+ if (level.equals("1.5") || level.equals("5") || level.equals("1.6") || level.equals("6")) {
+ 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
+ // 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);
+ 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;
+ }
}
- }
- 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) {
+ }
+
+ public void showError(String message) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
- location = new SourceLocation(buildConfig.getConfigFile(), 0);
- }
+ 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);
- }
-
+ // MessageUtil.error(handler, CONFIG_MSG + message);
+ }
+
protected void showWarning(String message) {
ISourceLocation location = null;
if (buildConfig.getConfigFile() != null) {
- location = new SourceLocation(buildConfig.getConfigFile(), 0);
- }
+ location = new SourceLocation(buildConfig.getConfigFile(), 0);
+ }
IMessage errorMessage = new Message(CONFIG_MSG + message, IMessage.WARNING, null, location);
handler.handleMessage(errorMessage);
-// MessageUtil.warn(handler, message);
- }
-
+ // 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;
+ if (dir == null || ret.isAbsolute())
+ return ret;
try {
dir = dir.getCanonicalFile();
- } catch (IOException ioe) { }
+ } catch (IOException ioe) {
+ }
return new File(dir, name);
}
- }
+ }
}
diff --git a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseResolvedMember.java b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseResolvedMember.java
index b4a2fae40..ae62d46a9 100644
--- a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseResolvedMember.java
+++ b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseResolvedMember.java
@@ -38,84 +38,91 @@ import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.World;
/**
- * In the pipeline world, we can be weaving before all types have come through from compilation.
- * In some cases this means the weaver will want to ask questions of eclipse types and this
- * subtype of ResolvedMemberImpl is here to answer some of those questions - it is backed by
- * the real eclipse MethodBinding object and can translate from Eclipse -> Weaver information.
- */
+ * In the pipeline world, we can be weaving before all types have come through from compilation. In some cases this means the weaver
+ * will want to ask questions of eclipse types and this subtype of ResolvedMemberImpl is here to answer some of those questions - it
+ * is backed by the real eclipse MethodBinding object and can translate from Eclipse -> Weaver information.
+ */
public class EclipseResolvedMember extends ResolvedMemberImpl {
-
- private static String[] NO_ARGS = new String[]{};
-
+
+ private static String[] NO_ARGS = new String[] {};
+
private Binding realBinding;
private String[] argumentNames;
private World w;
private ResolvedType[] cachedAnnotationTypes;
private EclipseFactory eclipseFactory;
-
- public EclipseResolvedMember(MethodBinding binding, MemberKind memberKind, ResolvedType realDeclaringType, int modifiers, UnresolvedType rettype, String name, UnresolvedType[] paramtypes, UnresolvedType[] extypes, EclipseFactory eclipseFactory) {
- super(memberKind,realDeclaringType,modifiers,rettype,name,paramtypes,extypes);
+
+ public EclipseResolvedMember(MethodBinding binding, MemberKind memberKind, ResolvedType realDeclaringType, int modifiers,
+ UnresolvedType rettype, String name, UnresolvedType[] paramtypes, UnresolvedType[] extypes,
+ EclipseFactory eclipseFactory) {
+ super(memberKind, realDeclaringType, modifiers, rettype, name, paramtypes, extypes);
this.realBinding = binding;
this.eclipseFactory = eclipseFactory;
this.w = realDeclaringType.getWorld();
}
- public EclipseResolvedMember(FieldBinding binding, MemberKind field, ResolvedType realDeclaringType, int modifiers, ResolvedType type, String string, UnresolvedType[] none) {
- super(field,realDeclaringType,modifiers,type,string,none);
+ public EclipseResolvedMember(FieldBinding binding, MemberKind field, ResolvedType realDeclaringType, int modifiers,
+ ResolvedType type, String string, UnresolvedType[] none) {
+ super(field, realDeclaringType, modifiers, type, string, none);
this.realBinding = binding;
this.w = realDeclaringType.getWorld();
}
-
public boolean hasAnnotation(UnresolvedType ofType) {
ResolvedType[] annotationTypes = getAnnotationTypes();
- if (annotationTypes==null) return false;
+ if (annotationTypes == null)
+ return false;
for (int i = 0; i < annotationTypes.length; i++) {
ResolvedType type = annotationTypes[i];
- if (type.equals(ofType)) return true;
+ if (type.equals(ofType))
+ return true;
}
return false;
}
public AnnotationX[] getAnnotations() {
- long abits = realBinding.getAnnotationTagBits(); // ensure resolved
+ // long abits =
+ realBinding.getAnnotationTagBits(); // ensure resolved
Annotation[] annos = getEclipseAnnotations();
- if (annos==null) return null;
- // TODO errr missing in action - we need to implement this! Probably using something like EclipseAnnotationConvertor - itself not finished ;)
+ if (annos == null)
+ return null;
+ // TODO errr missing in action - we need to implement this! Probably using something like EclipseAnnotationConvertor -
+ // itself not finished ;)
throw new RuntimeException("not yet implemented - please raise an AJ bug");
-// return super.getAnnotations();
+ // return super.getAnnotations();
}
-
public AnnotationX getAnnotationOfType(UnresolvedType ofType) {
- long abits = realBinding.getAnnotationTagBits(); // ensure resolved
+ // long abits =
+ realBinding.getAnnotationTagBits(); // ensure resolved
Annotation[] annos = getEclipseAnnotations();
- if (annos==null) return null;
+ if (annos == null)
+ return null;
for (int i = 0; i < annos.length; i++) {
Annotation anno = annos[i];
UnresolvedType ut = UnresolvedType.forSignature(new String(anno.resolvedType.signature()));
if (w.resolve(ut).equals(ofType)) {
// Found the one
- return EclipseAnnotationConvertor.convertEclipseAnnotation(anno,w,eclipseFactory);
+ return EclipseAnnotationConvertor.convertEclipseAnnotation(anno, w, eclipseFactory);
}
}
return null;
}
-
+
public String getAnnotationDefaultValue() {
if (realBinding instanceof MethodBinding) {
- AbstractMethodDeclaration methodDecl = getTypeDeclaration().declarationOf((MethodBinding)realBinding);
+ AbstractMethodDeclaration methodDecl = getTypeDeclaration().declarationOf((MethodBinding) realBinding);
if (methodDecl instanceof AnnotationMethodDeclaration) {
- AnnotationMethodDeclaration annoMethodDecl = (AnnotationMethodDeclaration)methodDecl;
+ AnnotationMethodDeclaration annoMethodDecl = (AnnotationMethodDeclaration) methodDecl;
Expression e = annoMethodDecl.defaultValue;
- if (e.resolvedType==null)
- e.resolve(methodDecl.scope);
+ if (e.resolvedType == null)
+ e.resolve(methodDecl.scope);
// TODO does not cope with many cases...
if (e instanceof QualifiedNameReference) {
-
- QualifiedNameReference qnr = (QualifiedNameReference)e;
+
+ QualifiedNameReference qnr = (QualifiedNameReference) e;
if (qnr.binding instanceof FieldBinding) {
- FieldBinding fb = (FieldBinding)qnr.binding;
+ FieldBinding fb = (FieldBinding) qnr.binding;
StringBuffer sb = new StringBuffer();
sb.append(fb.declaringClass.signature());
sb.append(fb.name);
@@ -126,11 +133,12 @@ public class EclipseResolvedMember extends ResolvedMemberImpl {
} else if (e instanceof FalseLiteral) {
return "false";
} else if (e instanceof StringLiteral) {
- return new String(((StringLiteral)e).source());
+ return new String(((StringLiteral) e).source());
} else if (e instanceof IntLiteral) {
- return Integer.toString(((IntConstant)e.constant).intValue());
+ return Integer.toString(((IntConstant) e.constant).intValue());
} else {
- throw new BCException("EclipseResolvedMember.getAnnotationDefaultValue() not implemented for value of type '"+e.getClass()+"' - raise an AspectJ bug !");
+ throw new BCException("EclipseResolvedMember.getAnnotationDefaultValue() not implemented for value of type '"
+ + e.getClass() + "' - raise an AspectJ bug !");
}
}
}
@@ -141,7 +149,7 @@ public class EclipseResolvedMember extends ResolvedMemberImpl {
if (cachedAnnotationTypes == null) {
long abits = realBinding.getAnnotationTagBits(); // ensure resolved
Annotation[] annos = getEclipseAnnotations();
- if (annos==null) {
+ if (annos == null) {
cachedAnnotationTypes = ResolvedType.EMPTY_RESOLVED_TYPE_ARRAY;
} else {
cachedAnnotationTypes = new ResolvedType[annos.length];
@@ -153,19 +161,20 @@ public class EclipseResolvedMember extends ResolvedMemberImpl {
}
return cachedAnnotationTypes;
}
-
-
public String[] getParameterNames() {
- if (argumentNames!=null) return argumentNames;
+ if (argumentNames != null)
+ return argumentNames;
if (realBinding instanceof FieldBinding) {
- argumentNames=NO_ARGS;
+ argumentNames = NO_ARGS;
} else {
TypeDeclaration typeDecl = getTypeDeclaration();
- AbstractMethodDeclaration methodDecl =(typeDecl==null?null:typeDecl.declarationOf((MethodBinding)realBinding));
- Argument[] args = (methodDecl==null?null:methodDecl.arguments); // dont like this - why isnt the method found sometimes? is it because other errors are being reported?
- if (args==null) {
- argumentNames=NO_ARGS;
+ AbstractMethodDeclaration methodDecl = (typeDecl == null ? null : typeDecl.declarationOf((MethodBinding) realBinding));
+ Argument[] args = (methodDecl == null ? null : methodDecl.arguments); // dont like this - why isnt the method found
+ // sometimes? is it because other errors are
+ // being reported?
+ if (args == null) {
+ argumentNames = NO_ARGS;
} else {
argumentNames = new String[args.length];
for (int i = 0; i < argumentNames.length; i++) {
@@ -175,13 +184,13 @@ public class EclipseResolvedMember extends ResolvedMemberImpl {
}
return argumentNames;
}
-
+
private Annotation[] getEclipseAnnotations() {
if (realBinding instanceof MethodBinding) {
- AbstractMethodDeclaration methodDecl = getTypeDeclaration().declarationOf((MethodBinding)realBinding);
+ AbstractMethodDeclaration methodDecl = getTypeDeclaration().declarationOf((MethodBinding) realBinding);
return methodDecl.annotations;
} else if (realBinding instanceof FieldBinding) {
- FieldDeclaration fieldDecl = getTypeDeclaration().declarationOf((FieldBinding)realBinding);
+ FieldDeclaration fieldDecl = getTypeDeclaration().declarationOf((FieldBinding) realBinding);
return fieldDecl.annotations;
}
return null;
@@ -189,25 +198,27 @@ public class EclipseResolvedMember extends ResolvedMemberImpl {
private TypeDeclaration getTypeDeclaration() {
if (realBinding instanceof MethodBinding) {
- MethodBinding mb = (MethodBinding)realBinding;
- if (mb!=null) {
- SourceTypeBinding stb = (SourceTypeBinding)mb.declaringClass;
- if (stb!=null) {
+ MethodBinding mb = (MethodBinding) realBinding;
+ if (mb != null) {
+ SourceTypeBinding stb = (SourceTypeBinding) mb.declaringClass;
+ if (stb != null) {
ClassScope cScope = stb.scope;
- if (cScope!=null) return cScope.referenceContext;
+ if (cScope != null)
+ return cScope.referenceContext;
}
- }
+ }
} else if (realBinding instanceof FieldBinding) {
- FieldBinding fb = (FieldBinding)realBinding;
- if (fb!=null) {
- SourceTypeBinding stb = (SourceTypeBinding)fb.declaringClass;
- if (stb!=null) {
+ FieldBinding fb = (FieldBinding) realBinding;
+ if (fb != null) {
+ SourceTypeBinding stb = (SourceTypeBinding) fb.declaringClass;
+ if (stb != null) {
ClassScope cScope = stb.scope;
- if (cScope!=null) return cScope.referenceContext;
+ if (cScope != null)
+ return cScope.referenceContext;
}
}
}
return null;
}
-
+
}
diff --git a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/problem/AjProblemReporter.java b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/problem/AjProblemReporter.java
index 027e40162..c9043ffc5 100644
--- a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/problem/AjProblemReporter.java
+++ b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/problem/AjProblemReporter.java
@@ -10,8 +10,7 @@
* PARC initial implementation
* ******************************************************************/
-
- package org.aspectj.ajdt.internal.compiler.problem;
+package org.aspectj.ajdt.internal.compiler.problem;
import java.io.PrintWriter;
import java.io.StringWriter;
@@ -64,77 +63,68 @@ import org.aspectj.weaver.patterns.DeclareSoft;
import org.aspectj.weaver.patterns.TypePattern;
/**
- * Extends problem reporter to support compiler-side implementation of declare soft.
- * Also overrides error reporting for the need to implement abstract methods to
- * account for inter-type declarations and pointcut declarations. This second
- * job might be better done directly in the SourceTypeBinding/ClassScope classes.
+ * Extends problem reporter to support compiler-side implementation of declare soft. Also overrides error reporting for the need to
+ * implement abstract methods to account for inter-type declarations and pointcut declarations. This second job might be better done
+ * directly in the SourceTypeBinding/ClassScope classes.
*
* @author Jim Hugunin
*/
public class AjProblemReporter extends ProblemReporter {
-
+
private static final boolean DUMP_STACK = false;
-
+
public EclipseFactory factory;
- public AjProblemReporter(
- IErrorHandlingPolicy policy,
- CompilerOptions options,
- IProblemFactory problemFactory) {
+ public AjProblemReporter(IErrorHandlingPolicy policy, CompilerOptions options, IProblemFactory problemFactory) {
super(policy, options, problemFactory);
}
-
-
- public void unhandledException(
- TypeBinding exceptionType,
- ASTNode location)
- {
+ public void unhandledException(TypeBinding exceptionType, ASTNode location) {
if (!factory.getWorld().getDeclareSoft().isEmpty()) {
Shadow callSite = factory.makeShadow(location, referenceContext);
Shadow enclosingExec = factory.makeShadow(referenceContext);
// PR 72157 - calls to super / this within a constructor are not part of the cons join point.
if ((callSite == null) && (enclosingExec.getKind() == Shadow.ConstructorExecution)
- && (location instanceof ExplicitConstructorCall)) {
+ && (location instanceof ExplicitConstructorCall)) {
super.unhandledException(exceptionType, location);
return;
}
-// System.err.println("about to show error for unhandled exception: " + new String(exceptionType.sourceName()) +
-// " at " + location + " in " + referenceContext);
-
- for (Iterator i = factory.getWorld().getDeclareSoft().iterator(); i.hasNext(); ) {
- DeclareSoft d = (DeclareSoft)i.next();
+ // System.err.println("about to show error for unhandled exception: " + new String(exceptionType.sourceName()) +
+ // " at " + location + " in " + referenceContext);
+
+ for (Iterator i = factory.getWorld().getDeclareSoft().iterator(); i.hasNext();) {
+ DeclareSoft d = (DeclareSoft) i.next();
// We need the exceptionType to match the type in the declare soft statement
// This means it must either be the same type or a subtype
- ResolvedType throwException = factory.fromEclipse((ReferenceBinding)exceptionType);
- FuzzyBoolean isExceptionTypeOrSubtype =
- d.getException().matchesInstanceof(throwException);
- if (!isExceptionTypeOrSubtype.alwaysTrue() ) continue;
+ ResolvedType throwException = factory.fromEclipse((ReferenceBinding) exceptionType);
+ FuzzyBoolean isExceptionTypeOrSubtype = d.getException().matchesInstanceof(throwException);
+ if (!isExceptionTypeOrSubtype.alwaysTrue())
+ continue;
if (callSite != null) {
FuzzyBoolean match = d.getPointcut().match(callSite);
if (match.alwaysTrue()) {
- //System.err.println("matched callSite: " + callSite + " with " + d);
+ // System.err.println("matched callSite: " + callSite + " with " + d);
return;
} else if (!match.alwaysFalse()) {
- //!!! need this check to happen much sooner
- //throw new RuntimeException("unimplemented, shouldn't have fuzzy match here");
+ // !!! need this check to happen much sooner
+ // throw new RuntimeException("unimplemented, shouldn't have fuzzy match here");
}
}
if (enclosingExec != null) {
FuzzyBoolean match = d.getPointcut().match(enclosingExec);
if (match.alwaysTrue()) {
- //System.err.println("matched enclosingExec: " + enclosingExec + " with " + d);
+ // System.err.println("matched enclosingExec: " + enclosingExec + " with " + d);
return;
} else if (!match.alwaysFalse()) {
- //!!! need this check to happen much sooner
- //throw new RuntimeException("unimplemented, shouldn't have fuzzy match here");
+ // !!! need this check to happen much sooner
+ // throw new RuntimeException("unimplemented, shouldn't have fuzzy match here");
}
}
}
}
-
- //??? is this always correct
+
+ // ??? is this always correct
if (location instanceof Proceed) {
return;
}
@@ -145,127 +135,120 @@ public class AjProblemReporter extends ProblemReporter {
private boolean isPointcutDeclaration(MethodBinding binding) {
return CharOperation.prefixEquals(PointcutDeclaration.mangledPrefix, binding.selector);
}
-
- private boolean isIntertypeDeclaration(MethodBinding binding) {
- return (binding instanceof InterTypeMethodBinding);
- }
-
- public void abstractMethodCannotBeOverridden(
- SourceTypeBinding type,
- MethodBinding concreteMethod)
- {
+
+ private boolean isIntertypeDeclaration(MethodBinding binding) {
+ return (binding instanceof InterTypeMethodBinding);
+ }
+
+ public void abstractMethodCannotBeOverridden(SourceTypeBinding type, MethodBinding concreteMethod) {
if (isPointcutDeclaration(concreteMethod)) {
return;
}
super.abstractMethodCannotBeOverridden(type, concreteMethod);
}
-
- public void inheritedMethodReducesVisibility(SourceTypeBinding type, MethodBinding concreteMethod, MethodBinding[] abstractMethods) {
+ public void inheritedMethodReducesVisibility(SourceTypeBinding type, MethodBinding concreteMethod,
+ MethodBinding[] abstractMethods) {
// if we implemented this method by a public inter-type declaration, then there is no error
-
- ResolvedType onTypeX = null;
+
+ ResolvedType onTypeX = null;
// If the type is anonymous, look at its supertype
if (!type.isAnonymousType()) {
onTypeX = factory.fromEclipse(type);
} else {
// Hmmm. If the ITD is on an interface that is being 'instantiated' using an anonymous type,
- // we sort it out elsewhere and don't come into this method -
+ // we sort it out elsewhere and don't come into this method -
// so we don't have to worry about interfaces, just the superclass.
- onTypeX = factory.fromEclipse(type.superclass()); //abstractMethod.declaringClass);
+ onTypeX = factory.fromEclipse(type.superclass()); // abstractMethod.declaringClass);
}
- for (Iterator i = onTypeX.getInterTypeMungersIncludingSupers().iterator(); i.hasNext(); ) {
- ConcreteTypeMunger m = (ConcreteTypeMunger)i.next();
+ for (Iterator i = onTypeX.getInterTypeMungersIncludingSupers().iterator(); i.hasNext();) {
+ ConcreteTypeMunger m = (ConcreteTypeMunger) i.next();
ResolvedMember sig = m.getSignature();
- if (!Modifier.isAbstract(sig.getModifiers())) {
- if (ResolvedType
- .matches(
- AjcMemberMaker.interMethod(
- sig,
- m.getAspectType(),
- sig.getDeclaringType().resolve(factory.getWorld()).isInterface()),
- factory.makeResolvedMember(concreteMethod))) {
+ if (!Modifier.isAbstract(sig.getModifiers())) {
+ if (ResolvedType.matches(AjcMemberMaker.interMethod(sig, m.getAspectType(), sig.getDeclaringType().resolve(
+ factory.getWorld()).isInterface()), factory.makeResolvedMember(concreteMethod))) {
return;
}
}
}
- super.inheritedMethodReducesVisibility(type,concreteMethod,abstractMethods);
+ super.inheritedMethodReducesVisibility(type, concreteMethod, abstractMethods);
}
// if either of the MethodBinding is an ITD, we have already reported it.
public void staticAndInstanceConflict(MethodBinding currentMethod, MethodBinding inheritedMethod) {
- if (currentMethod instanceof InterTypeMethodBinding) return;
- if (inheritedMethod instanceof InterTypeMethodBinding) return;
+ if (currentMethod instanceof InterTypeMethodBinding)
+ return;
+ if (inheritedMethod instanceof InterTypeMethodBinding)
+ return;
super.staticAndInstanceConflict(currentMethod, inheritedMethod);
}
-
- public void abstractMethodMustBeImplemented(
- SourceTypeBinding type,
- MethodBinding abstractMethod)
- {
+
+ public void abstractMethodMustBeImplemented(SourceTypeBinding type, MethodBinding abstractMethod) {
// if this is a PointcutDeclaration then there is no error
- if (isPointcutDeclaration(abstractMethod)) return;
-
- if (isIntertypeDeclaration(abstractMethod)) return; // when there is a problem with an ITD not being implemented, it will be reported elsewhere
-
+ if (isPointcutDeclaration(abstractMethod))
+ return;
+
+ if (isIntertypeDeclaration(abstractMethod))
+ return; // when there is a problem with an ITD not being implemented, it will be reported elsewhere
+
if (CharOperation.prefixEquals("ajc$interField".toCharArray(), abstractMethod.selector)) {
- //??? think through how this could go wrong
+ // ??? think through how this could go wrong
return;
}
-
+
// if we implemented this method by an inter-type declaration, then there is no error
- //??? be sure this is always right
+ // ??? be sure this is always right
ResolvedType onTypeX = null;
-
+
// If the type is anonymous, look at its supertype
if (!type.isAnonymousType()) {
onTypeX = factory.fromEclipse(type);
} else {
// Hmmm. If the ITD is on an interface that is being 'instantiated' using an anonymous type,
- // we sort it out elsewhere and don't come into this method -
+ // we sort it out elsewhere and don't come into this method -
// so we don't have to worry about interfaces, just the superclass.
- onTypeX = factory.fromEclipse(type.superclass()); //abstractMethod.declaringClass);
+ onTypeX = factory.fromEclipse(type.superclass()); // abstractMethod.declaringClass);
}
-
- if (onTypeX.isRawType()) onTypeX = onTypeX.getGenericType();
- for (Iterator i = onTypeX.getInterTypeMungersIncludingSupers().iterator(); i.hasNext(); ) {
- ConcreteTypeMunger m = (ConcreteTypeMunger)i.next();
+ if (onTypeX.isRawType())
+ onTypeX = onTypeX.getGenericType();
+
+ for (Iterator i = onTypeX.getInterTypeMungersIncludingSupers().iterator(); i.hasNext();) {
+ ConcreteTypeMunger m = (ConcreteTypeMunger) i.next();
ResolvedMember sig = m.getSignature();
- if (sig != null && !Modifier.isAbstract(sig.getModifiers())) {
- ResolvedMember abstractMember = factory.makeResolvedMember(abstractMethod);
- if (abstractMember.getName().startsWith("ajc$interMethodDispatch")) {
- ResolvedType dType = factory.getWorld().resolve(sig.getDeclaringType(),false);
- if (ResolvedType
- .matches(
- AjcMemberMaker.interMethod(
- sig,
- m.getAspectType(),
- dType.isInterface()),
- abstractMember
- )) {
+ if (sig != null && !Modifier.isAbstract(sig.getModifiers())) {
+ ResolvedMember abstractMember = factory.makeResolvedMember(abstractMethod);
+ if (abstractMember.getName().startsWith("ajc$interMethodDispatch")) {
+ ResolvedType dType = factory.getWorld().resolve(sig.getDeclaringType(), false);
+ if (ResolvedType.matches(AjcMemberMaker.interMethod(sig, m.getAspectType(), dType.isInterface()),
+ abstractMember)) {
return;
}
- } else {
- // In this case we have something like:
- // interface I {}
- // abstract class C implements I { abstract void foo();}
- // class D extends C {}
- // ITD: public void I.foo() {...}
- // The ITD is providing the implementation of foo in the class D but when checking for whether the abstract
- // method is overridden, we won't be looking at whether the ITD overrides ajc$interMethodDispath$...foo but
- // whether it overrides the foo method from class C
- if (ResolvedType.matches(sig,factory.makeResolvedMember(abstractMethod))) return;
- }
+ } else {
+ // In this case we have something like:
+ // interface I {}
+ // abstract class C implements I { abstract void foo();}
+ // class D extends C {}
+ // ITD: public void I.foo() {...}
+ // The ITD is providing the implementation of foo in the class D but when checking for whether the abstract
+ // method is overridden, we won't be looking at whether the ITD overrides ajc$interMethodDispath$...foo but
+ // whether it overrides the foo method from class C
+ if (ResolvedType.matches(sig, factory.makeResolvedMember(abstractMethod)))
+ return;
+ }
}
}
super.abstractMethodMustBeImplemented(type, abstractMethod);
}
- /* (non-Javadoc)
- * @see org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter#disallowedTargetForAnnotation(org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation)
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter#disallowedTargetForAnnotation(org.aspectj.org.eclipse
+ * .jdt.internal.compiler.ast.Annotation)
*/
public void disallowedTargetForAnnotation(Annotation annotation) {
// if the annotation's recipient is an ITD, it might be allowed after all...
@@ -275,322 +258,365 @@ public class AjProblemReporter extends ProblemReporter {
if (name.startsWith("ajc$")) {
long metaTagBits = annotation.resolvedType.getAnnotationTagBits(); // could be forward reference
if (name.indexOf("interField") != -1) {
- if ((metaTagBits & TagBits.AnnotationForField) != 0) return;
- } else if (name.indexOf("interConstructor") != -1) {
- if ((metaTagBits & TagBits.AnnotationForConstructor) != 0) return;
+ if ((metaTagBits & TagBits.AnnotationForField) != 0)
+ return;
+ } else if (name.indexOf("interConstructor") != -1) {
+ if ((metaTagBits & TagBits.AnnotationForConstructor) != 0)
+ return;
} else if (name.indexOf("interMethod") != -1) {
- if ((metaTagBits & TagBits.AnnotationForMethod) != 0) return;
- } else if (name.indexOf("declare_"+DeclareAnnotation.AT_TYPE+"_")!=-1) {
- if ((metaTagBits & TagBits.AnnotationForAnnotationType)!=0 ||
- (metaTagBits & TagBits.AnnotationForType)!=0) return;
- } else if (name.indexOf("declare_"+DeclareAnnotation.AT_FIELD+"_")!=-1) {
- if ((metaTagBits & TagBits.AnnotationForField)!=0) return;
- } else if (name.indexOf("declare_"+DeclareAnnotation.AT_CONSTRUCTOR+"_")!=-1) {
- if ((metaTagBits & TagBits.AnnotationForConstructor)!=0) return;
+ if ((metaTagBits & TagBits.AnnotationForMethod) != 0)
+ return;
+ } else if (name.indexOf("declare_" + DeclareAnnotation.AT_TYPE + "_") != -1) {
+ if ((metaTagBits & TagBits.AnnotationForAnnotationType) != 0 || (metaTagBits & TagBits.AnnotationForType) != 0)
+ return;
+ } else if (name.indexOf("declare_" + DeclareAnnotation.AT_FIELD + "_") != -1) {
+ if ((metaTagBits & TagBits.AnnotationForField) != 0)
+ return;
+ } else if (name.indexOf("declare_" + DeclareAnnotation.AT_CONSTRUCTOR + "_") != -1) {
+ if ((metaTagBits & TagBits.AnnotationForConstructor) != 0)
+ return;
} else if (name.indexOf("declare_eow") != -1) {
- if ((metaTagBits & TagBits.AnnotationForField) != 0) return;
+ if ((metaTagBits & TagBits.AnnotationForField) != 0)
+ return;
}
}
}
-
+
// not our special case, report the problem...
super.disallowedTargetForAnnotation(annotation);
}
-
+
public void overridesPackageDefaultMethod(MethodBinding localMethod, MethodBinding inheritedMethod) {
- if (new String(localMethod.selector).startsWith("ajc$")) return;
- super.overridesPackageDefaultMethod(localMethod,inheritedMethod);
+ if (new String(localMethod.selector).startsWith("ajc$"))
+ return;
+ super.overridesPackageDefaultMethod(localMethod, inheritedMethod);
}
-
- public void handle(
- int problemId,
- String[] problemArguments,
- String[] messageArguments,
- int severity,
- int problemStartPosition,
- int problemEndPosition,
- ReferenceContext referenceContext,
- CompilationResult unitResult)
- {
+
+ public void handle(int problemId, String[] problemArguments, String[] messageArguments, int severity, int problemStartPosition,
+ int problemEndPosition, ReferenceContext referenceContext, CompilationResult unitResult) {
if (severity != ProblemSeverities.Ignore && DUMP_STACK) {
Thread.dumpStack();
}
- super.handle(
- problemId,
- problemArguments,
- messageArguments,
- severity,
- problemStartPosition,
- problemEndPosition,
- referenceContext,
- unitResult);
+ super.handle(problemId, problemArguments, messageArguments, severity, problemStartPosition, problemEndPosition,
+ referenceContext, unitResult);
+ }
+
+ // PR71076
+ public void javadocMissingParamTag(char[] name, int sourceStart, int sourceEnd, int modifiers) {
+ boolean reportIt = true;
+ String sName = new String(name);
+ if (sName.startsWith("ajc$"))
+ reportIt = false;
+ if (sName.equals("thisJoinPoint"))
+ reportIt = false;
+ if (sName.equals("thisJoinPointStaticPart"))
+ reportIt = false;
+ if (sName.equals("thisEnclosingJoinPointStaticPart"))
+ reportIt = false;
+ if (sName.equals("ajc_aroundClosure"))
+ reportIt = false;
+ if (reportIt)
+ super.javadocMissingParamTag(name, sourceStart, sourceEnd, modifiers);
+ }
+
+ public void abstractMethodInAbstractClass(SourceTypeBinding type, AbstractMethodDeclaration methodDecl) {
+
+ String abstractMethodName = new String(methodDecl.selector);
+ if (abstractMethodName.startsWith("ajc$pointcut")) {
+ // This will already have been reported, see: PointcutDeclaration.postParse()
+ return;
+ }
+ String[] arguments = new String[] { new String(type.sourceName()), abstractMethodName };
+ super.handle(IProblem.AbstractMethodInAbstractClass, arguments, arguments, methodDecl.sourceStart, methodDecl.sourceEnd,
+ this.referenceContext, this.referenceContext == null ? null : this.referenceContext.compilationResult());
}
-
-
-
- // PR71076
- public void javadocMissingParamTag(char[] name, int sourceStart, int sourceEnd, int modifiers) {
- boolean reportIt = true;
- String sName = new String(name);
- if (sName.startsWith("ajc$")) reportIt = false;
- if (sName.equals("thisJoinPoint")) reportIt = false;
- if (sName.equals("thisJoinPointStaticPart")) reportIt = false;
- if (sName.equals("thisEnclosingJoinPointStaticPart")) reportIt = false;
- if (sName.equals("ajc_aroundClosure")) reportIt = false;
- if (reportIt)
- super.javadocMissingParamTag(name,sourceStart,sourceEnd,modifiers);
- }
-
- public void abstractMethodInAbstractClass(SourceTypeBinding type, AbstractMethodDeclaration methodDecl) {
-
- String abstractMethodName = new String(methodDecl.selector);
- if (abstractMethodName.startsWith("ajc$pointcut")) {
- // This will already have been reported, see: PointcutDeclaration.postParse()
- return;
- }
- String[] arguments = new String[] {new String(type.sourceName()), abstractMethodName};
- super.handle(
- IProblem.AbstractMethodInAbstractClass,
- arguments,
- arguments,
- methodDecl.sourceStart,
- methodDecl.sourceEnd,this.referenceContext,
- this.referenceContext == null ? null : this.referenceContext.compilationResult());
- }
-
-
- /**
- * Called when there is an ITD marked @override that doesn't override a supertypes method.
- * The method and the binding are passed - some information is useful from each. The 'method'
- * knows about source offsets for the message, the 'binding' has the signature of what the
- * ITD is trying to be in the target class.
- */
- public void itdMethodMustOverride(AbstractMethodDeclaration method,MethodBinding binding) {
- this.handle(
- IProblem.MethodMustOverride,
- new String[] {new String(binding.selector), typesAsString(binding.isVarargs(), binding.parameters, false), new String(binding.declaringClass.readableName()), },
- new String[] {new String(binding.selector), typesAsString(binding.isVarargs(), binding.parameters, true), new String(binding.declaringClass.shortReadableName()),},
- method.sourceStart,
- method.sourceEnd,
- this.referenceContext,
- this.referenceContext == null ? null : this.referenceContext.compilationResult());
+
+ /**
+ * Called when there is an ITD marked @override that doesn't override a supertypes method. The method and the binding are passed
+ * - some information is useful from each. The 'method' knows about source offsets for the message, the 'binding' has the
+ * signature of what the ITD is trying to be in the target class.
+ */
+ public void itdMethodMustOverride(AbstractMethodDeclaration method, MethodBinding binding) {
+ this.handle(IProblem.MethodMustOverride,
+ new String[] { new String(binding.selector), typesAsString(binding.isVarargs(), binding.parameters, false),
+ new String(binding.declaringClass.readableName()), }, new String[] { new String(binding.selector),
+ typesAsString(binding.isVarargs(), binding.parameters, true),
+ new String(binding.declaringClass.shortReadableName()), }, method.sourceStart, method.sourceEnd,
+ this.referenceContext, this.referenceContext == null ? null : this.referenceContext.compilationResult());
}
-
- /**
- * Overrides the implementation in ProblemReporter and is ITD aware.
- * To report a *real* problem with an ITD marked @override, the other methodMustOverride() method is used.
- */
- public void methodMustOverride(AbstractMethodDeclaration method) {
- MethodBinding binding = method.binding;
-
- // ignore ajc$ methods
- if (new String(method.selector).startsWith("ajc$")) return;
+
+ /**
+ * Overrides the implementation in ProblemReporter and is ITD aware. To report a *real* problem with an ITD marked @override,
+ * the other methodMustOverride() method is used.
+ */
+ public void methodMustOverride(AbstractMethodDeclaration method) {
+ MethodBinding binding = method.binding;
+
+ // ignore ajc$ methods
+ if (new String(method.selector).startsWith("ajc$"))
+ return;
ResolvedMember possiblyErroneousRm = factory.makeResolvedMember(method.binding);
-
- ResolvedType onTypeX = factory.fromEclipse(method.binding.declaringClass);
- // Can't use 'getInterTypeMungersIncludingSupers()' since that will exclude abstract ITDs
- // on any super classes - so we have to trawl up ourselves.. I wonder if this problem
- // affects other code in the problem reporter that looks through ITDs...
- ResolvedType supertypeToLookAt = onTypeX.getSuperclass();
- while (supertypeToLookAt!=null) {
- List itMungers = supertypeToLookAt.getInterTypeMungers();
- for (Iterator i = itMungers.iterator(); i.hasNext(); ) {
- ConcreteTypeMunger m = (ConcreteTypeMunger)i.next();
+
+ ResolvedType onTypeX = factory.fromEclipse(method.binding.declaringClass);
+ // Can't use 'getInterTypeMungersIncludingSupers()' since that will exclude abstract ITDs
+ // on any super classes - so we have to trawl up ourselves.. I wonder if this problem
+ // affects other code in the problem reporter that looks through ITDs...
+ ResolvedType supertypeToLookAt = onTypeX.getSuperclass();
+ while (supertypeToLookAt != null) {
+ List itMungers = supertypeToLookAt.getInterTypeMungers();
+ for (Iterator i = itMungers.iterator(); i.hasNext();) {
+ ConcreteTypeMunger m = (ConcreteTypeMunger) i.next();
ResolvedMember sig = m.getSignature();
- if (sig==null) continue; // we aren't interested in other kinds of munger
+ if (sig == null)
+ continue; // we aren't interested in other kinds of munger
UnresolvedType dType = sig.getDeclaringType();
- if (dType==null) continue;
+ if (dType == null)
+ continue;
ResolvedType resolvedDeclaringType = dType.resolve(factory.getWorld());
- ResolvedMember rm = AjcMemberMaker.interMethod(sig,m.getAspectType(),
- resolvedDeclaringType.isInterface());
- if (ResolvedType.matches(rm,possiblyErroneousRm)) {
+ ResolvedMember rm = AjcMemberMaker.interMethod(sig, m.getAspectType(), resolvedDeclaringType.isInterface());
+ if (ResolvedType.matches(rm, possiblyErroneousRm)) {
// match, so dont need to report a problem!
return;
}
}
- supertypeToLookAt = supertypeToLookAt.getSuperclass();
- }
- // report the error...
- super.methodMustOverride(method);
- }
-
-
- private String typesAsString(boolean isVarargs, TypeBinding[] types, boolean makeShort) {
- StringBuffer buffer = new StringBuffer(10);
- for (int i = 0, length = types.length; i < length; i++) {
- if (i != 0)
- buffer.append(", "); //$NON-NLS-1$
- TypeBinding type = types[i];
- boolean isVarargType = isVarargs && i == length-1;
- if (isVarargType) type = ((ArrayBinding)type).elementsType();
- buffer.append(new String(makeShort ? type.shortReadableName() : type.readableName()));
- if (isVarargType) buffer.append("..."); //$NON-NLS-1$
- }
- return buffer.toString();
- }
-
- public void visibilityConflict(MethodBinding currentMethod, MethodBinding inheritedMethod) {
- // Not quite sure if the conditions on this test are right - basically I'm saying
- // DONT WORRY if its ITDs since the error will be reported another way...
- if (isIntertypeDeclaration(currentMethod) &&
- isIntertypeDeclaration(inheritedMethod) &&
- Modifier.isPrivate(currentMethod.modifiers) &&
- Modifier.isPrivate(inheritedMethod.modifiers)) {
- return;
- }
- super.visibilityConflict(currentMethod,inheritedMethod);
- }
-
- public void unusedPrivateType(TypeDeclaration typeDecl) {
- // don't output unused type warnings for aspects!
- if (typeDecl instanceof AspectDeclaration) return;
- if (typeDecl.enclosingType!=null && (typeDecl.enclosingType instanceof AspectDeclaration)) {
- AspectDeclaration ad = (AspectDeclaration)typeDecl.enclosingType;
- if (ad.concreteName!=null) {
- List declares = ad.concreteName.declares;
- for (Iterator iter = declares.iterator(); iter.hasNext();) {
- Object dec = iter.next();
+ supertypeToLookAt = supertypeToLookAt.getSuperclass();
+ }
+ // report the error...
+ super.methodMustOverride(method);
+ }
+
+ private String typesAsString(boolean isVarargs, TypeBinding[] types, boolean makeShort) {
+ StringBuffer buffer = new StringBuffer(10);
+ for (int i = 0, length = types.length; i < length; i++) {
+ if (i != 0)
+ buffer.append(", "); //$NON-NLS-1$
+ TypeBinding type = types[i];
+ boolean isVarargType = isVarargs && i == length - 1;
+ if (isVarargType)
+ type = ((ArrayBinding) type).elementsType();
+ buffer.append(new String(makeShort ? type.shortReadableName() : type.readableName()));
+ if (isVarargType)
+ buffer.append("..."); //$NON-NLS-1$
+ }
+ return buffer.toString();
+ }
+
+ public void visibilityConflict(MethodBinding currentMethod, MethodBinding inheritedMethod) {
+ // Not quite sure if the conditions on this test are right - basically I'm saying
+ // DONT WORRY if its ITDs since the error will be reported another way...
+ if (isIntertypeDeclaration(currentMethod) && isIntertypeDeclaration(inheritedMethod)
+ && Modifier.isPrivate(currentMethod.modifiers) && Modifier.isPrivate(inheritedMethod.modifiers)) {
+ return;
+ }
+ super.visibilityConflict(currentMethod, inheritedMethod);
+ }
+
+ public void unusedPrivateType(TypeDeclaration typeDecl) {
+ // don't output unused type warnings for aspects!
+ if (typeDecl instanceof AspectDeclaration)
+ return;
+ if (typeDecl.enclosingType != null && (typeDecl.enclosingType instanceof AspectDeclaration)) {
+ AspectDeclaration ad = (AspectDeclaration) typeDecl.enclosingType;
+ if (ad.concreteName != null) {
+ List declares = ad.concreteName.declares;
+ for (Iterator iter = declares.iterator(); iter.hasNext();) {
+ Object dec = iter.next();
if (dec instanceof DeclareParents) {
- DeclareParents decp = (DeclareParents)dec;
+ DeclareParents decp = (DeclareParents) dec;
TypePattern[] newparents = decp.getParents().getTypePatterns();
for (int i = 0; i < newparents.length; i++) {
TypePattern pattern = newparents[i];
UnresolvedType ut = pattern.getExactType();
- if (ut==null) continue;
- if (CharOperation.compareWith(typeDecl.binding.signature(),ut.getSignature().toCharArray())==0) return;
+ if (ut == null)
+ continue;
+ if (CharOperation.compareWith(typeDecl.binding.signature(), ut.getSignature().toCharArray()) == 0)
+ return;
}
}
}
- }
- }
- super.unusedPrivateType(typeDecl);
- }
-
- public void unusedPrivateMethod(AbstractMethodDeclaration methodDecl) {
- // don't output unused warnings for pointcuts...
- if (!(methodDecl instanceof PointcutDeclaration))
- super.unusedPrivateMethod(methodDecl);
- }
-
- public void caseExpressionMustBeConstant(Expression expression) {
- if (expression instanceof QualifiedNameReference) {
- QualifiedNameReference qnr = (QualifiedNameReference)expression;
- if (qnr.otherBindings!=null && qnr.otherBindings.length>0 && qnr.otherBindings[0] instanceof PrivilegedFieldBinding) {
- super.signalError(expression.sourceStart,expression.sourceEnd,"Fields accessible due to an aspect being privileged can not be used in switch statements");
- referenceContext.tagAsHavingErrors();
- return;
- }
- }
- super.caseExpressionMustBeConstant(expression);
- }
-
- public void unusedArgument(LocalDeclaration localDecl) {
- // don't warn if this is an aj synthetic arg
- String argType = new String(localDecl.type.resolvedType.signature());
- if (argType.startsWith("Lorg/aspectj/runtime/internal")) return;
-
- // If the unused argument is in a pointcut, don't report the problem (for now... pr148219)
- if (localDecl!=null && localDecl instanceof Argument) {
- Argument arg = (Argument)localDecl;
- if (arg.binding!=null && arg.binding.declaringScope!=null) {
- ReferenceContext context = arg.binding.declaringScope.referenceContext();
- if (context!=null && context instanceof PointcutDeclaration) return;
- }
- }
- super.unusedArgument(localDecl);
- }
-
- /**
- * A side-effect of the way that we handle itds on default methods on top-most implementors
- * of interfaces is that a class acquiring a final default ITD will erroneously report
- * that it can't override its own member. This method detects that situation.
- */
- public void finalMethodCannotBeOverridden(MethodBinding currentMethod, MethodBinding inheritedMethod) {
- if (currentMethod == inheritedMethod) return;
- super.finalMethodCannotBeOverridden(currentMethod, inheritedMethod);
- }
-
- /**
- * The method verifier is a bit 'keen' and doesn't cope well with ITDMs which are
- * of course to be considered a 'default' implementation if the target type doesn't
- * supply one. This test may not be complete - it is possible that it should read if
- * *either* is an ITD...but I dont have a testcase that shows that is required. yet.
- * (pr115788)
- */
- public void duplicateInheritedMethods(SourceTypeBinding type, MethodBinding inheritedMethod1, MethodBinding inheritedMethod2) {
- if (inheritedMethod1 instanceof InterTypeMethodBinding || inheritedMethod2 instanceof InterTypeMethodBinding) return;
- if ((inheritedMethod1 instanceof ParameterizedMethodBinding) && ((ParameterizedMethodBinding)inheritedMethod1).original() instanceof InterTypeMethodBinding) return;
- if ((inheritedMethod2 instanceof ParameterizedMethodBinding) && ((ParameterizedMethodBinding)inheritedMethod2).original() instanceof InterTypeMethodBinding) return;
- super.duplicateInheritedMethods(type,inheritedMethod1,inheritedMethod2);
- }
-
- /**
- * All problems end up routed through here at some point...
- */
- public IProblem createProblem(char[] fileName, int problemId, String[] problemArguments, String[] messageArguments, int severity, int problemStartPosition, int problemEndPosition, int lineNumber) {
- IProblem problem = super.createProblem(fileName, problemId, problemArguments,
- messageArguments, severity, problemStartPosition, problemEndPosition,
- lineNumber,0);
- if (factory.getWorld().isInPinpointMode()) {
- MessageIssued ex = new MessageIssued();
- ex.fillInStackTrace();
- StringWriter sw = new StringWriter();
- ex.printStackTrace(new PrintWriter(sw));
- StringBuffer sb = new StringBuffer();
- sb.append(CompilationAndWeavingContext.getCurrentContext());
- sb.append(sw.toString());
- problem = new PinpointedProblem(problem,sb.toString());
- }
- return problem;
- }
-
- private static class MessageIssued extends RuntimeException {
- public String getMessage() {
- return "message issued...";
- }
- }
-
- private static class PinpointedProblem implements IProblem {
-
- private IProblem delegate;
- private String message;
-
- public PinpointedProblem(IProblem aProblem, String pinpoint) {
- this.delegate = aProblem;
- // if this was a problem that came via the weaver, it will already have
- // pinpoint info, don't do it twice...
- if (delegate.getMessage().indexOf("message issued...") == -1) {
- this.message = delegate.getMessage() + "\n" + pinpoint;
- } else {
- this.message = delegate.getMessage();
- }
- }
-
- public String[] getArguments() {return delegate.getArguments();}
- public int getID() {return delegate.getID();}
- public String getMessage() { return message; }
- public char[] getOriginatingFileName() {return delegate.getOriginatingFileName();}
- public int getSourceEnd() { return delegate.getSourceEnd();}
- public int getSourceLineNumber() { return delegate.getSourceLineNumber();}
- public int getSourceStart() { return delegate.getSourceStart();}
- public boolean isError() { return delegate.isError();}
- public boolean isWarning() { return delegate.isWarning();}
- public void setSourceEnd(int sourceEnd) { delegate.setSourceEnd(sourceEnd); }
- public void setSourceLineNumber(int lineNumber) { delegate.setSourceLineNumber(lineNumber);}
- public void setSourceStart(int sourceStart) { delegate.setSourceStart(sourceStart);}
- public void setSeeAlsoProblems(IProblem[] problems) { delegate.setSeeAlsoProblems(problems);}
- public IProblem[] seeAlso() { return delegate.seeAlso();}
- public void setSupplementaryMessageInfo(String msg) { delegate.setSupplementaryMessageInfo(msg);}
- public String getSupplementaryMessageInfo() { return delegate.getSupplementaryMessageInfo();}
- }
-
- public void duplicateMethodInType(SourceTypeBinding type, AbstractMethodDeclaration methodDecl) {
- if (new String(methodDecl.selector).startsWith("ajc$interMethod")) {
- // this is an ITD clash and will be reported in another way by AspectJ (173602)
- return;
- }
- super.duplicateMethodInType(type, methodDecl);
- }
+ }
+ }
+ super.unusedPrivateType(typeDecl);
+ }
+
+ public void unusedPrivateMethod(AbstractMethodDeclaration methodDecl) {
+ // don't output unused warnings for pointcuts...
+ if (!(methodDecl instanceof PointcutDeclaration))
+ super.unusedPrivateMethod(methodDecl);
+ }
+
+ public void caseExpressionMustBeConstant(Expression expression) {
+ if (expression instanceof QualifiedNameReference) {
+ QualifiedNameReference qnr = (QualifiedNameReference) expression;
+ if (qnr.otherBindings != null && qnr.otherBindings.length > 0 && qnr.otherBindings[0] instanceof PrivilegedFieldBinding) {
+ super.signalError(expression.sourceStart, expression.sourceEnd,
+ "Fields accessible due to an aspect being privileged can not be used in switch statements");
+ referenceContext.tagAsHavingErrors();
+ return;
+ }
+ }
+ super.caseExpressionMustBeConstant(expression);
+ }
+
+ public void unusedArgument(LocalDeclaration localDecl) {
+ // don't warn if this is an aj synthetic arg
+ String argType = new String(localDecl.type.resolvedType.signature());
+ if (argType.startsWith("Lorg/aspectj/runtime/internal"))
+ return;
+
+ // If the unused argument is in a pointcut, don't report the problem (for now... pr148219)
+ if (localDecl instanceof Argument) {
+ Argument arg = (Argument) localDecl;
+ if (arg.binding != null && arg.binding.declaringScope != null) {
+ ReferenceContext context = arg.binding.declaringScope.referenceContext();
+ if (context != null && context instanceof PointcutDeclaration)
+ return;
+ }
+ }
+ super.unusedArgument(localDecl);
+ }
+
+ /**
+ * A side-effect of the way that we handle itds on default methods on top-most implementors of interfaces is that a class
+ * acquiring a final default ITD will erroneously report that it can't override its own member. This method detects that
+ * situation.
+ */
+ public void finalMethodCannotBeOverridden(MethodBinding currentMethod, MethodBinding inheritedMethod) {
+ if (currentMethod == inheritedMethod)
+ return;
+ super.finalMethodCannotBeOverridden(currentMethod, inheritedMethod);
+ }
+
+ /**
+ * The method verifier is a bit 'keen' and doesn't cope well with ITDMs which are of course to be considered a 'default'
+ * implementation if the target type doesn't supply one. This test may not be complete - it is possible that it should read if
+ * *either* is an ITD...but I dont have a testcase that shows that is required. yet. (pr115788)
+ */
+ public void duplicateInheritedMethods(SourceTypeBinding type, MethodBinding inheritedMethod1, MethodBinding inheritedMethod2) {
+ if (inheritedMethod1 instanceof InterTypeMethodBinding || inheritedMethod2 instanceof InterTypeMethodBinding)
+ return;
+ if ((inheritedMethod1 instanceof ParameterizedMethodBinding)
+ && ((ParameterizedMethodBinding) inheritedMethod1).original() instanceof InterTypeMethodBinding)
+ return;
+ if ((inheritedMethod2 instanceof ParameterizedMethodBinding)
+ && ((ParameterizedMethodBinding) inheritedMethod2).original() instanceof InterTypeMethodBinding)
+ return;
+ super.duplicateInheritedMethods(type, inheritedMethod1, inheritedMethod2);
+ }
+
+ /**
+ * All problems end up routed through here at some point...
+ */
+ public IProblem createProblem(char[] fileName, int problemId, String[] problemArguments, String[] messageArguments,
+ int severity, int problemStartPosition, int problemEndPosition, int lineNumber) {
+ IProblem problem = super.createProblem(fileName, problemId, problemArguments, messageArguments, severity,
+ problemStartPosition, problemEndPosition, lineNumber, 0);
+ if (factory.getWorld().isInPinpointMode()) {
+ MessageIssued ex = new MessageIssued();
+ ex.fillInStackTrace();
+ StringWriter sw = new StringWriter();
+ ex.printStackTrace(new PrintWriter(sw));
+ StringBuffer sb = new StringBuffer();
+ sb.append(CompilationAndWeavingContext.getCurrentContext());
+ sb.append(sw.toString());
+ problem = new PinpointedProblem(problem, sb.toString());
+ }
+ return problem;
+ }
+
+ private static class MessageIssued extends RuntimeException {
+ public String getMessage() {
+ return "message issued...";
+ }
+ }
+
+ private static class PinpointedProblem implements IProblem {
+
+ private IProblem delegate;
+ private String message;
+
+ public PinpointedProblem(IProblem aProblem, String pinpoint) {
+ this.delegate = aProblem;
+ // if this was a problem that came via the weaver, it will already have
+ // pinpoint info, don't do it twice...
+ if (delegate.getMessage().indexOf("message issued...") == -1) {
+ this.message = delegate.getMessage() + "\n" + pinpoint;
+ } else {
+ this.message = delegate.getMessage();
+ }
+ }
+
+ public String[] getArguments() {
+ return delegate.getArguments();
+ }
+
+ public int getID() {
+ return delegate.getID();
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public char[] getOriginatingFileName() {
+ return delegate.getOriginatingFileName();
+ }
+
+ public int getSourceEnd() {
+ return delegate.getSourceEnd();
+ }
+
+ public int getSourceLineNumber() {
+ return delegate.getSourceLineNumber();
+ }
+
+ public int getSourceStart() {
+ return delegate.getSourceStart();
+ }
+
+ public boolean isError() {
+ return delegate.isError();
+ }
+
+ public boolean isWarning() {
+ return delegate.isWarning();
+ }
+
+ public void setSourceEnd(int sourceEnd) {
+ delegate.setSourceEnd(sourceEnd);
+ }
+ public void setSourceLineNumber(int lineNumber) {
+ delegate.setSourceLineNumber(lineNumber);
+ }
+
+ public void setSourceStart(int sourceStart) {
+ delegate.setSourceStart(sourceStart);
+ }
+
+ public void setSeeAlsoProblems(IProblem[] problems) {
+ delegate.setSeeAlsoProblems(problems);
+ }
+
+ public IProblem[] seeAlso() {
+ return delegate.seeAlso();
+ }
+
+ public void setSupplementaryMessageInfo(String msg) {
+ delegate.setSupplementaryMessageInfo(msg);
+ }
+
+ public String getSupplementaryMessageInfo() {
+ return delegate.getSupplementaryMessageInfo();
+ }
+ }
+
+ public void duplicateMethodInType(SourceTypeBinding type, AbstractMethodDeclaration methodDecl) {
+ if (new String(methodDecl.selector).startsWith("ajc$interMethod")) {
+ // this is an ITD clash and will be reported in another way by AspectJ (173602)
+ return;
+ }
+ super.duplicateMethodInType(type, methodDecl);
+ }
}
diff --git a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjState.java b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjState.java
index 849e676ab..8614ed3ad 100644
--- a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjState.java
+++ b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjState.java
@@ -10,7 +10,6 @@
* PARC initial implementation
* ******************************************************************/
-
package org.aspectj.ajdt.internal.core.builder;
import java.io.File;
@@ -54,59 +53,56 @@ import org.aspectj.weaver.bcel.BcelWeaver;
import org.aspectj.weaver.bcel.BcelWorld;
import org.aspectj.weaver.bcel.UnwovenClassFile;
-
/**
* Maintains state needed for incremental compilation
*
- * tests: two ajdt projects, aspect is changed in dependent, does dependee do a full build? (could just do it if on
- * aspect path but lets just do it for all now)
+ * tests: two ajdt projects, aspect is changed in dependent, does dependee do a full build? (could just do it if on aspect path but
+ * lets just do it for all now)
*
*/
public class AjState {
-
- // SECRETAPI static so beware of multi-threading bugs...
- public static IStateListener stateListener = null;
- public static boolean FORCE_INCREMENTAL_DURING_TESTING = false;
+ // SECRETAPI static so beware of multi-threading bugs...
+ public static IStateListener stateListener = null;
+
+ public static boolean FORCE_INCREMENTAL_DURING_TESTING = false;
- // if set to true we will not do a full build if we see a type changed on our classpath
- // but no type in this state instance references it
- public static boolean IGNORE_NON_REFERENCED_TYPES = true;
+ // if set to true we will not do a full build if we see a type changed on our classpath
+ // but no type in this state instance references it
+ public static boolean IGNORE_NON_REFERENCED_TYPES = true;
- private AjBuildManager buildManager;
+ private AjBuildManager buildManager;
private boolean couldBeSubsequentIncrementalBuild = false;
-
+
private IHierarchy structureModel;
private IRelationshipMap relmap;
-
+
/**
- * When looking at changes on the classpath, this set accumulates files in our state instance that affected by those
- * changes. Then if we can do an incremental build - these must be compiled.
- */
- private Set affectedFiles = new HashSet();
-
+ * When looking at changes on the classpath, this set accumulates files in our state instance that affected by those changes.
+ * Then if we can do an incremental build - these must be compiled.
+ */
+ private Set affectedFiles = new HashSet();
+
private long lastSuccessfulFullBuildTime = -1;
- private Hashtable /* File, long */ structuralChangesSinceLastFullBuild = new Hashtable();
-
+ 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.
+ * 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();
-
+ private Map/* <File, List<ClassFile> */fullyQualifiedTypeNamesResultingFromCompilationUnit = new HashMap();
+
/**
* Source files defining aspects
*
@@ -114,108 +110,101 @@ public class AjState {
*
* Added by AMC during state refactoring, 1Q06.
*/
- private Set/*<File>*/ sourceFilesDefiningAspects = new HashSet();
-
+ 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.
+ * 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();
-
+ 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.
+ * 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.
+ * 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 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.
+ * 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();
+ 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.
+ * 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();
-
+ 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.
+ * 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();
-
+ 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.
+ * 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.
+ *
+ * Passed into StatefulNameEnvironment during incremental compilation to support findType lookups.
*/
- private Map/*<String, File>*/ classesFromName = new HashMap();
-
+ private Map/* <String, File> */classesFromName = new HashMap();
+
/**
- * Populated by AjBuildManager to record the aspects with the file name in which they're
- * contained. This is later used when writing the outxml file in AjBuildManager. Need
- * to record the file name because want to write an outxml file for each of the output
- * directories and in order to ask the OutputLocationManager for the output location
- * for a given aspect we need the file in which it is contained.
+ * Populated by AjBuildManager to record the aspects with the file name in which they're contained. This is later used when
+ * writing the outxml file in AjBuildManager. Need to record the file name because want to write an outxml file for each of the
+ * output directories and in order to ask the OutputLocationManager for the output location for a given aspect we need the file
+ * in which it is contained.
*/
- private Map /*<String, char[]>*/ aspectsFromFileNames;
-
+ private Map /* <String, char[]> */aspectsFromFileNames;
+
private Set/* File */compiledSourceFiles = new HashSet();
- private List/*String*/ resources = new ArrayList();
-
- // these are references created on a particular compile run - when looping round in
+ private List/* String */resources = new ArrayList();
+
+ // these are references created on a particular compile run - when looping round in
// addAffectedSourceFiles(), if some have been created then we look at which source files
// touch upon those and get them recompiled.
private StringSet qualifiedStrings = new StringSet(3);
- private StringSet simpleStrings = new StringSet(3);
-
+ private StringSet simpleStrings = new StringSet(3);
+
private Set addedFiles;
private Set deletedFiles;
- private Set /*BinarySourceFile*/addedBinaryFiles;
- private Set /*BinarySourceFile*/deletedBinaryFiles;
-
+ 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) {
+
+ void successfulCompile(AjBuildConfig config, boolean wasFullBuild) {
buildConfig = config;
lastSuccessfulBuildTime = currentBuildTime;
- if (stateListener!=null) stateListener.buildSuccessful(wasFullBuild);
- if (wasFullBuild) lastSuccessfulFullBuildTime = currentBuildTime;
+ if (stateListener != null)
+ stateListener.buildSuccessful(wasFullBuild);
+ if (wasFullBuild)
+ lastSuccessfulFullBuildTime = currentBuildTime;
}
-
+
/**
* Returns false if a batch build is needed.
*/
@@ -223,461 +212,485 @@ public class AjState {
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");
+ 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");
+ 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");
+ 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");
+ if (listenerDefined())
+ getListener().recordDecision("Preparing for build: not going to be incremental because outjar being used");
return false;
}
-
- affectedFiles.clear();
-
+
+ affectedFiles.clear();
+
// 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();
+ 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;
+ if (listenerDefined())
+ getListener()
+ .recordDecision(
+ "Preparing for build: not going to be incremental because path change detected (one of classpath/aspectpath/inpath/injars)");
+ return false;
}
-
+
if (simpleStrings.elementSize > 20)
- simpleStrings = new StringSet(3);
- else
- simpleStrings.clear();
- if (qualifiedStrings.elementSize > 20)
- qualifiedStrings = new StringSet(3);
- else
- qualifiedStrings.clear();
-
+ simpleStrings = new StringSet(3);
+ else
+ simpleStrings.clear();
+ if (qualifiedStrings.elementSize > 20)
+ qualifiedStrings = new StringSet(3);
+ else
+ qualifiedStrings.clear();
+
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");
+ 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");
+
+ 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.
+ * 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) {
+ private boolean processDeletedFiles(Set deletedFiles) {
for (Iterator iter = deletedFiles.iterator(); iter.hasNext();) {
- File aDeletedFile = (File ) iter.next();
+ File aDeletedFile = (File) iter.next();
if (this.sourceFilesDefiningAspects.contains(aDeletedFile)) {
removeAllResultsOfLastBuild();
- if (stateListener!=null) stateListener.detectedAspectDeleted(aDeletedFile);
- return false;
+ if (stateListener != null)
+ stateListener.detectedAspectDeleted(aDeletedFile);
+ return false;
}
- List/*ClassFile*/ classes = (List)fullyQualifiedTypeNamesResultingFromCompilationUnit.get(aDeletedFile);
- if (classes!=null) {
+ List/* ClassFile */classes = (List) fullyQualifiedTypeNamesResultingFromCompilationUnit.get(aDeletedFile);
+ if (classes != null) {
for (Iterator iterator = classes.iterator(); iterator.hasNext();) {
ClassFile element = (ClassFile) iterator.next();
resolvedTypeStructuresFromLastBuild.remove(element.fullyQualifiedTypeName);
}
- }
+ }
}
return true;
- }
-
- private Collection getModifiedFiles() {
+ }
+
+ private Collection getModifiedFiles() {
return getModifiedFiles(lastSuccessfulBuildTime);
}
Collection getModifiedFiles(long lastBuildTime) {
Set ret = new HashSet();
- //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;
-
+ // 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);
+ // 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);
- }
+ }
}
ret.addAll(affectedFiles);
return ret;
}
- private Collection getModifiedBinaryFiles() {
+ 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();
+ // 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;
-
+ if (!file.exists())
+ continue;
+
long modTime = file.lastModified();
- //System.out.println("check: " + file + " mod " + modTime + " build " + lastBuildTime);
+ // 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 static int CLASS_FILE_NO_CHANGES = 0;
- private static int CLASS_FILE_CHANGED_THAT_NEEDS_INCREMENTAL_BUILD = 1;
+ private static int CLASS_FILE_CHANGED_THAT_NEEDS_INCREMENTAL_BUILD = 1;
+
+ private static int CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD = 2;
- private static int CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD = 2;
+ private static int MAX_AFFECTED_FILES_BEFORE_FULL_BUILD = 30;
- private static int MAX_AFFECTED_FILES_BEFORE_FULL_BUILD = 30;
-
/**
- * Analyse .class files in the directory specified, if they have changed since the last successful build then see if
- * we can determine which source files in our project depend on the change. If we can then we can still do an
- * incremental build, if we can't then we have to do a full build.
- *
- */
+ * Analyse .class files in the directory specified, if they have changed since the last successful build then see if we can
+ * determine which source files in our project depend on the change. If we can then we can still do an incremental build, if we
+ * can't then we have to do a full build.
+ *
+ */
private int classFileChangedInDirSinceLastBuildRequiringFullBuild(File dir) {
- int defaultReply = (IGNORE_NON_REFERENCED_TYPES ? CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD : CLASS_FILE_CHANGED_THAT_NEEDS_INCREMENTAL_BUILD);
+ int defaultReply = (IGNORE_NON_REFERENCED_TYPES ? CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD
+ : CLASS_FILE_CHANGED_THAT_NEEDS_INCREMENTAL_BUILD);
// Is another AspectJ project building into that directory?
AjState state = IncrementalStateManager.findStateManagingOutputLocation(dir);
if (listenerDefined()) {
- if (state != null) {
- getListener().recordDecision("Found state instance managing output location : " + dir);
- } else {
- getListener().recordDecision("Failed to find a state instance managing output location : " + dir);
- }
- }
+ if (state != null) {
+ getListener().recordDecision("Found state instance managing output location : " + dir);
+ } else {
+ getListener().recordDecision("Failed to find a state instance managing output location : " + 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) {
+ 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) {
- if (state.isAspect(classFiles[i])) {
- return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
- }
- if (state.hasStructuralChangedSince(classFiles[i], lastSuccessfulBuildTime)) {
- if (listenerDefined())
- getListener().recordDecision("Structural change detected in : " + classFiles[i]);
-
- if (!IGNORE_NON_REFERENCED_TYPES || isTypeWeReferTo(classFiles[i])) {
- if (affectedFiles.size() > MAX_AFFECTED_FILES_BEFORE_FULL_BUILD)
- return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
- }
- } else {
- if (listenerDefined())
- getListener().recordDecision("Change detected in " + classFiles[i] + " but it is not structural");
- }
- // Is the change in a type that any of our source files care about? and if it is, is it
- // a structural change?
- // if (!IGNORE_NON_REFERENCED_TYPES || isTypeWeReferTo(classFiles[i])) {
- // if (affectedFiles.size() > MAX_AFFECTED_FILES_BEFORE_FULL_BUILD)
- // return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
- // if (state.hasStructuralChangedSince(classFiles[i], lastSuccessfulBuildTime))
- // return defaultReply;
- // }
- } else {
- // No state object to ask, so it only matters if we know which type depends on this file
- if (!IGNORE_NON_REFERENCED_TYPES) {
- return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
- } else {
- if (isTypeWeReferTo(classFiles[i])) {
- if (affectedFiles.size() > MAX_AFFECTED_FILES_BEFORE_FULL_BUILD)
- return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
- return CLASS_FILE_CHANGED_THAT_NEEDS_INCREMENTAL_BUILD;
- } else {
- return CLASS_FILE_NO_CHANGES;
- }
- }
- }
+ if (state != null) {
+ if (state.isAspect(classFiles[i])) {
+ return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
+ }
+ if (state.hasStructuralChangedSince(classFiles[i], lastSuccessfulBuildTime)) {
+ if (listenerDefined())
+ getListener().recordDecision("Structural change detected in : " + classFiles[i]);
+
+ if (!IGNORE_NON_REFERENCED_TYPES || isTypeWeReferTo(classFiles[i])) {
+ if (affectedFiles.size() > MAX_AFFECTED_FILES_BEFORE_FULL_BUILD)
+ return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
+ }
+ } else {
+ if (listenerDefined())
+ getListener().recordDecision("Change detected in " + classFiles[i] + " but it is not structural");
+ }
+ // Is the change in a type that any of our source files care about? and if it is, is it
+ // a structural change?
+ // if (!IGNORE_NON_REFERENCED_TYPES || isTypeWeReferTo(classFiles[i])) {
+ // if (affectedFiles.size() > MAX_AFFECTED_FILES_BEFORE_FULL_BUILD)
+ // return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
+ // if (state.hasStructuralChangedSince(classFiles[i], lastSuccessfulBuildTime))
+ // return defaultReply;
+ // }
+ } else {
+ // No state object to ask, so it only matters if we know which type depends on this file
+ if (!IGNORE_NON_REFERENCED_TYPES) {
+ return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
+ } else {
+ if (isTypeWeReferTo(classFiles[i])) {
+ if (affectedFiles.size() > MAX_AFFECTED_FILES_BEFORE_FULL_BUILD)
+ return CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD;
+ return CLASS_FILE_CHANGED_THAT_NEEDS_INCREMENTAL_BUILD;
+ } else {
+ return CLASS_FILE_NO_CHANGES;
+ }
+ }
+ }
}
}
return CLASS_FILE_NO_CHANGES;
}
-
+
private boolean isAspect(File file) {
- if (aspectsFromFileNames == null)
- return false;
- return aspectsFromFileNames.containsKey(file);
- }
-
- public static class SoftHashMap extends AbstractMap {
-
- private Map map;
-
- private ReferenceQueue rq = new ReferenceQueue();
-
- public SoftHashMap(Map map) {
- this.map = map;
- }
-
- public SoftHashMap() {
- this(new HashMap());
- }
-
- public SoftHashMap(Map map, boolean b) {
- this(map);
- }
-
- class SoftReferenceKnownKey extends SoftReference {
-
- private final Object key;
-
- SoftReferenceKnownKey(Object k, Object v) {
- super(v, rq);
- this.key = k;
- }
- }
-
- private void processQueue() {
- SoftReferenceKnownKey sv = null;
- while ((sv = (SoftReferenceKnownKey) rq.poll()) != null) {
- map.remove(sv.key);
- }
- }
-
- public Object get(Object key) {
- SoftReferenceKnownKey value = (SoftReferenceKnownKey) map.get(key);
- if (value == null)
- return null;
- if (value.get() == null) {
- // it got GC'd
- map.remove(value.key);
- return null;
- } else {
- return value.get();
- }
- }
-
- public Object put(Object k, Object v) {
- processQueue();
- return map.put(k, new SoftReferenceKnownKey(k, v));
- }
-
- public Set entrySet() {
- return map.entrySet();
- }
-
- public void clear() {
- processQueue();
- map.clear();
- }
-
- public int size() {
- processQueue();
- return map.size();
- }
-
- public Object remove(Object k) {
- processQueue();
- SoftReferenceKnownKey value = (SoftReferenceKnownKey) map.remove(k);
- if (value == null)
- return null;
- if (value.get() != null) {
- return value.get();
- }
- return null;
- }
- }
-
+ if (aspectsFromFileNames == null)
+ return false;
+ return aspectsFromFileNames.containsKey(file);
+ }
+
+ public static class SoftHashMap extends AbstractMap {
+
+ private Map map;
+
+ private ReferenceQueue rq = new ReferenceQueue();
+
+ public SoftHashMap(Map map) {
+ this.map = map;
+ }
+
+ public SoftHashMap() {
+ this(new HashMap());
+ }
+
+ public SoftHashMap(Map map, boolean b) {
+ this(map);
+ }
+
+ class SoftReferenceKnownKey extends SoftReference {
+
+ private final Object key;
+
+ SoftReferenceKnownKey(Object k, Object v) {
+ super(v, rq);
+ this.key = k;
+ }
+ }
+
+ private void processQueue() {
+ SoftReferenceKnownKey sv = null;
+ while ((sv = (SoftReferenceKnownKey) rq.poll()) != null) {
+ map.remove(sv.key);
+ }
+ }
+
+ public Object get(Object key) {
+ SoftReferenceKnownKey value = (SoftReferenceKnownKey) map.get(key);
+ if (value == null)
+ return null;
+ if (value.get() == null) {
+ // it got GC'd
+ map.remove(value.key);
+ return null;
+ } else {
+ return value.get();
+ }
+ }
+
+ public Object put(Object k, Object v) {
+ processQueue();
+ return map.put(k, new SoftReferenceKnownKey(k, v));
+ }
+
+ public Set entrySet() {
+ return map.entrySet();
+ }
+
+ public void clear() {
+ processQueue();
+ map.clear();
+ }
+
+ public int size() {
+ processQueue();
+ return map.size();
+ }
+
+ public Object remove(Object k) {
+ processQueue();
+ SoftReferenceKnownKey value = (SoftReferenceKnownKey) map.remove(k);
+ if (value == null)
+ return null;
+ if (value.get() != null) {
+ return value.get();
+ }
+ return null;
+ }
+ }
+
SoftHashMap/* <baseDir,SoftHashMap<theFile,className>> */fileToClassNameMap = new SoftHashMap();
/**
- * If a class file has changed in a path on our classpath, it may not be for a type that any of our source files
- * care about. This method checks if any of our source files have a dependency on the class in question and if not,
- * we don't consider it an interesting change.
- */
+ * If a class file has changed in a path on our classpath, it may not be for a type that any of our source files care about.
+ * This method checks if any of our source files have a dependency on the class in question and if not, we don't consider it an
+ * interesting change.
+ */
private boolean isTypeWeReferTo(File file) {
- String fpath = file.getAbsolutePath();
- int finalSeparator = fpath.lastIndexOf(File.separator);
- String baseDir = fpath.substring(0, finalSeparator);
- String theFile = fpath.substring(finalSeparator + 1);
- SoftHashMap classNames = (SoftHashMap) fileToClassNameMap.get(baseDir);
- if (classNames == null) {
- classNames = new SoftHashMap();
- fileToClassNameMap.put(baseDir, classNames);
- }
- char[] className = (char[]) classNames.get(theFile);
- if (className == null) {
-// if (listenerDefined())
-// getListener().recordDecision("Cache miss, looking up classname for : " + fpath);
-
- ClassFileReader cfr;
- try {
- cfr = ClassFileReader.read(file);
- } catch (ClassFormatException e) {
- return true;
- } catch (IOException e) {
- return true;
- }
- className = cfr.getName();
- classNames.put(theFile, className);
-// } else {
-// if (listenerDefined())
-// getListener().recordDecision("Cache hit, looking up classname for : " + fpath);
- }
-
- char[][][] qualifiedNames = null;
- char[][] simpleNames = null;
- if (CharOperation.indexOf('/', className) != -1) {
- qualifiedNames = new char[1][][];
- qualifiedNames[0] = CharOperation.splitOn('/', className);
- qualifiedNames = ReferenceCollection.internQualifiedNames(qualifiedNames);
- } else {
- simpleNames = new char[1][];
- simpleNames[0] = className;
- simpleNames = ReferenceCollection.internSimpleNames(simpleNames, true);
- }
-
- 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)) {
- if (listenerDefined()) {
- getListener().recordDecision(
- toString() + ": type " + new String(className) + " is depended upon by '" + entry.getKey() + "'");
- }
- affectedFiles.add(entry.getKey());
- if (affectedFiles.size() > MAX_AFFECTED_FILES_BEFORE_FULL_BUILD)
- return true;
- // return true;
- }
- }
- if (affectedFiles.size() > 0)
- return true;
- if (listenerDefined())
- getListener().recordDecision(
- toString() + ": type " + new String(className) + " is not depended upon by this state");
-
- return false;
- }
-
+ String fpath = file.getAbsolutePath();
+ int finalSeparator = fpath.lastIndexOf(File.separator);
+ String baseDir = fpath.substring(0, finalSeparator);
+ String theFile = fpath.substring(finalSeparator + 1);
+ SoftHashMap classNames = (SoftHashMap) fileToClassNameMap.get(baseDir);
+ if (classNames == null) {
+ classNames = new SoftHashMap();
+ fileToClassNameMap.put(baseDir, classNames);
+ }
+ char[] className = (char[]) classNames.get(theFile);
+ if (className == null) {
+ // if (listenerDefined())
+ // getListener().recordDecision("Cache miss, looking up classname for : " + fpath);
+
+ ClassFileReader cfr;
+ try {
+ cfr = ClassFileReader.read(file);
+ } catch (ClassFormatException e) {
+ return true;
+ } catch (IOException e) {
+ return true;
+ }
+ className = cfr.getName();
+ classNames.put(theFile, className);
+ // } else {
+ // if (listenerDefined())
+ // getListener().recordDecision("Cache hit, looking up classname for : " + fpath);
+ }
+
+ char[][][] qualifiedNames = null;
+ char[][] simpleNames = null;
+ if (CharOperation.indexOf('/', className) != -1) {
+ qualifiedNames = new char[1][][];
+ qualifiedNames[0] = CharOperation.splitOn('/', className);
+ qualifiedNames = ReferenceCollection.internQualifiedNames(qualifiedNames);
+ } else {
+ simpleNames = new char[1][];
+ simpleNames[0] = className;
+ simpleNames = ReferenceCollection.internSimpleNames(simpleNames, true);
+ }
+
+ 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)) {
+ if (listenerDefined()) {
+ getListener().recordDecision(
+ toString() + ": type " + new String(className) + " is depended upon by '" + entry.getKey() + "'");
+ }
+ affectedFiles.add(entry.getKey());
+ if (affectedFiles.size() > MAX_AFFECTED_FILES_BEFORE_FULL_BUILD)
+ return true;
+ // return true;
+ }
+ }
+ if (affectedFiles.size() > 0)
+ return true;
+ if (listenerDefined())
+ getListener().recordDecision(toString() + ": type " + new String(className) + " is not depended upon by this state");
+
+ return false;
+ }
+
/**
- * For a given class file, determine which source file it came from. This will only succeed if the class file is
- * from a source file within this project.
- */
+ * For a given class file, determine which source file it came from. This will only succeed if the class file is from a source
+ * file within this project.
+ */
private File getSourceFileForClassFile(File classfile) {
- Set sourceFiles = fullyQualifiedTypeNamesResultingFromCompilationUnit.keySet();
- for (Iterator sourceFileIterator = sourceFiles.iterator(); sourceFileIterator.hasNext();) {
- File sourceFile = (File) sourceFileIterator.next();
- List/* ClassFile */ classesFromSourceFile = (List/* ClassFile */) fullyQualifiedTypeNamesResultingFromCompilationUnit.get(sourceFile);
- for (int i=0;i<classesFromSourceFile.size();i++) {
- if (((ClassFile)classesFromSourceFile.get(i)).locationOnDisk.equals(classfile)) return sourceFile;
- }
- }
- return null;
- }
-
+ Set sourceFiles = fullyQualifiedTypeNamesResultingFromCompilationUnit.keySet();
+ for (Iterator sourceFileIterator = sourceFiles.iterator(); sourceFileIterator.hasNext();) {
+ File sourceFile = (File) sourceFileIterator.next();
+ List/* ClassFile */classesFromSourceFile = (List/* ClassFile */) fullyQualifiedTypeNamesResultingFromCompilationUnit
+ .get(sourceFile);
+ for (int i = 0; i < classesFromSourceFile.size(); i++) {
+ if (((ClassFile) classesFromSourceFile.get(i)).locationOnDisk.equals(classfile))
+ return sourceFile;
+ }
+ }
+ return null;
+ }
+
public String toString() {
- StringBuffer sb = new StringBuffer();
- // null config means failed build i think as it is only set on successful full build?
- sb.append("AjState(").append((buildConfig == null ? "NULLCONFIG" : buildConfig.getConfigFile().toString())).append(")");
- return sb.toString();
- }
-
- /**
- * 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());
+ StringBuffer sb = new StringBuffer();
+ // null config means failed build i think as it is only set on successful full build?
+ sb.append("AjState(").append((buildConfig == null ? "NULLCONFIG" : buildConfig.getConfigFile().toString())).append(")");
+ return sb.toString();
+ }
+
+ /**
+ * 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;
+ 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);
+ return (strucModTime > lastSuccessfulBuildTime);
}
private boolean pathChange(AjBuildConfig oldConfig, AjBuildConfig newConfig) {
boolean changed = false;
-
+
List oldOutputLocs = getOutputLocations(oldConfig);
-
+
List oldClasspath = oldConfig.getClasspath();
List newClasspath = newConfig.getClasspath();
- if (stateListener!=null) stateListener.aboutToCompareClasspaths(oldClasspath,newClasspath);
- if (changedAndNeedsFullBuild(oldClasspath,newClasspath,true,oldOutputLocs)) return true;
+ if (stateListener != null)
+ stateListener.aboutToCompareClasspaths(oldClasspath, newClasspath);
+ if (changedAndNeedsFullBuild(oldClasspath, newClasspath, true, oldOutputLocs))
+ return true;
List oldAspectpath = oldConfig.getAspectpath();
List newAspectpath = newConfig.getAspectpath();
- if (changedAndNeedsFullBuild(oldAspectpath,newAspectpath,true,oldOutputLocs)) return true;
+ if (changedAndNeedsFullBuild(oldAspectpath, newAspectpath, true, oldOutputLocs))
+ return true;
List oldInJars = oldConfig.getInJars();
List newInJars = newConfig.getInJars();
- if (changedAndNeedsFullBuild(oldInJars,newInJars,false,oldOutputLocs)) return true;
+ if (changedAndNeedsFullBuild(oldInJars, newInJars, false, oldOutputLocs))
+ return true;
List oldInPath = oldConfig.getInpath();
List newInPath = newConfig.getInpath();
- if (changedAndNeedsFullBuild(oldInPath, newInPath,false,oldOutputLocs)) return true;
+ if (changedAndNeedsFullBuild(oldInPath, newInPath, false, oldOutputLocs))
+ return true;
return changed;
}
-
- private List /*File*/ getOutputLocations(AjBuildConfig config) {
+
+ private List /* File */getOutputLocations(AjBuildConfig config) {
List outputLocs = new ArrayList();
if (config.getOutputDir() != null) {
try {
outputLocs.add(config.getOutputDir().getCanonicalFile());
- } catch (IOException e) {}
+ } catch (IOException e) {
+ }
}
if (config.getCompilationResultDestinationManager() != null) {
List dirs = config.getCompilationResultDestinationManager().getAllOutputLocations();
@@ -687,16 +700,19 @@ public class AjState {
if (!outputLocs.contains(f.getCanonicalFile())) {
outputLocs.add(f.getCanonicalFile());
}
-
- } catch (IOException e) {}
+
+ } catch (IOException e) {
+ }
}
}
return outputLocs;
}
-
- private boolean changedAndNeedsFullBuild(List oldPath, List newPath, boolean checkClassFiles, List outputLocs) {
- if (oldPath == null) oldPath = new ArrayList();
- if (newPath == null) newPath = new ArrayList();
+
+ private boolean changedAndNeedsFullBuild(List oldPath, List newPath, boolean checkClassFiles, List outputLocs) {
+ if (oldPath == null)
+ oldPath = new ArrayList();
+ if (newPath == null)
+ newPath = new ArrayList();
if (oldPath.size() != newPath.size()) {
return true;
}
@@ -705,10 +721,10 @@ public class AjState {
if (!oldPath.get(i).equals(newPath.get(i))) {
return true;
}
- Object o = oldPath.get(i); // String on classpath, File on other paths
+ Object o = oldPath.get(i); // String on classpath, File on other paths
File f = null;
if (o instanceof String) {
- f = new File((String)o);
+ f = new File((String) o);
} else {
f = (File) o;
}
@@ -717,21 +733,20 @@ public class AjState {
}
if (f.exists() && f.isDirectory() && checkClassFiles) {
boolean foundMatch = false;
- for (Iterator iterator = outputLocs.iterator(); iterator
- .hasNext();) {
+ for (Iterator iterator = outputLocs.iterator(); iterator.hasNext();) {
File dir = (File) iterator.next();
if (f.equals(dir)) {
foundMatch = true;
}
}
if (!foundMatch) {
- if (!analysedPaths.contains(f.getAbsolutePath())) { // Do not check paths more than once
- analysedPaths.add(f.getAbsolutePath());
- int classFileChanges = classFileChangedInDirSinceLastBuildRequiringFullBuild(f);
- if (classFileChanges == CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD)
- return true;
- // if (b && stateListener!=null) stateListener.detectedClassChangeInThisDir(f);
- }
+ if (!analysedPaths.contains(f.getAbsolutePath())) { // Do not check paths more than once
+ analysedPaths.add(f.getAbsolutePath());
+ int classFileChanges = classFileChangedInDirSinceLastBuildRequiringFullBuild(f);
+ if (classFileChanges == CLASS_FILE_CHANGED_THAT_NEEDS_FULL_BUILD)
+ return true;
+ // if (b && stateListener!=null) stateListener.detectedClassChangeInThisDir(f);
+ }
}
}
}
@@ -743,33 +758,33 @@ public class AjState {
if (firstPass) {
compiledSourceFiles = new HashSet();
Collection modifiedFiles = getModifiedFiles();
- //System.out.println("modified: " + modifiedFiles);
+ // 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);
- // }
-
- if(addedFiles != null) {
- for (Iterator fIter = addedFiles.iterator(); fIter.hasNext();) {
- Object o = fIter.next();
- if (!thisTime.contains(o))
- thisTime.add(o);
- }
- // thisTime.addAll(addedFiles);
- }
-
+ // ??? eclipse IncrementalImageBuilder appears to do this
+ // for (Iterator i = modifiedFiles.iterator(); i.hasNext();) {
+ // File file = (File) i.next();
+ // addDependentsOf(file);
+ // }
+
+ if (addedFiles != null) {
+ for (Iterator fIter = addedFiles.iterator(); fIter.hasNext();) {
+ Object o = fIter.next();
+ if (!thisTime.contains(o))
+ thisTime.add(o);
+ }
+ // thisTime.addAll(addedFiles);
+ }
+
deleteClassFiles();
// Do not delete resources on incremental build, AJDT will handle
- // copying updates to the output folder. AspectJ only does a copy
+ // copying updates to the output folder. AspectJ only does a copy
// of them on full build (see copyResourcesToDestination() call
// in AjBuildManager)
-// deleteResources();
-
- addAffectedSourceFiles(thisTime,thisTime);
+ // deleteResources();
+
+ addAffectedSourceFiles(thisTime, thisTime);
} else {
- addAffectedSourceFiles(thisTime,compiledSourceFiles);
+ addAffectedSourceFiles(thisTime, compiledSourceFiles);
}
compiledSourceFiles = thisTime;
return thisTime;
@@ -778,8 +793,8 @@ public class AjState {
private boolean maybeIncremental() {
return (FORCE_INCREMENTAL_DURING_TESTING || this.couldBeSubsequentIncrementalBuild);
}
-
- public Map /* String -> List<ucf> */ getBinaryFilesToCompile(boolean firstTime) {
+
+ public Map /* String -> List<ucf> */getBinaryFilesToCompile(boolean firstTime) {
if (lastSuccessfulBuildTime == -1 || buildConfig == null || !maybeIncremental()) {
return binarySourceFiles;
}
@@ -792,15 +807,16 @@ public class AjState {
for (Iterator iter = addedOrModified.iterator(); iter.hasNext();) {
AjBuildConfig.BinarySourceFile bsf = (AjBuildConfig.BinarySourceFile) iter.next();
UnwovenClassFile ucf = createUnwovenClassFile(bsf);
- if (ucf == null) continue;
+ if (ucf == null)
+ continue;
List ucfs = new ArrayList();
ucfs.add(ucf);
recordTypeChanged(ucf.getClassName());
- binarySourceFiles.put(bsf.binSrc.getPath(),ucfs);
+ 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);
+ toWeave.put(bsf.binSrc.getPath(), ucfs);
}
deleteBinaryClassFiles();
} else {
@@ -808,43 +824,43 @@ public class AjState {
}
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...
+ * 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();
+ // 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();
List outputDirs = getOutputLocations(buildConfig);
for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) {
File dir = (File) iterator.next();
- File f = new File(dir,resource);
+ File f = new File(dir, resource);
if (f.exists()) {
f.delete();
- }
+ }
}
- }
+ }
}
-
+
private void deleteClassFiles() {
- if (deletedFiles == null) return;
- for (Iterator i = deletedFiles.iterator(); i.hasNext(); ) {
- File deletedFile = (File)i.next();
+ if (deletedFiles == null)
+ return;
+ 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);
@@ -854,107 +870,104 @@ public class AjState {
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());
+ 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();
+ for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext();) {
+ File inPathElement = (File) i.next();
if (inPathElement.isDirectory() && AjBuildManager.COPY_INPATH_DIR_RESOURCES) {
- deleteResourcesFromDirectory(inPathElement,oldResources);
- }
- }
-
+ deleteResourcesFromDirectory(inPathElement, oldResources);
+ }
+ }
+
if (buildConfig.getSourcePathResources() != null) {
- for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext(); ) {
- String resource = (String)i.next();
+ 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();
List outputDirs = getOutputLocations(buildConfig);
for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) {
File dir = (File) iterator.next();
- File f = new File(dir,victim);
+ File f = new File(dir, victim);
if (f.exists()) {
f.delete();
- }
- resources.remove(victim);
+ }
+ resources.remove(victim);
}
}
}
-
+
private void maybeDeleteResource(String resName, List oldResources) {
if (resources.contains(resName)) {
oldResources.remove(resName);
List outputDirs = getOutputLocations(buildConfig);
for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) {
File dir = (File) iterator.next();
- File source = new File(dir,resName);
- if ((source != null) && (source.exists()) &&
- (source.lastModified() >= lastSuccessfulBuildTime)) {
+ File source = new File(dir, resName);
+ if (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() {
+ File[] files = FileUtil.listFiles(dir, new FileFilter() {
public boolean accept(File f) {
- boolean accept = !(f.isDirectory() || f.getName().endsWith(".class")) ;
+ 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=null;
+ String filename = null;
try {
- filename = files[i].getCanonicalPath().substring(
- dir.getCanonicalPath().length()+1);
+ filename = files[i].getCanonicalPath().substring(dir.getCanonicalPath().length() + 1);
} catch (IOException e) {
- // we are in trouble if this happens...
- IMessage msg = new Message("call to getCanonicalPath() failed for file " + files[i]+" with: "+e.getMessage(),
- new SourceLocation(files[i],0),false);
+ // we are in trouble if this happens...
+ IMessage msg = new Message("call to getCanonicalPath() failed for file " + files[i] + " with: " + e.getMessage(),
+ new SourceLocation(files[i], 0), false);
buildManager.handler.handleMessage(msg);
- filename = files[i].getAbsolutePath().substring(
- dir.getAbsolutePath().length()+1);
+ filename = files[i].getAbsolutePath().substring(dir.getAbsolutePath().length() + 1);
}
maybeDeleteResource(filename, oldResources);
- }
+ }
}
- private void deleteClassFile(ClassFile cf) {
+ 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 {
@@ -966,20 +979,18 @@ public class AjState {
outputDir = buildConfig.getCompilationResultDestinationManager().getDefaultOutputLocation();
}
ucf = weaver.addClassFile(bsf.binSrc, bsf.fromInPathDirectory, outputDir);
- } catch(IOException ex) {
- IMessage msg = new Message("can't read class file " + bsf.binSrc.getPath(),
- new SourceLocation(bsf.binSrc,0),false);
+ } 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();
@@ -987,29 +998,30 @@ public class AjState {
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()));
+ 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);
+ recordWhetherCompilationUnitDefinedAspect(sourceFile, cr);
deleteTypesThatWereInThisCompilationUnitLastTimeRoundButHaveBeenDeletedInThisIncrement(sourceFile, unwovenClassFiles);
-
- recordFQNsResultingFromCompilationUnit(sourceFile,result);
+
+ recordFQNsResultingFromCompilationUnit(sourceFile, result);
}
/**
* @param sourceFile
* @param unwovenClassFiles
*/
- private void deleteTypesThatWereInThisCompilationUnitLastTimeRoundButHaveBeenDeletedInThisIncrement(File sourceFile, UnwovenClassFile[] 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);
+ removeFromClassFilesIfPresent(unwovenClassFiles[i].getClassName(), classFiles);
}
for (Iterator iter = classFiles.iterator(); iter.hasNext();) {
ClassFile cf = (ClassFile) iter.next();
@@ -1017,8 +1029,7 @@ public class AjState {
}
}
}
-
-
+
private void removeFromClassFilesIfPresent(String className, List classFiles) {
ClassFile victim = null;
for (Iterator iter = classFiles.iterator(); iter.hasNext();) {
@@ -1032,10 +1043,9 @@ public class AjState {
classFiles.remove(victim);
}
}
-
+
/**
- * Record the fully-qualified names of the types that were declared in the given
- * source file.
+ * 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
@@ -1044,28 +1054,26 @@ public class AjState {
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())));
+ classFiles.add(new ClassFile(types[i].getClassName(), new File(types[i].getFilename())));
}
- this.fullyQualifiedTypeNamesResultingFromCompilationUnit.put(sourceFile,classFiles);
+ 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.
+ * 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) {
+
+ if (cr != null) {
Map compiledTypes = cr.compiledTypes;
- if (compiledTypes!=null) {
+ if (compiledTypes != null) {
for (Iterator iterator = compiledTypes.keySet().iterator(); iterator.hasNext();) {
- char[] className = (char[])iterator.next();
- String typeName = new String(className).replace('/','.');
+ char[] className = (char[]) iterator.next();
+ String typeName = new String(className).replace('/', '.');
if (typeName.indexOf(BcelWeaver.SYNTHETIC_CLASS_POSTFIX) == -1) {
ResolvedType rt = world.resolve(typeName);
if (rt.isMissing()) {
@@ -1079,11 +1087,12 @@ public class AjState {
}
}
}
-
+
}
-
+
private UnwovenClassFile removeFromPreviousIfPresent(UnwovenClassFile cf, InterimCompilationResult previous) {
- if (previous == null) return null;
+ if (previous == null)
+ return null;
UnwovenClassFile[] unwovenClassFiles = previous.unwovenClassFiles();
for (int i = 0; i < unwovenClassFiles.length; i++) {
UnwovenClassFile candidate = unwovenClassFiles[i];
@@ -1094,7 +1103,7 @@ public class AjState {
}
return null;
}
-
+
private void recordClassFile(UnwovenClassFile thisTime, File lastTime) {
if (simpleStrings == null) {
// batch build
@@ -1105,25 +1114,28 @@ public class AjState {
if (!rType.isMissing()) {
try {
ClassFileReader reader = new ClassFileReader(thisTime.getBytes(), null);
- this.resolvedTypeStructuresFromLastBuild.put(thisTime.getClassName(),new CompactTypeStructureRepresentation(reader));
+ this.resolvedTypeStructuresFromLastBuild.put(thisTime.getClassName(), new CompactTypeStructureRepresentation(
+ reader));
} catch (ClassFormatException cfe) {
- throw new BCException("Unexpected problem processing class",cfe);
+ throw new BCException("Unexpected problem processing class", cfe);
}
}
return;
}
- CompactTypeStructureRepresentation existingStructure = (CompactTypeStructureRepresentation) this.resolvedTypeStructuresFromLastBuild.get(thisTime.getClassName());
+ CompactTypeStructureRepresentation existingStructure = (CompactTypeStructureRepresentation) this.resolvedTypeStructuresFromLastBuild
+ .get(thisTime.getClassName());
ResolvedType newResolvedType = world.resolve(thisTime.getClassName());
if (!newResolvedType.isMissing()) {
try {
ClassFileReader reader = new ClassFileReader(thisTime.getBytes(), null);
- this.resolvedTypeStructuresFromLastBuild.put(thisTime.getClassName(),new CompactTypeStructureRepresentation(reader));
+ this.resolvedTypeStructuresFromLastBuild.put(thisTime.getClassName(),
+ new CompactTypeStructureRepresentation(reader));
} catch (ClassFormatException cfe) {
- throw new BCException("Unexpected problem processing class",cfe);
+ throw new BCException("Unexpected problem processing class", cfe);
}
}
-
+
if (lastTime == null) {
recordTypeChanged(thisTime.getClassName());
return;
@@ -1138,32 +1150,31 @@ public class AjState {
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));
- recordTypeChanged(new String(reader.getName()).replace('/','.'));
+ 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));
+ recordTypeChanged(new String(reader.getName()).replace('/', '.'));
}
}
} catch (ClassFormatException e) {
recordTypeChanged(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....)
+ * 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.
*
- * 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...
*
- * Warning : long but boring method implementation...
* @param reader
* @param existingType
* @return
@@ -1172,167 +1183,179 @@ public class AjState {
if (existingType == null) {
return true;
}
-
+
// modifiers
- if (!modifiersEqual(reader.getModifiers(),existingType.modifiers)) {
+ if (!modifiersEqual(reader.getModifiers(), existingType.modifiers)) {
return true;
}
-
+
// generic signature
- if (!CharOperation.equals(reader.getGenericSignature(),existingType.genericSignature)) {
+ if (!CharOperation.equals(reader.getGenericSignature(), existingType.genericSignature)) {
return true;
}
-
+
// superclass name
- if (!CharOperation.equals(reader.getSuperclassName(),existingType.superclassName)) {
+ 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;
+ 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])) {
+ if (CharOperation.equals(existingIfs[j], newIfsAsChars[i])) {
continue new_interface_loop;
}
}
return true;
}
-
+
// fields
-// CompactMemberStructureRepresentation[] existingFields = existingType.fields;
+ // CompactMemberStructureRepresentation[] existingFields = existingType.fields;
IBinaryField[] newFields = reader.getFields();
- if (newFields == null) { newFields = CompactTypeStructureRepresentation.NoField; }
+ if (newFields == null) {
+ newFields = CompactTypeStructureRepresentation.NoField;
+ }
// 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);
-// //}
-// }
+ // 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);
+ // //}
+ // }
IBinaryField[] existingFs = existingType.binFields;
- if (newFields.length != existingFs.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 < existingFs.length; j++) {
- if (CharOperation.equals(existingFs[j].getName(),fieldName)) {
- if (!modifiersEqual(field.getModifiers(),existingFs[j].getModifiers())) {
- return true;
- }
- if (!CharOperation.equals(existingFs[j].getTypeName(),field.getTypeName())) {
- return true;
- }
- continue new_field_loop;
+ if (newFields.length != existingFs.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 < existingFs.length; j++) {
+ if (CharOperation.equals(existingFs[j].getName(), fieldName)) {
+ if (!modifiersEqual(field.getModifiers(), existingFs[j].getModifiers())) {
+ return true;
+ }
+ if (!CharOperation.equals(existingFs[j].getTypeName(), field.getTypeName())) {
+ return true;
}
+ continue new_field_loop;
}
- return true;
}
-
+ return true;
+ }
+
// methods
-// CompactMemberStructureRepresentation[] existingMethods = existingType.methods;
+ // CompactMemberStructureRepresentation[] existingMethods = existingType.methods;
IBinaryMethod[] newMethods = reader.getMethods();
- if (newMethods == null) { newMethods = CompactTypeStructureRepresentation.NoMethod; }
-
+ if (newMethods == null) {
+ newMethods = CompactTypeStructureRepresentation.NoMethod;
+ }
+
// 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
+ // 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);
-//// }
-// }
+ // 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);
+ // // }
+ // }
IBinaryMethod[] existingMs = existingType.binMethods;
- if (newMethods.length != existingMs.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 < existingMs.length; j++) {
- if (CharOperation.equals(existingMs[j].getSelector(),methodName)) {
- // candidate match
- if (!CharOperation.equals(method.getMethodDescriptor(),existingMs[j].getMethodDescriptor())) {
+ if (newMethods.length != existingMs.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 < existingMs.length; j++) {
+ if (CharOperation.equals(existingMs[j].getSelector(), methodName)) {
+ // candidate match
+ if (!CharOperation.equals(method.getMethodDescriptor(), existingMs[j].getMethodDescriptor())) {
// 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(),existingMs[j].getModifiers())) {
- return true;
- }
- continue new_method_loop;
+ // 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(), existingMs[j].getModifiers())) {
+ return true;
}
+ continue new_method_loop;
}
}
- return true; // (no match found)
}
-
+ return true; // (no match found)
+ }
+
return false;
}
-
private boolean modifiersEqual(int eclipseModifiers, int resolvedTypeModifiers) {
resolvedTypeModifiers = resolvedTypeModifiers & ExtraCompilerModifiers.AccJustFlag;
eclipseModifiers = eclipseModifiers & ExtraCompilerModifiers.AccJustFlag;
-// if ((eclipseModifiers & CompilerModifiers.AccSuper) != 0) {
-// eclipseModifiers -= CompilerModifiers.AccSuper;
-// }
+ // 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();) {
@@ -1341,26 +1364,27 @@ public class AjState {
}
return ret;
}
-
- private String stringifyList(Set l) {
- StringBuffer sb = new StringBuffer();
- sb.append("{");
- for (Iterator iter = l.iterator(); iter.hasNext();) {
+ private String stringifyList(Set l) {
+ StringBuffer sb = new StringBuffer();
+ sb.append("{");
+ for (Iterator iter = l.iterator(); iter.hasNext();) {
Object el = iter.next();
sb.append(el);
- if (iter.hasNext()) sb.append(",");
+ if (iter.hasNext())
+ sb.append(",");
}
- sb.append("}");
- return sb.toString();
- }
-
+ sb.append("}");
+ return sb.toString();
+ }
+
protected void addAffectedSourceFiles(Set addTo, Set lastTimeSources) {
- if (qualifiedStrings.elementSize == 0 && simpleStrings.elementSize == 0)
- return;
+ if (qualifiedStrings.elementSize == 0 && simpleStrings.elementSize == 0)
+ return;
if (listenerDefined())
- getListener().recordDecision(
- "Examining whether any other files now need compilation based on just compiling: '" + stringifyList(lastTimeSources) + "'");
+ getListener().recordDecision(
+ "Examining whether any other files now need compilation based on just compiling: '"
+ + stringifyList(lastTimeSources) + "'");
// the qualifiedStrings are of the form 'p1/p2' & the simpleStrings are just 'X'
char[][][] qualifiedNames = ReferenceCollection.internQualifiedNames(qualifiedStrings);
// if a well known qualified name was found then we can skip over these
@@ -1371,18 +1395,18 @@ public class AjState {
if (simpleNames.length < simpleStrings.elementSize)
simpleNames = null;
- //System.err.println("simple: " + simpleStrings);
- //System.err.println("qualif: " + qualifiedStrings);
+ // 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();
+ ReferenceCollection refs = (ReferenceCollection) entry.getValue();
if (refs != null && refs.includes(qualifiedNames, simpleNames)) {
- File file = (File)entry.getKey();
+ File file = (File) entry.getKey();
if (file.exists()) {
- if (!lastTimeSources.contains(file)) { //??? O(n**2)
+ if (!lastTimeSources.contains(file)) { // ??? O(n**2)
if (listenerDefined()) {
- getListener().recordDecision("Need to recompile '"+file.getName().toString()+"'");
+ getListener().recordDecision("Need to recompile '" + file.getName().toString() + "'");
}
addTo.add(file);
}
@@ -1393,38 +1417,37 @@ public class AjState {
// 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)
if (addTo.size() > 0)
- addTo.addAll(lastTimeSources);
- // // 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();
+ addTo.addAll(lastTimeSources);
+ // // 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();
}
/**
- * Record that a particular type has been touched during a compilation run. Information is used to ensure any types
- * depending upon this one are also recompiled.
- *
- * @param typename (possibly qualified) type name
- */
- protected void recordTypeChanged(String typename) {
- int lastDot = typename.lastIndexOf('.');
+ * Record that a particular type has been touched during a compilation run. Information is used to ensure any types depending
+ * upon this one are also recompiled.
+ *
+ * @param typename (possibly qualified) type name
+ */
+ protected void recordTypeChanged(String typename) {
+ int lastDot = typename.lastIndexOf('.');
String typeName;
if (lastDot != -1) {
- String packageName = typename.substring(0, lastDot).replace('.', '/');
+ String packageName = typename.substring(0, lastDot).replace('.', '/');
qualifiedStrings.add(packageName);
- typeName = typename.substring(lastDot+1);
+ typeName = typename.substring(lastDot + 1);
} else {
qualifiedStrings.add("");
- typeName = typename;
+ typeName = typename;
}
-
int memberIndex = typeName.indexOf('$');
if (memberIndex > 0)
typeName = typeName.substring(0, memberIndex);
@@ -1433,7 +1456,7 @@ public class AjState {
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();
@@ -1448,27 +1471,42 @@ public class AjState {
}
public IHierarchy getStructureModel() {
- return structureModel;
+ return structureModel;
+ }
+
+ public void setWeaver(BcelWeaver bw) {
+ weaver = bw;
+ }
+
+ public BcelWeaver getWeaver() {
+ return weaver;
}
- 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 void setWorld(BcelWorld bw) {world=bw;}
- public BcelWorld getBcelWorld() {return world; }
-
- public void setRelationshipMap(IRelationshipMap irm) { relmap = irm;}
- public IRelationshipMap getRelationshipMap() { return relmap;}
+ 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;
@@ -1480,13 +1518,13 @@ public class AjState {
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);
+ this.binarySourceFiles.put(fromPathName, unwovenClassFiles);
if (this.maybeIncremental()) {
List simpleClassFiles = new LinkedList();
for (Iterator iter = unwovenClassFiles.iterator(); iter.hasNext();) {
@@ -1494,7 +1532,7 @@ public class AjState {
ClassFile cf = getClassFileFor(ucf);
simpleClassFiles.add(cf);
}
- this.inputClassFilesBySource.put(fromPathName,simpleClassFiles);
+ this.inputClassFilesBySource.put(fromPathName, simpleClassFiles);
}
}
@@ -1503,21 +1541,21 @@ public class AjState {
* @return
*/
private ClassFile getClassFileFor(UnwovenClassFile ucf) {
- return new ClassFile(ucf.getClassName(),new File(ucf.getFilename()));
+ 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);
}
@@ -1535,35 +1573,36 @@ public class AjState {
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 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('.'));
+ namePrefix = namePrefix.substring(0, namePrefix.lastIndexOf('.'));
final String targetPrefix = namePrefix + BcelWeaver.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) {
+ }
+ });
+ if (weaverGenerated != null) {
for (int i = 0; i < weaverGenerated.length; i++) {
weaverGenerated[i].delete();
}
@@ -1577,7 +1616,7 @@ public class AjState {
buildManager.state = null;
buildManager.setStructureModel(null);
}
-
+
public Map getAspectNamesToFileNameMap() {
return aspectsFromFileNames;
}
@@ -1585,20 +1624,20 @@ public class AjState {
public void initializeAspectNamesToFileNameMap() {
this.aspectsFromFileNames = new HashMap();
}
-
+
// Will allow us to record decisions made during incremental processing, hopefully aid in debugging
public boolean listenerDefined() {
- return stateListener!=null;
+ return stateListener != null;
}
-
+
public IStateListener getListener() {
return stateListener;
}
public IBinaryType checkPreviousBuild(String name) {
- return (IBinaryType)resolvedTypeStructuresFromLastBuild.get(name);
+ return (IBinaryType) resolvedTypeStructuresFromLastBuild.get(name);
}
-
+
public AjBuildManager getAjBuildManager() {
return buildManager;
}
diff --git a/org.aspectj.ajdt.core/src/org/aspectj/org/eclipse/jdt/core/dom/AjASTConverter.java b/org.aspectj.ajdt.core/src/org/aspectj/org/eclipse/jdt/core/dom/AjASTConverter.java
index 251e869c2..d846bedcb 100644
--- a/org.aspectj.ajdt.core/src/org/aspectj/org/eclipse/jdt/core/dom/AjASTConverter.java
+++ b/org.aspectj.ajdt.core/src/org/aspectj/org/eclipse/jdt/core/dom/AjASTConverter.java
@@ -157,7 +157,7 @@ public class AjASTConverter extends ASTConverter {
adviceDecl.setBody(block);
}
if (block != null && statements != null) {
- int statementsLength = statements == null ? 0 : statements.length;
+ int statementsLength = statements.length;
for (int i = 0; i < statementsLength; i++) {
if (statements[i] instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration) {
checkAndAddMultipleLocalDeclaration(statements, i, block.statements());
diff --git a/org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/ajc/AjdtCommandTestCase.java b/org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/ajc/AjdtCommandTestCase.java
index fdc14146b..6702208d1 100644
--- a/org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/ajc/AjdtCommandTestCase.java
+++ b/org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/ajc/AjdtCommandTestCase.java
@@ -10,184 +10,168 @@
* PARC initial implementation
* ******************************************************************/
-
package org.aspectj.ajdt.ajc;
//import org.aspectj.ajdt.internal.core.builder.AjBuildConfig;
-import org.aspectj.ajdt.StreamPrintWriter;
-import org.aspectj.bridge.*;
-import org.aspectj.util.*;
-import org.aspectj.org.eclipse.jdt.core.compiler.InvalidInputException;
-
-import java.io.*;
-import java.util.*;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.ListIterator;
import junit.framework.TestCase;
+import org.aspectj.ajdt.StreamPrintWriter;
+import org.aspectj.bridge.AbortException;
+import org.aspectj.bridge.CountingMessageHandler;
+import org.aspectj.bridge.IMessage;
+import org.aspectj.bridge.IMessageHolder;
+import org.aspectj.bridge.MessageHandler;
+import org.aspectj.bridge.MessageWriter;
+import org.aspectj.org.eclipse.jdt.core.compiler.InvalidInputException;
+import org.aspectj.util.FileUtil;
+
/**
* Some black-box test is happening here.
*/
public class AjdtCommandTestCase extends TestCase {
- private ArrayList tempFiles = new ArrayList();
+ private ArrayList tempFiles = new ArrayList();
private StreamPrintWriter outputWriter = new StreamPrintWriter(new PrintWriter(System.out));
-// private AjdtCommand command = new AjdtCommand();
+ // private AjdtCommand command = new AjdtCommand();
private MessageWriter messageWriter = new MessageWriter(outputWriter, false);
- private CountingMessageHandler counter
- = new CountingMessageHandler(messageWriter);
+ private CountingMessageHandler counter = new CountingMessageHandler(messageWriter);
+
public AjdtCommandTestCase(String name) {
super(name);
-// command.buildArgParser.out = outputWriter;
+ // command.buildArgParser.out = outputWriter;
+ }
+
+ private static boolean delete(File file) {
+ if ((null == file) || !file.exists()) {
+ return true;
+ } else if (!file.canWrite()) {
+ return false;
+ }
+ if (file.isDirectory()) {
+ FileUtil.deleteContents(file);
+ }
+ return file.delete();
+ }
+
+ public void testIncrementalHandler() throws IOException {
+ // verify that AjdtCommand respects handler parm
+ // in runCommand and repeatCommand
+ final String sig = getClass().getName() + ".testIncrementalHandler";
+ boolean runTest = false;
+ try {
+ runTest = null != System.getProperty(sig);
+ } catch (Throwable t) {
+ }
+ if (!runTest) {
+ System.out.println("warning: to run " + sig + "(), set system property " + sig);
+ return;
+ }
+ // setup initial compile
+ File testBase = new File("testdata/ajdtCommand");
+ assertTrue(testBase.isDirectory());
+ assertTrue(testBase.canWrite());
+ File genBase = new File(testBase, "genBase");
+ tempFiles.add(genBase);
+ if (genBase.exists()) {
+ FileUtil.deleteContents(genBase);
+ } else {
+ genBase.mkdirs();
+ }
+ assertTrue(genBase.canWrite());
+ File classesDir = new File(testBase, "classes");
+ tempFiles.add(classesDir);
+ assertTrue(classesDir.mkdirs());
+ File mainSrc = new File(testBase, "Main-1.java");
+ File main = new File(genBase, "Main.java");
+ FileUtil.copyFile(mainSrc, main);
+ assertTrue(main.canRead());
+ long initialSize = main.length();
+
+ // do initial compile
+ String[] args = new String[] { "-d", classesDir.getPath(), "-classpath", "../lib/test/aspectjrt.jar", main.getPath() };
+ AjdtCommand command = new AjdtCommand();
+ IMessageHolder holder = new MessageHandler();
+ boolean result = command.runCommand(args, holder);
+ assertTrue(result);
+ assertTrue(!holder.hasAnyMessage(IMessage.WARNING, true));
+ int initialMessages = holder.numMessages(null, true);
+
+ // do repeat compile, introducing an error
+ mainSrc = new File(testBase, "Main-2.java");
+ FileUtil.copyFile(mainSrc, main);
+ assertTrue(main.canRead());
+ long nextSize = main.length();
+ assertTrue(nextSize > initialSize);
+ IMessageHolder newHolder = new MessageHandler();
+ result = command.repeatCommand(newHolder);
+
+ // verify failed, no effect on first holder, error in second
+ assertFalse(result);
+ assertEquals(1, newHolder.numMessages(IMessage.ERROR, false));
+ assertEquals(initialMessages, holder.numMessages(null, true));
}
-
- private static boolean delete(File file) {
- if ((null == file) || !file.exists()) {
- return true;
- } else if (!file.canWrite()) {
- return false;
- }
- if (file.isDirectory()) {
- FileUtil.deleteContents(file);
- }
- return file.delete();
- }
-
- public void testIncrementalHandler() throws IOException {
- // verify that AjdtCommand respects handler parm
- // in runCommand and repeatCommand
- final String sig = getClass().getName()
- + ".testIncrementalHandler";
- boolean runTest = false;
- try {
- runTest = null != System.getProperty(sig);
- } catch (Throwable t) {
- }
- if (!runTest) {
- System.out.println("warning: to run " + sig
- + "(), set system property " + sig);
- return;
- }
- // setup initial compile
- File testBase = new File("testdata/ajdtCommand");
- assertTrue(testBase.isDirectory());
- assertTrue(testBase.canWrite());
- File genBase = new File(testBase, "genBase");
- tempFiles.add(genBase);
- if (genBase.exists()) {
- FileUtil.deleteContents(genBase);
- } else {
- genBase.mkdirs();
- }
- assertTrue(genBase.canWrite());
- File classesDir = new File(testBase, "classes");
- tempFiles.add(classesDir);
- assertTrue(classesDir.mkdirs());
- File mainSrc= new File(testBase, "Main-1.java");
- File main = new File(genBase, "Main.java");
- FileUtil.copyFile(mainSrc, main);
- assertTrue(main.canRead());
- long initialSize = main.length();
-
- // do initial compile
- String[] args = new String[] {
- "-d",
- classesDir.getPath(),
- "-classpath",
- "../lib/test/aspectjrt.jar",
- main.getPath()
- };
- AjdtCommand command = new AjdtCommand();
- IMessageHolder holder = new MessageHandler();
- boolean result = command.runCommand(args, holder);
- assertTrue(result);
- assertTrue(!holder.hasAnyMessage(IMessage.WARNING, true));
- int initialMessages = holder.numMessages(null, true);
-
- // do repeat compile, introducing an error
- mainSrc= new File(testBase, "Main-2.java");
- FileUtil.copyFile(mainSrc, main);
- assertTrue(main.canRead());
- long nextSize = main.length();
- assertTrue(nextSize > initialSize);
- IMessageHolder newHolder = new MessageHandler();
- result = command.repeatCommand(newHolder);
-
- // verify failed, no effect on first holder, error in second
- assertFalse(result);
- assertEquals(1, newHolder.numMessages(IMessage.ERROR, false));
- assertEquals(initialMessages, holder.numMessages(null, true));
- }
public void testIncrementalOption() throws InvalidInputException {
- AjdtCommand.genBuildConfig(
- new String[] { "-incremental" },
- counter);
-
- assertTrue(
- "didn't specify source root",
- outputWriter.getContents().indexOf("specify a source root") != -1);
-
- outputWriter.flushBuffer();
- AjdtCommand.genBuildConfig(
- new String[] { "-incremental", "-sourceroots",
- AjdtAjcTests.TESTDATA_PATH + "/src1" },
- counter);
-
- assertTrue(
- outputWriter.getContents(),
- outputWriter.getContents().equals(""));
-
- outputWriter.flushBuffer();
- AjdtCommand.genBuildConfig(
- new String[] { "-incremental", "testdata/src1/Hello.java" },
- counter);
-
- assertTrue(
- "specified a file",
- outputWriter.getContents().indexOf("incremental mode only handles source files using -sourceroots") != -1); ;
+ AjdtCommand.genBuildConfig(new String[] { "-incremental" }, counter);
+
+ assertTrue("didn't specify source root", outputWriter.getContents().indexOf("specify a source root") != -1);
+
+ outputWriter.flushBuffer();
+ AjdtCommand.genBuildConfig(new String[] { "-incremental", "-sourceroots", AjdtAjcTests.TESTDATA_PATH + "/src1" }, counter);
+
+ assertTrue(outputWriter.getContents(), outputWriter.getContents().equals(""));
+
+ outputWriter.flushBuffer();
+ AjdtCommand.genBuildConfig(new String[] { "-incremental", "testdata/src1/Hello.java" }, counter);
+
+ assertTrue("specified a file", outputWriter.getContents().indexOf(
+ "incremental mode only handles source files using -sourceroots") != -1);
}
-
+
public void testBadOptionAndUsagePrinting() throws InvalidInputException {
try {
- AjdtCommand.genBuildConfig(
- new String[] { "-mubleBadOption" },
- counter);
- } catch (AbortException ae) { }
+ AjdtCommand.genBuildConfig(new String[] { "-mubleBadOption" }, counter);
+ } catch (AbortException ae) {
+ }
// usage printed by caller to genBuildConfig now...
- assertTrue(
- outputWriter.getContents() + " contains? " + "Usage",
- outputWriter.getContents().indexOf("-mubleBadOption") != -1);
-
+ assertTrue(outputWriter.getContents() + " contains? " + "Usage",
+ outputWriter.getContents().indexOf("-mubleBadOption") != -1);
+
}
-
+
public void testHelpUsagePrinting() {
String[] args = new String[] { "-help" };
-
+
PrintStream saveOut = System.out;
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
PrintStream newOut = new PrintStream(byteArrayOut);
System.setOut(newOut);
-
+
try {
try {
-
- AjdtCommand.genBuildConfig(
- args,
- counter);
- } catch (AbortException ae) { }
+
+ AjdtCommand.genBuildConfig(args, counter);
+ } catch (AbortException ae) {
+ }
} finally {
System.setOut(saveOut);
}
-
+
String text = byteArrayOut.toString();
- assertTrue(
- text + " contains? " + "Usage",
- text.indexOf("Usage") != -1);
+ assertTrue(text + " contains? " + "Usage", text.indexOf("Usage") != -1);
}
-
- public void q() throws InvalidInputException {
+
+ public void q() throws InvalidInputException {
String[] args = new String[] { "-version" };
-
+
PrintStream saveOut = System.out;
PrintStream saveErr = System.err;
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
@@ -196,48 +180,42 @@ public class AjdtCommandTestCase extends TestCase {
PrintStream newErr = new PrintStream(byteArrayErr);
System.setOut(newOut);
System.setErr(newErr);
-
+
try {
try {
-
- AjdtCommand.genBuildConfig(
- args,
- counter);
- } catch (AbortException ae) { }
+
+ AjdtCommand.genBuildConfig(args, counter);
+ } catch (AbortException ae) {
+ }
} finally {
System.setOut(saveOut);
System.setErr(saveErr);
}
-
+
String text = byteArrayOut.toString();
String text2 = byteArrayErr.toString();
- assertTrue(
- "version output does not include 'AspectJ Compiler', output was:\n'"+text+"'",
- text.indexOf("AspectJ Compiler") != -1);
+ assertTrue("version output does not include 'AspectJ Compiler', output was:\n'" + text + "'", text
+ .indexOf("AspectJ Compiler") != -1);
}
-
+
public void testNonExistingLstFile() {
- AjdtCommand.genBuildConfig(
- new String[] { "@mumbleDoesNotExist" },
- counter);
-
- assertTrue(
- outputWriter.getContents(),
- outputWriter.getContents().indexOf("file does not exist") != -1);
+ AjdtCommand.genBuildConfig(new String[] { "@mumbleDoesNotExist" }, counter);
+
+ assertTrue(outputWriter.getContents(), outputWriter.getContents().indexOf("file does not exist") != -1);
}
-
+
protected void setUp() throws Exception {
super.setUp();
}
-
+
protected void tearDown() throws Exception {
super.tearDown();
outputWriter.flushBuffer();
- for (ListIterator iter = tempFiles.listIterator(); iter.hasNext();) {
- File file = (File) iter.next();
- if (delete(file)) {
- iter.remove();
- }
- }
+ for (ListIterator iter = tempFiles.listIterator(); iter.hasNext();) {
+ File file = (File) iter.next();
+ if (delete(file)) {
+ iter.remove();
+ }
+ }
}
}
diff --git a/org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/CompilerDumpTestCase.java b/org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/CompilerDumpTestCase.java
index f2c198a77..9851cda08 100644
--- a/org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/CompilerDumpTestCase.java
+++ b/org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/CompilerDumpTestCase.java
@@ -24,78 +24,75 @@ public class CompilerDumpTestCase extends AjcTestCase {
private File baseDir;
private File dumpFile;
private IMessage.Kind savedDumpCondition;
-
+
protected void setUp() throws Exception {
super.setUp();
- baseDir = new File("../org.aspectj.ajdt.core/testdata",PROJECT_DIR);
+ baseDir = new File("../org.aspectj.ajdt.core/testdata", PROJECT_DIR);
dumpFile = null;
savedDumpCondition = Dump.getDumpOnExit();
}
protected void tearDown() throws Exception {
super.tearDown();
-
+
if (dumpFile != null && dumpFile.exists()) {
boolean deleted = dumpFile.delete();
- assertTrue("Dump file '" + dumpFile.getPath() + "' could not be deleted",deleted);
- }
+ assertTrue("Dump file '" + dumpFile.getPath() + "' could not be deleted", deleted);
+ }
Dump.setDumpOnExit(savedDumpCondition);
}
/**
- * Aim: Dump after successful compile to ensure it contains the command
- * line information.
+ * Aim: Dump after successful compile to ensure it contains the command line information.
*
- * Inputs to the compiler:
- * HelloWorld.java Pointcuts.aj Aspect.aj
+ * Inputs to the compiler: HelloWorld.java Pointcuts.aj Aspect.aj
*
* Expected result = Compile succeeds.
*/
- public void testDump () {
+ public void testDump() {
String[] args = new String[] { "src/HelloWorld.java", "src/Pointcuts.aj", "src/Aspect.aj" };
- CompilationResult result = ajc(baseDir,args);
+ CompilationResult result = ajc(baseDir, args);
assertNoMessages(result);
String fileName = Dump.dump("DumpTestCase.testDump()");
dumpFile = new File(fileName);
- org.aspectj.weaver.DumpTestCase.assertContents(dumpFile,"Command Line","HelloWorld.java");
+ org.aspectj.weaver.DumpTestCase.assertContents(dumpFile, "Command Line", "HelloWorld.java");
}
-
+
/**
- * Aim: Dump after successful compile to ensure it contains warning
- * messages.
+ * Aim: Dump after successful compile to ensure it contains warning messages.
*
- * Inputs to the compiler:
- * HelloWorld.java Pointcuts.aj Aspect.aj DeclareWarning.aj
+ * Inputs to the compiler: HelloWorld.java Pointcuts.aj Aspect.aj DeclareWarning.aj
*
* Expected result = Compile succeeds.
*/
- public void testDumpWithWarnings () {
+ public void testDumpWithWarnings() {
String[] args = new String[] { "src/HelloWorld.java", "src/Pointcuts.aj", "src/DeclareWarning.aj" };
Dump.preserveOnNextReset();
- CompilationResult result = ajc(baseDir,args);
+ // CompilationResult result =
+ ajc(baseDir, args);
String fileName = Dump.dump("DumpTestCase.testDumpWithWarnings()");
dumpFile = new File(fileName);
- org.aspectj.weaver.DumpTestCase.assertContents(dumpFile,"Compiler Messages","warning");
+ org.aspectj.weaver.DumpTestCase.assertContents(dumpFile, "Compiler Messages", "warning");
}
-
+
/**
- * Aim: Dump due to errors.
+ * Aim: Dump due to errors.
*
- * Inputs to the compiler:
- * HelloWorld.java Pointcuts.aj Aspect.aj DeclareError.aj
+ * Inputs to the compiler: HelloWorld.java Pointcuts.aj Aspect.aj DeclareError.aj
*
* Expected result = Compile fails and dump file created.
*/
- public void testWithErrors () {
+ public void testWithErrors() {
Dump.setDumpOnExit(IMessage.ERROR);
String previousFileName = Dump.getLastDumpFileName();
String[] args = new String[] { "src/HelloWorld.java", "src/Pointcuts.aj", "src/DeclareError.aj" };
- CompilationResult result = ajc(baseDir,args);
+ // CompilationResult result =
+ ajc(baseDir, args);
String fileName = Dump.getLastDumpFileName();
- assertTrue("Dump file should be created",!fileName.equals(previousFileName));
+ assertTrue("Dump file should be created", !fileName.equals(previousFileName));
dumpFile = new File(fileName);
- org.aspectj.weaver.DumpTestCase.assertContents(dumpFile,"Compiler Messages","error");
+ org.aspectj.weaver.DumpTestCase.assertContents(dumpFile, "Compiler Messages", "error");
}
}
diff --git a/org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/DeclareParents.java b/org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/DeclareParents.java
index 9d3464e38..a1d323dbd 100644
--- a/org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/DeclareParents.java
+++ b/org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/DeclareParents.java
@@ -24,471 +24,425 @@ import org.aspectj.bridge.IMessage;
import org.aspectj.tools.ajc.AjcTestCase;
import org.aspectj.tools.ajc.CompilationResult;
-
-
/**
- * These tests verify the behavior of the binary implementation of declare parents.
- * Basically we attempt a source compile with all the classes/aspects - we get some
- * set of errors/warnings and weaving messages out from doing this. We then compile the
- * source files and aspects separately and binary weave them together - we should
- * get the same set of weaving information messages. Where possible we also execute one of the
- * classes after the binary weave to check it passes the verifier and executes.
+ * These tests verify the behavior of the binary implementation of declare parents. Basically we attempt a source compile with all
+ * the classes/aspects - we get some set of errors/warnings and weaving messages out from doing this. We then compile the source
+ * files and aspects separately and binary weave them together - we should get the same set of weaving information messages. Where
+ * possible we also execute one of the classes after the binary weave to check it passes the verifier and executes.
*
- * There are some notes about the implementation throughout these testcases and they
- * are marked: 'IMPORTANT:'
+ * There are some notes about the implementation throughout these testcases and they are marked: 'IMPORTANT:'
*
*
* Two things missing:
-
- * In the case where inherited methods can't be overridden to reduce visibility, we should cope
- * with a subclass of the decp target also trying to do it ? We need a way once we see a type
- * to say 'hey, watch out for this guys kids...' - this will also help us when working with abstract
- * classes that don't provide method implementations where their children might.
-
+ *
+ * In the case where inherited methods can't be overridden to reduce visibility, we should cope with a subclass of the decp target
+ * also trying to do it ? We need a way once we see a type to say 'hey, watch out for this guys kids...' - this will also help us
+ * when working with abstract classes that don't provide method implementations where their children might.
+ *
* Field inheritance? Is there something to worry about here?
-
+ *
* Covariance on method overrides is supported but untested because we need a Java5 compiler (so we can write easy tests)
-
*/
public class DeclareParents extends AjcTestCase {
-
- private static final boolean verbose = false;
-
- public static final String PROJECT_DIR = "binaryParents";
-
- private File baseDir;
-
-
- /**
- * Check the order doesn't make a difference. (order1)
- */
- public void testVerifyOrderOfProcessingIrrelevant1() {
- File testBase = new File(baseDir,"TestA");
- runSourceAndBinaryTestcase(testBase,new String[]{"Z.java","B.java"},
- new String[]{"AspectAB.aj"},false);
-// runClass("B");
- }
-
-
- /**
- * Check the order doesn't make a difference. (order2)
- */
- public void testVerifyOrderOfProcessingIrrelevant2() {
- File testBase = new File(baseDir,"TestA");
- runSourceAndBinaryTestcase(testBase,new String[]{"B.java","Z.java"},
- new String[]{"AspectAB.aj"},false);
-// runClass("B");
- }
-
-
- /**
- * Three classes:
- * Top1, Middle1, Bottom1. Bottom1 extends Top1. Middle1 extends Top1.
- * AspectX1: declares Bottom1 extends Middle1
- * Result:
- * Should be OK, fits into the hierarchy no problem.
- */
- public void testSimpleDeclareParents() {
- File testBase = new File(baseDir,"TestA");
- runSourceAndBinaryTestcase(testBase,new String[]{"Top1.java","Middle1.java","Bottom1.java"},
- new String[]{"AspectX1.java"},false);
-// runClass("Bottom1");
- }
-
-
- /**
- * Three classes:
- * Top2, Middle2, Bottom2. Bottom2 extends Top2. Middle2 extends Top2.
- * Bottom2 includes a call to super in a ctor.
- * AspectX2: declares Bottom2 extends Middle2
- * Result:
- * Should be OK, fits into the hierarchy no problem.
- * Implementation:
- * The super call should be modified from a Top2.<init> call to a Middle2.<init> call
- */
- public void test_SuperCtorCall() {
- File testBase = new File(baseDir,"TestA");
- runSourceAndBinaryTestcase(testBase,new String[]{"Top2.java","Middle2.java","Bottom2.java"},
- new String[]{"AspectX2.java"},false);
-// runClass("Bottom2");
- }
-
-
- /**
- * Three classes:
- * Top3, Middle3, Bottom3. Bottom3 extends Top3. Middle3 extends Top3.
- * Bottom3 includes a call to a super method in an instance method.
- * AspectX3: declares Bottom3 extends Middle3
- * Result: Should be OK.
- * Implementation:
- * We don't modify the call to Top3.m() that is in the Bottom3 class, we don't have to because
- * the JVM will ensure that the m() chosen at runtime is the one nearest the Bottom3 class -
- * when the hierarchy has changed this will be the Middle3.m() version and so it all works.
- * IMPORTANT:
- * This leaves a subtle difference in the code generated from decp application at source time
- * and decp application at weave time - in the source time case the call in Bottom3 will have
- * been set to Middle3.m() during code gen, whereas in the weave time case it will still
- * say Top3.m() - I'm not sure this makes any practical difference though? We could easily
- * fix it and morph the Top3.m() call to a Middle3.m() call but it would impact peformance
- * crawling through all the bytecodes to make this change.
- */
- public void test_SuperMethodCall() {
- File testBase = new File(baseDir,"TestA");
- runSourceAndBinaryTestcase(testBase,new String[]{"Top3.java","Middle3.java","Bottom3.java"},
- new String[]{"AspectX3.java"},false);
-// runClass("Bottom3");
- }
-
-
- /**
- * Three classes:
- * Top4, Middle4, Bottom4. Bottom4 extends Top4. Middle4 extends Top4.
- * AspectX4: declares Bottom4 extends Middle4
- * Result: Should fail - because Middle4 doesn't include a ctor that takes a String, which is called by Bottom4
- */
- public void test_missingCtorInIntroducedClass() {
- File testBase = new File(baseDir,"TestA");
- runSourceAndBinaryTestcase(testBase,new String[]{"Top4.java","Middle4.java","Bottom4.java"},
- new String[]{"AspectX4.java"},true,false);
- }
-
-
- /**
- * If overriding an instance method, can't make it static.
- * If overriding a static method, can't make it an instance method.
- *
- * Note: Error messages and locations for binary weaving are much better than their source counterparts !
- */
- public void test_cantMakeInheritedInstanceMethodsStatic() {
- File testBase = new File(baseDir,"TestC");
- CompilationResult result = null;
- runSourceAndBinaryTestcase(new File(baseDir,"TestC"),
- new String[]{"A1.java","B1.java"},
- new String[]{"X1.java"},true,false);
- }
-
- /**
- * Cannot extend a final class
- */
- public void xxxtest_cantExtendFinalClass() { // XXX removed test, need to discuss with andy how to repair...
- File testBase = new File(baseDir,"TestC");
- CompilationResult result = null;
- runSourceAndBinaryTestcase(new File(baseDir,"TestC"),
- new String[]{"A2.java","B2.java"},
- new String[]{"X2.java"},true,true);
- }
-
- /**
- * The Object class cannot be subject to declare parents extends
- *
- * This is tested when the aspect is compiled - so couldn't occur during binary weaving of decp.
- */
-
-
- /**
- * if you inherit methods you cannot override them and reduce their visibility
- */
- public void test_cantReduceVisibilityOfOverriddenMethods_1() {
- File testBase = new File(baseDir,"TestB");
- CompilationResult result = null;
- runSourceAndBinaryTestcase(new File(baseDir,"TestB"),
- new String[]{"Top1.java","Middle1.java"},
- new String[]{"Aspect1.java"},true,false);
- }
-
- /**
- * if you inherit methods you cannot override them and reduce their visibility.
- *
- * test 2 in this set checks methods from a superclass of the named new parent.
- */
- public void test_cantReduceVisibilityOfOverriddenMethods_2() {
- File testBase = new File(baseDir,"TestB");
- CompilationResult result = null;
- runSourceAndBinaryTestcase(new File(baseDir,"TestB"),
- new String[]{"TopTop6.java","Top6.java","Middle6.java"},
- new String[]{"Aspect6.java"},true,false);
- }
-
-
-
- /**
- * If you inherit methods you cannot have incompatible return types (java1.5 will
- * make this a little messier).
- */
- public void test_overriddenMethodsCantHaveIncompatibleReturnTypes() {
- File testBase = new File(baseDir,"TestB");
- CompilationResult result = null;
- runSourceAndBinaryTestcase(new File(baseDir,"TestB"),
- new String[]{"Top2.java","Middle2.java","Super.java","Sub.java"},
- new String[]{"Aspect2.java"},true);
- }
-
-
- /**
- * Testing: If you inherit abstract methods and you are not abstract you need to provide
- * an implementation.
- *
- * Test 1 in this set is simple.
- */
- public void test_inheritedAbstractMethodsMustBeImplemented_1() {
- File testBase = new File(baseDir,"TestB");
- CompilationResult result = null;
- runSourceAndBinaryTestcase(new File(baseDir,"TestB"),
- new String[]{"Top3.java","Middle3.java","Super.java","Sub.java"},
- new String[]{"Aspect3.java"},true);
- }
-
- /**
- * Testing: If the decp makes you implement an interface, you must provide the implementation
- */
- public void test_interfaceMethodsImplemented() {
- File testBase = new File(baseDir,"TestD");
- CompilationResult result = null;
- runSourceAndBinaryTestcase(testBase,
- new String[]{"SimpleClass1.java","SimpleIntf1.java"},
- new String[]{"SimpleAspect1.java"},true);
- }
-
- /**
- * Testing: If you inherit abstract methods and you are not abstract you need to provide
- * an implementation.
- *
- * Test 2 in this set includes methods further up the hierarchy that must be
- * implemented.
- */
- public void test_inheritedAbstractMethodsMustBeImplemented_2() {
- File testBase = new File(baseDir,"TestB");
- CompilationResult result = null;
- runSourceAndBinaryTestcase(new File(baseDir,"TestB"),
- new String[]{"TopTop4.java","Top4.java","Middle4.java"},
- new String[]{"Aspect4.java"},true);
- }
-
-
- /**
- * Testing: If you inherit abstract methods and you are not abstract you need to provide
- * an implementation.
- *
- * Test 3 in this set includes methods further up the hierarchy that must be
- * implemented *and* the dependencies are satisfied by ITDs from the aspect
- */
- public void test_inheritedAbstractMethodsMustBeImplemented_3() {
- File testBase = new File(baseDir,"TestD");
- CompilationResult result = null;
- runSourceAndBinaryTestcase(new File(baseDir,"TestD"),
- new String[]{"SimpleClass2.java"},
- new String[]{"SimpleAspect2.java"},true);
- }
-
- /**
- * If adding a type into a hierarchy, any missing ctor could be added via an ITDC so allow for
- * that !
- */
- public void test_missingCtorAddedViaITD() {
- File testBase = new File(baseDir,"TestE");
- CompilationResult result = null;
- runSourceAndBinaryTestcase(testBase,
- new String[]{"A.java","B.java","C.java"},
- new String[]{"X.java"},true);
- }
-
- //////////////////////////////////////////////////////////////////////////////////////////
- //////////////////////////////////////////////////////////////////////////////////////////
- //////////////////////////////////////////////////////////////////////////////////////////
-
- public void runSourceAndBinaryTestcase(File testBase,String[] classes,String[] aspects,boolean expectErrors) {
- runSourceAndBinaryTestcase(testBase,classes,aspects,expectErrors,true);
- }
-
- public void runSourceAndBinaryTestcase(File testBase,String[] classes,String[] aspects,boolean expectErrors,boolean compareErrors) {
- // Do a compile of everything together from source ...
- CompilationResult result = null;
-
- // Execute: "ajc <classes> <aspects> -showWeaveInfo"
- String[] sourceCompileCommandLine = new String[classes.length+aspects.length+1];
- System.arraycopy(classes,0,sourceCompileCommandLine,0,classes.length);
- System.arraycopy(aspects,0,sourceCompileCommandLine,classes.length,aspects.length);
- String[] extraOption = new String[]{"-showWeaveInfo"};
- System.arraycopy(extraOption,0,sourceCompileCommandLine,classes.length+aspects.length,1);
- result = ajc(testBase,sourceCompileCommandLine);
- if (!expectErrors) assertTrue("errors? \n"+result.getErrorMessages(),!result.hasErrorMessages());
- List sourceWeaveMessages = getWeaveMessages(result);
- int sourceWeaveMessagesCount = sourceWeaveMessages.size();
- List sourceErrorMessages = result.getErrorMessages();
- int sourceErrorMessagesCount = sourceErrorMessages.size();
-
- if (verbose) {
- System.err.println("Source Compilation: Error count = "+sourceErrorMessagesCount+"\n"+sourceErrorMessages);
- System.err.println("Source Compilation: Weaving count = "+sourceWeaveMessagesCount+"\n"+sourceWeaveMessages);
- }
-
- // Do separate compiles of the classes then the aspects then do a binary weave
-
- // Execute: "ajc <classes> -g -d classes"
- result = ajc(testBase,mergeOptions(classes,new String[]{"-g","-d","classes"}));
- setShouldEmptySandbox(false);
- // Execute: "ajc <aspects> -g -outjar aspects.jar -classpath classes -proceedOnError"
- result = ajc(testBase,mergeOptions(aspects,new String[]{"-g","-outjar","aspects.jar","-classpath","classes","-proceedOnError"}));
- if (result.getErrorMessages().size()!=0) System.err.println("Expecting no errors from jar building but got\n"+result.getErrorMessages());
- assertTrue("Should get no errors for this compile, but got: "+result.getErrorMessages().size(),result.getErrorMessages().size()==0);
- // Execute: "ajc -inpath classes -showWeaveInfo -d classes2 -aspectpath aspects.jar"
- result = ajc(testBase,new String[]{"-inpath","classes","-showWeaveInfo","-d","classes2","-aspectpath","aspects.jar"});
-
- if (!expectErrors) assertTrue("unexpected errors? \n"+result.getErrorMessages(),!result.hasErrorMessages());
-
- List binaryWeaveMessages = getWeaveMessages(result);
- int binaryWeaveMessagesCount = binaryWeaveMessages.size();
- List binaryErrorMessages = result.getErrorMessages();
- int binaryErrorMessagesCount = binaryErrorMessages.size();
-
- if (verbose) {
- System.err.println("Binary Compilation: Error count = "+binaryErrorMessagesCount+"\n"+binaryErrorMessages);
- System.err.println("Binary Compilation: Weaving count = "+binaryWeaveMessagesCount+"\n"+binaryWeaveMessages);
- System.err.println("StandardError from final binary compile stage: "+result.getStandardError());
- }
-
- assertTrue("Should have same number of errors in either case: "+sourceErrorMessagesCount+"!="+binaryErrorMessagesCount,
- sourceErrorMessagesCount==binaryErrorMessagesCount);
-
- /////////////////////////////////////////////////////////////////////////////
- // Check the error messages are comparable (allow for differing orderings)
- if (compareErrors) {
- for (Iterator iter = binaryErrorMessages.iterator(); iter.hasNext();) {
- IMessage binaryMessage = (IMessage) iter.next();
- IMessage correctSourceMessage = null;
- for (Iterator iterator = sourceErrorMessages.iterator(); iterator.hasNext() && correctSourceMessage==null;) {
- IMessage sourceMessage = (IMessage) iterator.next();
-
- if (sourceMessage.getMessage().equals(binaryMessage.getMessage())) {
- correctSourceMessage = sourceMessage;
- }
+
+ private static final boolean verbose = false;
+
+ public static final String PROJECT_DIR = "binaryParents";
+
+ private File baseDir;
+
+ /**
+ * Check the order doesn't make a difference. (order1)
+ */
+ public void testVerifyOrderOfProcessingIrrelevant1() {
+ File testBase = new File(baseDir, "TestA");
+ runSourceAndBinaryTestcase(testBase, new String[] { "Z.java", "B.java" }, new String[] { "AspectAB.aj" }, false);
+ // runClass("B");
+ }
+
+ /**
+ * Check the order doesn't make a difference. (order2)
+ */
+ public void testVerifyOrderOfProcessingIrrelevant2() {
+ File testBase = new File(baseDir, "TestA");
+ runSourceAndBinaryTestcase(testBase, new String[] { "B.java", "Z.java" }, new String[] { "AspectAB.aj" }, false);
+ // runClass("B");
+ }
+
+ /**
+ * Three classes: Top1, Middle1, Bottom1. Bottom1 extends Top1. Middle1 extends Top1. AspectX1: declares Bottom1 extends Middle1
+ * Result: Should be OK, fits into the hierarchy no problem.
+ */
+ public void testSimpleDeclareParents() {
+ File testBase = new File(baseDir, "TestA");
+ runSourceAndBinaryTestcase(testBase, new String[] { "Top1.java", "Middle1.java", "Bottom1.java" },
+ new String[] { "AspectX1.java" }, false);
+ // runClass("Bottom1");
+ }
+
+ /**
+ * Three classes: Top2, Middle2, Bottom2. Bottom2 extends Top2. Middle2 extends Top2. Bottom2 includes a call to super in a
+ * ctor. AspectX2: declares Bottom2 extends Middle2 Result: Should be OK, fits into the hierarchy no problem. Implementation:
+ * The super call should be modified from a Top2.<init> call to a Middle2.<init> call
+ */
+ public void test_SuperCtorCall() {
+ File testBase = new File(baseDir, "TestA");
+ runSourceAndBinaryTestcase(testBase, new String[] { "Top2.java", "Middle2.java", "Bottom2.java" },
+ new String[] { "AspectX2.java" }, false);
+ // runClass("Bottom2");
+ }
+
+ /**
+ * Three classes: Top3, Middle3, Bottom3. Bottom3 extends Top3. Middle3 extends Top3. Bottom3 includes a call to a super method
+ * in an instance method. AspectX3: declares Bottom3 extends Middle3 Result: Should be OK. Implementation: We don't modify the
+ * call to Top3.m() that is in the Bottom3 class, we don't have to because the JVM will ensure that the m() chosen at runtime is
+ * the one nearest the Bottom3 class - when the hierarchy has changed this will be the Middle3.m() version and so it all works.
+ * IMPORTANT: This leaves a subtle difference in the code generated from decp application at source time and decp application at
+ * weave time - in the source time case the call in Bottom3 will have been set to Middle3.m() during code gen, whereas in the
+ * weave time case it will still say Top3.m() - I'm not sure this makes any practical difference though? We could easily fix it
+ * and morph the Top3.m() call to a Middle3.m() call but it would impact peformance crawling through all the bytecodes to make
+ * this change.
+ */
+ public void test_SuperMethodCall() {
+ File testBase = new File(baseDir, "TestA");
+ runSourceAndBinaryTestcase(testBase, new String[] { "Top3.java", "Middle3.java", "Bottom3.java" },
+ new String[] { "AspectX3.java" }, false);
+ // runClass("Bottom3");
+ }
+
+ /**
+ * Three classes: Top4, Middle4, Bottom4. Bottom4 extends Top4. Middle4 extends Top4. AspectX4: declares Bottom4 extends Middle4
+ * Result: Should fail - because Middle4 doesn't include a ctor that takes a String, which is called by Bottom4
+ */
+ public void test_missingCtorInIntroducedClass() {
+ File testBase = new File(baseDir, "TestA");
+ runSourceAndBinaryTestcase(testBase, new String[] { "Top4.java", "Middle4.java", "Bottom4.java" },
+ new String[] { "AspectX4.java" }, true, false);
+ }
+
+ /**
+ * If overriding an instance method, can't make it static. If overriding a static method, can't make it an instance method.
+ *
+ * Note: Error messages and locations for binary weaving are much better than their source counterparts !
+ */
+ public void test_cantMakeInheritedInstanceMethodsStatic() {
+ File testBase = new File(baseDir, "TestC");
+ runSourceAndBinaryTestcase(new File(baseDir, "TestC"), new String[] { "A1.java", "B1.java" }, new String[] { "X1.java" },
+ true, false);
+ }
+
+ /**
+ * Cannot extend a final class
+ */
+ public void xxxtest_cantExtendFinalClass() { // XXX removed test, need to discuss with andy how to repair...
+ File testBase = new File(baseDir, "TestC");
+ runSourceAndBinaryTestcase(new File(baseDir, "TestC"), new String[] { "A2.java", "B2.java" }, new String[] { "X2.java" },
+ true, true);
+ }
+
+ /**
+ * The Object class cannot be subject to declare parents extends
+ *
+ * This is tested when the aspect is compiled - so couldn't occur during binary weaving of decp.
+ */
+
+ /**
+ * if you inherit methods you cannot override them and reduce their visibility
+ */
+ public void test_cantReduceVisibilityOfOverriddenMethods_1() {
+ File testBase = new File(baseDir, "TestB");
+ runSourceAndBinaryTestcase(new File(baseDir, "TestB"), new String[] { "Top1.java", "Middle1.java" },
+ new String[] { "Aspect1.java" }, true, false);
+ }
+
+ /**
+ * if you inherit methods you cannot override them and reduce their visibility.
+ *
+ * test 2 in this set checks methods from a superclass of the named new parent.
+ */
+ public void test_cantReduceVisibilityOfOverriddenMethods_2() {
+ File testBase = new File(baseDir, "TestB");
+ runSourceAndBinaryTestcase(new File(baseDir, "TestB"), new String[] { "TopTop6.java", "Top6.java", "Middle6.java" },
+ new String[] { "Aspect6.java" }, true, false);
+ }
+
+ /**
+ * If you inherit methods you cannot have incompatible return types (java1.5 will make this a little messier).
+ */
+ public void test_overriddenMethodsCantHaveIncompatibleReturnTypes() {
+ File testBase = new File(baseDir, "TestB");
+ CompilationResult result = null;
+ runSourceAndBinaryTestcase(new File(baseDir, "TestB"),
+ new String[] { "Top2.java", "Middle2.java", "Super.java", "Sub.java" }, new String[] { "Aspect2.java" }, true);
+ }
+
+ /**
+ * Testing: If you inherit abstract methods and you are not abstract you need to provide an implementation.
+ *
+ * Test 1 in this set is simple.
+ */
+ public void test_inheritedAbstractMethodsMustBeImplemented_1() {
+ File testBase = new File(baseDir, "TestB");
+ CompilationResult result = null;
+ runSourceAndBinaryTestcase(new File(baseDir, "TestB"),
+ new String[] { "Top3.java", "Middle3.java", "Super.java", "Sub.java" }, new String[] { "Aspect3.java" }, true);
+ }
+
+ /**
+ * Testing: If the decp makes you implement an interface, you must provide the implementation
+ */
+ public void test_interfaceMethodsImplemented() {
+ File testBase = new File(baseDir, "TestD");
+ CompilationResult result = null;
+ runSourceAndBinaryTestcase(testBase, new String[] { "SimpleClass1.java", "SimpleIntf1.java" },
+ new String[] { "SimpleAspect1.java" }, true);
+ }
+
+ /**
+ * Testing: If you inherit abstract methods and you are not abstract you need to provide an implementation.
+ *
+ * Test 2 in this set includes methods further up the hierarchy that must be implemented.
+ */
+ public void test_inheritedAbstractMethodsMustBeImplemented_2() {
+ File testBase = new File(baseDir, "TestB");
+ CompilationResult result = null;
+ runSourceAndBinaryTestcase(new File(baseDir, "TestB"), new String[] { "TopTop4.java", "Top4.java", "Middle4.java" },
+ new String[] { "Aspect4.java" }, true);
+ }
+
+ /**
+ * Testing: If you inherit abstract methods and you are not abstract you need to provide an implementation.
+ *
+ * Test 3 in this set includes methods further up the hierarchy that must be implemented *and* the dependencies are satisfied by
+ * ITDs from the aspect
+ */
+ public void test_inheritedAbstractMethodsMustBeImplemented_3() {
+ File testBase = new File(baseDir, "TestD");
+ CompilationResult result = null;
+ runSourceAndBinaryTestcase(new File(baseDir, "TestD"), new String[] { "SimpleClass2.java" },
+ new String[] { "SimpleAspect2.java" }, true);
+ }
+
+ /**
+ * If adding a type into a hierarchy, any missing ctor could be added via an ITDC so allow for that !
+ */
+ public void test_missingCtorAddedViaITD() {
+ File testBase = new File(baseDir, "TestE");
+ CompilationResult result = null;
+ runSourceAndBinaryTestcase(testBase, new String[] { "A.java", "B.java", "C.java" }, new String[] { "X.java" }, true);
+ }
+
+ // ////////////////////////////////////////////////////////////////////////////////////////
+ // ////////////////////////////////////////////////////////////////////////////////////////
+ // ////////////////////////////////////////////////////////////////////////////////////////
+
+ public void runSourceAndBinaryTestcase(File testBase, String[] classes, String[] aspects, boolean expectErrors) {
+ runSourceAndBinaryTestcase(testBase, classes, aspects, expectErrors, true);
+ }
+
+ public void runSourceAndBinaryTestcase(File testBase, String[] classes, String[] aspects, boolean expectErrors,
+ boolean compareErrors) {
+ // Do a compile of everything together from source ...
+ CompilationResult result = null;
+
+ // Execute: "ajc <classes> <aspects> -showWeaveInfo"
+ String[] sourceCompileCommandLine = new String[classes.length + aspects.length + 1];
+ System.arraycopy(classes, 0, sourceCompileCommandLine, 0, classes.length);
+ System.arraycopy(aspects, 0, sourceCompileCommandLine, classes.length, aspects.length);
+ String[] extraOption = new String[] { "-showWeaveInfo" };
+ System.arraycopy(extraOption, 0, sourceCompileCommandLine, classes.length + aspects.length, 1);
+ result = ajc(testBase, sourceCompileCommandLine);
+ if (!expectErrors)
+ assertTrue("errors? \n" + result.getErrorMessages(), !result.hasErrorMessages());
+ List sourceWeaveMessages = getWeaveMessages(result);
+ int sourceWeaveMessagesCount = sourceWeaveMessages.size();
+ List sourceErrorMessages = result.getErrorMessages();
+ int sourceErrorMessagesCount = sourceErrorMessages.size();
+
+ if (verbose) {
+ System.err.println("Source Compilation: Error count = " + sourceErrorMessagesCount + "\n" + sourceErrorMessages);
+ System.err.println("Source Compilation: Weaving count = " + sourceWeaveMessagesCount + "\n" + sourceWeaveMessages);
+ }
+
+ // Do separate compiles of the classes then the aspects then do a binary weave
+
+ // Execute: "ajc <classes> -g -d classes"
+ result = ajc(testBase, mergeOptions(classes, new String[] { "-g", "-d", "classes" }));
+ setShouldEmptySandbox(false);
+ // Execute: "ajc <aspects> -g -outjar aspects.jar -classpath classes -proceedOnError"
+ result = ajc(testBase, mergeOptions(aspects, new String[] { "-g", "-outjar", "aspects.jar", "-classpath", "classes",
+ "-proceedOnError" }));
+ if (result.getErrorMessages().size() != 0)
+ System.err.println("Expecting no errors from jar building but got\n" + result.getErrorMessages());
+ assertTrue("Should get no errors for this compile, but got: " + result.getErrorMessages().size(), result.getErrorMessages()
+ .size() == 0);
+ // Execute: "ajc -inpath classes -showWeaveInfo -d classes2 -aspectpath aspects.jar"
+ result = ajc(testBase, new String[] { "-inpath", "classes", "-showWeaveInfo", "-d", "classes2", "-aspectpath",
+ "aspects.jar" });
+
+ if (!expectErrors)
+ assertTrue("unexpected errors? \n" + result.getErrorMessages(), !result.hasErrorMessages());
+
+ List binaryWeaveMessages = getWeaveMessages(result);
+ int binaryWeaveMessagesCount = binaryWeaveMessages.size();
+ List binaryErrorMessages = result.getErrorMessages();
+ int binaryErrorMessagesCount = binaryErrorMessages.size();
+
+ if (verbose) {
+ System.err.println("Binary Compilation: Error count = " + binaryErrorMessagesCount + "\n" + binaryErrorMessages);
+ System.err.println("Binary Compilation: Weaving count = " + binaryWeaveMessagesCount + "\n" + binaryWeaveMessages);
+ System.err.println("StandardError from final binary compile stage: " + result.getStandardError());
+ }
+
+ assertTrue("Should have same number of errors in either case: " + sourceErrorMessagesCount + "!="
+ + binaryErrorMessagesCount, sourceErrorMessagesCount == binaryErrorMessagesCount);
+
+ // ///////////////////////////////////////////////////////////////////////////
+ // Check the error messages are comparable (allow for differing orderings)
+ if (compareErrors) {
+ for (Iterator iter = binaryErrorMessages.iterator(); iter.hasNext();) {
+ IMessage binaryMessage = (IMessage) iter.next();
+ IMessage correctSourceMessage = null;
+ for (Iterator iterator = sourceErrorMessages.iterator(); iterator.hasNext() && correctSourceMessage == null;) {
+ IMessage sourceMessage = (IMessage) iterator.next();
+
+ if (sourceMessage.getMessage().equals(binaryMessage.getMessage())) {
+ correctSourceMessage = sourceMessage;
+ }
+ }
+ if (correctSourceMessage == null) {
+ fail("This error obtained during binary weaving '" + binaryMessage
+ + "' has no equivalent in the list of messages from source compilation");
+ }
+ sourceErrorMessages.remove(correctSourceMessage);
+ }
+ if (sourceErrorMessages.size() > 0) {
+ for (Iterator iter = sourceErrorMessages.iterator(); iter.hasNext();) {
+ IMessage srcMsg = (IMessage) iter.next();
+ System.err.println("This error message from source compilation '" + srcMsg
+ + "' didn't occur during binary weaving.");
+ }
+ fail("Got " + sourceErrorMessages.size() + " extra error messages during source compilation");
+ }
+ }
+
+ // //////////////////////////////////////////////////////////////////////////
+ // Check the weaving messages are comparable
+ if (sourceWeaveMessagesCount != binaryWeaveMessagesCount) {
+ fail("Didn't get same number of weave info messages when source weaving and binary weaving: "
+ + sourceWeaveMessagesCount + "!=" + binaryWeaveMessagesCount);
+ }
+
+ // Check weaving messages are comparable
+ for (int i = 0; i < sourceWeaveMessages.size(); i++) {
+ IMessage m1 = (IMessage) sourceWeaveMessages.get(i);
+ IMessage m2 = (IMessage) binaryWeaveMessages.get(i);
+ String s1 = m1.getDetails();
+ String s2 = m2.getDetails();
+
+ if (!s1.equals(s2)) {
+ System.err.println("Source Weave Messages: #" + sourceWeaveMessages.size() + "\n" + sourceWeaveMessages);
+ System.err.println("Binary Weave Messages: #" + binaryWeaveMessages.size() + "\n" + binaryWeaveMessages);
+ fail("Two weaving messages aren't the same?? sourceMessage=[" + s1 + "] binaryMessage=[" + s2 + "]");
+ }
+ if (m1.getSourceLocation() != null || m2.getSourceLocation() != null) {
+ if (!m1.getSourceLocation().equals(m2.getSourceLocation())) {
+ fail("Different source locations for weaving messages? \n" + m1.getSourceLocation() + "\n"
+ + m2.getSourceLocation());
+ }
+ }
+ }
+
+ // // Check the result of binary weaving !
+ // ClassPath cp = new ClassPath(ajc.getSandboxDirectory()+File.separator+"classes2"+
+ // File.pathSeparator+System.getProperty("sun.boot.class.path"));
+ // System.err.println(cp);
+ // SyntheticRepository r = SyntheticRepository.getInstance(cp);
+ // Repository.setRepository(r);
+ // for (int i = 0; i < classes.length; i++) {
+ // String name = classes[i].substring(0,classes[i].lastIndexOf("."));
+ // List verificationProblems = verify(name);
+ // assertTrue("Did not expect any verification problems for class: "+name+": \n"+verificationProblems,verificationProblems.
+ // size()==0);
+ // }
+ }
+
+ public String[] mergeOptions(String[] input, String[] extras) {
+ String[] ret = new String[input.length + extras.length];
+ System.arraycopy(input, 0, ret, 0, input.length);
+ System.arraycopy(extras, 0, ret, input.length, extras.length);
+ return ret;
+ }
+
+ private List getWeaveMessages(CompilationResult result) {
+ List infoMessages = result.getInfoMessages();
+ List weaveMessages = new ArrayList();
+ for (Iterator iter = infoMessages.iterator(); iter.hasNext();) {
+ IMessage element = (IMessage) iter.next();
+ if (element.getKind() == IMessage.WEAVEINFO)
+ weaveMessages.add(element);
+ }
+ return weaveMessages;
+ }
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ baseDir = new File("../org.aspectj.ajdt.core/testdata", PROJECT_DIR);
+ }
+
+ private List verify(String name) {
+ List verifyProblems = new ArrayList();
+ System.out.println("Now verifying: " + name + "\n");
+
+ Verifier v = VerifierFactory.getVerifier(name);
+ VerificationResult vr;
+
+ vr = v.doPass1();
+ if (vr != VerificationResult.VR_OK)
+ verifyProblems.add("Pass1: " + vr.getMessage());
+
+ vr = v.doPass2();
+ if (vr != VerificationResult.VR_OK)
+ verifyProblems.add("Pass2: " + vr.getMessage());
+
+ if (vr == VerificationResult.VR_OK) {
+ JavaClass jc = Repository.lookupClass(name);
+ for (int i = 0; i < jc.getMethods().length; i++) {
+ vr = v.doPass3a(i);
+ if (vr != VerificationResult.VR_OK)
+ verifyProblems.add("Pass3a: " + jc.getMethods()[i] + " " + vr.getMessage());
+
+ vr = v.doPass3b(i);
+ if (vr != VerificationResult.VR_OK)
+ verifyProblems.add("Pass3b: " + jc.getMethods()[i] + " " + vr.getMessage());
}
- if (correctSourceMessage == null) {
- fail("This error obtained during binary weaving '"+binaryMessage+"' has no equivalent in the list of messages from source compilation");
- }
- sourceErrorMessages.remove(correctSourceMessage);
- }
- if (sourceErrorMessages.size()>0) {
- for (Iterator iter = sourceErrorMessages.iterator(); iter.hasNext();) {
- IMessage srcMsg = (IMessage) iter.next();
- System.err.println("This error message from source compilation '"+srcMsg+"' didn't occur during binary weaving.");
- }
- fail("Got "+sourceErrorMessages.size()+" extra error messages during source compilation");
- }
- }
-
- ////////////////////////////////////////////////////////////////////////////
- // Check the weaving messages are comparable
- if (sourceWeaveMessagesCount!=binaryWeaveMessagesCount) {
- fail("Didn't get same number of weave info messages when source weaving and binary weaving: "+sourceWeaveMessagesCount+"!="+binaryWeaveMessagesCount);
- }
-
- // Check weaving messages are comparable
- for (int i=0; i<sourceWeaveMessages.size(); i++) {
- IMessage m1 = (IMessage)sourceWeaveMessages.get(i);
- IMessage m2 = (IMessage)binaryWeaveMessages.get(i);
- String s1 = m1.getDetails();
- String s2 = m2.getDetails();
-
- if (!s1.equals(s2)) {
- System.err.println("Source Weave Messages: #"+sourceWeaveMessages.size()+"\n"+sourceWeaveMessages);
- System.err.println("Binary Weave Messages: #"+binaryWeaveMessages.size()+"\n"+binaryWeaveMessages);
- fail("Two weaving messages aren't the same?? sourceMessage=["+s1+"] binaryMessage=["+s2+"]");
- }
- if (m1.getSourceLocation()!=null || m2.getSourceLocation()!=null) {
- if (!m1.getSourceLocation().equals(m2.getSourceLocation())) {
- fail("Different source locations for weaving messages? \n"+m1.getSourceLocation()+"\n"+m2.getSourceLocation()) ;
- }
- }
- }
-
-// // Check the result of binary weaving !
-// ClassPath cp = new ClassPath(ajc.getSandboxDirectory()+File.separator+"classes2"+
-// File.pathSeparator+System.getProperty("sun.boot.class.path"));
-// System.err.println(cp);
-// SyntheticRepository r = SyntheticRepository.getInstance(cp);
-// Repository.setRepository(r);
-// for (int i = 0; i < classes.length; i++) {
-// String name = classes[i].substring(0,classes[i].lastIndexOf("."));
-// List verificationProblems = verify(name);
-// assertTrue("Did not expect any verification problems for class: "+name+": \n"+verificationProblems,verificationProblems.size()==0);
-// }
- }
-
- public String[] mergeOptions(String[] input,String[] extras) {
- String[] ret = new String[input.length+extras.length];
- System.arraycopy(input,0,ret,0,input.length);
- System.arraycopy(extras,0,ret,input.length,extras.length);
- return ret;
- }
-
-
-
-
- private List getWeaveMessages(CompilationResult result) {
- List infoMessages = result.getInfoMessages();
- List weaveMessages = new ArrayList();
- for (Iterator iter = infoMessages.iterator(); iter.hasNext();) {
- IMessage element = (IMessage) iter.next();
- if (element.getKind()== IMessage.WEAVEINFO) weaveMessages.add(element);
- }
- return weaveMessages;
- }
-
-
- protected void setUp() throws Exception {
- super.setUp();
- baseDir = new File("../org.aspectj.ajdt.core/testdata",PROJECT_DIR);
- }
-
- private List verify(String name) {
- List verifyProblems = new ArrayList();
- System.out.println("Now verifying: "+name+"\n");
-
- Verifier v = VerifierFactory.getVerifier(name);
- VerificationResult vr;
-
- vr = v.doPass1();
- if (vr != VerificationResult.VR_OK) verifyProblems.add("Pass1: "+vr.getMessage());
-
- vr = v.doPass2();
- if (vr != VerificationResult.VR_OK) verifyProblems.add("Pass2: "+vr.getMessage());
-
- if (vr == VerificationResult.VR_OK){
- JavaClass jc = Repository.lookupClass(name);
- for (int i=0; i<jc.getMethods().length; i++){
- vr = v.doPass3a(i);
- if (vr != VerificationResult.VR_OK) verifyProblems.add("Pass3a: "+jc.getMethods()[i]+" "+vr.getMessage());
-
- vr = v.doPass3b(i);
- if (vr != VerificationResult.VR_OK) verifyProblems.add("Pass3b: "+jc.getMethods()[i]+" "+vr.getMessage());
- }
- }
-
- System.out.println("Warnings:");
- String[] warnings = v.getMessages();
- if (warnings.length == 0) System.out.println("<none>");
- for (int j=0; j<warnings.length; j++){
- System.out.println(warnings[j]);
- }
-
- System.out.println("\n");
-
- // avoid swapping.
- v.flush();
- Repository.clearCache();
- return verifyProblems;
- }
-
- private void runClass(String name) {
- RunResult rr = null;
- try {
- rr = run(name,new String[]{},ajc.getSandboxDirectory()+File.separator+"classes2");
- } catch (VerifyError ve) {
- ve.printStackTrace();
- fail("Unexpected VerifyError for type upon which we declared parents");
- }
- //assertTrue("Didn't expect any errors from the run of "+name+", but got: "+rr.toString(),rr.get);
- }
-
+ }
+
+ System.out.println("Warnings:");
+ String[] warnings = v.getMessages();
+ if (warnings.length == 0)
+ System.out.println("<none>");
+ for (int j = 0; j < warnings.length; j++) {
+ System.out.println(warnings[j]);
+ }
+
+ System.out.println("\n");
+
+ // avoid swapping.
+ v.flush();
+ Repository.clearCache();
+ return verifyProblems;
+ }
+
+ private void runClass(String name) {
+ RunResult rr = null;
+ try {
+ rr = run(name, new String[] {}, ajc.getSandboxDirectory() + File.separator + "classes2");
+ } catch (VerifyError ve) {
+ ve.printStackTrace();
+ fail("Unexpected VerifyError for type upon which we declared parents");
+ }
+ // assertTrue("Didn't expect any errors from the run of "+name+", but got: "+rr.toString(),rr.get);
+ }
+
}
diff --git a/org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/ProceedOnErrorTestCase.java b/org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/ProceedOnErrorTestCase.java
index 5e353cc3c..70d42bf4a 100644
--- a/org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/ProceedOnErrorTestCase.java
+++ b/org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/internal/compiler/batch/ProceedOnErrorTestCase.java
@@ -16,59 +16,53 @@ import java.io.File;
import java.io.IOException;
import java.util.Date;
-import org.aspectj.ajdt.internal.core.builder.AjBuildManager;
-
-
public class ProceedOnErrorTestCase extends CommandTestCase {
public ProceedOnErrorTestCase(String name) {
super(name);
}
- /**
- * Compile C1.java that defines C.class then compile C2.java which contains another version of C.class but also
- * contains errors. Because -proceedOnError is not supplied, the .class file should not be touched when compiling
- * C2.java.
+ /**
+ * Compile C1.java that defines C.class then compile C2.java which contains another version of C.class but also contains errors.
+ * Because -proceedOnError is not supplied, the .class file should not be touched when compiling C2.java.
*/
public void testNoProceedOnError() throws IOException {
-// try {
-// AjBuildManager.continueWhenErrors=false;
- checkCompile("src1/C1.java", NO_ERRORS);
- File f =new File(getSandboxName(),"C.class");
- long oldmodtime = f.lastModified();
- pause(2);
- checkCompile("src1/C2.java", new int[]{1});
- f =new File(getSandboxName(),"C.class");
- long newmodtime = f.lastModified();
- // Without -proceedOnError supplied, we should *not* change the time stamp on the .class file
- assertTrue("The .class file should not have been modified as '-proceedOnError' was not supplied (old="+
- new Date(oldmodtime).toString()+")(new="+new Date(newmodtime).toString()+")",
- oldmodtime==newmodtime);
-// } finally {
-// AjBuildManager.continueWhenErrors=true;
-// }
+ // try {
+ // AjBuildManager.continueWhenErrors=false;
+ checkCompile("src1/C1.java", NO_ERRORS);
+ File f = new File(getSandboxName(), "C.class");
+ long oldmodtime = f.lastModified();
+ pause(2);
+ checkCompile("src1/C2.java", new int[] { 1 });
+ f = new File(getSandboxName(), "C.class");
+ long newmodtime = f.lastModified();
+ // Without -proceedOnError supplied, we should *not* change the time stamp on the .class file
+ assertTrue("The .class file should not have been modified as '-proceedOnError' was not supplied (old="
+ + new Date(oldmodtime).toString() + ")(new=" + new Date(newmodtime).toString() + ")", oldmodtime == newmodtime);
+ // } finally {
+ // AjBuildManager.continueWhenErrors=true;
+ // }
}
public void testProceedOnError() throws IOException {
checkCompile("src1/C1.java", NO_ERRORS);
- File f =new File(getSandboxName(),"C.class");
- long oldmodtime = f.lastModified();
- pause(2);
- String sandboxName = getSandboxName();
- checkCompile("src1/C2.java",new String[]{"-proceedOnError"}, new int[]{1}, sandboxName);
- f =new File(sandboxName,"C.class");
- long newmodtime = f.lastModified();
- // Without -proceedOnError supplied, we should *not* change the time stamp on the .class file
- assertTrue("The .class file should have been modified as '-proceedOnError' *was* supplied (old="+
- new Date(oldmodtime).toString()+")(new="+new Date(newmodtime).toString()+")",
- newmodtime>oldmodtime);
- }
-
-
+ File f = new File(getSandboxName(), "C.class");
+ long oldmodtime = f.lastModified();
+ pause(2);
+ String sandboxName = getSandboxName();
+ checkCompile("src1/C2.java", new String[] { "-proceedOnError" }, new int[] { 1 }, sandboxName);
+ f = new File(sandboxName, "C.class");
+ long newmodtime = f.lastModified();
+ // Without -proceedOnError supplied, we should *not* change the time stamp on the .class file
+ assertTrue("The .class file should have been modified as '-proceedOnError' *was* supplied (old="
+ + new Date(oldmodtime).toString() + ")(new=" + new Date(newmodtime).toString() + ")", newmodtime > oldmodtime);
+ }
+
private void pause(int secs) {
try {
- Thread.sleep(secs*1000);
- } catch (InterruptedException ie) {}
+ Thread.sleep(secs * 1000);
+ } catch (InterruptedException ie) {
+ }
}
-
+
}
diff --git a/org.aspectj.ajdt.core/testsrc/org/aspectj/tools/ajc/AjASTTest.java b/org.aspectj.ajdt.core/testsrc/org/aspectj/tools/ajc/AjASTTest.java
index 9f7011c61..ba7196de5 100644
--- a/org.aspectj.ajdt.core/testsrc/org/aspectj/tools/ajc/AjASTTest.java
+++ b/org.aspectj.ajdt.core/testsrc/org/aspectj/tools/ajc/AjASTTest.java
@@ -68,344 +68,306 @@ import org.aspectj.org.eclipse.jdt.core.dom.TypePattern;
/**
* For each AspectJ ASTNode there is a test for:
*
- * - that a new instance can be created via ajast.newXXX()
- * - that the property descriptors have been set correctly
- * - that the get/set methods for the different properties
- * work as expected
- * - that the clone0 method sets the correct properties
- * - that the internalStructuralPropertiesForType(int) and
- * internalGetSetXXXProperty(..) methods have been implemented
- * correctly
- *
- * These are all that is required for an ASTNode, except an
- * implementation of the accept0() method which is tested
- * in ASTVisitorTest.
+ * - that a new instance can be created via ajast.newXXX() - that the property descriptors have been set correctly - that the
+ * get/set methods for the different properties work as expected - that the clone0 method sets the correct properties - that the
+ * internalStructuralPropertiesForType(int) and internalGetSetXXXProperty(..) methods have been implemented correctly
+ *
+ * These are all that is required for an ASTNode, except an implementation of the accept0() method which is tested in
+ * ASTVisitorTest.
*/
public class AjASTTest extends AjASTTestCase {
-
+
// -------------- DefaultPointcut tests ---------------
-
+
public void testNewDefaultPointcut() {
AjAST ajast = createAjAST();
DefaultPointcut p = ajast.newDefaultPointcut();
- assertNotNull("a new DefaultPointcut should have been created",p);
+ assertNotNull("a new DefaultPointcut should have been created", p);
}
public void testGetAndSetDetail() {
AjAST ajast = createAjAST();
DefaultPointcut p = ajast.newDefaultPointcut();
- assertEquals("The default detail should be the empty string","",p.getDetail());
+ assertEquals("The default detail should be the empty string", "", p.getDetail());
p.setDetail("some detail");
- assertEquals("The detail should now be 'some detail'","some detail",p.getDetail());
+ assertEquals("The detail should now be 'some detail'", "some detail", p.getDetail());
}
-
+
// -------------- ReferencePointcut tests ---------------
public void testNewReferencePointcut() {
AjAST ajast = createAjAST();
ReferencePointcut p = ajast.newReferencePointcut();
- assertNotNull("a new ReferencePointcut should have been created",p);
+ assertNotNull("a new ReferencePointcut should have been created", p);
}
-
+
/**
- * ReferencePointcut's have a name property - tests
- * the getting and setting of this property
+ * ReferencePointcut's have a name property - tests the getting and setting of this property
*/
public void testGetAndSetRefPointcutName() {
AjAST ajast = createAjAST();
ReferencePointcut p = ajast.newReferencePointcut();
- assertEquals("the default reference pointcut name should be MISSING",
- "MISSING",p.getName().getFullyQualifiedName());
+ assertEquals("the default reference pointcut name should be MISSING", "MISSING", p.getName().getFullyQualifiedName());
p.setName(ajast.newSimpleName("refPointcutName"));
- assertEquals("the pointcut name should now be set to 'refPointcutName'",
- "refPointcutName",p.getName().getFullyQualifiedName());
+ assertEquals("the pointcut name should now be set to 'refPointcutName'", "refPointcutName", p.getName()
+ .getFullyQualifiedName());
}
-
+
public void testNewAndPointcut() {
AjAST ajast = createAjAST();
AndPointcut p = ajast.newAndPointcut();
- assertNotNull("a new AndPointcut should have been created",p);
+ assertNotNull("a new AndPointcut should have been created", p);
}
-
+
// -------------- AndPointcut tests ---------------
/**
- * AndPointcut's have a left property - test the getting
- * and setting of this property
+ * AndPointcut's have a left property - test the getting and setting of this property
*/
public void testGetAndSetLeftOfAndPointcut() {
AjAST ajast = createAjAST();
AndPointcut ap = ajast.newAndPointcut();
- assertNull("by default the left side of an AndPointcut should be null",
- ap.getLeft());
+ assertNull("by default the left side of an AndPointcut should be null", ap.getLeft());
ReferencePointcut p = ajast.newReferencePointcut();
ap.setLeft(p);
- assertEquals("the left side of the AndPointcut should now be the" +
- " ReferencePointcut",p,ap.getLeft());
+ assertEquals("the left side of the AndPointcut should now be the" + " ReferencePointcut", p, ap.getLeft());
}
-
+
/**
- * AndPointcut's have a right property - test the getting
- * and setting of this property
- */
+ * AndPointcut's have a right property - test the getting and setting of this property
+ */
public void testGetAndSetRightOfAndPointcut() {
AjAST ajast = createAjAST();
AndPointcut ap = ajast.newAndPointcut();
- assertNull("by default the right side of an AndPointcut should be null",
- ap.getRight());
+ assertNull("by default the right side of an AndPointcut should be null", ap.getRight());
ReferencePointcut p = ajast.newReferencePointcut();
ap.setRight(p);
- assertEquals("the right side of the AndPointcut should now be the" +
- " ReferencePointcut",p,ap.getRight());
+ assertEquals("the right side of the AndPointcut should now be the" + " ReferencePointcut", p, ap.getRight());
}
-
+
// -------------- CflowPointcut tests ---------------
public void testNewCflowPointcut() {
AjAST ajast = createAjAST();
CflowPointcut p = ajast.newCflowPointcut();
- assertNotNull("a new CflowPointcut should have been created",p);
+ assertNotNull("a new CflowPointcut should have been created", p);
}
-
+
/**
- * CflowPointcut's have a body property - test the getting
- * and setting of this property
+ * CflowPointcut's have a body property - test the getting and setting of this property
*/
public void testGetAndSetBodyOfCflowPointcut() {
AjAST ajast = createAjAST();
CflowPointcut p = ajast.newCflowPointcut();
- assertNull("by default a CflowPointcut should have a null body",p.getBody());
+ assertNull("by default a CflowPointcut should have a null body", p.getBody());
ReferencePointcut rp = ajast.newReferencePointcut();
p.setBody(rp);
- assertEquals("the body of the CflowPointcut should now be a " +
- "ReferencePointcut", rp, p.getBody());
+ assertEquals("the body of the CflowPointcut should now be a " + "ReferencePointcut", rp, p.getBody());
}
-
+
// -------------- NotPointcut tests ---------------
public void testNewNotPointcut() {
AjAST ajast = createAjAST();
NotPointcut p = ajast.newNotPointcut();
- assertNotNull("a new NotPointcut should have been created",p);
+ assertNotNull("a new NotPointcut should have been created", p);
}
-
+
/**
- * NotPointcut's have a body property - test the getting
- * and setting of this property
+ * NotPointcut's have a body property - test the getting and setting of this property
*/
public void testGetAndSetBodyOfNotPointcut() {
AjAST ajast = createAjAST();
NotPointcut p = ajast.newNotPointcut();
- assertNull("by default a NotPointcut should have a null body",p.getBody());
+ assertNull("by default a NotPointcut should have a null body", p.getBody());
ReferencePointcut rp = ajast.newReferencePointcut();
p.setBody(rp);
- assertEquals("the body of the NotPointcut should now be a " +
- "ReferencePointcut", rp, p.getBody());
+ assertEquals("the body of the NotPointcut should now be a " + "ReferencePointcut", rp, p.getBody());
}
-
+
// -------------- OrPointcut tests ---------------
public void testNewOrPointcut() {
AjAST ajast = createAjAST();
OrPointcut p = ajast.newOrPointcut();
- assertNotNull("a new OrPointcut should have been created",p);
+ assertNotNull("a new OrPointcut should have been created", p);
}
-
+
/**
- * OrPointcut's have a left property - test the getting
- * and setting of this property
+ * OrPointcut's have a left property - test the getting and setting of this property
*/
public void testGetAndSetLeftOfOrPointcut() {
AjAST ajast = createAjAST();
OrPointcut op = ajast.newOrPointcut();
- assertNull("by default the left side of an OrPointcut should be null",
- op.getLeft());
+ assertNull("by default the left side of an OrPointcut should be null", op.getLeft());
ReferencePointcut p = ajast.newReferencePointcut();
op.setLeft(p);
- assertEquals("the left side of the OrPointcut should now be the" +
- " ReferencePointcut",p,op.getLeft());
+ assertEquals("the left side of the OrPointcut should now be the" + " ReferencePointcut", p, op.getLeft());
}
-
+
/**
- * OrPointcut's have a right property - test the getting
- * and setting of this property
+ * OrPointcut's have a right property - test the getting and setting of this property
*/
public void testGetAndSetRightOfOrPointcut() {
AjAST ajast = createAjAST();
OrPointcut op = ajast.newOrPointcut();
- assertNull("by default the right side of an OrPointcut should be null",
- op.getRight());
+ assertNull("by default the right side of an OrPointcut should be null", op.getRight());
ReferencePointcut p = ajast.newReferencePointcut();
op.setRight(p);
- assertEquals("the right side of the OrPointcut should now be the" +
- " ReferencePointcut",p,op.getRight());
+ assertEquals("the right side of the OrPointcut should now be the" + " ReferencePointcut", p, op.getRight());
}
-
+
// -------------- PerCflow tests ---------------
public void testNewPerCflow() {
AjAST ajast = createAjAST();
PerCflow p = ajast.newPerCflow();
- assertNotNull("a new PerCflow should have been created",p);
+ assertNotNull("a new PerCflow should have been created", p);
}
-
+
/**
- * PerCflow's have a body property - test the getting
- * and setting of this property
+ * PerCflow's have a body property - test the getting and setting of this property
*/
public void testGetAndSetBodyOfPerCflow() {
AjAST ajast = createAjAST();
PerCflow p = ajast.newPerCflow();
- assertNull("by default a PerCflow should have a null body",p.getBody());
+ assertNull("by default a PerCflow should have a null body", p.getBody());
ReferencePointcut rp = ajast.newReferencePointcut();
p.setBody(rp);
- assertEquals("the body of the PerCflow should now be a " +
- "ReferencePointcut", rp, p.getBody());
+ assertEquals("the body of the PerCflow should now be a " + "ReferencePointcut", rp, p.getBody());
}
-
+
// -------------- PerObject tests ---------------
public void testNewPerObject() {
AjAST ajast = createAjAST();
PerObject p = ajast.newPerObject();
- assertNotNull("a new PerObject should have been created",p);
+ assertNotNull("a new PerObject should have been created", p);
}
-
+
/**
- * PerObject's have a body property - test the getting
- * and setting of this property
+ * PerObject's have a body property - test the getting and setting of this property
*/
public void testGetAndSetBodyOfPerObject() {
AjAST ajast = createAjAST();
PerObject p = ajast.newPerObject();
- assertNull("by default a PerObject should have a null body",p.getBody());
+ assertNull("by default a PerObject should have a null body", p.getBody());
ReferencePointcut rp = ajast.newReferencePointcut();
p.setBody(rp);
- assertEquals("the body of the PerObject should now be a " +
- "ReferencePointcut", rp, p.getBody());
+ assertEquals("the body of the PerObject should now be a " + "ReferencePointcut", rp, p.getBody());
}
-
+
// -------------- PerTypeWithin tests ---------------
public void testNewPerTypeWithin() {
AjAST ajast = createAjAST();
PerTypeWithin p = ajast.newPerTypeWithin();
- assertNotNull("a new PerTypeWithin should have been created",p);
+ assertNotNull("a new PerTypeWithin should have been created", p);
}
-
+
// -------------- DefaultTypePattern tests ---------------
-
+
public void testNewDefaultTypePattern() {
AjAST ajast = createAjAST();
DefaultTypePattern p = ajast.newDefaultTypePattern();
- assertNotNull("a new DefaultTypePattern should have been created",p);
+ assertNotNull("a new DefaultTypePattern should have been created", p);
}
public void testGetAndSetDetailInDefaultTypePattern() {
AjAST ajast = createAjAST();
DefaultTypePattern p = ajast.newDefaultTypePattern();
- assertEquals("The default detail should be the empty string","",p.getDetail());
+ assertEquals("The default detail should be the empty string", "", p.getDetail());
p.setDetail("some detail");
- assertEquals("The detail should now be 'some detail'","some detail",p.getDetail());
+ assertEquals("The detail should now be 'some detail'", "some detail", p.getDetail());
}
-
+
public void testPropertyDescriptorsForDefaultTypePattern() {
AjAST ajast = createAjAST();
DefaultTypePattern d = ajast.newDefaultTypePattern();
List props = DefaultTypePattern.propertyDescriptors(AST.JLS3);
- assertEquals("there should be no properties for the DefaultTypePattern",
- 0,props.size());
+ assertEquals("there should be no properties for the DefaultTypePattern", 0, props.size());
}
-
+
public void testCloneDefaultTypePattern() {
AjAST ajast = createAjAST();
DefaultTypePattern d = ajast.newDefaultTypePattern();
d.setDetail("new detail");
- DefaultTypePattern copy = (DefaultTypePattern)ASTNode.copySubtree(ajast,d);
- assertEquals("the copy should have detail 'new detail'","new detail",copy.getDetail());
+ DefaultTypePattern copy = (DefaultTypePattern) ASTNode.copySubtree(ajast, d);
+ assertEquals("the copy should have detail 'new detail'", "new detail", copy.getDetail());
}
-
+
// -------------- SignaturePattern tests ---------------
-
+
public void testNewSignaturePattern() {
AjAST ajast = createAjAST();
SignaturePattern p = ajast.newSignaturePattern();
- assertNotNull("a new SignaturePattern should have been created",p);
+ assertNotNull("a new SignaturePattern should have been created", p);
}
public void testGetAndSetDetailInSignaturePattern() {
AjAST ajast = createAjAST();
SignaturePattern p = ajast.newSignaturePattern();
- assertEquals("The default detail should be the empty string","",p.getDetail());
+ assertEquals("The default detail should be the empty string", "", p.getDetail());
p.setDetail("some detail");
- assertEquals("The detail should now be 'some detail'","some detail",p.getDetail());
+ assertEquals("The detail should now be 'some detail'", "some detail", p.getDetail());
}
-
+
public void testPropertyDescriptorsForSignaturePattern() {
AjAST ajast = createAjAST();
SignaturePattern p = ajast.newSignaturePattern();
List props = SignaturePattern.propertyDescriptors(AST.JLS3);
- assertEquals("there should be no properties for the DefaultTypePattern",
- 0,props.size());
+ assertEquals("there should be no properties for the DefaultTypePattern", 0, props.size());
}
-
+
public void testCloneDefaultSignaturePattern() {
AjAST ajast = createAjAST();
SignaturePattern p = ajast.newSignaturePattern();
p.setDetail("new detail");
- SignaturePattern copy = (SignaturePattern)ASTNode.copySubtree(ajast,p);
- assertEquals("the copy should have detail 'new detail'","new detail",copy.getDetail());
+ SignaturePattern copy = (SignaturePattern) ASTNode.copySubtree(ajast, p);
+ assertEquals("the copy should have detail 'new detail'", "new detail", copy.getDetail());
}
-
+
// -------------- PointcutDeclaration tests ---------------
public void testNewPointcutDeclaration() {
AjAST ajast = createAjAST();
PointcutDeclaration pd = ajast.newPointcutDeclaration();
- assertNotNull("a new PointcutDeclaration should have been created",pd);
+ assertNotNull("a new PointcutDeclaration should have been created", pd);
}
-
+
/**
- * PointcutDeclarations's have a name property - test the getting
- * and setting of this property
+ * PointcutDeclarations's have a name property - test the getting and setting of this property
*/
public void testGetAndSetPointcutName() {
AjAST ajast = createAjAST();
PointcutDeclaration pd = ajast.newPointcutDeclaration();
- assertEquals("the default pointcut name should be MISSING",
- "MISSING",pd.getName().getFullyQualifiedName());
+ assertEquals("the default pointcut name should be MISSING", "MISSING", pd.getName().getFullyQualifiedName());
pd.setName(ajast.newSimpleName("p"));
- assertEquals("the pointcut name should now be set to 'p'",
- "p",pd.getName().getFullyQualifiedName());
+ assertEquals("the pointcut name should now be set to 'p'", "p", pd.getName().getFullyQualifiedName());
}
-
+
/**
- * PointcutDeclarations's have a designator property - test the getting
- * and setting of this property
+ * PointcutDeclarations's have a designator property - test the getting and setting of this property
*/
public void testGetAndSetPointcutDesignator() {
AjAST ajast = createAjAST();
PointcutDeclaration pd = ajast.newPointcutDeclaration();
- assertNull("by default the pointcut designator is null",pd.getDesignator());
+ assertNull("by default the pointcut designator is null", pd.getDesignator());
ReferencePointcut rp = ajast.newReferencePointcut();
pd.setDesignator(rp);
- assertEquals("should have set the pointcut designator to be " +
- "the ReferencePointcut",rp,pd.getDesignator());
+ assertEquals("should have set the pointcut designator to be " + "the ReferencePointcut", rp, pd.getDesignator());
}
-
- public void testGetAndSetPointcutArguments(){
+
+ public void testGetAndSetPointcutArguments() {
AjAST ajast = createAjAST();
PointcutDeclaration pd = ajast.newPointcutDeclaration();
- assertEquals("by default the number of arguments is zero",pd.parameters().size(), 0);
+ assertEquals("by default the number of arguments is zero", pd.parameters().size(), 0);
List l = pd.parameters();
- assertEquals("there shouldn't be any arguments associated with" +
- "the pointcut yet",0,l.size());
+ assertEquals("there shouldn't be any arguments associated with" + "the pointcut yet", 0, l.size());
SingleVariableDeclaration p1 = ajast.newSingleVariableDeclaration();
l.add(p1);
- assertEquals("there should be one parameter associated with" +
- "the pointcut",1,pd.parameters().size());
- assertEquals("there should be a SingleVariableDeclaration associated with" +
- "the pointcut",p1,pd.parameters().get(0));
+ assertEquals("there should be one parameter associated with" + "the pointcut", 1, pd.parameters().size());
+ assertEquals("there should be a SingleVariableDeclaration associated with" + "the pointcut", p1, pd.parameters().get(0));
}
public void testPropertyDescriptorsForPointcutDeclaration() {
@@ -420,7 +382,7 @@ public class AjASTTest extends AjASTTestCase {
for (Iterator iter = props.iterator(); iter.hasNext();) {
Object o = iter.next();
if ((o instanceof ChildPropertyDescriptor)) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor)o;
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
String id = element.getId();
if (id.equals("javadoc")) {
foundJavadoc = true;
@@ -432,9 +394,9 @@ public class AjASTTest extends AjASTTestCase {
fail("unknown PropertyDescriptor associated with PointcutDeclaration: " + element.getId());
}
} else if (o instanceof ChildListPropertyDescriptor) {
- ChildListPropertyDescriptor element = (ChildListPropertyDescriptor)o;
+ ChildListPropertyDescriptor element = (ChildListPropertyDescriptor) o;
if (element.getId().equals("parameters")) {
- foundParamList= true;
+ foundParamList = true;
} else if (element.getId().equals("modifiers")) {
foundModifiers = true;
}
@@ -442,25 +404,23 @@ public class AjASTTest extends AjASTTestCase {
fail("unknown PropertyDescriptor associated with PointcutDeclaration: " + o);
}
}
- assertTrue("PointcutDeclaration should have a javadoc PropertyDescriptor",foundJavadoc);
- assertTrue("PointcutDeclaration should have a designator PropertyDescriptor",foundDesignator);
- assertTrue("PointcutDeclaration should have an name PropertyDescriptor",foundName);
- assertTrue("PointcutDeclaration should have a parameters PropertyDescriptor",foundParamList);
- assertTrue("PointcutDeclaration should have a modifiers PropertyDescriptor",foundModifiers);
+ assertTrue("PointcutDeclaration should have a javadoc PropertyDescriptor", foundJavadoc);
+ assertTrue("PointcutDeclaration should have a designator PropertyDescriptor", foundDesignator);
+ assertTrue("PointcutDeclaration should have an name PropertyDescriptor", foundName);
+ assertTrue("PointcutDeclaration should have a parameters PropertyDescriptor", foundParamList);
+ assertTrue("PointcutDeclaration should have a modifiers PropertyDescriptor", foundModifiers);
}
-
+
public void testClonePointcutDeclaration() {
AjAST ajast = createAjAST();
PointcutDeclaration d = ajast.newPointcutDeclaration();
d.setName(ajast.newSimpleName("pointcut_name"));
d.parameters().add(ajast.newSingleVariableDeclaration());
- PointcutDeclaration copy = (PointcutDeclaration)ASTNode.copySubtree(ajast,d);
- assertEquals("there should be one parameter associated with" +
- "the pointcut copy",1,copy.parameters().size());
- assertEquals("the PointcutDeclaration clone should have the name ", "pointcut_name",
- copy.getName().toString());
+ PointcutDeclaration copy = (PointcutDeclaration) ASTNode.copySubtree(ajast, d);
+ assertEquals("there should be one parameter associated with" + "the pointcut copy", 1, copy.parameters().size());
+ assertEquals("the PointcutDeclaration clone should have the name ", "pointcut_name", copy.getName().toString());
}
-
+
public void testInternalPointcutDeclaration() {
AjAST ajast = createAjAST();
PointcutDeclaration d = ajast.newPointcutDeclaration();
@@ -468,31 +428,27 @@ public class AjASTTest extends AjASTTestCase {
for (Iterator iter = props.iterator(); iter.hasNext();) {
Object o = iter.next();
if (o instanceof ChildPropertyDescriptor) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor)o;
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
if (element.getId().equals("name")) {
- assertNotNull("PointcutDeclaration's " + element.getId() + " property" +
- " should not be null since it is lazily created",
- d.getStructuralProperty(element));
+ assertNotNull("PointcutDeclaration's " + element.getId() + " property"
+ + " should not be null since it is lazily created", d.getStructuralProperty(element));
} else {
- assertNull("PointcutDeclaration's " + element.getId() + " property" +
- " should be null since we haven't set it yet",
- d.getStructuralProperty(element));
- }
+ assertNull("PointcutDeclaration's " + element.getId() + " property"
+ + " should be null since we haven't set it yet", d.getStructuralProperty(element));
+ }
} else if (o instanceof ChildListPropertyDescriptor) {
- ChildListPropertyDescriptor element = (ChildListPropertyDescriptor)o;
- assertNotNull("PointcutDeclaration's " + element.getId() + " property" +
- "should not be null since it is a list",
- d.getStructuralProperty(element));
+ ChildListPropertyDescriptor element = (ChildListPropertyDescriptor) o;
+ assertNotNull("PointcutDeclaration's " + element.getId() + " property" + "should not be null since it is a list", d
+ .getStructuralProperty(element));
boolean isIExtendedModifier = element.getElementType().equals(IExtendedModifier.class);
boolean isSingleVariable = element.getElementType().equals(SingleVariableDeclaration.class);
- assertTrue("should only be able to put SingleVariableDeclaration's" +
- " (which itself has node type IExtendedModifier) into the list",
- isIExtendedModifier || isSingleVariable);
+ assertTrue("should only be able to put SingleVariableDeclaration's"
+ + " (which itself has node type IExtendedModifier) into the list", isIExtendedModifier || isSingleVariable);
} else if (o instanceof SimplePropertyDescriptor) {
- SimplePropertyDescriptor element = (SimplePropertyDescriptor)o;
- assertNotNull("PointcutDeclaration's " + element.getId() + " property" +
- "should not be null since it is a boolean",
- d.getStructuralProperty(element));
+ SimplePropertyDescriptor element = (SimplePropertyDescriptor) o;
+ assertNotNull(
+ "PointcutDeclaration's " + element.getId() + " property" + "should not be null since it is a boolean", d
+ .getStructuralProperty(element));
} else {
fail("unknown PropertyDescriptor associated with PointcutDeclaration: " + o);
}
@@ -503,29 +459,29 @@ public class AjASTTest extends AjASTTestCase {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
if (element.getId().equals("designator")) {
ReferencePointcut rp = ajast.newReferencePointcut();
- d.setStructuralProperty(element,rp);
- assertEquals("PointcutDeclaration's designator property should" +
- " now be a ReferencePointcut",rp,d.getStructuralProperty(element));
+ d.setStructuralProperty(element, rp);
+ assertEquals("PointcutDeclaration's designator property should" + " now be a ReferencePointcut", rp, d
+ .getStructuralProperty(element));
} else if (element.getId().equals("javadoc")) {
// do nothing since makes no sense to have javadoc
} else if (element.getId().equals("name")) {
SimpleName sn = ajast.newSimpleName("p");
- d.setStructuralProperty(element,sn);
- assertEquals("PointcutDeclaration's name property should" +
- " now be a SimpleName",sn,d.getStructuralProperty(element));
+ d.setStructuralProperty(element, sn);
+ assertEquals("PointcutDeclaration's name property should" + " now be a SimpleName", sn, d
+ .getStructuralProperty(element));
}
- }
+ }
}
}
-
+
// -------------- AspectDeclaration tests ---------------
public void testNewAspectDeclaration() {
AjAST ajast = createAjAST();
AspectDeclaration ad = ajast.newAspectDeclaration();
- assertNotNull("a new AspectDeclaration should have been created",ad);
+ assertNotNull("a new AspectDeclaration should have been created", ad);
}
-
+
public void testPropertyDescriptorsForAspectDeclaration() {
AjAST ajast = createAjAST();
AspectDeclaration d = ajast.newAspectDeclaration();
@@ -537,7 +493,7 @@ public class AjASTTest extends AjASTTestCase {
for (Iterator iter = props.iterator(); iter.hasNext();) {
Object o = iter.next();
if ((o instanceof ChildPropertyDescriptor)) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor)o;
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
String id = element.getId();
if (id.equals("javadoc")) {
foundJavadoc = true;
@@ -545,7 +501,7 @@ public class AjASTTest extends AjASTTestCase {
foundPerClause = true;
}
} else if (o instanceof SimplePropertyDescriptor) {
- SimplePropertyDescriptor element = (SimplePropertyDescriptor)o;
+ SimplePropertyDescriptor element = (SimplePropertyDescriptor) o;
String id = element.getId();
if (id.equals("privileged")) {
foundIsPrivileged = true;
@@ -554,231 +510,210 @@ public class AjASTTest extends AjASTTestCase {
}
}
}
- assertTrue("AspectDeclaration should have a javadoc PropertyDescriptor",foundJavadoc);
- assertTrue("AspectDeclaration should have a perClause PropertyDescriptor",foundPerClause);
- assertTrue("AspectDeclaration should have a privileged PropertyDescriptor",foundIsPrivileged);
- assertTrue("AspectDeclaration should have inherited an aspect PropertyDescriptor",foundIsAspect);
+ assertTrue("AspectDeclaration should have a javadoc PropertyDescriptor", foundJavadoc);
+ assertTrue("AspectDeclaration should have a perClause PropertyDescriptor", foundPerClause);
+ assertTrue("AspectDeclaration should have a privileged PropertyDescriptor", foundIsPrivileged);
+ assertTrue("AspectDeclaration should have inherited an aspect PropertyDescriptor", foundIsAspect);
}
-
+
public void testCloneAspectDeclaration() {
AjAST ajast = createAjAST();
AspectDeclaration d = ajast.newAspectDeclaration();
d.setPerClause(ajast.newPerTypeWithin());
d.setPrivileged(true);
- AspectDeclaration copy = (AspectDeclaration)ASTNode.copySubtree(ajast,d);
- assertNotNull("the AspectDeclaration clone should have a perClause set",
- copy.getPerClause());
- assertTrue("the AspectDeclaration clone should be a 'privileged'",
- copy.isPrivileged());
- }
-
-
+ AspectDeclaration copy = (AspectDeclaration) ASTNode.copySubtree(ajast, d);
+ assertNotNull("the AspectDeclaration clone should have a perClause set", copy.getPerClause());
+ assertTrue("the AspectDeclaration clone should be a 'privileged'", copy.isPrivileged());
+ }
+
/**
- * AsepctDeclarations's have a perClause property - test the getting
- * and setting of this property
+ * AsepctDeclarations's have a perClause property - test the getting and setting of this property
*/
public void testSetPerClauseInAspectDeclaration() {
AjAST ajast = createAjAST();
AspectDeclaration ad = ajast.newAspectDeclaration();
- assertNull("by default the perClause should be null",ad.getPerClause());
+ assertNull("by default the perClause should be null", ad.getPerClause());
PerCflow pcf = ajast.newPerCflow();
ad.setPerClause(pcf);
- assertEquals("should have set the perClause to be a PerCflow",
- pcf,ad.getPerClause());
+ assertEquals("should have set the perClause to be a PerCflow", pcf, ad.getPerClause());
}
-
+
/**
- * AsepctDeclarations's have a isPrivileged property - test the getting
- * and setting of this property
+ * AsepctDeclarations's have a isPrivileged property - test the getting and setting of this property
*/
public void testSetPrivilegedInAspectDeclaration() {
AjAST ajast = createAjAST();
AspectDeclaration ad = ajast.newAspectDeclaration();
- assertFalse("by default the aspect should not be privileged",ad.isPrivileged());
+ assertFalse("by default the aspect should not be privileged", ad.isPrivileged());
ad.setPrivileged(true);
- assertTrue("the aspect should now privileged",ad.isPrivileged());
+ assertTrue("the aspect should now privileged", ad.isPrivileged());
}
-
+
// -------------- AfterAdviceDeclaration tests ---------------
public void testNewAfterAdviceDeclaration() {
AjAST ajast = createAjAST();
AfterAdviceDeclaration ad = ajast.newAfterAdviceDeclaration();
- assertNotNull("a new AfterAdviceDeclaration should have been created",ad);
+ assertNotNull("a new AfterAdviceDeclaration should have been created", ad);
}
-
+
// -------------- BeforeAdviceDeclaration tests ---------------
public void testNewBeforeAdviceDeclaration() {
AjAST ajast = createAjAST();
BeforeAdviceDeclaration bd = ajast.newBeforeAdviceDeclaration();
- assertNotNull("a new BeforeAdviceDeclaration should have been created",bd);
+ assertNotNull("a new BeforeAdviceDeclaration should have been created", bd);
}
-
+
/**
- * AdviceDeclarations's have a pointcut property - test the getting
- * and setting of this property
+ * AdviceDeclarations's have a pointcut property - test the getting and setting of this property
*/
public void testGetAndSetPointcutInAdviceDeclaration() {
AjAST ajast = createAjAST();
BeforeAdviceDeclaration bd = ajast.newBeforeAdviceDeclaration();
- assertNull("by default there should be no pointcut associated with" +
- " the advice",bd.getPointcut());
+ assertNull("by default there should be no pointcut associated with" + " the advice", bd.getPointcut());
AndPointcut p = ajast.newAndPointcut();
bd.setPointcut(p);
- assertEquals("there should now be an AndPointcut associated with" +
- " the advice",p,bd.getPointcut());
+ assertEquals("there should now be an AndPointcut associated with" + " the advice", p, bd.getPointcut());
}
-
+
/**
- * AdviceDeclarations's have a body property - test the getting
- * and setting of this property
+ * AdviceDeclarations's have a body property - test the getting and setting of this property
*/
public void testGetAndSetBodyInAdviceDeclaration() {
AjAST ajast = createAjAST();
BeforeAdviceDeclaration bd = ajast.newBeforeAdviceDeclaration();
- assertNull("by default there should be no body associated with" +
- " the advice",bd.getBody());
+ assertNull("by default there should be no body associated with" + " the advice", bd.getBody());
Block b = ajast.newBlock();
bd.setBody(b);
- assertEquals("there should now be a body associated with" +
- " the advice",b,bd.getBody());
+ assertEquals("there should now be a body associated with" + " the advice", b, bd.getBody());
}
-
+
// -------------- AfterReturningAdviceDeclaration tests ---------------
public void testNewAfterReturningAdviceDeclaration() {
AjAST ajast = createAjAST();
AfterReturningAdviceDeclaration d = ajast.newAfterReturningAdviceDeclaration();
- assertNotNull("should have created an AfterReturningAdviceDeclaration",d);
+ assertNotNull("should have created an AfterReturningAdviceDeclaration", d);
}
-
+
/**
- * AfterReturningAdviceDeclarations's have a returning property -
- * test the getting and setting of this property
+ * AfterReturningAdviceDeclarations's have a returning property - test the getting and setting of this property
*/
public void testGetAndSetReturning() {
AjAST ajast = createAjAST();
AfterReturningAdviceDeclaration d = ajast.newAfterReturningAdviceDeclaration();
- assertNull("by default there should be no returning property associated with" +
- " the AfterReturningAdviceDeclaration",d.getReturning());
+ assertNull("by default there should be no returning property associated with" + " the AfterReturningAdviceDeclaration", d
+ .getReturning());
SingleVariableDeclaration s = ajast.newSingleVariableDeclaration();
d.setReturning(s);
- assertEquals("there should now be a returning property associated with" +
- " the AfterReturningAdviceDeclaration",s,d.getReturning());
+ assertEquals("there should now be a returning property associated with" + " the AfterReturningAdviceDeclaration", s, d
+ .getReturning());
}
-
+
// -------------- AfterThrowingAdviceDeclaration tests ---------------
public void testNewAfterThrowingAdviceDeclaration() {
AjAST ajast = createAjAST();
AfterThrowingAdviceDeclaration d = ajast.newAfterThrowingAdviceDeclaration();
- assertNotNull("should have created an AfterThrowingAdviceDeclaration",d);
+ assertNotNull("should have created an AfterThrowingAdviceDeclaration", d);
}
-
+
/**
- * AfterThrowingAdviceDeclaration's have a throwing property -
- * test the getting and setting of this property
+ * AfterThrowingAdviceDeclaration's have a throwing property - test the getting and setting of this property
*/
public void testGetAndSetThrowing() {
AjAST ajast = createAjAST();
AfterThrowingAdviceDeclaration d = ajast.newAfterThrowingAdviceDeclaration();
- assertNull("by default there should be no throwing property associated with" +
- " the AfterThrowingAdviceDeclaration",d.getThrowing());
+ assertNull("by default there should be no throwing property associated with" + " the AfterThrowingAdviceDeclaration", d
+ .getThrowing());
SingleVariableDeclaration s = ajast.newSingleVariableDeclaration();
d.setThrowing(s);
- assertEquals("there should now be a throwing property associated with" +
- " the AfterThrowingAdviceDeclaration",s,d.getThrowing());
+ assertEquals("there should now be a throwing property associated with" + " the AfterThrowingAdviceDeclaration", s, d
+ .getThrowing());
}
-
+
// -------------- AroundAdviceDeclaration tests ---------------
public void testNewAroundAdviceDeclaration() {
AjAST ajast = createAjAST();
AroundAdviceDeclaration d = ajast.newAroundAdviceDeclaration();
- assertNotNull("should have created an AroundAdviceDeclaration",d);
+ assertNotNull("should have created an AroundAdviceDeclaration", d);
}
-
+
/**
- * AroundAdviceDeclaration's have a return type property -
- * test the getting and setting of this property (different
+ * AroundAdviceDeclaration's have a return type property - test the getting and setting of this property (different
* implementation for JLS2 and JLS3)
*/
public void testGetAndSetReturnTypeJLS2() {
AjAST ajast = createAjAST(AST.JLS2);
AroundAdviceDeclaration d = ajast.newAroundAdviceDeclaration();
Type t = d.getReturnType();
- assertTrue("by default the return type associated with the" +
- " AroundAdviceDeclaration should be a PrimitiveType",
+ assertTrue("by default the return type associated with the" + " AroundAdviceDeclaration should be a PrimitiveType",
t instanceof PrimitiveType);
- assertEquals("by default there should be the PrimitiveType.VOID return " +
- "type associated with the AroundAdviceDeclaration",
- PrimitiveType.VOID.toString(),((PrimitiveType)t).toString());
+ assertEquals("by default there should be the PrimitiveType.VOID return "
+ + "type associated with the AroundAdviceDeclaration", PrimitiveType.VOID.toString(), ((PrimitiveType) t).toString());
SimpleType s = ajast.newSimpleType(ajast.newSimpleName("name"));
d.setReturnType(s);
- assertEquals("there should now be a SimpleType return type associated with" +
- " the AroundAdviceDeclaration",s,d.getReturnType());
+ assertEquals("there should now be a SimpleType return type associated with" + " the AroundAdviceDeclaration", s, d
+ .getReturnType());
}
/**
- * AroundAdviceDeclaration's have a return type property -
- * test the getting and setting of this property (different
+ * AroundAdviceDeclaration's have a return type property - test the getting and setting of this property (different
* implementation for JLS2 and JLS3)
*/
public void testGetAndSetReturnTypeJLS3() {
AjAST ajast = createAjAST();
AroundAdviceDeclaration d = ajast.newAroundAdviceDeclaration();
Type t = d.getReturnType2();
- assertTrue("by default the return type associated with the" +
- " AroundAdviceDeclaration should be a PrimitiveType",
+ assertTrue("by default the return type associated with the" + " AroundAdviceDeclaration should be a PrimitiveType",
t instanceof PrimitiveType);
- assertEquals("by default there should be the PrimitiveType.VOID return " +
- "type associated with the AroundAdviceDeclaration",
- PrimitiveType.VOID.toString(),((PrimitiveType)t).toString());
+ assertEquals("by default there should be the PrimitiveType.VOID return "
+ + "type associated with the AroundAdviceDeclaration", PrimitiveType.VOID.toString(), ((PrimitiveType) t).toString());
SimpleType s = ajast.newSimpleType(ajast.newSimpleName("name"));
d.setReturnType2(s);
- assertEquals("there should now be a SimpleType return type associated with" +
- " the AroundAdviceDeclaration",s,d.getReturnType2());
+ assertEquals("there should now be a SimpleType return type associated with" + " the AroundAdviceDeclaration", s, d
+ .getReturnType2());
}
-
+
// -------------- InterTypeFieldDeclaration tests ---------------
public void testNewITDFieldDeclaration() {
AjAST ajast = createAjAST();
InterTypeFieldDeclaration d = ajast.newInterTypeFieldDeclaration();
- assertNotNull("should have created an InterTypeFieldDeclaration",d);
+ assertNotNull("should have created an InterTypeFieldDeclaration", d);
}
-
+
// -------------- InterTypeMethodDeclaration tests ---------------
public void testNewITDMethodDeclaration() {
AjAST ajast = createAjAST();
InterTypeMethodDeclaration d = ajast.newInterTypeMethodDeclaration();
- assertNotNull("should have created an InterTypeMethodDeclaration",d);
+ assertNotNull("should have created an InterTypeMethodDeclaration", d);
}
-
+
// -------------- AjTypeDeclaration tests ---------------
public void testNewAjTypeDeclaration() {
AjAST ajast = createAjAST();
AjTypeDeclaration d = ajast.newAjTypeDeclaration();
- assertNotNull("should have created an AjTypeDeclaration",d);
+ assertNotNull("should have created an AjTypeDeclaration", d);
}
-
+
/**
- * AjTypeDeclaration's have an isAspect property -
- * test the getting and setting of this property
+ * AjTypeDeclaration's have an isAspect property - test the getting and setting of this property
*/
public void testGetAndSetIsAspect() {
AjAST ajast = createAjAST();
AjTypeDeclaration d = ajast.newAjTypeDeclaration();
- assertFalse("by default an AjTypeDeclaration should be a class",d.isAspect());
+ assertFalse("by default an AjTypeDeclaration should be a class", d.isAspect());
d.setAspect(true);
- assertTrue("AjTypeDeclaration should now be an aspect",d.isAspect());
+ assertTrue("AjTypeDeclaration should now be an aspect", d.isAspect());
d.setAspect(false);
- assertFalse("AjTypeDeclaration should now be a class",d.isAspect());
+ assertFalse("AjTypeDeclaration should now be a class", d.isAspect());
}
-
+
public void testPropertyDescriptorsForAjTypeDeclaration() {
AjAST ajast = createAjAST();
AjTypeDeclaration d = ajast.newAjTypeDeclaration();
@@ -787,26 +722,25 @@ public class AjASTTest extends AjASTTestCase {
for (Iterator iter = props.iterator(); iter.hasNext();) {
Object o = iter.next();
if (o instanceof SimplePropertyDescriptor) {
- SimplePropertyDescriptor element = (SimplePropertyDescriptor)o;
+ SimplePropertyDescriptor element = (SimplePropertyDescriptor) o;
String id = element.getId();
if (id.equals("aspect")) {
foundAspect = true;
- }
+ }
}
}
- assertTrue("AjTypeDeclaration should have an aspect PropertyDescriptor",foundAspect);
+ assertTrue("AjTypeDeclaration should have an aspect PropertyDescriptor", foundAspect);
}
-
+
public void testCloneAjTypeDeclaration() {
AjAST ajast = createAjAST();
AjTypeDeclaration d = ajast.newAjTypeDeclaration();
d.setAspect(true);
- AjTypeDeclaration copy = (AjTypeDeclaration)ASTNode.copySubtree(ajast,d);
- assertTrue("the AjTypeDeclaration clone should be an aspect",
- copy.isAspect());
+ AjTypeDeclaration copy = (AjTypeDeclaration) ASTNode.copySubtree(ajast, d);
+ assertTrue("the AjTypeDeclaration clone should be an aspect", copy.isAspect());
}
- // test for bug 125809 - make sure the property descriptors
+ // test for bug 125809 - make sure the property descriptors
// associated with the AspectDeclaration aren't consequently
// associated with the AjTypeDeclaration
public void testPropertyDescriptorsForAjTypeDeclaration2() {
@@ -821,23 +755,23 @@ public class AjASTTest extends AjASTTestCase {
for (Iterator iter = props.iterator(); iter.hasNext();) {
Object o = iter.next();
if (o instanceof SimplePropertyDescriptor) {
- SimplePropertyDescriptor element = (SimplePropertyDescriptor)o;
+ SimplePropertyDescriptor element = (SimplePropertyDescriptor) o;
String id = element.getId();
if (id.equals("privileged")) {
foundPrivileged = true;
- }
+ }
} else if (o instanceof ChildPropertyDescriptor) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor)o;
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
if (element.getId().equals("perClause")) {
foundPerClause = true;
}
}
}
- assertFalse("AjTypeDeclaration should not have a privileged PropertyDescriptor",foundPrivileged);
- assertFalse("AjTypeDeclaration should not have a perClause PropertyDescriptor",foundPerClause);
+ assertFalse("AjTypeDeclaration should not have a privileged PropertyDescriptor", foundPrivileged);
+ assertFalse("AjTypeDeclaration should not have a perClause PropertyDescriptor", foundPerClause);
}
-
- // test for bug 125809 - make sure the property descriptors
+
+ // test for bug 125809 - make sure the property descriptors
// associated with the AjTypeDeclaration aren't consequently
// associated with the TypeDeclaration
public void testPropertyDescriptorsForAjTypeDeclaration3() {
@@ -850,24 +784,24 @@ public class AjASTTest extends AjASTTestCase {
for (Iterator iter = props.iterator(); iter.hasNext();) {
Object o = iter.next();
if (o instanceof SimplePropertyDescriptor) {
- SimplePropertyDescriptor element = (SimplePropertyDescriptor)o;
+ SimplePropertyDescriptor element = (SimplePropertyDescriptor) o;
String id = element.getId();
if (id.equals("aspect")) {
foundAspect = true;
- }
- }
+ }
+ }
}
- assertFalse("TypeDeclaration should not have an aspect PropertyDescriptor",foundAspect);
+ assertFalse("TypeDeclaration should not have an aspect PropertyDescriptor", foundAspect);
}
-
+
// -------------- DeclareAtFieldDeclaration tests ---------------
public void testNewDeclareAtFieldDeclaration() {
AjAST ajast = createAjAST();
DeclareAtFieldDeclaration d = ajast.newDeclareAtFieldDeclaration();
- assertNotNull("should have created a DeclareAtFieldDeclaration",d);
+ assertNotNull("should have created a DeclareAtFieldDeclaration", d);
}
-
+
public void testPropertyDescriptorsForDeclareAtField() {
AjAST ajast = createAjAST();
DeclareAtFieldDeclaration d = ajast.newDeclareAtFieldDeclaration();
@@ -876,7 +810,7 @@ public class AjASTTest extends AjASTTestCase {
boolean foundPattern = false;
boolean foundAnnotationName = false;
for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor)iter.next();
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
String id = element.getId();
if (id.equals("javadoc")) {
foundJavadoc = true;
@@ -886,46 +820,43 @@ public class AjASTTest extends AjASTTestCase {
foundAnnotationName = true;
} else {
fail("unknown PropertyDescriptor associated with DeclareAtFieldDeclaration: " + element.getId());
- }
+ }
}
- assertTrue("DeclareAtFieldDeclaration should have a javadoc PropertyDescriptor",foundJavadoc);
- assertTrue("DeclareAtFieldDeclaration should have a attern PropertyDescriptor",foundPattern);
- assertTrue("DeclareAtFieldDeclaration should have a annotationName PropertyDescriptor",foundAnnotationName);
+ assertTrue("DeclareAtFieldDeclaration should have a javadoc PropertyDescriptor", foundJavadoc);
+ assertTrue("DeclareAtFieldDeclaration should have a attern PropertyDescriptor", foundPattern);
+ assertTrue("DeclareAtFieldDeclaration should have a annotationName PropertyDescriptor", foundAnnotationName);
}
-
+
public void testGetAndSetPatternNodeInDeclareAtField() {
AjAST ajast = createAjAST();
DeclareAtFieldDeclaration d = ajast.newDeclareAtFieldDeclaration();
- assertNull("by default there should be no typePattern associated with" +
- " the declare @field annotation",d.getPatternNode());
+ assertNull("by default there should be no typePattern associated with" + " the declare @field annotation", d
+ .getPatternNode());
SignaturePattern p = ajast.newSignaturePattern();
d.setPatternNode(p);
- assertEquals("there should now be a DefaultTypePattern associated with" +
- " the declare @field annotation",p,d.getPatternNode());
+ assertEquals("there should now be a DefaultTypePattern associated with" + " the declare @field annotation", p, d
+ .getPatternNode());
}
-
+
public void testGetAndSetAnnNameInDeclareAtField() {
AjAST ajast = createAjAST();
DeclareAtFieldDeclaration d = ajast.newDeclareAtFieldDeclaration();
- assertEquals("the default annotation name should be MISSING",
- "MISSING",d.getAnnotationName().getFullyQualifiedName());
+ assertEquals("the default annotation name should be MISSING", "MISSING", d.getAnnotationName().getFullyQualifiedName());
d.setAnnotationName(ajast.newSimpleName("MyAnnotation"));
- assertEquals("the annotation name should now be set to 'MyAnnotation'",
- "MyAnnotation",d.getAnnotationName().getFullyQualifiedName());
+ assertEquals("the annotation name should now be set to 'MyAnnotation'", "MyAnnotation", d.getAnnotationName()
+ .getFullyQualifiedName());
}
-
+
public void testCloneDeclareAtField() {
AjAST ajast = createAjAST();
DeclareAtFieldDeclaration d = ajast.newDeclareAtFieldDeclaration();
d.setPatternNode(ajast.newSignaturePattern());
d.setAnnotationName(ajast.newSimpleName("MyAnnotation"));
- DeclareAtFieldDeclaration copy = (DeclareAtFieldDeclaration)ASTNode.copySubtree(ajast,d);
- assertNotNull("the DeclareAtFieldDeclaration clone should have a TypePattern set",
- copy.getPatternNode());
- assertNotNull("the DeclareAtFieldDeclaration clone should have a Annotation name set",
- copy.getAnnotationName());
+ DeclareAtFieldDeclaration copy = (DeclareAtFieldDeclaration) ASTNode.copySubtree(ajast, d);
+ assertNotNull("the DeclareAtFieldDeclaration clone should have a TypePattern set", copy.getPatternNode());
+ assertNotNull("the DeclareAtFieldDeclaration clone should have a Annotation name set", copy.getAnnotationName());
}
-
+
public void testInternalDeclareAtField() {
AjAST ajast = createAjAST();
DeclareAtFieldDeclaration d = ajast.newDeclareAtFieldDeclaration();
@@ -933,27 +864,25 @@ public class AjASTTest extends AjASTTestCase {
for (Iterator iter = props.iterator(); iter.hasNext();) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
if (element.getId().equals("annotationName")) {
- assertNotNull("DeclareAtFieldDeclaration's " + element.getId() + " property" +
- " should not be null since it is lazily created",
- d.getStructuralProperty(element));
+ assertNotNull("DeclareAtFieldDeclaration's " + element.getId() + " property"
+ + " should not be null since it is lazily created", d.getStructuralProperty(element));
} else {
- assertNull("DeclareAtFieldDeclaration's " + element.getId() + " property" +
- " should be null since we haven't set it yet",
- d.getStructuralProperty(element));
+ assertNull("DeclareAtFieldDeclaration's " + element.getId() + " property"
+ + " should be null since we haven't set it yet", d.getStructuralProperty(element));
}
}
for (Iterator iter = props.iterator(); iter.hasNext();) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
if (element.getId().equals("pattern")) {
SignaturePattern p = ajast.newSignaturePattern();
- d.setStructuralProperty(element,p);
- assertEquals("DeclareAtFieldDeclaration's pattern property should" +
- " now be a SignaturePattern",p,d.getStructuralProperty(element));
+ d.setStructuralProperty(element, p);
+ assertEquals("DeclareAtFieldDeclaration's pattern property should" + " now be a SignaturePattern", p, d
+ .getStructuralProperty(element));
} else if (element.getId().equals("annotationName")) {
SimpleName s = ajast.newSimpleName("MyAnnotation");
- d.setStructuralProperty(element,s);
- assertEquals("DeclareAtFieldDeclaration's annotationName property should" +
- " now be a SimpleName",s,d.getStructuralProperty(element));
+ d.setStructuralProperty(element, s);
+ assertEquals("DeclareAtFieldDeclaration's annotationName property should" + " now be a SimpleName", s, d
+ .getStructuralProperty(element));
} else if (element.getId().equals("javadoc")) {
// do nothing since makes no sense to have javadoc
} else {
@@ -967,18 +896,19 @@ public class AjASTTest extends AjASTTestCase {
public void testNewDeclareAtMethodDeclaration() {
AjAST ajast = createAjAST();
DeclareAtMethodDeclaration d = ajast.newDeclareAtMethodDeclaration();
- assertNotNull("should have created a DeclareAtMethodDeclaration",d);
+ assertNotNull("should have created a DeclareAtMethodDeclaration", d);
}
-
+
public void testPropertyDescriptorsForDeclareAtMethod() {
AjAST ajast = createAjAST();
- DeclareAtMethodDeclaration d = ajast.newDeclareAtMethodDeclaration();
+ // DeclareAtMethodDeclaration d =
+ ajast.newDeclareAtMethodDeclaration();
List props = DeclareAtMethodDeclaration.propertyDescriptors(AST.JLS3);
boolean foundJavadoc = false;
boolean foundPattern = false;
boolean foundAnnotationName = false;
for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor)iter.next();
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
String id = element.getId();
if (id.equals("javadoc")) {
foundJavadoc = true;
@@ -988,46 +918,43 @@ public class AjASTTest extends AjASTTestCase {
foundAnnotationName = true;
} else {
fail("unknown PropertyDescriptor associated with DeclareAtMethodDeclaration: " + element.getId());
- }
+ }
}
- assertTrue("DeclareAtMethodDeclaration should have a javadoc PropertyDescriptor",foundJavadoc);
- assertTrue("DeclareAtMethodDeclaration should have a attern PropertyDescriptor",foundPattern);
- assertTrue("DeclareAtMethodDeclaration should have a annotationName PropertyDescriptor",foundAnnotationName);
+ assertTrue("DeclareAtMethodDeclaration should have a javadoc PropertyDescriptor", foundJavadoc);
+ assertTrue("DeclareAtMethodDeclaration should have a attern PropertyDescriptor", foundPattern);
+ assertTrue("DeclareAtMethodDeclaration should have a annotationName PropertyDescriptor", foundAnnotationName);
}
-
+
public void testGetAndSetPatternNodeInDeclareAtMethod() {
AjAST ajast = createAjAST();
DeclareAtMethodDeclaration d = ajast.newDeclareAtMethodDeclaration();
- assertNull("by default there should be no typePattern associated with" +
- " the declare @method annotation",d.getPatternNode());
+ assertNull("by default there should be no typePattern associated with" + " the declare @method annotation", d
+ .getPatternNode());
SignaturePattern p = ajast.newSignaturePattern();
d.setPatternNode(p);
- assertEquals("there should now be a DefaultTypePattern associated with" +
- " the declare @method annotation",p,d.getPatternNode());
+ assertEquals("there should now be a DefaultTypePattern associated with" + " the declare @method annotation", p, d
+ .getPatternNode());
}
-
+
public void testGetAndSetAnnNameInDeclareAtMethod() {
AjAST ajast = createAjAST();
DeclareAtMethodDeclaration d = ajast.newDeclareAtMethodDeclaration();
- assertEquals("the default annotation name should be MISSING",
- "MISSING",d.getAnnotationName().getFullyQualifiedName());
+ assertEquals("the default annotation name should be MISSING", "MISSING", d.getAnnotationName().getFullyQualifiedName());
d.setAnnotationName(ajast.newSimpleName("MyAnnotation"));
- assertEquals("the annotation name should now be set to 'MyAnnotation'",
- "MyAnnotation",d.getAnnotationName().getFullyQualifiedName());
+ assertEquals("the annotation name should now be set to 'MyAnnotation'", "MyAnnotation", d.getAnnotationName()
+ .getFullyQualifiedName());
}
-
+
public void testCloneDeclareAtMethod() {
AjAST ajast = createAjAST();
DeclareAtMethodDeclaration d = ajast.newDeclareAtMethodDeclaration();
d.setPatternNode(ajast.newSignaturePattern());
d.setAnnotationName(ajast.newSimpleName("MyAnnotation"));
- DeclareAtMethodDeclaration copy = (DeclareAtMethodDeclaration)ASTNode.copySubtree(ajast,d);
- assertNotNull("the DeclareAtMethodDeclaration clone should have a TypePattern set",
- copy.getPatternNode());
- assertNotNull("the DeclareAtMethodDeclaration clone should have a Annotation name set",
- copy.getAnnotationName());
+ DeclareAtMethodDeclaration copy = (DeclareAtMethodDeclaration) ASTNode.copySubtree(ajast, d);
+ assertNotNull("the DeclareAtMethodDeclaration clone should have a TypePattern set", copy.getPatternNode());
+ assertNotNull("the DeclareAtMethodDeclaration clone should have a Annotation name set", copy.getAnnotationName());
}
-
+
public void testInternalDeclareAtMethod() {
AjAST ajast = createAjAST();
DeclareAtMethodDeclaration d = ajast.newDeclareAtMethodDeclaration();
@@ -1035,27 +962,25 @@ public class AjASTTest extends AjASTTestCase {
for (Iterator iter = props.iterator(); iter.hasNext();) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
if (element.getId().equals("annotationName")) {
- assertNotNull("DeclareAtMethodDeclaration's " + element.getId() + " property" +
- " should not be null since it is lazily created",
- d.getStructuralProperty(element));
+ assertNotNull("DeclareAtMethodDeclaration's " + element.getId() + " property"
+ + " should not be null since it is lazily created", d.getStructuralProperty(element));
} else {
- assertNull("DeclareAtMethodDeclaration's " + element.getId() + " property" +
- " should be null since we haven't set it yet",
- d.getStructuralProperty(element));
+ assertNull("DeclareAtMethodDeclaration's " + element.getId() + " property"
+ + " should be null since we haven't set it yet", d.getStructuralProperty(element));
}
}
for (Iterator iter = props.iterator(); iter.hasNext();) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
if (element.getId().equals("pattern")) {
SignaturePattern p = ajast.newSignaturePattern();
- d.setStructuralProperty(element,p);
- assertEquals("DeclareAtMethodDeclaration's pattern property should" +
- " now be a SignaturePattern",p,d.getStructuralProperty(element));
+ d.setStructuralProperty(element, p);
+ assertEquals("DeclareAtMethodDeclaration's pattern property should" + " now be a SignaturePattern", p, d
+ .getStructuralProperty(element));
} else if (element.getId().equals("annotationName")) {
SimpleName s = ajast.newSimpleName("MyAnnotation");
- d.setStructuralProperty(element,s);
- assertEquals("DeclareAtMethodDeclaration's annotationName property should" +
- " now be a SimpleName",s,d.getStructuralProperty(element));
+ d.setStructuralProperty(element, s);
+ assertEquals("DeclareAtMethodDeclaration's annotationName property should" + " now be a SimpleName", s, d
+ .getStructuralProperty(element));
} else if (element.getId().equals("javadoc")) {
// do nothing since makes no sense to have javadoc
} else {
@@ -1063,24 +988,25 @@ public class AjASTTest extends AjASTTestCase {
}
}
}
-
+
// -------------- DeclareAtConstructorDeclaration tests ---------------
public void testNewDeclareAtConstructorDeclaration() {
AjAST ajast = createAjAST();
DeclareAtConstructorDeclaration d = ajast.newDeclareAtConstructorDeclaration();
- assertNotNull("should have created a DeclareAtConstructorDeclaration",d);
+ assertNotNull("should have created a DeclareAtConstructorDeclaration", d);
}
-
+
public void testPropertyDescriptorsForDeclareAtConstructor() {
AjAST ajast = createAjAST();
- DeclareAtConstructorDeclaration d = ajast.newDeclareAtConstructorDeclaration();
+ // DeclareAtConstructorDeclaration d =
+ ajast.newDeclareAtConstructorDeclaration();
List props = DeclareAtConstructorDeclaration.propertyDescriptors(AST.JLS3);
boolean foundJavadoc = false;
boolean foundPattern = false;
boolean foundAnnotationName = false;
for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor)iter.next();
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
String id = element.getId();
if (id.equals("javadoc")) {
foundJavadoc = true;
@@ -1090,46 +1016,43 @@ public class AjASTTest extends AjASTTestCase {
foundAnnotationName = true;
} else {
fail("unknown PropertyDescriptor associated with DeclareAtConstructorDeclaration: " + element.getId());
- }
+ }
}
- assertTrue("DeclareAtConstructorDeclaration should have a javadoc PropertyDescriptor",foundJavadoc);
- assertTrue("DeclareAtConstructorDeclaration should have a attern PropertyDescriptor",foundPattern);
- assertTrue("DeclareAtConstructorDeclaration should have a annotationName PropertyDescriptor",foundAnnotationName);
+ assertTrue("DeclareAtConstructorDeclaration should have a javadoc PropertyDescriptor", foundJavadoc);
+ assertTrue("DeclareAtConstructorDeclaration should have a attern PropertyDescriptor", foundPattern);
+ assertTrue("DeclareAtConstructorDeclaration should have a annotationName PropertyDescriptor", foundAnnotationName);
}
-
+
public void testGetAndSetPatternNodeInDeclareAtConstructor() {
AjAST ajast = createAjAST();
DeclareAtConstructorDeclaration d = ajast.newDeclareAtConstructorDeclaration();
- assertNull("by default there should be no typePattern associated with" +
- " the declare @constructor annotation",d.getPatternNode());
+ assertNull("by default there should be no typePattern associated with" + " the declare @constructor annotation", d
+ .getPatternNode());
SignaturePattern p = ajast.newSignaturePattern();
d.setPatternNode(p);
- assertEquals("there should now be a DefaultTypePattern associated with" +
- " the declare @constructor annotation",p,d.getPatternNode());
+ assertEquals("there should now be a DefaultTypePattern associated with" + " the declare @constructor annotation", p, d
+ .getPatternNode());
}
-
+
public void testGetAndSetAnnNameInDeclareAtConstructor() {
AjAST ajast = createAjAST();
DeclareAtConstructorDeclaration d = ajast.newDeclareAtConstructorDeclaration();
- assertEquals("the default annotation name should be MISSING",
- "MISSING",d.getAnnotationName().getFullyQualifiedName());
+ assertEquals("the default annotation name should be MISSING", "MISSING", d.getAnnotationName().getFullyQualifiedName());
d.setAnnotationName(ajast.newSimpleName("MyAnnotation"));
- assertEquals("the annotation name should now be set to 'MyAnnotation'",
- "MyAnnotation",d.getAnnotationName().getFullyQualifiedName());
+ assertEquals("the annotation name should now be set to 'MyAnnotation'", "MyAnnotation", d.getAnnotationName()
+ .getFullyQualifiedName());
}
-
+
public void testCloneDeclareAtConstructor() {
AjAST ajast = createAjAST();
DeclareAtConstructorDeclaration d = ajast.newDeclareAtConstructorDeclaration();
d.setPatternNode(ajast.newSignaturePattern());
d.setAnnotationName(ajast.newSimpleName("MyAnnotation"));
- DeclareAtConstructorDeclaration copy = (DeclareAtConstructorDeclaration)ASTNode.copySubtree(ajast,d);
- assertNotNull("the DeclareAtConstructorDeclaration clone should have a SignaturePattern set",
- copy.getPatternNode());
- assertNotNull("the DeclareAtConstructorDeclaration clone should have a Annotation name set",
- copy.getAnnotationName());
+ DeclareAtConstructorDeclaration copy = (DeclareAtConstructorDeclaration) ASTNode.copySubtree(ajast, d);
+ assertNotNull("the DeclareAtConstructorDeclaration clone should have a SignaturePattern set", copy.getPatternNode());
+ assertNotNull("the DeclareAtConstructorDeclaration clone should have a Annotation name set", copy.getAnnotationName());
}
-
+
public void testInternalDeclareAtConstructor() {
AjAST ajast = createAjAST();
DeclareAtConstructorDeclaration d = ajast.newDeclareAtConstructorDeclaration();
@@ -1137,27 +1060,25 @@ public class AjASTTest extends AjASTTestCase {
for (Iterator iter = props.iterator(); iter.hasNext();) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
if (element.getId().equals("annotationName")) {
- assertNotNull("DeclareAtConstructorDeclaration's " + element.getId() + " property" +
- " should not be null since it is lazily created",
- d.getStructuralProperty(element));
+ assertNotNull("DeclareAtConstructorDeclaration's " + element.getId() + " property"
+ + " should not be null since it is lazily created", d.getStructuralProperty(element));
} else {
- assertNull("DeclareAtConstructorDeclaration's " + element.getId() + " property" +
- " should be null since we haven't set it yet",
- d.getStructuralProperty(element));
+ assertNull("DeclareAtConstructorDeclaration's " + element.getId() + " property"
+ + " should be null since we haven't set it yet", d.getStructuralProperty(element));
}
}
for (Iterator iter = props.iterator(); iter.hasNext();) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
if (element.getId().equals("pattern")) {
SignaturePattern p = ajast.newSignaturePattern();
- d.setStructuralProperty(element,p);
- assertEquals("DeclareAtConstructorDeclaration's pattern property should" +
- " now be a SignaturePattern",p,d.getStructuralProperty(element));
+ d.setStructuralProperty(element, p);
+ assertEquals("DeclareAtConstructorDeclaration's pattern property should" + " now be a SignaturePattern", p, d
+ .getStructuralProperty(element));
} else if (element.getId().equals("annotationName")) {
SimpleName s = ajast.newSimpleName("MyAnnotation");
- d.setStructuralProperty(element,s);
- assertEquals("DeclareAtConstructorDeclaration's annotationName property should" +
- " now be a SimpleName",s,d.getStructuralProperty(element));
+ d.setStructuralProperty(element, s);
+ assertEquals("DeclareAtConstructorDeclaration's annotationName property should" + " now be a SimpleName", s, d
+ .getStructuralProperty(element));
} else if (element.getId().equals("javadoc")) {
// do nothing since makes no sense to have javadoc
} else {
@@ -1165,15 +1086,15 @@ public class AjASTTest extends AjASTTestCase {
}
}
}
-
+
// -------------- DeclareAtTypeDeclaration tests ---------------
public void testNewDeclareAtTypeDeclaration() {
AjAST ajast = createAjAST();
DeclareAtTypeDeclaration d = ajast.newDeclareAtTypeDeclaration();
- assertNotNull("should have created a DeclareAtTypeDeclaration",d);
+ assertNotNull("should have created a DeclareAtTypeDeclaration", d);
}
-
+
public void testPropertyDescriptorsForDeclareAtType() {
AjAST ajast = createAjAST();
DeclareAtTypeDeclaration d = ajast.newDeclareAtTypeDeclaration();
@@ -1182,7 +1103,7 @@ public class AjASTTest extends AjASTTestCase {
boolean foundPattern = false;
boolean foundAnnotationName = false;
for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor)iter.next();
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
String id = element.getId();
if (id.equals("javadoc")) {
foundJavadoc = true;
@@ -1192,46 +1113,43 @@ public class AjASTTest extends AjASTTestCase {
foundAnnotationName = true;
} else {
fail("unknown PropertyDescriptor associated with DeclareAtTypeDeclaration: " + element.getId());
- }
+ }
}
- assertTrue("DeclareAtTypeDeclaration should have a javadoc PropertyDescriptor",foundJavadoc);
- assertTrue("DeclareAtTypeDeclaration should have a attern PropertyDescriptor",foundPattern);
- assertTrue("DeclareAtTypeDeclaration should have a annotationName PropertyDescriptor",foundAnnotationName);
+ assertTrue("DeclareAtTypeDeclaration should have a javadoc PropertyDescriptor", foundJavadoc);
+ assertTrue("DeclareAtTypeDeclaration should have a attern PropertyDescriptor", foundPattern);
+ assertTrue("DeclareAtTypeDeclaration should have a annotationName PropertyDescriptor", foundAnnotationName);
}
-
+
public void testGetAndSetPatternNodeInDeclareAtType() {
AjAST ajast = createAjAST();
DeclareAtTypeDeclaration d = ajast.newDeclareAtTypeDeclaration();
- assertNull("by default there should be no typePattern associated with" +
- " the declare @type annotation",d.getPatternNode());
+ assertNull("by default there should be no typePattern associated with" + " the declare @type annotation", d
+ .getPatternNode());
DefaultTypePattern dtp = ajast.newDefaultTypePattern();
d.setPatternNode(dtp);
- assertEquals("there should now be a DefaultTypePattern associated with" +
- " the declare @type annotation",dtp,d.getPatternNode());
+ assertEquals("there should now be a DefaultTypePattern associated with" + " the declare @type annotation", dtp, d
+ .getPatternNode());
}
-
+
public void testGetAndSetAnnNameInDeclareAtType() {
AjAST ajast = createAjAST();
DeclareAtTypeDeclaration d = ajast.newDeclareAtTypeDeclaration();
- assertEquals("the default annotation name should be MISSING",
- "MISSING",d.getAnnotationName().getFullyQualifiedName());
+ assertEquals("the default annotation name should be MISSING", "MISSING", d.getAnnotationName().getFullyQualifiedName());
d.setAnnotationName(ajast.newSimpleName("MyAnnotation"));
- assertEquals("the annotation name should now be set to 'MyAnnotation'",
- "MyAnnotation",d.getAnnotationName().getFullyQualifiedName());
+ assertEquals("the annotation name should now be set to 'MyAnnotation'", "MyAnnotation", d.getAnnotationName()
+ .getFullyQualifiedName());
}
-
+
public void testCloneDeclareAtType() {
AjAST ajast = createAjAST();
DeclareAtTypeDeclaration d = ajast.newDeclareAtTypeDeclaration();
d.setPatternNode(ajast.newDefaultTypePattern());
d.setAnnotationName(ajast.newSimpleName("MyAnnotation"));
- DeclareAtTypeDeclaration copy = (DeclareAtTypeDeclaration)ASTNode.copySubtree(ajast,d);
- assertNotNull("the DeclareAtTypeDeclaration clone should have a TypePattern set",
- copy.getPatternNode());
- assertNotNull("the DeclareAtTypeDeclaration clone should have a Annotation name set",
- copy.getAnnotationName());
+ DeclareAtTypeDeclaration copy = (DeclareAtTypeDeclaration) ASTNode.copySubtree(ajast, d);
+ assertNotNull("the DeclareAtTypeDeclaration clone should have a TypePattern set", copy.getPatternNode());
+ assertNotNull("the DeclareAtTypeDeclaration clone should have a Annotation name set", copy.getAnnotationName());
}
-
+
public void testInternalDeclareAtType() {
AjAST ajast = createAjAST();
DeclareAtTypeDeclaration d = ajast.newDeclareAtTypeDeclaration();
@@ -1239,27 +1157,25 @@ public class AjASTTest extends AjASTTestCase {
for (Iterator iter = props.iterator(); iter.hasNext();) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
if (element.getId().equals("annotationName")) {
- assertNotNull("DeclareAtTypeDeclaration's " + element.getId() + " property" +
- " should not be null since it is lazily created",
- d.getStructuralProperty(element));
+ assertNotNull("DeclareAtTypeDeclaration's " + element.getId() + " property"
+ + " should not be null since it is lazily created", d.getStructuralProperty(element));
} else {
- assertNull("DeclareAtTypeDeclaration's " + element.getId() + " property" +
- " should be null since we haven't set it yet",
- d.getStructuralProperty(element));
+ assertNull("DeclareAtTypeDeclaration's " + element.getId() + " property"
+ + " should be null since we haven't set it yet", d.getStructuralProperty(element));
}
}
for (Iterator iter = props.iterator(); iter.hasNext();) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
if (element.getId().equals("pattern")) {
DefaultTypePattern p = ajast.newDefaultTypePattern();
- d.setStructuralProperty(element,p);
- assertEquals("DeclareAtTypeDeclaration's pattern property should" +
- " now be a DefaultTypePattern",p,d.getStructuralProperty(element));
+ d.setStructuralProperty(element, p);
+ assertEquals("DeclareAtTypeDeclaration's pattern property should" + " now be a DefaultTypePattern", p, d
+ .getStructuralProperty(element));
} else if (element.getId().equals("annotationName")) {
SimpleName s = ajast.newSimpleName("MyAnnotation");
- d.setStructuralProperty(element,s);
- assertEquals("DeclareAtTypeDeclaration's annotationName property should" +
- " now be a SimpleName",s,d.getStructuralProperty(element));
+ d.setStructuralProperty(element, s);
+ assertEquals("DeclareAtTypeDeclaration's annotationName property should" + " now be a SimpleName", s, d
+ .getStructuralProperty(element));
} else if (element.getId().equals("javadoc")) {
// do nothing since makes no sense to have javadoc
} else {
@@ -1267,15 +1183,15 @@ public class AjASTTest extends AjASTTestCase {
}
}
}
-
+
// -------------- DeclareErrorDeclaration tests ---------------
-
+
public void testNewDeclareErrorDeclaration() {
AjAST ajast = createAjAST();
DeclareErrorDeclaration d = ajast.newDeclareErrorDeclaration();
- assertNotNull("should have created a DeclareErrorDeclaration",d);
+ assertNotNull("should have created a DeclareErrorDeclaration", d);
}
-
+
public void testPropertyDescriptorsForDeclareErrorDeclaration() {
AjAST ajast = createAjAST();
DeclareErrorDeclaration d = ajast.newDeclareErrorDeclaration();
@@ -1296,67 +1212,60 @@ public class AjASTTest extends AjASTTestCase {
fail("unknown PropertyDescriptor associated with DeclareErrorDeclaration");
}
}
- assertTrue("DeclareErrorDeclaration should have a javadoc PropertyDescriptor",foundJavadoc);
- assertTrue("DeclareErrorDeclaration should have a pointcut PropertyDescriptor",foundPointcut);
- assertTrue("DeclareErrorDeclaration should have a message PropertyDescriptor",foundMessage);
+ assertTrue("DeclareErrorDeclaration should have a javadoc PropertyDescriptor", foundJavadoc);
+ assertTrue("DeclareErrorDeclaration should have a pointcut PropertyDescriptor", foundPointcut);
+ assertTrue("DeclareErrorDeclaration should have a message PropertyDescriptor", foundMessage);
}
-
+
public void testGetAndSetPointcutInErrorDeclaration() {
AjAST ajast = createAjAST();
DeclareErrorDeclaration d = ajast.newDeclareErrorDeclaration();
- assertNull("by default there should be no pointcut associated with" +
- " the declare error",d.getPointcut());
+ assertNull("by default there should be no pointcut associated with" + " the declare error", d.getPointcut());
AndPointcut p = ajast.newAndPointcut();
d.setPointcut(p);
- assertEquals("there should now be an AndPointcut associated with" +
- " the declare error",p,d.getPointcut());
+ assertEquals("there should now be an AndPointcut associated with" + " the declare error", p, d.getPointcut());
}
-
+
public void testGetAndSetMessageInErrorDeclaration() {
AjAST ajast = createAjAST();
DeclareErrorDeclaration d = ajast.newDeclareErrorDeclaration();
- assertNull("by default there should be no message associated with" +
- " the declare error",d.getMessage());
+ assertNull("by default there should be no message associated with" + " the declare error", d.getMessage());
StringLiteral s = ajast.newStringLiteral();
d.setMessage(s);
- assertEquals("there should now be a StringLiteral message associated with" +
- " the declare error",s,d.getMessage());
+ assertEquals("there should now be a StringLiteral message associated with" + " the declare error", s, d.getMessage());
}
-
+
public void testCloneDeclareErrorDeclaration() {
AjAST ajast = createAjAST();
DeclareErrorDeclaration d = ajast.newDeclareErrorDeclaration();
d.setPointcut(ajast.newAndPointcut());
d.setMessage(ajast.newStringLiteral());
- DeclareErrorDeclaration copy = (DeclareErrorDeclaration)ASTNode.copySubtree(ajast,d);
- assertNotNull("the DeclareErrorDeclaration clone should have a pointcut set",
- copy.getPointcut());
- assertNotNull("the DeclareErrorDeclaration clone should have a message set",
- copy.getMessage());
+ DeclareErrorDeclaration copy = (DeclareErrorDeclaration) ASTNode.copySubtree(ajast, d);
+ assertNotNull("the DeclareErrorDeclaration clone should have a pointcut set", copy.getPointcut());
+ assertNotNull("the DeclareErrorDeclaration clone should have a message set", copy.getMessage());
}
-
+
public void testInternalDeclareErrorDeclaration() {
AjAST ajast = createAjAST();
DeclareErrorDeclaration d = ajast.newDeclareErrorDeclaration();
List props = DeclareErrorDeclaration.propertyDescriptors(AST.JLS3);
for (Iterator iter = props.iterator(); iter.hasNext();) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
- assertNull("DeclareErrorDeclaration's " + element.getId() + " property" +
- "should be null since we haven't set it yet",
+ assertNull("DeclareErrorDeclaration's " + element.getId() + " property" + "should be null since we haven't set it yet",
d.getStructuralProperty(element));
}
for (Iterator iter = props.iterator(); iter.hasNext();) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
if (element.getId().equals("pointcut")) {
AndPointcut p = ajast.newAndPointcut();
- d.setStructuralProperty(element,p);
- assertEquals("DeclareErrorDeclaration's pointcut property should" +
- " now be an AndPointcut",p,d.getStructuralProperty(element));
+ d.setStructuralProperty(element, p);
+ assertEquals("DeclareErrorDeclaration's pointcut property should" + " now be an AndPointcut", p, d
+ .getStructuralProperty(element));
} else if (element.getId().equals("message")) {
StringLiteral s = ajast.newStringLiteral();
- d.setStructuralProperty(element,s);
- assertEquals("DeclareErrorDeclaration's message property should" +
- " now be an AndPointcut",s,d.getStructuralProperty(element));
+ d.setStructuralProperty(element, s);
+ assertEquals("DeclareErrorDeclaration's message property should" + " now be an AndPointcut", s, d
+ .getStructuralProperty(element));
} else if (element.getId().equals("javadoc")) {
// do nothing since makes no sense to have javadoc
} else {
@@ -1364,15 +1273,15 @@ public class AjASTTest extends AjASTTestCase {
}
}
}
-
+
// -------------- DeclareParentsDeclaration tests ---------------
public void testNewDeclareParentsDeclaration() {
AjAST ajast = createAjAST();
DeclareParentsDeclaration d = ajast.newDeclareParentsDeclaration();
- assertNotNull("should have created a DeclareParentsDeclaration",d);
+ assertNotNull("should have created a DeclareParentsDeclaration", d);
}
-
+
public void testPropertyDescriptorsForDeclareParentsDeclaration() {
AjAST ajast = createAjAST();
DeclareParentsDeclaration d = ajast.newDeclareParentsDeclaration();
@@ -1384,7 +1293,7 @@ public class AjASTTest extends AjASTTestCase {
for (Iterator iter = props.iterator(); iter.hasNext();) {
Object o = iter.next();
if ((o instanceof ChildPropertyDescriptor)) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor)o;
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
String id = element.getId();
if (id.equals("javadoc")) {
foundJavadoc = true;
@@ -1394,78 +1303,71 @@ public class AjASTTest extends AjASTTestCase {
fail("unknown PropertyDescriptor associated with DeclareParentsDeclaration: " + element.getId());
}
} else if ((o instanceof ChildListPropertyDescriptor)
- && ((ChildListPropertyDescriptor)o).getId().equals("typePatternsList")) {
- foundTypePatternList= true;
- } else if ((o instanceof SimplePropertyDescriptor)
- && ((SimplePropertyDescriptor)o).getId().equals("isExtends")) {
+ && ((ChildListPropertyDescriptor) o).getId().equals("typePatternsList")) {
+ foundTypePatternList = true;
+ } else if ((o instanceof SimplePropertyDescriptor) && ((SimplePropertyDescriptor) o).getId().equals("isExtends")) {
foundIsExtends = true;
} else {
fail("unknown PropertyDescriptor associated with DeclareErrorDeclaration: " + o);
}
}
- assertTrue("DeclareParentsDeclaration should have a javadoc PropertyDescriptor",foundJavadoc);
- assertTrue("DeclareParentsDeclaration should have a typePattern PropertyDescriptor",foundTypePattern);
- assertTrue("DeclareParentsDeclaration should have an isExtends PropertyDescriptor",foundIsExtends);
- assertTrue("DeclareParentsDeclaration should have a typePatternList PropertyDescriptor",foundTypePatternList);
+ assertTrue("DeclareParentsDeclaration should have a javadoc PropertyDescriptor", foundJavadoc);
+ assertTrue("DeclareParentsDeclaration should have a typePattern PropertyDescriptor", foundTypePattern);
+ assertTrue("DeclareParentsDeclaration should have an isExtends PropertyDescriptor", foundIsExtends);
+ assertTrue("DeclareParentsDeclaration should have a typePatternList PropertyDescriptor", foundTypePatternList);
}
-
+
public void testGetAndSetTypePatternInDeclareParentsDeclaration() {
AjAST ajast = createAjAST();
DeclareParentsDeclaration d = ajast.newDeclareParentsDeclaration();
- assertNull("by default there should be no TypePattern associated with" +
- " the declare parents",d.getChildTypePattern());
+ assertNull("by default there should be no TypePattern associated with" + " the declare parents", d.getChildTypePattern());
DefaultTypePattern dtp = ajast.newDefaultTypePattern();
d.setChildTypePattern(dtp);
- assertEquals("there should now be a DefaultTypePattern associated with" +
- " the declare parents",dtp,d.getChildTypePattern());
+ assertEquals("there should now be a DefaultTypePattern associated with" + " the declare parents", dtp, d
+ .getChildTypePattern());
}
-
+
public void testGetAndSetIsExtendsInDeclareParentsDeclaration() {
AjAST ajast = createAjAST();
DeclareParentsDeclaration d = ajast.newDeclareParentsDeclaration();
- assertFalse("by default the declare parents should not be 'extends'",d.isExtends());
+ assertFalse("by default the declare parents should not be 'extends'", d.isExtends());
d.setExtends(true);
- assertTrue("the declare parents should now be 'extends'",d.isExtends());
+ assertTrue("the declare parents should now be 'extends'", d.isExtends());
}
-
+
public void testTypePatternsInDeclareParents() {
AjAST ajast = createAjAST();
DeclareParentsDeclaration d = ajast.newDeclareParentsDeclaration();
List l = d.parentTypePatterns();
- assertEquals("there shouldn't be any type patterns associated with" +
- "the declare parents yet",0,l.size());
+ assertEquals("there shouldn't be any type patterns associated with" + "the declare parents yet", 0, l.size());
DefaultTypePattern dtp = ajast.newDefaultTypePattern();
l.add(dtp);
- assertEquals("there should be one type patterns associated with" +
- "the declare parents",1,l.size());
- assertEquals("there should be a DefaultTypePattern associated with" +
- "the declare parents",dtp,l.get(0));
-
+ assertEquals("there should be one type patterns associated with" + "the declare parents", 1, l.size());
+ assertEquals("there should be a DefaultTypePattern associated with" + "the declare parents", dtp, l.get(0));
+
}
-
+
public void testCloneDeclareParentsDeclaration() {
AjAST ajast = createAjAST();
DeclareParentsDeclaration d = ajast.newDeclareParentsDeclaration();
d.setChildTypePattern(ajast.newDefaultTypePattern());
d.setExtends(true);
d.parentTypePatterns().add(ajast.newDefaultTypePattern());
- DeclareParentsDeclaration copy = (DeclareParentsDeclaration)ASTNode.copySubtree(ajast,d);
- assertEquals("there should be one type patterns associated with" +
- "the declare parents copy",1,copy.parentTypePatterns().size());
- assertNotNull("the DeclareParentsDeclaration clone should have a typePattern set",
- copy.getChildTypePattern());
- assertTrue("the DeclareParentsDeclaration clone should be an 'extends'",
- copy.isExtends());
- }
-
+ DeclareParentsDeclaration copy = (DeclareParentsDeclaration) ASTNode.copySubtree(ajast, d);
+ assertEquals("there should be one type patterns associated with" + "the declare parents copy", 1, copy.parentTypePatterns()
+ .size());
+ assertNotNull("the DeclareParentsDeclaration clone should have a typePattern set", copy.getChildTypePattern());
+ assertTrue("the DeclareParentsDeclaration clone should be an 'extends'", copy.isExtends());
+ }
+
// -------------- DeclarePrecedenceDeclaration tests ---------------
public void testNewDeclarePrecedenceDeclaration() {
AjAST ajast = createAjAST();
DeclarePrecedenceDeclaration d = ajast.newDeclarePrecedenceDeclaration();
- assertNotNull("should have created a DeclarePrecedenceDeclaration",d);
+ assertNotNull("should have created a DeclarePrecedenceDeclaration", d);
}
-
+
public void testPropertyDescriptorsForDeclarePrecedence() {
AjAST ajast = createAjAST();
DeclarePrecedenceDeclaration d = ajast.newDeclarePrecedenceDeclaration();
@@ -1474,44 +1376,40 @@ public class AjASTTest extends AjASTTestCase {
boolean foundTypePatterns = false;
for (Iterator iter = props.iterator(); iter.hasNext();) {
Object o = iter.next();
- if ((o instanceof ChildPropertyDescriptor)
- && ((ChildPropertyDescriptor)o).getId().equals("javadoc")) {
+ if ((o instanceof ChildPropertyDescriptor) && ((ChildPropertyDescriptor) o).getId().equals("javadoc")) {
foundJavadoc = true;
} else if ((o instanceof ChildListPropertyDescriptor)
- && ((ChildListPropertyDescriptor)o).getId().equals("parentTypePatterns")) {
+ && ((ChildListPropertyDescriptor) o).getId().equals("parentTypePatterns")) {
foundTypePatterns = true;
} else {
fail("unknown PropertyDescriptor associated with DeclareErrorDeclaration: " + o);
}
}
- assertTrue("DeclareErrorDeclaration should have a javadoc PropertyDescriptor",foundJavadoc);
- assertTrue("DeclareErrorDeclaration should have a pointcut PropertyDescriptor",foundTypePatterns);
+ assertTrue("DeclareErrorDeclaration should have a javadoc PropertyDescriptor", foundJavadoc);
+ assertTrue("DeclareErrorDeclaration should have a pointcut PropertyDescriptor", foundTypePatterns);
}
-
+
public void testTypePatternsInDeclarePrecedence() {
AjAST ajast = createAjAST();
DeclarePrecedenceDeclaration d = ajast.newDeclarePrecedenceDeclaration();
List l = d.typePatterns();
- assertEquals("there shouldn't be any type patterns associated with" +
- "the declare precedence yet",0,l.size());
+ assertEquals("there shouldn't be any type patterns associated with" + "the declare precedence yet", 0, l.size());
DefaultTypePattern dtp = ajast.newDefaultTypePattern();
l.add(dtp);
- assertEquals("there should be one type patterns associated with" +
- "the declare precedence",1,l.size());
- assertEquals("there should be a DefaultTypePattern associated with" +
- "the declare precedence",dtp,l.get(0));
-
+ assertEquals("there should be one type patterns associated with" + "the declare precedence", 1, l.size());
+ assertEquals("there should be a DefaultTypePattern associated with" + "the declare precedence", dtp, l.get(0));
+
}
-
+
public void testCloneDeclarePrecedenceDeclaration() {
AjAST ajast = createAjAST();
DeclarePrecedenceDeclaration d = ajast.newDeclarePrecedenceDeclaration();
d.typePatterns().add(ajast.newDefaultTypePattern());
- DeclarePrecedenceDeclaration copy = (DeclarePrecedenceDeclaration)ASTNode.copySubtree(ajast,d);
- assertEquals("there should be one type patterns associated with" +
- "the declare precedence copy",1,copy.typePatterns().size());
+ DeclarePrecedenceDeclaration copy = (DeclarePrecedenceDeclaration) ASTNode.copySubtree(ajast, d);
+ assertEquals("there should be one type patterns associated with" + "the declare precedence copy", 1, copy.typePatterns()
+ .size());
}
-
+
public void testInternalDeclarePrecedenceDeclaration() {
AjAST ajast = createAjAST();
DeclarePrecedenceDeclaration d = ajast.newDeclarePrecedenceDeclaration();
@@ -1519,32 +1417,28 @@ public class AjASTTest extends AjASTTestCase {
for (Iterator iter = props.iterator(); iter.hasNext();) {
Object o = iter.next();
if (o instanceof ChildPropertyDescriptor) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor)o;
- assertNull("DeclareErrorDeclaration's " + element.getId() + " property" +
- "should be null since we haven't set it yet",
- d.getStructuralProperty(element));
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
+ assertNull("DeclareErrorDeclaration's " + element.getId() + " property"
+ + "should be null since we haven't set it yet", d.getStructuralProperty(element));
} else if (o instanceof ChildListPropertyDescriptor) {
- ChildListPropertyDescriptor element = (ChildListPropertyDescriptor)o;
- assertNotNull("DeclareErrorDeclaration's " + element.getId() + " property" +
- "should not be null since it is a list",
- d.getStructuralProperty(element));
- assertEquals("should only be able to put TypePattern's into the list",
- TypePattern.class,element.getElementType());
+ ChildListPropertyDescriptor element = (ChildListPropertyDescriptor) o;
+ assertNotNull("DeclareErrorDeclaration's " + element.getId() + " property"
+ + "should not be null since it is a list", d.getStructuralProperty(element));
+ assertEquals("should only be able to put TypePattern's into the list", TypePattern.class, element.getElementType());
} else {
fail("unknown PropertyDescriptor associated with DeclareErrorDeclaration: " + o);
}
}
}
-
// -------------- DeclareSoftDeclaration tests ---------------
-
+
public void testNewDeclareSoftDeclaration() {
AjAST ajast = createAjAST();
DeclareSoftDeclaration d = ajast.newDeclareSoftDeclaration();
- assertNotNull("should have created a DeclareSoftDeclaration",d);
+ assertNotNull("should have created a DeclareSoftDeclaration", d);
}
-
+
public void testPropertyDescriptorsForDeclareSoftDeclaration() {
AjAST ajast = createAjAST();
DeclareSoftDeclaration d = ajast.newDeclareSoftDeclaration();
@@ -1562,71 +1456,63 @@ public class AjASTTest extends AjASTTestCase {
} else if (id.equals("typePattern")) {
foundTypePattern = true;
} else {
- fail("unknown PropertyDescriptor associated with " +
- "DeclareSoftDeclaration: " + element.getId());
+ fail("unknown PropertyDescriptor associated with " + "DeclareSoftDeclaration: " + element.getId());
}
}
- assertTrue("DeclareSoftDeclaration should have a javadoc PropertyDescriptor",foundJavadoc);
- assertTrue("DeclareSoftDeclaration should have a pointcut PropertyDescriptor",foundPointcut);
- assertTrue("DeclareSoftDeclaration should have a type PropertyDescriptor",foundTypePattern);
+ assertTrue("DeclareSoftDeclaration should have a javadoc PropertyDescriptor", foundJavadoc);
+ assertTrue("DeclareSoftDeclaration should have a pointcut PropertyDescriptor", foundPointcut);
+ assertTrue("DeclareSoftDeclaration should have a type PropertyDescriptor", foundTypePattern);
}
-
+
public void testGetAndSetPointcutInSoftDeclaration() {
AjAST ajast = createAjAST();
DeclareSoftDeclaration d = ajast.newDeclareSoftDeclaration();
- assertNull("by default there should be no pointcut associated with" +
- " the declare soft",d.getPointcut());
+ assertNull("by default there should be no pointcut associated with" + " the declare soft", d.getPointcut());
AndPointcut p = ajast.newAndPointcut();
d.setPointcut(p);
- assertEquals("there should now be an AndPointcut associated with" +
- " the declare soft",p,d.getPointcut());
+ assertEquals("there should now be an AndPointcut associated with" + " the declare soft", p, d.getPointcut());
}
-
+
public void testGetAndSetTypePatternInSoftDeclaration() {
AjAST ajast = createAjAST();
DeclareSoftDeclaration d = ajast.newDeclareSoftDeclaration();
- assertNull("by default there should be no TypePattern associated with" +
- " the declare soft",d.getTypePattern());
+ assertNull("by default there should be no TypePattern associated with" + " the declare soft", d.getTypePattern());
DefaultTypePattern dtp = ajast.newDefaultTypePattern();
d.setTypePattern(dtp);
- assertEquals("there should now be a DefaultTypePattern associated with" +
- " the declare soft",dtp,d.getTypePattern());
+ assertEquals("there should now be a DefaultTypePattern associated with" + " the declare soft", dtp, d.getTypePattern());
}
-
+
public void testCloneDeclareSoftDeclaration() {
AjAST ajast = createAjAST();
DeclareSoftDeclaration d = ajast.newDeclareSoftDeclaration();
d.setPointcut(ajast.newAndPointcut());
d.setTypePattern(ajast.newDefaultTypePattern());
- DeclareSoftDeclaration copy = (DeclareSoftDeclaration)ASTNode.copySubtree(ajast,d);
- assertNotNull("the DeclareSoftDeclaration clone should have a pointcut set",
- copy.getPointcut());
- assertNotNull("the DeclareSoftDeclaration clone should have a typePattern set",
- copy.getTypePattern());
+ DeclareSoftDeclaration copy = (DeclareSoftDeclaration) ASTNode.copySubtree(ajast, d);
+ assertNotNull("the DeclareSoftDeclaration clone should have a pointcut set", copy.getPointcut());
+ assertNotNull("the DeclareSoftDeclaration clone should have a typePattern set", copy.getTypePattern());
}
-
+
public void testInternalDeclareSoftDeclaration() {
AjAST ajast = createAjAST();
DeclareSoftDeclaration d = ajast.newDeclareSoftDeclaration();
List props = DeclareSoftDeclaration.propertyDescriptors(AST.JLS3);
for (Iterator iter = props.iterator(); iter.hasNext();) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
- assertNull("DeclareSoftDeclaration's " + element.getId() + " property" +
- "should be null since we haven't set it yet",
+ assertNull("DeclareSoftDeclaration's " + element.getId() + " property" + "should be null since we haven't set it yet",
d.getStructuralProperty(element));
}
for (Iterator iter = props.iterator(); iter.hasNext();) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
if (element.getId().equals("pointcut")) {
AndPointcut p = ajast.newAndPointcut();
- d.setStructuralProperty(element,p);
- assertEquals("DeclareSoftDeclaration's pointcut property should" +
- " now be an AndPointcut",p,d.getStructuralProperty(element));
+ d.setStructuralProperty(element, p);
+ assertEquals("DeclareSoftDeclaration's pointcut property should" + " now be an AndPointcut", p, d
+ .getStructuralProperty(element));
} else if (element.getId().equals("typePattern")) {
DefaultTypePattern dtp = ajast.newDefaultTypePattern();
- d.setStructuralProperty(element,dtp);
- assertEquals("DeclareSoftDeclaration's typePattern property should" +
- " now be an DefaultTypePattern",dtp,d.getStructuralProperty(element));
+ d.setStructuralProperty(element, dtp);
+ assertEquals("DeclareSoftDeclaration's typePattern property should" + " now be an DefaultTypePattern", dtp, d
+ .getStructuralProperty(element));
} else if (element.getId().equals("javadoc")) {
// do nothing since makes no sense to have javadoc
} else {
@@ -1634,15 +1520,15 @@ public class AjASTTest extends AjASTTestCase {
}
}
}
-
+
// -------------- DeclareWarningDeclaration tests ---------------
public void testNewDeclareWarningDeclaration() {
AjAST ajast = createAjAST();
DeclareWarningDeclaration d = ajast.newDeclareWarningDeclaration();
- assertNotNull("should have created a DeclareWarningDeclaration",d);
+ assertNotNull("should have created a DeclareWarningDeclaration", d);
}
-
+
public void testPropertyDescriptorsForDeclareWarningDeclaration() {
AjAST ajast = createAjAST();
DeclareWarningDeclaration d = ajast.newDeclareWarningDeclaration();
@@ -1663,67 +1549,60 @@ public class AjASTTest extends AjASTTestCase {
fail("unknown PropertyDescriptor associated with DeclareWarningDeclaration");
}
}
- assertTrue("DeclareWarningDeclaration should have a javadoc PropertyDescriptor",foundJavadoc);
- assertTrue("DeclareWarningDeclaration should have a pointcut PropertyDescriptor",foundPointcut);
- assertTrue("DeclareWarningDeclaration should have a message PropertyDescriptor",foundMessage);
+ assertTrue("DeclareWarningDeclaration should have a javadoc PropertyDescriptor", foundJavadoc);
+ assertTrue("DeclareWarningDeclaration should have a pointcut PropertyDescriptor", foundPointcut);
+ assertTrue("DeclareWarningDeclaration should have a message PropertyDescriptor", foundMessage);
}
-
+
public void testGetAndSetPointcutInWarningDeclaration() {
AjAST ajast = createAjAST();
DeclareWarningDeclaration d = ajast.newDeclareWarningDeclaration();
- assertNull("by default there should be no pointcut associated with" +
- " the declare warning",d.getPointcut());
+ assertNull("by default there should be no pointcut associated with" + " the declare warning", d.getPointcut());
AndPointcut p = ajast.newAndPointcut();
d.setPointcut(p);
- assertEquals("there should now be an AndPointcut associated with" +
- " the declare warning",p,d.getPointcut());
+ assertEquals("there should now be an AndPointcut associated with" + " the declare warning", p, d.getPointcut());
}
-
+
public void testGetAndSetMessageInWarningDeclaration() {
AjAST ajast = createAjAST();
DeclareWarningDeclaration d = ajast.newDeclareWarningDeclaration();
- assertNull("by default there should be no message associated with" +
- " the declare warning",d.getMessage());
+ assertNull("by default there should be no message associated with" + " the declare warning", d.getMessage());
StringLiteral s = ajast.newStringLiteral();
d.setMessage(s);
- assertEquals("there should now be a StringLiteral message associated with" +
- " the declare warning",s,d.getMessage());
+ assertEquals("there should now be a StringLiteral message associated with" + " the declare warning", s, d.getMessage());
}
-
+
public void testCloneDeclareWarningDeclaration() {
AjAST ajast = createAjAST();
DeclareWarningDeclaration d = ajast.newDeclareWarningDeclaration();
d.setPointcut(ajast.newAndPointcut());
d.setMessage(ajast.newStringLiteral());
- DeclareWarningDeclaration copy = (DeclareWarningDeclaration)ASTNode.copySubtree(ajast,d);
- assertNotNull("the DeclareWarningDeclaration clone should have a pointcut set",
- copy.getPointcut());
- assertNotNull("the DeclareWarningDeclaration clone should have a message set",
- copy.getMessage());
+ DeclareWarningDeclaration copy = (DeclareWarningDeclaration) ASTNode.copySubtree(ajast, d);
+ assertNotNull("the DeclareWarningDeclaration clone should have a pointcut set", copy.getPointcut());
+ assertNotNull("the DeclareWarningDeclaration clone should have a message set", copy.getMessage());
}
-
+
public void testInternalDeclareWarningDeclaration() {
AjAST ajast = createAjAST();
DeclareWarningDeclaration d = ajast.newDeclareWarningDeclaration();
List props = DeclareWarningDeclaration.propertyDescriptors(AST.JLS3);
for (Iterator iter = props.iterator(); iter.hasNext();) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
- assertNull("DeclareWarningDeclaration's " + element.getId() + " property" +
- "should be null since we haven't set it yet",
- d.getStructuralProperty(element));
+ assertNull("DeclareWarningDeclaration's " + element.getId() + " property"
+ + "should be null since we haven't set it yet", d.getStructuralProperty(element));
}
for (Iterator iter = props.iterator(); iter.hasNext();) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
if (element.getId().equals("pointcut")) {
AndPointcut p = ajast.newAndPointcut();
- d.setStructuralProperty(element,p);
- assertEquals("DeclareWarningDeclaration's pointcut property should" +
- " now be an AndPointcut",p,d.getStructuralProperty(element));
+ d.setStructuralProperty(element, p);
+ assertEquals("DeclareWarningDeclaration's pointcut property should" + " now be an AndPointcut", p, d
+ .getStructuralProperty(element));
} else if (element.getId().equals("message")) {
StringLiteral s = ajast.newStringLiteral();
- d.setStructuralProperty(element,s);
- assertEquals("DeclareWarningDeclaration's message property should" +
- " now be an AndPointcut",s,d.getStructuralProperty(element));
+ d.setStructuralProperty(element, s);
+ assertEquals("DeclareWarningDeclaration's message property should" + " now be an AndPointcut", s, d
+ .getStructuralProperty(element));
} else if (element.getId().equals("javadoc")) {
// do nothing since makes no sense to have javadoc
} else {
@@ -1731,78 +1610,76 @@ public class AjASTTest extends AjASTTestCase {
}
}
}
-
+
// --------- testing that the source ranges have been set correctly ---------
-
- public void testDeclareAnnotationType(){
- checkJLS3("@interface MyAnnotation{}class C{}aspect A{declare @type: C : @MyAnnotation;}",
- 43,33);
+
+ public void testDeclareAnnotationType() {
+ checkJLS3("@interface MyAnnotation{}class C{}aspect A{declare @type: C : @MyAnnotation;}", 43, 33);
}
- public void testDeclareAnnotationMethod(){
- checkJLS3("@interface MyAnnotation{}class C{}aspect A{declare @method:public * C.*(..) : @MyAnnotation;}",
- 43,49);
+
+ public void testDeclareAnnotationMethod() {
+ checkJLS3("@interface MyAnnotation{}class C{}aspect A{declare @method:public * C.*(..) : @MyAnnotation;}", 43, 49);
}
- public void testDeclareAnnotationField(){
- checkJLS3("@interface MyAnnotation{}class C{}aspect A{declare @field: * C+.* : @MyAnnotation;}",
- 43,39);
+
+ public void testDeclareAnnotationField() {
+ checkJLS3("@interface MyAnnotation{}class C{}aspect A{declare @field: * C+.* : @MyAnnotation;}", 43, 39);
}
- public void testDeclareAnnotationConstructor(){
- checkJLS3("@interface MyAnnotation{}class C{}aspect A{declare @constructor: C+.new(..) : @MyAnnotation;}",
- 43,49);
+
+ public void testDeclareAnnotationConstructor() {
+ checkJLS3("@interface MyAnnotation{}class C{}aspect A{declare @constructor: C+.new(..) : @MyAnnotation;}", 43, 49);
}
- public void testDeclareParents(){
- checkJLS3("class A{}class B{}aspect C {declare parents : A extends B;}",
- 28,29);
+
+ public void testDeclareParents() {
+ checkJLS3("class A{}class B{}aspect C {declare parents : A extends B;}", 28, 29);
}
- public void testDeclareWarning(){
- checkJLS3("aspect A {pointcut a();declare warning: a(): \"error\";}",
- 23,30);
+
+ public void testDeclareWarning() {
+ checkJLS3("aspect A {pointcut a();declare warning: a(): \"error\";}", 23, 30);
}
- public void testDeclareError(){
- checkJLS3("aspect A {pointcut a();declare error: a(): \"error\";}",
- 23,28);
+
+ public void testDeclareError() {
+ checkJLS3("aspect A {pointcut a();declare error: a(): \"error\";}", 23, 28);
}
- public void testDeclareSoft(){
- checkJLS3("aspect A {pointcut a();declare soft: Exception+: a();}",
- 23,29);
+
+ public void testDeclareSoft() {
+ checkJLS3("aspect A {pointcut a();declare soft: Exception+: a();}", 23, 29);
}
- public void testDeclarePrecedence(){
- checkJLS3("aspect A{}aspect B{declare precedence: B,A;}",
- 19,23);
+
+ public void testDeclarePrecedence() {
+ checkJLS3("aspect A{}aspect B{declare precedence: B,A;}", 19, 23);
}
// --------- tests for bugs ----------
-
+
public void testJavadocCommentForDeclareExists_pr150467() {
ASTParser parser = ASTParser.newParser(AST.JLS3);
- parser.setSource("aspect X {/** I have a doc comment */declare parents : Y implements Z;}".toCharArray());
- parser.setCompilerOptions(Collections.EMPTY_MAP);
- parser.setKind(ASTParser.K_COMPILATION_UNIT);
- CompilationUnit cu = (CompilationUnit) parser.createAST(null);
- Javadoc javadoc = ((DeclareParentsDeclaration) ((TypeDeclaration)
- cu.types().get(0)).bodyDeclarations().get(0)).getJavadoc();
- assertNull("expected the doc comment node to be null but it wasn't",javadoc);
- assertEquals("expected there to be one comment but found " +
- cu.getCommentList().size(),1,cu.getCommentList().size());
- }
-
+ parser.setSource("aspect X {/** I have a doc comment */declare parents : Y implements Z;}".toCharArray());
+ parser.setCompilerOptions(Collections.EMPTY_MAP);
+ parser.setKind(ASTParser.K_COMPILATION_UNIT);
+ CompilationUnit cu = (CompilationUnit) parser.createAST(null);
+ Javadoc javadoc = ((DeclareParentsDeclaration) ((TypeDeclaration) cu.types().get(0)).bodyDeclarations().get(0))
+ .getJavadoc();
+ assertNull("expected the doc comment node to be null but it wasn't", javadoc);
+ assertEquals("expected there to be one comment but found " + cu.getCommentList().size(), 1, cu.getCommentList().size());
+ }
+
}
class SourceRangeVisitor extends AjASTVisitor {
-
+
boolean visitTheKids = true;
boolean visitDocTags;
int start, length;
-
+
SourceRangeVisitor() {
this(false);
}
-
+
SourceRangeVisitor(boolean visitDocTags) {
super(visitDocTags);
this.visitDocTags = visitDocTags;
}
-
+
public boolean isVisitingChildren() {
return visitTheKids;
}
@@ -1810,55 +1687,63 @@ class SourceRangeVisitor extends AjASTVisitor {
public void setVisitingChildren(boolean visitChildren) {
visitTheKids = visitChildren;
}
-
+
public int getStart() {
return start;
}
-
+
public int getLength() {
return length;
}
-
+
public boolean visit(DeclareAtTypeDeclaration node) {
start = node.getStartPosition();
length = node.getLength();
return isVisitingChildren();
}
+
public boolean visit(DeclareAtMethodDeclaration node) {
start = node.getStartPosition();
length = node.getLength();
return isVisitingChildren();
}
+
public boolean visit(DeclareAtConstructorDeclaration node) {
start = node.getStartPosition();
length = node.getLength();
return isVisitingChildren();
}
+
public boolean visit(DeclareAtFieldDeclaration node) {
start = node.getStartPosition();
length = node.getLength();
return isVisitingChildren();
}
+
public boolean visit(DeclareWarningDeclaration node) {
start = node.getStartPosition();
length = node.getLength();
return isVisitingChildren();
}
+
public boolean visit(DeclareErrorDeclaration node) {
start = node.getStartPosition();
length = node.getLength();
return isVisitingChildren();
}
+
public boolean visit(DeclareParentsDeclaration node) {
start = node.getStartPosition();
length = node.getLength();
return isVisitingChildren();
}
+
public boolean visit(DeclarePrecedenceDeclaration node) {
start = node.getStartPosition();
length = node.getLength();
return isVisitingChildren();
}
+
public boolean visit(DeclareSoftDeclaration node) {
start = node.getStartPosition();
length = node.getLength();