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