1 /*
   2  * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.tools.javac.comp;
  27 
  28 import java.util.*;
  29 import java.util.function.BiConsumer;
  30 import java.util.function.BiPredicate;
  31 import java.util.function.Consumer;
  32 import java.util.function.Predicate;
  33 import java.util.function.Supplier;
  34 import java.util.function.ToIntBiFunction;
  35 import java.util.stream.Collectors;
  36 import java.util.stream.StreamSupport;
  37 
  38 import javax.lang.model.element.ElementKind;
  39 import javax.lang.model.element.NestingKind;
  40 import javax.tools.JavaFileManager;
  41 
  42 import com.sun.source.tree.CaseTree;
  43 import com.sun.tools.javac.code.*;
  44 import com.sun.tools.javac.code.Attribute.Compound;
  45 import com.sun.tools.javac.code.Directive.ExportsDirective;
  46 import com.sun.tools.javac.code.Directive.RequiresDirective;
  47 import com.sun.tools.javac.code.Source.Feature;
  48 import com.sun.tools.javac.comp.Annotate.AnnotationTypeMetadata;
  49 import com.sun.tools.javac.jvm.*;
  50 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  51 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  52 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
  53 import com.sun.tools.javac.tree.*;
  54 import com.sun.tools.javac.util.*;
  55 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
  56 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  57 import com.sun.tools.javac.util.JCDiagnostic.Error;
  58 import com.sun.tools.javac.util.JCDiagnostic.Fragment;
  59 import com.sun.tools.javac.util.JCDiagnostic.Warning;
  60 import com.sun.tools.javac.util.List;
  61 
  62 import com.sun.tools.javac.code.Lint;
  63 import com.sun.tools.javac.code.Lint.LintCategory;
  64 import com.sun.tools.javac.code.Scope.WriteableScope;
  65 import com.sun.tools.javac.code.Type.*;
  66 import com.sun.tools.javac.code.Symbol.*;
  67 import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
  68 import com.sun.tools.javac.tree.JCTree.*;
  69 
  70 import static com.sun.tools.javac.code.Flags.*;
  71 import static com.sun.tools.javac.code.Flags.ANNOTATION;
  72 import static com.sun.tools.javac.code.Flags.SYNCHRONIZED;
  73 import static com.sun.tools.javac.code.Kinds.*;
  74 import static com.sun.tools.javac.code.Kinds.Kind.*;
  75 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
  76 import static com.sun.tools.javac.code.Scope.LookupKind.RECURSIVE;
  77 import static com.sun.tools.javac.code.TypeTag.*;
  78 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
  79 
  80 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  81 import javax.lang.model.element.Element;
  82 import javax.lang.model.element.ExecutableElement;
  83 import javax.lang.model.element.TypeElement;
  84 import javax.lang.model.type.DeclaredType;
  85 import javax.lang.model.type.TypeMirror;
  86 import javax.lang.model.util.ElementFilter;
  87 import javax.lang.model.util.ElementKindVisitor14;
  88 
  89 /** Type checking helper class for the attribution phase.
  90  *
  91  *  <p><b>This is NOT part of any supported API.
  92  *  If you write code that depends on this, you do so at your own risk.
  93  *  This code and its internal interfaces are subject to change or
  94  *  deletion without notice.</b>
  95  */
  96 public class Check {
  97     protected static final Context.Key<Check> checkKey = new Context.Key<>();
  98 
  99     // Flag bits indicating which item(s) chosen from a pair of items
 100     private static final int FIRST = 0x01;
 101     private static final int SECOND = 0x02;
 102 
 103     private final Names names;
 104     private final Log log;
 105     private final Resolve rs;
 106     private final Symtab syms;
 107     private final Enter enter;
 108     private final DeferredAttr deferredAttr;
 109     private final Infer infer;
 110     private final Types types;
 111     private final TypeAnnotations typeAnnotations;
 112     private final JCDiagnostic.Factory diags;
 113     private final JavaFileManager fileManager;
 114     private final Source source;
 115     private final Target target;
 116     private final Profile profile;
 117     private final Preview preview;
 118     private final boolean warnOnAnyAccessToMembers;
 119 
 120     public boolean disablePreviewCheck;
 121 
 122     // The set of lint options currently in effect. It is initialized
 123     // from the context, and then is set/reset as needed by Attr as it
 124     // visits all the various parts of the trees during attribution.
 125     private Lint lint;
 126 
 127     // The method being analyzed in Attr - it is set/reset as needed by
 128     // Attr as it visits new method declarations.
 129     private MethodSymbol method;
 130 
 131     public static Check instance(Context context) {
 132         Check instance = context.get(checkKey);
 133         if (instance == null)
 134             instance = new Check(context);
 135         return instance;
 136     }
 137 
 138     @SuppressWarnings("this-escape")
 139     protected Check(Context context) {
 140         context.put(checkKey, this);
 141 
 142         names = Names.instance(context);
 143         log = Log.instance(context);
 144         rs = Resolve.instance(context);
 145         syms = Symtab.instance(context);
 146         enter = Enter.instance(context);
 147         deferredAttr = DeferredAttr.instance(context);
 148         infer = Infer.instance(context);
 149         types = Types.instance(context);
 150         typeAnnotations = TypeAnnotations.instance(context);
 151         diags = JCDiagnostic.Factory.instance(context);
 152         Options options = Options.instance(context);
 153         lint = Lint.instance(context);
 154         fileManager = context.get(JavaFileManager.class);
 155 
 156         source = Source.instance(context);
 157         target = Target.instance(context);
 158         warnOnAnyAccessToMembers = options.isSet("warnOnAccessToMembers");
 159 
 160         disablePreviewCheck = false;
 161 
 162         Target target = Target.instance(context);
 163         syntheticNameChar = target.syntheticNameChar();
 164 
 165         profile = Profile.instance(context);
 166         preview = Preview.instance(context);
 167 
 168         boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
 169         boolean verboseRemoval = lint.isEnabled(LintCategory.REMOVAL);
 170         boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
 171         boolean enforceMandatoryWarnings = true;
 172 
 173         deprecationHandler = new MandatoryWarningHandler(log, null, verboseDeprecated,
 174                 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
 175         removalHandler = new MandatoryWarningHandler(log, null, verboseRemoval,
 176                 enforceMandatoryWarnings, "removal", LintCategory.REMOVAL);
 177         uncheckedHandler = new MandatoryWarningHandler(log, null, verboseUnchecked,
 178                 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
 179         sunApiHandler = new MandatoryWarningHandler(log, null, false,
 180                 enforceMandatoryWarnings, "sunapi", null);
 181 
 182         deferredLintHandler = DeferredLintHandler.instance(context);
 183 
 184         allowModules = Feature.MODULES.allowedInSource(source);
 185         allowRecords = Feature.RECORDS.allowedInSource(source);
 186         allowSealed = Feature.SEALED_CLASSES.allowedInSource(source);

 187     }
 188 
 189     /** Character for synthetic names
 190      */
 191     char syntheticNameChar;
 192 
 193     /** A table mapping flat names of all compiled classes for each module in this run
 194      *  to their symbols; maintained from outside.
 195      */
 196     private Map<Pair<ModuleSymbol, Name>,ClassSymbol> compiled = new HashMap<>();
 197 
 198     /** A handler for messages about deprecated usage.
 199      */
 200     private MandatoryWarningHandler deprecationHandler;
 201 
 202     /** A handler for messages about deprecated-for-removal usage.
 203      */
 204     private MandatoryWarningHandler removalHandler;
 205 
 206     /** A handler for messages about unchecked or unsafe usage.
 207      */
 208     private MandatoryWarningHandler uncheckedHandler;
 209 
 210     /** A handler for messages about using proprietary API.
 211      */
 212     private MandatoryWarningHandler sunApiHandler;
 213 
 214     /** A handler for deferred lint warnings.
 215      */
 216     private DeferredLintHandler deferredLintHandler;
 217 
 218     /** Are modules allowed
 219      */
 220     private final boolean allowModules;
 221 
 222     /** Are records allowed
 223      */
 224     private final boolean allowRecords;
 225 
 226     /** Are sealed classes allowed
 227      */
 228     private final boolean allowSealed;
 229 




 230 /* *************************************************************************
 231  * Errors and Warnings
 232  **************************************************************************/
 233 
 234     Lint setLint(Lint newLint) {
 235         Lint prev = lint;
 236         lint = newLint;
 237         return prev;
 238     }
 239 
 240     MethodSymbol setMethod(MethodSymbol newMethod) {
 241         MethodSymbol prev = method;
 242         method = newMethod;
 243         return prev;
 244     }
 245 
 246     /** Warn about deprecated symbol.
 247      *  @param pos        Position to be used for error reporting.
 248      *  @param sym        The deprecated symbol.
 249      */
 250     void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
 251         if (sym.isDeprecatedForRemoval()) {
 252             if (!lint.isSuppressed(LintCategory.REMOVAL)) {
 253                 if (sym.kind == MDL) {
 254                     removalHandler.report(pos, Warnings.HasBeenDeprecatedForRemovalModule(sym));
 255                 } else {
 256                     removalHandler.report(pos, Warnings.HasBeenDeprecatedForRemoval(sym, sym.location()));
 257                 }
 258             }
 259         } else if (!lint.isSuppressed(LintCategory.DEPRECATION)) {
 260             if (sym.kind == MDL) {
 261                 deprecationHandler.report(pos, Warnings.HasBeenDeprecatedModule(sym));
 262             } else {
 263                 deprecationHandler.report(pos, Warnings.HasBeenDeprecated(sym, sym.location()));
 264             }
 265         }
 266     }
 267 
 268     /** Log a preview warning.
 269      *  @param pos        Position to be used for error reporting.
 270      *  @param msg        A Warning describing the problem.
 271      */
 272     public void warnPreviewAPI(DiagnosticPosition pos, Warning warnKey) {
 273         if (!lint.isSuppressed(LintCategory.PREVIEW))
 274             preview.reportPreviewWarning(pos, warnKey);
 275     }
 276 
 277     /** Log a preview warning.
 278      *  @param pos        Position to be used for error reporting.
 279      *  @param msg        A Warning describing the problem.
 280      */
 281     public void warnDeclaredUsingPreview(DiagnosticPosition pos, Symbol sym) {
 282         if (!lint.isSuppressed(LintCategory.PREVIEW))
 283             preview.reportPreviewWarning(pos, Warnings.DeclaredUsingPreview(kindName(sym), sym));
 284     }
 285 
 286     /** Log a preview warning.
 287      *  @param pos        Position to be used for error reporting.
 288      *  @param msg        A Warning describing the problem.
 289      */
 290     public void warnRestrictedAPI(DiagnosticPosition pos, Symbol sym) {
 291         if (lint.isEnabled(LintCategory.RESTRICTED))
 292             log.warning(LintCategory.RESTRICTED, pos, Warnings.RestrictedMethod(sym.enclClass(), sym));
 293     }
 294 
 295     /** Warn about unchecked operation.
 296      *  @param pos        Position to be used for error reporting.
 297      *  @param msg        A string describing the problem.
 298      */
 299     public void warnUnchecked(DiagnosticPosition pos, Warning warnKey) {
 300         if (!lint.isSuppressed(LintCategory.UNCHECKED))
 301             uncheckedHandler.report(pos, warnKey);
 302     }
 303 
 304     /** Warn about unsafe vararg method decl.
 305      *  @param pos        Position to be used for error reporting.
 306      */
 307     void warnUnsafeVararg(DiagnosticPosition pos, Warning warnKey) {
 308         if (lint.isEnabled(LintCategory.VARARGS))
 309             log.warning(LintCategory.VARARGS, pos, warnKey);
 310     }
 311 
 312     public void warnStatic(DiagnosticPosition pos, Warning warnKey) {
 313         if (lint.isEnabled(LintCategory.STATIC))
 314             log.warning(LintCategory.STATIC, pos, warnKey);
 315     }
 316 
 317     /** Warn about division by integer constant zero.
 318      *  @param pos        Position to be used for error reporting.
 319      */
 320     void warnDivZero(DiagnosticPosition pos) {
 321         if (lint.isEnabled(LintCategory.DIVZERO))
 322             log.warning(LintCategory.DIVZERO, pos, Warnings.DivZero);
 323     }
 324 
 325     /**
 326      * Report any deferred diagnostics.
 327      */
 328     public void reportDeferredDiagnostics() {
 329         deprecationHandler.reportDeferredDiagnostic();
 330         removalHandler.reportDeferredDiagnostic();
 331         uncheckedHandler.reportDeferredDiagnostic();
 332         sunApiHandler.reportDeferredDiagnostic();
 333     }
 334 
 335 
 336     /** Report a failure to complete a class.
 337      *  @param pos        Position to be used for error reporting.
 338      *  @param ex         The failure to report.
 339      */
 340     public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
 341         log.error(JCDiagnostic.DiagnosticFlag.NON_DEFERRABLE, pos, Errors.CantAccess(ex.sym, ex.getDetailValue()));
 342         return syms.errType;
 343     }
 344 
 345     /** Report an error that wrong type tag was found.
 346      *  @param pos        Position to be used for error reporting.
 347      *  @param required   An internationalized string describing the type tag
 348      *                    required.
 349      *  @param found      The type that was found.
 350      */
 351     Type typeTagError(DiagnosticPosition pos, JCDiagnostic required, Object found) {
 352         // this error used to be raised by the parser,
 353         // but has been delayed to this point:
 354         if (found instanceof Type type && type.hasTag(VOID)) {
 355             log.error(pos, Errors.IllegalStartOfType);
 356             return syms.errType;
 357         }
 358         log.error(pos, Errors.TypeFoundReq(found, required));
 359         return types.createErrorType(found instanceof Type type ? type : syms.errType);
 360     }
 361 
 362     /** Report an error that symbol cannot be referenced before super
 363      *  has been called.
 364      *  @param pos        Position to be used for error reporting.
 365      *  @param sym        The referenced symbol.
 366      */
 367     void earlyRefError(DiagnosticPosition pos, Symbol sym) {
 368         log.error(pos, Errors.CantRefBeforeCtorCalled(sym));
 369     }
 370 
 371     /** Report duplicate declaration error.
 372      */
 373     void duplicateError(DiagnosticPosition pos, Symbol sym) {
 374         if (!sym.type.isErroneous()) {
 375             Symbol location = sym.location();
 376             if (location.kind == MTH &&
 377                     ((MethodSymbol)location).isStaticOrInstanceInit()) {
 378                 log.error(pos,
 379                           Errors.AlreadyDefinedInClinit(kindName(sym),
 380                                                         sym,
 381                                                         kindName(sym.location()),
 382                                                         kindName(sym.location().enclClass()),
 383                                                         sym.location().enclClass()));
 384             } else {
 385                 /* dont error if this is a duplicated parameter of a generated canonical constructor
 386                  * as we should have issued an error for the duplicated fields
 387                  */
 388                 if (location.kind != MTH ||
 389                         ((sym.owner.flags_field & GENERATEDCONSTR) == 0) ||
 390                         ((sym.owner.flags_field & RECORD) == 0)) {
 391                     log.error(pos,
 392                             Errors.AlreadyDefined(kindName(sym),
 393                                     sym,
 394                                     kindName(sym.location()),
 395                                     sym.location()));
 396                 }
 397             }
 398         }
 399     }
 400 
 401     /** Report array/varargs duplicate declaration
 402      */
 403     void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
 404         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
 405             log.error(pos, Errors.ArrayAndVarargs(sym1, sym2, sym2.location()));
 406         }
 407     }
 408 
 409 /* ************************************************************************
 410  * duplicate declaration checking
 411  *************************************************************************/
 412 
 413     /** Check that variable does not hide variable with same name in
 414      *  immediately enclosing local scope.
 415      *  @param pos           Position for error reporting.
 416      *  @param v             The symbol.
 417      *  @param s             The scope.
 418      */
 419     void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
 420         for (Symbol sym : s.getSymbolsByName(v.name)) {
 421             if (sym.owner != v.owner) break;
 422             if (sym.kind == VAR &&
 423                 sym.owner.kind.matches(KindSelector.VAL_MTH) &&
 424                 v.name != names.error) {
 425                 duplicateError(pos, sym);
 426                 return;
 427             }
 428         }
 429     }
 430 
 431     /** Check that a class or interface does not hide a class or
 432      *  interface with same name in immediately enclosing local scope.
 433      *  @param pos           Position for error reporting.
 434      *  @param c             The symbol.
 435      *  @param s             The scope.
 436      */
 437     void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
 438         for (Symbol sym : s.getSymbolsByName(c.name)) {
 439             if (sym.owner != c.owner) break;
 440             if (sym.kind == TYP && !sym.type.hasTag(TYPEVAR) &&
 441                 sym.owner.kind.matches(KindSelector.VAL_MTH) &&
 442                 c.name != names.error) {
 443                 duplicateError(pos, sym);
 444                 return;
 445             }
 446         }
 447     }
 448 
 449     /** Check that class does not have the same name as one of
 450      *  its enclosing classes, or as a class defined in its enclosing scope.
 451      *  return true if class is unique in its enclosing scope.
 452      *  @param pos           Position for error reporting.
 453      *  @param name          The class name.
 454      *  @param s             The enclosing scope.
 455      */
 456     boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
 457         for (Symbol sym : s.getSymbolsByName(name, NON_RECURSIVE)) {
 458             if (sym.kind == TYP && sym.name != names.error) {
 459                 duplicateError(pos, sym);
 460                 return false;
 461             }
 462         }
 463         for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
 464             if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
 465                 duplicateError(pos, sym);
 466                 return true;
 467             }
 468         }
 469         return true;
 470     }
 471 
 472 /* *************************************************************************
 473  * Class name generation
 474  **************************************************************************/
 475 
 476 
 477     private Map<Pair<Name, Name>, Integer> localClassNameIndexes = new HashMap<>();
 478 
 479     /** Return name of local class.
 480      *  This is of the form   {@code <enclClass> $ n <classname> }
 481      *  where
 482      *    enclClass is the flat name of the enclosing class,
 483      *    classname is the simple name of the local class
 484      */
 485     public Name localClassName(ClassSymbol c) {
 486         Name enclFlatname = c.owner.enclClass().flatname;
 487         String enclFlatnameStr = enclFlatname.toString();
 488         Pair<Name, Name> key = new Pair<>(enclFlatname, c.name);
 489         Integer index = localClassNameIndexes.get(key);
 490         for (int i = (index == null) ? 1 : index; ; i++) {
 491             Name flatname = names.fromString(enclFlatnameStr
 492                     + syntheticNameChar + i + c.name);
 493             if (getCompiled(c.packge().modle, flatname) == null) {
 494                 localClassNameIndexes.put(key, i + 1);
 495                 return flatname;
 496             }
 497         }
 498     }
 499 
 500     public void clearLocalClassNameIndexes(ClassSymbol c) {
 501         if (c.owner != null && c.owner.kind != NIL) {
 502             localClassNameIndexes.remove(new Pair<>(
 503                     c.owner.enclClass().flatname, c.name));
 504         }
 505     }
 506 
 507     public void newRound() {
 508         compiled.clear();
 509         localClassNameIndexes.clear();
 510     }
 511 
 512     public void clear() {
 513         deprecationHandler.clear();
 514         removalHandler.clear();
 515         uncheckedHandler.clear();
 516         sunApiHandler.clear();
 517     }
 518 
 519     public void putCompiled(ClassSymbol csym) {
 520         compiled.put(Pair.of(csym.packge().modle, csym.flatname), csym);
 521     }
 522 
 523     public ClassSymbol getCompiled(ClassSymbol csym) {
 524         return compiled.get(Pair.of(csym.packge().modle, csym.flatname));
 525     }
 526 
 527     public ClassSymbol getCompiled(ModuleSymbol msym, Name flatname) {
 528         return compiled.get(Pair.of(msym, flatname));
 529     }
 530 
 531     public void removeCompiled(ClassSymbol csym) {
 532         compiled.remove(Pair.of(csym.packge().modle, csym.flatname));
 533     }
 534 
 535 /* *************************************************************************
 536  * Type Checking
 537  **************************************************************************/
 538 
 539     /**
 540      * A check context is an object that can be used to perform compatibility
 541      * checks - depending on the check context, meaning of 'compatibility' might
 542      * vary significantly.
 543      */
 544     public interface CheckContext {
 545         /**
 546          * Is type 'found' compatible with type 'req' in given context
 547          */
 548         boolean compatible(Type found, Type req, Warner warn);
 549         /**
 550          * Report a check error
 551          */
 552         void report(DiagnosticPosition pos, JCDiagnostic details);
 553         /**
 554          * Obtain a warner for this check context
 555          */
 556         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req);
 557 
 558         public InferenceContext inferenceContext();
 559 
 560         public DeferredAttr.DeferredAttrContext deferredAttrContext();
 561     }
 562 
 563     /**
 564      * This class represent a check context that is nested within another check
 565      * context - useful to check sub-expressions. The default behavior simply
 566      * redirects all method calls to the enclosing check context leveraging
 567      * the forwarding pattern.
 568      */
 569     static class NestedCheckContext implements CheckContext {
 570         CheckContext enclosingContext;
 571 
 572         NestedCheckContext(CheckContext enclosingContext) {
 573             this.enclosingContext = enclosingContext;
 574         }
 575 
 576         public boolean compatible(Type found, Type req, Warner warn) {
 577             return enclosingContext.compatible(found, req, warn);
 578         }
 579 
 580         public void report(DiagnosticPosition pos, JCDiagnostic details) {
 581             enclosingContext.report(pos, details);
 582         }
 583 
 584         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
 585             return enclosingContext.checkWarner(pos, found, req);
 586         }
 587 
 588         public InferenceContext inferenceContext() {
 589             return enclosingContext.inferenceContext();
 590         }
 591 
 592         public DeferredAttrContext deferredAttrContext() {
 593             return enclosingContext.deferredAttrContext();
 594         }
 595     }
 596 
 597     /**
 598      * Check context to be used when evaluating assignment/return statements
 599      */
 600     CheckContext basicHandler = new CheckContext() {
 601         public void report(DiagnosticPosition pos, JCDiagnostic details) {
 602             log.error(pos, Errors.ProbFoundReq(details));
 603         }
 604         public boolean compatible(Type found, Type req, Warner warn) {
 605             return types.isAssignable(found, req, warn);
 606         }
 607 
 608         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
 609             return convertWarner(pos, found, req);
 610         }
 611 
 612         public InferenceContext inferenceContext() {
 613             return infer.emptyContext;
 614         }
 615 
 616         public DeferredAttrContext deferredAttrContext() {
 617             return deferredAttr.emptyDeferredAttrContext;
 618         }
 619 
 620         @Override
 621         public String toString() {
 622             return "CheckContext: basicHandler";
 623         }
 624     };
 625 
 626     /** Check that a given type is assignable to a given proto-type.
 627      *  If it is, return the type, otherwise return errType.
 628      *  @param pos        Position to be used for error reporting.
 629      *  @param found      The type that was found.
 630      *  @param req        The type that was required.
 631      */
 632     public Type checkType(DiagnosticPosition pos, Type found, Type req) {
 633         return checkType(pos, found, req, basicHandler);
 634     }
 635 
 636     Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
 637         final InferenceContext inferenceContext = checkContext.inferenceContext();
 638         if (inferenceContext.free(req) || inferenceContext.free(found)) {
 639             inferenceContext.addFreeTypeListener(List.of(req, found),
 640                     solvedContext -> checkType(pos, solvedContext.asInstType(found), solvedContext.asInstType(req), checkContext));
 641         }
 642         if (req.hasTag(ERROR))
 643             return req;
 644         if (req.hasTag(NONE))
 645             return found;
 646         if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
 647             return found;
 648         } else {
 649             if (found.isNumeric() && req.isNumeric()) {
 650                 checkContext.report(pos, diags.fragment(Fragments.PossibleLossOfPrecision(found, req)));
 651                 return types.createErrorType(found);
 652             }
 653             checkContext.report(pos, diags.fragment(Fragments.InconvertibleTypes(found, req)));
 654             return types.createErrorType(found);
 655         }
 656     }
 657 
 658     /** Check that a given type can be cast to a given target type.
 659      *  Return the result of the cast.
 660      *  @param pos        Position to be used for error reporting.
 661      *  @param found      The type that is being cast.
 662      *  @param req        The target type of the cast.
 663      */
 664     Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
 665         return checkCastable(pos, found, req, basicHandler);
 666     }
 667     Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
 668         if (types.isCastable(found, req, castWarner(pos, found, req))) {
 669             return req;
 670         } else {
 671             checkContext.report(pos, diags.fragment(Fragments.InconvertibleTypes(found, req)));
 672             return types.createErrorType(found);
 673         }
 674     }
 675 
 676     /** Check for redundant casts (i.e. where source type is a subtype of target type)
 677      * The problem should only be reported for non-292 cast
 678      */
 679     public void checkRedundantCast(Env<AttrContext> env, final JCTypeCast tree) {
 680         if (!tree.type.isErroneous()
 681                 && types.isSameType(tree.expr.type, tree.clazz.type)
 682                 && !(ignoreAnnotatedCasts && TreeInfo.containsTypeAnnotation(tree.clazz))
 683                 && !is292targetTypeCast(tree)) {
 684             deferredLintHandler.report(() -> {
 685                 if (lint.isEnabled(LintCategory.CAST))
 686                     log.warning(LintCategory.CAST,
 687                             tree.pos(), Warnings.RedundantCast(tree.clazz.type));
 688             });
 689         }
 690     }
 691     //where
 692         private boolean is292targetTypeCast(JCTypeCast tree) {
 693             boolean is292targetTypeCast = false;
 694             JCExpression expr = TreeInfo.skipParens(tree.expr);
 695             if (expr.hasTag(APPLY)) {
 696                 JCMethodInvocation apply = (JCMethodInvocation)expr;
 697                 Symbol sym = TreeInfo.symbol(apply.meth);
 698                 is292targetTypeCast = sym != null &&
 699                     sym.kind == MTH &&
 700                     (sym.flags() & HYPOTHETICAL) != 0;
 701             }
 702             return is292targetTypeCast;
 703         }
 704 
 705         private static final boolean ignoreAnnotatedCasts = true;
 706 
 707     /** Check that a type is within some bounds.
 708      *
 709      *  Used in TypeApply to verify that, e.g., X in {@code V<X>} is a valid
 710      *  type argument.
 711      *  @param a             The type that should be bounded by bs.
 712      *  @param bound         The bound.
 713      */
 714     private boolean checkExtends(Type a, Type bound) {
 715          if (a.isUnbound()) {
 716              return true;
 717          } else if (!a.hasTag(WILDCARD)) {
 718              a = types.cvarUpperBound(a);
 719              return types.isSubtype(a, bound);
 720          } else if (a.isExtendsBound()) {
 721              return types.isCastable(bound, types.wildUpperBound(a), types.noWarnings);
 722          } else if (a.isSuperBound()) {
 723              return !types.notSoftSubtype(types.wildLowerBound(a), bound);
 724          }
 725          return true;
 726      }
 727 
 728     /** Check that type is different from 'void'.
 729      *  @param pos           Position to be used for error reporting.
 730      *  @param t             The type to be checked.
 731      */
 732     Type checkNonVoid(DiagnosticPosition pos, Type t) {
 733         if (t.hasTag(VOID)) {
 734             log.error(pos, Errors.VoidNotAllowedHere);
 735             return types.createErrorType(t);
 736         } else {
 737             return t;
 738         }
 739     }
 740 
 741     Type checkClassOrArrayType(DiagnosticPosition pos, Type t) {
 742         if (!t.hasTag(CLASS) && !t.hasTag(ARRAY) && !t.hasTag(ERROR)) {
 743             return typeTagError(pos,
 744                                 diags.fragment(Fragments.TypeReqClassArray),
 745                                 asTypeParam(t));
 746         } else {
 747             return t;
 748         }
 749     }
 750 
 751     /** Check that type is a class or interface type.
 752      *  @param pos           Position to be used for error reporting.
 753      *  @param t             The type to be checked.
 754      */
 755     Type checkClassType(DiagnosticPosition pos, Type t) {
 756         if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) {
 757             return typeTagError(pos,
 758                                 diags.fragment(Fragments.TypeReqClass),
 759                                 asTypeParam(t));
 760         } else {
 761             return t;
 762         }
 763     }
 764     //where
 765         private Object asTypeParam(Type t) {
 766             return (t.hasTag(TYPEVAR))
 767                                     ? diags.fragment(Fragments.TypeParameter(t))
 768                                     : t;
 769         }
 770 

























 771     /** Check that type is a valid qualifier for a constructor reference expression
 772      */
 773     Type checkConstructorRefType(DiagnosticPosition pos, Type t) {
 774         t = checkClassOrArrayType(pos, t);
 775         if (t.hasTag(CLASS)) {
 776             if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
 777                 log.error(pos, Errors.AbstractCantBeInstantiated(t.tsym));
 778                 t = types.createErrorType(t);
 779             } else if ((t.tsym.flags() & ENUM) != 0) {
 780                 log.error(pos, Errors.EnumCantBeInstantiated);
 781                 t = types.createErrorType(t);
 782             } else {
 783                 t = checkClassType(pos, t, true);
 784             }
 785         } else if (t.hasTag(ARRAY)) {
 786             if (!types.isReifiable(((ArrayType)t).elemtype)) {
 787                 log.error(pos, Errors.GenericArrayCreation);
 788                 t = types.createErrorType(t);
 789             }
 790         }
 791         return t;
 792     }
 793 
 794     /** Check that type is a class or interface type.
 795      *  @param pos           Position to be used for error reporting.
 796      *  @param t             The type to be checked.
 797      *  @param noBounds    True if type bounds are illegal here.
 798      */
 799     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
 800         t = checkClassType(pos, t);
 801         if (noBounds && t.isParameterized()) {
 802             List<Type> args = t.getTypeArguments();
 803             while (args.nonEmpty()) {
 804                 if (args.head.hasTag(WILDCARD))
 805                     return typeTagError(pos,
 806                                         diags.fragment(Fragments.TypeReqExact),
 807                                         args.head);
 808                 args = args.tail;
 809             }
 810         }
 811         return t;
 812     }
 813 
 814     /** Check that type is a reference type, i.e. a class, interface or array type
 815      *  or a type variable.
 816      *  @param pos           Position to be used for error reporting.
 817      *  @param t             The type to be checked.
 818      */
 819     Type checkRefType(DiagnosticPosition pos, Type t) {
 820         if (t.isReference())
 821             return t;
 822         else
 823             return typeTagError(pos,
 824                                 diags.fragment(Fragments.TypeReqRef),
 825                                 t);
 826     }
 827 






















 828     /** Check that each type is a reference type, i.e. a class, interface or array type
 829      *  or a type variable.
 830      *  @param trees         Original trees, used for error reporting.
 831      *  @param types         The types to be checked.
 832      */
 833     List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
 834         List<JCExpression> tl = trees;
 835         for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
 836             l.head = checkRefType(tl.head.pos(), l.head);
 837             tl = tl.tail;
 838         }
 839         return types;
 840     }
 841 
 842     /** Check that type is a null or reference type.
 843      *  @param pos           Position to be used for error reporting.
 844      *  @param t             The type to be checked.
 845      */
 846     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
 847         if (t.isReference() || t.hasTag(BOT))
 848             return t;
 849         else
 850             return typeTagError(pos,
 851                                 diags.fragment(Fragments.TypeReqRef),
 852                                 t);
 853     }
 854 
 855     /** Check that flag set does not contain elements of two conflicting sets. s
 856      *  Return true if it doesn't.
 857      *  @param pos           Position to be used for error reporting.
 858      *  @param flags         The set of flags to be checked.
 859      *  @param set1          Conflicting flags set #1.
 860      *  @param set2          Conflicting flags set #2.
 861      */
 862     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
 863         if ((flags & set1) != 0 && (flags & set2) != 0) {
 864             log.error(pos,
 865                       Errors.IllegalCombinationOfModifiers(asFlagSet(TreeInfo.firstFlag(flags & set1)),
 866                                                            asFlagSet(TreeInfo.firstFlag(flags & set2))));
 867             return false;
 868         } else
 869             return true;
 870     }
 871 
 872     /** Check that usage of diamond operator is correct (i.e. diamond should not
 873      * be used with non-generic classes or in anonymous class creation expressions)
 874      */
 875     Type checkDiamond(JCNewClass tree, Type t) {
 876         if (!TreeInfo.isDiamond(tree) ||
 877                 t.isErroneous()) {
 878             return checkClassType(tree.clazz.pos(), t, true);
 879         } else {
 880             if (tree.def != null && !Feature.DIAMOND_WITH_ANONYMOUS_CLASS_CREATION.allowedInSource(source)) {
 881                 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.clazz.pos(),
 882                         Errors.CantApplyDiamond1(t, Feature.DIAMOND_WITH_ANONYMOUS_CLASS_CREATION.fragment(source.name)));
 883             }
 884             if (t.tsym.type.getTypeArguments().isEmpty()) {
 885                 log.error(tree.clazz.pos(),
 886                           Errors.CantApplyDiamond1(t,
 887                                                    Fragments.DiamondNonGeneric(t)));
 888                 return types.createErrorType(t);
 889             } else if (tree.typeargs != null &&
 890                     tree.typeargs.nonEmpty()) {
 891                 log.error(tree.clazz.pos(),
 892                           Errors.CantApplyDiamond1(t,
 893                                                    Fragments.DiamondAndExplicitParams(t)));
 894                 return types.createErrorType(t);
 895             } else {
 896                 return t;
 897             }
 898         }
 899     }
 900 
 901     /** Check that the type inferred using the diamond operator does not contain
 902      *  non-denotable types such as captured types or intersection types.
 903      *  @param t the type inferred using the diamond operator
 904      *  @return  the (possibly empty) list of non-denotable types.
 905      */
 906     List<Type> checkDiamondDenotable(ClassType t) {
 907         ListBuffer<Type> buf = new ListBuffer<>();
 908         for (Type arg : t.allparams()) {
 909             if (!checkDenotable(arg)) {
 910                 buf.append(arg);
 911             }
 912         }
 913         return buf.toList();
 914     }
 915 
 916     public boolean checkDenotable(Type t) {
 917         return denotableChecker.visit(t, null);
 918     }
 919         // where
 920 
 921         /** diamondTypeChecker: A type visitor that descends down the given type looking for non-denotable
 922          *  types. The visit methods return false as soon as a non-denotable type is encountered and true
 923          *  otherwise.
 924          */
 925         private static final Types.SimpleVisitor<Boolean, Void> denotableChecker = new Types.SimpleVisitor<Boolean, Void>() {
 926             @Override
 927             public Boolean visitType(Type t, Void s) {
 928                 return true;
 929             }
 930             @Override
 931             public Boolean visitClassType(ClassType t, Void s) {
 932                 if (t.isUnion() || t.isIntersection()) {
 933                     return false;
 934                 }
 935                 for (Type targ : t.allparams()) {
 936                     if (!visit(targ, s)) {
 937                         return false;
 938                     }
 939                 }
 940                 return true;
 941             }
 942 
 943             @Override
 944             public Boolean visitTypeVar(TypeVar t, Void s) {
 945                 /* Any type variable mentioned in the inferred type must have been declared as a type parameter
 946                   (i.e cannot have been produced by inference (18.4))
 947                 */
 948                 return (t.tsym.flags() & SYNTHETIC) == 0;
 949             }
 950 
 951             @Override
 952             public Boolean visitCapturedType(CapturedType t, Void s) {
 953                 /* Any type variable mentioned in the inferred type must have been declared as a type parameter
 954                   (i.e cannot have been produced by capture conversion (5.1.10))
 955                 */
 956                 return false;
 957             }
 958 
 959             @Override
 960             public Boolean visitArrayType(ArrayType t, Void s) {
 961                 return visit(t.elemtype, s);
 962             }
 963 
 964             @Override
 965             public Boolean visitWildcardType(WildcardType t, Void s) {
 966                 return visit(t.type, s);
 967             }
 968         };
 969 
 970     void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
 971         MethodSymbol m = tree.sym;
 972         boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
 973         Type varargElemType = null;
 974         if (m.isVarArgs()) {
 975             varargElemType = types.elemtype(tree.params.last().type);
 976         }
 977         if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
 978             if (varargElemType != null) {
 979                 JCDiagnostic msg = Feature.PRIVATE_SAFE_VARARGS.allowedInSource(source) ?
 980                         diags.fragment(Fragments.VarargsTrustmeOnVirtualVarargs(m)) :
 981                         diags.fragment(Fragments.VarargsTrustmeOnVirtualVarargsFinalOnly(m));
 982                 log.error(tree,
 983                           Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym,
 984                                                            msg));
 985             } else {
 986                 log.error(tree,
 987                           Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym,
 988                                                            Fragments.VarargsTrustmeOnNonVarargsMeth(m)));
 989             }
 990         } else if (hasTrustMeAnno && varargElemType != null &&
 991                             types.isReifiable(varargElemType)) {
 992             warnUnsafeVararg(tree, Warnings.VarargsRedundantTrustmeAnno(
 993                                 syms.trustMeType.tsym,
 994                                 diags.fragment(Fragments.VarargsTrustmeOnReifiableVarargs(varargElemType))));
 995         }
 996         else if (!hasTrustMeAnno && varargElemType != null &&
 997                 !types.isReifiable(varargElemType)) {
 998             warnUnchecked(tree.params.head.pos(), Warnings.UncheckedVarargsNonReifiableType(varargElemType));
 999         }
