1 /*
  2  * Copyright (c) 2005, 2022, 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 
 26 package com.sun.tools.javac.code;
 27 
 28 import java.util.Arrays;
 29 import java.util.EnumSet;
 30 import java.util.Map;
 31 import java.util.concurrent.ConcurrentHashMap;
 32 
 33 import com.sun.tools.javac.code.Symbol.*;
 34 import com.sun.tools.javac.main.Option;
 35 import com.sun.tools.javac.util.Context;
 36 import com.sun.tools.javac.util.List;
 37 import com.sun.tools.javac.util.Options;
 38 import com.sun.tools.javac.util.Pair;
 39 
 40 /**
 41  * A class for handling -Xlint suboptions and @SuppressWarnings.
 42  *
 43  *  <p><b>This is NOT part of any supported API.
 44  *  If you write code that depends on this, you do so at your own risk.
 45  *  This code and its internal interfaces are subject to change or
 46  *  deletion without notice.</b>
 47  */
 48 public class Lint
 49 {
 50     /** The context key for the root Lint object. */
 51     protected static final Context.Key<Lint> lintKey = new Context.Key<>();
 52 
 53     /** Get the root Lint instance. */
 54     public static Lint instance(Context context) {
 55         Lint instance = context.get(lintKey);
 56         if (instance == null)
 57             instance = new Lint(context);
 58         return instance;
 59     }
 60 
 61     /**
 62      * Returns the result of combining the values in this object with
 63      * the given annotation.
 64      */
 65     public Lint augment(Attribute.Compound attr) {
 66         return augmentor.augment(this, attr);
 67     }
 68 
 69 
 70     /**
 71      * Returns the result of combining the values in this object with
 72      * the metadata on the given symbol.
 73      */
 74     public Lint augment(Symbol sym) {
 75         Lint l = augmentor.augment(this, sym.getDeclarationAttributes());
 76         if (sym.isDeprecated() && sym.isDeprecatableViaAnnotation()) {
 77             if (l == this)
 78                 l = new Lint(this);
 79             l.values.remove(LintCategory.DEPRECATION);
 80             l.suppressedValues.add(LintCategory.DEPRECATION);
 81         }
 82         return l;
 83     }
 84 
 85     /**
 86      * Returns a new Lint that has the given LintCategorys suppressed.
 87      * @param lc one or more categories to be suppressed
 88      */
 89     public Lint suppress(LintCategory... lc) {
 90         Lint l = new Lint(this);
 91         l.values.removeAll(Arrays.asList(lc));
 92         l.suppressedValues.addAll(Arrays.asList(lc));
 93         return l;
 94     }
 95 
 96     private final AugmentVisitor augmentor;
 97 
 98     private final EnumSet<LintCategory> values;
 99     private final EnumSet<LintCategory> suppressedValues;
100 
101     private static final Map<String, LintCategory> map = new ConcurrentHashMap<>(20);
102 
103     protected Lint(Context context) {
104         // initialize values according to the lint options
105         Options options = Options.instance(context);
106 
107         if (options.isSet(Option.XLINT) || options.isSet(Option.XLINT_CUSTOM, "all")) {
108             // If -Xlint or -Xlint:all is given, enable all categories by default
109             values = EnumSet.allOf(LintCategory.class);
110         } else if (options.isSet(Option.XLINT_CUSTOM, "none")) {
111             // if -Xlint:none is given, disable all categories by default
112             values = EnumSet.noneOf(LintCategory.class);
113         } else {
114             // otherwise, enable on-by-default categories
115             values = EnumSet.noneOf(LintCategory.class);
116 
117             Source source = Source.instance(context);
118             if (source.compareTo(Source.JDK9) >= 0) {
119                 values.add(LintCategory.DEP_ANN);
120             }
121             if (Source.Feature.REDUNDANT_STRICTFP.allowedInSource(source)) {
122                 values.add(LintCategory.STRICTFP);
123             }
124             values.add(LintCategory.REQUIRES_TRANSITIVE_AUTOMATIC);
125             values.add(LintCategory.OPENS);
126             values.add(LintCategory.MODULE);
127             values.add(LintCategory.REMOVAL);
128             if (!options.isSet(Option.PREVIEW)) {
129                 values.add(LintCategory.PREVIEW);
130             }
131             values.add(LintCategory.SYNCHRONIZATION);
132         }
133 
134         // Look for specific overrides
135         for (LintCategory lc : LintCategory.values()) {
136             if (options.isSet(Option.XLINT_CUSTOM, lc.option)) {
137                 values.add(lc);
138             } else if (options.isSet(Option.XLINT_CUSTOM, "-" + lc.option)) {
139                 values.remove(lc);
140             }
141         }
142 
143         suppressedValues = EnumSet.noneOf(LintCategory.class);
144 
145         context.put(lintKey, this);
146         augmentor = new AugmentVisitor(context);
147     }
148 
149     protected Lint(Lint other) {
150         this.augmentor = other.augmentor;
151         this.values = other.values.clone();
152         this.suppressedValues = other.suppressedValues.clone();
153     }
154 
155     @Override
156     public String toString() {
157         return "Lint:[values" + values + " suppressedValues" + suppressedValues + "]";
158     }
159 
160     /**
161      * Categories of warnings that can be generated by the compiler.
162      */
163     public enum LintCategory {
164         /**
165          * Warn when code refers to a auxiliary class that is hidden in a source file (ie source file name is
166          * different from the class name, and the type is not properly nested) and the referring code
167          * is not located in the same source file.
168          */
169         AUXILIARYCLASS("auxiliaryclass"),
170 
171         /**
172          * Warn about use of unnecessary casts.
173          */
174         CAST("cast"),
175 
176         /**
177          * Warn about issues related to classfile contents
178          */
179         CLASSFILE("classfile"),
180 
181         /**
182          * Warn about use of deprecated items.
183          */
184         DEPRECATION("deprecation"),
185 
186         /**
187          * Warn about items which are documented with an {@code @deprecated} JavaDoc
188          * comment, but which do not have {@code @Deprecated} annotation.
189          */
190         DEP_ANN("dep-ann"),
191 
192         /**
193          * Warn about division by constant integer 0.
194          */
195         DIVZERO("divzero"),
196 
197         /**
198          * Warn about empty statement after if.
199          */
200         EMPTY("empty"),
201 
202         /**
203          * Warn about issues regarding module exports.
204          */
205         EXPORTS("exports"),
206 
207         /**
208          * Warn about falling through from one case of a switch statement to the next.
209          */
210         FALLTHROUGH("fallthrough"),
211 
212         /**
213          * Warn about finally clauses that do not terminate normally.
214          */
215         FINALLY("finally"),
216 
217         /**
218           * Warn about compiler possible lossy conversions.
219           */
220         LOSSY_CONVERSIONS("lossy-conversions"),
221 
222         /**
223           * Warn about compiler generation of a default constructor.
224           */
225         MISSING_EXPLICIT_CTOR("missing-explicit-ctor"),
226 
227         /**
228          * Warn about module system related issues.
229          */
230         MODULE("module"),
231 
232         /**
233          * Warn about issues regarding module opens.
234          */
235         OPENS("opens"),
236 
237         /**
238          * Warn about issues relating to use of command line options
239          */
240         OPTIONS("options"),
241 
242         /**
243          * Warn about issues regarding method overloads.
244          */
245         OVERLOADS("overloads"),
246 
247         /**
248          * Warn about issues regarding method overrides.
249          */
250         OVERRIDES("overrides"),
251 
252         /**
253          * Warn about invalid path elements on the command line.
254          * Such warnings cannot be suppressed with the SuppressWarnings
255          * annotation.
256          */
257         PATH("path"),
258 
259         /**
260          * Warn about issues regarding annotation processing.
261          */
262         PROCESSING("processing"),
263 
264         /**
265          * Warn about unchecked operations on raw types.
266          */
267         RAW("rawtypes"),
268 
269         /**
270          * Warn about use of deprecated-for-removal items.
271          */
272         REMOVAL("removal"),
273 
274         /**
275          * Warn about use of automatic modules in the requires clauses.
276          */
277         REQUIRES_AUTOMATIC("requires-automatic"),
278 
279         /**
280          * Warn about automatic modules in requires transitive.
281          */
282         REQUIRES_TRANSITIVE_AUTOMATIC("requires-transitive-automatic"),
283 
284         /**
285          * Warn about Serializable classes that do not provide a serial version ID.
286          */
287         SERIAL("serial"),
288 
289         /**
290          * Warn about issues relating to use of statics
291          */
292         STATIC("static"),
293 
294         /**
295          * Warn about unnecessary uses of the strictfp modifier
296          */
297         STRICTFP("strictfp"),
298 
299         /**
300          * Warn about synchronization attempts on instances of @ValueBased classes.
301          */
302         SYNCHRONIZATION("synchronization"),
303 
304         /**
305          * Warn about issues relating to use of text blocks
306          */
307         TEXT_BLOCKS("text-blocks"),
308 
309         /**
310          * Warn about issues relating to use of try blocks (i.e. try-with-resources)
311          */
312         TRY("try"),
313 
314         /**
315          * Warn about unchecked operations on raw types.
316          */
317         UNCHECKED("unchecked"),
318 
319         /**
320          * Warn about potentially unsafe vararg methods
321          */
322         VARARGS("varargs"),
323 
324         /**
325          * Warn about use of preview features.
326          */
327         PREVIEW("preview");
328 
329         LintCategory(String option) {
330             this(option, false);
331         }
332 
333         LintCategory(String option, boolean hidden) {
334             this.option = option;
335             this.hidden = hidden;
336             map.put(option, this);
337         }
338 
339         static LintCategory get(String option) {
340             return map.get(option);
341         }
342 
343         public final String option;
344         public final boolean hidden;
345     }
346 
347     /**
348      * Checks if a warning category is enabled. A warning category may be enabled
349      * on the command line, or by default, and can be temporarily disabled with
350      * the SuppressWarnings annotation.
351      */
352     public boolean isEnabled(LintCategory lc) {
353         return values.contains(lc);
354     }
355 
356     /**
357      * Checks is a warning category has been specifically suppressed, by means
358      * of the SuppressWarnings annotation, or, in the case of the deprecated
359      * category, whether it has been implicitly suppressed by virtue of the
360      * current entity being itself deprecated.
361      */
362     public boolean isSuppressed(LintCategory lc) {
363         return suppressedValues.contains(lc);
364     }
365 
366     protected static class AugmentVisitor implements Attribute.Visitor {
367         private final Context context;
368         private Symtab syms;
369         private Lint parent;
370         private Lint lint;
371 
372         AugmentVisitor(Context context) {
373             // to break an ugly sequence of initialization dependencies,
374             // we defer the initialization of syms until it is needed
375             this.context = context;
376         }
377 
378         Lint augment(Lint parent, Attribute.Compound attr) {
379             initSyms();
380             this.parent = parent;
381             lint = null;
382             attr.accept(this);
383             return (lint == null ? parent : lint);
384         }
385 
386         Lint augment(Lint parent, List<Attribute.Compound> attrs) {
387             initSyms();
388             this.parent = parent;
389             lint = null;
390             for (Attribute.Compound a: attrs) {
391                 a.accept(this);
392             }
393             return (lint == null ? parent : lint);
394         }
395 
396         private void initSyms() {
397             if (syms == null)
398                 syms = Symtab.instance(context);
399         }
400 
401         private void suppress(LintCategory lc) {
402             if (lint == null)
403                 lint = new Lint(parent);
404             lint.suppressedValues.add(lc);
405             lint.values.remove(lc);
406         }
407 
408         public void visitConstant(Attribute.Constant value) {
409             if (value.type.tsym == syms.stringType.tsym) {
410                 LintCategory lc = LintCategory.get((String) (value.value));
411                 if (lc != null)
412                     suppress(lc);
413             }
414         }
415 
416         public void visitClass(Attribute.Class clazz) {
417         }
418 
419         // If we find a @SuppressWarnings annotation, then we continue
420         // walking the tree, in order to suppress the individual warnings
421         // specified in the @SuppressWarnings annotation.
422         public void visitCompound(Attribute.Compound compound) {
423             if (compound.type.tsym == syms.suppressWarningsType.tsym) {
424                 for (List<Pair<MethodSymbol,Attribute>> v = compound.values;
425                      v.nonEmpty(); v = v.tail) {
426                     Pair<MethodSymbol,Attribute> value = v.head;
427                     if (value.fst.name.toString().equals("value"))
428                         value.snd.accept(this);
429                 }
430 
431             }
432         }
433 
434         public void visitArray(Attribute.Array array) {
435             for (Attribute value : array.values)
436                 value.accept(this);
437         }
438 
439         public void visitEnum(Attribute.Enum e) {
440         }
441 
442         public void visitError(Attribute.Error e) {
443         }
444     }
445 }