Mon, 21 Jan 2013 01:27:42 -0500
8004182: Add support for profiles in javac
Reviewed-by: mcimadamore
1 /*
2 * Copyright (c) 2005, 2012, 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 Boolean call() {
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.isOK();
132 } else {
133 throw new IllegalStateException("multiple calls to method 'call'");
134 }
135 }
137 public void setProcessors(Iterable<? extends Processor> processors) {
138 processors.getClass(); // null check
139 // not mt-safe
140 if (used.get())
141 throw new IllegalStateException();
142 this.processors = processors;
143 }
145 public void setLocale(Locale locale) {
146 if (used.get())
147 throw new IllegalStateException();
148 this.locale = locale;
149 }
151 private void prepareCompiler() throws IOException {
152 if (used.getAndSet(true)) {
153 if (compiler == null)
154 throw new IllegalStateException();
155 } else {
156 initContext();
157 compilerMain.log = Log.instance(context);
158 compilerMain.setOptions(Options.instance(context));
159 compilerMain.filenames = new LinkedHashSet<File>();
160 Collection<File> filenames = compilerMain.processArgs(CommandLine.parse(args), classNames);
161 if (filenames != null && !filenames.isEmpty())
162 throw new IllegalArgumentException("Malformed arguments " + toString(filenames, " "));
163 compiler = JavaCompiler.instance(context);
164 compiler.keepComments = true;
165 compiler.genEndPos = true;
166 // NOTE: this value will be updated after annotation processing
167 compiler.initProcessAnnotations(processors);
168 notYetEntered = new HashMap<JavaFileObject, JCCompilationUnit>();
169 for (JavaFileObject file: fileObjects)
170 notYetEntered.put(file, null);
171 genList = new ListBuffer<Env<AttrContext>>();
172 // endContext will be called when all classes have been generated
173 // TODO: should handle the case after each phase if errors have occurred
174 args = null;
175 classNames = null;
176 }
177 }
179 <T> String toString(Iterable<T> items, String sep) {
180 String currSep = "";
181 StringBuilder sb = new StringBuilder();
182 for (T item: items) {
183 sb.append(currSep);
184 sb.append(item.toString());
185 currSep = sep;
186 }
187 return sb.toString();
188 }
190 private void initContext() {
191 context.put(JavacTask.class, this);
192 //initialize compiler's default locale
193 context.put(Locale.class, locale);
194 }
196 void cleanup() {
197 if (compiler != null)
198 compiler.close();
199 compiler = null;
200 compilerMain = null;
201 args = null;
202 classNames = null;
203 context = null;
204 fileObjects = null;
205 notYetEntered = null;
206 }
208 /**
209 * Construct a JavaFileObject from the given file.
210 *
211 * <p><b>TODO: this method is useless here</b></p>
212 *
213 * @param file a file
214 * @return a JavaFileObject from the standard file manager.
215 */
216 public JavaFileObject asJavaFileObject(File file) {
217 JavacFileManager fm = (JavacFileManager)context.get(JavaFileManager.class);
218 return fm.getRegularFile(file);
219 }
221 /**
222 * Parse the specified files returning a list of abstract syntax trees.
223 *
224 * @throws java.io.IOException TODO
225 * @return a list of abstract syntax trees
226 */
227 public Iterable<? extends CompilationUnitTree> parse() throws IOException {
228 try {
229 prepareCompiler();
230 List<JCCompilationUnit> units = compiler.parseFiles(fileObjects);
231 for (JCCompilationUnit unit: units) {
232 JavaFileObject file = unit.getSourceFile();
233 if (notYetEntered.containsKey(file))
234 notYetEntered.put(file, unit);
235 }
236 return units;
237 }
238 finally {
239 parsed = true;
240 if (compiler != null && compiler.log != null)
241 compiler.log.flush();
242 }
243 }
245 private boolean parsed = false;
247 /**
248 * Translate all the abstract syntax trees to elements.
249 *
250 * @throws IOException TODO
251 * @return a list of elements corresponding to the top level
252 * classes in the abstract syntax trees
253 */
254 public Iterable<? extends TypeElement> enter() throws IOException {
255 return enter(null);
256 }
258 /**
259 * Translate the given abstract syntax trees to elements.
260 *
261 * @param trees a list of abstract syntax trees.
262 * @throws java.io.IOException TODO
263 * @return a list of elements corresponding to the top level
264 * classes in the abstract syntax trees
265 */
266 public Iterable<? extends TypeElement> enter(Iterable<? extends CompilationUnitTree> trees)
267 throws IOException
268 {
269 if (trees == null && notYetEntered != null && notYetEntered.isEmpty())
270 return List.nil();
272 prepareCompiler();
274 ListBuffer<JCCompilationUnit> roots = null;
276 if (trees == null) {
277 // If there are still files which were specified to be compiled
278 // (i.e. in fileObjects) but which have not yet been entered,
279 // then we make sure they have been parsed and add them to the
280 // list to be entered.
281 if (notYetEntered.size() > 0) {
282 if (!parsed)
283 parse(); // TODO would be nice to specify files needed to be parsed
284 for (JavaFileObject file: fileObjects) {
285 JCCompilationUnit unit = notYetEntered.remove(file);
286 if (unit != null) {
287 if (roots == null)
288 roots = new ListBuffer<JCCompilationUnit>();
289 roots.append(unit);
290 }
291 }
292 notYetEntered.clear();
293 }
294 }
295 else {
296 for (CompilationUnitTree cu : trees) {
297 if (cu instanceof JCCompilationUnit) {
298 if (roots == null)
299 roots = new ListBuffer<JCCompilationUnit>();
300 roots.append((JCCompilationUnit)cu);
301 notYetEntered.remove(cu.getSourceFile());
302 }
303 else
304 throw new IllegalArgumentException(cu.toString());
305 }
306 }
308 if (roots == null)
309 return List.nil();
311 try {
312 List<JCCompilationUnit> units = compiler.enterTrees(roots.toList());
314 if (notYetEntered.isEmpty())
315 compiler = compiler.processAnnotations(units);
317 ListBuffer<TypeElement> elements = new ListBuffer<TypeElement>();
318 for (JCCompilationUnit unit : units) {
319 for (JCTree node : unit.defs) {
320 if (node.hasTag(JCTree.Tag.CLASSDEF)) {
321 JCClassDecl cdef = (JCClassDecl) node;
322 if (cdef.sym != null) // maybe null if errors in anno processing
323 elements.append(cdef.sym);
324 }
325 }
326 }
327 return elements.toList();
328 }
329 finally {
330 compiler.log.flush();
331 }
332 }
334 /**
335 * Complete all analysis.
336 * @throws IOException TODO
337 */
338 @Override
339 public Iterable<? extends Element> analyze() throws IOException {
340 return analyze(null);
341 }
343 /**
344 * Complete all analysis on the given classes.
345 * This can be used to ensure that all compile time errors are reported.
346 * The classes must have previously been returned from {@link #enter}.
347 * If null is specified, all outstanding classes will be analyzed.
348 *
349 * @param classes a list of class elements
350 */
351 // This implementation requires that we open up privileges on JavaCompiler.
352 // An alternative implementation would be to move this code to JavaCompiler and
353 // wrap it here
354 public Iterable<? extends Element> analyze(Iterable<? extends TypeElement> classes) throws IOException {
355 enter(null); // ensure all classes have been entered
357 final ListBuffer<Element> results = new ListBuffer<Element>();
358 try {
359 if (classes == null) {
360 handleFlowResults(compiler.flow(compiler.attribute(compiler.todo)), results);
361 } else {
362 Filter f = new Filter() {
363 public void process(Env<AttrContext> env) {
364 handleFlowResults(compiler.flow(compiler.attribute(env)), results);
365 }
366 };
367 f.run(compiler.todo, classes);
368 }
369 } finally {
370 compiler.log.flush();
371 }
372 return results;
373 }
374 // where
375 private void handleFlowResults(Queue<Env<AttrContext>> queue, ListBuffer<Element> elems) {
376 for (Env<AttrContext> env: queue) {
377 switch (env.tree.getTag()) {
378 case CLASSDEF:
379 JCClassDecl cdef = (JCClassDecl) env.tree;
380 if (cdef.sym != null)
381 elems.append(cdef.sym);
382 break;
383 case TOPLEVEL:
384 JCCompilationUnit unit = (JCCompilationUnit) env.tree;
385 if (unit.packge != null)
386 elems.append(unit.packge);
387 break;
388 }
389 }
390 genList.addAll(queue);
391 }
394 /**
395 * Generate code.
396 * @throws IOException TODO
397 */
398 @Override
399 public Iterable<? extends JavaFileObject> generate() throws IOException {
400 return generate(null);
401 }
403 /**
404 * Generate code corresponding to the given classes.
405 * The classes must have previously been returned from {@link #enter}.
406 * If there are classes outstanding to be analyzed, that will be done before
407 * any classes are generated.
408 * If null is specified, code will be generated for all outstanding classes.
409 *
410 * @param classes a list of class elements
411 */
412 public Iterable<? extends JavaFileObject> generate(Iterable<? extends TypeElement> classes) throws IOException {
413 final ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();
414 try {
415 analyze(null); // ensure all classes have been parsed, entered, and analyzed
417 if (classes == null) {
418 compiler.generate(compiler.desugar(genList), results);
419 genList.clear();
420 }
421 else {
422 Filter f = new Filter() {
423 public void process(Env<AttrContext> env) {
424 compiler.generate(compiler.desugar(ListBuffer.of(env)), results);
425 }
426 };
427 f.run(genList, classes);
428 }
429 if (genList.isEmpty()) {
430 compiler.reportDeferredDiagnostics();
431 cleanup();
432 }
433 }
434 finally {
435 if (compiler != null)
436 compiler.log.flush();
437 }
438 return results;
439 }
441 public TypeMirror getTypeMirror(Iterable<? extends Tree> path) {
442 // TODO: Should complete attribution if necessary
443 Tree last = null;
444 for (Tree node : path)
445 last = node;
446 return ((JCTree)last).type;
447 }
449 public JavacElements getElements() {
450 if (context == null)
451 throw new IllegalStateException();
452 return JavacElements.instance(context);
453 }
455 public JavacTypes getTypes() {
456 if (context == null)
457 throw new IllegalStateException();
458 return JavacTypes.instance(context);
459 }
461 public Iterable<? extends Tree> pathFor(CompilationUnitTree unit, Tree node) {
462 return TreeInfo.pathFor((JCTree) node, (JCTree.JCCompilationUnit) unit).reverse();
463 }
465 abstract class Filter {
466 void run(Queue<Env<AttrContext>> list, Iterable<? extends TypeElement> classes) {
467 Set<TypeElement> set = new HashSet<TypeElement>();
468 for (TypeElement item: classes)
469 set.add(item);
471 ListBuffer<Env<AttrContext>> defer = ListBuffer.<Env<AttrContext>>lb();
472 while (list.peek() != null) {
473 Env<AttrContext> env = list.remove();
474 ClassSymbol csym = env.enclClass.sym;
475 if (csym != null && set.contains(csym.outermostClass()))
476 process(env);
477 else
478 defer = defer.append(env);
479 }
481 list.addAll(defer);
482 }
484 abstract void process(Env<AttrContext> env);
485 }
487 /**
488 * For internal use only. This method will be
489 * removed without warning.
490 */
491 public Type parseType(String expr, TypeElement scope) {
492 if (expr == null || expr.equals(""))
493 throw new IllegalArgumentException();
494 compiler = JavaCompiler.instance(context);
495 JavaFileObject prev = compiler.log.useSource(null);
496 ParserFactory parserFactory = ParserFactory.instance(context);
497 Attr attr = Attr.instance(context);
498 try {
499 CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
500 Parser parser = parserFactory.newParser(buf, false, false, false);
501 JCTree tree = parser.parseType();
502 return attr.attribType(tree, (Symbol.TypeSymbol)scope);
503 } finally {
504 compiler.log.useSource(prev);
505 }
506 }
508 }