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

Thu, 10 Jun 2010 16:08:01 -0700

author
jjg
date
Thu, 10 Jun 2010 16:08:01 -0700
changeset 581
f2fdd52e4e87
parent 554
9d9f26857129
child 584
d1ea43cb71c1
permissions
-rw-r--r--

6944312: Potential rebranding issues in openjdk/langtools repository sources
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", 100);
   129         this.MaxWarnings = getIntOption(options, "-Xmaxwarns", 100);
   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     /** The default writer for diagnostics
   159      */
   160     static final PrintWriter defaultWriter(Context context) {
   161         PrintWriter result = context.get(outKey);
   162         if (result == null)
   163             context.put(outKey, result = new PrintWriter(System.err));
   164         return result;
   165     }
   167     /** Construct a log with default settings.
   168      */
   169     protected Log(Context context) {
   170         this(context, defaultWriter(context));
   171     }
   173     /** Construct a log with all output redirected.
   174      */
   175     protected Log(Context context, PrintWriter defaultWriter) {
   176         this(context, defaultWriter, defaultWriter, defaultWriter);
   177     }
   179     /** Get the Log instance for this context. */
   180     public static Log instance(Context context) {
   181         Log instance = context.get(logKey);
   182         if (instance == null)
   183             instance = new Log(context);
   184         return instance;
   185     }
   187     /** The number of errors encountered so far.
   188      */
   189     public int nerrors = 0;
   191     /** The number of warnings encountered so far.
   192      */
   193     public int nwarnings = 0;
   195     /**
   196      * Whether or not an unrecoverable error has been seen.
   197      * Unrecoverable errors prevent subsequent annotation processing.
   198      */
   199     public boolean unrecoverableError;
   201     /** A set of all errors generated so far. This is used to avoid printing an
   202      *  error message more than once. For each error, a pair consisting of the
   203      *  source file name and source code position of the error is added to the set.
   204      */
   205     private Set<Pair<JavaFileObject, Integer>> recorded = new HashSet<Pair<JavaFileObject,Integer>>();
   207     public boolean hasDiagnosticListener() {
   208         return diagListener != null;
   209     }
   211     public void setEndPosTable(JavaFileObject name, Map<JCTree, Integer> table) {
   212         name.getClass(); // null check
   213         getSource(name).setEndPosTable(table);
   214     }
   216     /** Return current sourcefile.
   217      */
   218     public JavaFileObject currentSourceFile() {
   219         return source == null ? null : source.getFile();
   220     }
   222     /** Get the current diagnostic formatter.
   223      */
   224     public DiagnosticFormatter<JCDiagnostic> getDiagnosticFormatter() {
   225         return diagFormatter;
   226     }
   228     /** Set the current diagnostic formatter.
   229      */
   230     public void setDiagnosticFormatter(DiagnosticFormatter<JCDiagnostic> diagFormatter) {
   231         this.diagFormatter = diagFormatter;
   232     }
   234     /** Flush the logs
   235      */
   236     public void flush() {
   237         errWriter.flush();
   238         warnWriter.flush();
   239         noticeWriter.flush();
   240     }
   242     /** Returns true if an error needs to be reported for a given
   243      * source name and pos.
   244      */
   245     protected boolean shouldReport(JavaFileObject file, int pos) {
   246         if (multipleErrors || file == null)
   247             return true;
   249         Pair<JavaFileObject,Integer> coords = new Pair<JavaFileObject,Integer>(file, pos);
   250         boolean shouldReport = !recorded.contains(coords);
   251         if (shouldReport)
   252             recorded.add(coords);
   253         return shouldReport;
   254     }
   256     /** Prompt user after an error.
   257      */
   258     public void prompt() {
   259         if (promptOnError) {
   260             System.err.println(getLocalizedString("resume.abort"));
   261             char ch;
   262             try {
   263                 while (true) {
   264                     switch (System.in.read()) {
   265                     case 'a': case 'A':
   266                         System.exit(-1);
   267                         return;
   268                     case 'r': case 'R':
   269                         return;
   270                     case 'x': case 'X':
   271                         throw new AssertionError("user abort");
   272                     default:
   273                     }
   274                 }
   275             } catch (IOException e) {}
   276         }
   277     }
   279     /** Print the faulty source code line and point to the error.
   280      *  @param pos   Buffer index of the error position, must be on current line
   281      */
   282     private void printErrLine(int pos, PrintWriter writer) {
   283         String line = (source == null ? null : source.getLine(pos));
   284         if (line == null)
   285             return;
   286         int col = source.getColumnNumber(pos, false);
   288         printLines(writer, line);
   289         for (int i = 0; i < col - 1; i++) {
   290             writer.print((line.charAt(i) == '\t') ? "\t" : " ");
   291         }
   292         writer.println("^");
   293         writer.flush();
   294     }
   296     /** Print the text of a message, translating newlines appropriately
   297      *  for the platform.
   298      */
   299     public static void printLines(PrintWriter writer, String msg) {
   300         int nl;
   301         while ((nl = msg.indexOf('\n')) != -1) {
   302             writer.println(msg.substring(0, nl));
   303             msg = msg.substring(nl+1);
   304         }
   305         if (msg.length() != 0) writer.println(msg);
   306     }
   308     protected void directError(String key, Object... args) {
   309         printLines(errWriter, getLocalizedString(key, args));
   310         errWriter.flush();
   311     }
   313     /** Report a warning that cannot be suppressed.
   314      *  @param pos    The source position at which to report the warning.
   315      *  @param key    The key for the localized warning message.
   316      *  @param args   Fields of the warning message.
   317      */
   318     public void strictWarning(DiagnosticPosition pos, String key, Object ... args) {
   319         writeDiagnostic(diags.warning(source, pos, key, args));
   320         nwarnings++;
   321     }
   323     /**
   324      * Common diagnostic handling.
   325      * The diagnostic is counted, and depending on the options and how many diagnostics have been
   326      * reported so far, the diagnostic may be handed off to writeDiagnostic.
   327      */
   328     public void report(JCDiagnostic diagnostic) {
   329         if (expectDiagKeys != null)
   330             expectDiagKeys.remove(diagnostic.getCode());
   332         switch (diagnostic.getType()) {
   333         case FRAGMENT:
   334             throw new IllegalArgumentException();
   336         case NOTE:
   337             // Print out notes only when we are permitted to report warnings
   338             // Notes are only generated at the end of a compilation, so should be small
   339             // in number.
   340             if ((emitWarnings || diagnostic.isMandatory()) && !suppressNotes) {
   341                 writeDiagnostic(diagnostic);
   342             }
   343             break;
   345         case WARNING:
   346             if (emitWarnings || diagnostic.isMandatory()) {
   347                 if (nwarnings < MaxWarnings) {
   348                     writeDiagnostic(diagnostic);
   349                     nwarnings++;
   350                 }
   351             }
   352             break;
   354         case ERROR:
   355             if (nerrors < MaxErrors
   356                 && shouldReport(diagnostic.getSource(), diagnostic.getIntPosition())) {
   357                 writeDiagnostic(diagnostic);
   358                 nerrors++;
   359             }
   360             break;
   361         }
   362     }
   364     /**
   365      * Write out a diagnostic.
   366      */
   367     protected void writeDiagnostic(JCDiagnostic diag) {
   368         if (diagListener != null) {
   369             try {
   370                 diagListener.report(diag);
   371                 return;
   372             }
   373             catch (Throwable t) {
   374                 throw new ClientCodeException(t);
   375             }
   376         }
   378         PrintWriter writer = getWriterForDiagnosticType(diag.getType());
   380         printLines(writer, diagFormatter.format(diag, messages.getCurrentLocale()));
   382         if (promptOnError) {
   383             switch (diag.getType()) {
   384             case ERROR:
   385             case WARNING:
   386                 prompt();
   387             }
   388         }
   390         if (dumpOnError)
   391             new RuntimeException().printStackTrace(writer);
   393         writer.flush();
   394     }
   396     @Deprecated
   397     protected PrintWriter getWriterForDiagnosticType(DiagnosticType dt) {
   398         switch (dt) {
   399         case FRAGMENT:
   400             throw new IllegalArgumentException();
   402         case NOTE:
   403             return noticeWriter;
   405         case WARNING:
   406             return warnWriter;
   408         case ERROR:
   409             return errWriter;
   411         default:
   412             throw new Error();
   413         }
   414     }
   416     /** Find a localized string in the resource bundle.
   417      *  @param key    The key for the localized string.
   418      *  @param args   Fields to substitute into the string.
   419      */
   420     public static String getLocalizedString(String key, Object ... args) {
   421         return JavacMessages.getDefaultLocalizedString("compiler.misc." + key, args);
   422     }
   424 /***************************************************************************
   425  * raw error messages without internationalization; used for experimentation
   426  * and quick prototyping
   427  ***************************************************************************/
   429     /** print an error or warning message:
   430      */
   431     private void printRawError(int pos, String msg) {
   432         if (source == null || pos == Position.NOPOS) {
   433             printLines(errWriter, "error: " + msg);
   434         } else {
   435             int line = source.getLineNumber(pos);
   436             JavaFileObject file = source.getFile();
   437             if (file != null)
   438                 printLines(errWriter,
   439                            file.getName() + ":" +
   440                            line + ": " + msg);
   441             printErrLine(pos, errWriter);
   442         }
   443         errWriter.flush();
   444     }
   446     /** report an error:
   447      */
   448     public void rawError(int pos, String msg) {
   449         if (nerrors < MaxErrors && shouldReport(currentSourceFile(), pos)) {
   450             printRawError(pos, msg);
   451             prompt();
   452             nerrors++;
   453         }
   454         errWriter.flush();
   455     }
   457     /** report a warning:
   458      */
   459     public void rawWarning(int pos, String msg) {
   460         if (nwarnings < MaxWarnings && emitWarnings) {
   461             printRawError(pos, "warning: " + msg);
   462         }
   463         prompt();
   464         nwarnings++;
   465         errWriter.flush();
   466     }
   468     public static String format(String fmt, Object... args) {
   469         return String.format((java.util.Locale)null, fmt, args);
   470     }
   472 }

mercurial