Tue, 16 Jun 2009 10:46:16 +0100
6835428: regression: return-type inference rejects valid code
Summary: Redundant subtyping test during type-inference ends up in rejecting legal code
Reviewed-by: jjg
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 * All captured types that have been encountered during diagnostic formatting.
81 * This info is used by the FormatterPrinter in order to print friendly unique
82 * ids for captured types
83 */
84 private List<Type> allCaptured = List.nil();
86 /**
87 * Initialize an AbstractDiagnosticFormatter by setting its JavacMessages object.
88 * @param messages
89 */
90 protected AbstractDiagnosticFormatter(JavacMessages messages, SimpleConfiguration config) {
91 this.messages = messages;
92 this.config = config;
93 }
95 public String formatKind(JCDiagnostic d, Locale l) {
96 switch (d.getType()) {
97 case FRAGMENT: return "";
98 case NOTE: return localize(l, "compiler.note.note");
99 case WARNING: return localize(l, "compiler.warn.warning");
100 case ERROR: return localize(l, "compiler.err.error");
101 default:
102 throw new AssertionError("Unknown diagnostic type: " + d.getType());
103 }
104 }
106 @Override
107 public String format(JCDiagnostic d, Locale locale) {
108 allCaptured = List.nil();
109 return formatDiagnostic(d, locale);
110 }
112 abstract String formatDiagnostic(JCDiagnostic d, Locale locale);
114 public String formatPosition(JCDiagnostic d, PositionKind pk,Locale l) {
115 assert (d.getPosition() != Position.NOPOS);
116 return String.valueOf(getPosition(d, pk));
117 }
118 //where
119 private long getPosition(JCDiagnostic d, PositionKind pk) {
120 switch (pk) {
121 case START: return d.getIntStartPosition();
122 case END: return d.getIntEndPosition();
123 case LINE: return d.getLineNumber();
124 case COLUMN: return d.getColumnNumber();
125 case OFFSET: return d.getIntPosition();
126 default:
127 throw new AssertionError("Unknown diagnostic position: " + pk);
128 }
129 }
131 public String formatSource(JCDiagnostic d, boolean fullname, Locale l) {
132 assert (d.getSource() != null);
133 return fullname ? d.getSourceName() : d.getSource().getName();
134 }
136 /**
137 * Format the arguments of a given diagnostic.
138 *
139 * @param d diagnostic whose arguments are to be formatted
140 * @param l locale object to be used for i18n
141 * @return a Collection whose elements are the formatted arguments of the diagnostic
142 */
143 protected Collection<String> formatArguments(JCDiagnostic d, Locale l) {
144 ListBuffer<String> buf = new ListBuffer<String>();
145 for (Object o : d.getArgs()) {
146 buf.append(formatArgument(d, o, l));
147 }
148 return buf.toList();
149 }
151 /**
152 * Format a single argument of a given diagnostic.
153 *
154 * @param d diagnostic whose argument is to be formatted
155 * @param arg argument to be formatted
156 * @param l locale object to be used for i18n
157 * @return string representation of the diagnostic argument
158 */
159 protected String formatArgument(JCDiagnostic d, Object arg, Locale l) {
160 if (arg instanceof JCDiagnostic) {
161 String s = null;
162 depth++;
163 try {
164 s = formatMessage((JCDiagnostic)arg, l);
165 }
166 finally {
167 depth--;
168 }
169 return s;
170 }
171 else if (arg instanceof Iterable<?>) {
172 return formatIterable(d, (Iterable<?>)arg, l);
173 }
174 else if (arg instanceof Type) {
175 return printer.visit((Type)arg, l);
176 }
177 else if (arg instanceof Symbol) {
178 return printer.visit((Symbol)arg, l);
179 }
180 else if (arg instanceof JavaFileObject) {
181 return JavacFileManager.getJavacBaseFileName((JavaFileObject)arg);
182 }
183 else if (arg instanceof Formattable) {
184 return ((Formattable)arg).toString(l, messages);
185 }
186 else {
187 return String.valueOf(arg);
188 }
189 }
191 /**
192 * Format an iterable argument of a given diagnostic.
193 *
194 * @param d diagnostic whose argument is to be formatted
195 * @param it iterable argument to be formatted
196 * @param l locale object to be used for i18n
197 * @return string representation of the diagnostic iterable argument
198 */
199 protected String formatIterable(JCDiagnostic d, Iterable<?> it, Locale l) {
200 StringBuilder sbuf = new StringBuilder();
201 String sep = "";
202 for (Object o : it) {
203 sbuf.append(sep);
204 sbuf.append(formatArgument(d, o, l));
205 sep = ",";
206 }
207 return sbuf.toString();
208 }
210 /**
211 * Format all the subdiagnostics attached to a given diagnostic.
212 *
213 * @param d diagnostic whose subdiagnostics are to be formatted
214 * @param l locale object to be used for i18n
215 * @return list of all string representations of the subdiagnostics
216 */
217 protected List<String> formatSubdiagnostics(JCDiagnostic d, Locale l) {
218 List<String> subdiagnostics = List.nil();
219 int maxDepth = config.getMultilineLimit(MultilineLimit.DEPTH);
220 if (maxDepth == -1 || depth < maxDepth) {
221 depth++;
222 try {
223 int maxCount = config.getMultilineLimit(MultilineLimit.LENGTH);
224 int count = 0;
225 for (JCDiagnostic d2 : d.getSubdiagnostics()) {
226 if (maxCount == -1 || count < maxCount) {
227 subdiagnostics = subdiagnostics.append(formatSubdiagnostic(d, d2, l));
228 count++;
229 }
230 else
231 break;
232 }
233 }
234 finally {
235 depth--;
236 }
237 }
238 return subdiagnostics;
239 }
241 /**
242 * Format a subdiagnostics attached to a given diagnostic.
243 *
244 * @param parent multiline diagnostic whose subdiagnostics is to be formatted
245 * @param sub subdiagnostic to be formatted
246 * @param l locale object to be used for i18n
247 * @return string representation of the subdiagnostics
248 */
249 protected String formatSubdiagnostic(JCDiagnostic parent, JCDiagnostic sub, Locale l) {
250 return formatMessage(sub, l);
251 }
253 /** Format the faulty source code line and point to the error.
254 * @param d The diagnostic for which the error line should be printed
255 */
256 protected String formatSourceLine(JCDiagnostic d, int nSpaces) {
257 StringBuilder buf = new StringBuilder();
258 DiagnosticSource source = d.getDiagnosticSource();
259 int pos = d.getIntPosition();
260 if (d.getIntPosition() == Position.NOPOS)
261 throw new AssertionError();
262 String line = (source == null ? null : source.getLine(pos));
263 if (line == null)
264 return "";
265 buf.append(indent(line, nSpaces));
266 int col = source.getColumnNumber(pos, false);
267 if (config.isCaretEnabled()) {
268 buf.append("\n");
269 for (int i = 0; i < col - 1; i++) {
270 buf.append((line.charAt(i) == '\t') ? "\t" : " ");
271 }
272 buf.append(indent("^", nSpaces));
273 }
274 return buf.toString();
275 }
277 /**
278 * Converts a String into a locale-dependent representation accordingly to a given locale.
279 *
280 * @param l locale object to be used for i18n
281 * @param key locale-independent key used for looking up in a resource file
282 * @param args localization arguments
283 * @return a locale-dependent string
284 */
285 protected String localize(Locale l, String key, Object... args) {
286 return messages.getLocalizedString(l, key, args);
287 }
289 public boolean displaySource(JCDiagnostic d) {
290 return config.getVisible().contains(DiagnosticPart.SOURCE) &&
291 d.getType() != FRAGMENT &&
292 d.getIntPosition() != Position.NOPOS;
293 }
295 public boolean isRaw() {
296 return false;
297 }
299 /**
300 * Creates a string with a given amount of empty spaces. Useful for
301 * indenting the text of a diagnostic message.
302 *
303 * @param nSpaces the amount of spaces to be added to the result string
304 * @return the indentation string
305 */
306 protected String indentString(int nSpaces) {
307 String spaces = " ";
308 if (nSpaces <= spaces.length())
309 return spaces.substring(0, nSpaces);
310 else {
311 StringBuilder buf = new StringBuilder();
312 for (int i = 0 ; i < nSpaces ; i++)
313 buf.append(" ");
314 return buf.toString();
315 }
316 }
318 /**
319 * Indent a string by prepending a given amount of empty spaces to each line
320 * of the string.
321 *
322 * @param s the string to be indented
323 * @param nSpaces the amount of spaces that should be prepended to each line
324 * of the string
325 * @return an indented string
326 */
327 protected String indent(String s, int nSpaces) {
328 String indent = indentString(nSpaces);
329 StringBuilder buf = new StringBuilder();
330 String nl = "";
331 for (String line : s.split("\n")) {
332 buf.append(nl);
333 buf.append(indent + line);
334 nl = "\n";
335 }
336 return buf.toString();
337 }
339 public SimpleConfiguration getConfiguration() {
340 return config;
341 }
343 static public class SimpleConfiguration implements Configuration {
345 protected Map<MultilineLimit, Integer> multilineLimits;
346 protected EnumSet<DiagnosticPart> visibleParts;
347 protected boolean caretEnabled;
349 public SimpleConfiguration(Set<DiagnosticPart> parts) {
350 multilineLimits = new HashMap<MultilineLimit, Integer>();
351 setVisible(parts);
352 setMultilineLimit(MultilineLimit.DEPTH, -1);
353 setMultilineLimit(MultilineLimit.LENGTH, -1);
354 setCaretEnabled(true);
355 }
357 @SuppressWarnings("fallthrough")
358 public SimpleConfiguration(Options options, Set<DiagnosticPart> parts) {
359 this(parts);
360 String showSource = null;
361 if ((showSource = options.get("showSource")) != null) {
362 if (showSource.equals("true"))
363 setVisiblePart(DiagnosticPart.SOURCE, true);
364 else if (showSource.equals("false"))
365 setVisiblePart(DiagnosticPart.SOURCE, false);
366 }
367 String diagOpts = options.get("diags");
368 if (diagOpts != null) {//override -XDshowSource
369 Collection<String> args = Arrays.asList(diagOpts.split(","));
370 if (args.contains("short")) {
371 setVisiblePart(DiagnosticPart.DETAILS, false);
372 setVisiblePart(DiagnosticPart.SUBDIAGNOSTICS, false);
373 }
374 if (args.contains("source"))
375 setVisiblePart(DiagnosticPart.SOURCE, true);
376 if (args.contains("-source"))
377 setVisiblePart(DiagnosticPart.SOURCE, false);
378 }
379 String multiPolicy = null;
380 if ((multiPolicy = options.get("multilinePolicy")) != null) {
381 if (multiPolicy.equals("disabled"))
382 setVisiblePart(DiagnosticPart.SUBDIAGNOSTICS, false);
383 else if (multiPolicy.startsWith("limit:")) {
384 String limitString = multiPolicy.substring("limit:".length());
385 String[] limits = limitString.split(":");
386 try {
387 switch (limits.length) {
388 case 2: {
389 if (!limits[1].equals("*"))
390 setMultilineLimit(MultilineLimit.DEPTH, Integer.parseInt(limits[1]));
391 }
392 case 1: {
393 if (!limits[0].equals("*"))
394 setMultilineLimit(MultilineLimit.LENGTH, Integer.parseInt(limits[0]));
395 }
396 }
397 }
398 catch(NumberFormatException ex) {
399 setMultilineLimit(MultilineLimit.DEPTH, -1);
400 setMultilineLimit(MultilineLimit.LENGTH, -1);
401 }
402 }
403 }
404 String showCaret = null;
405 if (((showCaret = options.get("showCaret")) != null) &&
406 showCaret.equals("false"))
407 setCaretEnabled(false);
408 else
409 setCaretEnabled(true);
410 }
412 public int getMultilineLimit(MultilineLimit limit) {
413 return multilineLimits.get(limit);
414 }
416 public EnumSet<DiagnosticPart> getVisible() {
417 return EnumSet.copyOf(visibleParts);
418 }
420 public void setMultilineLimit(MultilineLimit limit, int value) {
421 multilineLimits.put(limit, value < -1 ? -1 : value);
422 }
425 public void setVisible(Set<DiagnosticPart> diagParts) {
426 visibleParts = EnumSet.copyOf(diagParts);
427 }
429 public void setVisiblePart(DiagnosticPart diagParts, boolean enabled) {
430 if (enabled)
431 visibleParts.add(diagParts);
432 else
433 visibleParts.remove(diagParts);
434 }
436 /**
437 * Shows a '^' sign under the source line displayed by the formatter
438 * (if applicable).
439 *
440 * @param caretEnabled if true enables caret
441 */
442 public void setCaretEnabled(boolean caretEnabled) {
443 this.caretEnabled = caretEnabled;
444 }
446 /**
447 * Tells whether the caret display is active or not.
448 *
449 * @param caretEnabled if true the caret is enabled
450 */
451 public boolean isCaretEnabled() {
452 return caretEnabled;
453 }
454 }
456 public Printer getPrinter() {
457 return printer;
458 }
460 public void setPrinter(Printer printer) {
461 this.printer = printer;
462 }
464 /**
465 * An enhanced printer for formatting types/symbols used by
466 * AbstractDiagnosticFormatter. Provides alternate numbering of captured
467 * types (they are numbered starting from 1 on each new diagnostic, instead
468 * of relying on the underlying hashcode() method which generates unstable
469 * output). Also detects cycles in wildcard messages (e.g. if the wildcard
470 * type referred by a given captured type C contains C itself) which might
471 * lead to infinite loops.
472 */
473 protected Printer printer = new Printer() {
474 @Override
475 protected String localize(Locale locale, String key, Object... args) {
476 return AbstractDiagnosticFormatter.this.localize(locale, key, args);
477 }
478 @Override
479 protected String capturedVarId(CapturedType t, Locale locale) {
480 return "" + (allCaptured.indexOf(t) + 1);
481 }
482 @Override
483 public String visitCapturedType(CapturedType t, Locale locale) {
484 if (!allCaptured.contains(t)) {
485 allCaptured = allCaptured.append(t);
486 }
487 return super.visitCapturedType(t, locale);
488 }
489 };
490 }