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