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

Mon, 19 Jan 2009 19:36:14 -0800

author
jjg
date
Mon, 19 Jan 2009 19:36:14 -0800
changeset 194
d0b33fe8e710
parent 168
4cdaaf4c5dca
child 221
6ada6122dd4f
permissions
-rw-r--r--

6794959: add new switch -XDexpectKeys=key,key....
Reviewed-by: mcimadamore

     1 /*
     2  * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Sun designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Sun in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    22  * CA 95054 USA or visit www.sun.com if you need additional information or
    23  * have any questions.
    24  */
    26 package com.sun.tools.javac.util;
    28 import java.io.*;
    29 import java.util.Arrays;
    30 import java.util.HashSet;
    31 import java.util.Map;
    32 import java.util.Set;
    33 import javax.tools.DiagnosticListener;
    34 import javax.tools.JavaFileObject;
    36 import com.sun.tools.javac.file.JavacFileManager;
    37 import com.sun.tools.javac.tree.JCTree;
    38 import com.sun.tools.javac.api.DiagnosticFormatter;
    39 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    40 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
    42 /** A class for error logs. Reports errors and warnings, and
    43  *  keeps track of error numbers and positions.
    44  *
    45  *  <p><b>This is NOT part of any API supported by Sun Microsystems.  If
    46  *  you write code that depends on this, you do so at your own risk.
    47  *  This code and its internal interfaces are subject to change or
    48  *  deletion without notice.</b>
    49  */
    50 public class Log extends AbstractLog {
    51     /** The context key for the log. */
    52     public static final Context.Key<Log> logKey
    53         = new Context.Key<Log>();
    55     /** The context key for the output PrintWriter. */
    56     public static final Context.Key<PrintWriter> outKey =
    57         new Context.Key<PrintWriter>();
    59     //@Deprecated
    60     public final PrintWriter errWriter;
    62     //@Deprecated
    63     public final PrintWriter warnWriter;
    65     //@Deprecated
    66     public final PrintWriter noticeWriter;
    68     /** The maximum number of errors/warnings that are reported.
    69      */
    70     public final int MaxErrors;
    71     public final int MaxWarnings;
    73     /** Switch: prompt user on each error.
    74      */
    75     public boolean promptOnError;
    77     /** Switch: emit warning messages.
    78      */
    79     public boolean emitWarnings;
    81     /** Print stack trace on errors?
    82      */
    83     public boolean dumpOnError;
    85     /** Print multiple errors for same source locations.
    86      */
    87     public boolean multipleErrors;
    89     /**
    90      * Diagnostic listener, if provided through programmatic
    91      * interface to javac (JSR 199).
    92      */
    93     protected DiagnosticListener<? super JavaFileObject> diagListener;
    95     /**
    96      * Formatter for diagnostics
    97      */
    98     private DiagnosticFormatter<JCDiagnostic> diagFormatter;
   100     /**
   101      * Keys for expected diagnostics
   102      */
   103     public Set<String> expectDiagKeys;
   105     /**
   106      * JavacMessages object used for localization
   107      */
   108     private JavacMessages messages;
   110     /** Construct a log with given I/O redirections.
   111      */
   112     @Deprecated
   113     protected Log(Context context, PrintWriter errWriter, PrintWriter warnWriter, PrintWriter noticeWriter) {
   114         super(JCDiagnostic.Factory.instance(context));
   115         context.put(logKey, this);
   116         this.errWriter = errWriter;
   117         this.warnWriter = warnWriter;
   118         this.noticeWriter = noticeWriter;
   120         Options options = Options.instance(context);
   121         this.dumpOnError = options.get("-doe") != null;
   122         this.promptOnError = options.get("-prompt") != null;
   123         this.emitWarnings = options.get("-Xlint:none") == null;
   124         this.MaxErrors = getIntOption(options, "-Xmaxerrs", 100);
   125         this.MaxWarnings = getIntOption(options, "-Xmaxwarns", 100);
   127         boolean rawDiagnostics = options.get("rawDiagnostics") != null;
   128         messages = JavacMessages.instance(context);
   129         this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(options) :
   130                                               new BasicDiagnosticFormatter(options, messages);
   131         @SuppressWarnings("unchecked") // FIXME
   132         DiagnosticListener<? super JavaFileObject> dl =
   133             context.get(DiagnosticListener.class);
   134         this.diagListener = dl;
   136         String ek = options.get("expectKeys");
   137         if (ek != null)
   138             expectDiagKeys = new HashSet<String>(Arrays.asList(ek.split(", *")));
   139     }
   140     // where
   141         private int getIntOption(Options options, String optionName, int defaultValue) {
   142             String s = options.get(optionName);
   143             try {
   144                 if (s != null) return Integer.parseInt(s);
   145             } catch (NumberFormatException e) {
   146                 // silently ignore ill-formed numbers
   147             }
   148             return defaultValue;
   149         }
   151     /** The default writer for diagnostics
   152      */
   153     static final PrintWriter defaultWriter(Context context) {
   154         PrintWriter result = context.get(outKey);
   155         if (result == null)
   156             context.put(outKey, result = new PrintWriter(System.err));
   157         return result;
   158     }
   160     /** Construct a log with default settings.
   161      */
   162     protected Log(Context context) {
   163         this(context, defaultWriter(context));
   164     }
   166     /** Construct a log with all output redirected.
   167      */
   168     protected Log(Context context, PrintWriter defaultWriter) {
   169         this(context, defaultWriter, defaultWriter, defaultWriter);
   170     }
   172     /** Get the Log instance for this context. */
   173     public static Log instance(Context context) {
   174         Log instance = context.get(logKey);
   175         if (instance == null)
   176             instance = new Log(context);
   177         return instance;
   178     }
   180     /** The number of errors encountered so far.
   181      */
   182     public int nerrors = 0;
   184     /** The number of warnings encountered so far.
   185      */
   186     public int nwarnings = 0;
   188     /** A set of all errors generated so far. This is used to avoid printing an
   189      *  error message more than once. For each error, a pair consisting of the
   190      *  source file name and source code position of the error is added to the set.
   191      */
   192     private Set<Pair<JavaFileObject, Integer>> recorded = new HashSet<Pair<JavaFileObject,Integer>>();
   194     public boolean hasDiagnosticListener() {
   195         return diagListener != null;
   196     }
   198     public void setEndPosTable(JavaFileObject name, Map<JCTree, Integer> table) {
   199         name.getClass(); // null check
   200         getSource(name).setEndPosTable(table);
   201     }
   203     /** Return current sourcefile.
   204      */
   205     public JavaFileObject currentSourceFile() {
   206         return source == null ? null : source.getFile();
   207     }
   209     /** Flush the logs
   210      */
   211     public void flush() {
   212         errWriter.flush();
   213         warnWriter.flush();
   214         noticeWriter.flush();
   215     }
   217     /** Returns true if an error needs to be reported for a given
   218      * source name and pos.
   219      */
   220     protected boolean shouldReport(JavaFileObject file, int pos) {
   221         if (multipleErrors || file == null)
   222             return true;
   224         Pair<JavaFileObject,Integer> coords = new Pair<JavaFileObject,Integer>(file, pos);
   225         boolean shouldReport = !recorded.contains(coords);
   226         if (shouldReport)
   227             recorded.add(coords);
   228         return shouldReport;
   229     }
   231     /** Prompt user after an error.
   232      */
   233     public void prompt() {
   234         if (promptOnError) {
   235             System.err.println(getLocalizedString("resume.abort"));
   236             char ch;
   237             try {
   238                 while (true) {
   239                     switch (System.in.read()) {
   240                     case 'a': case 'A':
   241                         System.exit(-1);
   242                         return;
   243                     case 'r': case 'R':
   244                         return;
   245                     case 'x': case 'X':
   246                         throw new AssertionError("user abort");
   247                     default:
   248                     }
   249                 }
   250             } catch (IOException e) {}
   251         }
   252     }
   254     /** Print the faulty source code line and point to the error.
   255      *  @param pos   Buffer index of the error position, must be on current line
   256      */
   257     private void printErrLine(int pos, PrintWriter writer) {
   258         String line = (source == null ? null : source.getLine(pos));
   259         if (line == null)
   260             return;
   261         int col = source.getColumnNumber(pos, false);
   263         printLines(writer, line);
   264         for (int i = 0; i < col - 1; i++) {
   265             writer.print((line.charAt(i) == '\t') ? "\t" : " ");
   266         }
   267         writer.println("^");
   268         writer.flush();
   269     }
   271     /** Print the text of a message, translating newlines appropriately
   272      *  for the platform.
   273      */
   274     public static void printLines(PrintWriter writer, String msg) {
   275         int nl;
   276         while ((nl = msg.indexOf('\n')) != -1) {
   277             writer.println(msg.substring(0, nl));
   278             msg = msg.substring(nl+1);
   279         }
   280         if (msg.length() != 0) writer.println(msg);
   281     }
   283     protected void directError(String key, Object... args) {
   284         printLines(errWriter, getLocalizedString(key, args));
   285         errWriter.flush();
   286     }
   288     /** Report a warning that cannot be suppressed.
   289      *  @param pos    The source position at which to report the warning.
   290      *  @param key    The key for the localized warning message.
   291      *  @param args   Fields of the warning message.
   292      */
   293     public void strictWarning(DiagnosticPosition pos, String key, Object ... args) {
   294         writeDiagnostic(diags.warning(source, pos, key, args));
   295         nwarnings++;
   296     }
   298     /**
   299      * Common diagnostic handling.
   300      * The diagnostic is counted, and depending on the options and how many diagnostics have been
   301      * reported so far, the diagnostic may be handed off to writeDiagnostic.
   302      */
   303     public void report(JCDiagnostic diagnostic) {
   304         if (expectDiagKeys != null)
   305             expectDiagKeys.remove(diagnostic.getCode());
   307         switch (diagnostic.getType()) {
   308         case FRAGMENT:
   309             throw new IllegalArgumentException();
   311         case NOTE:
   312             // Print out notes only when we are permitted to report warnings
   313             // Notes are only generated at the end of a compilation, so should be small
   314             // in number.
   315             if (emitWarnings || diagnostic.isMandatory()) {
   316                 writeDiagnostic(diagnostic);
   317             }
   318             break;
   320         case WARNING:
   321             if (emitWarnings || diagnostic.isMandatory()) {
   322                 if (nwarnings < MaxWarnings) {
   323                     writeDiagnostic(diagnostic);
   324                     nwarnings++;
   325                 }
   326             }
   327             break;
   329         case ERROR:
   330             if (nerrors < MaxErrors
   331                 && shouldReport(diagnostic.getSource(), diagnostic.getIntPosition())) {
   332                 writeDiagnostic(diagnostic);
   333                 nerrors++;
   334             }
   335             break;
   336         }
   337     }
   339     /**
   340      * Write out a diagnostic.
   341      */
   342     protected void writeDiagnostic(JCDiagnostic diag) {
   343         if (diagListener != null) {
   344             try {
   345                 diagListener.report(diag);
   346                 return;
   347             }
   348             catch (Throwable t) {
   349                 throw new ClientCodeException(t);
   350             }
   351         }
   353         PrintWriter writer = getWriterForDiagnosticType(diag.getType());
   355         printLines(writer, diagFormatter.format(diag, messages.getCurrentLocale()));
   357         if (promptOnError) {
   358             switch (diag.getType()) {
   359             case ERROR:
   360             case WARNING:
   361                 prompt();
   362             }
   363         }
   365         if (dumpOnError)
   366             new RuntimeException().printStackTrace(writer);
   368         writer.flush();
   369     }
   371     @Deprecated
   372     protected PrintWriter getWriterForDiagnosticType(DiagnosticType dt) {
   373         switch (dt) {
   374         case FRAGMENT:
   375             throw new IllegalArgumentException();
   377         case NOTE:
   378             return noticeWriter;
   380         case WARNING:
   381             return warnWriter;
   383         case ERROR:
   384             return errWriter;
   386         default:
   387             throw new Error();
   388         }
   389     }
   391     /** Find a localized string in the resource bundle.
   392      *  @param key    The key for the localized string.
   393      *  @param args   Fields to substitute into the string.
   394      */
   395     public static String getLocalizedString(String key, Object ... args) {
   396         return JavacMessages.getDefaultLocalizedString("compiler.misc." + key, args);
   397     }
   399 /***************************************************************************
   400  * raw error messages without internationalization; used for experimentation
   401  * and quick prototyping
   402  ***************************************************************************/
   404     /** print an error or warning message:
   405      */
   406     private void printRawError(int pos, String msg) {
   407         if (source == null || pos == Position.NOPOS) {
   408             printLines(errWriter, "error: " + msg);
   409         } else {
   410             int line = source.getLineNumber(pos);
   411             JavaFileObject file = source.getFile();
   412             if (file != null)
   413                 printLines(errWriter,
   414                            JavacFileManager.getJavacFileName(file) + ":" +
   415                            line + ": " + msg);
   416             printErrLine(pos, errWriter);
   417         }
   418         errWriter.flush();
   419     }
   421     /** report an error:
   422      */
   423     public void rawError(int pos, String msg) {
   424         if (nerrors < MaxErrors && shouldReport(currentSourceFile(), pos)) {
   425             printRawError(pos, msg);
   426             prompt();
   427             nerrors++;
   428         }
   429         errWriter.flush();
   430     }
   432     /** report a warning:
   433      */
   434     public void rawWarning(int pos, String msg) {
   435         if (nwarnings < MaxWarnings && emitWarnings) {
   436             printRawError(pos, "warning: " + msg);
   437         }
   438         prompt();
   439         nwarnings++;
   440         errWriter.flush();
   441     }
   443     public static String format(String fmt, Object... args) {
   444         return String.format((java.util.Locale)null, fmt, args);
   445     }
   447 }

mercurial