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