Fri, 02 Sep 2011 17:35:56 +0100
7086261: javac doesn't report error as expected, it only reports ClientCodeWrapper$DiagnosticSourceUnwrapper
Summary: Missing override for toString() in ClientCodeUnwrapper.DiagnosticSourceUnwrapper
Reviewed-by: jjg
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 ClientCodeWrapper ccw;
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(Main compilerMain,
84 String[] args,
85 Context context,
86 List<JavaFileObject> fileObjects) {
87 this.ccw = ClientCodeWrapper.instance(context);
88 this.compilerMain = compilerMain;
89 this.args = args;
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> flags,
101 Context context,
102 Iterable<String> classes,
103 Iterable<? extends JavaFileObject> fileObjects) {
104 this(compilerMain, toArray(flags, classes), context, toList(fileObjects));
105 }
107 static private String[] toArray(Iterable<String> flags, Iterable<String> classes) {
108 ListBuffer<String> result = new ListBuffer<String>();
109 if (flags != null)
110 for (String flag : flags)
111 result.append(flag);
112 if (classes != null)
113 for (String cls : classes)
114 result.append(cls);
115 return result.toArray(new String[result.length()]);
116 }
118 static private List<JavaFileObject> toList(Iterable<? extends JavaFileObject> fileObjects) {
119 if (fileObjects == null)
120 return List.nil();
121 ListBuffer<JavaFileObject> result = new ListBuffer<JavaFileObject>();
122 for (JavaFileObject fo : fileObjects)
123 result.append(fo);
124 return result.toList();
125 }
127 public Boolean call() {
128 if (!used.getAndSet(true)) {
129 initContext();
130 notYetEntered = new HashMap<JavaFileObject, JCCompilationUnit>();
131 compilerMain.setAPIMode(true);
132 result = compilerMain.compile(args, context, fileObjects, processors);
133 cleanup();
134 return result == 0;
135 } else {
136 throw new IllegalStateException("multiple calls to method 'call'");
137 }
138 }
140 public void setProcessors(Iterable<? extends Processor> processors) {
141 processors.getClass(); // null check
142 // not mt-safe
143 if (used.get())
144 throw new IllegalStateException();
145 this.processors = processors;
146 }
148 public void setLocale(Locale locale) {
149 if (used.get())
150 throw new IllegalStateException();
151 this.locale = locale;
152 }
154 private void prepareCompiler() throws IOException {
155 if (used.getAndSet(true)) {
156 if (compiler == null)
157 throw new IllegalStateException();
158 } else {
159 initContext();
160 compilerMain.setOptions(Options.instance(context));
161 compilerMain.filenames = new LinkedHashSet<File>();
162 Collection<File> filenames = compilerMain.processArgs(CommandLine.parse(args));
163 if (!filenames.isEmpty())
164 throw new IllegalArgumentException("Malformed arguments " + toString(filenames, " "));
165 compiler = JavaCompiler.instance(context);
166 compiler.keepComments = true;
167 compiler.genEndPos = true;
168 // NOTE: this value will be updated after annotation processing
169 compiler.initProcessAnnotations(processors);
170 notYetEntered = new HashMap<JavaFileObject, JCCompilationUnit>();
171 for (JavaFileObject file: fileObjects)
172 notYetEntered.put(file, null);
173 genList = new ListBuffer<Env<AttrContext>>();
174 // endContext will be called when all classes have been generated
175 // TODO: should handle the case after each phase if errors have occurred
176 args = null;
177 }
178 }
180 <T> String toString(Iterable<T> items, String sep) {
181 String currSep = "";
182 StringBuilder sb = new StringBuilder();
183 for (T item: items) {
184 sb.append(currSep);
185 sb.append(item.toString());
186 currSep = sep;
187 }
188 return sb.toString();
189 }
191 private void initContext() {
192 context.put(JavacTaskImpl.class, this);
193 if (context.get(TaskListener.class) != null)
194 context.put(TaskListener.class, (TaskListener)null);
195 if (taskListener != null)
196 context.put(TaskListener.class, ccw.wrap(taskListener));
197 //initialize compiler's default locale
198 context.put(Locale.class, locale);
199 }
201 void cleanup() {
202 if (compiler != null)
203 compiler.close();
204 compiler = null;
205 compilerMain = null;
206 args = 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 public void setTaskListener(TaskListener taskListener) {
226 this.taskListener = taskListener;
227 }
229 /**
230 * Parse the specified files returning a list of abstract syntax trees.
231 *
232 * @throws java.io.IOException TODO
233 * @return a list of abstract syntax trees
234 */
235 public Iterable<? extends CompilationUnitTree> parse() throws IOException {
236 try {
237 prepareCompiler();
238 List<JCCompilationUnit> units = compiler.parseFiles(fileObjects);
239 for (JCCompilationUnit unit: units) {
240 JavaFileObject file = unit.getSourceFile();
241 if (notYetEntered.containsKey(file))
242 notYetEntered.put(file, unit);
243 }
244 return units;
245 }
246 finally {
247 parsed = true;
248 if (compiler != null && compiler.log != null)
249 compiler.log.flush();
250 }
251 }
253 private boolean parsed = false;
255 /**
256 * Translate all the abstract syntax trees to elements.
257 *
258 * @throws IOException TODO
259 * @return a list of elements corresponding to the top level
260 * classes in the abstract syntax trees
261 */
262 public Iterable<? extends TypeElement> enter() throws IOException {
263 return enter(null);
264 }
266 /**
267 * Translate the given abstract syntax trees to elements.
268 *
269 * @param trees a list of abstract syntax trees.
270 * @throws java.io.IOException TODO
271 * @return a list of elements corresponding to the top level
272 * classes in the abstract syntax trees
273 */
274 public Iterable<? extends TypeElement> enter(Iterable<? extends CompilationUnitTree> trees)
275 throws IOException
276 {
277 prepareCompiler();
279 ListBuffer<JCCompilationUnit> roots = null;
281 if (trees == null) {
282 // If there are still files which were specified to be compiled
283 // (i.e. in fileObjects) but which have not yet been entered,
284 // then we make sure they have been parsed and add them to the
285 // list to be entered.
286 if (notYetEntered.size() > 0) {
287 if (!parsed)
288 parse(); // TODO would be nice to specify files needed to be parsed
289 for (JavaFileObject file: fileObjects) {
290 JCCompilationUnit unit = notYetEntered.remove(file);
291 if (unit != null) {
292 if (roots == null)
293 roots = new ListBuffer<JCCompilationUnit>();
294 roots.append(unit);
295 }
296 }
297 notYetEntered.clear();
298 }
299 }
300 else {
301 for (CompilationUnitTree cu : trees) {
302 if (cu instanceof JCCompilationUnit) {
303 if (roots == null)
304 roots = new ListBuffer<JCCompilationUnit>();
305 roots.append((JCCompilationUnit)cu);
306 notYetEntered.remove(cu.getSourceFile());
307 }
308 else
309 throw new IllegalArgumentException(cu.toString());
310 }
311 }
313 if (roots == null)
314 return List.nil();
316 try {
317 List<JCCompilationUnit> units = compiler.enterTrees(roots.toList());
319 if (notYetEntered.isEmpty())
320 compiler = compiler.processAnnotations(units);
322 ListBuffer<TypeElement> elements = new ListBuffer<TypeElement>();
323 for (JCCompilationUnit unit : units) {
324 for (JCTree node : unit.defs) {
325 if (node.getTag() == JCTree.CLASSDEF) {
326 JCClassDecl cdef = (JCClassDecl) node;
327 if (cdef.sym != null) // maybe null if errors in anno processing
328 elements.append(cdef.sym);
329 }
330 }
331 }
332 return elements.toList();
333 }
334 finally {
335 compiler.log.flush();
336 }
337 }
339 /**
340 * Complete all analysis.
341 * @throws IOException TODO
342 */
343 @Override
344 public Iterable<? extends Element> analyze() throws IOException {
345 return analyze(null);
346 }
348 /**
349 * Complete all analysis on the given classes.
350 * This can be used to ensure that all compile time errors are reported.
351 * The classes must have previously been returned from {@link #enter}.
352 * If null is specified, all outstanding classes will be analyzed.
353 *
354 * @param classes a list of class elements
355 */
356 // This implementation requires that we open up privileges on JavaCompiler.
357 // An alternative implementation would be to move this code to JavaCompiler and
358 // wrap it here
359 public Iterable<? extends Element> analyze(Iterable<? extends TypeElement> classes) throws IOException {
360 enter(null); // ensure all classes have been entered
362 final ListBuffer<Element> results = new ListBuffer<Element>();
363 try {
364 if (classes == null) {
365 handleFlowResults(compiler.flow(compiler.attribute(compiler.todo)), results);
366 } else {
367 Filter f = new Filter() {
368 public void process(Env<AttrContext> env) {
369 handleFlowResults(compiler.flow(compiler.attribute(env)), results);
370 }
371 };
372 f.run(compiler.todo, classes);
373 }
374 } finally {
375 compiler.log.flush();
376 }
377 return results;
378 }
379 // where
380 private void handleFlowResults(Queue<Env<AttrContext>> queue, ListBuffer<Element> elems) {
381 for (Env<AttrContext> env: queue) {
382 switch (env.tree.getTag()) {
383 case JCTree.CLASSDEF:
384 JCClassDecl cdef = (JCClassDecl) env.tree;
385 if (cdef.sym != null)
386 elems.append(cdef.sym);
387 break;
388 case JCTree.TOPLEVEL:
389 JCCompilationUnit unit = (JCCompilationUnit) env.tree;
390 if (unit.packge != null)
391 elems.append(unit.packge);
392 break;
393 }
394 }
395 genList.addAll(queue);
396 }
399 /**
400 * Generate code.
401 * @throws IOException TODO
402 */
403 @Override
404 public Iterable<? extends JavaFileObject> generate() throws IOException {
405 return generate(null);
406 }
408 /**
409 * Generate code corresponding to the given classes.
410 * The classes must have previously been returned from {@link #enter}.
411 * If there are classes outstanding to be analyzed, that will be done before
412 * any classes are generated.
413 * If null is specified, code will be generated for all outstanding classes.
414 *
415 * @param classes a list of class elements
416 */
417 public Iterable<? extends JavaFileObject> generate(Iterable<? extends TypeElement> classes) throws IOException {
418 final ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();
419 try {
420 analyze(null); // ensure all classes have been parsed, entered, and analyzed
422 if (classes == null) {
423 compiler.generate(compiler.desugar(genList), results);
424 genList.clear();
425 }
426 else {
427 Filter f = new Filter() {
428 public void process(Env<AttrContext> env) {
429 compiler.generate(compiler.desugar(ListBuffer.of(env)), results);
430 }
431 };
432 f.run(genList, classes);
433 }
434 if (genList.isEmpty()) {
435 compiler.reportDeferredDiagnostics();
436 cleanup();
437 }
438 }
439 finally {
440 if (compiler != null)
441 compiler.log.flush();
442 }
443 return results;
444 }
446 public TypeMirror getTypeMirror(Iterable<? extends Tree> path) {
447 // TODO: Should complete attribution if necessary
448 Tree last = null;
449 for (Tree node : path)
450 last = node;
451 return ((JCTree)last).type;
452 }
454 public JavacElements getElements() {
455 if (context == null)
456 throw new IllegalStateException();
457 return JavacElements.instance(context);
458 }
460 public JavacTypes getTypes() {
461 if (context == null)
462 throw new IllegalStateException();
463 return JavacTypes.instance(context);
464 }
466 public Iterable<? extends Tree> pathFor(CompilationUnitTree unit, Tree node) {
467 return TreeInfo.pathFor((JCTree) node, (JCTree.JCCompilationUnit) unit).reverse();
468 }
470 abstract class Filter {
471 void run(Queue<Env<AttrContext>> list, Iterable<? extends TypeElement> classes) {
472 Set<TypeElement> set = new HashSet<TypeElement>();
473 for (TypeElement item: classes)
474 set.add(item);
476 ListBuffer<Env<AttrContext>> defer = ListBuffer.<Env<AttrContext>>lb();
477 while (list.peek() != null) {
478 Env<AttrContext> env = list.remove();
479 ClassSymbol csym = env.enclClass.sym;
480 if (csym != null && set.contains(csym.outermostClass()))
481 process(env);
482 else
483 defer = defer.append(env);
484 }
486 list.addAll(defer);
487 }
489 abstract void process(Env<AttrContext> env);
490 }
492 /**
493 * For internal use only. This method will be
494 * removed without warning.
495 */
496 public Context getContext() {
497 return context;
498 }
500 /**
501 * For internal use only. This method will be
502 * removed without warning.
503 */
504 public void updateContext(Context newContext) {
505 context = newContext;
506 }
508 /**
509 * For internal use only. This method will be
510 * removed without warning.
511 */
512 public Type parseType(String expr, TypeElement scope) {
513 if (expr == null || expr.equals(""))
514 throw new IllegalArgumentException();
515 compiler = JavaCompiler.instance(context);
516 JavaFileObject prev = compiler.log.useSource(null);
517 ParserFactory parserFactory = ParserFactory.instance(context);
518 Attr attr = Attr.instance(context);
519 try {
520 CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
521 Parser parser = parserFactory.newParser(buf, false, false, false);
522 JCTree tree = parser.parseType();
523 return attr.attribType(tree, (Symbol.TypeSymbol)scope);
524 } finally {
525 compiler.log.useSource(prev);
526 }
527 }
529 }