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

Thu, 09 Oct 2008 16:07:38 +0100

author
mcimadamore
date
Thu, 09 Oct 2008 16:07:38 +0100
changeset 136
8eafba4f61be
parent 100
37551dc0f591
child 137
e4eaddca54b7
permissions
-rw-r--r--

6406133: JCDiagnostic.getMessage ignores locale argument
Summary: Compiler API should take into account locale settings
Reviewed-by: jjg

     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.HashSet;
    30 import java.util.Map;
    31 import java.util.Set;
    32 import javax.tools.DiagnosticListener;
    33 import javax.tools.JavaFileObject;
    35 import com.sun.tools.javac.file.JavacFileManager;
    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 API supported by Sun Microsystems.  If
    45  *  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     /** Print stack trace on errors?
    81      */
    82     public boolean dumpOnError;
    84     /** Print multiple errors for same source locations.
    85      */
    86     public boolean multipleErrors;
    88     /**
    89      * Diagnostic listener, if provided through programmatic
    90      * interface to javac (JSR 199).
    91      */
    92     protected DiagnosticListener<? super JavaFileObject> diagListener;
    94     /**
    95      * Formatter for diagnostics
    96      */
    97     private DiagnosticFormatter<JCDiagnostic> diagFormatter;
    99     /**
   100      * JavacMessages object used for localization
   101      */
   102     private JavacMessages messages;
   104     /** Construct a log with given I/O redirections.
   105      */
   106     @Deprecated
   107     protected Log(Context context, PrintWriter errWriter, PrintWriter warnWriter, PrintWriter noticeWriter) {
   108         super(JCDiagnostic.Factory.instance(context));
   109         context.put(logKey, this);
   110         this.errWriter = errWriter;
   111         this.warnWriter = warnWriter;
   112         this.noticeWriter = noticeWriter;
   114         Options options = Options.instance(context);
   115         this.dumpOnError = options.get("-doe") != null;
   116         this.promptOnError = options.get("-prompt") != null;
   117         this.emitWarnings = options.get("-Xlint:none") == null;
   118         this.MaxErrors = getIntOption(options, "-Xmaxerrs", 100);
   119         this.MaxWarnings = getIntOption(options, "-Xmaxwarns", 100);
   121         boolean rawDiagnostics = options.get("rawDiagnostics") != null;
   122         messages = JavacMessages.instance(context);
   123         this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(messages) :
   124                                               new BasicDiagnosticFormatter(options, messages);
   125         @SuppressWarnings("unchecked") // FIXME
   126         DiagnosticListener<? super JavaFileObject> diagListener =
   127             context.get(DiagnosticListener.class);
   128         this.diagListener = diagListener;
   129     }
   130     // where
   131         private int getIntOption(Options options, String optionName, int defaultValue) {
   132             String s = options.get(optionName);
   133             try {
   134                 if (s != null) return Integer.parseInt(s);
   135             } catch (NumberFormatException e) {
   136                 // silently ignore ill-formed numbers
   137             }
   138             return defaultValue;
   139         }
   141     /** The default writer for diagnostics
   142      */
   143     static final PrintWriter defaultWriter(Context context) {
   144         PrintWriter result = context.get(outKey);
   145         if (result == null)
   146             context.put(outKey, result = new PrintWriter(System.err));
   147         return result;
   148     }
   150     /** Construct a log with default settings.
   151      */
   152     protected Log(Context context) {
   153         this(context, defaultWriter(context));
   154     }
   156     /** Construct a log with all output redirected.
   157      */
   158     protected Log(Context context, PrintWriter defaultWriter) {
   159         this(context, defaultWriter, defaultWriter, defaultWriter);
   160     }
   162     /** Get the Log instance for this context. */
   163     public static Log instance(Context context) {
   164         Log instance = context.get(logKey);
   165         if (instance == null)
   166             instance = new Log(context);
   167         return instance;
   168     }
   170     /** The number of errors encountered so far.
   171      */
   172     public int nerrors = 0;
   174     /** The number of warnings encountered so far.
   175      */
   176     public int nwarnings = 0;
   178     /** A set of all errors generated so far. This is used to avoid printing an
   179      *  error message more than once. For each error, a pair consisting of the
   180      *  source file name and source code position of the error is added to the set.
   181      */
   182     private Set<Pair<JavaFileObject, Integer>> recorded = new HashSet<Pair<JavaFileObject,Integer>>();
   184     public boolean hasDiagnosticListener() {
   185         return diagListener != null;
   186     }
   188     public void setEndPosTable(JavaFileObject name, Map<JCTree, Integer> table) {
   189         name.getClass(); // null check
   190         getSource(name).setEndPosTable(table);
   191     }
   193     /** Return current source name.
   194      */
   195     public JavaFileObject currentSource() {
   196         return source == null ? null : source.getFile();
   197     }
   199     /** Flush the logs
   200      */
   201     public void flush() {
   202         errWriter.flush();
   203         warnWriter.flush();
   204         noticeWriter.flush();
   205     }
   207     /** Returns true if an error needs to be reported for a given
   208      * source name and pos.
   209      */
   210     protected boolean shouldReport(JavaFileObject file, int pos) {
   211         if (multipleErrors || file == null)
   212             return true;
   214         Pair<JavaFileObject,Integer> coords = new Pair<JavaFileObject,Integer>(file, pos);
   215         boolean shouldReport = !recorded.contains(coords);
   216         if (shouldReport)
   217             recorded.add(coords);
   218         return shouldReport;
   219     }
   221     /** Prompt user after an error.
   222      */
   223     public void prompt() {
   224         if (promptOnError) {
   225             System.err.println(getLocalizedString("resume.abort"));
   226             char ch;
   227             try {
   228                 while (true) {
   229                     switch (System.in.read()) {
   230                     case 'a': case 'A':
   231                         System.exit(-1);
   232                         return;
   233                     case 'r': case 'R':
   234                         return;
   235                     case 'x': case 'X':
   236                         throw new AssertionError("user abort");
   237                     default:
   238                     }
   239                 }
   240             } catch (IOException e) {}
   241         }
   242     }
   244     /** Print the faulty source code line and point to the error.
   245      *  @param pos   Buffer index of the error position, must be on current line
   246      */
   247     private void printErrLine(int pos, PrintWriter writer) {
   248         String line = (source == null ? null : source.getLine(pos));
   249         if (line == null)
   250             return;
   251         int col = source.getColumnNumber(pos, false);
   253         printLines(writer, line);
   254         for (int i = 0; i < col - 1; i++) {
   255             writer.print((line.charAt(i) == '\t') ? "\t" : " ");
   256         }
   257         writer.println("^");
   258         writer.flush();
   259     }
   261     /** Print the text of a message, translating newlines appropriately
   262      *  for the platform.
   263      */
   264     public static void printLines(PrintWriter writer, String msg) {
   265         int nl;
   266         while ((nl = msg.indexOf('\n')) != -1) {
   267             writer.println(msg.substring(0, nl));
   268             msg = msg.substring(nl+1);
   269         }
   270         if (msg.length() != 0) writer.println(msg);
   271     }
   273     protected void directError(String key, Object... args) {
   274         printLines(errWriter, getLocalizedString(key, args));
   275         errWriter.flush();
   276     }
   278     /** Report a warning that cannot be suppressed.
   279      *  @param pos    The source position at which to report the warning.
   280      *  @param key    The key for the localized warning message.
   281      *  @param args   Fields of the warning message.
   282      */
   283     public void strictWarning(DiagnosticPosition pos, String key, Object ... args) {
   284         writeDiagnostic(diags.warning(source, pos, key, args));
   285         nwarnings++;
   286     }
   288     /**
   289      * Common diagnostic handling.
   290      * The diagnostic is counted, and depending on the options and how many diagnostics have been
   291      * reported so far, the diagnostic may be handed off to writeDiagnostic.
   292      */
   293     public void report(JCDiagnostic diagnostic) {
   294         switch (diagnostic.getType()) {
   295         case FRAGMENT:
   296             throw new IllegalArgumentException();
   298         case NOTE:
   299             // Print out notes only when we are permitted to report warnings
   300             // Notes are only generated at the end of a compilation, so should be small
   301             // in number.
   302             if (emitWarnings || diagnostic.isMandatory()) {
   303                 writeDiagnostic(diagnostic);
   304             }
   305             break;
   307         case WARNING:
   308             if (emitWarnings || diagnostic.isMandatory()) {
   309                 if (nwarnings < MaxWarnings) {
   310                     writeDiagnostic(diagnostic);
   311                     nwarnings++;
   312                 }
   313             }
   314             break;
   316         case ERROR:
   317             if (nerrors < MaxErrors
   318                 && shouldReport(diagnostic.getSource(), diagnostic.getIntPosition())) {
   319                 writeDiagnostic(diagnostic);
   320                 nerrors++;
   321             }
   322             break;
   323         }
   324     }
   326     /**
   327      * Write out a diagnostic.
   328      */
   329     protected void writeDiagnostic(JCDiagnostic diag) {
   330         if (diagListener != null) {
   331             try {
   332                 diagListener.report(diag);
   333                 return;
   334             }
   335             catch (Throwable t) {
   336                 throw new ClientCodeException(t);
   337             }
   338         }
   340         PrintWriter writer = getWriterForDiagnosticType(diag.getType());
   342         printLines(writer, diagFormatter.format(diag, messages.getCurrentLocale()));
   343         if (diagFormatter.displaySource(diag)) {
   344             int pos = diag.getIntPosition();
   345             if (pos != Position.NOPOS) {
   346                 JavaFileObject prev = useSource(diag.getSource());
   347                 printErrLine(pos, writer);
   348                 useSource(prev);
   349             }
   350         }
   352         if (promptOnError) {
   353             switch (diag.getType()) {
   354             case ERROR:
   355             case WARNING:
   356                 prompt();
   357             }
   358         }
   360         if (dumpOnError)
   361             new RuntimeException().printStackTrace(writer);
   363         writer.flush();
   364     }
   366     @Deprecated
   367     protected PrintWriter getWriterForDiagnosticType(DiagnosticType dt) {
   368         switch (dt) {
   369         case FRAGMENT:
   370             throw new IllegalArgumentException();
   372         case NOTE:
   373             return noticeWriter;
   375         case WARNING:
   376             return warnWriter;
   378         case ERROR:
   379             return errWriter;
   381         default:
   382             throw new Error();
   383         }
   384     }
   386     /** Find a localized string in the resource bundle.
   387      *  @param key    The key for the localized string.
   388      *  @param args   Fields to substitute into the string.
   389      */
   390     public static String getLocalizedString(String key, Object ... args) {
   391         return JavacMessages.getDefaultLocalizedString("compiler.misc." + key, args);
   392     }
   394 /***************************************************************************
   395  * raw error messages without internationalization; used for experimentation
   396  * and quick prototyping
   397  ***************************************************************************/
   399     /** print an error or warning message:
   400      */
   401     private void printRawError(int pos, String msg) {
   402         if (source == null || pos == Position.NOPOS) {
   403             printLines(errWriter, "error: " + msg);
   404         } else {
   405             int line = source.getLineNumber(pos);
   406             JavaFileObject file = currentSource();
   407             if (file != null)
   408                 printLines(errWriter,
   409                            JavacFileManager.getJavacFileName(file) + ":" +
   410                            line + ": " + msg);
   411             printErrLine(pos, errWriter);
   412         }
   413         errWriter.flush();
   414     }
   416     /** report an error:
   417      */
   418     public void rawError(int pos, String msg) {
   419         if (nerrors < MaxErrors && shouldReport(currentSource(), pos)) {
   420             printRawError(pos, msg);
   421             prompt();
   422             nerrors++;
   423         }
   424         errWriter.flush();
   425     }
   427     /** report a warning:
   428      */
   429     public void rawWarning(int pos, String msg) {
   430         if (nwarnings < MaxWarnings && emitWarnings) {
   431             printRawError(pos, "warning: " + msg);
   432         }
   433         prompt();
   434         nwarnings++;
   435         errWriter.flush();
   436     }
   438     public static String format(String fmt, Object... args) {
   439         return String.format((java.util.Locale)null, fmt, args);
   440     }
   442 }

mercurial