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