src/share/classes/com/sun/tools/javac/util/Log.java

Fri, 13 Feb 2009 11:57:33 +0000

author
mcimadamore
date
Fri, 13 Feb 2009 11:57:33 +0000
changeset 221
6ada6122dd4f
parent 194
d0b33fe8e710
child 229
03bcd66bd8e7
permissions
-rw-r--r--

6769027: Source line should be displayed immediately after the first diagnostic line
Summary: Added support for customizing diagnostic output via API/command line flags
Reviewed-by: jjg

     1 /*
     2  * Copyright 1999-2008 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     /** Print stack trace on errors?
    82      */
    83     public boolean dumpOnError;
    85     /** Print multiple errors for same source locations.
    86      */
    87     public boolean multipleErrors;
    89     /**
    90      * Diagnostic listener, if provided through programmatic
    91      * interface to javac (JSR 199).
    92      */
    93     protected DiagnosticListener<? super JavaFileObject> diagListener;
    95     /**
    96      * Formatter for diagnostics.
    97      */
    98     private DiagnosticFormatter<JCDiagnostic> diagFormatter;
   100     /**
   101      * Keys for expected diagnostics.
   102      */
   103     public Set<String> expectDiagKeys;
   105     /**
   106      * JavacMessages object used for localization.
   107      */
   108     private JavacMessages messages;
   110     /** Construct a log with given I/O redirections.
   111      */
   112     @Deprecated
   113     protected Log(Context context, PrintWriter errWriter, PrintWriter warnWriter, PrintWriter noticeWriter) {
   114         super(JCDiagnostic.Factory.instance(context));
   115         context.put(logKey, this);
   116         this.errWriter = errWriter;
   117         this.warnWriter = warnWriter;
   118         this.noticeWriter = noticeWriter;
   120         Options options = Options.instance(context);
   121         this.dumpOnError = options.get("-doe") != null;
   122         this.promptOnError = options.get("-prompt") != null;
   123         this.emitWarnings = options.get("-Xlint:none") == null;
   124         this.MaxErrors = getIntOption(options, "-Xmaxerrs", 100);
   125         this.MaxWarnings = getIntOption(options, "-Xmaxwarns", 100);
   127         boolean rawDiagnostics = options.get("rawDiagnostics") != null;
   128         messages = JavacMessages.instance(context);
   129         this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(options) :
   130                                               new BasicDiagnosticFormatter(options, messages);
   131         @SuppressWarnings("unchecked") // FIXME
   132         DiagnosticListener<? super JavaFileObject> dl =
   133             context.get(DiagnosticListener.class);
   134         this.diagListener = dl;
   136         String ek = options.get("expectKeys");
   137         if (ek != null)
   138             expectDiagKeys = new HashSet<String>(Arrays.asList(ek.split(", *")));
   139     }
   140     // where
   141         private int getIntOption(Options options, String optionName, int defaultValue) {
   142             String s = options.get(optionName);
   143             try {
   144                 if (s != null) return Integer.parseInt(s);
   145             } catch (NumberFormatException e) {
   146                 // silently ignore ill-formed numbers
   147             }
   148             return defaultValue;
   149         }
   151     /** The default writer for diagnostics
   152      */
   153     static final PrintWriter defaultWriter(Context context) {
   154         PrintWriter result = context.get(outKey);
   155         if (result == null)
   156             context.put(outKey, result = new PrintWriter(System.err));
   157         return result;
   158     }
   160     /** Construct a log with default settings.
   161      */
   162     protected Log(Context context) {
   163         this(context, defaultWriter(context));
   164     }
   166     /** Construct a log with all output redirected.
   167      */
   168     protected Log(Context context, PrintWriter defaultWriter) {
   169         this(context, defaultWriter, defaultWriter, defaultWriter);
   170     }
   172     /** Get the Log instance for this context. */
   173     public static Log instance(Context context) {
   174         Log instance = context.get(logKey);
   175         if (instance == null)
   176             instance = new Log(context);
   177         return instance;
   178     }
   180     /** The number of errors encountered so far.
   181      */
   182     public int nerrors = 0;
   184     /** The number of warnings encountered so far.
   185      */
   186     public int nwarnings = 0;
   188     /** A set of all errors generated so far. This is used to avoid printing an
   189      *  error message more than once. For each error, a pair consisting of the
   190      *  source file name and source code position of the error is added to the set.
   191      */
   192     private Set<Pair<JavaFileObject, Integer>> recorded = new HashSet<Pair<JavaFileObject,Integer>>();
   194     public boolean hasDiagnosticListener() {
   195         return diagListener != null;
   196     }
   198     public void setEndPosTable(JavaFileObject name, Map<JCTree, Integer> table) {
   199         name.getClass(); // null check
   200         getSource(name).setEndPosTable(table);
   201     }
   203     /** Return current sourcefile.
   204      */
   205     public JavaFileObject currentSourceFile() {
   206         return source == null ? null : source.getFile();
   207     }
   209     /** Get the current diagnostic formatter.
   210      */
   211     public DiagnosticFormatter<JCDiagnostic> getDiagnosticFormatter() {
   212         return diagFormatter;
   213     }
   215     /** Set the current diagnostic formatter.
   216      */
   217     public void setDiagnosticFormatter(DiagnosticFormatter<JCDiagnostic> diagFormatter) {
   218         this.diagFormatter = diagFormatter;
   219     }
   221     /** Flush the logs
   222      */
   223     public void flush() {
   224         errWriter.flush();
   225         warnWriter.flush();
   226         noticeWriter.flush();
   227     }
   229     /** Returns true if an error needs to be reported for a given
   230      * source name and pos.
   231      */
   232     protected boolean shouldReport(JavaFileObject file, int pos) {
   233         if (multipleErrors || file == null)
   234             return true;
   236         Pair<JavaFileObject,Integer> coords = new Pair<JavaFileObject,Integer>(file, pos);
   237         boolean shouldReport = !recorded.contains(coords);
   238         if (shouldReport)
   239             recorded.add(coords);
   240         return shouldReport;
   241     }
   243     /** Prompt user after an error.
   244      */
   245     public void prompt() {
   246         if (promptOnError) {
   247             System.err.println(getLocalizedString("resume.abort"));
   248             char ch;
   249             try {
   250                 while (true) {
   251                     switch (System.in.read()) {
   252                     case 'a': case 'A':
   253                         System.exit(-1);
   254                         return;
   255                     case 'r': case 'R':
   256                         return;
   257                     case 'x': case 'X':
   258                         throw new AssertionError("user abort");
   259                     default:
   260                     }
   261                 }
   262             } catch (IOException e) {}
   263         }
   264     }
   266     /** Print the faulty source code line and point to the error.
   267      *  @param pos   Buffer index of the error position, must be on current line
   268      */
   269     private void printErrLine(int pos, PrintWriter writer) {
   270         String line = (source == null ? null : source.getLine(pos));
   271         if (line == null)
   272             return;
   273         int col = source.getColumnNumber(pos, false);
   275         printLines(writer, line);
   276         for (int i = 0; i < col - 1; i++) {
   277             writer.print((line.charAt(i) == '\t') ? "\t" : " ");
   278         }
   279         writer.println("^");
   280         writer.flush();
   281     }
   283     /** Print the text of a message, translating newlines appropriately
   284      *  for the platform.
   285      */
   286     public static void printLines(PrintWriter writer, String msg) {
   287         int nl;
   288         while ((nl = msg.indexOf('\n')) != -1) {
   289             writer.println(msg.substring(0, nl));
   290             msg = msg.substring(nl+1);
   291         }
   292         if (msg.length() != 0) writer.println(msg);
   293     }
   295     protected void directError(String key, Object... args) {
   296         printLines(errWriter, getLocalizedString(key, args));
   297         errWriter.flush();
   298     }
   300     /** Report a warning that cannot be suppressed.
   301      *  @param pos    The source position at which to report the warning.
   302      *  @param key    The key for the localized warning message.
   303      *  @param args   Fields of the warning message.
   304      */
   305     public void strictWarning(DiagnosticPosition pos, String key, Object ... args) {
   306         writeDiagnostic(diags.warning(source, pos, key, args));
   307         nwarnings++;
   308     }
   310     /**
   311      * Common diagnostic handling.
   312      * The diagnostic is counted, and depending on the options and how many diagnostics have been
   313      * reported so far, the diagnostic may be handed off to writeDiagnostic.
   314      */
   315     public void report(JCDiagnostic diagnostic) {
   316         if (expectDiagKeys != null)
   317             expectDiagKeys.remove(diagnostic.getCode());
   319         switch (diagnostic.getType()) {
   320         case FRAGMENT:
   321             throw new IllegalArgumentException();
   323         case NOTE:
   324             // Print out notes only when we are permitted to report warnings
   325             // Notes are only generated at the end of a compilation, so should be small
   326             // in number.
   327             if (emitWarnings || diagnostic.isMandatory()) {
   328                 writeDiagnostic(diagnostic);
   329             }
   330             break;
   332         case WARNING:
   333             if (emitWarnings || diagnostic.isMandatory()) {
   334                 if (nwarnings < MaxWarnings) {
   335                     writeDiagnostic(diagnostic);
   336                     nwarnings++;
   337                 }
   338             }
   339             break;
   341         case ERROR:
   342             if (nerrors < MaxErrors
   343                 && shouldReport(diagnostic.getSource(), diagnostic.getIntPosition())) {
   344                 writeDiagnostic(diagnostic);
   345                 nerrors++;
   346             }
   347             break;
   348         }
   349     }
   351     /**
   352      * Write out a diagnostic.
   353      */
   354     protected void writeDiagnostic(JCDiagnostic diag) {
   355         if (diagListener != null) {
   356             try {
   357                 diagListener.report(diag);
   358                 return;
   359             }
   360             catch (Throwable t) {
   361                 throw new ClientCodeException(t);
   362             }
   363         }
   365         PrintWriter writer = getWriterForDiagnosticType(diag.getType());
   367         printLines(writer, diagFormatter.format(diag, messages.getCurrentLocale()));
   369         if (promptOnError) {
   370             switch (diag.getType()) {
   371             case ERROR:
   372             case WARNING:
   373                 prompt();
   374             }
   375         }
   377         if (dumpOnError)
   378             new RuntimeException().printStackTrace(writer);
   380         writer.flush();
   381     }
   383     @Deprecated
   384     protected PrintWriter getWriterForDiagnosticType(DiagnosticType dt) {
   385         switch (dt) {
   386         case FRAGMENT:
   387             throw new IllegalArgumentException();
   389         case NOTE:
   390             return noticeWriter;
   392         case WARNING:
   393             return warnWriter;
   395         case ERROR:
   396             return errWriter;
   398         default:
   399             throw new Error();
   400         }
   401     }
   403     /** Find a localized string in the resource bundle.
   404      *  @param key    The key for the localized string.
   405      *  @param args   Fields to substitute into the string.
   406      */
   407     public static String getLocalizedString(String key, Object ... args) {
   408         return JavacMessages.getDefaultLocalizedString("compiler.misc." + key, args);
   409     }
   411 /***************************************************************************
   412  * raw error messages without internationalization; used for experimentation
   413  * and quick prototyping
   414  ***************************************************************************/
   416     /** print an error or warning message:
   417      */
   418     private void printRawError(int pos, String msg) {
   419         if (source == null || pos == Position.NOPOS) {
   420             printLines(errWriter, "error: " + msg);
   421         } else {
   422             int line = source.getLineNumber(pos);
   423             JavaFileObject file = source.getFile();
   424             if (file != null)
   425                 printLines(errWriter,
   426                            JavacFileManager.getJavacFileName(file) + ":" +
   427                            line + ": " + msg);
   428             printErrLine(pos, errWriter);
   429         }
   430         errWriter.flush();
   431     }
   433     /** report an error:
   434      */
   435     public void rawError(int pos, String msg) {
   436         if (nerrors < MaxErrors && shouldReport(currentSourceFile(), pos)) {
   437             printRawError(pos, msg);
   438             prompt();
   439             nerrors++;
   440         }
   441         errWriter.flush();
   442     }
   444     /** report a warning:
   445      */
   446     public void rawWarning(int pos, String msg) {
   447         if (nwarnings < MaxWarnings && emitWarnings) {
   448             printRawError(pos, "warning: " + msg);
   449         }
   450         prompt();
   451         nwarnings++;
   452         errWriter.flush();
   453     }
   455     public static String format(String fmt, Object... args) {
   456         return String.format((java.util.Locale)null, fmt, args);
   457     }
   459 }

mercurial