1 /*
   2  * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.tools.javac.comp;
  27 
  28 import java.util.*;
  29 import java.util.function.BiConsumer;
  30 import java.util.function.BiPredicate;
  31 import java.util.function.Predicate;
  32 import java.util.function.Supplier;
  33 import java.util.function.ToIntBiFunction;
  34 import java.util.stream.Collectors;
  35 import java.util.stream.StreamSupport;
  36 
  37 import javax.lang.model.element.ElementKind;
  38 import javax.lang.model.element.NestingKind;
  39 import javax.tools.JavaFileManager;
  40 
  41 import com.sun.source.tree.CaseTree;
  42 import com.sun.tools.javac.code.*;
  43 import com.sun.tools.javac.code.Attribute.Compound;
  44 import com.sun.tools.javac.code.Directive.ExportsDirective;
  45 import com.sun.tools.javac.code.Directive.RequiresDirective;
  46 import com.sun.tools.javac.code.Source.Feature;
  47 import com.sun.tools.javac.comp.Annotate.AnnotationTypeMetadata;
  48 import com.sun.tools.javac.jvm.*;
  49 import com.sun.tools.javac.resources.CompilerProperties;
  50 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  51 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  52 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
  53 import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
  54 import com.sun.tools.javac.tree.*;
  55 import com.sun.tools.javac.util.*;
  56 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
  57 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  58 import com.sun.tools.javac.util.JCDiagnostic.Error;
  59 import com.sun.tools.javac.util.JCDiagnostic.Fragment;
  60 import com.sun.tools.javac.util.JCDiagnostic.LintWarning;
  61 import com.sun.tools.javac.util.List;
  62 
  63 import com.sun.tools.javac.code.Lint;
  64 import com.sun.tools.javac.code.Lint.LintCategory;
  65 import com.sun.tools.javac.code.Scope.WriteableScope;
  66 import com.sun.tools.javac.code.Type.*;
  67 import com.sun.tools.javac.code.Symbol.*;
  68 import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
  69 import com.sun.tools.javac.tree.JCTree.*;
  70 
  71 import static com.sun.tools.javac.code.Flags.*;
  72 import static com.sun.tools.javac.code.Flags.ANNOTATION;
  73 import static com.sun.tools.javac.code.Flags.SYNCHRONIZED;
  74 import static com.sun.tools.javac.code.Kinds.*;
  75 import static com.sun.tools.javac.code.Kinds.Kind.*;
  76 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
  77 import static com.sun.tools.javac.code.Scope.LookupKind.RECURSIVE;
  78 import static com.sun.tools.javac.code.TypeTag.*;
  79 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
  80 
  81 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  82 import javax.lang.model.element.Element;
  83 import javax.lang.model.element.TypeElement;
  84 import javax.lang.model.type.DeclaredType;
  85 import javax.lang.model.util.ElementKindVisitor14;
  86 
  87 /** Type checking helper class for the attribution phase.
  88  *
  89  *  <p><b>This is NOT part of any supported API.
  90  *  If you write code that depends on this, you do so at your own risk.
  91  *  This code and its internal interfaces are subject to change or
  92  *  deletion without notice.</b>
  93  */
  94 public class Check {
  95     protected static final Context.Key<Check> checkKey = new Context.Key<>();
  96 
  97     // Flag bits indicating which item(s) chosen from a pair of items
  98     private static final int FIRST = 0x01;
  99     private static final int SECOND = 0x02;
 100 
 101     private final Names names;
 102     private final Log log;
 103     private final Resolve rs;
 104     private final Symtab syms;
 105     private final Enter enter;
 106     private final DeferredAttr deferredAttr;
 107     private final Infer infer;
 108     private final Types types;
 109     private final TypeAnnotations typeAnnotations;
 110     private final JCDiagnostic.Factory diags;
 111     private final JavaFileManager fileManager;
 112     private final Source source;
 113     private final Target target;
 114     private final Profile profile;
 115     private final Preview preview;
 116     private final boolean warnOnAnyAccessToMembers;
 117 
 118     public boolean disablePreviewCheck;
 119 
 120     // The set of lint options currently in effect. It is initialized
 121     // from the context, and then is set/reset as needed by Attr as it
 122     // visits all the various parts of the trees during attribution.
 123     private Lint lint;
 124 
 125     // The method being analyzed in Attr - it is set/reset as needed by
 126     // Attr as it visits new method declarations.
 127     private MethodSymbol method;
 128 
 129     public static Check instance(Context context) {
 130         Check instance = context.get(checkKey);
 131         if (instance == null)
 132             instance = new Check(context);
 133         return instance;
 134     }
 135 
 136     @SuppressWarnings("this-escape")
 137     protected Check(Context context) {
 138         context.put(checkKey, this);
 139 
 140         names = Names.instance(context);
 141         log = Log.instance(context);
 142         rs = Resolve.instance(context);
 143         syms = Symtab.instance(context);
 144         enter = Enter.instance(context);
 145         deferredAttr = DeferredAttr.instance(context);
 146         infer = Infer.instance(context);
 147         types = Types.instance(context);
 148         typeAnnotations = TypeAnnotations.instance(context);
 149         diags = JCDiagnostic.Factory.instance(context);
 150         Options options = Options.instance(context);
 151         lint = Lint.instance(context);
 152         fileManager = context.get(JavaFileManager.class);
 153 
 154         source = Source.instance(context);
 155         target = Target.instance(context);
 156         warnOnAnyAccessToMembers = options.isSet("warnOnAccessToMembers");
 157 
 158         disablePreviewCheck = false;
 159 
 160         Target target = Target.instance(context);
 161         syntheticNameChar = target.syntheticNameChar();
 162 
 163         profile = Profile.instance(context);
 164         preview = Preview.instance(context);
 165 
 166         allowModules = Feature.MODULES.allowedInSource(source);
 167         allowRecords = Feature.RECORDS.allowedInSource(source);
 168         allowSealed = Feature.SEALED_CLASSES.allowedInSource(source);
 169         allowPrimitivePatterns = preview.isEnabled() && Feature.PRIMITIVE_PATTERNS.allowedInSource(source);
 170         allowValueClasses = preview.isEnabled() && Feature.VALUE_CLASSES.allowedInSource(source);
 171     }
 172 
 173     /** Character for synthetic names
 174      */
 175     char syntheticNameChar;
 176 
 177     /** A table mapping flat names of all compiled classes for each module in this run
 178      *  to their symbols; maintained from outside.
 179      */
 180     private Map<Pair<ModuleSymbol, Name>,ClassSymbol> compiled = new HashMap<>();
 181 
 182     /** Are modules allowed
 183      */
 184     private final boolean allowModules;
 185 
 186     /** Are records allowed
 187      */
 188     private final boolean allowRecords;
 189 
 190     /** Are sealed classes allowed
 191      */
 192     private final boolean allowSealed;
 193 
 194     /** Are primitive patterns allowed
 195      */
 196     private final boolean allowPrimitivePatterns;
 197 
 198     /** Are value classes allowed
 199      */
 200     private final boolean allowValueClasses;
 201 
 202     /** Whether to force suppression of deprecation and preview warnings.
 203      *  This happens when attributing import statements for JDK 9+.
 204      *  @see Feature#DEPRECATION_ON_IMPORT
 205      */
 206     private boolean importSuppression;
 207 
 208 /* *************************************************************************
 209  * Errors and Warnings
 210  **************************************************************************/
 211 
 212     Lint setLint(Lint newLint) {
 213         Lint prev = lint;
 214         lint = newLint;
 215         return prev;
 216     }
 217 
 218     boolean setImportSuppression(boolean newImportSuppression) {
 219         boolean prev = importSuppression;
 220         importSuppression = newImportSuppression;
 221         return prev;
 222     }
 223 
 224     MethodSymbol setMethod(MethodSymbol newMethod) {
 225         MethodSymbol prev = method;
 226         method = newMethod;
 227         return prev;
 228     }
 229 
 230     /** Warn about deprecated symbol.
 231      *  @param pos        Position to be used for error reporting.
 232      *  @param sym        The deprecated symbol.
 233      */
 234     void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
 235         Assert.check(!importSuppression);
 236         LintWarning warningKey = sym.isDeprecatedForRemoval() ?
 237             (sym.kind == MDL ?
 238                 LintWarnings.HasBeenDeprecatedForRemovalModule(sym) :
 239                 LintWarnings.HasBeenDeprecatedForRemoval(sym, sym.location())) :
 240             (sym.kind == MDL ?
 241                 LintWarnings.HasBeenDeprecatedModule(sym) :
 242                 LintWarnings.HasBeenDeprecated(sym, sym.location()));
 243         log.warning(pos, warningKey);
 244     }
 245 
 246     /** Log a preview warning.
 247      *  @param pos        Position to be used for error reporting.
 248      *  @param msg        A Warning describing the problem.
 249      */
 250     public void warnPreviewAPI(DiagnosticPosition pos, LintWarning warnKey) {
 251         if (!importSuppression)
 252             log.warning(pos, warnKey);
 253     }
 254 
 255     /** Warn about unchecked operation.
 256      *  @param pos        Position to be used for error reporting.
 257      *  @param msg        A string describing the problem.
 258      */
 259     public void warnUnchecked(DiagnosticPosition pos, LintWarning warnKey) {
 260         log.warning(pos, warnKey);
 261     }
 262 
 263     /** Report a failure to complete a class.
 264      *  @param pos        Position to be used for error reporting.
 265      *  @param ex         The failure to report.
 266      */
 267     public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
 268         log.error(DiagnosticFlag.NON_DEFERRABLE, pos, Errors.CantAccess(ex.sym, ex.getDetailValue()));
 269         return syms.errType;
 270     }
 271 
 272     /** Report an error that wrong type tag was found.
 273      *  @param pos        Position to be used for error reporting.
 274      *  @param required   An internationalized string describing the type tag
 275      *                    required.
 276      *  @param type       The type that was found.
 277      */
 278     Type typeTagError(DiagnosticPosition pos, JCDiagnostic required, Type type) {
 279         // this error used to be raised by the parser,
 280         // but has been delayed to this point:
 281         if (type.hasTag(VOID)) {
 282             log.error(pos, Errors.IllegalStartOfType);
 283             return syms.errType;
 284         }
 285         log.error(pos, Errors.TypeFoundReq(asTypeParam(type), required));
 286         return types.createErrorType(type);
 287     }
 288 
 289     /** Report duplicate declaration error.
 290      */
 291     void duplicateError(DiagnosticPosition pos, Symbol sym) {
 292         if (!sym.type.isErroneous()) {
 293             Symbol location = sym.location();
 294             if (location.kind == MTH &&
 295                     ((MethodSymbol)location).isStaticOrInstanceInit()) {
 296                 log.error(pos,
 297                           Errors.AlreadyDefinedInClinit(kindName(sym),
 298                                                         sym,
 299                                                         kindName(sym.location()),
 300                                                         kindName(sym.location().enclClass()),
 301                                                         sym.location().enclClass()));
 302             } else {
 303                 /* dont error if this is a duplicated parameter of a generated canonical constructor
 304                  * as we should have issued an error for the duplicated fields
 305                  */
 306                 if (location.kind != MTH ||
 307                         ((sym.owner.flags_field & GENERATEDCONSTR) == 0) ||
 308                         ((sym.owner.flags_field & RECORD) == 0)) {
 309                     log.error(pos,
 310                             Errors.AlreadyDefined(kindName(sym),
 311                                     sym,
 312                                     kindName(sym.location()),
 313                                     sym.location()));
 314                 }
 315             }
 316         }
 317     }
 318 
 319     /** Report array/varargs duplicate declaration
 320      */
 321     void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
 322         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
 323             log.error(pos, Errors.ArrayAndVarargs(sym1, sym2, sym2.location()));
 324         }
 325     }
 326 
 327 /* ************************************************************************
 328  * duplicate declaration checking
 329  *************************************************************************/
 330 
 331     /** Check that variable does not hide variable with same name in
 332      *  immediately enclosing local scope.
 333      *  @param pos           Position for error reporting.
 334      *  @param v             The symbol.
 335      *  @param s             The scope.
 336      */
 337     void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
 338         for (Symbol sym : s.getSymbolsByName(v.name)) {
 339             if (sym.owner != v.owner) break;
 340             if (sym.kind == VAR &&
 341                 sym.owner.kind.matches(KindSelector.VAL_MTH) &&
 342                 v.name != names.error) {
 343                 duplicateError(pos, sym);
 344                 return;
 345             }
 346         }
 347     }
 348 
 349     /** Check that a class or interface does not hide a class or
 350      *  interface with same name in immediately enclosing local scope.
 351      *  @param pos           Position for error reporting.
 352      *  @param c             The symbol.
 353      *  @param s             The scope.
 354      */
 355     void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
 356         for (Symbol sym : s.getSymbolsByName(c.name)) {
 357             if (sym.owner != c.owner) break;
 358             if (sym.kind == TYP && !sym.type.hasTag(TYPEVAR) &&
 359                 sym.owner.kind.matches(KindSelector.VAL_MTH) &&
 360                 c.name != names.error) {
 361                 duplicateError(pos, sym);
 362                 return;
 363             }
 364         }
 365     }
 366 
 367     /** Check that class does not have the same name as one of
 368      *  its enclosing classes, or as a class defined in its enclosing scope.
 369      *  return true if class is unique in its enclosing scope.
 370      *  @param pos           Position for error reporting.
 371      *  @param name          The class name.
 372      *  @param s             The enclosing scope.
 373      */
 374     boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
 375         for (Symbol sym : s.getSymbolsByName(name, NON_RECURSIVE)) {
 376             if (sym.kind == TYP && sym.name != names.error) {
 377                 duplicateError(pos, sym);
 378                 return false;
 379             }
 380         }
 381         for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
 382             if (sym.kind == TYP && sym.name == name && sym.name != names.error &&
 383                     !sym.isImplicit()) {
 384                 duplicateError(pos, sym);
 385                 return true;
 386             }
 387         }
 388         return true;
 389     }
 390 
 391 /* *************************************************************************
 392  * Class name generation
 393  **************************************************************************/
 394 
 395 
 396     private Map<Pair<Name, Name>, Integer> localClassNameIndexes = new HashMap<>();
 397 
 398     /** Return name of local class.
 399      *  This is of the form   {@code <enclClass> $ n <classname> }
 400      *  where
 401      *    enclClass is the flat name of the enclosing class,
 402      *    classname is the simple name of the local class
 403      */
 404     public Name localClassName(ClassSymbol c) {
 405         Name enclFlatname = c.owner.enclClass().flatname;
 406         String enclFlatnameStr = enclFlatname.toString();
 407         Pair<Name, Name> key = new Pair<>(enclFlatname, c.name);
 408         Integer index = localClassNameIndexes.get(key);
 409         for (int i = (index == null) ? 1 : index; ; i++) {
 410             Name flatname = names.fromString(enclFlatnameStr
 411                     + syntheticNameChar + i + c.name);
 412             if (getCompiled(c.packge().modle, flatname) == null) {
 413                 localClassNameIndexes.put(key, i + 1);
 414                 return flatname;
 415             }
 416         }
 417     }
 418 
 419     public void clearLocalClassNameIndexes(ClassSymbol c) {
 420         if (c.owner != null && c.owner.kind != NIL) {
 421             localClassNameIndexes.remove(new Pair<>(
 422                     c.owner.enclClass().flatname, c.name));
 423         }
 424     }
 425 
 426     public void newRound() {
 427         compiled.clear();
 428         localClassNameIndexes.clear();
 429     }
 430 
 431     public void putCompiled(ClassSymbol csym) {
 432         compiled.put(Pair.of(csym.packge().modle, csym.flatname), csym);
 433     }
 434 
 435     public ClassSymbol getCompiled(ClassSymbol csym) {
 436         return compiled.get(Pair.of(csym.packge().modle, csym.flatname));
 437     }
 438 
 439     public ClassSymbol getCompiled(ModuleSymbol msym, Name flatname) {
 440         return compiled.get(Pair.of(msym, flatname));
 441     }
 442 
 443     public void removeCompiled(ClassSymbol csym) {
 444         compiled.remove(Pair.of(csym.packge().modle, csym.flatname));
 445     }
 446 
 447 /* *************************************************************************
 448  * Type Checking
 449  **************************************************************************/
 450 
 451     /**
 452      * A check context is an object that can be used to perform compatibility
 453      * checks - depending on the check context, meaning of 'compatibility' might
 454      * vary significantly.
 455      */
 456     public interface CheckContext {
 457         /**
 458          * Is type 'found' compatible with type 'req' in given context
 459          */
 460         boolean compatible(Type found, Type req, Warner warn);
 461         /**
 462          * Report a check error
 463          */
 464         void report(DiagnosticPosition pos, JCDiagnostic details);
 465         /**
 466          * Obtain a warner for this check context
 467          */
 468         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req);
 469 
 470         public InferenceContext inferenceContext();
 471 
 472         public DeferredAttr.DeferredAttrContext deferredAttrContext();
 473     }
 474 
 475     /**
 476      * This class represent a check context that is nested within another check
 477      * context - useful to check sub-expressions. The default behavior simply
 478      * redirects all method calls to the enclosing check context leveraging
 479      * the forwarding pattern.
 480      */
 481     static class NestedCheckContext implements CheckContext {
 482         CheckContext enclosingContext;
 483 
 484         NestedCheckContext(CheckContext enclosingContext) {
 485             this.enclosingContext = enclosingContext;
 486         }
 487 
 488         public boolean compatible(Type found, Type req, Warner warn) {
 489             return enclosingContext.compatible(found, req, warn);
 490         }
 491 
 492         public void report(DiagnosticPosition pos, JCDiagnostic details) {
 493             enclosingContext.report(pos, details);
 494         }
 495 
 496         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
 497             return enclosingContext.checkWarner(pos, found, req);
 498         }
 499 
 500         public InferenceContext inferenceContext() {
 501             return enclosingContext.inferenceContext();
 502         }
 503 
 504         public DeferredAttrContext deferredAttrContext() {
 505             return enclosingContext.deferredAttrContext();
 506         }
 507     }
 508 
 509     /**
 510      * Check context to be used when evaluating assignment/return statements
 511      */
 512     CheckContext basicHandler = new CheckContext() {
 513         public void report(DiagnosticPosition pos, JCDiagnostic details) {
 514             log.error(pos, Errors.ProbFoundReq(details));
 515         }
 516         public boolean compatible(Type found, Type req, Warner warn) {
 517             return types.isAssignable(found, req, warn);
 518         }
 519 
 520         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
 521             return convertWarner(pos, found, req);
 522         }
 523 
 524         public InferenceContext inferenceContext() {
 525             return infer.emptyContext;
 526         }
 527 
 528         public DeferredAttrContext deferredAttrContext() {
 529             return deferredAttr.emptyDeferredAttrContext;
 530         }
 531 
 532         @Override
 533         public String toString() {
 534             return "CheckContext: basicHandler";
 535         }
 536     };
 537 
 538     /** Check that a given type is assignable to a given proto-type.
 539      *  If it is, return the type, otherwise return errType.
 540      *  @param pos        Position to be used for error reporting.
 541      *  @param found      The type that was found.
 542      *  @param req        The type that was required.
 543      */
 544     public Type checkType(DiagnosticPosition pos, Type found, Type req) {
 545         return checkType(pos, found, req, basicHandler);
 546     }
 547 
 548     Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
 549         final InferenceContext inferenceContext = checkContext.inferenceContext();
 550         if (inferenceContext.free(req) || inferenceContext.free(found)) {
 551             inferenceContext.addFreeTypeListener(List.of(req, found),
 552                     solvedContext -> checkType(pos, solvedContext.asInstType(found), solvedContext.asInstType(req), checkContext));
 553         }
 554         if (req.hasTag(ERROR))
 555             return req;
 556         if (req.hasTag(NONE))
 557             return found;
 558         if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
 559             return found;
 560         } else {
 561             if (found.isNumeric() && req.isNumeric()) {
 562                 checkContext.report(pos, diags.fragment(Fragments.PossibleLossOfPrecision(found, req)));
 563                 return types.createErrorType(found);
 564             }
 565             checkContext.report(pos, diags.fragment(Fragments.InconvertibleTypes(found, req)));
 566             return types.createErrorType(found);
 567         }
 568     }
 569 
 570     /** Check that a given type can be cast to a given target type.
 571      *  Return the result of the cast.
 572      *  @param pos        Position to be used for error reporting.
 573      *  @param found      The type that is being cast.
 574      *  @param req        The target type of the cast.
 575      */
 576     Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
 577         return checkCastable(pos, found, req, basicHandler);
 578     }
 579     Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
 580         if (types.isCastable(found, req, castWarner(pos, found, req))) {
 581             return req;
 582         } else {
 583             checkContext.report(pos, diags.fragment(Fragments.InconvertibleTypes(found, req)));
 584             return types.createErrorType(found);
 585         }
 586     }
 587 
 588     /** Check for redundant casts (i.e. where source type is a subtype of target type)
 589      * The problem should only be reported for non-292 cast
 590      */
 591     public void checkRedundantCast(Env<AttrContext> env, final JCTypeCast tree) {
 592         if (!tree.type.isErroneous()
 593                 && types.isSameType(tree.expr.type, tree.clazz.type)
 594                 && !(ignoreAnnotatedCasts && TreeInfo.containsTypeAnnotation(tree.clazz))
 595                 && !is292targetTypeCast(tree)) {
 596             log.warning(tree.pos(), LintWarnings.RedundantCast(tree.clazz.type));
 597         }
 598     }
 599     //where
 600         private boolean is292targetTypeCast(JCTypeCast tree) {
 601             boolean is292targetTypeCast = false;
 602             JCExpression expr = TreeInfo.skipParens(tree.expr);
 603             if (expr.hasTag(APPLY)) {
 604                 JCMethodInvocation apply = (JCMethodInvocation)expr;
 605                 Symbol sym = TreeInfo.symbol(apply.meth);
 606                 is292targetTypeCast = sym != null &&
 607                     sym.kind == MTH &&
 608                     (sym.flags() & HYPOTHETICAL) != 0;
 609             }
 610             return is292targetTypeCast;
 611         }
 612 
 613         private static final boolean ignoreAnnotatedCasts = true;
 614 
 615     /** Check that a type is within some bounds.
 616      *
 617      *  Used in TypeApply to verify that, e.g., X in {@code V<X>} is a valid
 618      *  type argument.
 619      *  @param a             The type that should be bounded by bs.
 620      *  @param bound         The bound.
 621      */
 622     private boolean checkExtends(Type a, Type bound) {
 623          if (a.isUnbound()) {
 624              return true;
 625          } else if (!a.hasTag(WILDCARD)) {
 626              a = types.cvarUpperBound(a);
 627              return types.isSubtype(a, bound);
 628          } else if (a.isExtendsBound()) {
 629              return types.isCastable(bound, types.wildUpperBound(a), types.noWarnings);
 630          } else if (a.isSuperBound()) {
 631              return !types.notSoftSubtype(types.wildLowerBound(a), bound);
 632          }
 633          return true;
 634      }
 635 
 636     /** Check that type is different from 'void'.
 637      *  @param pos           Position to be used for error reporting.
 638      *  @param t             The type to be checked.
 639      */
 640     Type checkNonVoid(DiagnosticPosition pos, Type t) {
 641         if (t.hasTag(VOID)) {
 642             log.error(pos, Errors.VoidNotAllowedHere);
 643             return types.createErrorType(t);
 644         } else {
 645             return t;
 646         }
 647     }
 648 
 649     Type checkClassOrArrayType(DiagnosticPosition pos, Type t) {
 650         if (!t.hasTag(CLASS) && !t.hasTag(ARRAY) && !t.hasTag(ERROR)) {
 651             return typeTagError(pos,
 652                                 diags.fragment(Fragments.TypeReqClassArray),
 653                                 t);
 654         } else {
 655             return t;
 656         }
 657     }
 658 
 659     /** Check that type is a class or interface type.
 660      *  @param pos           Position to be used for error reporting.
 661      *  @param t             The type to be checked.
 662      */
 663     Type checkClassType(DiagnosticPosition pos, Type t) {
 664         if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) {
 665             return typeTagError(pos,
 666                                 diags.fragment(Fragments.TypeReqClass),
 667                                 t);
 668         } else {
 669             return t;
 670         }
 671     }
 672     //where
 673         private Object asTypeParam(Type t) {
 674             return (t.hasTag(TYPEVAR))
 675                                     ? diags.fragment(Fragments.TypeParameter(t))
 676                                     : t;
 677         }
 678 
 679     /** Check that type is a valid qualifier for a constructor reference expression
 680      */
 681     Type checkConstructorRefType(DiagnosticPosition pos, Type t) {
 682         t = checkClassOrArrayType(pos, t);
 683         if (t.hasTag(CLASS)) {
 684             if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
 685                 log.error(pos, Errors.AbstractCantBeInstantiated(t.tsym));
 686                 t = types.createErrorType(t);
 687             } else if ((t.tsym.flags() & ENUM) != 0) {
 688                 log.error(pos, Errors.EnumCantBeInstantiated);
 689                 t = types.createErrorType(t);
 690             } else {
 691                 t = checkClassType(pos, t, true);
 692             }
 693         } else if (t.hasTag(ARRAY)) {
 694             if (!types.isReifiable(((ArrayType)t).elemtype)) {
 695                 log.error(pos, Errors.GenericArrayCreation);
 696                 t = types.createErrorType(t);
 697             }
 698         }
 699         return t;
 700     }
 701 
 702     /** Check that type is a class or interface type.
 703      *  @param pos           Position to be used for error reporting.
 704      *  @param t             The type to be checked.
 705      *  @param noBounds    True if type bounds are illegal here.
 706      */
 707     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
 708         t = checkClassType(pos, t);
 709         if (noBounds && t.isParameterized()) {
 710             List<Type> args = t.getTypeArguments();
 711             while (args.nonEmpty()) {
 712                 if (args.head.hasTag(WILDCARD))
 713                     return typeTagError(pos,
 714                                         diags.fragment(Fragments.TypeReqExact),
 715                                         args.head);
 716                 args = args.tail;
 717             }
 718         }
 719         return t;
 720     }
 721 
 722     /** Check that type is a reference type, i.e. a class, interface or array type
 723      *  or a type variable.
 724      *  @param pos           Position to be used for error reporting.
 725      *  @param t             The type to be checked.
 726      */
 727     Type checkRefType(DiagnosticPosition pos, Type t) {
 728         if (t.isReference())
 729             return t;
 730         else
 731             return typeTagError(pos,
 732                                 diags.fragment(Fragments.TypeReqRef),
 733                                 t);
 734     }
 735 
 736     /** Check that type is an identity type, i.e. not a value type.
 737      *  When not discernible statically, give it the benefit of doubt
 738      *  and defer to runtime.
 739      *
 740      *  @param pos           Position to be used for error reporting.
 741      *  @param t             The type to be checked.
 742      */
 743     boolean checkIdentityType(DiagnosticPosition pos, Type t) {
 744         if (t.hasTag(TYPEVAR)) {
 745             t = types.skipTypeVars(t, false);
 746         }
 747         if (t.isIntersection()) {
 748             IntersectionClassType ict = (IntersectionClassType)t;
 749             boolean result = true;
 750             for (Type component : ict.getExplicitComponents()) {
 751                 result &= checkIdentityType(pos, component);
 752             }
 753             return result;
 754         }
 755         if (t.isPrimitive() || (t.isValueClass() && !t.tsym.isAbstract())) {
 756             typeTagError(pos, diags.fragment(Fragments.TypeReqIdentity), t);
 757             return false;
 758         }
 759         return true;
 760     }
 761 
 762     /** Check that each type is a reference type, i.e. a class, interface or array type
 763      *  or a type variable.
 764      *  @param trees         Original trees, used for error reporting.
 765      *  @param types         The types to be checked.
 766      */
 767     List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
 768         List<JCExpression> tl = trees;
 769         for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
 770             l.head = checkRefType(tl.head.pos(), l.head);
 771             tl = tl.tail;
 772         }
 773         return types;
 774     }
 775 
 776     /** Check that type is a null or reference type.
 777      *  @param pos           Position to be used for error reporting.
 778      *  @param t             The type to be checked.
 779      */
 780     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
 781         if (t.isReference() || t.hasTag(BOT))
 782             return t;
 783         else
 784             return typeTagError(pos,
 785                                 diags.fragment(Fragments.TypeReqRef),
 786                                 t);
 787     }
 788 
 789     /** Check that flag set does not contain elements of two conflicting sets. s
 790      *  Return true if it doesn't.
 791      *  @param pos           Position to be used for error reporting.
 792      *  @param flags         The set of flags to be checked.
 793      *  @param set1          Conflicting flags set #1.
 794      *  @param set2          Conflicting flags set #2.
 795      */
 796     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
 797         if ((flags & set1) != 0 && (flags & set2) != 0) {
 798             log.error(pos,
 799                       Errors.IllegalCombinationOfModifiers(asFlagSet(TreeInfo.firstFlag(flags & set1)),
 800                                                            asFlagSet(TreeInfo.firstFlag(flags & set2))));
 801             return false;
 802         } else
 803             return true;
 804     }
 805 
 806     /** Check that usage of diamond operator is correct (i.e. diamond should not
 807      * be used with non-generic classes or in anonymous class creation expressions)
 808      */
 809     Type checkDiamond(JCNewClass tree, Type t) {
 810         if (!TreeInfo.isDiamond(tree) ||
 811                 t.isErroneous()) {
 812             return checkClassType(tree.clazz.pos(), t, true);
 813         } else {
 814             if (tree.def != null && !Feature.DIAMOND_WITH_ANONYMOUS_CLASS_CREATION.allowedInSource(source)) {
 815                 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.clazz.pos(),
 816                         Errors.CantApplyDiamond1(t, Feature.DIAMOND_WITH_ANONYMOUS_CLASS_CREATION.fragment(source.name)));
 817             }
 818             if (t.tsym.type.getTypeArguments().isEmpty()) {
 819                 log.error(tree.clazz.pos(),
 820                           Errors.CantApplyDiamond1(t,
 821                                                    Fragments.DiamondNonGeneric(t)));
 822                 return types.createErrorType(t);
 823             } else if (tree.typeargs != null &&
 824                     tree.typeargs.nonEmpty()) {
 825                 log.error(tree.clazz.pos(),
 826                           Errors.CantApplyDiamond1(t,
 827                                                    Fragments.DiamondAndExplicitParams(t)));
 828                 return types.createErrorType(t);
 829             } else {
 830                 return t;
 831             }
 832         }
 833     }
 834 
 835     /** Check that the type inferred using the diamond operator does not contain
 836      *  non-denotable types such as captured types or intersection types.
 837      *  @param t the type inferred using the diamond operator
 838      *  @return  the (possibly empty) list of non-denotable types.
 839      */
 840     List<Type> checkDiamondDenotable(ClassType t) {
 841         ListBuffer<Type> buf = new ListBuffer<>();
 842         for (Type arg : t.allparams()) {
 843             if (!checkDenotable(arg)) {
 844                 buf.append(arg);
 845             }
 846         }
 847         return buf.toList();
 848     }
 849 
 850     public boolean checkDenotable(Type t) {
 851         return denotableChecker.visit(t, null);
 852     }
 853         // where
 854 
 855         /** diamondTypeChecker: A type visitor that descends down the given type looking for non-denotable
 856          *  types. The visit methods return false as soon as a non-denotable type is encountered and true
 857          *  otherwise.
 858          */
 859         private static final Types.SimpleVisitor<Boolean, Void> denotableChecker = new Types.SimpleVisitor<Boolean, Void>() {
 860             @Override
 861             public Boolean visitType(Type t, Void s) {
 862                 return true;
 863             }
 864             @Override
 865             public Boolean visitClassType(ClassType t, Void s) {
 866                 if (t.isUnion() || t.isIntersection()) {
 867                     return false;
 868                 }
 869                 for (Type targ : t.allparams()) {
 870                     if (!visit(targ, s)) {
 871                         return false;
 872                     }
 873                 }
 874                 return true;
 875             }
 876 
 877             @Override
 878             public Boolean visitTypeVar(TypeVar t, Void s) {
 879                 /* Any type variable mentioned in the inferred type must have been declared as a type parameter
 880                   (i.e cannot have been produced by inference (18.4))
 881                 */
 882                 return (t.tsym.flags() & SYNTHETIC) == 0;
 883             }
 884 
 885             @Override
 886             public Boolean visitCapturedType(CapturedType t, Void s) {
 887                 /* Any type variable mentioned in the inferred type must have been declared as a type parameter
 888                   (i.e cannot have been produced by capture conversion (5.1.10))
 889                 */
 890                 return false;
 891             }
 892 
 893             @Override
 894             public Boolean visitArrayType(ArrayType t, Void s) {
 895                 return visit(t.elemtype, s);
 896             }
 897 
 898             @Override
 899             public Boolean visitWildcardType(WildcardType t, Void s) {
 900                 return visit(t.type, s);
 901             }
 902         };
 903 
 904     void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
 905         MethodSymbol m = tree.sym;
 906         boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
 907         Type varargElemType = null;
 908         if (m.isVarArgs()) {
 909             varargElemType = types.elemtype(tree.params.last().type);
 910         }
 911         if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
 912             if (varargElemType != null) {
 913                 JCDiagnostic msg = Feature.PRIVATE_SAFE_VARARGS.allowedInSource(source) ?
 914                         diags.fragment(Fragments.VarargsTrustmeOnVirtualVarargs(m)) :
 915                         diags.fragment(Fragments.VarargsTrustmeOnVirtualVarargsFinalOnly(m));
 916                 log.error(tree,
 917                           Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym,
 918                                                            msg));
 919             } else {
 920                 log.error(tree,
 921                           Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym,
 922                                                            Fragments.VarargsTrustmeOnNonVarargsMeth(m)));
 923             }
 924         } else if (hasTrustMeAnno && varargElemType != null &&
 925                             types.isReifiable(varargElemType)) {
 926             log.warning(tree.pos(), LintWarnings.VarargsRedundantTrustmeAnno(
 927                                 syms.trustMeType.tsym,
 928                                 diags.fragment(Fragments.VarargsTrustmeOnReifiableVarargs(varargElemType))));
 929         }
 930         else if (!hasTrustMeAnno && varargElemType != null &&
 931                 !types.isReifiable(varargElemType)) {
 932             warnUnchecked(tree.params.last().pos(), LintWarnings.UncheckedVarargsNonReifiableType(varargElemType));
 933         }
 934     }
 935     //where
 936         private boolean isTrustMeAllowedOnMethod(Symbol s) {
 937             return (s.flags() & VARARGS) != 0 &&
 938                 (s.isConstructor() ||
 939                     (s.flags() & (STATIC | FINAL |
 940                                   (Feature.PRIVATE_SAFE_VARARGS.allowedInSource(source) ? PRIVATE : 0) )) != 0);
 941         }
 942 
 943     Type checkLocalVarType(DiagnosticPosition pos, Type t, Name name) {
 944         //check that resulting type is not the null type
 945         if (t.hasTag(BOT)) {
 946             log.error(pos, Errors.CantInferLocalVarType(name, Fragments.LocalCantInferNull));
 947             return types.createErrorType(t);
 948         } else if (t.hasTag(VOID)) {
 949             log.error(pos, Errors.CantInferLocalVarType(name, Fragments.LocalCantInferVoid));
 950             return types.createErrorType(t);
 951         }
 952 
 953         //upward project the initializer type
 954         return types.upward(t, types.captures(t)).baseType();
 955     }
 956 
 957     Type checkMethod(final Type mtype,
 958             final Symbol sym,
 959             final Env<AttrContext> env,
 960             final List<JCExpression> argtrees,
 961             final List<Type> argtypes,
 962             final boolean useVarargs,
 963             InferenceContext inferenceContext) {
 964         // System.out.println("call   : " + env.tree);
 965         // System.out.println("method : " + owntype);
 966         // System.out.println("actuals: " + argtypes);
 967         if (inferenceContext.free(mtype)) {
 968             inferenceContext.addFreeTypeListener(List.of(mtype),
 969                     solvedContext -> checkMethod(solvedContext.asInstType(mtype), sym, env, argtrees, argtypes, useVarargs, solvedContext));
 970             return mtype;
 971         }
 972         Type owntype = mtype;
 973         List<Type> formals = owntype.getParameterTypes();
 974         List<Type> nonInferred = sym.type.getParameterTypes();
 975         if (nonInferred.length() != formals.length()) nonInferred = formals;
 976         Type last = useVarargs ? formals.last() : null;
 977         if (sym.name == names.init && sym.owner == syms.enumSym) {
 978             formals = formals.tail.tail;
 979             nonInferred = nonInferred.tail.tail;
 980         }
 981         if ((sym.flags() & ANONCONSTR_BASED) != 0) {
 982             formals = formals.tail;
 983             nonInferred = nonInferred.tail;
 984         }
 985         List<JCExpression> args = argtrees;
 986         if (args != null) {
 987             //this is null when type-checking a method reference
 988             while (formals.head != last) {
 989                 JCTree arg = args.head;
 990                 Warner warn = convertWarner(arg.pos(), arg.type, nonInferred.head);
 991                 assertConvertible(arg, arg.type, formals.head, warn);
 992                 args = args.tail;
 993                 formals = formals.tail;
 994                 nonInferred = nonInferred.tail;
 995             }
 996             if (useVarargs) {
 997                 Type varArg = types.elemtype(last);
 998                 while (args.tail != null) {
 999                     JCTree arg = args.head;
1000                     Warner warn = convertWarner(arg.pos(), arg.type, varArg);
1001                     assertConvertible(arg, arg.type, varArg, warn);
1002                     args = args.tail;
1003                 }
1004             } else if ((sym.flags() & (VARARGS | SIGNATURE_POLYMORPHIC)) == VARARGS) {
1005                 // non-varargs call to varargs method
1006                 Type varParam = owntype.getParameterTypes().last();
1007                 Type lastArg = argtypes.last();
1008                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
1009                     !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
1010                     log.warning(argtrees.last().pos(),
1011                                 Warnings.InexactNonVarargsCall(types.elemtype(varParam),varParam));
1012             }
1013         }
1014         if (useVarargs) {
1015             Type argtype = owntype.getParameterTypes().last();
1016             if (!types.isReifiable(argtype) &&
1017                 (sym.baseSymbol().attribute(syms.trustMeType.tsym) == null ||
1018                  !isTrustMeAllowedOnMethod(sym))) {
1019                 warnUnchecked(env.tree.pos(), LintWarnings.UncheckedGenericArrayCreation(argtype));
1020             }
1021             TreeInfo.setVarargsElement(env.tree, types.elemtype(argtype));
1022          }
1023          return owntype;
1024     }
1025     //where
1026     private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
1027         if (types.isConvertible(actual, formal, warn))
1028             return;
1029 
1030         if (formal.isCompound()
1031             && types.isSubtype(actual, types.supertype(formal))
1032             && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
1033             return;
1034     }
1035 
1036     /**
1037      * Check that type 't' is a valid instantiation of a generic class
1038      * (see JLS 4.5)
1039      *
1040      * @param t class type to be checked
1041      * @return true if 't' is well-formed
1042      */
1043     public boolean checkValidGenericType(Type t) {
1044         return firstIncompatibleTypeArg(t) == null;
1045     }
1046     //WHERE
1047         private Type firstIncompatibleTypeArg(Type type) {
1048             List<Type> formals = type.tsym.type.allparams();
1049             List<Type> actuals = type.allparams();
1050             List<Type> args = type.getTypeArguments();
1051             List<Type> forms = type.tsym.type.getTypeArguments();
1052             ListBuffer<Type> bounds_buf = new ListBuffer<>();
1053 
1054             // For matching pairs of actual argument types `a' and
1055             // formal type parameters with declared bound `b' ...
1056             while (args.nonEmpty() && forms.nonEmpty()) {
1057                 // exact type arguments needs to know their
1058                 // bounds (for upper and lower bound
1059                 // calculations).  So we create new bounds where
1060                 // type-parameters are replaced with actuals argument types.
1061                 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
1062                 args = args.tail;
1063                 forms = forms.tail;
1064             }
1065 
1066             args = type.getTypeArguments();
1067             List<Type> tvars_cap = types.substBounds(formals,
1068                                       formals,
1069                                       types.capture(type).allparams());
1070             while (args.nonEmpty() && tvars_cap.nonEmpty()) {
1071                 // Let the actual arguments know their bound
1072                 args.head.withTypeVar((TypeVar)tvars_cap.head);
1073                 args = args.tail;
1074                 tvars_cap = tvars_cap.tail;
1075             }
1076 
1077             args = type.getTypeArguments();
1078             List<Type> bounds = bounds_buf.toList();
1079 
1080             while (args.nonEmpty() && bounds.nonEmpty()) {
1081                 Type actual = args.head;
1082                 if (!isTypeArgErroneous(actual) &&
1083                         !bounds.head.isErroneous() &&
1084                         !checkExtends(actual, bounds.head)) {
1085                     return args.head;
1086                 }
1087                 args = args.tail;
1088                 bounds = bounds.tail;
1089             }
1090 
1091             args = type.getTypeArguments();
1092             bounds = bounds_buf.toList();
1093 
1094             for (Type arg : types.capture(type).getTypeArguments()) {
1095                 if (arg.hasTag(TYPEVAR) &&
1096                         arg.getUpperBound().isErroneous() &&
1097                         !bounds.head.isErroneous() &&
1098                         !isTypeArgErroneous(args.head)) {
1099                     return args.head;
1100                 }
1101                 bounds = bounds.tail;
1102                 args = args.tail;
1103             }
1104 
1105             return null;
1106         }
1107         //where
1108         boolean isTypeArgErroneous(Type t) {
1109             return isTypeArgErroneous.visit(t);
1110         }
1111 
1112         Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
1113             public Boolean visitType(Type t, Void s) {
1114                 return t.isErroneous();
1115             }
1116             @Override
1117             public Boolean visitTypeVar(TypeVar t, Void s) {
1118                 return visit(t.getUpperBound());
1119             }
1120             @Override
1121             public Boolean visitCapturedType(CapturedType t, Void s) {
1122                 return visit(t.getUpperBound()) ||
1123                         visit(t.getLowerBound());
1124             }
1125             @Override
1126             public Boolean visitWildcardType(WildcardType t, Void s) {
1127                 return visit(t.type);
1128             }
1129         };
1130 
1131     /** Check that given modifiers are legal for given symbol and
1132      *  return modifiers together with any implicit modifiers for that symbol.
1133      *  Warning: we can't use flags() here since this method
1134      *  is called during class enter, when flags() would cause a premature
1135      *  completion.
1136      *  @param flags         The set of modifiers given in a definition.
1137      *  @param sym           The defined symbol.
1138      *  @param tree          The declaration
1139      */
1140     long checkFlags(long flags, Symbol sym, JCTree tree) {
1141         final DiagnosticPosition pos = tree.pos();
1142         long mask;
1143         long implicit = 0;
1144 
1145         switch (sym.kind) {
1146         case VAR:
1147             if (TreeInfo.isReceiverParam(tree))
1148                 mask = ReceiverParamFlags;
1149             else if (sym.owner.kind != TYP)
1150                 mask = LocalVarFlags;
1151             else if ((sym.owner.flags_field & INTERFACE) != 0)
1152                 mask = implicit = InterfaceVarFlags;
1153             else {
1154                 boolean isInstanceField = (flags & STATIC) == 0;
1155                 boolean isInstanceFieldOfValueClass = isInstanceField && sym.owner.type.isValueClass();
1156                 boolean isRecordField = isInstanceField && (sym.owner.flags_field & RECORD) != 0;
1157                 if (allowValueClasses && (isInstanceFieldOfValueClass || isRecordField)) {
1158                     implicit |= FINAL | STRICT;
1159                     mask = ValueFieldFlags;
1160                 } else {
1161                     mask = VarFlags;
1162                 }
1163             }
1164             break;
1165         case MTH:
1166             if (sym.name == names.init) {
1167                 if ((sym.owner.flags_field & ENUM) != 0) {
1168                     // enum constructors cannot be declared public or
1169                     // protected and must be implicitly or explicitly
1170                     // private
1171                     implicit = PRIVATE;
1172                     mask = PRIVATE;
1173                 } else
1174                     mask = ConstructorFlags;
1175             }  else if ((sym.owner.flags_field & INTERFACE) != 0) {
1176                 if ((sym.owner.flags_field & ANNOTATION) != 0) {
1177                     mask = AnnotationTypeElementMask;
1178                     implicit = PUBLIC | ABSTRACT;
1179                 } else if ((flags & (DEFAULT | STATIC | PRIVATE)) != 0) {
1180                     mask = InterfaceMethodMask;
1181                     implicit = (flags & PRIVATE) != 0 ? 0 : PUBLIC;
1182                     if ((flags & DEFAULT) != 0) {
1183                         implicit |= ABSTRACT;
1184                     }
1185                 } else {
1186                     mask = implicit = InterfaceMethodFlags;
1187                 }
1188             } else if ((sym.owner.flags_field & RECORD) != 0) {
1189                 mask = ((sym.owner.flags_field & VALUE_CLASS) != 0 && (flags & Flags.STATIC) == 0) ?
1190                         RecordMethodFlags & ~SYNCHRONIZED : RecordMethodFlags;
1191             } else {
1192                 // value objects do not have an associated monitor/lock
1193                 mask = ((sym.owner.flags_field & VALUE_CLASS) != 0 && (flags & Flags.STATIC) == 0) ?
1194                         MethodFlags & ~SYNCHRONIZED : MethodFlags;
1195             }
1196             if ((flags & STRICTFP) != 0) {
1197                 log.warning(tree.pos(), LintWarnings.Strictfp);
1198             }
1199             // Imply STRICTFP if owner has STRICTFP set.
1200             if (((flags|implicit) & Flags.ABSTRACT) == 0 ||
1201                 ((flags) & Flags.DEFAULT) != 0)
1202                 implicit |= sym.owner.flags_field & STRICTFP;
1203             break;
1204         case TYP:
1205             if (sym.owner.kind.matches(KindSelector.VAL_MTH) ||
1206                     (sym.isDirectlyOrIndirectlyLocal() && (flags & ANNOTATION) != 0)) {
1207                 boolean implicitlyStatic = !sym.isAnonymous() &&
1208                         ((flags & RECORD) != 0 || (flags & ENUM) != 0 || (flags & INTERFACE) != 0);
1209                 boolean staticOrImplicitlyStatic = (flags & STATIC) != 0 || implicitlyStatic;
1210                 // local statics are allowed only if records are allowed too
1211                 mask = staticOrImplicitlyStatic && allowRecords && (flags & ANNOTATION) == 0 ? ExtendedStaticLocalClassFlags : ExtendedLocalClassFlags;
1212                 implicit = implicitlyStatic ? STATIC : implicit;
1213             } else if (sym.owner.kind == TYP) {
1214                 // statics in inner classes are allowed only if records are allowed too
1215                 mask = ((flags & STATIC) != 0) && allowRecords && (flags & ANNOTATION) == 0 ? ExtendedMemberStaticClassFlags : ExtendedMemberClassFlags;
1216                 if (sym.owner.owner.kind == PCK ||
1217                     (sym.owner.flags_field & STATIC) != 0) {
1218                     mask |= STATIC;
1219                 } else if (!allowRecords && ((flags & ENUM) != 0 || (flags & RECORD) != 0)) {
1220                     log.error(pos, Errors.StaticDeclarationNotAllowedInInnerClasses);
1221                 }
1222                 // Nested interfaces and enums are always STATIC (Spec ???)
1223                 if ((flags & (INTERFACE | ENUM | RECORD)) != 0 ) implicit = STATIC;
1224             } else {
1225                 mask = ExtendedClassFlags;
1226             }
1227             if ((flags & (VALUE_CLASS | SEALED | ABSTRACT)) == (VALUE_CLASS | SEALED) ||
1228                 (flags & (VALUE_CLASS | NON_SEALED | ABSTRACT)) == (VALUE_CLASS | NON_SEALED)) {
1229                 log.error(pos, Errors.NonAbstractValueClassCantBeSealedOrNonSealed);
1230             }
1231             // Interfaces are always ABSTRACT
1232             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
1233 
1234             if ((flags & (INTERFACE | VALUE_CLASS)) == 0) {
1235                 implicit |= IDENTITY_TYPE;
1236             }
1237 
1238             if ((flags & ENUM) != 0) {
1239                 // enums can't be declared abstract, final, sealed or non-sealed or value
1240                 mask &= ~(ABSTRACT | FINAL | SEALED | NON_SEALED | VALUE_CLASS);
1241                 implicit |= implicitEnumFinalFlag(tree);
1242             }
1243             if ((flags & RECORD) != 0) {
1244                 // records can't be declared abstract
1245                 mask &= ~ABSTRACT;
1246                 implicit |= FINAL;
1247             }
1248             if ((flags & STRICTFP) != 0) {
1249                 log.warning(tree.pos(), LintWarnings.Strictfp);
1250             }
1251             // Imply STRICTFP if owner has STRICTFP set.
1252             implicit |= sym.owner.flags_field & STRICTFP;
1253 
1254             // concrete value classes are implicitly final
1255             if ((flags & (ABSTRACT | INTERFACE | VALUE_CLASS)) == VALUE_CLASS) {
1256                 implicit |= FINAL;
1257             }
1258             break;
1259         default:
1260             throw new AssertionError();
1261         }
1262         long illegal = flags & ExtendedStandardFlags & ~mask;
1263         if (illegal != 0) {
1264             if ((illegal & INTERFACE) != 0) {
1265                 log.error(pos, ((flags & ANNOTATION) != 0) ? Errors.AnnotationDeclNotAllowedHere : Errors.IntfNotAllowedHere);
1266                 mask |= INTERFACE;
1267             }
1268             else {
1269                 log.error(pos,
1270                         Errors.ModNotAllowedHere(asFlagSet(illegal)));
1271             }
1272         } else if ((sym.kind == TYP ||

1273                   // ISSUE: Disallowing abstract&private is no longer appropriate
1274                   // in the presence of inner classes. Should it be deleted here?
1275                   checkDisjoint(pos, flags,
1276                                 ABSTRACT,
1277                                 PRIVATE | STATIC | DEFAULT))
1278                  &&
1279                  checkDisjoint(pos, flags,
1280                                 STATIC | PRIVATE,
1281                                 DEFAULT)
1282                  &&
1283                  checkDisjoint(pos, flags,
1284                                ABSTRACT | INTERFACE,
1285                                FINAL | NATIVE | SYNCHRONIZED)
1286                  &&
1287                  checkDisjoint(pos, flags,
1288                                PUBLIC,
1289                                PRIVATE | PROTECTED)
1290                  &&
1291                  checkDisjoint(pos, flags,
1292                                PRIVATE,
1293                                PUBLIC | PROTECTED)
1294                  &&
1295                  // we are using `implicit` here as instance fields of value classes are implicitly final
1296                  checkDisjoint(pos, flags | implicit,
1297                                FINAL,
1298                                VOLATILE)
1299                  &&
1300                  (sym.kind == TYP ||
1301                   checkDisjoint(pos, flags,
1302                                 ABSTRACT | NATIVE,
1303                                 STRICTFP))
1304                  && checkDisjoint(pos, flags,
1305                                 FINAL,
1306                            SEALED | NON_SEALED)
1307                  && checkDisjoint(pos, flags,
1308                                 SEALED,
1309                            FINAL | NON_SEALED)
1310                  && checkDisjoint(pos, flags,
1311                                 SEALED,
1312                                 ANNOTATION)
1313                 && checkDisjoint(pos, flags,
1314                                 VALUE_CLASS,
1315                                 ANNOTATION)
1316                 && checkDisjoint(pos, flags,
1317                                 VALUE_CLASS,
1318                                 INTERFACE) ) {
1319             // skip
1320         }
1321         return flags & (mask | ~ExtendedStandardFlags) | implicit;
1322     }
1323 
1324     /** Determine if this enum should be implicitly final.
1325      *
1326      *  If the enum has no specialized enum constants, it is final.
1327      *
1328      *  If the enum does have specialized enum constants, it is
1329      *  <i>not</i> final.
1330      */
1331     private long implicitEnumFinalFlag(JCTree tree) {
1332         if (!tree.hasTag(CLASSDEF)) return 0;
1333         class SpecialTreeVisitor extends JCTree.Visitor {
1334             boolean specialized;
1335             SpecialTreeVisitor() {
1336                 this.specialized = false;
1337             }
1338 
1339             @Override
1340             public void visitTree(JCTree tree) { /* no-op */ }
1341 
1342             @Override
1343             public void visitVarDef(JCVariableDecl tree) {
1344                 if ((tree.mods.flags & ENUM) != 0) {
1345                     if (tree.init instanceof JCNewClass newClass && newClass.def != null) {
1346                         specialized = true;
1347                     }
1348                 }
1349             }
1350         }
1351 
1352         SpecialTreeVisitor sts = new SpecialTreeVisitor();
1353         JCClassDecl cdef = (JCClassDecl) tree;
1354         for (JCTree defs: cdef.defs) {
1355             defs.accept(sts);
1356             if (sts.specialized) return allowSealed ? SEALED : 0;
1357         }
1358         return FINAL;
1359     }
1360 
1361 /* *************************************************************************
1362  * Type Validation
1363  **************************************************************************/
1364 
1365     /** Validate a type expression. That is,
1366      *  check that all type arguments of a parametric type are within
1367      *  their bounds. This must be done in a second phase after type attribution
1368      *  since a class might have a subclass as type parameter bound. E.g:
1369      *
1370      *  <pre>{@code
1371      *  class B<A extends C> { ... }
1372      *  class C extends B<C> { ... }
1373      *  }</pre>
1374      *
1375      *  and we can't make sure that the bound is already attributed because
1376      *  of possible cycles.
1377      *
1378      * Visitor method: Validate a type expression, if it is not null, catching
1379      *  and reporting any completion failures.
1380      */
1381     void validate(JCTree tree, Env<AttrContext> env) {
1382         validate(tree, env, true);
1383     }
1384     void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
1385         new Validator(env).validateTree(tree, checkRaw, true);
1386     }
1387 
1388     /** Visitor method: Validate a list of type expressions.
1389      */
1390     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
1391         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1392             validate(l.head, env);
1393     }
1394 
1395     /** A visitor class for type validation.
1396      */
1397     class Validator extends JCTree.Visitor {
1398 
1399         boolean checkRaw;
1400         boolean isOuter;
1401         Env<AttrContext> env;
1402 
1403         Validator(Env<AttrContext> env) {
1404             this.env = env;
1405         }
1406 
1407         @Override
1408         public void visitTypeArray(JCArrayTypeTree tree) {
1409             validateTree(tree.elemtype, checkRaw, isOuter);
1410         }
1411 
1412         @Override
1413         public void visitTypeApply(JCTypeApply tree) {
1414             if (tree.type.hasTag(CLASS)) {
1415                 List<JCExpression> args = tree.arguments;
1416                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
1417 
1418                 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
1419                 if (incompatibleArg != null) {
1420                     for (JCTree arg : tree.arguments) {
1421                         if (arg.type == incompatibleArg) {
1422                             log.error(arg, Errors.NotWithinBounds(incompatibleArg, forms.head));
1423                         }
1424                         forms = forms.tail;
1425                      }
1426                  }
1427 
1428                 forms = tree.type.tsym.type.getTypeArguments();
1429 
1430                 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
1431 
1432                 // For matching pairs of actual argument types `a' and
1433                 // formal type parameters with declared bound `b' ...
1434                 while (args.nonEmpty() && forms.nonEmpty()) {
1435                     validateTree(args.head,
1436                             !(isOuter && is_java_lang_Class),
1437                             false);
1438                     args = args.tail;
1439                     forms = forms.tail;
1440                 }
1441 
1442                 // Check that this type is either fully parameterized, or
1443                 // not parameterized at all.
1444                 if (tree.type.getEnclosingType().isRaw())
1445                     log.error(tree.pos(), Errors.ImproperlyFormedTypeInnerRawParam);
1446                 if (tree.clazz.hasTag(SELECT))
1447                     visitSelectInternal((JCFieldAccess)tree.clazz);
1448             }
1449         }
1450 
1451         @Override
1452         public void visitTypeParameter(JCTypeParameter tree) {
1453             validateTrees(tree.bounds, true, isOuter);
1454             checkClassBounds(tree.pos(), tree.type);
1455         }
1456 
1457         @Override
1458         public void visitWildcard(JCWildcard tree) {
1459             if (tree.inner != null)
1460                 validateTree(tree.inner, true, isOuter);
1461         }
1462 
1463         @Override
1464         public void visitSelect(JCFieldAccess tree) {
1465             if (tree.type.hasTag(CLASS)) {
1466                 visitSelectInternal(tree);
1467 
1468                 // Check that this type is either fully parameterized, or
1469                 // not parameterized at all.
1470                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1471                     log.error(tree.pos(), Errors.ImproperlyFormedTypeParamMissing);
1472             }
1473         }
1474 
1475         public void visitSelectInternal(JCFieldAccess tree) {
1476             if (tree.type.tsym.isStatic() &&
1477                 tree.selected.type.isParameterized()) {
1478                 // The enclosing type is not a class, so we are
1479                 // looking at a static member type.  However, the
1480                 // qualifying expression is parameterized.
1481                 log.error(tree.pos(), Errors.CantSelectStaticClassFromParamType);
1482             } else {
1483                 // otherwise validate the rest of the expression
1484                 tree.selected.accept(this);
1485             }
1486         }
1487 
1488         @Override
1489         public void visitAnnotatedType(JCAnnotatedType tree) {
1490             tree.underlyingType.accept(this);
1491         }
1492 
1493         @Override
1494         public void visitTypeIdent(JCPrimitiveTypeTree that) {
1495             if (that.type.hasTag(TypeTag.VOID)) {
1496                 log.error(that.pos(), Errors.VoidNotAllowedHere);
1497             }
1498             super.visitTypeIdent(that);
1499         }
1500 
1501         /** Default visitor method: do nothing.
1502          */
1503         @Override
1504         public void visitTree(JCTree tree) {
1505         }
1506 
1507         public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
1508             if (tree != null) {
1509                 boolean prevCheckRaw = this.checkRaw;
1510                 this.checkRaw = checkRaw;
1511                 this.isOuter = isOuter;
1512 
1513                 try {
1514                     tree.accept(this);
1515                     if (checkRaw)
1516                         checkRaw(tree, env);
1517                 } catch (CompletionFailure ex) {
1518                     completionError(tree.pos(), ex);
1519                 } finally {
1520                     this.checkRaw = prevCheckRaw;
1521                 }
1522             }
1523         }
1524 
1525         public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1526             for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1527                 validateTree(l.head, checkRaw, isOuter);
1528         }
1529     }
1530 
1531     void checkRaw(JCTree tree, Env<AttrContext> env) {
1532         if (tree.type.hasTag(CLASS) &&
1533             !TreeInfo.isDiamond(tree) &&
1534             !withinAnonConstr(env) &&
1535             tree.type.isRaw()) {
1536             log.warning(tree.pos(), LintWarnings.RawClassUse(tree.type, tree.type.tsym.type));
1537         }
1538     }
1539     //where
1540         private boolean withinAnonConstr(Env<AttrContext> env) {
1541             return env.enclClass.name.isEmpty() &&
1542                     env.enclMethod != null && env.enclMethod.name == names.init;
1543         }
1544 
1545 /* *************************************************************************
1546  * Exception checking
1547  **************************************************************************/
1548 
1549     /* The following methods treat classes as sets that contain
1550      * the class itself and all their subclasses
1551      */
1552 
1553     /** Is given type a subtype of some of the types in given list?
1554      */
1555     boolean subset(Type t, List<Type> ts) {
1556         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1557             if (types.isSubtype(t, l.head)) return true;
1558         return false;
1559     }
1560 
1561     /** Is given type a subtype or supertype of
1562      *  some of the types in given list?
1563      */
1564     boolean intersects(Type t, List<Type> ts) {
1565         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1566             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
1567         return false;
1568     }
1569 
1570     /** Add type set to given type list, unless it is a subclass of some class
1571      *  in the list.
1572      */
1573     List<Type> incl(Type t, List<Type> ts) {
1574         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
1575     }
1576 
1577     /** Remove type set from type set list.
1578      */
1579     List<Type> excl(Type t, List<Type> ts) {
1580         if (ts.isEmpty()) {
1581             return ts;
1582         } else {
1583             List<Type> ts1 = excl(t, ts.tail);
1584             if (types.isSubtype(ts.head, t)) return ts1;
1585             else if (ts1 == ts.tail) return ts;
1586             else return ts1.prepend(ts.head);
1587         }
1588     }
1589 
1590     /** Form the union of two type set lists.
1591      */
1592     List<Type> union(List<Type> ts1, List<Type> ts2) {
1593         List<Type> ts = ts1;
1594         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1595             ts = incl(l.head, ts);
1596         return ts;
1597     }
1598 
1599     /** Form the difference of two type lists.
1600      */
1601     List<Type> diff(List<Type> ts1, List<Type> ts2) {
1602         List<Type> ts = ts1;
1603         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1604             ts = excl(l.head, ts);
1605         return ts;
1606     }
1607 
1608     /** Form the intersection of two type lists.
1609      */
1610     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
1611         List<Type> ts = List.nil();
1612         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
1613             if (subset(l.head, ts2)) ts = incl(l.head, ts);
1614         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1615             if (subset(l.head, ts1)) ts = incl(l.head, ts);
1616         return ts;
1617     }
1618 
1619     /** Is exc an exception symbol that need not be declared?
1620      */
1621     boolean isUnchecked(ClassSymbol exc) {
1622         return
1623             exc.kind == ERR ||
1624             exc.isSubClass(syms.errorType.tsym, types) ||
1625             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1626     }
1627 
1628     /** Is exc an exception type that need not be declared?
1629      */
1630     boolean isUnchecked(Type exc) {
1631         return
1632             (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) :
1633             (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) :
1634             exc.hasTag(BOT);
1635     }
1636 
1637     boolean isChecked(Type exc) {
1638         return !isUnchecked(exc);
1639     }
1640 
1641     /** Same, but handling completion failures.
1642      */
1643     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1644         try {
1645             return isUnchecked(exc);
1646         } catch (CompletionFailure ex) {
1647             completionError(pos, ex);
1648             return true;
1649         }
1650     }
1651 
1652     /** Is exc handled by given exception list?
1653      */
1654     boolean isHandled(Type exc, List<Type> handled) {
1655         return isUnchecked(exc) || subset(exc, handled);
1656     }
1657 
1658     /** Return all exceptions in thrown list that are not in handled list.
1659      *  @param thrown     The list of thrown exceptions.
1660      *  @param handled    The list of handled exceptions.
1661      */
1662     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
1663         List<Type> unhandled = List.nil();
1664         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1665             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1666         return unhandled;
1667     }
1668 
1669 /* *************************************************************************
1670  * Overriding/Implementation checking
1671  **************************************************************************/
1672 
1673     /** The level of access protection given by a flag set,
1674      *  where PRIVATE is highest and PUBLIC is lowest.
1675      */
1676     static int protection(long flags) {
1677         switch ((short)(flags & AccessFlags)) {
1678         case PRIVATE: return 3;
1679         case PROTECTED: return 1;
1680         default:
1681         case PUBLIC: return 0;
1682         case 0: return 2;
1683         }
1684     }
1685 
1686     /** A customized "cannot override" error message.
1687      *  @param m      The overriding method.
1688      *  @param other  The overridden method.
1689      *  @return       An internationalized string.
1690      */
1691     Fragment cannotOverride(MethodSymbol m, MethodSymbol other) {
1692         Symbol mloc = m.location();
1693         Symbol oloc = other.location();
1694 
1695         if ((other.owner.flags() & INTERFACE) == 0)
1696             return Fragments.CantOverride(m, mloc, other, oloc);
1697         else if ((m.owner.flags() & INTERFACE) == 0)
1698             return Fragments.CantImplement(m, mloc, other, oloc);
1699         else
1700             return Fragments.ClashesWith(m, mloc, other, oloc);
1701     }
1702 
1703     /** A customized "override" warning message.
1704      *  @param m      The overriding method.
1705      *  @param other  The overridden method.
1706      *  @return       An internationalized string.
1707      */
1708     Fragment uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1709         Symbol mloc = m.location();
1710         Symbol oloc = other.location();
1711 
1712         if ((other.owner.flags() & INTERFACE) == 0)
1713             return Fragments.UncheckedOverride(m, mloc, other, oloc);
1714         else if ((m.owner.flags() & INTERFACE) == 0)
1715             return Fragments.UncheckedImplement(m, mloc, other, oloc);
1716         else
1717             return Fragments.UncheckedClashWith(m, mloc, other, oloc);
1718     }
1719 
1720     /** A customized "override" warning message.
1721      *  @param m      The overriding method.
1722      *  @param other  The overridden method.
1723      *  @return       An internationalized string.
1724      */
1725     Fragment varargsOverrides(MethodSymbol m, MethodSymbol other) {
1726         Symbol mloc = m.location();
1727         Symbol oloc = other.location();
1728 
1729         if ((other.owner.flags() & INTERFACE) == 0)
1730             return Fragments.VarargsOverride(m, mloc, other, oloc);
1731         else  if ((m.owner.flags() & INTERFACE) == 0)
1732             return Fragments.VarargsImplement(m, mloc, other, oloc);
1733         else
1734             return Fragments.VarargsClashWith(m, mloc, other, oloc);
1735     }
1736 
1737     /** Check that this method conforms with overridden method 'other'.
1738      *  where `origin' is the class where checking started.
1739      *  Complications:
1740      *  (1) Do not check overriding of synthetic methods
1741      *      (reason: they might be final).
1742      *      todo: check whether this is still necessary.
1743      *  (2) Admit the case where an interface proxy throws fewer exceptions
1744      *      than the method it implements. Augment the proxy methods with the
1745      *      undeclared exceptions in this case.
1746      *  (3) When generics are enabled, admit the case where an interface proxy
1747      *      has a result type
1748      *      extended by the result type of the method it implements.
1749      *      Change the proxies result type to the smaller type in this case.
1750      *
1751      *  @param tree         The tree from which positions
1752      *                      are extracted for errors.
1753      *  @param m            The overriding method.
1754      *  @param other        The overridden method.
1755      *  @param origin       The class of which the overriding method
1756      *                      is a member.
1757      */
1758     void checkOverride(JCTree tree,
1759                        MethodSymbol m,
1760                        MethodSymbol other,
1761                        ClassSymbol origin) {
1762         // Don't check overriding of synthetic methods or by bridge methods.
1763         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1764             return;
1765         }
1766 
1767         // Error if static method overrides instance method (JLS 8.4.8.2).
1768         if ((m.flags() & STATIC) != 0 &&
1769                    (other.flags() & STATIC) == 0) {
1770             log.error(TreeInfo.diagnosticPositionFor(m, tree),
1771                       Errors.OverrideStatic(cannotOverride(m, other)));
1772             m.flags_field |= BAD_OVERRIDE;
1773             return;
1774         }
1775 
1776         // Error if instance method overrides static or final
1777         // method (JLS 8.4.8.1).
1778         if ((other.flags() & FINAL) != 0 ||
1779                  (m.flags() & STATIC) == 0 &&
1780                  (other.flags() & STATIC) != 0) {
1781             log.error(TreeInfo.diagnosticPositionFor(m, tree),
1782                       Errors.OverrideMeth(cannotOverride(m, other),
1783                                           asFlagSet(other.flags() & (FINAL | STATIC))));
1784             m.flags_field |= BAD_OVERRIDE;
1785             return;
1786         }
1787 
1788         if ((m.owner.flags() & ANNOTATION) != 0) {
1789             // handled in validateAnnotationMethod
1790             return;
1791         }
1792 
1793         // Error if overriding method has weaker access (JLS 8.4.8.3).
1794         if (protection(m.flags()) > protection(other.flags())) {
1795             log.error(TreeInfo.diagnosticPositionFor(m, tree),
1796                       (other.flags() & AccessFlags) == 0 ?
1797                               Errors.OverrideWeakerAccess(cannotOverride(m, other),
1798                                                           "package") :
1799                               Errors.OverrideWeakerAccess(cannotOverride(m, other),
1800                                                           asFlagSet(other.flags() & AccessFlags)));
1801             m.flags_field |= BAD_OVERRIDE;
1802             return;
1803         }
1804 
1805         if (shouldCheckPreview(m, other, origin)) {
1806             checkPreview(TreeInfo.diagnosticPositionFor(m, tree),
1807                          m, origin.type, other);
1808         }
1809 
1810         Type mt = types.memberType(origin.type, m);
1811         Type ot = types.memberType(origin.type, other);
1812         // Error if overriding result type is different
1813         // (or, in the case of generics mode, not a subtype) of
1814         // overridden result type. We have to rename any type parameters
1815         // before comparing types.
1816         List<Type> mtvars = mt.getTypeArguments();
1817         List<Type> otvars = ot.getTypeArguments();
1818         Type mtres = mt.getReturnType();
1819         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1820 
1821         overrideWarner.clear();
1822         boolean resultTypesOK =
1823             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1824         if (!resultTypesOK) {
1825             if ((m.flags() & STATIC) != 0 && (other.flags() & STATIC) != 0) {
1826                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1827                           Errors.OverrideIncompatibleRet(Fragments.CantHide(m, m.location(), other,
1828                                         other.location()), mtres, otres));
1829                 m.flags_field |= BAD_OVERRIDE;
1830             } else {
1831                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1832                           Errors.OverrideIncompatibleRet(cannotOverride(m, other), mtres, otres));
1833                 m.flags_field |= BAD_OVERRIDE;
1834             }
1835             return;
1836         } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
1837             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1838                     LintWarnings.OverrideUncheckedRet(uncheckedOverrides(m, other), mtres, otres));
1839         }
1840 
1841         // Error if overriding method throws an exception not reported
1842         // by overridden method.
1843         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1844         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1845         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1846         if (unhandledErased.nonEmpty()) {
1847             log.error(TreeInfo.diagnosticPositionFor(m, tree),
1848                       Errors.OverrideMethDoesntThrow(cannotOverride(m, other), unhandledUnerased.head));
1849             m.flags_field |= BAD_OVERRIDE;
1850             return;
1851         }
1852         else if (unhandledUnerased.nonEmpty()) {
1853             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1854                           LintWarnings.OverrideUncheckedThrown(cannotOverride(m, other), unhandledUnerased.head));
1855             return;
1856         }
1857 
1858         // Optional warning if varargs don't agree
1859         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)) {
1860             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1861                         ((m.flags() & Flags.VARARGS) != 0)
1862                         ? LintWarnings.OverrideVarargsMissing(varargsOverrides(m, other))
1863                         : LintWarnings.OverrideVarargsExtra(varargsOverrides(m, other)));
1864         }
1865 
1866         // Warn if instance method overrides bridge method (compiler spec ??)
1867         if ((other.flags() & BRIDGE) != 0) {
1868             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1869                         Warnings.OverrideBridge(uncheckedOverrides(m, other)));
1870         }
1871 
1872         // Warn if a deprecated method overridden by a non-deprecated one.
1873         if (!isDeprecatedOverrideIgnorable(other, origin)) {
1874             checkDeprecated(() -> TreeInfo.diagnosticPositionFor(m, tree), m, other);
1875         }
1876     }
1877     // where
1878         private boolean shouldCheckPreview(MethodSymbol m, MethodSymbol other, ClassSymbol origin) {
1879             if (m.owner != origin ||
1880                 //performance - only do the expensive checks when the overridden method is a Preview API:
1881                 ((other.flags() & PREVIEW_API) == 0 &&
1882                  (other.owner.flags() & PREVIEW_API) == 0)) {
1883                 return false;
1884             }
1885 
1886             for (Symbol s : types.membersClosure(origin.type, false).getSymbolsByName(m.name)) {
1887                 if (m != s && m.overrides(s, origin, types, false)) {
1888                     //only produce preview warnings or errors if "m" immediatelly overrides "other"
1889                     //without intermediate overriding methods:
1890                     return s == other;
1891                 }
1892             }
1893 
1894             return false;
1895         }
1896         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1897             // If the method, m, is defined in an interface, then ignore the issue if the method
1898             // is only inherited via a supertype and also implemented in the supertype,
1899             // because in that case, we will rediscover the issue when examining the method
1900             // in the supertype.
1901             // If the method, m, is not defined in an interface, then the only time we need to
1902             // address the issue is when the method is the supertype implementation: any other
1903             // case, we will have dealt with when examining the supertype classes
1904             ClassSymbol mc = m.enclClass();
1905             Type st = types.supertype(origin.type);
1906             if (!st.hasTag(CLASS))
1907                 return true;
1908             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1909 
1910             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1911                 List<Type> intfs = types.interfaces(origin.type);
1912                 return (intfs.contains(mc.type) ? false : (stimpl != null));
1913             }
1914             else
1915                 return (stimpl != m);
1916         }
1917 
1918 
1919     // used to check if there were any unchecked conversions
1920     Warner overrideWarner = new Warner();
1921 
1922     /** Check that a class does not inherit two concrete methods
1923      *  with the same signature.
1924      *  @param pos          Position to be used for error reporting.
1925      *  @param site         The class type to be checked.
1926      */
1927     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1928         Type sup = types.supertype(site);
1929         if (!sup.hasTag(CLASS)) return;
1930 
1931         for (Type t1 = sup;
1932              t1.hasTag(CLASS) && t1.tsym.type.isParameterized();
1933              t1 = types.supertype(t1)) {
1934             for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) {
1935                 if (s1.kind != MTH ||
1936                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1937                     !s1.isInheritedIn(site.tsym, types) ||
1938                     ((MethodSymbol)s1).implementation(site.tsym,
1939                                                       types,
1940                                                       true) != s1)
1941                     continue;
1942                 Type st1 = types.memberType(t1, s1);
1943                 int s1ArgsLength = st1.getParameterTypes().length();
1944                 if (st1 == s1.type) continue;
1945 
1946                 for (Type t2 = sup;
1947                      t2.hasTag(CLASS);
1948                      t2 = types.supertype(t2)) {
1949                     for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) {
1950                         if (s2 == s1 ||
1951                             s2.kind != MTH ||
1952                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1953                             s2.type.getParameterTypes().length() != s1ArgsLength ||
1954                             !s2.isInheritedIn(site.tsym, types) ||
1955                             ((MethodSymbol)s2).implementation(site.tsym,
1956                                                               types,
1957                                                               true) != s2)
1958                             continue;
1959                         Type st2 = types.memberType(t2, s2);
1960                         if (types.overrideEquivalent(st1, st2))
1961                             log.error(pos,
1962                                       Errors.ConcreteInheritanceConflict(s1, t1, s2, t2, sup));
1963                     }
1964                 }
1965             }
1966         }
1967     }
1968 
1969     /** Check that classes (or interfaces) do not each define an abstract
1970      *  method with same name and arguments but incompatible return types.
1971      *  @param pos          Position to be used for error reporting.
1972      *  @param t1           The first argument type.
1973      *  @param t2           The second argument type.
1974      */
1975     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1976                                             Type t1,
1977                                             Type t2,
1978                                             Type site) {
1979         if ((site.tsym.flags() & COMPOUND) != 0) {
1980             // special case for intersections: need to eliminate wildcards in supertypes
1981             t1 = types.capture(t1);
1982             t2 = types.capture(t2);
1983         }
1984         return firstIncompatibility(pos, t1, t2, site) == null;
1985     }
1986 
1987     /** Return the first method which is defined with same args
1988      *  but different return types in two given interfaces, or null if none
1989      *  exists.
1990      *  @param t1     The first type.
1991      *  @param t2     The second type.
1992      *  @param site   The most derived type.
1993      *  @return symbol from t2 that conflicts with one in t1.
1994      */
1995     private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1996         Map<TypeSymbol,Type> interfaces1 = new HashMap<>();
1997         closure(t1, interfaces1);
1998         Map<TypeSymbol,Type> interfaces2;
1999         if (t1 == t2)
2000             interfaces2 = interfaces1;
2001         else
2002             closure(t2, interfaces1, interfaces2 = new HashMap<>());
2003 
2004         for (Type t3 : interfaces1.values()) {
2005             for (Type t4 : interfaces2.values()) {
2006                 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
2007                 if (s != null) return s;
2008             }
2009         }
2010         return null;
2011     }
2012 
2013     /** Compute all the supertypes of t, indexed by type symbol. */
2014     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
2015         if (!t.hasTag(CLASS)) return;
2016         if (typeMap.put(t.tsym, t) == null) {
2017             closure(types.supertype(t), typeMap);
2018             for (Type i : types.interfaces(t))
2019                 closure(i, typeMap);
2020         }
2021     }
2022 
2023     /** Compute all the supertypes of t, indexed by type symbol (except those in typesSkip). */
2024     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
2025         if (!t.hasTag(CLASS)) return;
2026         if (typesSkip.get(t.tsym) != null) return;
2027         if (typeMap.put(t.tsym, t) == null) {
2028             closure(types.supertype(t), typesSkip, typeMap);
2029             for (Type i : types.interfaces(t))
2030                 closure(i, typesSkip, typeMap);
2031         }
2032     }
2033 
2034     /** Return the first method in t2 that conflicts with a method from t1. */
2035     private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
2036         for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) {
2037             Type st1 = null;
2038             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
2039                     (s1.flags() & SYNTHETIC) != 0) continue;
2040             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
2041             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
2042             for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) {
2043                 if (s1 == s2) continue;
2044                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
2045                         (s2.flags() & SYNTHETIC) != 0) continue;
2046                 if (st1 == null) st1 = types.memberType(t1, s1);
2047                 Type st2 = types.memberType(t2, s2);
2048                 if (types.overrideEquivalent(st1, st2)) {
2049                     List<Type> tvars1 = st1.getTypeArguments();
2050                     List<Type> tvars2 = st2.getTypeArguments();
2051                     Type rt1 = st1.getReturnType();
2052                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
2053                     boolean compat =
2054                         types.isSameType(rt1, rt2) ||
2055                         !rt1.isPrimitiveOrVoid() &&
2056                         !rt2.isPrimitiveOrVoid() &&
2057                         (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
2058                          types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
2059                          checkCommonOverriderIn(s1,s2,site);
2060                     if (!compat) {
2061                         if (types.isSameType(t1, t2)) {
2062                             log.error(pos, Errors.IncompatibleDiffRetSameType(t1,
2063                                     s2.name, types.memberType(t2, s2).getParameterTypes()));
2064                         } else {
2065                             log.error(pos, Errors.TypesIncompatible(t1, t2,
2066                                     Fragments.IncompatibleDiffRet(s2.name, types.memberType(t2, s2).getParameterTypes())));
2067                         }
2068                         return s2;
2069                     }
2070                 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
2071                         !checkCommonOverriderIn(s1, s2, site)) {
2072                     log.error(pos, Errors.NameClashSameErasureNoOverride(
2073                             s1.name, types.memberType(site, s1).asMethodType().getParameterTypes(), s1.location(),
2074                             s2.name, types.memberType(site, s2).asMethodType().getParameterTypes(), s2.location()));
2075                     return s2;
2076                 }
2077             }
2078         }
2079         return null;
2080     }
2081     //WHERE
2082     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
2083         Map<TypeSymbol,Type> supertypes = new HashMap<>();
2084         Type st1 = types.memberType(site, s1);
2085         Type st2 = types.memberType(site, s2);
2086         closure(site, supertypes);
2087         for (Type t : supertypes.values()) {
2088             for (Symbol s3 : t.tsym.members().getSymbolsByName(s1.name)) {
2089                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
2090                 Type st3 = types.memberType(site,s3);
2091                 if (types.overrideEquivalent(st3, st1) &&
2092                         types.overrideEquivalent(st3, st2) &&
2093                         types.returnTypeSubstitutable(st3, st1) &&
2094                         types.returnTypeSubstitutable(st3, st2)) {
2095                     return true;
2096                 }
2097             }
2098         }
2099         return false;
2100     }
2101 
2102     /** Check that a given method conforms with any method it overrides.
2103      *  @param tree         The tree from which positions are extracted
2104      *                      for errors.
2105      *  @param m            The overriding method.
2106      */
2107     void checkOverride(Env<AttrContext> env, JCMethodDecl tree, MethodSymbol m) {
2108         ClassSymbol origin = (ClassSymbol)m.owner;
2109         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name)) {
2110             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
2111                 log.error(tree.pos(), Errors.EnumNoFinalize);
2112                 return;
2113             }
2114         }
2115         if (allowValueClasses && origin.isValueClass() && names.finalize.equals(m.name)) {
2116             if (m.overrides(syms.objectFinalize, origin, types, false)) {
2117                 log.warning(tree.pos(), Warnings.ValueFinalize);
2118             }
2119         }
2120         if (allowRecords && origin.isRecord()) {
2121             // let's find out if this is a user defined accessor in which case the @Override annotation is acceptable
2122             Optional<? extends RecordComponent> recordComponent = origin.getRecordComponents().stream()
2123                     .filter(rc -> rc.accessor == tree.sym && (rc.accessor.flags_field & GENERATED_MEMBER) == 0).findFirst();
2124             if (recordComponent.isPresent()) {
2125                 return;
2126             }
2127         }
2128 
2129         for (Type t = origin.type; t.hasTag(CLASS);
2130              t = types.supertype(t)) {
2131             if (t != origin.type) {
2132                 checkOverride(tree, t, origin, m);
2133             }
2134             for (Type t2 : types.interfaces(t)) {
2135                 checkOverride(tree, t2, origin, m);
2136             }
2137         }
2138 
2139         final boolean explicitOverride = m.attribute(syms.overrideType.tsym) != null;
2140         // Check if this method must override a super method due to being annotated with @Override
2141         // or by virtue of being a member of a diamond inferred anonymous class. Latter case is to
2142         // be treated "as if as they were annotated" with @Override.
2143         boolean mustOverride = explicitOverride ||
2144                 (env.info.isAnonymousDiamond && !m.isConstructor() && !m.isPrivate());
2145         if (mustOverride && !isOverrider(m)) {
2146             DiagnosticPosition pos = tree.pos();
2147             for (JCAnnotation a : tree.getModifiers().annotations) {
2148                 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2149                     pos = a.pos();
2150                     break;
2151                 }
2152             }
2153             log.error(pos,
2154                       explicitOverride ? (m.isStatic() ? Errors.StaticMethodsCannotBeAnnotatedWithOverride(m, m.enclClass()) : Errors.MethodDoesNotOverrideSuperclass(m, m.enclClass())) :
2155                                 Errors.AnonymousDiamondMethodDoesNotOverrideSuperclass(Fragments.DiamondAnonymousMethodsImplicitlyOverride));
2156         }
2157     }
2158 
2159     void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
2160         TypeSymbol c = site.tsym;
2161         for (Symbol sym : c.members().getSymbolsByName(m.name)) {
2162             if (m.overrides(sym, origin, types, false)) {
2163                 if ((sym.flags() & ABSTRACT) == 0) {
2164                     checkOverride(tree, m, (MethodSymbol)sym, origin);
2165                 }
2166             }
2167         }
2168     }
2169 
2170     private Predicate<Symbol> equalsHasCodeFilter = s -> MethodSymbol.implementation_filter.test(s) &&
2171             (s.flags() & BAD_OVERRIDE) == 0;
2172 
2173     public void checkClassOverrideEqualsAndHashIfNeeded(DiagnosticPosition pos,
2174             ClassSymbol someClass) {
2175         /* At present, annotations cannot possibly have a method that is override
2176          * equivalent with Object.equals(Object) but in any case the condition is
2177          * fine for completeness.
2178          */
2179         if (someClass == (ClassSymbol)syms.objectType.tsym ||
2180             someClass.isInterface() || someClass.isEnum() ||
2181             (someClass.flags() & ANNOTATION) != 0 ||
2182             (someClass.flags() & ABSTRACT) != 0) return;
2183         //anonymous inner classes implementing interfaces need especial treatment
2184         if (someClass.isAnonymous()) {
2185             List<Type> interfaces =  types.interfaces(someClass.type);
2186             if (interfaces != null && !interfaces.isEmpty() &&
2187                 interfaces.head.tsym == syms.comparatorType.tsym) return;
2188         }
2189         checkClassOverrideEqualsAndHash(pos, someClass);
2190     }
2191 
2192     private void checkClassOverrideEqualsAndHash(DiagnosticPosition pos,
2193             ClassSymbol someClass) {
2194         if (lint.isEnabled(LintCategory.OVERRIDES)) {
2195             MethodSymbol equalsAtObject = (MethodSymbol)syms.objectType
2196                     .tsym.members().findFirst(names.equals);
2197             MethodSymbol hashCodeAtObject = (MethodSymbol)syms.objectType
2198                     .tsym.members().findFirst(names.hashCode);
2199             MethodSymbol equalsImpl = types.implementation(equalsAtObject,
2200                     someClass, false, equalsHasCodeFilter);
2201             boolean overridesEquals = equalsImpl != null &&
2202                                       equalsImpl.owner == someClass;
2203             boolean overridesHashCode = types.implementation(hashCodeAtObject,
2204                 someClass, false, equalsHasCodeFilter) != hashCodeAtObject;
2205 
2206             if (overridesEquals && !overridesHashCode) {
2207                 log.warning(pos,
2208                             LintWarnings.OverrideEqualsButNotHashcode(someClass));
2209             }
2210         }
2211     }
2212 
2213     public void checkHasMain(DiagnosticPosition pos, ClassSymbol c) {
2214         boolean found = false;
2215 
2216         for (Symbol sym : c.members().getSymbolsByName(names.main)) {
2217             if (sym.kind == MTH && (sym.flags() & PRIVATE) == 0) {
2218                 MethodSymbol meth = (MethodSymbol)sym;
2219                 if (!types.isSameType(meth.getReturnType(), syms.voidType)) {
2220                     continue;
2221                 }
2222                 if (meth.params.isEmpty()) {
2223                     found = true;
2224                     break;
2225                 }
2226                 if (meth.params.size() != 1) {
2227                     continue;
2228                 }
2229                 if (!types.isSameType(meth.params.head.type, types.makeArrayType(syms.stringType))) {
2230                     continue;
2231                 }
2232 
2233                 found = true;
2234                 break;
2235             }
2236         }
2237 
2238         if (!found) {
2239             log.error(pos, Errors.ImplicitClassDoesNotHaveMainMethod);
2240         }
2241     }
2242 
2243     public void checkModuleName (JCModuleDecl tree) {
2244         Name moduleName = tree.sym.name;
2245         Assert.checkNonNull(moduleName);
2246         if (lint.isEnabled(LintCategory.MODULE)) {
2247             JCExpression qualId = tree.qualId;
2248             while (qualId != null) {
2249                 Name componentName;
2250                 DiagnosticPosition pos;
2251                 switch (qualId.getTag()) {
2252                     case SELECT:
2253                         JCFieldAccess selectNode = ((JCFieldAccess) qualId);
2254                         componentName = selectNode.name;
2255                         pos = selectNode.pos();
2256                         qualId = selectNode.selected;
2257                         break;
2258                     case IDENT:
2259                         componentName = ((JCIdent) qualId).name;
2260                         pos = qualId.pos();
2261                         qualId = null;
2262                         break;
2263                     default:
2264                         throw new AssertionError("Unexpected qualified identifier: " + qualId.toString());
2265                 }
2266                 if (componentName != null) {
2267                     String moduleNameComponentString = componentName.toString();
2268                     int nameLength = moduleNameComponentString.length();
2269                     if (nameLength > 0 && Character.isDigit(moduleNameComponentString.charAt(nameLength - 1))) {
2270                         log.warning(pos, LintWarnings.PoorChoiceForModuleName(componentName));
2271                     }
2272                 }
2273             }
2274         }
2275     }
2276 
2277     private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
2278         ClashFilter cf = new ClashFilter(origin.type);
2279         return (cf.test(s1) &&
2280                 cf.test(s2) &&
2281                 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
2282     }
2283 
2284 
2285     /** Check that all abstract members of given class have definitions.
2286      *  @param pos          Position to be used for error reporting.
2287      *  @param c            The class.
2288      */
2289     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
2290         MethodSymbol undef = types.firstUnimplementedAbstract(c);
2291         if (undef != null) {
2292             MethodSymbol undef1 =
2293                 new MethodSymbol(undef.flags(), undef.name,
2294                                  types.memberType(c.type, undef), undef.owner);
2295             log.error(pos,
2296                       Errors.DoesNotOverrideAbstract(c, undef1, undef1.location()));
2297         }
2298     }
2299 
2300     void checkNonCyclicDecl(JCClassDecl tree) {
2301         CycleChecker cc = new CycleChecker();
2302         cc.scan(tree);
2303         if (!cc.errorFound && !cc.partialCheck) {
2304             tree.sym.flags_field |= ACYCLIC;
2305         }
2306     }
2307 
2308     class CycleChecker extends TreeScanner {
2309 
2310         Set<Symbol> seenClasses = new HashSet<>();
2311         boolean errorFound = false;
2312         boolean partialCheck = false;
2313 
2314         private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
2315             if (sym != null && sym.kind == TYP) {
2316                 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
2317                 if (classEnv != null) {
2318                     DiagnosticSource prevSource = log.currentSource();
2319                     try {
2320                         log.useSource(classEnv.toplevel.sourcefile);
2321                         scan(classEnv.tree);
2322                     }
2323                     finally {
2324                         log.useSource(prevSource.getFile());
2325                     }
2326                 } else if (sym.kind == TYP) {
2327                     checkClass(pos, sym, List.nil());
2328                 }
2329             } else if (sym == null || sym.kind != PCK) {
2330                 //not completed yet
2331                 partialCheck = true;
2332             }
2333         }
2334 
2335         @Override
2336         public void visitSelect(JCFieldAccess tree) {
2337             super.visitSelect(tree);
2338             checkSymbol(tree.pos(), tree.sym);
2339         }
2340 
2341         @Override
2342         public void visitIdent(JCIdent tree) {
2343             checkSymbol(tree.pos(), tree.sym);
2344         }
2345 
2346         @Override
2347         public void visitTypeApply(JCTypeApply tree) {
2348             scan(tree.clazz);
2349         }
2350 
2351         @Override
2352         public void visitTypeArray(JCArrayTypeTree tree) {
2353             scan(tree.elemtype);
2354         }
2355 
2356         @Override
2357         public void visitClassDef(JCClassDecl tree) {
2358             List<JCTree> supertypes = List.nil();
2359             if (tree.getExtendsClause() != null) {
2360                 supertypes = supertypes.prepend(tree.getExtendsClause());
2361             }
2362             if (tree.getImplementsClause() != null) {
2363                 for (JCTree intf : tree.getImplementsClause()) {
2364                     supertypes = supertypes.prepend(intf);
2365                 }
2366             }
2367             checkClass(tree.pos(), tree.sym, supertypes);
2368         }
2369 
2370         void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
2371             if ((c.flags_field & ACYCLIC) != 0)
2372                 return;
2373             if (seenClasses.contains(c)) {
2374                 errorFound = true;
2375                 log.error(pos, Errors.CyclicInheritance(c));
2376                 seenClasses.stream()
2377                   .filter(s -> !s.type.isErroneous())
2378                   .filter(ClassSymbol.class::isInstance)
2379                   .map(ClassSymbol.class::cast)
2380                   .forEach(Check.this::handleCyclic);
2381             } else if (!c.type.isErroneous()) {
2382                 try {
2383                     seenClasses.add(c);
2384                     if (c.type.hasTag(CLASS)) {
2385                         if (supertypes.nonEmpty()) {
2386                             scan(supertypes);
2387                         }
2388                         else {
2389                             ClassType ct = (ClassType)c.type;
2390                             if (ct.supertype_field == null ||
2391                                     ct.interfaces_field == null) {
2392                                 //not completed yet
2393                                 partialCheck = true;
2394                                 return;
2395                             }
2396                             checkSymbol(pos, ct.supertype_field.tsym);
2397                             for (Type intf : ct.interfaces_field) {
2398                                 checkSymbol(pos, intf.tsym);
2399                             }
2400                         }
2401                         if (c.owner.kind == TYP) {
2402                             checkSymbol(pos, c.owner);
2403                         }
2404                     }
2405                 } finally {
2406                     seenClasses.remove(c);
2407                 }
2408             }
2409         }
2410     }
2411 
2412     /** Check for cyclic references. Issue an error if the
2413      *  symbol of the type referred to has a LOCKED flag set.
2414      *
2415      *  @param pos      Position to be used for error reporting.
2416      *  @param t        The type referred to.
2417      */
2418     void checkNonCyclic(DiagnosticPosition pos, Type t) {
2419         checkNonCyclicInternal(pos, t);
2420     }
2421 
2422 
2423     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
2424         checkNonCyclic1(pos, t, List.nil());
2425     }
2426 
2427     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
2428         final TypeVar tv;
2429         if  (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
2430             return;
2431         if (seen.contains(t)) {
2432             tv = (TypeVar)t;
2433             tv.setUpperBound(types.createErrorType(t));
2434             log.error(pos, Errors.CyclicInheritance(t));
2435         } else if (t.hasTag(TYPEVAR)) {
2436             tv = (TypeVar)t;
2437             seen = seen.prepend(tv);
2438             for (Type b : types.getBounds(tv))
2439                 checkNonCyclic1(pos, b, seen);
2440         }
2441     }
2442 
2443     /** Check for cyclic references. Issue an error if the
2444      *  symbol of the type referred to has a LOCKED flag set.
2445      *
2446      *  @param pos      Position to be used for error reporting.
2447      *  @param t        The type referred to.
2448      *  @return        True if the check completed on all attributed classes
2449      */
2450     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
2451         boolean complete = true; // was the check complete?
2452         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
2453         Symbol c = t.tsym;
2454         if ((c.flags_field & ACYCLIC) != 0) return true;
2455 
2456         if ((c.flags_field & LOCKED) != 0) {
2457             log.error(pos, Errors.CyclicInheritance(c));
2458             handleCyclic((ClassSymbol)c);
2459         } else if (!c.type.isErroneous()) {
2460             try {
2461                 c.flags_field |= LOCKED;
2462                 if (c.type.hasTag(CLASS)) {
2463                     ClassType clazz = (ClassType)c.type;
2464                     if (clazz.interfaces_field != null)
2465                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
2466                             complete &= checkNonCyclicInternal(pos, l.head);
2467                     if (clazz.supertype_field != null) {
2468                         Type st = clazz.supertype_field;
2469                         if (st != null && st.hasTag(CLASS))
2470                             complete &= checkNonCyclicInternal(pos, st);
2471                     }
2472                     if (c.owner.kind == TYP)
2473                         complete &= checkNonCyclicInternal(pos, c.owner.type);
2474                 }
2475             } finally {
2476                 c.flags_field &= ~LOCKED;
2477             }
2478         }
2479         if (complete)
2480             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.isCompleted();
2481         if (complete) c.flags_field |= ACYCLIC;
2482         return complete;
2483     }
2484 
2485     /** Handle finding an inheritance cycle on a class by setting
2486      *  the class' and its supertypes' types to the error type.
2487      **/
2488     private void handleCyclic(ClassSymbol c) {
2489         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
2490             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
2491         Type st = types.supertype(c.type);
2492         if (st.hasTag(CLASS))
2493             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
2494         c.type = types.createErrorType(c, c.type);
2495         c.flags_field |= ACYCLIC;
2496     }
2497 
2498     /** Check that all methods which implement some
2499      *  method conform to the method they implement.
2500      *  @param tree         The class definition whose members are checked.
2501      */
2502     void checkImplementations(JCClassDecl tree) {
2503         checkImplementations(tree, tree.sym, tree.sym);
2504     }
2505     //where
2506         /** Check that all methods which implement some
2507          *  method in `ic' conform to the method they implement.
2508          */
2509         void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
2510             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
2511                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
2512                 if ((lc.flags() & ABSTRACT) != 0) {
2513                     for (Symbol sym : lc.members().getSymbols(NON_RECURSIVE)) {
2514                         if (sym.kind == MTH &&
2515                             (sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
2516                             MethodSymbol absmeth = (MethodSymbol)sym;
2517                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
2518                             if (implmeth != null && implmeth != absmeth &&
2519                                 (implmeth.owner.flags() & INTERFACE) ==
2520                                 (origin.flags() & INTERFACE)) {
2521                                 // don't check if implmeth is in a class, yet
2522                                 // origin is an interface. This case arises only
2523                                 // if implmeth is declared in Object. The reason is
2524                                 // that interfaces really don't inherit from
2525                                 // Object it's just that the compiler represents
2526                                 // things that way.
2527                                 checkOverride(tree, implmeth, absmeth, origin);
2528                             }
2529                         }
2530                     }
2531                 }
2532             }
2533         }
2534 
2535     /** Check that all abstract methods implemented by a class are
2536      *  mutually compatible.
2537      *  @param pos          Position to be used for error reporting.
2538      *  @param c            The class whose interfaces are checked.
2539      */
2540     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2541         List<Type> supertypes = types.interfaces(c);
2542         Type supertype = types.supertype(c);
2543         if (supertype.hasTag(CLASS) &&
2544             (supertype.tsym.flags() & ABSTRACT) != 0)
2545             supertypes = supertypes.prepend(supertype);
2546         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2547             if (!l.head.getTypeArguments().isEmpty() &&
2548                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2549                 return;
2550             for (List<Type> m = supertypes; m != l; m = m.tail)
2551                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2552                     return;
2553         }
2554         checkCompatibleConcretes(pos, c);
2555 
2556         Type identitySuper = null;
2557         Type superType = types.supertype(c);
2558         if (superType.isIdentityClass())
2559             identitySuper = superType;
2560         if (c.isValueClass() && identitySuper != null && identitySuper.tsym != syms.objectType.tsym) { // Object is special
2561             log.error(pos, Errors.ValueTypeHasIdentitySuperType(c, identitySuper));
2562         }
2563     }
2564 
2565     /** Check that all non-override equivalent methods accessible from 'site'
2566      *  are mutually compatible (JLS 8.4.8/9.4.1).
2567      *
2568      *  @param pos  Position to be used for error reporting.
2569      *  @param site The class whose methods are checked.
2570      *  @param sym  The method symbol to be checked.
2571      */
2572     void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2573          ClashFilter cf = new ClashFilter(site);
2574         //for each method m1 that is overridden (directly or indirectly)
2575         //by method 'sym' in 'site'...
2576 
2577         ArrayList<Symbol> symbolsByName = new ArrayList<>();
2578         types.membersClosure(site, false).getSymbolsByName(sym.name, cf).forEach(symbolsByName::add);
2579         for (Symbol m1 : symbolsByName) {
2580             if (!sym.overrides(m1, site.tsym, types, false)) {
2581                 continue;
2582             }
2583 
2584             //...check each method m2 that is a member of 'site'
2585             for (Symbol m2 : symbolsByName) {
2586                 if (m2 == m1) continue;
2587                 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2588                 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
2589                 if (!types.isSubSignature(sym.type, types.memberType(site, m2)) &&
2590                         types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
2591                     sym.flags_field |= CLASH;
2592                     if (m1 == sym) {
2593                         log.error(pos, Errors.NameClashSameErasureNoOverride(
2594                             m1.name, types.memberType(site, m1).asMethodType().getParameterTypes(), m1.location(),
2595                             m2.name, types.memberType(site, m2).asMethodType().getParameterTypes(), m2.location()));
2596                     } else {
2597                         ClassType ct = (ClassType)site;
2598                         String kind = ct.isInterface() ? "interface" : "class";
2599                         log.error(pos, Errors.NameClashSameErasureNoOverride1(
2600                             kind,
2601                             ct.tsym.name,
2602                             m1.name,
2603                             types.memberType(site, m1).asMethodType().getParameterTypes(),
2604                             m1.location(),
2605                             m2.name,
2606                             types.memberType(site, m2).asMethodType().getParameterTypes(),
2607                             m2.location()));
2608                     }
2609                     return;
2610                 }
2611             }
2612         }
2613     }
2614 
2615     /** Check that all static methods accessible from 'site' are
2616      *  mutually compatible (JLS 8.4.8).
2617      *
2618      *  @param pos  Position to be used for error reporting.
2619      *  @param site The class whose methods are checked.
2620      *  @param sym  The method symbol to be checked.
2621      */
2622     void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2623         ClashFilter cf = new ClashFilter(site);
2624         //for each method m1 that is a member of 'site'...
2625         for (Symbol s : types.membersClosure(site, true).getSymbolsByName(sym.name, cf)) {
2626             //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2627             //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
2628             if (!types.isSubSignature(sym.type, types.memberType(site, s))) {
2629                 if (types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
2630                     log.error(pos,
2631                               Errors.NameClashSameErasureNoHide(sym, sym.location(), s, s.location()));
2632                     return;
2633                 }
2634             }
2635          }
2636      }
2637 
2638      //where
2639      private class ClashFilter implements Predicate<Symbol> {
2640 
2641          Type site;
2642 
2643          ClashFilter(Type site) {
2644              this.site = site;
2645          }
2646 
2647          boolean shouldSkip(Symbol s) {
2648              return (s.flags() & CLASH) != 0 &&
2649                 s.owner == site.tsym;
2650          }
2651 
2652          @Override
2653          public boolean test(Symbol s) {
2654              return s.kind == MTH &&
2655                      (s.flags() & SYNTHETIC) == 0 &&
2656                      !shouldSkip(s) &&
2657                      s.isInheritedIn(site.tsym, types) &&
2658                      !s.isConstructor();
2659          }
2660      }
2661 
2662     void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
2663         DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
2664         for (Symbol m : types.membersClosure(site, false).getSymbols(dcf)) {
2665             Assert.check(m.kind == MTH);
2666             List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
2667             if (prov.size() > 1) {
2668                 ListBuffer<Symbol> abstracts = new ListBuffer<>();
2669                 ListBuffer<Symbol> defaults = new ListBuffer<>();
2670                 for (MethodSymbol provSym : prov) {
2671                     if ((provSym.flags() & DEFAULT) != 0) {
2672                         defaults = defaults.append(provSym);
2673                     } else if ((provSym.flags() & ABSTRACT) != 0) {
2674                         abstracts = abstracts.append(provSym);
2675                     }
2676                     if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
2677                         //strong semantics - issue an error if two sibling interfaces
2678                         //have two override-equivalent defaults - or if one is abstract
2679                         //and the other is default
2680                         Fragment diagKey;
2681                         Symbol s1 = defaults.first();
2682                         Symbol s2;
2683                         if (defaults.size() > 1) {
2684                             s2 = defaults.toList().tail.head;
2685                             diagKey = Fragments.IncompatibleUnrelatedDefaults(Kinds.kindName(site.tsym), site,
2686                                     m.name, types.memberType(site, m).getParameterTypes(),
2687                                     s1.location(), s2.location());
2688 
2689                         } else {
2690                             s2 = abstracts.first();
2691                             diagKey = Fragments.IncompatibleAbstractDefault(Kinds.kindName(site.tsym), site,
2692                                     m.name, types.memberType(site, m).getParameterTypes(),
2693                                     s1.location(), s2.location());
2694                         }
2695                         log.error(pos, Errors.TypesIncompatible(s1.location().type, s2.location().type, diagKey));
2696                         break;
2697                     }
2698                 }
2699             }
2700         }
2701     }
2702 
2703     //where
2704      private class DefaultMethodClashFilter implements Predicate<Symbol> {
2705 
2706          Type site;
2707 
2708          DefaultMethodClashFilter(Type site) {
2709              this.site = site;
2710          }
2711 
2712          @Override
2713          public boolean test(Symbol s) {
2714              return s.kind == MTH &&
2715                      (s.flags() & DEFAULT) != 0 &&
2716                      s.isInheritedIn(site.tsym, types) &&
2717                      !s.isConstructor();
2718          }
2719      }
2720 
2721     /** Report warnings for potentially ambiguous method declarations in the given site. */
2722     void checkPotentiallyAmbiguousOverloads(JCClassDecl tree, Type site) {
2723 
2724         // Skip if warning not enabled
2725         if (!lint.isEnabled(LintCategory.OVERLOADS))
2726             return;
2727 
2728         // Gather all of site's methods, including overridden methods, grouped by name (except Object methods)
2729         List<java.util.List<MethodSymbol>> methodGroups = methodsGroupedByName(site,
2730             new PotentiallyAmbiguousFilter(site), ArrayList::new);
2731 
2732         // Build the predicate that determines if site is responsible for an ambiguity
2733         BiPredicate<MethodSymbol, MethodSymbol> responsible = buildResponsiblePredicate(site, methodGroups);
2734 
2735         // Now remove overridden methods from each group, leaving only site's actual members
2736         methodGroups.forEach(list -> removePreempted(list, (m1, m2) -> m1.overrides(m2, site.tsym, types, false)));
2737 
2738         // Allow site's own declared methods (only) to apply @SuppressWarnings("overloads")
2739         methodGroups.forEach(list -> list.removeIf(
2740             m -> m.owner == site.tsym && !lint.augment(m).isEnabled(LintCategory.OVERLOADS)));
2741 
2742         // Warn about ambiguous overload method pairs for which site is responsible
2743         methodGroups.forEach(list -> compareAndRemove(list, (m1, m2) -> {
2744 
2745             // See if this is an ambiguous overload for which "site" is responsible
2746             if (!potentiallyAmbiguousOverload(site, m1, m2) || !responsible.test(m1, m2))
2747                 return 0;
2748 
2749             // Locate the warning at one of the methods, if possible
2750             DiagnosticPosition pos =
2751                 m1.owner == site.tsym ? TreeInfo.diagnosticPositionFor(m1, tree) :
2752                 m2.owner == site.tsym ? TreeInfo.diagnosticPositionFor(m2, tree) :
2753                 tree.pos();
2754 
2755             // Log the warning
2756             log.warning(pos,
2757                 LintWarnings.PotentiallyAmbiguousOverload(
2758                     m1.asMemberOf(site, types), m1.location(),
2759                     m2.asMemberOf(site, types), m2.location()));
2760 
2761             // Don't warn again for either of these two methods
2762             return FIRST | SECOND;
2763         }));
2764     }
2765 
2766     /** Build a predicate that determines, given two methods that are members of the given class,
2767      *  whether the class should be held "responsible" if the methods are potentially ambiguous.
2768      *
2769      *  Sometimes ambiguous methods are unavoidable because they're inherited from a supertype.
2770      *  For example, any subtype of Spliterator.OfInt will have ambiguities for both
2771      *  forEachRemaining() and tryAdvance() (in both cases the overloads are IntConsumer and
2772      *  Consumer&lt;? super Integer&gt;). So we only want to "blame" a class when that class is
2773      *  itself responsible for creating the ambiguity. We declare that a class C is "responsible"
2774      *  for the ambiguity between two methods m1 and m2 if there is no direct supertype T of C
2775      *  such that m1 and m2, or some overrides thereof, both exist in T and are ambiguous in T.
2776      *  As an optimization, we first check if either method is declared in C and does not override
2777      *  any other methods; in this case the class is definitely responsible.
2778      */
2779     BiPredicate<MethodSymbol, MethodSymbol> buildResponsiblePredicate(Type site,
2780         List<? extends Collection<MethodSymbol>> methodGroups) {
2781 
2782         // Define the "overrides" predicate
2783         BiPredicate<MethodSymbol, MethodSymbol> overrides = (m1, m2) -> m1.overrides(m2, site.tsym, types, false);
2784 
2785         // Map each method declared in site to a list of the supertype method(s) it directly overrides
2786         HashMap<MethodSymbol, ArrayList<MethodSymbol>> overriddenMethodsMap = new HashMap<>();
2787         methodGroups.forEach(list -> {
2788             for (MethodSymbol m : list) {
2789 
2790                 // Skip methods not declared in site
2791                 if (m.owner != site.tsym)
2792                     continue;
2793 
2794                 // Gather all supertype methods overridden by m, directly or indirectly
2795                 ArrayList<MethodSymbol> overriddenMethods = list.stream()
2796                   .filter(m2 -> m2 != m && overrides.test(m, m2))
2797                   .collect(Collectors.toCollection(ArrayList::new));
2798 
2799                 // Eliminate non-direct overrides
2800                 removePreempted(overriddenMethods, overrides);
2801 
2802                 // Add to map
2803                 overriddenMethodsMap.put(m, overriddenMethods);
2804             }
2805         });
2806 
2807         // Build the predicate
2808         return (m1, m2) -> {
2809 
2810             // Get corresponding supertype methods (if declared in site)
2811             java.util.List<MethodSymbol> overriddenMethods1 = overriddenMethodsMap.get(m1);
2812             java.util.List<MethodSymbol> overriddenMethods2 = overriddenMethodsMap.get(m2);
2813 
2814             // Quick check for the case where a method was added by site itself
2815             if (overriddenMethods1 != null && overriddenMethods1.isEmpty())
2816                 return true;
2817             if (overriddenMethods2 != null && overriddenMethods2.isEmpty())
2818                 return true;
2819 
2820             // Get each method's corresponding method(s) from supertypes of site
2821             java.util.List<MethodSymbol> supertypeMethods1 = overriddenMethods1 != null ?
2822               overriddenMethods1 : Collections.singletonList(m1);
2823             java.util.List<MethodSymbol> supertypeMethods2 = overriddenMethods2 != null ?
2824               overriddenMethods2 : Collections.singletonList(m2);
2825 
2826             // See if we can blame some direct supertype instead
2827             return types.directSupertypes(site).stream()
2828               .filter(stype -> stype != syms.objectType)
2829               .map(stype -> stype.tsym.type)                // view supertype in its original form
2830               .noneMatch(stype -> {
2831                 for (MethodSymbol sm1 : supertypeMethods1) {
2832                     if (!types.isSubtype(types.erasure(stype), types.erasure(sm1.owner.type)))
2833                         continue;
2834                     for (MethodSymbol sm2 : supertypeMethods2) {
2835                         if (!types.isSubtype(types.erasure(stype), types.erasure(sm2.owner.type)))
2836                             continue;
2837                         if (potentiallyAmbiguousOverload(stype, sm1, sm2))
2838                             return true;
2839                     }
2840                 }
2841                 return false;
2842             });
2843         };
2844     }
2845 
2846     /** Gather all of site's methods, including overridden methods, grouped and sorted by name,
2847      *  after applying the given filter.
2848      */
2849     <C extends Collection<MethodSymbol>> List<C> methodsGroupedByName(Type site,
2850             Predicate<Symbol> filter, Supplier<? extends C> groupMaker) {
2851         Iterable<Symbol> symbols = types.membersClosure(site, false).getSymbols(filter, RECURSIVE);
2852         return StreamSupport.stream(symbols.spliterator(), false)
2853           .map(MethodSymbol.class::cast)
2854           .collect(Collectors.groupingBy(m -> m.name, Collectors.toCollection(groupMaker)))
2855           .entrySet()
2856           .stream()
2857           .sorted(Comparator.comparing(e -> e.getKey().toString()))
2858           .map(Map.Entry::getValue)
2859           .collect(List.collector());
2860     }
2861 
2862     /** Compare elements in a list pair-wise in order to remove some of them.
2863      *  @param list mutable list of items
2864      *  @param comparer returns flag bit(s) to remove FIRST and/or SECOND
2865      */
2866     <T> void compareAndRemove(java.util.List<T> list, ToIntBiFunction<? super T, ? super T> comparer) {
2867         for (int index1 = 0; index1 < list.size() - 1; index1++) {
2868             T item1 = list.get(index1);
2869             for (int index2 = index1 + 1; index2 < list.size(); index2++) {
2870                 T item2 = list.get(index2);
2871                 int flags = comparer.applyAsInt(item1, item2);
2872                 if ((flags & SECOND) != 0)
2873                     list.remove(index2--);          // remove item2
2874                 if ((flags & FIRST) != 0) {
2875                     list.remove(index1--);          // remove item1
2876                     break;
2877                 }
2878             }
2879         }
2880     }
2881 
2882     /** Remove elements in a list that are preempted by some other element in the list.
2883      *  @param list mutable list of items
2884      *  @param preempts decides if one item preempts another, causing the second one to be removed
2885      */
2886     <T> void removePreempted(java.util.List<T> list, BiPredicate<? super T, ? super T> preempts) {
2887         compareAndRemove(list, (item1, item2) -> {
2888             int flags = 0;
2889             if (preempts.test(item1, item2))
2890                 flags |= SECOND;
2891             if (preempts.test(item2, item1))
2892                 flags |= FIRST;
2893             return flags;
2894         });
2895     }
2896 
2897     /** Filters method candidates for the "potentially ambiguous method" check */
2898     class PotentiallyAmbiguousFilter extends ClashFilter {
2899 
2900         PotentiallyAmbiguousFilter(Type site) {
2901             super(site);
2902         }
2903 
2904         @Override
2905         boolean shouldSkip(Symbol s) {
2906             return s.owner.type.tsym == syms.objectType.tsym || super.shouldSkip(s);
2907         }
2908     }
2909 
2910     /**
2911       * Report warnings for potentially ambiguous method declarations. Two declarations
2912       * are potentially ambiguous if they feature two unrelated functional interface
2913       * in same argument position (in which case, a call site passing an implicit
2914       * lambda would be ambiguous). This assumes they already have the same name.
2915       */
2916     boolean potentiallyAmbiguousOverload(Type site, MethodSymbol msym1, MethodSymbol msym2) {
2917         Assert.check(msym1.name == msym2.name);
2918         if (msym1 == msym2)
2919             return false;
2920         Type mt1 = types.memberType(site, msym1);
2921         Type mt2 = types.memberType(site, msym2);
2922         //if both generic methods, adjust type variables
2923         if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL) &&
2924                 types.hasSameBounds((ForAll)mt1, (ForAll)mt2)) {
2925             mt2 = types.subst(mt2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars);
2926         }
2927         //expand varargs methods if needed
2928         int maxLength = Math.max(mt1.getParameterTypes().length(), mt2.getParameterTypes().length());
2929         List<Type> args1 = rs.adjustArgs(mt1.getParameterTypes(), msym1, maxLength, true);
2930         List<Type> args2 = rs.adjustArgs(mt2.getParameterTypes(), msym2, maxLength, true);
2931         //if arities don't match, exit
2932         if (args1.length() != args2.length())
2933             return false;
2934         boolean potentiallyAmbiguous = false;
2935         while (args1.nonEmpty() && args2.nonEmpty()) {
2936             Type s = args1.head;
2937             Type t = args2.head;
2938             if (!types.isSubtype(t, s) && !types.isSubtype(s, t)) {
2939                 if (types.isFunctionalInterface(s) && types.isFunctionalInterface(t) &&
2940                         types.findDescriptorType(s).getParameterTypes().length() > 0 &&
2941                         types.findDescriptorType(s).getParameterTypes().length() ==
2942                         types.findDescriptorType(t).getParameterTypes().length()) {
2943                     potentiallyAmbiguous = true;
2944                 } else {
2945                     return false;
2946                 }
2947             }
2948             args1 = args1.tail;
2949             args2 = args2.tail;
2950         }
2951         return potentiallyAmbiguous;
2952     }
2953 
2954     // Apply special flag "-XDwarnOnAccessToMembers" which turns on just this particular warning for all types of access
2955     void checkAccessFromSerializableElement(final JCTree tree, boolean isLambda) {
2956         if (warnOnAnyAccessToMembers || isLambda)
2957             checkAccessFromSerializableElementInner(tree, isLambda);
2958     }
2959 
2960     private void checkAccessFromSerializableElementInner(final JCTree tree, boolean isLambda) {
2961         Symbol sym = TreeInfo.symbol(tree);
2962         if (!sym.kind.matches(KindSelector.VAL_MTH)) {
2963             return;
2964         }
2965 
2966         if (sym.kind == VAR) {
2967             if ((sym.flags() & PARAMETER) != 0 ||
2968                 sym.isDirectlyOrIndirectlyLocal() ||
2969                 sym.name == names._this ||
2970                 sym.name == names._super) {
2971                 return;
2972             }
2973         }
2974 
2975         if (!types.isSubtype(sym.owner.type, syms.serializableType) && isEffectivelyNonPublic(sym)) {
2976             DiagnosticFlag flag = warnOnAnyAccessToMembers ? DiagnosticFlag.DEFAULT_ENABLED : null;
2977             if (isLambda) {
2978                 if (belongsToRestrictedPackage(sym)) {
2979                     log.warning(flag, tree.pos(), LintWarnings.AccessToMemberFromSerializableLambda(sym));
2980                 }
2981             } else {
2982                 log.warning(flag, tree.pos(), LintWarnings.AccessToMemberFromSerializableElement(sym));
2983             }
2984         }
2985     }
2986 
2987     private boolean isEffectivelyNonPublic(Symbol sym) {
2988         if (sym.packge() == syms.rootPackage) {
2989             return false;
2990         }
2991 
2992         while (sym.kind != PCK) {
2993             if ((sym.flags() & PUBLIC) == 0) {
2994                 return true;
2995             }
2996             sym = sym.owner;
2997         }
2998         return false;
2999     }
3000 
3001     private boolean belongsToRestrictedPackage(Symbol sym) {
3002         String fullName = sym.packge().fullname.toString();
3003         return fullName.startsWith("java.") ||
3004                 fullName.startsWith("javax.") ||
3005                 fullName.startsWith("sun.") ||
3006                 fullName.contains(".internal.");
3007     }
3008 
3009     /** Check that class c does not implement directly or indirectly
3010      *  the same parameterized interface with two different argument lists.
3011      *  @param pos          Position to be used for error reporting.
3012      *  @param type         The type whose interfaces are checked.
3013      */
3014     void checkClassBounds(DiagnosticPosition pos, Type type) {
3015         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
3016     }
3017 //where
3018         /** Enter all interfaces of type `type' into the hash table `seensofar'
3019          *  with their class symbol as key and their type as value. Make
3020          *  sure no class is entered with two different types.
3021          */
3022         void checkClassBounds(DiagnosticPosition pos,
3023                               Map<TypeSymbol,Type> seensofar,
3024                               Type type) {
3025             if (type.isErroneous()) return;
3026             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
3027                 Type it = l.head;
3028                 if (type.hasTag(CLASS) && !it.hasTag(CLASS)) continue; // JLS 8.1.5
3029 
3030                 Type oldit = seensofar.put(it.tsym, it);
3031                 if (oldit != null) {
3032                     List<Type> oldparams = oldit.allparams();
3033                     List<Type> newparams = it.allparams();
3034                     if (!types.containsTypeEquivalent(oldparams, newparams))
3035                         log.error(pos,
3036                                   Errors.CantInheritDiffArg(it.tsym,
3037                                                             Type.toString(oldparams),
3038                                                             Type.toString(newparams)));
3039                 }
3040                 checkClassBounds(pos, seensofar, it);
3041             }
3042             Type st = types.supertype(type);
3043             if (type.hasTag(CLASS) && !st.hasTag(CLASS)) return; // JLS 8.1.4
3044             if (st != Type.noType) checkClassBounds(pos, seensofar, st);
3045         }
3046 
3047     /** Enter interface into into set.
3048      *  If it existed already, issue a "repeated interface" error.
3049      */
3050     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Symbol> its) {
3051         if (its.contains(it.tsym))
3052             log.error(pos, Errors.RepeatedInterface);
3053         else {
3054             its.add(it.tsym);
3055         }
3056     }
3057 
3058 /* *************************************************************************
3059  * Check annotations
3060  **************************************************************************/
3061 
3062     /**
3063      * Recursively validate annotations values
3064      */
3065     void validateAnnotationTree(JCTree tree) {
3066         class AnnotationValidator extends TreeScanner {
3067             @Override
3068             public void visitAnnotation(JCAnnotation tree) {
3069                 if (!tree.type.isErroneous() && tree.type.tsym.isAnnotationType()) {
3070                     super.visitAnnotation(tree);
3071                     validateAnnotation(tree);
3072                 }
3073             }
3074         }
3075         tree.accept(new AnnotationValidator());
3076     }
3077 
3078     /**
3079      *  {@literal
3080      *  Annotation types are restricted to primitives, String, an
3081      *  enum, an annotation, Class, Class<?>, Class<? extends
3082      *  Anything>, arrays of the preceding.
3083      *  }
3084      */
3085     void validateAnnotationType(JCTree restype) {
3086         // restype may be null if an error occurred, so don't bother validating it
3087         if (restype != null) {
3088             validateAnnotationType(restype.pos(), restype.type);
3089         }
3090     }
3091 
3092     void validateAnnotationType(DiagnosticPosition pos, Type type) {
3093         if (type.isPrimitive()) return;
3094         if (types.isSameType(type, syms.stringType)) return;
3095         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
3096         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
3097         if (types.cvarLowerBound(type).tsym == syms.classType.tsym) return;
3098         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
3099             validateAnnotationType(pos, types.elemtype(type));
3100             return;
3101         }
3102         log.error(pos, Errors.InvalidAnnotationMemberType);
3103     }
3104 
3105     /**
3106      * "It is also a compile-time error if any method declared in an
3107      * annotation type has a signature that is override-equivalent to
3108      * that of any public or protected method declared in class Object
3109      * or in the interface annotation.Annotation."
3110      *
3111      * @jls 9.6 Annotation Types
3112      */
3113     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
3114         for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
3115             Scope s = sup.tsym.members();
3116             for (Symbol sym : s.getSymbolsByName(m.name)) {
3117                 if (sym.kind == MTH &&
3118                     (sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
3119                     types.overrideEquivalent(m.type, sym.type))
3120                     log.error(pos, Errors.IntfAnnotationMemberClash(sym, sup));
3121             }
3122         }
3123     }
3124 
3125     /** Check the annotations of a symbol.
3126      */
3127     public void validateAnnotations(List<JCAnnotation> annotations, JCTree declarationTree, Symbol s) {
3128         for (JCAnnotation a : annotations)
3129             validateAnnotation(a, declarationTree, s);
3130     }
3131 
3132     /** Check the type annotations.
3133      */
3134     public void validateTypeAnnotations(List<JCAnnotation> annotations, Symbol s, boolean isTypeParameter) {
3135         for (JCAnnotation a : annotations)
3136             validateTypeAnnotation(a, s, isTypeParameter);
3137     }
3138 
3139     /** Check an annotation of a symbol.
3140      */
3141     private void validateAnnotation(JCAnnotation a, JCTree declarationTree, Symbol s) {
3142         /** NOTE: if annotation processors are present, annotation processing rounds can happen after this method,
3143          *  this can impact in particular records for which annotations are forcibly propagated.
3144          */
3145         validateAnnotationTree(a);
3146         boolean isRecordMember = ((s.flags_field & RECORD) != 0 || s.enclClass() != null && s.enclClass().isRecord());
3147 
3148         boolean isRecordField = (s.flags_field & RECORD) != 0 &&
3149                 declarationTree.hasTag(VARDEF) &&
3150                 s.owner.kind == TYP;
3151 
3152         if (isRecordField) {
3153             // first we need to check if the annotation is applicable to records
3154             Name[] targets = getTargetNames(a);
3155             boolean appliesToRecords = false;
3156             for (Name target : targets) {
3157                 appliesToRecords =
3158                                 target == names.FIELD ||
3159                                 target == names.PARAMETER ||
3160                                 target == names.METHOD ||
3161                                 target == names.TYPE_USE ||
3162                                 target == names.RECORD_COMPONENT;
3163                 if (appliesToRecords) {
3164                     break;
3165                 }
3166             }
3167             if (!appliesToRecords) {
3168                 log.error(a.pos(), Errors.AnnotationTypeNotApplicable);
3169             } else {
3170                 /* lets now find the annotations in the field that are targeted to record components and append them to
3171                  * the corresponding record component
3172                  */
3173                 ClassSymbol recordClass = (ClassSymbol) s.owner;
3174                 RecordComponent rc = recordClass.getRecordComponent((VarSymbol)s);
3175                 SymbolMetadata metadata = rc.getMetadata();
3176                 if (metadata == null || metadata.isEmpty()) {
3177                     /* if not is empty then we have already been here, which is the case if multiple annotations are applied
3178                      * to the record component declaration
3179                      */
3180                     rc.appendAttributes(s.getRawAttributes().stream().filter(anno ->
3181                             Arrays.stream(getTargetNames(anno.type.tsym)).anyMatch(name -> name == names.RECORD_COMPONENT)
3182                     ).collect(List.collector()));
3183 
3184                     JCVariableDecl fieldAST = (JCVariableDecl) declarationTree;
3185                     for (JCAnnotation fieldAnnot : fieldAST.mods.annotations) {
3186                         for (JCAnnotation rcAnnot : rc.declarationFor().mods.annotations) {
3187                             if (rcAnnot.pos == fieldAnnot.pos) {
3188                                 rcAnnot.setType(fieldAnnot.type);
3189                                 break;
3190                             }
3191                         }
3192                     }
3193 
3194                     /* At this point, we used to carry over any type annotations from the VARDEF to the record component, but
3195                      * that is problematic, since we get here only when *some* annotation is applied to the SE5 (declaration)
3196                      * annotation location, inadvertently failing to carry over the type annotations when the VarDef has no
3197                      * annotations in the SE5 annotation location.
3198                      *
3199                      * Now type annotations are assigned to record components in a method that would execute irrespective of
3200                      * whether there are SE5 annotations on a VarDef viz com.sun.tools.javac.code.TypeAnnotations.TypeAnnotationPositions.visitVarDef
3201                      */
3202                 }
3203             }
3204         }
3205 
3206         /* the section below is tricky. Annotations applied to record components are propagated to the corresponding
3207          * record member so if an annotation has target: FIELD, it is propagated to the corresponding FIELD, if it has
3208          * target METHOD, it is propagated to the accessor and so on. But at the moment when method members are generated
3209          * there is no enough information to propagate only the right annotations. So all the annotations are propagated
3210          * to all the possible locations.
3211          *
3212          * At this point we need to remove all the annotations that are not in place before going on with the annotation
3213          * party. On top of the above there is the issue that there is no AST representing record components, just symbols
3214          * so the corresponding field has been holding all the annotations and it's metadata has been modified as if it
3215          * was both a field and a record component.
3216          *
3217          * So there are two places where we need to trim annotations from: the metadata of the symbol and / or the modifiers
3218          * in the AST. Whatever is in the metadata will be written to the class file, whatever is in the modifiers could
3219          * be see by annotation processors.
3220          *
3221          * The metadata contains both type annotations and declaration annotations. At this point of the game we don't
3222          * need to care about type annotations, they are all in the right place. But we could need to remove declaration
3223          * annotations. So for declaration annotations if they are not applicable to the record member, excluding type
3224          * annotations which are already correct, then we will remove it. For the AST modifiers if the annotation is not
3225          * applicable either as type annotation and or declaration annotation, only in that case it will be removed.
3226          *
3227          * So it could be that annotation is removed as a declaration annotation but it is kept in the AST modifier for
3228          * further inspection by annotation processors.
3229          *
3230          * For example:
3231          *
3232          *     import java.lang.annotation.*;
3233          *
3234          *     @Target({ElementType.TYPE_USE, ElementType.RECORD_COMPONENT})
3235          *     @Retention(RetentionPolicy.RUNTIME)
3236          *     @interface Anno { }
3237          *
3238          *     record R(@Anno String s) {}
3239          *
3240          * at this point we will have for the case of the generated field:
3241          *   - @Anno in the modifier
3242          *   - @Anno as a type annotation
3243          *   - @Anno as a declaration annotation
3244          *
3245          * the last one should be removed because the annotation has not FIELD as target but it was applied as a
3246          * declaration annotation because the field was being treated both as a field and as a record component
3247          * as we have already copied the annotations to the record component, now the field doesn't need to hold
3248          * annotations that are not intended for it anymore. Still @Anno has to be kept in the AST's modifiers as it
3249          * is applicable as a type annotation to the type of the field.
3250          */
3251 
3252         if (a.type.tsym.isAnnotationType()) {
3253             Optional<Set<Name>> applicableTargetsOp = getApplicableTargets(a, s);
3254             if (!applicableTargetsOp.isEmpty()) {
3255                 Set<Name> applicableTargets = applicableTargetsOp.get();
3256                 boolean notApplicableOrIsTypeUseOnly = applicableTargets.isEmpty() ||
3257                         applicableTargets.size() == 1 && applicableTargets.contains(names.TYPE_USE);
3258                 boolean isCompGeneratedRecordElement = isRecordMember && (s.flags_field & Flags.GENERATED_MEMBER) != 0;
3259                 boolean isCompRecordElementWithNonApplicableDeclAnno = isCompGeneratedRecordElement && notApplicableOrIsTypeUseOnly;
3260 
3261                 if (applicableTargets.isEmpty() || isCompRecordElementWithNonApplicableDeclAnno) {
3262                     if (isCompRecordElementWithNonApplicableDeclAnno) {
3263                             /* so we have found an annotation that is not applicable to a record member that was generated by the
3264                              * compiler. This was intentionally done at TypeEnter, now is the moment strip away the annotations
3265                              * that are not applicable to the given record member
3266                              */
3267                         JCModifiers modifiers = TreeInfo.getModifiers(declarationTree);
3268                             /* lets first remove the annotation from the modifier if it is not applicable, we have to check again as
3269                              * it could be a type annotation
3270                              */
3271                         if (modifiers != null && applicableTargets.isEmpty()) {
3272                             ListBuffer<JCAnnotation> newAnnotations = new ListBuffer<>();
3273                             for (JCAnnotation anno : modifiers.annotations) {
3274                                 if (anno != a) {
3275                                     newAnnotations.add(anno);
3276                                 }
3277                             }
3278                             modifiers.annotations = newAnnotations.toList();
3279                         }
3280                         // now lets remove it from the symbol
3281                         s.getMetadata().removeDeclarationMetadata(a.attribute);
3282                     } else {
3283                         log.error(a.pos(), Errors.AnnotationTypeNotApplicable);
3284                     }
3285                 }
3286                 /* if we are seeing the @SafeVarargs annotation applied to a compiler generated accessor,
3287                  * then this is an error as we know that no compiler generated accessor will be a varargs
3288                  * method, better to fail asap
3289                  */
3290                 if (isCompGeneratedRecordElement && !isRecordField && a.type.tsym == syms.trustMeType.tsym && declarationTree.hasTag(METHODDEF)) {
3291                     log.error(a.pos(), Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym, Fragments.VarargsTrustmeOnNonVarargsAccessor(s)));
3292                 }
3293             }
3294         }
3295 
3296         if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
3297             if (s.kind != TYP) {
3298                 log.error(a.pos(), Errors.BadFunctionalIntfAnno);
3299             } else if (!s.isInterface() || (s.flags() & ANNOTATION) != 0) {
3300                 log.error(a.pos(), Errors.BadFunctionalIntfAnno1(Fragments.NotAFunctionalIntf(s)));
3301             }
3302         }
3303     }
3304 
3305     public void validateTypeAnnotation(JCAnnotation a, Symbol s, boolean isTypeParameter) {
3306         Assert.checkNonNull(a.type);
3307         // we just want to validate that the anotation doesn't have any wrong target
3308         if (s != null) getApplicableTargets(a, s);
3309         validateAnnotationTree(a);
3310 
3311         if (a.hasTag(TYPE_ANNOTATION) &&
3312                 !a.annotationType.type.isErroneous() &&
3313                 !isTypeAnnotation(a, isTypeParameter)) {
3314             log.error(a.pos(), Errors.AnnotationTypeNotApplicableToType(a.type));
3315         }
3316     }
3317 
3318     /**
3319      * Validate the proposed container 'repeatable' on the
3320      * annotation type symbol 's'. Report errors at position
3321      * 'pos'.
3322      *
3323      * @param s The (annotation)type declaration annotated with a @Repeatable
3324      * @param repeatable the @Repeatable on 's'
3325      * @param pos where to report errors
3326      */
3327     public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
3328         Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
3329 
3330         Type t = null;
3331         List<Pair<MethodSymbol,Attribute>> l = repeatable.values;
3332         if (!l.isEmpty()) {
3333             Assert.check(l.head.fst.name == names.value);
3334             if (l.head.snd instanceof Attribute.Class) {
3335                 t = ((Attribute.Class)l.head.snd).getValue();
3336             }
3337         }
3338 
3339         if (t == null) {
3340             // errors should already have been reported during Annotate
3341             return;
3342         }
3343 
3344         validateValue(t.tsym, s, pos);
3345         validateRetention(t.tsym, s, pos);
3346         validateDocumented(t.tsym, s, pos);
3347         validateInherited(t.tsym, s, pos);
3348         validateTarget(t.tsym, s, pos);
3349         validateDefault(t.tsym, pos);
3350     }
3351 
3352     private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
3353         Symbol sym = container.members().findFirst(names.value);
3354         if (sym != null && sym.kind == MTH) {
3355             MethodSymbol m = (MethodSymbol) sym;
3356             Type ret = m.getReturnType();
3357             if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
3358                 log.error(pos,
3359                           Errors.InvalidRepeatableAnnotationValueReturn(container,
3360                                                                         ret,
3361                                                                         types.makeArrayType(contained.type)));
3362             }
3363         } else {
3364             log.error(pos, Errors.InvalidRepeatableAnnotationNoValue(container));
3365         }
3366     }
3367 
3368     private void validateRetention(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
3369         Attribute.RetentionPolicy containerRetention = types.getRetention(container);
3370         Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
3371 
3372         boolean error = false;
3373         switch (containedRetention) {
3374         case RUNTIME:
3375             if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
3376                 error = true;
3377             }
3378             break;
3379         case CLASS:
3380             if (containerRetention == Attribute.RetentionPolicy.SOURCE)  {
3381                 error = true;
3382             }
3383         }
3384         if (error ) {
3385             log.error(pos,
3386                       Errors.InvalidRepeatableAnnotationRetention(container,
3387                                                                   containerRetention.name(),
3388                                                                   contained,
3389                                                                   containedRetention.name()));
3390         }
3391     }
3392 
3393     private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
3394         if (contained.attribute(syms.documentedType.tsym) != null) {
3395             if (container.attribute(syms.documentedType.tsym) == null) {
3396                 log.error(pos, Errors.InvalidRepeatableAnnotationNotDocumented(container, contained));
3397             }
3398         }
3399     }
3400 
3401     private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
3402         if (contained.attribute(syms.inheritedType.tsym) != null) {
3403             if (container.attribute(syms.inheritedType.tsym) == null) {
3404                 log.error(pos, Errors.InvalidRepeatableAnnotationNotInherited(container, contained));
3405             }
3406         }
3407     }
3408 
3409     private void validateTarget(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
3410         // The set of targets the container is applicable to must be a subset
3411         // (with respect to annotation target semantics) of the set of targets
3412         // the contained is applicable to. The target sets may be implicit or
3413         // explicit.
3414 
3415         Set<Name> containerTargets;
3416         Attribute.Array containerTarget = getAttributeTargetAttribute(container);
3417         if (containerTarget == null) {
3418             containerTargets = getDefaultTargetSet();
3419         } else {
3420             containerTargets = new HashSet<>();
3421             for (Attribute app : containerTarget.values) {
3422                 if (!(app instanceof Attribute.Enum attributeEnum)) {
3423                     continue; // recovery
3424                 }
3425                 containerTargets.add(attributeEnum.value.name);
3426             }
3427         }
3428 
3429         Set<Name> containedTargets;
3430         Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
3431         if (containedTarget == null) {
3432             containedTargets = getDefaultTargetSet();
3433         } else {
3434             containedTargets = new HashSet<>();
3435             for (Attribute app : containedTarget.values) {
3436                 if (!(app instanceof Attribute.Enum attributeEnum)) {
3437                     continue; // recovery
3438                 }
3439                 containedTargets.add(attributeEnum.value.name);
3440             }
3441         }
3442 
3443         if (!isTargetSubsetOf(containerTargets, containedTargets)) {
3444             log.error(pos, Errors.InvalidRepeatableAnnotationIncompatibleTarget(container, contained));
3445         }
3446     }
3447 
3448     /* get a set of names for the default target */
3449     private Set<Name> getDefaultTargetSet() {
3450         if (defaultTargets == null) {
3451             defaultTargets = Set.of(defaultTargetMetaInfo());
3452         }
3453 
3454         return defaultTargets;
3455     }
3456     private Set<Name> defaultTargets;
3457 
3458 
3459     /** Checks that s is a subset of t, with respect to ElementType
3460      * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE},
3461      * and {TYPE_USE} covers the set {ANNOTATION_TYPE, TYPE, TYPE_USE,
3462      * TYPE_PARAMETER}.
3463      */
3464     private boolean isTargetSubsetOf(Set<Name> s, Set<Name> t) {
3465         // Check that all elements in s are present in t
3466         for (Name n2 : s) {
3467             boolean currentElementOk = false;
3468             for (Name n1 : t) {
3469                 if (n1 == n2) {
3470                     currentElementOk = true;
3471                     break;
3472                 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
3473                     currentElementOk = true;
3474                     break;
3475                 } else if (n1 == names.TYPE_USE &&
3476                         (n2 == names.TYPE ||
3477                          n2 == names.ANNOTATION_TYPE ||
3478                          n2 == names.TYPE_PARAMETER)) {
3479                     currentElementOk = true;
3480                     break;
3481                 }
3482             }
3483             if (!currentElementOk)
3484                 return false;
3485         }
3486         return true;
3487     }
3488 
3489     private void validateDefault(Symbol container, DiagnosticPosition pos) {
3490         // validate that all other elements of containing type has defaults
3491         Scope scope = container.members();
3492         for(Symbol elm : scope.getSymbols()) {
3493             if (elm.name != names.value &&
3494                 elm.kind == MTH &&
3495                 ((MethodSymbol)elm).defaultValue == null) {
3496                 log.error(pos,
3497                           Errors.InvalidRepeatableAnnotationElemNondefault(container, elm));
3498             }
3499         }
3500     }
3501 
3502     /** Is s a method symbol that overrides a method in a superclass? */
3503     boolean isOverrider(Symbol s) {
3504         if (s.kind != MTH || s.isStatic())
3505             return false;
3506         MethodSymbol m = (MethodSymbol)s;
3507         TypeSymbol owner = (TypeSymbol)m.owner;
3508         for (Type sup : types.closure(owner.type)) {
3509             if (sup == owner.type)
3510                 continue; // skip "this"
3511             Scope scope = sup.tsym.members();
3512             for (Symbol sym : scope.getSymbolsByName(m.name)) {
3513                 if (!sym.isStatic() && m.overrides(sym, owner, types, true))
3514                     return true;
3515             }
3516         }
3517         return false;
3518     }
3519 
3520     /** Is the annotation applicable to types? */
3521     protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
3522         List<Attribute> targets = typeAnnotations.annotationTargets(a.annotationType.type.tsym);
3523         return (targets == null) ?
3524                 (Feature.NO_TARGET_ANNOTATION_APPLICABILITY.allowedInSource(source) && isTypeParameter) :
3525                 targets.stream()
3526                         .anyMatch(attr -> isTypeAnnotation(attr, isTypeParameter));
3527     }
3528     //where
3529         boolean isTypeAnnotation(Attribute a, boolean isTypeParameter) {
3530             Attribute.Enum e = (Attribute.Enum)a;
3531             return (e.value.name == names.TYPE_USE ||
3532                     (isTypeParameter && e.value.name == names.TYPE_PARAMETER));
3533         }
3534 
3535     /** Is the annotation applicable to the symbol? */
3536     Name[] getTargetNames(JCAnnotation a) {
3537         return getTargetNames(a.annotationType.type.tsym);
3538     }
3539 
3540     public Name[] getTargetNames(TypeSymbol annoSym) {
3541         Attribute.Array arr = getAttributeTargetAttribute(annoSym);
3542         Name[] targets;
3543         if (arr == null) {
3544             targets = defaultTargetMetaInfo();
3545         } else {
3546             // TODO: can we optimize this?
3547             targets = new Name[arr.values.length];
3548             for (int i=0; i<arr.values.length; ++i) {
3549                 Attribute app = arr.values[i];
3550                 if (!(app instanceof Attribute.Enum attributeEnum)) {
3551                     return new Name[0];
3552                 }
3553                 targets[i] = attributeEnum.value.name;
3554             }
3555         }
3556         return targets;
3557     }
3558 
3559     boolean annotationApplicable(JCAnnotation a, Symbol s) {
3560         Optional<Set<Name>> targets = getApplicableTargets(a, s);
3561         /* the optional could be empty if the annotation is unknown in that case
3562          * we return that it is applicable and if it is erroneous that should imply
3563          * an error at the declaration site
3564          */
3565         return targets.isEmpty() || targets.isPresent() && !targets.get().isEmpty();
3566     }
3567 
3568     Optional<Set<Name>> getApplicableTargets(JCAnnotation a, Symbol s) {
3569         Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
3570         Name[] targets;
3571         Set<Name> applicableTargets = new HashSet<>();
3572 
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                     // recovery
3582                     return Optional.empty();
3583                 }
3584                 targets[i] = attributeEnum.value.name;
3585             }
3586         }
3587         for (Name target : targets) {
3588             if (target == names.TYPE) {
3589                 if (s.kind == TYP)
3590                     applicableTargets.add(names.TYPE);
3591             } else if (target == names.FIELD) {
3592                 if (s.kind == VAR && s.owner.kind != MTH)
3593                     applicableTargets.add(names.FIELD);
3594             } else if (target == names.RECORD_COMPONENT) {
3595                 if (s.getKind() == ElementKind.RECORD_COMPONENT) {
3596                     applicableTargets.add(names.RECORD_COMPONENT);
3597                 }
3598             } else if (target == names.METHOD) {
3599                 if (s.kind == MTH && !s.isConstructor())
3600                     applicableTargets.add(names.METHOD);
3601             } else if (target == names.PARAMETER) {
3602                 if (s.kind == VAR &&
3603                     (s.owner.kind == MTH && (s.flags() & PARAMETER) != 0)) {
3604                     applicableTargets.add(names.PARAMETER);
3605                 }
3606             } else if (target == names.CONSTRUCTOR) {
3607                 if (s.kind == MTH && s.isConstructor())
3608                     applicableTargets.add(names.CONSTRUCTOR);
3609             } else if (target == names.LOCAL_VARIABLE) {
3610                 if (s.kind == VAR && s.owner.kind == MTH &&
3611                       (s.flags() & PARAMETER) == 0) {
3612                     applicableTargets.add(names.LOCAL_VARIABLE);
3613                 }
3614             } else if (target == names.ANNOTATION_TYPE) {
3615                 if (s.kind == TYP && (s.flags() & ANNOTATION) != 0) {
3616                     applicableTargets.add(names.ANNOTATION_TYPE);
3617                 }
3618             } else if (target == names.PACKAGE) {
3619                 if (s.kind == PCK)
3620                     applicableTargets.add(names.PACKAGE);
3621             } else if (target == names.TYPE_USE) {
3622                 if (s.kind == VAR &&
3623                     (s.flags() & Flags.VAR_VARIABLE) != 0 &&
3624                     (!Feature.TYPE_ANNOTATIONS_ON_VAR_LAMBDA_PARAMETER.allowedInSource(source) ||
3625                      ((s.flags() & Flags.LAMBDA_PARAMETER) == 0))) {
3626                     //cannot type annotate implicitly typed locals
3627                     continue;
3628                 } else if (s.kind == TYP || s.kind == VAR ||
3629                         (s.kind == MTH && !s.isConstructor() &&
3630                                 !s.type.getReturnType().hasTag(VOID)) ||
3631                         (s.kind == MTH && s.isConstructor())) {
3632                     applicableTargets.add(names.TYPE_USE);
3633                 }
3634             } else if (target == names.TYPE_PARAMETER) {
3635                 if (s.kind == TYP && s.type.hasTag(TYPEVAR))
3636                     applicableTargets.add(names.TYPE_PARAMETER);
3637             } else if (target == names.MODULE) {
3638                 if (s.kind == MDL)
3639                     applicableTargets.add(names.MODULE);
3640             } else {
3641                 log.error(a, Errors.AnnotationUnrecognizedAttributeName(a.type, target));
3642                 return Optional.empty(); // Unknown ElementType
3643             }
3644         }
3645         return Optional.of(applicableTargets);
3646     }
3647 
3648     Attribute.Array getAttributeTargetAttribute(TypeSymbol s) {
3649         Attribute.Compound atTarget = s.getAnnotationTypeMetadata().getTarget();
3650         if (atTarget == null) return null; // ok, is applicable
3651         Attribute atValue = atTarget.member(names.value);
3652         return (atValue instanceof Attribute.Array attributeArray) ? attributeArray : null;
3653     }
3654 
3655     private Name[] dfltTargetMeta;
3656     private Name[] defaultTargetMetaInfo() {
3657         if (dfltTargetMeta == null) {
3658             ArrayList<Name> defaultTargets = new ArrayList<>();
3659             defaultTargets.add(names.PACKAGE);
3660             defaultTargets.add(names.TYPE);
3661             defaultTargets.add(names.FIELD);
3662             defaultTargets.add(names.METHOD);
3663             defaultTargets.add(names.CONSTRUCTOR);
3664             defaultTargets.add(names.ANNOTATION_TYPE);
3665             defaultTargets.add(names.LOCAL_VARIABLE);
3666             defaultTargets.add(names.PARAMETER);
3667             if (allowRecords) {
3668               defaultTargets.add(names.RECORD_COMPONENT);
3669             }
3670             if (allowModules) {
3671               defaultTargets.add(names.MODULE);
3672             }
3673             dfltTargetMeta = defaultTargets.toArray(new Name[0]);
3674         }
3675         return dfltTargetMeta;
3676     }
3677 
3678     /** Check an annotation value.
3679      *
3680      * @param a The annotation tree to check
3681      * @return true if this annotation tree is valid, otherwise false
3682      */
3683     public boolean validateAnnotationDeferErrors(JCAnnotation a) {
3684         boolean res = false;
3685         final Log.DiagnosticHandler diagHandler = log.new DiscardDiagnosticHandler();
3686         try {
3687             res = validateAnnotation(a);
3688         } finally {
3689             log.popDiagnosticHandler(diagHandler);
3690         }
3691         return res;
3692     }
3693 
3694     private boolean validateAnnotation(JCAnnotation a) {
3695         boolean isValid = true;
3696         AnnotationTypeMetadata metadata = a.annotationType.type.tsym.getAnnotationTypeMetadata();
3697 
3698         // collect an inventory of the annotation elements
3699         Set<MethodSymbol> elements = metadata.getAnnotationElements();
3700 
3701         // remove the ones that are assigned values
3702         for (JCTree arg : a.args) {
3703             if (!arg.hasTag(ASSIGN)) continue; // recovery
3704             JCAssign assign = (JCAssign)arg;
3705             Symbol m = TreeInfo.symbol(assign.lhs);
3706             if (m == null || m.type.isErroneous()) continue;
3707             if (!elements.remove(m)) {
3708                 isValid = false;
3709                 log.error(assign.lhs.pos(),
3710                           Errors.DuplicateAnnotationMemberValue(m.name, a.type));
3711             }
3712         }
3713 
3714         // all the remaining ones better have default values
3715         List<Name> missingDefaults = List.nil();
3716         Set<MethodSymbol> membersWithDefault = metadata.getAnnotationElementsWithDefault();
3717         for (MethodSymbol m : elements) {
3718             if (m.type.isErroneous())
3719                 continue;
3720 
3721             if (!membersWithDefault.contains(m))
3722                 missingDefaults = missingDefaults.append(m.name);
3723         }
3724         missingDefaults = missingDefaults.reverse();
3725         if (missingDefaults.nonEmpty()) {
3726             isValid = false;
3727             Error errorKey = (missingDefaults.size() > 1)
3728                     ? Errors.AnnotationMissingDefaultValue1(a.type, missingDefaults)
3729                     : Errors.AnnotationMissingDefaultValue(a.type, missingDefaults);
3730             log.error(a.pos(), errorKey);
3731         }
3732 
3733         return isValid && validateTargetAnnotationValue(a);
3734     }
3735 
3736     /* Validate the special java.lang.annotation.Target annotation */
3737     boolean validateTargetAnnotationValue(JCAnnotation a) {
3738         // special case: java.lang.annotation.Target must not have
3739         // repeated values in its value member
3740         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
3741                 a.args.tail == null)
3742             return true;
3743 
3744         boolean isValid = true;
3745         if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
3746         JCAssign assign = (JCAssign) a.args.head;
3747         Symbol m = TreeInfo.symbol(assign.lhs);
3748         if (m.name != names.value) return false;
3749         JCTree rhs = assign.rhs;
3750         if (!rhs.hasTag(NEWARRAY)) return false;
3751         JCNewArray na = (JCNewArray) rhs;
3752         Set<Symbol> targets = new HashSet<>();
3753         for (JCTree elem : na.elems) {
3754             if (!targets.add(TreeInfo.symbol(elem))) {
3755                 isValid = false;
3756                 log.error(elem.pos(), Errors.RepeatedAnnotationTarget);
3757             }
3758         }
3759         return isValid;
3760     }
3761 
3762     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
3763         if (lint.isEnabled(LintCategory.DEP_ANN) && s.isDeprecatableViaAnnotation() &&
3764             (s.flags() & DEPRECATED) != 0 &&
3765             !syms.deprecatedType.isErroneous() &&
3766             s.attribute(syms.deprecatedType.tsym) == null) {
3767             log.warning(pos, LintWarnings.MissingDeprecatedAnnotation);
3768         }
3769         // Note: @Deprecated has no effect on local variables, parameters and package decls.
3770         if (lint.isEnabled(LintCategory.DEPRECATION) && !s.isDeprecatableViaAnnotation() &&
3771             (s.flags() & RECORD) == 0 &&
3772             !syms.deprecatedType.isErroneous() &&
3773             s.attribute(syms.deprecatedType.tsym) != null) {
3774             log.warning(pos, LintWarnings.DeprecatedAnnotationHasNoEffect(Kinds.kindName(s)));
3775         }
3776     }
3777 
3778     void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
3779         checkDeprecated(() -> pos, other, s);
3780     }
3781 
3782     void checkDeprecated(Supplier<DiagnosticPosition> pos, final Symbol other, final Symbol s) {
3783         if (!importSuppression
3784                 && (s.isDeprecatedForRemoval() || s.isDeprecated() && !other.isDeprecated())
3785                 && (s.outermostClass() != other.outermostClass() || s.outermostClass() == null)
3786                 && s.kind != Kind.PCK) {
3787             warnDeprecated(pos.get(), s);
3788         }
3789     }
3790 
3791     void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
3792         if ((s.flags() & PROPRIETARY) != 0) {
3793             log.warning(pos, Warnings.SunProprietary(s));
3794         }
3795     }
3796 
3797     void checkProfile(final DiagnosticPosition pos, final Symbol s) {
3798         if (profile != Profile.DEFAULT && (s.flags() & NOT_IN_PROFILE) != 0) {
3799             log.error(pos, Errors.NotInProfile(s, profile));
3800         }
3801     }
3802 
3803     void checkPreview(DiagnosticPosition pos, Symbol other, Symbol s) {
3804         checkPreview(pos, other, Type.noType, s);
3805     }
3806 
3807     void checkPreview(DiagnosticPosition pos, Symbol other, Type site, Symbol s) {
3808         boolean sIsPreview;
3809         Symbol previewSymbol;
3810         if ((s.flags() & PREVIEW_API) != 0) {
3811             sIsPreview = true;
3812             previewSymbol=  s;
3813         } else if ((s.kind == Kind.MTH || s.kind == Kind.VAR) &&
3814                    site.tsym != null &&
3815                    (site.tsym.flags() & PREVIEW_API) == 0 &&
3816                    (s.owner.flags() & PREVIEW_API) != 0) {
3817             //calling a method, or using a field, whose owner is a preview, but
3818             //using a site that is not a preview. Also produce an error or warning:
3819             sIsPreview = true;
3820             previewSymbol = s.owner;
3821         } else {
3822             sIsPreview = false;
3823             previewSymbol = null;
3824         }
3825         if (sIsPreview && !preview.participatesInPreview(syms, other, s) && !disablePreviewCheck) {
3826             if ((previewSymbol.flags() & PREVIEW_REFLECTIVE) == 0) {
3827                 if (!preview.isEnabled()) {
3828                     log.error(pos, Errors.IsPreview(s));
3829                 } else {
3830                     preview.markUsesPreview(pos);
3831                     warnPreviewAPI(pos, LintWarnings.IsPreview(s));
3832                 }
3833             } else {
3834                 warnPreviewAPI(pos, LintWarnings.IsPreviewReflective(s));
3835             }
3836         }
3837         if (preview.declaredUsingPreviewFeature(s)) {
3838             if (preview.isEnabled()) {
3839                 //for preview disabled do presumably so not need to do anything?
3840                 //If "s" is compiled from source, then there was an error for it already;
3841                 //if "s" is from classfile, there already was an error for the classfile.
3842                 preview.markUsesPreview(pos);
3843                 warnPreviewAPI(pos, LintWarnings.DeclaredUsingPreview(kindName(s), s));
3844             }
3845         }
3846     }
3847 
3848     void checkRestricted(DiagnosticPosition pos, Symbol s) {
3849         if (s.kind == MTH && (s.flags() & RESTRICTED) != 0) {
3850             log.warning(pos, LintWarnings.RestrictedMethod(s.enclClass(), s));
3851         }
3852     }
3853 
3854 /* *************************************************************************
3855  * Check for recursive annotation elements.
3856  **************************************************************************/
3857 
3858     /** Check for cycles in the graph of annotation elements.
3859      */
3860     void checkNonCyclicElements(JCClassDecl tree) {
3861         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
3862         Assert.check((tree.sym.flags_field & LOCKED) == 0);
3863         try {
3864             tree.sym.flags_field |= LOCKED;
3865             for (JCTree def : tree.defs) {
3866                 if (!def.hasTag(METHODDEF)) continue;
3867                 JCMethodDecl meth = (JCMethodDecl)def;
3868                 checkAnnotationResType(meth.pos(), meth.restype.type);
3869             }
3870         } finally {
3871             tree.sym.flags_field &= ~LOCKED;
3872             tree.sym.flags_field |= ACYCLIC_ANN;
3873         }
3874     }
3875 
3876     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
3877         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
3878             return;
3879         if ((tsym.flags_field & LOCKED) != 0) {
3880             log.error(pos, Errors.CyclicAnnotationElement(tsym));
3881             return;
3882         }
3883         try {
3884             tsym.flags_field |= LOCKED;
3885             for (Symbol s : tsym.members().getSymbols(NON_RECURSIVE)) {
3886                 if (s.kind != MTH)
3887                     continue;
3888                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
3889             }
3890         } finally {
3891             tsym.flags_field &= ~LOCKED;
3892             tsym.flags_field |= ACYCLIC_ANN;
3893         }
3894     }
3895 
3896     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
3897         switch (type.getTag()) {
3898         case CLASS:
3899             if ((type.tsym.flags() & ANNOTATION) != 0)
3900                 checkNonCyclicElementsInternal(pos, type.tsym);
3901             break;
3902         case ARRAY:
3903             checkAnnotationResType(pos, types.elemtype(type));
3904             break;
3905         default:
3906             break; // int etc
3907         }
3908     }
3909 
3910 /* *************************************************************************
3911  * Check for cycles in the constructor call graph.
3912  **************************************************************************/
3913 
3914     /** Check for cycles in the graph of constructors calling other
3915      *  constructors.
3916      */
3917     void checkCyclicConstructors(JCClassDecl tree) {
3918         // use LinkedHashMap so we generate errors deterministically
3919         Map<Symbol,Symbol> callMap = new LinkedHashMap<>();
3920 
3921         // enter each constructor this-call into the map
3922         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3923             if (!TreeInfo.isConstructor(l.head))
3924                 continue;
3925             JCMethodDecl meth = (JCMethodDecl)l.head;
3926             JCMethodInvocation app = TreeInfo.findConstructorCall(meth);
3927             if (app != null && TreeInfo.name(app.meth) == names._this) {
3928                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
3929             } else {
3930                 meth.sym.flags_field |= ACYCLIC;
3931             }
3932         }
3933 
3934         // Check for cycles in the map
3935         Symbol[] ctors = new Symbol[0];
3936         ctors = callMap.keySet().toArray(ctors);
3937         for (Symbol caller : ctors) {
3938             checkCyclicConstructor(tree, caller, callMap);
3939         }
3940     }
3941 
3942     /** Look in the map to see if the given constructor is part of a
3943      *  call cycle.
3944      */
3945     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
3946                                         Map<Symbol,Symbol> callMap) {
3947         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
3948             if ((ctor.flags_field & LOCKED) != 0) {
3949                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree, false, t -> t.hasTag(IDENT)),
3950                           Errors.RecursiveCtorInvocation);
3951             } else {
3952                 ctor.flags_field |= LOCKED;
3953                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
3954                 ctor.flags_field &= ~LOCKED;
3955             }
3956             ctor.flags_field |= ACYCLIC;
3957         }
3958     }
3959 
3960 /* *************************************************************************
3961  * Verify the proper placement of super()/this() calls.
3962  *
3963  *    - super()/this() may only appear in constructors
3964  *    - There must be at most one super()/this() call per constructor
3965  *    - The super()/this() call, if any, must be a top-level statement in the
3966  *      constructor, i.e., not nested inside any other statement or block
3967  *    - There must be no return statements prior to the super()/this() call
3968  **************************************************************************/
3969 
3970     void checkSuperInitCalls(JCClassDecl tree) {
3971         new SuperThisChecker().check(tree);
3972     }
3973 
3974     private class SuperThisChecker extends TreeScanner {
3975 
3976         // Match this scan stack: 1=JCMethodDecl, 2=JCExpressionStatement, 3=JCMethodInvocation
3977         private static final int MATCH_SCAN_DEPTH = 3;
3978 
3979         private boolean constructor;        // is this method a constructor?
3980         private boolean firstStatement;     // at the first statement in method?
3981         private JCReturn earlyReturn;       // first return prior to the super()/init(), if any
3982         private Name initCall;              // whichever of "super" or "init" we've seen already
3983         private int scanDepth;              // current scan recursion depth in method body
3984 
3985         public void check(JCClassDecl classDef) {
3986             scan(classDef.defs);
3987         }
3988 
3989         @Override
3990         public void visitMethodDef(JCMethodDecl tree) {
3991             Assert.check(!constructor);
3992             Assert.check(earlyReturn == null);
3993             Assert.check(initCall == null);
3994             Assert.check(scanDepth == 1);
3995 
3996             // Initialize state for this method
3997             constructor = TreeInfo.isConstructor(tree);
3998             try {
3999 
4000                 // Scan method body
4001                 if (tree.body != null) {
4002                     firstStatement = true;
4003                     for (List<JCStatement> l = tree.body.stats; l.nonEmpty(); l = l.tail) {
4004                         scan(l.head);
4005                         firstStatement = false;
4006                     }
4007                 }
4008 
4009                 // Verify no 'return' seen prior to an explicit super()/this() call
4010                 if (constructor && earlyReturn != null && initCall != null)
4011                     log.error(earlyReturn.pos(), Errors.ReturnBeforeSuperclassInitialized);
4012             } finally {
4013                 firstStatement = false;
4014                 constructor = false;
4015                 earlyReturn = null;
4016                 initCall = null;
4017             }
4018         }
4019 
4020         @Override
4021         public void scan(JCTree tree) {
4022             scanDepth++;
4023             try {
4024                 super.scan(tree);
4025             } finally {
4026                 scanDepth--;
4027             }
4028         }
4029 
4030         @Override
4031         public void visitApply(JCMethodInvocation apply) {
4032             do {
4033 
4034                 // Is this a super() or this() call?
4035                 Name methodName = TreeInfo.name(apply.meth);
4036                 if (methodName != names._super && methodName != names._this)
4037                     break;
4038 
4039                 // super()/this() calls must only appear in a constructor
4040                 if (!constructor) {
4041                     log.error(apply.pos(), Errors.CallMustOnlyAppearInCtor);
4042                     break;
4043                 }
4044 
4045                 // super()/this() calls must be a top level statement
4046                 if (scanDepth != MATCH_SCAN_DEPTH) {
4047                     log.error(apply.pos(), Errors.CtorCallsNotAllowedHere);
4048                     break;
4049                 }
4050 
4051                 // super()/this() calls must not appear more than once
4052                 if (initCall != null) {
4053                     log.error(apply.pos(), Errors.RedundantSuperclassInit);
4054                     break;
4055                 }
4056 
4057                 // If super()/this() isn't first, require flexible constructors feature
4058                 if (!firstStatement)
4059                     preview.checkSourceLevel(apply.pos(), Feature.FLEXIBLE_CONSTRUCTORS);
4060 
4061                 // We found a legitimate super()/this() call; remember it
4062                 initCall = methodName;
4063             } while (false);
4064 
4065             // Proceed
4066             super.visitApply(apply);
4067         }
4068 
4069         @Override
4070         public void visitReturn(JCReturn tree) {
4071             if (constructor && initCall == null && earlyReturn == null)
4072                 earlyReturn = tree;             // we have seen a return but not (yet) a super()/this()
4073             super.visitReturn(tree);
4074         }
4075 
4076         @Override
4077         public void visitClassDef(JCClassDecl tree) {
4078             // don't descend any further
4079         }
4080 
4081         @Override
4082         public void visitLambda(JCLambda tree) {
4083             final boolean constructorPrev = constructor;
4084             final boolean firstStatementPrev = firstStatement;
4085             final JCReturn earlyReturnPrev = earlyReturn;
4086             final Name initCallPrev = initCall;
4087             final int scanDepthPrev = scanDepth;
4088             constructor = false;
4089             firstStatement = false;
4090             earlyReturn = null;
4091             initCall = null;
4092             scanDepth = 0;
4093             try {
4094                 super.visitLambda(tree);
4095             } finally {
4096                 constructor = constructorPrev;
4097                 firstStatement = firstStatementPrev;
4098                 earlyReturn = earlyReturnPrev;
4099                 initCall = initCallPrev;
4100                 scanDepth = scanDepthPrev;
4101             }
4102         }
4103     }
4104 
4105 /* *************************************************************************
4106  * Miscellaneous
4107  **************************************************************************/
4108 
4109     /**
4110      *  Check for division by integer constant zero
4111      *  @param pos           Position for error reporting.
4112      *  @param operator      The operator for the expression
4113      *  @param operand       The right hand operand for the expression
4114      */
4115     void checkDivZero(final DiagnosticPosition pos, Symbol operator, Type operand) {
4116         if (operand.constValue() != null
4117             && operand.getTag().isSubRangeOf(LONG)
4118             && ((Number) (operand.constValue())).longValue() == 0) {
4119             int opc = ((OperatorSymbol)operator).opcode;
4120             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
4121                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
4122                 log.warning(pos, LintWarnings.DivZero);
4123             }
4124         }
4125     }
4126 
4127     /**
4128      *  Check for bit shifts using an out-of-range bit count.
4129      *  @param pos           Position for error reporting.
4130      *  @param operator      The operator for the expression
4131      *  @param operand       The right hand operand for the expression
4132      */
4133     void checkOutOfRangeShift(final DiagnosticPosition pos, Symbol operator, Type operand) {
4134         if (operand.constValue() instanceof Number shiftAmount) {
4135             Type targetType;
4136             int maximumShift;
4137             switch (((OperatorSymbol)operator).opcode) {
4138             case ByteCodes.ishl, ByteCodes.ishr, ByteCodes.iushr, ByteCodes.ishll, ByteCodes.ishrl, ByteCodes.iushrl -> {
4139                 targetType = syms.intType;
4140                 maximumShift = 0x1f;
4141             }
4142             case ByteCodes.lshl, ByteCodes.lshr, ByteCodes.lushr, ByteCodes.lshll, ByteCodes.lshrl, ByteCodes.lushrl -> {
4143                 targetType = syms.longType;
4144                 maximumShift = 0x3f;
4145             }
4146             default -> {
4147                 return;
4148             }
4149             }
4150             long specifiedShift = shiftAmount.longValue();
4151             if (specifiedShift > maximumShift || specifiedShift < -maximumShift) {
4152                 int actualShift = (int)specifiedShift & (maximumShift - 1);
4153                 log.warning(pos, LintWarnings.BitShiftOutOfRange(targetType, specifiedShift, actualShift));
4154             }
4155         }
4156     }
4157 
4158     /**
4159      *  Check for possible loss of precission
4160      *  @param pos           Position for error reporting.
4161      *  @param found    The computed type of the tree
4162      *  @param req  The computed type of the tree
4163      */
4164     void checkLossOfPrecision(final DiagnosticPosition pos, Type found, Type req) {
4165         if (found.isNumeric() && req.isNumeric() && !types.isAssignable(found, req)) {
4166             log.warning(pos, LintWarnings.PossibleLossOfPrecision(found, req));
4167         }
4168     }
4169 
4170     /**
4171      * Check for empty statements after if
4172      */
4173     void checkEmptyIf(JCIf tree) {
4174         if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null) {
4175             log.warning(tree.thenpart.pos(), LintWarnings.EmptyIf);
4176         }
4177     }
4178 
4179     /** Check that symbol is unique in given scope.
4180      *  @param pos           Position for error reporting.
4181      *  @param sym           The symbol.
4182      *  @param s             The scope.
4183      */
4184     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
4185         if (sym.type.isErroneous())
4186             return true;
4187         if (sym.owner.name == names.any) return false;
4188         for (Symbol byName : s.getSymbolsByName(sym.name, NON_RECURSIVE)) {
4189             if (sym != byName &&
4190                     (byName.flags() & CLASH) == 0 &&
4191                     sym.kind == byName.kind &&
4192                     sym.name != names.error &&
4193                     (sym.kind != MTH ||
4194                      types.hasSameArgs(sym.type, byName.type) ||
4195                      types.hasSameArgs(types.erasure(sym.type), types.erasure(byName.type)))) {
4196                 if ((sym.flags() & VARARGS) != (byName.flags() & VARARGS)) {
4197                     sym.flags_field |= CLASH;
4198                     varargsDuplicateError(pos, sym, byName);
4199                     return true;
4200                 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, byName.type, false)) {
4201                     duplicateErasureError(pos, sym, byName);
4202                     sym.flags_field |= CLASH;
4203                     return true;
4204                 } else if ((sym.flags() & MATCH_BINDING) != 0 &&
4205                            (byName.flags() & MATCH_BINDING) != 0 &&
4206                            (byName.flags() & MATCH_BINDING_TO_OUTER) == 0) {
4207                     if (!sym.type.isErroneous()) {
4208                         log.error(pos, Errors.MatchBindingExists);
4209                         sym.flags_field |= CLASH;
4210                     }
4211                     return false;
4212                 } else {
4213                     duplicateError(pos, byName);
4214                     return false;
4215                 }
4216             }
4217         }
4218         return true;
4219     }
4220 
4221     /** Report duplicate declaration error.
4222      */
4223     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
4224         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
4225             log.error(pos, Errors.NameClashSameErasure(sym1, sym2));
4226         }
4227     }
4228 
4229     /**Check that types imported through the ordinary imports don't clash with types imported
4230      * by other (static or ordinary) imports. Note that two static imports may import two clashing
4231      * types without an error on the imports.
4232      * @param toplevel       The toplevel tree for which the test should be performed.
4233      */
4234     void checkImportsUnique(JCCompilationUnit toplevel) {
4235         WriteableScope ordinallyImportedSoFar = WriteableScope.create(toplevel.packge);
4236         WriteableScope staticallyImportedSoFar = WriteableScope.create(toplevel.packge);
4237         WriteableScope topLevelScope = toplevel.toplevelScope;
4238 
4239         for (JCTree def : toplevel.defs) {
4240             if (!def.hasTag(IMPORT))
4241                 continue;
4242 
4243             JCImport imp = (JCImport) def;
4244 
4245             if (imp.importScope == null)
4246                 continue;
4247 
4248             for (Symbol sym : imp.importScope.getSymbols(sym -> sym.kind == TYP)) {
4249                 if (imp.isStatic()) {
4250                     checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, true);
4251                     staticallyImportedSoFar.enter(sym);
4252                 } else {
4253                     checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, false);
4254                     ordinallyImportedSoFar.enter(sym);
4255                 }
4256             }
4257 
4258             imp.importScope = null;
4259         }
4260     }
4261 
4262     /** Check that single-type import is not already imported or top-level defined,
4263      *  but make an exception for two single-type imports which denote the same type.
4264      *  @param pos                     Position for error reporting.
4265      *  @param ordinallyImportedSoFar  A Scope containing types imported so far through
4266      *                                 ordinary imports.
4267      *  @param staticallyImportedSoFar A Scope containing types imported so far through
4268      *                                 static imports.
4269      *  @param topLevelScope           The current file's top-level Scope
4270      *  @param sym                     The symbol.
4271      *  @param staticImport            Whether or not this was a static import
4272      */
4273     private boolean checkUniqueImport(DiagnosticPosition pos, Scope ordinallyImportedSoFar,
4274                                       Scope staticallyImportedSoFar, Scope topLevelScope,
4275                                       Symbol sym, boolean staticImport) {
4276         Predicate<Symbol> duplicates = candidate -> candidate != sym && !candidate.type.isErroneous();
4277         Symbol ordinaryClashing = ordinallyImportedSoFar.findFirst(sym.name, duplicates);
4278         Symbol staticClashing = null;
4279         if (ordinaryClashing == null && !staticImport) {
4280             staticClashing = staticallyImportedSoFar.findFirst(sym.name, duplicates);
4281         }
4282         if (ordinaryClashing != null || staticClashing != null) {
4283             if (ordinaryClashing != null)
4284                 log.error(pos, Errors.AlreadyDefinedSingleImport(ordinaryClashing));
4285             else
4286                 log.error(pos, Errors.AlreadyDefinedStaticSingleImport(staticClashing));
4287             return false;
4288         }
4289         Symbol clashing = topLevelScope.findFirst(sym.name, duplicates);
4290         if (clashing != null) {
4291             log.error(pos, Errors.AlreadyDefinedThisUnit(clashing));
4292             return false;
4293         }
4294         return true;
4295     }
4296 
4297     /** Check that a qualified name is in canonical form (for import decls).
4298      */
4299     public void checkCanonical(JCTree tree) {
4300         if (!isCanonical(tree))
4301             log.error(tree.pos(),
4302                       Errors.ImportRequiresCanonical(TreeInfo.symbol(tree)));
4303     }
4304         // where
4305         private boolean isCanonical(JCTree tree) {
4306             while (tree.hasTag(SELECT)) {
4307                 JCFieldAccess s = (JCFieldAccess) tree;
4308                 if (s.sym.owner.getQualifiedName() != TreeInfo.symbol(s.selected).getQualifiedName())
4309                     return false;
4310                 tree = s.selected;
4311             }
4312             return true;
4313         }
4314 
4315     /** Check that an auxiliary class is not accessed from any other file than its own.
4316      */
4317     void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
4318         if ((c.flags() & AUXILIARY) != 0 &&
4319             rs.isAccessible(env, c) &&
4320             !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
4321         {
4322             log.warning(pos, LintWarnings.AuxiliaryClassAccessedFromOutsideOfItsSourceFile(c, c.sourcefile));
4323         }
4324     }
4325 
4326     /**
4327      * Check for a default constructor in an exported package.
4328      */
4329     void checkDefaultConstructor(ClassSymbol c, DiagnosticPosition pos) {
4330         if (lint.isEnabled(LintCategory.MISSING_EXPLICIT_CTOR) &&
4331             ((c.flags() & (ENUM | RECORD)) == 0) &&
4332             !c.isAnonymous() &&
4333             ((c.flags() & (PUBLIC | PROTECTED)) != 0) &&
4334             Feature.MODULES.allowedInSource(source)) {
4335             NestingKind nestingKind = c.getNestingKind();
4336             switch (nestingKind) {
4337                 case ANONYMOUS,
4338                      LOCAL -> {return;}
4339                 case TOP_LEVEL -> {;} // No additional checks needed
4340                 case MEMBER -> {
4341                     // For nested member classes, all the enclosing
4342                     // classes must be public or protected.
4343                     Symbol owner = c.owner;
4344                     while (owner != null && owner.kind == TYP) {
4345                         if ((owner.flags() & (PUBLIC | PROTECTED)) == 0)
4346                             return;
4347                         owner = owner.owner;
4348                     }
4349                 }
4350             }
4351 
4352             // Only check classes in named packages exported by its module
4353             PackageSymbol pkg = c.packge();
4354             if (!pkg.isUnnamed()) {
4355                 ModuleSymbol modle = pkg.modle;
4356                 for (ExportsDirective exportDir : modle.exports) {
4357                     // Report warning only if the containing
4358                     // package is unconditionally exported
4359                     if (exportDir.packge.equals(pkg)) {
4360                         if (exportDir.modules == null || exportDir.modules.isEmpty()) {
4361                             // Warning may be suppressed by
4362                             // annotations; check again for being
4363                             // enabled in the deferred context.
4364                             log.warning(pos, LintWarnings.MissingExplicitCtor(c, pkg, modle));
4365                         } else {
4366                             return;
4367                         }
4368                     }
4369                 }
4370             }
4371         }
4372         return;
4373     }
4374 
4375     private class ConversionWarner extends Warner {
4376         final String uncheckedKey;
4377         final Type found;
4378         final Type expected;
4379         public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
4380             super(pos);
4381             this.uncheckedKey = uncheckedKey;
4382             this.found = found;
4383             this.expected = expected;
4384         }
4385 
4386         @Override
4387         public void warn(LintCategory lint) {
4388             boolean warned = this.warned;
4389             super.warn(lint);
4390             if (warned) return; // suppress redundant diagnostics
4391             switch (lint) {
4392                 case UNCHECKED:
4393                     Check.this.warnUnchecked(pos(), LintWarnings.ProbFoundReq(diags.fragment(uncheckedKey), found, expected));
4394                     break;
4395                 case VARARGS:
4396                     if (method != null &&
4397                             method.attribute(syms.trustMeType.tsym) != null &&
4398                             isTrustMeAllowedOnMethod(method) &&
4399                             !types.isReifiable(method.type.getParameterTypes().last())) {
4400                         log.warning(pos(), LintWarnings.VarargsUnsafeUseVarargsParam(method.params.last()));
4401                     }
4402                     break;
4403                 default:
4404                     throw new AssertionError("Unexpected lint: " + lint);
4405             }
4406         }
4407     }
4408 
4409     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
4410         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
4411     }
4412 
4413     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
4414         return new ConversionWarner(pos, "unchecked.assign", found, expected);
4415     }
4416 
4417     public void checkFunctionalInterface(JCClassDecl tree, ClassSymbol cs) {
4418         Compound functionalType = cs.attribute(syms.functionalInterfaceType.tsym);
4419 
4420         if (functionalType != null) {
4421             try {
4422                 types.findDescriptorSymbol((TypeSymbol)cs);
4423             } catch (Types.FunctionDescriptorLookupError ex) {
4424                 DiagnosticPosition pos = tree.pos();
4425                 for (JCAnnotation a : tree.getModifiers().annotations) {
4426                     if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
4427                         pos = a.pos();
4428                         break;
4429                     }
4430                 }
4431                 log.error(pos, Errors.BadFunctionalIntfAnno1(ex.getDiagnostic()));
4432             }
4433         }
4434     }
4435 
4436     public void checkImportsResolvable(final JCCompilationUnit toplevel) {
4437         for (final JCImportBase impBase : toplevel.getImports()) {
4438             if (!(impBase instanceof JCImport imp))
4439                 continue;
4440             if (!imp.staticImport || !imp.qualid.hasTag(SELECT))
4441                 continue;
4442             final JCFieldAccess select = imp.qualid;
4443             final Symbol origin;
4444             if (select.name == names.asterisk || (origin = TreeInfo.symbol(select.selected)) == null || origin.kind != TYP)
4445                 continue;
4446 
4447             TypeSymbol site = (TypeSymbol) TreeInfo.symbol(select.selected);
4448             if (!checkTypeContainsImportableElement(site, site, toplevel.packge, select.name, new HashSet<Symbol>())) {
4449                 log.error(imp.pos(),
4450                           Errors.CantResolveLocation(KindName.STATIC,
4451                                                      select.name,
4452                                                      null,
4453                                                      null,
4454                                                      Fragments.Location(kindName(site),
4455                                                                         site,
4456                                                                         null)));
4457             }
4458         }
4459     }
4460 
4461     // Check that packages imported are in scope (JLS 7.4.3, 6.3, 6.5.3.1, 6.5.3.2)
4462     public void checkImportedPackagesObservable(final JCCompilationUnit toplevel) {
4463         OUTER: for (JCImportBase impBase : toplevel.getImports()) {
4464             if (impBase instanceof JCImport imp && !imp.staticImport &&
4465                 TreeInfo.name(imp.qualid) == names.asterisk) {
4466                 TypeSymbol tsym = imp.qualid.selected.type.tsym;
4467                 if (tsym.kind == PCK && tsym.members().isEmpty() &&
4468                     !(Feature.IMPORT_ON_DEMAND_OBSERVABLE_PACKAGES.allowedInSource(source) && tsym.exists())) {
4469                     log.error(DiagnosticFlag.RESOLVE_ERROR, imp.qualid.selected.pos(), Errors.DoesntExist(tsym));
4470                 }
4471             }
4472         }
4473     }
4474 
4475     private boolean checkTypeContainsImportableElement(TypeSymbol tsym, TypeSymbol origin, PackageSymbol packge, Name name, Set<Symbol> processed) {
4476         if (tsym == null || !processed.add(tsym))
4477             return false;
4478 
4479             // also search through inherited names
4480         if (checkTypeContainsImportableElement(types.supertype(tsym.type).tsym, origin, packge, name, processed))
4481             return true;
4482 
4483         for (Type t : types.interfaces(tsym.type))
4484             if (checkTypeContainsImportableElement(t.tsym, origin, packge, name, processed))
4485                 return true;
4486 
4487         for (Symbol sym : tsym.members().getSymbolsByName(name)) {
4488             if (sym.isStatic() &&
4489                 importAccessible(sym, packge) &&
4490                 sym.isMemberOf(origin, types)) {
4491                 return true;
4492             }
4493         }
4494 
4495         return false;
4496     }
4497 
4498     // is the sym accessible everywhere in packge?
4499     public boolean importAccessible(Symbol sym, PackageSymbol packge) {
4500         try {
4501             int flags = (int)(sym.flags() & AccessFlags);
4502             switch (flags) {
4503             default:
4504             case PUBLIC:
4505                 return true;
4506             case PRIVATE:
4507                 return false;
4508             case 0:
4509             case PROTECTED:
4510                 return sym.packge() == packge;
4511             }
4512         } catch (ClassFinder.BadClassFile err) {
4513             throw err;
4514         } catch (CompletionFailure ex) {
4515             return false;
4516         }
4517     }
4518 
4519     public void checkLeaksNotAccessible(Env<AttrContext> env, JCClassDecl check) {
4520         JCCompilationUnit toplevel = env.toplevel;
4521 
4522         if (   toplevel.modle == syms.unnamedModule
4523             || toplevel.modle == syms.noModule
4524             || (check.sym.flags() & COMPOUND) != 0) {
4525             return ;
4526         }
4527 
4528         ExportsDirective currentExport = findExport(toplevel.packge);
4529 
4530         if (   currentExport == null //not exported
4531             || currentExport.modules != null) //don't check classes in qualified export
4532             return ;
4533 
4534         new TreeScanner() {
4535             Lint lint = env.info.lint;
4536             boolean inSuperType;
4537 
4538             @Override
4539             public void visitBlock(JCBlock tree) {
4540             }
4541             @Override
4542             public void visitMethodDef(JCMethodDecl tree) {
4543                 if (!isAPISymbol(tree.sym))
4544                     return;
4545                 Lint prevLint = lint;
4546                 try {
4547                     lint = lint.augment(tree.sym);
4548                     if (lint.isEnabled(LintCategory.EXPORTS)) {
4549                         super.visitMethodDef(tree);
4550                     }
4551                 } finally {
4552                     lint = prevLint;
4553                 }
4554             }
4555             @Override
4556             public void visitVarDef(JCVariableDecl tree) {
4557                 if (!isAPISymbol(tree.sym) && tree.sym.owner.kind != MTH)
4558                     return;
4559                 Lint prevLint = lint;
4560                 try {
4561                     lint = lint.augment(tree.sym);
4562                     if (lint.isEnabled(LintCategory.EXPORTS)) {
4563                         scan(tree.mods);
4564                         scan(tree.vartype);
4565                     }
4566                 } finally {
4567                     lint = prevLint;
4568                 }
4569             }
4570             @Override
4571             public void visitClassDef(JCClassDecl tree) {
4572                 if (tree != check)
4573                     return ;
4574 
4575                 if (!isAPISymbol(tree.sym))
4576                     return ;
4577 
4578                 Lint prevLint = lint;
4579                 try {
4580                     lint = lint.augment(tree.sym);
4581                     if (lint.isEnabled(LintCategory.EXPORTS)) {
4582                         scan(tree.mods);
4583                         scan(tree.typarams);
4584                         try {
4585                             inSuperType = true;
4586                             scan(tree.extending);
4587                             scan(tree.implementing);
4588                         } finally {
4589                             inSuperType = false;
4590                         }
4591                         scan(tree.defs);
4592                     }
4593                 } finally {
4594                     lint = prevLint;
4595                 }
4596             }
4597             @Override
4598             public void visitTypeApply(JCTypeApply tree) {
4599                 scan(tree.clazz);
4600                 boolean oldInSuperType = inSuperType;
4601                 try {
4602                     inSuperType = false;
4603                     scan(tree.arguments);
4604                 } finally {
4605                     inSuperType = oldInSuperType;
4606                 }
4607             }
4608             @Override
4609             public void visitIdent(JCIdent tree) {
4610                 Symbol sym = TreeInfo.symbol(tree);
4611                 if (sym.kind == TYP && !sym.type.hasTag(TYPEVAR)) {
4612                     checkVisible(tree.pos(), sym, toplevel.packge, inSuperType);
4613                 }
4614             }
4615 
4616             @Override
4617             public void visitSelect(JCFieldAccess tree) {
4618                 Symbol sym = TreeInfo.symbol(tree);
4619                 Symbol sitesym = TreeInfo.symbol(tree.selected);
4620                 if (sym.kind == TYP && sitesym.kind == PCK) {
4621                     checkVisible(tree.pos(), sym, toplevel.packge, inSuperType);
4622                 } else {
4623                     super.visitSelect(tree);
4624                 }
4625             }
4626 
4627             @Override
4628             public void visitAnnotation(JCAnnotation tree) {
4629                 if (tree.attribute.type.tsym.getAnnotation(java.lang.annotation.Documented.class) != null)
4630                     super.visitAnnotation(tree);
4631             }
4632 
4633         }.scan(check);
4634     }
4635         //where:
4636         private ExportsDirective findExport(PackageSymbol pack) {
4637             for (ExportsDirective d : pack.modle.exports) {
4638                 if (d.packge == pack)
4639                     return d;
4640             }
4641 
4642             return null;
4643         }
4644         private boolean isAPISymbol(Symbol sym) {
4645             while (sym.kind != PCK) {
4646                 if ((sym.flags() & Flags.PUBLIC) == 0 && (sym.flags() & Flags.PROTECTED) == 0) {
4647                     return false;
4648                 }
4649                 sym = sym.owner;
4650             }
4651             return true;
4652         }
4653         private void checkVisible(DiagnosticPosition pos, Symbol what, PackageSymbol inPackage, boolean inSuperType) {
4654             if (!isAPISymbol(what) && !inSuperType) { //package private/private element
4655                 log.warning(pos, LintWarnings.LeaksNotAccessible(kindName(what), what, what.packge().modle));
4656                 return ;
4657             }
4658 
4659             PackageSymbol whatPackage = what.packge();
4660             ExportsDirective whatExport = findExport(whatPackage);
4661             ExportsDirective inExport = findExport(inPackage);
4662 
4663             if (whatExport == null) { //package not exported:
4664                 log.warning(pos, LintWarnings.LeaksNotAccessibleUnexported(kindName(what), what, what.packge().modle));
4665                 return ;
4666             }
4667 
4668             if (whatExport.modules != null) {
4669                 if (inExport.modules == null || !whatExport.modules.containsAll(inExport.modules)) {
4670                     log.warning(pos, LintWarnings.LeaksNotAccessibleUnexportedQualified(kindName(what), what, what.packge().modle));
4671                 }
4672             }
4673 
4674             if (whatPackage.modle != inPackage.modle && whatPackage.modle != syms.java_base) {
4675                 //check that relativeTo.modle requires transitive what.modle, somehow:
4676                 List<ModuleSymbol> todo = List.of(inPackage.modle);
4677 
4678                 while (todo.nonEmpty()) {
4679                     ModuleSymbol current = todo.head;
4680                     todo = todo.tail;
4681                     if (current == whatPackage.modle)
4682                         return ; //OK
4683                     if ((current.flags() & Flags.AUTOMATIC_MODULE) != 0)
4684                         continue; //for automatic modules, don't look into their dependencies
4685                     for (RequiresDirective req : current.requires) {
4686                         if (req.isTransitive()) {
4687                             todo = todo.prepend(req.module);
4688                         }
4689                     }
4690                 }
4691 
4692                 log.warning(pos, LintWarnings.LeaksNotAccessibleNotRequiredTransitive(kindName(what), what, what.packge().modle));
4693             }
4694         }
4695 
4696     void checkModuleExists(final DiagnosticPosition pos, ModuleSymbol msym) {
4697         if (msym.kind != MDL) {
4698             log.warning(pos, LintWarnings.ModuleNotFound(msym));
4699         }
4700     }
4701 
4702     void checkPackageExistsForOpens(final DiagnosticPosition pos, PackageSymbol packge) {
4703         if (packge.members().isEmpty() &&
4704             ((packge.flags() & Flags.HAS_RESOURCE) == 0)) {
4705             log.warning(pos, LintWarnings.PackageEmptyOrNotFound(packge));
4706         }
4707     }
4708 
4709     void checkModuleRequires(final DiagnosticPosition pos, final RequiresDirective rd) {
4710         if ((rd.module.flags() & Flags.AUTOMATIC_MODULE) != 0) {
4711             if (rd.isTransitive()) {    // see comment in Log.applyLint() for special logic that applies
4712                 log.warning(pos, LintWarnings.RequiresTransitiveAutomatic);
4713             } else {
4714                 log.warning(pos, LintWarnings.RequiresAutomatic);
4715             }
4716         }
4717     }
4718 
4719     /**
4720      * Verify the case labels conform to the constraints. Checks constraints related
4721      * combinations of patterns and other labels.
4722      *
4723      * @param cases the cases that should be checked.
4724      */
4725     void checkSwitchCaseStructure(List<JCCase> cases) {
4726         for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
4727             JCCase c = l.head;
4728             if (c.labels.head instanceof JCConstantCaseLabel constLabel) {
4729                 if (TreeInfo.isNull(constLabel.expr)) {
4730                     if (c.labels.tail.nonEmpty()) {
4731                         if (c.labels.tail.head instanceof JCDefaultCaseLabel defLabel) {
4732                             if (c.labels.tail.tail.nonEmpty()) {
4733                                 log.error(c.labels.tail.tail.head.pos(), Errors.InvalidCaseLabelCombination);
4734                             }
4735                         } else {
4736                             log.error(c.labels.tail.head.pos(), Errors.InvalidCaseLabelCombination);
4737                         }
4738                     }
4739                 } else {
4740                     for (JCCaseLabel label : c.labels.tail) {
4741                         if (!(label instanceof JCConstantCaseLabel) || TreeInfo.isNullCaseLabel(label)) {
4742                             log.error(label.pos(), Errors.InvalidCaseLabelCombination);
4743                             break;
4744                         }
4745                     }
4746                 }
4747             } else if (c.labels.tail.nonEmpty()) {
4748                 var patterCaseLabels = c.labels.stream().filter(ll -> ll instanceof JCPatternCaseLabel).map(cl -> (JCPatternCaseLabel)cl);
4749                 var allUnderscore = patterCaseLabels.allMatch(pcl -> !hasBindings(pcl.getPattern()));
4750 
4751                 if (!allUnderscore) {
4752                     log.error(c.labels.tail.head.pos(), Errors.FlowsThroughFromPattern);
4753                 }
4754 
4755                 boolean allPatternCaseLabels = c.labels.stream().allMatch(p -> p instanceof JCPatternCaseLabel);
4756 
4757                 if (allPatternCaseLabels) {
4758                     preview.checkSourceLevel(c.labels.tail.head.pos(), Feature.UNNAMED_VARIABLES);
4759                 }
4760 
4761                 for (JCCaseLabel label : c.labels.tail) {
4762                     if (label instanceof JCConstantCaseLabel) {
4763                         log.error(label.pos(), Errors.InvalidCaseLabelCombination);
4764                         break;
4765                     }
4766                 }
4767             }
4768         }
4769 
4770         boolean isCaseStatementGroup = cases.nonEmpty() &&
4771                                        cases.head.caseKind == CaseTree.CaseKind.STATEMENT;
4772 
4773         if (isCaseStatementGroup) {
4774             boolean previousCompletessNormally = false;
4775             for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
4776                 JCCase c = l.head;
4777                 if (previousCompletessNormally &&
4778                     c.stats.nonEmpty() &&
4779                     c.labels.head instanceof JCPatternCaseLabel patternLabel &&
4780                     (hasBindings(patternLabel.pat) || hasBindings(c.guard))) {
4781                     log.error(c.labels.head.pos(), Errors.FlowsThroughToPattern);
4782                 } else if (c.stats.isEmpty() &&
4783                            c.labels.head instanceof JCPatternCaseLabel patternLabel &&
4784                            (hasBindings(patternLabel.pat) || hasBindings(c.guard)) &&
4785                            hasStatements(l.tail)) {
4786                     log.error(c.labels.head.pos(), Errors.FlowsThroughFromPattern);
4787                 }
4788                 previousCompletessNormally = c.completesNormally;
4789             }
4790         }
4791     }
4792 
4793     boolean hasBindings(JCTree p) {
4794         boolean[] bindings = new boolean[1];
4795 
4796         new TreeScanner() {
4797             @Override
4798             public void visitBindingPattern(JCBindingPattern tree) {
4799                 bindings[0] |= !tree.var.sym.isUnnamedVariable();
4800                 super.visitBindingPattern(tree);
4801             }
4802         }.scan(p);
4803 
4804         return bindings[0];
4805     }
4806 
4807     boolean hasStatements(List<JCCase> cases) {
4808         for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
4809             if (l.head.stats.nonEmpty()) {
4810                 return true;
4811             }
4812         }
4813 
4814         return false;
4815     }
4816     void checkSwitchCaseLabelDominated(JCCaseLabel unconditionalCaseLabel, List<JCCase> cases) {
4817         List<Pair<JCCase, JCCaseLabel>> caseLabels = List.nil();
4818         boolean seenDefault = false;
4819         boolean seenDefaultLabel = false;
4820         boolean warnDominatedByDefault = false;
4821         boolean unconditionalFound = false;
4822 
4823         for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
4824             JCCase c = l.head;
4825             for (JCCaseLabel label : c.labels) {
4826                 if (label.hasTag(DEFAULTCASELABEL)) {
4827                     seenDefault = true;
4828                     seenDefaultLabel |=
4829                             TreeInfo.isNullCaseLabel(c.labels.head);
4830                     continue;
4831                 }
4832                 if (TreeInfo.isNullCaseLabel(label)) {
4833                     if (seenDefault) {
4834                         log.error(label.pos(), Errors.PatternDominated);
4835                     }
4836                     continue;
4837                 }
4838                 if (seenDefault && !warnDominatedByDefault) {
4839                     if (label.hasTag(PATTERNCASELABEL) ||
4840                         (label instanceof JCConstantCaseLabel && seenDefaultLabel)) {
4841                         log.error(label.pos(), Errors.PatternDominated);
4842                         warnDominatedByDefault = true;
4843                     }
4844                 }
4845                 Type currentType = labelType(label);
4846                 for (Pair<JCCase, JCCaseLabel> caseAndLabel : caseLabels) {
4847                     JCCase testCase = caseAndLabel.fst;
4848                     JCCaseLabel testCaseLabel = caseAndLabel.snd;
4849                     Type testType = labelType(testCaseLabel);
4850 
4851                     // an unconditional pattern cannot be followed by any other label
4852                     if (allowPrimitivePatterns && unconditionalCaseLabel == testCaseLabel && unconditionalCaseLabel != label) {
4853                         log.error(label.pos(), Errors.PatternDominated);
4854                         continue;
4855                     }
4856 
4857                     boolean dominated = false;
4858                     if (!currentType.hasTag(ERROR) && !testType.hasTag(ERROR)) {
4859                         // the current label is potentially dominated by the existing (test) label, check:
4860                         if (types.isUnconditionallyExactCombined(currentType, testType) &&
4861                                 label instanceof JCConstantCaseLabel) {
4862                             dominated = !(testCaseLabel instanceof JCConstantCaseLabel) &&
4863                                          TreeInfo.unguardedCase(testCase);
4864                         } else if (label instanceof JCPatternCaseLabel patternCL &&
4865                                    testCaseLabel instanceof JCPatternCaseLabel testPatternCaseLabel &&
4866                                    (testCase.equals(c) || TreeInfo.unguardedCase(testCase))) {
4867                             dominated = patternDominated(testPatternCaseLabel.pat, patternCL.pat);
4868                         }
4869                     }
4870                     if (dominated) {
4871                         log.error(label.pos(), Errors.PatternDominated);
4872                     }
4873                 }
4874                 caseLabels = caseLabels.prepend(Pair.of(c, label));
4875             }
4876         }
4877     }
4878         //where:
4879         private Type labelType(JCCaseLabel label) {
4880             return types.erasure(switch (label.getTag()) {
4881                 case PATTERNCASELABEL -> ((JCPatternCaseLabel) label).pat.type;
4882                 case CONSTANTCASELABEL -> ((JCConstantCaseLabel) label).expr.type;
4883                 default -> throw Assert.error("Unexpected tree kind: " + label.getTag());
4884             });
4885         }
4886         private boolean patternDominated(JCPattern existingPattern, JCPattern currentPattern) {
4887             Type existingPatternType = types.erasure(existingPattern.type);
4888             Type currentPatternType = types.erasure(currentPattern.type);
4889             if (!types.isUnconditionallyExactTypeBased(currentPatternType, existingPatternType)) {
4890                 return false;
4891             }
4892             if (currentPattern instanceof JCBindingPattern ||
4893                 currentPattern instanceof JCAnyPattern) {
4894                 return existingPattern instanceof JCBindingPattern ||
4895                        existingPattern instanceof JCAnyPattern;
4896             } else if (currentPattern instanceof JCRecordPattern currentRecordPattern) {
4897                 if (existingPattern instanceof JCBindingPattern ||
4898                     existingPattern instanceof JCAnyPattern) {
4899                     return true;
4900                 } else if (existingPattern instanceof JCRecordPattern existingRecordPattern) {
4901                     List<JCPattern> existingNested = existingRecordPattern.nested;
4902                     List<JCPattern> currentNested = currentRecordPattern.nested;
4903                     if (existingNested.size() != currentNested.size()) {
4904                         return false;
4905                     }
4906                     while (existingNested.nonEmpty()) {
4907                         if (!patternDominated(existingNested.head, currentNested.head)) {
4908                             return false;
4909                         }
4910                         existingNested = existingNested.tail;
4911                         currentNested = currentNested.tail;
4912                     }
4913                     return true;
4914                 } else {
4915                     Assert.error("Unknown pattern: " + existingPattern.getTag());
4916                 }
4917             } else {
4918                 Assert.error("Unknown pattern: " + currentPattern.getTag());
4919             }
4920             return false;
4921         }
4922 
4923     /** check if a type is a subtype of Externalizable, if that is available. */
4924     boolean isExternalizable(Type t) {
4925         try {
4926             syms.externalizableType.complete();
4927         } catch (CompletionFailure e) {
4928             return false;
4929         }
4930         return types.isSubtype(t, syms.externalizableType);
4931     }
4932 
4933     /**
4934      * Check structure of serialization declarations.
4935      */
4936     public void checkSerialStructure(Env<AttrContext> env, JCClassDecl tree, ClassSymbol c) {
4937         (new SerialTypeVisitor(env)).visit(c, tree);
4938     }
4939 
4940     /**
4941      * This visitor will warn if a serialization-related field or
4942      * method is declared in a suspicious or incorrect way. In
4943      * particular, it will warn for cases where the runtime
4944      * serialization mechanism will silently ignore a mis-declared
4945      * entity.
4946      *
4947      * Distinguished serialization-related fields and methods:
4948      *
4949      * Methods:
4950      *
4951      * private void writeObject(ObjectOutputStream stream) throws IOException
4952      * ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException
4953      *
4954      * private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException
4955      * private void readObjectNoData() throws ObjectStreamException
4956      * ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException
4957      *
4958      * Fields:
4959      *
4960      * private static final long serialVersionUID
4961      * private static final ObjectStreamField[] serialPersistentFields
4962      *
4963      * Externalizable: methods defined on the interface
4964      * public void writeExternal(ObjectOutput) throws IOException
4965      * public void readExternal(ObjectInput) throws IOException
4966      */
4967     private class SerialTypeVisitor extends ElementKindVisitor14<Void, JCClassDecl> {
4968         Env<AttrContext> env;
4969         SerialTypeVisitor(Env<AttrContext> env) {
4970             this.lint = Check.this.lint;
4971             this.env = env;
4972         }
4973 
4974         private static final Set<String> serialMethodNames =
4975             Set.of("writeObject", "writeReplace",
4976                    "readObject",  "readObjectNoData",
4977                    "readResolve");
4978 
4979         private static final Set<String> serialFieldNames =
4980             Set.of("serialVersionUID", "serialPersistentFields");
4981 
4982         // Type of serialPersistentFields
4983         private final Type OSF_TYPE = new Type.ArrayType(syms.objectStreamFieldType, syms.arrayClass);
4984 
4985         Lint lint;
4986 
4987         @Override
4988         public Void defaultAction(Element e, JCClassDecl p) {
4989             throw new IllegalArgumentException(Objects.requireNonNullElse(e.toString(), ""));
4990         }
4991 
4992         @Override
4993         public Void visitType(TypeElement e, JCClassDecl p) {
4994             runUnderLint(e, p, (symbol, param) -> super.visitType(symbol, param));
4995             return null;
4996         }
4997 
4998         @Override
4999         public Void visitTypeAsClass(TypeElement e,
5000                                      JCClassDecl p) {
5001             // Anonymous classes filtered out by caller.
5002 
5003             ClassSymbol c = (ClassSymbol)e;
5004 
5005             checkCtorAccess(p, c);
5006 
5007             /* Check for missing serialVersionUID; check *not* done
5008              * for enums or records.
5009              * Migrated value classes, need the value class and its corresponding
5010              * identity class to have the same SVUID.
5011              */
5012             VarSymbol svuidSym = null;
5013             for (Symbol sym : c.members().getSymbolsByName(names.serialVersionUID)) {
5014                 if (sym.kind == VAR) {
5015                     svuidSym = (VarSymbol)sym;
5016                     break;
5017                 }
5018             }
5019 
5020             if (svuidSym == null) {
5021                 log.warning(p.pos(), LintWarnings.MissingSVUID(c));
5022             }
5023 
5024             // Check for serialPersistentFields to gate checks for
5025             // non-serializable non-transient instance fields
5026             boolean serialPersistentFieldsPresent =
5027                     c.members()
5028                      .getSymbolsByName(names.serialPersistentFields, sym -> sym.kind == VAR)
5029                      .iterator()
5030                      .hasNext();
5031 
5032             // Check declarations of serialization-related methods and
5033             // fields
5034             final Map<String, Symbol> declaredSerialMethodNames = new HashMap<>();
5035             for(Symbol el : c.getEnclosedElements()) {
5036                 runUnderLint(el, p, (enclosed, tree) -> {
5037                     String name = null;
5038                     switch(enclosed.getKind()) {
5039                     case FIELD -> {
5040                         if (!serialPersistentFieldsPresent) {
5041                             var flags = enclosed.flags();
5042                             if ( ((flags & TRANSIENT) == 0) &&
5043                                  ((flags & STATIC) == 0)) {
5044                                 Type varType = enclosed.asType();
5045                                 if (!canBeSerialized(varType)) {
5046                                     // Note per JLS arrays are
5047                                     // serializable even if the
5048                                     // component type is not.
5049                                     log.warning(
5050                                             TreeInfo.diagnosticPositionFor(enclosed, tree),
5051                                                 LintWarnings.NonSerializableInstanceField);
5052                                 } else if (varType.hasTag(ARRAY)) {
5053                                     ArrayType arrayType = (ArrayType)varType;
5054                                     Type elementType = arrayType.elemtype;
5055                                     while (elementType.hasTag(ARRAY)) {
5056                                         arrayType = (ArrayType)elementType;
5057                                         elementType = arrayType.elemtype;
5058                                     }
5059                                     if (!canBeSerialized(elementType)) {
5060                                         log.warning(
5061                                                 TreeInfo.diagnosticPositionFor(enclosed, tree),
5062                                                     LintWarnings.NonSerializableInstanceFieldArray(elementType));
5063                                     }
5064                                 }
5065                             }
5066                         }
5067 
5068                         name = enclosed.getSimpleName().toString();
5069                         if (serialFieldNames.contains(name)) {
5070                             VarSymbol field = (VarSymbol)enclosed;
5071                             switch (name) {
5072                             case "serialVersionUID"       ->  checkSerialVersionUID(tree, e, field);
5073                             case "serialPersistentFields" ->  checkSerialPersistentFields(tree, e, field);
5074                             default -> throw new AssertionError();
5075                             }
5076                         }
5077                     }
5078 
5079                     // Correctly checking the serialization-related
5080                     // methods is subtle. For the methods declared to be
5081                     // private or directly declared in the class, the
5082                     // enclosed elements of the class can be checked in
5083                     // turn. However, writeReplace and readResolve can be
5084                     // declared in a superclass and inherited. Note that
5085                     // the runtime lookup walks the superclass chain
5086                     // looking for writeReplace/readResolve via
5087                     // Class.getDeclaredMethod. This differs from calling
5088                     // Elements.getAllMembers(TypeElement) as the latter
5089                     // will also pull in default methods from
5090                     // superinterfaces. In other words, the runtime checks
5091                     // (which long predate default methods on interfaces)
5092                     // do not admit the possibility of inheriting methods
5093                     // this way, a difference from general inheritance.
5094 
5095                     // The current implementation just checks the enclosed
5096                     // elements and does not directly check the inherited
5097                     // methods. If all the types are being checked this is
5098                     // less of a concern; however, there are cases that
5099                     // could be missed. In particular, readResolve and
5100                     // writeReplace could, in principle, by inherited from
5101                     // a non-serializable superclass and thus not checked
5102                     // even if compiled with a serializable child class.
5103                     case METHOD -> {
5104                         var method = (MethodSymbol)enclosed;
5105                         name = method.getSimpleName().toString();
5106                         if (serialMethodNames.contains(name)) {
5107                             if (switch (name) {
5108                                 case "writeObject"      -> hasAppropriateWriteObject(tree, e, method);
5109                                 case "writeReplace"     -> hasAppropriateWriteReplace(tree, method, true);
5110                                 case "readObject"       -> hasAppropriateReadObject(tree, e, method);
5111                                 case "readObjectNoData" -> hasAppropriateReadObjectNoData(tree, e, method);
5112                                 case "readResolve"      -> hasAppropriateReadResolve(tree, e, method);
5113                                 default ->  throw new AssertionError();
5114                             }) {
5115                                 declaredSerialMethodNames.put(name, el);
5116                             }
5117                         }
5118                     }
5119                     }
5120                 });
5121             }
5122             if (declaredSerialMethodNames.get("writeReplace") == null &&
5123                     (c.isValueClass() || hasAbstractValueSuperClass(c, Set.of(syms.numberType.tsym))) &&
5124                     !c.isAbstract() && !c.isRecord() &&
5125                     types.unboxedType(c.type) == Type.noType) {
5126                 /* if we are dealing with a value class or with a class with a super class that happens to
5127                  * be an abstract value class, that is not declaring a proper `writeReplace` method, then we
5128                  * need to make sure then that it is inheriting an appropriate one.
5129                  */
5130                 MethodSymbol ms = null;
5131                 Log.DiagnosticHandler discardHandler = log.new DiscardDiagnosticHandler();
5132                 try {
5133                     ms = rs.resolveInternalMethod(env.tree, env, c.type, names.writeReplace, List.nil(), List.nil());
5134                 } catch (FatalError fe) {
5135                     // ignore no method was found
5136                 } finally {
5137                     log.popDiagnosticHandler(discardHandler);
5138                 }
5139                 if (ms == null || !hasAppropriateWriteReplace(p, ms, false)) {
5140                     log.warning(p.pos(),
5141                             c.isValueClass() ? LintWarnings.SerializableValueClassWithoutWriteReplace1 :
5142                                     LintWarnings.SerializableValueClassWithoutWriteReplace2);
5143                 }
5144             }
5145             if (c.isValueClass()) {
5146                 /* Value classes are Serializable through the use of the serialization proxy pattern.
5147                  * The serialization protocol does not support a standard serialized form for value classes.
5148                  * The value class delegates to a serialization proxy by supplying an alternate
5149                  * record or object to be serialized instead of the value class.
5150                  * When the proxy is deserialized it re-constructs the value object and returns the value object.
5151                  *
5152                  * In particular methods:
5153                  *  - writeObject
5154                  *  - readObject and
5155                  *  - readObjectNoData
5156                  * are not invoked for value classes, we need to warn the user about this
5157                  */
5158                 for (Map.Entry<String, Symbol> entry : declaredSerialMethodNames.entrySet()) {
5159                     String key = entry.getKey();
5160                     if (key.equals("writeObject") || key.equals("readObject") || key.equals("readObjectNoData")) {
5161                         log.warning(TreeInfo.diagnosticPositionFor(entry.getValue(), p), LintWarnings.IneffectualSerialMethodValueClass(key));
5162                     }
5163                 }
5164             }
5165             return null;
5166         }
5167 
5168         boolean canBeSerialized(Type type) {
5169             return type.isPrimitive() || rs.isSerializable(type);
5170         }
5171 
5172         private boolean hasAbstractValueSuperClass(Symbol c, Set<Symbol> excluding) {
5173             while (c.getKind() == ElementKind.CLASS) {
5174                 Type sup = ((ClassSymbol)c).getSuperclass();
5175                 if (!sup.hasTag(CLASS) || sup.isErroneous() ||
5176                         sup.tsym == syms.objectType.tsym) {
5177                     return false;
5178                 }
5179                 // if it is a value super class it has to be abstract
5180                 if (sup.isValueClass() && !excluding.contains(sup.tsym)) {
5181                     return true;
5182                 }
5183                 c = sup.tsym;
5184             }
5185             return false;
5186         }
5187 
5188         /**
5189          * Check that Externalizable class needs a public no-arg
5190          * constructor.
5191          *
5192          * Check that a Serializable class has access to the no-arg
5193          * constructor of its first nonserializable superclass.
5194          */
5195         private void checkCtorAccess(JCClassDecl tree, ClassSymbol c) {
5196             if (isExternalizable(c.type)) {
5197                 for(var sym : c.getEnclosedElements()) {
5198                     if (sym.isConstructor() &&
5199                         ((sym.flags() & PUBLIC) == PUBLIC)) {
5200                         if (((MethodSymbol)sym).getParameters().isEmpty()) {
5201                             return;
5202                         }
5203                     }
5204                 }
5205                 log.warning(tree.pos(),
5206                             LintWarnings.ExternalizableMissingPublicNoArgCtor);
5207             } else {
5208                 // Approximate access to the no-arg constructor up in
5209                 // the superclass chain by checking that the
5210                 // constructor is not private. This may not handle
5211                 // some cross-package situations correctly.
5212                 Type superClass = c.getSuperclass();
5213                 // java.lang.Object is *not* Serializable so this loop
5214                 // should terminate.
5215                 while (rs.isSerializable(superClass) ) {
5216                     try {
5217                         superClass = (Type)((TypeElement)(((DeclaredType)superClass)).asElement()).getSuperclass();
5218                     } catch(ClassCastException cce) {
5219                         return ; // Don't try to recover
5220                     }
5221                 }
5222                 // Non-Serializable superclass
5223                 try {
5224                     ClassSymbol supertype = ((ClassSymbol)(((DeclaredType)superClass).asElement()));
5225                     for(var sym : supertype.getEnclosedElements()) {
5226                         if (sym.isConstructor()) {
5227                             MethodSymbol ctor = (MethodSymbol)sym;
5228                             if (ctor.getParameters().isEmpty()) {
5229                                 if (((ctor.flags() & PRIVATE) == PRIVATE) ||
5230                                     // Handle nested classes and implicit this$0
5231                                     (supertype.getNestingKind() == NestingKind.MEMBER &&
5232                                      ((supertype.flags() & STATIC) == 0)))
5233                                     log.warning(tree.pos(),
5234                                                 LintWarnings.SerializableMissingAccessNoArgCtor(supertype.getQualifiedName()));
5235                             }
5236                         }
5237                     }
5238                 } catch (ClassCastException cce) {
5239                     return ; // Don't try to recover
5240                 }
5241                 return;
5242             }
5243         }
5244 
5245         private void checkSerialVersionUID(JCClassDecl tree, Element e, VarSymbol svuid) {
5246             // To be effective, serialVersionUID must be marked static
5247             // and final, but private is recommended. But alas, in
5248             // practice there are many non-private serialVersionUID
5249             // fields.
5250              if ((svuid.flags() & (STATIC | FINAL)) !=
5251                  (STATIC | FINAL)) {
5252                  log.warning(
5253                          TreeInfo.diagnosticPositionFor(svuid, tree),
5254                              LintWarnings.ImproperSVUID((Symbol)e));
5255              }
5256 
5257              // check svuid has type long
5258              if (!svuid.type.hasTag(LONG)) {
5259                  log.warning(
5260                          TreeInfo.diagnosticPositionFor(svuid, tree),
5261                              LintWarnings.LongSVUID((Symbol)e));
5262              }
5263 
5264              if (svuid.getConstValue() == null)
5265                  log.warning(
5266                          TreeInfo.diagnosticPositionFor(svuid, tree),
5267                              LintWarnings.ConstantSVUID((Symbol)e));
5268         }
5269 
5270         private void checkSerialPersistentFields(JCClassDecl tree, Element e, VarSymbol spf) {
5271             // To be effective, serialPersisentFields must be private, static, and final.
5272              if ((spf.flags() & (PRIVATE | STATIC | FINAL)) !=
5273                  (PRIVATE | STATIC | FINAL)) {
5274                  log.warning(
5275                          TreeInfo.diagnosticPositionFor(spf, tree),
5276                              LintWarnings.ImproperSPF);
5277              }
5278 
5279              if (!types.isSameType(spf.type, OSF_TYPE)) {
5280                  log.warning(
5281                          TreeInfo.diagnosticPositionFor(spf, tree),
5282                              LintWarnings.OSFArraySPF);
5283              }
5284 
5285             if (isExternalizable((Type)(e.asType()))) {
5286                 log.warning(
5287                         TreeInfo.diagnosticPositionFor(spf, tree),
5288                             LintWarnings.IneffectualSerialFieldExternalizable);
5289             }
5290 
5291             // Warn if serialPersistentFields is initialized to a
5292             // literal null.
5293             JCTree spfDecl = TreeInfo.declarationFor(spf, tree);
5294             if (spfDecl != null && spfDecl.getTag() == VARDEF) {
5295                 JCVariableDecl variableDef = (JCVariableDecl) spfDecl;
5296                 JCExpression initExpr = variableDef.init;
5297                  if (initExpr != null && TreeInfo.isNull(initExpr)) {
5298                      log.warning(initExpr.pos(),
5299                                  LintWarnings.SPFNullInit);
5300                  }
5301             }
5302         }
5303 
5304         private boolean hasAppropriateWriteObject(JCClassDecl tree, Element e, MethodSymbol method) {
5305             // The "synchronized" modifier is seen in the wild on
5306             // readObject and writeObject methods and is generally
5307             // innocuous.
5308 
5309             // private void writeObject(ObjectOutputStream stream) throws IOException
5310             return isPrivateNonStaticMethod(tree, method) &  // no short-circuit we need to log warnings
5311                     isExpectedReturnType(tree, method, syms.voidType, true) &
5312                     hasExpectedArg(tree, method, syms.objectOutputStreamType) &
5313                     hasExpectedExceptions(tree, method, true, syms.ioExceptionType) &
5314                     checkExternalizable(tree, e, method);
5315         }
5316 
5317         private boolean hasAppropriateWriteReplace(JCClassDecl tree, MethodSymbol method, boolean warn) {
5318             // ANY-ACCESS-MODIFIER Object writeReplace() throws
5319             // ObjectStreamException
5320 
5321             // Excluding abstract, could have a more complicated
5322             // rule based on abstract-ness of the class
5323             return isConcreteInstanceMethod(tree, method, warn) &  // no short-circuit we need to log warnings
5324                     isExpectedReturnType(tree, method, syms.objectType, warn) &
5325                     hasNoArgs(tree, method, warn) &
5326                     hasExpectedExceptions(tree, method, warn, syms.objectStreamExceptionType);
5327         }
5328 
5329         private boolean hasAppropriateReadObject(JCClassDecl tree, Element e, MethodSymbol method) {
5330             // The "synchronized" modifier is seen in the wild on
5331             // readObject and writeObject methods and is generally
5332             // innocuous.
5333 
5334             // private void readObject(ObjectInputStream stream)
5335             //   throws IOException, ClassNotFoundException
5336             return isPrivateNonStaticMethod(tree, method) & // no short-circuit we need to log warnings
5337                     isExpectedReturnType(tree, method, syms.voidType, true) &
5338                     hasExpectedArg(tree, method, syms.objectInputStreamType) &
5339                     hasExpectedExceptions(tree, method, true, syms.ioExceptionType, syms.classNotFoundExceptionType) &
5340                     checkExternalizable(tree, e, method);
5341         }
5342 
5343         private boolean hasAppropriateReadObjectNoData(JCClassDecl tree, Element e, MethodSymbol method) {
5344             // private void readObjectNoData() throws ObjectStreamException
5345             return isPrivateNonStaticMethod(tree, method) & // no short-circuit we need to log warnings
5346                     isExpectedReturnType(tree, method, syms.voidType, true) &
5347                     hasNoArgs(tree, method, true) &
5348                     hasExpectedExceptions(tree, method, true, syms.objectStreamExceptionType) &
5349                     checkExternalizable(tree, e, method);
5350         }
5351 
5352         private boolean hasAppropriateReadResolve(JCClassDecl tree, Element e, MethodSymbol method) {
5353             // ANY-ACCESS-MODIFIER Object readResolve()
5354             // throws ObjectStreamException
5355 
5356             // Excluding abstract, could have a more complicated
5357             // rule based on abstract-ness of the class
5358             return isConcreteInstanceMethod(tree, method, true) & // no short-circuit we need to log warnings
5359                     isExpectedReturnType(tree, method, syms.objectType, true) &
5360                     hasNoArgs(tree, method, true) &
5361                     hasExpectedExceptions(tree, method, true, syms.objectStreamExceptionType);
5362         }
5363 
5364         private void checkWriteExternalRecord(JCClassDecl tree, Element e, MethodSymbol method, boolean isExtern) {
5365             //public void writeExternal(ObjectOutput) throws IOException
5366             checkExternMethodRecord(tree, e, method, syms.objectOutputType, isExtern);
5367         }
5368 
5369         private void checkReadExternalRecord(JCClassDecl tree, Element e, MethodSymbol method, boolean isExtern) {
5370             // public void readExternal(ObjectInput) throws IOException
5371             checkExternMethodRecord(tree, e, method, syms.objectInputType, isExtern);
5372          }
5373 
5374         private void checkExternMethodRecord(JCClassDecl tree, Element e, MethodSymbol method, Type argType,
5375                                              boolean isExtern) {
5376             if (isExtern && isExternMethod(tree, e, method, argType)) {
5377                 log.warning(
5378                         TreeInfo.diagnosticPositionFor(method, tree),
5379                             LintWarnings.IneffectualExternalizableMethodRecord(method.getSimpleName().toString()));
5380             }
5381         }
5382 
5383         boolean isPrivateNonStaticMethod(JCClassDecl tree, MethodSymbol method) {
5384             var flags = method.flags();
5385             boolean result = true;
5386             if ((flags & PRIVATE) == 0) {
5387                 log.warning(
5388                         TreeInfo.diagnosticPositionFor(method, tree),
5389                             LintWarnings.SerialMethodNotPrivate(method.getSimpleName()));
5390                 result = false;
5391             }
5392 
5393             if ((flags & STATIC) != 0) {
5394                 log.warning(
5395                         TreeInfo.diagnosticPositionFor(method, tree),
5396                             LintWarnings.SerialMethodStatic(method.getSimpleName()));
5397                 result = false;
5398             }
5399             return result;
5400         }
5401 
5402         /**
5403          * Per section 1.12 "Serialization of Enum Constants" of
5404          * the serialization specification, due to the special
5405          * serialization handling of enums, any writeObject,
5406          * readObject, writeReplace, and readResolve methods are
5407          * ignored as are serialPersistentFields and
5408          * serialVersionUID fields.
5409          */
5410         @Override
5411         public Void visitTypeAsEnum(TypeElement e,
5412                                     JCClassDecl p) {
5413             boolean isExtern = isExternalizable((Type)e.asType());
5414             for(Element el : e.getEnclosedElements()) {
5415                 runUnderLint(el, p, (enclosed, tree) -> {
5416                     String name = enclosed.getSimpleName().toString();
5417                     switch(enclosed.getKind()) {
5418                     case FIELD -> {
5419                         var field = (VarSymbol)enclosed;
5420                         if (serialFieldNames.contains(name)) {
5421                             log.warning(
5422                                     TreeInfo.diagnosticPositionFor(field, tree),
5423                                         LintWarnings.IneffectualSerialFieldEnum(name));
5424                         }
5425                     }
5426 
5427                     case METHOD -> {
5428                         var method = (MethodSymbol)enclosed;
5429                         if (serialMethodNames.contains(name)) {
5430                             log.warning(
5431                                     TreeInfo.diagnosticPositionFor(method, tree),
5432                                         LintWarnings.IneffectualSerialMethodEnum(name));
5433                         }
5434 
5435                         if (isExtern) {
5436                             switch(name) {
5437                             case "writeExternal" -> checkWriteExternalEnum(tree, e, method);
5438                             case "readExternal"  -> checkReadExternalEnum(tree, e, method);
5439                             }
5440                         }
5441                     }
5442 
5443                     // Also perform checks on any class bodies of enum constants, see JLS 8.9.1.
5444                     case ENUM_CONSTANT -> {
5445                         var field = (VarSymbol)enclosed;
5446                         JCVariableDecl decl = (JCVariableDecl) TreeInfo.declarationFor(field, p);
5447                         if (decl.init instanceof JCNewClass nc && nc.def != null) {
5448                             ClassSymbol enumConstantType = nc.def.sym;
5449                             visitTypeAsEnum(enumConstantType, p);
5450                         }
5451                     }
5452 
5453                     }});
5454             }
5455             return null;
5456         }
5457 
5458         private void checkWriteExternalEnum(JCClassDecl tree, Element e, MethodSymbol method) {
5459             //public void writeExternal(ObjectOutput) throws IOException
5460             checkExternMethodEnum(tree, e, method, syms.objectOutputType);
5461         }
5462 
5463         private void checkReadExternalEnum(JCClassDecl tree, Element e, MethodSymbol method) {
5464              // public void readExternal(ObjectInput) throws IOException
5465             checkExternMethodEnum(tree, e, method, syms.objectInputType);
5466          }
5467 
5468         private void checkExternMethodEnum(JCClassDecl tree, Element e, MethodSymbol method, Type argType) {
5469             if (isExternMethod(tree, e, method, argType)) {
5470                 log.warning(
5471                         TreeInfo.diagnosticPositionFor(method, tree),
5472                             LintWarnings.IneffectualExternMethodEnum(method.getSimpleName().toString()));
5473             }
5474         }
5475 
5476         private boolean isExternMethod(JCClassDecl tree, Element e, MethodSymbol method, Type argType) {
5477             long flags = method.flags();
5478             Type rtype = method.getReturnType();
5479 
5480             // Not necessary to check throws clause in this context
5481             return (flags & PUBLIC) != 0 && (flags & STATIC) == 0 &&
5482                 types.isSameType(syms.voidType, rtype) &&
5483                 hasExactlyOneArgWithType(tree, e, method, argType);
5484         }
5485 
5486         /**
5487          * Most serialization-related fields and methods on interfaces
5488          * are ineffectual or problematic.
5489          */
5490         @Override
5491         public Void visitTypeAsInterface(TypeElement e,
5492                                          JCClassDecl p) {
5493             for(Element el : e.getEnclosedElements()) {
5494                 runUnderLint(el, p, (enclosed, tree) -> {
5495                     String name = null;
5496                     switch(enclosed.getKind()) {
5497                     case FIELD -> {
5498                         var field = (VarSymbol)enclosed;
5499                         name = field.getSimpleName().toString();
5500                         switch(name) {
5501                         case "serialPersistentFields" -> {
5502                             log.warning(
5503                                     TreeInfo.diagnosticPositionFor(field, tree),
5504                                         LintWarnings.IneffectualSerialFieldInterface);
5505                         }
5506 
5507                         case "serialVersionUID" -> {
5508                             checkSerialVersionUID(tree, e, field);
5509                         }
5510                         }
5511                     }
5512 
5513                     case METHOD -> {
5514                         var method = (MethodSymbol)enclosed;
5515                         name = enclosed.getSimpleName().toString();
5516                         if (serialMethodNames.contains(name)) {
5517                             switch (name) {
5518                             case
5519                                 "readObject",
5520                                 "readObjectNoData",
5521                                 "writeObject"      -> checkPrivateMethod(tree, e, method);
5522 
5523                             case
5524                                 "writeReplace",
5525                                 "readResolve"      -> checkDefaultIneffective(tree, e, method);
5526 
5527                             default ->  throw new AssertionError();
5528                             }
5529 
5530                         }
5531                     }}
5532                 });
5533             }
5534 
5535             return null;
5536         }
5537 
5538         private void checkPrivateMethod(JCClassDecl tree,
5539                                         Element e,
5540                                         MethodSymbol method) {
5541             if ((method.flags() & PRIVATE) == 0) {
5542                 log.warning(
5543                         TreeInfo.diagnosticPositionFor(method, tree),
5544                             LintWarnings.NonPrivateMethodWeakerAccess);
5545             }
5546         }
5547 
5548         private void checkDefaultIneffective(JCClassDecl tree,
5549                                              Element e,
5550                                              MethodSymbol method) {
5551             if ((method.flags() & DEFAULT) == DEFAULT) {
5552                 log.warning(
5553                         TreeInfo.diagnosticPositionFor(method, tree),
5554                             LintWarnings.DefaultIneffective);
5555 
5556             }
5557         }
5558 
5559         @Override
5560         public Void visitTypeAsAnnotationType(TypeElement e,
5561                                               JCClassDecl p) {
5562             // Per the JLS, annotation types are not serializeable
5563             return null;
5564         }
5565 
5566         /**
5567          * From the Java Object Serialization Specification, 1.13
5568          * Serialization of Records:
5569          *
5570          * "The process by which record objects are serialized or
5571          * externalized cannot be customized; any class-specific
5572          * writeObject, readObject, readObjectNoData, writeExternal,
5573          * and readExternal methods defined by record classes are
5574          * ignored during serialization and deserialization. However,
5575          * a substitute object to be serialized or a designate
5576          * replacement may be specified, by the writeReplace and
5577          * readResolve methods, respectively. Any
5578          * serialPersistentFields field declaration is
5579          * ignored. Documenting serializable fields and data for
5580          * record classes is unnecessary, since there is no variation
5581          * in the serial form, other than whether a substitute or
5582          * replacement object is used. The serialVersionUID of a
5583          * record class is 0L unless explicitly declared. The
5584          * requirement for matching serialVersionUID values is waived
5585          * for record classes."
5586          */
5587         @Override
5588         public Void visitTypeAsRecord(TypeElement e,
5589                                       JCClassDecl p) {
5590             boolean isExtern = isExternalizable((Type)e.asType());
5591             for(Element el : e.getEnclosedElements()) {
5592                 runUnderLint(el, p, (enclosed, tree) -> {
5593                     String name = enclosed.getSimpleName().toString();
5594                     switch(enclosed.getKind()) {
5595                     case FIELD -> {
5596                         var field = (VarSymbol)enclosed;
5597                         switch(name) {
5598                         case "serialPersistentFields" -> {
5599                             log.warning(
5600                                     TreeInfo.diagnosticPositionFor(field, tree),
5601                                         LintWarnings.IneffectualSerialFieldRecord);
5602                         }
5603 
5604                         case "serialVersionUID" -> {
5605                             // Could generate additional warning that
5606                             // svuid value is not checked to match for
5607                             // records.
5608                             checkSerialVersionUID(tree, e, field);
5609                         }}
5610                     }
5611 
5612                     case METHOD -> {
5613                         var method = (MethodSymbol)enclosed;
5614                         switch(name) {
5615                         case "writeReplace" -> hasAppropriateWriteReplace(tree, method, true);
5616                         case "readResolve"  -> hasAppropriateReadResolve(tree, e, method);
5617 
5618                         case "writeExternal" -> checkWriteExternalRecord(tree, e, method, isExtern);
5619                         case "readExternal"  -> checkReadExternalRecord(tree, e, method, isExtern);
5620 
5621                         default -> {
5622                             if (serialMethodNames.contains(name)) {
5623                                 log.warning(
5624                                         TreeInfo.diagnosticPositionFor(method, tree),
5625                                             LintWarnings.IneffectualSerialMethodRecord(name));
5626                             }
5627                         }}
5628                     }}});
5629             }
5630             return null;
5631         }
5632 
5633         boolean isConcreteInstanceMethod(JCClassDecl tree,
5634                                          MethodSymbol method,
5635                                          boolean warn) {
5636             if ((method.flags() & (STATIC | ABSTRACT)) != 0) {
5637                 if (warn) {
5638                     log.warning(
5639                             TreeInfo.diagnosticPositionFor(method, tree),
5640                                 LintWarnings.SerialConcreteInstanceMethod(method.getSimpleName()));
5641                 }
5642                 return false;
5643             }
5644             return true;
5645         }
5646 
5647         private boolean isExpectedReturnType(JCClassDecl tree,
5648                                           MethodSymbol method,
5649                                           Type expectedReturnType,
5650                                           boolean warn) {
5651             // Note: there may be complications checking writeReplace
5652             // and readResolve since they return Object and could, in
5653             // principle, have covariant overrides and any synthetic
5654             // bridge method would not be represented here for
5655             // checking.
5656             Type rtype = method.getReturnType();
5657             if (!types.isSameType(expectedReturnType, rtype)) {
5658                 if (warn) {
5659                     log.warning(
5660                             TreeInfo.diagnosticPositionFor(method, tree),
5661                             LintWarnings.SerialMethodUnexpectedReturnType(method.getSimpleName(),
5662                                                                       rtype, expectedReturnType));
5663                 }
5664                 return false;
5665             }
5666             return true;
5667         }
5668 
5669         private boolean hasExpectedArg(JCClassDecl tree,
5670                                        MethodSymbol method,
5671                                        Type expectedType) {


5672 
5673             var parameters= method.getParameters();
5674 
5675             if (parameters.size() != 1) {
5676                 log.warning(
5677                         TreeInfo.diagnosticPositionFor(method, tree),
5678                             LintWarnings.SerialMethodOneArg(method.getSimpleName(), parameters.size()));
5679                 return false;
5680             }
5681 
5682             Type parameterType = parameters.get(0).asType();
5683             if (!types.isSameType(parameterType, expectedType)) {
5684                 log.warning(
5685                         TreeInfo.diagnosticPositionFor(method, tree),
5686                             LintWarnings.SerialMethodParameterType(method.getSimpleName(),
5687                                                                expectedType,
5688                                                                parameterType));
5689                 return false;
5690             }
5691             return true;
5692         }
5693 
5694         private boolean hasExactlyOneArgWithType(JCClassDecl tree,
5695                                                  Element enclosing,
5696                                                  MethodSymbol method,
5697                                                  Type expectedType) {
5698             var parameters = method.getParameters();
5699             return (parameters.size() == 1) &&
5700                 types.isSameType(parameters.get(0).asType(), expectedType);
5701         }
5702 
5703 
5704         boolean hasNoArgs(JCClassDecl tree, MethodSymbol method, boolean warn) {
5705             var parameters = method.getParameters();
5706             if (!parameters.isEmpty()) {
5707                 if (warn) {
5708                     log.warning(
5709                             TreeInfo.diagnosticPositionFor(parameters.get(0), tree),
5710                             LintWarnings.SerialMethodNoArgs(method.getSimpleName()));
5711                 }
5712                 return false;
5713             }
5714             return true;
5715         }
5716 
5717         private boolean checkExternalizable(JCClassDecl tree, Element enclosing, MethodSymbol method) {
5718             // If the enclosing class is externalizable, warn for the method
5719             if (isExternalizable((Type)enclosing.asType())) {
5720                 log.warning(
5721                         TreeInfo.diagnosticPositionFor(method, tree),
5722                             LintWarnings.IneffectualSerialMethodExternalizable(method.getSimpleName()));
5723                 return false;
5724             }
5725             return true;
5726         }
5727 
5728         private boolean hasExpectedExceptions(JCClassDecl tree,
5729                                               MethodSymbol method,
5730                                               boolean warn,
5731                                               Type... declaredExceptions) {
5732             for (Type thrownType: method.getThrownTypes()) {
5733                 // For each exception in the throws clause of the
5734                 // method, if not an Error and not a RuntimeException,
5735                 // check if the exception is a subtype of a declared
5736                 // exception from the throws clause of the
5737                 // serialization method in question.
5738                 if (types.isSubtype(thrownType, syms.runtimeExceptionType) ||
5739                     types.isSubtype(thrownType, syms.errorType) ) {
5740                     continue;
5741                 } else {
5742                     boolean declared = false;
5743                     for (Type declaredException : declaredExceptions) {
5744                         if (types.isSubtype(thrownType, declaredException)) {
5745                             declared = true;
5746                             continue;
5747                         }
5748                     }
5749                     if (!declared) {
5750                         if (warn) {
5751                             log.warning(
5752                                     TreeInfo.diagnosticPositionFor(method, tree),
5753                                     LintWarnings.SerialMethodUnexpectedException(method.getSimpleName(),
5754                                                                              thrownType));
5755                         }
5756                         return false;
5757                     }
5758                 }
5759             }
5760             return true;
5761         }
5762 
5763         private <E extends Element> Void runUnderLint(E symbol, JCClassDecl p, BiConsumer<E, JCClassDecl> task) {
5764             Lint prevLint = lint;
5765             try {
5766                 lint = lint.augment((Symbol) symbol);
5767 
5768                 if (lint.isEnabled(LintCategory.SERIAL)) {
5769                     task.accept(symbol, p);
5770                 }
5771 
5772                 return null;
5773             } finally {
5774                 lint = prevLint;
5775             }
5776         }
5777 
5778     }
5779 
5780     void checkRequiresIdentity(JCTree tree, Lint lint) {
5781         switch (tree) {
5782             case JCClassDecl classDecl -> {
5783                 Type st = types.supertype(classDecl.sym.type);
5784                 if (st != null &&
5785                         // no need to recheck j.l.Object, shortcut,
5786                         st.tsym != syms.objectType.tsym &&
5787                         // this one could be null, no explicit extends
5788                         classDecl.extending != null) {
5789                     checkIfIdentityIsExpected(classDecl.extending.pos(), st, lint);
5790                 }
5791                 for (JCExpression intrface: classDecl.implementing) {
5792                     checkIfIdentityIsExpected(intrface.pos(), intrface.type, lint);
5793                 }
5794                 for (JCTypeParameter tp : classDecl.typarams) {
5795                     checkIfIdentityIsExpected(tp.pos(), tp.type, lint);
5796                 }
5797             }
5798             case JCVariableDecl variableDecl -> {
5799                 if (variableDecl.vartype != null &&
5800                         ((variableDecl.sym.flags_field & RECORD) == 0 ||
5801                          (variableDecl.sym.flags_field & ~(Flags.PARAMETER | RECORD | GENERATED_MEMBER)) != 0)) {
5802                     /* we don't want to warn twice so if this variable is a compiler generated parameter of
5803                      * a canonical record constructor, we don't want to issue a warning as we will warn the
5804                      * corresponding compiler generated private record field anyways
5805                      */
5806                     checkIfIdentityIsExpected(variableDecl.vartype.pos(), variableDecl.vartype.type, lint);
5807                 }
5808             }
5809             case JCTypeCast typeCast -> checkIfIdentityIsExpected(typeCast.clazz.pos(), typeCast.clazz.type, lint);
5810             case JCBindingPattern bindingPattern -> {
5811                 if (bindingPattern.var.vartype != null) {
5812                     checkIfIdentityIsExpected(bindingPattern.var.vartype.pos(), bindingPattern.var.vartype.type, lint);
5813                 }
5814             }
5815             case JCMethodDecl methodDecl -> {
5816                 for (JCTypeParameter tp : methodDecl.typarams) {
5817                     checkIfIdentityIsExpected(tp.pos(), tp.type, lint);
5818                 }
5819                 if (methodDecl.restype != null && !methodDecl.restype.type.hasTag(VOID)) {
5820                     checkIfIdentityIsExpected(methodDecl.restype.pos(), methodDecl.restype.type, lint);
5821                 }
5822             }
5823             case JCMemberReference mref -> {
5824                 checkIfIdentityIsExpected(mref.expr.pos(), mref.target, lint);
5825                 checkIfTypeParamsRequiresIdentity(mref.sym.getMetadata(), mref.typeargs, lint);
5826             }
5827             case JCPolyExpression poly
5828                 when (poly instanceof JCNewClass || poly instanceof JCMethodInvocation) -> {
5829                 if (poly instanceof JCNewClass newClass) {
5830                     checkIfIdentityIsExpected(newClass.clazz.pos(), newClass.clazz.type, lint);
5831                 }
5832                 List<JCExpression> argExps = poly instanceof JCNewClass ?
5833                         ((JCNewClass)poly).args :
5834                         ((JCMethodInvocation)poly).args;
5835                 Symbol msym = TreeInfo.symbolFor(poly);
5836                 if (msym != null) {
5837                     if (!argExps.isEmpty() && msym instanceof MethodSymbol ms && ms.params != null) {
5838                         VarSymbol lastParam = ms.params.head;
5839                         for (VarSymbol param: ms.params) {
5840                             if ((param.flags_field & REQUIRES_IDENTITY) != 0 && argExps.head.type.isValueBased()) {
5841                                 log.warning(argExps.head.pos(), LintWarnings.AttemptToUseValueBasedWhereIdentityExpected);
5842                             }
5843                             lastParam = param;
5844                             argExps = argExps.tail;
5845                         }
5846                         while (argExps != null && !argExps.isEmpty() && lastParam != null) {
5847                             if ((lastParam.flags_field & REQUIRES_IDENTITY) != 0 && argExps.head.type.isValueBased()) {
5848                                 log.warning(argExps.head.pos(), LintWarnings.AttemptToUseValueBasedWhereIdentityExpected);
5849                             }
5850                             argExps = argExps.tail;
5851                         }
5852                     }
5853                     checkIfTypeParamsRequiresIdentity(
5854                             msym.getMetadata(),
5855                             poly instanceof JCNewClass ?
5856                                 ((JCNewClass)poly).typeargs :
5857                                 ((JCMethodInvocation)poly).typeargs,
5858                             lint);
5859                 }
5860             }
5861             default -> throw new AssertionError("unexpected tree " + tree);
5862         }
5863     }
5864 
5865     /** Check if a type required an identity class
5866      */
5867     private boolean checkIfIdentityIsExpected(DiagnosticPosition pos, Type t, Lint lint) {
5868         if (t != null &&
5869                 lint != null &&
5870                 lint.isEnabled(LintCategory.IDENTITY)) {
5871             RequiresIdentityVisitor requiresIdentityVisitor = new RequiresIdentityVisitor();
5872             // we need to avoid recursion due to self referencing type vars or captures, this is why we need a set
5873             requiresIdentityVisitor.visit(t, new HashSet<>());
5874             if (requiresIdentityVisitor.requiresWarning) {
5875                 log.warning(pos, LintWarnings.AttemptToUseValueBasedWhereIdentityExpected);
5876                 return true;
5877             }
5878         }
5879         return false;
5880     }
5881 
5882     // where
5883     private class RequiresIdentityVisitor extends Types.SimpleVisitor<Void, Set<Type>> {
5884         boolean requiresWarning = false;
5885 
5886         @Override
5887         public Void visitType(Type t, Set<Type> seen) {
5888             return null;
5889         }
5890 
5891         @Override
5892         public Void visitWildcardType(WildcardType t, Set<Type> seen) {
5893             return visit(t.type, seen);
5894         }
5895 
5896         @Override
5897         public Void visitTypeVar(TypeVar t, Set<Type> seen) {
5898             if (seen.add(t)) {
5899                 visit(t.getUpperBound(), seen);
5900             }
5901             return null;
5902         }
5903 
5904         @Override
5905         public Void visitCapturedType(CapturedType t, Set<Type> seen) {
5906             if (seen.add(t)) {
5907                 visit(t.getUpperBound(), seen);
5908                 visit(t.getLowerBound(), seen);
5909             }
5910             return null;
5911         }
5912 
5913         @Override
5914         public Void visitArrayType(ArrayType t, Set<Type> seen) {
5915             return visit(t.elemtype, seen);
5916         }
5917 
5918         @Override
5919         public Void visitClassType(ClassType t, Set<Type> seen) {
5920             if (t != null && t.tsym != null) {
5921                 SymbolMetadata sm = t.tsym.getMetadata();
5922                 if (sm != null && !t.getTypeArguments().isEmpty()) {
5923                     if (sm.getTypeAttributes().stream()
5924                             .filter(ta -> isRequiresIdentityAnnotation(ta.type.tsym) &&
5925                                     t.getTypeArguments().get(ta.position.parameter_index) != null &&
5926                                     t.getTypeArguments().get(ta.position.parameter_index).isValueBased()).findAny().isPresent()) {
5927                         requiresWarning = true;
5928                         return null;
5929                     }
5930                 }
5931             }
5932             visit(t.getEnclosingType(), seen);
5933             for (Type targ : t.getTypeArguments()) {
5934                 visit(targ, seen);
5935             }
5936             return null;
5937         }
5938     } // RequiresIdentityVisitor
5939 
5940     private void checkIfTypeParamsRequiresIdentity(SymbolMetadata sm,
5941                                                      List<JCExpression> typeParamTrees,
5942                                                      Lint lint) {
5943         if (typeParamTrees != null && !typeParamTrees.isEmpty()) {
5944             for (JCExpression targ : typeParamTrees) {
5945                 checkIfIdentityIsExpected(targ.pos(), targ.type, lint);
5946             }
5947             if (sm != null)
5948                 sm.getTypeAttributes().stream()
5949                         .filter(ta -> isRequiresIdentityAnnotation(ta.type.tsym) &&
5950                                 typeParamTrees.get(ta.position.parameter_index).type != null &&
5951                                 typeParamTrees.get(ta.position.parameter_index).type.isValueBased())
5952                         .forEach(ta -> log.warning(typeParamTrees.get(ta.position.parameter_index).pos(),
5953                                 CompilerProperties.LintWarnings.AttemptToUseValueBasedWhereIdentityExpected));
5954         }
5955     }
5956 
5957     private boolean isRequiresIdentityAnnotation(TypeSymbol annoType) {
5958         return annoType == syms.requiresIdentityType.tsym ||
5959                annoType.flatName() == syms.requiresIdentityInternalType.tsym.flatName();
5960     }
5961 }
--- EOF ---