1 /* 2 * Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 /* 25 * @test 26 * @bug 8192920 8204588 8246774 8248843 8268869 8235876 8328339 8335896 8344706 27 * 8362237 28 * @summary Test source launcher 29 * @library /tools/lib 30 * @modules jdk.compiler/com.sun.tools.javac.api 31 * jdk.compiler/com.sun.tools.javac.launcher 32 * jdk.compiler/com.sun.tools.javac.main 33 * java.base/jdk.internal.module 34 * @build toolbox.JavaTask toolbox.JavacTask toolbox.TestRunner toolbox.ToolBox 35 * @run main SourceLauncherTest 36 */ 37 38 import java.lang.classfile.*; 39 import java.lang.classfile.attribute.ModuleResolutionAttribute; 40 import java.io.ByteArrayOutputStream; 41 import java.io.File; 42 import java.io.IOException; 43 import java.io.OutputStream; 44 import java.io.PrintStream; 45 import java.io.PrintWriter; 46 import java.io.StringWriter; 47 import java.lang.reflect.InvocationTargetException; 48 import java.nio.file.Files; 49 import java.nio.file.Path; 50 import java.nio.file.Paths; 51 import java.util.ArrayList; 52 import java.util.Collections; 53 import java.util.List; 54 import java.util.Properties; 55 import java.util.regex.Pattern; 56 57 import com.sun.tools.javac.launcher.SourceLauncher; 58 import com.sun.tools.javac.launcher.Fault; 59 60 import toolbox.JavaTask; 61 import toolbox.JavacTask; 62 import toolbox.Task; 63 import toolbox.TestRunner; 64 import toolbox.ToolBox; 65 66 import static jdk.internal.module.ClassFileConstants.WARN_INCUBATING; 67 68 public class SourceLauncherTest extends TestRunner { 69 public static void main(String... args) throws Exception { 70 SourceLauncherTest t = new SourceLauncherTest(); 71 t.runTests(m -> new Object[] { Paths.get(m.getName()) }); 72 } 73 74 SourceLauncherTest() { 75 super(System.err); 76 tb = new ToolBox(); 77 System.err.println("version: " + thisVersion); 78 } 79 80 final ToolBox tb; 81 private static final String thisVersion = System.getProperty("java.specification.version"); 82 83 /* 84 * Positive tests. 85 */ 86 87 @Test 88 public void testHelloWorld(Path base) throws IOException { 89 tb.writeJavaFiles(base, 90 "import java.util.Arrays;\n" + 91 "class HelloWorld {\n" + 92 " public static void main(String... args) {\n" + 93 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 94 " }\n" + 95 "}"); 96 testSuccess(base.resolve("HelloWorld.java"), "Hello World! [1, 2, 3]\n"); 97 } 98 99 @Test 100 public void testHelloWorldInPackage(Path base) throws IOException { 101 tb.writeJavaFiles(base, 102 "package hello;\n" + 103 "import java.util.Arrays;\n" + 104 "class World {\n" + 105 " public static void main(String... args) {\n" + 106 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 107 " }\n" + 108 "}"); 109 testSuccess(base.resolve("hello").resolve("World.java"), "Hello World! [1, 2, 3]\n"); 110 } 111 112 @Test 113 public void testHelloWorldInPackageWithStaticImport(Path base) throws IOException { 114 tb.writeJavaFiles(base, 115 """ 116 package hello; 117 import static hello.Helper.*; 118 import java.util.Arrays; 119 class World { 120 public static void main(String... args) { 121 m(args); 122 } 123 } 124 class Helper { 125 static void m(String... args) { 126 System.out.println("Hello World! " + Arrays.toString(args)); 127 } 128 } 129 """); 130 testSuccess(base.resolve("hello").resolve("World.java"), "Hello World! [1, 2, 3]\n"); 131 } 132 133 @Test 134 public void testHelloWorldWithAux(Path base) throws IOException { 135 tb.writeJavaFiles(base, 136 "import java.util.Arrays;\n" + 137 "class HelloWorld {\n" + 138 " public static void main(String... args) {\n" + 139 " Aux.write(args);\n" + 140 " }\n" + 141 "}\n" + 142 "class Aux {\n" + 143 " static void write(String... args) {\n" + 144 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 145 " }\n" + 146 "}"); 147 testSuccess(base.resolve("HelloWorld.java"), "Hello World! [1, 2, 3]\n"); 148 } 149 150 @Test 151 public void testHelloWorldWithShebang(Path base) throws IOException { 152 tb.writeJavaFiles(base, 153 "#!/usr/bin/java --source " + thisVersion + "\n" + 154 "import java.util.Arrays;\n" + 155 "class HelloWorld {\n" + 156 " public static void main(String... args) {\n" + 157 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 158 " }\n" + 159 "}"); 160 Files.copy(base.resolve("HelloWorld.java"), base.resolve("HelloWorld")); 161 testSuccess(base.resolve("HelloWorld"), "Hello World! [1, 2, 3]\n"); 162 } 163 164 @Test 165 public void testNoAnnoProcessing(Path base) throws IOException { 166 Path annoSrc = base.resolve("annoSrc"); 167 tb.writeJavaFiles(annoSrc, 168 "import java.util.*;\n" + 169 "import javax.annotation.processing.*;\n" + 170 "import javax.lang.model.element.*;\n" + 171 "@SupportedAnnotationTypes(\"*\")\n" + 172 "public class AnnoProc extends AbstractProcessor {\n" + 173 " public boolean process(Set<? extends TypeElement> annos, RoundEnvironment rEnv) {\n" + 174 " throw new Error(\"Annotation processor should not be invoked\");\n" + 175 " }\n" + 176 "}\n"); 177 Path annoClasses = Files.createDirectories(base.resolve("classes")); 178 new JavacTask(tb) 179 .outdir(annoClasses) 180 .files(annoSrc.resolve("AnnoProc.java").toString()) 181 .run(); 182 Path serviceFile = annoClasses.resolve("META-INF").resolve("services") 183 .resolve("javax.annotation.processing.Processor"); 184 tb.writeFile(serviceFile, "AnnoProc"); 185 186 Path mainSrc = base.resolve("mainSrc"); 187 tb.writeJavaFiles(mainSrc, 188 "import java.util.Arrays;\n" + 189 "class HelloWorld {\n" + 190 " public static void main(String... args) {\n" + 191 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 192 " }\n" + 193 "}"); 194 195 List<String> javacArgs = List.of("-classpath", annoClasses.toString()); 196 List<String> classArgs = List.of("1", "2", "3"); 197 String expect = "Hello World! [1, 2, 3]\n"; 198 Result r = run(mainSrc.resolve("HelloWorld.java"), javacArgs, classArgs); 199 checkEqual("stdout", r.stdOut, expect); 200 checkEmpty("stderr", r.stdErr); 201 checkNull("exception", r.exception); 202 } 203 204 @Test 205 public void testEnablePreview(Path base) throws IOException { 206 tb.writeJavaFiles(base, 207 "import java.util.Arrays;\n" + 208 "class HelloWorld {\n" + 209 " public static void main(String... args) {\n" + 210 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 211 " }\n" + 212 "}"); 213 214 String log = new JavaTask(tb) 215 .vmOptions("--enable-preview", "--source", thisVersion) 216 .className(base.resolve("HelloWorld.java").toString()) 217 .classArgs("1", "2", "3") 218 .run(Task.Expect.SUCCESS) 219 .getOutput(Task.OutputKind.STDOUT); 220 checkEqual("stdout", log.trim(), "Hello World! [1, 2, 3]"); 221 } 222 223 @Test 224 public void testCodeSource(Path base) throws IOException { 225 tb.writeJavaFiles(base, 226 "import java.net.URL;\n" + 227 "class ShowCodeSource {\n" + 228 " public static void main(String... args) {\n" + 229 " URL u = ShowCodeSource.class.getProtectionDomain().getCodeSource().getLocation();\n" + 230 " System.out.println(u);\n" + 231 " }\n" + 232 "}"); 233 234 Path file = base.resolve("ShowCodeSource.java"); 235 String log = new JavaTask(tb) 236 .className(file.toString()) 237 .run(Task.Expect.SUCCESS) 238 .getOutput(Task.OutputKind.STDOUT); 239 checkEqual("stdout", log.trim(), file.toAbsolutePath().toUri().toURL().toString()); 240 } 241 242 @Test 243 public void testSystemProperty(Path base) throws IOException { 244 tb.writeJavaFiles(base, 245 "class ShowProperty {\n" + 246 " public static void main(String... args) {\n" + 247 " System.out.println(System.getProperty(\"jdk.launcher.sourcefile\"));\n" + 248 " }\n" + 249 "}"); 250 251 Path file = base.resolve("ShowProperty.java"); 252 String log = new JavaTask(tb) 253 .className(file.toString()) 254 .run(Task.Expect.SUCCESS) 255 .getOutput(Task.OutputKind.STDOUT); 256 checkEqual("stdout", log.trim(), file.toAbsolutePath().toString()); 257 } 258 259 @Test 260 public void testThreadContextClassLoader(Path base) throws IOException { 261 tb.writeJavaFiles(base, //language=java 262 """ 263 class ThreadContextClassLoader { 264 public static void main(String... args) { 265 var expected = ThreadContextClassLoader.class.getClassLoader(); 266 var actual = Thread.currentThread().getContextClassLoader(); 267 System.out.println(expected == actual); 268 } 269 } 270 """); 271 272 Path file = base.resolve("ThreadContextClassLoader.java"); 273 String log = new JavaTask(tb) 274 .className(file.toString()) 275 .run(Task.Expect.SUCCESS) 276 .getOutput(Task.OutputKind.STDOUT); 277 checkEqual("stdout", log.trim(), "true"); 278 } 279 280 void testSuccess(Path file, String expect) throws IOException { 281 Result r = run(file, Collections.emptyList(), List.of("1", "2", "3")); 282 checkEqual("stdout", r.stdOut, expect); 283 checkEmpty("stderr", r.stdErr); 284 checkNull("exception", r.exception); 285 } 286 287 288 @Test 289 public void testMainNoParams(Path base) throws IOException { 290 tb.writeJavaFiles(base, 291 "package hello;\n" + 292 "import java.util.Arrays;\n" + 293 "class World {\n" + 294 " public static void main(String... args) {\n" + 295 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 296 " }\n" + 297 "}"); 298 testSuccess(base.resolve("hello").resolve("World.java"), "Hello World! [1, 2, 3]\n"); 299 } 300 301 @Test 302 public void testMainNotPublic(Path base) throws IOException { 303 tb.writeJavaFiles(base, 304 "package hello;\n" + 305 "import java.util.Arrays;\n" + 306 "class World {\n" + 307 " static void main(String... args) {\n" + 308 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 309 " }\n" + 310 "}"); 311 testSuccess(base.resolve("hello").resolve("World.java"), "Hello World! [1, 2, 3]\n"); 312 } 313 314 @Test 315 public void testMainNotStatic(Path base) throws IOException { 316 tb.writeJavaFiles(base, 317 "package hello;\n" + 318 "import java.util.Arrays;\n" + 319 "class World {\n" + 320 " public void main(String... args) {\n" + 321 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 322 " }\n" + 323 "}"); 324 testSuccess(base.resolve("hello").resolve("World.java"), "Hello World! [1, 2, 3]\n"); 325 } 326 327 /* 328 * Negative tests: such as cannot find or execute main method. 329 */ 330 331 @Test 332 public void testHelloWorldWithShebangJava(Path base) throws IOException { 333 tb.writeJavaFiles(base, 334 "#!/usr/bin/java --source " + thisVersion + "\n" + 335 "import java.util.Arrays;\n" + 336 "class HelloWorld {\n" + 337 " public static void main(String... args) {\n" + 338 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 339 " }\n" + 340 "}"); 341 Path file = base.resolve("HelloWorld.java"); 342 testError(file, 343 file + ":1: error: illegal character: '#'\n" + 344 "#!/usr/bin/java --source " + thisVersion + "\n" + 345 "^\n" + 346 file + ":1: error: class, interface, annotation type, enum, record, method or field expected\n" + 347 "#!/usr/bin/java --source " + thisVersion + "\n" + 348 " ^\n" + 349 "2 errors\n", 350 "error: compilation failed"); 351 } 352 353 @Test 354 public void testNoClass(Path base) throws IOException { 355 var path = Files.createDirectories(base.resolve("p")); 356 Path file = path.resolve("NoClass.java"); 357 Files.write(file, List.of("package p;")); 358 testError(file, "", "error: no class declared in source file"); 359 } 360 361 @Test 362 public void testMismatchOfPathAndPackage(Path base) throws IOException { 363 Files.createDirectories(base); 364 Path file = base.resolve("MismatchOfPathAndPackage.java"); 365 Files.write(file, List.of("package p; class MismatchOfPathAndPackage {}")); 366 testError(file, "", "error: end of path to source file does not match its package name p: " + file); 367 } 368 369 @Test 370 public void testLoadClass(Path base) throws IOException { 371 Path src1 = base.resolve("src1"); 372 Path file1 = src1.resolve("LoadClass.java"); 373 tb.writeJavaFiles(src1, 374 "class LoadClass {\n" 375 + " public static void main(String... args) {\n" 376 + " System.out.println(\"on classpath\");\n" 377 + " };\n" 378 + "}\n"); 379 Path classes1 = Files.createDirectories(base.resolve("classes")); 380 new JavacTask(tb) 381 .outdir(classes1) 382 .files(file1) 383 .run(); 384 String log1 = new JavaTask(tb) 385 .classpath(classes1.toString()) 386 .className("LoadClass") 387 .run(Task.Expect.SUCCESS) 388 .getOutput(Task.OutputKind.STDOUT); 389 checkEqual("stdout", log1.trim(), 390 "on classpath"); 391 392 Path src2 = base.resolve("src2"); 393 Path file2 = src2.resolve("LoadClass.java"); 394 tb.writeJavaFiles(src2, 395 "class LoadClass {\n" 396 + " public static void main(String... args) {\n" 397 + " System.out.println(\"in source file\");\n" 398 + " };\n" 399 + "}\n"); 400 String log2 = new JavaTask(tb) 401 .classpath(classes1.toString()) 402 .className(file2.toString()) 403 .run(Task.Expect.SUCCESS) 404 .getOutput(Task.OutputKind.STDOUT); 405 checkEqual("stdout", log2.trim(), 406 "in source file"); 407 } 408 409 @Test 410 public void testGetResource(Path base) throws IOException { 411 Path src = base.resolve("src"); 412 Path file = src.resolve("GetResource.java"); 413 tb.writeJavaFiles(src, 414 "class GetResource {\n" 415 + " public static void main(String... args) {\n" 416 + " System.out.println(GetResource.class.getClassLoader().getResource(\"GetResource.class\"));\n" 417 + " };\n" 418 + "}\n"); 419 Path classes = Files.createDirectories(base.resolve("classes")); 420 new JavacTask(tb) 421 .outdir(classes) 422 .files(file) 423 .run(); 424 425 String log = new JavaTask(tb) 426 .classpath(classes.toString()) 427 .className(file.toString()) 428 .run(Task.Expect.SUCCESS) 429 .getOutput(Task.OutputKind.STDOUT); 430 checkMatch("stdout", log.trim(), 431 Pattern.compile("sourcelauncher-memoryclassloader[0-9]+:GetResource.class")); 432 } 433 434 @Test 435 public void testGetResources(Path base) throws IOException { 436 Path src = base.resolve("src"); 437 Path file = src.resolve("GetResources.java"); 438 tb.writeJavaFiles(src, 439 "import java.io.*; import java.net.*; import java.util.*;\n" 440 + "class GetResources {\n" 441 + " public static void main(String... args) throws IOException {\n" 442 + " Enumeration<URL> e =\n" 443 + " GetResources.class.getClassLoader().getResources(\"GetResources.class\");\n" 444 + " while (e.hasMoreElements()) System.out.println(e.nextElement());\n" 445 + " };\n" 446 + "}\n"); 447 Path classes = Files.createDirectories(base.resolve("classes")); 448 new JavacTask(tb) 449 .outdir(classes) 450 .files(file) 451 .run(); 452 453 List<String> log = new JavaTask(tb) 454 .classpath(classes.toString()) 455 .className(file.toString()) 456 .run(Task.Expect.SUCCESS) 457 .getOutputLines(Task.OutputKind.STDOUT); 458 checkMatch("stdout:0", log.get(0).trim(), 459 Pattern.compile("sourcelauncher-memoryclassloader[0-9]+:GetResources.class")); 460 checkMatch("stdout:1", log.get(1).trim(), 461 Pattern.compile("file:/.*/testGetResources/classes/GetResources.class")); 462 } 463 464 @Test 465 public void testSyntaxErr(Path base) throws IOException { 466 tb.writeJavaFiles(base, "class SyntaxErr {"); 467 Path file = base.resolve("SyntaxErr.java"); 468 testError(file, 469 file + ":1: error: reached end of file while parsing\n" + 470 "class SyntaxErr {\n" + 471 " ^\n" + 472 "1 error\n", 473 "error: compilation failed"); 474 } 475 476 @Test 477 public void testNoSourceOnClassPath(Path base) throws IOException { 478 Path extraSrc = base.resolve("extraSrc"); 479 tb.writeJavaFiles(extraSrc, 480 "public class Extra {\n" + 481 " static final String MESSAGE = \"Hello World\";\n" + 482 "}\n"); 483 484 Path mainSrc = base.resolve("mainSrc"); 485 tb.writeJavaFiles(mainSrc, 486 "import java.util.Arrays;\n" + 487 "class HelloWorld {\n" + 488 " public static void main(String... args) {\n" + 489 " System.out.println(Extra.MESSAGE + Arrays.toString(args));\n" + 490 " }\n" + 491 "}"); 492 493 List<String> javacArgs = List.of("-classpath", extraSrc.toString()); 494 List<String> classArgs = List.of("1", "2", "3"); 495 String FS = File.separator; 496 String expectStdErr = 497 "testNoSourceOnClassPath" + FS + "mainSrc" + FS + "HelloWorld.java:4: error: cannot find symbol\n" + 498 " System.out.println(Extra.MESSAGE + Arrays.toString(args));\n" + 499 " ^\n" + 500 " symbol: variable Extra\n" + 501 " location: class HelloWorld\n" + 502 "1 error\n"; 503 Result r = run(mainSrc.resolve("HelloWorld.java"), javacArgs, classArgs); 504 checkEmpty("stdout", r.stdOut); 505 checkEqual("stderr", r.stdErr, expectStdErr); 506 checkFault("exception", r.exception, "error: compilation failed"); 507 } 508 509 @Test 510 public void testClassNotFound(Path base) throws IOException { 511 Path src = base.resolve("src"); 512 Path file = src.resolve("ClassNotFound.java"); 513 tb.writeJavaFiles(src, 514 "class ClassNotFound {\n" 515 + " public static void main(String... args) {\n" 516 + " try {\n" 517 + " Class.forName(\"NoSuchClass\");\n" 518 + " System.out.println(\"no exception\");\n" 519 + " System.exit(1);\n" 520 + " } catch (ClassNotFoundException e) {\n" 521 + " System.out.println(\"Expected exception thrown: \" + e);\n" 522 + " }\n" 523 + " };\n" 524 + "}\n"); 525 Path classes = Files.createDirectories(base.resolve("classes")); 526 new JavacTask(tb) 527 .outdir(classes) 528 .files(file) 529 .run(); 530 531 String log = new JavaTask(tb) 532 .classpath(classes.toString()) 533 .className(file.toString()) 534 .run(Task.Expect.SUCCESS) 535 .getOutput(Task.OutputKind.STDOUT); 536 checkEqual("stdout", log.trim(), 537 "Expected exception thrown: java.lang.ClassNotFoundException: NoSuchClass"); 538 } 539 540 // For any source file that is invoked through the OS shebang mechanism, invalid shebang 541 // lines will be caught and handled by the OS, before the launcher is even invoked. 542 // However, if such a file is passed directly to the launcher, perhaps using the --source 543 // option, a well-formed shebang line will be removed but a badly-formed one will be not be 544 // removed and will cause compilation errors. 545 @Test 546 public void testBadShebang(Path base) throws IOException { 547 tb.writeJavaFiles(base, 548 "#/usr/bin/java --source " + thisVersion + "\n" + 549 "import java.util.Arrays;\n" + 550 "class HelloWorld {\n" + 551 " public static void main(String... args) {\n" + 552 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 553 " }\n" + 554 "}"); 555 Path file = base.resolve("HelloWorld.java"); 556 testError(file, 557 file + ":1: error: illegal character: '#'\n" + 558 "#/usr/bin/java --source " + thisVersion + "\n" + 559 "^\n" + 560 file + ":1: error: class, interface, annotation type, enum, record, method or field expected\n" + 561 "#/usr/bin/java --source " + thisVersion + "\n" + 562 " ^\n" + 563 "2 errors\n", 564 "error: compilation failed"); 565 } 566 567 @Test 568 public void testBadSourceOpt(Path base) throws IOException { 569 Files.createDirectories(base); 570 Path file = base.resolve("DummyClass.java"); 571 Files.write(file, List.of("class DummyClass { }")); 572 Properties sysProps = System.getProperties(); 573 Properties p = new Properties(sysProps); 574 p.setProperty("jdk.internal.javac.source", "<BAD>"); 575 System.setProperties(p); 576 try { 577 testError(file, "", "error: invalid value for --source option: <BAD>"); 578 } finally { 579 System.setProperties(sysProps); 580 } 581 } 582 583 @Test 584 public void testEnablePreviewNoSource(Path base) throws IOException { 585 tb.writeJavaFiles(base, 586 "import java.util.Arrays;\n" + 587 "class HelloWorld {\n" + 588 " public static void main(String... args) {\n" + 589 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 590 " }\n" + 591 "}"); 592 593 List<String> log = new JavaTask(tb) 594 .vmOptions("--enable-preview") 595 .className(base.resolve("HelloWorld.java").toString()) 596 .run(Task.Expect.SUCCESS) 597 .getOutputLines(Task.OutputKind.STDOUT); 598 checkEqual("stdout", log, List.of("Hello World! []")); 599 } 600 601 @Test 602 public void testNoMain(Path base) throws IOException { 603 tb.writeJavaFiles(base, "class NoMain { }"); 604 testError(base.resolve("NoMain.java"), "", 605 "error: can't find main(String[]) or main() method in class: NoMain"); 606 } 607 608 @Test 609 public void testMainBadParams(Path base) throws IOException { 610 tb.writeJavaFiles(base, 611 "class BadParams { public static void main(int n) { } }"); 612 testError(base.resolve("BadParams.java"), "", 613 "error: can't find main(String[]) or main() method in class: BadParams"); 614 } 615 616 @Test 617 public void testMainNotVoid(Path base) throws IOException { 618 tb.writeJavaFiles(base, 619 "class NotVoid { public static int main(String... args) { return 0; } }"); 620 testError(base.resolve("NotVoid.java"), "", 621 "error: can't find main(String[]) or main() method in class: NotVoid"); 622 } 623 624 @Test 625 public void testClassInModule(Path base) throws IOException { 626 tb.writeJavaFiles(base, "package java.net; class InModule { }"); 627 Path file = base.resolve("java").resolve("net").resolve("InModule.java"); 628 testError(file, 629 file + ":1: error: package exists in another module: java.base\n" + 630 "package java.net; class InModule { }\n" + 631 "^\n" + 632 "1 error\n", 633 "error: compilation failed"); 634 } 635 636 @Test 637 public void testNoRecompileWithSuggestions(Path base) throws IOException { 638 tb.writeJavaFiles(base, 639 "class NoRecompile {\n" + 640 " void use(String s) {}\n" + 641 " void test() {\n" + 642 " use(1);\n" + 643 " }\n" + 644 " <T> void test(T t, Object o) {\n" + 645 " T t1 = (T) o;\n" + 646 " }\n" + 647 " static class Generic<T> {\n" + 648 " T t;\n" + 649 " void raw(Generic raw) {\n" + 650 " raw.t = \"\";\n" + 651 " }\n" + 652 " }\n" + 653 " void deprecation() {\n" + 654 " Thread.currentThread().stop();\n" + 655 " }\n" + 656 " void preview(Object o) {\n" + 657 " if (o instanceof String s) {\n" + 658 " System.out.println(s);\n" + 659 " }\n" + 660 " }\n" + 661 "}"); 662 Result r = run(base.resolve("NoRecompile.java"), Collections.emptyList(), Collections.emptyList()); 663 if (r.stdErr.contains("recompile with")) { 664 error("Unexpected recompile suggestions in error output: " + r.stdErr); 665 } 666 } 667 668 @Test 669 public void testNoOptionsWarnings(Path base) throws IOException { 670 tb.writeJavaFiles(base, "public class Main { public static void main(String... args) {}}"); 671 String log = new JavaTask(tb) 672 .vmOptions("--source", "21") 673 .className(base.resolve("Main.java").toString()) 674 .run(Task.Expect.SUCCESS) 675 .getOutput(Task.OutputKind.STDERR); 676 677 if (log.contains("warning: [options]")) { 678 error("Unexpected options warning in error output: " + log); 679 } 680 } 681 682 void testError(Path file, String expectStdErr, String expectFault) throws IOException { 683 Result r = run(file, Collections.emptyList(), List.of("1", "2", "3")); 684 checkEmpty("stdout", r.stdOut); 685 checkEqual("stderr", r.stdErr, expectStdErr); 686 checkFault("exception", r.exception, expectFault); 687 } 688 689 /* 690 * Tests in which main throws an exception. 691 */ 692 @Test 693 public void testTargetException1(Path base) throws IOException { 694 tb.writeJavaFiles(base, 695 "import java.util.Arrays;\n" + 696 "class Thrower {\n" + 697 " public static void main(String... args) {\n" + 698 " throwWhenZero(Integer.parseInt(args[0]));\n" + 699 " }\n" + 700 " static void throwWhenZero(int arg) {\n" + 701 " if (arg == 0) throw new Error(\"zero!\");\n" + 702 " throwWhenZero(arg - 1);\n" + 703 " }\n" + 704 "}"); 705 Path file = base.resolve("Thrower.java"); 706 Result r = run(file, Collections.emptyList(), List.of("3")); 707 checkEmpty("stdout", r.stdOut); 708 checkEmpty("stderr", r.stdErr); 709 checkTrace("exception", r.exception, 710 "java.lang.Error: zero!", 711 "at Thrower.throwWhenZero(Thrower.java:7)", 712 "at Thrower.throwWhenZero(Thrower.java:8)", 713 "at Thrower.throwWhenZero(Thrower.java:8)", 714 "at Thrower.throwWhenZero(Thrower.java:8)", 715 "at Thrower.main(Thrower.java:4)"); 716 } 717 718 /* 719 * Tests in which main throws a traceless exception. 720 */ 721 @Test 722 public void testTracelessTargetException(Path base) throws IOException { 723 tb.writeJavaFiles(base, """ 724 class TestLauncherException extends RuntimeException { 725 TestLauncherException() { 726 super("No trace", null, true, false); // No writable trace 727 } 728 729 public static void main(String... args) { 730 throw new TestLauncherException(); 731 } 732 } 733 """); 734 Path file = base.resolve("TestLauncherException.java"); 735 SourceLauncherTest.Result r = run(file, List.of(), List.of("3")); 736 checkEmpty("stdout", r.stdOut()); 737 checkEmpty("stderr", r.stdErr()); 738 checkTrace("exception", r.exception(), "TestLauncherException: No trace"); 739 } 740 741 @Test 742 public void testNoDuplicateIncubatorWarning(Path base) throws Exception { 743 Path module = base.resolve("lib"); 744 Path moduleSrc = module.resolve("src"); 745 Path moduleClasses = module.resolve("classes"); 746 Files.createDirectories(moduleClasses); 747 tb.cleanDirectory(moduleClasses); 748 tb.writeJavaFiles(moduleSrc, "module test {}"); 749 new JavacTask(tb) 750 .outdir(moduleClasses) 751 .files(tb.findJavaFiles(moduleSrc)) 752 .run() 753 .writeAll(); 754 markModuleAsIncubator(moduleClasses.resolve("module-info.class")); 755 tb.writeJavaFiles(base, "public class Main { public static void main(String... args) {}}"); 756 String log = new JavaTask(tb) 757 .vmOptions("--module-path", moduleClasses.toString(), 758 "--add-modules", "test") 759 .className(base.resolve("Main.java").toString()) 760 .run(Task.Expect.SUCCESS) 761 .writeAll() 762 .getOutput(Task.OutputKind.STDERR); 763 764 int numberOfWarnings = log.split("WARNING").length - 1; 765 766 if (log.contains("warning:") || numberOfWarnings != 1) { 767 error("Unexpected warning in error output: " + log); 768 } 769 770 List<String> compileLog = new JavacTask(tb) 771 .options("--module-path", moduleClasses.toString(), 772 "--add-modules", "test", 773 "-XDrawDiagnostics", 774 "-XDsourceLauncher", 775 "-XDshould-stop.at=FLOW") 776 .files(base.resolve("Main.java").toString()) 777 .run(Task.Expect.SUCCESS) 778 .writeAll() 779 .getOutputLines(Task.OutputKind.DIRECT); 780 781 List<String> expectedOutput = List.of( 782 "- compiler.warn.incubating.modules: test", 783 "1 warning" 784 ); 785 786 if (!expectedOutput.equals(compileLog)) { 787 error("Unexpected options : " + compileLog); 788 } 789 } 790 //where: 791 private static void markModuleAsIncubator(Path moduleInfoFile) throws Exception { 792 ClassModel cf = ClassFile.of().parse(moduleInfoFile); 793 ModuleResolutionAttribute newAttr = ModuleResolutionAttribute.of(WARN_INCUBATING); 794 byte[] newBytes = ClassFile.of().transformClass(cf, 795 ClassTransform.endHandler(classBuilder -> classBuilder.with(newAttr))); 796 try (OutputStream out = Files.newOutputStream(moduleInfoFile)) { 797 out.write(newBytes); 798 } 799 } 800 801 @Test 802 public void testAbstractClassInstanceMain(Path base) throws IOException { 803 tb.writeJavaFiles(base, 804 """ 805 public abstract class AbstractMain { 806 void main(String[] args) {} 807 } 808 """); 809 testError(base.resolve("AbstractMain.java"), "", 810 "error: abstract class: AbstractMain can not be instantiated"); 811 } 812 813 @Test 814 public void testWrongMainPrivate(Path base) throws IOException { 815 tb.writeJavaFiles(base, 816 """ 817 public class WrongMainPrivate { 818 private static void main(String[] args) {} 819 void main() { 820 System.out.println("correct"); 821 } 822 } 823 """); 824 testSuccess(base.resolve("WrongMainPrivate.java"), 825 "correct\n"); 826 } 827 828 @Test 829 public void testWrongMainPrivateInstance(Path base) throws IOException { 830 tb.writeJavaFiles(base, 831 """ 832 public class WrongMainPrivate { 833 private void main(String[] args) {} 834 void main() { 835 System.out.println("correct"); 836 } 837 } 838 """); 839 testSuccess(base.resolve("WrongMainPrivate.java"), 840 "correct\n"); 841 } 842 843 @Test 844 public void testWrongMainReturnType(Path base) throws IOException { 845 tb.writeJavaFiles(base, 846 """ 847 public class WrongMainReturnType { 848 public static int main(String[] args) { 849 return -1; 850 } 851 void main() { 852 System.out.println("correct"); 853 } 854 } 855 """); 856 testSuccess(base.resolve("WrongMainReturnType.java"), 857 "correct\n"); 858 } 859 860 @Test 861 public void testWrongMainReturnTypeInstance(Path base) throws IOException { 862 tb.writeJavaFiles(base, 863 """ 864 public class WrongMainReturnType { 865 public int main(String[] args) { 866 return -1; 867 } 868 void main() { 869 System.out.println("correct"); 870 } 871 } 872 """); 873 testSuccess(base.resolve("WrongMainReturnType.java"), 874 "correct\n"); 875 } 876 877 Result run(Path file, List<String> runtimeArgs, List<String> appArgs) { 878 List<String> args = new ArrayList<>(); 879 args.add(file.toString()); 880 args.addAll(appArgs); 881 882 PrintStream prev = System.out; 883 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 884 try (PrintStream out = new PrintStream(baos, true)) { 885 System.setOut(out); 886 StringWriter sw = new StringWriter(); 887 try (PrintWriter err = new PrintWriter(sw, true)) { 888 SourceLauncher m = new SourceLauncher(err); 889 m.run(toArray(runtimeArgs), toArray(args)); 890 return new Result(baos.toString(), sw.toString(), null); 891 } catch (Throwable t) { 892 return new Result(baos.toString(), sw.toString(), t); 893 } 894 } finally { 895 System.setOut(prev); 896 } 897 } 898 899 void checkEqual(String name, String found, String expect) { 900 expect = expect.replace("\n", tb.lineSeparator); 901 out.println(name + ": " + found); 902 if (!expect.equals(found)) { 903 error("Unexpected output; expected: " + expect); 904 } 905 } 906 907 void checkContains(String name, String found, String expect) { 908 expect = expect.replace("\n", tb.lineSeparator); 909 out.println(name + ": " + found); 910 if (!found.contains(expect)) { 911 error("Expected output not found: " + expect); 912 } 913 } 914 915 void checkEqual(String name, List<String> found, List<String> expect) { 916 out.println(name + ": " + found); 917 tb.checkEqual(expect, found); 918 } 919 920 void checkMatch(String name, String found, Pattern expect) { 921 out.println(name + ": " + found); 922 if (!expect.matcher(found).matches()) { 923 error("Unexpected output; expected match for: " + expect); 924 } 925 } 926 927 void checkEmpty(String name, String found) { 928 out.println(name + ": " + found); 929 if (!found.isEmpty()) { 930 error("Unexpected output; expected empty string"); 931 } 932 } 933 934 void checkNull(String name, Throwable found) { 935 out.println(name + ": " + found); 936 if (found != null) { 937 error("Unexpected exception; expected null"); 938 } 939 } 940 941 void checkFault(String name, Throwable found, String expect) { 942 expect = expect.replace("\n", tb.lineSeparator); 943 out.println(name + ": " + found); 944 if (found == null) { 945 error("No exception thrown; expected Fault"); 946 } else { 947 if (!(found instanceof Fault)) { 948 error("Unexpected exception; expected Fault"); 949 } 950 if (!(found.getMessage().equals(expect))) { 951 error("Unexpected detail message; expected: " + expect); 952 } 953 } 954 } 955 956 void checkTrace(String name, Throwable found, String... expect) { 957 if (!(found instanceof InvocationTargetException)) { 958 error("Unexpected exception; expected InvocationTargetException"); 959 out.println("Found:"); 960 found.printStackTrace(out); 961 } 962 StringWriter sw = new StringWriter(); 963 try (PrintWriter pw = new PrintWriter(sw)) { 964 ((InvocationTargetException) found).getTargetException().printStackTrace(pw); 965 } 966 String trace = sw.toString(); 967 out.println(name + ":\n" + trace); 968 String[] traceLines = trace.trim().split("[\r\n]+\\s+"); 969 try { 970 tb.checkEqual(List.of(traceLines), List.of(expect)); 971 } catch (Error e) { 972 error(e.getMessage()); 973 } 974 } 975 976 String[] toArray(List<String> list) { 977 return list.toArray(new String[list.size()]); 978 } 979 980 record Result(String stdOut, String stdErr, Throwable exception) {} 981 }