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

Wed, 20 Jun 2012 13:23:26 -0700

author
jjg
date
Wed, 20 Jun 2012 13:23:26 -0700
changeset 1280
5c0b3faeb0b0
parent 1159
4261dc8af622
child 1323
1a7c11b22192
permissions
-rw-r--r--

7174143: encapsulate doc comment table
Reviewed-by: ksrini, mcimadamore

     1 /*
     2  * Copyright (c) 1999, 2012, 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     public enum WriterKind { NOTICE, WARNING, ERROR };
    78     protected PrintWriter errWriter;
    80     protected PrintWriter warnWriter;
    82     protected PrintWriter noticeWriter;
    84     /** The maximum number of errors/warnings that are reported.
    85      */
    86     protected int MaxErrors;
    87     protected int MaxWarnings;
    89     /** Switch: prompt user on each error.
    90      */
    91     public boolean promptOnError;
    93     /** Switch: emit warning messages.
    94      */
    95     public boolean emitWarnings;
    97     /** Switch: suppress note messages.
    98      */
    99     public boolean suppressNotes;
   101     /** Print stack trace on errors?
   102      */
   103     public boolean dumpOnError;
   105     /** Print multiple errors for same source locations.
   106      */
   107     public boolean multipleErrors;
   109     /**
   110      * Diagnostic listener, if provided through programmatic
   111      * interface to javac (JSR 199).
   112      */
   113     protected DiagnosticListener<? super JavaFileObject> diagListener;
   115     /**
   116      * Formatter for diagnostics.
   117      */
   118     private DiagnosticFormatter<JCDiagnostic> diagFormatter;
   120     /**
   121      * Keys for expected diagnostics.
   122      */
   123     public Set<String> expectDiagKeys;
   125     /**
   126      * JavacMessages object used for localization.
   127      */
   128     private JavacMessages messages;
   130     /**
   131      * Deferred diagnostics
   132      */
   133     public boolean deferDiagnostics;
   134     public Queue<JCDiagnostic> deferredDiagnostics = new ListBuffer<JCDiagnostic>();
   136     /** Construct a log with given I/O redirections.
   137      */
   138     protected Log(Context context, PrintWriter errWriter, PrintWriter warnWriter, PrintWriter noticeWriter) {
   139         super(JCDiagnostic.Factory.instance(context));
   140         context.put(logKey, this);
   141         this.errWriter = errWriter;
   142         this.warnWriter = warnWriter;
   143         this.noticeWriter = noticeWriter;
   145         @SuppressWarnings("unchecked") // FIXME
   146         DiagnosticListener<? super JavaFileObject> dl =
   147             context.get(DiagnosticListener.class);
   148         this.diagListener = dl;
   150         messages = JavacMessages.instance(context);
   151         messages.add(Main.javacBundleName);
   153         final Options options = Options.instance(context);
   154         initOptions(options);
   155         options.addListener(new Runnable() {
   156             public void run() {
   157                 initOptions(options);
   158             }
   159         });
   160     }
   161     // where
   162         private void initOptions(Options options) {
   163             this.dumpOnError = options.isSet(DOE);
   164             this.promptOnError = options.isSet(PROMPT);
   165             this.emitWarnings = options.isUnset(XLINT_CUSTOM, "none");
   166             this.suppressNotes = options.isSet("suppressNotes");
   167             this.MaxErrors = getIntOption(options, XMAXERRS, getDefaultMaxErrors());
   168             this.MaxWarnings = getIntOption(options, XMAXWARNS, getDefaultMaxWarnings());
   170             boolean rawDiagnostics = options.isSet("rawDiagnostics");
   171             this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(options) :
   172                                                   new BasicDiagnosticFormatter(options, messages);
   174             String ek = options.get("expectKeys");
   175             if (ek != null)
   176                 expectDiagKeys = new HashSet<String>(Arrays.asList(ek.split(", *")));
   177         }
   179         private int getIntOption(Options options, Option option, int defaultValue) {
   180             String s = options.get(option);
   181             try {
   182                 if (s != null) {
   183                     int n = Integer.parseInt(s);
   184                     return (n <= 0 ? Integer.MAX_VALUE : n);
   185                 }
   186             } catch (NumberFormatException e) {
   187                 // silently ignore ill-formed numbers
   188             }
   189             return defaultValue;
   190         }
   192         /** Default value for -Xmaxerrs.
   193          */
   194         protected int getDefaultMaxErrors() {
   195             return 100;
   196         }
   198         /** Default value for -Xmaxwarns.
   199          */
   200         protected int getDefaultMaxWarnings() {
   201             return 100;
   202         }
   204     /** The default writer for diagnostics
   205      */
   206     static PrintWriter defaultWriter(Context context) {
   207         PrintWriter result = context.get(outKey);
   208         if (result == null)
   209             context.put(outKey, result = new PrintWriter(System.err));
   210         return result;
   211     }
   213     /** Construct a log with default settings.
   214      */
   215     protected Log(Context context) {
   216         this(context, defaultWriter(context));
   217     }
   219     /** Construct a log with all output redirected.
   220      */
   221     protected Log(Context context, PrintWriter defaultWriter) {
   222         this(context, defaultWriter, defaultWriter, defaultWriter);
   223     }
   225     /** Get the Log instance for this context. */
   226     public static Log instance(Context context) {
   227         Log instance = context.get(logKey);
   228         if (instance == null)
   229             instance = new Log(context);
   230         return instance;
   231     }
   233     /** The number of errors encountered so far.
   234      */
   235     public int nerrors = 0;
   237     /** The number of warnings encountered so far.
   238      */
   239     public int nwarnings = 0;
   241     /** A set of all errors generated so far. This is used to avoid printing an
   242      *  error message more than once. For each error, a pair consisting of the
   243      *  source file name and source code position of the error is added to the set.
   244      */
   245     private Set<Pair<JavaFileObject, Integer>> recorded = new HashSet<Pair<JavaFileObject,Integer>>();
   247     public boolean hasDiagnosticListener() {
   248         return diagListener != null;
   249     }
   251     public void setEndPosTable(JavaFileObject name, EndPosTable endPosTable) {
   252         name.getClass(); // null check
   253         getSource(name).setEndPosTable(endPosTable);
   254     }
   256     /** Return current sourcefile.
   257      */
   258     public JavaFileObject currentSourceFile() {
   259         return source == null ? null : source.getFile();
   260     }
   262     /** Get the current diagnostic formatter.
   263      */
   264     public DiagnosticFormatter<JCDiagnostic> getDiagnosticFormatter() {
   265         return diagFormatter;
   266     }
   268     /** Set the current diagnostic formatter.
   269      */
   270     public void setDiagnosticFormatter(DiagnosticFormatter<JCDiagnostic> diagFormatter) {
   271         this.diagFormatter = diagFormatter;
   272     }
   274     public PrintWriter getWriter(WriterKind kind) {
   275         switch (kind) {
   276             case NOTICE:    return noticeWriter;
   277             case WARNING:   return warnWriter;
   278             case ERROR:     return errWriter;
   279             default:        throw new IllegalArgumentException();
   280         }
   281     }
   283     public void setWriter(WriterKind kind, PrintWriter pw) {
   284         pw.getClass();
   285         switch (kind) {
   286             case NOTICE:    noticeWriter = pw;  break;
   287             case WARNING:   warnWriter = pw;    break;
   288             case ERROR:     errWriter = pw;     break;
   289             default:        throw new IllegalArgumentException();
   290         }
   291     }
   293     public void setWriters(PrintWriter pw) {
   294         pw.getClass();
   295         noticeWriter = warnWriter = errWriter = pw;
   296     }
   298     public void setWriters(Log other) {
   299         this.noticeWriter = other.noticeWriter;
   300         this.warnWriter = other.warnWriter;
   301         this.errWriter = other.errWriter;
   302     }
   304     /** Flush the logs
   305      */
   306     public void flush() {
   307         errWriter.flush();
   308         warnWriter.flush();
   309         noticeWriter.flush();
   310     }
   312     public void flush(WriterKind kind) {
   313         getWriter(kind).flush();
   314     }
   316     /** Returns true if an error needs to be reported for a given
   317      * source name and pos.
   318      */
   319     protected boolean shouldReport(JavaFileObject file, int pos) {
   320         if (multipleErrors || file == null)
   321             return true;
   323         Pair<JavaFileObject,Integer> coords = new Pair<JavaFileObject,Integer>(file, pos);
   324         boolean shouldReport = !recorded.contains(coords);
   325         if (shouldReport)
   326             recorded.add(coords);
   327         return shouldReport;
   328     }
   330     /** Prompt user after an error.
   331      */
   332     public void prompt() {
   333         if (promptOnError) {
   334             System.err.println(localize("resume.abort"));
   335             try {
   336                 while (true) {
   337                     switch (System.in.read()) {
   338                     case 'a': case 'A':
   339                         System.exit(-1);
   340                         return;
   341                     case 'r': case 'R':
   342                         return;
   343                     case 'x': case 'X':
   344                         throw new AssertionError("user abort");
   345                     default:
   346                     }
   347                 }
   348             } catch (IOException e) {}
   349         }
   350     }
   352     /** Print the faulty source code line and point to the error.
   353      *  @param pos   Buffer index of the error position, must be on current line
   354      */
   355     private void printErrLine(int pos, PrintWriter writer) {
   356         String line = (source == null ? null : source.getLine(pos));
   357         if (line == null)
   358             return;
   359         int col = source.getColumnNumber(pos, false);
   361         printRawLines(writer, line);
   362         for (int i = 0; i < col - 1; i++) {
   363             writer.print((line.charAt(i) == '\t') ? "\t" : " ");
   364         }
   365         writer.println("^");
   366         writer.flush();
   367     }
   369     public void printNewline() {
   370         noticeWriter.println();
   371     }
   373     public void printNewline(WriterKind wk) {
   374         getWriter(wk).println();
   375     }
   377     public void printLines(String key, Object... args) {
   378         printRawLines(noticeWriter, localize(key, args));
   379     }
   381     public void printLines(PrefixKind pk, String key, Object... args) {
   382         printRawLines(noticeWriter, localize(pk, key, args));
   383     }
   385     public void printLines(WriterKind wk, String key, Object... args) {
   386         printRawLines(getWriter(wk), localize(key, args));
   387     }
   389     public void printLines(WriterKind wk, PrefixKind pk, String key, Object... args) {
   390         printRawLines(getWriter(wk), localize(pk, key, args));
   391     }
   393     /** Print the text of a message, translating newlines appropriately
   394      *  for the platform.
   395      */
   396     public void printRawLines(String msg) {
   397         printRawLines(noticeWriter, msg);
   398     }
   400     /** Print the text of a message, translating newlines appropriately
   401      *  for the platform.
   402      */
   403     public void printRawLines(WriterKind kind, String msg) {
   404         printRawLines(getWriter(kind), msg);
   405     }
   407     /** Print the text of a message, translating newlines appropriately
   408      *  for the platform.
   409      */
   410     public static void printRawLines(PrintWriter writer, String msg) {
   411         int nl;
   412         while ((nl = msg.indexOf('\n')) != -1) {
   413             writer.println(msg.substring(0, nl));
   414             msg = msg.substring(nl+1);
   415         }
   416         if (msg.length() != 0) writer.println(msg);
   417     }
   419     /**
   420      * Print the localized text of a "verbose" message to the
   421      * noticeWriter stream.
   422      */
   423     public void printVerbose(String key, Object... args) {
   424         printRawLines(noticeWriter, localize("verbose." + key, args));
   425     }
   427     protected void directError(String key, Object... args) {
   428         printRawLines(errWriter, localize(key, args));
   429         errWriter.flush();
   430     }
   432     /** Report a warning that cannot be suppressed.
   433      *  @param pos    The source position at which to report the warning.
   434      *  @param key    The key for the localized warning message.
   435      *  @param args   Fields of the warning message.
   436      */
   437     public void strictWarning(DiagnosticPosition pos, String key, Object ... args) {
   438         writeDiagnostic(diags.warning(source, pos, key, args));
   439         nwarnings++;
   440     }
   442     /** Report all deferred diagnostics, and clear the deferDiagnostics flag. */
   443     public void reportDeferredDiagnostics() {
   444         reportDeferredDiagnostics(EnumSet.allOf(JCDiagnostic.Kind.class));
   445     }
   447     /** Report selected deferred diagnostics, and clear the deferDiagnostics flag. */
   448     public void reportDeferredDiagnostics(Set<JCDiagnostic.Kind> kinds) {
   449         deferDiagnostics = false;
   450         JCDiagnostic d;
   451         while ((d = deferredDiagnostics.poll()) != null) {
   452             if (kinds.contains(d.getKind()))
   453                 report(d);
   454         }
   455     }
   457     /**
   458      * Common diagnostic handling.
   459      * The diagnostic is counted, and depending on the options and how many diagnostics have been
   460      * reported so far, the diagnostic may be handed off to writeDiagnostic.
   461      */
   462     public void report(JCDiagnostic diagnostic) {
   463         if (deferDiagnostics) {
   464             deferredDiagnostics.add(diagnostic);
   465             return;
   466         }
   468         if (expectDiagKeys != null)
   469             expectDiagKeys.remove(diagnostic.getCode());
   471         switch (diagnostic.getType()) {
   472         case FRAGMENT:
   473             throw new IllegalArgumentException();
   475         case NOTE:
   476             // Print out notes only when we are permitted to report warnings
   477             // Notes are only generated at the end of a compilation, so should be small
   478             // in number.
   479             if ((emitWarnings || diagnostic.isMandatory()) && !suppressNotes) {
   480                 writeDiagnostic(diagnostic);
   481             }
   482             break;
   484         case WARNING:
   485             if (emitWarnings || diagnostic.isMandatory()) {
   486                 if (nwarnings < MaxWarnings) {
   487                     writeDiagnostic(diagnostic);
   488                     nwarnings++;
   489                 }
   490             }
   491             break;
   493         case ERROR:
   494             if (nerrors < MaxErrors
   495                 && shouldReport(diagnostic.getSource(), diagnostic.getIntPosition())) {
   496                 writeDiagnostic(diagnostic);
   497                 nerrors++;
   498             }
   499             break;
   500         }
   501     }
   503     /**
   504      * Write out a diagnostic.
   505      */
   506     protected void writeDiagnostic(JCDiagnostic diag) {
   507         if (diagListener != null) {
   508             diagListener.report(diag);
   509             return;
   510         }
   512         PrintWriter writer = getWriterForDiagnosticType(diag.getType());
   514         printRawLines(writer, diagFormatter.format(diag, messages.getCurrentLocale()));
   516         if (promptOnError) {
   517             switch (diag.getType()) {
   518             case ERROR:
   519             case WARNING:
   520                 prompt();
   521             }
   522         }
   524         if (dumpOnError)
   525             new RuntimeException().printStackTrace(writer);
   527         writer.flush();
   528     }
   530     @Deprecated
   531     protected PrintWriter getWriterForDiagnosticType(DiagnosticType dt) {
   532         switch (dt) {
   533         case FRAGMENT:
   534             throw new IllegalArgumentException();
   536         case NOTE:
   537             return noticeWriter;
   539         case WARNING:
   540             return warnWriter;
   542         case ERROR:
   543             return errWriter;
   545         default:
   546             throw new Error();
   547         }
   548     }
   550     /** Find a localized string in the resource bundle.
   551      *  Because this method is static, it ignores the locale.
   552      *  Use localize(key, args) when possible.
   553      *  @param key    The key for the localized string.
   554      *  @param args   Fields to substitute into the string.
   555      */
   556     public static String getLocalizedString(String key, Object ... args) {
   557         return JavacMessages.getDefaultLocalizedString(PrefixKind.COMPILER_MISC.key(key), args);
   558     }
   560     /** Find a localized string in the resource bundle.
   561      *  @param key    The key for the localized string.
   562      *  @param args   Fields to substitute into the string.
   563      */
   564     public String localize(String key, Object... args) {
   565         return localize(PrefixKind.COMPILER_MISC, key, args);
   566     }
   568     /** Find a localized string in the resource bundle.
   569      *  @param key    The key for the localized string.
   570      *  @param args   Fields to substitute into the string.
   571      */
   572     public String localize(PrefixKind pk, String key, Object... args) {
   573         if (useRawMessages)
   574             return pk.key(key);
   575         else
   576             return messages.getLocalizedString(pk.key(key), args);
   577     }
   578     // where
   579         // backdoor hook for testing, should transition to use -XDrawDiagnostics
   580         private static boolean useRawMessages = false;
   582 /***************************************************************************
   583  * raw error messages without internationalization; used for experimentation
   584  * and quick prototyping
   585  ***************************************************************************/
   587     /** print an error or warning message:
   588      */
   589     private void printRawError(int pos, String msg) {
   590         if (source == null || pos == Position.NOPOS) {
   591             printRawLines(errWriter, "error: " + msg);
   592         } else {
   593             int line = source.getLineNumber(pos);
   594             JavaFileObject file = source.getFile();
   595             if (file != null)
   596                 printRawLines(errWriter,
   597                            file.getName() + ":" +
   598                            line + ": " + msg);
   599             printErrLine(pos, errWriter);
   600         }
   601         errWriter.flush();
   602     }
   604     /** report an error:
   605      */
   606     public void rawError(int pos, String msg) {
   607         if (nerrors < MaxErrors && shouldReport(currentSourceFile(), pos)) {
   608             printRawError(pos, msg);
   609             prompt();
   610             nerrors++;
   611         }
   612         errWriter.flush();
   613     }
   615     /** report a warning:
   616      */
   617     public void rawWarning(int pos, String msg) {
   618         if (nwarnings < MaxWarnings && emitWarnings) {
   619             printRawError(pos, "warning: " + msg);
   620         }
   621         prompt();
   622         nwarnings++;
   623         errWriter.flush();
   624     }
   626     public static String format(String fmt, Object... args) {
   627         return String.format((java.util.Locale)null, fmt, args);
   628     }
   630 }

mercurial