private JavaCompiler.CompilationTask makeCompilationTask(String... files) throws IOException {
JavaCompiler compiler = BazelJavaCompiler.newInstance();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
fileManager.setLocation(StandardLocation.CLASS_PATH, Arrays.asList(new File("third_party/ijar/test/interface_ijar_testlib.jar")));
fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(getTmpDir()));
diagnostics = new DiagnosticCollector();
return compiler.getTask(null, fileManager, diagnostics, // used for deprecation tests
Arrays.asList("-Xlint:deprecation"), null, fileManager.getJavaFileObjects(files));
}
private CompilationTask compileJava(String... sourcePaths) {
java.util.List sourceFiles = new ArrayList(sourcePaths.length);
for (String file : sourcePaths) {
sourceFiles.add(new File(getPackagePath(), file));
}
JavaCompiler runCompiler = ToolProvider.getSystemJavaCompiler();
assertNotNull("Missing Java compiler, this test is probably being run with a JRE instead of a JDK!", runCompiler);
StandardJavaFileManager runFileManager = runCompiler.getStandardFileManager(null, null, null);
// make sure the destination repo exists
new File(destDir).mkdirs();
List options = new LinkedList();
options.addAll(Arrays.asList("-sourcepath", getSourcePath(), "-d", destDir, "-cp", getClassPathAsPath()));
Iterable extends JavaFileObject> compilationUnits1 = runFileManager.getJavaFileObjectsFromFiles(sourceFiles);
return runCompiler.getTask(null, runFileManager, null, options, null, compilationUnits1);
}
@Parameters(name = "{0}")
public static Collection parameters() {
JavaCompiler systemJavaCompiler = Compiler.systemJavaCompiler();
JavaCompiler eclipseCompiler = Compiler.eclipseCompiler();
return Arrays.asList(new Object[][] { { "includeAccessorsWithSystemJavaCompiler", systemJavaCompiler, config("includeDynamicAccessors", true), "/schema/dynamic/parentType.json", Matchers.empty() }, { "includeAccessorsWithEclipseCompiler", eclipseCompiler, config("includeDynamicAccessors", true), "/schema/dynamic/parentType.json", onlyCastExceptions() } });
}
private void compile() throws IOException {
//$NON-NLS-1$
LOG.debug("compiling generated Java source files");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
throw new IllegalStateException(//$NON-NLS-1$
Messages.getString("FilePackager.errorMissingJavaCompiler"));
}
if (sourceDirectory.isDirectory() == false) {
return;
}
List sources = collect(sourceDirectory, new ArrayList());
if (sources.isEmpty()) {
return;
}
compile(compiler, sources);
}
@Test
public void testCompilerNewInstance() throws Exception {
JavaCompiler javac = BazelJavaCompiler.newInstance();
assertNotNull(javac.getStandardFileManager(null, null, null));
// This is a simplified pattern of invoking the compiler API. Note, however, that
// many examples cast to JavacTask or JavacTaskImpl and invoke the phases separately.
// Currently, either cast will fail with something that looks like classloader issues:
// "com.sun.tools.javac.api.JavacTask cannot be cast to com.sun.tools.javac.api.JavacTask"
assertNotNull(javac.getTask(null, null, null, null, null, null));
}
private void assertCompileSucceeds(final String uri, final String content) throws Exception {
JavaCompiler javac = BazelJavaCompiler.newInstance();
JavaFileObject source = new SimpleJavaFileObject(URI.create(uri), JavaFileObject.Kind.SOURCE) {
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return content;
}
};
StandardJavaFileManager fileManager = javac.getStandardFileManager(null, null, null);
// setting the output path by passing a flag to getTask is not reliable
fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(getTmpDir()));
DiagnosticCollector messages = new DiagnosticCollector<>();
JavaCompiler.CompilationTask task = javac.getTask(null, fileManager, messages, null, null, Collections.singletonList(source));
assertTrue(task.call());
assertTrue(messages.getDiagnostics().isEmpty());
}
@Override
protected JavaCompiler createCompiler(ExecutionContext context, SourcePathResolver resolver) {
JavaCompiler compiler;
synchronized (ToolProvider.class) {
// ToolProvider has no synchronization internally, so if we don't synchronize from the
// outside we could wind up loading the compiler classes multiple times from different
// class loaders.
compiler = ToolProvider.getSystemJavaCompiler();
}
if (compiler == null) {
throw new HumanReadableException("No system compiler found. Did you install the JRE instead of the JDK?");
}
return compiler;
}
static void check(String destPath, ClassName clazz, ClassName sup) throws Exception {
File destDir = new File(workDir, destPath);
destDir.mkdir();
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavacTask ct = (JavacTask) tool.getTask(null, null, null, Arrays.asList("-d", destPath), null, Arrays.asList(initialSources));
ct.generate();
File fileToRemove = new File(destPath, clazz.name + ".class");
fileToRemove.delete();
JavaSource newSource = new JavaSource(clazz, sup);
DiagnosticChecker checker = new DiagnosticChecker();
ct = (JavacTask) tool.getTask(null, null, checker, Arrays.asList("-cp", destPath), null, Arrays.asList(newSource));
ct.analyze();
if (!checker.errorFound) {
throw new AssertionError(newSource.source);
}
}
public static void main(String[] args) throws Exception {
String SCRATCH_DIR = System.getProperty("user.dir");
JavaCompiler javacTool = ToolProvider.getSystemJavaCompiler();
int n = 0;
for (TestKind testKind : TestKind.values()) {
for (EnumActionKind actionKind : EnumActionKind.values()) {
File testDir = new File(SCRATCH_DIR, "test" + n);
new T6550655(javacTool, testDir, testKind, actionKind).test();
n++;
}
}
if (nerrors > 0) {
throw new AssertionError("Some errors have been detected");
}
}
public static void main(String[] args) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
task = (JavacTask) compiler.getTask(null, null, null, null, null, List.of(new MyFileObject()));
Iterable extends CompilationUnitTree> asts = task.parse();
task.analyze();
trees = Trees.instance(task);
MyVisitor myVisitor = new MyVisitor();
for (CompilationUnitTree ast : asts) {
myVisitor.compilationUnit = ast;
myVisitor.scan(ast, null);
}
if (!myVisitor.foundError) {
throw new AssertionError("Expected error not found!");
}
}
public static void main(String[] args) throws Exception {
//NOI18N
final String bootPath = System.getProperty("sun.boot.class.path");
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
assert tool != null;
final JavacTask ct = (JavacTask) tool.getTask(null, null, null, Arrays.asList("-bootclasspath", bootPath), null, Arrays.asList(new MyFileObject()));
CompilationUnitTree cut = ct.parse().iterator().next();
TreePath tp = new TreePath(new TreePath(cut), cut.getTypeDecls().get(0));
Scope s = Trees.instance(ct).getScope(tp);
TypeElement type = ct.getElements().getTypeElement("com.sun.java.util.jar.pack.Package.File");
if (Trees.instance(ct).isAccessible(s, type)) {
//"false" would be expected here.
throw new IllegalStateException("");
}
}
public static void main(String[] args) throws IOException {
JavaFileObject sfo = new SimpleJavaFileObject(URI.create(""), Kind.SOURCE) {
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return "class Test { void test(){}}";
}
};
List extends JavaFileObject> files = Arrays.asList(sfo);
String bootPath = System.getProperty("sun.boot.class.path");
List opts = Arrays.asList("-bootclasspath", bootPath, "-Xjcov");
JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavacTask ct = (JavacTask) tool.getTask(null, null, null, opts, null, files);
ct.analyze();
}
public static void main(String[] args) throws IOException {
JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"), Kind.SOURCE) {
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return "class BadName { Object o = j; }";
}
};
List extends JavaFileObject> files = Arrays.asList(sfo);
JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavacTask ct = (JavacTask) tool.getTask(null, null, null, null, null, files);
Iterable extends CompilationUnitTree> compUnits = ct.parse();
CompilationUnitTree cu = compUnits.iterator().next();
ClassTree cdef = (ClassTree) cu.getTypeDecls().get(0);
JCVariableDecl vdef = (JCVariableDecl) cdef.getMembers().get(0);
TreePath path = TreePath.getPath(cu, vdef.init);
Trees.instance(ct).getScope(path);
}
public void run() throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable extends JavaFileObject> tests = fileManager.getJavaFileObjects(writeTestFile());
JavaCompiler.CompilationTask task = ToolProvider.getSystemJavaCompiler().getTask(null, null, null, Arrays.asList("-processor", this.getClass().getName()), null, tests);
task.call();
}
static void compileAndCheck(PackageKind pk, ConstructorKind ck) throws Exception {
FooClass foo = new FooClass(pk, ck);
ClientClass client = new ClientClass(pk);
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
ErrorListener el = new ErrorListener();
JavacTask ct = (JavacTask) tool.getTask(null, null, el, null, null, Arrays.asList(foo, client));
ct.analyze();
if (el.errors > 0 == check(pk, ck)) {
String msg = el.errors > 0 ? "Error compiling files" : "No error when compiling files";
throw new AssertionError(msg + ": \n" + foo.source + "\n" + client.source);
}
}
public static void main(String... args) throws Exception {
//create default shared JavaCompiler - reused across multiple compilations
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
for (BoundKind boundKind : BoundKind.values()) {
for (ConstructorKind constructorKind : ConstructorKind.values()) {
for (TypeArgumentKind declArgKind : TypeArgumentKind.values()) {
for (TypeArgArity arity : TypeArgArity.values()) {
for (TypeArgumentKind useArgKind : TypeArgumentKind.values()) {
for (TypeArgumentKind diamondArgKind : TypeArgumentKind.values()) {
for (ArgumentKind argKind : ArgumentKind.values()) {
new GenericConstructorAndDiamondTest(boundKind, constructorKind, declArgKind, arity, useArgKind, diamondArgKind, argKind).run(comp, fm);
}
}
}
}
}
}
}
}
public static void main(String[] args) throws Exception {
String SCRATCH_DIR = System.getProperty("user.dir");
JavaCompiler javacTool = ToolProvider.getSystemJavaCompiler();
int n = 0;
for (HierarchyKind hierarchyKind : HierarchyKind.values()) {
for (TestKind testKind : TestKind.values()) {
for (ActionKind actionKind : ActionKind.values()) {
File testDir = new File(SCRATCH_DIR, "test" + n);
new EagerInterfaceCompletionTest(javacTool, testDir, hierarchyKind, testKind, actionKind).test();
n++;
}
}
}
if (nerrors > 0) {
throw new AssertionError("Some errors have been detected");
}
}
public static void main(String[] args) throws Exception {
//NOI18N
final String bootPath = System.getProperty("sun.boot.class.path");
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
assert tool != null;
String code = "package test; public class Test {private void test() {Object o = null; boolean b = o != null && o instanceof String;} private Test() {}}";
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, Arrays.asList("-bootclasspath", bootPath, "-Xjcov"), null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(0);
VariableTree condSt = (VariableTree) method.getBody().getStatements().get(1);
BinaryTree cond = (BinaryTree) condSt.getInitializer();
JCTree condJC = (JCTree) cond;
if (condJC.pos != 93)
throw new IllegalStateException("Unexpected position=" + condJC.pos);
}
public static void main(String[] args) throws Exception {
File testSrc = new File(System.getProperty("test.src"));
File thisSrc = new File(testSrc, T6963934.class.getSimpleName() + ".java");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
JavacTask task = (JavacTask) compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjects(thisSrc));
CompilationUnitTree tree = task.parse().iterator().next();
int count = 0;
for (ImportTree importTree : tree.getImports()) {
System.out.println(importTree);
count++;
}
int expected = 7;
if (count != expected)
throw new Exception("unexpected number of imports found: " + count + ", expected: " + expected);
}
public static void main(String... args) throws Exception {
//create default shared JavaCompiler - reused across multiple compilations
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
for (XlintOption xlint : XlintOption.values()) {
for (SuppressLevel suppress_decl : SuppressLevel.values()) {
for (SuppressLevel suppress_use : SuppressLevel.values()) {
for (ClassKind ck : ClassKind.values()) {
for (ExceptionKind ek_decl : ExceptionKind.values()) {
for (ExceptionKind ek_use : ExceptionKind.values()) {
new InterruptedExceptionTest(xlint, suppress_decl, suppress_use, ck, ek_decl, ek_use).run(comp, fm);
}
}
}
}
}
}
}
static void test(SourceLevel sourceLevel, TrustMe trustMe, SuppressLevel suppressLevelClient, SuppressLevel suppressLevelDecl, ModifierKind modKind, Signature vararg_meth, Signature client_meth) throws Exception {
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavaSource source = new JavaSource(trustMe, suppressLevelClient, suppressLevelDecl, modKind, vararg_meth, client_meth);
DiagnosticChecker dc = new DiagnosticChecker();
JavacTask ct = (JavacTask) tool.getTask(null, fm, dc, Arrays.asList("-Xlint:unchecked", "-source", sourceLevel.sourceKey), null, Arrays.asList(source));
//to get mandatory notes
ct.generate();
check(dc.warnings, sourceLevel, new boolean[] { vararg_meth.giveUnchecked(client_meth), vararg_meth.giveVarargs(client_meth) }, source, trustMe, suppressLevelClient, suppressLevelDecl, modKind);
}
@Test
public void testCeylonModule() throws IOException, ModuleNotFoundException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
File moduleFile = new File("test/foo/foo", "$module_.java");
Iterable extends JavaFileObject> units = fileManager.getJavaFileObjects(moduleFile);
File destDir = new File("build/mainTest");
FileUtil.delete(destDir);
destDir.mkdirs();
CompilationTask task = compiler.getTask(null, null, null, Arrays.asList("-d", destDir.getPath(), "-cp", "build/classes" + File.pathSeparator + "../language/ide-dist/ceylon.language-" + Versions.CEYLON_VERSION_NUMBER + ".car"), null, units);
Boolean result = task.call();
assertTrue(result != null && result.booleanValue());
File compiledModuleFile = new File(destDir, "foo/foo/$module_.class");
assertTrue(compiledModuleFile.isFile());
File jar = jar(compiledModuleFile, "foo/foo");
try {
checkJarDependencies(jar);
} finally {
jar.delete();
}
}
public static void main(String... args) {
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
JFileChooser fileChooser;
Preferences prefs = Preferences.userNodeForPackage(Launcher.class);
if (args.length > 0)
fileChooser = new JFileChooser(args[0]);
else {
String fileName = prefs.get("recent.file", null);
fileChooser = new JFileChooser();
if (fileName != null) {
fileChooser = new JFileChooser();
fileChooser.setSelectedFile(new File(fileName));
}
}
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
String fileName = fileChooser.getSelectedFile().getPath();
prefs.put("recent.file", fileName);
javac.run(System.in, null, null, "-d", "/tmp", fileName);
}
}
static void check(String destPath, ClassName clazz, ClassName sup) throws Exception {
File destDir = new File(workDir, destPath);
destDir.mkdir();
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavacTask ct = (JavacTask) tool.getTask(null, null, null, Arrays.asList("-d", destPath), null, Arrays.asList(initialSources));
ct.generate();
File fileToRemove = new File(destPath, clazz.name + ".class");
fileToRemove.delete();
JavaSource newSource = new JavaSource(clazz, sup);
DiagnosticChecker checker = new DiagnosticChecker();
ct = (JavacTask) tool.getTask(null, null, checker, Arrays.asList("-cp", destPath), null, Arrays.asList(newSource));
ct.analyze();
if (!checker.errorFound) {
throw new AssertionError(newSource.source);
}
}
public static void main(String[] args) throws Exception {
String SCRATCH_DIR = System.getProperty("user.dir");
JavaCompiler javacTool = ToolProvider.getSystemJavaCompiler();
int n = 0;
for (TestKind testKind : TestKind.values()) {
for (EnumActionKind actionKind : EnumActionKind.values()) {
File testDir = new File(SCRATCH_DIR, "test" + n);
new T6550655(javacTool, testDir, testKind, actionKind).test();
n++;
}
}
if (nerrors > 0) {
throw new AssertionError("Some errors have been detected");
}
}
public static void main(String[] args) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
task = (JavacTask) compiler.getTask(null, null, null, null, null, List.of(new MyFileObject()));
Iterable extends CompilationUnitTree> asts = task.parse();
task.analyze();
trees = Trees.instance(task);
MyVisitor myVisitor = new MyVisitor();
for (CompilationUnitTree ast : asts) {
myVisitor.compilationUnit = ast;
myVisitor.scan(ast, null);
}
if (!myVisitor.foundError) {
throw new AssertionError("Expected error not found!");
}
}
public static void main(String[] args) throws IOException {
JavaFileObject sfo = new SimpleJavaFileObject(URI.create(""), Kind.SOURCE) {
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return "class Test { void test(){}}";
}
};
List extends JavaFileObject> files = Arrays.asList(sfo);
String bootPath = System.getProperty("sun.boot.class.path");
List opts = Arrays.asList("-bootclasspath", bootPath, "-Xjcov");
JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavacTask ct = (JavacTask) tool.getTask(null, null, null, opts, null, files);
ct.analyze();
}
public static void main(String[] args) throws IOException {
JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"), Kind.SOURCE) {
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return "class BadName { Object o = j; }";
}
};
List extends JavaFileObject> files = Arrays.asList(sfo);
JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavacTask ct = (JavacTask) tool.getTask(null, null, null, null, null, files);
Iterable extends CompilationUnitTree> compUnits = ct.parse();
CompilationUnitTree cu = compUnits.iterator().next();
ClassTree cdef = (ClassTree) cu.getTypeDecls().get(0);
JCVariableDecl vdef = (JCVariableDecl) cdef.getMembers().get(0);
TreePath path = TreePath.getPath(cu, vdef.init);
Trees.instance(ct).getScope(path);
}
public void run() throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable extends JavaFileObject> tests = fileManager.getJavaFileObjects(writeTestFile());
JavaCompiler.CompilationTask task = ToolProvider.getSystemJavaCompiler().getTask(null, null, null, Arrays.asList("-processor", this.getClass().getName()), null, tests);
task.call();
}
static void compileAndCheck(PackageKind pk, ConstructorKind ck) throws Exception {
FooClass foo = new FooClass(pk, ck);
ClientClass client = new ClientClass(pk);
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
ErrorListener el = new ErrorListener();
JavacTask ct = (JavacTask) tool.getTask(null, null, el, null, null, Arrays.asList(foo, client));
ct.analyze();
if (el.errors > 0 == check(pk, ck)) {
String msg = el.errors > 0 ? "Error compiling files" : "No error when compiling files";
throw new AssertionError(msg + ": \n" + foo.source + "\n" + client.source);
}
}
public static void main(String... args) throws Exception {
//create default shared JavaCompiler - reused across multiple compilations
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
for (BoundKind boundKind : BoundKind.values()) {
for (ConstructorKind constructorKind : ConstructorKind.values()) {
for (TypeArgumentKind declArgKind : TypeArgumentKind.values()) {
for (TypeArgArity arity : TypeArgArity.values()) {
for (TypeArgumentKind useArgKind : TypeArgumentKind.values()) {
for (TypeArgumentKind diamondArgKind : TypeArgumentKind.values()) {
for (ArgumentKind argKind : ArgumentKind.values()) {
new GenericConstructorAndDiamondTest(boundKind, constructorKind, declArgKind, arity, useArgKind, diamondArgKind, argKind).run(comp, fm);
}
}
}
}
}
}
}
}
public static void main(String[] args) throws Exception {
String SCRATCH_DIR = System.getProperty("user.dir");
JavaCompiler javacTool = ToolProvider.getSystemJavaCompiler();
int n = 0;
for (HierarchyKind hierarchyKind : HierarchyKind.values()) {
for (TestKind testKind : TestKind.values()) {
for (ActionKind actionKind : ActionKind.values()) {
File testDir = new File(SCRATCH_DIR, "test" + n);
new EagerInterfaceCompletionTest(javacTool, testDir, hierarchyKind, testKind, actionKind).test();
n++;
}
}
}
if (nerrors > 0) {
throw new AssertionError("Some errors have been detected");
}
}
public static void main(String[] args) throws Exception {
//NOI18N
final String bootPath = System.getProperty("sun.boot.class.path");
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
assert tool != null;
String code = "package test; public class Test {private void test() {Object o = null; boolean b = o != null && o instanceof String;} private Test() {}}";
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, Arrays.asList("-bootclasspath", bootPath, "-Xjcov"), null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(0);
VariableTree condSt = (VariableTree) method.getBody().getStatements().get(1);
BinaryTree cond = (BinaryTree) condSt.getInitializer();
JCTree condJC = (JCTree) cond;
if (condJC.pos != 93)
throw new IllegalStateException("Unexpected position=" + condJC.pos);
}
public static void main(String[] args) throws Exception {
File testSrc = new File(System.getProperty("test.src"));
File thisSrc = new File(testSrc, T6963934.class.getSimpleName() + ".java");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
JavacTask task = (JavacTask) compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjects(thisSrc));
CompilationUnitTree tree = task.parse().iterator().next();
int count = 0;
for (ImportTree importTree : tree.getImports()) {
System.out.println(importTree);
count++;
}
int expected = 7;
if (count != expected)
throw new Exception("unexpected number of imports found: " + count + ", expected: " + expected);
}
public static void main(String... args) throws Exception {
//create default shared JavaCompiler - reused across multiple compilations
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
for (XlintOption xlint : XlintOption.values()) {
for (SuppressLevel suppress_decl : SuppressLevel.values()) {
for (SuppressLevel suppress_use : SuppressLevel.values()) {
for (ClassKind ck : ClassKind.values()) {
for (ExceptionKind ek_decl : ExceptionKind.values()) {
for (ExceptionKind ek_use : ExceptionKind.values()) {
new InterruptedExceptionTest(xlint, suppress_decl, suppress_use, ck, ek_decl, ek_use).run(comp, fm);
}
}
}
}
}
}
}
public static void main(String... args) throws Exception {
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
int errors = 0;
for (ClassKind ck : ClassKind.values()) {
for (GenericKind gk : GenericKind.values()) {
for (SuperKind sk : SuperKind.values()) {
errors += new TestSuperclass(ck, gk, sk).run(comp, fm);
}
}
}
if (errors > 0)
throw new Exception(errors + " errors found");
}
@Test
public void testCeylonModule() throws IOException, ModuleNotFoundException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
File moduleFile = new File("test-jvm/foo/foo", "$module_.java");
Iterable extends JavaFileObject> units = fileManager.getJavaFileObjects(moduleFile);
File destDir = new File("build/mainTest");
FileUtil.delete(destDir);
destDir.mkdirs();
CompilationTask task = compiler.getTask(null, null, null, Arrays.asList("-d", destDir.getPath(), "-cp", "build/classes" + File.pathSeparator + "ide-dist/ceylon.language-" + Versions.CEYLON_VERSION_NUMBER + ".car"), null, units);
Boolean result = task.call();
assertTrue(result != null && result.booleanValue());
File compiledModuleFile = new File(destDir, "foo/foo/$module_.class");
assertTrue(compiledModuleFile.isFile());
File jar = jar(compiledModuleFile, "foo/foo");
try {
checkJarDependencies(jar);
} finally {
jar.delete();
}
}
public static void main(String[] args) {
final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
final StandardJavaFileManager fileManager = javac.getStandardFileManager(null, null, null);
if (!doStuff(javac, fileManager)) {
System.exit(1);
}
if (!doStuff(javac, fileManager)) {
System.exit(1);
}
if (!doStuff(javac, fileManager)) {
System.exit(1);
}
}
Class> compile() throws Exception {
String source = packageDir.getPath() + "/" + sourceName;
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector diagnostics = new DiagnosticCollector();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
Iterable extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromStrings(Arrays.asList(source));
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits);
boolean success = task.call();
fileManager.close();
if (success) {
return getClassLoader().loadClass(GEN_CLASS + className);
} else {
return null;
}
}
/**
* Compile {@code sources} using {@code processors}.
*
* @throws RuntimeException if compilation fails.
*/
static Result compile(Iterable extends Processor> processors, Iterable options, Iterable extends JavaFileObject> sources) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
throw new IllegalStateException("Java Compiler is not present. " + "May be, you need to include tools.jar on your dependency list.");
}
DiagnosticCollector diagnosticCollector = new DiagnosticCollector();
InMemoryJavaFileManager fileManager = new InMemoryJavaFileManager(compiler.getStandardFileManager(diagnosticCollector, Locale.getDefault(), UTF_8));
CompilationTask task = compiler.getTask(// explicitly use the default because old versions of javac log some output on stderr
null, fileManager, diagnosticCollector, ImmutableList.copyOf(options), ImmutableSet.of(), sources);
task.setProcessors(processors);
boolean successful = task.call();
return new Result(successful, sortDiagnosticsByKind(diagnosticCollector.getDiagnostics()), fileManager.getOutputFiles());
}
@Test
public void testCompile() throws Exception {
assertTrue(this.sourceDir.exists());
assertTrue(this.outDir.exists() || this.outDir.mkdirs());
Enunciate enunciate = new Enunciate();
final ArrayList javaFiles = new ArrayList();
enunciate.visitFiles(sourceDir, Enunciate.JAVA_FILTER, new Enunciate.FileVisitor() {
@Override
public void visit(File file) {
javaFiles.add(file);
}
});
String classpath = System.getProperty("java.class.path");
JavaCompiler compiler = JavacTool.create();
List options = Arrays.asList("-source", "1.5", "-target", "1.5", "-encoding", "UTF-8", "-cp", classpath, "-d", this.outDir.getAbsolutePath());
JavaCompiler.CompilationTask task = compiler.getTask(null, null, null, options, null, compiler.getStandardFileManager(null, null, null).getJavaFileObjectsFromFiles(javaFiles));
assertTrue(task.call());
}
private void checkWellFormed(Iterable sources, String[] args) {
JavaCompiler compiler = JavacTool.create();
OutputStream outputStream = new ByteArrayOutputStream();
String[] remainingArgs = null;
try {
remainingArgs = ErrorProneOptions.processArgs(args).getRemainingArgs();
} catch (InvalidCommandLineOptionException e) {
fail("Exception during argument processing: " + e);
}
CompilationTask task = compiler.getTask(new PrintWriter(outputStream, /*autoFlush=*/
true), fileManager, null, buildArguments(Arrays.asList(remainingArgs)), null, sources);
boolean result = task.call();
assertWithMessage(String.format("Test program failed to compile with non Error Prone error: %s", outputStream.toString())).that(result).isTrue();
}
@Test
public void testRun() {
JavaCompiler mockCompiler = mock(JavaCompiler.class);
ErrorProneJavaCompiler compiler = new ErrorProneJavaCompiler(mockCompiler);
InputStream in = mock(InputStream.class);
OutputStream out = mock(OutputStream.class);
OutputStream err = mock(OutputStream.class);
String[] arguments = { "-source", "8", "-target", "8" };
compiler.run(in, out, err, arguments);
verify(mockCompiler).run(in, out, err, arguments);
}
protected void compile(TreeScanner scanner, JavaFileObject fileObject) {
JavaCompiler compiler = JavacTool.create();
DiagnosticCollector diagnosticsCollector = new DiagnosticCollector();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticsCollector, Locale.ENGLISH, UTF_8);
JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(CharStreams.nullWriter(), fileManager, diagnosticsCollector, ImmutableList.of(), null, ImmutableList.of(fileObject));
try {
this.sourceFile = SourceFile.create(fileObject);
Iterable extends CompilationUnitTree> trees = task.parse();
task.analyze();
for (CompilationUnitTree tree : trees) {
scanner.scan((JCCompilationUnit) tree);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
this.context = task.getContext();
}
private File compile(List classpaths, List files, boolean generate) throws IOException {
JavaCompiler systemJavaCompiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = systemJavaCompiler.getStandardFileManager(null, null, null);
if (classpaths.size() > 0)
fm.setLocation(StandardLocation.CLASS_PATH, classpaths);
JavacTask ct = (JavacTask) systemJavaCompiler.getTask(null, fm, diags, compileOptions, null, files);
if (generate) {
File destDir = new File(root, Integer.toString(counter.incrementAndGet()));
// @@@ Assert that this directory didn't exist, or start counter at max+1
destDir.mkdirs();
fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir));
ct.generate();
return destDir;
} else {
ct.analyze();
return nullDir;
}
}
static void check(String destPath, ClassName clazz, ClassName sup) throws Exception {
File destDir = new File(workDir, destPath);
destDir.mkdir();
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavacTask ct = (JavacTask) tool.getTask(null, null, null, Arrays.asList("-d", destPath), null, Arrays.asList(initialSources));
ct.generate();
File fileToRemove = new File(destPath, clazz.name + ".class");
fileToRemove.delete();
JavaSource newSource = new JavaSource(clazz, sup);
DiagnosticChecker checker = new DiagnosticChecker();
ct = (JavacTask) tool.getTask(null, null, checker, Arrays.asList("-cp", destPath), null, Arrays.asList(newSource));
ct.analyze();
if (!checker.errorFound) {
throw new AssertionError(newSource.source);
}
}
public static void main(String... args) throws Exception {
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
int count = 0;
for (SourceKind sk1 : SourceKind.values()) {
for (SourceKind sk2 : SourceKind.values()) {
for (TestKind tk : TestKind.values()) {
for (ClientKind ck : ClientKind.values()) {
new TestCircularClassfile("sub_" + count++, sk1, sk2, tk, ck).check(comp, fm);
}
}
}
}
}
void run() throws Exception {
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
File classesDir = new File(System.getProperty("user.dir"), "classes");
classesDir.mkdirs();
JavaSource[] sources = new JavaSource[] { new JavaSource("TestOneIgnorableChar", "AA\\u0000BB"), new JavaSource("TestMultipleIgnorableChar", "AA\\u0000\\u0000\\u0000BB") };
JavacTask ct = (JavacTask) comp.getTask(null, null, null, Arrays.asList("-d", classesDir.getPath()), null, Arrays.asList(sources));
try {
if (!ct.call()) {
throw new AssertionError("Error thrown when compiling test cases");
}
} catch (Throwable ex) {
throw new AssertionError("Error thrown when compiling test cases");
}
check(classesDir, "TestOneIgnorableChar.class", "TestOneIgnorableChar$AABB.class", "TestMultipleIgnorableChar.class", "TestMultipleIgnorableChar$AABB.class");
if (errors > 0)
throw new AssertionError("There are some errors in the test check the error output");
}
void run() throws Exception {
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
JavaSource source = new JavaSource();
JavacTask ct = (JavacTask) comp.getTask(null, null, null, null, null, Arrays.asList(source));
try {
if (!ct.call()) {
throw new AssertionError(errorMessage + source.getCharContent(true));
}
} catch (Throwable ex) {
throw new AssertionError(errorMessage + source.getCharContent(true));
}
check();
}
public static void main(String[] args) throws Exception {
String SCRATCH_DIR = System.getProperty("user.dir");
JavaCompiler javacTool = ToolProvider.getSystemJavaCompiler();
int n = 0;
for (TestKind testKind : TestKind.values()) {
for (EnumActionKind actionKind : EnumActionKind.values()) {
File testDir = new File(SCRATCH_DIR, "test" + n);
new T6550655(javacTool, testDir, testKind, actionKind).test();
n++;
}
}
if (nerrors > 0) {
throw new AssertionError("Some errors have been detected");
}
}
// Create and compile FileObject using values for className and contents
public static boolean compileCode(String className, String contents, DiagnosticCollector diagnostics) {
boolean ok = false;
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
throw new RuntimeException("can't get javax.tools.JavaCompiler!");
}
JavaFileObject file = getFile(className, contents);
Iterable extends JavaFileObject> compilationUnit = Arrays.asList(file);
CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnit);
ok = task.call();
return ok;
}
public static void main(String[] args) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
task = (JavacTask) compiler.getTask(null, null, null, null, null, List.of(new MyFileObject()));
Iterable extends CompilationUnitTree> asts = task.parse();
task.analyze();
trees = Trees.instance(task);
MyVisitor myVisitor = new MyVisitor();
for (CompilationUnitTree ast : asts) {
myVisitor.compilationUnit = ast;
myVisitor.scan(ast, null);
}
if (!myVisitor.foundError) {
throw new AssertionError("Expected error not found!");
}
}
public static void main(String[] args) throws Exception {
//NOI18N
final String bootPath = System.getProperty("sun.boot.class.path");
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
assert tool != null;
final JavacTask ct = (JavacTask) tool.getTask(null, null, null, Arrays.asList("-bootclasspath", bootPath), null, Arrays.asList(new MyFileObject()));
CompilationUnitTree cut = ct.parse().iterator().next();
TreePath tp = new TreePath(new TreePath(cut), cut.getTypeDecls().get(0));
Scope s = Trees.instance(ct).getScope(tp);
TypeElement type = ct.getElements().getTypeElement("com.sun.java.util.jar.pack.Package.File");
if (Trees.instance(ct).isAccessible(s, type)) {
//"false" would be expected here.
throw new IllegalStateException("");
}
}
public static void main(String[] args) throws IOException {
JavaFileObject sfo = new SimpleJavaFileObject(URI.create(""), Kind.SOURCE) {
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return "class Test { void test(){}}";
}
};
List extends JavaFileObject> files = Arrays.asList(sfo);
String bootPath = System.getProperty("sun.boot.class.path");
List opts = Arrays.asList("-bootclasspath", bootPath, "-Xjcov");
JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavacTask ct = (JavacTask) tool.getTask(null, null, null, opts, null, files);
ct.analyze();
}
public static void main(String[] args) throws IOException {
JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"), Kind.SOURCE) {
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return "class BadName { Object o = j; }";
}
};
List extends JavaFileObject> files = Arrays.asList(sfo);
JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavacTask ct = (JavacTask) tool.getTask(null, null, null, null, null, files);
Iterable extends CompilationUnitTree> compUnits = ct.parse();
CompilationUnitTree cu = compUnits.iterator().next();
ClassTree cdef = (ClassTree) cu.getTypeDecls().get(0);
JCVariableDecl vdef = (JCVariableDecl) cdef.getMembers().get(0);
TreePath path = TreePath.getPath(cu, vdef.init);
Trees.instance(ct).getScope(path);
}
public void run() {
File srcDir = new File(System.getProperty("test.src"));
File thisFile = new File(srcDir, getClass().getName() + ".java");
JavaCompiler c = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = c.getStandardFileManager(null, null, null);
List opts = Arrays.asList("-proc:only", "-doe");
Iterable extends JavaFileObject> files = fm.getJavaFileObjects(thisFile);
JavacTask t = (JavacTask) c.getTask(null, fm, null, opts, null, files);
t.setProcessors(Collections.singleton(this));
boolean ok = t.call();
if (!ok)
throw new Error("compilation failed");
}
public void run() throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable extends JavaFileObject> tests = fileManager.getJavaFileObjects(writeTestFile());
JavaCompiler.CompilationTask task = ToolProvider.getSystemJavaCompiler().getTask(null, null, null, Arrays.asList("-processor", this.getClass().getName()), null, tests);
task.call();
}
@Override
public void run() {
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavacTask ct = (JavacTask) tool.getTask(null, fm.get(), diagChecker, null, null, Arrays.asList(source));
try {
ct.analyze();
} catch (Throwable ex) {
throw new AssertionError("Error thrown when compiling the following code:\n" + source.getCharContent(true));
}
check();
}
private InMemoryFileManager compile(List options, Function src2JavaFileObject, List sources) throws IOException, CompilationException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
List extends JavaFileObject> src = sources.stream().map(src2JavaFileObject).collect(Collectors.toList());
DiagnosticCollector super JavaFileObject> dc = new DiagnosticCollector<>();
try (InMemoryFileManager fileManager = new InMemoryFileManager(compiler.getStandardFileManager(null, null, null))) {
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, dc, options, null, src);
boolean success = task.call();
if (!success) {
String errorMessage = dc.getDiagnostics().stream().map(Object::toString).collect(Collectors.joining("\n"));
throw new CompilationException("Compilation Error\n\n" + errorMessage);
}
return fileManager;
}
}
private static void test(String classname, String expected) throws Exception {
File classfile = new File(System.getProperty("test.classes", "."), classname + ".class");
ClassFile cf = ClassFile.read(classfile);
cf = new ClassFile(cf.magic, Target.JDK1_7.minorVersion, Target.JDK1_7.majorVersion, cf.constant_pool, cf.access_flags, cf.this_class, cf.super_class, cf.interfaces, cf.fields, cf.methods, cf.attributes);
new ClassWriter().write(cf, classfile);
JavaCompiler c = ToolProvider.getSystemJavaCompiler();
JavacTaskImpl task = (JavacTaskImpl) c.getTask(null, null, null, Arrays.asList("-classpath", System.getProperty("test.classes", ".")), null, null);
try {
Symbol clazz = com.sun.tools.javac.main.JavaCompiler.instance(task.getContext()).resolveIdent(classname);
clazz.complete();
} catch (BadClassFile f) {
JCDiagnostic embeddedDiag = (JCDiagnostic) f.diag.getArgs()[1];
assertEquals(expected, embeddedDiag.getCode());
assertEquals(Integer.toString(Target.JDK1_7.majorVersion), embeddedDiag.getArgs()[0]);
assertEquals(Integer.toString(Target.JDK1_7.minorVersion), embeddedDiag.getArgs()[1]);
}
}
public static void main(String... args) throws Exception {
//create default shared JavaCompiler - reused across multiple compilations
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
for (VersionKind vk : VersionKind.values()) {
for (EnclosingKind ek : EnclosingKind.values()) {
for (MethodKind mk : MethodKind.values()) {
for (ModifierKind modk1 : ModifierKind.values()) {
for (ModifierKind modk2 : ModifierKind.values()) {
new TestDefaultMethodsSyntax(vk, ek, mk, modk1, modk2).run(comp, fm);
}
}
}
}
}
System.out.println("Total check executed: " + checkCount);
}
void run() throws Exception {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
System.err.println("using " + compiler.getClass() + " from " + compiler.getClass().getProtectionDomain().getCodeSource());
CompilationTask task = compiler.getTask(null, null, null, Collections.singleton("-proc:only"), Collections.singleton("java.lang.Object"), null);
task.setProcessors(Collections.singleton(new Proc()));
check("compilation", task.call());
task = compiler.getTask(null, null, null, Arrays.asList("-proc:only", "-AexpectFile"), Collections.singleton("java.lang.Object"), null);
task.setProcessors(Collections.singleton(new Proc()));
check("compilation", task.call());
}
static void compileAndCheck(PackageKind pk, ConstructorKind ck) throws Exception {
FooClass foo = new FooClass(pk, ck);
ClientClass client = new ClientClass(pk);
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
ErrorListener el = new ErrorListener();
JavacTask ct = (JavacTask) tool.getTask(null, null, el, null, null, Arrays.asList(foo, client));
ct.analyze();
if (el.errors > 0 == check(pk, ck)) {
String msg = el.errors > 0 ? "Error compiling files" : "No error when compiling files";
throw new AssertionError(msg + ": \n" + foo.source + "\n" + client.source);
}
}
public static void main(String... args) throws Exception {
//create default shared JavaCompiler - reused across multiple compilations
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
for (BoundKind boundKind : BoundKind.values()) {
for (ConstructorKind constructorKind : ConstructorKind.values()) {
for (TypeArgumentKind declArgKind : TypeArgumentKind.values()) {
for (TypeArgArity arity : TypeArgArity.values()) {
for (TypeArgumentKind useArgKind : TypeArgumentKind.values()) {
for (TypeArgumentKind diamondArgKind : TypeArgumentKind.values()) {
for (ArgumentKind argKind : ArgumentKind.values()) {
new GenericConstructorAndDiamondTest(boundKind, constructorKind, declArgKind, arity, useArgKind, diamondArgKind, argKind).run(comp, fm);
}
}
}
}
}
}
}
}
public static void main(String... args) throws Exception {
//create default shared JavaCompiler - reused across multiple compilations
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
for (TypeKind a1 : TypeKind.values()) {
for (TypeKind a2 : TypeKind.values()) {
for (TypeKind a3 : TypeKind.values()) {
for (MethodCallKind mck : MethodCallKind.values()) {
new T7086601b(a1, a2, a3, mck).run(comp, fm);
}
}
}
}
System.out.println("Total check executed: " + checkCount);
}
public static void main(String... args) throws Exception {
String SCRATCH_DIR = System.getProperty("user.dir");
JavaCompiler javacTool = ToolProvider.getSystemJavaCompiler();
java.io.File testDir = new java.io.File(SCRATCH_DIR);
sourceA.dumpTo(testDir);
sourceB.dumpTo(testDir);
DiagnosticChecker diagChecker = new DiagnosticChecker();
JavacTask ct = (JavacTask) javacTool.getTask(null, null, diagChecker, Arrays.asList("-XDrawDiagnostics", "-cp", testDir.getAbsolutePath()), null, Arrays.asList(sourceA.asJFO(testDir)));
try {
ct.analyze();
} catch (Throwable ex) {
}
if (!diagChecker.errorFound) {
throw new AssertionError("Missing diagnostic");
}
}
public static void main(String... args) throws Exception {
//create default shared JavaCompiler - reused across multiple compilations
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
for (ParameterListKind plk : ParameterListKind.values()) {
for (ParameterKind pk : ParameterKind.values()) {
for (ArrowKind ak : ArrowKind.values()) {
for (ExprKind ek : ExprKind.values()) {
new BadLambdaExpr(plk, pk, ak, ek).run(comp, fm);
}
}
}
}
System.out.println("Total check executed: " + checkCount);
}
@Override
public void run() {
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavacTask ct = (JavacTask) tool.getTask(null, fm.get(), dc, null, null, Arrays.asList(samSourceFile, pkgClassSourceFile, clientSourceFile));
try {
ct.analyze();
} catch (IOException ex) {
throw new AssertionError("Test failing with cause", ex.getCause());
}
if (dc.errorFound == checkSamConversion()) {
throw new AssertionError(samSourceFile + "\n\n" + pkgClassSourceFile + "\n\n" + clientSourceFile);
}
}
public static void main(String... args) throws Exception {
//create default shared JavaCompiler - reused across multiple compilations
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
for (CastInfo cInfo : allCastInfo()) {
for (ExpressionKind ek : ExpressionKind.values()) {
new IntersectionTargetTypeTest(cInfo, ek).run(comp, fm);
}
}
System.out.println("Total check executed: " + checkCount);
}
void test() throws Exception {
System.out.println("\n====================================");
System.out.println(fInterface + ", " + context + ", " + lambdaKind + ", " + lambdaBody + ", " + returnValue);
System.out.println(samSourceFile + "\n");
String clientFileStr = clientSourceFile.toString();
System.out.println(clientFileStr.substring(0, clientFileStr.indexOf("\n\n")));
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
DiagnosticChecker dc = new DiagnosticChecker();
JavacTask ct = (JavacTask) tool.getTask(null, null, dc, null, null, Arrays.asList(samSourceFile, clientSourceFile));
try {
ct.analyze();
} catch (Exception e) {
throw new AssertionError("failing SAM source file \n" + samSourceFile + "\n\n" + "failing client source file \n" + clientSourceFile);
}
if (dc.errorFound == checkSamConversion()) {
throw new AssertionError(samSourceFile + "\n\n" + clientSourceFile);
}
count++;
}
public static void main(String... args) throws Exception {
//create default shared JavaCompiler - reused across multiple compilations
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
for (EnclosingKind ek : EnclosingKind.values()) {
for (SiteKind sk : SiteKind.values()) {
if (sk == SiteKind.STATIC_INIT && ek == EnclosingKind.MEMBER_INNER)
continue;
for (InnerKind ik : InnerKind.values()) {
if (ik != InnerKind.NONE && sk == SiteKind.NONE)
break;
for (RefKind rk : RefKind.values()) {
new TestSelfRef(ek, sk, ik, rk).run(comp, fm);
}
}
}
}
System.out.println("Total check executed: " + checkCount);
}
public static void main(String... args) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector collector = new DiagnosticCollector<>();
String source = "class Test extends CompleteOnClosedOther {" + " class Inner extends Undefined { }" + "}";
Iterable files = Arrays.asList(new ToolBox.JavaSource(source));
Iterable options = Arrays.asList("-processor", "CompleteOnClosed");
CompilationTask task = compiler.getTask(null, null, collector, options, null, files);
task.call();
for (Diagnostic extends JavaFileObject> d : collector.getDiagnostics()) {
System.out.println(d.toString());
}
}
public static void main(String[] args) throws Exception {
String SCRATCH_DIR = System.getProperty("user.dir");
JavaCompiler javacTool = ToolProvider.getSystemJavaCompiler();
int n = 0;
for (VersionKind versionKind : VersionKind.values()) {
for (HierarchyKind hierarchyKind : HierarchyKind.values()) {
for (TestKind testKind : TestKind.values()) {
for (ActionKind actionKind : ActionKind.values()) {
File testDir = new File(SCRATCH_DIR, "test" + n);
new EagerInterfaceCompletionTest(javacTool, testDir, versionKind, hierarchyKind, testKind, actionKind).test();
n++;
}
}
}
}
if (nerrors > 0) {
throw new AssertionError("Some errors have been detected");
}
}
public static void main(String[] args) throws Exception {
//NOI18N
final String bootPath = System.getProperty("sun.boot.class.path");
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
assert tool != null;
String code = "package test; public class Test {private void test() {Object o = null; boolean b = o != null && o instanceof String;} private Test() {}}";
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, Arrays.asList("-bootclasspath", bootPath, "-Xjcov"), null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(0);
VariableTree condSt = (VariableTree) method.getBody().getStatements().get(1);
BinaryTree cond = (BinaryTree) condSt.getInitializer();
JCTree condJC = (JCTree) cond;
if (condJC.pos != 93)
throw new IllegalStateException("Unexpected position=" + condJC.pos);
}
public static void main(String[] args) throws Exception {
File src = new File("C.java");
Writer w = new FileWriter(src);
try {
w.write("import static p.Generated.m;\nclass C { {m(); } }\n");
w.flush();
} finally {
w.close();
}
JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
JavaCompiler.CompilationTask task = jc.getTask(null, null, null, null, null, jc.getStandardFileManager(null, null, null).getJavaFileObjects(src));
task.setProcessors(Collections.singleton(new Proc()));
if (!task.call()) {
throw new Error("Test failed");
}
}
void analyzeResource(URI resource) throws IOException, ConstantPoolException, InvalidDescriptor {
JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
JavaFileManager.Location location = StandardLocation.locationFor(resource.getPath());
fm.setLocation(location, com.sun.tools.javac.util.List.of(new File(resource.getPath())));
for (JavaFileObject file : fm.list(location, "", EnumSet.of(CLASS), true)) {
String className = fm.inferBinaryName(location, file);
int index = className.lastIndexOf('.');
String pckName = index == -1 ? "" : className.substring(0, index);
if (shouldAnalyzePackage(pckName)) {
analyzeClassFile(ClassFile.read(file.openInputStream()));
}
}
}
public static void main(String[] args) throws Exception {
File testSrc = new File(System.getProperty("test.src"));
File thisSrc = new File(testSrc, T6963934.class.getSimpleName() + ".java");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
JavacTask task = (JavacTask) compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjects(thisSrc));
CompilationUnitTree tree = task.parse().iterator().next();
int count = 0;
for (ImportTree importTree : tree.getImports()) {
System.out.println(importTree);
count++;
}
int expected = 7;
if (count != expected)
throw new Exception("unexpected number of imports found: " + count + ", expected: " + expected);
}
public static void main(String... args) throws Exception {
//create default shared JavaCompiler - reused across multiple compilations
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
for (XlintOption xlint : XlintOption.values()) {
for (SuppressLevel suppress_decl : SuppressLevel.values()) {
for (SuppressLevel suppress_use : SuppressLevel.values()) {
for (ClassKind ck : ClassKind.values()) {
for (ExceptionKind ek_decl : ExceptionKind.values()) {
for (ExceptionKind ek_use : ExceptionKind.values()) {
new InterruptedExceptionTest(xlint, suppress_decl, suppress_use, ck, ek_decl, ek_use).run(comp, fm);
}
}
}
}
}
}
}
@Override
public void run() {
int id = checkCount.incrementAndGet();
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavaSource source = new JavaSource(id);
JavacTask ct = (JavacTask) tool.getTask(null, fm.get(), diagChecker, Arrays.asList("-Xlint:unchecked", "-source", sourceLevel.sourceKey), null, Arrays.asList(source));
//to get mandatory notes
ct.call();
check(source, new boolean[] { vararg_meth.giveUnchecked(client_meth), vararg_meth.giveVarargs(client_meth) });
}
@Override
public void run() {
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavacTask ct = (JavacTask) tool.getTask(null, fm.get(), dc, Arrays.asList(xlint.getXlintOption(), "-source", sourceLevel.sourceKey), null, Arrays.asList(source));
try {
ct.analyze();
} catch (Throwable t) {
processException(t);
}
check();
}
public static void main(String... args) throws Exception {
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
int errors = 0;
for (ClassKind ck : ClassKind.values()) {
for (GenericKind gk : GenericKind.values()) {
for (SuperKind sk : SuperKind.values()) {
errors += new TestSuperclass(ck, gk, sk).run(comp, fm);
}
}
}
if (errors > 0)
throw new Exception(errors + " errors found");
}
public boolean compile() throws Exception {
String fullName = clsNode.getFullName();
String code = clsNode.getCode().toString();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
fileManager = new ClassFileManager(compiler.getStandardFileManager(null, null, null));
List jFiles = new ArrayList(1);
jFiles.add(new CharSequenceJavaFileObject(fullName, code));
CompilationTask compilerTask = compiler.getTask(null, fileManager, null, null, null, jFiles);
return Boolean.TRUE.equals(compilerTask.call());
}
public static List compile(List files, File outDir, boolean includeDebugInfo) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(files);
StaticFileManager staticFileManager = new StaticFileManager(fileManager, outDir);
List options = new ArrayList();
options.add(includeDebugInfo ? "-g" : "-g:none");
options.addAll(COMMON_ARGS);
CompilationTask task = compiler.getTask(null, staticFileManager, null, options, null, compilationUnits);
Boolean result = task.call();
fileManager.close();
if (Boolean.TRUE.equals(result)) {
return staticFileManager.outputFiles();
}
return Collections.emptyList();
}
@Before
public void setUp() throws MalformedURLException {
LogProvider.injectDebugLogger(System.out::println);
final String testClassPath = "src/test/jaxrs-test";
// invoke compilation for jaxrs-test classes
final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
final List compilationUnits = findClassFiles(testClassPath, fileManager);
final JavaCompiler.CompilationTask compilationTask = compiler.getTask(null, null, null, singletonList("-g"), null, compilationUnits);
assertTrue("Could not compile test project", compilationTask.call());
path = Paths.get(testClassPath).toAbsolutePath();
classUnderTest = new ProjectAnalyzer(path);
}
private void compile(final File f) throws IOException {
// set up compiler
final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
final DiagnosticCollector diagnostics = new DiagnosticCollector<>();
final List errors = new ArrayList<>();
try (final StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null)) {
final Iterable extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(f));
// compile generated source
// (switch off annotation processing: no need to create Log4j2Plugins.dat)
final List options = Arrays.asList("-proc:none");
compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits).call();
// check we don't have any compilation errors
for (final Diagnostic extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
if (diagnostic.getKind() == Diagnostic.Kind.ERROR) {
errors.add(String.format("Compile error: %s%n", diagnostic.getMessage(Locale.getDefault())));
}
}
}
assertTrue(errors.toString(), errors.isEmpty());
}
static void createTestClass() throws IOException {
FileOutputStream fos = new FileOutputStream(TESTFILE + ".java");
PrintStream ps = new PrintStream(fos);
ps.println("public class " + TESTFILE + "{");
ps.println("public static void main(String[] args) {\n");
ps.println("System.out.println(System.getProperty(\"sun.boot.library.path\"));\n");
ps.println("}}\n");
ps.close();
fos.close();
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
String javacOpts[] = { TESTFILE + ".java" };
if (javac.run(null, null, null, javacOpts) != 0) {
throw new RuntimeException("compilation of " + TESTFILE + ".java Failed");
}
}
/**
* Compile all the java sources in {@code /**} to
* {@code /**}. The destination directory will be created if
* it doesn't exist.
*
* All warnings/errors emitted by the compiler are output to System.out/err.
*
* @return true if the compilation is successful
*
* @throws IOException if there is an I/O error scanning the source tree or
* creating the destination directory
*/
public static boolean compile(Path source, Path destination, String... options) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null);
List sources = Files.find(source, Integer.MAX_VALUE, ( file, attrs) -> (file.toString().endsWith(".java"))).collect(Collectors.toList());
Files.createDirectories(destination);
jfm.setLocation(StandardLocation.CLASS_PATH, Collections.EMPTY_LIST);
jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT, Arrays.asList(destination));
List opts = Arrays.asList(options);
JavaCompiler.CompilationTask task = compiler.getTask(null, jfm, null, opts, null, jfm.getJavaFileObjectsFromPaths(sources));
return task.call();
}
static void javac(Path dest, List sourceFiles) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
List files = sourceFiles.stream().map( p -> p.toFile()).collect(Collectors.toList());
Iterable extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(files);
fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(dest.toFile()));
fileManager.setLocation(StandardLocation.CLASS_PATH, Arrays.asList(TEST_CLASSES.toFile()));
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits);
boolean passed = task.call();
if (!passed)
throw new RuntimeException("Error compiling " + files);
}
}
static void javac(Path dest, Path... sourceFiles) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
List files = Stream.of(sourceFiles).map( p -> p.toFile()).collect(Collectors.toList());
List dests = Stream.of(dest).map( p -> p.toFile()).collect(Collectors.toList());
Iterable extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(files);
fileManager.setLocation(StandardLocation.CLASS_OUTPUT, dests);
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits);
boolean passed = task.call();
if (!passed)
throw new RuntimeException("Error compiling " + files);
}
}
public static boolean compile(Path source, Path destination, String... options) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null)) {
List sources = Files.find(source, Integer.MAX_VALUE, ( file, attrs) -> file.toString().endsWith(".java")).collect(Collectors.toList());
Files.createDirectories(destination);
jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT, Collections.singleton(destination));
List opts = Arrays.asList(options);
JavaCompiler.CompilationTask task = compiler.getTask(null, jfm, null, opts, null, jfm.getJavaFileObjectsFromPaths(sources));
List list = new ArrayList<>(opts);
list.addAll(sources.stream().map(Path::toString).collect(Collectors.toList()));
System.err.println("javac options: " + optionsPrettyPrint(list.toArray(new String[list.size()])));
return task.call();
}
}
private File compile(List classpaths, List files, boolean generate) throws IOException {
JavaCompiler systemJavaCompiler = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fm = systemJavaCompiler.getStandardFileManager(null, null, null)) {
if (classpaths.size() > 0)
fm.setLocation(StandardLocation.CLASS_PATH, classpaths);
JavacTask ct = (JavacTask) systemJavaCompiler.getTask(null, fm, diags, compileOptions, null, files);
if (generate) {
File destDir = new File(root, Integer.toString(counter.incrementAndGet()));
// @@@ Assert that this directory didn't exist, or start counter at max+1
destDir.mkdirs();
fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir));
ct.generate();
return destDir;
} else {
ct.analyze();
return nullDir;
}
}
}
static void check(String destPath, ClassName clazz, ClassName sup) throws Exception {
File destDir = new File(workDir, destPath);
destDir.mkdir();
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
JavacTask ct = (JavacTask) tool.getTask(null, null, null, Arrays.asList("-d", destPath), null, Arrays.asList(initialSources));
ct.generate();
File fileToRemove = new File(destPath, clazz.name + ".class");
fileToRemove.delete();
JavaSource newSource = new JavaSource(clazz, sup);
DiagnosticChecker checker = new DiagnosticChecker();
ct = (JavacTask) tool.getTask(null, null, checker, Arrays.asList("-cp", destPath), null, Arrays.asList(newSource));
ct.analyze();
if (!checker.errorFound) {
throw new AssertionError(newSource.source);
}
}
public static void main(String... args) throws Exception {
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
int count = 0;
for (SourceKind sk1 : SourceKind.values()) {
for (SourceKind sk2 : SourceKind.values()) {
for (TestKind tk : TestKind.values()) {
for (ClientKind ck : ClientKind.values()) {
new TestCircularClassfile("sub_" + count++, sk1, sk2, tk, ck).check(comp, fm);
}
}
}
}
}
}
void run() throws Exception {
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
File classesDir = new File(System.getProperty("user.dir"), "classes");
classesDir.mkdirs();
JavaSource[] sources = new JavaSource[] { new JavaSource("TestOneIgnorableChar", "AA\\u0000BB"), new JavaSource("TestMultipleIgnorableChar", "AA\\u0000\\u0000\\u0000BB") };
JavacTask ct = (JavacTask) comp.getTask(null, null, null, Arrays.asList("-d", classesDir.getPath()), null, Arrays.asList(sources));
try {
if (!ct.call()) {
throw new AssertionError("Error thrown when compiling test cases");
}
} catch (Throwable ex) {
throw new AssertionError("Error thrown when compiling test cases");
}
check(classesDir, "TestOneIgnorableChar.class", "TestOneIgnorableChar$AABB.class", "TestMultipleIgnorableChar.class", "TestMultipleIgnorableChar$AABB.class");
if (errors > 0)
throw new AssertionError("There are some errors in the test check the error output");
}
void run() throws Exception {
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
JavaSource source = new JavaSource();
JavacTask ct = (JavacTask) comp.getTask(null, null, null, null, null, Arrays.asList(source));
try {
if (!ct.call()) {
throw new AssertionError(errorMessage + source.getCharContent(true));
}
} catch (Throwable ex) {
throw new AssertionError(errorMessage + source.getCharContent(true));
}
check();
}
public static void main(String[] args) throws Exception {
String SCRATCH_DIR = System.getProperty("user.dir");
JavaCompiler javacTool = ToolProvider.getSystemJavaCompiler();
int n = 0;
for (TestKind testKind : TestKind.values()) {
for (EnumActionKind actionKind : EnumActionKind.values()) {
File testDir = new File(SCRATCH_DIR, "test" + n);
new T6550655(javacTool, testDir, testKind, actionKind).test();
n++;
}
}
if (nerrors > 0) {
throw new AssertionError("Some errors have been detected");
}
}
// Create and compile FileObject using values for className and contents
public static boolean compileCode(String className, String contents, DiagnosticCollector diagnostics) {
boolean ok = false;
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
throw new RuntimeException("can't get javax.tools.JavaCompiler!");
}
JavaFileObject file = getFile(className, contents);
Iterable extends JavaFileObject> compilationUnit = Arrays.asList(file);
CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnit);
ok = task.call();
return ok;
}