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

Mon, 14 Nov 2011 15:11:10 -0800

author
ksrini
date
Mon, 14 Nov 2011 15:11:10 -0800
changeset 1138
7375d4979bd3
parent 1136
ae361e7f435a
child 1157
3809292620c9
permissions
-rw-r--r--

7106166: (javac) re-factor EndPos parser
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2011, 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 com.sun.tools.javac.main.Main;
    29 import java.io.*;
    30 import java.util.Arrays;
    31 import java.util.EnumSet;
    32 import java.util.HashSet;
    33 import java.util.Map;
    34 import java.util.Queue;
    35 import java.util.Set;
    36 import javax.tools.DiagnosticListener;
    37 import javax.tools.JavaFileObject;
    39 import com.sun.tools.javac.api.DiagnosticFormatter;
    40 import com.sun.tools.javac.main.OptionName;
    41 import com.sun.tools.javac.parser.EndPosTable;
    42 import com.sun.tools.javac.tree.JCTree;
    43 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    44 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
    46 import static com.sun.tools.javac.main.OptionName.*;
    48 /** A class for error logs. Reports errors and warnings, and
    49  *  keeps track of error numbers and positions.
    50  *
    51  *  <p><b>This is NOT part of any supported API.
    52  *  If you write code that depends on this, you do so at your own risk.
    53  *  This code and its internal interfaces are subject to change or
    54  *  deletion without notice.</b>
    55  */
    56 public class Log extends AbstractLog {
    57     /** The context key for the log. */
    58     public static final Context.Key<Log> logKey
    59         = new Context.Key<Log>();
    61     /** The context key for the output PrintWriter. */
    62     public static final Context.Key<PrintWriter> outKey =
    63         new Context.Key<PrintWriter>();
    65     /* TODO: Should unify this with prefix handling in JCDiagnostic.Factory. */
    66     public enum PrefixKind {
    67         JAVAC("javac."),
    68         COMPILER_MISC("compiler.misc.");
    69         PrefixKind(String v) {
    70             value = v;
    71         }
    72         public String key(String k) {
    73             return value + k;
    74         }
    75         final String value;
    76     }
    78     public enum WriterKind { NOTICE, WARNING, ERROR };
    80     protected PrintWriter errWriter;
    82     protected PrintWriter warnWriter;
    84     protected PrintWriter noticeWriter;
    86     /** The maximum number of errors/warnings that are reported.
    87      */
    88     protected int MaxErrors;
    89     protected int MaxWarnings;
    91     /** Switch: prompt user on each error.
    92      */
    93     public boolean promptOnError;
    95     /** Switch: emit warning messages.
    96      */
    97     public boolean emitWarnings;
    99     /** Switch: suppress note messages.
   100      */
   101     public boolean suppressNotes;
   103     /** Print stack trace on errors?
   104      */
   105     public boolean dumpOnError;
   107     /** Print multiple errors for same source locations.
   108      */
   109     public boolean multipleErrors;
   111     /**
   112      * Diagnostic listener, if provided through programmatic
   113      * interface to javac (JSR 199).
   114      */
   115     protected DiagnosticListener<? super JavaFileObject> diagListener;
   117     /**
   118      * Formatter for diagnostics.
   119      */
   120     private DiagnosticFormatter<JCDiagnostic> diagFormatter;
   122     /**
   123      * Keys for expected diagnostics.
   124      */
   125     public Set<String> expectDiagKeys;
   127     /**
   128      * JavacMessages object used for localization.
   129      */
   130     private JavacMessages messages;
   132     /**
   133      * Deferred diagnostics
   134      */
   135     public boolean deferDiagnostics;
   136     public Queue<JCDiagnostic> deferredDiagnostics = new ListBuffer<JCDiagnostic>();
   138     /** Construct a log with given I/O redirections.
   139      */
   140     @Deprecated
   141     protected Log(Context context, PrintWriter errWriter, PrintWriter warnWriter, PrintWriter noticeWriter) {
   142         super(JCDiagnostic.Factory.instance(context));
   143         context.put(logKey, this);
   144         this.errWriter = errWriter;
   145         this.warnWriter = warnWriter;
   146         this.noticeWriter = noticeWriter;
   148         @SuppressWarnings("unchecked") // FIXME
   149         DiagnosticListener<? super JavaFileObject> dl =
   150             context.get(DiagnosticListener.class);
   151         this.diagListener = dl;
   153         messages = JavacMessages.instance(context);
   154         messages.add(Main.javacBundleName);
   156         final Options options = Options.instance(context);
   157         initOptions(options);
   158         options.addListener(new Runnable() {
   159             public void run() {
   160                 initOptions(options);
   161             }
   162         });
   163     }
   164     // where
   165         private void initOptions(Options options) {
   166             this.dumpOnError = options.isSet(DOE);
   167             this.promptOnError = options.isSet(PROMPT);
   168             this.emitWarnings = options.isUnset(XLINT_CUSTOM, "none");
   169             this.suppressNotes = options.isSet("suppressNotes");
   170             this.MaxErrors = getIntOption(options, XMAXERRS, getDefaultMaxErrors());
   171             this.MaxWarnings = getIntOption(options, XMAXWARNS, getDefaultMaxWarnings());
   173             boolean rawDiagnostics = options.isSet("rawDiagnostics");
   174             this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(options) :
   175                                                   new BasicDiagnosticFormatter(options, messages);
   177             String ek = options.get("expectKeys");
   178             if (ek != null)
   179                 expectDiagKeys = new HashSet<String>(Arrays.asList(ek.split(", *")));
   180         }
   182         private int getIntOption(Options options, OptionName optionName, int defaultValue) {
   183             String s = options.get(optionName);
   184             try {
   185                 if (s != null) {
   186                     int n = Integer.parseInt(s);
   187                     return (n <= 0 ? Integer.MAX_VALUE : n);
   188                 }
   189             } catch (NumberFormatException e) {
   190                 // silently ignore ill-formed numbers
   191             }
   192             return defaultValue;
   193         }
   195         /** Default value for -Xmaxerrs.
   196          */
   197         protected int getDefaultMaxErrors() {
   198             return 100;
   199         }
   201         /** Default value for -Xmaxwarns.
   202          */
   203         protected int getDefaultMaxWarnings() {
   204             return 100;
   205         }
   207     /** The default writer for diagnostics
   208      */
   209     static PrintWriter defaultWriter(Context context) {
   210         PrintWriter result = context.get(outKey);
   211         if (result == null)
   212             context.put(outKey, result = new PrintWriter(System.err));
   213         return result;
   214     }
   216     /** Construct a log with default settings.
   217      */
   218     protected Log(Context context) {
   219         this(context, defaultWriter(context));
   220     }
   222     /** Construct a log with all output redirected.
   223      */
   224     protected Log(Context context, PrintWriter defaultWriter) {
   225         this(context, defaultWriter, defaultWriter, defaultWriter);
   226     }
   228     /** Get the Log instance for this context. */
   229     public static Log instance(Context context) {
   230         Log instance = context.get(logKey);
   231         if (instance == null)
   232             instance = new Log(context);
   233         return instance;
   234     }
   236     /** The number of errors encountered so far.
   237      */
   238     public int nerrors = 0;
   240     /** The number of warnings encountered so far.
   241      */
   242     public int nwarnings = 0;
   244     /** A set of all errors generated so far. This is used to avoid printing an
   245      *  error message more than once. For each error, a pair consisting of the
   246      *  source file name and source code position of the error is added to the set.
   247      */
   248     private Set<Pair<JavaFileObject, Integer>> recorded = new HashSet<Pair<JavaFileObject,Integer>>();
   250     public boolean hasDiagnosticListener() {
   251         return diagListener != null;
   252     }
   254     public void setEndPosTable(JavaFileObject name, EndPosTable endPosTable) {
   255         name.getClass(); // null check
   256         getSource(name).setEndPosTable(endPosTable);
   257     }
   259     /** Return current sourcefile.
   260      */
   261     public JavaFileObject currentSourceFile() {
   262         return source == null ? null : source.getFile();
   263     }
   265     /** Get the current diagnostic formatter.
   266      */
   267     public DiagnosticFormatter<JCDiagnostic> getDiagnosticFormatter() {
   268         return diagFormatter;
   269     }
   271     /** Set the current diagnostic formatter.
   272      */
   273     public void setDiagnosticFormatter(DiagnosticFormatter<JCDiagnostic> diagFormatter) {
   274         this.diagFormatter = diagFormatter;
   275     }
   277     public PrintWriter getWriter(WriterKind kind) {
   278         switch (kind) {
   279             case NOTICE:    return noticeWriter;
   280             case WARNING:   return warnWriter;
   281             case ERROR:     return errWriter;
   282             default:        throw new IllegalArgumentException();
   283         }
   284     }
   286     public void setWriter(WriterKind kind, PrintWriter pw) {
   287         pw.getClass();
   288         switch (kind) {
   289             case NOTICE:    noticeWriter = pw;  break;
   290             case WARNING:   warnWriter = pw;    break;
   291             case ERROR:     errWriter = pw;     break;
   292             default:        throw new IllegalArgumentException();
   293         }
   294     }
   296     public void setWriters(PrintWriter pw) {
   297         pw.getClass();
   298         noticeWriter = warnWriter = errWriter = pw;
   299     }
   301     /** Flush the logs
   302      */
   303     public void flush() {
   304         errWriter.flush();
   305         warnWriter.flush();
   306         noticeWriter.flush();
   307     }
   309     public void flush(WriterKind kind) {
   310         getWriter(kind).flush();
   311     }
   313     /** Returns true if an error needs to be reported for a given
   314      * source name and pos.
   315      */
   316     protected boolean shouldReport(JavaFileObject file, int pos) {
   317         if (multipleErrors || file == null)
   318             return true;
   320         Pair<JavaFileObject,Integer> coords = new Pair<JavaFileObject,Integer>(file, pos);
   321         boolean shouldReport = !recorded.contains(coords);
   322         if (shouldReport)
   323             recorded.add(coords);
   324         return shouldReport;
   325     }
   327     /** Prompt user after an error.
   328      */
   329     public void prompt() {
   330         if (promptOnError) {
   331             System.err.println(localize("resume.abort"));
   332             try {
   333                 while (true) {
   334                     switch (System.in.read()) {
   335                     case 'a': case 'A':
   336                         System.exit(-1);
   337                         return;
   338                     case 'r': case 'R':
   339                         return;
   340                     case 'x': case 'X':
   341                         throw new AssertionError("user abort");
   342                     default:
   343                     }
   344                 }
   345             } catch (IOException e) {}
   346         }
   347     }
   349     /** Print the faulty source code line and point to the error.
   350      *  @param pos   Buffer index of the error position, must be on current line
   351      */
   352     private void printErrLine(int pos, PrintWriter writer) {
   353         String line = (source == null ? null : source.getLine(pos));
   354         if (line == null)
   355             return;
   356         int col = source.getColumnNumber(pos, false);
   358         printRawLines(writer, line);
   359         for (int i = 0; i < col - 1; i++) {
   360             writer.print((line.charAt(i) == '\t') ? "\t" : " ");
   361         }
   362         writer.println("^");
   363         writer.flush();
   364     }
   366     public void printNewline() {
   367         noticeWriter.println();
   368     }
   370     public void printNewline(WriterKind wk) {
   371         getWriter(wk).println();
   372     }
   374     public void printLines(String key, Object... args) {
   375         printRawLines(noticeWriter, localize(key, args));
   376     }
   378     public void printLines(PrefixKind pk, String key, Object... args) {
   379         printRawLines(noticeWriter, localize(pk, key, args));
   380     }
   382     public void printLines(WriterKind wk, String key, Object... args) {
   383         printRawLines(getWriter(wk), localize(key, args));
   384     }
   386     public void printLines(WriterKind wk, PrefixKind pk, String key, Object... args) {
   387         printRawLines(getWriter(wk), localize(pk, key, args));
   388     }
   390     /** Print the text of a message, translating newlines appropriately
   391      *  for the platform.
   392      */
   393     public void printRawLines(String msg) {
   394         printRawLines(noticeWriter, msg);
   395     }
   397     /** Print the text of a message, translating newlines appropriately
   398      *  for the platform.
   399      */
   400     public void printRawLines(WriterKind kind, String msg) {
   401         printRawLines(getWriter(kind), msg);
   402     }
   404     /** Print the text of a message, translating newlines appropriately
   405      *  for the platform.
   406      */
   407     public static void printRawLines(PrintWriter writer, String msg) {
   408         int nl;
   409         while ((nl = msg.indexOf('\n')) != -1) {
   410             writer.println(msg.substring(0, nl));
   411             msg = msg.substring(nl+1);
   412         }
   413         if (msg.length() != 0) writer.println(msg);
   414     }
   416     /**
   417      * Print the localized text of a "verbose" message to the
   418      * noticeWriter stream.
   419      */
   420     public void printVerbose(String key, Object... args) {
   421         printRawLines(noticeWriter, localize("verbose." + key, args));
   422     }
   424     protected void directError(String key, Object... args) {
   425         printRawLines(errWriter, localize(key, args));
   426         errWriter.flush();
   427     }
   429     /** Report a warning that cannot be suppressed.
   430      *  @param pos    The source position at which to report the warning.
   431      *  @param key    The key for the localized warning message.
   432      *  @param args   Fields of the warning message.
   433      */
   434     public void strictWarning(DiagnosticPosition pos, String key, Object ... args) {
   435         writeDiagnostic(diags.warning(source, pos, key, args));
   436         nwarnings++;
   437     }
   439     /** Report all deferred diagnostics, and clear the deferDiagnostics flag. */
   440     public void reportDeferredDiagnostics() {
   441         reportDeferredDiagnostics(EnumSet.allOf(JCDiagnostic.Kind.class));
   442     }
   444     /** Report selected deferred diagnostics, and clear the deferDiagnostics flag. */
   445     public void reportDeferredDiagnostics(Set<JCDiagnostic.Kind> kinds) {
   446         deferDiagnostics = false;
   447         JCDiagnostic d;
   448         while ((d = deferredDiagnostics.poll()) != null) {
   449             if (kinds.contains(d.getKind()))
   450                 report(d);
   451         }
   452     }
   454     /**
   455      * Common diagnostic handling.
   456      * The diagnostic is counted, and depending on the options and how many diagnostics have been
   457      * reported so far, the diagnostic may be handed off to writeDiagnostic.
   458      */
   459     public void report(JCDiagnostic diagnostic) {
   460         if (deferDiagnostics) {
   461             deferredDiagnostics.add(diagnostic);
   462             return;
   463         }
   465         if (expectDiagKeys != null)
   466             expectDiagKeys.remove(diagnostic.getCode());
   468         switch (diagnostic.getType()) {
   469         case FRAGMENT:
   470             throw new IllegalArgumentException();
   472         case NOTE:
   473             // Print out notes only when we are permitted to report warnings
   474             // Notes are only generated at the end of a compilation, so should be small
   475             // in number.
   476             if ((emitWarnings || diagnostic.isMandatory()) && !suppressNotes) {
   477                 writeDiagnostic(diagnostic);
   478             }
   479             break;
   481         case WARNING:
   482             if (emitWarnings || diagnostic.isMandatory()) {
   483                 if (nwarnings < MaxWarnings) {
   484                     writeDiagnostic(diagnostic);
   485                     nwarnings++;
   486                 }
   487             }
   488             break;
   490         case ERROR:
   491             if (nerrors < MaxErrors
   492                 && shouldReport(diagnostic.getSource(), diagnostic.getIntPosition())) {
   493                 writeDiagnostic(diagnostic);
   494                 nerrors++;
   495             }
   496             break;
   497         }
   498     }
   500     /**
   501      * Write out a diagnostic.
   502      */
   503     protected void writeDiagnostic(JCDiagnostic diag) {
   504         if (diagListener != null) {
   505             diagListener.report(diag);
   506             return;
   507         }
   509         PrintWriter writer = getWriterForDiagnosticType(diag.getType());
   511         printRawLines(writer, diagFormatter.format(diag, messages.getCurrentLocale()));
   513         if (promptOnError) {
   514             switch (diag.getType()) {
   515             case ERROR:
   516             case WARNING:
   517                 prompt();
   518             }
   519         }
   521         if (dumpOnError)
   522             new RuntimeException().printStackTrace(writer);
   524         writer.flush();
   525     }
   527     @Deprecated
   528     protected PrintWriter getWriterForDiagnosticType(DiagnosticType dt) {
   529         switch (dt) {
   530         case FRAGMENT:
   531             throw new IllegalArgumentException();
   533         case NOTE:
   534             return noticeWriter;
   536         case WARNING:
   537             return warnWriter;
   539         case ERROR:
   540             return errWriter;
   542         default:
   543             throw new Error();
   544         }
   545     }
   547     /** Find a localized string in the resource bundle.
   548      *  Because this method is static, it ignores the locale.
   549      *  Use localize(key, args) when possible.
   550      *  @param key    The key for the localized string.
   551      *  @param args   Fields to substitute into the string.
   552      */
   553     public static String getLocalizedString(String key, Object ... args) {
   554         return JavacMessages.getDefaultLocalizedString(PrefixKind.COMPILER_MISC.key(key), args);
   555     }
   557     /** Find a localized string in the resource bundle.
   558      *  @param key    The key for the localized string.
   559      *  @param args   Fields to substitute into the string.
   560      */
   561     public String localize(String key, Object... args) {
   562         return localize(PrefixKind.COMPILER_MISC, key, args);
   563     }
   565     /** Find a localized string in the resource bundle.
   566      *  @param key    The key for the localized string.
   567      *  @param args   Fields to substitute into the string.
   568      */
   569     public String localize(PrefixKind pk, String key, Object... args) {
   570         if (useRawMessages)
   571             return pk.key(key);
   572         else
   573             return messages.getLocalizedString(pk.key(key), args);
   574     }
   575     // where
   576         // backdoor hook for testing, should transition to use -XDrawDiagnostics
   577         private static boolean useRawMessages = false;
   579 /***************************************************************************
   580  * raw error messages without internationalization; used for experimentation
   581  * and quick prototyping
   582  ***************************************************************************/
   584     /** print an error or warning message:
   585      */
   586     private void printRawError(int pos, String msg) {
   587         if (source == null || pos == Position.NOPOS) {
   588             printRawLines(errWriter, "error: " + msg);
   589         } else {
   590             int line = source.getLineNumber(pos);
   591             JavaFileObject file = source.getFile();
   592             if (file != null)
   593                 printRawLines(errWriter,
   594                            file.getName() + ":" +
   595                            line + ": " + msg);
   596             printErrLine(pos, errWriter);
   597         }
   598         errWriter.flush();
   599     }
   601     /** report an error:
   602      */
   603     public void rawError(int pos, String msg) {
   604         if (nerrors < MaxErrors && shouldReport(currentSourceFile(), pos)) {
   605             printRawError(pos, msg);
   606             prompt();
   607             nerrors++;
   608         }
   609         errWriter.flush();
   610     }
   612     /** report a warning:
   613      */
   614     public void rawWarning(int pos, String msg) {
   615         if (nwarnings < MaxWarnings && emitWarnings) {
   616             printRawError(pos, "warning: " + msg);
   617         }
   618         prompt();
   619         nwarnings++;
   620         errWriter.flush();
   621     }
   623     public static String format(String fmt, Object... args) {
   624         return String.format((java.util.Locale)null, fmt, args);
   625     }
   627 }

mercurial