File: TestDocComments.java

package info (click to toggle)
libnb-javaparser-java 9%2B2018-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 65,320 kB
  • sloc: java: 440,096; xml: 6,359; sh: 865; makefile: 314
file content (302 lines) | stat: -rw-r--r-- 10,883 bytes parent folder | download | duplicates (12)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/*
 * Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * @test
 * @bug 6877202 6986246
 * @summary Elements.getDocComment() is not getting JavaDocComments
 * @library /tools/javac/lib
 * @modules jdk.compiler
 * @build JavacTestingAbstractProcessor TestDocComments
 * @run main TestDocComments
 */

import com.sun.source.tree.*;
import com.sun.source.util.*;
import java.io.*;
import java.util.*;
import javax.annotation.processing.*;
import javax.lang.model.*;
import javax.lang.model.element.*;
import javax.lang.model.util.*;
import javax.tools.*;

/*
 * For a mixture of pre-existing and generated source files, ensure that we can
 * get the doc comments.
 * The test uses both a standard ElementScanner to find all the elements being
 * processed, and a TreeScanner to find all the local and anonymous inner classes
 * as well.
 * And, because the relevant code paths in the compiler are different for
 * command line and JSR 199 invocation, the test covers both ways of invoking the
 * compiler.
 */

@SupportedOptions("scan")
public class TestDocComments extends JavacTestingAbstractProcessor {
    enum CompileKind { API, CMD };
    enum ScanKind { TREE, ELEMENT };

    // ----- Main test driver: invoke compiler for the various test cases ------

    public static void main(String... args) throws Exception {
        for (CompileKind ck: CompileKind.values()) {
            for (ScanKind sk: ScanKind.values()) {
                try {
                    test(ck, sk);
                } catch (IOException e) {
                    error(e.toString());
                }
            }
        }

        if (errors > 0)
            throw new Exception(errors + " errors occurred");
    }

    static void test(CompileKind ck, ScanKind sk) throws IOException {
        String testClasses = System.getProperty("test.class.path");
        String testSrc = System.getProperty("test.src");
        File testDir = new File("test." + ck + "." + sk);
        testDir.mkdirs();
        String[] opts = {
            "-d", testDir.getPath(),
            "-implicit:none",
            "-processor", TestDocComments.class.getName(),
            "-processorpath", testClasses,
            //"-XprintRounds",
            "-Ascan=" + sk
        };
        File[] files = {
            new File(testSrc, "a/First.java")
        };

        if (ck == CompileKind.API)
            test_javac_api(opts, files);
        else
            test_javac_cmd(opts, files);
    }

    static void test_javac_api(String[] opts, File[] files) throws IOException {
        System.err.println("test javac api: " + Arrays.asList(opts) + " " + Arrays.asList(files));
        DiagnosticListener<JavaFileObject> dl = new DiagnosticListener<JavaFileObject>() {
            public void report(Diagnostic diagnostic) {
                error(diagnostic.toString());
            }
        };
        JavaCompiler c = ToolProvider.getSystemJavaCompiler();
        try (StandardJavaFileManager fm = c.getStandardFileManager(null, null, null)) {
            Iterable<? extends JavaFileObject> units = fm.getJavaFileObjects(files);
            JavacTask t = (JavacTask) c.getTask(null, fm, dl, Arrays.asList(opts), null, units);
            t.parse();
            t.analyze();
        }
    }

    static void test_javac_cmd(String[] opts, File[] files) {
        System.err.println("test javac cmd: " + Arrays.asList(opts) + " " + Arrays.asList(files));
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        List<String> args = new ArrayList<String>(Arrays.asList(opts));
        for (File f: files)
            args.add(f.getPath());
        int rc = com.sun.tools.javac.Main.compile(args.toArray(new String[args.size()]), pw);
        pw.close();
        String out = sw.toString();
        if (out.length() > 0)
            System.err.println(out);
        if (rc > 0)
            error("Compilation failed: rc=" + rc);
    }

    static void error(String msg) {
        System.err.println(msg);
        errors++;
        //throw new Error(msg);
    }

    static int errors;

    // ----- Annotation processor: scan for elements and check doc comments ----

    Map<String,String> options;
    Trees trees;
    ScanKind skind;

    int round = 0;

