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