Tue, 31 Mar 2009 11:07:55 -0700
6817950: refactor ClassReader to improve attribute handling
Reviewed-by: mcimadamore
1 /*
2 * Copyright 2008-2009 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 */
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;
34 import javax.tools.JavaFileObject;
36 import com.sun.tools.javac.api.DiagnosticFormatter;
37 import com.sun.tools.javac.api.DiagnosticFormatter.Configuration.DiagnosticPart;
38 import com.sun.tools.javac.api.DiagnosticFormatter.Configuration.MultilineLimit;
39 import com.sun.tools.javac.api.DiagnosticFormatter.PositionKind;
40 import com.sun.tools.javac.api.Formattable;
41 import com.sun.tools.javac.code.Printer;
42 import com.sun.tools.javac.code.Symbol;
43 import com.sun.tools.javac.code.Type;
44 import com.sun.tools.javac.code.Type.CapturedType;
45 import com.sun.tools.javac.file.JavacFileManager;
47 import static com.sun.tools.javac.util.JCDiagnostic.DiagnosticType.*;
49 /**
50 * This abstract class provides a basic implementation of the functionalities that should be provided
51 * by any formatter used by javac. Among the main features provided by AbstractDiagnosticFormatter are:
52 *
53 * <ul>
54 * <li> Provides a standard implementation of the visitor-like methods defined in the interface DiagnisticFormatter.
55 * Those implementations are specifically targeting JCDiagnostic objects.
56 * <li> Provides basic support for i18n and a method for executing all locale-dependent conversions
57 * <li> Provides the formatting logic for rendering the arguments of a JCDiagnostic object.
58 * <ul>
59 *
60 */
61 public abstract class AbstractDiagnosticFormatter implements DiagnosticFormatter<JCDiagnostic> {
63 /**
64 * JavacMessages object used by this formatter for i18n.
65 */
66 protected JavacMessages messages;
68 /**
69 * Configuration object used by this formatter
70 */
71 private SimpleConfiguration config;
73 /**
74 * Current depth level of the disgnostic being formatted
75 * (!= 0 for subdiagnostics)
76 */
77 protected int depth = 0;
79 /**
80 * Printer instance to be used for formatting types/symbol
81 */
82 protected Printer printer;
84 /**
85 * Initialize an AbstractDiagnosticFormatter by setting its JavacMessages object.
86 * @param messages
87 */
88 protected AbstractDiagnosticFormatter(JavacMessages messages, SimpleConfiguration config) {
89 this.messages = messages;
90 this.config = config;
91 this.printer = new FormatterPrinter();
92 }
94 public String formatKind(JCDiagnostic d, Locale l) {
95 switch (d.getType()) {
96 case FRAGMENT: return "";
97 case NOTE: return localize(l, "compiler.note.note");
98 case WARNING: return localize(l, "compiler.warn.warning");
99 case ERROR: return localize(l, "compiler.err.error");
100 default:
101 throw new AssertionError("Unknown diagnostic type: " + d.getType());
102 }
103 }
105 @Override
106 public String format(JCDiagnostic d, Locale locale) {
107 printer = new FormatterPrinter();
108 return formatDiagnostic(d, locale);
109 }
111 abstract String formatDiagnostic(JCDiagnostic d, Locale locale);
113 public String formatPosition(JCDiagnostic d, PositionKind pk,Locale l) {
114 assert (d.getPosition() != Position.NOPOS);
115 return String.valueOf(getPosition(d, pk));
116 }
117 //where
118 private long getPosition(JCDiagnostic d, PositionKind pk) {
119 switch (pk) {
120 case START: return d.getIntStartPosition();
121 case END: return d.getIntEndPosition();
122 case LINE: return d.getLineNumber();
123 case COLUMN: return d.getColumnNumber();
124 case OFFSET: return d.getIntPosition();
125 default:
126 throw new AssertionError("Unknown diagnostic position: " + pk);
127 }
128 }
130 public String formatSource(JCDiagnostic d, boolean fullname, Locale l) {
131 assert (d.getSource() != null);
132 return fullname ? d.getSourceName() : d.getSource().getName();
133 }
135 /**
136 * Format the arguments of a given diagnostic.
137 *
138 * @param d diagnostic whose arguments are to be formatted
139 * @param l locale object to be used for i18n
140 * @return a Collection whose elements are the formatted arguments of the diagnostic
141 */
142 protected Collection<String> formatArguments(JCDiagnostic d, Locale l) {
143 ListBuffer<String> buf = new ListBuffer<String>();
144 for (Object o : d.getArgs()) {
145 buf.append(formatArgument(d, o, l));
146 }
147 return buf.toList();
148 }
150 /**
151 * Format a single argument of a given diagnostic.
152 *
153 * @param d diagnostic whose argument is to be formatted
154 * @param arg argument to be formatted
155 * @param l locale object to be used for i18n
156 * @return string representation of the diagnostic argument
157 */
158 protected String formatArgument(JCDiagnostic d, Object arg, Locale l) {
159 if (arg instanceof JCDiagnostic) {
160 String s = null;
161 depth++;
162 try {
163 s = formatMessage((JCDiagnostic)arg, l);
164 }
165 finally {
166 depth--;
167 }
168 return s;
169 }
170 else if (arg instanceof Iterable<?>) {
171 return formatIterable(d, (Iterable<?>)arg, l);
172 }
173 else if (arg instanceof Type) {
174 return printer.visit((Type)arg, l);
175 }
176 else if (arg instanceof Symbol) {
177 return printer.visit((Symbol)arg, l);
178 }
179 else if (arg instanceof JavaFileObject) {
180 return JavacFileManager.getJavacBaseFileName((JavaFileObject)arg);
181 }
182 else if (arg instanceof Formattable) {
183 return ((Formattable)arg).toString(l, messages);
184 }
185 else {
186 return String.valueOf(arg);
187 }
188 }
190 /**
191 * Format an iterable argument of a given diagnostic.
192 *
193 * @param d diagnostic whose argument is to be formatted
194 * @param it iterable argument to be formatted
195 * @param l locale object to be used for i18n
196 * @return string representation of the diagnostic iterable argument
197 */
198 protected String formatIterable(JCDiagnostic d, Iterable<?> it, Locale l) {
199 StringBuilder sbuf = new StringBuilder();
200 String sep = "";
201 for (Object o : it) {
202 sbuf.append(sep);
203 sbuf.append(formatArgument(d, o, l));
204 sep = ",";
205 }
206 return sbuf.toString();
207 }
209 /**
210 * Format all the subdiagnostics attached to a given diagnostic.
211 *
212 * @param d diagnostic whose subdiagnostics are to be formatted
213 * @param l locale object to be used for i18n
214 * @return list of all string representations of the subdiagnostics
215 */
216 protected List<String> formatSubdiagnostics(JCDiagnostic d, Locale l) {
217 List<String> subdiagnostics = List.nil();
218 int maxDepth = config.getMultilineLimit(MultilineLimit.DEPTH);
219 if (maxDepth == -1 || depth < maxDepth) {
220 depth++;
221 try {
222 int maxCount = config.getMultilineLimit(MultilineLimit.LENGTH);
223 int count = 0;
224 for (JCDiagnostic d2 : d.getSubdiagnostics()) {
225 if (maxCount == -1 || count < maxCount) {
226 subdiagnostics = subdiagnostics.append(formatSubdiagnostic(d, d2, l));
227 count++;
228 }
229 else
230 break;
231 }
232 }
233 finally {
234 depth--;
235 }
236 }
237 return subdiagnostics;
238 }
240 /**
241 * Format a subdiagnostics attached to a given diagnostic.
242 *
243 * @param parent multiline diagnostic whose subdiagnostics is to be formatted
244 * @param sub subdiagnostic to be formatted
245 * @param l locale object to be used for i18n
246 * @return string representation of the subdiagnostics
247 */
248 protected String formatSubdiagnostic(JCDiagnostic parent, JCDiagnostic sub, Locale l) {
249 return formatMessage(sub, l);
250 }
252 /** Format the faulty source code line and point to the error.
253 * @param d The diagnostic for which the error line should be printed
254 */
255 protected String formatSourceLine(JCDiagnostic d, int nSpaces) {
256 StringBuilder buf = new StringBuilder();
257 DiagnosticSource source = d.getDiagnosticSource();
258 int pos = d.getIntPosition();
259 if (d.getIntPosition() == Position.NOPOS)
260 throw new AssertionError();
261 String line = (source == null ? null : source.getLine(pos));
262 if (line == null)
263 return "";
264 buf.append(indent(line, nSpaces));
265 int col = source.getColumnNumber(pos, false);
266 if (config.isCaretEnabled()) {
267 buf.append("\n");
268 for (int i = 0; i < col - 1; i++) {
269 buf.append((line.charAt(i) == '\t') ? "\t" : " ");
270 }
271 buf.append(indent("^", nSpaces));
272 }
273 return buf.toString();
274 }
276 /**
277 * Converts a String into a locale-dependent representation accordingly to a given locale.
278 *
279 * @param l locale object to be used for i18n
280 * @param key locale-independent key used for looking up in a resource file
281 * @param args localization arguments
282 * @return a locale-dependent string
283 */
284 protected String localize(Locale l, String key, Object... args) {
285 return messages.getLocalizedString(l, key, args);
286 }
288 public boolean displaySource(JCDiagnostic d) {
289 return config.getVisible().contains(DiagnosticPart.SOURCE) &&
290 d.getType() != FRAGMENT &&
291 d.getIntPosition() != Position.NOPOS;
292 }
294 /**
295 * Creates a string with a given amount of empty spaces. Useful for
296 * indenting the text of a diagnostic message.
297 *
298 * @param nSpaces the amount of spaces to be added to the result string
299 * @return the indentation string
300 */
301 protected String indentString(int nSpaces) {
302 String spaces = " ";
303 if (nSpaces <= spaces.length())
304 return spaces.substring(0, nSpaces);
305 else {
306 StringBuilder buf = new StringBuilder();
307 for (int i = 0 ; i < nSpaces ; i++)
308 buf.append(" ");
309 return buf.toString();
310 }
311 }
313 /**
314 * Indent a string by prepending a given amount of empty spaces to each line
315 * of the string.
316 *
317 * @param s the string to be indented
318 * @param nSpaces the amount of spaces that should be prepended to each line
319 * of the string
320 * @return an indented string
321 */
322 protected String indent(String s, int nSpaces) {
323 String indent = indentString(nSpaces);
324 StringBuilder buf = new StringBuilder();
325 String nl = "";
326 for (String line : s.split("\n")) {
327 buf.append(nl);
328 buf.append(indent + line);
329 nl = "\n";
330 }
331 return buf.toString();
332 }
334 public SimpleConfiguration getConfiguration() {
335 return config;
336 }
338 static public class SimpleConfiguration implements Configuration {
340 protected Map<MultilineLimit, Integer> multilineLimits;
341 protected EnumSet<DiagnosticPart> visibleParts;
342 protected boolean caretEnabled;
344 public SimpleConfiguration(Set<DiagnosticPart> parts) {
345 multilineLimits = new HashMap<MultilineLimit, Integer>();
346 setVisible(parts);
347 setMultilineLimit(MultilineLimit.DEPTH, -1);
348 setMultilineLimit(MultilineLimit.LENGTH, -1);
349 setCaretEnabled(true);
350 }
352 @SuppressWarnings("fallthrough")
353 public SimpleConfiguration(Options options, Set<DiagnosticPart> parts) {
354 this(parts);
355 String showSource = null;
356 if ((showSource = options.get("showSource")) != null) {
357 if (showSource.equals("true"))
358 visibleParts.add(DiagnosticPart.SOURCE);
359 else if (showSource.equals("false"))
360 visibleParts.remove(DiagnosticPart.SOURCE);
361 }
362 String diagOpts = options.get("diags");
363 if (diagOpts != null) {//override -XDshowSource
364 Collection<String> args = Arrays.asList(diagOpts.split(","));
365 if (args.contains("short")) {
366 visibleParts.remove(DiagnosticPart.DETAILS);
367 visibleParts.remove(DiagnosticPart.SUBDIAGNOSTICS);
368 }
369 if (args.contains("source"))
370 visibleParts.add(DiagnosticPart.SOURCE);
371 if (args.contains("-source"))
372 visibleParts.remove(DiagnosticPart.SOURCE);
373 }
374 String multiPolicy = null;
375 if ((multiPolicy = options.get("multilinePolicy")) != null) {
376 if (multiPolicy.equals("disabled"))
377 visibleParts.remove(DiagnosticPart.SUBDIAGNOSTICS);
378 else if (multiPolicy.startsWith("limit:")) {
379 String limitString = multiPolicy.substring("limit:".length());
380 String[] limits = limitString.split(":");
381 try {
382 switch (limits.length) {
383 case 2: {
384 if (!limits[1].equals("*"))
385 setMultilineLimit(MultilineLimit.DEPTH, Integer.parseInt(limits[1]));
386 }
387 case 1: {
388 if (!limits[0].equals("*"))
389 setMultilineLimit(MultilineLimit.LENGTH, Integer.parseInt(limits[0]));
390 }
391 }
392 }
393 catch(NumberFormatException ex) {
394 setMultilineLimit(MultilineLimit.DEPTH, -1);
395 setMultilineLimit(MultilineLimit.LENGTH, -1);
396 }
397 }
398 }
399 String showCaret = null;
400 if (((showCaret = options.get("showCaret")) != null) &&
401 showCaret.equals("false"))
402 setCaretEnabled(false);
403 else
404 setCaretEnabled(true);
405 }
407 public int getMultilineLimit(MultilineLimit limit) {
408 return multilineLimits.get(limit);
409 }
411 public EnumSet<DiagnosticPart> getVisible() {
412 return EnumSet.copyOf(visibleParts);
413 }
415 public void setMultilineLimit(MultilineLimit limit, int value) {
416 multilineLimits.put(limit, value < -1 ? -1 : value);
417 }
420 public void setVisible(Set<DiagnosticPart> diagParts) {
421 visibleParts = EnumSet.copyOf(diagParts);
422 }
424 /**
425 * Shows a '^' sign under the source line displayed by the formatter
426 * (if applicable).
427 *
428 * @param caretEnabled if true enables caret
429 */
430 public void setCaretEnabled(boolean caretEnabled) {
431 this.caretEnabled = caretEnabled;
432 }
434 /**
435 * Tells whether the caret display is active or not.
436 *
437 * @param caretEnabled if true the caret is enabled
438 */
439 public boolean isCaretEnabled() {
440 return caretEnabled;
441 }
442 }
444 /**
445 * An enhanced printer for formatting types/symbols used by
446 * AbstractDiagnosticFormatter. Provides alternate numbering of captured
447 * types (they are numbered starting from 1 on each new diagnostic, instead
448 * of relying on the underlying hashcode() method which generates unstable
449 * output). Also detects cycles in wildcard messages (e.g. if the wildcard
450 * type referred by a given captured type C contains C itself) which might
451 * lead to infinite loops.
452 */
453 protected class FormatterPrinter extends Printer {
455 List<Type> allCaptured = List.nil();
456 List<Type> seenCaptured = List.nil();
458 @Override
459 protected String localize(Locale locale, String key, Object... args) {
460 return AbstractDiagnosticFormatter.this.localize(locale, key, args);
461 }
463 @Override
464 public String visitCapturedType(CapturedType t, Locale locale) {
465 if (seenCaptured.contains(t))
466 return localize(locale, "compiler.misc.type.captureof.1",
467 allCaptured.indexOf(t) + 1);
468 else {
469 try {
470 seenCaptured = seenCaptured.prepend(t);
471 allCaptured = allCaptured.append(t);
472 return localize(locale, "compiler.misc.type.captureof",
473 allCaptured.indexOf(t) + 1,
474 visit(t.wildcard, locale));
475 }
476 finally {
477 seenCaptured = seenCaptured.tail;
478 }
479 }
480 }
481 }
482 }