jdk

Форк
0
/
ReferenceTest.java 
299 строк · 10.9 Кб
1
/*
2
 * Copyright (c) 2012, 2024, 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.
8
 *
9
 * This code is distributed in the hope that it will be useful, but WITHOUT
10
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12
 * version 2 for more details (a copy is included in the LICENSE file that
13
 * accompanied this code).
14
 *
15
 * You should have received a copy of the GNU General Public License version
16
 * 2 along with this work; if not, write to the Free Software Foundation,
17
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
 *
19
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
 * or visit www.oracle.com if you need additional information or have any
21
 * questions.
22
 */
23

24
/*
25
 * @test
26
 * @bug 7021614 8278373 8164094
27
 * @summary extend com.sun.source API to support parsing javadoc comments
28
 * @summary check references in at-see and {at-link} tags
29
 * @modules jdk.compiler
30
 * @build ReferenceTest
31
 * @compile -processor ReferenceTest -proc:only ReferenceTest.java
32
 */
33

34
import com.sun.source.doctree.DocCommentTree;
35
import com.sun.source.doctree.DocTree;
36
import com.sun.source.doctree.LinkTree;
37
import com.sun.source.doctree.ReferenceTree;
38
import com.sun.source.doctree.SeeTree;
39
import com.sun.source.doctree.TextTree;
40
import com.sun.source.util.DocTreePath;
41
import com.sun.source.util.DocTreePathScanner;
42
import com.sun.source.util.DocTrees;
43
import com.sun.source.util.TreePath;
44

45
import java.util.List;
46
import java.util.Set;
47
import java.util.stream.Collectors;
48
import javax.annotation.processing.AbstractProcessor;
49
import javax.annotation.processing.ProcessingEnvironment;
50
import javax.annotation.processing.RoundEnvironment;
51
import javax.annotation.processing.SupportedAnnotationTypes;
52
import javax.lang.model.SourceVersion;
53
import javax.lang.model.element.Element;
54
import javax.lang.model.element.ExecutableElement;
55
import javax.lang.model.element.QualifiedNameable;
56
import javax.lang.model.element.TypeElement;
57
import javax.lang.model.type.DeclaredType;
58
import javax.lang.model.type.TypeMirror;
59
import javax.tools.Diagnostic.Kind;
60

61
/**
62
 * {@link java.lang        Package}
63
 * {@link java.lang.ERROR  Bad}
64
 * {@link java.lang#ERROR  Bad}
65
 *
66
 * {@link java.lang.String Class}
67
 * {@link           String Class}
68
 * {@link java.lang.String#CASE_INSENSITIVE_ORDER Field}
69
 * {@link java.lang.String#String Constructor}
70
 * {@link java.lang.String#String(byte[]) Constructor}
71
 * {@link java.lang.String#String(byte[] bytes) Constructor}
72
 * {@link java.lang.String#String(byte[], String) Constructor}
73
 * {@link java.lang.String#String(byte[] bytes, String charSetName) Constructor}
74
 * {@link java.lang.String#isEmpty Method}
75
 * {@link java.lang.String#isEmpty() Method}
76
 * {@link java.lang.String#ERROR Bad}
77
 * {@link java.lang.String#equals(Object) Method}
78
 *
79
 * {@link AbstractProcessor Class}
80
 *
81
 * {@link List#add(Object) Method}
82
 *
83
 * {@link #trees Field}
84
 * {@link #getSupportedSourceVersion Method}
85
 * {@link #init(ProcessingEnvironment Method}
86
 *
87
 * @see java.lang        Package
88
 * @see java.lang.ERROR  Bad
89
 * @see java.lang#ERROR  Bad
90
 *
91
 * @see java.lang.String Class
92
 * @see           String Class
93
 * @see java.lang.String#CASE_INSENSITIVE_ORDER Field
94
 * @see java.lang.String#String Constructor
95
 * @see java.lang.String#String(byte[]) Constructor
96
 * @see java.lang.String#String(byte[] bytes) Constructor
97
 * @see java.lang.String#String(byte[],String) Constructor
98
 * @see java.lang.String#String(byte[] bytes, String charsetName) Constructor
99
 * @see java.lang.String#isEmpty Method
100
 * @see java.lang.String#isEmpty() Method
101
 * @see java.lang.String#ERROR Bad
102
 * @see java.lang.String#equals(Object) Method
103
 *
104
 * @see AbstractProcessor Class
105
 *
106
 * @see List#add(Object) Method
107
 *
108
 * @see #trees Field
109
 * @see #getSupportedSourceVersion Method
110
 * @see #init(ProcessingEnvironment) Method
111
 *
112
 * @see java.io.BufferedInputStream#BufferedInputStream(InputStream) Constructor
113
 */
