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