Thu, 21 Feb 2013 17:49:56 -0800
Merge
1 /*
2 * Copyright (c) 2005, 2013, 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.main.JavaCompiler;
48 import com.sun.tools.javac.model.*;
49 import com.sun.tools.javac.parser.Parser;
50 import com.sun.tools.javac.parser.ParserFactory;
51 import com.sun.tools.javac.tree.*;
52 import com.sun.tools.javac.tree.JCTree.*;
53 import com.sun.tools.javac.util.*;
54 import com.sun.tools.javac.util.List;
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 BasicJavacTask {
68 private Main compilerMain;
69 private JavaCompiler compiler;
70 private Locale locale;
71 private String[] args;
72 private String[] classNames;
73 private List<JavaFileObject> fileObjects;
74 private Map<JavaFileObject, JCCompilationUnit> notYetEntered;
75 private ListBuffer<Env<AttrContext>> genList;
76 private final AtomicBoolean used = new AtomicBoolean();
77 private Iterable<? extends Processor> processors;
79 private Main.Result result = null;
81 JavacTaskImpl(Main compilerMain,
82 String[] args,
83 String[] classNames,
84 Context context,
85 List<JavaFileObject> fileObjects) {
86 super(null, false);
87 this.compilerMain = compilerMain;
88 this.args = args;
89 this.classNames = classNames;
90 this.context = context;
91 this.fileObjects = fileObjects;
92 setLocale(Locale.getDefault());
93 // null checks
94 compilerMain.getClass();
95 args.getClass();
96 fileObjects.getClass();
97 }
99 JavacTaskImpl(Main compilerMain,
100 Iterable<String> args,
101 Context context,
102 Iterable<String> classes,
103 Iterable<? extends JavaFileObject> fileObjects) {
104 this(compilerMain, toArray(args), toArray(classes), context, toList(fileObjects));
105 }
107 static private String[] toArray(Iterable<String> iter) {
108 ListBuffer<String> result = new ListBuffer<String>();
109 if (iter != null)
110 for (String s : iter)
111 result.append(s);
112 return result.toArray(new String[result.length()]);
113 }
115 static private List<JavaFileObject> toList(Iterable<? extends JavaFileObject> fileObjects) {
116 if (fileObjects == null)
117 return List.nil();
118 ListBuffer<JavaFileObject> result = new ListBuffer<JavaFileObject>();
119 for (JavaFileObject fo : fileObjects)
120 result.append(fo);
121 return result.toList();
122 }
124 public Main.Result doCall() {
125 if (!used.getAndSet(true)) {
126 initContext();
127 notYetEntered = new HashMap<JavaFileObject, JCCompilationUnit>();
128 compilerMain.setAPIMode(true);
129 result = compilerMain.compile(args, classNames, context, fileObjects, processors);
130 cleanup();
131 return result;
132 } else {
133 throw new IllegalStateException("multiple calls to method 'call'");
134 }
135 }
137 public Boolean call() {
138 return doCall().isOK();
139 }
141 public void setProcessors(Iterable<? extends Processor> processors) {
142 processors.getClass(); // null check
143 // not mt-safe
144 if (used.get())
145 throw new IllegalStateException();
146 this.processors = processors;
147 }
149 public void setLocale(Locale locale) {
150 if (used.get())
151 throw new IllegalStateException();
152 this.locale = locale;
153 }
155 private void prepareCompiler() throws IOException {
156 if (used.getAndSet(true)) {
157 if (compiler == null)
158 throw new IllegalStateException();
159 } else {
160 initContext();
161 compilerMain.log = Log.instance(context);
162 compilerMain.setOptions(Options.instance(context));
163 compilerMain.filenames = new LinkedHashSet<File>();
164 Collection<File> filenames = compilerMain.processArgs(CommandLine.parse(args), classNames);
165 if (filenames != null && !filenames.isEmpty())
166 throw new IllegalArgumentException("Malformed arguments " + toString(filenames, " "));
167 compiler = JavaCompiler.instance(context);
168 compiler.keepComments = true;
169 compiler.genEndPos = true;
170 // NOTE: this value will be updated after annotation processing
171 compiler.initProcessAnnotations(processors);
172 notYetEntered = new HashMap<JavaFileObject, JCCompilationUnit>();
173 for (JavaFileObject file: fileObjects)
174 notYetEntered.put(file, null);
175 genList = new ListBuffer<Env<AttrContext>>();
176 // endContext will be called when all classes have been generated
177 // TODO: should handle the case after each phase if errors have occurred
178 args = null;
179 classNames = null;
180 }
181 }
183 <T> String toString(Iterable<T> items, String sep) {
184 String currSep = "";
185 StringBuilder sb = new StringBuilder();
186 for (T item: items) {
187 sb.append(currSep);
188 sb.append(item.toString());
189 currSep = sep;
190 }
191 return sb.toString();
192 }
194 private void initContext() {
195 context.put(JavacTask.class, this);
196 //initialize compiler's default locale
197 context.put(Locale.class, locale);
198 }
200 void cleanup() {
201 if (compiler != null)
202 compiler.close();
203 compiler = null;
204 compilerMain = null;
205 args = null;
206 classNames = null;
207 context = null;
208 fileObjects = null;
209 notYetEntered = null;
210 }
212 /**
213 * Construct a JavaFileObject from the given file.
214 *
215 * <p><b>TODO: this method is useless here</b></p>
216 *
217 * @param file a file
218 * @return a JavaFileObject from the standard file manager.
219 */
220 public JavaFileObject asJavaFileObject(File file) {
221 JavacFileManager fm = (JavacFileManager)context.get(JavaFileManager.class);
222 return fm.getRegularFile(file);
223 }
225 /**
226 * Parse the specified files returning a list of abstract syntax trees.
227 *
228 * @throws java.io.IOException TODO
229 * @return a list of abstract syntax trees
230 */
231 public Iterable<? extends CompilationUnitTree> parse() throws IOException {
232 try {
233 prepareCompiler();
234 List<JCCompilationUnit> units = compiler.parseFiles(fileObjects);
235 for (JCCompilationUnit unit: units) {
236 JavaFileObject file = unit.getSourceFile();
237 if (notYetEntered.containsKey(file))
238 notYetEntered.put(file, unit);
239 }
240 return units;
241 }
242 finally {
243 parsed = true;
244 if (compiler != null && compiler.log != null)
245 compiler.log.flush();
246 }
247 }
249 private boolean parsed = false;
251 /**
252 * Translate all the abstract syntax trees to elements.
253 *
254 * @throws IOException TODO
255 * @return a list of elements corresponding to the top level
256 * classes in the abstract syntax trees
257 */
258 public Iterable<? extends TypeElement> enter() throws IOException {
259 return enter(null);
260 }
262 /**
263 * Translate the given abstract syntax trees to elements.
264 *
265 * @param trees a list of abstract syntax trees.
266 * @throws java.io.IOException TODO
267 * @return a list of elements corresponding to the top level
268 * classes in the abstract syntax trees
269 */
270 public Iterable<? extends TypeElement> enter(Iterable<? extends CompilationUnitTree> trees)
271 throws IOException
272 {
273 if (trees == null && notYetEntered != null && notYetEntered.isEmpty())
274 return List.nil();
276 prepareCompiler();
278 ListBuffer<JCCompilationUnit> roots = null;
280 if (trees == null) {
281 // If there are still files which were specified to be compiled
282 // (i.e. in fileObjects) but which have not yet been entered,
283 // then we make sure they have been parsed and add them to the
284 // list to be entered.
285 if (notYetEntered.size() > 0) {
286 if (!parsed)
287 parse(); // TODO would be nice to specify files needed to be parsed
288 for (JavaFileObject file: fileObjects) {
289 JCCompilationUnit unit = notYetEntered.remove(file);
290 if (unit != null) {
291 if (roots == null)
292 roots = new ListBuffer<JCCompilationUnit>();
293 roots.append(unit);
294 }
295 }
296 notYetEntered.clear();
297 }
298 }
299 else {
300 for (CompilationUnitTree cu : trees) {
301 if (cu instanceof JCCompilationUnit) {
302 if (roots == null)
303 roots = new ListBuffer<JCCompilationUnit>();
304 roots.append((JCCompilationUnit)cu);
305 notYetEntered.remove(cu.getSourceFile());
306 }
307 else
308 throw new IllegalArgumentException(cu.toString());
309 }
310 }
312 if (roots == null)
313 return List.nil();
315 try {
316 List<JCCompilationUnit> units = compiler.enterTrees(roots.toList());
318 if (notYetEntered.isEmpty())
319 compiler = compiler.processAnnotations(units);
321 ListBuffer<TypeElement> elements = new ListBuffer<TypeElement>();
322 for (JCCompilationUnit unit : units) {
323 for (JCTree node : unit.defs) {
324 if (node.hasTag(JCTree.Tag.CLASSDEF)) {
325 JCClassDecl cdef = (JCClassDecl) node;
326 if (cdef.sym != null) // maybe null if errors in anno processing
327 elements.append(cdef.sym);
328 }
329 }
330 }
331 return elements.toList();
332 }
333 finally {
334 compiler.log.flush();
335 }
336 }
338 /**
339 * Complete all analysis.
340 * @throws IOException TODO
341 */
342 @Override
343 public Iterable<? extends Element> analyze() throws IOException {
344 return analyze(null);
345 }
347 /**
348 * Complete all analysis on the given classes.
349 * This can be used to ensure that all compile time errors are reported.
350 * The classes must have previously been returned from {@link #enter}.
351 * If null is specified, all outstanding classes will be analyzed.
352 *
353 * @param classes a list of class elements
354 */
355 // This implementation requires that we open up privileges on JavaCompiler.
356 // An alternative implementation would be to move this code to JavaCompiler and
357 // wrap it here
358 public Iterable<? extends Element> analyze(Iterable<? extends TypeElement> classes) throws IOException {
359 enter(null); // ensure all classes have been entered
361 final ListBuffer<Element> results = new ListBuffer<Element>();
362 try {
363 if (classes == null) {
364 handleFlowResults(compiler.flow(compiler.attribute(compiler.todo)), results);
365 } else {
366 Filter f = new Filter() {
367 public void process(Env<AttrContext> env) {
368 handleFlowResults(compiler.flow(compiler.attribute(env)), results);
369 }
370 };
371 f.run(compiler.todo, classes);
372 }
373 } finally {
374 compiler.log.flush();
375 }
376 return results;
377 }
378 // where
379 private void handleFlowResults(Queue<Env<AttrContext>> queue, ListBuffer<Element> elems) {
380 for (Env<AttrContext> env: queue) {
381 switch (env.tree.getTag()) {
382 case CLASSDEF:
383 JCClassDecl cdef = (JCClassDecl) env.tree;
384 if (cdef.sym != null)
385 elems.append(cdef.sym);
386 break;
387 case TOPLEVEL:
388 JCCompilationUnit unit = (JCCompilationUnit) env.tree;
389 if (unit.packge != null)
390 elems.append(unit.packge);
391 break;
392 }
393 }
394 genList.addAll(queue);
395 }
398 /**
399 * Generate code.
400 * @throws IOException TODO
401 */
402 @Override
403 public Iterable<? extends JavaFileObject> generate() throws IOException {
404 return generate(null);
405 }
407 /**
408 * Generate code corresponding to the given classes.
409 * The classes must have previously been returned from {@link #enter}.
410 * If there are classes outstanding to be analyzed, that will be done before
411 * any classes are generated.
412 * If null is specified, code will be generated for all outstanding classes.
413 *
414 * @param classes a list of class elements
415 */
416 public Iterable<? extends JavaFileObject> generate(Iterable<? extends TypeElement> classes) throws IOException {
417 final ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();
418 try {
419 analyze(null); // ensure all classes have been parsed, entered, and analyzed
421 if (classes == null) {
422 compiler.generate(compiler.desugar(genList), results);
423 genList.clear();
424 }
425 else {
426 Filter f = new Filter() {
427 public void process(Env<AttrContext> env) {
428 compiler.generate(compiler.desugar(ListBuffer.of(env)), results);
429 }
430 };
431 f.run(genList, classes);
432 }
433 if (genList.isEmpty()) {
434 compiler.reportDeferredDiagnostics();
435 cleanup();
436 }
437 }
438 finally {
439 if (compiler != null)
440 compiler.log.flush();
441 }
442 return results;
443 }
445 public TypeMirror getTypeMirror(Iterable<? extends Tree> path) {
446 // TODO: Should complete attribution if necessary
447 Tree last = null;
448 for (Tree node : path)
449 last = node;
450 return ((JCTree)last).type;
451 }
453 public JavacElements getElements() {
454 if (context == null)
455 throw new IllegalStateException();
456 return JavacElements.instance(context);
457 }
459 public JavacTypes getTypes() {
460 if (context == null)
461 throw new IllegalStateException();
462 return JavacTypes.instance(context);
463 }
465 public Iterable<? extends Tree> pathFor(CompilationUnitTree unit, Tree node) {
466 return TreeInfo.pathFor((JCTree) node, (JCTree.JCCompilationUnit) unit).reverse();
467 }
469 abstract class Filter {
470 void run(Queue<Env<AttrContext>> list, Iterable<? extends TypeElement> classes) {
471 Set<TypeElement> set = new HashSet<TypeElement>();
472 for (TypeElement item: classes)
473 set.add(item);
475 ListBuffer<Env<AttrContext>> defer = ListBuffer.<Env<AttrContext>>lb();
476 while (list.peek() != null) {
477 Env<AttrContext> env = list.remove();
478 ClassSymbol csym = env.enclClass.sym;
479 if (csym != null && set.contains(csym.outermostClass()))
480 process(env);
481 else
482 defer = defer.append(env);
483 }
485 list.addAll(defer);
486 }
488 abstract void process(Env<AttrContext> env);
489 }
491 /**
492 * For internal use only. This method will be
493 * removed without warning.
494 */
495 public Type parseType(String expr, TypeElement scope) {
496 if (expr == null || expr.equals(""))
497 throw new IllegalArgumentException();
498 compiler = JavaCompiler.instance(context);
499 JavaFileObject prev = compiler.log.useSource(null);
500 ParserFactory parserFactory = ParserFactory.instance(context);
501 Attr attr = Attr.instance(context);
502 try {
503 CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
504 Parser parser = parserFactory.newParser(buf, false, false, false);
505 JCTree tree = parser.parseType();
506 return attr.attribType(tree, (Symbol.TypeSymbol)scope);
507 } finally {
508 compiler.log.useSource(prev);
509 }
510 }
512 }