1 /*
   2  * Copyright (c) 1999, 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.comp;
  27 
  28 import java.util.*;
  29 import java.util.function.BiConsumer;
  30 import java.util.function.Predicate;
  31 import java.util.function.Supplier;
  32 
  33 import javax.lang.model.element.ElementKind;
  34 import javax.lang.model.element.NestingKind;
  35 import javax.tools.JavaFileManager;
  36 
  37 import com.sun.source.tree.CaseTree;
  38 import com.sun.tools.javac.code.*;
  39 import com.sun.tools.javac.code.Attribute.Compound;
  40 import com.sun.tools.javac.code.Directive.ExportsDirective;
  41 import com.sun.tools.javac.code.Directive.RequiresDirective;
  42 import com.sun.tools.javac.code.Source.Feature;
  43 import com.sun.tools.javac.comp.Annotate.AnnotationTypeMetadata;
  44 import com.sun.tools.javac.jvm.*;
  45 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  46 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  47 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
  48 import com.sun.tools.javac.tree.*;
  49 import com.sun.tools.javac.util.*;
  50 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
  51 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  52 import com.sun.tools.javac.util.JCDiagnostic.Error;
  53 import com.sun.tools.javac.util.JCDiagnostic.Fragment;
  54 import com.sun.tools.javac.util.JCDiagnostic.Warning;
  55 import com.sun.tools.javac.util.List;
  56 
  57 import com.sun.tools.javac.code.Lint;
  58 import com.sun.tools.javac.code.Lint.LintCategory;
  59 import com.sun.tools.javac.code.Scope.WriteableScope;
  60 import com.sun.tools.javac.code.Type.*;
  61 import com.sun.tools.javac.code.Symbol.*;
  62 import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
  63 import com.sun.tools.javac.tree.JCTree.*;
  64 
  65 import static com.sun.tools.javac.code.Flags.*;
  66 import static com.sun.tools.javac.code.Flags.ANNOTATION;
  67 import static com.sun.tools.javac.code.Flags.SYNCHRONIZED;
  68 import static com.sun.tools.javac.code.Kinds.*;
  69 import static com.sun.tools.javac.code.Kinds.Kind.*;
  70 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
  71 import static com.sun.tools.javac.code.TypeTag.*;
  72 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
  73 
  74 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  75 import javax.lang.model.element.Element;
  76 import javax.lang.model.element.ExecutableElement;
  77 import javax.lang.model.element.TypeElement;
  78 import javax.lang.model.type.DeclaredType;
  79 import javax.lang.model.type.TypeMirror;
  80 import javax.lang.model.util.ElementFilter;
  81 import javax.lang.model.util.ElementKindVisitor14;
  82 
  83 /** Type checking helper class for the attribution phase.
  84  *
  85  *  <p><b>This is NOT part of any supported API.
  86  *  If you write code that depends on this, you do so at your own risk.
  87  *  This code and its internal interfaces are subject to change or
  88  *  deletion without notice.</b>
  89  */
  90 public class Check {
  91     protected static final Context.Key<Check> checkKey = new Context.Key<>();
  92 
  93     private final Names names;
  94     private final Log log;
  95     private final Resolve rs;
  96     private final Symtab syms;
  97     private final Enter enter;
  98     private final DeferredAttr deferredAttr;
  99     private final Infer infer;
 100     private final Types types;
 101     private final TypeAnnotations typeAnnotations;
 102     private final JCDiagnostic.Factory diags;
 103     private final JavaFileManager fileManager;
 104     private final Source source;
 105     private final Target target;
 106     private final Profile profile;
 107     private final Preview preview;
 108     private final boolean warnOnAnyAccessToMembers;
 109 
 110     // The set of lint options currently in effect. It is initialized
 111     // from the context, and then is set/reset as needed by Attr as it
 112     // visits all the various parts of the trees during attribution.
 113     private Lint lint;
 114 
 115     // The method being analyzed in Attr - it is set/reset as needed by
 116     // Attr as it visits new method declarations.
 117     private MethodSymbol method;
 118 
 119     public static Check instance(Context context) {
 120         Check instance = context.get(checkKey);
 121         if (instance == null)
 122             instance = new Check(context);
 123         return instance;
 124     }
 125 
 126     protected Check(Context context) {
 127         context.put(checkKey, this);
 128 
 129         names = Names.instance(context);
 130         log = Log.instance(context);
 131         rs = Resolve.instance(context);
 132         syms = Symtab.instance(context);
 133         enter = Enter.instance(context);
 134         deferredAttr = DeferredAttr.instance(context);
 135         infer = Infer.instance(context);
 136         types = Types.instance(context);
 137         typeAnnotations = TypeAnnotations.instance(context);
 138         diags = JCDiagnostic.Factory.instance(context);
 139         Options options = Options.instance(context);
 140         lint = Lint.instance(context);
 141         fileManager = context.get(JavaFileManager.class);
 142 
 143         source = Source.instance(context);
 144         target = Target.instance(context);
 145         warnOnAnyAccessToMembers = options.isSet("warnOnAccessToMembers");
 146 
 147         Target target = Target.instance(context);
 148         syntheticNameChar = target.syntheticNameChar();
 149 
 150         profile = Profile.instance(context);
 151         preview = Preview.instance(context);
 152 
 153         boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
 154         boolean verboseRemoval = lint.isEnabled(LintCategory.REMOVAL);
 155         boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
 156         boolean enforceMandatoryWarnings = true;
 157 
 158         deprecationHandler = new MandatoryWarningHandler(log, null, verboseDeprecated,
 159                 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
 160         removalHandler = new MandatoryWarningHandler(log, null, verboseRemoval,
 161                 enforceMandatoryWarnings, "removal", LintCategory.REMOVAL);
 162         uncheckedHandler = new MandatoryWarningHandler(log, null, verboseUnchecked,
 163                 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
 164         sunApiHandler = new MandatoryWarningHandler(log, null, false,
 165                 enforceMandatoryWarnings, "sunapi", null);
 166 
 167         deferredLintHandler = DeferredLintHandler.instance(context);
 168 
 169         allowModules = Feature.MODULES.allowedInSource(source);
 170         allowRecords = Feature.RECORDS.allowedInSource(source);
 171         allowSealed = Feature.SEALED_CLASSES.allowedInSource(source);
 172     }
 173 
 174     /** Character for synthetic names
 175      */
 176     char syntheticNameChar;
 177 
 178     /** A table mapping flat names of all compiled classes for each module in this run
 179      *  to their symbols; maintained from outside.
 180      */
 181     private Map<Pair<ModuleSymbol, Name>,ClassSymbol> compiled = new HashMap<>();
 182 
 183     /** A handler for messages about deprecated usage.
 184      */
 185     private MandatoryWarningHandler deprecationHandler;
 186 
 187     /** A handler for messages about deprecated-for-removal usage.
 188      */
 189     private MandatoryWarningHandler removalHandler;
 190 
 191     /** A handler for messages about unchecked or unsafe usage.
 192      */
 193     private MandatoryWarningHandler uncheckedHandler;
 194 
 195     /** A handler for messages about using proprietary API.
 196      */
 197     private MandatoryWarningHandler sunApiHandler;
 198 
 199     /** A handler for deferred lint warnings.
 200      */
 201     private DeferredLintHandler deferredLintHandler;
 202 
 203     /** Are modules allowed
 204      */
 205     private final boolean allowModules;
 206 
 207     /** Are records allowed
 208      */
 209     private final boolean allowRecords;
 210 
 211     /** Are sealed classes allowed
 212      */
 213     private final boolean allowSealed;
 214 
 215 /* *************************************************************************
 216  * Errors and Warnings
 217  **************************************************************************/
 218 
 219     Lint setLint(Lint newLint) {
 220         Lint prev = lint;
 221         lint = newLint;
 222         return prev;
 223     }
 224 
 225     MethodSymbol setMethod(MethodSymbol newMethod) {
 226         MethodSymbol prev = method;
 227         method = newMethod;
 228         return prev;
 229     }
 230 
 231     /** Warn about deprecated symbol.
 232      *  @param pos        Position to be used for error reporting.
 233      *  @param sym        The deprecated symbol.
 234      */
 235     void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
 236         if (sym.isDeprecatedForRemoval()) {
 237             if (!lint.isSuppressed(LintCategory.REMOVAL)) {
 238                 if (sym.kind == MDL) {
 239                     removalHandler.report(pos, Warnings.HasBeenDeprecatedForRemovalModule(sym));
 240                 } else {
 241                     removalHandler.report(pos, Warnings.HasBeenDeprecatedForRemoval(sym, sym.location()));
 242                 }
 243             }
 244         } else if (!lint.isSuppressed(LintCategory.DEPRECATION)) {
 245             if (sym.kind == MDL) {
 246                 deprecationHandler.report(pos, Warnings.HasBeenDeprecatedModule(sym));
 247             } else {
 248                 deprecationHandler.report(pos, Warnings.HasBeenDeprecated(sym, sym.location()));
 249             }
 250         }
 251     }
 252 
 253     /** Log a preview warning.
 254      *  @param pos        Position to be used for error reporting.
 255      *  @param msg        A Warning describing the problem.
 256      */
 257     public void warnPreviewAPI(DiagnosticPosition pos, Warning warnKey) {
 258         if (!lint.isSuppressed(LintCategory.PREVIEW))
 259             preview.reportPreviewWarning(pos, warnKey);
 260     }
 261 
 262     /** Log a preview warning.
 263      *  @param pos        Position to be used for error reporting.
 264      *  @param msg        A Warning describing the problem.
 265      */
 266     public void warnDeclaredUsingPreview(DiagnosticPosition pos, Symbol sym) {
 267         if (!lint.isSuppressed(LintCategory.PREVIEW))
 268             preview.reportPreviewWarning(pos, Warnings.DeclaredUsingPreview(kindName(sym), sym));
 269     }
 270 
 271     /** Warn about unchecked operation.
 272      *  @param pos        Position to be used for error reporting.
 273      *  @param msg        A string describing the problem.
 274      */
 275     public void warnUnchecked(DiagnosticPosition pos, Warning warnKey) {
 276         if (!lint.isSuppressed(LintCategory.UNCHECKED))
 277             uncheckedHandler.report(pos, warnKey);
 278     }
 279 
 280     /** Warn about unsafe vararg method decl.
 281      *  @param pos        Position to be used for error reporting.
 282      */
 283     void warnUnsafeVararg(DiagnosticPosition pos, Warning warnKey) {
 284         if (lint.isEnabled(LintCategory.VARARGS))
 285             log.warning(LintCategory.VARARGS, pos, warnKey);
 286     }
 287 
 288     public void warnStatic(DiagnosticPosition pos, Warning warnKey) {
 289         if (lint.isEnabled(LintCategory.STATIC))
 290             log.warning(LintCategory.STATIC, pos, warnKey);
 291     }
 292 
 293     /** Warn about division by integer constant zero.
 294      *  @param pos        Position to be used for error reporting.
 295      */
 296     void warnDivZero(DiagnosticPosition pos) {
 297         if (lint.isEnabled(LintCategory.DIVZERO))
 298             log.warning(LintCategory.DIVZERO, pos, Warnings.DivZero);
 299     }
 300 
 301     /**
 302      * Report any deferred diagnostics.
 303      */
 304     public void reportDeferredDiagnostics() {
 305         deprecationHandler.reportDeferredDiagnostic();
 306         removalHandler.reportDeferredDiagnostic();
 307         uncheckedHandler.reportDeferredDiagnostic();
 308         sunApiHandler.reportDeferredDiagnostic();
 309     }
 310 
 311 
 312     /** Report a failure to complete a class.
 313      *  @param pos        Position to be used for error reporting.
 314      *  @param ex         The failure to report.
 315      */
 316     public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
 317         log.error(JCDiagnostic.DiagnosticFlag.NON_DEFERRABLE, pos, Errors.CantAccess(ex.sym, ex.getDetailValue()));
 318         return syms.errType;
 319     }
 320 
 321     /** Report an error that wrong type tag was found.
 322      *  @param pos        Position to be used for error reporting.
 323      *  @param required   An internationalized string describing the type tag
 324      *                    required.
 325      *  @param found      The type that was found.
 326      */
 327     Type typeTagError(DiagnosticPosition pos, JCDiagnostic required, Object found) {
 328         // this error used to be raised by the parser,
 329         // but has been delayed to this point:
 330         if (found instanceof Type type && type.hasTag(VOID)) {
 331             log.error(pos, Errors.IllegalStartOfType);
 332             return syms.errType;
 333         }
 334         log.error(pos, Errors.TypeFoundReq(found, required));
 335         return types.createErrorType(found instanceof Type type ? type : syms.errType);
 336     }
 337 
 338     /** Report an error that symbol cannot be referenced before super
 339      *  has been called.
 340      *  @param pos        Position to be used for error reporting.
 341      *  @param sym        The referenced symbol.
 342      */
 343     void earlyRefError(DiagnosticPosition pos, Symbol sym) {
 344         log.error(pos, Errors.CantRefBeforeCtorCalled(sym));
 345     }
 346 
 347     /** Report duplicate declaration error.
 348      */
 349     void duplicateError(DiagnosticPosition pos, Symbol sym) {
 350         if (!sym.type.isErroneous()) {
 351             Symbol location = sym.location();
 352             if (location.kind == MTH &&
 353                     ((MethodSymbol)location).isStaticOrInstanceInit()) {
 354                 log.error(pos,
 355                           Errors.AlreadyDefinedInClinit(kindName(sym),
 356                                                         sym,
 357                                                         kindName(sym.location()),
 358                                                         kindName(sym.location().enclClass()),
 359                                                         sym.location().enclClass()));
 360             } else {
 361                 /* dont error if this is a duplicated parameter of a generated canonical constructor
 362                  * as we should have issued an error for the duplicated fields
 363                  */
 364                 if (location.kind != MTH ||
 365                         ((sym.owner.flags_field & GENERATEDCONSTR) == 0) ||
 366                         ((sym.owner.flags_field & RECORD) == 0)) {
 367                     log.error(pos,
 368                             Errors.AlreadyDefined(kindName(sym),
 369                                     sym,
 370                                     kindName(sym.location()),
 371                                     sym.location()));
 372                 }
 373             }
 374         }
 375     }
 376 
 377     /** Report array/varargs duplicate declaration
 378      */
 379     void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
 380         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
 381             log.error(pos, Errors.ArrayAndVarargs(sym1, sym2, sym2.location()));
 382         }
 383     }
 384 
 385 /* ************************************************************************
 386  * duplicate declaration checking
 387  *************************************************************************/
 388 
 389     /** Check that variable does not hide variable with same name in
 390      *  immediately enclosing local scope.
 391      *  @param pos           Position for error reporting.
 392      *  @param v             The symbol.
 393      *  @param s             The scope.
 394      */
 395     void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
 396         for (Symbol sym : s.getSymbolsByName(v.name)) {
 397             if (sym.owner != v.owner) break;
 398             if (sym.kind == VAR &&
 399                 sym.owner.kind.matches(KindSelector.VAL_MTH) &&
 400                 v.name != names.error) {
 401                 duplicateError(pos, sym);
 402                 return;
 403             }
 404         }
 405     }
 406 
 407     /** Check that a class or interface does not hide a class or
 408      *  interface with same name in immediately enclosing local scope.
 409      *  @param pos           Position for error reporting.
 410      *  @param c             The symbol.
 411      *  @param s             The scope.
 412      */
 413     void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
 414         for (Symbol sym : s.getSymbolsByName(c.name)) {
 415             if (sym.owner != c.owner) break;
 416             if (sym.kind == TYP && !sym.type.hasTag(TYPEVAR) &&
 417                 sym.owner.kind.matches(KindSelector.VAL_MTH) &&
 418                 c.name != names.error) {
 419                 duplicateError(pos, sym);
 420                 return;
 421             }
 422         }
 423     }
 424 
 425     /** Check that class does not have the same name as one of
 426      *  its enclosing classes, or as a class defined in its enclosing scope.
 427      *  return true if class is unique in its enclosing scope.
 428      *  @param pos           Position for error reporting.
 429      *  @param name          The class name.
 430      *  @param s             The enclosing scope.
 431      */
 432     boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
 433         for (Symbol sym : s.getSymbolsByName(name, NON_RECURSIVE)) {
 434             if (sym.kind == TYP && sym.name != names.error) {
 435                 duplicateError(pos, sym);
 436                 return false;
 437             }
 438         }
 439         for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
 440             if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
 441                 duplicateError(pos, sym);
 442                 return true;
 443             }
 444         }
 445         return true;
 446     }
 447 
 448 /* *************************************************************************
 449  * Class name generation
 450  **************************************************************************/
 451 
 452 
 453     private Map<Pair<Name, Name>, Integer> localClassNameIndexes = new HashMap<>();
 454 
 455     /** Return name of local class.
 456      *  This is of the form   {@code <enclClass> $ n <classname> }
 457      *  where
 458      *    enclClass is the flat name of the enclosing class,
 459      *    classname is the simple name of the local class
 460      */
 461     public Name localClassName(ClassSymbol c) {
 462         Name enclFlatname = c.owner.enclClass().flatname;
 463         String enclFlatnameStr = enclFlatname.toString();
 464         Pair<Name, Name> key = new Pair<>(enclFlatname, c.name);
 465         Integer index = localClassNameIndexes.get(key);
 466         for (int i = (index == null) ? 1 : index; ; i++) {
 467             Name flatname = names.fromString(enclFlatnameStr
 468                     + syntheticNameChar + i + c.name);
 469             if (getCompiled(c.packge().modle, flatname) == null) {
 470                 localClassNameIndexes.put(key, i + 1);
 471                 return flatname;
 472             }
 473         }
 474     }
 475 
 476     public void clearLocalClassNameIndexes(ClassSymbol c) {
 477         if (c.owner != null && c.owner.kind != NIL) {
 478             localClassNameIndexes.remove(new Pair<>(
 479                     c.owner.enclClass().flatname, c.name));
 480         }
 481     }
 482 
 483     public void newRound() {
 484         compiled.clear();
 485         localClassNameIndexes.clear();
 486     }
 487 
 488     public void clear() {
 489         deprecationHandler.clear();
 490         removalHandler.clear();
 491         uncheckedHandler.clear();
 492         sunApiHandler.clear();
 493     }
 494 
 495     public void putCompiled(ClassSymbol csym) {
 496         compiled.put(Pair.of(csym.packge().modle, csym.flatname), csym);
 497     }
 498 
 499     public ClassSymbol getCompiled(ClassSymbol csym) {
 500         return compiled.get(Pair.of(csym.packge().modle, csym.flatname));
 501     }
 502 
 503     public ClassSymbol getCompiled(ModuleSymbol msym, Name flatname) {
 504         return compiled.get(Pair.of(msym, flatname));
 505     }
 506 
 507     public void removeCompiled(ClassSymbol csym) {
 508         compiled.remove(Pair.of(csym.packge().modle, csym.flatname));
 509     }
 510 
 511 /* *************************************************************************
 512  * Type Checking
 513  **************************************************************************/
 514 
 515     /**
 516      * A check context is an object that can be used to perform compatibility
 517      * checks - depending on the check context, meaning of 'compatibility' might
 518      * vary significantly.
 519      */
 520     public interface CheckContext {
 521         /**
 522          * Is type 'found' compatible with type 'req' in given context
 523          */
 524         boolean compatible(Type found, Type req, Warner warn);
 525         /**
 526          * Report a check error
 527          */
 528         void report(DiagnosticPosition pos, JCDiagnostic details);
 529         /**
 530          * Obtain a warner for this check context
 531          */
 532         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req);
 533 
 534         public InferenceContext inferenceContext();
 535 
 536         public DeferredAttr.DeferredAttrContext deferredAttrContext();
 537     }
 538 
 539     /**
 540      * This class represent a check context that is nested within another check
 541      * context - useful to check sub-expressions. The default behavior simply
 542      * redirects all method calls to the enclosing check context leveraging
 543      * the forwarding pattern.
 544      */
 545     static class NestedCheckContext implements CheckContext {
 546         CheckContext enclosingContext;
 547 
 548         NestedCheckContext(CheckContext enclosingContext) {
 549             this.enclosingContext = enclosingContext;
 550         }
 551 
 552         public boolean compatible(Type found, Type req, Warner warn) {
 553             return enclosingContext.compatible(found, req, warn);
 554         }
 555 
 556         public void report(DiagnosticPosition pos, JCDiagnostic details) {
 557             enclosingContext.report(pos, details);
 558         }
 559 
 560         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
 561             return enclosingContext.checkWarner(pos, found, req);
 562         }
 563 
 564         public InferenceContext inferenceContext() {
 565             return enclosingContext.inferenceContext();
 566         }
 567 
 568         public DeferredAttrContext deferredAttrContext() {
 569             return enclosingContext.deferredAttrContext();
 570         }
 571     }
 572 
 573     /**
 574      * Check context to be used when evaluating assignment/return statements
 575      */
 576     CheckContext basicHandler = new CheckContext() {
 577         public void report(DiagnosticPosition pos, JCDiagnostic details) {
 578             log.error(pos, Errors.ProbFoundReq(details));
 579         }
 580         public boolean compatible(Type found, Type req, Warner warn) {
 581             return types.isAssignable(found, req, warn);
 582         }
 583 
 584         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
 585             return convertWarner(pos, found, req);
 586         }
 587 
 588         public InferenceContext inferenceContext() {
 589             return infer.emptyContext;
 590         }
 591 
 592         public DeferredAttrContext deferredAttrContext() {
 593             return deferredAttr.emptyDeferredAttrContext;
 594         }
 595 
 596         @Override
 597         public String toString() {
 598             return "CheckContext: basicHandler";
 599         }
 600     };
 601 
 602     /** Check that a given type is assignable to a given proto-type.
 603      *  If it is, return the type, otherwise return errType.
 604      *  @param pos        Position to be used for error reporting.
 605      *  @param found      The type that was found.
 606      *  @param req        The type that was required.
 607      */
 608     public Type checkType(DiagnosticPosition pos, Type found, Type req) {
 609         return checkType(pos, found, req, basicHandler);
 610     }
 611 
 612     Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
 613         final InferenceContext inferenceContext = checkContext.inferenceContext();
 614         if (inferenceContext.free(req) || inferenceContext.free(found)) {
 615             inferenceContext.addFreeTypeListener(List.of(req, found),
 616                     solvedContext -> checkType(pos, solvedContext.asInstType(found), solvedContext.asInstType(req), checkContext));
 617         }
 618         if (req.hasTag(ERROR))
 619             return req;
 620         if (req.hasTag(NONE))
 621             return found;
 622         if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
 623             return found;
 624         } else {
 625             if (found.isNumeric() && req.isNumeric()) {
 626                 checkContext.report(pos, diags.fragment(Fragments.PossibleLossOfPrecision(found, req)));
 627                 return types.createErrorType(found);
 628             }
 629             checkContext.report(pos, diags.fragment(Fragments.InconvertibleTypes(found, req)));
 630             return types.createErrorType(found);
 631         }
 632     }
 633 
 634     /** Check that a given type can be cast to a given target type.
 635      *  Return the result of the cast.
 636      *  @param pos        Position to be used for error reporting.
 637      *  @param found      The type that is being cast.
 638      *  @param req        The target type of the cast.
 639      */
 640     Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
 641         return checkCastable(pos, found, req, basicHandler);
 642     }
 643     Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
 644         if (types.isCastable(found, req, castWarner(pos, found, req))) {
 645             return req;
 646         } else {
 647             checkContext.report(pos, diags.fragment(Fragments.InconvertibleTypes(found, req)));
 648             return types.createErrorType(found);
 649         }
 650     }
 651 
 652     /** Check for redundant casts (i.e. where source type is a subtype of target type)
 653      * The problem should only be reported for non-292 cast
 654      */
 655     public void checkRedundantCast(Env<AttrContext> env, final JCTypeCast tree) {
 656         if (!tree.type.isErroneous()
 657                 && types.isSameType(tree.expr.type, tree.clazz.type)
 658                 && !(ignoreAnnotatedCasts && TreeInfo.containsTypeAnnotation(tree.clazz))
 659                 && !is292targetTypeCast(tree)) {
 660             deferredLintHandler.report(() -> {
 661                 if (lint.isEnabled(LintCategory.CAST))
 662                     log.warning(LintCategory.CAST,
 663                             tree.pos(), Warnings.RedundantCast(tree.clazz.type));
 664             });
 665         }
 666     }
 667     //where
 668         private boolean is292targetTypeCast(JCTypeCast tree) {
 669             boolean is292targetTypeCast = false;
 670             JCExpression expr = TreeInfo.skipParens(tree.expr);
 671             if (expr.hasTag(APPLY)) {
 672                 JCMethodInvocation apply = (JCMethodInvocation)expr;
 673                 Symbol sym = TreeInfo.symbol(apply.meth);
 674                 is292targetTypeCast = sym != null &&
 675                     sym.kind == MTH &&
 676                     (sym.flags() & HYPOTHETICAL) != 0;
 677             }
 678             return is292targetTypeCast;
 679         }
 680 
 681         private static final boolean ignoreAnnotatedCasts = true;
 682 
 683     /** Check that a type is within some bounds.
 684      *
 685      *  Used in TypeApply to verify that, e.g., X in {@code V<X>} is a valid
 686      *  type argument.
 687      *  @param a             The type that should be bounded by bs.
 688      *  @param bound         The bound.
 689      */
 690     private boolean checkExtends(Type a, Type bound) {
 691          if (a.isUnbound()) {
 692              return true;
 693          } else if (!a.hasTag(WILDCARD)) {
 694              a = types.cvarUpperBound(a);
 695              return types.isSubtype(a, bound);
 696          } else if (a.isExtendsBound()) {
 697              return types.isCastable(bound, types.wildUpperBound(a), types.noWarnings);
 698          } else if (a.isSuperBound()) {
 699              return !types.notSoftSubtype(types.wildLowerBound(a), bound);
 700          }
 701          return true;
 702      }
 703 
 704     /** Check that type is different from 'void'.
 705      *  @param pos           Position to be used for error reporting.
 706      *  @param t             The type to be checked.
 707      */
 708     Type checkNonVoid(DiagnosticPosition pos, Type t) {
 709         if (t.hasTag(VOID)) {
 710             log.error(pos, Errors.VoidNotAllowedHere);
 711             return types.createErrorType(t);
 712         } else {
 713             return t;
 714         }
 715     }
 716 
 717     Type checkClassOrArrayType(DiagnosticPosition pos, Type t) {
 718         if (!t.hasTag(CLASS) && !t.hasTag(ARRAY) && !t.hasTag(ERROR)) {
 719             return typeTagError(pos,
 720                                 diags.fragment(Fragments.TypeReqClassArray),
 721                                 asTypeParam(t));
 722         } else {
 723             return t;
 724         }
 725     }
 726 
 727     /** Check that type is a class or interface type.
 728      *  @param pos           Position to be used for error reporting.
 729      *  @param t             The type to be checked.
 730      */
 731     Type checkClassType(DiagnosticPosition pos, Type t) {
 732         if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) {
 733             return typeTagError(pos,
 734                                 diags.fragment(Fragments.TypeReqClass),
 735                                 asTypeParam(t));
 736         } else {
 737             return t;
 738         }
 739     }
 740     //where
 741         private Object asTypeParam(Type t) {
 742             return (t.hasTag(TYPEVAR))
 743                                     ? diags.fragment(Fragments.TypeParameter(t))
 744                                     : t;
 745         }
 746 
 747     /** Check that type is a valid qualifier for a constructor reference expression
 748      */
 749     Type checkConstructorRefType(DiagnosticPosition pos, Type t) {
 750         t = checkClassOrArrayType(pos, t);
 751         if (t.hasTag(CLASS)) {
 752             if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
 753                 log.error(pos, Errors.AbstractCantBeInstantiated(t.tsym));
 754                 t = types.createErrorType(t);
 755             } else if ((t.tsym.flags() & ENUM) != 0) {
 756                 log.error(pos, Errors.EnumCantBeInstantiated);
 757                 t = types.createErrorType(t);
 758             } else {
 759                 t = checkClassType(pos, t, true);
 760             }
 761         } else if (t.hasTag(ARRAY)) {
 762             if (!types.isReifiable(((ArrayType)t).elemtype)) {
 763                 log.error(pos, Errors.GenericArrayCreation);
 764                 t = types.createErrorType(t);
 765             }
 766         }
 767         return t;
 768     }
 769 
 770     /** Check that type is a class or interface type.
 771      *  @param pos           Position to be used for error reporting.
 772      *  @param t             The type to be checked.
 773      *  @param noBounds    True if type bounds are illegal here.
 774      */
 775     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
 776         t = checkClassType(pos, t);
 777         if (noBounds && t.isParameterized()) {
 778             List<Type> args = t.getTypeArguments();
 779             while (args.nonEmpty()) {
 780                 if (args.head.hasTag(WILDCARD))
 781                     return typeTagError(pos,
 782                                         diags.fragment(Fragments.TypeReqExact),
 783                                         args.head);
 784                 args = args.tail;
 785             }
 786         }
 787         return t;
 788     }
 789 
 790     /** Check that type is a reference type, i.e. a class, interface or array type
 791      *  or a type variable.
 792      *  @param pos           Position to be used for error reporting.
 793      *  @param t             The type to be checked.
 794      */
 795     Type checkRefType(DiagnosticPosition pos, Type t) {
 796         if (t.isReference())
 797             return t;
 798         else
 799             return typeTagError(pos,
 800                                 diags.fragment(Fragments.TypeReqRef),
 801                                 t);
 802     }
 803 
 804     /** Check that each type is a reference type, i.e. a class, interface or array type
 805      *  or a type variable.
 806      *  @param trees         Original trees, used for error reporting.
 807      *  @param types         The types to be checked.
 808      */
 809     List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
 810         List<JCExpression> tl = trees;
 811         for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
 812             l.head = checkRefType(tl.head.pos(), l.head);
 813             tl = tl.tail;
 814         }
 815         return types;
 816     }
 817 
 818     /** Check that type is a null or reference type.
 819      *  @param pos           Position to be used for error reporting.
 820      *  @param t             The type to be checked.
 821      */
 822     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
 823         if (t.isReference() || t.hasTag(BOT))
 824             return t;
 825         else
 826             return typeTagError(pos,
 827                                 diags.fragment(Fragments.TypeReqRef),
 828                                 t);
 829     }
 830 
 831     /** Check that flag set does not contain elements of two conflicting sets. s
 832      *  Return true if it doesn't.
 833      *  @param pos           Position to be used for error reporting.
 834      *  @param flags         The set of flags to be checked.
 835      *  @param set1          Conflicting flags set #1.
 836      *  @param set2          Conflicting flags set #2.
 837      */
 838     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
 839         if ((flags & set1) != 0 && (flags & set2) != 0) {
 840             log.error(pos,
 841                       Errors.IllegalCombinationOfModifiers(asFlagSet(TreeInfo.firstFlag(flags & set1)),
 842                                                            asFlagSet(TreeInfo.firstFlag(flags & set2))));
 843             return false;
 844         } else
 845             return true;
 846     }
 847 
 848     /** Check that usage of diamond operator is correct (i.e. diamond should not
 849      * be used with non-generic classes or in anonymous class creation expressions)
 850      */
 851     Type checkDiamond(JCNewClass tree, Type t) {
 852         if (!TreeInfo.isDiamond(tree) ||
 853                 t.isErroneous()) {
 854             return checkClassType(tree.clazz.pos(), t, true);
 855         } else {
 856             if (tree.def != null && !Feature.DIAMOND_WITH_ANONYMOUS_CLASS_CREATION.allowedInSource(source)) {
 857                 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.clazz.pos(),
 858                         Errors.CantApplyDiamond1(t, Feature.DIAMOND_WITH_ANONYMOUS_CLASS_CREATION.fragment(source.name)));
 859             }
 860             if (t.tsym.type.getTypeArguments().isEmpty()) {
 861                 log.error(tree.clazz.pos(),
 862                           Errors.CantApplyDiamond1(t,
 863                                                    Fragments.DiamondNonGeneric(t)));
 864                 return types.createErrorType(t);
 865             } else if (tree.typeargs != null &&
 866                     tree.typeargs.nonEmpty()) {
 867                 log.error(tree.clazz.pos(),
 868                           Errors.CantApplyDiamond1(t,
 869                                                    Fragments.DiamondAndExplicitParams(t)));
 870                 return types.createErrorType(t);
 871             } else {
 872                 return t;
 873             }
 874         }
 875     }
 876 
 877     /** Check that the type inferred using the diamond operator does not contain
 878      *  non-denotable types such as captured types or intersection types.
 879      *  @param t the type inferred using the diamond operator
 880      *  @return  the (possibly empty) list of non-denotable types.
 881      */
 882     List<Type> checkDiamondDenotable(ClassType t) {
 883         ListBuffer<Type> buf = new ListBuffer<>();
 884         for (Type arg : t.allparams()) {
 885             if (!checkDenotable(arg)) {
 886                 buf.append(arg);
 887             }
 888         }
 889         return buf.toList();
 890     }
 891 
 892     public boolean checkDenotable(Type t) {
 893         return denotableChecker.visit(t, null);
 894     }
 895         // where
 896 
 897         /** diamondTypeChecker: A type visitor that descends down the given type looking for non-denotable
 898          *  types. The visit methods return false as soon as a non-denotable type is encountered and true
 899          *  otherwise.
 900          */
 901         private static final Types.SimpleVisitor<Boolean, Void> denotableChecker = new Types.SimpleVisitor<Boolean, Void>() {
 902             @Override
 903             public Boolean visitType(Type t, Void s) {
 904                 return true;
 905             }
 906             @Override
 907             public Boolean visitClassType(ClassType t, Void s) {
 908                 if (t.isUnion() || t.isIntersection()) {
 909                     return false;
 910                 }
 911                 for (Type targ : t.allparams()) {
 912                     if (!visit(targ, s)) {
 913                         return false;
 914                     }
 915                 }
 916                 return true;
 917             }
 918 
 919             @Override
 920             public Boolean visitTypeVar(TypeVar t, Void s) {
 921                 /* Any type variable mentioned in the inferred type must have been declared as a type parameter
 922                   (i.e cannot have been produced by inference (18.4))
 923                 */
 924                 return (t.tsym.flags() & SYNTHETIC) == 0;
 925             }
 926 
 927             @Override
 928             public Boolean visitCapturedType(CapturedType t, Void s) {
 929                 /* Any type variable mentioned in the inferred type must have been declared as a type parameter
 930                   (i.e cannot have been produced by capture conversion (5.1.10))
 931                 */
 932                 return false;
 933             }
 934 
 935             @Override
 936             public Boolean visitArrayType(ArrayType t, Void s) {
 937                 return visit(t.elemtype, s);
 938             }
 939 
 940             @Override
 941             public Boolean visitWildcardType(WildcardType t, Void s) {
 942                 return visit(t.type, s);
 943             }
 944         };
 945 
 946     void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
 947         MethodSymbol m = tree.sym;
 948         boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
 949         Type varargElemType = null;
 950         if (m.isVarArgs()) {
 951             varargElemType = types.elemtype(tree.params.last().type);
 952         }
 953         if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
 954             if (varargElemType != null) {
 955                 JCDiagnostic msg = Feature.PRIVATE_SAFE_VARARGS.allowedInSource(source) ?
 956                         diags.fragment(Fragments.VarargsTrustmeOnVirtualVarargs(m)) :
 957                         diags.fragment(Fragments.VarargsTrustmeOnVirtualVarargsFinalOnly(m));
 958                 log.error(tree,
 959                           Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym,
 960                                                            msg));
 961             } else {
 962                 log.error(tree,
 963                           Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym,
 964                                                            Fragments.VarargsTrustmeOnNonVarargsMeth(m)));
 965             }
 966         } else if (hasTrustMeAnno && varargElemType != null &&
 967                             types.isReifiable(varargElemType)) {
 968             warnUnsafeVararg(tree, Warnings.VarargsRedundantTrustmeAnno(
 969                                 syms.trustMeType.tsym,
 970                                 diags.fragment(Fragments.VarargsTrustmeOnReifiableVarargs(varargElemType))));
 971         }
 972         else if (!hasTrustMeAnno && varargElemType != null &&
 973                 !types.isReifiable(varargElemType)) {
 974             warnUnchecked(tree.params.head.pos(), Warnings.UncheckedVarargsNonReifiableType(varargElemType));
 975         }
 976     }
 977     //where
 978         private boolean isTrustMeAllowedOnMethod(Symbol s) {
 979             return (s.flags() & VARARGS) != 0 &&
 980                 (s.isConstructor() ||
 981                     (s.flags() & (STATIC | FINAL |
 982                                   (Feature.PRIVATE_SAFE_VARARGS.allowedInSource(source) ? PRIVATE : 0) )) != 0);
 983         }
 984 
 985     Type checkLocalVarType(DiagnosticPosition pos, Type t, Name name) {
 986         //check that resulting type is not the null type
 987         if (t.hasTag(BOT)) {
 988             log.error(pos, Errors.CantInferLocalVarType(name, Fragments.LocalCantInferNull));
 989             return types.createErrorType(t);
 990         } else if (t.hasTag(VOID)) {
 991             log.error(pos, Errors.CantInferLocalVarType(name, Fragments.LocalCantInferVoid));
 992             return types.createErrorType(t);
 993         }
 994 
 995         //upward project the initializer type
 996         return types.upward(t, types.captures(t)).baseType();
 997     }
 998 
 999     Type checkMethod(final Type mtype,
1000             final Symbol sym,
1001             final Env<AttrContext> env,
1002             final List<JCExpression> argtrees,
1003             final List<Type> argtypes,
1004             final boolean useVarargs,
1005             InferenceContext inferenceContext) {
1006         // System.out.println("call   : " + env.tree);
1007         // System.out.println("method : " + owntype);
1008         // System.out.println("actuals: " + argtypes);
1009         if (inferenceContext.free(mtype)) {
1010             inferenceContext.addFreeTypeListener(List.of(mtype),
1011                     solvedContext -> checkMethod(solvedContext.asInstType(mtype), sym, env, argtrees, argtypes, useVarargs, solvedContext));
1012             return mtype;
1013         }
1014         Type owntype = mtype;
1015         List<Type> formals = owntype.getParameterTypes();
1016         List<Type> nonInferred = sym.type.getParameterTypes();
1017         if (nonInferred.length() != formals.length()) nonInferred = formals;
1018         Type last = useVarargs ? formals.last() : null;
1019         if (sym.name == names.init && sym.owner == syms.enumSym) {
1020             formals = formals.tail.tail;
1021             nonInferred = nonInferred.tail.tail;
1022         }
1023         if ((sym.flags() & ANONCONSTR_BASED) != 0) {
1024             formals = formals.tail;
1025             nonInferred = nonInferred.tail;
1026         }
1027         List<JCExpression> args = argtrees;
1028         if (args != null) {
1029             //this is null when type-checking a method reference
1030             while (formals.head != last) {
1031                 JCTree arg = args.head;
1032                 Warner warn = convertWarner(arg.pos(), arg.type, nonInferred.head);
1033                 assertConvertible(arg, arg.type, formals.head, warn);
1034                 args = args.tail;
1035                 formals = formals.tail;
1036                 nonInferred = nonInferred.tail;
1037             }
1038             if (useVarargs) {
1039                 Type varArg = types.elemtype(last);
1040                 while (args.tail != null) {
1041                     JCTree arg = args.head;
1042                     Warner warn = convertWarner(arg.pos(), arg.type, varArg);
1043                     assertConvertible(arg, arg.type, varArg, warn);
1044                     args = args.tail;
1045                 }
1046             } else if ((sym.flags() & (VARARGS | SIGNATURE_POLYMORPHIC)) == VARARGS) {
1047                 // non-varargs call to varargs method
1048                 Type varParam = owntype.getParameterTypes().last();
1049                 Type lastArg = argtypes.last();
1050                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
1051                     !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
1052                     log.warning(argtrees.last().pos(),
1053                                 Warnings.InexactNonVarargsCall(types.elemtype(varParam),varParam));
1054             }
1055         }
1056         if (useVarargs) {
1057             Type argtype = owntype.getParameterTypes().last();
1058             if (!types.isReifiable(argtype) &&
1059                 (sym.baseSymbol().attribute(syms.trustMeType.tsym) == null ||
1060                  !isTrustMeAllowedOnMethod(sym))) {
1061                 warnUnchecked(env.tree.pos(), Warnings.UncheckedGenericArrayCreation(argtype));
1062             }
1063             TreeInfo.setVarargsElement(env.tree, types.elemtype(argtype));
1064          }
1065          return owntype;
1066     }
1067     //where
1068     private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
1069         if (types.isConvertible(actual, formal, warn))
1070             return;
1071 
1072         if (formal.isCompound()
1073             && types.isSubtype(actual, types.supertype(formal))
1074             && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
1075             return;
1076     }
1077 
1078     /**
1079      * Check that type 't' is a valid instantiation of a generic class
1080      * (see JLS 4.5)
1081      *
1082      * @param t class type to be checked
1083      * @return true if 't' is well-formed
1084      */
1085     public boolean checkValidGenericType(Type t) {
1086         return firstIncompatibleTypeArg(t) == null;
1087     }
1088     //WHERE
1089         private Type firstIncompatibleTypeArg(Type type) {
1090             List<Type> formals = type.tsym.type.allparams();
1091             List<Type> actuals = type.allparams();
1092             List<Type> args = type.getTypeArguments();
1093             List<Type> forms = type.tsym.type.getTypeArguments();
1094             ListBuffer<Type> bounds_buf = new ListBuffer<>();
1095 
1096             // For matching pairs of actual argument types `a' and
1097             // formal type parameters with declared bound `b' ...
1098             while (args.nonEmpty() && forms.nonEmpty()) {
1099                 // exact type arguments needs to know their
1100                 // bounds (for upper and lower bound
1101                 // calculations).  So we create new bounds where
1102                 // type-parameters are replaced with actuals argument types.
1103                 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
1104                 args = args.tail;
1105                 forms = forms.tail;
1106             }
1107 
1108             args = type.getTypeArguments();
1109             List<Type> tvars_cap = types.substBounds(formals,
1110                                       formals,
1111                                       types.capture(type).allparams());
1112             while (args.nonEmpty() && tvars_cap.nonEmpty()) {
1113                 // Let the actual arguments know their bound
1114                 args.head.withTypeVar((TypeVar)tvars_cap.head);
1115                 args = args.tail;
1116                 tvars_cap = tvars_cap.tail;
1117             }
1118 
1119             args = type.getTypeArguments();
1120             List<Type> bounds = bounds_buf.toList();
1121 
1122             while (args.nonEmpty() && bounds.nonEmpty()) {
1123                 Type actual = args.head;
1124                 if (!isTypeArgErroneous(actual) &&
1125                         !bounds.head.isErroneous() &&
1126                         !checkExtends(actual, bounds.head)) {
1127                     return args.head;
1128                 }
1129                 args = args.tail;
1130                 bounds = bounds.tail;
1131             }
1132 
1133             args = type.getTypeArguments();
1134             bounds = bounds_buf.toList();
1135 
1136             for (Type arg : types.capture(type).getTypeArguments()) {
1137                 if (arg.hasTag(TYPEVAR) &&
1138                         arg.getUpperBound().isErroneous() &&
1139                         !bounds.head.isErroneous() &&
1140                         !isTypeArgErroneous(args.head)) {
1141                     return args.head;
1142                 }
1143                 bounds = bounds.tail;
1144                 args = args.tail;
1145             }
1146 
1147             return null;
1148         }
1149         //where
1150         boolean isTypeArgErroneous(Type t) {
1151             return isTypeArgErroneous.visit(t);
1152         }
1153 
1154         Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
1155             public Boolean visitType(Type t, Void s) {
1156                 return t.isErroneous();
1157             }
1158             @Override
1159             public Boolean visitTypeVar(TypeVar t, Void s) {
1160                 return visit(t.getUpperBound());
1161             }
1162             @Override
1163             public Boolean visitCapturedType(CapturedType t, Void s) {
1164                 return visit(t.getUpperBound()) ||
1165                         visit(t.getLowerBound());
1166             }
1167             @Override
1168             public Boolean visitWildcardType(WildcardType t, Void s) {
1169                 return visit(t.type);
1170             }
1171         };
1172 
1173     /** Check that given modifiers are legal for given symbol and
1174      *  return modifiers together with any implicit modifiers for that symbol.
1175      *  Warning: we can't use flags() here since this method
1176      *  is called during class enter, when flags() would cause a premature
1177      *  completion.
1178      *  @param pos           Position to be used for error reporting.
1179      *  @param flags         The set of modifiers given in a definition.
1180      *  @param sym           The defined symbol.
1181      */
1182     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
1183         long mask;
1184         long implicit = 0;
1185 
1186         switch (sym.kind) {
1187         case VAR:
1188             if (TreeInfo.isReceiverParam(tree))
1189                 mask = ReceiverParamFlags;
1190             else if (sym.owner.kind != TYP)
1191                 mask = LocalVarFlags;
1192             else if ((sym.owner.flags_field & INTERFACE) != 0)
1193                 mask = implicit = InterfaceVarFlags;
1194             else
1195                 mask = VarFlags;
1196             break;
1197         case MTH:
1198             if (sym.name == names.init) {
1199                 if ((sym.owner.flags_field & ENUM) != 0) {
1200                     // enum constructors cannot be declared public or
1201                     // protected and must be implicitly or explicitly
1202                     // private
1203                     implicit = PRIVATE;
1204                     mask = PRIVATE;
1205                 } else
1206                     mask = ConstructorFlags;
1207             }  else if ((sym.owner.flags_field & INTERFACE) != 0) {
1208                 if ((sym.owner.flags_field & ANNOTATION) != 0) {
1209                     mask = AnnotationTypeElementMask;
1210                     implicit = PUBLIC | ABSTRACT;
1211                 } else if ((flags & (DEFAULT | STATIC | PRIVATE)) != 0) {
1212                     mask = InterfaceMethodMask;
1213                     implicit = (flags & PRIVATE) != 0 ? 0 : PUBLIC;
1214                     if ((flags & DEFAULT) != 0) {
1215                         implicit |= ABSTRACT;
1216                     }
1217                 } else {
1218                     mask = implicit = InterfaceMethodFlags;
1219                 }
1220             } else if ((sym.owner.flags_field & RECORD) != 0) {
1221                 mask = RecordMethodFlags;
1222             } else {
1223                 mask = MethodFlags;
1224             }
1225             if ((flags & STRICTFP) != 0) {
1226                 warnOnExplicitStrictfp(pos);
1227             }
1228             // Imply STRICTFP if owner has STRICTFP set.
1229             if (((flags|implicit) & Flags.ABSTRACT) == 0 ||
1230                 ((flags) & Flags.DEFAULT) != 0)
1231                 implicit |= sym.owner.flags_field & STRICTFP;
1232             break;
1233         case TYP:
1234             if (sym.owner.kind.matches(KindSelector.VAL_MTH) ||
1235                     (sym.isDirectlyOrIndirectlyLocal() && (flags & ANNOTATION) != 0)) {
1236                 boolean implicitlyStatic = !sym.isAnonymous() &&
1237                         ((flags & RECORD) != 0 || (flags & ENUM) != 0 || (flags & INTERFACE) != 0);
1238                 boolean staticOrImplicitlyStatic = (flags & STATIC) != 0 || implicitlyStatic;
1239                 // local statics are allowed only if records are allowed too
1240                 mask = staticOrImplicitlyStatic && allowRecords && (flags & ANNOTATION) == 0 ? StaticLocalFlags : LocalClassFlags;
1241                 implicit = implicitlyStatic ? STATIC : implicit;
1242             } else if (sym.owner.kind == TYP) {
1243                 // statics in inner classes are allowed only if records are allowed too
1244                 mask = ((flags & STATIC) != 0) && allowRecords && (flags & ANNOTATION) == 0 ? ExtendedMemberStaticClassFlags : ExtendedMemberClassFlags;
1245                 if (sym.owner.owner.kind == PCK ||
1246                     (sym.owner.flags_field & STATIC) != 0) {
1247                     mask |= STATIC;
1248                 } else if (!allowRecords && ((flags & ENUM) != 0 || (flags & RECORD) != 0)) {
1249                     log.error(pos, Errors.StaticDeclarationNotAllowedInInnerClasses);
1250                 }
1251                 // Nested interfaces and enums are always STATIC (Spec ???)
1252                 if ((flags & (INTERFACE | ENUM | RECORD)) != 0 ) implicit = STATIC;
1253             } else {
1254                 mask = ExtendedClassFlags;
1255             }
1256             // Interfaces are always ABSTRACT
1257             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
1258 
1259             if ((flags & ENUM) != 0) {
1260                 // enums can't be declared abstract, final, sealed or non-sealed
1261                 mask &= ~(ABSTRACT | FINAL | SEALED | NON_SEALED);
1262                 implicit |= implicitEnumFinalFlag(tree);
1263             }
1264             if ((flags & RECORD) != 0) {
1265                 // records can't be declared abstract
1266                 mask &= ~ABSTRACT;
1267                 implicit |= FINAL;
1268             }
1269             if ((flags & STRICTFP) != 0) {
1270                 warnOnExplicitStrictfp(pos);
1271             }
1272             // Imply STRICTFP if owner has STRICTFP set.
1273             implicit |= sym.owner.flags_field & STRICTFP;
1274             break;
1275         default:
1276             throw new AssertionError();
1277         }
1278         long illegal = flags & ExtendedStandardFlags & ~mask;
1279         if (illegal != 0) {
1280             if ((illegal & INTERFACE) != 0) {
1281                 log.error(pos, ((flags & ANNOTATION) != 0) ? Errors.AnnotationDeclNotAllowedHere : Errors.IntfNotAllowedHere);
1282                 mask |= INTERFACE;
1283             }
1284             else {
1285                 log.error(pos,
1286                         Errors.ModNotAllowedHere(asFlagSet(illegal)));
1287             }
1288         }
1289         else if ((sym.kind == TYP ||
1290                   // ISSUE: Disallowing abstract&private is no longer appropriate
1291                   // in the presence of inner classes. Should it be deleted here?
1292                   checkDisjoint(pos, flags,
1293                                 ABSTRACT,
1294                                 PRIVATE | STATIC | DEFAULT))
1295                  &&
1296                  checkDisjoint(pos, flags,
1297                                 STATIC | PRIVATE,
1298                                 DEFAULT)
1299                  &&
1300                  checkDisjoint(pos, flags,
1301                                ABSTRACT | INTERFACE,
1302                                FINAL | NATIVE | SYNCHRONIZED)
1303                  &&
1304                  checkDisjoint(pos, flags,
1305                                PUBLIC,
1306                                PRIVATE | PROTECTED)
1307                  &&
1308                  checkDisjoint(pos, flags,
1309                                PRIVATE,
1310                                PUBLIC | PROTECTED)
1311                  &&
1312                  checkDisjoint(pos, flags,
1313                                FINAL,
1314                                VOLATILE)
1315                  &&
1316                  (sym.kind == TYP ||
1317                   checkDisjoint(pos, flags,
1318                                 ABSTRACT | NATIVE,
1319                                 STRICTFP))
1320                  && checkDisjoint(pos, flags,
1321                                 FINAL,
1322                            SEALED | NON_SEALED)
1323                  && checkDisjoint(pos, flags,
1324                                 SEALED,
1325                            FINAL | NON_SEALED)
1326                  && checkDisjoint(pos, flags,
1327                                 SEALED,
1328                                 ANNOTATION)) {
1329             // skip
1330         }
1331         return flags & (mask | ~ExtendedStandardFlags) | implicit;
1332     }
1333 
1334     private void warnOnExplicitStrictfp(DiagnosticPosition pos) {
1335         DiagnosticPosition prevLintPos = deferredLintHandler.setPos(pos);
1336         try {
1337             deferredLintHandler.report(() -> {
1338                                            if (lint.isEnabled(LintCategory.STRICTFP)) {
1339                                                log.warning(LintCategory.STRICTFP,
1340                                                            pos, Warnings.Strictfp); }
1341                                        });
1342         } finally {
1343             deferredLintHandler.setPos(prevLintPos);
1344         }
1345     }
1346 
1347 
1348     /** Determine if this enum should be implicitly final.
1349      *
1350      *  If the enum has no specialized enum constants, it is final.
1351      *
1352      *  If the enum does have specialized enum constants, it is
1353      *  <i>not</i> final.
1354      */
1355     private long implicitEnumFinalFlag(JCTree tree) {
1356         if (!tree.hasTag(CLASSDEF)) return 0;
1357         class SpecialTreeVisitor extends JCTree.Visitor {
1358             boolean specialized;
1359             SpecialTreeVisitor() {
1360                 this.specialized = false;
1361             }
1362 
1363             @Override
1364             public void visitTree(JCTree tree) { /* no-op */ }
1365 
1366             @Override
1367             public void visitVarDef(JCVariableDecl tree) {
1368                 if ((tree.mods.flags & ENUM) != 0) {
1369                     if (tree.init instanceof JCNewClass newClass && newClass.def != null) {
1370                         specialized = true;
1371                     }
1372                 }
1373             }
1374         }
1375 
1376         SpecialTreeVisitor sts = new SpecialTreeVisitor();
1377         JCClassDecl cdef = (JCClassDecl) tree;
1378         for (JCTree defs: cdef.defs) {
1379             defs.accept(sts);
1380             if (sts.specialized) return allowSealed ? SEALED : 0;
1381         }
1382         return FINAL;
1383     }
1384 
1385 /* *************************************************************************
1386  * Type Validation
1387  **************************************************************************/
1388 
1389     /** Validate a type expression. That is,
1390      *  check that all type arguments of a parametric type are within
1391      *  their bounds. This must be done in a second phase after type attribution
1392      *  since a class might have a subclass as type parameter bound. E.g:
1393      *
1394      *  <pre>{@code
1395      *  class B<A extends C> { ... }
1396      *  class C extends B<C> { ... }
1397      *  }</pre>
1398      *
1399      *  and we can't make sure that the bound is already attributed because
1400      *  of possible cycles.
1401      *
1402      * Visitor method: Validate a type expression, if it is not null, catching
1403      *  and reporting any completion failures.
1404      */
1405     void validate(JCTree tree, Env<AttrContext> env) {
1406         validate(tree, env, true);
1407     }
1408     void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
1409         new Validator(env).validateTree(tree, checkRaw, true);
1410     }
1411 
1412     /** Visitor method: Validate a list of type expressions.
1413      */
1414     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
1415         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1416             validate(l.head, env);
1417     }
1418 
1419     /** A visitor class for type validation.
1420      */
1421     class Validator extends JCTree.Visitor {
1422 
1423         boolean checkRaw;
1424         boolean isOuter;
1425         Env<AttrContext> env;
1426 
1427         Validator(Env<AttrContext> env) {
1428             this.env = env;
1429         }
1430 
1431         @Override
1432         public void visitTypeArray(JCArrayTypeTree tree) {
1433             validateTree(tree.elemtype, checkRaw, isOuter);
1434         }
1435 
1436         @Override
1437         public void visitTypeApply(JCTypeApply tree) {
1438             if (tree.type.hasTag(CLASS)) {
1439                 List<JCExpression> args = tree.arguments;
1440                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
1441 
1442                 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
1443                 if (incompatibleArg != null) {
1444                     for (JCTree arg : tree.arguments) {
1445                         if (arg.type == incompatibleArg) {
1446                             log.error(arg, Errors.NotWithinBounds(incompatibleArg, forms.head));
1447                         }
1448                         forms = forms.tail;
1449                      }
1450                  }
1451 
1452                 forms = tree.type.tsym.type.getTypeArguments();
1453 
1454                 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
1455 
1456                 // For matching pairs of actual argument types `a' and
1457                 // formal type parameters with declared bound `b' ...
1458                 while (args.nonEmpty() && forms.nonEmpty()) {
1459                     validateTree(args.head,
1460                             !(isOuter && is_java_lang_Class),
1461                             false);
1462                     args = args.tail;
1463                     forms = forms.tail;
1464                 }
1465 
1466                 // Check that this type is either fully parameterized, or
1467                 // not parameterized at all.
1468                 if (tree.type.getEnclosingType().isRaw())
1469                     log.error(tree.pos(), Errors.ImproperlyFormedTypeInnerRawParam);
1470                 if (tree.clazz.hasTag(SELECT))
1471                     visitSelectInternal((JCFieldAccess)tree.clazz);
1472             }
1473         }
1474 
1475         @Override
1476         public void visitTypeParameter(JCTypeParameter tree) {
1477             validateTrees(tree.bounds, true, isOuter);
1478             checkClassBounds(tree.pos(), tree.type);
1479         }
1480 
1481         @Override
1482         public void visitWildcard(JCWildcard tree) {
1483             if (tree.inner != null)
1484                 validateTree(tree.inner, true, isOuter);
1485         }
1486 
1487         @Override
1488         public void visitSelect(JCFieldAccess tree) {
1489             if (tree.type.hasTag(CLASS)) {
1490                 visitSelectInternal(tree);
1491 
1492                 // Check that this type is either fully parameterized, or
1493                 // not parameterized at all.
1494                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1495                     log.error(tree.pos(), Errors.ImproperlyFormedTypeParamMissing);
1496             }
1497         }
1498 
1499         public void visitSelectInternal(JCFieldAccess tree) {
1500             if (tree.type.tsym.isStatic() &&
1501                 tree.selected.type.isParameterized()) {
1502                 // The enclosing type is not a class, so we are
1503                 // looking at a static member type.  However, the
1504                 // qualifying expression is parameterized.
1505                 log.error(tree.pos(), Errors.CantSelectStaticClassFromParamType);
1506             } else {
1507                 // otherwise validate the rest of the expression
1508                 tree.selected.accept(this);
1509             }
1510         }
1511 
1512         @Override
1513         public void visitAnnotatedType(JCAnnotatedType tree) {
1514             tree.underlyingType.accept(this);
1515         }
1516 
1517         @Override
1518         public void visitTypeIdent(JCPrimitiveTypeTree that) {
1519             if (that.type.hasTag(TypeTag.VOID)) {
1520                 log.error(that.pos(), Errors.VoidNotAllowedHere);
1521             }
1522             super.visitTypeIdent(that);
1523         }
1524 
1525         /** Default visitor method: do nothing.
1526          */
1527         @Override
1528         public void visitTree(JCTree tree) {
1529         }
1530 
1531         public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
1532             if (tree != null) {
1533                 boolean prevCheckRaw = this.checkRaw;
1534                 this.checkRaw = checkRaw;
1535                 this.isOuter = isOuter;
1536 
1537                 try {
1538                     tree.accept(this);
1539                     if (checkRaw)
1540                         checkRaw(tree, env);
1541                 } catch (CompletionFailure ex) {
1542                     completionError(tree.pos(), ex);
1543                 } finally {
1544                     this.checkRaw = prevCheckRaw;
1545                 }
1546             }
1547         }
1548 
1549         public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1550             for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1551                 validateTree(l.head, checkRaw, isOuter);
1552         }
1553     }
1554 
1555     void checkRaw(JCTree tree, Env<AttrContext> env) {
1556         if (lint.isEnabled(LintCategory.RAW) &&
1557             tree.type.hasTag(CLASS) &&
1558             !TreeInfo.isDiamond(tree) &&
1559             !withinAnonConstr(env) &&
1560             tree.type.isRaw()) {
1561             log.warning(LintCategory.RAW,
1562                     tree.pos(), Warnings.RawClassUse(tree.type, tree.type.tsym.type));
1563         }
1564     }
1565     //where
1566         private boolean withinAnonConstr(Env<AttrContext> env) {
1567             return env.enclClass.name.isEmpty() &&
1568                     env.enclMethod != null && env.enclMethod.name == names.init;
1569         }
1570 
1571 /* *************************************************************************
1572  * Exception checking
1573  **************************************************************************/
1574 
1575     /* The following methods treat classes as sets that contain
1576      * the class itself and all their subclasses
1577      */
1578 
1579     /** Is given type a subtype of some of the types in given list?
1580      */
1581     boolean subset(Type t, List<Type> ts) {
1582         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1583             if (types.isSubtype(t, l.head)) return true;
1584         return false;
1585     }
1586 
1587     /** Is given type a subtype or supertype of
1588      *  some of the types in given list?
1589      */
1590     boolean intersects(Type t, List<Type> ts) {
1591         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1592             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
1593         return false;
1594     }
1595 
1596     /** Add type set to given type list, unless it is a subclass of some class
1597      *  in the list.
1598      */
1599     List<Type> incl(Type t, List<Type> ts) {
1600         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
1601     }
1602 
1603     /** Remove type set from type set list.
1604      */
1605     List<Type> excl(Type t, List<Type> ts) {
1606         if (ts.isEmpty()) {
1607             return ts;
1608         } else {
1609             List<Type> ts1 = excl(t, ts.tail);
1610             if (types.isSubtype(ts.head, t)) return ts1;
1611             else if (ts1 == ts.tail) return ts;
1612             else return ts1.prepend(ts.head);
1613         }
1614     }
1615 
1616     /** Form the union of two type set lists.
1617      */
1618     List<Type> union(List<Type> ts1, List<Type> ts2) {
1619         List<Type> ts = ts1;
1620         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1621             ts = incl(l.head, ts);
1622         return ts;
1623     }
1624 
1625     /** Form the difference of two type lists.
1626      */
1627     List<Type> diff(List<Type> ts1, List<Type> ts2) {
1628         List<Type> ts = ts1;
1629         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1630             ts = excl(l.head, ts);
1631         return ts;
1632     }
1633 
1634     /** Form the intersection of two type lists.
1635      */
1636     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
1637         List<Type> ts = List.nil();
1638         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
1639             if (subset(l.head, ts2)) ts = incl(l.head, ts);
1640         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1641             if (subset(l.head, ts1)) ts = incl(l.head, ts);
1642         return ts;
1643     }
1644 
1645     /** Is exc an exception symbol that need not be declared?
1646      */
1647     boolean isUnchecked(ClassSymbol exc) {
1648         return
1649             exc.kind == ERR ||
1650             exc.isSubClass(syms.errorType.tsym, types) ||
1651             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1652     }
1653 
1654     /** Is exc an exception type that need not be declared?
1655      */
1656     boolean isUnchecked(Type exc) {
1657         return
1658             (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) :
1659             (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) :
1660             exc.hasTag(BOT);
1661     }
1662 
1663     boolean isChecked(Type exc) {
1664         return !isUnchecked(exc);
1665     }
1666 
1667     /** Same, but handling completion failures.
1668      */
1669     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1670         try {
1671             return isUnchecked(exc);
1672         } catch (CompletionFailure ex) {
1673             completionError(pos, ex);
1674             return true;
1675         }
1676     }
1677 
1678     /** Is exc handled by given exception list?
1679      */
1680     boolean isHandled(Type exc, List<Type> handled) {
1681         return isUnchecked(exc) || subset(exc, handled);
1682     }
1683 
1684     /** Return all exceptions in thrown list that are not in handled list.
1685      *  @param thrown     The list of thrown exceptions.
1686      *  @param handled    The list of handled exceptions.
1687      */
1688     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
1689         List<Type> unhandled = List.nil();
1690         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1691             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1692         return unhandled;
1693     }
1694 
1695 /* *************************************************************************
1696  * Overriding/Implementation checking
1697  **************************************************************************/
1698 
1699     /** The level of access protection given by a flag set,
1700      *  where PRIVATE is highest and PUBLIC is lowest.
1701      */
1702     static int protection(long flags) {
1703         switch ((short)(flags & AccessFlags)) {
1704         case PRIVATE: return 3;
1705         case PROTECTED: return 1;
1706         default:
1707         case PUBLIC: return 0;
1708         case 0: return 2;
1709         }
1710     }
1711 
1712     /** A customized "cannot override" error message.
1713      *  @param m      The overriding method.
1714      *  @param other  The overridden method.
1715      *  @return       An internationalized string.
1716      */
1717     Fragment cannotOverride(MethodSymbol m, MethodSymbol other) {
1718         Symbol mloc = m.location();
1719         Symbol oloc = other.location();
1720 
1721         if ((other.owner.flags() & INTERFACE) == 0)
1722             return Fragments.CantOverride(m, mloc, other, oloc);
1723         else if ((m.owner.flags() & INTERFACE) == 0)
1724             return Fragments.CantImplement(m, mloc, other, oloc);
1725         else
1726             return Fragments.ClashesWith(m, mloc, other, oloc);
1727     }
1728 
1729     /** A customized "override" warning message.
1730      *  @param m      The overriding method.
1731      *  @param other  The overridden method.
1732      *  @return       An internationalized string.
1733      */
1734     Fragment uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1735         Symbol mloc = m.location();
1736         Symbol oloc = other.location();
1737 
1738         if ((other.owner.flags() & INTERFACE) == 0)
1739             return Fragments.UncheckedOverride(m, mloc, other, oloc);
1740         else if ((m.owner.flags() & INTERFACE) == 0)
1741             return Fragments.UncheckedImplement(m, mloc, other, oloc);
1742         else
1743             return Fragments.UncheckedClashWith(m, mloc, other, oloc);
1744     }
1745 
1746     /** A customized "override" warning message.
1747      *  @param m      The overriding method.
1748      *  @param other  The overridden method.
1749      *  @return       An internationalized string.
1750      */
1751     Fragment varargsOverrides(MethodSymbol m, MethodSymbol other) {
1752         Symbol mloc = m.location();
1753         Symbol oloc = other.location();
1754 
1755         if ((other.owner.flags() & INTERFACE) == 0)
1756             return Fragments.VarargsOverride(m, mloc, other, oloc);
1757         else  if ((m.owner.flags() & INTERFACE) == 0)
1758             return Fragments.VarargsImplement(m, mloc, other, oloc);
1759         else
1760             return Fragments.VarargsClashWith(m, mloc, other, oloc);
1761     }
1762 
1763     /** Check that this method conforms with overridden method 'other'.
1764      *  where `origin' is the class where checking started.
1765      *  Complications:
1766      *  (1) Do not check overriding of synthetic methods
1767      *      (reason: they might be final).
1768      *      todo: check whether this is still necessary.
1769      *  (2) Admit the case where an interface proxy throws fewer exceptions
1770      *      than the method it implements. Augment the proxy methods with the
1771      *      undeclared exceptions in this case.
1772      *  (3) When generics are enabled, admit the case where an interface proxy
1773      *      has a result type
1774      *      extended by the result type of the method it implements.
1775      *      Change the proxies result type to the smaller type in this case.
1776      *
1777      *  @param tree         The tree from which positions
1778      *                      are extracted for errors.
1779      *  @param m            The overriding method.
1780      *  @param other        The overridden method.
1781      *  @param origin       The class of which the overriding method
1782      *                      is a member.
1783      */
1784     void checkOverride(JCTree tree,
1785                        MethodSymbol m,
1786                        MethodSymbol other,
1787                        ClassSymbol origin) {
1788         // Don't check overriding of synthetic methods or by bridge methods.
1789         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1790             return;
1791         }
1792 
1793         // Error if static method overrides instance method (JLS 8.4.8.2).
1794         if ((m.flags() & STATIC) != 0 &&
1795                    (other.flags() & STATIC) == 0) {
1796             log.error(TreeInfo.diagnosticPositionFor(m, tree),
1797                       Errors.OverrideStatic(cannotOverride(m, other)));
1798             m.flags_field |= BAD_OVERRIDE;
1799             return;
1800         }
1801 
1802         // Error if instance method overrides static or final
1803         // method (JLS 8.4.8.1).
1804         if ((other.flags() & FINAL) != 0 ||
1805                  (m.flags() & STATIC) == 0 &&
1806                  (other.flags() & STATIC) != 0) {
1807             log.error(TreeInfo.diagnosticPositionFor(m, tree),
1808                       Errors.OverrideMeth(cannotOverride(m, other),
1809                                           asFlagSet(other.flags() & (FINAL | STATIC))));
1810             m.flags_field |= BAD_OVERRIDE;
1811             return;
1812         }
1813 
1814         if ((m.owner.flags() & ANNOTATION) != 0) {
1815             // handled in validateAnnotationMethod
1816             return;
1817         }
1818 
1819         // Error if overriding method has weaker access (JLS 8.4.8.3).
1820         if (protection(m.flags()) > protection(other.flags())) {
1821             log.error(TreeInfo.diagnosticPositionFor(m, tree),
1822                       (other.flags() & AccessFlags) == 0 ?
1823                               Errors.OverrideWeakerAccess(cannotOverride(m, other),
1824                                                           "package") :
1825                               Errors.OverrideWeakerAccess(cannotOverride(m, other),
1826                                                           asFlagSet(other.flags() & AccessFlags)));
1827             m.flags_field |= BAD_OVERRIDE;
1828             return;
1829         }
1830 
1831         if (shouldCheckPreview(m, other, origin)) {
1832             checkPreview(tree.pos(), m, other);
1833         }
1834 
1835         Type mt = types.memberType(origin.type, m);
1836         Type ot = types.memberType(origin.type, other);
1837         // Error if overriding result type is different
1838         // (or, in the case of generics mode, not a subtype) of
1839         // overridden result type. We have to rename any type parameters
1840         // before comparing types.
1841         List<Type> mtvars = mt.getTypeArguments();
1842         List<Type> otvars = ot.getTypeArguments();
1843         Type mtres = mt.getReturnType();
1844         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1845 
1846         overrideWarner.clear();
1847         boolean resultTypesOK =
1848             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1849         if (!resultTypesOK) {
1850             if ((m.flags() & STATIC) != 0 && (other.flags() & STATIC) != 0) {
1851                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1852                           Errors.OverrideIncompatibleRet(Fragments.CantHide(m, m.location(), other,
1853                                         other.location()), mtres, otres));
1854                 m.flags_field |= BAD_OVERRIDE;
1855             } else {
1856                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1857                           Errors.OverrideIncompatibleRet(cannotOverride(m, other), mtres, otres));
1858                 m.flags_field |= BAD_OVERRIDE;
1859             }
1860             return;
1861         } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
1862             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1863                     Warnings.OverrideUncheckedRet(uncheckedOverrides(m, other), mtres, otres));
1864         }
1865 
1866         // Error if overriding method throws an exception not reported
1867         // by overridden method.
1868         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1869         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1870         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1871         if (unhandledErased.nonEmpty()) {
1872             log.error(TreeInfo.diagnosticPositionFor(m, tree),
1873                       Errors.OverrideMethDoesntThrow(cannotOverride(m, other), unhandledUnerased.head));
1874             m.flags_field |= BAD_OVERRIDE;
1875             return;
1876         }
1877         else if (unhandledUnerased.nonEmpty()) {
1878             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1879                           Warnings.OverrideUncheckedThrown(cannotOverride(m, other), unhandledUnerased.head));
1880             return;
1881         }
1882 
1883         // Optional warning if varargs don't agree
1884         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1885             && lint.isEnabled(LintCategory.OVERRIDES)) {
1886             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1887                         ((m.flags() & Flags.VARARGS) != 0)
1888                         ? Warnings.OverrideVarargsMissing(varargsOverrides(m, other))
1889                         : Warnings.OverrideVarargsExtra(varargsOverrides(m, other)));
1890         }
1891 
1892         // Warn if instance method overrides bridge method (compiler spec ??)
1893         if ((other.flags() & BRIDGE) != 0) {
1894             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1895                         Warnings.OverrideBridge(uncheckedOverrides(m, other)));
1896         }
1897 
1898         // Warn if a deprecated method overridden by a non-deprecated one.
1899         if (!isDeprecatedOverrideIgnorable(other, origin)) {
1900             Lint prevLint = setLint(lint.augment(m));
1901             try {
1902                 checkDeprecated(() -> TreeInfo.diagnosticPositionFor(m, tree), m, other);
1903             } finally {
1904                 setLint(prevLint);
1905             }
1906         }
1907     }
1908     // where
1909         private boolean shouldCheckPreview(MethodSymbol m, MethodSymbol other, ClassSymbol origin) {
1910             if (m.owner != origin ||
1911                 //performance - only do the expensive checks when the overridden method is a Preview API:
1912                 (other.flags() & PREVIEW_API) == 0) {
1913                 return false;
1914             }
1915 
1916             for (Symbol s : types.membersClosure(origin.type, false).getSymbolsByName(m.name)) {
1917                 if (m != s && m.overrides(s, origin, types, false)) {
1918                     //only produce preview warnings or errors if "m" immediatelly overrides "other"
1919                     //without intermediate overriding methods:
1920                     return s == other;
1921                 }
1922             }
1923 
1924             return false;
1925         }
1926         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1927             // If the method, m, is defined in an interface, then ignore the issue if the method
1928             // is only inherited via a supertype and also implemented in the supertype,
1929             // because in that case, we will rediscover the issue when examining the method
1930             // in the supertype.
1931             // If the method, m, is not defined in an interface, then the only time we need to
1932             // address the issue is when the method is the supertype implementation: any other
1933             // case, we will have dealt with when examining the supertype classes
1934             ClassSymbol mc = m.enclClass();
1935             Type st = types.supertype(origin.type);
1936             if (!st.hasTag(CLASS))
1937                 return true;
1938             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1939 
1940             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1941                 List<Type> intfs = types.interfaces(origin.type);
1942                 return (intfs.contains(mc.type) ? false : (stimpl != null));
1943             }
1944             else
1945                 return (stimpl != m);
1946         }
1947 
1948 
1949     // used to check if there were any unchecked conversions
1950     Warner overrideWarner = new Warner();
1951 
1952     /** Check that a class does not inherit two concrete methods
1953      *  with the same signature.
1954      *  @param pos          Position to be used for error reporting.
1955      *  @param site         The class type to be checked.
1956      */
1957     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1958         Type sup = types.supertype(site);
1959         if (!sup.hasTag(CLASS)) return;
1960 
1961         for (Type t1 = sup;
1962              t1.hasTag(CLASS) && t1.tsym.type.isParameterized();
1963              t1 = types.supertype(t1)) {
1964             for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) {
1965                 if (s1.kind != MTH ||
1966                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1967                     !s1.isInheritedIn(site.tsym, types) ||
1968                     ((MethodSymbol)s1).implementation(site.tsym,
1969                                                       types,
1970                                                       true) != s1)
1971                     continue;
1972                 Type st1 = types.memberType(t1, s1);
1973                 int s1ArgsLength = st1.getParameterTypes().length();
1974                 if (st1 == s1.type) continue;
1975 
1976                 for (Type t2 = sup;
1977                      t2.hasTag(CLASS);
1978                      t2 = types.supertype(t2)) {
1979                     for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) {
1980                         if (s2 == s1 ||
1981                             s2.kind != MTH ||
1982                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1983                             s2.type.getParameterTypes().length() != s1ArgsLength ||
1984                             !s2.isInheritedIn(site.tsym, types) ||
1985                             ((MethodSymbol)s2).implementation(site.tsym,
1986                                                               types,
1987                                                               true) != s2)
1988                             continue;
1989                         Type st2 = types.memberType(t2, s2);
1990                         if (types.overrideEquivalent(st1, st2))
1991                             log.error(pos,
1992                                       Errors.ConcreteInheritanceConflict(s1, t1, s2, t2, sup));
1993                     }
1994                 }
1995             }
1996         }
1997     }
1998 
1999     /** Check that classes (or interfaces) do not each define an abstract
2000      *  method with same name and arguments but incompatible return types.
2001      *  @param pos          Position to be used for error reporting.
2002      *  @param t1           The first argument type.
2003      *  @param t2           The second argument type.
2004      */
2005     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
2006                                             Type t1,
2007                                             Type t2,
2008                                             Type site) {
2009         if ((site.tsym.flags() & COMPOUND) != 0) {
2010             // special case for intersections: need to eliminate wildcards in supertypes
2011             t1 = types.capture(t1);
2012             t2 = types.capture(t2);
2013         }
2014         return firstIncompatibility(pos, t1, t2, site) == null;
2015     }
2016 
2017     /** Return the first method which is defined with same args
2018      *  but different return types in two given interfaces, or null if none
2019      *  exists.
2020      *  @param t1     The first type.
2021      *  @param t2     The second type.
2022      *  @param site   The most derived type.
2023      *  @return symbol from t2 that conflicts with one in t1.
2024      */
2025     private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
2026         Map<TypeSymbol,Type> interfaces1 = new HashMap<>();
2027         closure(t1, interfaces1);
2028         Map<TypeSymbol,Type> interfaces2;
2029         if (t1 == t2)
2030             interfaces2 = interfaces1;
2031         else
2032             closure(t2, interfaces1, interfaces2 = new HashMap<>());
2033 
2034         for (Type t3 : interfaces1.values()) {
2035             for (Type t4 : interfaces2.values()) {
2036                 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
2037                 if (s != null) return s;
2038             }
2039         }
2040         return null;
2041     }
2042 
2043     /** Compute all the supertypes of t, indexed by type symbol. */
2044     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
2045         if (!t.hasTag(CLASS)) return;
2046         if (typeMap.put(t.tsym, t) == null) {
2047             closure(types.supertype(t), typeMap);
2048             for (Type i : types.interfaces(t))
2049                 closure(i, typeMap);
2050         }
2051     }
2052 
2053     /** Compute all the supertypes of t, indexed by type symbol (except those in typesSkip). */
2054     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
2055         if (!t.hasTag(CLASS)) return;
2056         if (typesSkip.get(t.tsym) != null) return;
2057         if (typeMap.put(t.tsym, t) == null) {
2058             closure(types.supertype(t), typesSkip, typeMap);
2059             for (Type i : types.interfaces(t))
2060                 closure(i, typesSkip, typeMap);
2061         }
2062     }
2063 
2064     /** Return the first method in t2 that conflicts with a method from t1. */
2065     private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
2066         for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) {
2067             Type st1 = null;
2068             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
2069                     (s1.flags() & SYNTHETIC) != 0) continue;
2070             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
2071             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
2072             for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) {
2073                 if (s1 == s2) continue;
2074                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
2075                         (s2.flags() & SYNTHETIC) != 0) continue;
2076                 if (st1 == null) st1 = types.memberType(t1, s1);
2077                 Type st2 = types.memberType(t2, s2);
2078                 if (types.overrideEquivalent(st1, st2)) {
2079                     List<Type> tvars1 = st1.getTypeArguments();
2080                     List<Type> tvars2 = st2.getTypeArguments();
2081                     Type rt1 = st1.getReturnType();
2082                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
2083                     boolean compat =
2084                         types.isSameType(rt1, rt2) ||
2085                         !rt1.isPrimitiveOrVoid() &&
2086                         !rt2.isPrimitiveOrVoid() &&
2087                         (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
2088                          types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
2089                          checkCommonOverriderIn(s1,s2,site);
2090                     if (!compat) {
2091                         log.error(pos, Errors.TypesIncompatible(t1, t2,
2092                                 Fragments.IncompatibleDiffRet(s2.name, types.memberType(t2, s2).getParameterTypes())));
2093                         return s2;
2094                     }
2095                 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
2096                         !checkCommonOverriderIn(s1, s2, site)) {
2097                     log.error(pos, Errors.NameClashSameErasureNoOverride(
2098                             s1.name, types.memberType(site, s1).asMethodType().getParameterTypes(), s1.location(),
2099                             s2.name, types.memberType(site, s2).asMethodType().getParameterTypes(), s2.location()));
2100                     return s2;
2101                 }
2102             }
2103         }
2104         return null;
2105     }
2106     //WHERE
2107     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
2108         Map<TypeSymbol,Type> supertypes = new HashMap<>();
2109         Type st1 = types.memberType(site, s1);
2110         Type st2 = types.memberType(site, s2);
2111         closure(site, supertypes);
2112         for (Type t : supertypes.values()) {
2113             for (Symbol s3 : t.tsym.members().getSymbolsByName(s1.name)) {
2114                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
2115                 Type st3 = types.memberType(site,s3);
2116                 if (types.overrideEquivalent(st3, st1) &&
2117                         types.overrideEquivalent(st3, st2) &&
2118                         types.returnTypeSubstitutable(st3, st1) &&
2119                         types.returnTypeSubstitutable(st3, st2)) {
2120                     return true;
2121                 }
2122             }
2123         }
2124         return false;
2125     }
2126 
2127     /** Check that a given method conforms with any method it overrides.
2128      *  @param tree         The tree from which positions are extracted
2129      *                      for errors.
2130      *  @param m            The overriding method.
2131      */
2132     void checkOverride(Env<AttrContext> env, JCMethodDecl tree, MethodSymbol m) {
2133         ClassSymbol origin = (ClassSymbol)m.owner;
2134         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name)) {
2135             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
2136                 log.error(tree.pos(), Errors.EnumNoFinalize);
2137                 return;
2138             }
2139         }
2140         if (allowRecords && origin.isRecord()) {
2141             // let's find out if this is a user defined accessor in which case the @Override annotation is acceptable
2142             Optional<? extends RecordComponent> recordComponent = origin.getRecordComponents().stream()
2143                     .filter(rc -> rc.accessor == tree.sym && (rc.accessor.flags_field & GENERATED_MEMBER) == 0).findFirst();
2144             if (recordComponent.isPresent()) {
2145                 return;
2146             }
2147         }
2148 
2149         for (Type t = origin.type; t.hasTag(CLASS);
2150              t = types.supertype(t)) {
2151             if (t != origin.type) {
2152                 checkOverride(tree, t, origin, m);
2153             }
2154             for (Type t2 : types.interfaces(t)) {
2155                 checkOverride(tree, t2, origin, m);
2156             }
2157         }
2158 
2159         final boolean explicitOverride = m.attribute(syms.overrideType.tsym) != null;
2160         // Check if this method must override a super method due to being annotated with @Override
2161         // or by virtue of being a member of a diamond inferred anonymous class. Latter case is to
2162         // be treated "as if as they were annotated" with @Override.
2163         boolean mustOverride = explicitOverride ||
2164                 (env.info.isAnonymousDiamond && !m.isConstructor() && !m.isPrivate());
2165         if (mustOverride && !isOverrider(m)) {
2166             DiagnosticPosition pos = tree.pos();
2167             for (JCAnnotation a : tree.getModifiers().annotations) {
2168                 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2169                     pos = a.pos();
2170                     break;
2171                 }
2172             }
2173             log.error(pos,
2174                       explicitOverride ? (m.isStatic() ? Errors.StaticMethodsCannotBeAnnotatedWithOverride : Errors.MethodDoesNotOverrideSuperclass) :
2175                                 Errors.AnonymousDiamondMethodDoesNotOverrideSuperclass(Fragments.DiamondAnonymousMethodsImplicitlyOverride));
2176         }
2177     }
2178 
2179     void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
2180         TypeSymbol c = site.tsym;
2181         for (Symbol sym : c.members().getSymbolsByName(m.name)) {
2182             if (m.overrides(sym, origin, types, false)) {
2183                 if ((sym.flags() & ABSTRACT) == 0) {
2184                     checkOverride(tree, m, (MethodSymbol)sym, origin);
2185                 }
2186             }
2187         }
2188     }
2189 
2190     private Predicate<Symbol> equalsHasCodeFilter = s -> MethodSymbol.implementation_filter.test(s) &&
2191             (s.flags() & BAD_OVERRIDE) == 0;
2192 
2193     public void checkClassOverrideEqualsAndHashIfNeeded(DiagnosticPosition pos,
2194             ClassSymbol someClass) {
2195         /* At present, annotations cannot possibly have a method that is override
2196          * equivalent with Object.equals(Object) but in any case the condition is
2197          * fine for completeness.
2198          */
2199         if (someClass == (ClassSymbol)syms.objectType.tsym ||
2200             someClass.isInterface() || someClass.isEnum() ||
2201             (someClass.flags() & ANNOTATION) != 0 ||
2202             (someClass.flags() & ABSTRACT) != 0) return;
2203         //anonymous inner classes implementing interfaces need especial treatment
2204         if (someClass.isAnonymous()) {
2205             List<Type> interfaces =  types.interfaces(someClass.type);
2206             if (interfaces != null && !interfaces.isEmpty() &&
2207                 interfaces.head.tsym == syms.comparatorType.tsym) return;
2208         }
2209         checkClassOverrideEqualsAndHash(pos, someClass);
2210     }
2211 
2212     private void checkClassOverrideEqualsAndHash(DiagnosticPosition pos,
2213             ClassSymbol someClass) {
2214         if (lint.isEnabled(LintCategory.OVERRIDES)) {
2215             MethodSymbol equalsAtObject = (MethodSymbol)syms.objectType
2216                     .tsym.members().findFirst(names.equals);
2217             MethodSymbol hashCodeAtObject = (MethodSymbol)syms.objectType
2218                     .tsym.members().findFirst(names.hashCode);
2219             MethodSymbol equalsImpl = types.implementation(equalsAtObject,
2220                     someClass, false, equalsHasCodeFilter);
2221             boolean overridesEquals = equalsImpl != null &&
2222                                       equalsImpl.owner == someClass;
2223             boolean overridesHashCode = types.implementation(hashCodeAtObject,
2224                 someClass, false, equalsHasCodeFilter) != hashCodeAtObject;
2225 
2226             if (overridesEquals && !overridesHashCode) {
2227                 log.warning(LintCategory.OVERRIDES, pos,
2228                             Warnings.OverrideEqualsButNotHashcode(someClass));
2229             }
2230         }
2231     }
2232 
2233     public void checkModuleName (JCModuleDecl tree) {
2234         Name moduleName = tree.sym.name;
2235         Assert.checkNonNull(moduleName);
2236         if (lint.isEnabled(LintCategory.MODULE)) {
2237             JCExpression qualId = tree.qualId;
2238             while (qualId != null) {
2239                 Name componentName;
2240                 DiagnosticPosition pos;
2241                 switch (qualId.getTag()) {
2242                     case SELECT:
2243                         JCFieldAccess selectNode = ((JCFieldAccess) qualId);
2244                         componentName = selectNode.name;
2245                         pos = selectNode.pos();
2246                         qualId = selectNode.selected;
2247                         break;
2248                     case IDENT:
2249                         componentName = ((JCIdent) qualId).name;
2250                         pos = qualId.pos();
2251                         qualId = null;
2252                         break;
2253                     default:
2254                         throw new AssertionError("Unexpected qualified identifier: " + qualId.toString());
2255                 }
2256                 if (componentName != null) {
2257                     String moduleNameComponentString = componentName.toString();
2258                     int nameLength = moduleNameComponentString.length();
2259                     if (nameLength > 0 && Character.isDigit(moduleNameComponentString.charAt(nameLength - 1))) {
2260                         log.warning(Lint.LintCategory.MODULE, pos, Warnings.PoorChoiceForModuleName(componentName));
2261                     }
2262                 }
2263             }
2264         }
2265     }
2266 
2267     private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
2268         ClashFilter cf = new ClashFilter(origin.type);
2269         return (cf.test(s1) &&
2270                 cf.test(s2) &&
2271                 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
2272     }
2273 
2274 
2275     /** Check that all abstract members of given class have definitions.
2276      *  @param pos          Position to be used for error reporting.
2277      *  @param c            The class.
2278      */
2279     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
2280         MethodSymbol undef = types.firstUnimplementedAbstract(c);
2281         if (undef != null) {
2282             MethodSymbol undef1 =
2283                 new MethodSymbol(undef.flags(), undef.name,
2284                                  types.memberType(c.type, undef), undef.owner);
2285             log.error(pos,
2286                       Errors.DoesNotOverrideAbstract(c, undef1, undef1.location()));
2287         }
2288     }
2289 
2290     void checkNonCyclicDecl(JCClassDecl tree) {
2291         CycleChecker cc = new CycleChecker();
2292         cc.scan(tree);
2293         if (!cc.errorFound && !cc.partialCheck) {
2294             tree.sym.flags_field |= ACYCLIC;
2295         }
2296     }
2297 
2298     class CycleChecker extends TreeScanner {
2299 
2300         Set<Symbol> seenClasses = new HashSet<>();
2301         boolean errorFound = false;
2302         boolean partialCheck = false;
2303 
2304         private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
2305             if (sym != null && sym.kind == TYP) {
2306                 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
2307                 if (classEnv != null) {
2308                     DiagnosticSource prevSource = log.currentSource();
2309                     try {
2310                         log.useSource(classEnv.toplevel.sourcefile);
2311                         scan(classEnv.tree);
2312                     }
2313                     finally {
2314                         log.useSource(prevSource.getFile());
2315                     }
2316                 } else if (sym.kind == TYP) {
2317                     checkClass(pos, sym, List.nil());
2318                 }
2319             } else if (sym == null || sym.kind != PCK) {
2320                 //not completed yet
2321                 partialCheck = true;
2322             }
2323         }
2324 
2325         @Override
2326         public void visitSelect(JCFieldAccess tree) {
2327             super.visitSelect(tree);
2328             checkSymbol(tree.pos(), tree.sym);
2329         }
2330 
2331         @Override
2332         public void visitIdent(JCIdent tree) {
2333             checkSymbol(tree.pos(), tree.sym);
2334         }
2335 
2336         @Override
2337         public void visitTypeApply(JCTypeApply tree) {
2338             scan(tree.clazz);
2339         }
2340 
2341         @Override
2342         public void visitTypeArray(JCArrayTypeTree tree) {
2343             scan(tree.elemtype);
2344         }
2345 
2346         @Override
2347         public void visitClassDef(JCClassDecl tree) {
2348             List<JCTree> supertypes = List.nil();
2349             if (tree.getExtendsClause() != null) {
2350                 supertypes = supertypes.prepend(tree.getExtendsClause());
2351             }
2352             if (tree.getImplementsClause() != null) {
2353                 for (JCTree intf : tree.getImplementsClause()) {
2354                     supertypes = supertypes.prepend(intf);
2355                 }
2356             }
2357             checkClass(tree.pos(), tree.sym, supertypes);
2358         }
2359 
2360         void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
2361             if ((c.flags_field & ACYCLIC) != 0)
2362                 return;
2363             if (seenClasses.contains(c)) {
2364                 errorFound = true;
2365                 noteCyclic(pos, (ClassSymbol)c);
2366             } else if (!c.type.isErroneous()) {
2367                 try {
2368                     seenClasses.add(c);
2369                     if (c.type.hasTag(CLASS)) {
2370                         if (supertypes.nonEmpty()) {
2371                             scan(supertypes);
2372                         }
2373                         else {
2374                             ClassType ct = (ClassType)c.type;
2375                             if (ct.supertype_field == null ||
2376                                     ct.interfaces_field == null) {
2377                                 //not completed yet
2378                                 partialCheck = true;
2379                                 return;
2380                             }
2381                             checkSymbol(pos, ct.supertype_field.tsym);
2382                             for (Type intf : ct.interfaces_field) {
2383                                 checkSymbol(pos, intf.tsym);
2384                             }
2385                         }
2386                         if (c.owner.kind == TYP) {
2387                             checkSymbol(pos, c.owner);
2388                         }
2389                     }
2390                 } finally {
2391                     seenClasses.remove(c);
2392                 }
2393             }
2394         }
2395     }
2396 
2397     /** Check for cyclic references. Issue an error if the
2398      *  symbol of the type referred to has a LOCKED flag set.
2399      *
2400      *  @param pos      Position to be used for error reporting.
2401      *  @param t        The type referred to.
2402      */
2403     void checkNonCyclic(DiagnosticPosition pos, Type t) {
2404         checkNonCyclicInternal(pos, t);
2405     }
2406 
2407 
2408     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
2409         checkNonCyclic1(pos, t, List.nil());
2410     }
2411 
2412     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
2413         final TypeVar tv;
2414         if  (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
2415             return;
2416         if (seen.contains(t)) {
2417             tv = (TypeVar)t;
2418             tv.setUpperBound(types.createErrorType(t));
2419             log.error(pos, Errors.CyclicInheritance(t));
2420         } else if (t.hasTag(TYPEVAR)) {
2421             tv = (TypeVar)t;
2422             seen = seen.prepend(tv);
2423             for (Type b : types.getBounds(tv))
2424                 checkNonCyclic1(pos, b, seen);
2425         }
2426     }
2427 
2428     /** Check for cyclic references. Issue an error if the
2429      *  symbol of the type referred to has a LOCKED flag set.
2430      *
2431      *  @param pos      Position to be used for error reporting.
2432      *  @param t        The type referred to.
2433      *  @returns        True if the check completed on all attributed classes
2434      */
2435     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
2436         boolean complete = true; // was the check complete?
2437         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
2438         Symbol c = t.tsym;
2439         if ((c.flags_field & ACYCLIC) != 0) return true;
2440 
2441         if ((c.flags_field & LOCKED) != 0) {
2442             noteCyclic(pos, (ClassSymbol)c);
2443         } else if (!c.type.isErroneous()) {
2444             try {
2445                 c.flags_field |= LOCKED;
2446                 if (c.type.hasTag(CLASS)) {
2447                     ClassType clazz = (ClassType)c.type;
2448                     if (clazz.interfaces_field != null)
2449                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
2450                             complete &= checkNonCyclicInternal(pos, l.head);
2451                     if (clazz.supertype_field != null) {
2452                         Type st = clazz.supertype_field;
2453                         if (st != null && st.hasTag(CLASS))
2454                             complete &= checkNonCyclicInternal(pos, st);
2455                     }
2456                     if (c.owner.kind == TYP)
2457                         complete &= checkNonCyclicInternal(pos, c.owner.type);
2458                 }
2459             } finally {
2460                 c.flags_field &= ~LOCKED;
2461             }
2462         }
2463         if (complete)
2464             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.isCompleted();
2465         if (complete) c.flags_field |= ACYCLIC;
2466         return complete;
2467     }
2468 
2469     /** Note that we found an inheritance cycle. */
2470     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
2471         log.error(pos, Errors.CyclicInheritance(c));
2472         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
2473             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
2474         Type st = types.supertype(c.type);
2475         if (st.hasTag(CLASS))
2476             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
2477         c.type = types.createErrorType(c, c.type);
2478         c.flags_field |= ACYCLIC;
2479     }
2480 
2481     /** Check that all methods which implement some
2482      *  method conform to the method they implement.
2483      *  @param tree         The class definition whose members are checked.
2484      */
2485     void checkImplementations(JCClassDecl tree) {
2486         checkImplementations(tree, tree.sym, tree.sym);
2487     }
2488     //where
2489         /** Check that all methods which implement some
2490          *  method in `ic' conform to the method they implement.
2491          */
2492         void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
2493             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
2494                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
2495                 if ((lc.flags() & ABSTRACT) != 0) {
2496                     for (Symbol sym : lc.members().getSymbols(NON_RECURSIVE)) {
2497                         if (sym.kind == MTH &&
2498                             (sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
2499                             MethodSymbol absmeth = (MethodSymbol)sym;
2500                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
2501                             if (implmeth != null && implmeth != absmeth &&
2502                                 (implmeth.owner.flags() & INTERFACE) ==
2503                                 (origin.flags() & INTERFACE)) {
2504                                 // don't check if implmeth is in a class, yet
2505                                 // origin is an interface. This case arises only
2506                                 // if implmeth is declared in Object. The reason is
2507                                 // that interfaces really don't inherit from
2508                                 // Object it's just that the compiler represents
2509                                 // things that way.
2510                                 checkOverride(tree, implmeth, absmeth, origin);
2511                             }
2512                         }
2513                     }
2514                 }
2515             }
2516         }
2517 
2518     /** Check that all abstract methods implemented by a class are
2519      *  mutually compatible.
2520      *  @param pos          Position to be used for error reporting.
2521      *  @param c            The class whose interfaces are checked.
2522      */
2523     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2524         List<Type> supertypes = types.interfaces(c);
2525         Type supertype = types.supertype(c);
2526         if (supertype.hasTag(CLASS) &&
2527             (supertype.tsym.flags() & ABSTRACT) != 0)
2528             supertypes = supertypes.prepend(supertype);
2529         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2530             if (!l.head.getTypeArguments().isEmpty() &&
2531                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2532                 return;
2533             for (List<Type> m = supertypes; m != l; m = m.tail)
2534                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2535                     return;
2536         }
2537         checkCompatibleConcretes(pos, c);
2538     }
2539 
2540     /** Check that all non-override equivalent methods accessible from 'site'
2541      *  are mutually compatible (JLS 8.4.8/9.4.1).
2542      *
2543      *  @param pos  Position to be used for error reporting.
2544      *  @param site The class whose methods are checked.
2545      *  @param sym  The method symbol to be checked.
2546      */
2547     void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2548          ClashFilter cf = new ClashFilter(site);
2549         //for each method m1 that is overridden (directly or indirectly)
2550         //by method 'sym' in 'site'...
2551 
2552         List<MethodSymbol> potentiallyAmbiguousList = List.nil();
2553         boolean overridesAny = false;
2554         ArrayList<Symbol> symbolsByName = new ArrayList<>();
2555         types.membersClosure(site, false).getSymbolsByName(sym.name, cf).forEach(symbolsByName::add);
2556         for (Symbol m1 : symbolsByName) {
2557             if (!sym.overrides(m1, site.tsym, types, false)) {
2558                 if (m1 == sym) {
2559                     continue;
2560                 }
2561 
2562                 if (!overridesAny) {
2563                     potentiallyAmbiguousList = potentiallyAmbiguousList.prepend((MethodSymbol)m1);
2564                 }
2565                 continue;
2566             }
2567 
2568             if (m1 != sym) {
2569                 overridesAny = true;
2570                 potentiallyAmbiguousList = List.nil();
2571             }
2572 
2573             //...check each method m2 that is a member of 'site'
2574             for (Symbol m2 : symbolsByName) {
2575                 if (m2 == m1) continue;
2576                 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2577                 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
2578                 if (!types.isSubSignature(sym.type, types.memberType(site, m2)) &&
2579                         types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
2580                     sym.flags_field |= CLASH;
2581                     if (m1 == sym) {
2582                         log.error(pos, Errors.NameClashSameErasureNoOverride(
2583                             m1.name, types.memberType(site, m1).asMethodType().getParameterTypes(), m1.location(),
2584                             m2.name, types.memberType(site, m2).asMethodType().getParameterTypes(), m2.location()));
2585                     } else {
2586                         ClassType ct = (ClassType)site;
2587                         String kind = ct.isInterface() ? "interface" : "class";
2588                         log.error(pos, Errors.NameClashSameErasureNoOverride1(
2589                             kind,
2590                             ct.tsym.name,
2591                             m1.name,
2592                             types.memberType(site, m1).asMethodType().getParameterTypes(),
2593                             m1.location(),
2594                             m2.name,
2595                             types.memberType(site, m2).asMethodType().getParameterTypes(),
2596                             m2.location()));
2597                     }
2598                     return;
2599                 }
2600             }
2601         }
2602 
2603         if (!overridesAny) {
2604             for (MethodSymbol m: potentiallyAmbiguousList) {
2605                 checkPotentiallyAmbiguousOverloads(pos, site, sym, m);
2606             }
2607         }
2608     }
2609 
2610     /** Check that all static methods accessible from 'site' are
2611      *  mutually compatible (JLS 8.4.8).
2612      *
2613      *  @param pos  Position to be used for error reporting.
2614      *  @param site The class whose methods are checked.
2615      *  @param sym  The method symbol to be checked.
2616      */
2617     void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2618         ClashFilter cf = new ClashFilter(site);
2619         //for each method m1 that is a member of 'site'...
2620         for (Symbol s : types.membersClosure(site, true).getSymbolsByName(sym.name, cf)) {
2621             //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2622             //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
2623             if (!types.isSubSignature(sym.type, types.memberType(site, s))) {
2624                 if (types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
2625                     log.error(pos,
2626                               Errors.NameClashSameErasureNoHide(sym, sym.location(), s, s.location()));
2627                     return;
2628                 } else {
2629                     checkPotentiallyAmbiguousOverloads(pos, site, sym, (MethodSymbol)s);
2630                 }
2631             }
2632          }
2633      }
2634 
2635      //where
2636      private class ClashFilter implements Predicate<Symbol> {
2637 
2638          Type site;
2639 
2640          ClashFilter(Type site) {
2641              this.site = site;
2642          }
2643 
2644          boolean shouldSkip(Symbol s) {
2645              return (s.flags() & CLASH) != 0 &&
2646                 s.owner == site.tsym;
2647          }
2648 
2649          @Override
2650          public boolean test(Symbol s) {
2651              return s.kind == MTH &&
2652                      (s.flags() & SYNTHETIC) == 0 &&
2653                      !shouldSkip(s) &&
2654                      s.isInheritedIn(site.tsym, types) &&
2655                      !s.isConstructor();
2656          }
2657      }
2658 
2659     void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
2660         DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
2661         for (Symbol m : types.membersClosure(site, false).getSymbols(dcf)) {
2662             Assert.check(m.kind == MTH);
2663             List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
2664             if (prov.size() > 1) {
2665                 ListBuffer<Symbol> abstracts = new ListBuffer<>();
2666                 ListBuffer<Symbol> defaults = new ListBuffer<>();
2667                 for (MethodSymbol provSym : prov) {
2668                     if ((provSym.flags() & DEFAULT) != 0) {
2669                         defaults = defaults.append(provSym);
2670                     } else if ((provSym.flags() & ABSTRACT) != 0) {
2671                         abstracts = abstracts.append(provSym);
2672                     }
2673                     if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
2674                         //strong semantics - issue an error if two sibling interfaces
2675                         //have two override-equivalent defaults - or if one is abstract
2676                         //and the other is default
2677                         Fragment diagKey;
2678                         Symbol s1 = defaults.first();
2679                         Symbol s2;
2680                         if (defaults.size() > 1) {
2681                             s2 = defaults.toList().tail.head;
2682                             diagKey = Fragments.IncompatibleUnrelatedDefaults(Kinds.kindName(site.tsym), site,
2683                                     m.name, types.memberType(site, m).getParameterTypes(),
2684                                     s1.location(), s2.location());
2685 
2686                         } else {
2687                             s2 = abstracts.first();
2688                             diagKey = Fragments.IncompatibleAbstractDefault(Kinds.kindName(site.tsym), site,
2689                                     m.name, types.memberType(site, m).getParameterTypes(),
2690                                     s1.location(), s2.location());
2691                         }
2692                         log.error(pos, Errors.TypesIncompatible(s1.location().type, s2.location().type, diagKey));
2693                         break;
2694                     }
2695                 }
2696             }
2697         }
2698     }
2699 
2700     //where
2701      private class DefaultMethodClashFilter implements Predicate<Symbol> {
2702 
2703          Type site;
2704 
2705          DefaultMethodClashFilter(Type site) {
2706              this.site = site;
2707          }
2708 
2709          @Override
2710          public boolean test(Symbol s) {
2711              return s.kind == MTH &&
2712                      (s.flags() & DEFAULT) != 0 &&
2713                      s.isInheritedIn(site.tsym, types) &&
2714                      !s.isConstructor();
2715          }
2716      }
2717 
2718     /**
2719       * Report warnings for potentially ambiguous method declarations. Two declarations
2720       * are potentially ambiguous if they feature two unrelated functional interface
2721       * in same argument position (in which case, a call site passing an implicit
2722       * lambda would be ambiguous).
2723       */
2724     void checkPotentiallyAmbiguousOverloads(DiagnosticPosition pos, Type site,
2725             MethodSymbol msym1, MethodSymbol msym2) {
2726         if (msym1 != msym2 &&
2727                 lint.isEnabled(LintCategory.OVERLOADS) &&
2728                 (msym1.flags() & POTENTIALLY_AMBIGUOUS) == 0 &&
2729                 (msym2.flags() & POTENTIALLY_AMBIGUOUS) == 0) {
2730             Type mt1 = types.memberType(site, msym1);
2731             Type mt2 = types.memberType(site, msym2);
2732             //if both generic methods, adjust type variables
2733             if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL) &&
2734                     types.hasSameBounds((ForAll)mt1, (ForAll)mt2)) {
2735                 mt2 = types.subst(mt2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars);
2736             }
2737             //expand varargs methods if needed
2738             int maxLength = Math.max(mt1.getParameterTypes().length(), mt2.getParameterTypes().length());
2739             List<Type> args1 = rs.adjustArgs(mt1.getParameterTypes(), msym1, maxLength, true);
2740             List<Type> args2 = rs.adjustArgs(mt2.getParameterTypes(), msym2, maxLength, true);
2741             //if arities don't match, exit
2742             if (args1.length() != args2.length()) return;
2743             boolean potentiallyAmbiguous = false;
2744             while (args1.nonEmpty() && args2.nonEmpty()) {
2745                 Type s = args1.head;
2746                 Type t = args2.head;
2747                 if (!types.isSubtype(t, s) && !types.isSubtype(s, t)) {
2748                     if (types.isFunctionalInterface(s) && types.isFunctionalInterface(t) &&
2749                             types.findDescriptorType(s).getParameterTypes().length() > 0 &&
2750                             types.findDescriptorType(s).getParameterTypes().length() ==
2751                             types.findDescriptorType(t).getParameterTypes().length()) {
2752                         potentiallyAmbiguous = true;
2753                     } else {
2754                         return;
2755                     }
2756                 }
2757                 args1 = args1.tail;
2758                 args2 = args2.tail;
2759             }
2760             if (potentiallyAmbiguous) {
2761                 //we found two incompatible functional interfaces with same arity
2762                 //this means a call site passing an implicit lambda would be ambiguous
2763                 msym1.flags_field |= POTENTIALLY_AMBIGUOUS;
2764                 msym2.flags_field |= POTENTIALLY_AMBIGUOUS;
2765                 log.warning(LintCategory.OVERLOADS, pos,
2766                             Warnings.PotentiallyAmbiguousOverload(msym1, msym1.location(),
2767                                                                   msym2, msym2.location()));
2768                 return;
2769             }
2770         }
2771     }
2772 
2773     void checkAccessFromSerializableElement(final JCTree tree, boolean isLambda) {
2774         if (warnOnAnyAccessToMembers ||
2775             (lint.isEnabled(LintCategory.SERIAL) &&
2776             !lint.isSuppressed(LintCategory.SERIAL) &&
2777             isLambda)) {
2778             Symbol sym = TreeInfo.symbol(tree);
2779             if (!sym.kind.matches(KindSelector.VAL_MTH)) {
2780                 return;
2781             }
2782 
2783             if (sym.kind == VAR) {
2784                 if ((sym.flags() & PARAMETER) != 0 ||
2785                     sym.isDirectlyOrIndirectlyLocal() ||
2786                     sym.name == names._this ||
2787                     sym.name == names._super) {
2788                     return;
2789                 }
2790             }
2791 
2792             if (!types.isSubtype(sym.owner.type, syms.serializableType) &&
2793                 isEffectivelyNonPublic(sym)) {
2794                 if (isLambda) {
2795                     if (belongsToRestrictedPackage(sym)) {
2796                         log.warning(LintCategory.SERIAL, tree.pos(),
2797                                     Warnings.AccessToMemberFromSerializableLambda(sym));
2798                     }
2799                 } else {
2800                     log.warning(tree.pos(),
2801                                 Warnings.AccessToMemberFromSerializableElement(sym));
2802                 }
2803             }
2804         }
2805     }
2806 
2807     private boolean isEffectivelyNonPublic(Symbol sym) {
2808         if (sym.packge() == syms.rootPackage) {
2809             return false;
2810         }
2811 
2812         while (sym.kind != PCK) {
2813             if ((sym.flags() & PUBLIC) == 0) {
2814                 return true;
2815             }
2816             sym = sym.owner;
2817         }
2818         return false;
2819     }
2820 
2821     private boolean belongsToRestrictedPackage(Symbol sym) {
2822         String fullName = sym.packge().fullname.toString();
2823         return fullName.startsWith("java.") ||
2824                 fullName.startsWith("javax.") ||
2825                 fullName.startsWith("sun.") ||
2826                 fullName.contains(".internal.");
2827     }
2828 
2829     /** Check that class c does not implement directly or indirectly
2830      *  the same parameterized interface with two different argument lists.
2831      *  @param pos          Position to be used for error reporting.
2832      *  @param type         The type whose interfaces are checked.
2833      */
2834     void checkClassBounds(DiagnosticPosition pos, Type type) {
2835         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
2836     }
2837 //where
2838         /** Enter all interfaces of type `type' into the hash table `seensofar'
2839          *  with their class symbol as key and their type as value. Make
2840          *  sure no class is entered with two different types.
2841          */
2842         void checkClassBounds(DiagnosticPosition pos,
2843                               Map<TypeSymbol,Type> seensofar,
2844                               Type type) {
2845             if (type.isErroneous()) return;
2846             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
2847                 Type it = l.head;
2848                 if (type.hasTag(CLASS) && !it.hasTag(CLASS)) continue; // JLS 8.1.5
2849 
2850                 Type oldit = seensofar.put(it.tsym, it);
2851                 if (oldit != null) {
2852                     List<Type> oldparams = oldit.allparams();
2853                     List<Type> newparams = it.allparams();
2854                     if (!types.containsTypeEquivalent(oldparams, newparams))
2855                         log.error(pos,
2856                                   Errors.CantInheritDiffArg(it.tsym,
2857                                                             Type.toString(oldparams),
2858                                                             Type.toString(newparams)));
2859                 }
2860                 checkClassBounds(pos, seensofar, it);
2861             }
2862             Type st = types.supertype(type);
2863             if (type.hasTag(CLASS) && !st.hasTag(CLASS)) return; // JLS 8.1.4
2864             if (st != Type.noType) checkClassBounds(pos, seensofar, st);
2865         }
2866 
2867     /** Enter interface into into set.
2868      *  If it existed already, issue a "repeated interface" error.
2869      */
2870     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
2871         if (its.contains(it))
2872             log.error(pos, Errors.RepeatedInterface);
2873         else {
2874             its.add(it);
2875         }
2876     }
2877 
2878 /* *************************************************************************
2879  * Check annotations
2880  **************************************************************************/
2881 
2882     /**
2883      * Recursively validate annotations values
2884      */
2885     void validateAnnotationTree(JCTree tree) {
2886         class AnnotationValidator extends TreeScanner {
2887             @Override
2888             public void visitAnnotation(JCAnnotation tree) {
2889                 if (!tree.type.isErroneous() && tree.type.tsym.isAnnotationType()) {
2890                     super.visitAnnotation(tree);
2891                     validateAnnotation(tree);
2892                 }
2893             }
2894         }
2895         tree.accept(new AnnotationValidator());
2896     }
2897 
2898     /**
2899      *  {@literal
2900      *  Annotation types are restricted to primitives, String, an
2901      *  enum, an annotation, Class, Class<?>, Class<? extends
2902      *  Anything>, arrays of the preceding.
2903      *  }
2904      */
2905     void validateAnnotationType(JCTree restype) {
2906         // restype may be null if an error occurred, so don't bother validating it
2907         if (restype != null) {
2908             validateAnnotationType(restype.pos(), restype.type);
2909         }
2910     }
2911 
2912     void validateAnnotationType(DiagnosticPosition pos, Type type) {
2913         if (type.isPrimitive()) return;
2914         if (types.isSameType(type, syms.stringType)) return;
2915         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
2916         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
2917         if (types.cvarLowerBound(type).tsym == syms.classType.tsym) return;
2918         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
2919             validateAnnotationType(pos, types.elemtype(type));
2920             return;
2921         }
2922         log.error(pos, Errors.InvalidAnnotationMemberType);
2923     }
2924 
2925     /**
2926      * "It is also a compile-time error if any method declared in an
2927      * annotation type has a signature that is override-equivalent to
2928      * that of any public or protected method declared in class Object
2929      * or in the interface annotation.Annotation."
2930      *
2931      * @jls 9.6 Annotation Types
2932      */
2933     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
2934         for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
2935             Scope s = sup.tsym.members();
2936             for (Symbol sym : s.getSymbolsByName(m.name)) {
2937                 if (sym.kind == MTH &&
2938                     (sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
2939                     types.overrideEquivalent(m.type, sym.type))
2940                     log.error(pos, Errors.IntfAnnotationMemberClash(sym, sup));
2941             }
2942         }
2943     }
2944 
2945     /** Check the annotations of a symbol.
2946      */
2947     public void validateAnnotations(List<JCAnnotation> annotations, JCTree declarationTree, Symbol s) {
2948         for (JCAnnotation a : annotations)
2949             validateAnnotation(a, declarationTree, s);
2950     }
2951 
2952     /** Check the type annotations.
2953      */
2954     public void validateTypeAnnotations(List<JCAnnotation> annotations, boolean isTypeParameter) {
2955         for (JCAnnotation a : annotations)
2956             validateTypeAnnotation(a, isTypeParameter);
2957     }
2958 
2959     /** Check an annotation of a symbol.
2960      */
2961     private void validateAnnotation(JCAnnotation a, JCTree declarationTree, Symbol s) {
2962         /** NOTE: if annotation processors are present, annotation processing rounds can happen after this method,
2963          *  this can impact in particular records for which annotations are forcibly propagated.
2964          */
2965         validateAnnotationTree(a);
2966         boolean isRecordMember = ((s.flags_field & RECORD) != 0 || s.enclClass() != null && s.enclClass().isRecord());
2967 
2968         boolean isRecordField = (s.flags_field & RECORD) != 0 &&
2969                 declarationTree.hasTag(VARDEF) &&
2970                 s.owner.kind == TYP;
2971 
2972         if (isRecordField) {
2973             // first we need to check if the annotation is applicable to records
2974             Name[] targets = getTargetNames(a);
2975             boolean appliesToRecords = false;
2976             for (Name target : targets) {
2977                 appliesToRecords =
2978                                 target == names.FIELD ||
2979                                 target == names.PARAMETER ||
2980                                 target == names.METHOD ||
2981                                 target == names.TYPE_USE ||
2982                                 target == names.RECORD_COMPONENT;
2983                 if (appliesToRecords) {
2984                     break;
2985                 }
2986             }
2987             if (!appliesToRecords) {
2988                 log.error(a.pos(), Errors.AnnotationTypeNotApplicable);
2989             } else {
2990                 /* lets now find the annotations in the field that are targeted to record components and append them to
2991                  * the corresponding record component
2992                  */
2993                 ClassSymbol recordClass = (ClassSymbol) s.owner;
2994                 RecordComponent rc = recordClass.getRecordComponent((VarSymbol)s);
2995                 SymbolMetadata metadata = rc.getMetadata();
2996                 if (metadata == null || metadata.isEmpty()) {
2997                     /* if not is empty then we have already been here, which is the case if multiple annotations are applied
2998                      * to the record component declaration
2999                      */
3000                     rc.appendAttributes(s.getRawAttributes().stream().filter(anno ->
3001                             Arrays.stream(getTargetNames(anno.type.tsym)).anyMatch(name -> name == names.RECORD_COMPONENT)
3002                     ).collect(List.collector()));
3003                     rc.setTypeAttributes(s.getRawTypeAttributes());
3004                     // to get all the type annotations applied to the type
3005                     rc.type = s.type;
3006                 }
3007             }
3008         }
3009 
3010         /* the section below is tricky. Annotations applied to record components are propagated to the corresponding
3011          * record member so if an annotation has target: FIELD, it is propagated to the corresponding FIELD, if it has
3012          * target METHOD, it is propagated to the accessor and so on. But at the moment when method members are generated
3013          * there is no enough information to propagate only the right annotations. So all the annotations are propagated
3014          * to all the possible locations.
3015          *
3016          * At this point we need to remove all the annotations that are not in place before going on with the annotation
3017          * party. On top of the above there is the issue that there is no AST representing record components, just symbols
3018          * so the corresponding field has been holding all the annotations and it's metadata has been modified as if it
3019          * was both a field and a record component.
3020          *
3021          * So there are two places where we need to trim annotations from: the metadata of the symbol and / or the modifiers
3022          * in the AST. Whatever is in the metadata will be written to the class file, whatever is in the modifiers could
3023          * be see by annotation processors.
3024          *
3025          * The metadata contains both type annotations and declaration annotations. At this point of the game we don't
3026          * need to care about type annotations, they are all in the right place. But we could need to remove declaration
3027          * annotations. So for declaration annotations if they are not applicable to the record member, excluding type
3028          * annotations which are already correct, then we will remove it. For the AST modifiers if the annotation is not
3029          * applicable either as type annotation and or declaration annotation, only in that case it will be removed.
3030          *
3031          * So it could be that annotation is removed as a declaration annotation but it is kept in the AST modifier for
3032          * further inspection by annotation processors.
3033          *
3034          * For example:
3035          *
3036          *     import java.lang.annotation.*;
3037          *
3038          *     @Target({ElementType.TYPE_USE, ElementType.RECORD_COMPONENT})
3039          *     @Retention(RetentionPolicy.RUNTIME)
3040          *     @interface Anno { }
3041          *
3042          *     record R(@Anno String s) {}
3043          *
3044          * at this point we will have for the case of the generated field:
3045          *   - @Anno in the modifier
3046          *   - @Anno as a type annotation
3047          *   - @Anno as a declaration annotation
3048          *
3049          * the last one should be removed because the annotation has not FIELD as target but it was applied as a
3050          * declaration annotation because the field was being treated both as a field and as a record component
3051          * as we have already copied the annotations to the record component, now the field doesn't need to hold
3052          * annotations that are not intended for it anymore. Still @Anno has to be kept in the AST's modifiers as it
3053          * is applicable as a type annotation to the type of the field.
3054          */
3055 
3056         if (a.type.tsym.isAnnotationType()) {
3057             Optional<Set<Name>> applicableTargetsOp = getApplicableTargets(a, s);
3058             if (!applicableTargetsOp.isEmpty()) {
3059                 Set<Name> applicableTargets = applicableTargetsOp.get();
3060                 boolean notApplicableOrIsTypeUseOnly = applicableTargets.isEmpty() ||
3061                         applicableTargets.size() == 1 && applicableTargets.contains(names.TYPE_USE);
3062                 boolean isCompGeneratedRecordElement = isRecordMember && (s.flags_field & Flags.GENERATED_MEMBER) != 0;
3063                 boolean isCompRecordElementWithNonApplicableDeclAnno = isCompGeneratedRecordElement && notApplicableOrIsTypeUseOnly;
3064 
3065                 if (applicableTargets.isEmpty() || isCompRecordElementWithNonApplicableDeclAnno) {
3066                     if (isCompRecordElementWithNonApplicableDeclAnno) {
3067                             /* so we have found an annotation that is not applicable to a record member that was generated by the
3068                              * compiler. This was intentionally done at TypeEnter, now is the moment strip away the annotations
3069                              * that are not applicable to the given record member
3070                              */
3071                         JCModifiers modifiers = TreeInfo.getModifiers(declarationTree);
3072                             /* lets first remove the annotation from the modifier if it is not applicable, we have to check again as
3073                              * it could be a type annotation
3074                              */
3075                         if (modifiers != null && applicableTargets.isEmpty()) {
3076                             ListBuffer<JCAnnotation> newAnnotations = new ListBuffer<>();
3077                             for (JCAnnotation anno : modifiers.annotations) {
3078                                 if (anno != a) {
3079                                     newAnnotations.add(anno);
3080                                 }
3081                             }
3082                             modifiers.annotations = newAnnotations.toList();
3083                         }
3084                         // now lets remove it from the symbol
3085                         s.getMetadata().removeDeclarationMetadata(a.attribute);
3086                     } else {
3087                         log.error(a.pos(), Errors.AnnotationTypeNotApplicable);
3088                     }
3089                 }
3090                 /* if we are seeing the @SafeVarargs annotation applied to a compiler generated accessor,
3091                  * then this is an error as we know that no compiler generated accessor will be a varargs
3092                  * method, better to fail asap
3093                  */
3094                 if (isCompGeneratedRecordElement && !isRecordField && a.type.tsym == syms.trustMeType.tsym && declarationTree.hasTag(METHODDEF)) {
3095                     log.error(a.pos(), Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym, Fragments.VarargsTrustmeOnNonVarargsAccessor(s)));
3096                 }
3097             }
3098         }
3099 
3100         if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
3101             if (s.kind != TYP) {
3102                 log.error(a.pos(), Errors.BadFunctionalIntfAnno);
3103             } else if (!s.isInterface() || (s.flags() & ANNOTATION) != 0) {
3104                 log.error(a.pos(), Errors.BadFunctionalIntfAnno1(Fragments.NotAFunctionalIntf(s)));
3105             }
3106         }
3107     }
3108 
3109     public void validateTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
3110         Assert.checkNonNull(a.type);
3111         validateAnnotationTree(a);
3112 
3113         if (a.hasTag(TYPE_ANNOTATION) &&
3114                 !a.annotationType.type.isErroneous() &&
3115                 !isTypeAnnotation(a, isTypeParameter)) {
3116             log.error(a.pos(), Errors.AnnotationTypeNotApplicableToType(a.type));
3117         }
3118     }
3119 
3120     /**
3121      * Validate the proposed container 'repeatable' on the
3122      * annotation type symbol 's'. Report errors at position
3123      * 'pos'.
3124      *
3125      * @param s The (annotation)type declaration annotated with a @Repeatable
3126      * @param repeatable the @Repeatable on 's'
3127      * @param pos where to report errors
3128      */
3129     public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
3130         Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
3131 
3132         Type t = null;
3133         List<Pair<MethodSymbol,Attribute>> l = repeatable.values;
3134         if (!l.isEmpty()) {
3135             Assert.check(l.head.fst.name == names.value);
3136             if (l.head.snd instanceof Attribute.Class) {
3137                 t = ((Attribute.Class)l.head.snd).getValue();
3138             }
3139         }
3140 
3141         if (t == null) {
3142             // errors should already have been reported during Annotate
3143             return;
3144         }
3145 
3146         validateValue(t.tsym, s, pos);
3147         validateRetention(t.tsym, s, pos);
3148         validateDocumented(t.tsym, s, pos);
3149         validateInherited(t.tsym, s, pos);
3150         validateTarget(t.tsym, s, pos);
3151         validateDefault(t.tsym, pos);
3152     }
3153 
3154     private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
3155         Symbol sym = container.members().findFirst(names.value);
3156         if (sym != null && sym.kind == MTH) {
3157             MethodSymbol m = (MethodSymbol) sym;
3158             Type ret = m.getReturnType();
3159             if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
3160                 log.error(pos,
3161                           Errors.InvalidRepeatableAnnotationValueReturn(container,
3162                                                                         ret,
3163                                                                         types.makeArrayType(contained.type)));
3164             }
3165         } else {
3166             log.error(pos, Errors.InvalidRepeatableAnnotationNoValue(container));
3167         }
3168     }
3169 
3170     private void validateRetention(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
3171         Attribute.RetentionPolicy containerRetention = types.getRetention(container);
3172         Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
3173 
3174         boolean error = false;
3175         switch (containedRetention) {
3176         case RUNTIME:
3177             if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
3178                 error = true;
3179             }
3180             break;
3181         case CLASS:
3182             if (containerRetention == Attribute.RetentionPolicy.SOURCE)  {
3183                 error = true;
3184             }
3185         }
3186         if (error ) {
3187             log.error(pos,
3188                       Errors.InvalidRepeatableAnnotationRetention(container,
3189                                                                   containerRetention.name(),
3190                                                                   contained,
3191                                                                   containedRetention.name()));
3192         }
3193     }
3194 
3195     private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
3196         if (contained.attribute(syms.documentedType.tsym) != null) {
3197             if (container.attribute(syms.documentedType.tsym) == null) {
3198                 log.error(pos, Errors.InvalidRepeatableAnnotationNotDocumented(container, contained));
3199             }
3200         }
3201     }
3202 
3203     private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
3204         if (contained.attribute(syms.inheritedType.tsym) != null) {
3205             if (container.attribute(syms.inheritedType.tsym) == null) {
3206                 log.error(pos, Errors.InvalidRepeatableAnnotationNotInherited(container, contained));
3207             }
3208         }
3209     }
3210 
3211     private void validateTarget(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
3212         // The set of targets the container is applicable to must be a subset
3213         // (with respect to annotation target semantics) of the set of targets
3214         // the contained is applicable to. The target sets may be implicit or
3215         // explicit.
3216 
3217         Set<Name> containerTargets;
3218         Attribute.Array containerTarget = getAttributeTargetAttribute(container);
3219         if (containerTarget == null) {
3220             containerTargets = getDefaultTargetSet();
3221         } else {
3222             containerTargets = new HashSet<>();
3223             for (Attribute app : containerTarget.values) {
3224                 if (!(app instanceof Attribute.Enum attributeEnum)) {
3225                     continue; // recovery
3226                 }
3227                 containerTargets.add(attributeEnum.value.name);
3228             }
3229         }
3230 
3231         Set<Name> containedTargets;
3232         Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
3233         if (containedTarget == null) {
3234             containedTargets = getDefaultTargetSet();
3235         } else {
3236             containedTargets = new HashSet<>();
3237             for (Attribute app : containedTarget.values) {
3238                 if (!(app instanceof Attribute.Enum attributeEnum)) {
3239                     continue; // recovery
3240                 }
3241                 containedTargets.add(attributeEnum.value.name);
3242             }
3243         }
3244 
3245         if (!isTargetSubsetOf(containerTargets, containedTargets)) {
3246             log.error(pos, Errors.InvalidRepeatableAnnotationIncompatibleTarget(container, contained));
3247         }
3248     }
3249 
3250     /* get a set of names for the default target */
3251     private Set<Name> getDefaultTargetSet() {
3252         if (defaultTargets == null) {
3253             defaultTargets = Set.of(defaultTargetMetaInfo());
3254         }
3255 
3256         return defaultTargets;
3257     }
3258     private Set<Name> defaultTargets;
3259 
3260 
3261     /** Checks that s is a subset of t, with respect to ElementType
3262      * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE},
3263      * and {TYPE_USE} covers the set {ANNOTATION_TYPE, TYPE, TYPE_USE,
3264      * TYPE_PARAMETER}.
3265      */
3266     private boolean isTargetSubsetOf(Set<Name> s, Set<Name> t) {
3267         // Check that all elements in s are present in t
3268         for (Name n2 : s) {
3269             boolean currentElementOk = false;
3270             for (Name n1 : t) {
3271                 if (n1 == n2) {
3272                     currentElementOk = true;
3273                     break;
3274                 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
3275                     currentElementOk = true;
3276                     break;
3277                 } else if (n1 == names.TYPE_USE &&
3278                         (n2 == names.TYPE ||
3279                          n2 == names.ANNOTATION_TYPE ||
3280                          n2 == names.TYPE_PARAMETER)) {
3281                     currentElementOk = true;
3282                     break;
3283                 }
3284             }
3285             if (!currentElementOk)
3286                 return false;
3287         }
3288         return true;
3289     }
3290 
3291     private void validateDefault(Symbol container, DiagnosticPosition pos) {
3292         // validate that all other elements of containing type has defaults
3293         Scope scope = container.members();
3294         for(Symbol elm : scope.getSymbols()) {
3295             if (elm.name != names.value &&
3296                 elm.kind == MTH &&
3297                 ((MethodSymbol)elm).defaultValue == null) {
3298                 log.error(pos,
3299                           Errors.InvalidRepeatableAnnotationElemNondefault(container, elm));
3300             }
3301         }
3302     }
3303 
3304     /** Is s a method symbol that overrides a method in a superclass? */
3305     boolean isOverrider(Symbol s) {
3306         if (s.kind != MTH || s.isStatic())
3307             return false;
3308         MethodSymbol m = (MethodSymbol)s;
3309         TypeSymbol owner = (TypeSymbol)m.owner;
3310         for (Type sup : types.closure(owner.type)) {
3311             if (sup == owner.type)
3312                 continue; // skip "this"
3313             Scope scope = sup.tsym.members();
3314             for (Symbol sym : scope.getSymbolsByName(m.name)) {
3315                 if (!sym.isStatic() && m.overrides(sym, owner, types, true))
3316                     return true;
3317             }
3318         }
3319         return false;
3320     }
3321 
3322     /** Is the annotation applicable to types? */
3323     protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
3324         List<Attribute> targets = typeAnnotations.annotationTargets(a.annotationType.type.tsym);
3325         return (targets == null) ?
3326                 false :
3327                 targets.stream()
3328                         .anyMatch(attr -> isTypeAnnotation(attr, isTypeParameter));
3329     }
3330     //where
3331         boolean isTypeAnnotation(Attribute a, boolean isTypeParameter) {
3332             Attribute.Enum e = (Attribute.Enum)a;
3333             return (e.value.name == names.TYPE_USE ||
3334                     (isTypeParameter && e.value.name == names.TYPE_PARAMETER));
3335         }
3336 
3337     /** Is the annotation applicable to the symbol? */
3338     Name[] getTargetNames(JCAnnotation a) {
3339         return getTargetNames(a.annotationType.type.tsym);
3340     }
3341 
3342     public Name[] getTargetNames(TypeSymbol annoSym) {
3343         Attribute.Array arr = getAttributeTargetAttribute(annoSym);
3344         Name[] targets;
3345         if (arr == null) {
3346             targets = defaultTargetMetaInfo();
3347         } else {
3348             // TODO: can we optimize this?
3349             targets = new Name[arr.values.length];
3350             for (int i=0; i<arr.values.length; ++i) {
3351                 Attribute app = arr.values[i];
3352                 if (!(app instanceof Attribute.Enum attributeEnum)) {
3353                     return new Name[0];
3354                 }
3355                 targets[i] = attributeEnum.value.name;
3356             }
3357         }
3358         return targets;
3359     }
3360 
3361     boolean annotationApplicable(JCAnnotation a, Symbol s) {
3362         Optional<Set<Name>> targets = getApplicableTargets(a, s);
3363         /* the optional could be empty if the annotation is unknown in that case
3364          * we return that it is applicable and if it is erroneous that should imply
3365          * an error at the declaration site
3366          */
3367         return targets.isEmpty() || targets.isPresent() && !targets.get().isEmpty();
3368     }
3369 
3370     Optional<Set<Name>> getApplicableTargets(JCAnnotation a, Symbol s) {
3371         Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
3372         Name[] targets;
3373         Set<Name> applicableTargets = new HashSet<>();
3374 
3375         if (arr == null) {
3376             targets = defaultTargetMetaInfo();
3377         } else {
3378             // TODO: can we optimize this?
3379             targets = new Name[arr.values.length];
3380             for (int i=0; i<arr.values.length; ++i) {
3381                 Attribute app = arr.values[i];
3382                 if (!(app instanceof Attribute.Enum attributeEnum)) {
3383                     // recovery
3384                     return Optional.empty();
3385                 }
3386                 targets[i] = attributeEnum.value.name;
3387             }
3388         }
3389         for (Name target : targets) {
3390             if (target == names.TYPE) {
3391                 if (s.kind == TYP)
3392                     applicableTargets.add(names.TYPE);
3393             } else if (target == names.FIELD) {
3394                 if (s.kind == VAR && s.owner.kind != MTH)
3395                     applicableTargets.add(names.FIELD);
3396             } else if (target == names.RECORD_COMPONENT) {
3397                 if (s.getKind() == ElementKind.RECORD_COMPONENT) {
3398                     applicableTargets.add(names.RECORD_COMPONENT);
3399                 }
3400             } else if (target == names.METHOD) {
3401                 if (s.kind == MTH && !s.isConstructor())
3402                     applicableTargets.add(names.METHOD);
3403             } else if (target == names.PARAMETER) {
3404                 if (s.kind == VAR &&
3405                     (s.owner.kind == MTH && (s.flags() & PARAMETER) != 0)) {
3406                     applicableTargets.add(names.PARAMETER);
3407                 }
3408             } else if (target == names.CONSTRUCTOR) {
3409                 if (s.kind == MTH && s.isConstructor())
3410                     applicableTargets.add(names.CONSTRUCTOR);
3411             } else if (target == names.LOCAL_VARIABLE) {
3412                 if (s.kind == VAR && s.owner.kind == MTH &&
3413                       (s.flags() & PARAMETER) == 0) {
3414                     applicableTargets.add(names.LOCAL_VARIABLE);
3415                 }
3416             } else if (target == names.ANNOTATION_TYPE) {
3417                 if (s.kind == TYP && (s.flags() & ANNOTATION) != 0) {
3418                     applicableTargets.add(names.ANNOTATION_TYPE);
3419                 }
3420             } else if (target == names.PACKAGE) {
3421                 if (s.kind == PCK)
3422                     applicableTargets.add(names.PACKAGE);
3423             } else if (target == names.TYPE_USE) {
3424                 if (s.kind == VAR && s.owner.kind == MTH && s.type.hasTag(NONE)) {
3425                     //cannot type annotate implicitly typed locals
3426                     continue;
3427                 } else if (s.kind == TYP || s.kind == VAR ||
3428                         (s.kind == MTH && !s.isConstructor() &&
3429                                 !s.type.getReturnType().hasTag(VOID)) ||
3430                         (s.kind == MTH && s.isConstructor())) {
3431                     applicableTargets.add(names.TYPE_USE);
3432                 }
3433             } else if (target == names.TYPE_PARAMETER) {
3434                 if (s.kind == TYP && s.type.hasTag(TYPEVAR))
3435                     applicableTargets.add(names.TYPE_PARAMETER);
3436             } else if (target == names.MODULE) {
3437                 if (s.kind == MDL)
3438                     applicableTargets.add(names.MODULE);
3439             } else
3440                 return Optional.empty(); // Unknown ElementType. This should be an error at declaration site,
3441                                          // assume applicable.
3442         }
3443         return Optional.of(applicableTargets);
3444     }
3445 
3446     Attribute.Array getAttributeTargetAttribute(TypeSymbol s) {
3447         Attribute.Compound atTarget = s.getAnnotationTypeMetadata().getTarget();
3448         if (atTarget == null) return null; // ok, is applicable
3449         Attribute atValue = atTarget.member(names.value);
3450         return (atValue instanceof Attribute.Array attributeArray) ? attributeArray : null;
3451     }
3452 
3453     private Name[] dfltTargetMeta;
3454     private Name[] defaultTargetMetaInfo() {
3455         if (dfltTargetMeta == null) {
3456             ArrayList<Name> defaultTargets = new ArrayList<>();
3457             defaultTargets.add(names.PACKAGE);
3458             defaultTargets.add(names.TYPE);
3459             defaultTargets.add(names.FIELD);
3460             defaultTargets.add(names.METHOD);
3461             defaultTargets.add(names.CONSTRUCTOR);
3462             defaultTargets.add(names.ANNOTATION_TYPE);
3463             defaultTargets.add(names.LOCAL_VARIABLE);
3464             defaultTargets.add(names.PARAMETER);
3465             if (allowRecords) {
3466               defaultTargets.add(names.RECORD_COMPONENT);
3467             }
3468             if (allowModules) {
3469               defaultTargets.add(names.MODULE);
3470             }
3471             dfltTargetMeta = defaultTargets.toArray(new Name[0]);
3472         }
3473         return dfltTargetMeta;
3474     }
3475 
3476     /** Check an annotation value.
3477      *
3478      * @param a The annotation tree to check
3479      * @return true if this annotation tree is valid, otherwise false
3480      */
3481     public boolean validateAnnotationDeferErrors(JCAnnotation a) {
3482         boolean res = false;
3483         final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
3484         try {
3485             res = validateAnnotation(a);
3486         } finally {
3487             log.popDiagnosticHandler(diagHandler);
3488         }
3489         return res;
3490     }
3491 
3492     private boolean validateAnnotation(JCAnnotation a) {
3493         boolean isValid = true;
3494         AnnotationTypeMetadata metadata = a.annotationType.type.tsym.getAnnotationTypeMetadata();
3495 
3496         // collect an inventory of the annotation elements
3497         Set<MethodSymbol> elements = metadata.getAnnotationElements();
3498 
3499         // remove the ones that are assigned values
3500         for (JCTree arg : a.args) {
3501             if (!arg.hasTag(ASSIGN)) continue; // recovery
3502             JCAssign assign = (JCAssign)arg;
3503             Symbol m = TreeInfo.symbol(assign.lhs);
3504             if (m == null || m.type.isErroneous()) continue;
3505             if (!elements.remove(m)) {
3506                 isValid = false;
3507                 log.error(assign.lhs.pos(),
3508                           Errors.DuplicateAnnotationMemberValue(m.name, a.type));
3509             }
3510         }
3511 
3512         // all the remaining ones better have default values
3513         List<Name> missingDefaults = List.nil();
3514         Set<MethodSymbol> membersWithDefault = metadata.getAnnotationElementsWithDefault();
3515         for (MethodSymbol m : elements) {
3516             if (m.type.isErroneous())
3517                 continue;
3518 
3519             if (!membersWithDefault.contains(m))
3520                 missingDefaults = missingDefaults.append(m.name);
3521         }
3522         missingDefaults = missingDefaults.reverse();
3523         if (missingDefaults.nonEmpty()) {
3524             isValid = false;
3525             Error errorKey = (missingDefaults.size() > 1)
3526                     ? Errors.AnnotationMissingDefaultValue1(a.type, missingDefaults)
3527                     : Errors.AnnotationMissingDefaultValue(a.type, missingDefaults);
3528             log.error(a.pos(), errorKey);
3529         }
3530 
3531         return isValid && validateTargetAnnotationValue(a);
3532     }
3533 
3534     /* Validate the special java.lang.annotation.Target annotation */
3535     boolean validateTargetAnnotationValue(JCAnnotation a) {
3536         // special case: java.lang.annotation.Target must not have
3537         // repeated values in its value member
3538         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
3539                 a.args.tail == null)
3540             return true;
3541 
3542         boolean isValid = true;
3543         if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
3544         JCAssign assign = (JCAssign) a.args.head;
3545         Symbol m = TreeInfo.symbol(assign.lhs);
3546         if (m.name != names.value) return false;
3547         JCTree rhs = assign.rhs;
3548         if (!rhs.hasTag(NEWARRAY)) return false;
3549         JCNewArray na = (JCNewArray) rhs;
3550         Set<Symbol> targets = new HashSet<>();
3551         for (JCTree elem : na.elems) {
3552             if (!targets.add(TreeInfo.symbol(elem))) {
3553                 isValid = false;
3554                 log.error(elem.pos(), Errors.RepeatedAnnotationTarget);
3555             }
3556         }
3557         return isValid;
3558     }
3559 
3560     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
3561         if (lint.isEnabled(LintCategory.DEP_ANN) && s.isDeprecatableViaAnnotation() &&
3562             (s.flags() & DEPRECATED) != 0 &&
3563             !syms.deprecatedType.isErroneous() &&
3564             s.attribute(syms.deprecatedType.tsym) == null) {
3565             log.warning(LintCategory.DEP_ANN,
3566                     pos, Warnings.MissingDeprecatedAnnotation);
3567         }
3568         // Note: @Deprecated has no effect on local variables, parameters and package decls.
3569         if (lint.isEnabled(LintCategory.DEPRECATION) && !s.isDeprecatableViaAnnotation()) {
3570             if (!syms.deprecatedType.isErroneous() && s.attribute(syms.deprecatedType.tsym) != null) {
3571                 log.warning(LintCategory.DEPRECATION, pos,
3572                             Warnings.DeprecatedAnnotationHasNoEffect(Kinds.kindName(s)));
3573             }
3574         }
3575     }
3576 
3577     void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
3578         checkDeprecated(() -> pos, other, s);
3579     }
3580 
3581     void checkDeprecated(Supplier<DiagnosticPosition> pos, final Symbol other, final Symbol s) {
3582         if ( (s.isDeprecatedForRemoval()
3583                 || s.isDeprecated() && !other.isDeprecated())
3584                 && (s.outermostClass() != other.outermostClass() || s.outermostClass() == null)
3585                 && s.kind != Kind.PCK) {
3586             deferredLintHandler.report(() -> warnDeprecated(pos.get(), s));
3587         }
3588     }
3589 
3590     void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
3591         if ((s.flags() & PROPRIETARY) != 0) {
3592             deferredLintHandler.report(() -> {
3593                 log.mandatoryWarning(pos, Warnings.SunProprietary(s));
3594             });
3595         }
3596     }
3597 
3598     void checkProfile(final DiagnosticPosition pos, final Symbol s) {
3599         if (profile != Profile.DEFAULT && (s.flags() & NOT_IN_PROFILE) != 0) {
3600             log.error(pos, Errors.NotInProfile(s, profile));
3601         }
3602     }
3603 
3604     void checkPreview(DiagnosticPosition pos, Symbol other, Symbol s) {
3605         if ((s.flags() & PREVIEW_API) != 0 && !preview.participatesInPreview(syms, other, s)) {
3606             if ((s.flags() & PREVIEW_REFLECTIVE) == 0) {
3607                 if (!preview.isEnabled()) {
3608                     log.error(pos, Errors.IsPreview(s));
3609                 } else {
3610                     preview.markUsesPreview(pos);
3611                     deferredLintHandler.report(() -> warnPreviewAPI(pos, Warnings.IsPreview(s)));
3612                 }
3613             } else {
3614                     deferredLintHandler.report(() -> warnPreviewAPI(pos, Warnings.IsPreviewReflective(s)));
3615             }
3616         }
3617         if (preview.declaredUsingPreviewFeature(s)) {
3618             if (preview.isEnabled()) {
3619                 //for preview disabled do presumably so not need to do anything?
3620                 //If "s" is compiled from source, then there was an error for it already;
3621                 //if "s" is from classfile, there already was an error for the classfile.
3622                 preview.markUsesPreview(pos);
3623                 deferredLintHandler.report(() -> warnDeclaredUsingPreview(pos, s));
3624             }
3625         }
3626     }
3627 
3628 /* *************************************************************************
3629  * Check for recursive annotation elements.
3630  **************************************************************************/
3631 
3632     /** Check for cycles in the graph of annotation elements.
3633      */
3634     void checkNonCyclicElements(JCClassDecl tree) {
3635         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
3636         Assert.check((tree.sym.flags_field & LOCKED) == 0);
3637         try {
3638             tree.sym.flags_field |= LOCKED;
3639             for (JCTree def : tree.defs) {
3640                 if (!def.hasTag(METHODDEF)) continue;
3641                 JCMethodDecl meth = (JCMethodDecl)def;
3642                 checkAnnotationResType(meth.pos(), meth.restype.type);
3643             }
3644         } finally {
3645             tree.sym.flags_field &= ~LOCKED;
3646             tree.sym.flags_field |= ACYCLIC_ANN;
3647         }
3648     }
3649 
3650     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
3651         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
3652             return;
3653         if ((tsym.flags_field & LOCKED) != 0) {
3654             log.error(pos, Errors.CyclicAnnotationElement(tsym));
3655             return;
3656         }
3657         try {
3658             tsym.flags_field |= LOCKED;
3659             for (Symbol s : tsym.members().getSymbols(NON_RECURSIVE)) {
3660                 if (s.kind != MTH)
3661                     continue;
3662                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
3663             }
3664         } finally {
3665             tsym.flags_field &= ~LOCKED;
3666             tsym.flags_field |= ACYCLIC_ANN;
3667         }
3668     }
3669 
3670     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
3671         switch (type.getTag()) {
3672         case CLASS:
3673             if ((type.tsym.flags() & ANNOTATION) != 0)
3674                 checkNonCyclicElementsInternal(pos, type.tsym);
3675             break;
3676         case ARRAY:
3677             checkAnnotationResType(pos, types.elemtype(type));
3678             break;
3679         default:
3680             break; // int etc
3681         }
3682     }
3683 
3684 /* *************************************************************************
3685  * Check for cycles in the constructor call graph.
3686  **************************************************************************/
3687 
3688     /** Check for cycles in the graph of constructors calling other
3689      *  constructors.
3690      */
3691     void checkCyclicConstructors(JCClassDecl tree) {
3692         Map<Symbol,Symbol> callMap = new HashMap<>();
3693 
3694         // enter each constructor this-call into the map
3695         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3696             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
3697             if (app == null) continue;
3698             JCMethodDecl meth = (JCMethodDecl) l.head;
3699             if (TreeInfo.name(app.meth) == names._this) {
3700                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
3701             } else {
3702                 meth.sym.flags_field |= ACYCLIC;
3703             }
3704         }
3705 
3706         // Check for cycles in the map
3707         Symbol[] ctors = new Symbol[0];
3708         ctors = callMap.keySet().toArray(ctors);
3709         for (Symbol caller : ctors) {
3710             checkCyclicConstructor(tree, caller, callMap);
3711         }
3712     }
3713 
3714     /** Look in the map to see if the given constructor is part of a
3715      *  call cycle.
3716      */
3717     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
3718                                         Map<Symbol,Symbol> callMap) {
3719         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
3720             if ((ctor.flags_field & LOCKED) != 0) {
3721                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
3722                           Errors.RecursiveCtorInvocation);
3723             } else {
3724                 ctor.flags_field |= LOCKED;
3725                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
3726                 ctor.flags_field &= ~LOCKED;
3727             }
3728             ctor.flags_field |= ACYCLIC;
3729         }
3730     }
3731 
3732 /* *************************************************************************
3733  * Miscellaneous
3734  **************************************************************************/
3735 
3736     /**
3737      *  Check for division by integer constant zero
3738      *  @param pos           Position for error reporting.
3739      *  @param operator      The operator for the expression
3740      *  @param operand       The right hand operand for the expression
3741      */
3742     void checkDivZero(final DiagnosticPosition pos, Symbol operator, Type operand) {
3743         if (operand.constValue() != null
3744             && operand.getTag().isSubRangeOf(LONG)
3745             && ((Number) (operand.constValue())).longValue() == 0) {
3746             int opc = ((OperatorSymbol)operator).opcode;
3747             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
3748                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
3749                 deferredLintHandler.report(() -> warnDivZero(pos));
3750             }
3751         }
3752     }
3753 
3754     /**
3755      *  Check for possible loss of precission
3756      *  @param pos           Position for error reporting.
3757      *  @param found    The computed type of the tree
3758      *  @param req  The computed type of the tree
3759      */
3760     void checkLossOfPrecision(final DiagnosticPosition pos, Type found, Type req) {
3761         if (found.isNumeric() && req.isNumeric() && !types.isAssignable(found, req)) {
3762             deferredLintHandler.report(() -> {
3763                 if (lint.isEnabled(LintCategory.LOSSY_CONVERSIONS))
3764                     log.warning(LintCategory.LOSSY_CONVERSIONS,
3765                             pos, Warnings.PossibleLossOfPrecision(found, req));
3766             });
3767         }
3768     }
3769 
3770     /**
3771      * Check for empty statements after if
3772      */
3773     void checkEmptyIf(JCIf tree) {
3774         if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
3775                 lint.isEnabled(LintCategory.EMPTY))
3776             log.warning(LintCategory.EMPTY, tree.thenpart.pos(), Warnings.EmptyIf);
3777     }
3778 
3779     /** Check that symbol is unique in given scope.
3780      *  @param pos           Position for error reporting.
3781      *  @param sym           The symbol.
3782      *  @param s             The scope.
3783      */
3784     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
3785         if (sym.type.isErroneous())
3786             return true;
3787         if (sym.owner.name == names.any) return false;
3788         for (Symbol byName : s.getSymbolsByName(sym.name, NON_RECURSIVE)) {
3789             if (sym != byName &&
3790                     (byName.flags() & CLASH) == 0 &&
3791                     sym.kind == byName.kind &&
3792                     sym.name != names.error &&
3793                     (sym.kind != MTH ||
3794                      types.hasSameArgs(sym.type, byName.type) ||
3795                      types.hasSameArgs(types.erasure(sym.type), types.erasure(byName.type)))) {
3796                 if ((sym.flags() & VARARGS) != (byName.flags() & VARARGS)) {
3797                     sym.flags_field |= CLASH;
3798                     varargsDuplicateError(pos, sym, byName);
3799                     return true;
3800                 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, byName.type, false)) {
3801                     duplicateErasureError(pos, sym, byName);
3802                     sym.flags_field |= CLASH;
3803                     return true;
3804                 } else if ((sym.flags() & MATCH_BINDING) != 0 &&
3805                            (byName.flags() & MATCH_BINDING) != 0 &&
3806                            (byName.flags() & MATCH_BINDING_TO_OUTER) == 0) {
3807                     if (!sym.type.isErroneous()) {
3808                         log.error(pos, Errors.MatchBindingExists);
3809                         sym.flags_field |= CLASH;
3810                     }
3811                     return false;
3812                 } else {
3813                     duplicateError(pos, byName);
3814                     return false;
3815                 }
3816             }
3817         }
3818         return true;
3819     }
3820 
3821     /** Report duplicate declaration error.
3822      */
3823     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
3824         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
3825             log.error(pos, Errors.NameClashSameErasure(sym1, sym2));
3826         }
3827     }
3828 
3829     /**Check that types imported through the ordinary imports don't clash with types imported
3830      * by other (static or ordinary) imports. Note that two static imports may import two clashing
3831      * types without an error on the imports.
3832      * @param toplevel       The toplevel tree for which the test should be performed.
3833      */
3834     void checkImportsUnique(JCCompilationUnit toplevel) {
3835         WriteableScope ordinallyImportedSoFar = WriteableScope.create(toplevel.packge);
3836         WriteableScope staticallyImportedSoFar = WriteableScope.create(toplevel.packge);
3837         WriteableScope topLevelScope = toplevel.toplevelScope;
3838 
3839         for (JCTree def : toplevel.defs) {
3840             if (!def.hasTag(IMPORT))
3841                 continue;
3842 
3843             JCImport imp = (JCImport) def;
3844 
3845             if (imp.importScope == null)
3846                 continue;
3847 
3848             for (Symbol sym : imp.importScope.getSymbols(sym -> sym.kind == TYP)) {
3849                 if (imp.isStatic()) {
3850                     checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, true);
3851                     staticallyImportedSoFar.enter(sym);
3852                 } else {
3853                     checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, false);
3854                     ordinallyImportedSoFar.enter(sym);
3855                 }
3856             }
3857 
3858             imp.importScope = null;
3859         }
3860     }
3861 
3862     /** Check that single-type import is not already imported or top-level defined,
3863      *  but make an exception for two single-type imports which denote the same type.
3864      *  @param pos                     Position for error reporting.
3865      *  @param ordinallyImportedSoFar  A Scope containing types imported so far through
3866      *                                 ordinary imports.
3867      *  @param staticallyImportedSoFar A Scope containing types imported so far through
3868      *                                 static imports.
3869      *  @param topLevelScope           The current file's top-level Scope
3870      *  @param sym                     The symbol.
3871      *  @param staticImport            Whether or not this was a static import
3872      */
3873     private boolean checkUniqueImport(DiagnosticPosition pos, Scope ordinallyImportedSoFar,
3874                                       Scope staticallyImportedSoFar, Scope topLevelScope,
3875                                       Symbol sym, boolean staticImport) {
3876         Predicate<Symbol> duplicates = candidate -> candidate != sym && !candidate.type.isErroneous();
3877         Symbol ordinaryClashing = ordinallyImportedSoFar.findFirst(sym.name, duplicates);
3878         Symbol staticClashing = null;
3879         if (ordinaryClashing == null && !staticImport) {
3880             staticClashing = staticallyImportedSoFar.findFirst(sym.name, duplicates);
3881         }
3882         if (ordinaryClashing != null || staticClashing != null) {
3883             if (ordinaryClashing != null)
3884                 log.error(pos, Errors.AlreadyDefinedSingleImport(ordinaryClashing));
3885             else
3886                 log.error(pos, Errors.AlreadyDefinedStaticSingleImport(staticClashing));
3887             return false;
3888         }
3889         Symbol clashing = topLevelScope.findFirst(sym.name, duplicates);
3890         if (clashing != null) {
3891             log.error(pos, Errors.AlreadyDefinedThisUnit(clashing));
3892             return false;
3893         }
3894         return true;
3895     }
3896 
3897     /** Check that a qualified name is in canonical form (for import decls).
3898      */
3899     public void checkCanonical(JCTree tree) {
3900         if (!isCanonical(tree))
3901             log.error(tree.pos(),
3902                       Errors.ImportRequiresCanonical(TreeInfo.symbol(tree)));
3903     }
3904         // where
3905         private boolean isCanonical(JCTree tree) {
3906             while (tree.hasTag(SELECT)) {
3907                 JCFieldAccess s = (JCFieldAccess) tree;
3908                 if (s.sym.owner.getQualifiedName() != TreeInfo.symbol(s.selected).getQualifiedName())
3909                     return false;
3910                 tree = s.selected;
3911             }
3912             return true;
3913         }
3914 
3915     /** Check that an auxiliary class is not accessed from any other file than its own.
3916      */
3917     void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
3918         if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
3919             (c.flags() & AUXILIARY) != 0 &&
3920             rs.isAccessible(env, c) &&
3921             !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
3922         {
3923             log.warning(pos,
3924                         Warnings.AuxiliaryClassAccessedFromOutsideOfItsSourceFile(c, c.sourcefile));
3925         }
3926     }
3927 
3928     /**
3929      * Check for a default constructor in an exported package.
3930      */
3931     void checkDefaultConstructor(ClassSymbol c, DiagnosticPosition pos) {
3932         if (lint.isEnabled(LintCategory.MISSING_EXPLICIT_CTOR) &&
3933             ((c.flags() & (ENUM | RECORD)) == 0) &&
3934             !c.isAnonymous() &&
3935             ((c.flags() & (PUBLIC | PROTECTED)) != 0) &&
3936             Feature.MODULES.allowedInSource(source)) {
3937             NestingKind nestingKind = c.getNestingKind();
3938             switch (nestingKind) {
3939                 case ANONYMOUS,
3940                      LOCAL -> {return;}
3941                 case TOP_LEVEL -> {;} // No additional checks needed
3942                 case MEMBER -> {
3943                     // For nested member classes, all the enclosing
3944                     // classes must be public or protected.
3945                     Symbol owner = c.owner;
3946                     while (owner != null && owner.kind == TYP) {
3947                         if ((owner.flags() & (PUBLIC | PROTECTED)) == 0)
3948                             return;
3949                         owner = owner.owner;
3950                     }
3951                 }
3952             }
3953 
3954             // Only check classes in named packages exported by its module
3955             PackageSymbol pkg = c.packge();
3956             if (!pkg.isUnnamed()) {
3957                 ModuleSymbol modle = pkg.modle;
3958                 for (ExportsDirective exportDir : modle.exports) {
3959                     // Report warning only if the containing
3960                     // package is unconditionally exported
3961                     if (exportDir.packge.equals(pkg)) {
3962                         if (exportDir.modules == null || exportDir.modules.isEmpty()) {
3963                             // Warning may be suppressed by
3964                             // annotations; check again for being
3965                             // enabled in the deferred context.
3966                             deferredLintHandler.report(() -> {
3967                                 if (lint.isEnabled(LintCategory.MISSING_EXPLICIT_CTOR))
3968                                    log.warning(LintCategory.MISSING_EXPLICIT_CTOR,
3969                                                pos, Warnings.MissingExplicitCtor(c, pkg, modle));
3970                                                        });
3971                         } else {
3972                             return;
3973                         }
3974                     }
3975                 }
3976             }
3977         }
3978         return;
3979     }
3980 
3981     private class ConversionWarner extends Warner {
3982         final String uncheckedKey;
3983         final Type found;
3984         final Type expected;
3985         public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
3986             super(pos);
3987             this.uncheckedKey = uncheckedKey;
3988             this.found = found;
3989             this.expected = expected;
3990         }
3991 
3992         @Override
3993         public void warn(LintCategory lint) {
3994             boolean warned = this.warned;
3995             super.warn(lint);
3996             if (warned) return; // suppress redundant diagnostics
3997             switch (lint) {
3998                 case UNCHECKED:
3999                     Check.this.warnUnchecked(pos(), Warnings.ProbFoundReq(diags.fragment(uncheckedKey), found, expected));
4000                     break;
4001                 case VARARGS:
4002                     if (method != null &&
4003                             method.attribute(syms.trustMeType.tsym) != null &&
4004                             isTrustMeAllowedOnMethod(method) &&
4005                             !types.isReifiable(method.type.getParameterTypes().last())) {
4006                         Check.this.warnUnsafeVararg(pos(), Warnings.VarargsUnsafeUseVarargsParam(method.params.last()));
4007                     }
4008                     break;
4009                 default:
4010                     throw new AssertionError("Unexpected lint: " + lint);
4011             }
4012         }
4013     }
4014 
4015     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
4016         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
4017     }
4018 
4019     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
4020         return new ConversionWarner(pos, "unchecked.assign", found, expected);
4021     }
4022 
4023     public void checkFunctionalInterface(JCClassDecl tree, ClassSymbol cs) {
4024         Compound functionalType = cs.attribute(syms.functionalInterfaceType.tsym);
4025 
4026         if (functionalType != null) {
4027             try {
4028                 types.findDescriptorSymbol((TypeSymbol)cs);
4029             } catch (Types.FunctionDescriptorLookupError ex) {
4030                 DiagnosticPosition pos = tree.pos();
4031                 for (JCAnnotation a : tree.getModifiers().annotations) {
4032                     if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
4033                         pos = a.pos();
4034                         break;
4035                     }
4036                 }
4037                 log.error(pos, Errors.BadFunctionalIntfAnno1(ex.getDiagnostic()));
4038             }
4039         }
4040     }
4041 
4042     public void checkImportsResolvable(final JCCompilationUnit toplevel) {
4043         for (final JCImport imp : toplevel.getImports()) {
4044             if (!imp.staticImport || !imp.qualid.hasTag(SELECT))
4045                 continue;
4046             final JCFieldAccess select = (JCFieldAccess) imp.qualid;
4047             final Symbol origin;
4048             if (select.name == names.asterisk || (origin = TreeInfo.symbol(select.selected)) == null || origin.kind != TYP)
4049                 continue;
4050 
4051             TypeSymbol site = (TypeSymbol) TreeInfo.symbol(select.selected);
4052             if (!checkTypeContainsImportableElement(site, site, toplevel.packge, select.name, new HashSet<Symbol>())) {
4053                 log.error(imp.pos(),
4054                           Errors.CantResolveLocation(KindName.STATIC,
4055                                                      select.name,
4056                                                      null,
4057                                                      null,
4058                                                      Fragments.Location(kindName(site),
4059                                                                         site,
4060                                                                         null)));
4061             }
4062         }
4063     }
4064 
4065     // Check that packages imported are in scope (JLS 7.4.3, 6.3, 6.5.3.1, 6.5.3.2)
4066     public void checkImportedPackagesObservable(final JCCompilationUnit toplevel) {
4067         OUTER: for (JCImport imp : toplevel.getImports()) {
4068             if (!imp.staticImport && TreeInfo.name(imp.qualid) == names.asterisk) {
4069                 TypeSymbol tsym = ((JCFieldAccess)imp.qualid).selected.type.tsym;
4070                 if (tsym.kind == PCK && tsym.members().isEmpty() &&
4071                     !(Feature.IMPORT_ON_DEMAND_OBSERVABLE_PACKAGES.allowedInSource(source) && tsym.exists())) {
4072                     log.error(DiagnosticFlag.RESOLVE_ERROR, imp.pos, Errors.DoesntExist(tsym));
4073                 }
4074             }
4075         }
4076     }
4077 
4078     private boolean checkTypeContainsImportableElement(TypeSymbol tsym, TypeSymbol origin, PackageSymbol packge, Name name, Set<Symbol> processed) {
4079         if (tsym == null || !processed.add(tsym))
4080             return false;
4081 
4082             // also search through inherited names
4083         if (checkTypeContainsImportableElement(types.supertype(tsym.type).tsym, origin, packge, name, processed))
4084             return true;
4085 
4086         for (Type t : types.interfaces(tsym.type))
4087             if (checkTypeContainsImportableElement(t.tsym, origin, packge, name, processed))
4088                 return true;
4089 
4090         for (Symbol sym : tsym.members().getSymbolsByName(name)) {
4091             if (sym.isStatic() &&
4092                 importAccessible(sym, packge) &&
4093                 sym.isMemberOf(origin, types)) {
4094                 return true;
4095             }
4096         }
4097 
4098         return false;
4099     }
4100 
4101     // is the sym accessible everywhere in packge?
4102     public boolean importAccessible(Symbol sym, PackageSymbol packge) {
4103         try {
4104             int flags = (int)(sym.flags() & AccessFlags);
4105             switch (flags) {
4106             default:
4107             case PUBLIC:
4108                 return true;
4109             case PRIVATE:
4110                 return false;
4111             case 0:
4112             case PROTECTED:
4113                 return sym.packge() == packge;
4114             }
4115         } catch (ClassFinder.BadClassFile err) {
4116             throw err;
4117         } catch (CompletionFailure ex) {
4118             return false;
4119         }
4120     }
4121 
4122     public void checkLeaksNotAccessible(Env<AttrContext> env, JCClassDecl check) {
4123         JCCompilationUnit toplevel = env.toplevel;
4124 
4125         if (   toplevel.modle == syms.unnamedModule
4126             || toplevel.modle == syms.noModule
4127             || (check.sym.flags() & COMPOUND) != 0) {
4128             return ;
4129         }
4130 
4131         ExportsDirective currentExport = findExport(toplevel.packge);
4132 
4133         if (   currentExport == null //not exported
4134             || currentExport.modules != null) //don't check classes in qualified export
4135             return ;
4136 
4137         new TreeScanner() {
4138             Lint lint = env.info.lint;
4139             boolean inSuperType;
4140 
4141             @Override
4142             public void visitBlock(JCBlock tree) {
4143             }
4144             @Override
4145             public void visitMethodDef(JCMethodDecl tree) {
4146                 if (!isAPISymbol(tree.sym))
4147                     return;
4148                 Lint prevLint = lint;
4149                 try {
4150                     lint = lint.augment(tree.sym);
4151                     if (lint.isEnabled(LintCategory.EXPORTS)) {
4152                         super.visitMethodDef(tree);
4153                     }
4154                 } finally {
4155                     lint = prevLint;
4156                 }
4157             }
4158             @Override
4159             public void visitVarDef(JCVariableDecl tree) {
4160                 if (!isAPISymbol(tree.sym) && tree.sym.owner.kind != MTH)
4161                     return;
4162                 Lint prevLint = lint;
4163                 try {
4164                     lint = lint.augment(tree.sym);
4165                     if (lint.isEnabled(LintCategory.EXPORTS)) {
4166                         scan(tree.mods);
4167                         scan(tree.vartype);
4168                     }
4169                 } finally {
4170                     lint = prevLint;
4171                 }
4172             }
4173             @Override
4174             public void visitClassDef(JCClassDecl tree) {
4175                 if (tree != check)
4176                     return ;
4177 
4178                 if (!isAPISymbol(tree.sym))
4179                     return ;
4180 
4181                 Lint prevLint = lint;
4182                 try {
4183                     lint = lint.augment(tree.sym);
4184                     if (lint.isEnabled(LintCategory.EXPORTS)) {
4185                         scan(tree.mods);
4186                         scan(tree.typarams);
4187                         try {
4188                             inSuperType = true;
4189                             scan(tree.extending);
4190                             scan(tree.implementing);
4191                         } finally {
4192                             inSuperType = false;
4193                         }
4194                         scan(tree.defs);
4195                     }
4196                 } finally {
4197                     lint = prevLint;
4198                 }
4199             }
4200             @Override
4201             public void visitTypeApply(JCTypeApply tree) {
4202                 scan(tree.clazz);
4203                 boolean oldInSuperType = inSuperType;
4204                 try {
4205                     inSuperType = false;
4206                     scan(tree.arguments);
4207                 } finally {
4208                     inSuperType = oldInSuperType;
4209                 }
4210             }
4211             @Override
4212             public void visitIdent(JCIdent tree) {
4213                 Symbol sym = TreeInfo.symbol(tree);
4214                 if (sym.kind == TYP && !sym.type.hasTag(TYPEVAR)) {
4215                     checkVisible(tree.pos(), sym, toplevel.packge, inSuperType);
4216                 }
4217             }
4218 
4219             @Override
4220             public void visitSelect(JCFieldAccess tree) {
4221                 Symbol sym = TreeInfo.symbol(tree);
4222                 Symbol sitesym = TreeInfo.symbol(tree.selected);
4223                 if (sym.kind == TYP && sitesym.kind == PCK) {
4224                     checkVisible(tree.pos(), sym, toplevel.packge, inSuperType);
4225                 } else {
4226                     super.visitSelect(tree);
4227                 }
4228             }
4229 
4230             @Override
4231             public void visitAnnotation(JCAnnotation tree) {
4232                 if (tree.attribute.type.tsym.getAnnotation(java.lang.annotation.Documented.class) != null)
4233                     super.visitAnnotation(tree);
4234             }
4235 
4236         }.scan(check);
4237     }
4238         //where:
4239         private ExportsDirective findExport(PackageSymbol pack) {
4240             for (ExportsDirective d : pack.modle.exports) {
4241                 if (d.packge == pack)
4242                     return d;
4243             }
4244 
4245             return null;
4246         }
4247         private boolean isAPISymbol(Symbol sym) {
4248             while (sym.kind != PCK) {
4249                 if ((sym.flags() & Flags.PUBLIC) == 0 && (sym.flags() & Flags.PROTECTED) == 0) {
4250                     return false;
4251                 }
4252                 sym = sym.owner;
4253             }
4254             return true;
4255         }
4256         private void checkVisible(DiagnosticPosition pos, Symbol what, PackageSymbol inPackage, boolean inSuperType) {
4257             if (!isAPISymbol(what) && !inSuperType) { //package private/private element
4258                 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessible(kindName(what), what, what.packge().modle));
4259                 return ;
4260             }
4261 
4262             PackageSymbol whatPackage = what.packge();
4263             ExportsDirective whatExport = findExport(whatPackage);
4264             ExportsDirective inExport = findExport(inPackage);
4265 
4266             if (whatExport == null) { //package not exported:
4267                 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleUnexported(kindName(what), what, what.packge().modle));
4268                 return ;
4269             }
4270 
4271             if (whatExport.modules != null) {
4272                 if (inExport.modules == null || !whatExport.modules.containsAll(inExport.modules)) {
4273                     log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleUnexportedQualified(kindName(what), what, what.packge().modle));
4274                 }
4275             }
4276 
4277             if (whatPackage.modle != inPackage.modle && whatPackage.modle != syms.java_base) {
4278                 //check that relativeTo.modle requires transitive what.modle, somehow:
4279                 List<ModuleSymbol> todo = List.of(inPackage.modle);
4280 
4281                 while (todo.nonEmpty()) {
4282                     ModuleSymbol current = todo.head;
4283                     todo = todo.tail;
4284                     if (current == whatPackage.modle)
4285                         return ; //OK
4286                     if ((current.flags() & Flags.AUTOMATIC_MODULE) != 0)
4287                         continue; //for automatic modules, don't look into their dependencies
4288                     for (RequiresDirective req : current.requires) {
4289                         if (req.isTransitive()) {
4290                             todo = todo.prepend(req.module);
4291                         }
4292                     }
4293                 }
4294 
4295                 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleNotRequiredTransitive(kindName(what), what, what.packge().modle));
4296             }
4297         }
4298 
4299     void checkModuleExists(final DiagnosticPosition pos, ModuleSymbol msym) {
4300         if (msym.kind != MDL) {
4301             deferredLintHandler.report(() -> {
4302                 if (lint.isEnabled(LintCategory.MODULE))
4303                     log.warning(LintCategory.MODULE, pos, Warnings.ModuleNotFound(msym));
4304             });
4305         }
4306     }
4307 
4308     void checkPackageExistsForOpens(final DiagnosticPosition pos, PackageSymbol packge) {
4309         if (packge.members().isEmpty() &&
4310             ((packge.flags() & Flags.HAS_RESOURCE) == 0)) {
4311             deferredLintHandler.report(() -> {
4312                 if (lint.isEnabled(LintCategory.OPENS))
4313                     log.warning(pos, Warnings.PackageEmptyOrNotFound(packge));
4314             });
4315         }
4316     }
4317 
4318     void checkModuleRequires(final DiagnosticPosition pos, final RequiresDirective rd) {
4319         if ((rd.module.flags() & Flags.AUTOMATIC_MODULE) != 0) {
4320             deferredLintHandler.report(() -> {
4321                 if (rd.isTransitive() && lint.isEnabled(LintCategory.REQUIRES_TRANSITIVE_AUTOMATIC)) {
4322                     log.warning(pos, Warnings.RequiresTransitiveAutomatic);
4323                 } else if (lint.isEnabled(LintCategory.REQUIRES_AUTOMATIC)) {
4324                     log.warning(pos, Warnings.RequiresAutomatic);
4325                 }
4326             });
4327         }
4328     }
4329 
4330     /**
4331      * Verify the case labels conform to the constraints. Checks constraints related
4332      * combinations of patterns and other labels.
4333      *
4334      * @param cases the cases that should be checked.
4335      */
4336     void checkSwitchCaseStructure(List<JCCase> cases) {
4337         boolean wasConstant = false;          // Seen a constant in the same case label
4338         boolean wasDefault = false;           // Seen a default in the same case label
4339         boolean wasNullPattern = false;       // Seen a null pattern in the same case label,
4340                                               //or fall through from a null pattern
4341         boolean wasPattern = false;           // Seen a pattern in the same case label
4342                                               //or fall through from a pattern
4343         boolean wasTypePattern = false;       // Seen a pattern in the same case label
4344                                               //or fall through from a type pattern
4345         boolean wasNonEmptyFallThrough = false;
4346         for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
4347             JCCase c = l.head;
4348             for (JCCaseLabel label : c.labels) {
4349                 if (label.hasTag(CONSTANTCASELABEL)) {
4350                     JCExpression expr = ((JCConstantCaseLabel) label).expr;
4351                     if (TreeInfo.isNull(expr)) {
4352                         if (wasPattern && !wasTypePattern && !wasNonEmptyFallThrough) {
4353                             log.error(label.pos(), Errors.FlowsThroughFromPattern);
4354                         }
4355                         wasNullPattern = true;
4356                     } else {
4357                         if (wasPattern && !wasNonEmptyFallThrough) {
4358                             log.error(label.pos(), Errors.FlowsThroughFromPattern);
4359                         }
4360                         wasConstant = true;
4361                     }
4362                 } else if (label.hasTag(DEFAULTCASELABEL)) {
4363                     if (wasPattern && !wasNonEmptyFallThrough) {
4364                         log.error(label.pos(), Errors.FlowsThroughFromPattern);
4365                     }
4366                     wasDefault = true;
4367                 } else {
4368                     JCPattern pat = ((JCPatternCaseLabel) label).pat;
4369                     while (pat instanceof JCParenthesizedPattern parenthesized) {
4370                         pat = parenthesized.pattern;
4371                     }
4372                     boolean isTypePattern = pat.hasTag(BINDINGPATTERN);
4373                     if (wasPattern || wasConstant || wasDefault ||
4374                         (wasNullPattern && (!isTypePattern || wasNonEmptyFallThrough))) {
4375                         log.error(label.pos(), Errors.FlowsThroughToPattern);
4376                     }
4377                     wasPattern = true;
4378                     wasTypePattern = isTypePattern;
4379                 }
4380             }
4381 
4382             boolean completesNormally = c.caseKind == CaseTree.CaseKind.STATEMENT ? c.completesNormally
4383                                                                                   : false;
4384 
4385             if (c.stats.nonEmpty()) {
4386                 wasConstant = false;
4387                 wasDefault = false;
4388                 wasNullPattern &= completesNormally;
4389                 wasPattern &= completesNormally;
4390                 wasTypePattern &= completesNormally;
4391             }
4392 
4393             wasNonEmptyFallThrough = c.stats.nonEmpty() && completesNormally;
4394         }
4395     }
4396 
4397     void checkSwitchCaseLabelDominated(List<JCCase> cases) {
4398         List<JCCaseLabel> caseLabels = List.nil();
4399         for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
4400             JCCase c = l.head;
4401             for (JCCaseLabel label : c.labels) {
4402                 if (label.hasTag(DEFAULTCASELABEL) || TreeInfo.isNullCaseLabel(label)) {
4403                     continue;
4404                 }
4405                 Type currentType = labelType(label);
4406                 for (JCCaseLabel testCaseLabel : caseLabels) {
4407                     Type testType = labelType(testCaseLabel);
4408                     if (types.isSubtype(currentType, testType) &&
4409                         !currentType.hasTag(ERROR) && !testType.hasTag(ERROR)) {
4410                         //the current label is potentially dominated by the existing (test) label, check:
4411                         boolean dominated = false;
4412                         if (label instanceof JCConstantCaseLabel) {
4413                             dominated |= !(testCaseLabel instanceof JCConstantCaseLabel);
4414                         } else if (label instanceof JCPatternCaseLabel patternCL &&
4415                                    testCaseLabel instanceof JCPatternCaseLabel testPatternCaseLabel &&
4416                                    TreeInfo.unguardedCaseLabel(testCaseLabel)) {
4417                             dominated = patternDominated(testPatternCaseLabel.pat,
4418                                                          patternCL.pat);
4419                         }
4420                         if (dominated) {
4421                             log.error(label.pos(), Errors.PatternDominated);
4422                         }
4423                     }
4424                 }
4425                 caseLabels = caseLabels.prepend(label);
4426             }
4427         }
4428     }
4429         //where:
4430         private Type labelType(JCCaseLabel label) {
4431             return types.erasure(switch (label.getTag()) {
4432                 case PATTERNCASELABEL -> ((JCPatternCaseLabel) label).pat.type;
4433                 case CONSTANTCASELABEL -> types.boxedTypeOrType(((JCConstantCaseLabel) label).expr.type);
4434                 default -> throw Assert.error("Unexpected tree kind: " + label.getTag());
4435             });
4436         }
4437         private boolean patternDominated(JCPattern existingPattern, JCPattern currentPattern) {
4438             Type existingPatternType = types.erasure(existingPattern.type);
4439             Type currentPatternType = types.erasure(currentPattern.type);
4440             if (existingPatternType.isPrimitive() ^ currentPatternType.isPrimitive()) {
4441                 return false;
4442             }
4443             if (existingPatternType.isPrimitive()) {
4444                 return types.isSameType(existingPatternType, currentPatternType);
4445             } else {
4446                 if (!types.isSubtype(currentPatternType, existingPatternType)) {
4447                     return false;
4448                 }
4449             }
4450             while (existingPattern instanceof JCParenthesizedPattern parenthesized) {
4451                 existingPattern = parenthesized.pattern;
4452             }
4453             while (currentPattern instanceof JCParenthesizedPattern parenthesized) {
4454                 currentPattern = parenthesized.pattern;
4455             }
4456             if (currentPattern instanceof JCBindingPattern) {
4457                 return existingPattern instanceof JCBindingPattern;
4458             } else if (currentPattern instanceof JCRecordPattern currentRecordPattern) {
4459                 if (existingPattern instanceof JCBindingPattern) {
4460                     return true;
4461                 } else if (existingPattern instanceof JCRecordPattern existingRecordPattern) {
4462                     List<JCPattern> existingNested = existingRecordPattern.nested;
4463                     List<JCPattern> currentNested = currentRecordPattern.nested;
4464                     if (existingNested.size() != currentNested.size()) {
4465                         return false;
4466                     }
4467                     while (existingNested.nonEmpty()) {
4468                         if (!patternDominated(existingNested.head, currentNested.head)) {
4469                             return false;
4470                         }
4471                         existingNested = existingNested.tail;
4472                         currentNested = currentNested.tail;
4473                     }
4474                     return true;
4475                 } else {
4476                     Assert.error("Unknown pattern: " + existingPattern.getTag());
4477                 }
4478             } else {
4479                 Assert.error("Unknown pattern: " + currentPattern.getTag());
4480             }
4481             return false;
4482         }
4483 
4484     /** check if a type is a subtype of Externalizable, if that is available. */
4485     boolean isExternalizable(Type t) {
4486         try {
4487             syms.externalizableType.complete();
4488         }
4489         catch (CompletionFailure e) {
4490             return false;
4491         }
4492         return types.isSubtype(t, syms.externalizableType);
4493     }
4494 
4495     /**
4496      * Check structure of serialization declarations.
4497      */
4498     public void checkSerialStructure(JCClassDecl tree, ClassSymbol c) {
4499         (new SerialTypeVisitor()).visit(c, tree);
4500     }
4501 
4502     /**
4503      * This visitor will warn if a serialization-related field or
4504      * method is declared in a suspicious or incorrect way. In
4505      * particular, it will warn for cases where the runtime
4506      * serialization mechanism will silently ignore a mis-declared
4507      * entity.
4508      *
4509      * Distinguished serialization-related fields and methods:
4510      *
4511      * Methods:
4512      *
4513      * private void writeObject(ObjectOutputStream stream) throws IOException
4514      * ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException
4515      *
4516      * private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException
4517      * private void readObjectNoData() throws ObjectStreamException
4518      * ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException
4519      *
4520      * Fields:
4521      *
4522      * private static final long serialVersionUID
4523      * private static final ObjectStreamField[] serialPersistentFields
4524      *
4525      * Externalizable: methods defined on the interface
4526      * public void writeExternal(ObjectOutput) throws IOException
4527      * public void readExternal(ObjectInput) throws IOException
4528      */
4529     private class SerialTypeVisitor extends ElementKindVisitor14<Void, JCClassDecl> {
4530         SerialTypeVisitor() {
4531             this.lint = Check.this.lint;
4532         }
4533 
4534         private static final Set<String> serialMethodNames =
4535             Set.of("writeObject", "writeReplace",
4536                    "readObject",  "readObjectNoData",
4537                    "readResolve");
4538 
4539         private static final Set<String> serialFieldNames =
4540             Set.of("serialVersionUID", "serialPersistentFields");
4541 
4542         // Type of serialPersistentFields
4543         private final Type OSF_TYPE = new Type.ArrayType(syms.objectStreamFieldType, syms.arrayClass);
4544 
4545         Lint lint;
4546 
4547         @Override
4548         public Void defaultAction(Element e, JCClassDecl p) {
4549             throw new IllegalArgumentException(Objects.requireNonNullElse(e.toString(), ""));
4550         }
4551 
4552         @Override
4553         public Void visitType(TypeElement e, JCClassDecl p) {
4554             runUnderLint(e, p, (symbol, param) -> super.visitType(symbol, param));
4555             return null;
4556         }
4557 
4558         @Override
4559         public Void visitTypeAsClass(TypeElement e,
4560                                      JCClassDecl p) {
4561             // Anonymous classes filtered out by caller.
4562 
4563             ClassSymbol c = (ClassSymbol)e;
4564 
4565             checkCtorAccess(p, c);
4566 
4567             // Check for missing serialVersionUID; check *not* done
4568             // for enums or records.
4569             VarSymbol svuidSym = null;
4570             for (Symbol sym : c.members().getSymbolsByName(names.serialVersionUID)) {
4571                 if (sym.kind == VAR) {
4572                     svuidSym = (VarSymbol)sym;
4573                     break;
4574                 }
4575             }
4576 
4577             if (svuidSym == null) {
4578                 log.warning(LintCategory.SERIAL, p.pos(), Warnings.MissingSVUID(c));
4579             }
4580 
4581             // Check for serialPersistentFields to gate checks for
4582             // non-serializable non-transient instance fields
4583             boolean serialPersistentFieldsPresent =
4584                     c.members()
4585                      .getSymbolsByName(names.serialPersistentFields, sym -> sym.kind == VAR)
4586                      .iterator()
4587                      .hasNext();
4588 
4589             // Check declarations of serialization-related methods and
4590             // fields
4591             for(Symbol el : c.getEnclosedElements()) {
4592                 runUnderLint(el, p, (enclosed, tree) -> {
4593                     String name = null;
4594                     switch(enclosed.getKind()) {
4595                     case FIELD -> {
4596                         if (!serialPersistentFieldsPresent) {
4597                             var flags = enclosed.flags();
4598                             if ( ((flags & TRANSIENT) == 0) &&
4599                                  ((flags & STATIC) == 0)) {
4600                                 Type varType = enclosed.asType();
4601                                 if (!canBeSerialized(varType)) {
4602                                     // Note per JLS arrays are
4603                                     // serializable even if the
4604                                     // component type is not.
4605                                     log.warning(LintCategory.SERIAL,
4606                                                 TreeInfo.diagnosticPositionFor(enclosed, tree),
4607                                                 Warnings.NonSerializableInstanceField);
4608                                 } else if (varType.hasTag(ARRAY)) {
4609                                     ArrayType arrayType = (ArrayType)varType;
4610                                     Type elementType = arrayType.elemtype;
4611                                     while (elementType.hasTag(ARRAY)) {
4612                                         arrayType = (ArrayType)elementType;
4613                                         elementType = arrayType.elemtype;
4614                                     }
4615                                     if (!canBeSerialized(elementType)) {
4616                                         log.warning(LintCategory.SERIAL,
4617                                                     TreeInfo.diagnosticPositionFor(enclosed, tree),
4618                                                     Warnings.NonSerializableInstanceFieldArray(elementType));
4619                                     }
4620                                 }
4621                             }
4622                         }
4623 
4624                         name = enclosed.getSimpleName().toString();
4625                         if (serialFieldNames.contains(name)) {
4626                             VarSymbol field = (VarSymbol)enclosed;
4627                             switch (name) {
4628                             case "serialVersionUID"       ->  checkSerialVersionUID(tree, e, field);
4629                             case "serialPersistentFields" ->  checkSerialPersistentFields(tree, e, field);
4630                             default -> throw new AssertionError();
4631                             }
4632                         }
4633                     }
4634 
4635                     // Correctly checking the serialization-related
4636                     // methods is subtle. For the methods declared to be
4637                     // private or directly declared in the class, the
4638                     // enclosed elements of the class can be checked in
4639                     // turn. However, writeReplace and readResolve can be
4640                     // declared in a superclass and inherited. Note that
4641                     // the runtime lookup walks the superclass chain
4642                     // looking for writeReplace/readResolve via
4643                     // Class.getDeclaredMethod. This differs from calling
4644                     // Elements.getAllMembers(TypeElement) as the latter
4645                     // will also pull in default methods from
4646                     // superinterfaces. In other words, the runtime checks
4647                     // (which long predate default methods on interfaces)
4648                     // do not admit the possibility of inheriting methods
4649                     // this way, a difference from general inheritance.
4650 
4651                     // The current implementation just checks the enclosed
4652                     // elements and does not directly check the inherited
4653                     // methods. If all the types are being checked this is
4654                     // less of a concern; however, there are cases that
4655                     // could be missed. In particular, readResolve and
4656                     // writeReplace could, in principle, by inherited from
4657                     // a non-serializable superclass and thus not checked
4658                     // even if compiled with a serializable child class.
4659                     case METHOD -> {
4660                         var method = (MethodSymbol)enclosed;
4661                         name = method.getSimpleName().toString();
4662                         if (serialMethodNames.contains(name)) {
4663                             switch (name) {
4664                             case "writeObject"      -> checkWriteObject(tree, e, method);
4665                             case "writeReplace"     -> checkWriteReplace(tree,e, method);
4666                             case "readObject"       -> checkReadObject(tree,e, method);
4667                             case "readObjectNoData" -> checkReadObjectNoData(tree, e, method);
4668                             case "readResolve"      -> checkReadResolve(tree, e, method);
4669                             default ->  throw new AssertionError();
4670                             }
4671                         }
4672                     }
4673                     }
4674                 });
4675             }
4676 
4677             return null;
4678         }
4679 
4680         boolean canBeSerialized(Type type) {
4681             return type.isPrimitive() || rs.isSerializable(type);
4682         }
4683 
4684         /**
4685          * Check that Externalizable class needs a public no-arg
4686          * constructor.
4687          *
4688          * Check that a Serializable class has access to the no-arg
4689          * constructor of its first nonserializable superclass.
4690          */
4691         private void checkCtorAccess(JCClassDecl tree, ClassSymbol c) {
4692             if (isExternalizable(c.type)) {
4693                 for(var sym : c.getEnclosedElements()) {
4694                     if (sym.isConstructor() &&
4695                         ((sym.flags() & PUBLIC) == PUBLIC)) {
4696                         if (((MethodSymbol)sym).getParameters().isEmpty()) {
4697                             return;
4698                         }
4699                     }
4700                 }
4701                 log.warning(LintCategory.SERIAL, tree.pos(),
4702                             Warnings.ExternalizableMissingPublicNoArgCtor);
4703             } else {
4704                 // Approximate access to the no-arg constructor up in
4705                 // the superclass chain by checking that the
4706                 // constructor is not private. This may not handle
4707                 // some cross-package situations correctly.
4708                 Type superClass = c.getSuperclass();
4709                 // java.lang.Object is *not* Serializable so this loop
4710                 // should terminate.
4711                 while (rs.isSerializable(superClass) ) {
4712                     try {
4713                         superClass = (Type)((TypeElement)(((DeclaredType)superClass)).asElement()).getSuperclass();
4714                     } catch(ClassCastException cce) {
4715                         return ; // Don't try to recover
4716                     }
4717                 }
4718                 // Non-Serializable superclass
4719                 try {
4720                     ClassSymbol supertype = ((ClassSymbol)(((DeclaredType)superClass).asElement()));
4721                     for(var sym : supertype.getEnclosedElements()) {
4722                         if (sym.isConstructor()) {
4723                             MethodSymbol ctor = (MethodSymbol)sym;
4724                             if (ctor.getParameters().isEmpty()) {
4725                                 if (((ctor.flags() & PRIVATE) == PRIVATE) ||
4726                                     // Handle nested classes and implicit this$0
4727                                     (supertype.getNestingKind() == NestingKind.MEMBER &&
4728                                      ((supertype.flags() & STATIC) == 0)))
4729                                     log.warning(LintCategory.SERIAL, tree.pos(),
4730                                                 Warnings.SerializableMissingAccessNoArgCtor(supertype.getQualifiedName()));
4731                             }
4732                         }
4733                     }
4734                 } catch (ClassCastException cce) {
4735                     return ; // Don't try to recover
4736                 }
4737                 return;
4738             }
4739         }
4740 
4741         private void checkSerialVersionUID(JCClassDecl tree, Element e, VarSymbol svuid) {
4742             // To be effective, serialVersionUID must be marked static
4743             // and final, but private is recommended. But alas, in
4744             // practice there are many non-private serialVersionUID
4745             // fields.
4746              if ((svuid.flags() & (STATIC | FINAL)) !=
4747                  (STATIC | FINAL)) {
4748                  log.warning(LintCategory.SERIAL,
4749                              TreeInfo.diagnosticPositionFor(svuid, tree),
4750                              Warnings.ImproperSVUID((Symbol)e));
4751              }
4752 
4753              // check svuid has type long
4754              if (!svuid.type.hasTag(LONG)) {
4755                  log.warning(LintCategory.SERIAL,
4756                              TreeInfo.diagnosticPositionFor(svuid, tree),
4757                              Warnings.LongSVUID((Symbol)e));
4758              }
4759 
4760              if (svuid.getConstValue() == null)
4761                  log.warning(LintCategory.SERIAL,
4762                             TreeInfo.diagnosticPositionFor(svuid, tree),
4763                              Warnings.ConstantSVUID((Symbol)e));
4764         }
4765 
4766         private void checkSerialPersistentFields(JCClassDecl tree, Element e, VarSymbol spf) {
4767             // To be effective, serialPersisentFields must be private, static, and final.
4768              if ((spf.flags() & (PRIVATE | STATIC | FINAL)) !=
4769                  (PRIVATE | STATIC | FINAL)) {
4770                  log.warning(LintCategory.SERIAL,
4771                              TreeInfo.diagnosticPositionFor(spf, tree), Warnings.ImproperSPF);
4772              }
4773 
4774              if (!types.isSameType(spf.type, OSF_TYPE)) {
4775                  log.warning(LintCategory.SERIAL,
4776                              TreeInfo.diagnosticPositionFor(spf, tree), Warnings.OSFArraySPF);
4777              }
4778 
4779             if (isExternalizable((Type)(e.asType()))) {
4780                 log.warning(LintCategory.SERIAL, tree.pos(),
4781                             Warnings.IneffectualSerialFieldExternalizable);
4782             }
4783 
4784             // Warn if serialPersistentFields is initialized to a
4785             // literal null.
4786             JCTree spfDecl = TreeInfo.declarationFor(spf, tree);
4787             if (spfDecl != null && spfDecl.getTag() == VARDEF) {
4788                 JCVariableDecl variableDef = (JCVariableDecl) spfDecl;
4789                 JCExpression initExpr = variableDef.init;
4790                  if (initExpr != null && TreeInfo.isNull(initExpr)) {
4791                      log.warning(LintCategory.SERIAL, initExpr.pos(),
4792                                  Warnings.SPFNullInit);
4793                  }
4794             }
4795         }
4796 
4797         private void checkWriteObject(JCClassDecl tree, Element e, MethodSymbol method) {
4798             // The "synchronized" modifier is seen in the wild on
4799             // readObject and writeObject methods and is generally
4800             // innocuous.
4801 
4802             // private void writeObject(ObjectOutputStream stream) throws IOException
4803             checkPrivateNonStaticMethod(tree, method);
4804             checkReturnType(tree, e, method, syms.voidType);
4805             checkOneArg(tree, e, method, syms.objectOutputStreamType);
4806             checkExceptions(tree, e, method, syms.ioExceptionType);
4807             checkExternalizable(tree, e, method);
4808         }
4809 
4810         private void checkWriteReplace(JCClassDecl tree, Element e, MethodSymbol method) {
4811             // ANY-ACCESS-MODIFIER Object writeReplace() throws
4812             // ObjectStreamException
4813 
4814             // Excluding abstract, could have a more complicated
4815             // rule based on abstract-ness of the class
4816             checkConcreteInstanceMethod(tree, e, method);
4817             checkReturnType(tree, e, method, syms.objectType);
4818             checkNoArgs(tree, e, method);
4819             checkExceptions(tree, e, method, syms.objectStreamExceptionType);
4820         }
4821 
4822         private void checkReadObject(JCClassDecl tree, Element e, MethodSymbol method) {
4823             // The "synchronized" modifier is seen in the wild on
4824             // readObject and writeObject methods and is generally
4825             // innocuous.
4826 
4827             // private void readObject(ObjectInputStream stream)
4828             //   throws IOException, ClassNotFoundException
4829             checkPrivateNonStaticMethod(tree, method);
4830             checkReturnType(tree, e, method, syms.voidType);
4831             checkOneArg(tree, e, method, syms.objectInputStreamType);
4832             checkExceptions(tree, e, method, syms.ioExceptionType, syms.classNotFoundExceptionType);
4833             checkExternalizable(tree, e, method);
4834         }
4835 
4836         private void checkReadObjectNoData(JCClassDecl tree, Element e, MethodSymbol method) {
4837             // private void readObjectNoData() throws ObjectStreamException
4838             checkPrivateNonStaticMethod(tree, method);
4839             checkReturnType(tree, e, method, syms.voidType);
4840             checkNoArgs(tree, e, method);
4841             checkExceptions(tree, e, method, syms.objectStreamExceptionType);
4842             checkExternalizable(tree, e, method);
4843         }
4844 
4845         private void checkReadResolve(JCClassDecl tree, Element e, MethodSymbol method) {
4846             // ANY-ACCESS-MODIFIER Object readResolve()
4847             // throws ObjectStreamException
4848 
4849             // Excluding abstract, could have a more complicated
4850             // rule based on abstract-ness of the class
4851             checkConcreteInstanceMethod(tree, e, method);
4852             checkReturnType(tree,e, method, syms.objectType);
4853             checkNoArgs(tree, e, method);
4854             checkExceptions(tree, e, method, syms.objectStreamExceptionType);
4855         }
4856 
4857         void checkPrivateNonStaticMethod(JCClassDecl tree, MethodSymbol method) {
4858             var flags = method.flags();
4859             if ((flags & PRIVATE) == 0) {
4860                 log.warning(LintCategory.SERIAL,
4861                             TreeInfo.diagnosticPositionFor(method, tree),
4862                             Warnings.SerialMethodNotPrivate(method.getSimpleName()));
4863             }
4864 
4865             if ((flags & STATIC) != 0) {
4866                 log.warning(LintCategory.SERIAL,
4867                             TreeInfo.diagnosticPositionFor(method, tree),
4868                             Warnings.SerialMethodStatic(method.getSimpleName()));
4869             }
4870         }
4871 
4872         /**
4873          * Per section 1.12 "Serialization of Enum Constants" of
4874          * the serialization specification, due to the special
4875          * serialization handling of enums, any writeObject,
4876          * readObject, writeReplace, and readResolve methods are
4877          * ignored as are serialPersistentFields and
4878          * serialVersionUID fields.
4879          */
4880         @Override
4881         public Void visitTypeAsEnum(TypeElement e,
4882                                     JCClassDecl p) {
4883             for(Element el : e.getEnclosedElements()) {
4884                 runUnderLint(el, p, (enclosed, tree) -> {
4885                     String name = enclosed.getSimpleName().toString();
4886                     switch(enclosed.getKind()) {
4887                     case FIELD -> {
4888                         if (serialFieldNames.contains(name)) {
4889                             log.warning(LintCategory.SERIAL, tree.pos(),
4890                                         Warnings.IneffectualSerialFieldEnum(name));
4891                         }
4892                     }
4893 
4894                     case METHOD -> {
4895                         if (serialMethodNames.contains(name)) {
4896                             log.warning(LintCategory.SERIAL, tree.pos(),
4897                                         Warnings.IneffectualSerialMethodEnum(name));
4898                         }
4899                     }
4900                     }
4901                 });
4902             }
4903             return null;
4904         }
4905 
4906         /**
4907          * Most serialization-related fields and methods on interfaces
4908          * are ineffectual or problematic.
4909          */
4910         @Override
4911         public Void visitTypeAsInterface(TypeElement e,
4912                                          JCClassDecl p) {
4913             for(Element el : e.getEnclosedElements()) {
4914                 runUnderLint(el, p, (enclosed, tree) -> {
4915                     String name = null;
4916                     switch(enclosed.getKind()) {
4917                     case FIELD -> {
4918                         var field = (VarSymbol)enclosed;
4919                         name = field.getSimpleName().toString();
4920                         switch(name) {
4921                         case "serialPersistentFields" -> {
4922                             log.warning(LintCategory.SERIAL,
4923                                         TreeInfo.diagnosticPositionFor(field, tree),
4924                                         Warnings.IneffectualSerialFieldInterface);
4925                         }
4926 
4927                         case "serialVersionUID" -> {
4928                             checkSerialVersionUID(tree, e, field);
4929                         }
4930                         }
4931                     }
4932 
4933                     case METHOD -> {
4934                         var method = (MethodSymbol)enclosed;
4935                         name = enclosed.getSimpleName().toString();
4936                         if (serialMethodNames.contains(name)) {
4937                             switch (name) {
4938                             case
4939                                 "readObject",
4940                                 "readObjectNoData",
4941                                 "writeObject"      -> checkPrivateMethod(tree, e, method);
4942 
4943                             case
4944                                 "writeReplace",
4945                                 "readResolve"      -> checkDefaultIneffective(tree, e, method);
4946 
4947                             default ->  throw new AssertionError();
4948                             }
4949 
4950                         }
4951                     }
4952                     }
4953                 });
4954             }
4955 
4956             return null;
4957         }
4958 
4959         private void checkPrivateMethod(JCClassDecl tree,
4960                                         Element e,
4961                                         MethodSymbol method) {
4962             if ((method.flags() & PRIVATE) == 0) {
4963                 log.warning(LintCategory.SERIAL,
4964                             TreeInfo.diagnosticPositionFor(method, tree),
4965                             Warnings.NonPrivateMethodWeakerAccess);
4966             }
4967         }
4968 
4969         private void checkDefaultIneffective(JCClassDecl tree,
4970                                              Element e,
4971                                              MethodSymbol method) {
4972             if ((method.flags() & DEFAULT) == DEFAULT) {
4973                 log.warning(LintCategory.SERIAL,
4974                             TreeInfo.diagnosticPositionFor(method, tree),
4975                             Warnings.DefaultIneffective);
4976 
4977             }
4978         }
4979 
4980         @Override
4981         public Void visitTypeAsAnnotationType(TypeElement e,
4982                                               JCClassDecl p) {
4983             // Per the JLS, annotation types are not serializeable
4984             return null;
4985         }
4986 
4987         /**
4988          * From the Java Object Serialization Specification, 1.13
4989          * Serialization of Records:
4990          *
4991          * "The process by which record objects are serialized or
4992          * externalized cannot be customized; any class-specific
4993          * writeObject, readObject, readObjectNoData, writeExternal,
4994          * and readExternal methods defined by record classes are
4995          * ignored during serialization and deserialization. However,
4996          * a substitute object to be serialized or a designate
4997          * replacement may be specified, by the writeReplace and
4998          * readResolve methods, respectively. Any
4999          * serialPersistentFields field declaration is
5000          * ignored. Documenting serializable fields and data for
5001          * record classes is unnecessary, since there is no variation
5002          * in the serial form, other than whether a substitute or
5003          * replacement object is used. The serialVersionUID of a
5004          * record class is 0L unless explicitly declared. The
5005          * requirement for matching serialVersionUID values is waived
5006          * for record classes."
5007          */
5008         @Override
5009         public Void visitTypeAsRecord(TypeElement e,
5010                                       JCClassDecl p) {
5011             for(Element el : e.getEnclosedElements()) {
5012                 runUnderLint(el, p, (enclosed, tree) -> {
5013                     String name = enclosed.getSimpleName().toString();
5014                     switch(enclosed.getKind()) {
5015                     case FIELD -> {
5016                         switch(name) {
5017                         case "serialPersistentFields" -> {
5018                             log.warning(LintCategory.SERIAL, tree.pos(),
5019                                         Warnings.IneffectualSerialFieldRecord);
5020                         }
5021 
5022                         case "serialVersionUID" -> {
5023                             // Could generate additional warning that
5024                             // svuid value is not checked to match for
5025                             // records.
5026                             checkSerialVersionUID(tree, e, (VarSymbol)enclosed);
5027                         }
5028 
5029                         }
5030                     }
5031 
5032                     case METHOD -> {
5033                         var method = (MethodSymbol)enclosed;
5034                         switch(name) {
5035                         case "writeReplace" -> checkWriteReplace(tree, e, method);
5036                         case "readResolve"  -> checkReadResolve(tree, e, method);
5037                         default -> {
5038                             if (serialMethodNames.contains(name)) {
5039                                 log.warning(LintCategory.SERIAL, tree.pos(),
5040                                             Warnings.IneffectualSerialMethodRecord(name));
5041                             }
5042                         }
5043                         }
5044 
5045                     }
5046                     }
5047                 });
5048             }
5049             return null;
5050         }
5051 
5052         void checkConcreteInstanceMethod(JCClassDecl tree,
5053                                          Element enclosing,
5054                                          MethodSymbol method) {
5055             if ((method.flags() & (STATIC | ABSTRACT)) != 0) {
5056                     log.warning(LintCategory.SERIAL,
5057                                 TreeInfo.diagnosticPositionFor(method, tree),
5058                                 Warnings.SerialConcreteInstanceMethod(method.getSimpleName()));
5059             }
5060         }
5061 
5062         private void checkReturnType(JCClassDecl tree,
5063                                      Element enclosing,
5064                                      MethodSymbol method,
5065                                      Type expectedReturnType) {
5066             // Note: there may be complications checking writeReplace
5067             // and readResolve since they return Object and could, in
5068             // principle, have covariant overrides and any synthetic
5069             // bridge method would not be represented here for
5070             // checking.
5071             Type rtype = method.getReturnType();
5072             if (!types.isSameType(expectedReturnType, rtype)) {
5073                 log.warning(LintCategory.SERIAL,
5074                             TreeInfo.diagnosticPositionFor(method, tree),
5075                             Warnings.SerialMethodUnexpectedReturnType(method.getSimpleName(),
5076                                                                       rtype, expectedReturnType));
5077             }
5078         }
5079 
5080         private void checkOneArg(JCClassDecl tree,
5081                                  Element enclosing,
5082                                  MethodSymbol method,
5083                                  Type expectedType) {
5084             String name = method.getSimpleName().toString();
5085 
5086             var parameters= method.getParameters();
5087 
5088             if (parameters.size() != 1) {
5089                 log.warning(LintCategory.SERIAL,
5090                             TreeInfo.diagnosticPositionFor(method, tree),
5091                             Warnings.SerialMethodOneArg(method.getSimpleName(), parameters.size()));
5092                 return;
5093             }
5094 
5095             Type parameterType = parameters.get(0).asType();
5096             if (!types.isSameType(parameterType, expectedType)) {
5097                 log.warning(LintCategory.SERIAL,
5098                             TreeInfo.diagnosticPositionFor(method, tree),
5099                             Warnings.SerialMethodParameterType(method.getSimpleName(),
5100                                                                expectedType,
5101                                                                parameterType));
5102             }
5103         }
5104 
5105         private void checkNoArgs(JCClassDecl tree, Element enclosing, MethodSymbol method) {
5106             var parameters = method.getParameters();
5107             if (!parameters.isEmpty()) {
5108                 log.warning(LintCategory.SERIAL,
5109                             TreeInfo.diagnosticPositionFor(parameters.get(0), tree),
5110                             Warnings.SerialMethodNoArgs(method.getSimpleName()));
5111             }
5112         }
5113 
5114         private void checkExternalizable(JCClassDecl tree, Element enclosing, MethodSymbol method) {
5115             // If the enclosing class is externalizable, warn for the method
5116             if (isExternalizable((Type)enclosing.asType())) {
5117                 log.warning(LintCategory.SERIAL, tree.pos(),
5118                             Warnings.IneffectualSerialMethodExternalizable(method.getSimpleName()));
5119             }
5120             return;
5121         }
5122 
5123         private void checkExceptions(JCClassDecl tree,
5124                                      Element enclosing,
5125                                      MethodSymbol method,
5126                                      Type... declaredExceptions) {
5127             for (Type thrownType: method.getThrownTypes()) {
5128                 // For each exception in the throws clause of the
5129                 // method, if not an Error and not a RuntimeException,
5130                 // check if the exception is a subtype of a declared
5131                 // exception from the throws clause of the
5132                 // serialization method in question.
5133                 if (types.isSubtype(thrownType, syms.runtimeExceptionType) ||
5134                     types.isSubtype(thrownType, syms.errorType) ) {
5135                     continue;
5136                 } else {
5137                     boolean declared = false;
5138                     for (Type declaredException : declaredExceptions) {
5139                         if (types.isSubtype(thrownType, declaredException)) {
5140                             declared = true;
5141                             continue;
5142                         }
5143                     }
5144                     if (!declared) {
5145                         log.warning(LintCategory.SERIAL,
5146                                     TreeInfo.diagnosticPositionFor(method, tree),
5147                                     Warnings.SerialMethodUnexpectedException(method.getSimpleName(),
5148                                                                              thrownType));
5149                     }
5150                 }
5151             }
5152             return;
5153         }
5154 
5155         private <E extends Element> Void runUnderLint(E symbol, JCClassDecl p, BiConsumer<E, JCClassDecl> task) {
5156             Lint prevLint = lint;
5157             try {
5158                 lint = lint.augment((Symbol) symbol);
5159 
5160                 if (lint.isEnabled(LintCategory.SERIAL)) {
5161                     task.accept(symbol, p);
5162                 }
5163 
5164                 return null;
5165             } finally {
5166                 lint = prevLint;
5167             }
5168         }
5169 
5170     }
5171 
5172 }