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