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