duke@1: /* jjg@909: * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved. duke@1: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. duke@1: * duke@1: * This code is free software; you can redistribute it and/or modify it duke@1: * under the terms of the GNU General Public License version 2 only, as ohair@554: * published by the Free Software Foundation. Oracle designates this duke@1: * particular file as subject to the "Classpath" exception as provided ohair@554: * by Oracle in the LICENSE file that accompanied this code. duke@1: * duke@1: * This code is distributed in the hope that it will be useful, but WITHOUT duke@1: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or duke@1: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License duke@1: * version 2 for more details (a copy is included in the LICENSE file that duke@1: * accompanied this code). duke@1: * duke@1: * You should have received a copy of the GNU General Public License version duke@1: * 2 along with this work; if not, write to the Free Software Foundation, duke@1: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. duke@1: * ohair@554: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA ohair@554: * or visit www.oracle.com if you need additional information or have any ohair@554: * questions. duke@1: */ duke@1: duke@1: package com.sun.tools.javac.util; duke@1: jjg@1136: import com.sun.tools.javac.main.Main; duke@1: import java.io.*; jjg@194: import java.util.Arrays; jjg@664: import java.util.EnumSet; duke@1: import java.util.HashSet; duke@1: import java.util.Map; jjg@664: import java.util.Queue; duke@1: import java.util.Set; duke@1: import javax.tools.DiagnosticListener; duke@1: import javax.tools.JavaFileObject; jjg@50: jjg@700: import com.sun.tools.javac.api.DiagnosticFormatter; jjg@700: import com.sun.tools.javac.main.OptionName; ksrini@1138: import com.sun.tools.javac.parser.EndPosTable; duke@1: import com.sun.tools.javac.tree.JCTree; duke@1: import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; duke@1: import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType; duke@1: jjg@700: import static com.sun.tools.javac.main.OptionName.*; jjg@700: duke@1: /** A class for error logs. Reports errors and warnings, and duke@1: * keeps track of error numbers and positions. duke@1: * jjg@581: *

This is NOT part of any supported API. jjg@581: * If you write code that depends on this, you do so at your own risk. duke@1: * This code and its internal interfaces are subject to change or duke@1: * deletion without notice. duke@1: */ jjg@73: public class Log extends AbstractLog { duke@1: /** The context key for the log. */ duke@1: public static final Context.Key logKey duke@1: = new Context.Key(); duke@1: duke@1: /** The context key for the output PrintWriter. */ duke@1: public static final Context.Key outKey = duke@1: new Context.Key(); duke@1: jjg@1136: /* TODO: Should unify this with prefix handling in JCDiagnostic.Factory. */ jjg@1136: public enum PrefixKind { jjg@1136: JAVAC("javac."), jjg@1136: COMPILER_MISC("compiler.misc."); jjg@1136: PrefixKind(String v) { jjg@1136: value = v; jjg@1136: } jjg@1136: public String key(String k) { jjg@1136: return value + k; jjg@1136: } jjg@1136: final String value; jjg@1136: } jjg@1136: jjg@1135: public enum WriterKind { NOTICE, WARNING, ERROR }; duke@1: jjg@1135: protected PrintWriter errWriter; duke@1: jjg@1135: protected PrintWriter warnWriter; jjg@1135: jjg@1135: protected PrintWriter noticeWriter; duke@1: duke@1: /** The maximum number of errors/warnings that are reported. duke@1: */ jjg@1135: protected int MaxErrors; jjg@1135: protected int MaxWarnings; duke@1: duke@1: /** Switch: prompt user on each error. duke@1: */ duke@1: public boolean promptOnError; duke@1: duke@1: /** Switch: emit warning messages. duke@1: */ duke@1: public boolean emitWarnings; duke@1: jjg@376: /** Switch: suppress note messages. jjg@376: */ jjg@376: public boolean suppressNotes; jjg@376: duke@1: /** Print stack trace on errors? duke@1: */ duke@1: public boolean dumpOnError; duke@1: duke@1: /** Print multiple errors for same source locations. duke@1: */ duke@1: public boolean multipleErrors; duke@1: duke@1: /** duke@1: * Diagnostic listener, if provided through programmatic duke@1: * interface to javac (JSR 199). duke@1: */ duke@1: protected DiagnosticListener diagListener; jjg@73: duke@1: /** mcimadamore@221: * Formatter for diagnostics. duke@1: */ mcimadamore@83: private DiagnosticFormatter diagFormatter; duke@1: mcimadamore@136: /** mcimadamore@221: * Keys for expected diagnostics. jjg@194: */ jjg@194: public Set expectDiagKeys; jjg@194: jjg@194: /** mcimadamore@221: * JavacMessages object used for localization. mcimadamore@136: */ mcimadamore@136: private JavacMessages messages; mcimadamore@136: jjg@664: /** jjg@664: * Deferred diagnostics jjg@664: */ jjg@664: public boolean deferDiagnostics; jjg@664: public Queue deferredDiagnostics = new ListBuffer(); jjg@664: duke@1: /** Construct a log with given I/O redirections. duke@1: */ duke@1: @Deprecated duke@1: protected Log(Context context, PrintWriter errWriter, PrintWriter warnWriter, PrintWriter noticeWriter) { jjg@73: super(JCDiagnostic.Factory.instance(context)); duke@1: context.put(logKey, this); duke@1: this.errWriter = errWriter; duke@1: this.warnWriter = warnWriter; duke@1: this.noticeWriter = noticeWriter; duke@1: duke@1: @SuppressWarnings("unchecked") // FIXME jjg@194: DiagnosticListener dl = duke@1: context.get(DiagnosticListener.class); jjg@194: this.diagListener = dl; jjg@194: jjg@1135: messages = JavacMessages.instance(context); jjg@1136: messages.add(Main.javacBundleName); jjg@1135: jjg@1135: final Options options = Options.instance(context); jjg@1135: initOptions(options); jjg@1135: options.addListener(new Runnable() { jjg@1135: public void run() { jjg@1135: initOptions(options); jjg@1135: } jjg@1135: }); duke@1: } duke@1: // where jjg@1135: private void initOptions(Options options) { jjg@1135: this.dumpOnError = options.isSet(DOE); jjg@1135: this.promptOnError = options.isSet(PROMPT); jjg@1135: this.emitWarnings = options.isUnset(XLINT_CUSTOM, "none"); jjg@1135: this.suppressNotes = options.isSet("suppressNotes"); jjg@1135: this.MaxErrors = getIntOption(options, XMAXERRS, getDefaultMaxErrors()); jjg@1135: this.MaxWarnings = getIntOption(options, XMAXWARNS, getDefaultMaxWarnings()); jjg@1135: jjg@1135: boolean rawDiagnostics = options.isSet("rawDiagnostics"); jjg@1135: this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(options) : jjg@1135: new BasicDiagnosticFormatter(options, messages); jjg@1135: jjg@1135: String ek = options.get("expectKeys"); jjg@1135: if (ek != null) jjg@1135: expectDiagKeys = new HashSet(Arrays.asList(ek.split(", *"))); jjg@1135: } jjg@1135: jjg@700: private int getIntOption(Options options, OptionName optionName, int defaultValue) { duke@1: String s = options.get(optionName); duke@1: try { jjg@464: if (s != null) { jjg@464: int n = Integer.parseInt(s); jjg@464: return (n <= 0 ? Integer.MAX_VALUE : n); jjg@464: } duke@1: } catch (NumberFormatException e) { duke@1: // silently ignore ill-formed numbers duke@1: } duke@1: return defaultValue; duke@1: } duke@1: jjg@584: /** Default value for -Xmaxerrs. jjg@584: */ jjg@584: protected int getDefaultMaxErrors() { jjg@584: return 100; jjg@584: } jjg@584: jjg@584: /** Default value for -Xmaxwarns. jjg@584: */ jjg@584: protected int getDefaultMaxWarnings() { jjg@584: return 100; jjg@584: } jjg@584: duke@1: /** The default writer for diagnostics duke@1: */ jjg@1135: static PrintWriter defaultWriter(Context context) { duke@1: PrintWriter result = context.get(outKey); duke@1: if (result == null) duke@1: context.put(outKey, result = new PrintWriter(System.err)); duke@1: return result; duke@1: } duke@1: duke@1: /** Construct a log with default settings. duke@1: */ duke@1: protected Log(Context context) { duke@1: this(context, defaultWriter(context)); duke@1: } duke@1: duke@1: /** Construct a log with all output redirected. duke@1: */ duke@1: protected Log(Context context, PrintWriter defaultWriter) { duke@1: this(context, defaultWriter, defaultWriter, defaultWriter); duke@1: } duke@1: duke@1: /** Get the Log instance for this context. */ duke@1: public static Log instance(Context context) { duke@1: Log instance = context.get(logKey); duke@1: if (instance == null) duke@1: instance = new Log(context); duke@1: return instance; duke@1: } duke@1: duke@1: /** The number of errors encountered so far. duke@1: */ duke@1: public int nerrors = 0; duke@1: duke@1: /** The number of warnings encountered so far. duke@1: */ duke@1: public int nwarnings = 0; duke@1: duke@1: /** A set of all errors generated so far. This is used to avoid printing an duke@1: * error message more than once. For each error, a pair consisting of the duke@1: * source file name and source code position of the error is added to the set. duke@1: */ duke@1: private Set> recorded = new HashSet>(); duke@1: duke@1: public boolean hasDiagnosticListener() { duke@1: return diagListener != null; duke@1: } duke@1: ksrini@1138: public void setEndPosTable(JavaFileObject name, EndPosTable endPosTable) { jjg@73: name.getClass(); // null check ksrini@1138: getSource(name).setEndPosTable(endPosTable); duke@1: } duke@1: mcimadamore@168: /** Return current sourcefile. duke@1: */ mcimadamore@168: public JavaFileObject currentSourceFile() { duke@1: return source == null ? null : source.getFile(); duke@1: } duke@1: mcimadamore@221: /** Get the current diagnostic formatter. mcimadamore@221: */ mcimadamore@221: public DiagnosticFormatter getDiagnosticFormatter() { mcimadamore@221: return diagFormatter; mcimadamore@221: } mcimadamore@221: mcimadamore@221: /** Set the current diagnostic formatter. mcimadamore@221: */ mcimadamore@221: public void setDiagnosticFormatter(DiagnosticFormatter diagFormatter) { mcimadamore@221: this.diagFormatter = diagFormatter; mcimadamore@221: } mcimadamore@221: jjg@1135: public PrintWriter getWriter(WriterKind kind) { jjg@1135: switch (kind) { jjg@1135: case NOTICE: return noticeWriter; jjg@1135: case WARNING: return warnWriter; jjg@1135: case ERROR: return errWriter; jjg@1135: default: throw new IllegalArgumentException(); jjg@1135: } jjg@1135: } jjg@1135: jjg@1135: public void setWriter(WriterKind kind, PrintWriter pw) { jjg@1135: pw.getClass(); jjg@1135: switch (kind) { jjg@1135: case NOTICE: noticeWriter = pw; break; jjg@1135: case WARNING: warnWriter = pw; break; jjg@1135: case ERROR: errWriter = pw; break; jjg@1135: default: throw new IllegalArgumentException(); jjg@1135: } jjg@1135: } jjg@1135: jjg@1135: public void setWriters(PrintWriter pw) { jjg@1135: pw.getClass(); jjg@1135: noticeWriter = warnWriter = errWriter = pw; jjg@1135: } jjg@1135: duke@1: /** Flush the logs duke@1: */ duke@1: public void flush() { duke@1: errWriter.flush(); duke@1: warnWriter.flush(); duke@1: noticeWriter.flush(); duke@1: } duke@1: jjg@1135: public void flush(WriterKind kind) { jjg@1135: getWriter(kind).flush(); jjg@1135: } jjg@1135: duke@1: /** Returns true if an error needs to be reported for a given duke@1: * source name and pos. duke@1: */ duke@1: protected boolean shouldReport(JavaFileObject file, int pos) { duke@1: if (multipleErrors || file == null) duke@1: return true; duke@1: duke@1: Pair coords = new Pair(file, pos); duke@1: boolean shouldReport = !recorded.contains(coords); duke@1: if (shouldReport) duke@1: recorded.add(coords); duke@1: return shouldReport; duke@1: } duke@1: duke@1: /** Prompt user after an error. duke@1: */ duke@1: public void prompt() { duke@1: if (promptOnError) { jjg@604: System.err.println(localize("resume.abort")); duke@1: try { duke@1: while (true) { duke@1: switch (System.in.read()) { duke@1: case 'a': case 'A': duke@1: System.exit(-1); duke@1: return; duke@1: case 'r': case 'R': duke@1: return; duke@1: case 'x': case 'X': duke@1: throw new AssertionError("user abort"); duke@1: default: duke@1: } duke@1: } duke@1: } catch (IOException e) {} duke@1: } duke@1: } duke@1: duke@1: /** Print the faulty source code line and point to the error. duke@1: * @param pos Buffer index of the error position, must be on current line duke@1: */ duke@1: private void printErrLine(int pos, PrintWriter writer) { jjg@73: String line = (source == null ? null : source.getLine(pos)); jjg@73: if (line == null) duke@1: return; mcimadamore@100: int col = source.getColumnNumber(pos, false); duke@1: jjg@1136: printRawLines(writer, line); jjg@73: for (int i = 0; i < col - 1; i++) { jjg@73: writer.print((line.charAt(i) == '\t') ? "\t" : " "); duke@1: } duke@1: writer.println("^"); duke@1: writer.flush(); duke@1: } duke@1: jjg@1136: public void printNewline() { jjg@1136: noticeWriter.println(); jjg@1136: } jjg@1136: jjg@1136: public void printNewline(WriterKind wk) { jjg@1136: getWriter(wk).println(); jjg@1136: } jjg@1136: jjg@1136: public void printLines(String key, Object... args) { jjg@1136: printRawLines(noticeWriter, localize(key, args)); jjg@1136: } jjg@1136: jjg@1136: public void printLines(PrefixKind pk, String key, Object... args) { jjg@1136: printRawLines(noticeWriter, localize(pk, key, args)); jjg@1136: } jjg@1136: jjg@1136: public void printLines(WriterKind wk, String key, Object... args) { jjg@1136: printRawLines(getWriter(wk), localize(key, args)); jjg@1136: } jjg@1136: jjg@1136: public void printLines(WriterKind wk, PrefixKind pk, String key, Object... args) { jjg@1136: printRawLines(getWriter(wk), localize(pk, key, args)); jjg@1135: } jjg@1135: jjg@1135: /** Print the text of a message, translating newlines appropriately jjg@1135: * for the platform. jjg@1135: */ jjg@1136: public void printRawLines(String msg) { jjg@1136: printRawLines(noticeWriter, msg); jjg@1136: } jjg@1136: jjg@1136: /** Print the text of a message, translating newlines appropriately jjg@1136: * for the platform. jjg@1136: */ jjg@1136: public void printRawLines(WriterKind kind, String msg) { jjg@1136: printRawLines(getWriter(kind), msg); jjg@1136: } jjg@1136: jjg@1136: /** Print the text of a message, translating newlines appropriately jjg@1136: * for the platform. jjg@1136: */ jjg@1136: public static void printRawLines(PrintWriter writer, String msg) { duke@1: int nl; duke@1: while ((nl = msg.indexOf('\n')) != -1) { duke@1: writer.println(msg.substring(0, nl)); duke@1: msg = msg.substring(nl+1); duke@1: } duke@1: if (msg.length() != 0) writer.println(msg); duke@1: } duke@1: jjg@909: /** jjg@909: * Print the localized text of a "verbose" message to the jjg@909: * noticeWriter stream. jjg@909: */ jjg@909: public void printVerbose(String key, Object... args) { jjg@1136: printRawLines(noticeWriter, localize("verbose." + key, args)); jjg@909: } jjg@909: jjg@73: protected void directError(String key, Object... args) { jjg@1136: printRawLines(errWriter, localize(key, args)); jjg@73: errWriter.flush(); duke@1: } duke@1: duke@1: /** Report a warning that cannot be suppressed. duke@1: * @param pos The source position at which to report the warning. duke@1: * @param key The key for the localized warning message. duke@1: * @param args Fields of the warning message. duke@1: */ duke@1: public void strictWarning(DiagnosticPosition pos, String key, Object ... args) { duke@1: writeDiagnostic(diags.warning(source, pos, key, args)); duke@1: nwarnings++; duke@1: } duke@1: jjg@664: /** Report all deferred diagnostics, and clear the deferDiagnostics flag. */ jjg@664: public void reportDeferredDiagnostics() { jjg@664: reportDeferredDiagnostics(EnumSet.allOf(JCDiagnostic.Kind.class)); jjg@664: } jjg@664: jjg@664: /** Report selected deferred diagnostics, and clear the deferDiagnostics flag. */ jjg@664: public void reportDeferredDiagnostics(Set kinds) { jjg@664: deferDiagnostics = false; jjg@664: JCDiagnostic d; jjg@664: while ((d = deferredDiagnostics.poll()) != null) { jjg@664: if (kinds.contains(d.getKind())) jjg@664: report(d); jjg@664: } jjg@664: } jjg@664: duke@1: /** duke@1: * Common diagnostic handling. duke@1: * The diagnostic is counted, and depending on the options and how many diagnostics have been duke@1: * reported so far, the diagnostic may be handed off to writeDiagnostic. duke@1: */ duke@1: public void report(JCDiagnostic diagnostic) { jjg@664: if (deferDiagnostics) { jjg@664: deferredDiagnostics.add(diagnostic); jjg@664: return; jjg@664: } jjg@664: jjg@194: if (expectDiagKeys != null) jjg@194: expectDiagKeys.remove(diagnostic.getCode()); jjg@194: duke@1: switch (diagnostic.getType()) { duke@1: case FRAGMENT: duke@1: throw new IllegalArgumentException(); duke@1: duke@1: case NOTE: duke@1: // Print out notes only when we are permitted to report warnings duke@1: // Notes are only generated at the end of a compilation, so should be small duke@1: // in number. jjg@376: if ((emitWarnings || diagnostic.isMandatory()) && !suppressNotes) { duke@1: writeDiagnostic(diagnostic); duke@1: } duke@1: break; duke@1: duke@1: case WARNING: duke@1: if (emitWarnings || diagnostic.isMandatory()) { duke@1: if (nwarnings < MaxWarnings) { duke@1: writeDiagnostic(diagnostic); duke@1: nwarnings++; duke@1: } duke@1: } duke@1: break; duke@1: duke@1: case ERROR: duke@1: if (nerrors < MaxErrors duke@1: && shouldReport(diagnostic.getSource(), diagnostic.getIntPosition())) { duke@1: writeDiagnostic(diagnostic); duke@1: nerrors++; duke@1: } duke@1: break; duke@1: } duke@1: } duke@1: duke@1: /** duke@1: * Write out a diagnostic. duke@1: */ duke@1: protected void writeDiagnostic(JCDiagnostic diag) { duke@1: if (diagListener != null) { jjg@946: diagListener.report(diag); jjg@946: return; duke@1: } duke@1: duke@1: PrintWriter writer = getWriterForDiagnosticType(diag.getType()); duke@1: jjg@1136: printRawLines(writer, diagFormatter.format(diag, messages.getCurrentLocale())); duke@1: duke@1: if (promptOnError) { duke@1: switch (diag.getType()) { duke@1: case ERROR: duke@1: case WARNING: duke@1: prompt(); duke@1: } duke@1: } duke@1: duke@1: if (dumpOnError) duke@1: new RuntimeException().printStackTrace(writer); duke@1: duke@1: writer.flush(); duke@1: } duke@1: duke@1: @Deprecated duke@1: protected PrintWriter getWriterForDiagnosticType(DiagnosticType dt) { duke@1: switch (dt) { duke@1: case FRAGMENT: duke@1: throw new IllegalArgumentException(); duke@1: duke@1: case NOTE: duke@1: return noticeWriter; duke@1: duke@1: case WARNING: duke@1: return warnWriter; duke@1: duke@1: case ERROR: duke@1: return errWriter; duke@1: duke@1: default: duke@1: throw new Error(); duke@1: } duke@1: } duke@1: duke@1: /** Find a localized string in the resource bundle. jjg@604: * Because this method is static, it ignores the locale. jjg@604: * Use localize(key, args) when possible. duke@1: * @param key The key for the localized string. duke@1: * @param args Fields to substitute into the string. duke@1: */ duke@1: public static String getLocalizedString(String key, Object ... args) { jjg@1136: return JavacMessages.getDefaultLocalizedString(PrefixKind.COMPILER_MISC.key(key), args); duke@1: } duke@1: jjg@604: /** Find a localized string in the resource bundle. jjg@604: * @param key The key for the localized string. jjg@604: * @param args Fields to substitute into the string. jjg@604: */ jjg@604: public String localize(String key, Object... args) { jjg@1136: return localize(PrefixKind.COMPILER_MISC, key, args); jjg@604: } jjg@604: jjg@1136: /** Find a localized string in the resource bundle. jjg@1136: * @param key The key for the localized string. jjg@1136: * @param args Fields to substitute into the string. jjg@1136: */ jjg@1136: public String localize(PrefixKind pk, String key, Object... args) { jjg@1136: if (useRawMessages) jjg@1136: return pk.key(key); jjg@1136: else jjg@1136: return messages.getLocalizedString(pk.key(key), args); jjg@1136: } jjg@1136: // where jjg@1136: // backdoor hook for testing, should transition to use -XDrawDiagnostics jjg@1136: private static boolean useRawMessages = false; jjg@1136: duke@1: /*************************************************************************** duke@1: * raw error messages without internationalization; used for experimentation duke@1: * and quick prototyping duke@1: ***************************************************************************/ duke@1: jjg@73: /** print an error or warning message: jjg@73: */ duke@1: private void printRawError(int pos, String msg) { jjg@73: if (source == null || pos == Position.NOPOS) { jjg@1136: printRawLines(errWriter, "error: " + msg); duke@1: } else { jjg@73: int line = source.getLineNumber(pos); mcimadamore@168: JavaFileObject file = source.getFile(); duke@1: if (file != null) jjg@1136: printRawLines(errWriter, jjg@415: file.getName() + ":" + duke@1: line + ": " + msg); duke@1: printErrLine(pos, errWriter); duke@1: } duke@1: errWriter.flush(); duke@1: } duke@1: jjg@73: /** report an error: jjg@73: */ duke@1: public void rawError(int pos, String msg) { mcimadamore@168: if (nerrors < MaxErrors && shouldReport(currentSourceFile(), pos)) { duke@1: printRawError(pos, msg); duke@1: prompt(); duke@1: nerrors++; duke@1: } duke@1: errWriter.flush(); duke@1: } duke@1: jjg@73: /** report a warning: jjg@73: */ duke@1: public void rawWarning(int pos, String msg) { duke@1: if (nwarnings < MaxWarnings && emitWarnings) { duke@1: printRawError(pos, "warning: " + msg); duke@1: } duke@1: prompt(); duke@1: nwarnings++; duke@1: errWriter.flush(); duke@1: } duke@1: duke@1: public static String format(String fmt, Object... args) { duke@1: return String.format((java.util.Locale)null, fmt, args); duke@1: } duke@1: duke@1: }