diff options
author | Walter Harley | 2006-12-21 00:06:25 +0000 |
---|---|---|
committer | Walter Harley | 2006-12-21 00:06:25 +0000 |
commit | 3363755daf5e11f7ba5c27ee1ed39285b9c60a26 (patch) | |
tree | aaee6cb04a545406327581eb4b2664049d54ecce | |
parent | b7f468690a70977c68b74d1aeee81bdba359d238 (diff) | |
download | eclipse.jdt.core-3363755daf5e11f7ba5c27ee1ed39285b9c60a26.tar.gz eclipse.jdt.core-3363755daf5e11f7ba5c27ee1ed39285b9c60a26.tar.xz eclipse.jdt.core-3363755daf5e11f7ba5c27ee1ed39285b9c60a26.zip |
Initial check-in of JSR269 APT test code. This only tests against javac, for now, since APT is not yet working in Eclipse compiler.
14 files changed, 711 insertions, 0 deletions
diff --git a/org.eclipse.jdt.compiler.apt.tests/.classpath b/org.eclipse.jdt.compiler.apt.tests/.classpath new file mode 100644 index 0000000000..8c8c8d2b5d --- /dev/null +++ b/org.eclipse.jdt.compiler.apt.tests/.classpath @@ -0,0 +1,8 @@ +<?xml version="1.0" encoding="UTF-8"?> +<classpath> + <classpathentry kind="src" path="src"/> + <classpathentry kind="src" path="processors"/> + <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/> + <classpathentry kind="output" path="bin"/> +</classpath> diff --git a/org.eclipse.jdt.compiler.apt.tests/.cvsignore b/org.eclipse.jdt.compiler.apt.tests/.cvsignore new file mode 100644 index 0000000000..c5e82d7458 --- /dev/null +++ b/org.eclipse.jdt.compiler.apt.tests/.cvsignore @@ -0,0 +1 @@ +bin
\ No newline at end of file diff --git a/org.eclipse.jdt.compiler.apt.tests/.project b/org.eclipse.jdt.compiler.apt.tests/.project index 5dc12adebd..42bae08041 100644 --- a/org.eclipse.jdt.compiler.apt.tests/.project +++ b/org.eclipse.jdt.compiler.apt.tests/.project @@ -5,7 +5,24 @@ <projects> </projects> <buildSpec> + <buildCommand> + <name>org.eclipse.jdt.core.javabuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.ManifestBuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.SchemaBuilder</name> + <arguments> + </arguments> + </buildCommand> </buildSpec> <natures> + <nature>org.eclipse.pde.PluginNature</nature> + <nature>org.eclipse.jdt.core.javanature</nature> </natures> </projectDescription> diff --git a/org.eclipse.jdt.compiler.apt.tests/.settings/org.eclipse.jdt.core.prefs b/org.eclipse.jdt.compiler.apt.tests/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..dbefeaa4c5 --- /dev/null +++ b/org.eclipse.jdt.compiler.apt.tests/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,62 @@ +#Tue Dec 05 20:54:14 EST 2006 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +org.eclipse.jdt.core.compiler.problem.deprecation=warning +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled +org.eclipse.jdt.core.compiler.problem.discouragedReference=ignore +org.eclipse.jdt.core.compiler.problem.emptyStatement=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore +org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore +org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning +org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=ignore +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore +org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning +org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore +org.eclipse.jdt.core.compiler.problem.nullReference=ignore +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore +org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +org.eclipse.jdt.core.compiler.problem.unusedImport=warning +org.eclipse.jdt.core.compiler.problem.unusedLabel=warning +org.eclipse.jdt.core.compiler.problem.unusedLocal=warning +org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/org.eclipse.jdt.compiler.apt.tests/META-INF/MANIFEST.MF b/org.eclipse.jdt.compiler.apt.tests/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..6465ff73b5 --- /dev/null +++ b/org.eclipse.jdt.compiler.apt.tests/META-INF/MANIFEST.MF @@ -0,0 +1,13 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: %pluginName +Bundle-SymbolicName: org.eclipse.jdt.compiler.apt.tests +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: %providerName +Bundle-Localization: plugin +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Require-Bundle: org.eclipse.jdt.core;bundle-version="3.2.2", + org.junit, + org.eclipse.jdt.compiler.tool +Bundle-ClassPath: compilerapttests.jar +Export-Package: org.eclipse.jdt.compiler.apt.tests diff --git a/org.eclipse.jdt.compiler.apt.tests/META-INF/services/javax.annotation.processing.Processor b/org.eclipse.jdt.compiler.apt.tests/META-INF/services/javax.annotation.processing.Processor new file mode 100644 index 0000000000..e10fb74ce3 --- /dev/null +++ b/org.eclipse.jdt.compiler.apt.tests/META-INF/services/javax.annotation.processing.Processor @@ -0,0 +1 @@ +proc.genclass.GenClassProc
\ No newline at end of file diff --git a/org.eclipse.jdt.compiler.apt.tests/apttestprocessors.jardesc b/org.eclipse.jdt.compiler.apt.tests/apttestprocessors.jardesc new file mode 100644 index 0000000000..3d3f01dae8 --- /dev/null +++ b/org.eclipse.jdt.compiler.apt.tests/apttestprocessors.jardesc @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="WINDOWS-1252"?> +<jardesc> +<jar path="./export/apttestprocessors.jar"/> +<options buildIfNeeded="true" compress="true" descriptionLocation="/org.eclipse.jdt.compiler.apt.tests/apttestprocessors.jardesc" exportErrors="false" exportWarnings="true" includeDirectoryEntries="false" overwrite="true" saveDescription="true" storeRefactorings="false" useSourceFolders="false"/> +<storedRefactorings deprecationInfo="true" structuralOnly="false"/> +<selectedProjects/> +<manifest generateManifest="true" manifestLocation="" manifestVersion="1.0" reuseManifest="false" saveManifest="false" usesManifest="true"> +<sealing sealJar="false"> +<packagesToSeal/> +<packagesToUnSeal/> +</sealing> +</manifest> +<selectedElements exportClassFiles="true" exportJavaFiles="true" exportOutputFolder="false"> +<folder path="/org.eclipse.jdt.compiler.apt.tests/META-INF/services"/> +<javaElement handleIdentifier="=org.eclipse.jdt.compiler.apt.tests/processors"/> +</selectedElements> +</jardesc> diff --git a/org.eclipse.jdt.compiler.apt.tests/build.properties b/org.eclipse.jdt.compiler.apt.tests/build.properties new file mode 100644 index 0000000000..3dbceb94a9 --- /dev/null +++ b/org.eclipse.jdt.compiler.apt.tests/build.properties @@ -0,0 +1,33 @@ +############################################################################### +# Copyright (c) 2006 BEA Systems Inc. +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# wharley@bea.com - initial API and implementation +############################################################################### +bin.includes = META-INF/,\ + about.html,\ + plugin.properties,\ + test.xml,\ + compilerapttests.jar,\ + apttestprocessors.jar +src.includes = src/,\ + about.html,\ + META-INF/,\ + .project,\ + .cvsignore,\ + build.properties,\ + plugin.properties,\ + .classpath,\ + test.xml,\ + .settings/,\ + processors/,\ + apttestprocessors.jardesc +source.compilerapttests.jar = src/ +bin.excludes = META-INF/services/ +jars.compile.order = compilerapttests.jar,\ + apttestprocessors.jar +source.apttestprocessors.jar = processors/ diff --git a/org.eclipse.jdt.compiler.apt.tests/plugin.properties b/org.eclipse.jdt.compiler.apt.tests/plugin.properties new file mode 100644 index 0000000000..e2ee11fb77 --- /dev/null +++ b/org.eclipse.jdt.compiler.apt.tests/plugin.properties @@ -0,0 +1,12 @@ +############################################################################### +# Copyright (c) 2006 BEA Systems Inc. and others. +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# wharley@bea.com - initial API and implementation +############################################################################### +providerName=Eclipse.org +pluginName=Java Annotation Processing Tests diff --git a/org.eclipse.jdt.compiler.apt.tests/processors/anno/GenClass.java b/org.eclipse.jdt.compiler.apt.tests/processors/anno/GenClass.java new file mode 100644 index 0000000000..6ac26deba0 --- /dev/null +++ b/org.eclipse.jdt.compiler.apt.tests/processors/anno/GenClass.java @@ -0,0 +1,22 @@ +/******************************************************************************* + * Copyright (c) 2006 BEA Systems, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * wharley@bea.com - initial API and implementation + * + *******************************************************************************/ +package anno; + +/** + * Processing this annotation will produce a class whose name is the value of + * <code>clazz</code>, with a method whose name is the value of + * <code>method</code> and whose return type is <code>String</code>. + */ +public @interface GenClass { + String clazz(); + String method(); +} diff --git a/org.eclipse.jdt.compiler.apt.tests/processors/proc/genclass/GenClassProc.java b/org.eclipse.jdt.compiler.apt.tests/processors/proc/genclass/GenClassProc.java new file mode 100644 index 0000000000..67f50d3fcb --- /dev/null +++ b/org.eclipse.jdt.compiler.apt.tests/processors/proc/genclass/GenClassProc.java @@ -0,0 +1,145 @@ +/******************************************************************************* + * Copyright (c) 2006 BEA Systems, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * wharley@bea.com - initial API and implementation + * + *******************************************************************************/ +package proc.genclass; + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.Writer; +import java.util.Map; +import java.util.Set; + +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.Filer; +import javax.annotation.processing.Messager; +import javax.annotation.processing.ProcessingEnvironment; +import javax.annotation.processing.RoundEnvironment; +import javax.annotation.processing.SupportedAnnotationTypes; +import javax.annotation.processing.SupportedSourceVersion; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.AnnotationValue; +import javax.lang.model.element.Element; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.util.Elements; +import javax.tools.Diagnostic; +import javax.tools.JavaFileObject; + +@SupportedAnnotationTypes("anno.GenClass") +@SupportedSourceVersion(SourceVersion.RELEASE_6) +public class GenClassProc extends AbstractProcessor { + + private Messager _messager; + private Filer _filer; + private Elements _elementUtil; + private TypeElement _annoDecl; + + @Override + public synchronized void init(ProcessingEnvironment processingEnv) { + super.init(processingEnv); + _filer = processingEnv.getFiler(); + _messager = processingEnv.getMessager(); + _elementUtil = processingEnv.getElementUtils(); + _annoDecl = _elementUtil.getTypeElement("anno.GenClass"); + + //System.out.println("Processor options are: "); + //for (Map.Entry<String, String> option : processingEnv.getOptions().entrySet()) { + // System.out.println(option.getKey() + " -> " + option.getValue()); + //} + } + + @Override + public boolean process(Set<? extends TypeElement> annotations, + RoundEnvironment roundEnv) { + + if (annotations == null || annotations.isEmpty()) { + return true; + } + // sanity check + if (!annotations.contains(_annoDecl)) { + throw new IllegalArgumentException("process() called on an unexpected set of annotations"); + } + + // get annotated declarations - could also use getElsAnnoWith(Class) form. + for (Element d : roundEnv.getElementsAnnotatedWith(_annoDecl)) { + // get annotations on the declaration + String clazz = null; + String method = null; + for (AnnotationMirror am : d.getAnnotationMirrors()) { + if (am.getAnnotationType().asElement().equals(_annoDecl)) { + // query the annotation to get its values + Map<? extends ExecutableElement, ? extends AnnotationValue> values = am.getElementValues(); + // find the "clazz" and "msg" values + for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : values.entrySet()) { + // System.out.println("found a value named " + entry.getKey().getSimpleName() + " with value " + entry.getValue().getValue()); + if ("clazz".equals(entry.getKey().getSimpleName().toString())) { + clazz = (String)entry.getValue().getValue(); + } + if ("method".equals(entry.getKey().getSimpleName().toString())) { + method = (String)entry.getValue().getValue(); + } + } + + if (null == clazz || clazz.length() > 40) { + _messager.printMessage(Diagnostic.Kind.WARNING, "Long name for clazz()", d, am); + clazz = null; + break; + } + if (null == method || method.length() > 10) { + _messager.printMessage(Diagnostic.Kind.WARNING, "Long name for method()", d, am); + method = null; + break; + } + } + } + + if (null != clazz && null != method) + createSourceFile(clazz, method); + } + return true; + } + + /** + * Create a source file named 'name', with contents + * that reflect 'method' and 'name'. + * @param clazz a fully qualified classname + * @param method the name of a method that will be + * added to the class + */ + private void createSourceFile(String clazz, String method) { + int lastDot = clazz.lastIndexOf('.'); + if (lastDot <= 0 || clazz.length() == lastDot) + return; + String pkg = clazz.substring(0, lastDot); + String lname = clazz.substring(lastDot + 1); + Writer w = null; + PrintWriter pw = null; + try { + JavaFileObject jfo = _filer.createSourceFile(clazz); + w = jfo.openWriter(); + pw = new PrintWriter(w); + pw.println("package " + pkg + ";"); + pw.println("public class " + lname + " {"); + pw.println("\tpublic String " + method + "() {"); + // This compile error won't be reported if the -proc:only flag is set: + // pw.println("\t\tb = a;"); + pw.println("\t\treturn new String(\"" + clazz + "\");"); + pw.println("\t}"); + pw.println("}"); + pw.close(); + w.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/org.eclipse.jdt.compiler.apt.tests/src/org/eclipse/jdt/compiler/apt/tests/AllTests.java b/org.eclipse.jdt.compiler.apt.tests/src/org/eclipse/jdt/compiler/apt/tests/AllTests.java new file mode 100644 index 0000000000..04e237d5ec --- /dev/null +++ b/org.eclipse.jdt.compiler.apt.tests/src/org/eclipse/jdt/compiler/apt/tests/AllTests.java @@ -0,0 +1,28 @@ +/******************************************************************************* + * Copyright (c) 2006 BEA Systems, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * wharley@bea.com - initial API and implementation + * + *******************************************************************************/ +package org.eclipse.jdt.compiler.apt.tests; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Helper class to run all the compiler tool tests + */ +public class AllTests extends TestCase { + // run all tests + public static Test suite() { + TestSuite suite = new TestSuite(); + suite.addTestSuite(CompilerAptTests.class); + return suite; + } +} diff --git a/org.eclipse.jdt.compiler.apt.tests/src/org/eclipse/jdt/compiler/apt/tests/CompilerAptTests.java b/org.eclipse.jdt.compiler.apt.tests/src/org/eclipse/jdt/compiler/apt/tests/CompilerAptTests.java new file mode 100644 index 0000000000..ebfcea4b57 --- /dev/null +++ b/org.eclipse.jdt.compiler.apt.tests/src/org/eclipse/jdt/compiler/apt/tests/CompilerAptTests.java @@ -0,0 +1,300 @@ +/******************************************************************************* + * Copyright (c) 2006 BEA Systems, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * wharley@bea.com - initial API and implementation + * + *******************************************************************************/ +package org.eclipse.jdt.compiler.apt.tests; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.ServiceLoader; + +import javax.tools.FileObject; +import javax.tools.ForwardingJavaFileManager; +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +import javax.tools.StandardJavaFileManager; +import javax.tools.ToolProvider; +import javax.tools.JavaCompiler.CompilationTask; +import javax.tools.JavaFileObject.Kind; + +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.jdt.internal.compiler.tool.EclipseCompiler; + +public class CompilerAptTests extends TestCase { + + // relative to workspace root + protected static final String _processorJarName = "..\\export\\apttestprocessors.jar"; + + // class that generates another class, using processor for @Echo + protected static final String _echoSource = + "package p;\n" + + "import anno.GenClass;\n" + + "import gen.XGen;\n" + + "@GenClass(clazz=\"gen.XGen\", method=\"foo\")\n" + + "public class X {\n" + + "\tXGen _xgen;\n" + + "}\n" ; + + // locations to generate files + protected static final String _tmpFolder = System.getProperty("java.io.tmpdir") + "eclipse-temp"; + + private static final String[] ONE_ARG_OPTIONS = { + "-s", + "-processor", + "-processorpath" + }; + private static final String[] ZERO_ARG_OPTIONS = { + "-proc:none", + "-proc:only", + "-XprintProcessorInfo", + "-XprintRounds" + }; + + protected JavaCompiler _eclipseCompiler; + + protected String _tmpSrcFolderName; + protected File _tmpSrcDir; + protected String _tmpBinFolderName; + protected File _tmpBinDir; + protected String _tmpGenFolderName; + protected File _tmpGenDir; + + public static TestSuite suite() { + TestSuite suite = new TestSuite(); + suite.addTestSuite(CompilerAptTests.class); + return suite; + } + + public CompilerAptTests(String name) { + super(name); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + + _tmpBinFolderName = _tmpFolder + File.separator + "bin"; + _tmpBinDir = new File(_tmpBinFolderName); + deleteTree(_tmpBinDir); // remove existing contents + _tmpBinDir.mkdirs(); + assert _tmpBinDir.exists() : "couldn't mkdirs " + _tmpBinFolderName; + + _tmpGenFolderName = _tmpFolder + File.separator + "gen-src"; + _tmpGenDir = new File(_tmpGenFolderName); + deleteTree(_tmpGenDir); // remove existing contents + _tmpGenDir.mkdirs(); + assert _tmpGenDir.exists() : "couldn't mkdirs " + _tmpGenFolderName; + + _tmpSrcFolderName = _tmpFolder + File.separator + "src"; + _tmpSrcDir = new File(_tmpSrcFolderName); + deleteTree(_tmpSrcDir); // remove existing contents + _tmpSrcDir.mkdirs(); + assert _tmpSrcDir.exists() : "couldn't mkdirs " + _tmpSrcFolderName; + + File processorJar = new File(_processorJarName); + assertTrue("Couldn't find processor jar at " + processorJar.getAbsolutePath(), processorJar.exists()); + + ServiceLoader<JavaCompiler> javaCompilerLoader = ServiceLoader.load(JavaCompiler.class);//, EclipseCompiler.class.getClassLoader()); + int compilerCounter = 0; + for (JavaCompiler javaCompiler : javaCompilerLoader) { + compilerCounter++; + if (javaCompiler instanceof EclipseCompiler) { + _eclipseCompiler = javaCompiler; + } + } + assertEquals("Only one compiler available", 1, compilerCounter); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + + /** + * Verify that Eclipse compiler properly supports apt-related command line options + */ + public void testCheckOptions() { + assertNotNull("No compiler found", _eclipseCompiler); + for (String option : ONE_ARG_OPTIONS) { + assertEquals(option + " requires 1 argument", 1, _eclipseCompiler.isSupportedOption(option)); + } + for (String option : ZERO_ARG_OPTIONS) { + assertEquals(option + " requires no argument", 0, _eclipseCompiler.isSupportedOption(option)); + } + } + + /** + * Read annotation values and generate a class using system compiler (javac) + * This is a sanity check to verify that the processors, sample code, and + * compiler options are correct. + */ + public void testCompilerOneClassWithSystemCompiler() { + // System compiler + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + compileOneClass(compiler); + } + + /** + * Read annotation values and generate a class using Eclipse compiler + * TODO: disabled until APT is working + */ + public void _testCompilerOneClassWithEclipseCompiler() { + // Eclipse compiler + JavaCompiler compiler = _eclipseCompiler; + compileOneClass(compiler); + } + + /* + * Clean up the compiler + */ + public void testCleanUp() { + _eclipseCompiler = null; + } + + /** + * Create a class that contains an annotation that generates another class, + * and compile it. Verify that generation and compilation succeeded. + */ + private void compileOneClass(JavaCompiler compiler) { + StandardJavaFileManager manager = compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset()); + ForwardingJavaFileManager<StandardJavaFileManager> forwardingJavaFileManager = getForwardingFileManager(manager); + + File inputFile = writeSourceFile(_tmpSrcFolderName, "X.java", _echoSource); + + // create new list containing inputfile + List<File> files = new ArrayList<File>(); + files.add(inputFile); + Iterable<? extends JavaFileObject> units = manager.getJavaFileObjectsFromFiles(files); + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + + List<String> options = new ArrayList<String>(); + if (compiler == _eclipseCompiler) { + options.add("-6.0"); // not the default for Eclipse compiler + } + options.add("-d"); + options.add(_tmpBinFolderName); + options.add("-s"); + options.add(_tmpGenFolderName); + options.add("-cp"); + options.add(_tmpSrcFolderName + File.pathSeparator + _tmpGenFolderName + File.pathSeparator + _processorJarName); + options.add("-XprintRounds"); + CompilationTask task = compiler.getTask(printWriter, forwardingJavaFileManager, null, options, null, units); + Boolean result = task.call(); + + if (!result.booleanValue()) { + System.err.println("Compilation failed: " + stringWriter.getBuffer().toString()); + assertTrue("Compilation failed ", false); + } + // check that the src and class files were generated + File genSrcFile = new File(_tmpGenFolderName + File.separator + "gen" + File.separator + "XGen.java"); + assertTrue("generated src file does not exist", genSrcFile.exists()); + File classFile = new File(_tmpBinFolderName + File.separator + "p" + File.separator + "X.class"); + assertTrue("ordinary src file was not compiled", classFile.exists()); + File genClassFile = new File(_tmpBinFolderName + File.separator + "gen" + File.separator + "XGen.class"); + assertTrue("generated src file was not compiled", genClassFile.exists()); + } + + /** + * Recursively delete the contents of a directory, including any subdirectories. + * This is not optimized to handle very large or deep directory trees efficiently. + * @param f is either a normal file (which will be deleted) or a directory + * (which will be emptied and then deleted). + */ + protected static void deleteTree(File f) + { + if (null == f) { + return; + } + File[] children = f.listFiles(); + if (null != children) { + // if f has any children, (recursively) delete them + for (File child : children) { + deleteTree(child); + } + } + // At this point f is either a normal file or an empty directory + f.delete(); + } + + /** + * Get a JavaFileManager that can spit out diagnostic info. + */ + private ForwardingJavaFileManager<StandardJavaFileManager> getForwardingFileManager( + StandardJavaFileManager manager) { + ForwardingJavaFileManager<StandardJavaFileManager> forwardingJavaFileManager = new ForwardingJavaFileManager<StandardJavaFileManager>(manager) { + @Override + public FileObject getFileForInput(Location location, String packageName, String relativeName) + throws IOException { + System.out.println("Create file for input : " + packageName + " " + relativeName + " in location " + location); + return super.getFileForInput(location, packageName, relativeName); + } + @Override + public JavaFileObject getJavaFileForInput(Location location, String className, Kind kind) + throws IOException { + System.out.println("Create java file for input : " + className + " in location " + location); + return super.getJavaFileForInput(location, className, kind); + } + @Override + public JavaFileObject getJavaFileForOutput(Location location, + String className, + Kind kind, + FileObject sibling) throws IOException { + + if (null != sibling) { + System.out.println("Create .class file for " + className + " in location " + location + " with sibling " + sibling.toUri()); + } + else { + System.out.println("Create .class file for " + className + " in location " + location); + } + JavaFileObject javaFileForOutput = super.getJavaFileForOutput(location, className, kind, sibling); + System.out.println(javaFileForOutput.toUri()); + return javaFileForOutput; + } + }; + return forwardingJavaFileManager; + } + + /** + * Write a Java source file with the specified name and content. + */ + private File writeSourceFile(String tmpFolder, String name, String content) { + File inputFile = new File(tmpFolder, name); + BufferedWriter writer = null; + try { + writer = new BufferedWriter(new FileWriter(inputFile)); + writer.write(content); + writer.flush(); + writer.close(); + } catch (IOException e) { + // ignore + } finally { + if (writer != null) { + try { + writer.close(); + } catch (IOException e) { + // ignore + } + } + } + return inputFile; + } + +} diff --git a/org.eclipse.jdt.compiler.apt.tests/test.xml b/org.eclipse.jdt.compiler.apt.tests/test.xml new file mode 100644 index 0000000000..640eb8b700 --- /dev/null +++ b/org.eclipse.jdt.compiler.apt.tests/test.xml @@ -0,0 +1,52 @@ +<?xml version="1.0"?> + +<project name="testsuite" default="run" basedir="."> + <!-- The property ${eclipse-home} should be passed into this script --> + <!-- Set a meaningful default value for when it is not. --> + <property name="eclipse-home" value="${basedir}\..\.." /> + + <!-- sets the properties eclipse-home, and library-file --> + <property name="plugin-name" value="org.eclipse.jdt.compiler.apt.tests" /> + <property name="library-file" value="${eclipse-home}/plugins/org.eclipse.test/library.xml" /> + + <!-- This target holds all initialization code that needs to be done for --> + <!-- all tests that are to be run. Initialization for individual tests --> + <!-- should be done within the body of the suite target. --> + <target name="init"> + <tstamp /> + <delete> + <fileset dir="${eclipse-home}" includes="org*.xml" /> + </delete> + </target> + + <!-- This target defines the tests that need to be run. --> + <target name="suite"> + <property name="jdt-compiler-apt-folder" value="${eclipse-home}/jdt_compiler_apt_folder" /> + <delete dir="${jdt-compiler-apt-folder}" quiet="true" /> + <ant target="core-test" antfile="${library-file}" dir="${eclipse-home}"> + <property name="data-dir" value="${jdt-compiler-apt-folder}/data" /> + <property name="plugin-name" value="${plugin-name}" /> + <property name="classname" value="org.eclipse.jdt.compiler.apt.tests.AllTests" /> + </ant> + </target> + + <!-- This target holds code to cleanup the testing environment after --> + <!-- after all of the tests have been run. You can use this target to --> + <!-- delete temporary files that have been created. --> + <target name="cleanup"> + </target> + + <!-- This target runs the test suite. Any actions that need to happen --> + <!-- after all the tests have been run should go here. --> + <target name="run" depends="init,suite,cleanup"> + <ant target="collect" antfile="${library-file}" dir="${eclipse-home}"> + <property name="includes" value="org*.xml" /> + <property name="output-file" value="${plugin-name}.xml" /> + </ant> + </target> + + <!-- This target runs the performance test suites. --> + <target name="performance"> + </target> + +</project> |