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

Tue, 05 Mar 2013 14:12:07 +0000

author
mcimadamore
date
Tue, 05 Mar 2013 14:12:07 +0000
changeset 1613
d2a98dde7ecc
parent 1521
71f35e4b93a5
child 1759
05ec778794d0
permissions
-rw-r--r--

8009227: Certain diagnostics should not be deferred
Summary: Add new diagnostic flag to mark non deferrable diagnostics
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2013, 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.Queue;
    33 import java.util.Set;
    34 import javax.tools.DiagnosticListener;
    35 import javax.tools.JavaFileObject;
    37 import com.sun.tools.javac.api.DiagnosticFormatter;
    38 import com.sun.tools.javac.main.Main;
    39 import com.sun.tools.javac.main.Option;
    40 import com.sun.tools.javac.tree.EndPosTable;
    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.Option.*;
    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     /* TODO: Should unify this with prefix handling in JCDiagnostic.Factory. */
    64     public enum PrefixKind {
    65         JAVAC("javac."),
    66         COMPILER_MISC("compiler.misc.");
    67         PrefixKind(String v) {
    68             value = v;
    69         }
    70         public String key(String k) {
    71             return value + k;
    72         }
    73         final String value;
    74     }
    76     /**
    77      * DiagnosticHandler's provide the initial handling for diagnostics.
    78      * When a diagnostic handler is created and has been initialized, it
    79      * should install itself as the current diagnostic handler. When a
    80      * client has finished using a handler, the client should call
    81      * {@code log.removeDiagnosticHandler();}
    82      *
    83      * Note that javax.tools.DiagnosticListener (if set) is called later in the
    84      * diagnostic pipeline.
    85      */
    86     public static abstract class DiagnosticHandler {
    87         /**
    88          * The previously installed diagnostic handler.
    89          */
    90         protected DiagnosticHandler prev;
    92         /**
    93          * Install this diagnostic handler as the current one,
    94          * recording the previous one.
    95          */
    96         protected void install(Log log) {
    97             prev = log.diagnosticHandler;
    98             log.diagnosticHandler = this;
    99         }
   101         /**
   102          * Handle a diagnostic.
   103          */
   104         public abstract void report(JCDiagnostic diag);
   105     }
   107     /**
   108      * A DiagnosticHandler that discards all diagnostics.
   109      */
   110     public static class DiscardDiagnosticHandler extends DiagnosticHandler {
   111         public DiscardDiagnosticHandler(Log log) {
   112             install(log);
   113         }
   115         public void report(JCDiagnostic diag) { }
   116     }
   118     /**
   119      * A DiagnosticHandler that can defer some or all diagnostics,
   120      * by buffering them for later examination and/or reporting.
   121      * If a diagnostic is not deferred, or is subsequently reported
   122      * with reportAllDiagnostics(), it will be reported to the previously
   123      * active diagnostic handler.
   124      */
   125     public static class DeferredDiagnosticHandler extends DiagnosticHandler {
   126         private Queue<JCDiagnostic> deferred = ListBuffer.lb();
   127         private final Filter<JCDiagnostic> filter;
   129         public DeferredDiagnosticHandler(Log log) {
   130             this(log, null);
   131         }
   133         public DeferredDiagnosticHandler(Log log, Filter<JCDiagnostic> filter) {
   134             this.filter = filter;
   135             install(log);
   136         }
   138         public void report(JCDiagnostic diag) {
   139             if (!diag.isFlagSet(JCDiagnostic.DiagnosticFlag.NON_DEFERRABLE) &&
   140                 (filter == null || filter.accepts(diag))) {
   141                 deferred.add(diag);
   142             } else {
   143                 prev.report(diag);
   144             }
   145         }
   147         public Queue<JCDiagnostic> getDiagnostics() {
   148             return deferred;
   149         }
   151         /** Report all deferred diagnostics. */
   152         public void reportDeferredDiagnostics() {
   153             reportDeferredDiagnostics(EnumSet.allOf(JCDiagnostic.Kind.class));
   154         }
   156         /** Report selected deferred diagnostics. */
   157         public void reportDeferredDiagnostics(Set<JCDiagnostic.Kind> kinds) {
   158             JCDiagnostic d;
   159             while ((d = deferred.poll()) != null) {
   160                 if (kinds.contains(d.getKind()))
   161                     prev.report(d);
   162             }
   163             deferred = null; // prevent accidental ongoing use
   164         }
   165     }
   167     public enum WriterKind { NOTICE, WARNING, ERROR };
   169     protected PrintWriter errWriter;
   171     protected PrintWriter warnWriter;
   173     protected PrintWriter noticeWriter;
   175     /** The maximum number of errors/warnings that are reported.
   176      */
   177     protected int MaxErrors;
   178     protected int MaxWarnings;
   180     /** Switch: prompt user on each error.
   181      */
   182     public boolean promptOnError;
   184     /** Switch: emit warning messages.
   185      */
   186     public boolean emitWarnings;
   188     /** Switch: suppress note messages.
   189      */
   190     public boolean suppressNotes;
   192     /** Print stack trace on errors?
   193      */
   194     public boolean dumpOnError;
   196     /** Print multiple errors for same source locations.
   197      */
   198     public boolean multipleErrors;
   200     /**
   201      * Diagnostic listener, if provided through programmatic
   202      * interface to javac (JSR 199).
   203      */
   204     protected DiagnosticListener<? super JavaFileObject> diagListener;
   206     /**
   207      * Formatter for diagnostics.
   208      */
   209     private DiagnosticFormatter<JCDiagnostic> diagFormatter;
   211     /**
   212      * Keys for expected diagnostics.
   213      */
   214     public Set<String> expectDiagKeys;
   216     /**
   217      * JavacMessages object used for localization.
   218      */
   219     private JavacMessages messages;
   221     /**
   222      * Handler for initial dispatch of diagnostics.
   223      */
   224     private DiagnosticHandler diagnosticHandler;
   226     /** Construct a log with given I/O redirections.
   227      */
   228     protected Log(Context context, PrintWriter errWriter, PrintWriter warnWriter, PrintWriter noticeWriter) {
   229         super(JCDiagnostic.Factory.instance(context));
   230         context.put(logKey, this);
   231         this.errWriter = errWriter;
   232         this.warnWriter = warnWriter;
   233         this.noticeWriter = noticeWriter;
   235         @SuppressWarnings("unchecked") // FIXME
   236         DiagnosticListener<? super JavaFileObject> dl =
   237             context.get(DiagnosticListener.class);
   238         this.diagListener = dl;
   240         diagnosticHandler = new DefaultDiagnosticHandler();
   242         messages = JavacMessages.instance(context);
   243         messages.add(Main.javacBundleName);
   245         final Options options = Options.instance(context);
   246         initOptions(options);
   247         options.addListener(new Runnable() {
   248             public void run() {
   249                 initOptions(options);
   250             }
   251         });
   252     }
   253     // where
   254         private void initOptions(Options options) {
   255             this.dumpOnError = options.isSet(DOE);
   256             this.promptOnError = options.isSet(PROMPT);
   257             this.emitWarnings = options.isUnset(XLINT_CUSTOM, "none");
   258             this.suppressNotes = options.isSet("suppressNotes");
   259             this.MaxErrors = getIntOption(options, XMAXERRS, getDefaultMaxErrors());
   260             this.MaxWarnings = getIntOption(options, XMAXWARNS, getDefaultMaxWarnings());
   262             boolean rawDiagnostics = options.isSet("rawDiagnostics");
   263             this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(options) :
   264                                                   new BasicDiagnosticFormatter(options, messages);
   266             String ek = options.get("expectKeys");
   267             if (ek != null)
   268                 expectDiagKeys = new HashSet<String>(Arrays.asList(ek.split(", *")));
   269         }
   271         private int getIntOption(Options options, Option option, int defaultValue) {
   272             String s = options.get(option);
   273             try {
   274                 if (s != null) {
   275                     int n = Integer.parseInt(s);
   276                     return (n <= 0 ? Integer.MAX_VALUE : n);
   277                 }
   278             } catch (NumberFormatException e) {
   279                 // silently ignore ill-formed numbers
   280             }
   281             return defaultValue;
   282         }
   284         /** Default value for -Xmaxerrs.
   285          */
   286         protected int getDefaultMaxErrors() {
   287             return 100;
   288         }
   290         /** Default value for -Xmaxwarns.
   291          */
   292         protected int getDefaultMaxWarnings() {
   293             return 100;
   294         }
   296     /** The default writer for diagnostics
   297      */
   298     static PrintWriter defaultWriter(Context context) {
   299         PrintWriter result = context.get(outKey);
   300         if (result == null)
   301             context.put(outKey, result = new PrintWriter(System.err));
   302         return result;
   303     }
   305     /** Construct a log with default settings.
   306      */
   307     protected Log(Context context) {
   308         this(context, defaultWriter(context));
   309     }
   311     /** Construct a log with all output redirected.
   312      */
   313     protected Log(Context context, PrintWriter defaultWriter) {
   314         this(context, defaultWriter, defaultWriter, defaultWriter);
   315     }
   317     /** Get the Log instance for this context. */
   318     public static Log instance(Context context) {
   319         Log instance = context.get(logKey);
   320         if (instance == null)
   321             instance = new Log(context);
   322         return instance;
   323     }
   325     /** The number of errors encountered so far.
   326      */
   327     public int nerrors = 0;
   329     /** The number of warnings encountered so far.
   330      */
   331     public int nwarnings = 0;
   333     /** A set of all errors generated so far. This is used to avoid printing an
   334      *  error message more than once. For each error, a pair consisting of the
   335      *  source file name and source code position of the error is added to the set.
   336      */
   337     private Set<Pair<JavaFileObject, Integer>> recorded = new HashSet<Pair<JavaFileObject,Integer>>();
   339     public boolean hasDiagnosticListener() {
   340         return diagListener != null;
   341     }
   343     public void setEndPosTable(JavaFileObject name, EndPosTable endPosTable) {
   344         name.getClass(); // null check
   345         getSource(name).setEndPosTable(endPosTable);
   346     }
   348     /** Return current sourcefile.
   349      */
   350     public JavaFileObject currentSourceFile() {
   351         return source == null ? null : source.getFile();
   352     }
   354     /** Get the current diagnostic formatter.
   355      */
   356     public DiagnosticFormatter<JCDiagnostic> getDiagnosticFormatter() {
   357         return diagFormatter;
   358     }
   360     /** Set the current diagnostic formatter.
   361      */
   362     public void setDiagnosticFormatter(DiagnosticFormatter<JCDiagnostic> diagFormatter) {
   363         this.diagFormatter = diagFormatter;
   364     }
   366     public PrintWriter getWriter(WriterKind kind) {
   367         switch (kind) {
   368             case NOTICE:    return noticeWriter;
   369             case WARNING:   return warnWriter;
   370             case ERROR:     return errWriter;
   371             default:        throw new IllegalArgumentException();
   372         }
   373     }
   375     public void setWriter(WriterKind kind, PrintWriter pw) {
   376         pw.getClass();
   377         switch (kind) {
   378             case NOTICE:    noticeWriter = pw;  break;
   379             case WARNING:   warnWriter = pw;    break;
   380             case ERROR:     errWriter = pw;     break;
   381             default:        throw new IllegalArgumentException();
   382         }
   383     }
   385     public void setWriters(PrintWriter pw) {
   386         pw.getClass();
   387         noticeWriter = warnWriter = errWriter = pw;
   388     }
   390     /**
   391      * Propagate the previous log's information.
   392      */
   393     public void initRound(Log other) {
   394         this.noticeWriter = other.noticeWriter;
   395         this.warnWriter = other.warnWriter;
   396         this.errWriter = other.errWriter;
   397         this.sourceMap = other.sourceMap;
   398         this.recorded = other.recorded;
   399         this.nerrors = other.nerrors;
   400         this.nwarnings = other.nwarnings;
   401     }
   403     /**
   404      * Replace the specified diagnostic handler with the
   405      * handler that was current at the time this handler was created.
   406      * The given handler must be the currently installed handler;
   407      * it must be specified explicitly for clarity and consistency checking.
   408      */
   409     public void popDiagnosticHandler(DiagnosticHandler h) {
   410         Assert.check(diagnosticHandler == h);
   411         diagnosticHandler = h.prev;
   412     }
   414     /** Flush the logs
   415      */
   416     public void flush() {
   417         errWriter.flush();
   418         warnWriter.flush();
   419         noticeWriter.flush();
   420     }
   422     public void flush(WriterKind kind) {
   423         getWriter(kind).flush();
   424     }
   426     /** Returns true if an error needs to be reported for a given
   427      * source name and pos.
   428      */
   429     protected boolean shouldReport(JavaFileObject file, int pos) {
   430         if (multipleErrors || file == null)
   431             return true;
   433         Pair<JavaFileObject,Integer> coords = new Pair<JavaFileObject,Integer>(file, pos);
   434         boolean shouldReport = !recorded.contains(coords);
   435         if (shouldReport)
   436             recorded.add(coords);
   437         return shouldReport;
   438     }
   440     /** Prompt user after an error.
   441      */
   442     public void prompt() {
   443         if (promptOnError) {
   444             System.err.println(localize("resume.abort"));
   445             try {
   446                 while (true) {
   447                     switch (System.in.read()) {
   448                     case 'a': case 'A':
   449                         System.exit(-1);
   450                         return;
   451                     case 'r': case 'R':
   452                         return;
   453                     case 'x': case 'X':
   454                         throw new AssertionError("user abort");
   455                     default:
   456                     }
   457                 }
   458             } catch (IOException e) {}
   459         }
   460     }
   462     /** Print the faulty source code line and point to the error.
   463      *  @param pos   Buffer index of the error position, must be on current line
   464      */
   465     private void printErrLine(int pos, PrintWriter writer) {
   466         String line = (source == null ? null : source.getLine(pos));
   467         if (line == null)
   468             return;
   469         int col = source.getColumnNumber(pos, false);
   471         printRawLines(writer, line);
   472         for (int i = 0; i < col - 1; i++) {
   473             writer.print((line.charAt(i) == '\t') ? "\t" : " ");
   474         }
   475         writer.println("^");
   476         writer.flush();
   477     }
   479     public void printNewline() {
   480         noticeWriter.println();
   481     }
   483     public void printNewline(WriterKind wk) {
   484         getWriter(wk).println();
   485     }
   487     public void printLines(String key, Object... args) {
   488         printRawLines(noticeWriter, localize(key, args));
   489     }
   491     public void printLines(PrefixKind pk, String key, Object... args) {
   492         printRawLines(noticeWriter, localize(pk, key, args));
   493     }
   495     public void printLines(WriterKind wk, String key, Object... args) {
   496         printRawLines(getWriter(wk), localize(key, args));
   497     }
   499     public void printLines(WriterKind wk, PrefixKind pk, String key, Object... args) {
   500         printRawLines(getWriter(wk), localize(pk, key, args));
   501     }
   503     /** Print the text of a message, translating newlines appropriately
   504      *  for the platform.
   505      */
   506     public void printRawLines(String msg) {
   507         printRawLines(noticeWriter, msg);
   508     }
   510     /** Print the text of a message, translating newlines appropriately
   511      *  for the platform.
   512      */
   513     public void printRawLines(WriterKind kind, String msg) {
   514         printRawLines(getWriter(kind), msg);
   515     }
   517     /** Print the text of a message, translating newlines appropriately
   518      *  for the platform.
   519      */
   520     public static void printRawLines(PrintWriter writer, String msg) {
   521         int nl;
   522         while ((nl = msg.indexOf('\n')) != -1) {
   523             writer.println(msg.substring(0, nl));
   524             msg = msg.substring(nl+1);
   525         }
   526         if (msg.length() != 0) writer.println(msg);
   527     }
   529     /**
   530      * Print the localized text of a "verbose" message to the
   531      * noticeWriter stream.
   532      */
   533     public void printVerbose(String key, Object... args) {
   534         printRawLines(noticeWriter, localize("verbose." + key, args));
   535     }
   537     protected void directError(String key, Object... args) {
   538         printRawLines(errWriter, localize(key, args));
   539         errWriter.flush();
   540     }
   542     /** Report a warning that cannot be suppressed.
   543      *  @param pos    The source position at which to report the warning.
   544      *  @param key    The key for the localized warning message.
   545      *  @param args   Fields of the warning message.
   546      */
   547     public void strictWarning(DiagnosticPosition pos, String key, Object ... args) {
   548         writeDiagnostic(diags.warning(source, pos, key, args));
   549         nwarnings++;
   550     }
   552     /**
   553      * Primary method to report a diagnostic.
   554      * @param diagnostic
   555      */
   556     public void report(JCDiagnostic diagnostic) {
   557         diagnosticHandler.report(diagnostic);
   558      }
   560     /**
   561      * Common diagnostic handling.
   562      * The diagnostic is counted, and depending on the options and how many diagnostics have been
   563      * reported so far, the diagnostic may be handed off to writeDiagnostic.
   564      */
   565     private class DefaultDiagnosticHandler extends DiagnosticHandler {
   566         public void report(JCDiagnostic diagnostic) {
   567             if (expectDiagKeys != null)
   568                 expectDiagKeys.remove(diagnostic.getCode());
   570             switch (diagnostic.getType()) {
   571             case FRAGMENT:
   572                 throw new IllegalArgumentException();
   574             case NOTE:
   575                 // Print out notes only when we are permitted to report warnings
   576                 // Notes are only generated at the end of a compilation, so should be small
   577                 // in number.
   578                 if ((emitWarnings || diagnostic.isMandatory()) && !suppressNotes) {
   579                     writeDiagnostic(diagnostic);
   580                 }
   581                 break;
   583             case WARNING:
   584                 if (emitWarnings || diagnostic.isMandatory()) {
   585                     if (nwarnings < MaxWarnings) {
   586                         writeDiagnostic(diagnostic);
   587                         nwarnings++;
   588                     }
   589                 }
   590                 break;
   592             case ERROR:
   593                 if (nerrors < MaxErrors
   594                     && shouldReport(diagnostic.getSource(), diagnostic.getIntPosition())) {
   595                     writeDiagnostic(diagnostic);
   596                     nerrors++;
   597                 }
   598                 break;
   599             }
   600         }
   601     }
   603     /**
   604      * Write out a diagnostic.
   605      */
   606     protected void writeDiagnostic(JCDiagnostic diag) {
   607         if (diagListener != null) {
   608             diagListener.report(diag);
   609             return;
   610         }
   612         PrintWriter writer = getWriterForDiagnosticType(diag.getType());
   614         printRawLines(writer, diagFormatter.format(diag, messages.getCurrentLocale()));
   616         if (promptOnError) {
   617             switch (diag.getType()) {
   618             case ERROR:
   619             case WARNING:
   620                 prompt();
   621             }
   622         }
   624         if (dumpOnError)
   625             new RuntimeException().printStackTrace(writer);
   627         writer.flush();
   628     }
   630     @Deprecated
   631     protected PrintWriter getWriterForDiagnosticType(DiagnosticType dt) {
   632         switch (dt) {
   633         case FRAGMENT:
   634             throw new IllegalArgumentException();
   636         case NOTE:
   637             return noticeWriter;
   639         case WARNING:
   640             return warnWriter;
   642         case ERROR:
   643             return errWriter;
   645         default:
   646             throw new Error();
   647         }
   648     }
   650     /** Find a localized string in the resource bundle.
   651      *  Because this method is static, it ignores the locale.
   652      *  Use localize(key, args) when possible.
   653      *  @param key    The key for the localized string.
   654      *  @param args   Fields to substitute into the string.
   655      */
   656     public static String getLocalizedString(String key, Object ... args) {
   657         return JavacMessages.getDefaultLocalizedString(PrefixKind.COMPILER_MISC.key(key), args);
   658     }
   660     /** Find a localized string in the resource bundle.
   661      *  @param key    The key for the localized string.
   662      *  @param args   Fields to substitute into the string.
   663      */
   664     public String localize(String key, Object... args) {
   665         return localize(PrefixKind.COMPILER_MISC, key, args);
   666     }
   668     /** Find a localized string in the resource bundle.
   669      *  @param key    The key for the localized string.
   670      *  @param args   Fields to substitute into the string.
   671      */
   672     public String localize(PrefixKind pk, String key, Object... args) {
   673         if (useRawMessages)
   674             return pk.key(key);
   675         else
   676             return messages.getLocalizedString(pk.key(key), args);
   677     }
   678     // where
   679         // backdoor hook for testing, should transition to use -XDrawDiagnostics
   680         private static boolean useRawMessages = false;
   682 /***************************************************************************
   683  * raw error messages without internationalization; used for experimentation
   684  * and quick prototyping
   685  ***************************************************************************/
   687     /** print an error or warning message:
   688      */
   689     private void printRawError(int pos, String msg) {
   690         if (source == null || pos == Position.NOPOS) {
   691             printRawLines(errWriter, "error: " + msg);
   692         } else {
   693             int line = source.getLineNumber(pos);
   694             JavaFileObject file = source.getFile();
   695             if (file != null)
   696                 printRawLines(errWriter,
   697                            file.getName() + ":" +
   698                            line + ": " + msg);
   699             printErrLine(pos, errWriter);
   700         }
   701         errWriter.flush();
   702     }
   704     /** report an error:
   705      */
   706     public void rawError(int pos, String msg) {
   707         if (nerrors < MaxErrors && shouldReport(currentSourceFile(), pos)) {
   708             printRawError(pos, msg);
   709             prompt();
   710             nerrors++;
   711         }
   712         errWriter.flush();
   713     }
   715     /** report a warning:
   716      */
   717     public void rawWarning(int pos, String msg) {
   718         if (nwarnings < MaxWarnings && emitWarnings) {
   719             printRawError(pos, "warning: " + msg);
   720         }
   721         prompt();
   722         nwarnings++;
   723         errWriter.flush();
   724     }
   726     public static String format(String fmt, Object... args) {
   727         return String.format((java.util.Locale)null, fmt, args);
   728     }
   730 }

mercurial