PrintingProcessor.java revision 2601:8e638f046bf0
1/*
2 * Copyright (c) 2005, 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.processing;
27
28import javax.annotation.processing.*;
29import javax.lang.model.*;
30import javax.lang.model.element.*;
31import static javax.lang.model.element.ElementKind.*;
32import static javax.lang.model.element.NestingKind.*;
33import javax.lang.model.type.*;
34import javax.lang.model.util.*;
35
36import java.io.PrintWriter;
37import java.io.Writer;
38import java.util.*;
39
40import com.sun.tools.javac.util.DefinedBy;
41import com.sun.tools.javac.util.DefinedBy.Api;
42import com.sun.tools.javac.util.StringUtils;
43
44/**
45 * A processor which prints out elements.  Used to implement the
46 * -Xprint option; the included visitor class is used to implement
47 * Elements.printElements.
48 *
49 * <p><b>This is NOT part of any supported API.
50 * If you write code that depends on this, you do so at your own risk.
51 * This code and its internal interfaces are subject to change or
52 * deletion without notice.</b>
53 */
54@SupportedAnnotationTypes("*")
55@SupportedSourceVersion(SourceVersion.RELEASE_9)
56public class PrintingProcessor extends AbstractProcessor {
57    PrintWriter writer;
58
59    public PrintingProcessor() {
60        super();
61        writer = new PrintWriter(System.out);
62    }
63
64    public void setWriter(Writer w) {
65        writer = new PrintWriter(w);
66    }
67
68    @Override @DefinedBy(Api.ANNOTATION_PROCESSING)
69    public boolean process(Set<? extends TypeElement> tes,
70                           RoundEnvironment renv) {
71
72        for(Element element : renv.getRootElements()) {
73            print(element);
74        }
75
76        // Just print the elements, nothing more to do.
77        return true;
78    }
79
80    void print(Element element) {
81        new PrintingElementVisitor(writer, processingEnv.getElementUtils()).
82            visit(element).flush();
83    }
84
85    /**
86     * Used for the -Xprint option and called by Elements.printElements
87     */
88    public static class PrintingElementVisitor
89        extends SimpleElementVisitor9<PrintingElementVisitor, Boolean> {
90        int indentation; // Indentation level;
91        final PrintWriter writer;
92        final Elements elementUtils;
93
94        public PrintingElementVisitor(Writer w, Elements elementUtils) {
95            super();
96            this.writer = new PrintWriter(w);
97            this.elementUtils = elementUtils;
98            indentation = 0;
99        }
100
101        @Override @DefinedBy(Api.LANGUAGE_MODEL)
102        protected PrintingElementVisitor defaultAction(Element e, Boolean newLine) {
103            if (newLine != null && newLine)
104                writer.println();
105            printDocComment(e);
106            printModifiers(e);
107            return this;
108        }
109
110        @Override @DefinedBy(Api.LANGUAGE_MODEL)
111        public PrintingElementVisitor visitExecutable(ExecutableElement e, Boolean p) {
112            ElementKind kind = e.getKind();
113
114            if (kind != STATIC_INIT &&
115                kind != INSTANCE_INIT) {
116                Element enclosing = e.getEnclosingElement();
117
118                // Don't print out the constructor of an anonymous class
119                if (kind == CONSTRUCTOR &&
120                    enclosing != null &&
121                    NestingKind.ANONYMOUS ==
122                    // Use an anonymous class to determine anonymity!
123                    (new SimpleElementVisitor7<NestingKind, Void>() {
124                        @Override @DefinedBy(Api.LANGUAGE_MODEL)
125                        public NestingKind visitType(TypeElement e, Void p) {
126                            return e.getNestingKind();
127                        }
128                    }).visit(enclosing))
129                    return this;
130
131                defaultAction(e, true);
132                printFormalTypeParameters(e, true);
133
134                switch(kind) {
135                    case CONSTRUCTOR:
136                    // Print out simple name of the class
137                    writer.print(e.getEnclosingElement().getSimpleName());
138                    break;
139
140                    case METHOD:
141                    writer.print(e.getReturnType().toString());
142                    writer.print(" ");
143                    writer.print(e.getSimpleName().toString());
144                    break;
145                }
146
147                writer.print("(");
148                printParameters(e);
149                writer.print(")");
150                AnnotationValue defaultValue = e.getDefaultValue();
151                if (defaultValue != null)
152                    writer.print(" default " + defaultValue);
153
154                printThrows(e);
155                writer.println(";");
156            }
157            return this;
158        }
159
160
161        @Override @DefinedBy(Api.LANGUAGE_MODEL)
162        public PrintingElementVisitor visitType(TypeElement e, Boolean p) {
163            ElementKind kind = e.getKind();
164            NestingKind nestingKind = e.getNestingKind();
165
166            if (NestingKind.ANONYMOUS == nestingKind) {
167                // Print out an anonymous class in the style of a
168                // class instance creation expression rather than a
169                // class declaration.
170                writer.print("new ");
171
172                // If the anonymous class implements an interface
173                // print that name, otherwise print the superclass.
174                List<? extends TypeMirror> interfaces = e.getInterfaces();
175                if (!interfaces.isEmpty())
176                    writer.print(interfaces.get(0));
177                else
178                    writer.print(e.getSuperclass());
179
180                writer.print("(");
181                // Anonymous classes that implement an interface can't
182                // have any constructor arguments.
183                if (interfaces.isEmpty()) {
184                    // Print out the parameter list from the sole
185                    // constructor.  For now, don't try to elide any
186                    // synthetic parameters by determining if the
187                    // anonymous class is in a static context, etc.
188                    List<? extends ExecutableElement> constructors =
189                        ElementFilter.constructorsIn(e.getEnclosedElements());
190
191                    if (!constructors.isEmpty())
192                        printParameters(constructors.get(0));
193                }
194                writer.print(")");
195            } else {
196                if (nestingKind == TOP_LEVEL) {
197                    PackageElement pkg = elementUtils.getPackageOf(e);
198                    if (!pkg.isUnnamed())
199                        writer.print("package " + pkg.getQualifiedName() + ";\n");
200                }
201
202                defaultAction(e, true);
203
204                switch(kind) {
205                case ANNOTATION_TYPE:
206                    writer.print("@interface");
207                    break;
208                default:
209                    writer.print(StringUtils.toLowerCase(kind.toString()));
210                }
211                writer.print(" ");
212                writer.print(e.getSimpleName());
213
214                printFormalTypeParameters(e, false);
215
216                // Print superclass information if informative
217                if (kind == CLASS) {
218                    TypeMirror supertype = e.getSuperclass();
219                    if (supertype.getKind() != TypeKind.NONE) {
220                        TypeElement e2 = (TypeElement)
221                            ((DeclaredType) supertype).asElement();
222                        if (e2.getSuperclass().getKind() != TypeKind.NONE)
223                            writer.print(" extends " + supertype);
224                    }
225                }
226
227                printInterfaces(e);
228            }
229            writer.println(" {");
230            indentation++;
231
232            if (kind == ENUM) {
233                List<Element> enclosedElements = new ArrayList<>(e.getEnclosedElements());
234                // Handle any enum constants specially before other entities.
235                List<Element> enumConstants = new ArrayList<>();
236                for(Element element : enclosedElements) {
237                    if (element.getKind() == ENUM_CONSTANT)
238                        enumConstants.add(element);
239                }
240                if (!enumConstants.isEmpty()) {
241                    int i;
242                    for(i = 0; i < enumConstants.size()-1; i++) {
243                        this.visit(enumConstants.get(i), true);
244                        writer.print(",");
245                    }
246                    this.visit(enumConstants.get(i), true);
247                    writer.println(";\n");
248
249                    enclosedElements.removeAll(enumConstants);
250                }
251
252                for(Element element : enclosedElements)
253                    this.visit(element);
254            } else {
255                for(Element element : e.getEnclosedElements())
256                    this.visit(element);
257            }
258
259            indentation--;
260            indent();
261            writer.println("}");
262            return this;
263        }
264
265        @Override @DefinedBy(Api.LANGUAGE_MODEL)
266        public PrintingElementVisitor visitVariable(VariableElement e, Boolean newLine) {
267            ElementKind kind = e.getKind();
268            defaultAction(e, newLine);
269
270            if (kind == ENUM_CONSTANT)
271                writer.print(e.getSimpleName());
272            else {
273                writer.print(e.asType().toString() + " " + e.getSimpleName() );
274                Object constantValue  = e.getConstantValue();
275                if (constantValue != null) {
276                    writer.print(" = ");
277                    writer.print(elementUtils.getConstantExpression(constantValue));
278                }
279                writer.println(";");
280            }
281            return this;
282        }
283
284        @Override @DefinedBy(Api.LANGUAGE_MODEL)
285        public PrintingElementVisitor visitTypeParameter(TypeParameterElement e, Boolean p) {
286            writer.print(e.getSimpleName());
287            return this;
288        }
289
290        // Should we do more here?
291        @Override @DefinedBy(Api.LANGUAGE_MODEL)
292        public PrintingElementVisitor visitPackage(PackageElement e, Boolean p) {
293            defaultAction(e, false);
294            if (!e.isUnnamed())
295                writer.println("package " + e.getQualifiedName() + ";");
296            else
297                writer.println("// Unnamed package");
298            return this;
299        }
300
301        public void flush() {
302            writer.flush();
303        }
304
305        private void printDocComment(Element e) {
306            String docComment = elementUtils.getDocComment(e);
307
308            if (docComment != null) {
309                // Break comment into lines
310                java.util.StringTokenizer st = new StringTokenizer(docComment,
311                                                                  "\n\r");
312                indent();
313                writer.println("/**");
314
315                while(st.hasMoreTokens()) {
316                    indent();
317                    writer.print(" *");
318                    writer.println(st.nextToken());
319                }
320
321                indent();
322                writer.println(" */");
323            }
324        }
325
326        private void printModifiers(Element e) {
327            ElementKind kind = e.getKind();
328            if (kind == PARAMETER) {
329                printAnnotationsInline(e);
330            } else {
331                printAnnotations(e);
332                indent();
333            }
334
335            if (kind == ENUM_CONSTANT)
336                return;
337
338            Set<Modifier> modifiers = new LinkedHashSet<>();
339            modifiers.addAll(e.getModifiers());
340
341            switch (kind) {
342            case ANNOTATION_TYPE:
343            case INTERFACE:
344                modifiers.remove(Modifier.ABSTRACT);
345                break;
346
347            case ENUM:
348                modifiers.remove(Modifier.FINAL);
349                modifiers.remove(Modifier.ABSTRACT);
350                break;
351
352            case METHOD:
353            case FIELD:
354                Element enclosingElement = e.getEnclosingElement();
355                if (enclosingElement != null &&
356                    enclosingElement.getKind().isInterface()) {
357                    modifiers.remove(Modifier.PUBLIC);
358                    modifiers.remove(Modifier.ABSTRACT); // only for methods
359                    modifiers.remove(Modifier.STATIC);   // only for fields
360                    modifiers.remove(Modifier.FINAL);    // only for fields
361                }
362                break;
363
364            }
365
366            for(Modifier m: modifiers) {
367                writer.print(m.toString() + " ");
368            }
369        }
370
371        private void printFormalTypeParameters(Parameterizable e,
372                                               boolean pad) {
373            List<? extends TypeParameterElement> typeParams = e.getTypeParameters();
374            if (typeParams.size() > 0) {
375                writer.print("<");
376
377                boolean first = true;
378                for(TypeParameterElement tpe: typeParams) {
379                    if (!first)
380                        writer.print(", ");
381                    printAnnotationsInline(tpe);
382                    writer.print(tpe.toString());
383                    first = false;
384                }
385
386                writer.print(">");
387                if (pad)
388                    writer.print(" ");
389            }
390        }
391
392        private void printAnnotationsInline(Element e) {
393            List<? extends AnnotationMirror> annots = e.getAnnotationMirrors();
394            for(AnnotationMirror annotationMirror : annots) {
395                writer.print(annotationMirror);
396                writer.print(" ");
397            }
398        }
399
400        private void printAnnotations(Element e) {
401            List<? extends AnnotationMirror> annots = e.getAnnotationMirrors();
402            for(AnnotationMirror annotationMirror : annots) {
403                indent();
404                writer.println(annotationMirror);
405            }
406        }
407
408        // TODO: Refactor
409        private void printParameters(ExecutableElement e) {
410            List<? extends VariableElement> parameters = e.getParameters();
411            int size = parameters.size();
412
413            switch (size) {
414            case 0:
415                break;
416
417            case 1:
418                for(VariableElement parameter: parameters) {
419                    printModifiers(parameter);
420
421                    if (e.isVarArgs() ) {
422                        TypeMirror tm = parameter.asType();
423                        if (tm.getKind() != TypeKind.ARRAY)
424                            throw new AssertionError("Var-args parameter is not an array type: " + tm);
425                        writer.print((ArrayType.class.cast(tm)).getComponentType() );
426                        writer.print("...");
427                    } else
428                        writer.print(parameter.asType());
429                    writer.print(" " + parameter.getSimpleName());
430                }
431                break;
432
433            default:
434                {
435                    int i = 1;
436                    for(VariableElement parameter: parameters) {
437                        if (i == 2)
438                            indentation++;
439
440                        if (i > 1)
441                            indent();
442
443                        printModifiers(parameter);
444
445                        if (i == size && e.isVarArgs() ) {
446                            TypeMirror tm = parameter.asType();
447                            if (tm.getKind() != TypeKind.ARRAY)
448                                throw new AssertionError("Var-args parameter is not an array type: " + tm);
449                                    writer.print((ArrayType.class.cast(tm)).getComponentType() );
450
451                            writer.print("...");
452                        } else
453                            writer.print(parameter.asType());
454                        writer.print(" " + parameter.getSimpleName());
455
456                        if (i < size)
457                            writer.println(",");
458
459                        i++;
460                    }
461
462                    if (parameters.size() >= 2)
463                        indentation--;
464                }
465                break;
466            }
467        }
468
469        private void printInterfaces(TypeElement e) {
470            ElementKind kind = e.getKind();
471
472            if(kind != ANNOTATION_TYPE) {
473                List<? extends TypeMirror> interfaces = e.getInterfaces();
474                if (interfaces.size() > 0) {
475                    writer.print((kind.isClass() ? " implements" : " extends"));
476
477                    boolean first = true;
478                    for(TypeMirror interf: interfaces) {
479                        if (!first)
480                            writer.print(",");
481                        writer.print(" ");
482                        writer.print(interf.toString());
483                        first = false;
484                    }
485                }
486            }
487        }
488
489        private void printThrows(ExecutableElement e) {
490            List<? extends TypeMirror> thrownTypes = e.getThrownTypes();
491            final int size = thrownTypes.size();
492            if (size != 0) {
493                writer.print(" throws");
494
495                int i = 1;
496                for(TypeMirror thrownType: thrownTypes) {
497                    if (i == 1)
498                        writer.print(" ");
499
500                    if (i == 2)
501                        indentation++;
502
503                    if (i >= 2)
504                        indent();
505
506                    writer.print(thrownType);
507
508                    if (i != size)
509                        writer.println(", ");
510
511                    i++;
512                }
513
514                if (size >= 2)
515                    indentation--;
516            }
517        }
518
519        private static final String [] spaces = {
520            "",
521            "  ",
522            "    ",
523            "      ",
524            "        ",
525            "          ",
526            "            ",
527            "              ",
528            "                ",
529            "                  ",
530            "                    "
531        };
532
533        private void indent() {
534            int indentation = this.indentation;
535            if (indentation < 0)
536                return;
537            final int maxIndex = spaces.length - 1;
538
539            while (indentation > maxIndex) {
540                writer.print(spaces[maxIndex]);
541                indentation -= maxIndex;
542            }
543            writer.print(spaces[indentation]);
544        }
545
546    }
547}
548