Debian Codegraph @

org.eclipse.jdt.core.tests.model/workspace/Converter15/src/test0247/EclipseCompiler.java

raw
1 /*******************************************************************************
2 * Copyright (c) 2006 IBM Corporation and others.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 * IBM Corporation - initial API and implementation
10 *******************************************************************************/
11 package org.eclipse.jdt.internal.compiler.tool;
12
13 import java.io.BufferedOutputStream;
14 import java.io.File;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.io.OutputStream;
18 import java.io.OutputStreamWriter;
19 import java.io.PrintWriter;
20 import java.io.Writer;
21 import java.nio.charset.Charset;
22 import java.util.ArrayList;
23 import java.util.Collections;
24 import java.util.EnumSet;
25 import java.util.HashMap;
26 import java.util.Iterator;
27 import java.util.Locale;
28 import java.util.Map;
29 import java.util.Set;
30
31 import javax.annotation.processing.Processor;
32 import javax.lang.model.SourceVersion;
33 import javax.tools.DiagnosticListener;
34 import javax.tools.Diagnostic;
35 import javax.tools.JavaCompiler;
36 import javax.tools.JavaFileManager;
37 import javax.tools.JavaFileObject;
38 import javax.tools.StandardJavaFileManager;
39 import javax.tools.StandardLocation;
40
41 import org.eclipse.jdt.core.compiler.CategorizedProblem;
42 import org.eclipse.jdt.core.compiler.CharOperation;
43 import org.eclipse.jdt.core.compiler.InvalidInputException;
44 import org.eclipse.jdt.internal.compiler.ClassFile;
45 import org.eclipse.jdt.internal.compiler.CompilationResult;
46 import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
47 import org.eclipse.jdt.internal.compiler.IProblemFactory;
48 import org.eclipse.jdt.internal.compiler.batch.CompilationUnit;
49 import org.eclipse.jdt.internal.compiler.batch.FileSystem;
50 import org.eclipse.jdt.internal.compiler.batch.Main;
51 import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
52 import org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
53 import org.eclipse.jdt.internal.compiler.problem.AbortCompilationUnit;
54 import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
55 import org.eclipse.jdt.internal.compiler.problem.ProblemSeverities;
56 import org.eclipse.jdt.internal.compiler.util.Messages;
57 import org.eclipse.jdt.internal.compiler.util.SuffixConstants;
58
59 /**
60 * Implementation of a batch compiler that supports the jsr199
61 */
62 public class EclipseCompiler extends Main implements JavaCompiler {
63
64 private HashMap<CompilationUnit, JavaFileObject> javaFileObjectMap;
65 private static Set<SourceVersion> SupportedSourceVersions;
66 static {
67 // Eclipse compiler supports all possible versions from version 0 to
68 // version 6
69 // we don't care about the order
70 EnumSet<SourceVersion> enumSet = EnumSet.range(SourceVersion.RELEASE_0, SourceVersion.RELEASE_6);
71 // we don't want anybody to modify this list
72 SupportedSourceVersions = Collections.unmodifiableSet(enumSet);
73 }
74
75 Iterable<? extends JavaFileObject> compilationUnits;
76 public DiagnosticListener<? super JavaFileObject> diagnosticListener;
77 public JavaFileManager fileManager;
78 protected Processor[] processors;
79
80 public EclipseCompiler(PrintWriter out, PrintWriter err, boolean systemExitWhenFinished) {
81 super(out, err, systemExitWhenFinished);
82 }
83
84 public EclipseCompiler() {
85 super(null, null, false);
86 }
87
88 public boolean call() {
89 try {
90 if (this.proceed) {
91 this.globalProblemsCount = 0;
92 this.globalErrorsCount = 0;
93 this.globalWarningsCount = 0;
94 this.globalTasksCount = 0;
95 this.lineCount = 0;
96 this.exportedClassFilesCounter = 0;
97 // request compilation
98 performCompilation();
99 }
100 try {
101 if (this.fileManager != null) {
102 this.fileManager.flush();
103 }
104 } catch (IOException e) {
105 // ignore
106 }
107 } catch (InvalidInputException e) {
108 this.logger.logException(e);
109 if (this.systemExitWhenFinished) {
110 this.logger.flush();
111 this.logger.close();
112 System.exit(-1);
113 }
114 return false;
115 } catch(IllegalArgumentException e) {
116 throw e;
117 } catch (RuntimeException e) { // internal compiler failure
118 this.logger.logException(e);
119 return false;
120 } finally {
121 this.logger.flush();
122 this.logger.close();
123 }
124 if (this.globalErrorsCount == 0)
125 return true;
126 return false;
127 }
128
129 public CompilationUnit[] getCompilationUnits() {
130 ArrayList<CompilationUnit> units = new ArrayList<CompilationUnit>();
131 for (final JavaFileObject javaFileObject : this.compilationUnits) {
132 if (javaFileObject.getKind() != JavaFileObject.Kind.SOURCE) {
133 throw new IllegalArgumentException();
134 }
135 String name = javaFileObject.getName();
136 name = name.replace('\\', '/');
137 CompilationUnit compilationUnit = new CompilationUnit(null,
138 name,
139 null) {
140
141 public char[] getContents() {
142 try {
143 return javaFileObject.getCharContent(true).toString().toCharArray();
144 } catch(IOException e) {
145 e.printStackTrace();
146 throw new AbortCompilationUnit(null, e, null);
147 }
148 }
149 };
150 units.add(compilationUnit);
151 this.javaFileObjectMap.put(compilationUnit, javaFileObject);
152 }
153 CompilationUnit[] result = new CompilationUnit[units.size()];
154 units.toArray(result);
155 return result;
156 }
157 /*
158 * Low-level API performing the actual compilation
159 */
160 public IErrorHandlingPolicy getHandlingPolicy() {
161 // passes the initial set of files to the batch oracle (to avoid finding more than once the same units when case insensitive match)
162 return new IErrorHandlingPolicy() {
163 public boolean proceedOnErrors() {
164 return false; // stop if there are some errors
165 }
166 public boolean stopOnFirstError() {
167 return false;
168 }
169 };
170 }
171
172 public IProblemFactory getProblemFactory() {
173 return new DefaultProblemFactory() {
174 @Override
175 public CategorizedProblem createProblem(
176 final char[] originatingFileName,
177 final int problemId,
178 final String[] problemArguments,
179 final String[] messageArguments,
180 final int severity,
181 final int startPosition,
182 final int endPosition,
183 final int lineNumber,
184 final int columnNumber) {
185
186 DiagnosticListener<? super JavaFileObject> diagnosticListener = EclipseCompiler.this.diagnosticListener;
187 if (diagnosticListener != null) {
188 diagnosticListener.report(new Diagnostic<JavaFileObject>() {
189 public String getCode() {
190 return Integer.toString(problemId);
191 }
192 public long getColumnNumber() {
193 return columnNumber;
194 }
195 public long getEndPosition() {
196 return endPosition;
197 }
198 public Kind getKind() {
199 if ((severity & ProblemSeverities.Error) != 0) {
200 return Diagnostic.Kind.ERROR;
201 }
202 if ((severity & ProblemSeverities.Optional) != 0) {
203 return Diagnostic.Kind.WARNING;
204 }
205 if ((severity & ProblemSeverities.Warning) != 0) {
206 return Diagnostic.Kind.MANDATORY_WARNING;
207 }
208 return Diagnostic.Kind.OTHER;
209 }
210 public long getLineNumber() {
211 return lineNumber;
212 }
213 public String getMessage(Locale locale) {
214 setLocale(locale);
215 return getLocalizedMessage(problemId, problemArguments);
216 }
217 public long getPosition() {
218 return startPosition;
219 }
220 public JavaFileObject getSource() {
221 try {
222 if (EclipseCompiler.this.fileManager.hasLocation(StandardLocation.SOURCE_PATH)) {
223 return EclipseCompiler.this.fileManager.getJavaFileForInput(
224 StandardLocation.SOURCE_PATH,
225 new String(originatingFileName),
226 JavaFileObject.Kind.SOURCE);
227 }
228 } catch (IOException e) {
229 // ignore
230 }
231 return null;
232 }
233 public long getStartPosition() {
234 return startPosition;
235 }
236 });
237 }
238 return super.createProblem(originatingFileName, problemId, problemArguments, messageArguments, severity, startPosition, endPosition, lineNumber, columnNumber);
239 }
240 };
241 }
242
243 /*
244 * (non-Javadoc)
245 *
246 * @see javax.tools.Tool#getSourceVersions()
247 */
248 public Set<SourceVersion> getSourceVersions() {
249 return SupportedSourceVersions;
250 }
251 /*
252 * (non-Javadoc)
253 *
254 * @see javax.tools.JavaCompiler#getStandardFileManager(javax.tools.DiagnosticListener,
255 * java.util.Locale, java.nio.charset.Charset)
256 */
257 public StandardJavaFileManager getStandardFileManager(DiagnosticListener<? super JavaFileObject> diagnosticListener,
258 Locale locale,
259 Charset charset) {
260 this.diagnosticListener = diagnosticListener;
261 return new EclipseFileManager(this, locale, charset);
262 }
263 /*
264 * (non-Javadoc)
265 *
266 * @see javax.tools.JavaCompiler#getTask(java.io.Writer,
267 * javax.tools.JavaFileManager, javax.tools.DiagnosticListener,
268 * java.lang.Iterable, java.lang.Iterable, java.lang.Iterable)
269 */
270 @SuppressWarnings("unchecked")
271 public CompilationTask getTask(Writer out,
272 JavaFileManager fileManager,
273 DiagnosticListener<? super JavaFileObject> diagnosticListener,
274 Iterable<String> options,
275 Iterable<String> classes,
276 Iterable<? extends JavaFileObject> compilationUnits) {
277
278 for ()
279 PrintWriter writerOut = null;
280 PrintWriter writerErr = null;
281 if (out == null) {
282 writerOut = new PrintWriter(System.out);
283 writerErr = new PrintWriter(System.err);
284 } else {
285 writerOut = new PrintWriter(out);
286 writerErr = new PrintWriter(out);
287 }
288 this.compilationUnits = compilationUnits;
289 this.diagnosticListener = diagnosticListener;
290 if (fileManager != null) {
291 this.fileManager = fileManager;
292 } else {
293 this.fileManager = this.getStandardFileManager(diagnosticListener, null, null);
294 }
295
296 initialize(writerOut, writerErr, false);
297 this.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6);
298 this.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6);
299 this.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
300
301 // TODO FIXME (olivier) REMOVE BEFORE 3.3 once the APT1.6 IS WORKING FINE
302 for (String option : options ) {
303 if ("-processorpath".equals(option) //$NON-NLS-1$
304 || ("-processor".equals(option))) { //$NON-NLS-1$
305 this.options.put(CompilerOptions.OPTION_Process_Annotations, CompilerOptions.ENABLED);
306 }
307 }
308
309 ArrayList<String> allOptions = new ArrayList<String>();
310 if (options != null) {
311 for (Iterator<String> iterator = options.iterator(); iterator.hasNext(); ) {
312 this.fileManager.handleOption(iterator.next(), iterator);
313 }
314 for (String option : options) {
315 allOptions.add(option);
316 }
317 }
318 if (compilationUnits != null) {
319 for (JavaFileObject javaFileObject : compilationUnits) {
320 allOptions.add(new File(javaFileObject.toUri()).getAbsolutePath());
321 }
322 }
323
324 final String[] optionsToProcess = new String[allOptions.size()];
325 allOptions.toArray(optionsToProcess);
326 try {
327 this.configure(optionsToProcess);
328 } catch (InvalidInputException e) {
329 throw new RuntimeException(e);
330 }
331
332 if (this.fileManager instanceof StandardJavaFileManager) {
333 StandardJavaFileManager javaFileManager = (StandardJavaFileManager) this.fileManager;
334
335 Iterable<? extends File> location = javaFileManager.getLocation(StandardLocation.CLASS_OUTPUT);
336 if (location != null) {
337 this.setDestinationPath(location.iterator().next().getAbsolutePath());
338 }
339 }
340
341 return new CompilationTask() {
342 private boolean hasRun = false;
343 public Boolean call() {
344 // set up compiler with passed options
345 if (this.hasRun) {
346 throw new IllegalStateException("This task has already been run"); //$NON-NLS-1$
347 }
348 Boolean value = EclipseCompiler.this.call() ? Boolean.TRUE : Boolean.FALSE;
349 this.hasRun = true;
350 return value;
351 }
352 public void setLocale(Locale locale) {
353 EclipseCompiler.this.setLocale(locale);
354 }
355 public void setProcessors(Iterable<? extends Processor> processors) {
356 ArrayList<Processor> temp = new ArrayList<Processor>();
357 for (Processor processor : processors) {
358 temp.add(processor);
359 }
360 Processor[] processors2 = new Processor[temp.size()];
361 temp.toArray(processors2);
362 EclipseCompiler.this.processors = processors2;
363 }
364 };
365 }
366
367 @Override
368 @SuppressWarnings("unchecked")
369 protected void initialize(PrintWriter outWriter, PrintWriter errWriter, boolean systemExit, Map customDefaultOptions) {
370 super.initialize(outWriter, errWriter, systemExit, customDefaultOptions);
371 this.javaFileObjectMap = new HashMap<CompilationUnit, JavaFileObject>();
372 }
373
374 @Override
375 protected void initializeAnnotationProcessorManager() {
376 super.initializeAnnotationProcessorManager();
377 if (this.batchCompiler.annotationProcessorManager != null &&
378 this.processors != null) {
379 this.batchCompiler.annotationProcessorManager.setProcessors(this.processors);
380 } else if (this.processors != null) {
381 throw new UnsupportedOperationException("Cannot handle annotation processing"); //$NON-NLS-1$
382 }
383 }
384
385 /*
386 * (non-Javadoc)
387 *
388 * @see javax.tools.OptionChecker#isSupportedOption(java.lang.String)
389 */
390 public int isSupportedOption(String option) {
391 return Options.processOptions(option);
392 }
393
394 // Dump classfiles onto disk for all compilation units that where successful
395 // and do not carry a -d none spec, either directly or inherited from Main.
396 public void outputClassFiles(CompilationResult unitResult) {
397 if (!((unitResult == null) || (unitResult.hasErrors() && !this.proceedOnError))) {
398 ClassFile[] classFiles = unitResult.getClassFiles();
399 boolean generateClasspathStructure = this.fileManager.hasLocation(StandardLocation.CLASS_OUTPUT);
400 String currentDestinationPath = this.destinationPath;
401 File outputLocation = null;
402 if (currentDestinationPath != null) {
403 outputLocation = new File(currentDestinationPath);
404 outputLocation.mkdirs();
405 }
406 for (int i = 0, fileCount = classFiles.length; i < fileCount; i++) {
407 // retrieve the key and the corresponding classfile
408 ClassFile classFile = classFiles[i];
409 char[] filename = classFile.fileName();
410 int length = filename.length;
411 char[] relativeName = new char[length + 6];
412 System.arraycopy(filename, 0, relativeName, 0, length);
413 System.arraycopy(SuffixConstants.SUFFIX_class, 0, relativeName, length, 6);
414 CharOperation.replace(relativeName, '/', File.separatorChar);
415 String relativeStringName = new String(relativeName);
416 if (this.compilerOptions.verbose) {
417 EclipseCompiler.this.out.println(
418 Messages.bind(
419 Messages.compilation_write,
420 new String[] {
421 String.valueOf(this.exportedClassFilesCounter+1),
422 relativeStringName
423 }));
424 }
425 try {
426 JavaFileObject javaFileForOutput =
427 this.fileManager.getJavaFileForOutput(
428 StandardLocation.CLASS_OUTPUT,
429 new String(filename),
430 JavaFileObject.Kind.CLASS,
431 this.javaFileObjectMap.get(unitResult.compilationUnit));
432
433 if (generateClasspathStructure) {
434 if (currentDestinationPath != null) {
435 int index = CharOperation.lastIndexOf(File.separatorChar, relativeName);
436 if (index != -1) {
437 File currentFolder = new File(currentDestinationPath, relativeStringName.substring(0, index));
438 currentFolder.mkdirs();
439 }
440 } else {
441 // create the subfolfers is necessary
442 // need a way to retrieve the folders to create
443 String path = javaFileForOutput.toUri().getPath();
444 int index = path.lastIndexOf('/');
445 if (index != -1) {
446 File file = new File(path.substring(0, index));
447 file.mkdirs();
448 }
449 }
450 }
451
452 OutputStream openOutputStream = javaFileForOutput.openOutputStream();
453 BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(openOutputStream);
454 bufferedOutputStream.write(classFile.header, 0, classFile.headerOffset);
455 bufferedOutputStream.write(classFile.contents, 0, classFile.contentsOffset);
456 bufferedOutputStream.flush();
457 bufferedOutputStream.close();
458 } catch (IOException e) {
459 this.logger.logNoClassFileCreated(currentDestinationPath, relativeStringName, e);
460 }
461 LookupEnvironment env = EclipseCompiler.this.batchCompiler.lookupEnvironment;
462 if (classFile.isShared) env.classFilePool.release(classFile);
463 this.logger.logClassFile(
464 generateClasspathStructure,
465 currentDestinationPath,
466 relativeStringName);
467 this.exportedClassFilesCounter++;
468 }
469 }
470 }
471
472 /*
473 * (non-Javadoc)
474 *
475 * @see javax.tools.Tool#run(java.io.InputStream, java.io.OutputStream,
476 * java.io.OutputStream, java.lang.String[])
477 */
478 public int run(InputStream in, OutputStream out, OutputStream err, String... arguments) {
479 boolean succeed = new Main(new PrintWriter(new OutputStreamWriter(out)), new PrintWriter(new OutputStreamWriter(err)), true).compile(arguments);
480 return succeed ? 0 : -1;
481 }
482
483 @Override
484 @SuppressWarnings("unchecked")
485 protected void setPaths(ArrayList bootclasspaths,
486 String sourcepathClasspathArg,
487 ArrayList sourcepathClasspaths,
488 ArrayList classpaths,
489 ArrayList extdirsClasspaths,
490 ArrayList endorsedDirClasspaths,
491 String customEncoding) throws InvalidInputException {
492
493 ArrayList<FileSystem.Classpath> fileSystemClasspaths = new ArrayList<FileSystem.Classpath>();
494 EclipseFileManager javaFileManager = null;
495 StandardJavaFileManager standardJavaFileManager = null;
496 if (this.fileManager instanceof EclipseFileManager) {
497 javaFileManager = (EclipseFileManager) this.fileManager;
498 }
499 if (this.fileManager instanceof StandardJavaFileManager) {
500 standardJavaFileManager = (StandardJavaFileManager) this.fileManager;
501 }
502
503 if (javaFileManager != null) {
504 if ((javaFileManager.flags & EclipseFileManager.HAS_ENDORSED_DIRS) == 0
505 && (javaFileManager.flags & EclipseFileManager.HAS_BOOTCLASSPATH) != 0) {
506 fileSystemClasspaths.addAll((ArrayList<? extends FileSystem.Classpath>) this.handleEndorseddirs(null));
507 }
508 }
509 Iterable<? extends File> location = null;
510 if (standardJavaFileManager != null) {
511 location = standardJavaFileManager.getLocation(StandardLocation.PLATFORM_CLASS_PATH);
512 }
513 if (location != null) {
514 for (File file : location) {
515 fileSystemClasspaths.add(FileSystem.getClasspath(
516 file.getAbsolutePath(),
517 null,
518 null));
519 }
520 }
521 if (javaFileManager != null) {
522 if ((javaFileManager.flags & EclipseFileManager.HAS_EXT_DIRS) == 0
523 && (javaFileManager.flags & EclipseFileManager.HAS_BOOTCLASSPATH) != 0) {
524 fileSystemClasspaths.addAll((ArrayList<? extends FileSystem.Classpath>) this.handleExtdirs(null));
525 }
526 }
527 if (standardJavaFileManager != null) {
528 location = standardJavaFileManager.getLocation(StandardLocation.SOURCE_PATH);
529 } else {
530 location = null;
531 }
532 if (location != null) {
533 for (File file : location) {
534 fileSystemClasspaths.add(FileSystem.getClasspath(
535 file.getAbsolutePath(),
536 null,
537 null));
538 }
539 }
540 if (standardJavaFileManager != null) {
541 location = standardJavaFileManager.getLocation(StandardLocation.CLASS_PATH);
542 } else {
543 location = null;
544 }
545 if (location != null) {
546 for (File file : location) {
547 fileSystemClasspaths.add(FileSystem.getClasspath(
548 file.getAbsolutePath(),
549 null,
550 null));
551 }
552 }
553 if (this.checkedClasspaths == null) {
554 fileSystemClasspaths.addAll((ArrayList<? extends FileSystem.Classpath>) this.handleBootclasspath(null, null));
555 fileSystemClasspaths.addAll((ArrayList<? extends FileSystem.Classpath>) this.handleClasspath(null, null));
556 }
557 final int size = fileSystemClasspaths.size();
558 if (size != 0) {
559 this.checkedClasspaths = new FileSystem.Classpath[size];
560 int i = 0;
561 for (FileSystem.Classpath classpath : fileSystemClasspaths) {
562 this.checkedClasspaths[i++] = classpath;
563 }
564 }
565 }
566 }