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

Mon, 30 Aug 2010 18:03:35 -0700

author
jjg
date
Mon, 30 Aug 2010 18:03:35 -0700
changeset 664
4124840b35fe
parent 604
a5454419dd46
child 700
7b413ac1a720
permissions
-rw-r--r--

6403465: javac should defer diagnostics until it can be determined they are persistent
Reviewed-by: mcimadamore, darcy

     1 /*
     2  * Copyright (c) 1999, 2009, 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.tree.JCTree;
    39 import com.sun.tools.javac.api.DiagnosticFormatter;
    40 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    41 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
    43 /** A class for error logs. Reports errors and warnings, and
    44  *  keeps track of error numbers and positions.
    45  *
    46  *  <p><b>This is NOT part of any supported API.
    47  *  If you write code that depends on this, you do so at your own risk.
    48  *  This code and its internal interfaces are subject to change or
    49  *  deletion without notice.</b>
    50  */
    51 public class Log extends AbstractLog {
    52     /** The context key for the log. */
    53     public static final Context.Key<Log> logKey
    54         = new Context.Key<Log>();
    56     /** The context key for the output PrintWriter. */
    57     public static final Context.Key<PrintWriter> outKey =
    58         new Context.Key<PrintWriter>();
    60     //@Deprecated
    61     public final PrintWriter errWriter;
    63     //@Deprecated
    64     public final PrintWriter warnWriter;
    66     //@Deprecated
    67     public final PrintWriter noticeWriter;
    69     /** The maximum number of errors/warnings that are reported.
    70      */
    71     public final int MaxErrors;
    72     public final int MaxWarnings;
    74     /** Switch: prompt user on each error.
    75      */
    76     public boolean promptOnError;
    78     /** Switch: emit warning messages.
    79      */
    80     public boolean emitWarnings;
    82     /** Switch: suppress note messages.
    83      */
    84     public boolean suppressNotes;
    86     /** Print stack trace on errors?
    87      */
    88     public boolean dumpOnError;
    90     /** Print multiple errors for same source locations.
    91      */
    92     public boolean multipleErrors;
    94     /**
    95      * Diagnostic listener, if provided through programmatic
    96      * interface to javac (JSR 199).
    97      */
    98     protected DiagnosticListener<? super JavaFileObject> diagListener;
   100     /**
   101      * Formatter for diagnostics.
   102      */
   103     private DiagnosticFormatter<JCDiagnostic> diagFormatter;
   105     /**
   106      * Keys for expected diagnostics.
   107      */
   108     public Set<String> expectDiagKeys;
   110     /**
   111      * JavacMessages object used for localization.
   112      */
   113     private JavacMessages messages;
   115     /**
   116      * Deferred diagnostics
   117      */
   118     public boolean deferDiagnostics;
   119     public Queue<JCDiagnostic> deferredDiagnostics = new ListBuffer<JCDiagnostic>();
   121     /** Construct a log with given I/O redirections.
   122      */
   123     @Deprecated
   124     protected Log(Context context, PrintWriter errWriter, PrintWriter warnWriter, PrintWriter noticeWriter) {
   125         super(JCDiagnostic.Factory.instance(context));
   126         context.put(logKey, this);
   127         this.errWriter = errWriter;
   128         this.warnWriter = warnWriter;
   129         this.noticeWriter = noticeWriter;
   131         Options options = Options.instance(context);
   132         this.dumpOnError = options.get("-doe") != null;
   133         this.promptOnError = options.get("-prompt") != null;
   134         this.emitWarnings = options.get("-Xlint:none") == null;
   135         this.suppressNotes = options.get("suppressNotes") != null;
   136         this.MaxErrors = getIntOption(options, "-Xmaxerrs", getDefaultMaxErrors());
   137         this.MaxWarnings = getIntOption(options, "-Xmaxwarns", getDefaultMaxWarnings());
   139         boolean rawDiagnostics = options.get("rawDiagnostics") != null;
   140         messages = JavacMessages.instance(context);
   141         this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(options) :
   142                                               new BasicDiagnosticFormatter(options, messages);
   143         @SuppressWarnings("unchecked") // FIXME
   144         DiagnosticListener<? super JavaFileObject> dl =
   145             context.get(DiagnosticListener.class);
   146         this.diagListener = dl;
   148         String ek = options.get("expectKeys");
   149         if (ek != null)
   150             expectDiagKeys = new HashSet<String>(Arrays.asList(ek.split(", *")));
   151     }
   152     // where
   153         private int getIntOption(Options options, String optionName, int defaultValue) {
   154             String s = options.get(optionName);
   155             try {
   156                 if (s != null) {
   157                     int n = Integer.parseInt(s);
   158                     return (n <= 0 ? Integer.MAX_VALUE : n);
   159                 }
   160             } catch (NumberFormatException e) {
   161                 // silently ignore ill-formed numbers
   162             }
   163             return defaultValue;
   164         }
   166         /** Default value for -Xmaxerrs.
   167          */
   168         protected int getDefaultMaxErrors() {
   169             return 100;
   170         }
   172         /** Default value for -Xmaxwarns.
   173          */
   174         protected int getDefaultMaxWarnings() {
   175             return 100;
   176         }
   178     /** The default writer for diagnostics
   179      */
   180     static final PrintWriter defaultWriter(Context context) {
   181         PrintWriter result = context.get(outKey);
   182         if (result == null)
   183             context.put(outKey, result = new PrintWriter(System.err));
   184         return result;
   185     }
   187     /** Construct a log with default settings.
   188      */
   189     protected Log(Context context) {
   190         this(context, defaultWriter(context));
   191     }
   193     /** Construct a log with all output redirected.
   194      */
   195     protected Log(Context context, PrintWriter defaultWriter) {
   196         this(context, defaultWriter, defaultWriter, defaultWriter);
   197     }
   199     /** Get the Log instance for this context. */
   200     public static Log instance(Context context) {
   201         Log instance = context.get(logKey);
   202         if (instance == null)
   203             instance = new Log(context);
   204         return instance;
   205     }
   207     /** The number of errors encountered so far.
   208      */
   209     public int nerrors = 0;
   211     /** The number of warnings encountered so far.
   212      */
   213     public int nwarnings = 0;
   215     /** A set of all errors generated so far. This is used to avoid printing an
   216      *  error message more than once. For each error, a pair consisting of the
   217      *  source file name and source code position of the error is added to the set.
   218      */
   219     private Set<Pair<JavaFileObject, Integer>> recorded = new HashSet<Pair<JavaFileObject,Integer>>();
   221     public boolean hasDiagnosticListener() {
   222         return diagListener != null;
   223     }
   225     public void setEndPosTable(JavaFileObject name, Map<JCTree, Integer> table) {
   226         name.getClass(); // null check
   227         getSource(name).setEndPosTable(table);
   228     }
   230     /** Return current sourcefile.
   231      */
   232     public JavaFileObject currentSourceFile() {
   233         return source == null ? null : source.getFile();
   234     }
   236     /** Get the current diagnostic formatter.
   237      */
   238     public DiagnosticFormatter<JCDiagnostic> getDiagnosticFormatter() {
   239         return diagFormatter;
   240     }
   242     /** Set the current diagnostic formatter.
   243      */
   244     public void setDiagnosticFormatter(DiagnosticFormatter<JCDiagnostic> diagFormatter) {
   245         this.diagFormatter = diagFormatter;
   246     }
   248     /** Flush the logs
   249      */
   250     public void flush() {
   251         errWriter.flush();
   252         warnWriter.flush();
   253         noticeWriter.flush();
   254     }
   256     /** Returns true if an error needs to be reported for a given
   257      * source name and pos.
   258      */
   259     protected boolean shouldReport(JavaFileObject file, int pos) {
   260         if (multipleErrors || file == null)
   261             return true;
   263         Pair<JavaFileObject,Integer> coords = new Pair<JavaFileObject,Integer>(file, pos);
   264         boolean shouldReport = !recorded.contains(coords);
   265         if (shouldReport)
   266             recorded.add(coords);
   267         return shouldReport;
   268     }
   270     /** Prompt user after an error.
   271      */
   272     public void prompt() {
   273         if (promptOnError) {
   274             System.err.println(localize("resume.abort"));
   275             char ch;
   276             try {
   277                 while (true) {
   278                     switch (System.in.read()) {
   279                     case 'a': case 'A':
   280                         System.exit(-1);
   281                         return;
   282                     case 'r': case 'R':
   283                         return;
   284                     case 'x': case 'X':
   285                         throw new AssertionError("user abort");
   286                     default:
   287                     }
   288                 }
   289             } catch (IOException e) {}
   290         }
   291     }
   293     /** Print the faulty source code line and point to the error.
   294      *  @param pos   Buffer index of the error position, must be on current line
   295      */
   296     private void printErrLine(int pos, PrintWriter writer) {
   297         String line = (source == null ? null : source.getLine(pos));
   298         if (line == null)
   299             return;
   300         int col = source.getColumnNumber(pos, false);
   302         printLines(writer, line);
   303         for (int i = 0; i < col - 1; i++) {
   304             writer.print((line.charAt(i) == '\t') ? "\t" : " ");
   305         }
   306         writer.println("^");
   307         writer.flush();
   308     }
   310     /** Print the text of a message, translating newlines appropriately
   311      *  for the platform.
   312      */
   313     public static void printLines(PrintWriter writer, String msg) {
   314         int nl;
   315         while ((nl = msg.indexOf('\n')) != -1) {
   316             writer.println(msg.substring(0, nl));
   317             msg = msg.substring(nl+1);
   318         }
   319         if (msg.length() != 0) writer.println(msg);
   320     }
   322     /** Print the text of a message to the errWriter stream,
   323      *  translating newlines appropriately for the platform.
   324      */
   325     public void printErrLines(String key, Object... args) {
   326         printLines(errWriter, localize(key, args));
   327     }
   330     /** Print the text of a message to the noticeWriter stream,
   331      *  translating newlines appropriately for the platform.
   332      */
   333     public void printNoteLines(String key, Object... args) {
   334         printLines(noticeWriter, localize(key, args));
   335     }
   337     protected void directError(String key, Object... args) {
   338         printErrLines(key, args);
   339         errWriter.flush();
   340     }
   342     /** Report a warning that cannot be suppressed.
   343      *  @param pos    The source position at which to report the warning.
   344      *  @param key    The key for the localized warning message.
   345      *  @param args   Fields of the warning message.
   346      */
   347     public void strictWarning(DiagnosticPosition pos, String key, Object ... args) {
   348         writeDiagnostic(diags.warning(source, pos, key, args));
   349         nwarnings++;
   350     }
   352     /** Report all deferred diagnostics, and clear the deferDiagnostics flag. */
   353     public void reportDeferredDiagnostics() {
   354         reportDeferredDiagnostics(EnumSet.allOf(JCDiagnostic.Kind.class));
   355     }
   357     /** Report selected deferred diagnostics, and clear the deferDiagnostics flag. */
   358     public void reportDeferredDiagnostics(Set<JCDiagnostic.Kind> kinds) {
   359         deferDiagnostics = false;
   360         JCDiagnostic d;
   361         while ((d = deferredDiagnostics.poll()) != null) {
   362             if (kinds.contains(d.getKind()))
   363                 report(d);
   364         }
   365     }
   367     /**
   368      * Common diagnostic handling.
   369      * The diagnostic is counted, and depending on the options and how many diagnostics have been
   370      * reported so far, the diagnostic may be handed off to writeDiagnostic.
   371      */
   372     public void report(JCDiagnostic diagnostic) {
   373         if (deferDiagnostics) {
   374             deferredDiagnostics.add(diagnostic);
   375             return;
   376         }
   378         if (expectDiagKeys != null)
   379             expectDiagKeys.remove(diagnostic.getCode());
   381         switch (diagnostic.getType()) {
   382         case FRAGMENT:
   383             throw new IllegalArgumentException();
   385         case NOTE:
   386             // Print out notes only when we are permitted to report warnings
   387             // Notes are only generated at the end of a compilation, so should be small
   388             // in number.
   389             if ((emitWarnings || diagnostic.isMandatory()) && !suppressNotes) {
   390                 writeDiagnostic(diagnostic);
   391             }
   392             break;
   394         case WARNING:
   395             if (emitWarnings || diagnostic.isMandatory()) {
   396                 if (nwarnings < MaxWarnings) {
   397                     writeDiagnostic(diagnostic);
   398                     nwarnings++;
   399                 }
   400             }
   401             break;
   403         case ERROR:
   404             if (nerrors < MaxErrors
   405                 && shouldReport(diagnostic.getSource(), diagnostic.getIntPosition())) {
   406                 writeDiagnostic(diagnostic);
   407                 nerrors++;
   408             }
   409             break;
   410         }
   411     }
   413     /**
   414      * Write out a diagnostic.
   415      */
   416     protected void writeDiagnostic(JCDiagnostic diag) {
   417         if (diagListener != null) {
   418             try {
   419                 diagListener.report(diag);
   420                 return;
   421             }
   422             catch (Throwable t) {
   423                 throw new ClientCodeException(t);
   424             }
   425         }
   427         PrintWriter writer = getWriterForDiagnosticType(diag.getType());
   429         printLines(writer, diagFormatter.format(diag, messages.getCurrentLocale()));
   431         if (promptOnError) {
   432             switch (diag.getType()) {
   433             case ERROR:
   434             case WARNING:
   435                 prompt();
   436             }
   437         }
   439         if (dumpOnError)
   440             new RuntimeException().printStackTrace(writer);
   442         writer.flush();
   443     }
   445     @Deprecated
   446     protected PrintWriter getWriterForDiagnosticType(DiagnosticType dt) {
   447         switch (dt) {
   448         case FRAGMENT:
   449             throw new IllegalArgumentException();
   451         case NOTE:
   452             return noticeWriter;
   454         case WARNING:
   455             return warnWriter;
   457         case ERROR:
   458             return errWriter;
   460         default:
   461             throw new Error();
   462         }
   463     }
   465     /** Find a localized string in the resource bundle.
   466      *  Because this method is static, it ignores the locale.
   467      *  Use localize(key, args) when possible.
   468      *  @param key    The key for the localized string.
   469      *  @param args   Fields to substitute into the string.
   470      */
   471     public static String getLocalizedString(String key, Object ... args) {
   472         return JavacMessages.getDefaultLocalizedString("compiler.misc." + key, args);
   473     }
   475     /** Find a localized string in the resource bundle.
   476      *  @param key    The key for the localized string.
   477      *  @param args   Fields to substitute into the string.
   478      */
   479     public String localize(String key, Object... args) {
   480         return messages.getLocalizedString("compiler.misc." + key, args);
   481     }
   483 /***************************************************************************
   484  * raw error messages without internationalization; used for experimentation
   485  * and quick prototyping
   486  ***************************************************************************/
   488     /** print an error or warning message:
   489      */
   490     private void printRawError(int pos, String msg) {
   491         if (source == null || pos == Position.NOPOS) {
   492             printLines(errWriter, "error: " + msg);
   493         } else {
   494             int line = source.getLineNumber(pos);
   495             JavaFileObject file = source.getFile();
   496             if (file != null)
   497                 printLines(errWriter,
   498                            file.getName() + ":" +
   499                            line + ": " + msg);
   500             printErrLine(pos, errWriter);
   501         }
   502         errWriter.flush();
   503     }
   505     /** report an error:
   506      */
   507     public void rawError(int pos, String msg) {
   508         if (nerrors < MaxErrors && shouldReport(currentSourceFile(), pos)) {
   509             printRawError(pos, msg);
   510             prompt();
   511             nerrors++;
   512         }
   513         errWriter.flush();
   514     }
   516     /** report a warning:
   517      */
   518     public void rawWarning(int pos, String msg) {
   519         if (nwarnings < MaxWarnings && emitWarnings) {
   520             printRawError(pos, "warning: " + msg);
   521         }
   522         prompt();
   523         nwarnings++;
   524         errWriter.flush();
   525     }
   527     public static String format(String fmt, Object... args) {
   528         return String.format((java.util.Locale)null, fmt, args);
   529     }
   531 }

mercurial