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         allowValueClasses = Feature.VALUE_CLASSES.allowedInSource(source);
 188     }
 189 
 190     /** Character for synthetic names
 191      */
 192     char syntheticNameChar;
 193 
 194     /** A table mapping flat names of all compiled classes for each module in this run
 195      *  to their symbols; maintained from outside.
 196      */
 197     private Map<Pair<ModuleSymbol, Name>,ClassSymbol> compiled = new HashMap<>();
 198 
 199     /** A handler for messages about deprecated usage.
 200      */
 201     private MandatoryWarningHandler deprecationHandler;
 202 
 203     /** A handler for messages about deprecated-for-removal usage.
 204      */
 205     private MandatoryWarningHandler removalHandler;
 206 
 207     /** A handler for messages about unchecked or unsafe usage.
 208      */
 209     private MandatoryWarningHandler uncheckedHandler;
 210 
 211     /** A handler for messages about using proprietary API.
 212      */
 213     private MandatoryWarningHandler sunApiHandler;
 214 
 215     /** A handler for deferred lint warnings.
 216      */
 217     private DeferredLintHandler deferredLintHandler;
 218 
 219     /** Are modules allowed
 220      */
 221     private final boolean allowModules;
 222 
 223     /** Are records allowed
 224      */
 225     private final boolean allowRecords;
 226 
 227     /** Are sealed classes allowed
 228      */
 229     private final boolean allowSealed;
 230 
 231     /** Are value classes allowed
 232      */
 233     private final boolean allowValueClasses;
 234 
 235 /* *************************************************************************
 236  * Errors and Warnings
 237  **************************************************************************/
 238 
 239     Lint setLint(Lint newLint) {
 240         Lint prev = lint;
 241         lint = newLint;
 242         return prev;
 243     }
 244 
 245     MethodSymbol setMethod(MethodSymbol newMethod) {
 246         MethodSymbol prev = method;
 247         method = newMethod;
 248         return prev;
 249     }
 250 
 251     /** Warn about deprecated symbol.
 252      *  @param pos        Position to be used for error reporting.
 253      *  @param sym        The deprecated symbol.
 254      */
 255     void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
 256         if (sym.isDeprecatedForRemoval()) {
 257             if (!lint.isSuppressed(LintCategory.REMOVAL)) {
 258                 if (sym.kind == MDL) {
 259                     removalHandler.report(pos, Warnings.HasBeenDeprecatedForRemovalModule(sym));
 260                 } else {
 261                     removalHandler.report(pos, Warnings.HasBeenDeprecatedForRemoval(sym, sym.location()));
 262                 }
 263             }
 264         } else if (!lint.isSuppressed(LintCategory.DEPRECATION)) {
 265             if (sym.kind == MDL) {
 266                 deprecationHandler.report(pos, Warnings.HasBeenDeprecatedModule(sym));
 267             } else {
 268                 deprecationHandler.report(pos, Warnings.HasBeenDeprecated(sym, sym.location()));
 269             }
 270         }
 271     }
 272 
 273     /** Log a preview warning.
 274      *  @param pos        Position to be used for error reporting.
 275      *  @param msg        A Warning describing the problem.
 276      */
 277     public void warnPreviewAPI(DiagnosticPosition pos, Warning warnKey) {
 278         if (!lint.isSuppressed(LintCategory.PREVIEW))
 279             preview.reportPreviewWarning(pos, warnKey);
 280     }
 281 
 282     /** Log a preview warning.
 283      *  @param pos        Position to be used for error reporting.
 284      *  @param msg        A Warning describing the problem.
 285      */
 286     public void warnDeclaredUsingPreview(DiagnosticPosition pos, Symbol sym) {
 287         if (!lint.isSuppressed(LintCategory.PREVIEW))
 288             preview.reportPreviewWarning(pos, Warnings.DeclaredUsingPreview(kindName(sym), sym));
 289     }
 290 
 291     /** Log a preview warning.
 292      *  @param pos        Position to be used for error reporting.
 293      *  @param msg        A Warning describing the problem.
 294      */
 295     public void warnRestrictedAPI(DiagnosticPosition pos, Symbol sym) {
 296         if (lint.isEnabled(LintCategory.RESTRICTED))
 297             log.warning(LintCategory.RESTRICTED, pos, Warnings.RestrictedMethod(sym.enclClass(), sym));
 298     }
 299 
 300     /** Warn about unchecked operation.
 301      *  @param pos        Position to be used for error reporting.
 302      *  @param msg        A string describing the problem.
 303      */
 304     public void warnUnchecked(DiagnosticPosition pos, Warning warnKey) {
 305         if (!lint.isSuppressed(LintCategory.UNCHECKED))
 306             uncheckedHandler.report(pos, warnKey);
 307     }
 308 
 309     /** Warn about unsafe vararg method decl.
 310      *  @param pos        Position to be used for error reporting.
 311      */
 312     void warnUnsafeVararg(DiagnosticPosition pos, Warning warnKey) {
 313         if (lint.isEnabled(LintCategory.VARARGS))
 314             log.warning(LintCategory.VARARGS, pos, warnKey);
 315     }
 316 
 317     public void warnStatic(DiagnosticPosition pos, Warning warnKey) {
 318         if (lint.isEnabled(LintCategory.STATIC))
 319             log.warning(LintCategory.STATIC, pos, warnKey);
 320     }
 321 
 322     /** Warn about division by integer constant zero.
 323      *  @param pos        Position to be used for error reporting.
 324      */
 325     void warnDivZero(DiagnosticPosition pos) {
 326         if (lint.isEnabled(LintCategory.DIVZERO))
 327             log.warning(LintCategory.DIVZERO, pos, Warnings.DivZero);
 328     }
 329 
 330     /**
 331      * Report any deferred diagnostics.
 332      */
 333     public void reportDeferredDiagnostics() {
 334         deprecationHandler.reportDeferredDiagnostic();
 335         removalHandler.reportDeferredDiagnostic();
 336         uncheckedHandler.reportDeferredDiagnostic();
 337         sunApiHandler.reportDeferredDiagnostic();
 338     }
 339 
 340 
 341     /** Report a failure to complete a class.
 342      *  @param pos        Position to be used for error reporting.
 343      *  @param ex         The failure to report.
 344      */
 345     public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
 346         log.error(JCDiagnostic.DiagnosticFlag.NON_DEFERRABLE, pos, Errors.CantAccess(ex.sym, ex.getDetailValue()));
 347         return syms.errType;
 348     }
 349 
 350     /** Report an error that wrong type tag was found.
 351      *  @param pos        Position to be used for error reporting.
 352      *  @param required   An internationalized string describing the type tag
 353      *                    required.
 354      *  @param found      The type that was found.
 355      */
 356     Type typeTagError(DiagnosticPosition pos, JCDiagnostic required, Object found) {
 357         // this error used to be raised by the parser,
 358         // but has been delayed to this point:
 359         if (found instanceof Type type && type.hasTag(VOID)) {
 360             log.error(pos, Errors.IllegalStartOfType);
 361             return syms.errType;
 362         }
 363         log.error(pos, Errors.TypeFoundReq(found, required));
 364         return types.createErrorType(found instanceof Type type ? type : syms.errType);
 365     }
 366 









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