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