Mon, 28 Feb 2011 11:48:53 +0000
7015430: Incorrect thrown type determined for unchecked invocations
Summary: Thrown types do not get updated after 15.12.2.8, and do not get erased as per 15.12.2.6
Reviewed-by: jjg, dlsmith
1 /*
2 * Copyright (c) 1999, 2010, 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 }
333 /** Print the text of a message to the noticeWriter stream,
334 * translating newlines appropriately for the platform.
335 */
336 public void printNoteLines(String key, Object... args) {
337 printLines(noticeWriter, localize(key, args));
338 }
340 protected void directError(String key, Object... args) {
341 printErrLines(key, args);
342 errWriter.flush();
343 }
345 /** Report a warning that cannot be suppressed.
346 * @param pos The source position at which to report the warning.
347 * @param key The key for the localized warning message.
348 * @param args Fields of the warning message.
349 */
350 public void strictWarning(DiagnosticPosition pos, String key, Object ... args) {
351 writeDiagnostic(diags.warning(source, pos, key, args));
352 nwarnings++;
353 }
355 /** Report all deferred diagnostics, and clear the deferDiagnostics flag. */
356 public void reportDeferredDiagnostics() {
357 reportDeferredDiagnostics(EnumSet.allOf(JCDiagnostic.Kind.class));
358 }
360 /** Report selected deferred diagnostics, and clear the deferDiagnostics flag. */
361 public void reportDeferredDiagnostics(Set<JCDiagnostic.Kind> kinds) {
362 deferDiagnostics = false;
363 JCDiagnostic d;
364 while ((d = deferredDiagnostics.poll()) != null) {
365 if (kinds.contains(d.getKind()))
366 report(d);
367 }
368 }
370 /**
371 * Common diagnostic handling.
372 * The diagnostic is counted, and depending on the options and how many diagnostics have been
373 * reported so far, the diagnostic may be handed off to writeDiagnostic.
374 */
375 public void report(JCDiagnostic diagnostic) {
376 if (deferDiagnostics) {
377 deferredDiagnostics.add(diagnostic);
378 return;
379 }
381 if (expectDiagKeys != null)
382 expectDiagKeys.remove(diagnostic.getCode());
384 switch (diagnostic.getType()) {
385 case FRAGMENT:
386 throw new IllegalArgumentException();
388 case NOTE:
389 // Print out notes only when we are permitted to report warnings
390 // Notes are only generated at the end of a compilation, so should be small
391 // in number.
392 if ((emitWarnings || diagnostic.isMandatory()) && !suppressNotes) {
393 writeDiagnostic(diagnostic);
394 }
395 break;
397 case WARNING:
398 if (emitWarnings || diagnostic.isMandatory()) {
399 if (nwarnings < MaxWarnings) {
400 writeDiagnostic(diagnostic);
401 nwarnings++;
402 }
403 }
404 break;
406 case ERROR:
407 if (nerrors < MaxErrors
408 && shouldReport(diagnostic.getSource(), diagnostic.getIntPosition())) {
409 writeDiagnostic(diagnostic);
410 nerrors++;
411 }
412 break;
413 }
414 }
416 /**
417 * Write out a diagnostic.
418 */
419 protected void writeDiagnostic(JCDiagnostic diag) {
420 if (diagListener != null) {
421 try {
422 diagListener.report(diag);
423 return;
424 }
425 catch (Throwable t) {
426 throw new ClientCodeException(t);
427 }
428 }
430 PrintWriter writer = getWriterForDiagnosticType(diag.getType());
432 printLines(writer, diagFormatter.format(diag, messages.getCurrentLocale()));
434 if (promptOnError) {
435 switch (diag.getType()) {
436 case ERROR:
437 case WARNING:
438 prompt();
439 }
440 }
442 if (dumpOnError)
443 new RuntimeException().printStackTrace(writer);
445 writer.flush();
446 }
448 @Deprecated
449 protected PrintWriter getWriterForDiagnosticType(DiagnosticType dt) {
450 switch (dt) {
451 case FRAGMENT:
452 throw new IllegalArgumentException();
454 case NOTE:
455 return noticeWriter;
457 case WARNING:
458 return warnWriter;
460 case ERROR:
461 return errWriter;
463 default:
464 throw new Error();
465 }
466 }
468 /** Find a localized string in the resource bundle.
469 * Because this method is static, it ignores the locale.
470 * Use localize(key, args) when possible.
471 * @param key The key for the localized string.
472 * @param args Fields to substitute into the string.
473 */
474 public static String getLocalizedString(String key, Object ... args) {
475 return JavacMessages.getDefaultLocalizedString("compiler.misc." + key, args);
476 }
478 /** Find a localized string in the resource bundle.
479 * @param key The key for the localized string.
480 * @param args Fields to substitute into the string.
481 */
482 public String localize(String key, Object... args) {
483 return messages.getLocalizedString("compiler.misc." + key, args);
484 }
486 /***************************************************************************
487 * raw error messages without internationalization; used for experimentation
488 * and quick prototyping
489 ***************************************************************************/
491 /** print an error or warning message:
492 */
493 private void printRawError(int pos, String msg) {
494 if (source == null || pos == Position.NOPOS) {
495 printLines(errWriter, "error: " + msg);
496 } else {
497 int line = source.getLineNumber(pos);
498 JavaFileObject file = source.getFile();
499 if (file != null)
500 printLines(errWriter,
501 file.getName() + ":" +
502 line + ": " + msg);
503 printErrLine(pos, errWriter);
504 }
505 errWriter.flush();
506 }
508 /** report an error:
509 */
510 public void rawError(int pos, String msg) {
511 if (nerrors < MaxErrors && shouldReport(currentSourceFile(), pos)) {
512 printRawError(pos, msg);
513 prompt();
514 nerrors++;
515 }
516 errWriter.flush();
517 }
519 /** report a warning:
520 */
521 public void rawWarning(int pos, String msg) {
522 if (nwarnings < MaxWarnings && emitWarnings) {
523 printRawError(pos, "warning: " + msg);
524 }
525 prompt();
526 nwarnings++;
527 errWriter.flush();
528 }
530 public static String format(String fmt, Object... args) {
531 return String.format((java.util.Locale)null, fmt, args);
532 }
534 }