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