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