1000     }
1001     //where
1002         private boolean isTrustMeAllowedOnMethod(Symbol s) {
1003             return (s.flags() & VARARGS) != 0 &&
1004                 (s.isConstructor() ||
1005                     (s.flags() & (STATIC | FINAL |
1006                                   (Feature.PRIVATE_SAFE_VARARGS.allowedInSource(source) ? PRIVATE : 0) )) != 0);
1007         }
1008 
1009     Type checkLocalVarType(DiagnosticPosition pos, Type t, Name name) {
1010         //check that resulting type is not the null type
1011         if (t.hasTag(BOT)) {
1012             log.error(pos, Errors.CantInferLocalVarType(name, Fragments.LocalCantInferNull));
1013             return types.createErrorType(t);
1014         } else if (t.hasTag(VOID)) {
1015             log.error(pos, Errors.CantInferLocalVarType(name, Fragments.LocalCantInferVoid));
1016             return types.createErrorType(t);
1017         }
1018 
1019         //upward project the initializer type
1020         return types.upward(t, types.captures(t)).baseType();
1021     }
1022 
1023     Type checkMethod(final Type mtype,
1024             final Symbol sym,
1025             final Env<AttrContext> env,
1026             final List<JCExpression> argtrees,
1027             final List<Type> argtypes,
1028             final boolean useVarargs,
1029             InferenceContext inferenceContext) {
1030         // System.out.println("call   : " + env.tree);
1031         // System.out.println("method : " + owntype);
1032         // System.out.println("actuals: " + argtypes);
1033         if (inferenceContext.free(mtype)) {
1034             inferenceContext.addFreeTypeListener(List.of(mtype),
1035                     solvedContext -> checkMethod(solvedContext.asInstType(mtype), sym, env, argtrees, argtypes, useVarargs, solvedContext));
1036             return mtype;
1037         }
1038         Type owntype = mtype;
1039         List<Type> formals = owntype.getParameterTypes();
1040         List<Type> nonInferred = sym.type.getParameterTypes();
1041         if (nonInferred.length() != formals.length()) nonInferred = formals;
1042         Type last = useVarargs ? formals.last() : null;
1043         if (sym.name == names.init && sym.owner == syms.enumSym) {
1044             formals = formals.tail.tail;
1045             nonInferred = nonInferred.tail.tail;
1046         }
1047         if ((sym.flags() & ANONCONSTR_BASED) != 0) {
1048             formals = formals.tail;
1049             nonInferred = nonInferred.tail;
1050         }
1051         List<JCExpression> args = argtrees;
1052         if (args != null) {
1053             //this is null when type-checking a method reference
1054             while (formals.head != last) {
1055                 JCTree arg = args.head;
1056                 Warner warn = convertWarner(arg.pos(), arg.type, nonInferred.head);
1057                 assertConvertible(arg, arg.type, formals.head, warn);
1058                 args = args.tail;
1059                 formals = formals.tail;
1060                 nonInferred = nonInferred.tail;
1061             }
1062             if (useVarargs) {
1063                 Type varArg = types.elemtype(last);
1064                 while (args.tail != null) {
1065                     JCTree arg = args.head;
1066                     Warner warn = convertWarner(arg.pos(), arg.type, varArg);
1067                     assertConvertible(arg, arg.type, varArg, warn);
1068                     args = args.tail;
1069                 }
1070             } else if ((sym.flags() & (VARARGS | SIGNATURE_POLYMORPHIC)) == VARARGS) {
1071                 // non-varargs call to varargs method
1072                 Type varParam = owntype.getParameterTypes().last();
1073                 Type lastArg = argtypes.last();
1074                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
1075                     !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
1076                     log.warning(argtrees.last().pos(),
1077                                 Warnings.InexactNonVarargsCall(types.elemtype(varParam),varParam));
1078             }
1079         }
1080         if (useVarargs) {
1081             Type argtype = owntype.getParameterTypes().last();
1082             if (!types.isReifiable(argtype) &&
1083                 (sym.baseSymbol().attribute(syms.trustMeType.tsym) == null ||
1084                  !isTrustMeAllowedOnMethod(sym))) {
1085                 warnUnchecked(env.tree.pos(), Warnings.UncheckedGenericArrayCreation(argtype));
1086             }
1087             TreeInfo.setVarargsElement(env.tree, types.elemtype(argtype));
1088          }
1089          return owntype;
1090     }
1091     //where
1092     private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
1093         if (types.isConvertible(actual, formal, warn))
1094             return;
1095 
1096         if (formal.isCompound()
1097             && types.isSubtype(actual, types.supertype(formal))
1098             && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
1099             return;
1100     }
1101 
1102     /**
1103      * Check that type 't' is a valid instantiation of a generic class
1104      * (see JLS 4.5)
1105      *
1106      * @param t class type to be checked
1107      * @return true if 't' is well-formed
1108      */
1109     public boolean checkValidGenericType(Type t) {
1110         return firstIncompatibleTypeArg(t) == null;
1111     }
1112     //WHERE
1113         private Type firstIncompatibleTypeArg(Type type) {
1114             List<Type> formals = type.tsym.type.allparams();
1115             List<Type> actuals = type.allparams();
1116             List<Type> args = type.getTypeArguments();
1117             List<Type> forms = type.tsym.type.getTypeArguments();
1118             ListBuffer<Type> bounds_buf = new ListBuffer<>();
1119 
1120             // For matching pairs of actual argument types `a' and
1121             // formal type parameters with declared bound `b' ...
1122             while (args.nonEmpty() && forms.nonEmpty()) {
1123                 // exact type arguments needs to know their
1124                 // bounds (for upper and lower bound
1125                 // calculations).  So we create new bounds where
1126                 // type-parameters are replaced with actuals argument types.
1127                 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
1128                 args = args.tail;
1129                 forms = forms.tail;
1130             }
1131 
1132             args = type.getTypeArguments();
1133             List<Type> tvars_cap = types.substBounds(formals,
1134                                       formals,
1135                                       types.capture(type).allparams());
1136             while (args.nonEmpty() && tvars_cap.nonEmpty()) {
1137                 // Let the actual arguments know their bound
1138                 args.head.withTypeVar((TypeVar)tvars_cap.head);
1139                 args = args.tail;
1140                 tvars_cap = tvars_cap.tail;
1141             }
1142 
1143             args = type.getTypeArguments();
1144             List<Type> bounds = bounds_buf.toList();
1145 
1146             while (args.nonEmpty() && bounds.nonEmpty()) {
1147                 Type actual = args.head;
1148                 if (!isTypeArgErroneous(actual) &&
1149                         !bounds.head.isErroneous() &&
1150                         !checkExtends(actual, bounds.head)) {
1151                     return args.head;
1152                 }
1153                 args = args.tail;
1154                 bounds = bounds.tail;
1155             }
1156 
1157             args = type.getTypeArguments();
1158             bounds = bounds_buf.toList();
1159 
1160             for (Type arg : types.capture(type).getTypeArguments()) {
1161                 if (arg.hasTag(TYPEVAR) &&
1162                         arg.getUpperBound().isErroneous() &&
1163                         !bounds.head.isErroneous() &&
1164                         !isTypeArgErroneous(args.head)) {
1165                     return args.head;
1166                 }
1167                 bounds = bounds.tail;
1168                 args = args.tail;
1169             }
1170 
1171             return null;
1172         }
1173         //where
1174         boolean isTypeArgErroneous(Type t) {
1175             return isTypeArgErroneous.visit(t);
1176         }
1177 
1178         Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
1179             public Boolean visitType(Type t, Void s) {
1180                 return t.isErroneous();
1181             }
1182             @Override
1183             public Boolean visitTypeVar(TypeVar t, Void s) {
1184                 return visit(t.getUpperBound());
1185             }
1186             @Override
1187             public Boolean visitCapturedType(CapturedType t, Void s) {
1188                 return visit(t.getUpperBound()) ||
1189                         visit(t.getLowerBound());
1190             }
1191             @Override
1192             public Boolean visitWildcardType(WildcardType t, Void s) {
1193                 return visit(t.type);
1194             }
1195         };
1196 
1197     /** Check that given modifiers are legal for given symbol and
1198      *  return modifiers together with any implicit modifiers for that symbol.
1199      *  Warning: we can't use flags() here since this method
1200      *  is called during class enter, when flags() would cause a premature
1201      *  completion.
1202      *  @param pos           Position to be used for error reporting.
1203      *  @param flags         The set of modifiers given in a definition.
1204      *  @param sym           The defined symbol.
1205      */
1206     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
1207         long mask;
1208         long implicit = 0;
1209 
1210         switch (sym.kind) {
1211         case VAR:
1212             if (TreeInfo.isReceiverParam(tree))
1213                 mask = ReceiverParamFlags;
1214             else if (sym.owner.kind != TYP)
1215                 mask = LocalVarFlags;
1216             else if ((sym.owner.flags_field & INTERFACE) != 0)
1217                 mask = implicit = InterfaceVarFlags;
1218             else
1219                 mask = VarFlags;





1220             break;
1221         case MTH:
1222             if (sym.name == names.init) {
1223                 if ((sym.owner.flags_field & ENUM) != 0) {
1224                     // enum constructors cannot be declared public or
1225                     // protected and must be implicitly or explicitly
1226                     // private
1227                     implicit = PRIVATE;
1228                     mask = PRIVATE;
1229                 } else
1230                     mask = ConstructorFlags;
1231             }  else if ((sym.owner.flags_field & INTERFACE) != 0) {
1232                 if ((sym.owner.flags_field & ANNOTATION) != 0) {
1233                     mask = AnnotationTypeElementMask;
1234                     implicit = PUBLIC | ABSTRACT;
1235                 } else if ((flags & (DEFAULT | STATIC | PRIVATE)) != 0) {
1236                     mask = InterfaceMethodMask;
1237                     implicit = (flags & PRIVATE) != 0 ? 0 : PUBLIC;
1238                     if ((flags & DEFAULT) != 0) {
1239                         implicit |= ABSTRACT;
1240                     }
1241                 } else {
1242                     mask = implicit = InterfaceMethodFlags;
1243                 }
1244             } else if ((sym.owner.flags_field & RECORD) != 0) {
1245                 mask = RecordMethodFlags;

1246             } else {
1247                 mask = MethodFlags;


1248             }
1249             if ((flags & STRICTFP) != 0) {
1250                 warnOnExplicitStrictfp(pos);
1251             }
1252             // Imply STRICTFP if owner has STRICTFP set.
1253             if (((flags|implicit) & Flags.ABSTRACT) == 0 ||
1254                 ((flags) & Flags.DEFAULT) != 0)
1255                 implicit |= sym.owner.flags_field & STRICTFP;
1256             break;
1257         case TYP:
1258             if (sym.owner.kind.matches(KindSelector.VAL_MTH) ||
1259                     (sym.isDirectlyOrIndirectlyLocal() && (flags & ANNOTATION) != 0)) {
1260                 boolean implicitlyStatic = !sym.isAnonymous() &&
1261                         ((flags & RECORD) != 0 || (flags & ENUM) != 0 || (flags & INTERFACE) != 0);
1262                 boolean staticOrImplicitlyStatic = (flags & STATIC) != 0 || implicitlyStatic;
1263                 // local statics are allowed only if records are allowed too
1264                 mask = staticOrImplicitlyStatic && allowRecords && (flags & ANNOTATION) == 0 ? StaticLocalFlags : LocalClassFlags;
1265                 implicit = implicitlyStatic ? STATIC : implicit;
1266             } else if (sym.owner.kind == TYP) {
1267                 // statics in inner classes are allowed only if records are allowed too
1268                 mask = ((flags & STATIC) != 0) && allowRecords && (flags & ANNOTATION) == 0 ? ExtendedMemberStaticClassFlags : ExtendedMemberClassFlags;
1269                 if (sym.owner.owner.kind == PCK ||
1270                     (sym.owner.flags_field & STATIC) != 0) {
1271                     mask |= STATIC;
1272                 } else if (!allowRecords && ((flags & ENUM) != 0 || (flags & RECORD) != 0)) {
1273                     log.error(pos, Errors.StaticDeclarationNotAllowedInInnerClasses);
1274                 }
1275                 // Nested interfaces and enums are always STATIC (Spec ???)
1276                 if ((flags & (INTERFACE | ENUM | RECORD)) != 0 ) implicit = STATIC;
1277             } else {
1278                 mask = ExtendedClassFlags;
1279             }
1280             // Interfaces are always ABSTRACT
1281             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
1282 




1283             if ((flags & ENUM) != 0) {
1284                 // enums can't be declared abstract, final, sealed or non-sealed
1285                 mask &= ~(ABSTRACT | FINAL | SEALED | NON_SEALED);
1286                 implicit |= implicitEnumFinalFlag(tree);
1287             }
1288             if ((flags & RECORD) != 0) {
1289                 // records can't be declared abstract
1290                 mask &= ~ABSTRACT;
1291                 implicit |= FINAL;
1292             }
1293             if ((flags & STRICTFP) != 0) {
1294                 warnOnExplicitStrictfp(pos);
1295             }
1296             // Imply STRICTFP if owner has STRICTFP set.
1297             implicit |= sym.owner.flags_field & STRICTFP;








1298             break;
1299         default:
1300             throw new AssertionError();
1301         }
1302         long illegal = flags & ExtendedStandardFlags & ~mask;
1303         if (illegal != 0) {
1304             if ((illegal & INTERFACE) != 0) {
1305                 log.error(pos, ((flags & ANNOTATION) != 0) ? Errors.AnnotationDeclNotAllowedHere : Errors.IntfNotAllowedHere);
1306                 mask |= INTERFACE;
1307             }
1308             else {
1309                 log.error(pos,
1310                         Errors.ModNotAllowedHere(asFlagSet(illegal)));
1311             }
1312         }
1313         else if ((sym.kind == TYP ||
1314                   // ISSUE: Disallowing abstract&private is no longer appropriate
1315                   // in the presence of inner classes. Should it be deleted here?
1316                   checkDisjoint(pos, flags,
1317                                 ABSTRACT,
1318                                 PRIVATE | STATIC | DEFAULT))
1319                  &&
1320                  checkDisjoint(pos, flags,
1321                                 STATIC | PRIVATE,
1322                                 DEFAULT)
1323                  &&
1324                  checkDisjoint(pos, flags,
1325                                ABSTRACT | INTERFACE,
1326                                FINAL | NATIVE | SYNCHRONIZED)
1327                  &&




1328                  checkDisjoint(pos, flags,
1329                                PUBLIC,
1330                                PRIVATE | PROTECTED)
1331                  &&
1332                  checkDisjoint(pos, flags,
1333                                PRIVATE,
1334                                PUBLIC | PROTECTED)
1335                  &&
1336                  checkDisjoint(pos, flags,
1337                                FINAL,
1338                                VOLATILE)
1339                  &&
1340                  (sym.kind == TYP ||
1341                   checkDisjoint(pos, flags,
1342                                 ABSTRACT | NATIVE,
1343                                 STRICTFP))
1344                  && checkDisjoint(pos, flags,
1345                                 FINAL,
1346                            SEALED | NON_SEALED)
1347                  && checkDisjoint(pos, flags,
1348                                 SEALED,
1349                            FINAL | NON_SEALED)
1350                  && checkDisjoint(pos, flags,
1351                                 SEALED,
1352                                 ANNOTATION)) {









1353             // skip
1354         }
1355         return flags & (mask | ~ExtendedStandardFlags) | implicit;
1356     }
1357 
1358     private void warnOnExplicitStrictfp(DiagnosticPosition pos) {
1359         DiagnosticPosition prevLintPos = deferredLintHandler.setPos(pos);
1360         try {
1361             deferredLintHandler.report(() -> {
1362                                            if (lint.isEnabled(LintCategory.STRICTFP)) {
1363                                                log.warning(LintCategory.STRICTFP,
1364                                                            pos, Warnings.Strictfp); }
1365                                        });
1366         } finally {
1367             deferredLintHandler.setPos(prevLintPos);
1368         }
1369     }
1370 
1371 
1372     /** Determine if this enum should be implicitly final.
1373      *
1374      *  If the enum has no specialized enum constants, it is final.
1375      *
1376      *  If the enum does have specialized enum constants, it is
1377      *  <i>not</i> final.
1378      */
1379     private long implicitEnumFinalFlag(JCTree tree) {
1380         if (!tree.hasTag(CLASSDEF)) return 0;
1381         class SpecialTreeVisitor extends JCTree.Visitor {
1382             boolean specialized;
1383             SpecialTreeVisitor() {
1384                 this.specialized = false;
1385             }
1386 
1387             @Override
1388             public void visitTree(JCTree tree) { /* no-op */ }
1389 
1390             @Override
1391             public void visitVarDef(JCVariableDecl tree) {
1392                 if ((tree.mods.flags & ENUM) != 0) {
1393                     if (tree.init instanceof JCNewClass newClass && newClass.def != null) {
1394                         specialized = true;
1395                     }
1396                 }
1397             }
1398         }
1399 
1400         SpecialTreeVisitor sts = new SpecialTreeVisitor();
1401         JCClassDecl cdef = (JCClassDecl) tree;
1402         for (JCTree defs: cdef.defs) {
1403             defs.accept(sts);
1404             if (sts.specialized) return allowSealed ? SEALED : 0;
1405         }
1406         return FINAL;
1407     }
1408 
1409 /* *************************************************************************
1410  * Type Validation
1411  **************************************************************************/
1412 
1413     /** Validate a type expression. That is,
1414      *  check that all type arguments of a parametric type are within
1415      *  their bounds. This must be done in a second phase after type attribution
1416      *  since a class might have a subclass as type parameter bound. E.g:
1417      *
1418      *  <pre>{@code
1419      *  class B<A extends C> { ... }
1420      *  class C extends B<C> { ... }
1421      *  }</pre>
1422      *
1423      *  and we can't make sure that the bound is already attributed because
1424      *  of possible cycles.
1425      *
1426      * Visitor method: Validate a type expression, if it is not null, catching
1427      *  and reporting any completion failures.
1428      */
1429     void validate(JCTree tree, Env<AttrContext> env) {
1430         validate(tree, env, true);
1431     }
1432     void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
1433         new Validator(env).validateTree(tree, checkRaw, true);
1434     }
1435 
1436     /** Visitor method: Validate a list of type expressions.
1437      */
1438     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
1439         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1440             validate(l.head, env);
1441     }
1442 
1443     /** A visitor class for type validation.
1444      */
1445     class Validator extends JCTree.Visitor {
1446 
1447         boolean checkRaw;
1448         boolean isOuter;
1449         Env<AttrContext> env;
1450 
1451         Validator(Env<AttrContext> env) {
1452             this.env = env;
1453         }
1454 
1455         @Override
1456         public void visitTypeArray(JCArrayTypeTree tree) {
1457             validateTree(tree.elemtype, checkRaw, isOuter);
1458         }
1459 
1460         @Override
1461         public void visitTypeApply(JCTypeApply tree) {
1462             if (tree.type.hasTag(CLASS)) {
1463                 List<JCExpression> args = tree.arguments;
1464                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
1465 
1466                 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
1467                 if (incompatibleArg != null) {
1468                     for (JCTree arg : tree.arguments) {
1469                         if (arg.type == incompatibleArg) {
1470                             log.error(arg, Errors.NotWithinBounds(incompatibleArg, forms.head));
1471                         }
1472                         forms = forms.tail;
1473                      }
1474                  }
1475 
1476                 forms = tree.type.tsym.type.getTypeArguments();
1477 
1478                 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
1479 
1480                 // For matching pairs of actual argument types `a' and
1481                 // formal type parameters with declared bound `b' ...
1482                 while (args.nonEmpty() && forms.nonEmpty()) {
1483                     validateTree(args.head,
1484                             !(isOuter && is_java_lang_Class),
1485                             false);
1486                     args = args.tail;
1487                     forms = forms.tail;
1488                 }
1489 
1490                 // Check that this type is either fully parameterized, or
1491                 // not parameterized at all.
1492                 if (tree.type.getEnclosingType().isRaw())
1493                     log.error(tree.pos(), Errors.ImproperlyFormedTypeInnerRawParam);
1494                 if (tree.clazz.hasTag(SELECT))
1495                     visitSelectInternal((JCFieldAccess)tree.clazz);
1496             }
1497         }
1498 
1499         @Override
1500         public void visitTypeParameter(JCTypeParameter tree) {
1501             validateTrees(tree.bounds, true, isOuter);
1502             checkClassBounds(tree.pos(), tree.type);
1503         }
1504 
1505         @Override
1506         public void visitWildcard(JCWildcard tree) {
1507             if (tree.inner != null)
1508                 validateTree(tree.inner, true, isOuter);
1509         }
1510 
1511         @Override
1512         public void visitSelect(JCFieldAccess tree) {
1513             if (tree.type.hasTag(CLASS)) {
1514                 visitSelectInternal(tree);
1515 
1516                 // Check that this type is either fully parameterized, or
1517                 // not parameterized at all.
1518                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1519                     log.error(tree.pos(), Errors.ImproperlyFormedTypeParamMissing);
1520             }
1521         }
1522 
1523         public void visitSelectInternal(JCFieldAccess tree) {
1524             if (tree.type.tsym.isStatic() &&
1525                 tree.selected.type.isParameterized()) {
1526                 // The enclosing type is not a class, so we are
1527                 // looking at a static member type.  However, the
1528                 // qualifying expression is parameterized.
1529                 log.error(tree.pos(), Errors.CantSelectStaticClassFromParamType);
1530             } else {
1531                 // otherwise validate the rest of the expression
1532                 tree.selected.accept(this);
1533             }
1534         }
1535 
1536         @Override
1537         public void visitAnnotatedType(JCAnnotatedType tree) {
1538             tree.underlyingType.accept(this);
1539         }
1540 
1541         @Override
1542         public void visitTypeIdent(JCPrimitiveTypeTree that) {
1543             if (that.type.hasTag(TypeTag.VOID)) {
1544                 log.error(that.pos(), Errors.VoidNotAllowedHere);
1545             }
1546             super.visitTypeIdent(that);
1547         }
1548 
1549         /** Default visitor method: do nothing.
1550          */
1551         @Override
1552         public void visitTree(JCTree tree) {
1553         }
1554 
1555         public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
1556             if (tree != null) {
1557                 boolean prevCheckRaw = this.checkRaw;
1558                 this.checkRaw = checkRaw;
1559                 this.isOuter = isOuter;
1560 
1561                 try {
1562                     tree.accept(this);
1563                     if (checkRaw)
1564                         checkRaw(tree, env);
1565                 } catch (CompletionFailure ex) {
1566                     completionError(tree.pos(), ex);
1567                 } finally {
1568                     this.checkRaw = prevCheckRaw;
1569                 }
1570             }
1571         }
1572 
1573         public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1574             for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1575                 validateTree(l.head, checkRaw, isOuter);
1576         }
1577     }
1578 
1579     void checkRaw(JCTree tree, Env<AttrContext> env) {
1580         if (lint.isEnabled(LintCategory.RAW) &&
1581             tree.type.hasTag(CLASS) &&
1582             !TreeInfo.isDiamond(tree) &&
1583             !withinAnonConstr(env) &&
1584             tree.type.isRaw()) {
1585             log.warning(LintCategory.RAW,
1586                     tree.pos(), Warnings.RawClassUse(tree.type, tree.type.tsym.type));
1587         }
1588     }
1589     //where
1590         private boolean withinAnonConstr(Env<AttrContext> env) {
1591             return env.enclClass.name.isEmpty() &&
1592                     env.enclMethod != null && env.enclMethod.name == names.init;
1593         }
1594 
1595 /* *************************************************************************
1596  * Exception checking
1597  **************************************************************************/
1598 
1599     /* The following methods treat classes as sets that contain
1600      * the class itself and all their subclasses
1601      */
1602 
1603     /** Is given type a subtype of some of the types in given list?
1604      */
1605     boolean subset(Type t, List<Type> ts) {
1606         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1607             if (types.isSubtype(t, l.head)) return true;
1608         return false;
1609     }
1610 
1611     /** Is given type a subtype or supertype of
1612      *  some of the types in given list?
1613      */
1614     boolean intersects(Type t, List<Type> ts) {
1615         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1616             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
1617         return false;
1618     }
1619 
1620     /** Add type set to given type list, unless it is a subclass of some class
1621      *  in the list.
1622      */
1623     List<Type> incl(Type t, List<Type> ts) {
1624         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
1625     }
1626 
1627     /** Remove type set from type set list.
1628      */
1629     List<Type> excl(Type t, List<Type> ts) {
1630         if (ts.isEmpty()) {
1631             return ts;
1632         } else {
1633             List<Type> ts1 = excl(t, ts.tail);
1634             if (types.isSubtype(ts.head, t)) return ts1;
1635             else if (ts1 == ts.tail) return ts;
1636             else return ts1.prepend(ts.head);
1637         }
1638     }
1639 
1640     /** Form the union of two type set lists.
1641      */
1642     List<Type> union(List<Type> ts1, List<Type> ts2) {
1643         List<Type> ts = ts1;
1644         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1645             ts = incl(l.head, ts);
1646         return ts;
1647     }
1648 
1649     /** Form the difference of two type lists.
1650      */
1651     List<Type> diff(List<Type> ts1, List<Type> ts2) {
1652         List<Type> ts = ts1;
1653         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1654             ts = excl(l.head, ts);
1655         return ts;
1656     }
1657 
1658     /** Form the intersection of two type lists.
1659      */
1660     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
1661         List<Type> ts = List.nil();
1662         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
1663             if (subset(l.head, ts2)) ts = incl(l.head, ts);
1664         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1665             if (subset(l.head, ts1)) ts = incl(l.head, ts);
1666         return ts;
1667     }
1668 
1669     /** Is exc an exception symbol that need not be declared?
1670      */
1671     boolean isUnchecked(ClassSymbol exc) {
1672         return
1673             exc.kind == ERR ||
1674             exc.isSubClass(syms.errorType.tsym, types) ||
1675             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1676     }
1677 
1678     /** Is exc an exception type that need not be declared?
1679      */
1680     boolean isUnchecked(Type exc) {
1681         return
1682             (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) :
1683             (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) :
1684             exc.hasTag(BOT);
1685     }
1686 
1687     boolean isChecked(Type exc) {
1688         return !isUnchecked(exc);
1689     }
1690 
1691     /** Same, but handling completion failures.
1692      */
1693     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1694         try {
1695             return isUnchecked(exc);
1696         } catch (CompletionFailure ex) {
1697             completionError(pos, ex);
1698             return true;
1699         }
1700     }
1701 
1702     /** Is exc handled by given exception list?
1703      */
1704     boolean isHandled(Type exc, List<Type> handled) {
1705         return isUnchecked(exc) || subset(exc, handled);
1706     }
1707 
1708     /** Return all exceptions in thrown list that are not in handled list.
1709      *  @param thrown     The list of thrown exceptions.
1710      *  @param handled    The list of handled exceptions.
1711      */
1712     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
1713         List<Type> unhandled = List.nil();
1714         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1715             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1716         return unhandled;
1717     }
1718 
1719 /* *************************************************************************
1720  * Overriding/Implementation checking
1721  **************************************************************************/
1722 
1723     /** The level of access protection given by a flag set,
1724      *  where PRIVATE is highest and PUBLIC is lowest.
1725      */
1726     static int protection(long flags) {
1727         switch ((short)(flags & AccessFlags)) {
1728         case PRIVATE: return 3;
1729         case PROTECTED: return 1;
1730         default:
1731         case PUBLIC: return 0;
1732         case 0: return 2;
1733         }
1734     }
1735 
1736     /** A customized "cannot override" error message.
1737      *  @param m      The overriding method.
1738      *  @param other  The overridden method.
1739      *  @return       An internationalized string.
1740      */
1741     Fragment cannotOverride(MethodSymbol m, MethodSymbol other) {
1742         Symbol mloc = m.location();
1743         Symbol oloc = other.location();
1744 
1745         if ((other.owner.flags() & INTERFACE) == 0)
1746             return Fragments.CantOverride(m, mloc, other, oloc);
1747         else if ((m.owner.flags() & INTERFACE) == 0)
1748             return Fragments.CantImplement(m, mloc, other, oloc);
1749         else
1750             return Fragments.ClashesWith(m, mloc, other, oloc);
1751     }
1752 
1753     /** A customized "override" warning message.
1754      *  @param m      The overriding method.
1755      *  @param other  The overridden method.
1756      *  @return       An internationalized string.
1757      */
1758     Fragment uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1759         Symbol mloc = m.location();
1760         Symbol oloc = other.location();
1761 
1762         if ((other.owner.flags() & INTERFACE) == 0)
1763             return Fragments.UncheckedOverride(m, mloc, other, oloc);
1764         else if ((m.owner.flags() & INTERFACE) == 0)
1765             return Fragments.UncheckedImplement(m, mloc, other, oloc);
1766         else
1767             return Fragments.UncheckedClashWith(m, mloc, other, oloc);
1768     }
1769 
1770     /** A customized "override" warning message.
1771      *  @param m      The overriding method.
1772      *  @param other  The overridden method.
1773      *  @return       An internationalized string.
1774      */
1775     Fragment varargsOverrides(MethodSymbol m, MethodSymbol other) {
1776         Symbol mloc = m.location();
1777         Symbol oloc = other.location();
1778 
1779         if ((other.owner.flags() & INTERFACE) == 0)
1780             return Fragments.VarargsOverride(m, mloc, other, oloc);
1781         else  if ((m.owner.flags() & INTERFACE) == 0)
1782             return Fragments.VarargsImplement(m, mloc, other, oloc);
1783         else
1784             return Fragments.VarargsClashWith(m, mloc, other, oloc);
1785     }
1786 
1787     /** Check that this method conforms with overridden method 'other'.
1788      *  where `origin' is the class where checking started.
1789      *  Complications:
1790      *  (1) Do not check overriding of synthetic methods
1791      *      (reason: they might be final).
1792      *      todo: check whether this is still necessary.
1793      *  (2) Admit the case where an interface proxy throws fewer exceptions
1794      *      than the method it implements. Augment the proxy methods with the
1795      *      undeclared exceptions in this case.
1796      *  (3) When generics are enabled, admit the case where an interface proxy
1797      *      has a result type
1798      *      extended by the result type of the method it implements.
1799      *      Change the proxies result type to the smaller type in this case.
1800      *
1801      *  @param tree         The tree from which positions
1802      *                      are extracted for errors.
1803      *  @param m            The overriding method.
1804      *  @param other        The overridden method.
1805      *  @param origin       The class of which the overriding method
1806      *                      is a member.
1807      */
1808     void checkOverride(JCTree tree,
1809                        MethodSymbol m,
1810                        MethodSymbol other,
1811                        ClassSymbol origin) {
1812         // Don't check overriding of synthetic methods or by bridge methods.
1813         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1814             return;
1815         }
1816 
1817         // Error if static method overrides instance method (JLS 8.4.8.2).
1818         if ((m.flags() & STATIC) != 0 &&
1819                    (other.flags() & STATIC) == 0) {
1820             log.error(TreeInfo.diagnosticPositionFor(m, tree),
1821                       Errors.OverrideStatic(cannotOverride(m, other)));
1822             m.flags_field |= BAD_OVERRIDE;
1823             return;
1824         }
1825 
1826         // Error if instance method overrides static or final
1827         // method (JLS 8.4.8.1).
1828         if ((other.flags() & FINAL) != 0 ||
1829                  (m.flags() & STATIC) == 0 &&
1830                  (other.flags() & STATIC) != 0) {
1831             log.error(TreeInfo.diagnosticPositionFor(m, tree),
1832                       Errors.OverrideMeth(cannotOverride(m, other),
1833                                           asFlagSet(other.flags() & (FINAL | STATIC))));
1834             m.flags_field |= BAD_OVERRIDE;
1835             return;
1836         }
1837 
1838         if ((m.owner.flags() & ANNOTATION) != 0) {
1839             // handled in validateAnnotationMethod
1840             return;
1841         }
1842 
1843         // Error if overriding method has weaker access (JLS 8.4.8.3).
1844         if (protection(m.flags()) > protection(other.flags())) {
1845             log.error(TreeInfo.diagnosticPositionFor(m, tree),
1846                       (other.flags() & AccessFlags) == 0 ?
1847                               Errors.OverrideWeakerAccess(cannotOverride(m, other),
1848                                                           "package") :
1849                               Errors.OverrideWeakerAccess(cannotOverride(m, other),
1850                                                           asFlagSet(other.flags() & AccessFlags)));
1851             m.flags_field |= BAD_OVERRIDE;
1852             return;
1853         }
1854 
1855         if (shouldCheckPreview(m, other, origin)) {
1856             checkPreview(tree.pos(), m, other);
1857         }
1858 
1859         Type mt = types.memberType(origin.type, m);
1860         Type ot = types.memberType(origin.type, other);
1861         // Error if overriding result type is different
1862         // (or, in the case of generics mode, not a subtype) of
1863         // overridden result type. We have to rename any type parameters
1864         // before comparing types.
1865         List<Type> mtvars = mt.getTypeArguments();
1866         List<Type> otvars = ot.getTypeArguments();
1867         Type mtres = mt.getReturnType();
1868         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1869 
1870         overrideWarner.clear();
1871         boolean resultTypesOK =
1872             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1873         if (!resultTypesOK) {
1874             if ((m.flags() & STATIC) != 0 && (other.flags() & STATIC) != 0) {
1875                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1876                           Errors.OverrideIncompatibleRet(Fragments.CantHide(m, m.location(), other,
1877                                         other.location()), mtres, otres));
1878                 m.flags_field |= BAD_OVERRIDE;
1879             } else {
1880                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1881                           Errors.OverrideIncompatibleRet(cannotOverride(m, other), mtres, otres));
1882                 m.flags_field |= BAD_OVERRIDE;
1883             }
1884             return;
1885         } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
1886             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1887                     Warnings.OverrideUncheckedRet(uncheckedOverrides(m, other), mtres, otres));
1888         }
1889 
1890         // Error if overriding method throws an exception not reported
1891         // by overridden method.
1892         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1893         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1894         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1895         if (unhandledErased.nonEmpty()) {
1896             log.error(TreeInfo.diagnosticPositionFor(m, tree),
1897                       Errors.OverrideMethDoesntThrow(cannotOverride(m, other), unhandledUnerased.head));
1898             m.flags_field |= BAD_OVERRIDE;
1899             return;
1900         }
1901         else if (unhandledUnerased.nonEmpty()) {
1902             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1903                           Warnings.OverrideUncheckedThrown(cannotOverride(m, other), unhandledUnerased.head));
1904             return;
1905         }
1906 
1907         // Optional warning if varargs don't agree
1908         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1909             && lint.isEnabled(LintCategory.OVERRIDES)) {
1910             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1911                         ((m.flags() & Flags.VARARGS) != 0)
1912                         ? Warnings.OverrideVarargsMissing(varargsOverrides(m, other))
1913                         : Warnings.OverrideVarargsExtra(varargsOverrides(m, other)));
1914         }
1915 
1916         // Warn if instance method overrides bridge method (compiler spec ??)
1917         if ((other.flags() & BRIDGE) != 0) {
1918             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1919                         Warnings.OverrideBridge(uncheckedOverrides(m, other)));
1920         }
1921 
1922         // Warn if a deprecated method overridden by a non-deprecated one.
1923         if (!isDeprecatedOverrideIgnorable(other, origin)) {
1924             Lint prevLint = setLint(lint.augment(m));
1925             try {
1926                 checkDeprecated(() -> TreeInfo.diagnosticPositionFor(m, tree), m, other);
1927             } finally {
1928                 setLint(prevLint);
1929             }
1930         }
1931     }
1932     // where
1933         private boolean shouldCheckPreview(MethodSymbol m, MethodSymbol other, ClassSymbol origin) {
1934             if (m.owner != origin ||
1935                 //performance - only do the expensive checks when the overridden method is a Preview API:
1936                 (other.flags() & PREVIEW_API) == 0) {
1937                 return false;
1938             }
1939 
1940             for (Symbol s : types.membersClosure(origin.type, false).getSymbolsByName(m.name)) {
1941                 if (m != s && m.overrides(s, origin, types, false)) {
1942                     //only produce preview warnings or errors if "m" immediatelly overrides "other"
1943                     //without intermediate overriding methods:
1944                     return s == other;
1945                 }
1946             }
1947 
1948             return false;
1949         }
1950         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1951             // If the method, m, is defined in an interface, then ignore the issue if the method
1952             // is only inherited via a supertype and also implemented in the supertype,
1953             // because in that case, we will rediscover the issue when examining the method
1954             // in the supertype.
1955             // If the method, m, is not defined in an interface, then the only time we need to
1956             // address the issue is when the method is the supertype implementation: any other
1957             // case, we will have dealt with when examining the supertype classes
1958             ClassSymbol mc = m.enclClass();
1959             Type st = types.supertype(origin.type);
1960             if (!st.hasTag(CLASS))
1961                 return true;
1962             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1963 
1964             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1965                 List<Type> intfs = types.interfaces(origin.type);
1966                 return (intfs.contains(mc.type) ? false : (stimpl != null));
1967             }
1968             else
1969                 return (stimpl != m);
1970         }
1971 
1972 
1973     // used to check if there were any unchecked conversions
1974     Warner overrideWarner = new Warner();
1975 
1976     /** Check that a class does not inherit two concrete methods
1977      *  with the same signature.
1978      *  @param pos          Position to be used for error reporting.
1979      *  @param site         The class type to be checked.
1980      */
1981     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1982         Type sup = types.supertype(site);
1983         if (!sup.hasTag(CLASS)) return;
1984 
1985         for (Type t1 = sup;
1986              t1.hasTag(CLASS) && t1.tsym.type.isParameterized();
1987              t1 = types.supertype(t1)) {
1988             for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) {
1989                 if (s1.kind != MTH ||
1990                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1991                     !s1.isInheritedIn(site.tsym, types) ||
1992                     ((MethodSymbol)s1).implementation(site.tsym,
1993                                                       types,
1994                                                       true) != s1)
1995                     continue;
1996                 Type st1 = types.memberType(t1, s1);
1997                 int s1ArgsLength = st1.getParameterTypes().length();
1998                 if (st1 == s1.type) continue;
1999 
2000                 for (Type t2 = sup;
2001                      t2.hasTag(CLASS);
2002                      t2 = types.supertype(t2)) {
2003                     for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) {
2004                         if (s2 == s1 ||
2005                             s2.kind != MTH ||
2006                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
2007                             s2.type.getParameterTypes().length() != s1ArgsLength ||
2008                             !s2.isInheritedIn(site.tsym, types) ||
2009                             ((MethodSymbol)s2).implementation(site.tsym,
2010                                                               types,
2011                                                               true) != s2)
2012                             continue;
2013                         Type st2 = types.memberType(t2, s2);
2014                         if (types.overrideEquivalent(st1, st2))
2015                             log.error(pos,
2016                                       Errors.ConcreteInheritanceConflict(s1, t1, s2, t2, sup));
2017                     }
2018                 }
2019             }
2020         }
2021     }
2022 
2023     /** Check that classes (or interfaces) do not each define an abstract
2024      *  method with same name and arguments but incompatible return types.
2025      *  @param pos          Position to be used for error reporting.
2026      *  @param t1           The first argument type.
2027      *  @param t2           The second argument type.
2028      */
2029     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
2030                                             Type t1,
2031                                             Type t2,
2032                                             Type site) {
2033         if ((site.tsym.flags() & COMPOUND) != 0) {
2034             // special case for intersections: need to eliminate wildcards in supertypes
2035             t1 = types.capture(t1);
2036             t2 = types.capture(t2);
2037         }
2038         return firstIncompatibility(pos, t1, t2, site) == null;
2039     }
2040 
2041     /** Return the first method which is defined with same args
2042      *  but different return types in two given interfaces, or null if none
2043      *  exists.
2044      *  @param t1     The first type.
2045      *  @param t2     The second type.
2046      *  @param site   The most derived type.
2047      *  @return symbol from t2 that conflicts with one in t1.
2048      */
2049     private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
2050         Map<TypeSymbol,Type> interfaces1 = new HashMap<>();
2051         closure(t1, interfaces1);
2052         Map<TypeSymbol,Type> interfaces2;
2053         if (t1 == t2)
2054             interfaces2 = interfaces1;
2055         else
2056             closure(t2, interfaces1, interfaces2 = new HashMap<>());
2057 
2058         for (Type t3 : interfaces1.values()) {
2059             for (Type t4 : interfaces2.values()) {
2060                 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
2061                 if (s != null) return s;
2062             }
2063         }
2064         return null;
2065     }
2066 
2067     /** Compute all the supertypes of t, indexed by type symbol. */
2068     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
2069         if (!t.hasTag(CLASS)) return;
2070         if (typeMap.put(t.tsym, t) == null) {
2071             closure(types.supertype(t), typeMap);
2072             for (Type i : types.interfaces(t))
2073                 closure(i, typeMap);
2074         }
2075     }
2076 
2077     /** Compute all the supertypes of t, indexed by type symbol (except those in typesSkip). */
2078     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
2079         if (!t.hasTag(CLASS)) return;
2080         if (typesSkip.get(t.tsym) != null) return;
2081         if (typeMap.put(t.tsym, t) == null) {
2082             closure(types.supertype(t), typesSkip, typeMap);
2083             for (Type i : types.interfaces(t))
2084                 closure(i, typesSkip, typeMap);
2085         }
2086     }
2087 
2088     /** Return the first method in t2 that conflicts with a method from t1. */
2089     private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
2090         for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) {
2091             Type st1 = null;
2092             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
2093                     (s1.flags() & SYNTHETIC) != 0) continue;
2094             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
2095             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
2096             for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) {
2097                 if (s1 == s2) continue;
2098                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
2099                         (s2.flags() & SYNTHETIC) != 0) continue;
2100                 if (st1 == null) st1 = types.memberType(t1, s1);
2101                 Type st2 = types.memberType(t2, s2);
2102                 if (types.overrideEquivalent(st1, st2)) {
2103                     List<Type> tvars1 = st1.getTypeArguments();
2104                     List<Type> tvars2 = st2.getTypeArguments();
2105                     Type rt1 = st1.getReturnType();
2106                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
2107                     boolean compat =
2108                         types.isSameType(rt1, rt2) ||
2109                         !rt1.isPrimitiveOrVoid() &&
2110                         !rt2.isPrimitiveOrVoid() &&
2111                         (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
2112                          types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
2113                          checkCommonOverriderIn(s1,s2,site);
2114                     if (!compat) {
2115                         if (types.isSameType(t1, t2)) {
2116                             log.error(pos, Errors.IncompatibleDiffRetSameType(t1,
2117                                     s2.name, types.memberType(t2, s2).getParameterTypes()));
2118                         } else {
2119                             log.error(pos, Errors.TypesIncompatible(t1, t2,
2120                                     Fragments.IncompatibleDiffRet(s2.name, types.memberType(t2, s2).getParameterTypes())));
2121                         }
2122                         return s2;
2123                     }
2124                 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
2125                         !checkCommonOverriderIn(s1, s2, site)) {
2126                     log.error(pos, Errors.NameClashSameErasureNoOverride(
2127                             s1.name, types.memberType(site, s1).asMethodType().getParameterTypes(), s1.location(),
2128                             s2.name, types.memberType(site, s2).asMethodType().getParameterTypes(), s2.location()));
2129                     return s2;
2130                 }
2131             }
2132         }
2133         return null;
2134     }
2135     //WHERE
2136     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
2137         Map<TypeSymbol,Type> supertypes = new HashMap<>();
2138         Type st1 = types.memberType(site, s1);
2139         Type st2 = types.memberType(site, s2);
2140         closure(site, supertypes);
2141         for (Type t : supertypes.values()) {
2142             for (Symbol s3 : t.tsym.members().getSymbolsByName(s1.name)) {
2143                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
2144                 Type st3 = types.memberType(site,s3);
2145                 if (types.overrideEquivalent(st3, st1) &&
2146                         types.overrideEquivalent(st3, st2) &&
2147                         types.returnTypeSubstitutable(st3, st1) &&
2148                         types.returnTypeSubstitutable(st3, st2)) {
2149                     return true;
2150                 }
2151             }
2152         }
2153         return false;
2154     }
2155 
2156     /** Check that a given method conforms with any method it overrides.
2157      *  @param tree         The tree from which positions are extracted
2158      *                      for errors.
2159      *  @param m            The overriding method.
2160      */
2161     void checkOverride(Env<AttrContext> env, JCMethodDecl tree, MethodSymbol m) {
2162         ClassSymbol origin = (ClassSymbol)m.owner;
2163         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name)) {
2164             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
2165                 log.error(tree.pos(), Errors.EnumNoFinalize);
2166                 return;
2167             }
2168         }
2169         if (allowRecords && origin.isRecord()) {
2170             // let's find out if this is a user defined accessor in which case the @Override annotation is acceptable
2171             Optional<? extends RecordComponent> recordComponent = origin.getRecordComponents().stream()
2172                     .filter(rc -> rc.accessor == tree.sym && (rc.accessor.flags_field & GENERATED_MEMBER) == 0).findFirst();
2173             if (recordComponent.isPresent()) {
2174                 return;
2175             }
2176         }
2177 
2178         for (Type t = origin.type; t.hasTag(CLASS);
2179              t = types.supertype(t)) {
2180             if (t != origin.type) {
2181                 checkOverride(tree, t, origin, m);
2182             }
2183             for (Type t2 : types.interfaces(t)) {
2184                 checkOverride(tree, t2, origin, m);
2185             }
2186         }
2187 
2188         final boolean explicitOverride = m.attribute(syms.overrideType.tsym) != null;
2189         // Check if this method must override a super method due to being annotated with @Override
2190         // or by virtue of being a member of a diamond inferred anonymous class. Latter case is to
2191         // be treated "as if as they were annotated" with @Override.
2192         boolean mustOverride = explicitOverride ||
2193                 (env.info.isAnonymousDiamond && !m.isConstructor() && !m.isPrivate());
2194         if (mustOverride && !isOverrider(m)) {
2195             DiagnosticPosition pos = tree.pos();
2196             for (JCAnnotation a : tree.getModifiers().annotations) {
2197                 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2198                     pos = a.pos();
2199                     break;
2200                 }
2201             }
2202             log.error(pos,
2203                       explicitOverride ? (m.isStatic() ? Errors.StaticMethodsCannotBeAnnotatedWithOverride : Errors.MethodDoesNotOverrideSuperclass) :
2204                                 Errors.AnonymousDiamondMethodDoesNotOverrideSuperclass(Fragments.DiamondAnonymousMethodsImplicitlyOverride));
2205         }
2206     }
2207 
2208     void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
2209         TypeSymbol c = site.tsym;
2210         for (Symbol sym : c.members().getSymbolsByName(m.name)) {
2211             if (m.overrides(sym, origin, types, false)) {
2212                 if ((sym.flags() & ABSTRACT) == 0) {
2213                     checkOverride(tree, m, (MethodSymbol)sym, origin);
2214                 }
2215             }
2216         }
2217     }
2218 
2219     private Predicate<Symbol> equalsHasCodeFilter = s -> MethodSymbol.implementation_filter.test(s) &&
2220             (s.flags() & BAD_OVERRIDE) == 0;
2221 
2222     public void checkClassOverrideEqualsAndHashIfNeeded(DiagnosticPosition pos,
2223             ClassSymbol someClass) {
2224         /* At present, annotations cannot possibly have a method that is override
2225          * equivalent with Object.equals(Object) but in any case the condition is
2226          * fine for completeness.
2227          */
2228         if (someClass == (ClassSymbol)syms.objectType.tsym ||
2229             someClass.isInterface() || someClass.isEnum() ||
2230             (someClass.flags() & ANNOTATION) != 0 ||
2231             (someClass.flags() & ABSTRACT) != 0) return;
2232         //anonymous inner classes implementing interfaces need especial treatment
2233         if (someClass.isAnonymous()) {
2234             List<Type> interfaces =  types.interfaces(someClass.type);
2235             if (interfaces != null && !interfaces.isEmpty() &&
2236                 interfaces.head.tsym == syms.comparatorType.tsym) return;
2237         }
2238         checkClassOverrideEqualsAndHash(pos, someClass);
2239     }
2240 
2241     private void checkClassOverrideEqualsAndHash(DiagnosticPosition pos,
2242             ClassSymbol someClass) {
2243         if (lint.isEnabled(LintCategory.OVERRIDES)) {
2244             MethodSymbol equalsAtObject = (MethodSymbol)syms.objectType
2245                     .tsym.members().findFirst(names.equals);
2246             MethodSymbol hashCodeAtObject = (MethodSymbol)syms.objectType
2247                     .tsym.members().findFirst(names.hashCode);
2248             MethodSymbol equalsImpl = types.implementation(equalsAtObject,
2249                     someClass, false, equalsHasCodeFilter);
2250             boolean overridesEquals = equalsImpl != null &&
2251                                       equalsImpl.owner == someClass;
2252             boolean overridesHashCode = types.implementation(hashCodeAtObject,
2253                 someClass, false, equalsHasCodeFilter) != hashCodeAtObject;
2254 
2255             if (overridesEquals && !overridesHashCode) {
2256                 log.warning(LintCategory.OVERRIDES, pos,
2257                             Warnings.OverrideEqualsButNotHashcode(someClass));
2258             }
2259         }
2260     }
2261 
2262     public void checkHasMain(DiagnosticPosition pos, ClassSymbol c) {
2263         boolean found = false;
2264 
2265         for (Symbol sym : c.members().getSymbolsByName(names.main)) {
2266             if (sym.kind == MTH && (sym.flags() & PRIVATE) == 0) {
2267                 MethodSymbol meth = (MethodSymbol)sym;
2268                 if (!types.isSameType(meth.getReturnType(), syms.voidType)) {
2269                     continue;
2270                 }
2271                 if (meth.params.isEmpty()) {
2272                     found = true;
2273                     break;
2274                 }
2275                 if (meth.params.size() != 1) {
2276                     continue;
2277                 }
2278                 if (!types.isSameType(meth.params.head.type, types.makeArrayType(syms.stringType))) {
2279                     continue;
2280                 }
2281 
2282                 found = true;
2283                 break;
2284             }
2285         }
2286 
2287         if (!found) {
2288             log.error(pos, Errors.UnnamedClassDoesNotHaveMainMethod);
2289         }
2290     }
2291 
2292     public void checkModuleName (JCModuleDecl tree) {
2293         Name moduleName = tree.sym.name;
2294         Assert.checkNonNull(moduleName);
2295         if (lint.isEnabled(LintCategory.MODULE)) {
2296             JCExpression qualId = tree.qualId;
2297             while (qualId != null) {
2298                 Name componentName;
2299                 DiagnosticPosition pos;
2300                 switch (qualId.getTag()) {
2301                     case SELECT:
2302                         JCFieldAccess selectNode = ((JCFieldAccess) qualId);
2303                         componentName = selectNode.name;
2304                         pos = selectNode.pos();
2305                         qualId = selectNode.selected;
2306                         break;
2307                     case IDENT:
2308                         componentName = ((JCIdent) qualId).name;
2309                         pos = qualId.pos();
2310                         qualId = null;
2311                         break;
2312                     default:
2313                         throw new AssertionError("Unexpected qualified identifier: " + qualId.toString());
2314                 }
2315                 if (componentName != null) {
2316                     String moduleNameComponentString = componentName.toString();
2317                     int nameLength = moduleNameComponentString.length();
2318                     if (nameLength > 0 && Character.isDigit(moduleNameComponentString.charAt(nameLength - 1))) {
2319                         log.warning(Lint.LintCategory.MODULE, pos, Warnings.PoorChoiceForModuleName(componentName));
2320                     }
2321                 }
2322             }
2323         }
2324     }
2325 
2326     private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
2327         ClashFilter cf = new ClashFilter(origin.type);
2328         return (cf.test(s1) &&
2329                 cf.test(s2) &&
2330                 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
2331     }
2332 
2333 
2334     /** Check that all abstract members of given class have definitions.
2335      *  @param pos          Position to be used for error reporting.
2336      *  @param c            The class.
2337      */
2338     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
2339         MethodSymbol undef = types.firstUnimplementedAbstract(c);
2340         if (undef != null) {
2341             MethodSymbol undef1 =
2342                 new MethodSymbol(undef.flags(), undef.name,
2343                                  types.memberType(c.type, undef), undef.owner);
2344             log.error(pos,
2345                       Errors.DoesNotOverrideAbstract(c, undef1, undef1.location()));
2346         }
2347     }
2348 
2349     void checkNonCyclicDecl(JCClassDecl tree) {
2350         CycleChecker cc = new CycleChecker();
2351         cc.scan(tree);
2352         if (!cc.errorFound && !cc.partialCheck) {
2353             tree.sym.flags_field |= ACYCLIC;
2354         }
2355     }
2356 
2357     class CycleChecker extends TreeScanner {
2358 
2359         Set<Symbol> seenClasses = new HashSet<>();
2360         boolean errorFound = false;
2361         boolean partialCheck = false;
2362 
2363         private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
2364             if (sym != null && sym.kind == TYP) {
2365                 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
2366                 if (classEnv != null) {
2367                     DiagnosticSource prevSource = log.currentSource();
2368                     try {
2369                         log.useSource(classEnv.toplevel.sourcefile);
2370                         scan(classEnv.tree);
2371                     }
2372                     finally {
2373                         log.useSource(prevSource.getFile());
2374                     }
2375                 } else if (sym.kind == TYP) {
2376                     checkClass(pos, sym, List.nil());
2377                 }
2378             } else if (sym == null || sym.kind != PCK) {
2379                 //not completed yet
2380                 partialCheck = true;
2381             }
2382         }
2383 
2384         @Override
2385         public void visitSelect(JCFieldAccess tree) {
2386             super.visitSelect(tree);
2387             checkSymbol(tree.pos(), tree.sym);
2388         }
2389 
2390         @Override
2391         public void visitIdent(JCIdent tree) {
2392             checkSymbol(tree.pos(), tree.sym);
2393         }
2394 
2395         @Override
2396         public void visitTypeApply(JCTypeApply tree) {
2397             scan(tree.clazz);
2398         }
2399 
2400         @Override
2401         public void visitTypeArray(JCArrayTypeTree tree) {
2402             scan(tree.elemtype);
2403         }
2404 
2405         @Override
2406         public void visitClassDef(JCClassDecl tree) {
2407             List<JCTree> supertypes = List.nil();
2408             if (tree.getExtendsClause() != null) {
2409                 supertypes = supertypes.prepend(tree.getExtendsClause());
2410             }
2411             if (tree.getImplementsClause() != null) {
2412                 for (JCTree intf : tree.getImplementsClause()) {
2413                     supertypes = supertypes.prepend(intf);
2414                 }
2415             }
2416             checkClass(tree.pos(), tree.sym, supertypes);
2417         }
2418 
2419         void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
2420             if ((c.flags_field & ACYCLIC) != 0)
2421                 return;
2422             if (seenClasses.contains(c)) {
2423                 errorFound = true;
2424                 noteCyclic(pos, (ClassSymbol)c);
2425             } else if (!c.type.isErroneous()) {
2426                 try {
2427                     seenClasses.add(c);
2428                     if (c.type.hasTag(CLASS)) {
2429                         if (supertypes.nonEmpty()) {
2430                             scan(supertypes);
2431                         }
2432                         else {
2433                             ClassType ct = (ClassType)c.type;
2434                             if (ct.supertype_field == null ||
2435                                     ct.interfaces_field == null) {
2436                                 //not completed yet
2437                                 partialCheck = true;
2438                                 return;
2439                             }
2440                             checkSymbol(pos, ct.supertype_field.tsym);
2441                             for (Type intf : ct.interfaces_field) {
2442                                 checkSymbol(pos, intf.tsym);
2443                             }
2444                         }
2445                         if (c.owner.kind == TYP) {
2446                             checkSymbol(pos, c.owner);
2447                         }
2448                     }
2449                 } finally {
2450                     seenClasses.remove(c);
2451                 }
2452             }
2453         }
2454     }
2455 
2456     /** Check for cyclic references. Issue an error if the
2457      *  symbol of the type referred to has a LOCKED flag set.
2458      *
2459      *  @param pos      Position to be used for error reporting.
2460      *  @param t        The type referred to.
2461      */
2462     void checkNonCyclic(DiagnosticPosition pos, Type t) {
2463         checkNonCyclicInternal(pos, t);
2464     }
2465 
2466 
2467     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
2468         checkNonCyclic1(pos, t, List.nil());
2469     }
2470 
2471     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
2472         final TypeVar tv;
2473         if  (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
2474             return;
2475         if (seen.contains(t)) {
2476             tv = (TypeVar)t;
2477             tv.setUpperBound(types.createErrorType(t));
2478             log.error(pos, Errors.CyclicInheritance(t));
2479         } else if (t.hasTag(TYPEVAR)) {
2480             tv = (TypeVar)t;
2481             seen = seen.prepend(tv);
2482             for (Type b : types.getBounds(tv))
2483                 checkNonCyclic1(pos, b, seen);
2484         }
2485     }
2486 
2487     /** Check for cyclic references. Issue an error if the
2488      *  symbol of the type referred to has a LOCKED flag set.
2489      *
2490      *  @param pos      Position to be used for error reporting.
2491      *  @param t        The type referred to.
2492      *  @return        True if the check completed on all attributed classes
2493      */
2494     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
2495         boolean complete = true; // was the check complete?
2496         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
2497         Symbol c = t.tsym;
2498         if ((c.flags_field & ACYCLIC) != 0) return true;
2499 
2500         if ((c.flags_field & LOCKED) != 0) {
2501             noteCyclic(pos, (ClassSymbol)c);
2502         } else if (!c.type.isErroneous()) {
2503             try {
2504                 c.flags_field |= LOCKED;
2505                 if (c.type.hasTag(CLASS)) {
2506                     ClassType clazz = (ClassType)c.type;
2507                     if (clazz.interfaces_field != null)
2508                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
2509                             complete &= checkNonCyclicInternal(pos, l.head);
2510                     if (clazz.supertype_field != null) {
2511                         Type st = clazz.supertype_field;
2512                         if (st != null && st.hasTag(CLASS))
2513                             complete &= checkNonCyclicInternal(pos, st);
2514                     }
2515                     if (c.owner.kind == TYP)
2516                         complete &= checkNonCyclicInternal(pos, c.owner.type);
2517                 }
2518             } finally {
2519                 c.flags_field &= ~LOCKED;
2520             }
2521         }
2522         if (complete)
2523             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.isCompleted();
2524         if (complete) c.flags_field |= ACYCLIC;
2525         return complete;
2526     }
2527 
2528     /** Note that we found an inheritance cycle. */
2529     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
2530         log.error(pos, Errors.CyclicInheritance(c));
2531         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
2532             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
2533         Type st = types.supertype(c.type);
2534         if (st.hasTag(CLASS))
2535             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
2536         c.type = types.createErrorType(c, c.type);
2537         c.flags_field |= ACYCLIC;
2538     }
2539 
2540     /** Check that all methods which implement some
2541      *  method conform to the method they implement.
2542      *  @param tree         The class definition whose members are checked.
2543      */
2544     void checkImplementations(JCClassDecl tree) {
2545         checkImplementations(tree, tree.sym, tree.sym);
2546     }
2547     //where
2548         /** Check that all methods which implement some
2549          *  method in `ic' conform to the method they implement.
2550          */
2551         void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
2552             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
2553                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
2554                 if ((lc.flags() & ABSTRACT) != 0) {
2555                     for (Symbol sym : lc.members().getSymbols(NON_RECURSIVE)) {
2556                         if (sym.kind == MTH &&
2557                             (sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
2558                             MethodSymbol absmeth = (MethodSymbol)sym;
2559                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
2560                             if (implmeth != null && implmeth != absmeth &&
2561                                 (implmeth.owner.flags() & INTERFACE) ==
2562                                 (origin.flags() & INTERFACE)) {
2563                                 // don't check if implmeth is in a class, yet
2564                                 // origin is an interface. This case arises only
2565                                 // if implmeth is declared in Object. The reason is
2566                                 // that interfaces really don't inherit from
2567                                 // Object it's just that the compiler represents
2568                                 // things that way.
2569                                 checkOverride(tree, implmeth, absmeth, origin);
2570                             }
2571                         }
2572                     }
2573                 }
2574             }
2575         }
2576 
2577     /** Check that all abstract methods implemented by a class are
2578      *  mutually compatible.
2579      *  @param pos          Position to be used for error reporting.
2580      *  @param c            The class whose interfaces are checked.
2581      */
2582     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2583         List<Type> supertypes = types.interfaces(c);
2584         Type supertype = types.supertype(c);
2585         if (supertype.hasTag(CLASS) &&
2586             (supertype.tsym.flags() & ABSTRACT) != 0)
2587             supertypes = supertypes.prepend(supertype);
2588         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2589             if (!l.head.getTypeArguments().isEmpty() &&
2590                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2591                 return;
2592             for (List<Type> m = supertypes; m != l; m = m.tail)
2593                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2594                     return;
2595         }
2596         checkCompatibleConcretes(pos, c);















