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