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