2597     }
2598 
2599     /** Check that all non-override equivalent methods accessible from 'site'
2600      *  are mutually compatible (JLS 8.4.8/9.4.1).
2601      *
2602      *  @param pos  Position to be used for error reporting.
2603      *  @param site The class whose methods are checked.
2604      *  @param sym  The method symbol to be checked.
2605      */
2606     void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2607          ClashFilter cf = new ClashFilter(site);
2608         //for each method m1 that is overridden (directly or indirectly)
2609         //by method 'sym' in 'site'...
2610 
2611         ArrayList<Symbol> symbolsByName = new ArrayList<>();
2612         types.membersClosure(site, false).getSymbolsByName(sym.name, cf).forEach(symbolsByName::add);
2613         for (Symbol m1 : symbolsByName) {
2614             if (!sym.overrides(m1, site.tsym, types, false)) {
2615                 continue;
2616             }
2617 
2618             //...check each method m2 that is a member of 'site'
2619             for (Symbol m2 : symbolsByName) {
2620                 if (m2 == m1) continue;
2621                 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2622                 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
2623                 if (!types.isSubSignature(sym.type, types.memberType(site, m2)) &&
2624                         types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
2625                     sym.flags_field |= CLASH;
2626                     if (m1 == sym) {
2627                         log.error(pos, Errors.NameClashSameErasureNoOverride(
2628                             m1.name, types.memberType(site, m1).asMethodType().getParameterTypes(), m1.location(),
2629                             m2.name, types.memberType(site, m2).asMethodType().getParameterTypes(), m2.location()));
2630                     } else {
2631                         ClassType ct = (ClassType)site;
2632                         String kind = ct.isInterface() ? "interface" : "class";
2633                         log.error(pos, Errors.NameClashSameErasureNoOverride1(
2634                             kind,
2635                             ct.tsym.name,
2636                             m1.name,
2637                             types.memberType(site, m1).asMethodType().getParameterTypes(),
2638                             m1.location(),
2639                             m2.name,
2640                             types.memberType(site, m2).asMethodType().getParameterTypes(),
2641                             m2.location()));
2642                     }
2643                     return;
2644                 }
2645             }
2646         }
2647     }
2648 
2649     /** Check that all static methods accessible from 'site' are
2650      *  mutually compatible (JLS 8.4.8).
2651      *
2652      *  @param pos  Position to be used for error reporting.
2653      *  @param site The class whose methods are checked.
2654      *  @param sym  The method symbol to be checked.
2655      */
2656     void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2657         ClashFilter cf = new ClashFilter(site);
2658         //for each method m1 that is a member of 'site'...
2659         for (Symbol s : types.membersClosure(site, true).getSymbolsByName(sym.name, cf)) {
2660             //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2661             //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
2662             if (!types.isSubSignature(sym.type, types.memberType(site, s))) {
2663                 if (types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
2664                     log.error(pos,
2665                               Errors.NameClashSameErasureNoHide(sym, sym.location(), s, s.location()));
2666                     return;
2667                 }
2668             }
2669          }
2670      }
2671 
2672      //where
2673      private class ClashFilter implements Predicate<Symbol> {
2674 
2675          Type site;
2676 
2677          ClashFilter(Type site) {
2678              this.site = site;
2679          }
2680 
2681          boolean shouldSkip(Symbol s) {
2682              return (s.flags() & CLASH) != 0 &&
2683                 s.owner == site.tsym;
2684          }
2685 
2686          @Override
2687          public boolean test(Symbol s) {
2688              return s.kind == MTH &&
2689                      (s.flags() & SYNTHETIC) == 0 &&
2690                      !shouldSkip(s) &&
2691                      s.isInheritedIn(site.tsym, types) &&
2692                      !s.isConstructor();
2693          }
2694      }
2695 
2696     void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
2697         DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
2698         for (Symbol m : types.membersClosure(site, false).getSymbols(dcf)) {
2699             Assert.check(m.kind == MTH);
2700             List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
2701             if (prov.size() > 1) {
2702                 ListBuffer<Symbol> abstracts = new ListBuffer<>();
2703                 ListBuffer<Symbol> defaults = new ListBuffer<>();
2704                 for (MethodSymbol provSym : prov) {
2705                     if ((provSym.flags() & DEFAULT) != 0) {
2706                         defaults = defaults.append(provSym);
2707                     } else if ((provSym.flags() & ABSTRACT) != 0) {
2708                         abstracts = abstracts.append(provSym);
2709                     }
2710                     if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
2711                         //strong semantics - issue an error if two sibling interfaces
2712                         //have two override-equivalent defaults - or if one is abstract
2713                         //and the other is default
2714                         Fragment diagKey;
2715                         Symbol s1 = defaults.first();
2716                         Symbol s2;
2717                         if (defaults.size() > 1) {
2718                             s2 = defaults.toList().tail.head;
2719                             diagKey = Fragments.IncompatibleUnrelatedDefaults(Kinds.kindName(site.tsym), site,
2720                                     m.name, types.memberType(site, m).getParameterTypes(),
2721                                     s1.location(), s2.location());
2722 
2723                         } else {
2724                             s2 = abstracts.first();
2725                             diagKey = Fragments.IncompatibleAbstractDefault(Kinds.kindName(site.tsym), site,
2726                                     m.name, types.memberType(site, m).getParameterTypes(),
2727                                     s1.location(), s2.location());
2728                         }
2729                         log.error(pos, Errors.TypesIncompatible(s1.location().type, s2.location().type, diagKey));
2730                         break;
2731                     }
2732                 }
2733             }
2734         }
2735     }
2736 
2737     //where
2738      private class DefaultMethodClashFilter implements Predicate<Symbol> {
2739 
2740          Type site;
2741 
2742          DefaultMethodClashFilter(Type site) {
2743              this.site = site;
2744          }
2745 
2746          @Override
2747          public boolean test(Symbol s) {
2748              return s.kind == MTH &&
2749                      (s.flags() & DEFAULT) != 0 &&
2750                      s.isInheritedIn(site.tsym, types) &&
2751                      !s.isConstructor();
2752          }
2753      }
2754 
2755     /** Report warnings for potentially ambiguous method declarations in the given site. */
2756     void checkPotentiallyAmbiguousOverloads(JCClassDecl tree, Type site) {
2757 
2758         // Skip if warning not enabled
2759         if (!lint.isEnabled(LintCategory.OVERLOADS))
2760             return;
2761 
2762         // Gather all of site's methods, including overridden methods, grouped by name (except Object methods)
2763         List<java.util.List<MethodSymbol>> methodGroups = methodsGroupedByName(site,
2764             new PotentiallyAmbiguousFilter(site), ArrayList::new);
2765 
2766         // Build the predicate that determines if site is responsible for an ambiguity
2767         BiPredicate<MethodSymbol, MethodSymbol> responsible = buildResponsiblePredicate(site, methodGroups);
2768 
2769         // Now remove overridden methods from each group, leaving only site's actual members
2770         methodGroups.forEach(list -> removePreempted(list, (m1, m2) -> m1.overrides(m2, site.tsym, types, false)));
2771 
2772         // Allow site's own declared methods (only) to apply @SuppressWarnings("overloads")
2773         methodGroups.forEach(list -> list.removeIf(
2774             m -> m.owner == site.tsym && !lint.augment(m).isEnabled(LintCategory.OVERLOADS)));
2775 
2776         // Warn about ambiguous overload method pairs for which site is responsible
2777         methodGroups.forEach(list -> compareAndRemove(list, (m1, m2) -> {
2778 
2779             // See if this is an ambiguous overload for which "site" is responsible
2780             if (!potentiallyAmbiguousOverload(site, m1, m2) || !responsible.test(m1, m2))
2781                 return 0;
2782 
2783             // Locate the warning at one of the methods, if possible
2784             DiagnosticPosition pos =
2785                 m1.owner == site.tsym ? TreeInfo.diagnosticPositionFor(m1, tree) :
2786                 m2.owner == site.tsym ? TreeInfo.diagnosticPositionFor(m2, tree) :
2787                 tree.pos();
2788 
2789             // Log the warning
2790             log.warning(LintCategory.OVERLOADS, pos,
2791                 Warnings.PotentiallyAmbiguousOverload(
2792                     m1.asMemberOf(site, types), m1.location(),
2793                     m2.asMemberOf(site, types), m2.location()));
2794 
2795             // Don't warn again for either of these two methods
2796             return FIRST | SECOND;
2797         }));
2798     }
2799 
2800     /** Build a predicate that determines, given two methods that are members of the given class,
2801      *  whether the class should be held "responsible" if the methods are potentially ambiguous.
2802      *
2803      *  Sometimes ambiguous methods are unavoidable because they're inherited from a supertype.
2804      *  For example, any subtype of Spliterator.OfInt will have ambiguities for both
2805      *  forEachRemaining() and tryAdvance() (in both cases the overloads are IntConsumer and
2806      *  Consumer&lt;? super Integer&gt;). So we only want to "blame" a class when that class is
2807      *  itself responsible for creating the ambiguity. We declare that a class C is "responsible"
2808      *  for the ambiguity between two methods m1 and m2 if there is no direct supertype T of C
2809      *  such that m1 and m2, or some overrides thereof, both exist in T and are ambiguous in T.
2810      *  As an optimization, we first check if either method is declared in C and does not override
2811      *  any other methods; in this case the class is definitely responsible.
2812      */
2813     BiPredicate<MethodSymbol, MethodSymbol> buildResponsiblePredicate(Type site,
2814         List<? extends Collection<MethodSymbol>> methodGroups) {
2815 
2816         // Define the "overrides" predicate
2817         BiPredicate<MethodSymbol, MethodSymbol> overrides = (m1, m2) -> m1.overrides(m2, site.tsym, types, false);
2818 
2819         // Map each method declared in site to a list of the supertype method(s) it directly overrides
2820         HashMap<MethodSymbol, ArrayList<MethodSymbol>> overriddenMethodsMap = new HashMap<>();
2821         methodGroups.forEach(list -> {
2822             for (MethodSymbol m : list) {
2823 
2824                 // Skip methods not declared in site
2825                 if (m.owner != site.tsym)
2826                     continue;
2827 
2828                 // Gather all supertype methods overridden by m, directly or indirectly
2829                 ArrayList<MethodSymbol> overriddenMethods = list.stream()
2830                   .filter(m2 -> m2 != m && overrides.test(m, m2))
2831                   .collect(Collectors.toCollection(ArrayList::new));
2832 
2833                 // Eliminate non-direct overrides
2834                 removePreempted(overriddenMethods, overrides);
2835 
2836                 // Add to map
2837                 overriddenMethodsMap.put(m, overriddenMethods);
2838             }
2839         });
2840 
2841         // Build the predicate
2842         return (m1, m2) -> {
2843 
2844             // Get corresponding supertype methods (if declared in site)
2845             java.util.List<MethodSymbol> overriddenMethods1 = overriddenMethodsMap.get(m1);
2846             java.util.List<MethodSymbol> overriddenMethods2 = overriddenMethodsMap.get(m2);
2847 
2848             // Quick check for the case where a method was added by site itself
2849             if (overriddenMethods1 != null && overriddenMethods1.isEmpty())
2850                 return true;
2851             if (overriddenMethods2 != null && overriddenMethods2.isEmpty())
2852                 return true;
2853 
2854             // Get each method's corresponding method(s) from supertypes of site
2855             java.util.List<MethodSymbol> supertypeMethods1 = overriddenMethods1 != null ?
2856               overriddenMethods1 : Collections.singletonList(m1);
2857             java.util.List<MethodSymbol> supertypeMethods2 = overriddenMethods2 != null ?
2858               overriddenMethods2 : Collections.singletonList(m2);
2859 
2860             // See if we can blame some direct supertype instead
2861             return types.directSupertypes(site).stream()
2862               .filter(stype -> stype != syms.objectType)
2863               .map(stype -> stype.tsym.type)                // view supertype in its original form
2864               .noneMatch(stype -> {
2865                 for (MethodSymbol sm1 : supertypeMethods1) {
2866                     if (!types.isSubtype(types.erasure(stype), types.erasure(sm1.owner.type)))
2867                         continue;
2868                     for (MethodSymbol sm2 : supertypeMethods2) {
2869                         if (!types.isSubtype(types.erasure(stype), types.erasure(sm2.owner.type)))
2870                             continue;
2871                         if (potentiallyAmbiguousOverload(stype, sm1, sm2))
2872                             return true;
2873                     }
2874                 }
2875                 return false;
2876             });
2877         };
2878     }
2879 
2880     /** Gather all of site's methods, including overridden methods, grouped and sorted by name,
2881      *  after applying the given filter.
2882      */
2883     <C extends Collection<MethodSymbol>> List<C> methodsGroupedByName(Type site,
2884             Predicate<Symbol> filter, Supplier<? extends C> groupMaker) {
2885         Iterable<Symbol> symbols = types.membersClosure(site, false).getSymbols(filter, RECURSIVE);
2886         return StreamSupport.stream(symbols.spliterator(), false)
2887           .map(MethodSymbol.class::cast)
2888           .collect(Collectors.groupingBy(m -> m.name, Collectors.toCollection(groupMaker)))
2889           .entrySet()
2890           .stream()
2891           .sorted(Comparator.comparing(e -> e.getKey().toString()))
2892           .map(Map.Entry::getValue)
2893           .collect(List.collector());
2894     }
2895 
2896     /** Compare elements in a list pair-wise in order to remove some of them.
2897      *  @param list mutable list of items
2898      *  @param comparer returns flag bit(s) to remove FIRST and/or SECOND
2899      */
2900     <T> void compareAndRemove(java.util.List<T> list, ToIntBiFunction<? super T, ? super T> comparer) {
2901         for (int index1 = 0; index1 < list.size() - 1; index1++) {
2902             T item1 = list.get(index1);
2903             for (int index2 = index1 + 1; index2 < list.size(); index2++) {
2904                 T item2 = list.get(index2);
2905                 int flags = comparer.applyAsInt(item1, item2);
2906                 if ((flags & SECOND) != 0)
2907                     list.remove(index2--);          // remove item2
2908                 if ((flags & FIRST) != 0) {
2909                     list.remove(index1--);          // remove item1
2910                     break;
2911                 }
2912             }
2913         }
2914     }
2915 
2916     /** Remove elements in a list that are preempted by some other element in the list.
2917      *  @param list mutable list of items
2918      *  @param preempts decides if one item preempts another, causing the second one to be removed
2919      */
2920     <T> void removePreempted(java.util.List<T> list, BiPredicate<? super T, ? super T> preempts) {
2921         compareAndRemove(list, (item1, item2) -> {
2922             int flags = 0;
2923             if (preempts.test(item1, item2))
2924                 flags |= SECOND;
2925             if (preempts.test(item2, item1))
2926                 flags |= FIRST;
2927             return flags;
2928         });
2929     }
2930 
2931     /** Filters method candidates for the "potentially ambiguous method" check */
2932     class PotentiallyAmbiguousFilter extends ClashFilter {
2933 
2934         PotentiallyAmbiguousFilter(Type site) {
2935             super(site);
2936         }
2937 
2938         @Override
2939         boolean shouldSkip(Symbol s) {
2940             return s.owner.type.tsym == syms.objectType.tsym || super.shouldSkip(s);
2941         }
2942     }
2943 
2944     /**
2945       * Report warnings for potentially ambiguous method declarations. Two declarations
2946       * are potentially ambiguous if they feature two unrelated functional interface
2947       * in same argument position (in which case, a call site passing an implicit
2948       * lambda would be ambiguous). This assumes they already have the same name.
2949       */
2950     boolean potentiallyAmbiguousOverload(Type site, MethodSymbol msym1, MethodSymbol msym2) {
2951         Assert.check(msym1.name == msym2.name);
2952         if (msym1 == msym2)
2953             return false;
2954         Type mt1 = types.memberType(site, msym1);
2955         Type mt2 = types.memberType(site, msym2);
2956         //if both generic methods, adjust type variables
2957         if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL) &&
2958                 types.hasSameBounds((ForAll)mt1, (ForAll)mt2)) {
2959             mt2 = types.subst(mt2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars);
2960         }
2961         //expand varargs methods if needed
2962         int maxLength = Math.max(mt1.getParameterTypes().length(), mt2.getParameterTypes().length());
2963         List<Type> args1 = rs.adjustArgs(mt1.getParameterTypes(), msym1, maxLength, true);
2964         List<Type> args2 = rs.adjustArgs(mt2.getParameterTypes(), msym2, maxLength, true);
2965         //if arities don't match, exit
2966         if (args1.length() != args2.length())
2967             return false;
2968         boolean potentiallyAmbiguous = false;
2969         while (args1.nonEmpty() && args2.nonEmpty()) {
2970             Type s = args1.head;
2971             Type t = args2.head;
2972             if (!types.isSubtype(t, s) && !types.isSubtype(s, t)) {
2973                 if (types.isFunctionalInterface(s) && types.isFunctionalInterface(t) &&
2974                         types.findDescriptorType(s).getParameterTypes().length() > 0 &&
2975                         types.findDescriptorType(s).getParameterTypes().length() ==
2976                         types.findDescriptorType(t).getParameterTypes().length()) {
2977                     potentiallyAmbiguous = true;
2978                 } else {
2979                     return false;
2980                 }
2981             }
2982             args1 = args1.tail;
2983             args2 = args2.tail;
2984         }
2985         return potentiallyAmbiguous;
2986     }
2987 
2988     void checkAccessFromSerializableElement(final JCTree tree, boolean isLambda) {
2989         if (warnOnAnyAccessToMembers ||
2990             (lint.isEnabled(LintCategory.SERIAL) &&
2991             !lint.isSuppressed(LintCategory.SERIAL) &&
2992             isLambda)) {
2993             Symbol sym = TreeInfo.symbol(tree);
2994             if (!sym.kind.matches(KindSelector.VAL_MTH)) {
2995                 return;
2996             }
2997 
2998             if (sym.kind == VAR) {
2999                 if ((sym.flags() & PARAMETER) != 0 ||
3000                     sym.isDirectlyOrIndirectlyLocal() ||
3001                     sym.name == names._this ||
3002                     sym.name == names._super) {
3003                     return;
3004                 }
3005             }
3006 
3007             if (!types.isSubtype(sym.owner.type, syms.serializableType) &&
3008                 isEffectivelyNonPublic(sym)) {
3009                 if (isLambda) {
3010                     if (belongsToRestrictedPackage(sym)) {
3011                         log.warning(LintCategory.SERIAL, tree.pos(),
3012                                     Warnings.AccessToMemberFromSerializableLambda(sym));
3013                     }
3014                 } else {
3015                     log.warning(tree.pos(),
3016                                 Warnings.AccessToMemberFromSerializableElement(sym));
3017                 }
3018             }
3019         }
3020     }
3021 
3022     private boolean isEffectivelyNonPublic(Symbol sym) {
3023         if (sym.packge() == syms.rootPackage) {
3024             return false;
3025         }
3026 
3027         while (sym.kind != PCK) {
3028             if ((sym.flags() & PUBLIC) == 0) {
3029                 return true;
3030             }
3031             sym = sym.owner;
3032         }
3033         return false;
3034     }
3035 
3036     private boolean belongsToRestrictedPackage(Symbol sym) {
3037         String fullName = sym.packge().fullname.toString();
3038         return fullName.startsWith("java.") ||
3039                 fullName.startsWith("javax.") ||
3040                 fullName.startsWith("sun.") ||
3041                 fullName.contains(".internal.");
3042     }
3043 
3044     /** Check that class c does not implement directly or indirectly
3045      *  the same parameterized interface with two different argument lists.
3046      *  @param pos          Position to be used for error reporting.
3047      *  @param type         The type whose interfaces are checked.
3048      */
3049     void checkClassBounds(DiagnosticPosition pos, Type type) {
3050         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
3051     }
3052 //where
3053         /** Enter all interfaces of type `type' into the hash table `seensofar'
3054          *  with their class symbol as key and their type as value. Make
3055          *  sure no class is entered with two different types.
3056          */
3057         void checkClassBounds(DiagnosticPosition pos,
3058                               Map<TypeSymbol,Type> seensofar,
3059                               Type type) {
3060             if (type.isErroneous()) return;
3061             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
3062                 Type it = l.head;
3063                 if (type.hasTag(CLASS) && !it.hasTag(CLASS)) continue; // JLS 8.1.5
3064 
3065                 Type oldit = seensofar.put(it.tsym, it);
3066                 if (oldit != null) {
3067                     List<Type> oldparams = oldit.allparams();
3068                     List<Type> newparams = it.allparams();
3069                     if (!types.containsTypeEquivalent(oldparams, newparams))
3070                         log.error(pos,
3071                                   Errors.CantInheritDiffArg(it.tsym,
3072                                                             Type.toString(oldparams),
3073                                                             Type.toString(newparams)));
3074                 }
3075                 checkClassBounds(pos, seensofar, it);
3076             }
3077             Type st = types.supertype(type);
3078             if (type.hasTag(CLASS) && !st.hasTag(CLASS)) return; // JLS 8.1.4
3079             if (st != Type.noType) checkClassBounds(pos, seensofar, st);
3080         }
3081 
3082     /** Enter interface into into set.
3083      *  If it existed already, issue a "repeated interface" error.
3084      */
3085     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Symbol> its) {
3086         if (its.contains(it.tsym))
3087             log.error(pos, Errors.RepeatedInterface);
3088         else {
3089             its.add(it.tsym);
3090         }
3091     }
3092 
3093 /* *************************************************************************
3094  * Check annotations
3095  **************************************************************************/
3096 
3097     /**
3098      * Recursively validate annotations values
3099      */
3100     void validateAnnotationTree(JCTree tree) {
3101         class AnnotationValidator extends TreeScanner {
3102             @Override
3103             public void visitAnnotation(JCAnnotation tree) {
3104                 if (!tree.type.isErroneous() && tree.type.tsym.isAnnotationType()) {
3105                     super.visitAnnotation(tree);
3106                     validateAnnotation(tree);
3107                 }
3108             }
3109         }
3110         tree.accept(new AnnotationValidator());
3111     }
3112 
3113     /**
3114      *  {@literal
3115      *  Annotation types are restricted to primitives, String, an
3116      *  enum, an annotation, Class, Class<?>, Class<? extends
3117      *  Anything>, arrays of the preceding.
3118      *  }
3119      */
3120     void validateAnnotationType(JCTree restype) {
3121         // restype may be null if an error occurred, so don't bother validating it
3122         if (restype != null) {
3123             validateAnnotationType(restype.pos(), restype.type);
3124         }
3125     }
3126 
3127     void validateAnnotationType(DiagnosticPosition pos, Type type) {
3128         if (type.isPrimitive()) return;
3129         if (types.isSameType(type, syms.stringType)) return;
3130         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
3131         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
3132         if (types.cvarLowerBound(type).tsym == syms.classType.tsym) return;
3133         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
3134             validateAnnotationType(pos, types.elemtype(type));
3135             return;
3136         }
3137         log.error(pos, Errors.InvalidAnnotationMemberType);
3138     }
3139 
3140     /**
3141      * "It is also a compile-time error if any method declared in an
3142      * annotation type has a signature that is override-equivalent to
3143      * that of any public or protected method declared in class Object
3144      * or in the interface annotation.Annotation."
3145      *
3146      * @jls 9.6 Annotation Types
3147      */
3148     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
3149         for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
3150             Scope s = sup.tsym.members();
3151             for (Symbol sym : s.getSymbolsByName(m.name)) {
3152                 if (sym.kind == MTH &&
3153                     (sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
3154                     types.overrideEquivalent(m.type, sym.type))
3155                     log.error(pos, Errors.IntfAnnotationMemberClash(sym, sup));
3156             }
3157         }
3158     }
3159 
3160     /** Check the annotations of a symbol.
3161      */
3162     public void validateAnnotations(List<JCAnnotation> annotations, JCTree declarationTree, Symbol s) {
3163         for (JCAnnotation a : annotations)
3164             validateAnnotation(a, declarationTree, s);
3165     }
3166 
3167     /** Check the type annotations.
3168      */
3169     public void validateTypeAnnotations(List<JCAnnotation> annotations, Symbol s, boolean isTypeParameter) {
3170         for (JCAnnotation a : annotations)
3171             validateTypeAnnotation(a, s, isTypeParameter);
3172     }
3173 
3174     /** Check an annotation of a symbol.
3175      */
3176     private void validateAnnotation(JCAnnotation a, JCTree declarationTree, Symbol s) {
3177         /** NOTE: if annotation processors are present, annotation processing rounds can happen after this method,
3178          *  this can impact in particular records for which annotations are forcibly propagated.
3179          */
3180         validateAnnotationTree(a);
3181         boolean isRecordMember = ((s.flags_field & RECORD) != 0 || s.enclClass() != null && s.enclClass().isRecord());
3182 
3183         boolean isRecordField = (s.flags_field & RECORD) != 0 &&
3184                 declarationTree.hasTag(VARDEF) &&
3185                 s.owner.kind == TYP;
3186 
3187         if (isRecordField) {
3188             // first we need to check if the annotation is applicable to records
3189             Name[] targets = getTargetNames(a);
3190             boolean appliesToRecords = false;
3191             for (Name target : targets) {
3192                 appliesToRecords =
3193                                 target == names.FIELD ||
3194                                 target == names.PARAMETER ||
3195                                 target == names.METHOD ||
3196                                 target == names.TYPE_USE ||
3197                                 target == names.RECORD_COMPONENT;
3198                 if (appliesToRecords) {
3199                     break;
3200                 }
3201             }
3202             if (!appliesToRecords) {
3203                 log.error(a.pos(), Errors.AnnotationTypeNotApplicable);
3204             } else {
3205                 /* lets now find the annotations in the field that are targeted to record components and append them to
3206                  * the corresponding record component
3207                  */
3208                 ClassSymbol recordClass = (ClassSymbol) s.owner;
3209                 RecordComponent rc = recordClass.getRecordComponent((VarSymbol)s);
3210                 SymbolMetadata metadata = rc.getMetadata();
3211                 if (metadata == null || metadata.isEmpty()) {
3212                     /* if not is empty then we have already been here, which is the case if multiple annotations are applied
3213                      * to the record component declaration
3214                      */
3215                     rc.appendAttributes(s.getRawAttributes().stream().filter(anno ->
3216                             Arrays.stream(getTargetNames(anno.type.tsym)).anyMatch(name -> name == names.RECORD_COMPONENT)
3217                     ).collect(List.collector()));
3218 
3219                     JCVariableDecl fieldAST = (JCVariableDecl) declarationTree;
3220                     for (JCAnnotation fieldAnnot : fieldAST.mods.annotations) {
3221                         for (JCAnnotation rcAnnot : rc.declarationFor().mods.annotations) {
3222                             if (rcAnnot.pos == fieldAnnot.pos) {
3223                                 rcAnnot.setType(fieldAnnot.type);
3224                                 break;
3225                             }
3226                         }
3227                     }
3228 
3229                     /* At this point, we used to carry over any type annotations from the VARDEF to the record component, but
3230                      * that is problematic, since we get here only when *some* annotation is applied to the SE5 (declaration)
3231                      * annotation location, inadvertently failing to carry over the type annotations when the VarDef has no
3232                      * annotations in the SE5 annotation location.
3233                      *
3234                      * Now type annotations are assigned to record components in a method that would execute irrespective of
3235                      * whether there are SE5 annotations on a VarDef viz com.sun.tools.javac.code.TypeAnnotations.TypeAnnotationPositions.visitVarDef
3236                      */
3237                 }
3238             }
3239         }
3240 
3241         /* the section below is tricky. Annotations applied to record components are propagated to the corresponding
3242          * record member so if an annotation has target: FIELD, it is propagated to the corresponding FIELD, if it has
3243          * target METHOD, it is propagated to the accessor and so on. But at the moment when method members are generated
3244          * there is no enough information to propagate only the right annotations. So all the annotations are propagated
3245          * to all the possible locations.
3246          *
3247          * At this point we need to remove all the annotations that are not in place before going on with the annotation
3248          * party. On top of the above there is the issue that there is no AST representing record components, just symbols
3249          * so the corresponding field has been holding all the annotations and it's metadata has been modified as if it
3250          * was both a field and a record component.
3251          *
3252          * So there are two places where we need to trim annotations from: the metadata of the symbol and / or the modifiers
3253          * in the AST. Whatever is in the metadata will be written to the class file, whatever is in the modifiers could
3254          * be see by annotation processors.
3255          *
3256          * The metadata contains both type annotations and declaration annotations. At this point of the game we don't
3257          * need to care about type annotations, they are all in the right place. But we could need to remove declaration
3258          * annotations. So for declaration annotations if they are not applicable to the record member, excluding type
3259          * annotations which are already correct, then we will remove it. For the AST modifiers if the annotation is not
3260          * applicable either as type annotation and or declaration annotation, only in that case it will be removed.
3261          *
3262          * So it could be that annotation is removed as a declaration annotation but it is kept in the AST modifier for
3263          * further inspection by annotation processors.
3264          *
3265          * For example:
3266          *
3267          *     import java.lang.annotation.*;
3268          *
3269          *     @Target({ElementType.TYPE_USE, ElementType.RECORD_COMPONENT})
3270          *     @Retention(RetentionPolicy.RUNTIME)
3271          *     @interface Anno { }
3272          *
3273          *     record R(@Anno String s) {}
3274          *
3275          * at this point we will have for the case of the generated field:
3276          *   - @Anno in the modifier
3277          *   - @Anno as a type annotation
3278          *   - @Anno as a declaration annotation
3279          *
3280          * the last one should be removed because the annotation has not FIELD as target but it was applied as a
3281          * declaration annotation because the field was being treated both as a field and as a record component
3282          * as we have already copied the annotations to the record component, now the field doesn't need to hold
3283          * annotations that are not intended for it anymore. Still @Anno has to be kept in the AST's modifiers as it
3284          * is applicable as a type annotation to the type of the field.
3285          */
3286 
3287         if (a.type.tsym.isAnnotationType()) {
3288             Optional<Set<Name>> applicableTargetsOp = getApplicableTargets(a, s);
3289             if (!applicableTargetsOp.isEmpty()) {
3290                 Set<Name> applicableTargets = applicableTargetsOp.get();
3291                 boolean notApplicableOrIsTypeUseOnly = applicableTargets.isEmpty() ||
3292                         applicableTargets.size() == 1 && applicableTargets.contains(names.TYPE_USE);
3293                 boolean isCompGeneratedRecordElement = isRecordMember && (s.flags_field & Flags.GENERATED_MEMBER) != 0;
3294                 boolean isCompRecordElementWithNonApplicableDeclAnno = isCompGeneratedRecordElement && notApplicableOrIsTypeUseOnly;
3295 
3296                 if (applicableTargets.isEmpty() || isCompRecordElementWithNonApplicableDeclAnno) {
3297                     if (isCompRecordElementWithNonApplicableDeclAnno) {
3298                             /* so we have found an annotation that is not applicable to a record member that was generated by the
3299                              * compiler. This was intentionally done at TypeEnter, now is the moment strip away the annotations
3300                              * that are not applicable to the given record member
3301                              */
3302                         JCModifiers modifiers = TreeInfo.getModifiers(declarationTree);
3303                             /* lets first remove the annotation from the modifier if it is not applicable, we have to check again as
3304                              * it could be a type annotation
3305                              */
3306                         if (modifiers != null && applicableTargets.isEmpty()) {
3307                             ListBuffer<JCAnnotation> newAnnotations = new ListBuffer<>();
3308                             for (JCAnnotation anno : modifiers.annotations) {
3309                                 if (anno != a) {
3310                                     newAnnotations.add(anno);
3311                                 }
3312                             }
3313                             modifiers.annotations = newAnnotations.toList();
3314                         }
3315                         // now lets remove it from the symbol
3316                         s.getMetadata().removeDeclarationMetadata(a.attribute);
3317                     } else {
3318                         log.error(a.pos(), Errors.AnnotationTypeNotApplicable);
3319                     }
3320                 }
3321                 /* if we are seeing the @SafeVarargs annotation applied to a compiler generated accessor,
3322                  * then this is an error as we know that no compiler generated accessor will be a varargs
3323                  * method, better to fail asap
3324                  */
3325                 if (isCompGeneratedRecordElement && !isRecordField && a.type.tsym == syms.trustMeType.tsym && declarationTree.hasTag(METHODDEF)) {
3326                     log.error(a.pos(), Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym, Fragments.VarargsTrustmeOnNonVarargsAccessor(s)));
3327                 }
3328             }
3329         }
3330 
3331         if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
3332             if (s.kind != TYP) {
3333                 log.error(a.pos(), Errors.BadFunctionalIntfAnno);
3334             } else if (!s.isInterface() || (s.flags() & ANNOTATION) != 0) {
3335                 log.error(a.pos(), Errors.BadFunctionalIntfAnno1(Fragments.NotAFunctionalIntf(s)));
3336             }
3337         }
3338     }
3339 
3340     public void validateTypeAnnotation(JCAnnotation a, Symbol s, boolean isTypeParameter) {
3341         Assert.checkNonNull(a.type);
3342         // we just want to validate that the anotation doesn't have any wrong target
3343         if (s != null) getApplicableTargets(a, s);
3344         validateAnnotationTree(a);
3345 
3346         if (a.hasTag(TYPE_ANNOTATION) &&
3347                 !a.annotationType.type.isErroneous() &&
3348                 !isTypeAnnotation(a, isTypeParameter)) {
3349             log.error(a.pos(), Errors.AnnotationTypeNotApplicableToType(a.type));
3350         }
3351     }
3352 
3353     /**
3354      * Validate the proposed container 'repeatable' on the
3355      * annotation type symbol 's'. Report errors at position
3356      * 'pos'.
3357      *
3358      * @param s The (annotation)type declaration annotated with a @Repeatable
3359      * @param repeatable the @Repeatable on 's'
3360      * @param pos where to report errors
3361      */
3362     public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
3363         Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
3364 
3365         Type t = null;
3366         List<Pair<MethodSymbol,Attribute>> l = repeatable.values;
3367         if (!l.isEmpty()) {
3368             Assert.check(l.head.fst.name == names.value);
3369             if (l.head.snd instanceof Attribute.Class) {
3370                 t = ((Attribute.Class)l.head.snd).getValue();
3371             }
3372         }
3373 
3374         if (t == null) {
3375             // errors should already have been reported during Annotate
3376             return;
3377         }
3378 
3379         validateValue(t.tsym, s, pos);
3380         validateRetention(t.tsym, s, pos);
3381         validateDocumented(t.tsym, s, pos);
3382         validateInherited(t.tsym, s, pos);
3383         validateTarget(t.tsym, s, pos);
3384         validateDefault(t.tsym, pos);
3385     }
3386 
3387     private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
3388         Symbol sym = container.members().findFirst(names.value);
3389         if (sym != null && sym.kind == MTH) {
3390             MethodSymbol m = (MethodSymbol) sym;
3391             Type ret = m.getReturnType();
3392             if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
3393                 log.error(pos,
3394                           Errors.InvalidRepeatableAnnotationValueReturn(container,
3395                                                                         ret,
3396                                                                         types.makeArrayType(contained.type)));
3397             }
3398         } else {
3399             log.error(pos, Errors.InvalidRepeatableAnnotationNoValue(container));
3400         }
3401     }
3402 
3403     private void validateRetention(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
3404         Attribute.RetentionPolicy containerRetention = types.getRetention(container);
3405         Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
3406 
3407         boolean error = false;
3408         switch (containedRetention) {
3409         case RUNTIME:
3410             if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
3411                 error = true;
3412             }
3413             break;
3414         case CLASS:
3415             if (containerRetention == Attribute.RetentionPolicy.SOURCE)  {
3416                 error = true;
3417             }
3418         }
3419         if (error ) {
3420             log.error(pos,
3421                       Errors.InvalidRepeatableAnnotationRetention(container,
3422                                                                   containerRetention.name(),
3423                                                                   contained,
3424                                                                   containedRetention.name()));
3425         }
3426     }
3427 
3428     private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
3429         if (contained.attribute(syms.documentedType.tsym) != null) {
3430             if (container.attribute(syms.documentedType.tsym) == null) {
3431                 log.error(pos, Errors.InvalidRepeatableAnnotationNotDocumented(container, contained));
3432             }
3433         }
3434     }
3435 
3436     private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
3437         if (contained.attribute(syms.inheritedType.tsym) != null) {
3438             if (container.attribute(syms.inheritedType.tsym) == null) {
3439                 log.error(pos, Errors.InvalidRepeatableAnnotationNotInherited(container, contained));
3440             }
3441         }
3442     }
3443 
3444     private void validateTarget(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
3445         // The set of targets the container is applicable to must be a subset
3446         // (with respect to annotation target semantics) of the set of targets
3447         // the contained is applicable to. The target sets may be implicit or
3448         // explicit.
3449 
3450         Set<Name> containerTargets;
3451         Attribute.Array containerTarget = getAttributeTargetAttribute(container);
3452         if (containerTarget == null) {
3453             containerTargets = getDefaultTargetSet();
3454         } else {
3455             containerTargets = new HashSet<>();
3456             for (Attribute app : containerTarget.values) {
3457                 if (!(app instanceof Attribute.Enum attributeEnum)) {
3458                     continue; // recovery
3459                 }
3460                 containerTargets.add(attributeEnum.value.name);
3461             }
3462         }
3463 
3464         Set<Name> containedTargets;
3465         Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
3466         if (containedTarget == null) {
3467             containedTargets = getDefaultTargetSet();
3468         } else {
3469             containedTargets = new HashSet<>();
3470             for (Attribute app : containedTarget.values) {
3471                 if (!(app instanceof Attribute.Enum attributeEnum)) {
3472                     continue; // recovery
3473                 }
3474                 containedTargets.add(attributeEnum.value.name);
3475             }
3476         }
3477 
3478         if (!isTargetSubsetOf(containerTargets, containedTargets)) {
3479             log.error(pos, Errors.InvalidRepeatableAnnotationIncompatibleTarget(container, contained));
3480         }
3481     }
3482 
3483     /* get a set of names for the default target */
3484     private Set<Name> getDefaultTargetSet() {
3485         if (defaultTargets == null) {
3486             defaultTargets = Set.of(defaultTargetMetaInfo());
3487         }
3488 
3489         return defaultTargets;
3490     }
3491     private Set<Name> defaultTargets;
3492 
3493 
3494     /** Checks that s is a subset of t, with respect to ElementType
3495      * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE},
3496      * and {TYPE_USE} covers the set {ANNOTATION_TYPE, TYPE, TYPE_USE,
3497      * TYPE_PARAMETER}.
3498      */
3499     private boolean isTargetSubsetOf(Set<Name> s, Set<Name> t) {
3500         // Check that all elements in s are present in t
3501         for (Name n2 : s) {
3502             boolean currentElementOk = false;
3503             for (Name n1 : t) {
3504                 if (n1 == n2) {
3505                     currentElementOk = true;
3506                     break;
3507                 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
3508                     currentElementOk = true;
3509                     break;
3510                 } else if (n1 == names.TYPE_USE &&
3511                         (n2 == names.TYPE ||
3512                          n2 == names.ANNOTATION_TYPE ||
3513                          n2 == names.TYPE_PARAMETER)) {
3514                     currentElementOk = true;
3515                     break;
3516                 }
3517             }
3518             if (!currentElementOk)
3519                 return false;
3520         }
3521         return true;
3522     }
3523 
3524     private void validateDefault(Symbol container, DiagnosticPosition pos) {
3525         // validate that all other elements of containing type has defaults
3526         Scope scope = container.members();
3527         for(Symbol elm : scope.getSymbols()) {
3528             if (elm.name != names.value &&
3529                 elm.kind == MTH &&
3530                 ((MethodSymbol)elm).defaultValue == null) {
3531                 log.error(pos,
3532                           Errors.InvalidRepeatableAnnotationElemNondefault(container, elm));
3533             }
3534         }
3535     }
3536 
3537     /** Is s a method symbol that overrides a method in a superclass? */
3538     boolean isOverrider(Symbol s) {
3539         if (s.kind != MTH || s.isStatic())
3540             return false;
3541         MethodSymbol m = (MethodSymbol)s;
3542         TypeSymbol owner = (TypeSymbol)m.owner;
3543         for (Type sup : types.closure(owner.type)) {
3544             if (sup == owner.type)
3545                 continue; // skip "this"
3546             Scope scope = sup.tsym.members();
3547             for (Symbol sym : scope.getSymbolsByName(m.name)) {
3548                 if (!sym.isStatic() && m.overrides(sym, owner, types, true))
3549                     return true;
3550             }
3551         }
3552         return false;
3553     }
3554 
3555     /** Is the annotation applicable to types? */
3556     protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
3557         List<Attribute> targets = typeAnnotations.annotationTargets(a.annotationType.type.tsym);
3558         return (targets == null) ?
3559                 (Feature.NO_TARGET_ANNOTATION_APPLICABILITY.allowedInSource(source) && isTypeParameter) :
3560                 targets.stream()
3561                         .anyMatch(attr -> isTypeAnnotation(attr, isTypeParameter));
3562     }
3563     //where
3564         boolean isTypeAnnotation(Attribute a, boolean isTypeParameter) {
3565             Attribute.Enum e = (Attribute.Enum)a;
3566             return (e.value.name == names.TYPE_USE ||
3567                     (isTypeParameter && e.value.name == names.TYPE_PARAMETER));
3568         }
3569 
3570     /** Is the annotation applicable to the symbol? */
3571     Name[] getTargetNames(JCAnnotation a) {
3572         return getTargetNames(a.annotationType.type.tsym);
3573     }
3574 
3575     public Name[] getTargetNames(TypeSymbol annoSym) {
3576         Attribute.Array arr = getAttributeTargetAttribute(annoSym);
3577         Name[] targets;
3578         if (arr == null) {
3579             targets = defaultTargetMetaInfo();
3580         } else {
3581             // TODO: can we optimize this?
3582             targets = new Name[arr.values.length];
3583             for (int i=0; i<arr.values.length; ++i) {
3584                 Attribute app = arr.values[i];
3585                 if (!(app instanceof Attribute.Enum attributeEnum)) {
3586                     return new Name[0];
3587                 }
3588                 targets[i] = attributeEnum.value.name;
3589             }
3590         }
3591         return targets;
3592     }
3593 
3594     boolean annotationApplicable(JCAnnotation a, Symbol s) {
3595         Optional<Set<Name>> targets = getApplicableTargets(a, s);
3596         /* the optional could be empty if the annotation is unknown in that case
3597          * we return that it is applicable and if it is erroneous that should imply
3598          * an error at the declaration site
3599          */
3600         return targets.isEmpty() || targets.isPresent() && !targets.get().isEmpty();
3601     }
3602 
3603     Optional<Set<Name>> getApplicableTargets(JCAnnotation a, Symbol s) {
3604         Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
3605         Name[] targets;
3606         Set<Name> applicableTargets = new HashSet<>();
3607 
3608         if (arr == null) {
3609             targets = defaultTargetMetaInfo();
3610         } else {
3611             // TODO: can we optimize this?
3612             targets = new Name[arr.values.length];
3613             for (int i=0; i<arr.values.length; ++i) {
3614                 Attribute app = arr.values[i];
3615                 if (!(app instanceof Attribute.Enum attributeEnum)) {
3616                     // recovery
3617                     return Optional.empty();
3618                 }
3619                 targets[i] = attributeEnum.value.name;
3620             }
3621         }
3622         for (Name target : targets) {
3623             if (target == names.TYPE) {
3624                 if (s.kind == TYP)
3625                     applicableTargets.add(names.TYPE);
3626             } else if (target == names.FIELD) {
3627                 if (s.kind == VAR && s.owner.kind != MTH)
3628                     applicableTargets.add(names.FIELD);
3629             } else if (target == names.RECORD_COMPONENT) {
3630                 if (s.getKind() == ElementKind.RECORD_COMPONENT) {
3631                     applicableTargets.add(names.RECORD_COMPONENT);
3632                 }
3633             } else if (target == names.METHOD) {
3634                 if (s.kind == MTH && !s.isConstructor())
3635                     applicableTargets.add(names.METHOD);
3636             } else if (target == names.PARAMETER) {
3637                 if (s.kind == VAR &&
3638                     (s.owner.kind == MTH && (s.flags() & PARAMETER) != 0)) {
3639                     applicableTargets.add(names.PARAMETER);
3640                 }
3641             } else if (target == names.CONSTRUCTOR) {
3642                 if (s.kind == MTH && s.isConstructor())
3643                     applicableTargets.add(names.CONSTRUCTOR);
3644             } else if (target == names.LOCAL_VARIABLE) {
3645                 if (s.kind == VAR && s.owner.kind == MTH &&
3646                       (s.flags() & PARAMETER) == 0) {
3647                     applicableTargets.add(names.LOCAL_VARIABLE);
3648                 }
3649             } else if (target == names.ANNOTATION_TYPE) {
3650                 if (s.kind == TYP && (s.flags() & ANNOTATION) != 0) {
3651                     applicableTargets.add(names.ANNOTATION_TYPE);
3652                 }
3653             } else if (target == names.PACKAGE) {
3654                 if (s.kind == PCK)
3655                     applicableTargets.add(names.PACKAGE);
3656             } else if (target == names.TYPE_USE) {
3657                 if (s.kind == VAR && s.owner.kind == MTH && s.type.hasTag(NONE)) {
3658                     //cannot type annotate implicitly typed locals
3659                     continue;
3660                 } else if (s.kind == TYP || s.kind == VAR ||
3661                         (s.kind == MTH && !s.isConstructor() &&
3662                                 !s.type.getReturnType().hasTag(VOID)) ||
3663                         (s.kind == MTH && s.isConstructor())) {
3664                     applicableTargets.add(names.TYPE_USE);
3665                 }
3666             } else if (target == names.TYPE_PARAMETER) {
3667                 if (s.kind == TYP && s.type.hasTag(TYPEVAR))
3668                     applicableTargets.add(names.TYPE_PARAMETER);
3669             } else if (target == names.MODULE) {
3670                 if (s.kind == MDL)
3671                     applicableTargets.add(names.MODULE);
3672             } else {
3673                 log.error(a, Errors.AnnotationUnrecognizedAttributeName(a.type, target));
3674                 return Optional.empty(); // Unknown ElementType
3675             }
3676         }
3677         return Optional.of(applicableTargets);
3678     }
3679 
3680     Attribute.Array getAttributeTargetAttribute(TypeSymbol s) {
3681         Attribute.Compound atTarget = s.getAnnotationTypeMetadata().getTarget();
3682         if (atTarget == null) return null; // ok, is applicable
3683         Attribute atValue = atTarget.member(names.value);
3684         return (atValue instanceof Attribute.Array attributeArray) ? attributeArray : null;
3685     }
3686 
3687     private Name[] dfltTargetMeta;
3688     private Name[] defaultTargetMetaInfo() {
3689         if (dfltTargetMeta == null) {
3690             ArrayList<Name> defaultTargets = new ArrayList<>();
3691             defaultTargets.add(names.PACKAGE);
3692             defaultTargets.add(names.TYPE);
3693             defaultTargets.add(names.FIELD);
3694             defaultTargets.add(names.METHOD);
3695             defaultTargets.add(names.CONSTRUCTOR);
3696             defaultTargets.add(names.ANNOTATION_TYPE);
3697             defaultTargets.add(names.LOCAL_VARIABLE);
3698             defaultTargets.add(names.PARAMETER);
3699             if (allowRecords) {
3700               defaultTargets.add(names.RECORD_COMPONENT);
3701             }
3702             if (allowModules) {
3703               defaultTargets.add(names.MODULE);
3704             }
3705             dfltTargetMeta = defaultTargets.toArray(new Name[0]);
3706         }
3707         return dfltTargetMeta;
3708     }
3709 
3710     /** Check an annotation value.
3711      *
3712      * @param a The annotation tree to check
3713      * @return true if this annotation tree is valid, otherwise false
3714      */
3715     public boolean validateAnnotationDeferErrors(JCAnnotation a) {
3716         boolean res = false;
3717         final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
3718         try {
3719             res = validateAnnotation(a);
3720         } finally {
3721             log.popDiagnosticHandler(diagHandler);
3722         }
3723         return res;
3724     }
3725 
3726     private boolean validateAnnotation(JCAnnotation a) {
3727         boolean isValid = true;
3728         AnnotationTypeMetadata metadata = a.annotationType.type.tsym.getAnnotationTypeMetadata();
3729 
3730         // collect an inventory of the annotation elements
3731         Set<MethodSymbol> elements = metadata.getAnnotationElements();
3732 
3733         // remove the ones that are assigned values
3734         for (JCTree arg : a.args) {
3735             if (!arg.hasTag(ASSIGN)) continue; // recovery
3736             JCAssign assign = (JCAssign)arg;
3737             Symbol m = TreeInfo.symbol(assign.lhs);
3738             if (m == null || m.type.isErroneous()) continue;
3739             if (!elements.remove(m)) {
3740                 isValid = false;
3741                 log.error(assign.lhs.pos(),
3742                           Errors.DuplicateAnnotationMemberValue(m.name, a.type));
3743             }
3744         }
3745 
3746         // all the remaining ones better have default values
3747         List<Name> missingDefaults = List.nil();
3748         Set<MethodSymbol> membersWithDefault = metadata.getAnnotationElementsWithDefault();
3749         for (MethodSymbol m : elements) {
3750             if (m.type.isErroneous())
3751                 continue;
3752 
3753             if (!membersWithDefault.contains(m))
3754                 missingDefaults = missingDefaults.append(m.name);
3755         }
3756         missingDefaults = missingDefaults.reverse();
3757         if (missingDefaults.nonEmpty()) {
3758             isValid = false;
3759             Error errorKey = (missingDefaults.size() > 1)
3760                     ? Errors.AnnotationMissingDefaultValue1(a.type, missingDefaults)
3761                     : Errors.AnnotationMissingDefaultValue(a.type, missingDefaults);
3762             log.error(a.pos(), errorKey);
3763         }
3764 
3765         return isValid && validateTargetAnnotationValue(a);
3766     }
3767 
3768     /* Validate the special java.lang.annotation.Target annotation */
3769     boolean validateTargetAnnotationValue(JCAnnotation a) {
3770         // special case: java.lang.annotation.Target must not have
3771         // repeated values in its value member
3772         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
3773                 a.args.tail == null)
3774             return true;
3775 
3776         boolean isValid = true;
3777         if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
3778         JCAssign assign = (JCAssign) a.args.head;
3779         Symbol m = TreeInfo.symbol(assign.lhs);
3780         if (m.name != names.value) return false;
3781         JCTree rhs = assign.rhs;
3782         if (!rhs.hasTag(NEWARRAY)) return false;
3783         JCNewArray na = (JCNewArray) rhs;
3784         Set<Symbol> targets = new HashSet<>();
3785         for (JCTree elem : na.elems) {
3786             if (!targets.add(TreeInfo.symbol(elem))) {
3787                 isValid = false;
3788                 log.error(elem.pos(), Errors.RepeatedAnnotationTarget);
3789             }
3790         }
3791         return isValid;
3792     }
3793 
3794     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
3795         if (lint.isEnabled(LintCategory.DEP_ANN) && s.isDeprecatableViaAnnotation() &&
3796             (s.flags() & DEPRECATED) != 0 &&
3797             !syms.deprecatedType.isErroneous() &&
3798             s.attribute(syms.deprecatedType.tsym) == null) {
3799             log.warning(LintCategory.DEP_ANN,
3800                     pos, Warnings.MissingDeprecatedAnnotation);
3801         }
3802         // Note: @Deprecated has no effect on local variables, parameters and package decls.
3803         if (lint.isEnabled(LintCategory.DEPRECATION) && !s.isDeprecatableViaAnnotation()) {
3804             if (!syms.deprecatedType.isErroneous() && s.attribute(syms.deprecatedType.tsym) != null) {
3805                 log.warning(LintCategory.DEPRECATION, pos,
3806                             Warnings.DeprecatedAnnotationHasNoEffect(Kinds.kindName(s)));
3807             }
3808         }
3809     }
3810 
3811     void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
3812         checkDeprecated(() -> pos, other, s);
3813     }
3814 
3815     void checkDeprecated(Supplier<DiagnosticPosition> pos, final Symbol other, final Symbol s) {
3816         if ( (s.isDeprecatedForRemoval()
3817                 || s.isDeprecated() && !other.isDeprecated())
3818                 && (s.outermostClass() != other.outermostClass() || s.outermostClass() == null)
3819                 && s.kind != Kind.PCK) {
3820             deferredLintHandler.report(() -> warnDeprecated(pos.get(), s));
3821         }
3822     }
3823 
3824     void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
3825         if ((s.flags() & PROPRIETARY) != 0) {
3826             deferredLintHandler.report(() -> {
3827                 log.mandatoryWarning(pos, Warnings.SunProprietary(s));
3828             });
3829         }
3830     }
3831 
3832     void checkProfile(final DiagnosticPosition pos, final Symbol s) {
3833         if (profile != Profile.DEFAULT && (s.flags() & NOT_IN_PROFILE) != 0) {
3834             log.error(pos, Errors.NotInProfile(s, profile));
3835         }
3836     }
3837 
3838     void checkPreview(DiagnosticPosition pos, Symbol other, Symbol s) {
3839         if ((s.flags() & PREVIEW_API) != 0 && !preview.participatesInPreview(syms, other, s) && !disablePreviewCheck) {
3840             if ((s.flags() & PREVIEW_REFLECTIVE) == 0) {
3841                 if (!preview.isEnabled()) {
3842                     log.error(pos, Errors.IsPreview(s));
3843                 } else {
3844                     preview.markUsesPreview(pos);
3845                     deferredLintHandler.report(() -> warnPreviewAPI(pos, Warnings.IsPreview(s)));
3846                 }
3847             } else {
3848                     deferredLintHandler.report(() -> warnPreviewAPI(pos, Warnings.IsPreviewReflective(s)));
3849             }
3850         }
3851         if (preview.declaredUsingPreviewFeature(s)) {
3852             if (preview.isEnabled()) {
3853                 //for preview disabled do presumably so not need to do anything?
3854                 //If "s" is compiled from source, then there was an error for it already;
3855                 //if "s" is from classfile, there already was an error for the classfile.
3856                 preview.markUsesPreview(pos);
3857                 deferredLintHandler.report(() -> warnDeclaredUsingPreview(pos, s));
3858             }
3859         }
3860     }
3861 
3862     void checkRestricted(DiagnosticPosition pos, Symbol s) {
3863         if (s.kind == MTH && (s.flags() & RESTRICTED) != 0) {
3864             deferredLintHandler.report(() -> warnRestrictedAPI(pos, s));
3865         }
3866     }
3867 
3868 /* *************************************************************************
3869  * Check for recursive annotation elements.
3870  **************************************************************************/
3871 
3872     /** Check for cycles in the graph of annotation elements.
3873      */
3874     void checkNonCyclicElements(JCClassDecl tree) {
3875         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
3876         Assert.check((tree.sym.flags_field & LOCKED) == 0);
3877         try {
3878             tree.sym.flags_field |= LOCKED;
3879             for (JCTree def : tree.defs) {
3880                 if (!def.hasTag(METHODDEF)) continue;
3881                 JCMethodDecl meth = (JCMethodDecl)def;
3882                 checkAnnotationResType(meth.pos(), meth.restype.type);
3883             }
3884         } finally {
3885             tree.sym.flags_field &= ~LOCKED;
3886             tree.sym.flags_field |= ACYCLIC_ANN;
3887         }
3888     }
3889 
3890     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
3891         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
3892             return;
3893         if ((tsym.flags_field & LOCKED) != 0) {
3894             log.error(pos, Errors.CyclicAnnotationElement(tsym));
3895             return;
3896         }
3897         try {
3898             tsym.flags_field |= LOCKED;
3899             for (Symbol s : tsym.members().getSymbols(NON_RECURSIVE)) {
3900                 if (s.kind != MTH)
3901                     continue;
3902                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
3903             }
3904         } finally {
3905             tsym.flags_field &= ~LOCKED;
3906             tsym.flags_field |= ACYCLIC_ANN;
3907         }
3908     }
3909 
3910     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
3911         switch (type.getTag()) {
3912         case CLASS:
3913             if ((type.tsym.flags() & ANNOTATION) != 0)
3914                 checkNonCyclicElementsInternal(pos, type.tsym);
3915             break;
3916         case ARRAY:
3917             checkAnnotationResType(pos, types.elemtype(type));
3918             break;
3919         default:
3920             break; // int etc
3921         }
3922     }
3923 
3924 /* *************************************************************************
3925  * Check for cycles in the constructor call graph.
3926  **************************************************************************/
3927 
3928     /** Check for cycles in the graph of constructors calling other
3929      *  constructors.
3930      */
3931     void checkCyclicConstructors(JCClassDecl tree) {
3932         // use LinkedHashMap so we generate errors deterministically
3933         Map<Symbol,Symbol> callMap = new LinkedHashMap<>();
3934 
3935         // enter each constructor this-call into the map
3936         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3937             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
3938             if (app == null) continue;
3939             JCMethodDecl meth = (JCMethodDecl) l.head;
3940             if (TreeInfo.name(app.meth) == names._this) {

3941                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
3942             } else {
3943                 meth.sym.flags_field |= ACYCLIC;
3944             }
3945         }
3946 
3947         // Check for cycles in the map
3948         Symbol[] ctors = new Symbol[0];
3949         ctors = callMap.keySet().toArray(ctors);
3950         for (Symbol caller : ctors) {
3951             checkCyclicConstructor(tree, caller, callMap);
3952         }
3953     }
3954 
3955     /** Look in the map to see if the given constructor is part of a
3956      *  call cycle.
3957      */
3958     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
3959                                         Map<Symbol,Symbol> callMap) {
3960         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
3961             if ((ctor.flags_field & LOCKED) != 0) {
3962                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree, false, t -> t.hasTag(IDENT)),
3963                           Errors.RecursiveCtorInvocation);
3964             } else {
3965                 ctor.flags_field |= LOCKED;
3966                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
3967                 ctor.flags_field &= ~LOCKED;
3968             }
3969             ctor.flags_field |= ACYCLIC;
3970         }
3971     }
3972 





























































































































