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