1 /*
  2  * Copyright (c) 2005, 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.  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     @SuppressWarnings("this-escape")
104     protected Lint(Context context) {
105         // initialize values according to the lint options
106         Options options = Options.instance(context);
107 
108         if (options.isSet(Option.XLINT) || options.isSet(Option.XLINT_CUSTOM, "all")) {
109             // If -Xlint or -Xlint:all is given, enable all categories by default
110             values = EnumSet.allOf(LintCategory.class);
111         } else if (options.isSet(Option.XLINT_CUSTOM, "none")) {
112             // if -Xlint:none is given, disable all categories by default
113             values = EnumSet.noneOf(LintCategory.class);
114         } else {
115             // otherwise, enable on-by-default categories
116             values = EnumSet.noneOf(LintCategory.class);
117 
118             Source source = Source.instance(context);
119             if (source.compareTo(Source.JDK9) >= 0) {
120                 values.add(LintCategory.DEP_ANN);
121             }
122             if (Source.Feature.REDUNDANT_STRICTFP.allowedInSource(source)) {
123                 values.add(LintCategory.STRICTFP);
124             }
125             values.add(LintCategory.REQUIRES_TRANSITIVE_AUTOMATIC);
126             values.add(LintCategory.OPENS);
127             values.add(LintCategory.MODULE);
128             values.add(LintCategory.REMOVAL);
129             if (!options.isSet(Option.PREVIEW)) {
130                 values.add(LintCategory.PREVIEW);
131             }
132             values.add(LintCategory.SYNCHRONIZATION);
133             values.add(LintCategory.INCUBATING);
134         }
135 
136         // Look for specific overrides
137         for (LintCategory lc : LintCategory.values()) {
138             if (options.isSet(Option.XLINT_CUSTOM, lc.option)) {
139                 values.add(lc);
140             } else if (options.isSet(Option.XLINT_CUSTOM, "-" + lc.option)) {
141                 values.remove(lc);
142             }
143         }
144 
145         suppressedValues = EnumSet.noneOf(LintCategory.class);
146 
147         context.put(lintKey, this);
148         augmentor = new AugmentVisitor(context);
149     }
150 
151     protected Lint(Lint other) {
152         this.augmentor = other.augmentor;
153         this.values = other.values.clone();
154         this.suppressedValues = other.suppressedValues.clone();
155     }
156 
157     @Override
158     public String toString() {
159         return "Lint:[values" + values + " suppressedValues" + suppressedValues + "]";
160     }
161 
162     /**
163      * Categories of warnings that can be generated by the compiler.
164      */
165     public enum LintCategory {
166         /**
167          * Warn when code refers to a auxiliary class that is hidden in a source file (ie source file name is
168          * different from the class name, and the type is not properly nested) and the referring code
169          * is not located in the same source file.
170          */
171         AUXILIARYCLASS("auxiliaryclass"),
172 
173         /**
174          * Warn about use of unnecessary casts.
175          */
176         CAST("cast"),
177 
178         /**
179          * Warn about issues related to classfile contents
180          */
181         CLASSFILE("classfile"),
182 
183         /**
184          * Warn about"dangling" documentation comments,
185          * not attached to any declaration.
186          */
187         DANGLING_DOC_COMMENTS("dangling-doc-comments"),
188 
189         /**
190          * Warn about use of deprecated items.
191          */
192         DEPRECATION("deprecation"),
193 
194         /**
195          * Warn about items which are documented with an {@code @deprecated} JavaDoc
196          * comment, but which do not have {@code @Deprecated} annotation.
197          */
198         DEP_ANN("dep-ann"),
199 
200         /**
201          * Warn about division by constant integer 0.
202          */
203         DIVZERO("divzero"),
204 
205         /**
206          * Warn about empty statement after if.
207          */
208         EMPTY("empty"),
209 
210         /**
211          * Warn about issues regarding module exports.
212          */
213         EXPORTS("exports"),
214 
215         /**
216          * Warn about falling through from one case of a switch statement to the next.
217          */
218         FALLTHROUGH("fallthrough"),
219 
220         /**
221          * Warn about finally clauses that do not terminate normally.
222          */
223         FINALLY("finally"),
224 
225         /**
226          * Warn about use of incubating modules.
227          */
228         INCUBATING("incubating"),
229 
230         /**
231           * Warn about compiler possible lossy conversions.
232           */
233         LOSSY_CONVERSIONS("lossy-conversions"),
234 
235         /**
236           * Warn about compiler generation of a default constructor.
237           */
238         MISSING_EXPLICIT_CTOR("missing-explicit-ctor"),
239 
240         /**
241          * Warn about module system related issues.
242          */
243         MODULE("module"),
244 
245         /**
246          * Warn about issues related to migration of JDK classes.
247          */
248         MIGRATION("migration"),
249 
250         /**
251          * Warn about issues regarding module opens.
252          */
253         OPENS("opens"),
254 
255         /**
256          * Warn about issues relating to use of command line options
257          */
258         OPTIONS("options"),
259 
260         /**
261          * Warn when any output file is written to more than once.
262          */
263         OUTPUT_FILE_CLASH("output-file-clash"),
264 
265         /**
266          * Warn about issues regarding method overloads.
267          */
268         OVERLOADS("overloads"),
269 
270         /**
271          * Warn about issues regarding method overrides.
272          */
273         OVERRIDES("overrides"),
274 
275         /**
276          * Warn about invalid path elements on the command line.
277          * Such warnings cannot be suppressed with the SuppressWarnings
278          * annotation.
279          */
280         PATH("path"),
281 
282         /**
283          * Warn about issues regarding annotation processing.
284          */
285         PROCESSING("processing"),
286 
287         /**
288          * Warn about unchecked operations on raw types.
289          */
290         RAW("rawtypes"),
291 
292         /**
293          * Warn about use of deprecated-for-removal items.
294          */
295         REMOVAL("removal"),
296 
297         /**
298          * Warn about use of automatic modules in the requires clauses.
299          */
300         REQUIRES_AUTOMATIC("requires-automatic"),
301 
302         /**
303          * Warn about automatic modules in requires transitive.
304          */
305         REQUIRES_TRANSITIVE_AUTOMATIC("requires-transitive-automatic"),
306 
307         /**
308          * Warn about Serializable classes that do not provide a serial version ID.
309          */
310         SERIAL("serial"),
311 
312         /**
313          * Warn about issues relating to use of statics
314          */
315         STATIC("static"),
316 
317         /**
318          * Warn about unnecessary uses of the strictfp modifier
319          */
320         STRICTFP("strictfp"),
321 
322         /**
323          * Warn about synchronization attempts on instances of @ValueBased classes.
324          */
325         SYNCHRONIZATION("synchronization"),
326 
327         /**
328          * Warn about issues relating to use of text blocks
329          */
330         TEXT_BLOCKS("text-blocks"),
331 
332         /**
333          * Warn about possible 'this' escapes before subclass instance is fully initialized.
334          */
335         THIS_ESCAPE("this-escape"),
336 
337         /**
338          * Warn about issues relating to use of try blocks (i.e. try-with-resources)
339          */
340         TRY("try"),
341 
342         /**
343          * Warn about unchecked operations on raw types.
344          */
345         UNCHECKED("unchecked"),
346 
347         /**
348          * Warn about potentially unsafe vararg methods
349          */
350         VARARGS("varargs"),
351 
352         /**
353          * Warn about use of preview features.
354          */
355         PREVIEW("preview"),
356 
357         /**
358          * Warn about use of restricted methods.
359          */
360         RESTRICTED("restricted");
361 
362         LintCategory(String option) {
363             this.option = option;
364             map.put(option, this);
365         }
366 
367         static LintCategory get(String option) {
368             return map.get(option);
369         }
370 
371         public final String option;
372     }
373 
374     /**
375      * Checks if a warning category is enabled. A warning category may be enabled
376      * on the command line, or by default, and can be temporarily disabled with
377      * the SuppressWarnings annotation.
378      */
379     public boolean isEnabled(LintCategory lc) {
380         return values.contains(lc);
381     }
382 
383     /**
384      * Checks is a warning category has been specifically suppressed, by means
385      * of the SuppressWarnings annotation, or, in the case of the deprecated
386      * category, whether it has been implicitly suppressed by virtue of the
387      * current entity being itself deprecated.
388      */
389     public boolean isSuppressed(LintCategory lc) {
390         return suppressedValues.contains(lc);
391     }
392 
393     protected static class AugmentVisitor implements Attribute.Visitor {
394         private final Context context;
395         private Symtab syms;
396         private Lint parent;
397         private Lint lint;
398 
399         AugmentVisitor(Context context) {
400             // to break an ugly sequence of initialization dependencies,
401             // we defer the initialization of syms until it is needed
402             this.context = context;
403         }
404 
405         Lint augment(Lint parent, Attribute.Compound attr) {
406             initSyms();
407             this.parent = parent;
408             lint = null;
409             attr.accept(this);
410             return (lint == null ? parent : lint);
411         }
412 
413         Lint augment(Lint parent, List<Attribute.Compound> attrs) {
414             initSyms();
415             this.parent = parent;
416             lint = null;
417             for (Attribute.Compound a: attrs) {
418                 a.accept(this);
419             }
420             return (lint == null ? parent : lint);
421         }
422 
423         private void initSyms() {
424             if (syms == null)
425                 syms = Symtab.instance(context);
426         }
427 
428         private void suppress(LintCategory lc) {
429             if (lint == null)
430                 lint = new Lint(parent);
431             lint.suppressedValues.add(lc);
432             lint.values.remove(lc);
433         }
434 
435         public void visitConstant(Attribute.Constant value) {
436             if (value.type.tsym == syms.stringType.tsym) {
437                 LintCategory lc = LintCategory.get((String) (value.value));
438                 if (lc != null)
439                     suppress(lc);
440             }
441         }
442 
443         public void visitClass(Attribute.Class clazz) {
444         }
445 
446         // If we find a @SuppressWarnings annotation, then we continue
447         // walking the tree, in order to suppress the individual warnings
448         // specified in the @SuppressWarnings annotation.
449         public void visitCompound(Attribute.Compound compound) {
450             if (compound.type.tsym == syms.suppressWarningsType.tsym) {
451                 for (List<Pair<MethodSymbol,Attribute>> v = compound.values;
452                      v.nonEmpty(); v = v.tail) {
453                     Pair<MethodSymbol,Attribute> value = v.head;
454                     if (value.fst.name.toString().equals("value"))
455                         value.snd.accept(this);
456                 }
457 
458             }
459         }
460 
461         public void visitArray(Attribute.Array array) {
462             for (Attribute value : array.values)
463                 value.accept(this);
464         }
465 
466         public void visitEnum(Attribute.Enum e) {
467         }
468 
469         public void visitError(Attribute.Error e) {
470         }
471     }
472 }