-
Notifications
You must be signed in to change notification settings - Fork 6.3k
Expand file tree
/
Copy pathLint.java
More file actions
525 lines (452 loc) · 17.8 KB
/
Lint.java
File metadata and controls
525 lines (452 loc) · 17.8 KB
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
/*
* Copyright (c) 2005, 2025, 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package com.sun.tools.javac.code;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;
import java.util.SequencedMap;
import java.util.SequencedSet;
import java.util.Set;
import java.util.stream.Stream;
import com.sun.tools.javac.main.Option;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Names;
import com.sun.tools.javac.util.Options;
/**
* A class for handling -Xlint suboptions and @SuppressWarnings.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Lint {
/** The context key for the root Lint object. */
protected static final Context.Key<Lint> lintKey = new Context.Key<>();
/** Get the root Lint instance. */
public static Lint instance(Context context) {
Lint instance = context.get(lintKey);
if (instance == null)
instance = new Lint(context);
return instance;
}
/**
* Obtain an instance with additional warning supression applied from any
* @SuppressWarnings and/or @Deprecated annotations on the given symbol.
*
* <p>
* The returned instance will be different from this instance if and only if
* {@link #suppressionsFrom} returns a non-empty set.
*
* @param sym symbol
* @return lint instance with new warning suppressions applied, or this instance if none
*/
public Lint augment(Symbol sym) {
EnumSet<LintCategory> suppressions = suppressionsFrom(sym);
if (!suppressions.isEmpty()) {
Lint lint = new Lint(this);
lint.values.removeAll(suppressions);
lint.suppressedValues.addAll(suppressions);
return lint;
}
return this;
}
/**
* Returns a new Lint that has the given LintCategorys enabled.
* @param lc one or more categories to be enabled
*/
public Lint enable(LintCategory... lc) {
Lint l = new Lint(this);
l.values.addAll(Arrays.asList(lc));
l.suppressedValues.removeAll(Arrays.asList(lc));
return l;
}
/**
* Returns a new Lint that has the given LintCategorys suppressed.
* @param lc one or more categories to be suppressed
*/
public Lint suppress(LintCategory... lc) {
Lint l = new Lint(this);
l.values.removeAll(Arrays.asList(lc));
l.suppressedValues.addAll(Arrays.asList(lc));
return l;
}
private final Context context;
private final Options options;
private final Log log;
// These are initialized lazily to avoid dependency loops
private Symtab syms;
private Names names;
// Invariant: it's never the case that a category is in both "values" and "suppressedValues"
private EnumSet<LintCategory> values;
private EnumSet<LintCategory> suppressedValues;
@SuppressWarnings("this-escape")
protected Lint(Context context) {
this.context = context;
context.put(lintKey, this);
options = Options.instance(context);
log = Log.instance(context);
}
// Instantiate a non-root ("symbol scoped") instance
protected Lint(Lint other) {
other.initializeRootIfNeeded();
this.context = other.context;
this.options = other.options;
this.log = other.log;
this.syms = other.syms;
this.names = other.names;
this.values = other.values.clone();
this.suppressedValues = other.suppressedValues.clone();
}
// Process command line options on demand to allow use of root Lint early during startup
private void initializeRootIfNeeded() {
if (values == null) {
values = options.getLintCategoriesOf(Option.XLINT, this::getDefaults);
suppressedValues = LintCategory.newEmptySet();
}
}
// Obtain the set of on-by-default categories. Note that for a few categories,
// whether the category is on-by-default depends on other compiler options.
private EnumSet<LintCategory> getDefaults() {
EnumSet<LintCategory> defaults = LintCategory.newEmptySet();
Source source = Source.instance(context);
Stream.of(LintCategory.values())
.filter(lc ->
switch (lc) {
case DEP_ANN -> source.compareTo(Source.JDK9) >= 0;
case STRICTFP -> Source.Feature.REDUNDANT_STRICTFP.allowedInSource(source);
case PREVIEW -> !options.isSet(Option.PREVIEW);
default -> lc.enabledByDefault;
})
.forEach(defaults::add);
return defaults;
}
@Override
public String toString() {
initializeRootIfNeeded();
return "Lint:[enable" + values + ",suppress" + suppressedValues + "]";
}
/**
* Categories of warnings that can be generated by the compiler.
* Each lint category has a logical name (a string), which is the string used e.g. in a {@code SuppressWarning} annotation.
* To ensure automation, the enum field name for a lint category string {@code C} should be obtained by:
* <ol>
* <li>capitalize all the letters in {@code C}, and</li>
* <li>replacing any occurrence of {@code -} with {@code _}</li>
* </ol>
* For instance, the lint category string {@code dangling-doc-comments} corresponds to the enum field
* {@code DANGLING_DOC_COMMENTS}.
*/
public enum LintCategory {
/**
* Warn when code refers to a auxiliary class that is hidden in a source file (ie source file name is
* different from the class name, and the type is not properly nested) and the referring code
* is not located in the same source file.
*/
AUXILIARYCLASS("auxiliaryclass"),
/**
* Warn about use of unnecessary casts.
*/
CAST("cast"),
/**
* Warn about issues related to classfile contents.
*
* <p>
* This category is not supported by {@code @SuppressWarnings}.
*/
CLASSFILE("classfile", Property.NO_ANNOTATION_SUPPRESSION),
/**
* Warn about "dangling" documentation comments,
* not attached to any declaration.
*/
DANGLING_DOC_COMMENTS("dangling-doc-comments"),
/**
* Warn about use of deprecated items.
*/
DEPRECATION("deprecation"),
/**
* Warn about items which are documented with an {@code @deprecated} JavaDoc
* comment, but which do not have {@code @Deprecated} annotation.
*/
DEP_ANN("dep-ann", Property.ENABLED_BY_DEFAULT),
/**
* Warn about division by constant integer 0.
*/
DIVZERO("divzero"),
/**
* Warn about empty statement after if.
*/
EMPTY("empty"),
/**
* Warn about issues regarding module exports.
*/
EXPORTS("exports"),
/**
* Warn about falling through from one case of a switch statement to the next.
*/
FALLTHROUGH("fallthrough"),
/**
* Warn about finally clauses that do not terminate normally.
*/
FINALLY("finally"),
/**
* Warn about uses of @ValueBased classes where an identity class is expected.
*/
IDENTITY(List.of("identity", "synchronization"), Property.ENABLED_BY_DEFAULT),
/**
* Warn about use of incubating modules.
*
* <p>
* This category is not supported by {@code @SuppressWarnings}.
*/
INCUBATING("incubating", Property.NO_ANNOTATION_SUPPRESSION, Property.ENABLED_BY_DEFAULT),
/**
* Warn about compiler possible lossy conversions.
*/
LOSSY_CONVERSIONS("lossy-conversions"),
/**
* Warn about compiler generation of a default constructor.
*/
MISSING_EXPLICIT_CTOR("missing-explicit-ctor"),
/**
* Warn about module system related issues.
*/
MODULE("module", Property.ENABLED_BY_DEFAULT),
/**
* Warn about issues regarding module opens.
*/
OPENS("opens", Property.ENABLED_BY_DEFAULT),
/**
* Warn about issues relating to use of command line options.
*
* <p>
* This category is not supported by {@code @SuppressWarnings}.
*/
OPTIONS("options", Property.NO_ANNOTATION_SUPPRESSION),
/**
* Warn when any output file is written to more than once.
*
* <p>
* This category is not supported by {@code @SuppressWarnings}.
*/
OUTPUT_FILE_CLASH("output-file-clash", Property.NO_ANNOTATION_SUPPRESSION),
/**
* Warn about issues regarding method overloads.
*/
OVERLOADS("overloads"),
/**
* Warn about issues regarding method overrides.
*/
OVERRIDES("overrides"),
/**
* Warn about invalid path elements on the command line.
*
* <p>
* This category is not supported by {@code @SuppressWarnings}.
*/
PATH("path", Property.NO_ANNOTATION_SUPPRESSION),
/**
* Warn about issues regarding annotation processing.
*
* <p>
* This category is not supported by {@code @SuppressWarnings}.
*/
PROCESSING("processing", Property.NO_ANNOTATION_SUPPRESSION),
/**
* Warn about unchecked operations on raw types.
*/
RAWTYPES("rawtypes"),
/**
* Warn about use of deprecated-for-removal items.
*/
REMOVAL("removal", Property.ENABLED_BY_DEFAULT),
/**
* Warn about use of automatic modules in the requires clauses.
*/
REQUIRES_AUTOMATIC("requires-automatic"),
/**
* Warn about automatic modules in requires transitive.
*/
REQUIRES_TRANSITIVE_AUTOMATIC("requires-transitive-automatic", Property.ENABLED_BY_DEFAULT),
/**
* Warn about Serializable classes that do not provide a serial version ID.
*/
SERIAL("serial"),
/**
* Warn about issues relating to use of statics
*/
STATIC("static"),
/**
* Warn about unnecessary uses of the strictfp modifier
*/
STRICTFP("strictfp", Property.ENABLED_BY_DEFAULT),
/**
* Warn about issues relating to use of text blocks
*/
TEXT_BLOCKS("text-blocks"),
/**
* Warn about possible 'this' escapes before subclass instance is fully initialized.
*/
THIS_ESCAPE("this-escape"),
/**
* Warn about issues relating to use of try blocks (i.e. try-with-resources)
*/
TRY("try"),
/**
* Warn about unchecked operations on raw types.
*/
UNCHECKED("unchecked"),
/**
* Warn about potentially unsafe vararg methods
*/
VARARGS("varargs"),
/**
* Warn about use of preview features.
*/
PREVIEW("preview", Property.ENABLED_BY_DEFAULT),
/**
* Warn about use of restricted methods.
*/
RESTRICTED("restricted");
enum Property { NO_ANNOTATION_SUPPRESSION, ENABLED_BY_DEFAULT }
LintCategory(String option, Property... properties) {
this(List.of(option), properties);
}
LintCategory(List<String> options, Property... properties) {
this.option = options.getFirst();
this.optionList = options;
Set<Property> propertySet = properties.length == 0 ? Set.of() : EnumSet.copyOf(Arrays.asList(properties));
this.annotationSuppression = !propertySet.contains(Property.NO_ANNOTATION_SUPPRESSION);
this.enabledByDefault = propertySet.contains(Property.ENABLED_BY_DEFAULT);
}
private static final SequencedMap<String, LintCategory> lookup = createLookup();
private static SequencedMap<String, LintCategory> createLookup() {
var map = new LinkedHashMap<String, LintCategory>();
for (var category : values()) {
category.optionList.forEach(id -> map.put(id, category));
}
return Collections.unmodifiableSequencedMap(map);
}
/**
* Get the {@link LintCategory} having the given command line option.
*
* @param option lint category option string
* @return corresponding {@link LintCategory}, or empty if none exists
*/
public static Optional<LintCategory> get(String option) {
return Optional.ofNullable(lookup.get(option));
}
/**
* Get all lint category option strings and aliases.
*/
public static SequencedSet<String> options() {
return lookup.sequencedKeySet();
}
public static EnumSet<LintCategory> newEmptySet() {
return EnumSet.noneOf(LintCategory.class);
}
/** Get the "canonical" string representing this category in @SuppressAnnotations and -Xlint options. */
public final String option;
/** Get a list containing "option" followed by zero or more aliases. */
public final List<String> optionList;
/** Does this category support being suppressed by the {@code @SuppressWarnings} annotation? */
public final boolean annotationSuppression;
/**
* Is this category included in the default set of enabled lint categories?
* Note that for some categories, command line options can alter this at runtime.
*/
public final boolean enabledByDefault;
}
/**
* Checks if a warning category is enabled. A warning category may be enabled
* on the command line, or by default, and can be temporarily disabled with
* the SuppressWarnings annotation.
*/
public boolean isEnabled(LintCategory lc) {
initializeRootIfNeeded();
return values.contains(lc);
}
/**
* Checks is a warning category has been specifically suppressed, by means
* of the SuppressWarnings annotation, or, in the case of the deprecated
* category, whether it has been implicitly suppressed by virtue of the
* current entity being itself deprecated.
*/
public boolean isSuppressed(LintCategory lc) {
initializeRootIfNeeded();
return suppressedValues.contains(lc);
}
/**
* Obtain the set of recognized lint warning categories suppressed at the given symbol's declaration.
*
* <p>
* This set can be non-empty only if the symbol is annotated with either
* @SuppressWarnings or @Deprecated.
*
* @param symbol symbol corresponding to a possibly-annotated declaration
* @return new warning suppressions applied to sym
*/
public EnumSet<LintCategory> suppressionsFrom(Symbol symbol) {
EnumSet<LintCategory> suppressions = suppressionsFrom(symbol.getDeclarationAttributes().stream());
if (symbol.isDeprecated() && symbol.isDeprecatableViaAnnotation())
suppressions.add(LintCategory.DEPRECATION);
return suppressions;
}
// Find the @SuppressWarnings annotation in the given stream and extract the recognized suppressions
private EnumSet<LintCategory> suppressionsFrom(Stream<Attribute.Compound> attributes) {
initializeSymbolsIfNeeded();
EnumSet<LintCategory> result = LintCategory.newEmptySet();
attributes
.filter(attribute -> attribute.type.tsym == syms.suppressWarningsType.tsym)
.map(this::suppressionsFrom)
.forEach(result::addAll);
return result;
}
// Given a @SuppressWarnings annotation, extract the recognized suppressions
private EnumSet<LintCategory> suppressionsFrom(Attribute.Compound suppressWarnings) {
EnumSet<LintCategory> result = LintCategory.newEmptySet();
if (suppressWarnings.member(names.value) instanceof Attribute.Array values) {
for (Attribute value : values.values) {
Optional.of(value)
.filter(val -> val instanceof Attribute.Constant)
.map(val -> (String) ((Attribute.Constant) val).value)
.flatMap(LintCategory::get)
.filter(lc -> lc.annotationSuppression)
.ifPresent(result::add);
}
}
return result;
}
private void initializeSymbolsIfNeeded() {
if (syms == null) {
syms = Symtab.instance(context);
names = Names.instance(context);
}
}
}