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