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