Thu, 24 Mar 2011 16:14:30 -0700
6597678: JavaCompiler.getStandardFileManager always uses default charset not the one that user specifies
Reviewed-by: mcimadamore
1 /*
2 * Copyright (c) 2005, 2011, 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. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.tools.javac.api;
28 import java.io.File;
29 import java.io.IOException;
30 import java.nio.CharBuffer;
31 import java.util.*;
32 import java.util.concurrent.atomic.AtomicBoolean;
34 import javax.annotation.processing.Processor;
35 import javax.lang.model.element.Element;
36 import javax.lang.model.element.TypeElement;
37 import javax.lang.model.type.TypeMirror;
38 import javax.tools.*;
40 import com.sun.source.tree.*;
41 import com.sun.source.util.*;
42 import com.sun.tools.javac.code.*;
43 import com.sun.tools.javac.code.Symbol.*;
44 import com.sun.tools.javac.comp.*;
45 import com.sun.tools.javac.file.JavacFileManager;
46 import com.sun.tools.javac.main.*;
47 import com.sun.tools.javac.model.*;
48 import com.sun.tools.javac.parser.Parser;
49 import com.sun.tools.javac.parser.ParserFactory;
50 import com.sun.tools.javac.tree.*;
51 import com.sun.tools.javac.tree.JCTree.*;
52 import com.sun.tools.javac.util.*;
53 import com.sun.tools.javac.util.List;
54 import com.sun.tools.javac.main.JavaCompiler;
56 /**
57 * Provides access to functionality specific to the JDK Java Compiler, javac.
58 *
59 * <p><b>This is NOT part of any supported API.
60 * If you write code that depends on this, you do so at your own
61 * risk. This code and its internal interfaces are subject to change
62 * or deletion without notice.</b></p>
63 *
64 * @author Peter von der Ahé
65 * @author Jonathan Gibbons
66 */
67 public class JavacTaskImpl extends JavacTask {
68 private JavacTool tool;
69 private Main compilerMain;
70 private JavaCompiler compiler;
71 private Locale locale;
72 private String[] args;
73 private Context context;
74 private List<JavaFileObject> fileObjects;
75 private Map<JavaFileObject, JCCompilationUnit> notYetEntered;
76 private ListBuffer<Env<AttrContext>> genList;
77 private TaskListener taskListener;
78 private AtomicBoolean used = new AtomicBoolean();
79 private Iterable<? extends Processor> processors;
81 private Integer result = null;
83 JavacTaskImpl(JavacTool tool,
84 Main compilerMain,
85 String[] args,
86 Context context,
87 List<JavaFileObject> fileObjects) {
88 this.tool = tool;
89 this.compilerMain = compilerMain;
90 this.args = args;
91 this.context = context;
92 this.fileObjects = fileObjects;
93 setLocale(Locale.getDefault());
94 // null checks
95 compilerMain.getClass();
96 args.getClass();
97 context.getClass();
98 fileObjects.getClass();
99 }
101 JavacTaskImpl(JavacTool tool,
102 Main compilerMain,
103 Iterable<String> flags,
104 Context context,
105 Iterable<String> classes,
106 Iterable<? extends JavaFileObject> fileObjects) {
107 this(tool, compilerMain, toArray(flags, classes), context, toList(fileObjects));
108 }
110 static private String[] toArray(Iterable<String> flags, Iterable<String> classes) {
111 ListBuffer<String> result = new ListBuffer<String>();
112 if (flags != null)
113 for (String flag : flags)
114 result.append(flag);
115 if (classes != null)
116 for (String cls : classes)
117 result.append(cls);
118 return result.toArray(new String[result.length()]);
119 }
121 static private List<JavaFileObject> toList(Iterable<? extends JavaFileObject> fileObjects) {
122 if (fileObjects == null)
123 return List.nil();
124 ListBuffer<JavaFileObject> result = new ListBuffer<JavaFileObject>();
125 for (JavaFileObject fo : fileObjects)
126 result.append(fo);
127 return result.toList();
128 }
130 public Boolean call() {
131 if (!used.getAndSet(true)) {
132 initContext();
133 notYetEntered = new HashMap<JavaFileObject, JCCompilationUnit>();
134 compilerMain.setFatalErrors(true);
135 result = compilerMain.compile(args, context, fileObjects, processors);
136 cleanup();
137 return result == 0;
138 } else {
139 throw new IllegalStateException("multiple calls to method 'call'");
140 }
141 }
143 public void setProcessors(Iterable<? extends Processor> processors) {
144 processors.getClass(); // null check
145 // not mt-safe
146 if (used.get())
147 throw new IllegalStateException();
148 this.processors = processors;
149 }
151 public void setLocale(Locale locale) {
152 if (used.get())
153 throw new IllegalStateException();
154 this.locale = locale;
155 }
157 private void prepareCompiler() throws IOException {
158 if (used.getAndSet(true)) {
159 if (compiler == null)
160 throw new IllegalStateException();
161 } else {
162 initContext();
163 compilerMain.setOptions(Options.instance(context));
164 compilerMain.filenames = new ListBuffer<File>();
165 List<File> filenames = compilerMain.processArgs(CommandLine.parse(args));
166 if (!filenames.isEmpty())
167 throw new IllegalArgumentException("Malformed arguments " + filenames.toString(" "));
168 compiler = JavaCompiler.instance(context);
169 compiler.keepComments = true;
170 compiler.genEndPos = true;
171 // NOTE: this value will be updated after annotation processing
172 compiler.initProcessAnnotations(processors);
173 notYetEntered = new HashMap<JavaFileObject, JCCompilationUnit>();
174 for (JavaFileObject file: fileObjects)
175 notYetEntered.put(file, null);
176 genList = new ListBuffer<Env<AttrContext>>();
177 // endContext will be called when all classes have been generated
178 // TODO: should handle the case after each phase if errors have occurred
179 args = null;
180 }
181 }
183 private void initContext() {
184 context.put(JavacTaskImpl.class, this);
185 if (context.get(TaskListener.class) != null)
186 context.put(TaskListener.class, (TaskListener)null);
187 if (taskListener != null)
188 context.put(TaskListener.class, wrap(taskListener));
189 //initialize compiler's default locale
190 context.put(Locale.class, locale);
191 }
192 // where
193 private TaskListener wrap(final TaskListener tl) {
194 tl.getClass(); // null check
195 return new TaskListener() {
196 public void started(TaskEvent e) {
197 try {
198 tl.started(e);
199 } catch (Throwable t) {
200 throw new ClientCodeException(t);
201 }
202 }
204 public void finished(TaskEvent e) {
205 try {
206 tl.finished(e);
207 } catch (Throwable t) {
208 throw new ClientCodeException(t);
209 }
210 }
212 };
213 }
215 void cleanup() {
216 if (compiler != null)
217 compiler.close();
218 compiler = null;
219 compilerMain = null;
220 args = null;
221 context = null;
222 fileObjects = null;
223 notYetEntered = null;
224 }
226 /**
227 * Construct a JavaFileObject from the given file.
228 *
229 * <p><b>TODO: this method is useless here</b></p>
230 *
231 * @param file a file
232 * @return a JavaFileObject from the standard file manager.
233 */
234 public JavaFileObject asJavaFileObject(File file) {
235 JavacFileManager fm = (JavacFileManager)context.get(JavaFileManager.class);
236 return fm.getRegularFile(file);
237 }
239 public void setTaskListener(TaskListener taskListener) {
240 this.taskListener = taskListener;
241 }
243 /**
244 * Parse the specified files returning a list of abstract syntax trees.
245 *
246 * @throws java.io.IOException TODO
247 * @return a list of abstract syntax trees
248 */
249 public Iterable<? extends CompilationUnitTree> parse() throws IOException {
250 try {
251 prepareCompiler();
252 List<JCCompilationUnit> units = compiler.parseFiles(fileObjects);
253 for (JCCompilationUnit unit: units) {
254 JavaFileObject file = unit.getSourceFile();
255 if (notYetEntered.containsKey(file))
256 notYetEntered.put(file, unit);
257 }
258 return units;
259 }
260 finally {
261 parsed = true;
262 if (compiler != null && compiler.log != null)
263 compiler.log.flush();
264 }
265 }
267 private boolean parsed = false;
269 /**
270 * Translate all the abstract syntax trees to elements.
271 *
272 * @throws IOException TODO
273 * @return a list of elements corresponding to the top level
274 * classes in the abstract syntax trees
275 */
276 public Iterable<? extends TypeElement> enter() throws IOException {
277 return enter(null);
278 }
280 /**
281 * Translate the given abstract syntax trees to elements.
282 *
283 * @param trees a list of abstract syntax trees.
284 * @throws java.io.IOException TODO
285 * @return a list of elements corresponding to the top level
286 * classes in the abstract syntax trees
287 */
288 public Iterable<? extends TypeElement> enter(Iterable<? extends CompilationUnitTree> trees)
289 throws IOException
290 {
291 prepareCompiler();
293 ListBuffer<JCCompilationUnit> roots = null;
295 if (trees == null) {
296 // If there are still files which were specified to be compiled
297 // (i.e. in fileObjects) but which have not yet been entered,
298 // then we make sure they have been parsed and add them to the
299 // list to be entered.
300 if (notYetEntered.size() > 0) {
301 if (!parsed)
302 parse(); // TODO would be nice to specify files needed to be parsed
303 for (JavaFileObject file: fileObjects) {
304 JCCompilationUnit unit = notYetEntered.remove(file);
305 if (unit != null) {
306 if (roots == null)
307 roots = new ListBuffer<JCCompilationUnit>();
308 roots.append(unit);
309 }
310 }
311 notYetEntered.clear();
312 }
313 }
314 else {
315 for (CompilationUnitTree cu : trees) {
316 if (cu instanceof JCCompilationUnit) {
317 if (roots == null)
318 roots = new ListBuffer<JCCompilationUnit>();
319 roots.append((JCCompilationUnit)cu);
320 notYetEntered.remove(cu.getSourceFile());
321 }
322 else
323 throw new IllegalArgumentException(cu.toString());
324 }
325 }
327 if (roots == null)
328 return List.nil();
330 try {
331 List<JCCompilationUnit> units = compiler.enterTrees(roots.toList());
333 if (notYetEntered.isEmpty())
334 compiler = compiler.processAnnotations(units);
336 ListBuffer<TypeElement> elements = new ListBuffer<TypeElement>();
337 for (JCCompilationUnit unit : units) {
338 for (JCTree node : unit.defs) {
339 if (node.getTag() == JCTree.CLASSDEF) {
340 JCClassDecl cdef = (JCClassDecl) node;
341 if (cdef.sym != null) // maybe null if errors in anno processing
342 elements.append(cdef.sym);
343 }
344 }
345 }
346 return elements.toList();
347 }
348 finally {
349 compiler.log.flush();
350 }
351 }
353 /**
354 * Complete all analysis.
355 * @throws IOException TODO
356 */
357 @Override
358 public Iterable<? extends Element> analyze() throws IOException {
359 return analyze(null);
360 }
362 /**
363 * Complete all analysis on the given classes.
364 * This can be used to ensure that all compile time errors are reported.
365 * The classes must have previously been returned from {@link #enter}.
366 * If null is specified, all outstanding classes will be analyzed.
367 *
368 * @param classes a list of class elements
369 */
370 // This implementation requires that we open up privileges on JavaCompiler.
371 // An alternative implementation would be to move this code to JavaCompiler and
372 // wrap it here
373 public Iterable<? extends Element> analyze(Iterable<? extends TypeElement> classes) throws IOException {
374 enter(null); // ensure all classes have been entered
376 final ListBuffer<Element> results = new ListBuffer<Element>();
377 try {
378 if (classes == null) {
379 handleFlowResults(compiler.flow(compiler.attribute(compiler.todo)), results);
380 } else {
381 Filter f = new Filter() {
382 public void process(Env<AttrContext> env) {
383 handleFlowResults(compiler.flow(compiler.attribute(env)), results);
384 }
385 };
386 f.run(compiler.todo, classes);
387 }
388 } finally {
389 compiler.log.flush();
390 }
391 return results;
392 }
393 // where
394 private void handleFlowResults(Queue<Env<AttrContext>> queue, ListBuffer<Element> elems) {
395 for (Env<AttrContext> env: queue) {
396 switch (env.tree.getTag()) {
397 case JCTree.CLASSDEF:
398 JCClassDecl cdef = (JCClassDecl) env.tree;
399 if (cdef.sym != null)
400 elems.append(cdef.sym);
401 break;
402 case JCTree.TOPLEVEL:
403 JCCompilationUnit unit = (JCCompilationUnit) env.tree;
404 if (unit.packge != null)
405 elems.append(unit.packge);
406 break;
407 }
408 }
409 genList.addAll(queue);
410 }
413 /**
414 * Generate code.
415 * @throws IOException TODO
416 */
417 @Override
418 public Iterable<? extends JavaFileObject> generate() throws IOException {
419 return generate(null);
420 }
422 /**
423 * Generate code corresponding to the given classes.
424 * The classes must have previously been returned from {@link #enter}.
425 * If there are classes outstanding to be analyzed, that will be done before
426 * any classes are generated.
427 * If null is specified, code will be generated for all outstanding classes.
428 *
429 * @param classes a list of class elements
430 */
431 public Iterable<? extends JavaFileObject> generate(Iterable<? extends TypeElement> classes) throws IOException {
432 final ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();
433 try {
434 analyze(null); // ensure all classes have been parsed, entered, and analyzed
436 if (classes == null) {
437 compiler.generate(compiler.desugar(genList), results);
438 genList.clear();
439 }
440 else {
441 Filter f = new Filter() {
442 public void process(Env<AttrContext> env) {
443 compiler.generate(compiler.desugar(ListBuffer.of(env)), results);
444 }
445 };
446 f.run(genList, classes);
447 }
448 if (genList.isEmpty()) {
449 compiler.reportDeferredDiagnostics();
450 cleanup();
451 }
452 }
453 finally {
454 if (compiler != null)
455 compiler.log.flush();
456 }
457 return results;
458 }
460 public TypeMirror getTypeMirror(Iterable<? extends Tree> path) {
461 // TODO: Should complete attribution if necessary
462 Tree last = null;
463 for (Tree node : path)
464 last = node;
465 return ((JCTree)last).type;
466 }
468 public JavacElements getElements() {
469 if (context == null)
470 throw new IllegalStateException();
471 return JavacElements.instance(context);
472 }
474 public JavacTypes getTypes() {
475 if (context == null)
476 throw new IllegalStateException();
477 return JavacTypes.instance(context);
478 }
480 public Iterable<? extends Tree> pathFor(CompilationUnitTree unit, Tree node) {
481 return TreeInfo.pathFor((JCTree) node, (JCTree.JCCompilationUnit) unit).reverse();
482 }
484 abstract class Filter {
485 void run(Queue<Env<AttrContext>> list, Iterable<? extends TypeElement> classes) {
486 Set<TypeElement> set = new HashSet<TypeElement>();
487 for (TypeElement item: classes)
488 set.add(item);
490 ListBuffer<Env<AttrContext>> defer = ListBuffer.<Env<AttrContext>>lb();
491 while (list.peek() != null) {
492 Env<AttrContext> env = list.remove();
493 ClassSymbol csym = env.enclClass.sym;
494 if (csym != null && set.contains(csym.outermostClass()))
495 process(env);
496 else
497 defer = defer.append(env);
498 }
500 list.addAll(defer);
501 }
503 abstract void process(Env<AttrContext> env);
504 }
506 /**
507 * For internal use only. This method will be
508 * removed without warning.
509 */
510 public Context getContext() {
511 return context;
512 }
514 /**
515 * For internal use only. This method will be
516 * removed without warning.
517 */
518 public void updateContext(Context newContext) {
519 context = newContext;
520 }
522 /**
523 * For internal use only. This method will be
524 * removed without warning.
525 */
526 public Type parseType(String expr, TypeElement scope) {
527 if (expr == null || expr.equals(""))
528 throw new IllegalArgumentException();
529 compiler = JavaCompiler.instance(context);
530 JavaFileObject prev = compiler.log.useSource(null);
531 ParserFactory parserFactory = ParserFactory.instance(context);
532 Attr attr = Attr.instance(context);
533 try {
534 CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
535 Parser parser = parserFactory.newParser(buf, false, false, false);
536 JCTree tree = parser.parseType();
537 return attr.attribType(tree, (Symbol.TypeSymbol)scope);
538 } finally {
539 compiler.log.useSource(prev);
540 }
541 }
543 }