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