114
@SupportedAnnotationTypes("*")
115
public class ReferenceTest extends AbstractProcessor {
116
    DocTrees trees;
117

118
    @Override
119
    public SourceVersion getSupportedSourceVersion() {
120
        return SourceVersion.latest();
121
    }
122

123
    @Override
124
    public void init(ProcessingEnvironment pEnv) {
125
        super.init(pEnv);
126
        trees = DocTrees.instance(pEnv);
127
    }
128

129
    @Override
130
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
131
        for (Element e: roundEnv.getRootElements()) {
132
            new DocCommentScanner(trees.getPath(e)).scan();
133
            for (Element enc: e.getEnclosedElements()) {
134
                TreePath path = trees.getPath(enc);
135
                if (trees.getDocCommentTree(path) != null) {
136
                    new DocCommentScanner(path).scan();
137
                }
138
            }
139
        }
140
        return true;
141
    }
142

143
    class DocCommentScanner extends DocTreePathScanner<Void, Void> {
144
        TreePath path;
145
        DocCommentTree dc;
146

147
        DocCommentScanner(TreePath path) {
148
            this.path = path;
149
        }
150

151
        void scan() {
152
            dc = trees.getDocCommentTree(path);
153
            scan(new DocTreePath(path, dc), null);
154
        }
155

156
        @Override
157
        public Void visitLink(LinkTree tree, Void ignore) {
158
            checkReference(tree.getReference(), tree.getLabel());
159
            return null;
160
        }
161

162
        @Override
163
        public Void visitSee(SeeTree tree, Void ignore) {
164
            List<? extends DocTree> refLabel = tree.getReference();
165
            if (refLabel.size() > 1 && (refLabel.get(0) instanceof ReferenceTree)) {
166
                ReferenceTree ref = (ReferenceTree) refLabel.get(0);
167
                List<? extends DocTree> label = refLabel.subList(1, refLabel.size());
168
                checkReference(ref, label);
169
            }
170
            return null;
171
        }
172

173
        void checkReference(ReferenceTree tree, List<? extends DocTree> label) {
174
            String sig = tree.getSignature();
175

176
            Element found = trees.getElement(new DocTreePath(getCurrentPath(), tree));
177
            if (found == null) {
178
                System.err.println(sig + " NOT FOUND");
179
            } else {
180
                System.err.println(sig + " found " + found.getKind() + " " + found);
181
            }
182

183
            String expect = "UNKNOWN";
184
            if (label.size() > 0 && label.get(0) instanceof TextTree)
185
                expect = ((TextTree) label.get(0)).getBody();
186

187
            if (expect.startsWith("signature:")) {
188
                expect = expect.substring("signature:".length());
189

190
                String signature = found.getKind().name() + ":" + elementSignature(found);
191

192
                if (!expect.equalsIgnoreCase(signature)) {
193
                    error(tree, "Unexpected value found: " + signature +", expected: " + expect);
194
                }
195
            } else {
196
                if (!expect.equalsIgnoreCase(found == null ? "bad" : found.getKind().name())) {
197
                    error(tree, "Unexpected value found: " + found +", expected: " + expect);
198
                }
199
            }
200
        }
201

202
        void error(DocTree tree, String msg) {
203
            trees.printMessage(Kind.ERROR, msg, tree, dc, path.getCompilationUnit());
204
        }
205
    }
206

207
    String elementSignature(Element el) {
208
        return switch (el.getKind()) {
209
            case METHOD -> elementSignature(el.getEnclosingElement()) + "." + el.getSimpleName() + "(" + executableParamNames((ExecutableElement) el) + ")";
210
            case CLASS, INTERFACE -> ((QualifiedNameable) el).getQualifiedName().toString();
211
            default -> throw new AssertionError("Unhandled Element kind: " + el.getKind());
212
        };
213
    }