3973 /* *************************************************************************
3974  * Miscellaneous
3975  **************************************************************************/
3976 
3977     /**
3978      *  Check for division by integer constant zero
3979      *  @param pos           Position for error reporting.
3980      *  @param operator      The operator for the expression
3981      *  @param operand       The right hand operand for the expression
3982      */
3983     void checkDivZero(final DiagnosticPosition pos, Symbol operator, Type operand) {
3984         if (operand.constValue() != null
3985             && operand.getTag().isSubRangeOf(LONG)
3986             && ((Number) (operand.constValue())).longValue() == 0) {
3987             int opc = ((OperatorSymbol)operator).opcode;
3988             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
3989                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
3990                 deferredLintHandler.report(() -> warnDivZero(pos));
3991             }
3992         }
3993     }
3994 
3995     /**
3996      *  Check for possible loss of precission
3997      *  @param pos           Position for error reporting.
3998      *  @param found    The computed type of the tree
3999      *  @param req  The computed type of the tree
4000      */
4001     void checkLossOfPrecision(final DiagnosticPosition pos, Type found, Type req) {
4002         if (found.isNumeric() && req.isNumeric() && !types.isAssignable(found, req)) {
4003             deferredLintHandler.report(() -> {
4004                 if (lint.isEnabled(LintCategory.LOSSY_CONVERSIONS))
4005                     log.warning(LintCategory.LOSSY_CONVERSIONS,
4006                             pos, Warnings.PossibleLossOfPrecision(found, req));
4007             });
4008         }
4009     }
4010 
4011     /**
4012      * Check for empty statements after if
4013      */
4014     void checkEmptyIf(JCIf tree) {
4015         if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
4016                 lint.isEnabled(LintCategory.EMPTY))
4017             log.warning(LintCategory.EMPTY, tree.thenpart.pos(), Warnings.EmptyIf);
4018     }
4019 
4020     /** Check that symbol is unique in given scope.
4021      *  @param pos           Position for error reporting.
4022      *  @param sym           The symbol.
4023      *  @param s             The scope.
4024      */
4025     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
4026         if (sym.type.isErroneous())
4027             return true;
4028         if (sym.owner.name == names.any) return false;
4029         for (Symbol byName : s.getSymbolsByName(sym.name, NON_RECURSIVE)) {
4030             if (sym != byName &&
4031                     (byName.flags() & CLASH) == 0 &&
4032                     sym.kind == byName.kind &&
4033                     sym.name != names.error &&
4034                     (sym.kind != MTH ||
4035                      types.hasSameArgs(sym.type, byName.type) ||
4036                      types.hasSameArgs(types.erasure(sym.type), types.erasure(byName.type)))) {
4037                 if ((sym.flags() & VARARGS) != (byName.flags() & VARARGS)) {
4038                     sym.flags_field |= CLASH;
4039                     varargsDuplicateError(pos, sym, byName);
4040                     return true;
4041                 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, byName.type, false)) {
4042                     duplicateErasureError(pos, sym, byName);
4043                     sym.flags_field |= CLASH;
4044                     return true;
4045                 } else if ((sym.flags() & MATCH_BINDING) != 0 &&
4046                            (byName.flags() & MATCH_BINDING) != 0 &&
4047                            (byName.flags() & MATCH_BINDING_TO_OUTER) == 0) {
4048                     if (!sym.type.isErroneous()) {
4049                         log.error(pos, Errors.MatchBindingExists);
4050                         sym.flags_field |= CLASH;
4051                     }
4052                     return false;
4053                 } else {
4054                     duplicateError(pos, byName);
4055                     return false;
4056                 }
4057             }
4058         }
4059         return true;
4060     }
4061 
4062     /** Report duplicate declaration error.
4063      */
4064     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
4065         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
4066             log.error(pos, Errors.NameClashSameErasure(sym1, sym2));
4067         }
4068     }
4069 
4070     /**Check that types imported through the ordinary imports don't clash with types imported
4071      * by other (static or ordinary) imports. Note that two static imports may import two clashing
4072      * types without an error on the imports.
4073      * @param toplevel       The toplevel tree for which the test should be performed.
4074      */
4075     void checkImportsUnique(JCCompilationUnit toplevel) {
4076         WriteableScope ordinallyImportedSoFar = WriteableScope.create(toplevel.packge);
4077         WriteableScope staticallyImportedSoFar = WriteableScope.create(toplevel.packge);
4078         WriteableScope topLevelScope = toplevel.toplevelScope;
4079 
4080         for (JCTree def : toplevel.defs) {
4081             if (!def.hasTag(IMPORT))
4082                 continue;
4083 
4084             JCImport imp = (JCImport) def;
4085 
4086             if (imp.importScope == null)
4087                 continue;
4088 
4089             for (Symbol sym : imp.importScope.getSymbols(sym -> sym.kind == TYP)) {
4090                 if (imp.isStatic()) {
4091                     checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, true);
4092                     staticallyImportedSoFar.enter(sym);
4093                 } else {
4094                     checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, false);
4095                     ordinallyImportedSoFar.enter(sym);
4096                 }
4097             }
4098 
4099             imp.importScope = null;
4100         }
4101     }
4102 
4103     /** Check that single-type import is not already imported or top-level defined,
4104      *  but make an exception for two single-type imports which denote the same type.
4105      *  @param pos                     Position for error reporting.
4106      *  @param ordinallyImportedSoFar  A Scope containing types imported so far through
4107      *                                 ordinary imports.
4108      *  @param staticallyImportedSoFar A Scope containing types imported so far through
4109      *                                 static imports.
4110      *  @param topLevelScope           The current file's top-level Scope
4111      *  @param sym                     The symbol.
4112      *  @param staticImport            Whether or not this was a static import
4113      */
4114     private boolean checkUniqueImport(DiagnosticPosition pos, Scope ordinallyImportedSoFar,
4115                                       Scope staticallyImportedSoFar, Scope topLevelScope,
4116                                       Symbol sym, boolean staticImport) {
4117         Predicate<Symbol> duplicates = candidate -> candidate != sym && !candidate.type.isErroneous();
4118         Symbol ordinaryClashing = ordinallyImportedSoFar.findFirst(sym.name, duplicates);
4119         Symbol staticClashing = null;
4120         if (ordinaryClashing == null && !staticImport) {
4121             staticClashing = staticallyImportedSoFar.findFirst(sym.name, duplicates);
4122         }
4123         if (ordinaryClashing != null || staticClashing != null) {
4124             if (ordinaryClashing != null)
4125                 log.error(pos, Errors.AlreadyDefinedSingleImport(ordinaryClashing));
4126             else
4127                 log.error(pos, Errors.AlreadyDefinedStaticSingleImport(staticClashing));
4128             return false;
4129         }
4130         Symbol clashing = topLevelScope.findFirst(sym.name, duplicates);
4131         if (clashing != null) {
4132             log.error(pos, Errors.AlreadyDefinedThisUnit(clashing));
4133             return false;
4134         }
4135         return true;
4136     }
4137 
4138     /** Check that a qualified name is in canonical form (for import decls).
4139      */
4140     public void checkCanonical(JCTree tree) {
4141         if (!isCanonical(tree))
4142             log.error(tree.pos(),
4143                       Errors.ImportRequiresCanonical(TreeInfo.symbol(tree)));
4144     }
4145         // where
4146         private boolean isCanonical(JCTree tree) {
4147             while (tree.hasTag(SELECT)) {
4148                 JCFieldAccess s = (JCFieldAccess) tree;
4149                 if (s.sym.owner.getQualifiedName() != TreeInfo.symbol(s.selected).getQualifiedName())
4150                     return false;
4151                 tree = s.selected;
4152             }
4153             return true;
4154         }
4155 
4156     /** Check that an auxiliary class is not accessed from any other file than its own.
4157      */
4158     void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
4159         if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
4160             (c.flags() & AUXILIARY) != 0 &&
4161             rs.isAccessible(env, c) &&
4162             !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
4163         {
4164             log.warning(pos,
4165                         Warnings.AuxiliaryClassAccessedFromOutsideOfItsSourceFile(c, c.sourcefile));
4166         }
4167     }
4168 
4169     /**
4170      * Check for a default constructor in an exported package.
4171      */
4172     void checkDefaultConstructor(ClassSymbol c, DiagnosticPosition pos) {
4173         if (lint.isEnabled(LintCategory.MISSING_EXPLICIT_CTOR) &&
4174             ((c.flags() & (ENUM | RECORD)) == 0) &&
4175             !c.isAnonymous() &&
4176             ((c.flags() & (PUBLIC | PROTECTED)) != 0) &&
4177             Feature.MODULES.allowedInSource(source)) {
4178             NestingKind nestingKind = c.getNestingKind();
4179             switch (nestingKind) {
4180                 case ANONYMOUS,
4181                      LOCAL -> {return;}
4182                 case TOP_LEVEL -> {;} // No additional checks needed
4183                 case MEMBER -> {
4184                     // For nested member classes, all the enclosing
4185                     // classes must be public or protected.
4186                     Symbol owner = c.owner;
4187                     while (owner != null && owner.kind == TYP) {
4188                         if ((owner.flags() & (PUBLIC | PROTECTED)) == 0)
4189                             return;
4190                         owner = owner.owner;
4191                     }
4192                 }
4193             }
4194 
4195             // Only check classes in named packages exported by its module
4196             PackageSymbol pkg = c.packge();
4197             if (!pkg.isUnnamed()) {
4198                 ModuleSymbol modle = pkg.modle;
4199                 for (ExportsDirective exportDir : modle.exports) {
4200                     // Report warning only if the containing
4201                     // package is unconditionally exported
4202                     if (exportDir.packge.equals(pkg)) {
4203                         if (exportDir.modules == null || exportDir.modules.isEmpty()) {
4204                             // Warning may be suppressed by
4205                             // annotations; check again for being
4206                             // enabled in the deferred context.
4207                             deferredLintHandler.report(() -> {
4208                                 if (lint.isEnabled(LintCategory.MISSING_EXPLICIT_CTOR))
4209                                    log.warning(LintCategory.MISSING_EXPLICIT_CTOR,
4210                                                pos, Warnings.MissingExplicitCtor(c, pkg, modle));
4211                                                        });
4212                         } else {
4213                             return;
4214                         }
4215                     }
4216                 }
4217             }
4218         }
4219         return;
4220     }
4221 
4222     private class ConversionWarner extends Warner {
4223         final String uncheckedKey;
4224         final Type found;
4225         final Type expected;
4226         public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
4227             super(pos);
4228             this.uncheckedKey = uncheckedKey;
4229             this.found = found;
4230             this.expected = expected;
4231         }
4232 
4233         @Override
4234         public void warn(LintCategory lint) {
4235             boolean warned = this.warned;
4236             super.warn(lint);
4237             if (warned) return; // suppress redundant diagnostics
4238             switch (lint) {
4239                 case UNCHECKED:
4240                     Check.this.warnUnchecked(pos(), Warnings.ProbFoundReq(diags.fragment(uncheckedKey), found, expected));
4241                     break;
4242                 case VARARGS:
4243                     if (method != null &&
4244                             method.attribute(syms.trustMeType.tsym) != null &&
4245                             isTrustMeAllowedOnMethod(method) &&
4246                             !types.isReifiable(method.type.getParameterTypes().last())) {
4247                         Check.this.warnUnsafeVararg(pos(), Warnings.VarargsUnsafeUseVarargsParam(method.params.last()));
4248                     }
4249                     break;
4250                 default:
4251                     throw new AssertionError("Unexpected lint: " + lint);
4252             }
4253         }
4254     }
4255 
4256     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
4257         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
4258     }
4259 
4260     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
4261         return new ConversionWarner(pos, "unchecked.assign", found, expected);
4262     }
4263 
4264     public void checkFunctionalInterface(JCClassDecl tree, ClassSymbol cs) {
4265         Compound functionalType = cs.attribute(syms.functionalInterfaceType.tsym);
4266 
4267         if (functionalType != null) {
4268             try {
4269                 types.findDescriptorSymbol((TypeSymbol)cs);
4270             } catch (Types.FunctionDescriptorLookupError ex) {
4271                 DiagnosticPosition pos = tree.pos();
4272                 for (JCAnnotation a : tree.getModifiers().annotations) {
4273                     if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
4274                         pos = a.pos();
4275                         break;
4276                     }
4277                 }
4278                 log.error(pos, Errors.BadFunctionalIntfAnno1(ex.getDiagnostic()));
4279             }
4280         }
4281     }
4282 
4283     public void checkImportsResolvable(final JCCompilationUnit toplevel) {
4284         for (final JCImport imp : toplevel.getImports()) {
4285             if (!imp.staticImport || !imp.qualid.hasTag(SELECT))
4286                 continue;
4287             final JCFieldAccess select = imp.qualid;
4288             final Symbol origin;
4289             if (select.name == names.asterisk || (origin = TreeInfo.symbol(select.selected)) == null || origin.kind != TYP)
4290                 continue;
4291 
4292             TypeSymbol site = (TypeSymbol) TreeInfo.symbol(select.selected);
4293             if (!checkTypeContainsImportableElement(site, site, toplevel.packge, select.name, new HashSet<Symbol>())) {
4294                 log.error(imp.pos(),
4295                           Errors.CantResolveLocation(KindName.STATIC,
4296                                                      select.name,
4297                                                      null,
4298                                                      null,
4299                                                      Fragments.Location(kindName(site),
4300                                                                         site,
4301                                                                         null)));
4302             }
4303         }
4304     }
4305 
4306     // Check that packages imported are in scope (JLS 7.4.3, 6.3, 6.5.3.1, 6.5.3.2)
4307     public void checkImportedPackagesObservable(final JCCompilationUnit toplevel) {
4308         OUTER: for (JCImport imp : toplevel.getImports()) {
4309             if (!imp.staticImport && TreeInfo.name(imp.qualid) == names.asterisk) {
4310                 TypeSymbol tsym = imp.qualid.selected.type.tsym;
4311                 if (tsym.kind == PCK && tsym.members().isEmpty() &&
4312                     !(Feature.IMPORT_ON_DEMAND_OBSERVABLE_PACKAGES.allowedInSource(source) && tsym.exists())) {
4313                     log.error(DiagnosticFlag.RESOLVE_ERROR, imp.pos, Errors.DoesntExist(tsym));
4314                 }
4315             }
4316         }
4317     }
4318 
4319     private boolean checkTypeContainsImportableElement(TypeSymbol tsym, TypeSymbol origin, PackageSymbol packge, Name name, Set<Symbol> processed) {
4320         if (tsym == null || !processed.add(tsym))
4321             return false;
4322 
4323             // also search through inherited names
4324         if (checkTypeContainsImportableElement(types.supertype(tsym.type).tsym, origin, packge, name, processed))
4325             return true;
4326 
4327         for (Type t : types.interfaces(tsym.type))
4328             if (checkTypeContainsImportableElement(t.tsym, origin, packge, name, processed))
4329                 return true;
4330 
4331         for (Symbol sym : tsym.members().getSymbolsByName(name)) {
4332             if (sym.isStatic() &&
4333                 importAccessible(sym, packge) &&
4334                 sym.isMemberOf(origin, types)) {
4335                 return true;
4336             }
4337         }
4338 
4339         return false;
4340     }
4341 
4342     // is the sym accessible everywhere in packge?
4343     public boolean importAccessible(Symbol sym, PackageSymbol packge) {
4344         try {
4345             int flags = (int)(sym.flags() & AccessFlags);
4346             switch (flags) {
4347             default:
4348             case PUBLIC:
4349                 return true;
4350             case PRIVATE:
4351                 return false;
4352             case 0:
4353             case PROTECTED:
4354                 return sym.packge() == packge;
4355             }
4356         } catch (ClassFinder.BadClassFile err) {
4357             throw err;
4358         } catch (CompletionFailure ex) {
4359             return false;
4360         }
4361     }
4362 
4363     public Type checkProcessorType(JCExpression processor, Type resultType, Env<AttrContext> env) {
4364         Type processorType = processor.type;
4365         Type interfaceType = types.asSuper(processorType, syms.processorType.tsym);
4366 
4367         if (interfaceType != null) {
4368             List<Type> typeArguments = interfaceType.getTypeArguments();
4369 
4370             if (typeArguments.size() == 2) {
4371                 resultType = typeArguments.head;
4372             } else {
4373                 resultType = syms.objectType;
4374             }
4375         } else {
4376             log.error(DiagnosticFlag.RESOLVE_ERROR, processor.pos,
4377                     Errors.NotAProcessorType(processorType.tsym));
4378         }
4379 
4380         return resultType;
4381     }
4382 
4383     public void checkLeaksNotAccessible(Env<AttrContext> env, JCClassDecl check) {
4384         JCCompilationUnit toplevel = env.toplevel;
4385 
4386         if (   toplevel.modle == syms.unnamedModule
4387             || toplevel.modle == syms.noModule
4388             || (check.sym.flags() & COMPOUND) != 0) {
4389             return ;
4390         }
4391 
4392         ExportsDirective currentExport = findExport(toplevel.packge);
4393 
4394         if (   currentExport == null //not exported
4395             || currentExport.modules != null) //don't check classes in qualified export
4396             return ;
4397 
4398         new TreeScanner() {
4399             Lint lint = env.info.lint;
4400             boolean inSuperType;
4401 
4402             @Override
4403             public void visitBlock(JCBlock tree) {
4404             }
4405             @Override
4406             public void visitMethodDef(JCMethodDecl tree) {
4407                 if (!isAPISymbol(tree.sym))
4408                     return;
4409                 Lint prevLint = lint;
4410                 try {
4411                     lint = lint.augment(tree.sym);
4412                     if (lint.isEnabled(LintCategory.EXPORTS)) {
4413                         super.visitMethodDef(tree);
4414                     }
4415                 } finally {
4416                     lint = prevLint;
4417                 }
4418             }
4419             @Override
4420             public void visitVarDef(JCVariableDecl tree) {
4421                 if (!isAPISymbol(tree.sym) && tree.sym.owner.kind != MTH)
4422                     return;
4423                 Lint prevLint = lint;
4424                 try {
4425                     lint = lint.augment(tree.sym);
4426                     if (lint.isEnabled(LintCategory.EXPORTS)) {
4427                         scan(tree.mods);
4428                         scan(tree.vartype);
4429                     }
4430                 } finally {
4431                     lint = prevLint;
4432                 }
4433             }
4434             @Override
4435             public void visitClassDef(JCClassDecl tree) {
4436                 if (tree != check)
4437                     return ;
4438 
4439                 if (!isAPISymbol(tree.sym))
4440                     return ;
4441 
4442                 Lint prevLint = lint;
4443                 try {
4444                     lint = lint.augment(tree.sym);
4445                     if (lint.isEnabled(LintCategory.EXPORTS)) {
4446                         scan(tree.mods);
4447                         scan(tree.typarams);
4448                         try {
4449                             inSuperType = true;
4450                             scan(tree.extending);
4451                             scan(tree.implementing);
4452                         } finally {
4453                             inSuperType = false;
4454                         }
4455                         scan(tree.defs);
4456                     }
4457                 } finally {
4458                     lint = prevLint;
4459                 }
4460             }
4461             @Override
4462             public void visitTypeApply(JCTypeApply tree) {
4463                 scan(tree.clazz);
4464                 boolean oldInSuperType = inSuperType;
4465                 try {
4466                     inSuperType = false;
4467                     scan(tree.arguments);
4468                 } finally {
4469                     inSuperType = oldInSuperType;
4470                 }
4471             }
4472             @Override
4473             public void visitIdent(JCIdent tree) {
4474                 Symbol sym = TreeInfo.symbol(tree);
4475                 if (sym.kind == TYP && !sym.type.hasTag(TYPEVAR)) {
4476                     checkVisible(tree.pos(), sym, toplevel.packge, inSuperType);
4477                 }
4478             }
4479 
4480             @Override
4481             public void visitSelect(JCFieldAccess tree) {
4482                 Symbol sym = TreeInfo.symbol(tree);
4483                 Symbol sitesym = TreeInfo.symbol(tree.selected);
4484                 if (sym.kind == TYP && sitesym.kind == PCK) {
4485                     checkVisible(tree.pos(), sym, toplevel.packge, inSuperType);
4486                 } else {
4487                     super.visitSelect(tree);
4488                 }
4489             }
4490 
4491             @Override
4492             public void visitAnnotation(JCAnnotation tree) {
4493                 if (tree.attribute.type.tsym.getAnnotation(java.lang.annotation.Documented.class) != null)
4494                     super.visitAnnotation(tree);
4495             }
4496 
4497         }.scan(check);
4498     }
4499         //where:
4500         private ExportsDirective findExport(PackageSymbol pack) {
4501             for (ExportsDirective d : pack.modle.exports) {
4502                 if (d.packge == pack)
4503                     return d;
4504             }
4505 
4506             return null;
4507         }
4508         private boolean isAPISymbol(Symbol sym) {
4509             while (sym.kind != PCK) {
4510                 if ((sym.flags() & Flags.PUBLIC) == 0 && (sym.flags() & Flags.PROTECTED) == 0) {
4511                     return false;
4512                 }
4513                 sym = sym.owner;
4514             }
4515             return true;
4516         }
4517         private void checkVisible(DiagnosticPosition pos, Symbol what, PackageSymbol inPackage, boolean inSuperType) {
4518             if (!isAPISymbol(what) && !inSuperType) { //package private/private element
4519                 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessible(kindName(what), what, what.packge().modle));
4520                 return ;
4521             }
4522 
4523             PackageSymbol whatPackage = what.packge();
4524             ExportsDirective whatExport = findExport(whatPackage);
4525             ExportsDirective inExport = findExport(inPackage);
4526 
4527             if (whatExport == null) { //package not exported:
4528                 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleUnexported(kindName(what), what, what.packge().modle));
4529                 return ;
4530             }
4531 
4532             if (whatExport.modules != null) {
4533                 if (inExport.modules == null || !whatExport.modules.containsAll(inExport.modules)) {
4534                     log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleUnexportedQualified(kindName(what), what, what.packge().modle));
4535                 }
4536             }
4537 
4538             if (whatPackage.modle != inPackage.modle && whatPackage.modle != syms.java_base) {
4539                 //check that relativeTo.modle requires transitive what.modle, somehow:
4540                 List<ModuleSymbol> todo = List.of(inPackage.modle);
4541 
4542                 while (todo.nonEmpty()) {
4543                     ModuleSymbol current = todo.head;
4544                     todo = todo.tail;
4545                     if (current == whatPackage.modle)
4546                         return ; //OK
4547                     if ((current.flags() & Flags.AUTOMATIC_MODULE) != 0)
4548                         continue; //for automatic modules, don't look into their dependencies
4549                     for (RequiresDirective req : current.requires) {
4550                         if (req.isTransitive()) {
4551                             todo = todo.prepend(req.module);
4552                         }
4553                     }
4554                 }
4555 
4556                 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleNotRequiredTransitive(kindName(what), what, what.packge().modle));
4557             }
4558         }
4559 
4560     void checkModuleExists(final DiagnosticPosition pos, ModuleSymbol msym) {
4561         if (msym.kind != MDL) {
4562             deferredLintHandler.report(() -> {
4563                 if (lint.isEnabled(LintCategory.MODULE))
4564                     log.warning(LintCategory.MODULE, pos, Warnings.ModuleNotFound(msym));
4565             });
4566         }
4567     }
4568 
4569     void checkPackageExistsForOpens(final DiagnosticPosition pos, PackageSymbol packge) {
4570         if (packge.members().isEmpty() &&
4571             ((packge.flags() & Flags.HAS_RESOURCE) == 0)) {
4572             deferredLintHandler.report(() -> {
4573                 if (lint.isEnabled(LintCategory.OPENS))
4574                     log.warning(pos, Warnings.PackageEmptyOrNotFound(packge));
4575             });
4576         }
4577     }
4578 
4579     void checkModuleRequires(final DiagnosticPosition pos, final RequiresDirective rd) {
4580         if ((rd.module.flags() & Flags.AUTOMATIC_MODULE) != 0) {
4581             deferredLintHandler.report(() -> {
4582                 if (rd.isTransitive() && lint.isEnabled(LintCategory.REQUIRES_TRANSITIVE_AUTOMATIC)) {
4583                     log.warning(pos, Warnings.RequiresTransitiveAutomatic);
4584                 } else if (lint.isEnabled(LintCategory.REQUIRES_AUTOMATIC)) {
4585                     log.warning(pos, Warnings.RequiresAutomatic);
4586                 }
4587             });
4588         }
4589     }
4590 
4591     /**
4592      * Verify the case labels conform to the constraints. Checks constraints related
4593      * combinations of patterns and other labels.
4594      *
4595      * @param cases the cases that should be checked.
4596      */
4597     void checkSwitchCaseStructure(List<JCCase> cases) {
4598         for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
4599             JCCase c = l.head;
4600             if (c.labels.head instanceof JCConstantCaseLabel constLabel) {
4601                 if (TreeInfo.isNull(constLabel.expr)) {
4602                     if (c.labels.tail.nonEmpty()) {
4603                         if (c.labels.tail.head instanceof JCDefaultCaseLabel defLabel) {
4604                             if (c.labels.tail.tail.nonEmpty()) {
4605                                 log.error(c.labels.tail.tail.head.pos(), Errors.InvalidCaseLabelCombination);
4606                             }
4607                         } else {
4608                             log.error(c.labels.tail.head.pos(), Errors.InvalidCaseLabelCombination);
4609                         }
4610                     }
4611                 } else {
4612                     for (JCCaseLabel label : c.labels.tail) {
4613                         if (!(label instanceof JCConstantCaseLabel) || TreeInfo.isNullCaseLabel(label)) {
4614                             log.error(label.pos(), Errors.InvalidCaseLabelCombination);
4615                             break;
4616                         }
4617                     }
4618                 }
4619             } else if (c.labels.tail.nonEmpty()) {
4620                 var patterCaseLabels = c.labels.stream().filter(ll -> ll instanceof JCPatternCaseLabel).map(cl -> (JCPatternCaseLabel)cl);
4621                 var allUnderscore = patterCaseLabels.allMatch(pcl -> !hasBindings(pcl.getPattern()));
4622 
4623                 if (!allUnderscore) {
4624                     log.error(c.labels.tail.head.pos(), Errors.FlowsThroughFromPattern);
4625                 }
4626 
4627                 boolean allPatternCaseLabels = c.labels.stream().allMatch(p -> p instanceof JCPatternCaseLabel);
4628 
4629                 if (allPatternCaseLabels) {
4630                     preview.checkSourceLevel(c.labels.tail.head.pos(), Feature.UNNAMED_VARIABLES);
4631                 }
4632 
4633                 for (JCCaseLabel label : c.labels.tail) {
4634                     if (label instanceof JCConstantCaseLabel) {
4635                         log.error(label.pos(), Errors.InvalidCaseLabelCombination);
4636                         break;
4637                     }
4638                 }
4639             }
4640         }
4641 
4642         boolean isCaseStatementGroup = cases.nonEmpty() &&
4643                                        cases.head.caseKind == CaseTree.CaseKind.STATEMENT;
4644 
4645         if (isCaseStatementGroup) {
4646             boolean previousCompletessNormally = false;
4647             for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
4648                 JCCase c = l.head;
4649                 if (previousCompletessNormally &&
4650                     c.stats.nonEmpty() &&
4651                     c.labels.head instanceof JCPatternCaseLabel patternLabel &&
4652                     (hasBindings(patternLabel.pat) || hasBindings(c.guard))) {
4653                     log.error(c.labels.head.pos(), Errors.FlowsThroughToPattern);
4654                 } else if (c.stats.isEmpty() &&
4655                            c.labels.head instanceof JCPatternCaseLabel patternLabel &&
4656                            (hasBindings(patternLabel.pat) || hasBindings(c.guard)) &&
4657                            hasStatements(l.tail)) {
4658                     log.error(c.labels.head.pos(), Errors.FlowsThroughFromPattern);
4659                 }
4660                 previousCompletessNormally = c.completesNormally;
4661             }
4662         }
4663     }
4664 
4665     boolean hasBindings(JCTree p) {
4666         boolean[] bindings = new boolean[1];
4667 
4668         new TreeScanner() {
4669             @Override
4670             public void visitBindingPattern(JCBindingPattern tree) {
4671                 bindings[0] = !tree.var.sym.isUnnamedVariable();
4672                 super.visitBindingPattern(tree);
4673             }
4674         }.scan(p);
4675 
4676         return bindings[0];
4677     }
4678 
4679     boolean hasStatements(List<JCCase> cases) {
4680         for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
4681             if (l.head.stats.nonEmpty()) {
4682                 return true;
4683             }
4684         }
4685 
4686         return false;
4687     }
4688     void checkSwitchCaseLabelDominated(List<JCCase> cases) {
4689         List<Pair<JCCase, JCCaseLabel>> caseLabels = List.nil();
4690         boolean seenDefault = false;
4691         boolean seenDefaultLabel = false;
4692         boolean warnDominatedByDefault = false;
4693         for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
4694             JCCase c = l.head;
4695             for (JCCaseLabel label : c.labels) {
4696                 if (label.hasTag(DEFAULTCASELABEL)) {
4697                     seenDefault = true;
4698                     seenDefaultLabel |=
4699                             TreeInfo.isNullCaseLabel(c.labels.head);
4700                     continue;
4701                 }
4702                 if (TreeInfo.isNullCaseLabel(label)) {
4703                     if (seenDefault) {
4704                         log.error(label.pos(), Errors.PatternDominated);
4705                     }
4706                     continue;
4707                 }
4708                 if (seenDefault && !warnDominatedByDefault) {
4709                     if (label.hasTag(PATTERNCASELABEL) ||
4710                         (label instanceof JCConstantCaseLabel && seenDefaultLabel)) {
4711                         log.error(label.pos(), Errors.PatternDominated);
4712                         warnDominatedByDefault = true;
4713                     }
4714                 }
4715                 Type currentType = labelType(label);
4716                 for (Pair<JCCase, JCCaseLabel> caseAndLabel : caseLabels) {
4717                     JCCase testCase = caseAndLabel.fst;
4718                     JCCaseLabel testCaseLabel = caseAndLabel.snd;
4719                     Type testType = labelType(testCaseLabel);
4720                     if (types.isSubtype(currentType, testType) &&
4721                         !currentType.hasTag(ERROR) && !testType.hasTag(ERROR)) {
4722                         //the current label is potentially dominated by the existing (test) label, check:
4723                         boolean dominated = false;
4724                         if (label instanceof JCConstantCaseLabel) {
4725                             dominated |= !(testCaseLabel instanceof JCConstantCaseLabel) &&
4726                                          TreeInfo.unguardedCase(testCase);
4727                         } else if (label instanceof JCPatternCaseLabel patternCL &&
4728                                    testCaseLabel instanceof JCPatternCaseLabel testPatternCaseLabel &&
4729                                    (testCase.equals(c) || TreeInfo.unguardedCase(testCase))) {
4730                             dominated = patternDominated(testPatternCaseLabel.pat,
4731                                                          patternCL.pat);
4732                         }
4733                         if (dominated) {
4734                             log.error(label.pos(), Errors.PatternDominated);
4735                         }
4736                     }
4737                 }
4738                 caseLabels = caseLabels.prepend(Pair.of(c, label));
4739             }
4740         }
4741     }
4742         //where:
4743         private Type labelType(JCCaseLabel label) {
4744             return types.erasure(switch (label.getTag()) {
4745                 case PATTERNCASELABEL -> ((JCPatternCaseLabel) label).pat.type;
4746                 case CONSTANTCASELABEL -> types.boxedTypeOrType(((JCConstantCaseLabel) label).expr.type);
4747                 default -> throw Assert.error("Unexpected tree kind: " + label.getTag());
4748             });
4749         }
4750         private boolean patternDominated(JCPattern existingPattern, JCPattern currentPattern) {
4751             Type existingPatternType = types.erasure(existingPattern.type);
4752             Type currentPatternType = types.erasure(currentPattern.type);
4753             if (existingPatternType.isPrimitive() ^ currentPatternType.isPrimitive()) {
4754                 return false;
4755             }
4756             if (existingPatternType.isPrimitive()) {
4757                 return types.isSameType(existingPatternType, currentPatternType);
4758             } else {
4759                 if (!types.isSubtype(currentPatternType, existingPatternType)) {
4760                     return false;
4761                 }
4762             }
4763             if (currentPattern instanceof JCBindingPattern ||
4764                 currentPattern instanceof JCAnyPattern) {
4765                 return existingPattern instanceof JCBindingPattern ||
4766                        existingPattern instanceof JCAnyPattern;
4767             } else if (currentPattern instanceof JCRecordPattern currentRecordPattern) {
4768                 if (existingPattern instanceof JCBindingPattern ||
4769                     existingPattern instanceof JCAnyPattern) {
4770                     return true;
4771                 } else if (existingPattern instanceof JCRecordPattern existingRecordPattern) {
4772                     List<JCPattern> existingNested = existingRecordPattern.nested;
4773                     List<JCPattern> currentNested = currentRecordPattern.nested;
4774                     if (existingNested.size() != currentNested.size()) {
4775                         return false;
4776                     }
4777                     while (existingNested.nonEmpty()) {
4778                         if (!patternDominated(existingNested.head, currentNested.head)) {
4779                             return false;
4780                         }
4781                         existingNested = existingNested.tail;
4782                         currentNested = currentNested.tail;
4783                     }
4784                     return true;
4785                 } else {
4786                     Assert.error("Unknown pattern: " + existingPattern.getTag());
4787                 }
4788             } else {
4789                 Assert.error("Unknown pattern: " + currentPattern.getTag());
4790             }
4791             return false;
4792         }
4793 
4794     /** check if a type is a subtype of Externalizable, if that is available. */
4795     boolean isExternalizable(Type t) {
4796         try {
4797             syms.externalizableType.complete();
4798         } catch (CompletionFailure e) {
4799             return false;
4800         }
4801         return types.isSubtype(t, syms.externalizableType);
4802     }
4803 
4804     /**
4805      * Check structure of serialization declarations.
4806      */
4807     public void checkSerialStructure(JCClassDecl tree, ClassSymbol c) {
4808         (new SerialTypeVisitor()).visit(c, tree);
4809     }
4810 
4811     /**
4812      * This visitor will warn if a serialization-related field or
4813      * method is declared in a suspicious or incorrect way. In
4814      * particular, it will warn for cases where the runtime
4815      * serialization mechanism will silently ignore a mis-declared
4816      * entity.
4817      *
4818      * Distinguished serialization-related fields and methods:
4819      *
4820      * Methods:
4821      *
4822      * private void writeObject(ObjectOutputStream stream) throws IOException
4823      * ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException
4824      *
4825      * private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException
4826      * private void readObjectNoData() throws ObjectStreamException
4827      * ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException
4828      *
4829      * Fields:
4830      *
4831      * private static final long serialVersionUID
4832      * private static final ObjectStreamField[] serialPersistentFields
4833      *
4834      * Externalizable: methods defined on the interface
4835      * public void writeExternal(ObjectOutput) throws IOException
4836      * public void readExternal(ObjectInput) throws IOException
4837      */
4838     private class SerialTypeVisitor extends ElementKindVisitor14<Void, JCClassDecl> {
4839         SerialTypeVisitor() {
4840             this.lint = Check.this.lint;
4841         }
4842 
4843         private static final Set<String> serialMethodNames =
4844             Set.of("writeObject", "writeReplace",
4845                    "readObject",  "readObjectNoData",
4846                    "readResolve");
4847 
4848         private static final Set<String> serialFieldNames =
4849             Set.of("serialVersionUID", "serialPersistentFields");
4850 
4851         // Type of serialPersistentFields
4852         private final Type OSF_TYPE = new Type.ArrayType(syms.objectStreamFieldType, syms.arrayClass);
4853 
4854         Lint lint;
4855 
4856         @Override
4857         public Void defaultAction(Element e, JCClassDecl p) {
4858             throw new IllegalArgumentException(Objects.requireNonNullElse(e.toString(), ""));
4859         }
4860 
4861         @Override
4862         public Void visitType(TypeElement e, JCClassDecl p) {
4863             runUnderLint(e, p, (symbol, param) -> super.visitType(symbol, param));
4864             return null;
4865         }
4866 
4867         @Override
4868         public Void visitTypeAsClass(TypeElement e,
4869                                      JCClassDecl p) {
4870             // Anonymous classes filtered out by caller.
4871 
4872             ClassSymbol c = (ClassSymbol)e;
4873 
4874             checkCtorAccess(p, c);
4875 
4876             // Check for missing serialVersionUID; check *not* done
4877             // for enums or records.
4878             VarSymbol svuidSym = null;
4879             for (Symbol sym : c.members().getSymbolsByName(names.serialVersionUID)) {
4880                 if (sym.kind == VAR) {
4881                     svuidSym = (VarSymbol)sym;
4882                     break;
4883                 }
4884             }
4885 
4886             if (svuidSym == null) {
4887                 log.warning(LintCategory.SERIAL, p.pos(), Warnings.MissingSVUID(c));
4888             }
4889 
4890             // Check for serialPersistentFields to gate checks for
4891             // non-serializable non-transient instance fields
4892             boolean serialPersistentFieldsPresent =
4893                     c.members()
4894                      .getSymbolsByName(names.serialPersistentFields, sym -> sym.kind == VAR)
4895                      .iterator()
4896                      .hasNext();
4897 
4898             // Check declarations of serialization-related methods and
4899             // fields
4900             for(Symbol el : c.getEnclosedElements()) {
4901                 runUnderLint(el, p, (enclosed, tree) -> {
4902                     String name = null;
4903                     switch(enclosed.getKind()) {
4904                     case FIELD -> {
4905                         if (!serialPersistentFieldsPresent) {
4906                             var flags = enclosed.flags();
4907                             if ( ((flags & TRANSIENT) == 0) &&
4908                                  ((flags & STATIC) == 0)) {
4909                                 Type varType = enclosed.asType();
4910                                 if (!canBeSerialized(varType)) {
4911                                     // Note per JLS arrays are
4912                                     // serializable even if the
4913                                     // component type is not.
4914                                     log.warning(LintCategory.SERIAL,
4915                                                 TreeInfo.diagnosticPositionFor(enclosed, tree),
4916                                                 Warnings.NonSerializableInstanceField);
4917                                 } else if (varType.hasTag(ARRAY)) {
4918                                     ArrayType arrayType = (ArrayType)varType;
4919                                     Type elementType = arrayType.elemtype;
4920                                     while (elementType.hasTag(ARRAY)) {
4921                                         arrayType = (ArrayType)elementType;
4922                                         elementType = arrayType.elemtype;
4923                                     }
4924                                     if (!canBeSerialized(elementType)) {
4925                                         log.warning(LintCategory.SERIAL,
4926                                                     TreeInfo.diagnosticPositionFor(enclosed, tree),
4927                                                     Warnings.NonSerializableInstanceFieldArray(elementType));
4928                                     }
4929                                 }
4930                             }
4931                         }
4932 
4933                         name = enclosed.getSimpleName().toString();
4934                         if (serialFieldNames.contains(name)) {
4935                             VarSymbol field = (VarSymbol)enclosed;
4936                             switch (name) {
4937                             case "serialVersionUID"       ->  checkSerialVersionUID(tree, e, field);
4938                             case "serialPersistentFields" ->  checkSerialPersistentFields(tree, e, field);
4939                             default -> throw new AssertionError();
4940                             }
4941                         }
4942                     }
4943 
4944                     // Correctly checking the serialization-related
4945                     // methods is subtle. For the methods declared to be
4946                     // private or directly declared in the class, the
4947                     // enclosed elements of the class can be checked in
4948                     // turn. However, writeReplace and readResolve can be
4949                     // declared in a superclass and inherited. Note that
4950                     // the runtime lookup walks the superclass chain
4951                     // looking for writeReplace/readResolve via
4952                     // Class.getDeclaredMethod. This differs from calling
4953                     // Elements.getAllMembers(TypeElement) as the latter
4954                     // will also pull in default methods from
4955                     // superinterfaces. In other words, the runtime checks
4956                     // (which long predate default methods on interfaces)
4957                     // do not admit the possibility of inheriting methods
4958                     // this way, a difference from general inheritance.
4959 
4960                     // The current implementation just checks the enclosed
4961                     // elements and does not directly check the inherited
4962                     // methods. If all the types are being checked this is
4963                     // less of a concern; however, there are cases that
4964                     // could be missed. In particular, readResolve and
4965                     // writeReplace could, in principle, by inherited from
4966                     // a non-serializable superclass and thus not checked
4967                     // even if compiled with a serializable child class.
4968                     case METHOD -> {
4969                         var method = (MethodSymbol)enclosed;
4970                         name = method.getSimpleName().toString();
4971                         if (serialMethodNames.contains(name)) {
4972                             switch (name) {
4973                             case "writeObject"      -> checkWriteObject(tree, e, method);
4974                             case "writeReplace"     -> checkWriteReplace(tree,e, method);
4975                             case "readObject"       -> checkReadObject(tree,e, method);
4976                             case "readObjectNoData" -> checkReadObjectNoData(tree, e, method);
4977                             case "readResolve"      -> checkReadResolve(tree, e, method);
4978                             default ->  throw new AssertionError();
4979                             }
4980                         }
4981                     }
4982                     }
4983                 });
4984             }
4985 
4986             return null;
4987         }
4988 
4989         boolean canBeSerialized(Type type) {
4990             return type.isPrimitive() || rs.isSerializable(type);
4991         }
4992 
4993         /**
4994          * Check that Externalizable class needs a public no-arg
4995          * constructor.
4996          *
4997          * Check that a Serializable class has access to the no-arg
4998          * constructor of its first nonserializable superclass.
4999          */
5000         private void checkCtorAccess(JCClassDecl tree, ClassSymbol c) {
5001             if (isExternalizable(c.type)) {
5002                 for(var sym : c.getEnclosedElements()) {
5003                     if (sym.isConstructor() &&
5004                         ((sym.flags() & PUBLIC) == PUBLIC)) {
5005                         if (((MethodSymbol)sym).getParameters().isEmpty()) {
5006                             return;
5007                         }
5008                     }
5009                 }
5010                 log.warning(LintCategory.SERIAL, tree.pos(),
5011                             Warnings.ExternalizableMissingPublicNoArgCtor);
5012             } else {
5013                 // Approximate access to the no-arg constructor up in
5014                 // the superclass chain by checking that the
5015                 // constructor is not private. This may not handle
5016                 // some cross-package situations correctly.
5017                 Type superClass = c.getSuperclass();
5018                 // java.lang.Object is *not* Serializable so this loop
5019                 // should terminate.
5020                 while (rs.isSerializable(superClass) ) {
5021                     try {
5022                         superClass = (Type)((TypeElement)(((DeclaredType)superClass)).asElement()).getSuperclass();
5023                     } catch(ClassCastException cce) {
5024                         return ; // Don't try to recover
5025                     }
5026                 }
5027                 // Non-Serializable superclass
5028                 try {
5029                     ClassSymbol supertype = ((ClassSymbol)(((DeclaredType)superClass).asElement()));
5030                     for(var sym : supertype.getEnclosedElements()) {
5031                         if (sym.isConstructor()) {
5032                             MethodSymbol ctor = (MethodSymbol)sym;
5033                             if (ctor.getParameters().isEmpty()) {
5034                                 if (((ctor.flags() & PRIVATE) == PRIVATE) ||
5035                                     // Handle nested classes and implicit this$0
5036                                     (supertype.getNestingKind() == NestingKind.MEMBER &&
5037                                      ((supertype.flags() & STATIC) == 0)))
5038                                     log.warning(LintCategory.SERIAL, tree.pos(),
5039                                                 Warnings.SerializableMissingAccessNoArgCtor(supertype.getQualifiedName()));
5040                             }
5041                         }
5042                     }
5043                 } catch (ClassCastException cce) {
5044                     return ; // Don't try to recover
5045                 }
5046                 return;
5047             }
5048         }
5049 
5050         private void checkSerialVersionUID(JCClassDecl tree, Element e, VarSymbol svuid) {
5051             // To be effective, serialVersionUID must be marked static
5052             // and final, but private is recommended. But alas, in
5053             // practice there are many non-private serialVersionUID
5054             // fields.
5055              if ((svuid.flags() & (STATIC | FINAL)) !=
5056                  (STATIC | FINAL)) {
5057                  log.warning(LintCategory.SERIAL,
5058                              TreeInfo.diagnosticPositionFor(svuid, tree),
5059                              Warnings.ImproperSVUID((Symbol)e));
5060              }
5061 
5062              // check svuid has type long
5063              if (!svuid.type.hasTag(LONG)) {
5064                  log.warning(LintCategory.SERIAL,
5065                              TreeInfo.diagnosticPositionFor(svuid, tree),
5066                              Warnings.LongSVUID((Symbol)e));
5067              }
5068 
5069              if (svuid.getConstValue() == null)
5070                  log.warning(LintCategory.SERIAL,
5071                             TreeInfo.diagnosticPositionFor(svuid, tree),
5072                              Warnings.ConstantSVUID((Symbol)e));
5073         }
5074 
5075         private void checkSerialPersistentFields(JCClassDecl tree, Element e, VarSymbol spf) {
5076             // To be effective, serialPersisentFields must be private, static, and final.
5077              if ((spf.flags() & (PRIVATE | STATIC | FINAL)) !=
5078                  (PRIVATE | STATIC | FINAL)) {
5079                  log.warning(LintCategory.SERIAL,
5080                              TreeInfo.diagnosticPositionFor(spf, tree),
5081                              Warnings.ImproperSPF);
5082              }
5083 
5084              if (!types.isSameType(spf.type, OSF_TYPE)) {
5085                  log.warning(LintCategory.SERIAL,
5086                              TreeInfo.diagnosticPositionFor(spf, tree),
5087                              Warnings.OSFArraySPF);
5088              }
5089 
5090             if (isExternalizable((Type)(e.asType()))) {
5091                 log.warning(LintCategory.SERIAL,
5092                             TreeInfo.diagnosticPositionFor(spf, tree),
5093                             Warnings.IneffectualSerialFieldExternalizable);
5094             }
5095 
5096             // Warn if serialPersistentFields is initialized to a
5097             // literal null.
5098             JCTree spfDecl = TreeInfo.declarationFor(spf, tree);
5099             if (spfDecl != null && spfDecl.getTag() == VARDEF) {
5100                 JCVariableDecl variableDef = (JCVariableDecl) spfDecl;
5101                 JCExpression initExpr = variableDef.init;
5102                  if (initExpr != null && TreeInfo.isNull(initExpr)) {
5103                      log.warning(LintCategory.SERIAL, initExpr.pos(),
5104                                  Warnings.SPFNullInit);
5105                  }
5106             }
5107         }
5108 
5109         private void checkWriteObject(JCClassDecl tree, Element e, MethodSymbol method) {
5110             // The "synchronized" modifier is seen in the wild on
5111             // readObject and writeObject methods and is generally
5112             // innocuous.
5113 
5114             // private void writeObject(ObjectOutputStream stream) throws IOException
5115             checkPrivateNonStaticMethod(tree, method);
5116             checkReturnType(tree, e, method, syms.voidType);
5117             checkOneArg(tree, e, method, syms.objectOutputStreamType);
5118             checkExceptions(tree, e, method, syms.ioExceptionType);
5119             checkExternalizable(tree, e, method);
5120         }
5121 
5122         private void checkWriteReplace(JCClassDecl tree, Element e, MethodSymbol method) {
5123             // ANY-ACCESS-MODIFIER Object writeReplace() throws
5124             // ObjectStreamException
5125 
5126             // Excluding abstract, could have a more complicated
5127             // rule based on abstract-ness of the class
5128             checkConcreteInstanceMethod(tree, e, method);
5129             checkReturnType(tree, e, method, syms.objectType);
5130             checkNoArgs(tree, e, method);
5131             checkExceptions(tree, e, method, syms.objectStreamExceptionType);
5132         }
5133 
5134         private void checkReadObject(JCClassDecl tree, Element e, MethodSymbol method) {
5135             // The "synchronized" modifier is seen in the wild on
5136             // readObject and writeObject methods and is generally
5137             // innocuous.
5138 
5139             // private void readObject(ObjectInputStream stream)
5140             //   throws IOException, ClassNotFoundException
5141             checkPrivateNonStaticMethod(tree, method);
5142             checkReturnType(tree, e, method, syms.voidType);
5143             checkOneArg(tree, e, method, syms.objectInputStreamType);
5144             checkExceptions(tree, e, method, syms.ioExceptionType, syms.classNotFoundExceptionType);
5145             checkExternalizable(tree, e, method);
5146         }
5147 
5148         private void checkReadObjectNoData(JCClassDecl tree, Element e, MethodSymbol method) {
5149             // private void readObjectNoData() throws ObjectStreamException
5150             checkPrivateNonStaticMethod(tree, method);
5151             checkReturnType(tree, e, method, syms.voidType);
5152             checkNoArgs(tree, e, method);
5153             checkExceptions(tree, e, method, syms.objectStreamExceptionType);
5154             checkExternalizable(tree, e, method);
5155         }
5156 
5157         private void checkReadResolve(JCClassDecl tree, Element e, MethodSymbol method) {
5158             // ANY-ACCESS-MODIFIER Object readResolve()
5159             // throws ObjectStreamException
5160 
5161             // Excluding abstract, could have a more complicated
5162             // rule based on abstract-ness of the class
5163             checkConcreteInstanceMethod(tree, e, method);
5164             checkReturnType(tree,e, method, syms.objectType);
5165             checkNoArgs(tree, e, method);
5166             checkExceptions(tree, e, method, syms.objectStreamExceptionType);
5167         }
5168 
5169         private void checkWriteExternalRecord(JCClassDecl tree, Element e, MethodSymbol method, boolean isExtern) {
5170             //public void writeExternal(ObjectOutput) throws IOException
5171             checkExternMethodRecord(tree, e, method, syms.objectOutputType, isExtern);
5172         }
5173 
5174         private void checkReadExternalRecord(JCClassDecl tree, Element e, MethodSymbol method, boolean isExtern) {
5175             // public void readExternal(ObjectInput) throws IOException
5176             checkExternMethodRecord(tree, e, method, syms.objectInputType, isExtern);
5177          }
5178 
5179         private void checkExternMethodRecord(JCClassDecl tree, Element e, MethodSymbol method, Type argType,
5180                                              boolean isExtern) {
5181             if (isExtern && isExternMethod(tree, e, method, argType)) {
5182                 log.warning(LintCategory.SERIAL,
5183                             TreeInfo.diagnosticPositionFor(method, tree),
5184                             Warnings.IneffectualExternalizableMethodRecord(method.getSimpleName().toString()));
5185             }
5186         }
5187 
5188         void checkPrivateNonStaticMethod(JCClassDecl tree, MethodSymbol method) {
5189             var flags = method.flags();
5190             if ((flags & PRIVATE) == 0) {
5191                 log.warning(LintCategory.SERIAL,
5192                             TreeInfo.diagnosticPositionFor(method, tree),
5193                             Warnings.SerialMethodNotPrivate(method.getSimpleName()));
5194             }
5195 
5196             if ((flags & STATIC) != 0) {
5197                 log.warning(LintCategory.SERIAL,
5198                             TreeInfo.diagnosticPositionFor(method, tree),
5199                             Warnings.SerialMethodStatic(method.getSimpleName()));
5200             }
5201         }
5202 
5203         /**
5204          * Per section 1.12 "Serialization of Enum Constants" of
5205          * the serialization specification, due to the special
5206          * serialization handling of enums, any writeObject,
5207          * readObject, writeReplace, and readResolve methods are
5208          * ignored as are serialPersistentFields and
5209          * serialVersionUID fields.
5210          */
5211         @Override
5212         public Void visitTypeAsEnum(TypeElement e,
5213                                     JCClassDecl p) {
5214             boolean isExtern = isExternalizable((Type)e.asType());
5215             for(Element el : e.getEnclosedElements()) {
5216                 runUnderLint(el, p, (enclosed, tree) -> {
5217                     String name = enclosed.getSimpleName().toString();
5218                     switch(enclosed.getKind()) {
5219                     case FIELD -> {
5220                         var field = (VarSymbol)enclosed;
5221                         if (serialFieldNames.contains(name)) {
5222                             log.warning(LintCategory.SERIAL,
5223                                         TreeInfo.diagnosticPositionFor(field, tree),
5224                                         Warnings.IneffectualSerialFieldEnum(name));
5225                         }
5226                     }
5227 
5228                     case METHOD -> {
5229                         var method = (MethodSymbol)enclosed;
5230                         if (serialMethodNames.contains(name)) {
5231                             log.warning(LintCategory.SERIAL,
5232                                         TreeInfo.diagnosticPositionFor(method, tree),
5233                                         Warnings.IneffectualSerialMethodEnum(name));
5234                         }
5235 
5236                         if (isExtern) {
5237                             switch(name) {
5238                             case "writeExternal" -> checkWriteExternalEnum(tree, e, method);
5239                             case "readExternal"  -> checkReadExternalEnum(tree, e, method);
5240                             }
5241                         }
5242                     }
5243 
5244                     // Also perform checks on any class bodies of enum constants, see JLS 8.9.1.
5245                     case ENUM_CONSTANT -> {
5246                         var field = (VarSymbol)enclosed;
5247                         JCVariableDecl decl = (JCVariableDecl) TreeInfo.declarationFor(field, p);
5248                         if (decl.init instanceof JCNewClass nc && nc.def != null) {
5249                             ClassSymbol enumConstantType = nc.def.sym;
5250                             visitTypeAsEnum(enumConstantType, p);
5251                         }
5252                     }
5253 
5254                     }});
5255             }
5256             return null;
5257         }
5258 
5259         private void checkWriteExternalEnum(JCClassDecl tree, Element e, MethodSymbol method) {
5260             //public void writeExternal(ObjectOutput) throws IOException
5261             checkExternMethodEnum(tree, e, method, syms.objectOutputType);
5262         }
5263 
5264         private void checkReadExternalEnum(JCClassDecl tree, Element e, MethodSymbol method) {
5265              // public void readExternal(ObjectInput) throws IOException
5266             checkExternMethodEnum(tree, e, method, syms.objectInputType);
5267          }
5268 
5269         private void checkExternMethodEnum(JCClassDecl tree, Element e, MethodSymbol method, Type argType) {
5270             if (isExternMethod(tree, e, method, argType)) {
5271                 log.warning(LintCategory.SERIAL,
5272                             TreeInfo.diagnosticPositionFor(method, tree),
5273                             Warnings.IneffectualExternMethodEnum(method.getSimpleName().toString()));
5274             }
5275         }
5276 
5277         private boolean isExternMethod(JCClassDecl tree, Element e, MethodSymbol method, Type argType) {
5278             long flags = method.flags();
5279             Type rtype = method.getReturnType();
5280 
5281             // Not necessary to check throws clause in this context
5282             return (flags & PUBLIC) != 0 && (flags & STATIC) == 0 &&
5283                 types.isSameType(syms.voidType, rtype) &&
5284                 hasExactlyOneArgWithType(tree, e, method, argType);
5285         }
5286 
5287         /**
5288          * Most serialization-related fields and methods on interfaces
5289          * are ineffectual or problematic.
5290          */
5291         @Override
5292         public Void visitTypeAsInterface(TypeElement e,
5293                                          JCClassDecl p) {
5294             for(Element el : e.getEnclosedElements()) {
5295                 runUnderLint(el, p, (enclosed, tree) -> {
5296                     String name = null;
5297                     switch(enclosed.getKind()) {
5298                     case FIELD -> {
5299                         var field = (VarSymbol)enclosed;
5300                         name = field.getSimpleName().toString();
5301                         switch(name) {
5302                         case "serialPersistentFields" -> {
5303                             log.warning(LintCategory.SERIAL,
5304                                         TreeInfo.diagnosticPositionFor(field, tree),
5305                                         Warnings.IneffectualSerialFieldInterface);
5306                         }
5307 
5308                         case "serialVersionUID" -> {
5309                             checkSerialVersionUID(tree, e, field);
5310                         }
5311                         }
5312                     }
5313 
5314                     case METHOD -> {
5315                         var method = (MethodSymbol)enclosed;
5316                         name = enclosed.getSimpleName().toString();
5317                         if (serialMethodNames.contains(name)) {
5318                             switch (name) {
5319                             case
5320                                 "readObject",
5321                                 "readObjectNoData",
5322                                 "writeObject"      -> checkPrivateMethod(tree, e, method);
5323 
5324                             case
5325                                 "writeReplace",
5326                                 "readResolve"      -> checkDefaultIneffective(tree, e, method);
5327 
5328                             default ->  throw new AssertionError();
5329                             }
5330 
5331                         }
5332                     }}
5333                 });
5334             }
5335 
5336             return null;
5337         }
5338 
5339         private void checkPrivateMethod(JCClassDecl tree,
5340                                         Element e,
5341                                         MethodSymbol method) {
5342             if ((method.flags() & PRIVATE) == 0) {
5343                 log.warning(LintCategory.SERIAL,
5344                             TreeInfo.diagnosticPositionFor(method, tree),
5345                             Warnings.NonPrivateMethodWeakerAccess);
5346             }
5347         }
5348 
5349         private void checkDefaultIneffective(JCClassDecl tree,
5350                                              Element e,
5351                                              MethodSymbol method) {
5352             if ((method.flags() & DEFAULT) == DEFAULT) {
5353                 log.warning(LintCategory.SERIAL,
5354                             TreeInfo.diagnosticPositionFor(method, tree),
5355                             Warnings.DefaultIneffective);
5356 
5357             }
5358         }
5359 
5360         @Override
5361         public Void visitTypeAsAnnotationType(TypeElement e,
5362                                               JCClassDecl p) {
5363             // Per the JLS, annotation types are not serializeable
5364             return null;
5365         }
5366 
5367         /**
5368          * From the Java Object Serialization Specification, 1.13
5369          * Serialization of Records:
5370          *
5371          * "The process by which record objects are serialized or
5372          * externalized cannot be customized; any class-specific
5373          * writeObject, readObject, readObjectNoData, writeExternal,
5374          * and readExternal methods defined by record classes are
5375          * ignored during serialization and deserialization. However,
5376          * a substitute object to be serialized or a designate
5377          * replacement may be specified, by the writeReplace and
5378          * readResolve methods, respectively. Any
5379          * serialPersistentFields field declaration is
5380          * ignored. Documenting serializable fields and data for
5381          * record classes is unnecessary, since there is no variation
5382          * in the serial form, other than whether a substitute or
5383          * replacement object is used. The serialVersionUID of a
5384          * record class is 0L unless explicitly declared. The
5385          * requirement for matching serialVersionUID values is waived
5386          * for record classes."
5387          */
5388         @Override
5389         public Void visitTypeAsRecord(TypeElement e,
5390                                       JCClassDecl p) {
5391             boolean isExtern = isExternalizable((Type)e.asType());
5392             for(Element el : e.getEnclosedElements()) {
5393                 runUnderLint(el, p, (enclosed, tree) -> {
5394                     String name = enclosed.getSimpleName().toString();
5395                     switch(enclosed.getKind()) {
5396                     case FIELD -> {
5397                         var field = (VarSymbol)enclosed;
5398                         switch(name) {
5399                         case "serialPersistentFields" -> {
5400                             log.warning(LintCategory.SERIAL,
5401                                         TreeInfo.diagnosticPositionFor(field, tree),
5402                                         Warnings.IneffectualSerialFieldRecord);
5403                         }
5404 
5405                         case "serialVersionUID" -> {
5406                             // Could generate additional warning that
5407                             // svuid value is not checked to match for
5408                             // records.
5409                             checkSerialVersionUID(tree, e, field);
5410                         }}
5411                     }
5412 
5413                     case METHOD -> {
5414                         var method = (MethodSymbol)enclosed;
5415                         switch(name) {
5416                         case "writeReplace" -> checkWriteReplace(tree, e, method);
5417                         case "readResolve"  -> checkReadResolve(tree, e, method);
5418 
5419                         case "writeExternal" -> checkWriteExternalRecord(tree, e, method, isExtern);
5420                         case "readExternal"  -> checkReadExternalRecord(tree, e, method, isExtern);
5421 
5422                         default -> {
5423                             if (serialMethodNames.contains(name)) {
5424                                 log.warning(LintCategory.SERIAL,
5425                                             TreeInfo.diagnosticPositionFor(method, tree),
5426                                             Warnings.IneffectualSerialMethodRecord(name));
5427                             }
5428                         }}
5429                     }}});
5430             }
5431             return null;
5432         }
5433 
5434         void checkConcreteInstanceMethod(JCClassDecl tree,
5435                                          Element enclosing,
5436                                          MethodSymbol method) {
5437             if ((method.flags() & (STATIC | ABSTRACT)) != 0) {
5438                     log.warning(LintCategory.SERIAL,
5439                                 TreeInfo.diagnosticPositionFor(method, tree),
5440                                 Warnings.SerialConcreteInstanceMethod(method.getSimpleName()));
5441             }
5442         }
5443 
5444         private void checkReturnType(JCClassDecl tree,
5445                                      Element enclosing,
5446                                      MethodSymbol method,
5447                                      Type expectedReturnType) {
5448             // Note: there may be complications checking writeReplace
5449             // and readResolve since they return Object and could, in
5450             // principle, have covariant overrides and any synthetic
5451             // bridge method would not be represented here for
5452             // checking.
5453             Type rtype = method.getReturnType();
5454             if (!types.isSameType(expectedReturnType, rtype)) {
5455                 log.warning(LintCategory.SERIAL,
5456                             TreeInfo.diagnosticPositionFor(method, tree),
5457                             Warnings.SerialMethodUnexpectedReturnType(method.getSimpleName(),
5458                                                                       rtype, expectedReturnType));
5459             }
5460         }
5461 
5462         private void checkOneArg(JCClassDecl tree,
5463                                  Element enclosing,
5464                                  MethodSymbol method,
5465                                  Type expectedType) {
5466             String name = method.getSimpleName().toString();
5467 
5468             var parameters= method.getParameters();
5469 
5470             if (parameters.size() != 1) {
5471                 log.warning(LintCategory.SERIAL,
5472                             TreeInfo.diagnosticPositionFor(method, tree),
5473                             Warnings.SerialMethodOneArg(method.getSimpleName(), parameters.size()));
5474                 return;
5475             }
5476 
5477             Type parameterType = parameters.get(0).asType();
5478             if (!types.isSameType(parameterType, expectedType)) {
5479                 log.warning(LintCategory.SERIAL,
5480                             TreeInfo.diagnosticPositionFor(method, tree),
5481                             Warnings.SerialMethodParameterType(method.getSimpleName(),
5482                                                                expectedType,
5483                                                                parameterType));
5484             }
5485         }
5486 
5487         private boolean hasExactlyOneArgWithType(JCClassDecl tree,
5488                                                  Element enclosing,
5489                                                  MethodSymbol method,
5490                                                  Type expectedType) {
5491             var parameters = method.getParameters();
5492             return (parameters.size() == 1) &&
5493                 types.isSameType(parameters.get(0).asType(), expectedType);
5494         }
5495 
5496 
5497         private void checkNoArgs(JCClassDecl tree, Element enclosing, MethodSymbol method) {
5498             var parameters = method.getParameters();
5499             if (!parameters.isEmpty()) {
5500                 log.warning(LintCategory.SERIAL,
5501                             TreeInfo.diagnosticPositionFor(parameters.get(0), tree),
5502                             Warnings.SerialMethodNoArgs(method.getSimpleName()));
5503             }
5504         }
5505 
5506         private void checkExternalizable(JCClassDecl tree, Element enclosing, MethodSymbol method) {
5507             // If the enclosing class is externalizable, warn for the method
5508             if (isExternalizable((Type)enclosing.asType())) {
5509                 log.warning(LintCategory.SERIAL,
5510                             TreeInfo.diagnosticPositionFor(method, tree),
5511                             Warnings.IneffectualSerialMethodExternalizable(method.getSimpleName()));
5512             }
5513             return;
5514         }
5515 
5516         private void checkExceptions(JCClassDecl tree,
5517                                      Element enclosing,
5518                                      MethodSymbol method,
5519                                      Type... declaredExceptions) {
5520             for (Type thrownType: method.getThrownTypes()) {
5521                 // For each exception in the throws clause of the
5522                 // method, if not an Error and not a RuntimeException,
5523                 // check if the exception is a subtype of a declared
5524                 // exception from the throws clause of the
5525                 // serialization method in question.
5526                 if (types.isSubtype(thrownType, syms.runtimeExceptionType) ||
5527                     types.isSubtype(thrownType, syms.errorType) ) {
5528                     continue;
5529                 } else {
5530                     boolean declared = false;
5531                     for (Type declaredException : declaredExceptions) {
5532                         if (types.isSubtype(thrownType, declaredException)) {
5533                             declared = true;
5534                             continue;
5535                         }
5536                     }
5537                     if (!declared) {
5538                         log.warning(LintCategory.SERIAL,
5539                                     TreeInfo.diagnosticPositionFor(method, tree),
5540                                     Warnings.SerialMethodUnexpectedException(method.getSimpleName(),
5541                                                                              thrownType));
5542                     }
5543                 }
5544             }
5545             return;
5546         }
5547 
5548         private <E extends Element> Void runUnderLint(E symbol, JCClassDecl p, BiConsumer<E, JCClassDecl> task) {
5549             Lint prevLint = lint;
5550             try {
5551                 lint = lint.augment((Symbol) symbol);
5552 
5553                 if (lint.isEnabled(LintCategory.SERIAL)) {
5554                     task.accept(symbol, p);
5555                 }
5556 
5557                 return null;
5558             } finally {
5559                 lint = prevLint;
5560             }
5561         }
5562 
5563     }
5564 
5565 }
--- EOF ---