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

Tue, 13 Jul 2010 19:14:09 -0700

author
jjg
date
Tue, 13 Jul 2010 19:14:09 -0700
changeset 604
a5454419dd46
parent 584
d1ea43cb71c1
child 664
4124840b35fe
permissions
-rw-r--r--

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

mercurial