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