Fri, 21 Aug 2009 11:25:45 -0700
6873849: suppress notes generated by javac
Reviewed-by: darcy
1 /*
2 * Copyright 1999-2009 Sun Microsystems, Inc. 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. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
24 */
26 package com.sun.tools.javac.util;
28 import java.io.*;
29 import java.util.Arrays;
30 import java.util.HashSet;
31 import java.util.Map;
32 import java.util.Set;
33 import javax.tools.DiagnosticListener;
34 import javax.tools.JavaFileObject;
36 import com.sun.tools.javac.file.JavacFileManager;
37 import com.sun.tools.javac.tree.JCTree;
38 import com.sun.tools.javac.api.DiagnosticFormatter;
39 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
40 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
42 /** A class for error logs. Reports errors and warnings, and
43 * keeps track of error numbers and positions.
44 *
45 * <p><b>This is NOT part of any API supported by Sun Microsystems. If
46 * you write code that depends on this, you do so at your own risk.
47 * This code and its internal interfaces are subject to change or
48 * deletion without notice.</b>
49 */
50 public class Log extends AbstractLog {
51 /** The context key for the log. */
52 public static final Context.Key<Log> logKey
53 = new Context.Key<Log>();
55 /** The context key for the output PrintWriter. */
56 public static final Context.Key<PrintWriter> outKey =
57 new Context.Key<PrintWriter>();
59 //@Deprecated
60 public final PrintWriter errWriter;
62 //@Deprecated
63 public final PrintWriter warnWriter;
65 //@Deprecated
66 public final PrintWriter noticeWriter;
68 /** The maximum number of errors/warnings that are reported.
69 */
70 public final int MaxErrors;
71 public final int MaxWarnings;
73 /** Switch: prompt user on each error.
74 */
75 public boolean promptOnError;
77 /** Switch: emit warning messages.
78 */
79 public boolean emitWarnings;
81 /** Switch: suppress note messages.
82 */
83 public boolean suppressNotes;
85 /** Print stack trace on errors?
86 */
87 public boolean dumpOnError;
89 /** Print multiple errors for same source locations.
90 */
91 public boolean multipleErrors;
93 /**
94 * Diagnostic listener, if provided through programmatic
95 * interface to javac (JSR 199).
96 */
97 protected DiagnosticListener<? super JavaFileObject> diagListener;
99 /**
100 * Formatter for diagnostics.
101 */
102 private DiagnosticFormatter<JCDiagnostic> diagFormatter;
104 /**
105 * Keys for expected diagnostics.
106 */
107 public Set<String> expectDiagKeys;
109 /**
110 * JavacMessages object used for localization.
111 */
112 private JavacMessages messages;
114 /** Construct a log with given I/O redirections.
115 */
116 @Deprecated
117 protected Log(Context context, PrintWriter errWriter, PrintWriter warnWriter, PrintWriter noticeWriter) {
118 super(JCDiagnostic.Factory.instance(context));
119 context.put(logKey, this);
120 this.errWriter = errWriter;
121 this.warnWriter = warnWriter;
122 this.noticeWriter = noticeWriter;
124 Options options = Options.instance(context);
125 this.dumpOnError = options.get("-doe") != null;
126 this.promptOnError = options.get("-prompt") != null;
127 this.emitWarnings = options.get("-Xlint:none") == null;
128 this.suppressNotes = options.get("suppressNotes") != null;
129 this.MaxErrors = getIntOption(options, "-Xmaxerrs", 100);
130 this.MaxWarnings = getIntOption(options, "-Xmaxwarns", 100);
132 boolean rawDiagnostics = options.get("rawDiagnostics") != null;
133 messages = JavacMessages.instance(context);
134 this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(options) :
135 new BasicDiagnosticFormatter(options, messages);
136 @SuppressWarnings("unchecked") // FIXME
137 DiagnosticListener<? super JavaFileObject> dl =
138 context.get(DiagnosticListener.class);
139 this.diagListener = dl;
141 String ek = options.get("expectKeys");
142 if (ek != null)
143 expectDiagKeys = new HashSet<String>(Arrays.asList(ek.split(", *")));
144 }
145 // where
146 private int getIntOption(Options options, String optionName, int defaultValue) {
147 String s = options.get(optionName);
148 try {
149 if (s != null) return Integer.parseInt(s);
150 } catch (NumberFormatException e) {
151 // silently ignore ill-formed numbers
152 }
153 return defaultValue;
154 }
156 /** The default writer for diagnostics
157 */
158 static final PrintWriter defaultWriter(Context context) {
159 PrintWriter result = context.get(outKey);
160 if (result == null)
161 context.put(outKey, result = new PrintWriter(System.err));
162 return result;
163 }
165 /** Construct a log with default settings.
166 */
167 protected Log(Context context) {
168 this(context, defaultWriter(context));
169 }
171 /** Construct a log with all output redirected.
172 */
173 protected Log(Context context, PrintWriter defaultWriter) {
174 this(context, defaultWriter, defaultWriter, defaultWriter);
175 }
177 /** Get the Log instance for this context. */
178 public static Log instance(Context context) {
179 Log instance = context.get(logKey);
180 if (instance == null)
181 instance = new Log(context);
182 return instance;
183 }
185 /** The number of errors encountered so far.
186 */
187 public int nerrors = 0;
189 /** The number of warnings encountered so far.
190 */
191 public int nwarnings = 0;
193 /** A set of all errors generated so far. This is used to avoid printing an
194 * error message more than once. For each error, a pair consisting of the
195 * source file name and source code position of the error is added to the set.
196 */
197 private Set<Pair<JavaFileObject, Integer>> recorded = new HashSet<Pair<JavaFileObject,Integer>>();
199 public boolean hasDiagnosticListener() {
200 return diagListener != null;
201 }
203 public void setEndPosTable(JavaFileObject name, Map<JCTree, Integer> table) {
204 name.getClass(); // null check
205 getSource(name).setEndPosTable(table);
206 }
208 /** Return current sourcefile.
209 */
210 public JavaFileObject currentSourceFile() {
211 return source == null ? null : source.getFile();
212 }
214 /** Get the current diagnostic formatter.
215 */
216 public DiagnosticFormatter<JCDiagnostic> getDiagnosticFormatter() {
217 return diagFormatter;
218 }
220 /** Set the current diagnostic formatter.
221 */
222 public void setDiagnosticFormatter(DiagnosticFormatter<JCDiagnostic> diagFormatter) {
223 this.diagFormatter = diagFormatter;
224 }
226 /** Flush the logs
227 */
228 public void flush() {
229 errWriter.flush();
230 warnWriter.flush();
231 noticeWriter.flush();
232 }
234 /** Returns true if an error needs to be reported for a given
235 * source name and pos.
236 */
237 protected boolean shouldReport(JavaFileObject file, int pos) {
238 if (multipleErrors || file == null)
239 return true;
241 Pair<JavaFileObject,Integer> coords = new Pair<JavaFileObject,Integer>(file, pos);
242 boolean shouldReport = !recorded.contains(coords);
243 if (shouldReport)
244 recorded.add(coords);
245 return shouldReport;
246 }
248 /** Prompt user after an error.
249 */
250 public void prompt() {
251 if (promptOnError) {
252 System.err.println(getLocalizedString("resume.abort"));
253 char ch;
254 try {
255 while (true) {
256 switch (System.in.read()) {
257 case 'a': case 'A':
258 System.exit(-1);
259 return;
260 case 'r': case 'R':
261 return;
262 case 'x': case 'X':
263 throw new AssertionError("user abort");
264 default:
265 }
266 }
267 } catch (IOException e) {}
268 }
269 }
271 /** Print the faulty source code line and point to the error.
272 * @param pos Buffer index of the error position, must be on current line
273 */
274 private void printErrLine(int pos, PrintWriter writer) {
275 String line = (source == null ? null : source.getLine(pos));
276 if (line == null)
277 return;
278 int col = source.getColumnNumber(pos, false);
280 printLines(writer, line);
281 for (int i = 0; i < col - 1; i++) {
282 writer.print((line.charAt(i) == '\t') ? "\t" : " ");
283 }
284 writer.println("^");
285 writer.flush();
286 }
288 /** Print the text of a message, translating newlines appropriately
289 * for the platform.
290 */
291 public static void printLines(PrintWriter writer, String msg) {
292 int nl;
293 while ((nl = msg.indexOf('\n')) != -1) {
294 writer.println(msg.substring(0, nl));
295 msg = msg.substring(nl+1);
296 }
297 if (msg.length() != 0) writer.println(msg);
298 }
300 protected void directError(String key, Object... args) {
301 printLines(errWriter, getLocalizedString(key, args));
302 errWriter.flush();
303 }
305 /** Report a warning that cannot be suppressed.
306 * @param pos The source position at which to report the warning.
307 * @param key The key for the localized warning message.
308 * @param args Fields of the warning message.
309 */
310 public void strictWarning(DiagnosticPosition pos, String key, Object ... args) {
311 writeDiagnostic(diags.warning(source, pos, key, args));
312 nwarnings++;
313 }
315 /**
316 * Common diagnostic handling.
317 * The diagnostic is counted, and depending on the options and how many diagnostics have been
318 * reported so far, the diagnostic may be handed off to writeDiagnostic.
319 */
320 public void report(JCDiagnostic diagnostic) {
321 if (expectDiagKeys != null)
322 expectDiagKeys.remove(diagnostic.getCode());
324 switch (diagnostic.getType()) {
325 case FRAGMENT:
326 throw new IllegalArgumentException();
328 case NOTE:
329 // Print out notes only when we are permitted to report warnings
330 // Notes are only generated at the end of a compilation, so should be small
331 // in number.
332 if ((emitWarnings || diagnostic.isMandatory()) && !suppressNotes) {
333 writeDiagnostic(diagnostic);
334 }
335 break;
337 case WARNING:
338 if (emitWarnings || diagnostic.isMandatory()) {
339 if (nwarnings < MaxWarnings) {
340 writeDiagnostic(diagnostic);
341 nwarnings++;
342 }
343 }
344 break;
346 case ERROR:
347 if (nerrors < MaxErrors
348 && shouldReport(diagnostic.getSource(), diagnostic.getIntPosition())) {
349 writeDiagnostic(diagnostic);
350 nerrors++;
351 }
352 break;
353 }
354 }
356 /**
357 * Write out a diagnostic.
358 */
359 protected void writeDiagnostic(JCDiagnostic diag) {
360 if (diagListener != null) {
361 try {
362 diagListener.report(diag);
363 return;
364 }
365 catch (Throwable t) {
366 throw new ClientCodeException(t);
367 }
368 }
370 PrintWriter writer = getWriterForDiagnosticType(diag.getType());
372 printLines(writer, diagFormatter.format(diag, messages.getCurrentLocale()));
374 if (promptOnError) {
375 switch (diag.getType()) {
376 case ERROR:
377 case WARNING:
378 prompt();
379 }
380 }
382 if (dumpOnError)
383 new RuntimeException().printStackTrace(writer);
385 writer.flush();
386 }
388 @Deprecated
389 protected PrintWriter getWriterForDiagnosticType(DiagnosticType dt) {
390 switch (dt) {
391 case FRAGMENT:
392 throw new IllegalArgumentException();
394 case NOTE:
395 return noticeWriter;
397 case WARNING:
398 return warnWriter;
400 case ERROR:
401 return errWriter;
403 default:
404 throw new Error();
405 }
406 }
408 /** Find a localized string in the resource bundle.
409 * @param key The key for the localized string.
410 * @param args Fields to substitute into the string.
411 */
412 public static String getLocalizedString(String key, Object ... args) {
413 return JavacMessages.getDefaultLocalizedString("compiler.misc." + key, args);
414 }
416 /***************************************************************************
417 * raw error messages without internationalization; used for experimentation
418 * and quick prototyping
419 ***************************************************************************/
421 /** print an error or warning message:
422 */
423 private void printRawError(int pos, String msg) {
424 if (source == null || pos == Position.NOPOS) {
425 printLines(errWriter, "error: " + msg);
426 } else {
427 int line = source.getLineNumber(pos);
428 JavaFileObject file = source.getFile();
429 if (file != null)
430 printLines(errWriter,
431 JavacFileManager.getJavacFileName(file) + ":" +
432 line + ": " + msg);
433 printErrLine(pos, errWriter);
434 }
435 errWriter.flush();
436 }
438 /** report an error:
439 */
440 public void rawError(int pos, String msg) {
441 if (nerrors < MaxErrors && shouldReport(currentSourceFile(), pos)) {
442 printRawError(pos, msg);
443 prompt();
444 nerrors++;
445 }
446 errWriter.flush();
447 }
449 /** report a warning:
450 */
451 public void rawWarning(int pos, String msg) {
452 if (nwarnings < MaxWarnings && emitWarnings) {
453 printRawError(pos, "warning: " + msg);
454 }
455 prompt();
456 nwarnings++;
457 errWriter.flush();
458 }
460 public static String format(String fmt, Object... args) {
461 return String.format((java.util.Locale)null, fmt, args);
462 }
464 }