Tue, 12 Feb 2013 19:25:09 +0000
8007464: Add graph inference support
Summary: Add support for more aggressive type-inference scheme
Reviewed-by: jjg
1 /*
2 * Copyright (c) 1999, 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.util;
28 import java.io.*;
29 import java.util.Arrays;
30 import java.util.EnumSet;
31 import java.util.HashSet;
32 import java.util.Queue;
33 import java.util.Set;
34 import javax.tools.DiagnosticListener;
35 import javax.tools.JavaFileObject;
37 import com.sun.tools.javac.api.DiagnosticFormatter;
38 import com.sun.tools.javac.main.Main;
39 import com.sun.tools.javac.main.Option;
40 import com.sun.tools.javac.tree.EndPosTable;
41 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
42 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
44 import static com.sun.tools.javac.main.Option.*;
46 /** A class for error logs. Reports errors and warnings, and
47 * keeps track of error numbers and positions.
48 *
49 * <p><b>This is NOT part of any supported API.
50 * If you write code that depends on this, you do so at your own risk.
51 * This code and its internal interfaces are subject to change or
52 * deletion without notice.</b>
53 */
54 public class Log extends AbstractLog {
55 /** The context key for the log. */
56 public static final Context.Key<Log> logKey
57 = new Context.Key<Log>();
59 /** The context key for the output PrintWriter. */
60 public static final Context.Key<PrintWriter> outKey =
61 new Context.Key<PrintWriter>();
63 /* TODO: Should unify this with prefix handling in JCDiagnostic.Factory. */
64 public enum PrefixKind {
65 JAVAC("javac."),
66 COMPILER_MISC("compiler.misc.");
67 PrefixKind(String v) {
68 value = v;
69 }
70 public String key(String k) {
71 return value + k;
72 }
73 final String value;
74 }
76 /**
77 * DiagnosticHandler's provide the initial handling for diagnostics.
78 * When a diagnostic handler is created and has been initialized, it
79 * should install itself as the current diagnostic handler. When a
80 * client has finished using a handler, the client should call
81 * {@code log.removeDiagnosticHandler();}
82 *
83 * Note that javax.tools.DiagnosticListener (if set) is called later in the
84 * diagnostic pipeline.
85 */
86 public static abstract class DiagnosticHandler {
87 /**
88 * The previously installed diagnostic handler.
89 */
90 protected DiagnosticHandler prev;
92 /**
93 * Install this diagnostic handler as the current one,
94 * recording the previous one.
95 */
96 protected void install(Log log) {
97 prev = log.diagnosticHandler;
98 log.diagnosticHandler = this;
99 }
101 /**
102 * Handle a diagnostic.
103 */
104 public abstract void report(JCDiagnostic diag);
105 }
107 /**
108 * A DiagnosticHandler that discards all diagnostics.
109 */
110 public static class DiscardDiagnosticHandler extends DiagnosticHandler {
111 public DiscardDiagnosticHandler(Log log) {
112 install(log);
113 }
115 public void report(JCDiagnostic diag) { }
116 }
118 /**
119 * A DiagnosticHandler that can defer some or all diagnostics,
120 * by buffering them for later examination and/or reporting.
121 * If a diagnostic is not deferred, or is subsequently reported
122 * with reportAllDiagnostics(), it will be reported to the previously
123 * active diagnostic handler.
124 */
125 public static class DeferredDiagnosticHandler extends DiagnosticHandler {
126 private Queue<JCDiagnostic> deferred = ListBuffer.lb();
127 private final Filter<JCDiagnostic> filter;
129 public DeferredDiagnosticHandler(Log log) {
130 this(log, null);
131 }
133 public DeferredDiagnosticHandler(Log log, Filter<JCDiagnostic> filter) {
134 this.filter = filter;
135 install(log);
136 }
138 public void report(JCDiagnostic diag) {
139 if (filter == null || filter.accepts(diag))
140 deferred.add(diag);
141 else
142 prev.report(diag);
143 }
145 public Queue<JCDiagnostic> getDiagnostics() {
146 return deferred;
147 }
149 /** Report all deferred diagnostics. */
150 public void reportDeferredDiagnostics() {
151 reportDeferredDiagnostics(EnumSet.allOf(JCDiagnostic.Kind.class));
152 }
154 /** Report selected deferred diagnostics. */
155 public void reportDeferredDiagnostics(Set<JCDiagnostic.Kind> kinds) {
156 JCDiagnostic d;
157 while ((d = deferred.poll()) != null) {
158 if (kinds.contains(d.getKind()))
159 prev.report(d);
160 }
161 deferred = null; // prevent accidental ongoing use
162 }
163 }
165 public enum WriterKind { NOTICE, WARNING, ERROR };
167 protected PrintWriter errWriter;
169 protected PrintWriter warnWriter;
171 protected PrintWriter noticeWriter;
173 /** The maximum number of errors/warnings that are reported.
174 */
175 protected int MaxErrors;
176 protected int MaxWarnings;
178 /** Switch: prompt user on each error.
179 */
180 public boolean promptOnError;
182 /** Switch: emit warning messages.
183 */
184 public boolean emitWarnings;
186 /** Switch: suppress note messages.
187 */
188 public boolean suppressNotes;
190 /** Print stack trace on errors?
191 */
192 public boolean dumpOnError;
194 /** Print multiple errors for same source locations.
195 */
196 public boolean multipleErrors;
198 /**
199 * Diagnostic listener, if provided through programmatic
200 * interface to javac (JSR 199).
201 */
202 protected DiagnosticListener<? super JavaFileObject> diagListener;
204 /**
205 * Formatter for diagnostics.
206 */
207 private DiagnosticFormatter<JCDiagnostic> diagFormatter;
209 /**
210 * Keys for expected diagnostics.
211 */
212 public Set<String> expectDiagKeys;
214 /**
215 * JavacMessages object used for localization.
216 */
217 private JavacMessages messages;
219 /**
220 * Handler for initial dispatch of diagnostics.
221 */
222 private DiagnosticHandler diagnosticHandler;
224 /** Construct a log with given I/O redirections.
225 */
226 protected Log(Context context, PrintWriter errWriter, PrintWriter warnWriter, PrintWriter noticeWriter) {
227 super(JCDiagnostic.Factory.instance(context));
228 context.put(logKey, this);
229 this.errWriter = errWriter;
230 this.warnWriter = warnWriter;
231 this.noticeWriter = noticeWriter;
233 @SuppressWarnings("unchecked") // FIXME
234 DiagnosticListener<? super JavaFileObject> dl =
235 context.get(DiagnosticListener.class);
236 this.diagListener = dl;
238 diagnosticHandler = new DefaultDiagnosticHandler();
240 messages = JavacMessages.instance(context);
241 messages.add(Main.javacBundleName);
243 final Options options = Options.instance(context);
244 initOptions(options);
245 options.addListener(new Runnable() {
246 public void run() {
247 initOptions(options);
248 }
249 });
250 }
251 // where
252 private void initOptions(Options options) {
253 this.dumpOnError = options.isSet(DOE);
254 this.promptOnError = options.isSet(PROMPT);
255 this.emitWarnings = options.isUnset(XLINT_CUSTOM, "none");
256 this.suppressNotes = options.isSet("suppressNotes");
257 this.MaxErrors = getIntOption(options, XMAXERRS, getDefaultMaxErrors());
258 this.MaxWarnings = getIntOption(options, XMAXWARNS, getDefaultMaxWarnings());
260 boolean rawDiagnostics = options.isSet("rawDiagnostics");
261 this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(options) :
262 new BasicDiagnosticFormatter(options, messages);
264 String ek = options.get("expectKeys");
265 if (ek != null)
266 expectDiagKeys = new HashSet<String>(Arrays.asList(ek.split(", *")));
267 }
269 private int getIntOption(Options options, Option option, int defaultValue) {
270 String s = options.get(option);
271 try {
272 if (s != null) {
273 int n = Integer.parseInt(s);
274 return (n <= 0 ? Integer.MAX_VALUE : n);
275 }
276 } catch (NumberFormatException e) {
277 // silently ignore ill-formed numbers
278 }
279 return defaultValue;
280 }
282 /** Default value for -Xmaxerrs.
283 */
284 protected int getDefaultMaxErrors() {
285 return 100;
286 }
288 /** Default value for -Xmaxwarns.
289 */
290 protected int getDefaultMaxWarnings() {
291 return 100;
292 }
294 /** The default writer for diagnostics
295 */
296 static PrintWriter defaultWriter(Context context) {
297 PrintWriter result = context.get(outKey);
298 if (result == null)
299 context.put(outKey, result = new PrintWriter(System.err));
300 return result;
301 }
303 /** Construct a log with default settings.
304 */
305 protected Log(Context context) {
306 this(context, defaultWriter(context));
307 }
309 /** Construct a log with all output redirected.
310 */
311 protected Log(Context context, PrintWriter defaultWriter) {
312 this(context, defaultWriter, defaultWriter, defaultWriter);
313 }
315 /** Get the Log instance for this context. */
316 public static Log instance(Context context) {
317 Log instance = context.get(logKey);
318 if (instance == null)
319 instance = new Log(context);
320 return instance;
321 }
323 /** The number of errors encountered so far.
324 */
325 public int nerrors = 0;
327 /** The number of warnings encountered so far.
328 */
329 public int nwarnings = 0;
331 /** A set of all errors generated so far. This is used to avoid printing an
332 * error message more than once. For each error, a pair consisting of the
333 * source file name and source code position of the error is added to the set.
334 */
335 private Set<Pair<JavaFileObject, Integer>> recorded = new HashSet<Pair<JavaFileObject,Integer>>();
337 public boolean hasDiagnosticListener() {
338 return diagListener != null;
339 }
341 public void setEndPosTable(JavaFileObject name, EndPosTable endPosTable) {
342 name.getClass(); // null check
343 getSource(name).setEndPosTable(endPosTable);
344 }
346 /** Return current sourcefile.
347 */
348 public JavaFileObject currentSourceFile() {
349 return source == null ? null : source.getFile();
350 }
352 /** Get the current diagnostic formatter.
353 */
354 public DiagnosticFormatter<JCDiagnostic> getDiagnosticFormatter() {
355 return diagFormatter;
356 }
358 /** Set the current diagnostic formatter.
359 */
360 public void setDiagnosticFormatter(DiagnosticFormatter<JCDiagnostic> diagFormatter) {
361 this.diagFormatter = diagFormatter;
362 }
364 public PrintWriter getWriter(WriterKind kind) {
365 switch (kind) {
366 case NOTICE: return noticeWriter;
367 case WARNING: return warnWriter;
368 case ERROR: return errWriter;
369 default: throw new IllegalArgumentException();
370 }
371 }
373 public void setWriter(WriterKind kind, PrintWriter pw) {
374 pw.getClass();
375 switch (kind) {
376 case NOTICE: noticeWriter = pw; break;
377 case WARNING: warnWriter = pw; break;
378 case ERROR: errWriter = pw; break;
379 default: throw new IllegalArgumentException();
380 }
381 }
383 public void setWriters(PrintWriter pw) {
384 pw.getClass();
385 noticeWriter = warnWriter = errWriter = pw;
386 }
388 /**
389 * Propagate the previous log's information.
390 */
391 public void initRound(Log other) {
392 this.noticeWriter = other.noticeWriter;
393 this.warnWriter = other.warnWriter;
394 this.errWriter = other.errWriter;
395 this.sourceMap = other.sourceMap;
396 this.recorded = other.recorded;
397 this.nerrors = other.nerrors;
398 this.nwarnings = other.nwarnings;
399 }
401 /**
402 * Replace the specified diagnostic handler with the
403 * handler that was current at the time this handler was created.
404 * The given handler must be the currently installed handler;
405 * it must be specified explicitly for clarity and consistency checking.
406 */
407 public void popDiagnosticHandler(DiagnosticHandler h) {
408 Assert.check(diagnosticHandler == h);
409 diagnosticHandler = h.prev;
410 }
412 /** Flush the logs
413 */
414 public void flush() {
415 errWriter.flush();
416 warnWriter.flush();
417 noticeWriter.flush();
418 }
420 public void flush(WriterKind kind) {
421 getWriter(kind).flush();
422 }
424 /** Returns true if an error needs to be reported for a given
425 * source name and pos.
426 */
427 protected boolean shouldReport(JavaFileObject file, int pos) {
428 if (multipleErrors || file == null)
429 return true;
431 Pair<JavaFileObject,Integer> coords = new Pair<JavaFileObject,Integer>(file, pos);
432 boolean shouldReport = !recorded.contains(coords);
433 if (shouldReport)
434 recorded.add(coords);
435 return shouldReport;
436 }
438 /** Prompt user after an error.
439 */
440 public void prompt() {
441 if (promptOnError) {
442 System.err.println(localize("resume.abort"));
443 try {
444 while (true) {
445 switch (System.in.read()) {
446 case 'a': case 'A':
447 System.exit(-1);
448 return;
449 case 'r': case 'R':
450 return;
451 case 'x': case 'X':
452 throw new AssertionError("user abort");
453 default:
454 }
455 }
456 } catch (IOException e) {}
457 }
458 }
460 /** Print the faulty source code line and point to the error.
461 * @param pos Buffer index of the error position, must be on current line
462 */
463 private void printErrLine(int pos, PrintWriter writer) {
464 String line = (source == null ? null : source.getLine(pos));
465 if (line == null)
466 return;
467 int col = source.getColumnNumber(pos, false);
469 printRawLines(writer, line);
470 for (int i = 0; i < col - 1; i++) {
471 writer.print((line.charAt(i) == '\t') ? "\t" : " ");
472 }
473 writer.println("^");
474 writer.flush();
475 }
477 public void printNewline() {
478 noticeWriter.println();
479 }
481 public void printNewline(WriterKind wk) {
482 getWriter(wk).println();
483 }
485 public void printLines(String key, Object... args) {
486 printRawLines(noticeWriter, localize(key, args));
487 }
489 public void printLines(PrefixKind pk, String key, Object... args) {
490 printRawLines(noticeWriter, localize(pk, key, args));
491 }
493 public void printLines(WriterKind wk, String key, Object... args) {
494 printRawLines(getWriter(wk), localize(key, args));
495 }
497 public void printLines(WriterKind wk, PrefixKind pk, String key, Object... args) {
498 printRawLines(getWriter(wk), localize(pk, key, args));
499 }
501 /** Print the text of a message, translating newlines appropriately
502 * for the platform.
503 */
504 public void printRawLines(String msg) {
505 printRawLines(noticeWriter, msg);
506 }
508 /** Print the text of a message, translating newlines appropriately
509 * for the platform.
510 */
511 public void printRawLines(WriterKind kind, String msg) {
512 printRawLines(getWriter(kind), msg);
513 }
515 /** Print the text of a message, translating newlines appropriately
516 * for the platform.
517 */
518 public static void printRawLines(PrintWriter writer, String msg) {
519 int nl;
520 while ((nl = msg.indexOf('\n')) != -1) {
521 writer.println(msg.substring(0, nl));
522 msg = msg.substring(nl+1);
523 }
524 if (msg.length() != 0) writer.println(msg);
525 }
527 /**
528 * Print the localized text of a "verbose" message to the
529 * noticeWriter stream.
530 */
531 public void printVerbose(String key, Object... args) {
532 printRawLines(noticeWriter, localize("verbose." + key, args));
533 }
535 protected void directError(String key, Object... args) {
536 printRawLines(errWriter, localize(key, args));
537 errWriter.flush();
538 }
540 /** Report a warning that cannot be suppressed.
541 * @param pos The source position at which to report the warning.
542 * @param key The key for the localized warning message.
543 * @param args Fields of the warning message.
544 */
545 public void strictWarning(DiagnosticPosition pos, String key, Object ... args) {
546 writeDiagnostic(diags.warning(source, pos, key, args));
547 nwarnings++;
548 }
550 /**
551 * Primary method to report a diagnostic.
552 * @param diagnostic
553 */
554 public void report(JCDiagnostic diagnostic) {
555 diagnosticHandler.report(diagnostic);
556 }
558 /**
559 * Common diagnostic handling.
560 * The diagnostic is counted, and depending on the options and how many diagnostics have been
561 * reported so far, the diagnostic may be handed off to writeDiagnostic.
562 */
563 private class DefaultDiagnosticHandler extends DiagnosticHandler {
564 public void report(JCDiagnostic diagnostic) {
565 if (expectDiagKeys != null)
566 expectDiagKeys.remove(diagnostic.getCode());
568 switch (diagnostic.getType()) {
569 case FRAGMENT:
570 throw new IllegalArgumentException();
572 case NOTE:
573 // Print out notes only when we are permitted to report warnings
574 // Notes are only generated at the end of a compilation, so should be small
575 // in number.
576 if ((emitWarnings || diagnostic.isMandatory()) && !suppressNotes) {
577 writeDiagnostic(diagnostic);
578 }
579 break;
581 case WARNING:
582 if (emitWarnings || diagnostic.isMandatory()) {
583 if (nwarnings < MaxWarnings) {
584 writeDiagnostic(diagnostic);
585 nwarnings++;
586 }
587 }
588 break;
590 case ERROR:
591 if (nerrors < MaxErrors
592 && shouldReport(diagnostic.getSource(), diagnostic.getIntPosition())) {
593 writeDiagnostic(diagnostic);
594 nerrors++;
595 }
596 break;
597 }
598 }
599 }
601 /**
602 * Write out a diagnostic.
603 */
604 protected void writeDiagnostic(JCDiagnostic diag) {
605 if (diagListener != null) {
606 diagListener.report(diag);
607 return;
608 }
610 PrintWriter writer = getWriterForDiagnosticType(diag.getType());
612 printRawLines(writer, diagFormatter.format(diag, messages.getCurrentLocale()));
614 if (promptOnError) {
615 switch (diag.getType()) {
616 case ERROR:
617 case WARNING:
618 prompt();
619 }
620 }
622 if (dumpOnError)
623 new RuntimeException().printStackTrace(writer);
625 writer.flush();
626 }
628 @Deprecated
629 protected PrintWriter getWriterForDiagnosticType(DiagnosticType dt) {
630 switch (dt) {
631 case FRAGMENT:
632 throw new IllegalArgumentException();
634 case NOTE:
635 return noticeWriter;
637 case WARNING:
638 return warnWriter;
640 case ERROR:
641 return errWriter;
643 default:
644 throw new Error();
645 }
646 }
648 /** Find a localized string in the resource bundle.
649 * Because this method is static, it ignores the locale.
650 * Use localize(key, args) when possible.
651 * @param key The key for the localized string.
652 * @param args Fields to substitute into the string.
653 */
654 public static String getLocalizedString(String key, Object ... args) {
655 return JavacMessages.getDefaultLocalizedString(PrefixKind.COMPILER_MISC.key(key), args);
656 }
658 /** Find a localized string in the resource bundle.
659 * @param key The key for the localized string.
660 * @param args Fields to substitute into the string.
661 */
662 public String localize(String key, Object... args) {
663 return localize(PrefixKind.COMPILER_MISC, key, args);
664 }
666 /** Find a localized string in the resource bundle.
667 * @param key The key for the localized string.
668 * @param args Fields to substitute into the string.
669 */
670 public String localize(PrefixKind pk, String key, Object... args) {
671 if (useRawMessages)
672 return pk.key(key);
673 else
674 return messages.getLocalizedString(pk.key(key), args);
675 }
676 // where
677 // backdoor hook for testing, should transition to use -XDrawDiagnostics
678 private static boolean useRawMessages = false;
680 /***************************************************************************
681 * raw error messages without internationalization; used for experimentation
682 * and quick prototyping
683 ***************************************************************************/
685 /** print an error or warning message:
686 */
687 private void printRawError(int pos, String msg) {
688 if (source == null || pos == Position.NOPOS) {
689 printRawLines(errWriter, "error: " + msg);
690 } else {
691 int line = source.getLineNumber(pos);
692 JavaFileObject file = source.getFile();
693 if (file != null)
694 printRawLines(errWriter,
695 file.getName() + ":" +
696 line + ": " + msg);
697 printErrLine(pos, errWriter);
698 }
699 errWriter.flush();
700 }
702 /** report an error:
703 */
704 public void rawError(int pos, String msg) {
705 if (nerrors < MaxErrors && shouldReport(currentSourceFile(), pos)) {
706 printRawError(pos, msg);
707 prompt();
708 nerrors++;
709 }
710 errWriter.flush();
711 }
713 /** report a warning:
714 */
715 public void rawWarning(int pos, String msg) {
716 if (nwarnings < MaxWarnings && emitWarnings) {
717 printRawError(pos, "warning: " + msg);
718 }
719 prompt();
720 nwarnings++;
721 errWriter.flush();
722 }
724 public static String format(String fmt, Object... args) {
725 return String.format((java.util.Locale)null, fmt, args);
726 }
728 }