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