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