Mon, 11 Apr 2011 16:31:22 -0700
Merge
1 /*
2 * Copyright (c) 1999, 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.util;
28 import java.io.*;
29 import java.util.Arrays;
30 import java.util.EnumSet;
31 import java.util.HashSet;
32 import java.util.Map;
33 import java.util.Queue;
34 import java.util.Set;
35 import javax.tools.DiagnosticListener;
36 import javax.tools.JavaFileObject;
38 import com.sun.tools.javac.api.DiagnosticFormatter;
39 import com.sun.tools.javac.main.OptionName;
40 import com.sun.tools.javac.tree.JCTree;
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.OptionName.*;
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 //@Deprecated
64 public final PrintWriter errWriter;
66 //@Deprecated
67 public final PrintWriter warnWriter;
69 //@Deprecated
70 public final PrintWriter noticeWriter;
72 /** The maximum number of errors/warnings that are reported.
73 */
74 public final int MaxErrors;
75 public final int MaxWarnings;
77 /** Switch: prompt user on each error.
78 */
79 public boolean promptOnError;
81 /** Switch: emit warning messages.
82 */
83 public boolean emitWarnings;
85 /** Switch: suppress note messages.
86 */
87 public boolean suppressNotes;
89 /** Print stack trace on errors?
90 */
91 public boolean dumpOnError;
93 /** Print multiple errors for same source locations.
94 */
95 public boolean multipleErrors;
97 /**
98 * Diagnostic listener, if provided through programmatic
99 * interface to javac (JSR 199).
100 */
101 protected DiagnosticListener<? super JavaFileObject> diagListener;
103 /**
104 * Formatter for diagnostics.
105 */
106 private DiagnosticFormatter<JCDiagnostic> diagFormatter;
108 /**
109 * Keys for expected diagnostics.
110 */
111 public Set<String> expectDiagKeys;
113 /**
114 * JavacMessages object used for localization.
115 */
116 private JavacMessages messages;
118 /**
119 * Deferred diagnostics
120 */
121 public boolean deferDiagnostics;
122 public Queue<JCDiagnostic> deferredDiagnostics = new ListBuffer<JCDiagnostic>();
124 /** Construct a log with given I/O redirections.
125 */
126 @Deprecated
127 protected Log(Context context, PrintWriter errWriter, PrintWriter warnWriter, PrintWriter noticeWriter) {
128 super(JCDiagnostic.Factory.instance(context));
129 context.put(logKey, this);
130 this.errWriter = errWriter;
131 this.warnWriter = warnWriter;
132 this.noticeWriter = noticeWriter;
134 Options options = Options.instance(context);
135 this.dumpOnError = options.isSet(DOE);
136 this.promptOnError = options.isSet(PROMPT);
137 this.emitWarnings = options.isUnset(XLINT_CUSTOM, "none");
138 this.suppressNotes = options.isSet("suppressNotes");
139 this.MaxErrors = getIntOption(options, XMAXERRS, getDefaultMaxErrors());
140 this.MaxWarnings = getIntOption(options, XMAXWARNS, getDefaultMaxWarnings());
142 boolean rawDiagnostics = options.isSet("rawDiagnostics");
143 messages = JavacMessages.instance(context);
144 this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(options) :
145 new BasicDiagnosticFormatter(options, messages);
146 @SuppressWarnings("unchecked") // FIXME
147 DiagnosticListener<? super JavaFileObject> dl =
148 context.get(DiagnosticListener.class);
149 this.diagListener = dl;
151 String ek = options.get("expectKeys");
152 if (ek != null)
153 expectDiagKeys = new HashSet<String>(Arrays.asList(ek.split(", *")));
154 }
155 // where
156 private int getIntOption(Options options, OptionName optionName, int defaultValue) {
157 String s = options.get(optionName);
158 try {
159 if (s != null) {
160 int n = Integer.parseInt(s);
161 return (n <= 0 ? Integer.MAX_VALUE : n);
162 }
163 } catch (NumberFormatException e) {
164 // silently ignore ill-formed numbers
165 }
166 return defaultValue;
167 }
169 /** Default value for -Xmaxerrs.
170 */
171 protected int getDefaultMaxErrors() {
172 return 100;
173 }
175 /** Default value for -Xmaxwarns.
176 */
177 protected int getDefaultMaxWarnings() {
178 return 100;
179 }
181 /** The default writer for diagnostics
182 */
183 static final PrintWriter defaultWriter(Context context) {
184 PrintWriter result = context.get(outKey);
185 if (result == null)
186 context.put(outKey, result = new PrintWriter(System.err));
187 return result;
188 }
190 /** Construct a log with default settings.
191 */
192 protected Log(Context context) {
193 this(context, defaultWriter(context));
194 }
196 /** Construct a log with all output redirected.
197 */
198 protected Log(Context context, PrintWriter defaultWriter) {
199 this(context, defaultWriter, defaultWriter, defaultWriter);
200 }
202 /** Get the Log instance for this context. */
203 public static Log instance(Context context) {
204 Log instance = context.get(logKey);
205 if (instance == null)
206 instance = new Log(context);
207 return instance;
208 }
210 /** The number of errors encountered so far.
211 */
212 public int nerrors = 0;
214 /** The number of warnings encountered so far.
215 */
216 public int nwarnings = 0;
218 /** A set of all errors generated so far. This is used to avoid printing an
219 * error message more than once. For each error, a pair consisting of the
220 * source file name and source code position of the error is added to the set.
221 */
222 private Set<Pair<JavaFileObject, Integer>> recorded = new HashSet<Pair<JavaFileObject,Integer>>();
224 public boolean hasDiagnosticListener() {
225 return diagListener != null;
226 }
228 public void setEndPosTable(JavaFileObject name, Map<JCTree, Integer> table) {
229 name.getClass(); // null check
230 getSource(name).setEndPosTable(table);
231 }
233 /** Return current sourcefile.
234 */
235 public JavaFileObject currentSourceFile() {
236 return source == null ? null : source.getFile();
237 }
239 /** Get the current diagnostic formatter.
240 */
241 public DiagnosticFormatter<JCDiagnostic> getDiagnosticFormatter() {
242 return diagFormatter;
243 }
245 /** Set the current diagnostic formatter.
246 */
247 public void setDiagnosticFormatter(DiagnosticFormatter<JCDiagnostic> diagFormatter) {
248 this.diagFormatter = diagFormatter;
249 }
251 /** Flush the logs
252 */
253 public void flush() {
254 errWriter.flush();
255 warnWriter.flush();
256 noticeWriter.flush();
257 }
259 /** Returns true if an error needs to be reported for a given
260 * source name and pos.
261 */
262 protected boolean shouldReport(JavaFileObject file, int pos) {
263 if (multipleErrors || file == null)
264 return true;
266 Pair<JavaFileObject,Integer> coords = new Pair<JavaFileObject,Integer>(file, pos);
267 boolean shouldReport = !recorded.contains(coords);
268 if (shouldReport)
269 recorded.add(coords);
270 return shouldReport;
271 }
273 /** Prompt user after an error.
274 */
275 public void prompt() {
276 if (promptOnError) {
277 System.err.println(localize("resume.abort"));
278 char ch;
279 try {
280 while (true) {
281 switch (System.in.read()) {
282 case 'a': case 'A':
283 System.exit(-1);
284 return;
285 case 'r': case 'R':
286 return;
287 case 'x': case 'X':
288 throw new AssertionError("user abort");
289 default:
290 }
291 }
292 } catch (IOException e) {}
293 }
294 }
296 /** Print the faulty source code line and point to the error.
297 * @param pos Buffer index of the error position, must be on current line
298 */
299 private void printErrLine(int pos, PrintWriter writer) {
300 String line = (source == null ? null : source.getLine(pos));
301 if (line == null)
302 return;
303 int col = source.getColumnNumber(pos, false);
305 printLines(writer, line);
306 for (int i = 0; i < col - 1; i++) {
307 writer.print((line.charAt(i) == '\t') ? "\t" : " ");
308 }
309 writer.println("^");
310 writer.flush();
311 }
313 /** Print the text of a message, translating newlines appropriately
314 * for the platform.
315 */
316 public static void printLines(PrintWriter writer, String msg) {
317 int nl;
318 while ((nl = msg.indexOf('\n')) != -1) {
319 writer.println(msg.substring(0, nl));
320 msg = msg.substring(nl+1);
321 }
322 if (msg.length() != 0) writer.println(msg);
323 }
325 /** Print the text of a message to the errWriter stream,
326 * translating newlines appropriately for the platform.
327 */
328 public void printErrLines(String key, Object... args) {
329 printLines(errWriter, localize(key, args));
330 }
332 /** Print the text of a message to the noticeWriter stream,
333 * translating newlines appropriately for the platform.
334 */
335 public void printNoteLines(String key, Object... args) {
336 printLines(noticeWriter, localize(key, args));
337 }
339 /**
340 * Print the localized text of a "verbose" message to the
341 * noticeWriter stream.
342 */
343 public void printVerbose(String key, Object... args) {
344 printLines(noticeWriter, localize("verbose." + key, args));
345 }
347 protected void directError(String key, Object... args) {
348 printErrLines(key, args);
349 errWriter.flush();
350 }
352 /** Report a warning that cannot be suppressed.
353 * @param pos The source position at which to report the warning.
354 * @param key The key for the localized warning message.
355 * @param args Fields of the warning message.
356 */
357 public void strictWarning(DiagnosticPosition pos, String key, Object ... args) {
358 writeDiagnostic(diags.warning(source, pos, key, args));
359 nwarnings++;
360 }
362 /** Report all deferred diagnostics, and clear the deferDiagnostics flag. */
363 public void reportDeferredDiagnostics() {
364 reportDeferredDiagnostics(EnumSet.allOf(JCDiagnostic.Kind.class));
365 }
367 /** Report selected deferred diagnostics, and clear the deferDiagnostics flag. */
368 public void reportDeferredDiagnostics(Set<JCDiagnostic.Kind> kinds) {
369 deferDiagnostics = false;
370 JCDiagnostic d;
371 while ((d = deferredDiagnostics.poll()) != null) {
372 if (kinds.contains(d.getKind()))
373 report(d);
374 }
375 }
377 /**
378 * Common diagnostic handling.
379 * The diagnostic is counted, and depending on the options and how many diagnostics have been
380 * reported so far, the diagnostic may be handed off to writeDiagnostic.
381 */
382 public void report(JCDiagnostic diagnostic) {
383 if (deferDiagnostics) {
384 deferredDiagnostics.add(diagnostic);
385 return;
386 }
388 if (expectDiagKeys != null)
389 expectDiagKeys.remove(diagnostic.getCode());
391 switch (diagnostic.getType()) {
392 case FRAGMENT:
393 throw new IllegalArgumentException();
395 case NOTE:
396 // Print out notes only when we are permitted to report warnings
397 // Notes are only generated at the end of a compilation, so should be small
398 // in number.
399 if ((emitWarnings || diagnostic.isMandatory()) && !suppressNotes) {
400 writeDiagnostic(diagnostic);
401 }
402 break;
404 case WARNING:
405 if (emitWarnings || diagnostic.isMandatory()) {
406 if (nwarnings < MaxWarnings) {
407 writeDiagnostic(diagnostic);
408 nwarnings++;
409 }
410 }
411 break;
413 case ERROR:
414 if (nerrors < MaxErrors
415 && shouldReport(diagnostic.getSource(), diagnostic.getIntPosition())) {
416 writeDiagnostic(diagnostic);
417 nerrors++;
418 }
419 break;
420 }
421 }
423 /**
424 * Write out a diagnostic.
425 */
426 protected void writeDiagnostic(JCDiagnostic diag) {
427 if (diagListener != null) {
428 try {
429 diagListener.report(diag);
430 return;
431 }
432 catch (Throwable t) {
433 throw new ClientCodeException(t);
434 }
435 }
437 PrintWriter writer = getWriterForDiagnosticType(diag.getType());
439 printLines(writer, diagFormatter.format(diag, messages.getCurrentLocale()));
441 if (promptOnError) {
442 switch (diag.getType()) {
443 case ERROR:
444 case WARNING:
445 prompt();
446 }
447 }
449 if (dumpOnError)
450 new RuntimeException().printStackTrace(writer);
452 writer.flush();
453 }
455 @Deprecated
456 protected PrintWriter getWriterForDiagnosticType(DiagnosticType dt) {
457 switch (dt) {
458 case FRAGMENT:
459 throw new IllegalArgumentException();
461 case NOTE:
462 return noticeWriter;
464 case WARNING:
465 return warnWriter;
467 case ERROR:
468 return errWriter;
470 default:
471 throw new Error();
472 }
473 }
475 /** Find a localized string in the resource bundle.
476 * Because this method is static, it ignores the locale.
477 * Use localize(key, args) when possible.
478 * @param key The key for the localized string.
479 * @param args Fields to substitute into the string.
480 */
481 public static String getLocalizedString(String key, Object ... args) {
482 return JavacMessages.getDefaultLocalizedString("compiler.misc." + key, args);
483 }
485 /** Find a localized string in the resource bundle.
486 * @param key The key for the localized string.
487 * @param args Fields to substitute into the string.
488 */
489 public String localize(String key, Object... args) {
490 return messages.getLocalizedString("compiler.misc." + key, args);
491 }
493 /***************************************************************************
494 * raw error messages without internationalization; used for experimentation
495 * and quick prototyping
496 ***************************************************************************/
498 /** print an error or warning message:
499 */
500 private void printRawError(int pos, String msg) {
501 if (source == null || pos == Position.NOPOS) {
502 printLines(errWriter, "error: " + msg);
503 } else {
504 int line = source.getLineNumber(pos);
505 JavaFileObject file = source.getFile();
506 if (file != null)
507 printLines(errWriter,
508 file.getName() + ":" +
509 line + ": " + msg);
510 printErrLine(pos, errWriter);
511 }
512 errWriter.flush();
513 }
515 /** report an error:
516 */
517 public void rawError(int pos, String msg) {
518 if (nerrors < MaxErrors && shouldReport(currentSourceFile(), pos)) {
519 printRawError(pos, msg);
520 prompt();
521 nerrors++;
522 }
523 errWriter.flush();
524 }
526 /** report a warning:
527 */
528 public void rawWarning(int pos, String msg) {
529 if (nwarnings < MaxWarnings && emitWarnings) {
530 printRawError(pos, "warning: " + msg);
531 }
532 prompt();
533 nwarnings++;
534 errWriter.flush();
535 }
537 public static String format(String fmt, Object... args) {
538 return String.format((java.util.Locale)null, fmt, args);
539 }
541 }