jdk

Форк
0
/
JavacTestingAbstractProcessor.java 
404 строки · 13.3 Кб
1
/*
2
 * Copyright (c) 2010, 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
import java.io.Writer;
25
import java.util.*;
26
import javax.annotation.processing.*;
27
import javax.lang.model.SourceVersion;
28
import javax.lang.model.element.*;
29
import javax.lang.model.type.*;
30
import javax.lang.model.util.*;
31
import static javax.lang.model.SourceVersion.*;
32

33
/**
34
 * An abstract annotation processor tailored to {@code javac} regression testing.
35
 */
36
public abstract class JavacTestingAbstractProcessor extends AbstractProcessor {
37
    private static final Set<String> allAnnotations = Set.of("*");
38

39
    protected Elements eltUtils;
40
    protected Elements elements;
41
    protected Types    typeUtils;
42
    protected Types    types;
43
    protected Filer    filer;
44
    protected Messager messager;
45
    protected Map<String, String> options;
46

47
    /**
48
     * Constructor for subclasses to call.
49
     */
50
    protected JavacTestingAbstractProcessor() {
51
        super();
52
    }
53

54
    /**
55
     * Return the latest source version. Unless this method is
56
     * overridden, an {@code IllegalStateException} will be thrown if a
57
     * subclass has a {@code SupportedSourceVersion} annotation.
58
     */
59
    @Override
60
    public SourceVersion getSupportedSourceVersion() {
61
        SupportedSourceVersion ssv = this.getClass().getAnnotation(SupportedSourceVersion.class);
62
        if (ssv != null)
63
            throw new IllegalStateException("SupportedSourceVersion annotation not supported here.");
64

65
        return SourceVersion.latest();
66
    }
67

68
    /**
69
     * If the processor class is annotated with {@link
70
     * SupportedAnnotationTypes}, return an unmodifiable set with the
71
     * same set of strings as the annotation.  If the class is not so
72
     * annotated, a one-element set containing {@code "*"} is returned
73
     * to indicate all annotations are processed.
74
     *
75
     * @return the names of the annotation types supported by this
76
     * processor, or an empty set if none
77
     */
78
    @Override
79
    public Set<String> getSupportedAnnotationTypes() {
80
        SupportedAnnotationTypes sat = this.getClass().getAnnotation(SupportedAnnotationTypes.class);
81
        if (sat != null)
82
            return super.getSupportedAnnotationTypes();
83
        else
84
            return allAnnotations;
85
    }
86

87
    @Override
88
    public void init(ProcessingEnvironment processingEnv) {
89
        super.init(processingEnv);
90
        elements = eltUtils  = processingEnv.getElementUtils();
91
        types = typeUtils = processingEnv.getTypeUtils();
92
        filer     = processingEnv.getFiler();
93
        messager  = processingEnv.getMessager();
94
        options   = processingEnv.getOptions();
95
    }
96

97
    protected void addExports(String moduleName, String... packageNames) {
98
        for (String packageName : packageNames) {
99
            try {
100
                ModuleLayer layer = ModuleLayer.boot();
101
                Optional<Module> m = layer.findModule(moduleName);
102
                if (!m.isPresent())
103
                    throw new Error("module not found: " + moduleName);
104
                m.get().addExports(packageName, getClass().getModule());
105
            } catch (Exception e) {
106
                throw new Error("failed to add exports for " + moduleName + "/" + packageName);
107
            }
108
        }
109
    }
110

111
    /*
112
     * The set of visitors below will directly extend the most recent
113
     * corresponding platform visitor type.
114
     */
115

116
    @SupportedSourceVersion(RELEASE_24)
117
    @SuppressWarnings("preview")
118
    public static abstract class AbstractAnnotationValueVisitor<R, P> extends AbstractAnnotationValueVisitorPreview<R, P> {
119

120
        /**
121
         * Constructor for concrete subclasses to call.
122
         */
123
        protected AbstractAnnotationValueVisitor() {
124
            super();
125
        }
126
    }
127

128
    @SupportedSourceVersion(RELEASE_24)
129
    @SuppressWarnings("preview")
130
    public static abstract class AbstractElementVisitor<R, P> extends AbstractElementVisitorPreview<R, P> {
131
        /**
132
         * Constructor for concrete subclasses to call.
133
         */
134
        protected AbstractElementVisitor(){
135
            super();
136
        }
137
    }
138

139
    @SupportedSourceVersion(RELEASE_24)
140
    @SuppressWarnings("preview")
141
    public static abstract class AbstractTypeVisitor<R, P> extends AbstractTypeVisitorPreview<R, P> {
142
        /**
143
         * Constructor for concrete subclasses to call.
144
         */
145
        protected AbstractTypeVisitor() {
146
            super();
147
        }
148
    }
149

150
    @SupportedSourceVersion(RELEASE_24)
151
    @SuppressWarnings("preview")
152
    public static class ElementKindVisitor<R, P> extends ElementKindVisitorPreview<R, P> {
153
        /**
154
         * Constructor for concrete subclasses; uses {@code null} for the
155
         * default value.
156
         */
157
        protected ElementKindVisitor() {
158
            super(null);
159
        }
160

161
        /**
162
         * Constructor for concrete subclasses; uses the argument for the
163
         * default value.
164
         *
165
         * @param defaultValue the value to assign to {@link #DEFAULT_VALUE}
166
         */
167
        protected ElementKindVisitor(R defaultValue) {
168
            super(defaultValue);
169
        }
170
    }
171

172
    @SupportedSourceVersion(RELEASE_24)
173
    @SuppressWarnings("preview")
174
    public static class ElementScanner<R, P> extends ElementScannerPreview<R, P> {
175
        /**
176
         * Constructor for concrete subclasses; uses {@code null} for the
177
         * default value.
178
         */
179
        protected ElementScanner(){
180
            super(null);
181
        }
182

183
        /**
184
         * Constructor for concrete subclasses; uses the argument for the
185
         * default value.
186
         */
187
        protected ElementScanner(R defaultValue){
188
            super(defaultValue);
189
        }
190
    }
191

192
    @SupportedSourceVersion(RELEASE_24)
193
    @SuppressWarnings("preview")
194
    public static class SimpleAnnotationValueVisitor<R, P> extends SimpleAnnotationValueVisitorPreview<R, P> {
195
        /**
196
         * Constructor for concrete subclasses; uses {@code null} for the
197
         * default value.
198
         */
199
        protected SimpleAnnotationValueVisitor() {
200
            super(null);
201
        }
202

203
        /**
204
         * Constructor for concrete subclasses; uses the argument for the
205
         * default value.
206
         *
207
         * @param defaultValue the value to assign to {@link #DEFAULT_VALUE}
208
         */
209
        protected SimpleAnnotationValueVisitor(R defaultValue) {
210
            super(defaultValue);
211
        }
212
    }
213

214
    @SupportedSourceVersion(RELEASE_24)
215
    @SuppressWarnings("preview")
216
    public static class SimpleElementVisitor<R, P> extends SimpleElementVisitorPreview<R, P> {
217
        /**
218
         * Constructor for concrete subclasses; uses {@code null} for the
219
         * default value.
220
         */
221
        protected SimpleElementVisitor(){
222
            super(null);
223
        }
224

225
        /**
226
         * Constructor for concrete subclasses; uses the argument for the
227
         * default value.
228
         *
229
         * @param defaultValue the value to assign to {@link #DEFAULT_VALUE}
230
         */
231
        protected SimpleElementVisitor(R defaultValue){
232
            super(defaultValue);
233
        }
234
    }
235

236
    @SupportedSourceVersion(RELEASE_24)
237
    @SuppressWarnings("preview")
238
    public static class SimpleTypeVisitor<R, P> extends SimpleTypeVisitorPreview<R, P> {
239
        /**
240
         * Constructor for concrete subclasses; uses {@code null} for the
241
         * default value.
242
         */
243
        protected SimpleTypeVisitor(){
244
            super(null);
245
        }
246

247
        /**
248
         * Constructor for concrete subclasses; uses the argument for the
249
         * default value.
250
         *
251
         * @param defaultValue the value to assign to {@link #DEFAULT_VALUE}
252
         */
253
        protected SimpleTypeVisitor(R defaultValue){
254
            super(defaultValue);
255
        }
256
    }
257

258
    @SupportedSourceVersion(RELEASE_24)
259
    @SuppressWarnings("preview")
260
    public static class TypeKindVisitor<R, P> extends TypeKindVisitorPreview<R, P> {
261
        /**
262
         * Constructor for concrete subclasses to call; uses {@code null}
263
         * for the default value.
264
         */
265
        protected TypeKindVisitor() {
266
            super(null);
267
        }
268

269
        /**
270
         * Constructor for concrete subclasses to call; uses the argument
271
         * for the default value.
272
         *
273
         * @param defaultValue the value to assign to {@link #DEFAULT_VALUE}
274
         */
275
        protected TypeKindVisitor(R defaultValue) {
276
            super(defaultValue);
277
        }
278
    }
279

280
    /**
281
     * Vacuous implementation of javax.lang.model.util.Elements to aid
282
     * in test development. Methods with defaults in the interface are
283
     * *not* overridden to allow them to be tested.
284
     */
285
    public static class VacuousElements implements Elements {
286
        public VacuousElements() {}
287

288
        @Override
289
        public PackageElement getPackageElement(CharSequence name) {return null;}
290

291
        @Override
292
        public TypeElement getTypeElement(CharSequence name) {return null;}
293

294
        @Override
295
        public Map<? extends ExecutableElement, ? extends AnnotationValue>
296
                                                          getElementValuesWithDefaults(AnnotationMirror a) {return null;}
297
        @Override
298
        public String getDocComment(Element e) {return null;}
299

300
        @Override
301
        public boolean isDeprecated(Element e) {return false;}
302

303
        @Override
304
        public  Name getBinaryName(TypeElement type) {return null;}
305

306
        @Override
307
        public PackageElement getPackageOf(Element e) {return null;}
308

309
        @Override
310
        public List<? extends Element> getAllMembers(TypeElement type) {return null;}
311

312
        @Override
313
        public List<? extends AnnotationMirror> getAllAnnotationMirrors(Element e) {return null;}
314

315
        @Override
316
        public boolean hides(Element hider, Element hidden) {return false;}
317

318
        @Override
319
        public boolean overrides(ExecutableElement overrider,
320
                             ExecutableElement overridden,
321
                             TypeElement type) {return false;}
322

323
        @Override
324
        public String getConstantExpression(Object value) {return null;}
325

326
        @Override
327
        public void printElements(Writer w, Element... elements) {}
328

329
        @Override
330
        public Name getName(CharSequence cs)  {return null;}
331

332
        @Override
333
        public boolean isFunctionalInterface(TypeElement type) {return false;}
334
    }
335

336
    /**
337
     * Vacuous implementation of javax.lang.model.util.Types to aid
338
     * in test development. Methods with defaults in the interface are
339
     * *not* overridden to allow them to be tested.
340
     */
341
    public static class VacuousTypes implements Types {
342
        public VacuousTypes() {}
343

344
        @Override
345
        public Element asElement(TypeMirror t) {return null;}
346

347
        @Override
348
        public boolean isSameType(TypeMirror t1, TypeMirror t2) {return false;}
349

350
        @Override
351
        public boolean isSubtype(TypeMirror t1, TypeMirror t2) {return false;};
352

353
        @Override
354
        public boolean isAssignable(TypeMirror t1, TypeMirror t2) {return false;};
355

356
        @Override
357
        public boolean contains(TypeMirror t1, TypeMirror t2) {return false;};
358

359
        @Override
360
        public boolean isSubsignature(ExecutableType m1, ExecutableType m2) {return false;}
361

362
        @Override
363
        public List<? extends TypeMirror> directSupertypes(TypeMirror t) {return null;}
364

365
        @Override
366
        public TypeMirror erasure(TypeMirror t) {return null;}
367

368
        @Override
369
        public TypeElement boxedClass(PrimitiveType p) {return null;}
370

371
        @Override
372
        public PrimitiveType unboxedType(TypeMirror t) {return null;}
373

374
        @Override
375
        public TypeMirror capture(TypeMirror t) {return null;}
376

377
        @Override
378
        public PrimitiveType getPrimitiveType(TypeKind kind) {return null;}
379

380
        @Override
381
        public NullType getNullType() {return null;}
382

383
        @Override
384
        public NoType getNoType(TypeKind kind) {return null;}
385

386
        @Override
387
        public ArrayType getArrayType(TypeMirror componentType) {return null;}
388

389
        @Override
390
        public WildcardType getWildcardType(TypeMirror extendsBound,
391
                                 TypeMirror superBound) {return null;}
392

393
        @Override
394
        public DeclaredType getDeclaredType(TypeElement typeElem, TypeMirror... typeArgs) {return null;}
395

396

397
        @Override
398
        public DeclaredType getDeclaredType(DeclaredType containing,
399
                                 TypeElement typeElem, TypeMirror... typeArgs) {return null;}
400

401
        @Override
402
        public TypeMirror asMemberOf(DeclaredType containing, Element element) {return null;}
403
    }
404
}
405

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

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

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

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