Tue, 09 Oct 2012 19:10:00 -0700
8000663: clean up langtools imports
Reviewed-by: darcy
1 /*
2 * Copyright (c) 1999, 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.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 public enum WriterKind { NOTICE, WARNING, ERROR };
78 protected PrintWriter errWriter;
80 protected PrintWriter warnWriter;
82 protected PrintWriter noticeWriter;
84 /** The maximum number of errors/warnings that are reported.
85 */
86 protected int MaxErrors;
87 protected int MaxWarnings;
89 /** Switch: prompt user on each error.
90 */
91 public boolean promptOnError;
93 /** Switch: emit warning messages.
94 */
95 public boolean emitWarnings;
97 /** Switch: suppress note messages.
98 */
99 public boolean suppressNotes;
101 /** Print stack trace on errors?
102 */
103 public boolean dumpOnError;
105 /** Print multiple errors for same source locations.
106 */
107 public boolean multipleErrors;
109 /**
110 * Diagnostic listener, if provided through programmatic
111 * interface to javac (JSR 199).
112 */
113 protected DiagnosticListener<? super JavaFileObject> diagListener;
115 /**
116 * Formatter for diagnostics.
117 */
118 private DiagnosticFormatter<JCDiagnostic> diagFormatter;
120 /**
121 * Keys for expected diagnostics.
122 */
123 public Set<String> expectDiagKeys;
125 /**
126 * JavacMessages object used for localization.
127 */
128 private JavacMessages messages;
130 /**
131 * Deferred diagnostics
132 */
133 public Filter<JCDiagnostic> deferredDiagFilter;
134 public Queue<JCDiagnostic> deferredDiagnostics = new ListBuffer<JCDiagnostic>();
136 /** Construct a log with given I/O redirections.
137 */
138 protected Log(Context context, PrintWriter errWriter, PrintWriter warnWriter, PrintWriter noticeWriter) {
139 super(JCDiagnostic.Factory.instance(context));
140 context.put(logKey, this);
141 this.errWriter = errWriter;
142 this.warnWriter = warnWriter;
143 this.noticeWriter = noticeWriter;
145 @SuppressWarnings("unchecked") // FIXME
146 DiagnosticListener<? super JavaFileObject> dl =
147 context.get(DiagnosticListener.class);
148 this.diagListener = dl;
150 messages = JavacMessages.instance(context);
151 messages.add(Main.javacBundleName);
153 final Options options = Options.instance(context);
154 initOptions(options);
155 options.addListener(new Runnable() {
156 public void run() {
157 initOptions(options);
158 }
159 });
160 }
161 // where
162 private void initOptions(Options options) {
163 this.dumpOnError = options.isSet(DOE);
164 this.promptOnError = options.isSet(PROMPT);
165 this.emitWarnings = options.isUnset(XLINT_CUSTOM, "none");
166 this.suppressNotes = options.isSet("suppressNotes");
167 this.MaxErrors = getIntOption(options, XMAXERRS, getDefaultMaxErrors());
168 this.MaxWarnings = getIntOption(options, XMAXWARNS, getDefaultMaxWarnings());
170 boolean rawDiagnostics = options.isSet("rawDiagnostics");
171 this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(options) :
172 new BasicDiagnosticFormatter(options, messages);
174 String ek = options.get("expectKeys");
175 if (ek != null)
176 expectDiagKeys = new HashSet<String>(Arrays.asList(ek.split(", *")));
177 }
179 private int getIntOption(Options options, Option option, int defaultValue) {
180 String s = options.get(option);
181 try {
182 if (s != null) {
183 int n = Integer.parseInt(s);
184 return (n <= 0 ? Integer.MAX_VALUE : n);
185 }
186 } catch (NumberFormatException e) {
187 // silently ignore ill-formed numbers
188 }
189 return defaultValue;
190 }
192 /** Default value for -Xmaxerrs.
193 */
194 protected int getDefaultMaxErrors() {
195 return 100;
196 }
198 /** Default value for -Xmaxwarns.
199 */
200 protected int getDefaultMaxWarnings() {
201 return 100;
202 }
204 /** The default writer for diagnostics
205 */
206 static PrintWriter defaultWriter(Context context) {
207 PrintWriter result = context.get(outKey);
208 if (result == null)
209 context.put(outKey, result = new PrintWriter(System.err));
210 return result;
211 }
213 /** Construct a log with default settings.
214 */
215 protected Log(Context context) {
216 this(context, defaultWriter(context));
217 }
219 /** Construct a log with all output redirected.
220 */
221 protected Log(Context context, PrintWriter defaultWriter) {
222 this(context, defaultWriter, defaultWriter, defaultWriter);
223 }
225 /** Get the Log instance for this context. */
226 public static Log instance(Context context) {
227 Log instance = context.get(logKey);
228 if (instance == null)
229 instance = new Log(context);
230 return instance;
231 }
233 /** The number of errors encountered so far.
234 */
235 public int nerrors = 0;
237 /** The number of warnings encountered so far.
238 */
239 public int nwarnings = 0;
241 /** A set of all errors generated so far. This is used to avoid printing an
242 * error message more than once. For each error, a pair consisting of the
243 * source file name and source code position of the error is added to the set.
244 */
245 private Set<Pair<JavaFileObject, Integer>> recorded = new HashSet<Pair<JavaFileObject,Integer>>();
247 public boolean hasDiagnosticListener() {
248 return diagListener != null;
249 }
251 public void setEndPosTable(JavaFileObject name, EndPosTable endPosTable) {
252 name.getClass(); // null check
253 getSource(name).setEndPosTable(endPosTable);
254 }
256 /** Return current sourcefile.
257 */
258 public JavaFileObject currentSourceFile() {
259 return source == null ? null : source.getFile();
260 }
262 /** Get the current diagnostic formatter.
263 */
264 public DiagnosticFormatter<JCDiagnostic> getDiagnosticFormatter() {
265 return diagFormatter;
266 }
268 /** Set the current diagnostic formatter.
269 */
270 public void setDiagnosticFormatter(DiagnosticFormatter<JCDiagnostic> diagFormatter) {
271 this.diagFormatter = diagFormatter;
272 }
274 public PrintWriter getWriter(WriterKind kind) {
275 switch (kind) {
276 case NOTICE: return noticeWriter;
277 case WARNING: return warnWriter;
278 case ERROR: return errWriter;
279 default: throw new IllegalArgumentException();
280 }
281 }
283 public void setWriter(WriterKind kind, PrintWriter pw) {
284 pw.getClass();
285 switch (kind) {
286 case NOTICE: noticeWriter = pw; break;
287 case WARNING: warnWriter = pw; break;
288 case ERROR: errWriter = pw; break;
289 default: throw new IllegalArgumentException();
290 }
291 }
293 public void setWriters(PrintWriter pw) {
294 pw.getClass();
295 noticeWriter = warnWriter = errWriter = pw;
296 }
298 public void setWriters(Log other) {
299 this.noticeWriter = other.noticeWriter;
300 this.warnWriter = other.warnWriter;
301 this.errWriter = other.errWriter;
302 }
304 public void setSourceMap(Log other) {
305 this.sourceMap = other.sourceMap;
306 }
308 /** Flush the logs
309 */
310 public void flush() {
311 errWriter.flush();
312 warnWriter.flush();
313 noticeWriter.flush();
314 }
316 public void flush(WriterKind kind) {
317 getWriter(kind).flush();
318 }
320 /** Returns true if an error needs to be reported for a given
321 * source name and pos.
322 */
323 protected boolean shouldReport(JavaFileObject file, int pos) {
324 if (multipleErrors || file == null)
325 return true;
327 Pair<JavaFileObject,Integer> coords = new Pair<JavaFileObject,Integer>(file, pos);
328 boolean shouldReport = !recorded.contains(coords);
329 if (shouldReport)
330 recorded.add(coords);
331 return shouldReport;
332 }
334 /** Prompt user after an error.
335 */
336 public void prompt() {
337 if (promptOnError) {
338 System.err.println(localize("resume.abort"));
339 try {
340 while (true) {
341 switch (System.in.read()) {
342 case 'a': case 'A':
343 System.exit(-1);
344 return;
345 case 'r': case 'R':
346 return;
347 case 'x': case 'X':
348 throw new AssertionError("user abort");
349 default:
350 }
351 }
352 } catch (IOException e) {}
353 }
354 }
356 /** Print the faulty source code line and point to the error.
357 * @param pos Buffer index of the error position, must be on current line
358 */
359 private void printErrLine(int pos, PrintWriter writer) {
360 String line = (source == null ? null : source.getLine(pos));
361 if (line == null)
362 return;
363 int col = source.getColumnNumber(pos, false);
365 printRawLines(writer, line);
366 for (int i = 0; i < col - 1; i++) {
367 writer.print((line.charAt(i) == '\t') ? "\t" : " ");
368 }
369 writer.println("^");
370 writer.flush();
371 }
373 public void printNewline() {
374 noticeWriter.println();
375 }
377 public void printNewline(WriterKind wk) {
378 getWriter(wk).println();
379 }
381 public void printLines(String key, Object... args) {
382 printRawLines(noticeWriter, localize(key, args));
383 }
385 public void printLines(PrefixKind pk, String key, Object... args) {
386 printRawLines(noticeWriter, localize(pk, key, args));
387 }
389 public void printLines(WriterKind wk, String key, Object... args) {
390 printRawLines(getWriter(wk), localize(key, args));
391 }
393 public void printLines(WriterKind wk, PrefixKind pk, String key, Object... args) {
394 printRawLines(getWriter(wk), localize(pk, key, args));
395 }
397 /** Print the text of a message, translating newlines appropriately
398 * for the platform.
399 */
400 public void printRawLines(String msg) {
401 printRawLines(noticeWriter, msg);
402 }
404 /** Print the text of a message, translating newlines appropriately
405 * for the platform.
406 */
407 public void printRawLines(WriterKind kind, String msg) {
408 printRawLines(getWriter(kind), msg);
409 }
411 /** Print the text of a message, translating newlines appropriately
412 * for the platform.
413 */
414 public static void printRawLines(PrintWriter writer, String msg) {
415 int nl;
416 while ((nl = msg.indexOf('\n')) != -1) {
417 writer.println(msg.substring(0, nl));
418 msg = msg.substring(nl+1);
419 }
420 if (msg.length() != 0) writer.println(msg);
421 }
423 /**
424 * Print the localized text of a "verbose" message to the
425 * noticeWriter stream.
426 */
427 public void printVerbose(String key, Object... args) {
428 printRawLines(noticeWriter, localize("verbose." + key, args));
429 }
431 protected void directError(String key, Object... args) {
432 printRawLines(errWriter, localize(key, args));
433 errWriter.flush();
434 }
436 /** Report a warning that cannot be suppressed.
437 * @param pos The source position at which to report the warning.
438 * @param key The key for the localized warning message.
439 * @param args Fields of the warning message.
440 */
441 public void strictWarning(DiagnosticPosition pos, String key, Object ... args) {
442 writeDiagnostic(diags.warning(source, pos, key, args));
443 nwarnings++;
444 }
446 /** Report all deferred diagnostics, and clear the deferDiagnostics flag. */
447 public void reportDeferredDiagnostics() {
448 reportDeferredDiagnostics(EnumSet.allOf(JCDiagnostic.Kind.class));
449 }
451 /** Report selected deferred diagnostics, and clear the deferDiagnostics flag. */
452 public void reportDeferredDiagnostics(Set<JCDiagnostic.Kind> kinds) {
453 deferredDiagFilter = null;
454 JCDiagnostic d;
455 while ((d = deferredDiagnostics.poll()) != null) {
456 if (kinds.contains(d.getKind()))
457 report(d);
458 }
459 }
461 /**
462 * Common diagnostic handling.
463 * The diagnostic is counted, and depending on the options and how many diagnostics have been
464 * reported so far, the diagnostic may be handed off to writeDiagnostic.
465 */
466 public void report(JCDiagnostic diagnostic) {
467 if (deferredDiagFilter != null && deferredDiagFilter.accepts(diagnostic)) {
468 deferredDiagnostics.add(diagnostic);
469 return;
470 }
472 if (expectDiagKeys != null)
473 expectDiagKeys.remove(diagnostic.getCode());
475 switch (diagnostic.getType()) {
476 case FRAGMENT:
477 throw new IllegalArgumentException();
479 case NOTE:
480 // Print out notes only when we are permitted to report warnings
481 // Notes are only generated at the end of a compilation, so should be small
482 // in number.
483 if ((emitWarnings || diagnostic.isMandatory()) && !suppressNotes) {
484 writeDiagnostic(diagnostic);
485 }
486 break;
488 case WARNING:
489 if (emitWarnings || diagnostic.isMandatory()) {
490 if (nwarnings < MaxWarnings) {
491 writeDiagnostic(diagnostic);
492 nwarnings++;
493 }
494 }
495 break;
497 case ERROR:
498 if (nerrors < MaxErrors
499 && shouldReport(diagnostic.getSource(), diagnostic.getIntPosition())) {
500 writeDiagnostic(diagnostic);
501 nerrors++;
502 }
503 break;
504 }
505 }
507 /**
508 * Write out a diagnostic.
509 */
510 protected void writeDiagnostic(JCDiagnostic diag) {
511 if (diagListener != null) {
512 diagListener.report(diag);
513 return;
514 }
516 PrintWriter writer = getWriterForDiagnosticType(diag.getType());
518 printRawLines(writer, diagFormatter.format(diag, messages.getCurrentLocale()));
520 if (promptOnError) {
521 switch (diag.getType()) {
522 case ERROR:
523 case WARNING:
524 prompt();
525 }
526 }
528 if (dumpOnError)
529 new RuntimeException().printStackTrace(writer);
531 writer.flush();
532 }
534 @Deprecated
535 protected PrintWriter getWriterForDiagnosticType(DiagnosticType dt) {
536 switch (dt) {
537 case FRAGMENT:
538 throw new IllegalArgumentException();
540 case NOTE:
541 return noticeWriter;
543 case WARNING:
544 return warnWriter;
546 case ERROR:
547 return errWriter;
549 default:
550 throw new Error();
551 }
552 }
554 public void deferAll() {
555 deferredDiagFilter = new Filter<JCDiagnostic>() {
556 public boolean accepts(JCDiagnostic t) {
557 return true;
558 }
559 };
560 }
562 public void deferNone() {
563 deferredDiagFilter = null;
564 }
566 /** Find a localized string in the resource bundle.
567 * Because this method is static, it ignores the locale.
568 * Use localize(key, args) when possible.
569 * @param key The key for the localized string.
570 * @param args Fields to substitute into the string.
571 */
572 public static String getLocalizedString(String key, Object ... args) {
573 return JavacMessages.getDefaultLocalizedString(PrefixKind.COMPILER_MISC.key(key), args);
574 }
576 /** Find a localized string in the resource bundle.
577 * @param key The key for the localized string.
578 * @param args Fields to substitute into the string.
579 */
580 public String localize(String key, Object... args) {
581 return localize(PrefixKind.COMPILER_MISC, key, args);
582 }
584 /** Find a localized string in the resource bundle.
585 * @param key The key for the localized string.
586 * @param args Fields to substitute into the string.
587 */
588 public String localize(PrefixKind pk, String key, Object... args) {
589 if (useRawMessages)
590 return pk.key(key);
591 else
592 return messages.getLocalizedString(pk.key(key), args);
593 }
594 // where
595 // backdoor hook for testing, should transition to use -XDrawDiagnostics
596 private static boolean useRawMessages = false;
598 /***************************************************************************
599 * raw error messages without internationalization; used for experimentation
600 * and quick prototyping
601 ***************************************************************************/
603 /** print an error or warning message:
604 */
605 private void printRawError(int pos, String msg) {
606 if (source == null || pos == Position.NOPOS) {
607 printRawLines(errWriter, "error: " + msg);
608 } else {
609 int line = source.getLineNumber(pos);
610 JavaFileObject file = source.getFile();
611 if (file != null)
612 printRawLines(errWriter,
613 file.getName() + ":" +
614 line + ": " + msg);
615 printErrLine(pos, errWriter);
616 }
617 errWriter.flush();
618 }
620 /** report an error:
621 */
622 public void rawError(int pos, String msg) {
623 if (nerrors < MaxErrors && shouldReport(currentSourceFile(), pos)) {
624 printRawError(pos, msg);
625 prompt();
626 nerrors++;
627 }
628 errWriter.flush();
629 }
631 /** report a warning:
632 */
633 public void rawWarning(int pos, String msg) {
634 if (nwarnings < MaxWarnings && emitWarnings) {
635 printRawError(pos, "warning: " + msg);
636 }
637 prompt();
638 nwarnings++;
639 errWriter.flush();
640 }
642 public static String format(String fmt, Object... args) {
643 return String.format((java.util.Locale)null, fmt, args);
644 }
646 }