Mon, 11 Jan 2010 14:05:21 -0800
6326754: Compiler will fail to handle -Xmaxerrs with -ve numbers
Reviewed-by: ksrini
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.tree.JCTree;
37 import com.sun.tools.javac.api.DiagnosticFormatter;
38 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
39 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
41 /** A class for error logs. Reports errors and warnings, and
42 * keeps track of error numbers and positions.
43 *
44 * <p><b>This is NOT part of any API supported by Sun Microsystems. If
45 * you write code that depends on this, you do so at your own risk.
46 * This code and its internal interfaces are subject to change or
47 * deletion without notice.</b>
48 */
49 public class Log extends AbstractLog {
50 /** The context key for the log. */
51 public static final Context.Key<Log> logKey
52 = new Context.Key<Log>();
54 /** The context key for the output PrintWriter. */
55 public static final Context.Key<PrintWriter> outKey =
56 new Context.Key<PrintWriter>();
58 //@Deprecated
59 public final PrintWriter errWriter;
61 //@Deprecated
62 public final PrintWriter warnWriter;
64 //@Deprecated
65 public final PrintWriter noticeWriter;
67 /** The maximum number of errors/warnings that are reported.
68 */
69 public final int MaxErrors;
70 public final int MaxWarnings;
72 /** Switch: prompt user on each error.
73 */
74 public boolean promptOnError;
76 /** Switch: emit warning messages.
77 */
78 public boolean emitWarnings;
80 /** Switch: suppress note messages.
81 */
82 public boolean suppressNotes;
84 /** Print stack trace on errors?
85 */
86 public boolean dumpOnError;
88 /** Print multiple errors for same source locations.
89 */
90 public boolean multipleErrors;
92 /**
93 * Diagnostic listener, if provided through programmatic
94 * interface to javac (JSR 199).
95 */
96 protected DiagnosticListener<? super JavaFileObject> diagListener;
98 /**
99 * Formatter for diagnostics.
100 */
101 private DiagnosticFormatter<JCDiagnostic> diagFormatter;
103 /**
104 * Keys for expected diagnostics.
105 */
106 public Set<String> expectDiagKeys;
108 /**
109 * JavacMessages object used for localization.
110 */
111 private JavacMessages messages;
113 /** Construct a log with given I/O redirections.
114 */
115 @Deprecated
116 protected Log(Context context, PrintWriter errWriter, PrintWriter warnWriter, PrintWriter noticeWriter) {
117 super(JCDiagnostic.Factory.instance(context));
118 context.put(logKey, this);
119 this.errWriter = errWriter;
120 this.warnWriter = warnWriter;
121 this.noticeWriter = noticeWriter;
123 Options options = Options.instance(context);
124 this.dumpOnError = options.get("-doe") != null;
125 this.promptOnError = options.get("-prompt") != null;
126 this.emitWarnings = options.get("-Xlint:none") == null;
127 this.suppressNotes = options.get("suppressNotes") != null;
128 this.MaxErrors = getIntOption(options, "-Xmaxerrs", 100);
129 this.MaxWarnings = getIntOption(options, "-Xmaxwarns", 100);
131 boolean rawDiagnostics = options.get("rawDiagnostics") != null;
132 messages = JavacMessages.instance(context);
133 this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(options) :
134 new BasicDiagnosticFormatter(options, messages);
135 @SuppressWarnings("unchecked") // FIXME
136 DiagnosticListener<? super JavaFileObject> dl =
137 context.get(DiagnosticListener.class);
138 this.diagListener = dl;
140 String ek = options.get("expectKeys");
141 if (ek != null)
142 expectDiagKeys = new HashSet<String>(Arrays.asList(ek.split(", *")));
143 }
144 // where
145 private int getIntOption(Options options, String optionName, int defaultValue) {
146 String s = options.get(optionName);
147 try {
148 if (s != null) {
149 int n = Integer.parseInt(s);
150 return (n <= 0 ? Integer.MAX_VALUE : n);
151 }
152 } catch (NumberFormatException e) {
153 // silently ignore ill-formed numbers
154 }
155 return defaultValue;
156 }
158 /** The default writer for diagnostics
159 */
160 static final PrintWriter defaultWriter(Context context) {
161 PrintWriter result = context.get(outKey);
162 if (result == null)
163 context.put(outKey, result = new PrintWriter(System.err));
164 return result;
165 }
167 /** Construct a log with default settings.
168 */
169 protected Log(Context context) {
170 this(context, defaultWriter(context));
171 }
173 /** Construct a log with all output redirected.
174 */
175 protected Log(Context context, PrintWriter defaultWriter) {
176 this(context, defaultWriter, defaultWriter, defaultWriter);
177 }
179 /** Get the Log instance for this context. */
180 public static Log instance(Context context) {
181 Log instance = context.get(logKey);
182 if (instance == null)
183 instance = new Log(context);
184 return instance;
185 }
187 /** The number of errors encountered so far.
188 */
189 public int nerrors = 0;
191 /** The number of warnings encountered so far.
192 */
193 public int nwarnings = 0;
195 /** A set of all errors generated so far. This is used to avoid printing an
196 * error message more than once. For each error, a pair consisting of the
197 * source file name and source code position of the error is added to the set.
198 */
199 private Set<Pair<JavaFileObject, Integer>> recorded = new HashSet<Pair<JavaFileObject,Integer>>();
201 public boolean hasDiagnosticListener() {
202 return diagListener != null;
203 }
205 public void setEndPosTable(JavaFileObject name, Map<JCTree, Integer> table) {
206 name.getClass(); // null check
207 getSource(name).setEndPosTable(table);
208 }
210 /** Return current sourcefile.
211 */
212 public JavaFileObject currentSourceFile() {
213 return source == null ? null : source.getFile();
214 }
216 /** Get the current diagnostic formatter.
217 */
218 public DiagnosticFormatter<JCDiagnostic> getDiagnosticFormatter() {
219 return diagFormatter;
220 }
222 /** Set the current diagnostic formatter.
223 */
224 public void setDiagnosticFormatter(DiagnosticFormatter<JCDiagnostic> diagFormatter) {
225 this.diagFormatter = diagFormatter;
226 }
228 /** Flush the logs
229 */
230 public void flush() {
231 errWriter.flush();
232 warnWriter.flush();
233 noticeWriter.flush();
234 }
236 /** Returns true if an error needs to be reported for a given
237 * source name and pos.
238 */
239 protected boolean shouldReport(JavaFileObject file, int pos) {
240 if (multipleErrors || file == null)
241 return true;
243 Pair<JavaFileObject,Integer> coords = new Pair<JavaFileObject,Integer>(file, pos);
244 boolean shouldReport = !recorded.contains(coords);
245 if (shouldReport)
246 recorded.add(coords);
247 return shouldReport;
248 }
250 /** Prompt user after an error.
251 */
252 public void prompt() {
253 if (promptOnError) {
254 System.err.println(getLocalizedString("resume.abort"));
255 char ch;
256 try {
257 while (true) {
258 switch (System.in.read()) {
259 case 'a': case 'A':
260 System.exit(-1);
261 return;
262 case 'r': case 'R':
263 return;
264 case 'x': case 'X':
265 throw new AssertionError("user abort");
266 default:
267 }
268 }
269 } catch (IOException e) {}
270 }
271 }
273 /** Print the faulty source code line and point to the error.
274 * @param pos Buffer index of the error position, must be on current line
275 */
276 private void printErrLine(int pos, PrintWriter writer) {
277 String line = (source == null ? null : source.getLine(pos));
278 if (line == null)
279 return;
280 int col = source.getColumnNumber(pos, false);
282 printLines(writer, line);
283 for (int i = 0; i < col - 1; i++) {
284 writer.print((line.charAt(i) == '\t') ? "\t" : " ");
285 }
286 writer.println("^");
287 writer.flush();
288 }
290 /** Print the text of a message, translating newlines appropriately
291 * for the platform.
292 */
293 public static void printLines(PrintWriter writer, String msg) {
294 int nl;
295 while ((nl = msg.indexOf('\n')) != -1) {
296 writer.println(msg.substring(0, nl));
297 msg = msg.substring(nl+1);
298 }
299 if (msg.length() != 0) writer.println(msg);
300 }
302 protected void directError(String key, Object... args) {
303 printLines(errWriter, getLocalizedString(key, args));
304 errWriter.flush();
305 }
307 /** Report a warning that cannot be suppressed.
308 * @param pos The source position at which to report the warning.
309 * @param key The key for the localized warning message.
310 * @param args Fields of the warning message.
311 */
312 public void strictWarning(DiagnosticPosition pos, String key, Object ... args) {
313 writeDiagnostic(diags.warning(source, pos, key, args));
314 nwarnings++;
315 }
317 /**
318 * Common diagnostic handling.
319 * The diagnostic is counted, and depending on the options and how many diagnostics have been
320 * reported so far, the diagnostic may be handed off to writeDiagnostic.
321 */
322 public void report(JCDiagnostic diagnostic) {
323 if (expectDiagKeys != null)
324 expectDiagKeys.remove(diagnostic.getCode());
326 switch (diagnostic.getType()) {
327 case FRAGMENT:
328 throw new IllegalArgumentException();
330 case NOTE:
331 // Print out notes only when we are permitted to report warnings
332 // Notes are only generated at the end of a compilation, so should be small
333 // in number.
334 if ((emitWarnings || diagnostic.isMandatory()) && !suppressNotes) {
335 writeDiagnostic(diagnostic);
336 }
337 break;
339 case WARNING:
340 if (emitWarnings || diagnostic.isMandatory()) {
341 if (nwarnings < MaxWarnings) {
342 writeDiagnostic(diagnostic);
343 nwarnings++;
344 }
345 }
346 break;
348 case ERROR:
349 if (nerrors < MaxErrors
350 && shouldReport(diagnostic.getSource(), diagnostic.getIntPosition())) {
351 writeDiagnostic(diagnostic);
352 nerrors++;
353 }
354 break;
355 }
356 }
358 /**
359 * Write out a diagnostic.
360 */
361 protected void writeDiagnostic(JCDiagnostic diag) {
362 if (diagListener != null) {
363 try {
364 diagListener.report(diag);
365 return;
366 }
367 catch (Throwable t) {
368 throw new ClientCodeException(t);
369 }
370 }
372 PrintWriter writer = getWriterForDiagnosticType(diag.getType());
374 printLines(writer, diagFormatter.format(diag, messages.getCurrentLocale()));
376 if (promptOnError) {
377 switch (diag.getType()) {
378 case ERROR:
379 case WARNING:
380 prompt();
381 }
382 }
384 if (dumpOnError)
385 new RuntimeException().printStackTrace(writer);
387 writer.flush();
388 }
390 @Deprecated
391 protected PrintWriter getWriterForDiagnosticType(DiagnosticType dt) {
392 switch (dt) {
393 case FRAGMENT:
394 throw new IllegalArgumentException();
396 case NOTE:
397 return noticeWriter;
399 case WARNING:
400 return warnWriter;
402 case ERROR:
403 return errWriter;
405 default:
406 throw new Error();
407 }
408 }
410 /** Find a localized string in the resource bundle.
411 * @param key The key for the localized string.
412 * @param args Fields to substitute into the string.
413 */
414 public static String getLocalizedString(String key, Object ... args) {
415 return JavacMessages.getDefaultLocalizedString("compiler.misc." + key, args);
416 }
418 /***************************************************************************
419 * raw error messages without internationalization; used for experimentation
420 * and quick prototyping
421 ***************************************************************************/
423 /** print an error or warning message:
424 */
425 private void printRawError(int pos, String msg) {
426 if (source == null || pos == Position.NOPOS) {
427 printLines(errWriter, "error: " + msg);
428 } else {
429 int line = source.getLineNumber(pos);
430 JavaFileObject file = source.getFile();
431 if (file != null)
432 printLines(errWriter,
433 file.getName() + ":" +
434 line + ": " + msg);
435 printErrLine(pos, errWriter);
436 }
437 errWriter.flush();
438 }
440 /** report an error:
441 */
442 public void rawError(int pos, String msg) {
443 if (nerrors < MaxErrors && shouldReport(currentSourceFile(), pos)) {
444 printRawError(pos, msg);
445 prompt();
446 nerrors++;
447 }
448 errWriter.flush();
449 }
451 /** report a warning:
452 */
453 public void rawWarning(int pos, String msg) {
454 if (nwarnings < MaxWarnings && emitWarnings) {
455 printRawError(pos, "warning: " + msg);
456 }
457 prompt();
458 nwarnings++;
459 errWriter.flush();
460 }
462 public static String format(String fmt, Object... args) {
463 return String.format((java.util.Locale)null, fmt, args);
464 }
466 }