Wed, 23 Sep 2009 18:48:13 -0700
6410637: Make decision on deprecated methods in DefaultFileManager and BaseFileObject.
6747645: ZipFileObject.getName is incorrectly deprecated
6885123: JavaFileObject getName issues
Reviewed-by: mcimadamore
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) return Integer.parseInt(s);
149 } catch (NumberFormatException e) {
150 // silently ignore ill-formed numbers
151 }
152 return defaultValue;
153 }
155 /** The default writer for diagnostics
156 */
157 static final PrintWriter defaultWriter(Context context) {
158 PrintWriter result = context.get(outKey);
159 if (result == null)
160 context.put(outKey, result = new PrintWriter(System.err));
161 return result;
162 }
164 /** Construct a log with default settings.
165 */
166 protected Log(Context context) {
167 this(context, defaultWriter(context));
168 }
170 /** Construct a log with all output redirected.
171 */
172 protected Log(Context context, PrintWriter defaultWriter) {
173 this(context, defaultWriter, defaultWriter, defaultWriter);
174 }
176 /** Get the Log instance for this context. */
177 public static Log instance(Context context) {
178 Log instance = context.get(logKey);
179 if (instance == null)
180 instance = new Log(context);
181 return instance;
182 }
184 /** The number of errors encountered so far.
185 */
186 public int nerrors = 0;
188 /** The number of warnings encountered so far.
189 */
190 public int nwarnings = 0;
192 /** A set of all errors generated so far. This is used to avoid printing an
193 * error message more than once. For each error, a pair consisting of the
194 * source file name and source code position of the error is added to the set.
195 */
196 private Set<Pair<JavaFileObject, Integer>> recorded = new HashSet<Pair<JavaFileObject,Integer>>();
198 public boolean hasDiagnosticListener() {
199 return diagListener != null;
200 }
202 public void setEndPosTable(JavaFileObject name, Map<JCTree, Integer> table) {
203 name.getClass(); // null check
204 getSource(name).setEndPosTable(table);
205 }
207 /** Return current sourcefile.
208 */
209 public JavaFileObject currentSourceFile() {
210 return source == null ? null : source.getFile();
211 }
213 /** Get the current diagnostic formatter.
214 */
215 public DiagnosticFormatter<JCDiagnostic> getDiagnosticFormatter() {
216 return diagFormatter;
217 }
219 /** Set the current diagnostic formatter.
220 */
221 public void setDiagnosticFormatter(DiagnosticFormatter<JCDiagnostic> diagFormatter) {
222 this.diagFormatter = diagFormatter;
223 }
225 /** Flush the logs
226 */
227 public void flush() {
228 errWriter.flush();
229 warnWriter.flush();
230 noticeWriter.flush();
231 }
233 /** Returns true if an error needs to be reported for a given
234 * source name and pos.
235 */
236 protected boolean shouldReport(JavaFileObject file, int pos) {
237 if (multipleErrors || file == null)
238 return true;
240 Pair<JavaFileObject,Integer> coords = new Pair<JavaFileObject,Integer>(file, pos);
241 boolean shouldReport = !recorded.contains(coords);
242 if (shouldReport)
243 recorded.add(coords);
244 return shouldReport;
245 }
247 /** Prompt user after an error.
248 */
249 public void prompt() {
250 if (promptOnError) {
251 System.err.println(getLocalizedString("resume.abort"));
252 char ch;
253 try {
254 while (true) {
255 switch (System.in.read()) {
256 case 'a': case 'A':
257 System.exit(-1);
258 return;
259 case 'r': case 'R':
260 return;
261 case 'x': case 'X':
262 throw new AssertionError("user abort");
263 default:
264 }
265 }
266 } catch (IOException e) {}
267 }
268 }
270 /** Print the faulty source code line and point to the error.
271 * @param pos Buffer index of the error position, must be on current line
272 */
273 private void printErrLine(int pos, PrintWriter writer) {
274 String line = (source == null ? null : source.getLine(pos));
275 if (line == null)
276 return;
277 int col = source.getColumnNumber(pos, false);
279 printLines(writer, line);
280 for (int i = 0; i < col - 1; i++) {
281 writer.print((line.charAt(i) == '\t') ? "\t" : " ");
282 }
283 writer.println("^");
284 writer.flush();
285 }
287 /** Print the text of a message, translating newlines appropriately
288 * for the platform.
289 */
290 public static void printLines(PrintWriter writer, String msg) {
291 int nl;
292 while ((nl = msg.indexOf('\n')) != -1) {
293 writer.println(msg.substring(0, nl));
294 msg = msg.substring(nl+1);
295 }
296 if (msg.length() != 0) writer.println(msg);
297 }
299 protected void directError(String key, Object... args) {
300 printLines(errWriter, getLocalizedString(key, args));
301 errWriter.flush();
302 }
304 /** Report a warning that cannot be suppressed.
305 * @param pos The source position at which to report the warning.
306 * @param key The key for the localized warning message.
307 * @param args Fields of the warning message.
308 */
309 public void strictWarning(DiagnosticPosition pos, String key, Object ... args) {
310 writeDiagnostic(diags.warning(source, pos, key, args));
311 nwarnings++;
312 }
314 /**
315 * Common diagnostic handling.
316 * The diagnostic is counted, and depending on the options and how many diagnostics have been
317 * reported so far, the diagnostic may be handed off to writeDiagnostic.
318 */
319 public void report(JCDiagnostic diagnostic) {
320 if (expectDiagKeys != null)
321 expectDiagKeys.remove(diagnostic.getCode());
323 switch (diagnostic.getType()) {
324 case FRAGMENT:
325 throw new IllegalArgumentException();
327 case NOTE:
328 // Print out notes only when we are permitted to report warnings
329 // Notes are only generated at the end of a compilation, so should be small
330 // in number.
331 if ((emitWarnings || diagnostic.isMandatory()) && !suppressNotes) {
332 writeDiagnostic(diagnostic);
333 }
334 break;
336 case WARNING:
337 if (emitWarnings || diagnostic.isMandatory()) {
338 if (nwarnings < MaxWarnings) {
339 writeDiagnostic(diagnostic);
340 nwarnings++;
341 }
342 }
343 break;
345 case ERROR:
346 if (nerrors < MaxErrors
347 && shouldReport(diagnostic.getSource(), diagnostic.getIntPosition())) {
348 writeDiagnostic(diagnostic);
349 nerrors++;
350 }
351 break;
352 }
353 }
355 /**
356 * Write out a diagnostic.
357 */
358 protected void writeDiagnostic(JCDiagnostic diag) {
359 if (diagListener != null) {
360 try {
361 diagListener.report(diag);
362 return;
363 }
364 catch (Throwable t) {
365 throw new ClientCodeException(t);
366 }
367 }
369 PrintWriter writer = getWriterForDiagnosticType(diag.getType());
371 printLines(writer, diagFormatter.format(diag, messages.getCurrentLocale()));
373 if (promptOnError) {
374 switch (diag.getType()) {
375 case ERROR:
376 case WARNING:
377 prompt();
378 }
379 }
381 if (dumpOnError)
382 new RuntimeException().printStackTrace(writer);
384 writer.flush();
385 }
387 @Deprecated
388 protected PrintWriter getWriterForDiagnosticType(DiagnosticType dt) {
389 switch (dt) {
390 case FRAGMENT:
391 throw new IllegalArgumentException();
393 case NOTE:
394 return noticeWriter;
396 case WARNING:
397 return warnWriter;
399 case ERROR:
400 return errWriter;
402 default:
403 throw new Error();
404 }
405 }
407 /** Find a localized string in the resource bundle.
408 * @param key The key for the localized string.
409 * @param args Fields to substitute into the string.
410 */
411 public static String getLocalizedString(String key, Object ... args) {
412 return JavacMessages.getDefaultLocalizedString("compiler.misc." + key, args);
413 }
415 /***************************************************************************
416 * raw error messages without internationalization; used for experimentation
417 * and quick prototyping
418 ***************************************************************************/
420 /** print an error or warning message:
421 */
422 private void printRawError(int pos, String msg) {
423 if (source == null || pos == Position.NOPOS) {
424 printLines(errWriter, "error: " + msg);
425 } else {
426 int line = source.getLineNumber(pos);
427 JavaFileObject file = source.getFile();
428 if (file != null)
429 printLines(errWriter,
430 file.getName() + ":" +
431 line + ": " + msg);
432 printErrLine(pos, errWriter);
433 }
434 errWriter.flush();
435 }
437 /** report an error:
438 */
439 public void rawError(int pos, String msg) {
440 if (nerrors < MaxErrors && shouldReport(currentSourceFile(), pos)) {
441 printRawError(pos, msg);
442 prompt();
443 nerrors++;
444 }
445 errWriter.flush();
446 }
448 /** report a warning:
449 */
450 public void rawWarning(int pos, String msg) {
451 if (nwarnings < MaxWarnings && emitWarnings) {
452 printRawError(pos, "warning: " + msg);
453 }
454 prompt();
455 nwarnings++;
456 errWriter.flush();
457 }
459 public static String format(String fmt, Object... args) {
460 return String.format((java.util.Locale)null, fmt, args);
461 }
463 }