Printer.java revision 2571:10fc81ac75b4
1/*
2 * Copyright (c) 2009, 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
26package com.sun.tools.javac.code;
27
28import java.util.Locale;
29
30import com.sun.tools.javac.api.Messages;
31import com.sun.tools.javac.code.Type.ArrayType;
32import com.sun.tools.javac.code.Symbol.*;
33import com.sun.tools.javac.code.Type.*;
34import com.sun.tools.javac.util.List;
35import com.sun.tools.javac.util.ListBuffer;
36
37import static com.sun.tools.javac.code.BoundKind.*;
38import static com.sun.tools.javac.code.Flags.*;
39import static com.sun.tools.javac.code.TypeTag.CLASS;
40import static com.sun.tools.javac.code.TypeTag.FORALL;
41
42/**
43 * A combined type/symbol visitor for generating non-trivial localized string
44 * representation of types and symbols.
45 *
46 * <p><b>This is NOT part of any supported API.
47 * If you write code that depends on this, you do so at your own risk.
48 * This code and its internal interfaces are subject to change or
49 * deletion without notice.</b>
50 */
51public abstract class Printer implements Type.Visitor<String, Locale>, Symbol.Visitor<String, Locale> {
52
53    List<Type> seenCaptured = List.nil();
54    static final int PRIME = 997;  // largest prime less than 1000
55
56    protected Printer() { }
57
58    /**
59     * This method should be overriden in order to provide proper i18n support.
60     *
61     * @param locale the locale in which the string is to be rendered
62     * @param key the key corresponding to the message to be displayed
63     * @param args a list of optional arguments
64     * @return localized string representation
65     */
66    protected abstract String localize(Locale locale, String key, Object... args);
67
68    /**
69     * Maps a captured type into an unique identifier.
70     *
71     * @param t the captured type for which an id is to be retrieved
72     * @param locale locale settings
73     * @return unique id representing this captured type
74     */
75    protected abstract String capturedVarId(CapturedType t, Locale locale);
76
77    /**
78     * Create a printer with default i18n support provided by Messages. By default,
79     * captured types ids are generated using hashcode.
80     *
81     * @param messages Messages class to be used for i18n
82     * @return printer visitor instance
83     */
84    public static Printer createStandardPrinter(final Messages messages) {
85        return new Printer() {
86            @Override
87            protected String localize(Locale locale, String key, Object... args) {
88                return messages.getLocalizedString(locale, key, args);
89            }
90
91            @Override
92            protected String capturedVarId(CapturedType t, Locale locale) {
93                return (t.hashCode() & 0xFFFFFFFFL) % PRIME + "";
94        }};
95    }
96
97    /**
98     * Get a localized string representation for all the types in the input list.
99     *
100     * @param ts types to be displayed
101     * @param locale the locale in which the string is to be rendered
102     * @return localized string representation
103     */
104    public String visitTypes(List<Type> ts, Locale locale) {
105        ListBuffer<String> sbuf = new ListBuffer<>();
106        for (Type t : ts) {
107            sbuf.append(visit(t, locale));
108        }
109        return sbuf.toList().toString();
110    }
111
112    /**
113     * * Get a localized string representation for all the symbols in the input list.
114     *
115     * @param ts symbols to be displayed
116     * @param locale the locale in which the string is to be rendered
117     * @return localized string representation
118     */
119    public String visitSymbols(List<Symbol> ts, Locale locale) {
120        ListBuffer<String> sbuf = new ListBuffer<>();
121        for (Symbol t : ts) {
122            sbuf.append(visit(t, locale));
123        }
124        return sbuf.toList().toString();
125    }
126
127    /**
128     * Get a localized string representation for a given type.
129     *
130     * @param t type to be displayed
131     * @param locale the locale in which the string is to be rendered
132     * @return localized string representation
133     */
134    public String visit(Type t, Locale locale) {
135        return t.accept(this, locale);
136    }
137
138    /**
139     * Get a localized string representation for a given symbol.
140     *
141     * @param s symbol to be displayed
142     * @param locale the locale in which the string is to be rendered
143     * @return localized string representation
144     */
145    public String visit(Symbol s, Locale locale) {
146        return s.accept(this, locale);
147    }
148
149    @Override
150    public String visitCapturedType(CapturedType t, Locale locale) {
151        if (seenCaptured.contains(t))
152            return printAnnotations(t) +
153                localize(locale, "compiler.misc.type.captureof.1",
154                         capturedVarId(t, locale));
155        else {
156            try {
157                seenCaptured = seenCaptured.prepend(t);
158                return printAnnotations(t) +
159                    localize(locale, "compiler.misc.type.captureof",
160                             capturedVarId(t, locale),
161                             visit(t.wildcard, locale));
162            }
163            finally {
164                seenCaptured = seenCaptured.tail;
165            }
166        }
167    }
168
169    @Override
170    public String visitForAll(ForAll t, Locale locale) {
171        return printAnnotations(t) + "<" + visitTypes(t.tvars, locale) +
172            ">" + visit(t.qtype, locale);
173    }
174
175    @Override
176    public String visitUndetVar(UndetVar t, Locale locale) {
177        if (t.inst != null) {
178            return printAnnotations(t) + visit(t.inst, locale);
179        } else {
180            return printAnnotations(t) + visit(t.qtype, locale) + "?";
181        }
182    }
183
184    @Override
185    public String visitArrayType(ArrayType t, Locale locale) {
186        StringBuilder res = new StringBuilder();
187        printBaseElementType(t, res, locale);
188        printBrackets(t, res, locale);
189        return res.toString();
190    }
191
192    private String printAnnotations(Type t) {
193        return printAnnotations(t, false);
194    }
195
196    private String printAnnotations(Type t, boolean prefix) {
197        StringBuilder sb = new StringBuilder();
198        List<Attribute.TypeCompound> annos = t.getAnnotationMirrors();
199        if (!annos.isEmpty()) {
200            if (prefix) sb.append(' ');
201            sb.append(annos);
202            sb.append(' ');
203        }
204        return sb.toString();
205    }
206
207    private void printBaseElementType(Type t, StringBuilder sb, Locale locale) {
208        Type arrel = t;
209        while (arrel.hasTag(TypeTag.ARRAY)) {
210            arrel = ((ArrayType) arrel).elemtype;
211        }
212        sb.append(visit(arrel, locale));
213    }
214
215    private void printBrackets(Type t, StringBuilder sb, Locale locale) {
216        Type arrel = t;
217        while (arrel.hasTag(TypeTag.ARRAY)) {
218            sb.append(printAnnotations(arrel, true));
219            sb.append("[]");
220            arrel = ((ArrayType) arrel).elemtype;
221        }
222    }
223
224    @Override
225    public String visitClassType(ClassType t, Locale locale) {
226        StringBuilder buf = new StringBuilder();
227        if (t.getEnclosingType().hasTag(CLASS) && t.tsym.owner.kind == Kinds.TYP) {
228            buf.append(visit(t.getEnclosingType(), locale));
229            buf.append('.');
230            buf.append(printAnnotations(t));
231            buf.append(className(t, false, locale));
232        } else {
233            buf.append(printAnnotations(t));
234            buf.append(className(t, true, locale));
235        }
236        if (t.getTypeArguments().nonEmpty()) {
237            buf.append('<');
238            buf.append(visitTypes(t.getTypeArguments(), locale));
239            buf.append('>');
240        }
241        return buf.toString();
242    }
243
244    @Override
245    public String visitMethodType(MethodType t, Locale locale) {
246        return "(" + printMethodArgs(t.argtypes, false, locale) + ")" +
247            visit(t.restype, locale);
248    }
249
250    @Override
251    public String visitPackageType(PackageType t, Locale locale) {
252        return t.tsym.getQualifiedName().toString();
253    }
254
255    @Override
256    public String visitWildcardType(WildcardType t, Locale locale) {
257        StringBuilder s = new StringBuilder();
258        s.append(t.kind);
259        if (t.kind != UNBOUND) {
260            s.append(printAnnotations(t));
261            s.append(visit(t.type, locale));
262        }
263        return s.toString();
264    }
265
266    @Override
267    public String visitErrorType(ErrorType t, Locale locale) {
268        return visitType(t, locale);
269    }
270
271    @Override
272    public String visitTypeVar(TypeVar t, Locale locale) {
273        return visitType(t, locale);
274    }
275
276    public String visitType(Type t, Locale locale) {
277        String s = (t.tsym == null || t.tsym.name == null)
278                ? localize(locale, "compiler.misc.type.none")
279                : t.tsym.name.toString();
280        return s;
281    }
282
283    /**
284     * Converts a class name into a (possibly localized) string. Anonymous
285     * inner classes get converted into a localized string.
286     *
287     * @param t the type of the class whose name is to be rendered
288     * @param longform if set, the class' fullname is displayed - if unset the
289     * short name is chosen (w/o package)
290     * @param locale the locale in which the string is to be rendered
291     * @return localized string representation
292     */
293    protected String className(ClassType t, boolean longform, Locale locale) {
294        Symbol sym = t.tsym;
295        if (sym.name.length() == 0 && (sym.flags() & COMPOUND) != 0) {
296            StringBuilder s = new StringBuilder(visit(t.supertype_field, locale));
297            for (List<Type> is = t.interfaces_field; is.nonEmpty(); is = is.tail) {
298                s.append('&');
299                s.append(visit(is.head, locale));
300            }
301            return s.toString();
302        } else if (sym.name.length() == 0) {
303            String s;
304            ClassType norm = (ClassType) t.tsym.type;
305            if (norm == null) {
306                s = localize(locale, "compiler.misc.anonymous.class", (Object) null);
307            } else if (norm.interfaces_field != null && norm.interfaces_field.nonEmpty()) {
308                s = localize(locale, "compiler.misc.anonymous.class",
309                        visit(norm.interfaces_field.head, locale));
310            } else {
311                s = localize(locale, "compiler.misc.anonymous.class",
312                        visit(norm.supertype_field, locale));
313            }
314            return s;
315        } else if (longform) {
316            return sym.getQualifiedName().toString();
317        } else {
318            return sym.name.toString();
319        }
320    }
321
322    /**
323     * Converts a set of method argument types into their corresponding
324     * localized string representation.
325     *
326     * @param args arguments to be rendered
327     * @param varArgs if true, the last method argument is regarded as a vararg
328     * @param locale the locale in which the string is to be rendered
329     * @return localized string representation
330     */
331    protected String printMethodArgs(List<Type> args, boolean varArgs, Locale locale) {
332        if (!varArgs) {
333            return visitTypes(args, locale);
334        } else {
335            StringBuilder buf = new StringBuilder();
336            while (args.tail.nonEmpty()) {
337                buf.append(visit(args.head, locale));
338                args = args.tail;
339                buf.append(',');
340            }
341            if (args.head.hasTag(TypeTag.ARRAY)) {
342                buf.append(visit(((ArrayType) args.head).elemtype, locale));
343                if (args.head.getAnnotationMirrors().nonEmpty()) {
344                    buf.append(' ');
345                    buf.append(args.head.getAnnotationMirrors());
346                    buf.append(' ');
347                }
348                buf.append("...");
349            } else {
350                buf.append(visit(args.head, locale));
351            }
352            return buf.toString();
353        }
354    }
355
356    @Override
357    public String visitClassSymbol(ClassSymbol sym, Locale locale) {
358        return sym.name.isEmpty()
359                ? localize(locale, "compiler.misc.anonymous.class", sym.flatname)
360                : sym.fullname.toString();
361    }
362
363    @Override
364    public String visitMethodSymbol(MethodSymbol s, Locale locale) {
365        if (s.isStaticOrInstanceInit()) {
366            return s.owner.name.toString();
367        } else {
368            String ms = (s.name == s.name.table.names.init)
369                    ? s.owner.name.toString()
370                    : s.name.toString();
371            if (s.type != null) {
372                if (s.type.hasTag(FORALL)) {
373                    ms = "<" + visitTypes(s.type.getTypeArguments(), locale) + ">" + ms;
374                }
375                ms += "(" + printMethodArgs(
376                        s.type.getParameterTypes(),
377                        (s.flags() & VARARGS) != 0,
378                        locale) + ")";
379            }
380            return ms;
381        }
382    }
383
384    @Override
385    public String visitOperatorSymbol(OperatorSymbol s, Locale locale) {
386        return visitMethodSymbol(s, locale);
387    }
388
389    @Override
390    public String visitPackageSymbol(PackageSymbol s, Locale locale) {
391        return s.isUnnamed()
392                ? localize(locale, "compiler.misc.unnamed.package")
393                : s.fullname.toString();
394    }
395
396    @Override
397    public String visitTypeSymbol(TypeSymbol s, Locale locale) {
398        return visitSymbol(s, locale);
399    }
400
401    @Override
402    public String visitVarSymbol(VarSymbol s, Locale locale) {
403        return visitSymbol(s, locale);
404    }
405
406    @Override
407    public String visitSymbol(Symbol s, Locale locale) {
408        return s.name.toString();
409    }
410}
411