Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 17fa708b920f44e9e67c1a5a421612d92368ff41 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
/*******************************************************************************
 * Copyright (c) 2017, 2020 IBM Corporation and others.
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * This is an implementation of an early-draft specification developed under the Java
 * Community Process (JCP) and is made available for testing and evaluation purposes
 * only. The code is not compatible with any specification of the JCP.
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.jdt.compiler.tool.tests;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.ServiceLoader;
import java.util.Set;

import javax.lang.model.SourceVersion;
import javax.tools.Diagnostic;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileManager.Location;
import javax.tools.JavaFileObject.Kind;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler.CompilationTask;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jdt.compiler.tool.tests.AbstractCompilerToolTest.CompilerInvocationDiagnosticListener;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;
import org.eclipse.jdt.internal.compiler.tool.EclipseCompiler;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;

import junit.framework.TestCase;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class CompilerToolJava9Tests extends TestCase {
	private static final boolean DEBUG = false;
	private static final String RESOURCES_DIR = "resources";
	private JavaCompiler[] compilers;
	private String[] compilerNames;
	private boolean isJREBelow9;
	private static String _tmpFolder;
	private static String _tmpSrcFolderName;
	private static File _tmpSrcDir;
	private static String _tmpBinFolderName;
	private static File _tmpBinDir;
	public static String _tmpGenFolderName;
	private static File _tmpGenDir;

	private static String modules_directory;
	public CompilerToolJava9Tests(String name) {
		super(name);
	}
	@Override
	protected void setUp() throws Exception {
		this.isJREBelow9 = SourceVersion.latest().compareTo(SourceVersion.RELEASE_8) <= 0;
		if (isJREBelow9)
			return;
		this.compilers = new JavaCompiler[2];
		this.compilerNames = new String[2];
		ServiceLoader<JavaCompiler> javaCompilerLoader = ServiceLoader.load(JavaCompiler.class, EclipseCompiler.class.getClassLoader());
		for (JavaCompiler compiler : javaCompilerLoader) {
			if (compiler instanceof EclipseCompiler) {
				this.compilers[1] = compiler;
				this.compilerNames[1] = "Eclipse Compiler";
			}
		}
		this.compilerNames[0] = "System compiler";
		this.compilers[0] = ToolProvider.getSystemJavaCompiler();
		assertNotNull("System compiler unavailable", this.compilers[0]);
		assertNotNull("Eclipse compiler unavailable", this.compilers[1]);
		initializeLocations();
	}
	@Override
	protected void tearDown() throws Exception {
		if (isJREBelow9) {
			return;
		}
		deleteTree(new File(_tmpFolder));
		super.tearDown();
	}
	protected void initializeLocations() throws IOException {
		Path tempDirectory = Files.createTempDirectory("eclipse-temp");
		_tmpFolder = tempDirectory.toString();
		_tmpBinFolderName = _tmpFolder + File.separator + "bin";
		_tmpBinDir = new File(_tmpBinFolderName);
		deleteTree(_tmpBinDir); // remove existing contents
		Files.createDirectories(_tmpBinDir.toPath());
		assertTrue("couldn't mkdirs " + _tmpBinFolderName, _tmpBinDir.exists());

		_tmpGenFolderName = _tmpFolder + File.separator + "gen-src";
		_tmpGenDir = new File(_tmpGenFolderName);
		deleteTree(_tmpGenDir); // remove existing contents
		Files.createDirectories(_tmpGenDir.toPath());
		assertTrue("couldn't mkdirs " + _tmpGenFolderName, _tmpGenDir.exists());

		_tmpSrcFolderName = _tmpFolder + File.separator + "src";
		_tmpSrcDir = new File(_tmpSrcFolderName);
		deleteTree(_tmpSrcDir); // remove existing contents
		Files.createDirectories(_tmpSrcDir.toPath());
		assertTrue("couldn't mkdirs " + _tmpSrcFolderName, _tmpSrcDir.exists());

		modules_directory = getPluginDirectoryPath() + File.separator + "resources" + File.separator + "module_locations";

		Path moduleInfo = Paths.get(modules_directory, "source", "SimpleModules", "module.one", "module-info.java");
		assertTrue("File should exist: " + moduleInfo, Files.isReadable(moduleInfo));
		moduleInfo = Paths.get(modules_directory, "source", "SimpleModules", "module.two", "module-info.java");
		assertTrue("File should exist: " + moduleInfo, Files.isReadable(moduleInfo));
	}
	public void testGetLocationForModule1() {
		if (this.isJREBelow9) return;
		for(int i = 0; i < 2; i++) {
			String cName = this.compilerNames[i];
			JavaCompiler compiler = this.compilers[i];
			StandardJavaFileManager manager = compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset());
			try {
	            Location location = manager.getLocationForModule(StandardLocation.SYSTEM_MODULES, "java.base");
	            assertNotNull(cName + ": Location should not be null", location);
	        } catch (UnsupportedOperationException ex) {
	            fail(cName + ": Should support getLocationForModule()");
	        }
			catch (IOException e) {
	        	 fail(cName + ": Should support getLocationForModule()");
			}
		}

	}
	public void testSupportedCompilerVersions() throws IOException {
		if (this.isJREBelow9) return;
		for(int i = 0; i < 2; i++) {
			JavaCompiler compiler = this.compilers[i];
			Set<SourceVersion> sourceVersions = compiler.getSourceVersions();
			SourceVersion[] values = SourceVersion.values();
			for (SourceVersion sourceVersion : values) {
				// Javac doesn't appear to have < 3 versions in the supported list, but we do anyway
				if (!(compiler instanceof EclipseCompiler) &&
						sourceVersion.compareTo(SourceVersion.RELEASE_3) <= 0) {
					continue;
				}

				assertTrue("source version " + sourceVersion + " should be supported"
						+ "by compiler " + compiler.getClass().getName(), sourceVersions.contains(sourceVersion));
			}
			//	specifically test the last known - 9
			Object obj = SourceVersion.valueOf("RELEASE_9");
			assertTrue("source version 9 should be supported", sourceVersions.contains(obj));
		}
	}
	public void testGetLocationForModule2() throws IOException {
		if (this.isJREBelow9) return;
		for(int i = 0; i < 2; i++) {
			String cName = this.compilerNames[i];
			JavaCompiler compiler = this.compilers[i];
			if (!(compiler instanceof EclipseCompiler))
				continue;
			StandardJavaFileManager manager = compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset());
			Path path = Paths.get(modules_directory + File.separator + "source" + File.separator + "SimpleModules");
			manager.setLocationFromPaths(StandardLocation.MODULE_SOURCE_PATH, Arrays.asList(path));
			try {
				JavaFileManager.Location location = manager.getLocationForModule(StandardLocation.MODULE_SOURCE_PATH, "module.two");
				Path moduleInfo = path.resolve("module.two" + File.separator + "module-info.java");
				assertTrue("File should exist: " + moduleInfo, Files.isReadable(moduleInfo));
				assertNotNull(cName + ": module path location should not be null for path " + path, location);
			} catch (UnsupportedOperationException ex) {
				fail(cName + ":Should support getLocationForModule()");
			}
		}
	}
	// Incomplete tests - fails both with Javac and ECJ
	public void testGetLocationForModule3() throws IOException {
		if (this.isJREBelow9) return;
		for(int i = 0; i < 2; i++) {
			String cName = this.compilerNames[i];
			JavaCompiler compiler = this.compilers[i];
			if (!(compiler instanceof EclipseCompiler))
				continue;
			StandardJavaFileManager manager = compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset());
			Path path = Paths.get(modules_directory + File.separator + "source" + File.separator + "SimpleModules");
			manager.setLocationFromPaths(StandardLocation.MODULE_SOURCE_PATH, Arrays.asList(path));
			try {
				JavaFileManager.Location location = manager.getLocationForModule(StandardLocation.MODULE_SOURCE_PATH, "module.one");
				Path moduleInfo = path.resolve("module.one" + File.separator + "module-info.java");
				assertTrue("File should exist: " + moduleInfo, Files.isReadable(moduleInfo));
				assertNotNull(cName + ": module path location should not be null for path " + path, location);
			} catch (UnsupportedOperationException ex) {
				fail(cName + ":Should support getLocationForModule()");
			}
		}
	}
	public void testOptionRelease1() throws IOException {
		if (this.isJREBelow9) return;
		JavaCompiler compiler = this.compilers[1];
		String tmpFolder = _tmpFolder;
		File inputFile = new File(tmpFolder, "X.java");
		try (Writer writer = new BufferedWriter(new FileWriter(inputFile))) {
			writer.write(
				"package p;\n" +
				"public class X {}");
		}
		StandardJavaFileManager manager = compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset());

		ForwardingJavaFileManager<StandardJavaFileManager> forwardingJavaFileManager = new ForwardingJavaFileManager<StandardJavaFileManager>(manager) {
			@Override
			public FileObject getFileForInput(Location location, String packageName, String relativeName)
					throws IOException {
				if (DEBUG) {
					System.out.println("Create file for input : " + packageName + " " + relativeName + " in location " + location);
				}
				return super.getFileForInput(location, packageName, relativeName);
			}
			@Override
			public JavaFileObject getJavaFileForInput(Location location, String className, Kind kind)
					throws IOException {
				if (DEBUG) {
					System.out.println("Create java file for input : " + className + " in location " + location);
				}
				return super.getJavaFileForInput(location, className, kind);
			}
			@Override
			public JavaFileObject getJavaFileForOutput(Location location,
					String className,
					Kind kind,
					FileObject sibling) throws IOException {

				if (DEBUG) {
					System.out.println("Create .class file for " + className + " in location " + location + " with sibling " + sibling.toUri());
				}
				JavaFileObject javaFileForOutput = super.getJavaFileForOutput(location, className, kind, sibling);
				if (DEBUG) {
					System.out.println(javaFileForOutput.toUri());
				}
				return javaFileForOutput;
			}
		};
		// create new list containing input file
		List<File> files = new ArrayList<File>();
		files.add(inputFile);
		Iterable<? extends JavaFileObject> units = manager.getJavaFileObjectsFromFiles(files);
		StringWriter stringWriter = new StringWriter();
		PrintWriter printWriter = new PrintWriter(stringWriter);

		List<String> options = new ArrayList<String>();
		options.add("-d");
		options.add(tmpFolder);
		options.add("--release");
		options.add("8");
		ByteArrayOutputStream errBuffer = new ByteArrayOutputStream();
		PrintWriter err = new PrintWriter(errBuffer);
		CompilerInvocationDiagnosticListener listener = new CompilerInvocationDiagnosticListener(err) {
			@Override
			public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
				JavaFileObject source = diagnostic.getSource();
				assertNotNull("No source", source);
				super.report(diagnostic);
			}
		};
 		CompilationTask task = compiler.getTask(printWriter, forwardingJavaFileManager, listener, options, null, units);
 		// check the classpath location
 		assertTrue("Has no location CLASS_OUPUT", forwardingJavaFileManager.hasLocation(StandardLocation.CLASS_OUTPUT));
		Boolean result = task.call();
		printWriter.flush();
		printWriter.close();
 		if (!result.booleanValue()) {
 			System.err.println("Compilation failed: " + stringWriter.getBuffer().toString());
 	 		assertTrue("Compilation failed ", false);
 		}
 		ClassFileReader reader = null;
 		try {
			reader = ClassFileReader.read(new File(tmpFolder, "p/X.class"), true);
		} catch (ClassFormatException e) {
			assertTrue("Should not happen", false);
		} catch (IOException e) {
			assertTrue("Should not happen", false);
		}
		assertNotNull("No reader", reader);
		// This needs fix. This test case by design will produce different output every compiler version.
 		assertEquals("Wrong value", ClassFileConstants.JDK1_8, reader.getVersion());
		// check that the .class file exist for X
		assertTrue("delete failed", inputFile.delete());
	}
	public void testOptionRelease2() throws IOException {
		if (this.isJREBelow9) return;
		JavaCompiler compiler = this.compilers[1];
		String tmpFolder = _tmpFolder;
		File inputFile = new File(tmpFolder, "X.java");
		try (Writer writer = new BufferedWriter(new FileWriter(inputFile))){
			writer.write(
				"package p;\n" +
				"public class X {}");
		}
		StandardJavaFileManager manager = compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset());

		ForwardingJavaFileManager<StandardJavaFileManager> forwardingJavaFileManager = new ForwardingJavaFileManager<StandardJavaFileManager>(manager) {
			@Override
			public FileObject getFileForInput(Location location, String packageName, String relativeName)
					throws IOException {
				if (DEBUG) {
					System.out.println("Create file for input : " + packageName + " " + relativeName + " in location " + location);
				}
				return super.getFileForInput(location, packageName, relativeName);
			}
			@Override
			public JavaFileObject getJavaFileForInput(Location location, String className, Kind kind)
					throws IOException {
				if (DEBUG) {
					System.out.println("Create java file for input : " + className + " in location " + location);
				}
				return super.getJavaFileForInput(location, className, kind);
			}
			@Override
			public JavaFileObject getJavaFileForOutput(Location location,
					String className,
					Kind kind,
					FileObject sibling) throws IOException {

				if (DEBUG) {
					System.out.println("Create .class file for " + className + " in location " + location + " with sibling " + sibling.toUri());
				}
				JavaFileObject javaFileForOutput = super.getJavaFileForOutput(location, className, kind, sibling);
				if (DEBUG) {
					System.out.println(javaFileForOutput.toUri());
				}
				return javaFileForOutput;
			}
		};
		// create new list containing input file
		List<File> files = new ArrayList<File>();
		files.add(inputFile);
		Iterable<? extends JavaFileObject> units = manager.getJavaFileObjectsFromFiles(files);
		StringWriter stringWriter = new StringWriter();
		PrintWriter printWriter = new PrintWriter(stringWriter);

		List<String> options = new ArrayList<String>();
		options.add("-d");
		options.add(tmpFolder);
		options.add("--release");
		options.add("8");
		ByteArrayOutputStream errBuffer = new ByteArrayOutputStream();
		PrintWriter err = new PrintWriter(errBuffer);
		CompilerInvocationDiagnosticListener listener = new CompilerInvocationDiagnosticListener(err) {
			@Override
			public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
				JavaFileObject source = diagnostic.getSource();
				assertNotNull("No source", source);
				super.report(diagnostic);
			}
		};
 		CompilationTask task = compiler.getTask(printWriter, forwardingJavaFileManager, listener, options, null, units);
 		// check the classpath location
 		assertTrue("Has no location CLASS_OUPUT", forwardingJavaFileManager.hasLocation(StandardLocation.CLASS_OUTPUT));
		Boolean result = task.call();
		printWriter.flush();
		printWriter.close();
 		if (!result.booleanValue()) {
 			System.err.println("Compilation failed: " + stringWriter.getBuffer().toString());
 	 		assertTrue("Compilation failed ", false);
 		}
 		ClassFileReader reader = null;
 		try {
			reader = ClassFileReader.read(new File(tmpFolder, "p/X.class"), true);
		} catch (ClassFormatException e) {
			assertTrue("Should not happen", false);
		} catch (IOException e) {
			assertTrue("Should not happen", false);
		}
		assertNotNull("No reader", reader);
		// This needs fix. This test case by design will produce different output every compiler version.
 		assertEquals("Wrong value", ClassFileConstants.JDK1_8, reader.getVersion());
		// check that the .class file exist for X
		assertTrue("delete failed", inputFile.delete());
	}
	public void testOptionRelease3() throws IOException {
		if (this.isJREBelow9) return;
		JavaCompiler compiler = this.compilers[1];
		String tmpFolder = _tmpFolder;
		File inputFile = new File(tmpFolder, "X.java");
		try (Writer writer = new BufferedWriter(new FileWriter(inputFile))){
			writer.write(
				"package p;\n" +
				"public class X {}");
		}
		StandardJavaFileManager manager = compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset());

		ForwardingJavaFileManager<StandardJavaFileManager> forwardingJavaFileManager = new ForwardingJavaFileManager<StandardJavaFileManager>(manager) {
			@Override
			public FileObject getFileForInput(Location location, String packageName, String relativeName)
					throws IOException {
				if (DEBUG) {
					System.out.println("Create file for input : " + packageName + " " + relativeName + " in location " + location);
				}
				return super.getFileForInput(location, packageName, relativeName);
			}
			@Override
			public JavaFileObject getJavaFileForInput(Location location, String className, Kind kind)
					throws IOException {
				if (DEBUG) {
					System.out.println("Create java file for input : " + className + " in location " + location);
				}
				return super.getJavaFileForInput(location, className, kind);
			}
			@Override
			public JavaFileObject getJavaFileForOutput(Location location,
					String className,
					Kind kind,
					FileObject sibling) throws IOException {

				if (DEBUG) {
					System.out.println("Create .class file for " + className + " in location " + location + " with sibling " + sibling.toUri());
				}
				JavaFileObject javaFileForOutput = super.getJavaFileForOutput(location, className, kind, sibling);
				if (DEBUG) {
					System.out.println(javaFileForOutput.toUri());
				}
				return javaFileForOutput;
			}
		};
		// create new list containing input file
		List<File> files = new ArrayList<File>();
		files.add(inputFile);
		Iterable<? extends JavaFileObject> units = manager.getJavaFileObjectsFromFiles(files);
		StringWriter stringWriter = new StringWriter();
		PrintWriter printWriter = new PrintWriter(stringWriter);

		List<String> options = new ArrayList<String>();
		options.add("-d");
		options.add(tmpFolder);
		options.add("--release");
		options.add("8");
		options.add("-source");
		options.add("7");
		ByteArrayOutputStream errBuffer = new ByteArrayOutputStream();
		PrintWriter err = new PrintWriter(errBuffer);
		CompilerInvocationDiagnosticListener listener = new CompilerInvocationDiagnosticListener(err);
//		{ bug 533830 removed: an option error has no source associated with it, so the below was copied wrongly.
//			@Override
//			public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
//				JavaFileObject source = diagnostic.getSource();
//				assertNotNull("No source", source);
//				super.report(diagnostic);
//			}
//		};
		try {
			compiler.getTask(printWriter, forwardingJavaFileManager, listener, options, null, units);
			fail("compilation didn't fail as expected");
		} catch(IllegalArgumentException iae) {
			assertEquals("option -source is not supported when --release is used", iae.getMessage());
		}
	}
	public void testClassOutputLocationForModule_1() throws IOException {
		if (this.isJREBelow9) return;
		for(int i = 0; i < 2; i++) {
			String cName = this.compilerNames[i];
			JavaCompiler compiler = this.compilers[i];
			if (!(compiler instanceof EclipseCompiler))
				continue;
			StandardJavaFileManager manager = compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset());
			Path path = Paths.get(modules_directory + File.separator + "source" + File.separator + "SimpleModules");
			manager.setLocationFromPaths(StandardLocation.MODULE_SOURCE_PATH, Arrays.asList(path));
			manager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(_tmpBinDir));
			try {
				JavaFileManager.Location location = manager.getLocationForModule(StandardLocation.CLASS_OUTPUT, "module.two");
				assertNotNull(cName + ":module path location should not be null", location);
				assertTrue("should be output location", location.isOutputLocation());
			} catch (UnsupportedOperationException ex) {
				fail(cName + ":Should support getLocationForModule()");
			}
		}
	}
	public void testClassOutputLocationForModule_2() throws IOException {
		if (this.isJREBelow9) return;
		for(int i = 0; i < 2; i++) {
			String cName = this.compilerNames[i];
			JavaCompiler compiler = this.compilers[i];
			if (!(compiler instanceof EclipseCompiler))
				continue;
			StandardJavaFileManager manager = compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset());
			Path path = Paths.get(modules_directory + File.separator + "source" + File.separator + "SimpleModules" + File.separator + "module.one");
			manager.setLocationForModule(StandardLocation.MODULE_SOURCE_PATH, "module.one", Arrays.asList(path));
			path = Paths.get(modules_directory + File.separator + "source" + File.separator + "SimpleModules" + File.separator + "module.two");
			manager.setLocationForModule(StandardLocation.MODULE_SOURCE_PATH, "module.two", Arrays.asList(path));
			manager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(_tmpBinDir));
			try {
				JavaFileManager.Location location = manager.getLocationForModule(StandardLocation.CLASS_OUTPUT, "module.one");
				assertTrue("should be output location", location.isOutputLocation());
				assertNotNull(cName + ":module path location should not be null", location);
				Iterable<? extends Path> locationAsPaths = manager.getLocationAsPaths(location);
				int count = 0;
				boolean found = false;
				for (Path path2 : locationAsPaths) {
					if (path2.endsWith("module.one")) {
						found = true;
					}
					count++;
				}
				assertEquals("incorrect no of output locations", 1, count);
				assertTrue("output location for module.two not found", found);
				location = manager.getLocationForModule(StandardLocation.CLASS_OUTPUT, "module.two");
				assertTrue("should be output location", location.isOutputLocation());
				assertNotNull(cName + ":module path location should not be null", location);
				locationAsPaths = manager.getLocationAsPaths(location);
				count = 0;
				found = false;
				for (Path path2 : locationAsPaths) {
					if (path2.endsWith("module.two")) {
						found = true;
					}
					count++;
				}
				assertEquals("incorrect no of output locations", 1, count);
				assertTrue("output location for module.two not found", found);

			} catch (UnsupportedOperationException ex) {
				fail(cName + ":Should support getLocationForModule()");
			}
		}
	}
	// Test that non-module folders inside module-path are not considered 
	// to be automatic modules.
	public void testBug565748() throws IOException {
		if (this.isJREBelow9) return;
		JavaCompiler compiler = this.compilers[1];
		String tmpFolder = _tmpFolder;
		StandardJavaFileManager manager = compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset());

		// create new list containing input file
		List<File> files = new ArrayList<File>();
		files.add(new File(modules_directory + File.separator + "source" + File.separator + "SimpleModules" +
										File.separator + "module.one" + File.separator + "module-info.java"));
		files.add(new File(modules_directory + File.separator + "source" + File.separator + "SimpleModules" +
				File.separator + "module.two" + File.separator + "module-info.java"));
		Iterable<? extends JavaFileObject> units = manager.getJavaFileObjectsFromFiles(files);
		StringWriter stringWriter = new StringWriter();
		PrintWriter printWriter = new PrintWriter(stringWriter);

		List<String> options = new ArrayList<String>();
		options.add("-d");
		options.add(tmpFolder);
		options.add("--module-source-path");
		options.add(modules_directory + File.separator + "source" + File.separator + "SimpleModules");
		ByteArrayOutputStream errBuffer = new ByteArrayOutputStream();
		PrintWriter err = new PrintWriter(errBuffer);
		CompilerInvocationDiagnosticListener listener = new CompilerInvocationDiagnosticListener(err) {
			@Override
			public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
				JavaFileObject source = diagnostic.getSource();
				assertNotNull("No source", source);
				super.report(diagnostic);
			}
		};
 		CompilationTask task = compiler.getTask(printWriter, manager, listener, options, null, units);
 		// check the classpath location
		Boolean result = task.call();
		printWriter.flush();
		printWriter.close();
 		if (!result.booleanValue()) {
 			System.err.println("Compilation failed unexpectedly: " + stringWriter.getBuffer().toString());
 	 		assertTrue("Compilation failed ", false);
 		}
 		
 		// Try using the same outut as module-path and compile the new module (mod.test)
		manager = compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset());

		// create new list containing input file
		files = new ArrayList<File>();
		files.add(new File(modules_directory + File.separator + "bug565748" + File.separator + 
									"mod.test" + File.separator + "module-info.java"));
		units = manager.getJavaFileObjectsFromFiles(files);
		stringWriter = new StringWriter();
		printWriter = new PrintWriter(stringWriter);

		options = new ArrayList<String>();
		options.add("-d");
		options.add(tmpFolder);
		options.add("--module-path");
		options.add(tmpFolder);
		options.add("--module-source-path");
		options.add(modules_directory + File.separator + "bug565748");
		errBuffer = new ByteArrayOutputStream();
		err = new PrintWriter(errBuffer);
		listener = new CompilerInvocationDiagnosticListener(err) {
			@Override
			public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
				JavaFileObject source = diagnostic.getSource();
				assertNotNull("No source", source);
				super.report(diagnostic);
			}
		};
 		task = compiler.getTask(printWriter, manager, listener, options, null, units);
		result = task.call();
		printWriter.flush();
		printWriter.close();
 		if (!result.booleanValue()) {
 			System.err.println("Compilation failed unexpectedly: " + stringWriter.getBuffer().toString());
 	 		assertTrue("Compilation failed ", false);
 		}
 		
 		// Delete the module-info.class from the previously compiled modules
 		// and try compiling the same module mod.test
 		File file = new File(tmpFolder + File.separator + "mod.test" + File.separator + "module-info.class");
 		file.delete();
 		file = new File(tmpFolder + File.separator + "mod.test");
 		file.delete();
 		file = new File(tmpFolder + File.separator + "module.one" + File.separator + "module-info.class");
 		file.delete();
 		file = new File(tmpFolder + File.separator + "module.two" + File.separator + "module-info.class");
 		file.delete();
 		manager = compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset());

 		// create new list containing input file
 		files = new ArrayList<File>();
 		files.add(new File(modules_directory + File.separator + "bug565748" + File.separator + 
 				"mod.test" + File.separator + "module-info.java"));
 		units = manager.getJavaFileObjectsFromFiles(files);
 		stringWriter = new StringWriter();
 		printWriter = new PrintWriter(stringWriter);

 		options = new ArrayList<String>();
 		options.add("-d");
 		options.add(tmpFolder);
 		options.add("--module-path");
 		options.add(tmpFolder);
 		options.add("--module-source-path");
 		options.add(modules_directory + File.separator + "bug565748");
 		errBuffer = new ByteArrayOutputStream();
 		err = new PrintWriter(errBuffer);
 		listener = new CompilerInvocationDiagnosticListener(err) {
 			@Override
 			public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
 				JavaFileObject source = diagnostic.getSource();
 				assertNotNull("No source", source);
 				super.report(diagnostic);
 			}
 		};
 		task = compiler.getTask(printWriter, manager, listener, options, null, units);
 		result = task.call();
 		printWriter.flush();
 		printWriter.close();
 		if (result.booleanValue()) {
 			System.err.println("Compilation should fail: " + stringWriter.getBuffer().toString());
 			assertTrue("Compilation did not fail ", false);
 		}
	}
	public void testGetJavaFileObjects() {
		if (this.isJREBelow9) return;
	}
	public void testGetJavaFileObjects2() {
		if (this.isJREBelow9) return;
	}
	public void testSetLocationAsPaths() {
		if (this.isJREBelow9) return;
	}
	public void testContains() {
		if (this.isJREBelow9) return;
	}
	public void testGetServiceLoader() {
		if (this.isJREBelow9) return;
	}
	public void testInferModuleName() {
		if (this.isJREBelow9) return;
	}
	public void testListLocationsForModules() {
		if (this.isJREBelow9) return;
	}
	public void testAsPath() {
		if (this.isJREBelow9) return;
	}

	/*-- Code for testing bug 533830 --*/

	public void testBug533830_1() throws IOException {
		if (this.isJREBelow9) return;

		File src = createClassSource(
			"package p;\n"
		+	"public class X {}"
		);

		CompilerBuilder b = new CompilerBuilder()
			.option("--release", "8")
			.option("-source", "7")
			.file(src)
			;
		try {
			b.compile();
			fail("compilation didn't fail as expected");
		} catch(IllegalArgumentException iae) {
			assertEquals("option -source is not supported when --release is used", iae.getMessage());
		}

		//-- We must now also have a diagnostic
		assertTrue("The diagnostic listener did not receive an error for the illegal option", b.listener().hasDiagnostic("option -source is not supported when --release is used"));
	}

	/**
	 * Helps with building a compiler invocation, handling the common parts of testing.
	 */
	private final class CompilerBuilder {
		private final JavaCompiler compiler;

		private final List<String> options = new ArrayList<>();

		private final List<File> files = new ArrayList<>();

		private final StringWriter errorWriter = new StringWriter();

		private DiagListener listener;

		CompilerBuilder() {
			compiler = compilers[1];
		}

		public void compile() {
			String tmpFolder = _tmpFolder;
			StandardJavaFileManager manager = compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset());

			Iterable<? extends JavaFileObject> units = manager.getJavaFileObjectsFromFiles(files);
			PrintWriter errWriter = new PrintWriter(errorWriter);

			if(! options.contains("-d")) {
				option("-d", tmpFolder);
			}

			listener = new DiagListener(errWriter);

			ForwardingJavaFileManager<StandardJavaFileManager> forwardingManager = createFileManager(manager);
			compiler.getTask(errWriter, forwardingManager, listener, options, null, units);
		}

		public CompilerBuilder option(String... s) {
			options.addAll(Arrays.asList(s));
			return this;
		}

		public CompilerBuilder file(File f) {
			files.add(f);
			return this;
		}

		public DiagListener listener() {
			if(null == listener)
				throw new IllegalStateException("Call compile() before using the listener");
			return listener;
		}

		public ForwardingJavaFileManager<StandardJavaFileManager> createFileManager(StandardJavaFileManager manager) {
			ForwardingJavaFileManager<StandardJavaFileManager> forwardingJavaFileManager = new ForwardingJavaFileManager<StandardJavaFileManager>(manager) {
				@Override
				public FileObject getFileForInput(Location location, String packageName, String relativeName)
						throws IOException {
					if (DEBUG) {
						System.out.println("Create file for input : " + packageName + " " + relativeName + " in location " + location);
					}
					return super.getFileForInput(location, packageName, relativeName);
				}
				@Override
				public JavaFileObject getJavaFileForInput(Location location, String className, Kind kind)
						throws IOException {
					if (DEBUG) {
						System.out.println("Create java file for input : " + className + " in location " + location);
					}
					return super.getJavaFileForInput(location, className, kind);
				}
				@Override
				public JavaFileObject getJavaFileForOutput(Location location,
						String className,
						Kind kind,
						FileObject sibling) throws IOException {

					if (DEBUG) {
						System.out.println("Create .class file for " + className + " in location " + location + " with sibling " + sibling.toUri());
					}
					JavaFileObject javaFileForOutput = super.getJavaFileForOutput(location, className, kind, sibling);
					if (DEBUG) {
						System.out.println(javaFileForOutput.toUri());
					}
					return javaFileForOutput;
				}
			};
			return forwardingJavaFileManager;
		}
	}

	static private final class DiagListener extends CompilerInvocationDiagnosticListener {
		private List<Diagnostic<? extends JavaFileObject>> errorList = new ArrayList<>();

		DiagListener(PrintWriter err) {
			super(err);
		}

		@Override
		public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
			errorList.add(diagnostic);
			super.report(diagnostic);
		}

		public boolean hasDiagnostic(String match) {
			for(Diagnostic<? extends JavaFileObject> d: errorList) {
				String msg = d.getMessage(Locale.US).toLowerCase();
				if(msg.contains(match.toLowerCase()))
					return true;
			}
			return false;
		}
	}

	private File createClassSource(String source) throws IOException {
		String tmpFolder = _tmpFolder;
		File inputFile = new File(tmpFolder, "X.java");
		try (Writer writer = new FileWriter(inputFile)){
			writer.write(source);
			return inputFile;
		}
	}

	/*-- end code for bug 533830 --*/

	/**
	 * Recursively delete the contents of a directory, including any subdirectories.
	 * This is not optimized to handle very large or deep directory trees efficiently.
	 * @param f is either a normal file (which will be deleted) or a directory
	 * (which will be emptied and then deleted).
	 * @throws IOException
	 */
	public static void deleteTree(File f) throws IOException
	{
		if (null == f) {
			return;
		}
		File[] children = f.listFiles();
		if (null != children) {
			// if f has any children, (recursively) delete them
			for (File child : children) {
				deleteTree(child);
			}
		}
		// At this point f is either a normal file or an empty directory
		Files.deleteIfExists(f.toPath());
	}
	/**
	 * Copy a file from one location to another, unless the destination file already exists and has
	 * the same timestamp and file size. Create the destination location if necessary. Convert line
	 * delimiters according to {@link #shouldConvertToIndependentLineDelimiter(File)}.
	 *
	 * @param src
	 *            the full path to the resource location.
	 * @param destFolder
	 *            the full path to the destination location.
	 * @throws IOException
	 */
	public static void copyResource(File src, File dest) throws IOException {
		if (dest.exists() &&
				src.lastModified() < dest.lastModified() &&
				src.length() == dest.length())
		{
			return;
		}

		// read source bytes
		byte[] srcBytes = null;
		srcBytes = read(src);

		if (shouldConvertToIndependentLineDelimiter(src)) {
			String contents = new String(srcBytes);
			contents = convertToIndependentLineDelimiter(contents);
			srcBytes = contents.getBytes();
		}
		writeFile(dest, srcBytes);
	}

	public static void writeFile(File dest, byte[] srcBytes) throws IOException {
		File destFolder = dest.getParentFile();
		Files.createDirectories(destFolder.toPath());
		// write bytes to dest
		Files.write(dest.toPath(), srcBytes);
	}

	/**
	 * Copy a resource that is located under the <code>resources</code> folder of the plugin to a
	 * corresponding location under the specified target folder. Convert line delimiters according
	 * to {@link #shouldConvertToIndependentLineDelimiter(File)}.
	 *
	 * @param resourcePath
	 *            the relative path under <code>[plugin-root]/resources</code> of the resource to
	 *            be copied
	 * @param targetFolder
	 *            the absolute path of the folder under which the resource will be copied. Folder
	 *            and subfolders will be created if necessary.
	 * @return a file representing the copied resource
	 * @throws IOException
	 */
	public static File copyResource(String resourcePath, File targetFolder) throws IOException {
		File resDir = new File(getPluginDirectoryPath(), RESOURCES_DIR);
		File resourceFile = new File(resDir, resourcePath);
		File targetFile = new File(targetFolder, resourcePath);
		copyResource(resourceFile, targetFile);
		return targetFile;
	}

	/**
	 * Copy all the files under the directory specified by src to the directory
	 * specified by dest.  The src and dest directories must exist; child directories
	 * under dest will be created as required.  Existing files in dest will be
	 * overwritten.  Newlines will be converted according to
	 * {@link #shouldConvertToIndependentLineDelimiter(File)}.  Directories
	 * named "CVS" will be ignored.
	 * @param resourceFolderName the name of the source folder, relative to
	 * <code>[plugin-root]/resources</code>
	 * @param the absolute path of the destination folder
	 * @throws IOException
	 */
	public static void copyResources(String resourceFolderName, File destFolder) throws IOException {
		File resDir = new File(getPluginDirectoryPath(), RESOURCES_DIR);
		File resourceFolder = new File(resDir, resourceFolderName);
		copyResources(resourceFolder, destFolder);
	}

	private static void copyResources(File resourceFolder, File destFolder) throws IOException {
		if (resourceFolder == null) {
			return;
		}
		// Copy all resources in this folder
		String[] children = resourceFolder.list();
		if (null == children) {
			return;
		}
		// if there are any children, (recursively) copy them
		for (String child : children) {
			if ("CVS".equals(child)) {
				continue;
			}
			File childRes = new File(resourceFolder, child);
			File childDest = new File(destFolder, child);
			if (childRes.isDirectory()) {
				copyResources(childRes, childDest);
			}
			else {
				copyResource(childRes, childDest);
			}
		}
	}
	protected static String getPluginDirectoryPath() throws IOException {
		if (Platform.isRunning()) {
			URL platformURL = Platform.getBundle("org.eclipse.jdt.compiler.tool.tests").getEntry("/");
			return new File(FileLocator.toFileURL(platformURL).getFile()).getAbsolutePath();
		}
		return new File(System.getProperty("user.dir")).getAbsolutePath();
	}
	/**
	 * @return true if this file's end-of-line delimiters should be replaced with
	 * a platform-independent value, e.g. for compilation.
	 */
	public static boolean shouldConvertToIndependentLineDelimiter(File file) {
		return file.getName().endsWith(".java");
	}
	public static byte[] read(java.io.File file) throws java.io.IOException {
		return Files.readAllBytes(file.toPath());
	}

	public static String convertToIndependentLineDelimiter(String source) {
		if (source.indexOf('\n') == -1 && source.indexOf('\r') == -1) return source;
		StringBuffer buffer = new StringBuffer();
		for (int i = 0, length = source.length(); i < length; i++) {
			char car = source.charAt(i);
			if (car == '\r') {
				buffer.append('\n');
				if (i < length-1 && source.charAt(i+1) == '\n') {
					i++; // skip \n after \r
				}
			} else {
				buffer.append(car);
			}
		}
		return buffer.toString();
	}
}

Back to the top