214

215
    String executableParamNames(ExecutableElement ee) {
216
        return ee.getParameters()
217
                 .stream()
218
                 .map(p -> type2Name(p.asType()))
219
                 .collect(Collectors.joining(", "));
220
    }
221

222
    String type2Name(TypeMirror type) {
223
        return switch (type.getKind()) {
224
            case DECLARED -> elementSignature(((DeclaredType) type).asElement());
225
            case INT, LONG -> type.toString();
226
            default -> throw new AssertionError("Unhandled type kind: " + type.getKind());
227
        };
228
    }
229
}
230

231
/**
232
 * @see ReferenceTestExtras    Class
233
 * @see #ReferenceTestExtras   Field
234
 * @see #ReferenceTestExtras() Constructor
235
 *
236
 * @see #X    Field
237
 * @see #X()  Method
238
 *
239
 * @see #m    Method
240
 *
241
 * @see #varargs(int...)        Method
242
 * @see #varargs(int... args)   Method
243
 * @see #varargs(int[])         Method
244
 * @see #varargs(int[] args)    Method
245
 *
246
 * @see #methodSearch(String)   signature:METHOD:ReferenceTestExtras.methodSearch(java.lang.String)
247
 * @see #methodSearch(StringBuilder)   signature:METHOD:ReferenceTestExtras.methodSearch(java.lang.CharSequence)
248
 * @see #methodSearchPrimitive1(int, int)   signature:METHOD:ReferenceTestExtras.methodSearchPrimitive1(int, int)
249
 * @see #methodSearchPrimitive1(long, int)   signature:METHOD:ReferenceTestExtras.methodSearchPrimitive1(long, int)
250
 * @see #methodSearchPrimitive1(int, long)   signature:METHOD:ReferenceTestExtras.methodSearchPrimitive1(int, long)
251
 * @see #methodSearchPrimitive1(long, long)   signature:METHOD:ReferenceTestExtras.methodSearchPrimitive1(long, long)
252
 * @see #methodSearchPrimitive2(int, int)   signature:METHOD:ReferenceTestExtras.methodSearchPrimitive2(int, int)
253
 * @see #methodSearchPrimitive2(long, int)   signature:METHOD:ReferenceTestExtras.methodSearchPrimitive2(long, int)
254
 * @see #methodSearchPrimitive2(int, long)   signature:METHOD:ReferenceTestExtras.methodSearchPrimitive2(int, long)
255
 * @see #methodSearchPrimitive2(long, long)   signature:METHOD:ReferenceTestExtras.methodSearchPrimitive2(long, long)
256
 *
257
 * @see Inner#X    Bad
258
 * @see Inner#X()  Bad
259
 * @see Inner#m    Bad
260
 */
261
class ReferenceTestExtras {
262
    int ReferenceTestExtras;            // field
263
    ReferenceTestExtras() { }           // constructor
264
    void ReferenceTestExtras() { }      // method
265

266
    int X;
267
    void X() { }
268
    static class X { }
269

270
    void m() { }
271
    void m(int i) { }
272
    void m(int i, int j) { }
273

274
    void varargs(int... args) { }
275

276
    void methodSearch(Object o) {}
277
    void methodSearch(String s) {}
278
    void methodSearch(CharSequence cs) {}
279

280
    void methodSearchPrimitive1(int i, int j) {}
281
    void methodSearchPrimitive1(long i, int j) {}
282
    void methodSearchPrimitive1(int i, long j) {}
283
    void methodSearchPrimitive1(long i, long j) {}
284

285
    void methodSearchPrimitive2(long i, long j) {}
286
    void methodSearchPrimitive2(int i, long j) {}
287
    void methodSearchPrimitive2(long i, int j) {}
288
    void methodSearchPrimitive2(int i, int j) {}
289

290
    /**
291
     * @see #X         Field
292
     * @see #X()       Method
293
     * @see #m         Method
294
     * @see Inner#X    Bad
295
     * @see Inner#X()  Bad
296
     * @see Inner#m    Bad
297
     */
298
    interface Inner {}
299
}
300

301

302

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.