diff --git a/src/java.compiler/share/classes/javax/tools/SimpleJavaFileObject.java b/src/java.compiler/share/classes/javax/tools/SimpleJavaFileObject.java index a619cf34c9a..1e959133ff3 100644 --- a/src/java.compiler/share/classes/javax/tools/SimpleJavaFileObject.java +++ b/src/java.compiler/share/classes/javax/tools/SimpleJavaFileObject.java @@ -223,4 +223,48 @@ public class SimpleJavaFileObject implements JavaFileObject { public String toString() { return getClass().getName() + "[" + toUri() + "]"; } + + /** + * Creates a {@link JavaFileObject} which represents the given source content. + * + *

The provided {@code uri} will be returned from {@link #toUri()}. + * The provided {@code content} will be returned from {@link #getCharContent(boolean)}. + * The {@link #getKind()} method will return {@link Kind#SOURCE}. + * + *

All other methods will behave as described in the documentation in this class, + * as if the constructor is called with {@code uri} and {@code Kind.SOURCE}. + * + *

This method can be, for example, used to compile an in-memory String + * to a set of classfile in a target directory: + * {@snippet lang="java": + * var code = """ + * public class CompiledCode {} + * """; + * var compiler = ToolProvider.getSystemJavaCompiler(); + * var targetDirectory = "..."; + * var task = compiler.getTask(null, + * null, + * null, + * List.of("-d", targetDirectory), + * null, + * List.of(SimpleJavaFileObject.forSource(URI.create("CompiledCode.java"), code))); + * if (!task.call()) { + * throw new IllegalStateException("Compilation failed!"); + * } + * } + * + * @param uri that should be used for the resulting {@code JavaFileObject} + * @param content the content of the {@code JavaFileObject} + * @return a {@code JavaFileObject} representing the given source content. + * @since 23 + */ + public static JavaFileObject forSource(URI uri, String content) { + return new SimpleJavaFileObject(uri, Kind.SOURCE) { + @Override + public CharSequence getCharContent(boolean ignoreEncodingErrors) { + return content; + } + }; + } + } diff --git a/test/jdk/java/lang/template/StringTemplateTest.java b/test/jdk/java/lang/template/StringTemplateTest.java index 63556f75360..53aca6d83ff 100644 --- a/test/jdk/java/lang/template/StringTemplateTest.java +++ b/test/jdk/java/lang/template/StringTemplateTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -209,12 +209,8 @@ public class StringTemplateTest { // System.out.println(source); if (ToolProvider.getSystemJavaCompiler().getTask(null, fileManager, null, List.of("--enable-preview", "-source", String.valueOf(Runtime.version().feature())), null, - List.of(new SimpleJavaFileObject(URI.create("StringTemplateTest$.java"), JavaFileObject.Kind.SOURCE) { - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) { - return source; - } - })).call()) { + List.of(SimpleJavaFileObject.forSource(URI.create("StringTemplateTest$.java"), source)) + ).call()) { return fileManager.getClassLoader(CLASS_OUTPUT).loadClass("StringTemplateTest$"); } else { throw new AssertionError("compilation failed"); diff --git a/test/langtools/jdk/javadoc/tool/api/basic/APITest.java b/test/langtools/jdk/javadoc/tool/api/basic/APITest.java index 7bc76b05064..54f9cce497d 100644 --- a/test/langtools/jdk/javadoc/tool/api/basic/APITest.java +++ b/test/langtools/jdk/javadoc/tool/api/basic/APITest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -115,13 +115,8 @@ class APITest { } protected JavaFileObject createSimpleJavaFileObject(final String binaryName, final String content) { - return new SimpleJavaFileObject( - URI.create("myfo:///" + binaryName + ".java"), JavaFileObject.Kind.SOURCE) { - @Override - public CharSequence getCharContent(boolean ignoreEncoding) { - return content; - } - }; + return SimpleJavaFileObject.forSource( + URI.create("myfo:///" + binaryName + ".java"), content); } protected void checkFiles(File dir, Set expectFiles) { diff --git a/test/langtools/tools/doclint/tool/RunTest.java b/test/langtools/tools/doclint/tool/RunTest.java index 78415a95441..86691111bce 100644 --- a/test/langtools/tools/doclint/tool/RunTest.java +++ b/test/langtools/tools/doclint/tool/RunTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -188,12 +188,8 @@ public class RunTest { } JavaFileObject createFile(String name, final String body) { - return new SimpleJavaFileObject(URI.create(name), JavaFileObject.Kind.SOURCE) { - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { - return body; - } - }; + return SimpleJavaFileObject.forSource(URI.create(name), + body); } void error(String msg) { diff --git a/test/langtools/tools/javac/6902720/Test.java b/test/langtools/tools/javac/6902720/Test.java index 9945b03ca06..39d36e86b89 100644 --- a/test/langtools/tools/javac/6902720/Test.java +++ b/test/langtools/tools/javac/6902720/Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -75,12 +75,9 @@ public class Test { // verify the generated code is valid Java by compiling it JavacTool tool2 = JavacTool.create(); - JavaFileObject fo = new SimpleJavaFileObject(URI.create("output"), JavaFileObject.Kind.SOURCE) { - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) { - return out; - } - }; + JavaFileObject fo = + SimpleJavaFileObject.forSource(URI.create("output"), + out); JavacTask t2 = tool2.getTask(null, fm, null, null, null, Collections.singleton(fo)); boolean ok = t2.call(); if (!ok) diff --git a/test/langtools/tools/javac/7079713/TestCircularClassfile.java b/test/langtools/tools/javac/7079713/TestCircularClassfile.java index 7bd21511bee..bc9da02f66f 100644 --- a/test/langtools/tools/javac/7079713/TestCircularClassfile.java +++ b/test/langtools/tools/javac/7079713/TestCircularClassfile.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -53,13 +53,9 @@ public class TestCircularClassfile { this.sourceStr = sourceStr; } - SimpleJavaFileObject getSource() { - return new SimpleJavaFileObject(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE) { - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { - return sourceStr; - } - }; + JavaFileObject getSource() { + return SimpleJavaFileObject.forSource(URI.create("myfo:/Test.java"), + sourceStr); } } diff --git a/test/langtools/tools/javac/Diagnostics/8295024/T8295024.java b/test/langtools/tools/javac/Diagnostics/8295024/T8295024.java index df69b158c3e..9614c1b13bf 100644 --- a/test/langtools/tools/javac/Diagnostics/8295024/T8295024.java +++ b/test/langtools/tools/javac/Diagnostics/8295024/T8295024.java @@ -33,13 +33,8 @@ public class T8295024 { } """; - private static final SimpleJavaFileObject FILE = new SimpleJavaFileObject( - URI.create("string:///Cyclic.java"), JavaFileObject.Kind.SOURCE) { - @Override - public String getCharContent(boolean ignoreEncodingErrors) { - return SOURCE; - } - }; + private static final JavaFileObject FILE = SimpleJavaFileObject.forSource( + URI.create("string:///Cyclic.java"), SOURCE); public static void main(String[] args) throws Exception { @@ -47,7 +42,7 @@ public class T8295024 { final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); final StringWriter output = new StringWriter(); final Iterable options = Collections.singleton("-XDrawDiagnostics"); - final Iterable files = Collections.singleton(FILE); + final Iterable files = Collections.singleton(FILE); for (int i = 0; i < NUM_RUNS; i++) compiler.getTask(output, null, null, options, null, files).call(); diff --git a/test/langtools/tools/javac/MethodParameters/LegacyOutputTest/LegacyOutputTest.java b/test/langtools/tools/javac/MethodParameters/LegacyOutputTest/LegacyOutputTest.java index 117beccfe59..3f613be7e82 100644 --- a/test/langtools/tools/javac/MethodParameters/LegacyOutputTest/LegacyOutputTest.java +++ b/test/langtools/tools/javac/MethodParameters/LegacyOutputTest/LegacyOutputTest.java @@ -1,5 +1,6 @@ /* * Copyright (c) 2018, Google Inc. All rights reserved. + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,17 +35,14 @@ import java.lang.classfile.*; import java.lang.classfile.attribute.MethodParameterInfo; import java.lang.classfile.attribute.MethodParametersAttribute; -import java.io.IOException; import java.net.URI; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.Objects; import javax.tools.JavaCompiler; import javax.tools.JavaCompiler.CompilationTask; import javax.tools.JavaFileObject; -import javax.tools.JavaFileObject.Kind; import javax.tools.SimpleJavaFileObject; import javax.tools.ToolProvider; @@ -73,13 +71,8 @@ public class LegacyOutputTest { List getParameterNames(String release) throws Exception { JavaCompiler tool = ToolProvider.getSystemJavaCompiler(); JavaFileObject fileObject = - new SimpleJavaFileObject(URI.create("Test.java"), Kind.SOURCE) { - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) - throws IOException { - return "class Test { void f(int x, int y) {} }"; - } - }; + SimpleJavaFileObject.forSource(URI.create("Test.java"), + "class Test { void f(int x, int y) {} }"); CompilationTask task = tool.getTask( null, diff --git a/test/langtools/tools/javac/api/6608214/T6608214.java b/test/langtools/tools/javac/api/6608214/T6608214.java index 8796df17b7d..ef85d03c286 100644 --- a/test/langtools/tools/javac/api/6608214/T6608214.java +++ b/test/langtools/tools/javac/api/6608214/T6608214.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,15 +38,12 @@ import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.SimpleJavaFileObject; import javax.tools.ToolProvider; -import static javax.tools.JavaFileObject.Kind; public class T6608214 { 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(){}}"; - } - }; + JavaFileObject sfo = + SimpleJavaFileObject.forSource(URI.create(""), + "class Test { void test(){}}"); List files = Arrays.asList(sfo); List opts = Arrays.asList("-Xjcov"); JavaCompiler tool = ToolProvider.getSystemJavaCompiler(); diff --git a/test/langtools/tools/javac/api/6733837/T6733837.java b/test/langtools/tools/javac/api/6733837/T6733837.java index b95b28b60f2..1976e6bb1c7 100644 --- a/test/langtools/tools/javac/api/6733837/T6733837.java +++ b/test/langtools/tools/javac/api/6733837/T6733837.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -40,7 +40,6 @@ import java.util.Arrays; import java.util.List; import javax.tools.JavaFileObject; import javax.tools.SimpleJavaFileObject; -import static javax.tools.JavaFileObject.Kind; import com.sun.source.util.JavacTask; public class T6733837 extends ToolTester { @@ -52,11 +51,9 @@ public class T6733837 extends ToolTester { } public void exec() { - JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) { - public CharSequence getCharContent(boolean ignoreEncodingErrors) { - return "\tclass ErroneousWithTab"; - } - }; + JavaFileObject sfo = + SimpleJavaFileObject.forSource(URI.create("myfo:/Test.java"), + "\tclass ErroneousWithTab"); StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); List files = Arrays.asList(sfo); diff --git a/test/langtools/tools/javac/api/6852595/T6852595.java b/test/langtools/tools/javac/api/6852595/T6852595.java index 85b4b0c1666..f7a89ab4aa9 100644 --- a/test/langtools/tools/javac/api/6852595/T6852595.java +++ b/test/langtools/tools/javac/api/6852595/T6852595.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,15 +44,11 @@ import com.sun.source.util.TreePath; import com.sun.source.util.Trees; import com.sun.tools.javac.tree.JCTree.*; -import static javax.tools.JavaFileObject.Kind; - public class T6852595 { 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; }"; - } - }; + JavaFileObject sfo = + SimpleJavaFileObject.forSource(URI.create("myfo:/Test.java"), + "class BadName { Object o = j; }"); List files = Arrays.asList(sfo); JavaCompiler tool = ToolProvider.getSystemJavaCompiler(); JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, files); diff --git a/test/langtools/tools/javac/api/TestSearchPaths.java b/test/langtools/tools/javac/api/TestSearchPaths.java index 0c91bba24fa..86abb4e48de 100644 --- a/test/langtools/tools/javac/api/TestSearchPaths.java +++ b/test/langtools/tools/javac/api/TestSearchPaths.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -482,12 +482,8 @@ public class TestSearchPaths { } JavaFileObject getSource(final String source) { - return new SimpleJavaFileObject(getURIFromSource(source), JavaFileObject.Kind.SOURCE) { - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) { - return source; - } - }; + return SimpleJavaFileObject.forSource(getURIFromSource(source), + source); } void callTask(List options, List files) { diff --git a/test/langtools/tools/javac/api/taskListeners/TestTypeElement.java b/test/langtools/tools/javac/api/taskListeners/TestTypeElement.java index 555b9fbd16f..3e0a47f429f 100644 --- a/test/langtools/tools/javac/api/taskListeners/TestTypeElement.java +++ b/test/langtools/tools/javac/api/taskListeners/TestTypeElement.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,10 +29,8 @@ * @run main TestTypeElement */ -import java.io.IOException; import java.io.PrintStream; import java.net.URI; -import java.net.URISyntaxException; import java.util.List; import javax.lang.model.element.TypeElement; @@ -150,19 +148,7 @@ public class TestTypeElement { } private JavaFileObject createFileObject(String name, String body) { - return createFileObject(name, JavaFileObject.Kind.SOURCE, body); - } - - private JavaFileObject createFileObject(String name, JavaFileObject.Kind kind, String body) { - try { - return new SimpleJavaFileObject(new URI("myfo:///" + name), kind) { - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { - return body; - } - }; - } catch (URISyntaxException e) { - throw new IllegalArgumentException(name, e); - } + return SimpleJavaFileObject.forSource(URI.create("myfo:///" + name), + body); } } \ No newline at end of file diff --git a/test/langtools/tools/javac/doclint/DocLintTest.java b/test/langtools/tools/javac/doclint/DocLintTest.java index 6543e4395f9..74b5b0355fb 100644 --- a/test/langtools/tools/javac/doclint/DocLintTest.java +++ b/test/langtools/tools/javac/doclint/DocLintTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -114,12 +114,8 @@ public class DocLintTest { fm = javac.getStandardFileManager(null, null, null); try { fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File("."))); - file = new SimpleJavaFileObject(URI.create("Test.java"), JavaFileObject.Kind.SOURCE) { - @Override - public CharSequence getCharContent(boolean ignoreEncoding) { - return code; - } - }; + file = SimpleJavaFileObject.forSource(URI.create("Test.java"), + code); test(Collections.emptyList(), Main.Result.OK, diff --git a/test/langtools/tools/javac/lambda/abort/Abort.java b/test/langtools/tools/javac/lambda/abort/Abort.java index ff48f8eb8c0..2b242637f83 100644 --- a/test/langtools/tools/javac/lambda/abort/Abort.java +++ b/test/langtools/tools/javac/lambda/abort/Abort.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,17 +30,11 @@ */ import com.sun.source.util.JavacTask; -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.StringWriter; -import java.net.URI; -import java.net.URL; import java.util.Arrays; import javax.tools.Diagnostic; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.SimpleJavaFileObject; -import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; public class Abort { @@ -85,13 +79,9 @@ public class Abort { bw.close(); } - SimpleJavaFileObject asJFO(java.io.File dir) { - return new SimpleJavaFileObject(new java.io.File(dir, filename).toURI(), JavaFileObject.Kind.SOURCE) { - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { - return contents; - } - }; + JavaFileObject asJFO(java.io.File dir) { + return SimpleJavaFileObject.forSource(new java.io.File(dir, filename).toURI(), + contents); } } diff --git a/test/langtools/tools/javac/lambda/abort/CompletionFailure.java b/test/langtools/tools/javac/lambda/abort/CompletionFailure.java index 5f3d1855b43..5385fbd8d90 100644 --- a/test/langtools/tools/javac/lambda/abort/CompletionFailure.java +++ b/test/langtools/tools/javac/lambda/abort/CompletionFailure.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -99,13 +99,9 @@ public class CompletionFailure { bw.close(); } - SimpleJavaFileObject asJFO(java.io.File dir) { - return new SimpleJavaFileObject(new File(dir, filename).toURI(), JavaFileObject.Kind.SOURCE) { - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { - return contents; - } - }; + JavaFileObject asJFO(java.io.File dir) { + return SimpleJavaFileObject.forSource(new File(dir, filename).toURI(), + contents); } } diff --git a/test/langtools/tools/javac/lexer/JavaLexerTest.java b/test/langtools/tools/javac/lexer/JavaLexerTest.java index af9b4068b4d..6b9c789087c 100644 --- a/test/langtools/tools/javac/lexer/JavaLexerTest.java +++ b/test/langtools/tools/javac/lexer/JavaLexerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,11 +29,9 @@ * @summary Proper lexing of various token kinds. */ -import java.io.IOException; import java.net.URI; import java.util.Objects; -import javax.tools.JavaFileObject; import javax.tools.SimpleJavaFileObject; import com.sun.tools.javac.parser.JavaTokenizer; @@ -125,12 +123,8 @@ public class JavaLexerTest { Context ctx = new Context(); Log log = Log.instance(ctx); - log.useSource(new SimpleJavaFileObject(new URI("mem://Test.java"), JavaFileObject.Kind.SOURCE) { - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { - return test.input; - } - }); + log.useSource(SimpleJavaFileObject.forSource(URI.create("mem://Test.java"), + test.input)); char[] inputArr = test.input.toCharArray(); JavaTokenizer tokenizer = new JavaTokenizer(ScannerFactory.instance(ctx), inputArr, inputArr.length) {}; diff --git a/test/langtools/tools/javac/main/T8239544.java b/test/langtools/tools/javac/main/T8239544.java index 4e50b298e5e..30c1dec3c1a 100644 --- a/test/langtools/tools/javac/main/T8239544.java +++ b/test/langtools/tools/javac/main/T8239544.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -58,12 +58,8 @@ public class T8239544 { CompileState.ATTR, CompileState.FLOW, CompileState.TRANSTYPES, CompileState.TRANSPATTERNS, CompileState.UNLAMBDA, CompileState.LOWER}; //everything except GENERATE public static void main(String... args) throws IOException { - var f = new SimpleJavaFileObject(URI.create("TestLambdaClass.java"), JavaFileObject.Kind.SOURCE) { - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { - return "@Deprecated public class TestLambdaClass {{new Thread(() -> {});}}"; - } - }; + var f = SimpleJavaFileObject.forSource(URI.create("TestLambdaClass.java"), + "@Deprecated public class TestLambdaClass {{new Thread(() -> {});}}"); for (String compilePolicy : TESTED_COMPILE_POLICIES) { for (CompileState stop : TESTED_COMPILE_STATES) { var ctx = new Context(); diff --git a/test/langtools/tools/javac/parser/StringFoldingPosTest.java b/test/langtools/tools/javac/parser/StringFoldingPosTest.java index 8836c36fba1..a38db7db90b 100644 --- a/test/langtools/tools/javac/parser/StringFoldingPosTest.java +++ b/test/langtools/tools/javac/parser/StringFoldingPosTest.java @@ -1,5 +1,6 @@ /* * Copyright (c) 2020, Google LLC. All rights reserved. + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -63,15 +64,10 @@ public class StringFoldingPosTest { } private static JavaFileObject makeSource(String name, String code) { - return new SimpleJavaFileObject( + return SimpleJavaFileObject.forSource( URI.create( "file:/" + name.replace('.', '/') + JavaFileObject.Kind.SOURCE.extension), - JavaFileObject.Kind.SOURCE) { - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) { - return code; - } - }; + code); } private void run( diff --git a/test/langtools/tools/javac/patterns/InferenceUnitTest.java b/test/langtools/tools/javac/patterns/InferenceUnitTest.java index 2c246664686..f026833e2a9 100644 --- a/test/langtools/tools/javac/patterns/InferenceUnitTest.java +++ b/test/langtools/tools/javac/patterns/InferenceUnitTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -48,12 +48,9 @@ import com.sun.tools.javac.parser.ParserFactory; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; -import java.io.IOException; import java.net.URI; -import java.net.URISyntaxException; import java.util.Objects; import javax.tools.JavaCompiler; -import javax.tools.JavaFileObject; import javax.tools.SimpleJavaFileObject; import javax.tools.ToolProvider; @@ -67,30 +64,27 @@ public class InferenceUnitTest { new InferenceUnitTest().runAll(); } - void runAll() throws URISyntaxException { + void runAll() { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); - JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(null, null, null, null, null, List.of(new SimpleJavaFileObject(new URI("mem://Test.java"), JavaFileObject.Kind.SOURCE) { - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { - return """ - interface A {} - interface B extends A {} - interface C extends A {} - interface D extends A {} - interface E extends C {} - interface F extends A> {} - interface G extends A {} - interface H extends A {} - interface I extends H {} - class Test { - } - interface RecursiveTest1Interface> { } - interface RecursiveTest1Use> extends RecursiveTest1Interface { } - interface RecursiveTest2Interface { } - interface RecursiveTest2Use, Y> extends RecursiveTest2Interface { } - """; - } - })); + String source = """ + interface A {} + interface B extends A {} + interface C extends A {} + interface D extends A {} + interface E extends C {} + interface F extends A> {} + interface G extends A {} + interface H extends A {} + interface I extends H {} + class Test { + } + interface RecursiveTest1Interface> { } + interface RecursiveTest1Use> extends RecursiveTest1Interface { } + interface RecursiveTest2Interface { } + interface RecursiveTest2Use, Y> extends RecursiveTest2Interface { } + """; + + JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(null, null, null, null, null, List.of(SimpleJavaFileObject.forSource(URI.create("mem://Test.java"), source))); task.enter(); context = task.getContext(); infer = Infer.instance(context); diff --git a/test/langtools/tools/javac/records/ElementFilterRecordComponentTest.java b/test/langtools/tools/javac/records/ElementFilterRecordComponentTest.java index 3ca306ed34f..3b24bbe1cc6 100644 --- a/test/langtools/tools/javac/records/ElementFilterRecordComponentTest.java +++ b/test/langtools/tools/javac/records/ElementFilterRecordComponentTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,19 +41,14 @@ import com.sun.tools.javac.util.Assert; import java.util.HashSet; import java.util.Set; import javax.lang.model.util.ElementFilter; -import javax.tools.JavaFileObject; public class ElementFilterRecordComponentTest { public static void main(String... args) throws IOException { JavaCompiler c = ToolProvider.getSystemJavaCompiler(); JavacTask t = (JavacTask) c.getTask(null, null, null, null, null, - List.of(new SimpleJavaFileObject(URI.create("TestClass.java"), JavaFileObject.Kind.SOURCE) { - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { - return "record R(int val1, int val2) {}"; - } - })); + List.of(SimpleJavaFileObject.forSource(URI.create("TestClass.java"), + "record R(int val1, int val2) {}"))); TypeElement record = (TypeElement) t.analyze().iterator().next(); Set recordSet = ElementFilter.recordComponentsIn(new HashSet<>(record.getEnclosedElements())); Assert.check(recordSet.size() == 2); diff --git a/test/langtools/tools/javac/toolsapi/TestSimpleJavaFileObject.java b/test/langtools/tools/javac/toolsapi/TestSimpleJavaFileObject.java new file mode 100644 index 00000000000..09fef319659 --- /dev/null +++ b/test/langtools/tools/javac/toolsapi/TestSimpleJavaFileObject.java @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8325362 + * @summary Test SimpleJavaFileObject + * @library /tools/lib + * @modules + * jdk.compiler/com.sun.tools.javac.api + * jdk.compiler/com.sun.tools.javac.main + * @run main TestSimpleJavaFileObject + */ + +import java.io.IOException; +import java.net.URI; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import javax.tools.Diagnostic.Kind; +import javax.tools.DiagnosticListener; +import javax.tools.FileObject; +import javax.tools.ForwardingJavaFileManager; +import javax.tools.JavaCompiler; +import javax.tools.JavaFileManager; +import javax.tools.JavaFileObject; +import javax.tools.SimpleJavaFileObject; +import javax.tools.ToolProvider; +import toolbox.TestRunner; + +public class TestSimpleJavaFileObject extends TestRunner { + + public TestSimpleJavaFileObject() { + super(System.err); + } + + public static void main(String... args) throws Exception { + TestSimpleJavaFileObject t = new TestSimpleJavaFileObject(); + t.runTests(m -> new Object[] { Paths.get(m.getName()) }); + } + + @Test + public void testForSource(Path p) throws IOException { + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + List errors = new ArrayList<>(); + DiagnosticListener noErrors = d -> { + if (d.getKind() == Kind.ERROR) { + errors.add(d.getSource().toUri().toString() + ":" + + d.getLineNumber() + ":" + + d.getColumnNumber() + ":" + + d.getCode()); + } + }; + try (JavaFileManager fm = compiler.getStandardFileManager(null, null, null); + LoggingFileManager rfm = new LoggingFileManager(fm)) { + JavaFileObject src = SimpleJavaFileObject.forSource(URI.create("mem:///Test.java"), + """ + public class Test {} + """); + assertTrue("compilation didn't succeed!", + compiler.getTask(null, rfm, noErrors, null, null, List.of(src)) + .call()); + assertTrue("no compilation errors expected, but got: " + errors, + errors.isEmpty()); + Set expectedWrittenClasses = Set.of("Test"); + assertTrue("compiled correct classes: " + rfm.writtenClasses, + expectedWrittenClasses.equals(rfm.writtenClasses)); + } + + errors.clear(); + + JavaFileObject src = SimpleJavaFileObject.forSource(URI.create("mem:///Test.java"), + """ + public class Test { + Unknown u; + } + """); + assertTrue("compilation succeeded unexpectedly!", + !compiler.getTask(null, null, noErrors, null, null, List.of(src)) + .call()); + List expectedCompilationErrors = List.of( + "mem:///Test.java:2:5:compiler.err.cant.resolve.location" + ); + assertTrue("incorrect compilation errors, expected: " + expectedCompilationErrors + + "actual: " + errors, + expectedCompilationErrors.equals(errors)); + } + + private static final class LoggingFileManager extends ForwardingJavaFileManager { + + private final Set writtenClasses = new HashSet<>(); + + public LoggingFileManager(JavaFileManager fileManager) { + super(fileManager); + } + + @Override + public JavaFileObject getJavaFileForOutput(Location location, + String className, + JavaFileObject.Kind kind, + FileObject sibling) throws IOException { + writtenClasses.add(className); + + return super.getJavaFileForOutput(location, className, kind, sibling); + } + + } + + private static void assertTrue(String message, boolean c) { + if (!c) { + throw new AssertionError(message); + } + } +} diff --git a/test/langtools/tools/lib/snippets/SnippetUtils.java b/test/langtools/tools/lib/snippets/SnippetUtils.java index f3dffcb30fa..96b75b62a48 100644 --- a/test/langtools/tools/lib/snippets/SnippetUtils.java +++ b/test/langtools/tools/lib/snippets/SnippetUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,7 +24,6 @@ package snippets; import java.io.File; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.net.URI; @@ -35,7 +34,6 @@ import java.util.List; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Consumer; -import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -557,11 +555,7 @@ public class SnippetUtils { } }""".formatted(body); }; - JavaFileObject fo = new SimpleJavaFileObject(uri, JavaFileObject.Kind.SOURCE) { - public CharSequence getCharContent(boolean ignoreEncodingErrors) { - return compUnit; - } - }; + JavaFileObject fo = SimpleJavaFileObject.forSource(uri, compUnit); JavaFileManager fm = compiler.getStandardFileManager(dl, null, null);