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

Tue, 24 Dec 2013 09:17:37 -0800

author
ksrini
date
Tue, 24 Dec 2013 09:17:37 -0800
changeset 2227
998b10c43157
parent 1569
475eb15dfdad
child 2525
2eb010b6cb22
permissions
-rw-r--r--

8029230: Update copyright year to match last edit in jdk8 langtools repository for 2013
Reviewed-by: ksrini
Contributed-by: steve.sides@oracle.com

     1 /*
     2  * Copyright (c) 2008, 2013, 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  */
    25 package com.sun.tools.javac.util;
    27 import java.util.Arrays;
    28 import java.util.Collection;
    29 import java.util.EnumSet;
    30 import java.util.HashMap;
    31 import java.util.Locale;
    32 import java.util.Map;
    33 import java.util.Set;
    35 import javax.tools.JavaFileObject;
    37 import com.sun.tools.javac.api.DiagnosticFormatter;
    38 import com.sun.tools.javac.api.DiagnosticFormatter.Configuration.DiagnosticPart;
    39 import com.sun.tools.javac.api.DiagnosticFormatter.Configuration.MultilineLimit;
    40 import com.sun.tools.javac.api.DiagnosticFormatter.PositionKind;
    41 import com.sun.tools.javac.api.Formattable;
    42 import com.sun.tools.javac.code.Lint.LintCategory;
    43 import com.sun.tools.javac.code.Printer;
    44 import com.sun.tools.javac.code.Symbol;
    45 import com.sun.tools.javac.code.Type;
    46 import com.sun.tools.javac.code.Type.CapturedType;
    47 import com.sun.tools.javac.file.BaseFileObject;
    48 import com.sun.tools.javac.jvm.Profile;
    49 import com.sun.tools.javac.tree.JCTree.*;
    50 import com.sun.tools.javac.tree.Pretty;
    51 import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticType.*;
    53 /**
    54  * This abstract class provides a basic implementation of the functionalities that should be provided
    55  * by any formatter used by javac. Among the main features provided by AbstractDiagnosticFormatter are:
    56  *
    57  * <ul>
    58  *  <li> Provides a standard implementation of the visitor-like methods defined in the interface DiagnisticFormatter.
    59  *  Those implementations are specifically targeting JCDiagnostic objects.
    60  *  <li> Provides basic support for i18n and a method for executing all locale-dependent conversions
    61  *  <li> Provides the formatting logic for rendering the arguments of a JCDiagnostic object.
    62  * <ul>
    63  *
    64  * <p><b>This is NOT part of any supported API.
    65  * If you write code that depends on this, you do so at your own risk.
    66  * This code and its internal interfaces are subject to change or
    67  * deletion without notice.</b>
    68  */
    69 public abstract class AbstractDiagnosticFormatter implements DiagnosticFormatter<JCDiagnostic> {
    71     /**
    72      * JavacMessages object used by this formatter for i18n.
    73      */
    74     protected JavacMessages messages;
    76     /**
    77      * Configuration object used by this formatter
    78      */
    79     private SimpleConfiguration config;
    81     /**
    82      * Current depth level of the disgnostic being formatted
    83      * (!= 0 for subdiagnostics)
    84      */
    85     protected int depth = 0;
    87     /**
    88      * All captured types that have been encountered during diagnostic formatting.
    89      * This info is used by the FormatterPrinter in order to print friendly unique
    90      * ids for captured types
    91      */
    92     private List<Type> allCaptured = List.nil();
    94     /**
    95      * Initialize an AbstractDiagnosticFormatter by setting its JavacMessages object.
    96      * @param messages
    97      */
    98     protected AbstractDiagnosticFormatter(JavacMessages messages, SimpleConfiguration config) {
    99         this.messages = messages;
   100         this.config = config;
   101     }
   103     public String formatKind(JCDiagnostic d, Locale l) {
   104         switch (d.getType()) {
   105             case FRAGMENT: return "";
   106             case NOTE:     return localize(l, "compiler.note.note");
   107             case WARNING:  return localize(l, "compiler.warn.warning");
   108             case ERROR:    return localize(l, "compiler.err.error");
   109             default:
   110                 throw new AssertionError("Unknown diagnostic type: " + d.getType());
   111         }
   112     }
   114     @Override
   115     public String format(JCDiagnostic d, Locale locale) {
   116         allCaptured = List.nil();
   117         return formatDiagnostic(d, locale);
   118     }
   120     protected abstract String formatDiagnostic(JCDiagnostic d, Locale locale);
   122     public String formatPosition(JCDiagnostic d, PositionKind pk,Locale l) {
   123         Assert.check(d.getPosition() != Position.NOPOS);
   124         return String.valueOf(getPosition(d, pk));
   125     }
   126     //where
   127     private long getPosition(JCDiagnostic d, PositionKind pk) {
   128         switch (pk) {
   129             case START: return d.getIntStartPosition();
   130             case END: return d.getIntEndPosition();
   131             case LINE: return d.getLineNumber();
   132             case COLUMN: return d.getColumnNumber();
   133             case OFFSET: return d.getIntPosition();
   134             default:
   135                 throw new AssertionError("Unknown diagnostic position: " + pk);
   136         }
   137     }
   139     public String formatSource(JCDiagnostic d, boolean fullname, Locale l) {
   140         JavaFileObject fo = d.getSource();
   141         if (fo == null)
   142             throw new IllegalArgumentException(); // d should have source set
   143         if (fullname)
   144             return fo.getName();
   145         else if (fo instanceof BaseFileObject)
   146             return ((BaseFileObject) fo).getShortName();
   147         else
   148             return BaseFileObject.getSimpleName(fo);
   149     }
   151     /**
   152      * Format the arguments of a given diagnostic.
   153      *
   154      * @param d diagnostic whose arguments are to be formatted
   155      * @param l locale object to be used for i18n
   156      * @return a Collection whose elements are the formatted arguments of the diagnostic
   157      */
   158     protected Collection<String> formatArguments(JCDiagnostic d, Locale l) {
   159         ListBuffer<String> buf = new ListBuffer<String>();
   160         for (Object o : d.getArgs()) {
   161            buf.append(formatArgument(d, o, l));
   162         }
   163         return buf.toList();
   164     }
   166     /**
   167      * Format a single argument of a given diagnostic.
   168      *
   169      * @param d diagnostic whose argument is to be formatted
   170      * @param arg argument to be formatted
   171      * @param l locale object to be used for i18n
   172      * @return string representation of the diagnostic argument
   173      */
   174     protected String formatArgument(JCDiagnostic d, Object arg, Locale l) {
   175         if (arg instanceof JCDiagnostic) {
   176             String s = null;
   177             depth++;
   178             try {
   179                 s = formatMessage((JCDiagnostic)arg, l);
   180             }
   181             finally {
   182                 depth--;
   183             }
   184             return s;
   185         }
   186         else if (arg instanceof JCExpression) {
   187             return expr2String((JCExpression)arg);
   188         }
   189         else if (arg instanceof Iterable<?>) {
   190             return formatIterable(d, (Iterable<?>)arg, l);
   191         }
   192         else if (arg instanceof Type) {
   193             return printer.visit((Type)arg, l);
   194         }
   195         else if (arg instanceof Symbol) {
   196             return printer.visit((Symbol)arg, l);
   197         }
   198         else if (arg instanceof JavaFileObject) {
   199             return ((JavaFileObject)arg).getName();
   200         }
   201         else if (arg instanceof Profile) {
   202             return ((Profile)arg).name;
   203         }
   204         else if (arg instanceof Formattable) {
   205             return ((Formattable)arg).toString(l, messages);
   206         }
   207         else {
   208             return String.valueOf(arg);
   209         }
   210     }
   211     //where
   212             private String expr2String(JCExpression tree) {
   213                 switch(tree.getTag()) {
   214                     case PARENS:
   215                         return expr2String(((JCParens)tree).expr);
   216                     case LAMBDA:
   217                     case REFERENCE:
   218                     case CONDEXPR:
   219                         return Pretty.toSimpleString(tree);
   220                     default:
   221                         Assert.error("unexpected tree kind " + tree.getKind());
   222                         return null;
   223                 }
   224             }
   226     /**
   227      * Format an iterable argument of a given diagnostic.
   228      *
   229      * @param d diagnostic whose argument is to be formatted
   230      * @param it iterable argument to be formatted
   231      * @param l locale object to be used for i18n
   232      * @return string representation of the diagnostic iterable argument
   233      */
   234     protected String formatIterable(JCDiagnostic d, Iterable<?> it, Locale l) {
   235         StringBuilder sbuf = new StringBuilder();
   236         String sep = "";
   237         for (Object o : it) {
   238             sbuf.append(sep);
   239             sbuf.append(formatArgument(d, o, l));
   240             sep = ",";
   241         }
   242         return sbuf.toString();
   243     }
   245     /**
   246      * Format all the subdiagnostics attached to a given diagnostic.
   247      *
   248      * @param d diagnostic whose subdiagnostics are to be formatted
   249      * @param l locale object to be used for i18n
   250      * @return list of all string representations of the subdiagnostics
   251      */
   252     protected List<String> formatSubdiagnostics(JCDiagnostic d, Locale l) {
   253         List<String> subdiagnostics = List.nil();
   254         int maxDepth = config.getMultilineLimit(MultilineLimit.DEPTH);
   255         if (maxDepth == -1 || depth < maxDepth) {
   256             depth++;
   257             try {
   258                 int maxCount = config.getMultilineLimit(MultilineLimit.LENGTH);
   259                 int count = 0;
   260                 for (JCDiagnostic d2 : d.getSubdiagnostics()) {
   261                     if (maxCount == -1 || count < maxCount) {
   262                         subdiagnostics = subdiagnostics.append(formatSubdiagnostic(d, d2, l));
   263                         count++;
   264                     }
   265                     else
   266                         break;
   267                 }
   268             }
   269             finally {
   270                 depth--;
   271             }
   272         }
   273         return subdiagnostics;
   274     }
   276     /**
   277      * Format a subdiagnostics attached to a given diagnostic.
   278      *
   279      * @param parent multiline diagnostic whose subdiagnostics is to be formatted
   280      * @param sub subdiagnostic to be formatted
   281      * @param l locale object to be used for i18n
   282      * @return string representation of the subdiagnostics
   283      */
   284     protected String formatSubdiagnostic(JCDiagnostic parent, JCDiagnostic sub, Locale l) {
   285         return formatMessage(sub, l);
   286     }
   288     /** Format the faulty source code line and point to the error.
   289      *  @param d The diagnostic for which the error line should be printed
   290      */
   291     protected String formatSourceLine(JCDiagnostic d, int nSpaces) {
   292         StringBuilder buf = new StringBuilder();
   293         DiagnosticSource source = d.getDiagnosticSource();
   294         int pos = d.getIntPosition();
   295         if (d.getIntPosition() == Position.NOPOS)
   296             throw new AssertionError();
   297         String line = (source == null ? null : source.getLine(pos));
   298         if (line == null)
   299             return "";
   300         buf.append(indent(line, nSpaces));
   301         int col = source.getColumnNumber(pos, false);
   302         if (config.isCaretEnabled()) {
   303             buf.append("\n");
   304             for (int i = 0; i < col - 1; i++)  {
   305                 buf.append((line.charAt(i) == '\t') ? "\t" : " ");
   306             }
   307             buf.append(indent("^", nSpaces));
   308         }
   309         return buf.toString();
   310     }
   312     protected String formatLintCategory(JCDiagnostic d, Locale l) {
   313         LintCategory lc = d.getLintCategory();
   314         if (lc == null)
   315             return "";
   316         return localize(l, "compiler.warn.lintOption", lc.option);
   317     }
   319     /**
   320      * Converts a String into a locale-dependent representation accordingly to a given locale.
   321      *
   322      * @param l locale object to be used for i18n
   323      * @param key locale-independent key used for looking up in a resource file
   324      * @param args localization arguments
   325      * @return a locale-dependent string
   326      */
   327     protected String localize(Locale l, String key, Object... args) {
   328         return messages.getLocalizedString(l, key, args);
   329     }
   331     public boolean displaySource(JCDiagnostic d) {
   332         return config.getVisible().contains(DiagnosticPart.SOURCE) &&
   333                 d.getType() != FRAGMENT &&
   334                 d.getIntPosition() != Position.NOPOS;
   335     }
   337     public boolean isRaw() {
   338         return false;
   339     }
   341     /**
   342      * Creates a string with a given amount of empty spaces. Useful for
   343      * indenting the text of a diagnostic message.
   344      *
   345      * @param nSpaces the amount of spaces to be added to the result string
   346      * @return the indentation string
   347      */
   348     protected String indentString(int nSpaces) {
   349         String spaces = "                        ";
   350         if (nSpaces <= spaces.length())
   351             return spaces.substring(0, nSpaces);
   352         else {
   353             StringBuilder buf = new StringBuilder();
   354             for (int i = 0 ; i < nSpaces ; i++)
   355                 buf.append(" ");
   356             return buf.toString();
   357         }
   358     }
   360     /**
   361      * Indent a string by prepending a given amount of empty spaces to each line
   362      * of the string.
   363      *
   364      * @param s the string to be indented
   365      * @param nSpaces the amount of spaces that should be prepended to each line
   366      * of the string
   367      * @return an indented string
   368      */
   369     protected String indent(String s, int nSpaces) {
   370         String indent = indentString(nSpaces);
   371         StringBuilder buf = new StringBuilder();
   372         String nl = "";
   373         for (String line : s.split("\n")) {
   374             buf.append(nl);
   375             buf.append(indent + line);
   376             nl = "\n";
   377         }
   378         return buf.toString();
   379     }
   381     public SimpleConfiguration getConfiguration() {
   382         return config;
   383     }
   385     static public class SimpleConfiguration implements Configuration {
   387         protected Map<MultilineLimit, Integer> multilineLimits;
   388         protected EnumSet<DiagnosticPart> visibleParts;
   389         protected boolean caretEnabled;
   391         public SimpleConfiguration(Set<DiagnosticPart> parts) {
   392             multilineLimits = new HashMap<MultilineLimit, Integer>();
   393             setVisible(parts);
   394             setMultilineLimit(MultilineLimit.DEPTH, -1);
   395             setMultilineLimit(MultilineLimit.LENGTH, -1);
   396             setCaretEnabled(true);
   397         }
   399         @SuppressWarnings("fallthrough")
   400         public SimpleConfiguration(Options options, Set<DiagnosticPart> parts) {
   401             this(parts);
   402             String showSource = null;
   403             if ((showSource = options.get("showSource")) != null) {
   404                 if (showSource.equals("true"))
   405                     setVisiblePart(DiagnosticPart.SOURCE, true);
   406                 else if (showSource.equals("false"))
   407                     setVisiblePart(DiagnosticPart.SOURCE, false);
   408             }
   409             String diagOpts = options.get("diags");
   410             if (diagOpts != null) {//override -XDshowSource
   411                 Collection<String> args = Arrays.asList(diagOpts.split(","));
   412                 if (args.contains("short")) {
   413                     setVisiblePart(DiagnosticPart.DETAILS, false);
   414                     setVisiblePart(DiagnosticPart.SUBDIAGNOSTICS, false);
   415                 }
   416                 if (args.contains("source"))
   417                     setVisiblePart(DiagnosticPart.SOURCE, true);
   418                 if (args.contains("-source"))
   419                     setVisiblePart(DiagnosticPart.SOURCE, false);
   420             }
   421             String multiPolicy = null;
   422             if ((multiPolicy = options.get("multilinePolicy")) != null) {
   423                 if (multiPolicy.equals("disabled"))
   424                     setVisiblePart(DiagnosticPart.SUBDIAGNOSTICS, false);
   425                 else if (multiPolicy.startsWith("limit:")) {
   426                     String limitString = multiPolicy.substring("limit:".length());
   427                     String[] limits = limitString.split(":");
   428                     try {
   429                         switch (limits.length) {
   430                             case 2: {
   431                                 if (!limits[1].equals("*"))
   432                                     setMultilineLimit(MultilineLimit.DEPTH, Integer.parseInt(limits[1]));
   433                             }
   434                             case 1: {
   435                                 if (!limits[0].equals("*"))
   436                                     setMultilineLimit(MultilineLimit.LENGTH, Integer.parseInt(limits[0]));
   437                             }
   438                         }
   439                     }
   440                     catch(NumberFormatException ex) {
   441                         setMultilineLimit(MultilineLimit.DEPTH, -1);
   442                         setMultilineLimit(MultilineLimit.LENGTH, -1);
   443                     }
   444                 }
   445             }
   446             String showCaret = null;
   447             if (((showCaret = options.get("showCaret")) != null) &&
   448                 showCaret.equals("false"))
   449                     setCaretEnabled(false);
   450             else
   451                 setCaretEnabled(true);
   452         }
   454         public int getMultilineLimit(MultilineLimit limit) {
   455             return multilineLimits.get(limit);
   456         }
   458         public EnumSet<DiagnosticPart> getVisible() {
   459             return EnumSet.copyOf(visibleParts);
   460         }
   462         public void setMultilineLimit(MultilineLimit limit, int value) {
   463             multilineLimits.put(limit, value < -1 ? -1 : value);
   464         }
   467         public void setVisible(Set<DiagnosticPart> diagParts) {
   468             visibleParts = EnumSet.copyOf(diagParts);
   469         }
   471         public void setVisiblePart(DiagnosticPart diagParts, boolean enabled) {
   472             if (enabled)
   473                 visibleParts.add(diagParts);
   474             else
   475                 visibleParts.remove(diagParts);
   476         }
   478         /**
   479          * Shows a '^' sign under the source line displayed by the formatter
   480          * (if applicable).
   481          *
   482          * @param caretEnabled if true enables caret
   483          */
   484         public void setCaretEnabled(boolean caretEnabled) {
   485             this.caretEnabled = caretEnabled;
   486         }
   488         /**
   489          * Tells whether the caret display is active or not.
   490          *
   491          * @return true if the caret is enabled
   492          */
   493         public boolean isCaretEnabled() {
   494             return caretEnabled;
   495         }
   496     }
   498     public Printer getPrinter() {
   499         return printer;
   500     }
   502     public void setPrinter(Printer printer) {
   503         this.printer = printer;
   504     }
   506     /**
   507      * An enhanced printer for formatting types/symbols used by
   508      * AbstractDiagnosticFormatter. Provides alternate numbering of captured
   509      * types (they are numbered starting from 1 on each new diagnostic, instead
   510      * of relying on the underlying hashcode() method which generates unstable
   511      * output). Also detects cycles in wildcard messages (e.g. if the wildcard
   512      * type referred by a given captured type C contains C itself) which might
   513      * lead to infinite loops.
   514      */
   515     protected Printer printer = new Printer() {
   517         @Override
   518         protected String localize(Locale locale, String key, Object... args) {
   519             return AbstractDiagnosticFormatter.this.localize(locale, key, args);
   520         }
   521         @Override
   522         protected String capturedVarId(CapturedType t, Locale locale) {
   523             return "" + (allCaptured.indexOf(t) + 1);
   524         }
   525         @Override
   526         public String visitCapturedType(CapturedType t, Locale locale) {
   527             if (!allCaptured.contains(t)) {
   528                 allCaptured = allCaptured.append(t);
   529             }
   530             return super.visitCapturedType(t, locale);
   531         }
   532     };
   533 }

mercurial