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