    @Override
    public void init(ProcessingEnvironment pEnv) {
        super.init(pEnv);
        options = pEnv.getOptions();
        trees = Trees.instance(processingEnv);
        skind = ScanKind.valueOf(options.get("scan"));
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        round++;

        // Scan elements using an appropriate scanner, and for each element found,
        // call check(Element e) to verify the doc comment on that element
        for (Element e: roundEnv.getRootElements()) {
            System.err.println("scan " + skind + " " + e.getKind() + " " + e.getSimpleName());
            if (skind == ScanKind.TREE) {
                new TestTreeScanner().scan(trees.getPath(e), trees);
            }  else
                new TestElementScanner().scan(e);
        }

        // For a few rounds, generate new source files, so that we can check whether
        // doc comments are correctly handled in subsequent processing rounds
        final int MAX_ROUNDS = 3;
        if (round <= MAX_ROUNDS) {
            String pkg = "p";
            String currClass = "Gen" + round;
            String curr = pkg + "." + currClass;
            String next = (round < MAX_ROUNDS) ? (pkg + ".Gen" + (round + 1)) : "z.Last";
            StringBuilder text = new StringBuilder();
            text.append("package ").append(pkg).append(";\n");
            text.append("/** CLASS ").append(currClass).append(" */\n");
            text.append("public class ").append(currClass).append(" {\n");
            text.append("    /** CONSTRUCTOR <init> **/\n");
            text.append("    ").append(currClass).append("() { }\n");
            text.append("    /** FIELD x */\n");
            text.append("    ").append(next).append(" x;\n");
            text.append("    /** METHOD m */\n");
            text.append("    void m() { }\n");
            text.append("}\n");

            try {
                JavaFileObject fo = filer.createSourceFile(curr);
                Writer out = fo.openWriter();
                try {
                    out.write(text.toString());
                } finally {
                    out.close();
                }
            } catch (IOException e) {
                throw new Error(e);
            }
        }

        return true;
    }

    /*
     * Check that the doc comment on an element is as expected.
     * This method is invoked for each element found by the scanners run by process.
     */
    void check(Element e) {
        System.err.println("Checking " + e);

        String dc = elements.getDocComment(e);
        System.err.println("   found " + dc);

        String expect = (e.getKind() + " " + e.getSimpleName()); // default

        Name name = e.getSimpleName();
        Element encl = e.getEnclosingElement();
        Name enclName = encl.getSimpleName();
        ElementKind enclKind = encl.getKind();
        switch (e.getKind()) {
            case PARAMETER:
            case LOCAL_VARIABLE:
                // doc comments not retained for these elements
                expect = null;
                break;

            case CONSTRUCTOR:
                if (enclName.length() == 0 || enclKind == ElementKind.ENUM) {
                    // Enum constructor is synthetic
                    expect = null;
                }
                break;

            case METHOD:
                if (enclKind == ElementKind.ENUM
                        && (name.contentEquals("values") || name.contentEquals("valueOf"))) {
                    // synthetic enum methods
                    expect = null;
                }
                break;

            case CLASS:
                if (e.getSimpleName().length() == 0) {
                    // anon inner class
                    expect = null;
                }
                break;
        }

        System.err.println("  expect " + expect);

        if (dc == null ? expect == null : dc.trim().equals(expect))
            return;

        if (dc == null)
            messager.printMessage(Diagnostic.Kind.ERROR, "doc comment is null", e);
        else {
            messager.printMessage(Diagnostic.Kind.ERROR,
                    "unexpected comment: \"" + dc + "\", expected \"" + expect + "\"", e);
        }
    }

    // ----- Scanners to find elements -----------------------------------------

    class TestElementScanner extends ElementScanner<Void, Void> {
        @Override
        public Void visitExecutable(ExecutableElement e, Void p) {
            check(e);
            return super.visitExecutable(e, p);
        }
        @Override
        public Void visitType(TypeElement e, Void p) {
            check(e);
            return super.visitType(e, p);
        }
        @Override
        public Void visitVariable(VariableElement e, Void p) {
            check(e);
            return super.visitVariable(e, p);
        }
    }

    class TestTreeScanner extends TreePathScanner<Void,Trees> {
        @Override
        public Void visitClass(ClassTree tree, Trees trees) {
            check(trees.getElement(getCurrentPath()));
            return super.visitClass(tree, trees);
        }
        @Override
        public Void visitMethod(MethodTree tree, Trees trees) {
            check(trees.getElement(getCurrentPath()));
            return super.visitMethod(tree, trees);
        }
        @Override
        public Void visitVariable(VariableTree tree, Trees trees) {
            check(trees.getElement(getCurrentPath()));
            return super.visitVariable(tree, trees);
        }
    }
}