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