1 /*
   2  * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.tools.javac.comp;
  27 
  28 import java.util.*;
  29 import java.util.function.BiConsumer;
  30 import java.util.stream.Collectors;
  31 
  32 import javax.lang.model.element.ElementKind;
  33 import javax.tools.JavaFileObject;
  34 
  35 import com.sun.source.tree.CaseTree.CaseKind;
  36 import com.sun.source.tree.IdentifierTree;
  37 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
  38 import com.sun.source.tree.MemberSelectTree;
  39 import com.sun.source.tree.TreeVisitor;
  40 import com.sun.source.util.SimpleTreeVisitor;
  41 import com.sun.tools.javac.code.*;
  42 import com.sun.tools.javac.code.Lint.LintCategory;
  43 import com.sun.tools.javac.code.Scope.WriteableScope;
  44 import com.sun.tools.javac.code.Source.Feature;
  45 import com.sun.tools.javac.code.Symbol.*;
  46 import com.sun.tools.javac.code.Type.*;
  47 import com.sun.tools.javac.code.TypeMetadata.Annotations;
  48 import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError;
  49 import com.sun.tools.javac.comp.ArgumentAttr.LocalCacheContext;
  50 import com.sun.tools.javac.comp.Check.CheckContext;
  51 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
  52 import com.sun.tools.javac.comp.MatchBindingsComputer.BindingSymbol;
  53 import com.sun.tools.javac.jvm.*;
  54 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond;
  55 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArg;
  56 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArgs;
  57 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  58 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  59 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
  60 import com.sun.tools.javac.tree.*;
  61 import com.sun.tools.javac.tree.JCTree.*;
  62 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
  63 import com.sun.tools.javac.util.*;
  64 import com.sun.tools.javac.util.DefinedBy.Api;
  65 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  66 import com.sun.tools.javac.util.JCDiagnostic.Error;
  67 import com.sun.tools.javac.util.JCDiagnostic.Fragment;
  68 import com.sun.tools.javac.util.JCDiagnostic.Warning;
  69 import com.sun.tools.javac.util.List;
  70 
  71 import static com.sun.tools.javac.code.Flags.*;
  72 import static com.sun.tools.javac.code.Flags.ANNOTATION;
  73 import static com.sun.tools.javac.code.Flags.BLOCK;
  74 import static com.sun.tools.javac.code.Kinds.*;
  75 import static com.sun.tools.javac.code.Kinds.Kind.*;
  76 import static com.sun.tools.javac.code.TypeTag.*;
  77 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
  78 import com.sun.tools.javac.comp.Analyzer.AnalyzerMode;
  79 import com.sun.tools.javac.comp.MatchBindingsComputer.BindingSymbol;
  80 import com.sun.tools.javac.tree.JCTree.JCBreak;
  81 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  82 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
  83 import com.sun.tools.javac.util.Log.DeferredDiagnosticHandler;
  84 import com.sun.tools.javac.util.Log.DiscardDiagnosticHandler;
  85 
  86 /** This is the main context-dependent analysis phase in GJC. It
  87  *  encompasses name resolution, type checking and constant folding as
  88  *  subtasks. Some subtasks involve auxiliary classes.
  89  *  @see Check
  90  *  @see Resolve
  91  *  @see ConstFold
  92  *  @see Infer
  93  *
  94  *  <p><b>This is NOT part of any supported API.
  95  *  If you write code that depends on this, you do so at your own risk.
  96  *  This code and its internal interfaces are subject to change or
  97  *  deletion without notice.</b>
  98  */
  99 public class Attr extends JCTree.Visitor {
 100     protected static final Context.Key<Attr> attrKey = new Context.Key<>();
 101 
 102     final Names names;
 103     final Log log;
 104     final Symtab syms;
 105     final Resolve rs;
 106     final Operators operators;
 107     final Infer infer;
 108     final Analyzer analyzer;
 109     final DeferredAttr deferredAttr;
 110     final Check chk;
 111     final Flow flow;
 112     final MemberEnter memberEnter;
 113     final TypeEnter typeEnter;
 114     final TreeMaker make;
 115     final ConstFold cfolder;
 116     final Enter enter;
 117     final Target target;
 118     final Types types;
 119     final JCDiagnostic.Factory diags;
 120     final TypeAnnotations typeAnnotations;
 121     final DeferredLintHandler deferredLintHandler;
 122     final TypeEnvs typeEnvs;
 123     final Dependencies dependencies;
 124     final Annotate annotate;
 125     final ArgumentAttr argumentAttr;
 126     final MatchBindingsComputer matchBindingsComputer;
 127 
 128     public static Attr instance(Context context) {
 129         Attr instance = context.get(attrKey);
 130         if (instance == null)
 131             instance = new Attr(context);
 132         return instance;
 133     }
 134 
 135     protected Attr(Context context) {
 136         context.put(attrKey, this);
 137 
 138         names = Names.instance(context);
 139         log = Log.instance(context);
 140         syms = Symtab.instance(context);
 141         rs = Resolve.instance(context);
 142         operators = Operators.instance(context);
 143         chk = Check.instance(context);
 144         flow = Flow.instance(context);
 145         memberEnter = MemberEnter.instance(context);
 146         typeEnter = TypeEnter.instance(context);
 147         make = TreeMaker.instance(context);
 148         enter = Enter.instance(context);
 149         infer = Infer.instance(context);
 150         analyzer = Analyzer.instance(context);
 151         deferredAttr = DeferredAttr.instance(context);
 152         cfolder = ConstFold.instance(context);
 153         target = Target.instance(context);
 154         types = Types.instance(context);
 155         diags = JCDiagnostic.Factory.instance(context);
 156         annotate = Annotate.instance(context);
 157         typeAnnotations = TypeAnnotations.instance(context);
 158         deferredLintHandler = DeferredLintHandler.instance(context);
 159         typeEnvs = TypeEnvs.instance(context);
 160         dependencies = Dependencies.instance(context);
 161         argumentAttr = ArgumentAttr.instance(context);
 162         matchBindingsComputer = MatchBindingsComputer.instance(context);
 163 
 164         Options options = Options.instance(context);
 165 
 166         Source source = Source.instance(context);
 167         allowPoly = Feature.POLY.allowedInSource(source);
 168         allowTypeAnnos = Feature.TYPE_ANNOTATIONS.allowedInSource(source);
 169         allowLambda = Feature.LAMBDA.allowedInSource(source);
 170         allowDefaultMethods = Feature.DEFAULT_METHODS.allowedInSource(source);
 171         allowStaticInterfaceMethods = Feature.STATIC_INTERFACE_METHODS.allowedInSource(source);
 172         sourceName = source.name;
 173         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
 174 
 175         statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
 176         varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
 177         unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
 178         methodAttrInfo = new MethodAttrInfo();
 179         unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
 180         unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
 181         recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
 182     }
 183 
 184     /** Switch: support target-typing inference
 185      */
 186     boolean allowPoly;
 187 
 188     /** Switch: support type annotations.
 189      */
 190     boolean allowTypeAnnos;
 191 
 192     /** Switch: support lambda expressions ?
 193      */
 194     boolean allowLambda;
 195 
 196     /** Switch: support default methods ?
 197      */
 198     boolean allowDefaultMethods;
 199 
 200     /** Switch: static interface methods enabled?
 201      */
 202     boolean allowStaticInterfaceMethods;
 203 
 204     /**
 205      * Switch: warn about use of variable before declaration?
 206      * RFE: 6425594
 207      */
 208     boolean useBeforeDeclarationWarning;
 209 
 210     /**
 211      * Switch: name of source level; used for error reporting.
 212      */
 213     String sourceName;
 214 
 215     /** Check kind and type of given tree against protokind and prototype.
 216      *  If check succeeds, store type in tree and return it.
 217      *  If check fails, store errType in tree and return it.
 218      *  No checks are performed if the prototype is a method type.
 219      *  It is not necessary in this case since we know that kind and type
 220      *  are correct.
 221      *
 222      *  @param tree     The tree whose kind and type is checked
 223      *  @param found    The computed type of the tree
 224      *  @param ownkind  The computed kind of the tree
 225      *  @param resultInfo  The expected result of the tree
 226      */
 227     Type check(final JCTree tree,
 228                final Type found,
 229                final KindSelector ownkind,
 230                final ResultInfo resultInfo) {
 231         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
 232         Type owntype;
 233         boolean shouldCheck = !found.hasTag(ERROR) &&
 234                 !resultInfo.pt.hasTag(METHOD) &&
 235                 !resultInfo.pt.hasTag(FORALL);
 236         if (shouldCheck && !ownkind.subset(resultInfo.pkind)) {
 237             log.error(tree.pos(),
 238                       Errors.UnexpectedType(resultInfo.pkind.kindNames(),
 239                                             ownkind.kindNames()));
 240             owntype = types.createErrorType(found);
 241         } else if (allowPoly && inferenceContext.free(found)) {
 242             //delay the check if there are inference variables in the found type
 243             //this means we are dealing with a partially inferred poly expression
 244             owntype = shouldCheck ? resultInfo.pt : found;
 245             if (resultInfo.checkMode.installPostInferenceHook()) {
 246                 inferenceContext.addFreeTypeListener(List.of(found),
 247                         instantiatedContext -> {
 248                             ResultInfo pendingResult =
 249                                     resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
 250                             check(tree, inferenceContext.asInstType(found), ownkind, pendingResult);
 251                         });
 252             }
 253         } else {
 254             owntype = shouldCheck ?
 255             resultInfo.check(tree, found) :
 256             found;
 257         }
 258         if (resultInfo.checkMode.updateTreeType()) {
 259             tree.type = owntype;
 260         }
 261         return owntype;
 262     }
 263 
 264     /** Is given blank final variable assignable, i.e. in a scope where it
 265      *  may be assigned to even though it is final?
 266      *  @param v      The blank final variable.
 267      *  @param env    The current environment.
 268      */
 269     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
 270         Symbol owner = env.info.scope.owner;
 271            // owner refers to the innermost variable, method or
 272            // initializer block declaration at this point.
 273         return
 274             v.owner == owner
 275             ||
 276             ((owner.name == names.init ||    // i.e. we are in a constructor
 277               owner.kind == VAR ||           // i.e. we are in a variable initializer
 278               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
 279              &&
 280              v.owner == owner.owner
 281              &&
 282              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
 283     }
 284 
 285     /** Check that variable can be assigned to.
 286      *  @param pos    The current source code position.
 287      *  @param v      The assigned variable
 288      *  @param base   If the variable is referred to in a Select, the part
 289      *                to the left of the `.', null otherwise.
 290      *  @param env    The current environment.
 291      */
 292     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
 293         if (v.name == names._this) {
 294             log.error(pos, Errors.CantAssignValToThis);
 295         } else if ((v.flags() & FINAL) != 0 &&
 296             ((v.flags() & HASINIT) != 0
 297              ||
 298              !((base == null ||
 299                TreeInfo.isThisQualifier(base)) &&
 300                isAssignableAsBlankFinal(v, env)))) {
 301             if (v.isResourceVariable()) { //TWR resource
 302                 log.error(pos, Errors.TryResourceMayNotBeAssigned(v));
 303             } else if ((v.flags() & MATCH_BINDING) != 0) {
 304                 log.error(pos, Errors.PatternBindingMayNotBeAssigned(v));
 305             } else {
 306                 log.error(pos, Errors.CantAssignValToFinalVar(v));
 307             }
 308         }
 309     }
 310 
 311     /** Does tree represent a static reference to an identifier?
 312      *  It is assumed that tree is either a SELECT or an IDENT.
 313      *  We have to weed out selects from non-type names here.
 314      *  @param tree    The candidate tree.
 315      */
 316     boolean isStaticReference(JCTree tree) {
 317         if (tree.hasTag(SELECT)) {
 318             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
 319             if (lsym == null || lsym.kind != TYP) {
 320                 return false;
 321             }
 322         }
 323         return true;
 324     }
 325 
 326     /** Is this symbol a type?
 327      */
 328     static boolean isType(Symbol sym) {
 329         return sym != null && sym.kind == TYP;
 330     }
 331 
 332     /** The current `this' symbol.
 333      *  @param env    The current environment.
 334      */
 335     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
 336         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
 337     }
 338 
 339     /** Attribute a parsed identifier.
 340      * @param tree Parsed identifier name
 341      * @param topLevel The toplevel to use
 342      */
 343     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
 344         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
 345         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
 346                                            syms.errSymbol.name,
 347                                            null, null, null, null);
 348         localEnv.enclClass.sym = syms.errSymbol;
 349         return attribIdent(tree, localEnv);
 350     }
 351 
 352     /** Attribute a parsed identifier.
 353      * @param tree Parsed identifier name
 354      * @param env The env to use
 355      */
 356     public Symbol attribIdent(JCTree tree, Env<AttrContext> env) {
 357         return tree.accept(identAttributer, env);
 358     }
 359     // where
 360         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
 361         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
 362             @Override @DefinedBy(Api.COMPILER_TREE)
 363             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
 364                 Symbol site = visit(node.getExpression(), env);
 365                 if (site.kind == ERR || site.kind == ABSENT_TYP || site.kind == HIDDEN)
 366                     return site;
 367                 Name name = (Name)node.getIdentifier();
 368                 if (site.kind == PCK) {
 369                     env.toplevel.packge = (PackageSymbol)site;
 370                     return rs.findIdentInPackage(null, env, (TypeSymbol)site, name,
 371                             KindSelector.TYP_PCK);
 372                 } else {
 373                     env.enclClass.sym = (ClassSymbol)site;
 374                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
 375                 }
 376             }
 377 
 378             @Override @DefinedBy(Api.COMPILER_TREE)
 379             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
 380                 return rs.findIdent(null, env, (Name)node.getName(), KindSelector.TYP_PCK);
 381             }
 382         }
 383 
 384     public Type coerce(Type etype, Type ttype) {
 385         return cfolder.coerce(etype, ttype);
 386     }
 387 
 388     public Type attribType(JCTree node, TypeSymbol sym) {
 389         Env<AttrContext> env = typeEnvs.get(sym);
 390         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
 391         return attribTree(node, localEnv, unknownTypeInfo);
 392     }
 393 
 394     public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
 395         // Attribute qualifying package or class.
 396         JCFieldAccess s = (JCFieldAccess)tree.qualid;
 397         return attribTree(s.selected, env,
 398                           new ResultInfo(tree.staticImport ?
 399                                          KindSelector.TYP : KindSelector.TYP_PCK,
 400                        Type.noType));
 401     }
 402 
 403     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
 404         breakTree = tree;
 405         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
 406         EnumSet<AnalyzerMode> analyzerModes = EnumSet.copyOf(analyzer.analyzerModes);
 407         try {
 408             analyzer.analyzerModes.clear();
 409             attribExpr(expr, env);
 410         } catch (BreakAttr b) {
 411             return b.env;
 412         } catch (AssertionError ae) {
 413             if (ae.getCause() instanceof BreakAttr) {
 414                 return ((BreakAttr)(ae.getCause())).env;
 415             } else {
 416                 throw ae;
 417             }
 418         } finally {
 419             breakTree = null;
 420             log.useSource(prev);
 421             analyzer.analyzerModes.addAll(analyzerModes);
 422         }
 423         return env;
 424     }
 425 
 426     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
 427         breakTree = tree;
 428         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
 429         EnumSet<AnalyzerMode> analyzerModes = EnumSet.copyOf(analyzer.analyzerModes);
 430         try {
 431             analyzer.analyzerModes.clear();
 432             attribStat(stmt, env);
 433         } catch (BreakAttr b) {
 434             return b.env;
 435         } catch (AssertionError ae) {
 436             if (ae.getCause() instanceof BreakAttr) {
 437                 return ((BreakAttr)(ae.getCause())).env;
 438             } else {
 439                 throw ae;
 440             }
 441         } finally {
 442             breakTree = null;
 443             log.useSource(prev);
 444             analyzer.analyzerModes.addAll(analyzerModes);
 445         }
 446         return env;
 447     }
 448 
 449     private JCTree breakTree = null;
 450 
 451     private static class BreakAttr extends RuntimeException {
 452         static final long serialVersionUID = -6924771130405446405L;
 453         private Env<AttrContext> env;
 454         private BreakAttr(Env<AttrContext> env) {
 455             this.env = env;
 456         }
 457     }
 458 
 459     /**
 460      * Mode controlling behavior of Attr.Check
 461      */
 462     enum CheckMode {
 463 
 464         NORMAL,
 465 
 466         /**
 467          * Mode signalling 'fake check' - skip tree update. A side-effect of this mode is
 468          * that the captured var cache in {@code InferenceContext} will be used in read-only
 469          * mode when performing inference checks.
 470          */
 471         NO_TREE_UPDATE {
 472             @Override
 473             public boolean updateTreeType() {
 474                 return false;
 475             }
 476         },
 477         /**
 478          * Mode signalling that caller will manage free types in tree decorations.
 479          */
 480         NO_INFERENCE_HOOK {
 481             @Override
 482             public boolean installPostInferenceHook() {
 483                 return false;
 484             }
 485         };
 486 
 487         public boolean updateTreeType() {
 488             return true;
 489         }
 490         public boolean installPostInferenceHook() {
 491             return true;
 492         }
 493     }
 494 
 495 
 496     class ResultInfo {
 497         final KindSelector pkind;
 498         final Type pt;
 499         final CheckContext checkContext;
 500         final CheckMode checkMode;
 501 
 502         ResultInfo(KindSelector pkind, Type pt) {
 503             this(pkind, pt, chk.basicHandler, CheckMode.NORMAL);
 504         }
 505 
 506         ResultInfo(KindSelector pkind, Type pt, CheckMode checkMode) {
 507             this(pkind, pt, chk.basicHandler, checkMode);
 508         }
 509 
 510         protected ResultInfo(KindSelector pkind,
 511                              Type pt, CheckContext checkContext) {
 512             this(pkind, pt, checkContext, CheckMode.NORMAL);
 513         }
 514 
 515         protected ResultInfo(KindSelector pkind,
 516                              Type pt, CheckContext checkContext, CheckMode checkMode) {
 517             this.pkind = pkind;
 518             this.pt = pt;
 519             this.checkContext = checkContext;
 520             this.checkMode = checkMode;
 521         }
 522 
 523         /**
 524          * Should {@link Attr#attribTree} use the {@ArgumentAttr} visitor instead of this one?
 525          * @param tree The tree to be type-checked.
 526          * @return true if {@ArgumentAttr} should be used.
 527          */
 528         protected boolean needsArgumentAttr(JCTree tree) { return false; }
 529 
 530         protected Type check(final DiagnosticPosition pos, final Type found) {
 531             return chk.checkType(pos, found, pt, checkContext);
 532         }
 533 
 534         protected ResultInfo dup(Type newPt) {
 535             return new ResultInfo(pkind, newPt, checkContext, checkMode);
 536         }
 537 
 538         protected ResultInfo dup(CheckContext newContext) {
 539             return new ResultInfo(pkind, pt, newContext, checkMode);
 540         }
 541 
 542         protected ResultInfo dup(Type newPt, CheckContext newContext) {
 543             return new ResultInfo(pkind, newPt, newContext, checkMode);
 544         }
 545 
 546         protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) {
 547             return new ResultInfo(pkind, newPt, newContext, newMode);
 548         }
 549 
 550         protected ResultInfo dup(CheckMode newMode) {
 551             return new ResultInfo(pkind, pt, checkContext, newMode);
 552         }
 553 
 554         @Override
 555         public String toString() {
 556             if (pt != null) {
 557                 return pt.toString();
 558             } else {
 559                 return "";
 560             }
 561         }
 562     }
 563 
 564     class MethodAttrInfo extends ResultInfo {
 565         public MethodAttrInfo() {
 566             this(chk.basicHandler);
 567         }
 568 
 569         public MethodAttrInfo(CheckContext checkContext) {
 570             super(KindSelector.VAL, Infer.anyPoly, checkContext);
 571         }
 572 
 573         @Override
 574         protected boolean needsArgumentAttr(JCTree tree) {
 575             return true;
 576         }
 577 
 578         protected ResultInfo dup(Type newPt) {
 579             throw new IllegalStateException();
 580         }
 581 
 582         protected ResultInfo dup(CheckContext newContext) {
 583             return new MethodAttrInfo(newContext);
 584         }
 585 
 586         protected ResultInfo dup(Type newPt, CheckContext newContext) {
 587             throw new IllegalStateException();
 588         }
 589 
 590         protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) {
 591             throw new IllegalStateException();
 592         }
 593 
 594         protected ResultInfo dup(CheckMode newMode) {
 595             throw new IllegalStateException();
 596         }
 597     }
 598 
 599     class RecoveryInfo extends ResultInfo {
 600 
 601         public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
 602             this(deferredAttrContext, Type.recoveryType);
 603         }
 604 
 605         public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext, Type pt) {
 606             super(KindSelector.VAL, pt, new Check.NestedCheckContext(chk.basicHandler) {
 607                 @Override
 608                 public DeferredAttr.DeferredAttrContext deferredAttrContext() {
 609                     return deferredAttrContext;
 610                 }
 611                 @Override
 612                 public boolean compatible(Type found, Type req, Warner warn) {
 613                     return true;
 614                 }
 615                 @Override
 616                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
 617                     if (pt == Type.recoveryType) {
 618                         chk.basicHandler.report(pos, details);
 619                     }
 620                 }
 621             });
 622         }
 623     }
 624 
 625     final ResultInfo statInfo;
 626     final ResultInfo varAssignmentInfo;
 627     final ResultInfo methodAttrInfo;
 628     final ResultInfo unknownExprInfo;
 629     final ResultInfo unknownTypeInfo;
 630     final ResultInfo unknownTypeExprInfo;
 631     final ResultInfo recoveryInfo;
 632 
 633     Type pt() {
 634         return resultInfo.pt;
 635     }
 636 
 637     KindSelector pkind() {
 638         return resultInfo.pkind;
 639     }
 640 
 641 /* ************************************************************************
 642  * Visitor methods
 643  *************************************************************************/
 644 
 645     /** Visitor argument: the current environment.
 646      */
 647     Env<AttrContext> env;
 648 
 649     /** Visitor argument: the currently expected attribution result.
 650      */
 651     ResultInfo resultInfo;
 652 
 653     /** Visitor result: the computed type.
 654      */
 655     Type result;
 656 
 657     /** Visitor method: attribute a tree, catching any completion failure
 658      *  exceptions. Return the tree's type.
 659      *
 660      *  @param tree    The tree to be visited.
 661      *  @param env     The environment visitor argument.
 662      *  @param resultInfo   The result info visitor argument.
 663      */
 664     Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
 665         Env<AttrContext> prevEnv = this.env;
 666         ResultInfo prevResult = this.resultInfo;
 667         try {
 668             this.env = env;
 669             this.resultInfo = resultInfo;
 670             if (resultInfo.needsArgumentAttr(tree)) {
 671                 result = argumentAttr.attribArg(tree, env);
 672             } else {
 673                 tree.accept(this);
 674             }
 675             if (tree == breakTree &&
 676                     resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
 677                 breakTreeFound(copyEnv(env));
 678             }
 679             return result;
 680         } catch (CompletionFailure ex) {
 681             tree.type = syms.errType;
 682             return chk.completionError(tree.pos(), ex);
 683         } finally {
 684             this.env = prevEnv;
 685             this.resultInfo = prevResult;
 686         }
 687     }
 688 
 689     protected void breakTreeFound(Env<AttrContext> env) {
 690         throw new BreakAttr(env);
 691     }
 692 
 693     Env<AttrContext> copyEnv(Env<AttrContext> env) {
 694         Env<AttrContext> newEnv =
 695                 env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
 696         if (newEnv.outer != null) {
 697             newEnv.outer = copyEnv(newEnv.outer);
 698         }
 699         return newEnv;
 700     }
 701 
 702     WriteableScope copyScope(WriteableScope sc) {
 703         WriteableScope newScope = WriteableScope.create(sc.owner);
 704         List<Symbol> elemsList = List.nil();
 705         for (Symbol sym : sc.getSymbols()) {
 706             elemsList = elemsList.prepend(sym);
 707         }
 708         for (Symbol s : elemsList) {
 709             newScope.enter(s);
 710         }
 711         return newScope;
 712     }
 713 
 714     /** Derived visitor method: attribute an expression tree.
 715      */
 716     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
 717         return attribTree(tree, env, new ResultInfo(KindSelector.VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
 718     }
 719 
 720     /** Derived visitor method: attribute an expression tree with
 721      *  no constraints on the computed type.
 722      */
 723     public Type attribExpr(JCTree tree, Env<AttrContext> env) {
 724         return attribTree(tree, env, unknownExprInfo);
 725     }
 726 
 727     /** Derived visitor method: attribute a type tree.
 728      */
 729     public Type attribType(JCTree tree, Env<AttrContext> env) {
 730         Type result = attribType(tree, env, Type.noType);
 731         return result;
 732     }
 733 
 734     /** Derived visitor method: attribute a type tree.
 735      */
 736     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
 737         Type result = attribTree(tree, env, new ResultInfo(KindSelector.TYP, pt));
 738         return result;
 739     }
 740 
 741     /** Derived visitor method: attribute a statement or definition tree.
 742      */
 743     public Type attribStat(JCTree tree, Env<AttrContext> env) {
 744         Env<AttrContext> analyzeEnv = analyzer.copyEnvIfNeeded(tree, env);
 745         try {
 746             return attribTree(tree, env, statInfo);
 747         } finally {
 748             analyzer.analyzeIfNeeded(tree, analyzeEnv);
 749         }
 750     }
 751 
 752     /** Attribute a list of expressions, returning a list of types.
 753      */
 754     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
 755         ListBuffer<Type> ts = new ListBuffer<>();
 756         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
 757             ts.append(attribExpr(l.head, env, pt));
 758         return ts.toList();
 759     }
 760 
 761     /** Attribute a list of statements, returning nothing.
 762      */
 763     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
 764         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
 765             attribStat(l.head, env);
 766     }
 767 
 768     /** Attribute the arguments in a method call, returning the method kind.
 769      */
 770     KindSelector attribArgs(KindSelector initialKind, List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) {
 771         KindSelector kind = initialKind;
 772         for (JCExpression arg : trees) {
 773             Type argtype = chk.checkNonVoid(arg, attribTree(arg, env, allowPoly ? methodAttrInfo : unknownExprInfo));
 774             if (argtype.hasTag(DEFERRED)) {
 775                 kind = KindSelector.of(KindSelector.POLY, kind);
 776             }
 777             argtypes.append(argtype);
 778         }
 779         return kind;
 780     }
 781 
 782     /** Attribute a type argument list, returning a list of types.
 783      *  Caller is responsible for calling checkRefTypes.
 784      */
 785     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
 786         ListBuffer<Type> argtypes = new ListBuffer<>();
 787         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
 788             argtypes.append(attribType(l.head, env));
 789         return argtypes.toList();
 790     }
 791 
 792     /** Attribute a type argument list, returning a list of types.
 793      *  Check that all the types are references.
 794      */
 795     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
 796         List<Type> types = attribAnyTypes(trees, env);
 797         return chk.checkRefTypes(trees, types);
 798     }
 799 
 800     /**
 801      * Attribute type variables (of generic classes or methods).
 802      * Compound types are attributed later in attribBounds.
 803      * @param typarams the type variables to enter
 804      * @param env      the current environment
 805      */
 806     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env, boolean checkCyclic) {
 807         for (JCTypeParameter tvar : typarams) {
 808             TypeVar a = (TypeVar)tvar.type;
 809             a.tsym.flags_field |= UNATTRIBUTED;
 810             a.setUpperBound(Type.noType);
 811             if (!tvar.bounds.isEmpty()) {
 812                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
 813                 for (JCExpression bound : tvar.bounds.tail)
 814                     bounds = bounds.prepend(attribType(bound, env));
 815                 types.setBounds(a, bounds.reverse());
 816             } else {
 817                 // if no bounds are given, assume a single bound of
 818                 // java.lang.Object.
 819                 types.setBounds(a, List.of(syms.objectType));
 820             }
 821             a.tsym.flags_field &= ~UNATTRIBUTED;
 822         }
 823         if (checkCyclic) {
 824             for (JCTypeParameter tvar : typarams) {
 825                 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
 826             }
 827         }
 828     }
 829 
 830     /**
 831      * Attribute the type references in a list of annotations.
 832      */
 833     void attribAnnotationTypes(List<JCAnnotation> annotations,
 834                                Env<AttrContext> env) {
 835         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
 836             JCAnnotation a = al.head;
 837             attribType(a.annotationType, env);
 838         }
 839     }
 840 
 841     /**
 842      * Attribute a "lazy constant value".
 843      *  @param env         The env for the const value
 844      *  @param variable    The initializer for the const value
 845      *  @param type        The expected type, or null
 846      *  @see VarSymbol#setLazyConstValue
 847      */
 848     public Object attribLazyConstantValue(Env<AttrContext> env,
 849                                       JCVariableDecl variable,
 850                                       Type type) {
 851 
 852         DiagnosticPosition prevLintPos
 853                 = deferredLintHandler.setPos(variable.pos());
 854 
 855         final JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
 856         try {
 857             Type itype = attribExpr(variable.init, env, type);
 858             if (variable.isImplicitlyTyped()) {
 859                 //fixup local variable type
 860                 type = variable.type = variable.sym.type = chk.checkLocalVarType(variable, itype.baseType(), variable.name);
 861             }
 862             if (itype.constValue() != null) {
 863                 return coerce(itype, type).constValue();
 864             } else {
 865                 return null;
 866             }
 867         } finally {
 868             log.useSource(prevSource);
 869             deferredLintHandler.setPos(prevLintPos);
 870         }
 871     }
 872 
 873     /** Attribute type reference in an `extends' or `implements' clause.
 874      *  Supertypes of anonymous inner classes are usually already attributed.
 875      *
 876      *  @param tree              The tree making up the type reference.
 877      *  @param env               The environment current at the reference.
 878      *  @param classExpected     true if only a class is expected here.
 879      *  @param interfaceExpected true if only an interface is expected here.
 880      */
 881     Type attribBase(JCTree tree,
 882                     ClassSymbol subType,
 883                     Env<AttrContext> env,
 884                     boolean classExpected,
 885                     boolean interfaceExpected,
 886                     boolean checkExtensible) {
 887         Type t = tree.type != null ?
 888             tree.type :
 889             attribType(tree, env);
 890         return checkBase(t, subType, tree, env, classExpected, interfaceExpected, checkExtensible);
 891     }
 892     Type checkBase(Type t,
 893                    ClassSymbol subType,
 894                    JCTree tree,
 895                    Env<AttrContext> env,
 896                    boolean classExpected,
 897                    boolean interfaceExpected,
 898                    boolean checkExtensible) {
 899         final DiagnosticPosition pos = tree.hasTag(TYPEAPPLY) ?
 900                 (((JCTypeApply) tree).clazz).pos() : tree.pos();
 901         if (t.tsym.isAnonymous()) {
 902             log.error(pos, Errors.CantInheritFromAnon);
 903             return types.createErrorType(t);
 904         }
 905         if (t.isErroneous())
 906             return t;
 907         if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
 908             // check that type variable is already visible
 909             if (t.getUpperBound() == null) {
 910                 log.error(pos, Errors.IllegalForwardRef);
 911                 return types.createErrorType(t);
 912             }
 913         } else {
 914             t = chk.checkClassType(pos, t, checkExtensible);
 915         }
 916         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
 917             log.error(pos, Errors.IntfExpectedHere);
 918             // return errType is necessary since otherwise there might
 919             // be undetected cycles which cause attribution to loop
 920             return types.createErrorType(t);
 921         } else if (checkExtensible &&
 922                    classExpected &&
 923                    (t.tsym.flags() & INTERFACE) != 0) {
 924             log.error(pos, Errors.NoIntfExpectedHere);
 925             return types.createErrorType(t);
 926         }
 927         if (checkExtensible &&
 928             ((t.tsym.flags() & FINAL) != 0)) {
 929             log.error(pos,
 930                       Errors.CantInheritFromFinal(t.tsym));
 931         }
 932         chk.checkNonCyclic(pos, t);
 933         return t;
 934     }
 935 
 936     Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
 937         Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
 938         id.type = env.info.scope.owner.enclClass().type;
 939         id.sym = env.info.scope.owner.enclClass();
 940         return id.type;
 941     }
 942 
 943     public void visitClassDef(JCClassDecl tree) {
 944         Optional<ArgumentAttr.LocalCacheContext> localCacheContext =
 945                 Optional.ofNullable(env.info.isSpeculative ?
 946                         argumentAttr.withLocalCacheContext() : null);
 947         try {
 948             // Local and anonymous classes have not been entered yet, so we need to
 949             // do it now.
 950             if (env.info.scope.owner.kind.matches(KindSelector.VAL_MTH)) {
 951                 enter.classEnter(tree, env);
 952             } else {
 953                 // If this class declaration is part of a class level annotation,
 954                 // as in @MyAnno(new Object() {}) class MyClass {}, enter it in
 955                 // order to simplify later steps and allow for sensible error
 956                 // messages.
 957                 if (env.tree.hasTag(NEWCLASS) && TreeInfo.isInAnnotation(env, tree))
 958                     enter.classEnter(tree, env);
 959             }
 960 
 961             ClassSymbol c = tree.sym;
 962             if (c == null) {
 963                 // exit in case something drastic went wrong during enter.
 964                 result = null;
 965             } else {
 966                 // make sure class has been completed:
 967                 c.complete();
 968 
 969                 // If this class appears as an anonymous class
 970                 // in a superclass constructor call
 971                 // disable implicit outer instance from being passed.
 972                 // (This would be an illegal access to "this before super").
 973                 if (env.info.isSelfCall &&
 974                         env.tree.hasTag(NEWCLASS)) {
 975                     c.flags_field |= NOOUTERTHIS;
 976                 }
 977                 attribClass(tree.pos(), c);
 978                 result = tree.type = c.type;
 979             }
 980         } finally {
 981             localCacheContext.ifPresent(LocalCacheContext::leave);
 982         }
 983     }
 984 
 985     public void visitMethodDef(JCMethodDecl tree) {
 986         MethodSymbol m = tree.sym;
 987         boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
 988 
 989         Lint lint = env.info.lint.augment(m);
 990         Lint prevLint = chk.setLint(lint);
 991         MethodSymbol prevMethod = chk.setMethod(m);
 992         try {
 993             deferredLintHandler.flush(tree.pos());
 994             chk.checkDeprecatedAnnotation(tree.pos(), m);
 995 
 996 
 997             // Create a new environment with local scope
 998             // for attributing the method.
 999             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
1000             localEnv.info.lint = lint;
1001 
1002             attribStats(tree.typarams, localEnv);
1003 
1004             // If we override any other methods, check that we do so properly.
1005             // JLS ???
1006             if (m.isStatic()) {
1007                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
1008             } else {
1009                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
1010             }
1011             chk.checkOverride(env, tree, m);
1012 
1013             if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
1014                 log.error(tree, Errors.DefaultOverridesObjectMember(m.name, Kinds.kindName(m.location()), m.location()));
1015             }
1016 
1017             // Enter all type parameters into the local method scope.
1018             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
1019                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
1020 
1021             ClassSymbol owner = env.enclClass.sym;
1022             if ((owner.flags() & ANNOTATION) != 0 &&
1023                     (tree.params.nonEmpty() ||
1024                     tree.recvparam != null))
1025                 log.error(tree.params.nonEmpty() ?
1026                         tree.params.head.pos() :
1027                         tree.recvparam.pos(),
1028                         Errors.IntfAnnotationMembersCantHaveParams);
1029 
1030             // Attribute all value parameters.
1031             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1032                 attribStat(l.head, localEnv);
1033             }
1034 
1035             chk.checkVarargsMethodDecl(localEnv, tree);
1036 
1037             // Check that type parameters are well-formed.
1038             chk.validate(tree.typarams, localEnv);
1039 
1040             // Check that result type is well-formed.
1041             if (tree.restype != null && !tree.restype.type.hasTag(VOID))
1042                 chk.validate(tree.restype, localEnv);
1043 
1044             // Check that receiver type is well-formed.
1045             if (tree.recvparam != null) {
1046                 // Use a new environment to check the receiver parameter.
1047                 // Otherwise I get "might not have been initialized" errors.
1048                 // Is there a better way?
1049                 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
1050                 attribType(tree.recvparam, newEnv);
1051                 chk.validate(tree.recvparam, newEnv);
1052             }
1053 
1054             // annotation method checks
1055             if ((owner.flags() & ANNOTATION) != 0) {
1056                 // annotation method cannot have throws clause
1057                 if (tree.thrown.nonEmpty()) {
1058                     log.error(tree.thrown.head.pos(),
1059                               Errors.ThrowsNotAllowedInIntfAnnotation);
1060                 }
1061                 // annotation method cannot declare type-parameters
1062                 if (tree.typarams.nonEmpty()) {
1063                     log.error(tree.typarams.head.pos(),
1064                               Errors.IntfAnnotationMembersCantHaveTypeParams);
1065                 }
1066                 // validate annotation method's return type (could be an annotation type)
1067                 chk.validateAnnotationType(tree.restype);
1068                 // ensure that annotation method does not clash with members of Object/Annotation
1069                 chk.validateAnnotationMethod(tree.pos(), m);
1070             }
1071 
1072             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
1073                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
1074 
1075             if (tree.body == null) {
1076                 // Empty bodies are only allowed for
1077                 // abstract, native, or interface methods, or for methods
1078                 // in a retrofit signature class.
1079                 if (tree.defaultValue != null) {
1080                     if ((owner.flags() & ANNOTATION) == 0)
1081                         log.error(tree.pos(),
1082                                   Errors.DefaultAllowedInIntfAnnotationMember);
1083                 }
1084                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1085                     log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract);
1086             } else if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1087                 if ((owner.flags() & INTERFACE) != 0) {
1088                     log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1089                 } else {
1090                     log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1091                 }
1092             } else if ((tree.mods.flags & NATIVE) != 0) {
1093                 log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1094             } else {
1095                 // Add an implicit super() call unless an explicit call to
1096                 // super(...) or this(...) is given
1097                 // or we are compiling class java.lang.Object.
1098                 if (tree.name == names.init && owner.type != syms.objectType) {
1099                     JCBlock body = tree.body;
1100                     if (body.stats.isEmpty() ||
1101                             TreeInfo.getConstructorInvocationName(body.stats, names,
1102                                     (env.enclClass.sym.flags() & RECORD) != 0) == names.empty) {
1103                         JCStatement supCall = make.at(body.pos).Exec(make.Apply(List.nil(),
1104                                 make.Ident(names._super), make.Idents(List.nil())));
1105                         body.stats = body.stats.prepend(supCall);
1106                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1107                             (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1108                             TreeInfo.isSuperCall(body.stats.head)) {
1109                         // enum constructors are not allowed to call super
1110                         // directly, so make sure there aren't any super calls
1111                         // in enum constructors, except in the compiler
1112                         // generated one.
1113                         log.error(tree.body.stats.head.pos(),
1114                                   Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1115                     }
1116                 }
1117 
1118                 // Attribute all type annotations in the body
1119                 annotate.queueScanTreeAndTypeAnnotate(tree.body, localEnv, m, null);
1120                 annotate.flush();
1121 
1122                 // Attribute method body.
1123                 attribStat(tree.body, localEnv);
1124             }
1125 
1126             localEnv.info.scope.leave();
1127             result = tree.type = m.type;
1128         } finally {
1129             chk.setLint(prevLint);
1130             chk.setMethod(prevMethod);
1131         }
1132     }
1133 
1134     public void visitVarDef(JCVariableDecl tree) {
1135         // Local variables have not been entered yet, so we need to do it now:
1136         if (env.info.scope.owner.kind == MTH || env.info.scope.owner.kind == VAR) {
1137             if (tree.sym != null) {
1138                 // parameters have already been entered
1139                 env.info.scope.enter(tree.sym);
1140             } else {
1141                 if (tree.isImplicitlyTyped() && (tree.getModifiers().flags & PARAMETER) == 0) {
1142                     if (tree.init == null) {
1143                         //cannot use 'var' without initializer
1144                         log.error(tree, Errors.CantInferLocalVarType(tree.name, Fragments.LocalMissingInit));
1145                         tree.vartype = make.Erroneous();
1146                     } else {
1147                         Fragment msg = canInferLocalVarType(tree);
1148                         if (msg != null) {
1149                             //cannot use 'var' with initializer which require an explicit target
1150                             //(e.g. lambda, method reference, array initializer).
1151                             log.error(tree, Errors.CantInferLocalVarType(tree.name, msg));
1152                             tree.vartype = make.Erroneous();
1153                         }
1154                     }
1155                 }
1156                 try {
1157                     annotate.blockAnnotations();
1158                     memberEnter.memberEnter(tree, env);
1159                 } finally {
1160                     annotate.unblockAnnotations();
1161                 }
1162             }
1163         } else {
1164             if (tree.init != null) {
1165                 // Field initializer expression need to be entered.
1166                 annotate.queueScanTreeAndTypeAnnotate(tree.init, env, tree.sym, tree.pos());
1167                 annotate.flush();
1168             }
1169         }
1170 
1171         VarSymbol v = tree.sym;
1172         Lint lint = env.info.lint.augment(v);
1173         Lint prevLint = chk.setLint(lint);
1174 
1175         // Check that the variable's declared type is well-formed.
1176         boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
1177                 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
1178                 (tree.sym.flags() & PARAMETER) != 0;
1179         chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1180 
1181         try {
1182             v.getConstValue(); // ensure compile-time constant initializer is evaluated
1183             deferredLintHandler.flush(tree.pos());
1184             chk.checkDeprecatedAnnotation(tree.pos(), v);
1185 
1186             if (tree.init != null) {
1187                 if ((v.flags_field & FINAL) == 0 ||
1188                     !memberEnter.needsLazyConstValue(tree.init)) {
1189                     // Not a compile-time constant
1190                     // Attribute initializer in a new environment
1191                     // with the declared variable as owner.
1192                     // Check that initializer conforms to variable's declared type.
1193                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1194                     initEnv.info.lint = lint;
1195                     // In order to catch self-references, we set the variable's
1196                     // declaration position to maximal possible value, effectively
1197                     // marking the variable as undefined.
1198                     initEnv.info.enclVar = v;
1199                     attribExpr(tree.init, initEnv, v.type);
1200                     if (tree.isImplicitlyTyped()) {
1201                         //fixup local variable type
1202                         v.type = chk.checkLocalVarType(tree, tree.init.type.baseType(), tree.name);
1203                     }
1204                 }
1205                 if (tree.isImplicitlyTyped()) {
1206                     setSyntheticVariableType(tree, v.type);
1207                 }
1208             }
1209             result = tree.type = v.type;
1210         }
1211         finally {
1212             chk.setLint(prevLint);
1213         }
1214     }
1215 
1216     Fragment canInferLocalVarType(JCVariableDecl tree) {
1217         LocalInitScanner lis = new LocalInitScanner();
1218         lis.scan(tree.init);
1219         return lis.badInferenceMsg;
1220     }
1221 
1222     static class LocalInitScanner extends TreeScanner {
1223         Fragment badInferenceMsg = null;
1224         boolean needsTarget = true;
1225 
1226         @Override
1227         public void visitNewArray(JCNewArray tree) {
1228             if (tree.elemtype == null && needsTarget) {
1229                 badInferenceMsg = Fragments.LocalArrayMissingTarget;
1230             }
1231         }
1232 
1233         @Override
1234         public void visitLambda(JCLambda tree) {
1235             if (needsTarget) {
1236                 badInferenceMsg = Fragments.LocalLambdaMissingTarget;
1237             }
1238         }
1239 
1240         @Override
1241         public void visitTypeCast(JCTypeCast tree) {
1242             boolean prevNeedsTarget = needsTarget;
1243             try {
1244                 needsTarget = false;
1245                 super.visitTypeCast(tree);
1246             } finally {
1247                 needsTarget = prevNeedsTarget;
1248             }
1249         }
1250 
1251         @Override
1252         public void visitReference(JCMemberReference tree) {
1253             if (needsTarget) {
1254                 badInferenceMsg = Fragments.LocalMrefMissingTarget;
1255             }
1256         }
1257 
1258         @Override
1259         public void visitNewClass(JCNewClass tree) {
1260             boolean prevNeedsTarget = needsTarget;
1261             try {
1262                 needsTarget = false;
1263                 super.visitNewClass(tree);
1264             } finally {
1265                 needsTarget = prevNeedsTarget;
1266             }
1267         }
1268 
1269         @Override
1270         public void visitApply(JCMethodInvocation tree) {
1271             boolean prevNeedsTarget = needsTarget;
1272             try {
1273                 needsTarget = false;
1274                 super.visitApply(tree);
1275             } finally {
1276                 needsTarget = prevNeedsTarget;
1277             }
1278         }
1279     }
1280 
1281     public void visitSkip(JCSkip tree) {
1282         result = null;
1283     }
1284 
1285     public void visitBlock(JCBlock tree) {
1286         if (env.info.scope.owner.kind == TYP) {
1287             // Block is a static or instance initializer;
1288             // let the owner of the environment be a freshly
1289             // created BLOCK-method.
1290             Symbol fakeOwner =
1291                 new MethodSymbol(tree.flags | BLOCK |
1292                     env.info.scope.owner.flags() & STRICTFP, names.empty, null,
1293                     env.info.scope.owner);
1294             final Env<AttrContext> localEnv =
1295                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1296 
1297             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
1298             // Attribute all type annotations in the block
1299             annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
1300             annotate.flush();
1301             attribStats(tree.stats, localEnv);
1302 
1303             {
1304                 // Store init and clinit type annotations with the ClassSymbol
1305                 // to allow output in Gen.normalizeDefs.
1306                 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1307                 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1308                 if ((tree.flags & STATIC) != 0) {
1309                     cs.appendClassInitTypeAttributes(tas);
1310                 } else {
1311                     cs.appendInitTypeAttributes(tas);
1312                 }
1313             }
1314         } else {
1315             // Create a new local environment with a local scope.
1316             Env<AttrContext> localEnv =
1317                 env.dup(tree, env.info.dup(env.info.scope.dup()));
1318             try {
1319                 attribStats(tree.stats, localEnv);
1320             } finally {
1321                 localEnv.info.scope.leave();
1322             }
1323         }
1324         result = null;
1325     }
1326 
1327     public void visitDoLoop(JCDoWhileLoop tree) {
1328         attribStat(tree.body, env.dup(tree));
1329         attribExpr(tree.cond, env, syms.booleanType);
1330         if (!breaksOutOf(tree, tree.body)) {
1331             List<BindingSymbol> bindings = matchBindingsComputer.getMatchBindings(tree.cond, false);
1332 
1333             bindings.forEach(env.info.scope::enter);
1334             bindings.forEach(BindingSymbol::preserveBinding);
1335         }
1336         result = null;
1337     }
1338 
1339     public void visitWhileLoop(JCWhileLoop tree) {
1340         attribExpr(tree.cond, env, syms.booleanType);
1341         // include x.T in while's body
1342         Env<AttrContext> whileEnv = bindingEnv(env, matchBindingsComputer.getMatchBindings(tree.cond, true));
1343         try {
1344             attribStat(tree.body, whileEnv.dup(tree));
1345         } finally {
1346             whileEnv.info.scope.leave();
1347         }
1348         if (!breaksOutOf(tree, tree.body)) {
1349             List<BindingSymbol> bindings = matchBindingsComputer.getMatchBindings(tree.cond, false);
1350 
1351             bindings.forEach(env.info.scope::enter);
1352             bindings.forEach(BindingSymbol::preserveBinding);
1353         }
1354         result = null;
1355     }
1356 
1357     private boolean breaksOutOf(JCTree loop, JCTree body) {
1358         preFlow(body);
1359         return flow.breaksOutOf(env, loop, body, make);
1360     }
1361 
1362     public void visitForLoop(JCForLoop tree) {
1363         Env<AttrContext> loopEnv =
1364             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1365         try {
1366             attribStats(tree.init, loopEnv);
1367             List<BindingSymbol> matchBindings = List.nil();
1368             if (tree.cond != null) {
1369                 attribExpr(tree.cond, loopEnv, syms.booleanType);
1370                 // include x.T in the evaluation scopes of body & step.
1371                 matchBindings = matchBindingsComputer.getMatchBindings(tree.cond, true);
1372             }
1373             Env<AttrContext> bodyEnv = bindingEnv(loopEnv, matchBindings);
1374             try {
1375                 bodyEnv.tree = tree; // before, we were not in loop!
1376                 attribStats(tree.step, bodyEnv);
1377                 attribStat(tree.body, bodyEnv);
1378             } finally {
1379                 bodyEnv.info.scope.leave();
1380             }
1381             result = null;
1382         }
1383         finally {
1384             loopEnv.info.scope.leave(); // all injected match bindings vanish here.
1385         }
1386         if (!breaksOutOf(tree, tree.body)) {
1387             List<BindingSymbol> bindings = matchBindingsComputer.getMatchBindings(tree.cond, false);
1388 
1389             bindings.forEach(env.info.scope::enter);
1390             bindings.forEach(BindingSymbol::preserveBinding);
1391         }
1392     }
1393 
1394     public void visitForeachLoop(JCEnhancedForLoop tree) {
1395         Env<AttrContext> loopEnv =
1396             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1397         try {
1398             //the Formal Parameter of a for-each loop is not in the scope when
1399             //attributing the for-each expression; we mimick this by attributing
1400             //the for-each expression first (against original scope).
1401             Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
1402             chk.checkNonVoid(tree.pos(), exprType);
1403             Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
1404             if (elemtype == null) {
1405                 // or perhaps expr implements Iterable<T>?
1406                 Type base = types.asSuper(exprType, syms.iterableType.tsym);
1407                 if (base == null) {
1408                     log.error(tree.expr.pos(),
1409                               Errors.ForeachNotApplicableToType(exprType,
1410                                                                 Fragments.TypeReqArrayOrIterable));
1411                     elemtype = types.createErrorType(exprType);
1412                 } else {
1413                     List<Type> iterableParams = base.allparams();
1414                     elemtype = iterableParams.isEmpty()
1415                         ? syms.objectType
1416                         : types.wildUpperBound(iterableParams.head);
1417                 }
1418             }
1419             if (tree.var.isImplicitlyTyped()) {
1420                 Type inferredType = chk.checkLocalVarType(tree.var, elemtype, tree.var.name);
1421                 setSyntheticVariableType(tree.var, inferredType);
1422             }
1423             attribStat(tree.var, loopEnv);
1424             chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
1425             loopEnv.tree = tree; // before, we were not in loop!
1426             attribStat(tree.body, loopEnv);
1427             result = null;
1428         }
1429         finally {
1430             loopEnv.info.scope.leave();
1431         }
1432     }
1433 
1434     public void visitLabelled(JCLabeledStatement tree) {
1435         // Check that label is not used in an enclosing statement
1436         Env<AttrContext> env1 = env;
1437         while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
1438             if (env1.tree.hasTag(LABELLED) &&
1439                 ((JCLabeledStatement) env1.tree).label == tree.label) {
1440                 log.error(tree.pos(),
1441                           Errors.LabelAlreadyInUse(tree.label));
1442                 break;
1443             }
1444             env1 = env1.next;
1445         }
1446 
1447         attribStat(tree.body, env.dup(tree));
1448         result = null;
1449     }
1450 
1451     public void visitSwitch(JCSwitch tree) {
1452         handleSwitch(tree, tree.selector, tree.cases, (c, caseEnv) -> {
1453             attribStats(c.stats, caseEnv);
1454         });
1455         result = null;
1456     }
1457 
1458     public void visitSwitchExpression(JCSwitchExpression tree) {
1459         tree.polyKind = (pt().hasTag(NONE) && pt() != Type.recoveryType && pt() != Infer.anyPoly) ?
1460                 PolyKind.STANDALONE : PolyKind.POLY;
1461 
1462         if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
1463             //this means we are returning a poly conditional from void-compatible lambda expression
1464             resultInfo.checkContext.report(tree, diags.fragment(Fragments.SwitchExpressionTargetCantBeVoid));
1465             result = tree.type = types.createErrorType(resultInfo.pt);
1466             return;
1467         }
1468 
1469         ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
1470                 unknownExprInfo :
1471                 resultInfo.dup(switchExpressionContext(resultInfo.checkContext));
1472 
1473         ListBuffer<DiagnosticPosition> caseTypePositions = new ListBuffer<>();
1474         ListBuffer<Type> caseTypes = new ListBuffer<>();
1475 
1476         handleSwitch(tree, tree.selector, tree.cases, (c, caseEnv) -> {
1477             caseEnv.info.yieldResult = condInfo;
1478             attribStats(c.stats, caseEnv);
1479             new TreeScanner() {
1480                 @Override
1481                 public void visitYield(JCYield brk) {
1482                     if (brk.target == tree) {
1483                         caseTypePositions.append(brk.value != null ? brk.value.pos() : brk.pos());
1484                         caseTypes.append(brk.value != null ? brk.value.type : syms.errType);
1485                     }
1486                     super.visitYield(brk);
1487                 }
1488 
1489                 @Override public void visitClassDef(JCClassDecl tree) {}
1490                 @Override public void visitLambda(JCLambda tree) {}
1491             }.scan(c.stats);
1492         });
1493 
1494         if (tree.cases.isEmpty()) {
1495             log.error(tree.pos(),
1496                       Errors.SwitchExpressionEmpty);
1497         }
1498 
1499         Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(caseTypePositions.toList(), caseTypes.toList()) : pt();
1500 
1501         result = tree.type = check(tree, owntype, KindSelector.VAL, resultInfo);
1502     }
1503     //where:
1504         CheckContext switchExpressionContext(CheckContext checkContext) {
1505             return new Check.NestedCheckContext(checkContext) {
1506                 //this will use enclosing check context to check compatibility of
1507                 //subexpression against target type; if we are in a method check context,
1508                 //depending on whether boxing is allowed, we could have incompatibilities
1509                 @Override
1510                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1511                     enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleTypeInSwitchExpression(details)));
1512                 }
1513             };
1514         }
1515 
1516     private void handleSwitch(JCTree switchTree,
1517                               JCExpression selector,
1518                               List<JCCase> cases,
1519                               BiConsumer<JCCase, Env<AttrContext>> attribCase) {
1520         Type seltype = attribExpr(selector, env);
1521 
1522         Env<AttrContext> switchEnv =
1523             env.dup(switchTree, env.info.dup(env.info.scope.dup()));
1524 
1525         try {
1526             boolean enumSwitch = (seltype.tsym.flags() & Flags.ENUM) != 0;
1527             boolean stringSwitch = types.isSameType(seltype, syms.stringType);
1528             if (!enumSwitch && !stringSwitch)
1529                 seltype = chk.checkType(selector.pos(), seltype, syms.intType);
1530 
1531             // Attribute all cases and
1532             // check that there are no duplicate case labels or default clauses.
1533             Set<Object> labels = new HashSet<>(); // The set of case labels.
1534             boolean hasDefault = false;      // Is there a default label?
1535             @SuppressWarnings("removal")
1536             CaseKind caseKind = null;
1537             boolean wasError = false;
1538             for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
1539                 JCCase c = l.head;
1540                 if (caseKind == null) {
1541                     caseKind = c.caseKind;
1542                 } else if (caseKind != c.caseKind && !wasError) {
1543                     log.error(c.pos(),
1544                               Errors.SwitchMixingCaseTypes);
1545                     wasError = true;
1546                 }
1547                 if (c.getExpressions().nonEmpty()) {
1548                     for (JCExpression pat : c.getExpressions()) {
1549                         if (TreeInfo.isNull(pat)) {
1550                             log.error(pat.pos(),
1551                                       Errors.SwitchNullNotAllowed);
1552                         } else if (enumSwitch) {
1553                             Symbol sym = enumConstant(pat, seltype);
1554                             if (sym == null) {
1555                                 log.error(pat.pos(), Errors.EnumLabelMustBeUnqualifiedEnum);
1556                             } else if (!labels.add(sym)) {
1557                                 log.error(c.pos(), Errors.DuplicateCaseLabel);
1558                             }
1559                         } else {
1560                             Type pattype = attribExpr(pat, switchEnv, seltype);
1561                             if (!pattype.hasTag(ERROR)) {
1562                                 if (pattype.constValue() == null) {
1563                                     log.error(pat.pos(),
1564                                               (stringSwitch ? Errors.StringConstReq : Errors.ConstExprReq));
1565                                 } else if (!labels.add(pattype.constValue())) {
1566                                     log.error(c.pos(), Errors.DuplicateCaseLabel);
1567                                 }
1568                             }
1569                         }
1570                     }
1571                 } else if (hasDefault) {
1572                     log.error(c.pos(), Errors.DuplicateDefaultLabel);
1573                 } else {
1574                     hasDefault = true;
1575                 }
1576                 Env<AttrContext> caseEnv =
1577                     switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
1578                 try {
1579                     attribCase.accept(c, caseEnv);
1580                 } finally {
1581                     caseEnv.info.scope.leave();
1582                     addVars(c.stats, switchEnv.info.scope);
1583                 }
1584             }
1585         } finally {
1586             switchEnv.info.scope.leave();
1587         }
1588     }
1589     // where
1590         /** Add any variables defined in stats to the switch scope. */
1591         private static void addVars(List<JCStatement> stats, WriteableScope switchScope) {
1592             for (;stats.nonEmpty(); stats = stats.tail) {
1593                 JCTree stat = stats.head;
1594                 if (stat.hasTag(VARDEF))
1595                     switchScope.enter(((JCVariableDecl) stat).sym);
1596             }
1597         }
1598     // where
1599     /** Return the selected enumeration constant symbol, or null. */
1600     private Symbol enumConstant(JCTree tree, Type enumType) {
1601         if (tree.hasTag(IDENT)) {
1602             JCIdent ident = (JCIdent)tree;
1603             Name name = ident.name;
1604             for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1605                 if (sym.kind == VAR) {
1606                     Symbol s = ident.sym = sym;
1607                     ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1608                     ident.type = s.type;
1609                     return ((s.flags_field & Flags.ENUM) == 0)
1610                         ? null : s;
1611                 }
1612             }
1613         }
1614         return null;
1615     }
1616 
1617     public void visitSynchronized(JCSynchronized tree) {
1618         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1619         attribStat(tree.body, env);
1620         result = null;
1621     }
1622 
1623     public void visitTry(JCTry tree) {
1624         // Create a new local environment with a local
1625         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1626         try {
1627             boolean isTryWithResource = tree.resources.nonEmpty();
1628             // Create a nested environment for attributing the try block if needed
1629             Env<AttrContext> tryEnv = isTryWithResource ?
1630                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1631                 localEnv;
1632             try {
1633                 // Attribute resource declarations
1634                 for (JCTree resource : tree.resources) {
1635                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1636                         @Override
1637                         public void report(DiagnosticPosition pos, JCDiagnostic details) {
1638                             chk.basicHandler.report(pos, diags.fragment(Fragments.TryNotApplicableToType(details)));
1639                         }
1640                     };
1641                     ResultInfo twrResult =
1642                         new ResultInfo(KindSelector.VAR,
1643                                        syms.autoCloseableType,
1644                                        twrContext);
1645                     if (resource.hasTag(VARDEF)) {
1646                         attribStat(resource, tryEnv);
1647                         twrResult.check(resource, resource.type);
1648 
1649                         //check that resource type cannot throw InterruptedException
1650                         checkAutoCloseable(resource.pos(), localEnv, resource.type);
1651 
1652                         VarSymbol var = ((JCVariableDecl) resource).sym;
1653                         var.setData(ElementKind.RESOURCE_VARIABLE);
1654                     } else {
1655                         attribTree(resource, tryEnv, twrResult);
1656                     }
1657                 }
1658                 // Attribute body
1659                 attribStat(tree.body, tryEnv);
1660             } finally {
1661                 if (isTryWithResource)
1662                     tryEnv.info.scope.leave();
1663             }
1664 
1665             // Attribute catch clauses
1666             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1667                 JCCatch c = l.head;
1668                 Env<AttrContext> catchEnv =
1669                     localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
1670                 try {
1671                     Type ctype = attribStat(c.param, catchEnv);
1672                     if (TreeInfo.isMultiCatch(c)) {
1673                         //multi-catch parameter is implicitly marked as final
1674                         c.param.sym.flags_field |= FINAL | UNION;
1675                     }
1676                     if (c.param.sym.kind == VAR) {
1677                         c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
1678                     }
1679                     chk.checkType(c.param.vartype.pos(),
1680                                   chk.checkClassType(c.param.vartype.pos(), ctype),
1681                                   syms.throwableType);
1682                     attribStat(c.body, catchEnv);
1683                 } finally {
1684                     catchEnv.info.scope.leave();
1685                 }
1686             }
1687 
1688             // Attribute finalizer
1689             if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1690             result = null;
1691         }
1692         finally {
1693             localEnv.info.scope.leave();
1694         }
1695     }
1696 
1697     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
1698         if (!resource.isErroneous() &&
1699             types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
1700             !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
1701             Symbol close = syms.noSymbol;
1702             Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
1703             try {
1704                 close = rs.resolveQualifiedMethod(pos,
1705                         env,
1706                         types.skipTypeVars(resource, false),
1707                         names.close,
1708                         List.nil(),
1709                         List.nil());
1710             }
1711             finally {
1712                 log.popDiagnosticHandler(discardHandler);
1713             }
1714             if (close.kind == MTH &&
1715                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
1716                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
1717                     env.info.lint.isEnabled(LintCategory.TRY)) {
1718                 log.warning(LintCategory.TRY, pos, Warnings.TryResourceThrowsInterruptedExc(resource));
1719             }
1720         }
1721     }
1722 
1723     public void visitConditional(JCConditional tree) {
1724         Type condtype = attribExpr(tree.cond, env, syms.booleanType);
1725 
1726         tree.polyKind = (!allowPoly ||
1727                 pt().hasTag(NONE) && pt() != Type.recoveryType && pt() != Infer.anyPoly ||
1728                 isBooleanOrNumeric(env, tree)) ?
1729                 PolyKind.STANDALONE : PolyKind.POLY;
1730 
1731         if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
1732             //this means we are returning a poly conditional from void-compatible lambda expression
1733             resultInfo.checkContext.report(tree, diags.fragment(Fragments.ConditionalTargetCantBeVoid));
1734             result = tree.type = types.createErrorType(resultInfo.pt);
1735             return;
1736         }
1737 
1738         ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
1739                 unknownExprInfo :
1740                 resultInfo.dup(conditionalContext(resultInfo.checkContext));
1741 
1742         /*  if e = "x ? y : z", then:
1743                 include x.T in y
1744                 include x.F in z
1745         */
1746 
1747         Type truetype;
1748         Env<AttrContext> trueEnv = bindingEnv(env, matchBindingsComputer.getMatchBindings(tree.cond, true));
1749         try {
1750             truetype = attribTree(tree.truepart, trueEnv, condInfo);
1751         } finally {
1752             trueEnv.info.scope.leave();
1753         }
1754 
1755         Type falsetype;
1756         Env<AttrContext> falseEnv = bindingEnv(env, matchBindingsComputer.getMatchBindings(tree.cond, false));
1757         try {
1758             falsetype = attribTree(tree.falsepart, falseEnv, condInfo);
1759         } finally {
1760             falseEnv.info.scope.leave();
1761         }
1762 
1763         Type owntype = (tree.polyKind == PolyKind.STANDALONE) ?
1764                 condType(List.of(tree.truepart.pos(), tree.falsepart.pos()),
1765                          List.of(truetype, falsetype)) : pt();
1766         if (condtype.constValue() != null &&
1767                 truetype.constValue() != null &&
1768                 falsetype.constValue() != null &&
1769                 !owntype.hasTag(NONE)) {
1770             //constant folding
1771             owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
1772         }
1773         result = check(tree, owntype, KindSelector.VAL, resultInfo);
1774     }
1775     //where
1776         private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
1777             switch (tree.getTag()) {
1778                 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
1779                               ((JCLiteral)tree).typetag == BOOLEAN ||
1780                               ((JCLiteral)tree).typetag == BOT;
1781                 case LAMBDA: case REFERENCE: return false;
1782                 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
1783                 case CONDEXPR:
1784                     JCConditional condTree = (JCConditional)tree;
1785                     return isBooleanOrNumeric(env, condTree.truepart) &&
1786                             isBooleanOrNumeric(env, condTree.falsepart);
1787                 case APPLY:
1788                     JCMethodInvocation speculativeMethodTree =
1789                             (JCMethodInvocation)deferredAttr.attribSpeculative(
1790                                     tree, env, unknownExprInfo,
1791                                     argumentAttr.withLocalCacheContext());
1792                     Symbol msym = TreeInfo.symbol(speculativeMethodTree.meth);
1793                     Type receiverType = speculativeMethodTree.meth.hasTag(IDENT) ?
1794                             env.enclClass.type :
1795                             ((JCFieldAccess)speculativeMethodTree.meth).selected.type;
1796                     Type owntype = types.memberType(receiverType, msym).getReturnType();
1797                     return primitiveOrBoxed(owntype);
1798                 case NEWCLASS:
1799                     JCExpression className =
1800                             removeClassParams.translate(((JCNewClass)tree).clazz);
1801                     JCExpression speculativeNewClassTree =
1802                             (JCExpression)deferredAttr.attribSpeculative(
1803                                     className, env, unknownTypeInfo,
1804                                     argumentAttr.withLocalCacheContext());
1805                     return primitiveOrBoxed(speculativeNewClassTree.type);
1806                 default:
1807                     Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo,
1808                             argumentAttr.withLocalCacheContext()).type;
1809                     return primitiveOrBoxed(speculativeType);
1810             }
1811         }
1812         //where
1813             boolean primitiveOrBoxed(Type t) {
1814                 return (!t.hasTag(TYPEVAR) && types.unboxedTypeOrType(t).isPrimitive());
1815             }
1816 
1817             TreeTranslator removeClassParams = new TreeTranslator() {
1818                 @Override
1819                 public void visitTypeApply(JCTypeApply tree) {
1820                     result = translate(tree.clazz);
1821                 }
1822             };
1823 
1824         CheckContext conditionalContext(CheckContext checkContext) {
1825             return new Check.NestedCheckContext(checkContext) {
1826                 //this will use enclosing check context to check compatibility of
1827                 //subexpression against target type; if we are in a method check context,
1828                 //depending on whether boxing is allowed, we could have incompatibilities
1829                 @Override
1830                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1831                     enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleTypeInConditional(details)));
1832                 }
1833             };
1834         }
1835 
1836         /** Compute the type of a conditional expression, after
1837          *  checking that it exists.  See JLS 15.25. Does not take into
1838          *  account the special case where condition and both arms
1839          *  are constants.
1840          *
1841          *  @param pos      The source position to be used for error
1842          *                  diagnostics.
1843          *  @param thentype The type of the expression's then-part.
1844          *  @param elsetype The type of the expression's else-part.
1845          */
1846         Type condType(List<DiagnosticPosition> positions, List<Type> condTypes) {
1847             if (condTypes.isEmpty()) {
1848                 return syms.objectType; //TODO: how to handle?
1849             }
1850             Type first = condTypes.head;
1851             // If same type, that is the result
1852             if (condTypes.tail.stream().allMatch(t -> types.isSameType(first, t)))
1853                 return first.baseType();
1854 
1855             List<Type> unboxedTypes = condTypes.stream()
1856                                                .map(t -> t.isPrimitive() ? t : types.unboxedType(t))
1857                                                .collect(List.collector());
1858 
1859             // Otherwise, if both arms can be converted to a numeric
1860             // type, return the least numeric type that fits both arms
1861             // (i.e. return larger of the two, or return int if one
1862             // arm is short, the other is char).
1863             if (unboxedTypes.stream().allMatch(t -> t.isPrimitive())) {
1864                 // If one arm has an integer subrange type (i.e., byte,
1865                 // short, or char), and the other is an integer constant
1866                 // that fits into the subrange, return the subrange type.
1867                 for (Type type : unboxedTypes) {
1868                     if (!type.getTag().isStrictSubRangeOf(INT)) {
1869                         continue;
1870                     }
1871                     if (unboxedTypes.stream().filter(t -> t != type).allMatch(t -> t.hasTag(INT) && types.isAssignable(t, type)))
1872                         return type.baseType();
1873                 }
1874 
1875                 for (TypeTag tag : primitiveTags) {
1876                     Type candidate = syms.typeOfTag[tag.ordinal()];
1877                     if (unboxedTypes.stream().allMatch(t -> types.isSubtype(t, candidate))) {
1878                         return candidate;
1879                     }
1880                 }
1881             }
1882 
1883             // Those were all the cases that could result in a primitive
1884             condTypes = condTypes.stream()
1885                                  .map(t -> t.isPrimitive() ? types.boxedClass(t).type : t)
1886                                  .collect(List.collector());
1887 
1888             for (Type type : condTypes) {
1889                 if (condTypes.stream().filter(t -> t != type).allMatch(t -> types.isAssignable(t, type)))
1890                     return type.baseType();
1891             }
1892 
1893             Iterator<DiagnosticPosition> posIt = positions.iterator();
1894 
1895             condTypes = condTypes.stream()
1896                                  .map(t -> chk.checkNonVoid(posIt.next(), t))
1897                                  .collect(List.collector());
1898 
1899             // both are known to be reference types.  The result is
1900             // lub(thentype,elsetype). This cannot fail, as it will
1901             // always be possible to infer "Object" if nothing better.
1902             return types.lub(condTypes.stream().map(t -> t.baseType()).collect(List.collector()));
1903         }
1904 
1905     final static TypeTag[] primitiveTags = new TypeTag[]{
1906         BYTE,
1907         CHAR,
1908         SHORT,
1909         INT,
1910         LONG,
1911         FLOAT,
1912         DOUBLE,
1913         BOOLEAN,
1914     };
1915 
1916     Env<AttrContext> bindingEnv(Env<AttrContext> env, List<BindingSymbol> bindings) {
1917         Env<AttrContext> env1 = env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1918         bindings.forEach(env1.info.scope::enter);
1919         return env1;
1920     }
1921 
1922     public void visitIf(JCIf tree) {
1923         attribExpr(tree.cond, env, syms.booleanType);
1924 
1925         // if (x) { y } [ else z ] include x.T in y; include x.F in z
1926 
1927         List<BindingSymbol> thenBindings = matchBindingsComputer.getMatchBindings(tree.cond, true);
1928         Env<AttrContext> thenEnv = bindingEnv(env, thenBindings);
1929 
1930         try {
1931             attribStat(tree.thenpart, thenEnv);
1932         } finally {
1933             thenEnv.info.scope.leave();
1934         }
1935 
1936         preFlow(tree.thenpart);
1937         boolean aliveAfterThen = flow.aliveAfter(env, tree.thenpart, make);
1938         boolean aliveAfterElse;
1939         List<BindingSymbol> elseBindings = matchBindingsComputer.getMatchBindings(tree.cond, false);
1940 
1941         if (tree.elsepart != null) {
1942             Env<AttrContext> elseEnv = bindingEnv(env, elseBindings);
1943             try {
1944                 attribStat(tree.elsepart, elseEnv);
1945             } finally {
1946                 elseEnv.info.scope.leave();
1947             }
1948             preFlow(tree.elsepart);
1949             aliveAfterElse = flow.aliveAfter(env, tree.elsepart, make);
1950         } else {
1951             aliveAfterElse = true;
1952         }
1953 
1954         chk.checkEmptyIf(tree);
1955 
1956         List<BindingSymbol> afterIfBindings = List.nil();
1957 
1958         if (aliveAfterThen && !aliveAfterElse) {
1959             afterIfBindings = thenBindings;
1960         } else if (aliveAfterElse && !aliveAfterThen) {
1961             afterIfBindings = elseBindings;
1962         }
1963 
1964         afterIfBindings.forEach(env.info.scope::enter);
1965         afterIfBindings.forEach(BindingSymbol::preserveBinding);
1966 
1967         result = null;
1968     }
1969 
1970         void preFlow(JCTree tree) {
1971             new PostAttrAnalyzer() {
1972                 @Override
1973                 public void scan(JCTree tree) {
1974                     if (tree == null ||
1975                             (tree.type != null &&
1976                             tree.type == Type.stuckType)) {
1977                         //don't touch stuck expressions!
1978                         return;
1979                     }
1980                     super.scan(tree);
1981                 }
1982             }.scan(tree);
1983         }
1984 
1985     public void visitExec(JCExpressionStatement tree) {
1986         //a fresh environment is required for 292 inference to work properly ---
1987         //see Infer.instantiatePolymorphicSignatureInstance()
1988         Env<AttrContext> localEnv = env.dup(tree);
1989         attribExpr(tree.expr, localEnv);
1990         result = null;
1991     }
1992 
1993     public void visitBreak(JCBreak tree) {
1994         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1995         result = null;
1996     }
1997 
1998     public void visitYield(JCYield tree) {
1999         if (env.info.yieldResult != null) {
2000             attribTree(tree.value, env, env.info.yieldResult);
2001             tree.target = findJumpTarget(tree.pos(), tree.getTag(), names.empty, env);
2002         } else {
2003             log.error(tree.pos(), tree.value.hasTag(PARENS)
2004                     ? Errors.NoSwitchExpressionQualify
2005                     : Errors.NoSwitchExpression);
2006             attribTree(tree.value, env, unknownExprInfo);
2007         }
2008         result = null;
2009     }
2010 
2011     public void visitContinue(JCContinue tree) {
2012         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
2013         result = null;
2014     }
2015     //where
2016         /** Return the target of a break, continue or yield statement,
2017          *  if it exists, report an error if not.
2018          *  Note: The target of a labelled break or continue is the
2019          *  (non-labelled) statement tree referred to by the label,
2020          *  not the tree representing the labelled statement itself.
2021          *
2022          *  @param pos     The position to be used for error diagnostics
2023          *  @param tag     The tag of the jump statement. This is either
2024          *                 Tree.BREAK or Tree.CONTINUE.
2025          *  @param label   The label of the jump statement, or null if no
2026          *                 label is given.
2027          *  @param env     The environment current at the jump statement.
2028          */
2029         private JCTree findJumpTarget(DiagnosticPosition pos,
2030                                                    JCTree.Tag tag,
2031                                                    Name label,
2032                                                    Env<AttrContext> env) {
2033             Pair<JCTree, Error> jumpTarget = findJumpTargetNoError(tag, label, env);
2034 
2035             if (jumpTarget.snd != null) {
2036                 log.error(pos, jumpTarget.snd);
2037             }
2038 
2039             return jumpTarget.fst;
2040         }
2041         /** Return the target of a break or continue statement, if it exists,
2042          *  report an error if not.
2043          *  Note: The target of a labelled break or continue is the
2044          *  (non-labelled) statement tree referred to by the label,
2045          *  not the tree representing the labelled statement itself.
2046          *
2047          *  @param tag     The tag of the jump statement. This is either
2048          *                 Tree.BREAK or Tree.CONTINUE.
2049          *  @param label   The label of the jump statement, or null if no
2050          *                 label is given.
2051          *  @param env     The environment current at the jump statement.
2052          */
2053         private Pair<JCTree, JCDiagnostic.Error> findJumpTargetNoError(JCTree.Tag tag,
2054                                                                        Name label,
2055                                                                        Env<AttrContext> env) {
2056             // Search environments outwards from the point of jump.
2057             Env<AttrContext> env1 = env;
2058             JCDiagnostic.Error pendingError = null;
2059             LOOP:
2060             while (env1 != null) {
2061                 switch (env1.tree.getTag()) {
2062                     case LABELLED:
2063                         JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
2064                         if (label == labelled.label) {
2065                             // If jump is a continue, check that target is a loop.
2066                             if (tag == CONTINUE) {
2067                                 if (!labelled.body.hasTag(DOLOOP) &&
2068                                         !labelled.body.hasTag(WHILELOOP) &&
2069                                         !labelled.body.hasTag(FORLOOP) &&
2070                                         !labelled.body.hasTag(FOREACHLOOP)) {
2071                                     pendingError = Errors.NotLoopLabel(label);
2072                                 }
2073                                 // Found labelled statement target, now go inwards
2074                                 // to next non-labelled tree.
2075                                 return Pair.of(TreeInfo.referencedStatement(labelled), pendingError);
2076                             } else {
2077                                 return Pair.of(labelled, pendingError);
2078                             }
2079                         }
2080                         break;
2081                     case DOLOOP:
2082                     case WHILELOOP:
2083                     case FORLOOP:
2084                     case FOREACHLOOP:
2085                         if (label == null) return Pair.of(env1.tree, pendingError);
2086                         break;
2087                     case SWITCH:
2088                         if (label == null && tag == BREAK) return Pair.of(env1.tree, null);
2089                         break;
2090                     case SWITCH_EXPRESSION:
2091                         if (tag == YIELD) {
2092                             return Pair.of(env1.tree, null);
2093                         } else if (tag == BREAK) {
2094                             pendingError = Errors.BreakOutsideSwitchExpression;
2095                         } else {
2096                             pendingError = Errors.ContinueOutsideSwitchExpression;
2097                         }
2098                         break;
2099                     case LAMBDA:
2100                     case METHODDEF:
2101                     case CLASSDEF:
2102                         break LOOP;
2103                     default:
2104                 }
2105                 env1 = env1.next;
2106             }
2107             if (label != null)
2108                 return Pair.of(null, Errors.UndefLabel(label));
2109             else if (pendingError != null)
2110                 return Pair.of(null, pendingError);
2111             else if (tag == CONTINUE)
2112                 return Pair.of(null, Errors.ContOutsideLoop);
2113             else
2114                 return Pair.of(null, Errors.BreakOutsideSwitchLoop);
2115         }
2116 
2117     public void visitReturn(JCReturn tree) {
2118         // Check that there is an enclosing method which is
2119         // nested within than the enclosing class.
2120         if (env.info.returnResult == null) {
2121             log.error(tree.pos(), Errors.RetOutsideMeth);
2122         } else if (env.info.yieldResult != null) {
2123             log.error(tree.pos(), Errors.ReturnOutsideSwitchExpression);
2124         } else {
2125             // Attribute return expression, if it exists, and check that
2126             // it conforms to result type of enclosing method.
2127             if (tree.expr != null) {
2128                 if (env.info.returnResult.pt.hasTag(VOID)) {
2129                     env.info.returnResult.checkContext.report(tree.expr.pos(),
2130                               diags.fragment(Fragments.UnexpectedRetVal));
2131                 }
2132                 attribTree(tree.expr, env, env.info.returnResult);
2133             } else if (!env.info.returnResult.pt.hasTag(VOID) &&
2134                     !env.info.returnResult.pt.hasTag(NONE)) {
2135                 env.info.returnResult.checkContext.report(tree.pos(),
2136                               diags.fragment(Fragments.MissingRetVal(env.info.returnResult.pt)));
2137             }
2138         }
2139         result = null;
2140     }
2141 
2142     public void visitThrow(JCThrow tree) {
2143         Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
2144         if (allowPoly) {
2145             chk.checkType(tree, owntype, syms.throwableType);
2146         }
2147         result = null;
2148     }
2149 
2150     public void visitAssert(JCAssert tree) {
2151         attribExpr(tree.cond, env, syms.booleanType);
2152         if (tree.detail != null) {
2153             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
2154         }
2155         result = null;
2156     }
2157 
2158      /** Visitor method for method invocations.
2159      *  NOTE: The method part of an application will have in its type field
2160      *        the return type of the method, not the method's type itself!
2161      */
2162     public void visitApply(JCMethodInvocation tree) {
2163         // The local environment of a method application is
2164         // a new environment nested in the current one.
2165         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
2166 
2167         // The types of the actual method arguments.
2168         List<Type> argtypes;
2169 
2170         // The types of the actual method type arguments.
2171         List<Type> typeargtypes = null;
2172 
2173         Name methName = TreeInfo.name(tree.meth);
2174 
2175         boolean isConstructorCall =
2176             methName == names._this || methName == names._super;
2177 
2178         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2179         if (isConstructorCall) {
2180             // We are seeing a ...this(...) or ...super(...) call.
2181             // Check that this is the first statement in a constructor.
2182             if (checkFirstConstructorStat(tree, env)) {
2183 
2184                 // Record the fact
2185                 // that this is a constructor call (using isSelfCall).
2186                 localEnv.info.isSelfCall = true;
2187 
2188                 // Attribute arguments, yielding list of argument types.
2189                 KindSelector kind = attribArgs(KindSelector.MTH, tree.args, localEnv, argtypesBuf);
2190                 argtypes = argtypesBuf.toList();
2191                 typeargtypes = attribTypes(tree.typeargs, localEnv);
2192 
2193                 // Variable `site' points to the class in which the called
2194                 // constructor is defined.
2195                 Type site = env.enclClass.sym.type;
2196                 if (methName == names._super) {
2197                     if (site == syms.objectType) {
2198                         log.error(tree.meth.pos(), Errors.NoSuperclass(site));
2199                         site = types.createErrorType(syms.objectType);
2200                     } else {
2201                         site = types.supertype(site);
2202                     }
2203                 }
2204 
2205                 if (site.hasTag(CLASS)) {
2206                     Type encl = site.getEnclosingType();
2207                     while (encl != null && encl.hasTag(TYPEVAR))
2208                         encl = encl.getUpperBound();
2209                     if (encl.hasTag(CLASS)) {
2210                         // we are calling a nested class
2211 
2212                         if (tree.meth.hasTag(SELECT)) {
2213                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
2214 
2215                             // We are seeing a prefixed call, of the form
2216                             //     <expr>.super(...).
2217                             // Check that the prefix expression conforms
2218                             // to the outer instance type of the class.
2219                             chk.checkRefType(qualifier.pos(),
2220                                              attribExpr(qualifier, localEnv,
2221                                                         encl));
2222                         } else if (methName == names._super) {
2223                             // qualifier omitted; check for existence
2224                             // of an appropriate implicit qualifier.
2225                             rs.resolveImplicitThis(tree.meth.pos(),
2226                                                    localEnv, site, true);
2227                         }
2228                     } else if (tree.meth.hasTag(SELECT)) {
2229                         log.error(tree.meth.pos(),
2230                                   Errors.IllegalQualNotIcls(site.tsym));
2231                     }
2232 
2233                     // if we're calling a java.lang.Enum constructor,
2234                     // prefix the implicit String and int parameters
2235                     if (site.tsym == syms.enumSym)
2236                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
2237 
2238                     // Resolve the called constructor under the assumption
2239                     // that we are referring to a superclass instance of the
2240                     // current instance (JLS ???).
2241                     boolean selectSuperPrev = localEnv.info.selectSuper;
2242                     localEnv.info.selectSuper = true;
2243                     localEnv.info.pendingResolutionPhase = null;
2244                     Symbol sym = rs.resolveConstructor(
2245                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
2246                     localEnv.info.selectSuper = selectSuperPrev;
2247 
2248                     // Set method symbol to resolved constructor...
2249                     TreeInfo.setSymbol(tree.meth, sym);
2250 
2251                     // ...and check that it is legal in the current context.
2252                     // (this will also set the tree's type)
2253                     Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
2254                     checkId(tree.meth, site, sym, localEnv,
2255                             new ResultInfo(kind, mpt));
2256                 }
2257                 // Otherwise, `site' is an error type and we do nothing
2258             }
2259             result = tree.type = syms.voidType;
2260         } else {
2261             // Otherwise, we are seeing a regular method call.
2262             // Attribute the arguments, yielding list of argument types, ...
2263             KindSelector kind = attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
2264             argtypes = argtypesBuf.toList();
2265             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
2266 
2267             // ... and attribute the method using as a prototype a methodtype
2268             // whose formal argument types is exactly the list of actual
2269             // arguments (this will also set the method symbol).
2270             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
2271             localEnv.info.pendingResolutionPhase = null;
2272             Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
2273 
2274             // Compute the result type.
2275             Type restype = mtype.getReturnType();
2276             if (restype.hasTag(WILDCARD))
2277                 throw new AssertionError(mtype);
2278 
2279             Type qualifier = (tree.meth.hasTag(SELECT))
2280                     ? ((JCFieldAccess) tree.meth).selected.type
2281                     : env.enclClass.sym.type;
2282             Symbol msym = TreeInfo.symbol(tree.meth);
2283             restype = adjustMethodReturnType(msym, qualifier, methName, argtypes, restype);
2284 
2285             chk.checkRefTypes(tree.typeargs, typeargtypes);
2286 
2287             // Check that value of resulting type is admissible in the
2288             // current context.  Also, capture the return type
2289             Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true);
2290             result = check(tree, capturedRes, KindSelector.VAL, resultInfo);
2291         }
2292         chk.validate(tree.typeargs, localEnv);
2293     }
2294     //where
2295         Type adjustMethodReturnType(Symbol msym, Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
2296             if (msym != null &&
2297                     msym.owner == syms.objectType.tsym &&
2298                     methodName == names.getClass &&
2299                     argtypes.isEmpty()) {
2300                 // as a special case, x.getClass() has type Class<? extends |X|>
2301                 return new ClassType(restype.getEnclosingType(),
2302                         List.of(new WildcardType(types.erasure(qualifierType),
2303                                 BoundKind.EXTENDS,
2304                                 syms.boundClass)),
2305                         restype.tsym,
2306                         restype.getMetadata());
2307             } else if (msym != null &&
2308                     msym.owner == syms.arrayClass &&
2309                     methodName == names.clone &&
2310                     types.isArray(qualifierType)) {
2311                 // as a special case, array.clone() has a result that is
2312                 // the same as static type of the array being cloned
2313                 return qualifierType;
2314             } else {
2315                 return restype;
2316             }
2317         }
2318 
2319         /** Check that given application node appears as first statement
2320          *  in a constructor call.
2321          *  @param tree   The application node
2322          *  @param env    The environment current at the application.
2323          */
2324         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
2325             JCMethodDecl enclMethod = env.enclMethod;
2326             if (enclMethod != null && enclMethod.name == names.init) {
2327                 JCBlock body = enclMethod.body;
2328                 if (body.stats.head.hasTag(EXEC) &&
2329                     ((JCExpressionStatement) body.stats.head).expr == tree)
2330                     return true;
2331             }
2332             log.error(tree.pos(),
2333                       Errors.CallMustBeFirstStmtInCtor(TreeInfo.name(tree.meth)));
2334             return false;
2335         }
2336 
2337         /** Obtain a method type with given argument types.
2338          */
2339         Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
2340             MethodType mt = new MethodType(argtypes, restype, List.nil(), syms.methodClass);
2341             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
2342         }
2343 
2344     public void visitNewClass(final JCNewClass tree) {
2345         Type owntype = types.createErrorType(tree.type);
2346 
2347         // The local environment of a class creation is
2348         // a new environment nested in the current one.
2349         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
2350 
2351         // The anonymous inner class definition of the new expression,
2352         // if one is defined by it.
2353         JCClassDecl cdef = tree.def;
2354 
2355         // If enclosing class is given, attribute it, and
2356         // complete class name to be fully qualified
2357         JCExpression clazz = tree.clazz; // Class field following new
2358         JCExpression clazzid;            // Identifier in class field
2359         JCAnnotatedType annoclazzid;     // Annotated type enclosing clazzid
2360         annoclazzid = null;
2361 
2362         if (clazz.hasTag(TYPEAPPLY)) {
2363             clazzid = ((JCTypeApply) clazz).clazz;
2364             if (clazzid.hasTag(ANNOTATED_TYPE)) {
2365                 annoclazzid = (JCAnnotatedType) clazzid;
2366                 clazzid = annoclazzid.underlyingType;
2367             }
2368         } else {
2369             if (clazz.hasTag(ANNOTATED_TYPE)) {
2370                 annoclazzid = (JCAnnotatedType) clazz;
2371                 clazzid = annoclazzid.underlyingType;
2372             } else {
2373                 clazzid = clazz;
2374             }
2375         }
2376 
2377         JCExpression clazzid1 = clazzid; // The same in fully qualified form
2378 
2379         if (tree.encl != null) {
2380             // We are seeing a qualified new, of the form
2381             //    <expr>.new C <...> (...) ...
2382             // In this case, we let clazz stand for the name of the
2383             // allocated class C prefixed with the type of the qualifier
2384             // expression, so that we can
2385             // resolve it with standard techniques later. I.e., if
2386             // <expr> has type T, then <expr>.new C <...> (...)
2387             // yields a clazz T.C.
2388             Type encltype = chk.checkRefType(tree.encl.pos(),
2389                                              attribExpr(tree.encl, env));
2390             // TODO 308: in <expr>.new C, do we also want to add the type annotations
2391             // from expr to the combined type, or not? Yes, do this.
2392             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
2393                                                  ((JCIdent) clazzid).name);
2394 
2395             EndPosTable endPosTable = this.env.toplevel.endPositions;
2396             endPosTable.storeEnd(clazzid1, tree.getEndPosition(endPosTable));
2397             if (clazz.hasTag(ANNOTATED_TYPE)) {
2398                 JCAnnotatedType annoType = (JCAnnotatedType) clazz;
2399                 List<JCAnnotation> annos = annoType.annotations;
2400 
2401                 if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
2402                     clazzid1 = make.at(tree.pos).
2403                         TypeApply(clazzid1,
2404                                   ((JCTypeApply) clazz).arguments);
2405                 }
2406 
2407                 clazzid1 = make.at(tree.pos).
2408                     AnnotatedType(annos, clazzid1);
2409             } else if (clazz.hasTag(TYPEAPPLY)) {
2410                 clazzid1 = make.at(tree.pos).
2411                     TypeApply(clazzid1,
2412                               ((JCTypeApply) clazz).arguments);
2413             }
2414 
2415             clazz = clazzid1;
2416         }
2417 
2418         // Attribute clazz expression and store
2419         // symbol + type back into the attributed tree.
2420         Type clazztype;
2421 
2422         try {
2423             env.info.isNewClass = true;
2424             clazztype = TreeInfo.isEnumInit(env.tree) ?
2425                 attribIdentAsEnumType(env, (JCIdent)clazz) :
2426                 attribType(clazz, env);
2427         } finally {
2428             env.info.isNewClass = false;
2429         }
2430 
2431         clazztype = chk.checkDiamond(tree, clazztype);
2432         chk.validate(clazz, localEnv);
2433         if (tree.encl != null) {
2434             // We have to work in this case to store
2435             // symbol + type back into the attributed tree.
2436             tree.clazz.type = clazztype;
2437             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
2438             clazzid.type = ((JCIdent) clazzid).sym.type;
2439             if (annoclazzid != null) {
2440                 annoclazzid.type = clazzid.type;
2441             }
2442             if (!clazztype.isErroneous()) {
2443                 if (cdef != null && clazztype.tsym.isInterface()) {
2444                     log.error(tree.encl.pos(), Errors.AnonClassImplIntfNoQualForNew);
2445                 } else if (clazztype.tsym.isStatic()) {
2446                     log.error(tree.encl.pos(), Errors.QualifiedNewOfStaticClass(clazztype.tsym));
2447                 }
2448             }
2449         } else if (!clazztype.tsym.isInterface() &&
2450                    clazztype.getEnclosingType().hasTag(CLASS)) {
2451             // Check for the existence of an apropos outer instance
2452             rs.resolveImplicitThis(tree.pos(), env, clazztype);
2453         }
2454 
2455         // Attribute constructor arguments.
2456         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2457         final KindSelector pkind =
2458             attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
2459         List<Type> argtypes = argtypesBuf.toList();
2460         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
2461 
2462         if (clazztype.hasTag(CLASS) || clazztype.hasTag(ERROR)) {
2463             // Enums may not be instantiated except implicitly
2464             if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 &&
2465                 (!env.tree.hasTag(VARDEF) ||
2466                  (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 ||
2467                  ((JCVariableDecl) env.tree).init != tree))
2468                 log.error(tree.pos(), Errors.EnumCantBeInstantiated);
2469 
2470             boolean isSpeculativeDiamondInferenceRound = TreeInfo.isDiamond(tree) &&
2471                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2472             boolean skipNonDiamondPath = false;
2473             // Check that class is not abstract
2474             if (cdef == null && !isSpeculativeDiamondInferenceRound && // class body may be nulled out in speculative tree copy
2475                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
2476                 log.error(tree.pos(),
2477                           Errors.AbstractCantBeInstantiated(clazztype.tsym));
2478                 skipNonDiamondPath = true;
2479             } else if (cdef != null && clazztype.tsym.isInterface()) {
2480                 // Check that no constructor arguments are given to
2481                 // anonymous classes implementing an interface
2482                 if (!argtypes.isEmpty())
2483                     log.error(tree.args.head.pos(), Errors.AnonClassImplIntfNoArgs);
2484 
2485                 if (!typeargtypes.isEmpty())
2486                     log.error(tree.typeargs.head.pos(), Errors.AnonClassImplIntfNoTypeargs);
2487 
2488                 // Error recovery: pretend no arguments were supplied.
2489                 argtypes = List.nil();
2490                 typeargtypes = List.nil();
2491                 skipNonDiamondPath = true;
2492             }
2493             if (TreeInfo.isDiamond(tree)) {
2494                 ClassType site = new ClassType(clazztype.getEnclosingType(),
2495                             clazztype.tsym.type.getTypeArguments(),
2496                                                clazztype.tsym,
2497                                                clazztype.getMetadata());
2498 
2499                 Env<AttrContext> diamondEnv = localEnv.dup(tree);
2500                 diamondEnv.info.selectSuper = cdef != null || tree.classDeclRemoved();
2501                 diamondEnv.info.pendingResolutionPhase = null;
2502 
2503                 //if the type of the instance creation expression is a class type
2504                 //apply method resolution inference (JLS 15.12.2.7). The return type
2505                 //of the resolved constructor will be a partially instantiated type
2506                 Symbol constructor = rs.resolveDiamond(tree.pos(),
2507                             diamondEnv,
2508                             site,
2509                             argtypes,
2510                             typeargtypes);
2511                 tree.constructor = constructor.baseSymbol();
2512 
2513                 final TypeSymbol csym = clazztype.tsym;
2514                 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes),
2515                         diamondContext(tree, csym, resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
2516                 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
2517                 constructorType = checkId(tree, site,
2518                         constructor,
2519                         diamondEnv,
2520                         diamondResult);
2521 
2522                 tree.clazz.type = types.createErrorType(clazztype);
2523                 if (!constructorType.isErroneous()) {
2524                     tree.clazz.type = clazz.type = constructorType.getReturnType();
2525                     tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
2526                 }
2527                 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
2528             }
2529 
2530             // Resolve the called constructor under the assumption
2531             // that we are referring to a superclass instance of the
2532             // current instance (JLS ???).
2533             else if (!skipNonDiamondPath) {
2534                 //the following code alters some of the fields in the current
2535                 //AttrContext - hence, the current context must be dup'ed in
2536                 //order to avoid downstream failures
2537                 Env<AttrContext> rsEnv = localEnv.dup(tree);
2538                 rsEnv.info.selectSuper = cdef != null;
2539                 rsEnv.info.pendingResolutionPhase = null;
2540                 tree.constructor = rs.resolveConstructor(
2541                     tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
2542                 if (cdef == null) { //do not check twice!
2543                     tree.constructorType = checkId(tree,
2544                             clazztype,
2545                             tree.constructor,
2546                             rsEnv,
2547                             new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes), CheckMode.NO_TREE_UPDATE));
2548                     if (rsEnv.info.lastResolveVarargs())
2549                         Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
2550                 }
2551             }
2552 
2553             if (cdef != null) {
2554                 visitAnonymousClassDefinition(tree, clazz, clazztype, cdef, localEnv, argtypes, typeargtypes, pkind);
2555                 return;
2556             }
2557 
2558             if (tree.constructor != null && tree.constructor.kind == MTH)
2559                 owntype = clazztype;
2560         }
2561         result = check(tree, owntype, KindSelector.VAL, resultInfo);
2562         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
2563         if (tree.constructorType != null && inferenceContext.free(tree.constructorType)) {
2564             //we need to wait for inference to finish and then replace inference vars in the constructor type
2565             inferenceContext.addFreeTypeListener(List.of(tree.constructorType),
2566                     instantiatedContext -> {
2567                         tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
2568                     });
2569         }
2570         chk.validate(tree.typeargs, localEnv);
2571     }
2572 
2573         // where
2574         private void visitAnonymousClassDefinition(JCNewClass tree, JCExpression clazz, Type clazztype,
2575                                                    JCClassDecl cdef, Env<AttrContext> localEnv,
2576                                                    List<Type> argtypes, List<Type> typeargtypes,
2577                                                    KindSelector pkind) {
2578             // We are seeing an anonymous class instance creation.
2579             // In this case, the class instance creation
2580             // expression
2581             //
2582             //    E.new <typeargs1>C<typargs2>(args) { ... }
2583             //
2584             // is represented internally as
2585             //
2586             //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
2587             //
2588             // This expression is then *transformed* as follows:
2589             //
2590             // (1) add an extends or implements clause
2591             // (2) add a constructor.
2592             //
2593             // For instance, if C is a class, and ET is the type of E,
2594             // the expression
2595             //
2596             //    E.new <typeargs1>C<typargs2>(args) { ... }
2597             //
2598             // is translated to (where X is a fresh name and typarams is the
2599             // parameter list of the super constructor):
2600             //
2601             //   new <typeargs1>X(<*nullchk*>E, args) where
2602             //     X extends C<typargs2> {
2603             //       <typarams> X(ET e, args) {
2604             //         e.<typeargs1>super(args)
2605             //       }
2606             //       ...
2607             //     }
2608             InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
2609             final boolean isDiamond = TreeInfo.isDiamond(tree);
2610             if (isDiamond
2611                     && ((tree.constructorType != null && inferenceContext.free(tree.constructorType))
2612                     || (tree.clazz.type != null && inferenceContext.free(tree.clazz.type)))) {
2613                 final ResultInfo resultInfoForClassDefinition = this.resultInfo;
2614                 inferenceContext.addFreeTypeListener(List.of(tree.constructorType, tree.clazz.type),
2615                         instantiatedContext -> {
2616                             tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
2617                             tree.clazz.type = clazz.type = instantiatedContext.asInstType(clazz.type);
2618                             ResultInfo prevResult = this.resultInfo;
2619                             try {
2620                                 this.resultInfo = resultInfoForClassDefinition;
2621                                 visitAnonymousClassDefinition(tree, clazz, clazz.type, cdef,
2622                                                             localEnv, argtypes, typeargtypes, pkind);
2623                             } finally {
2624                                 this.resultInfo = prevResult;
2625                             }
2626                         });
2627             } else {
2628                 if (isDiamond && clazztype.hasTag(CLASS)) {
2629                     List<Type> invalidDiamondArgs = chk.checkDiamondDenotable((ClassType)clazztype);
2630                     if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
2631                         // One or more types inferred in the previous steps is non-denotable.
2632                         Fragment fragment = Diamond(clazztype.tsym);
2633                         log.error(tree.clazz.pos(),
2634                                 Errors.CantApplyDiamond1(
2635                                         fragment,
2636                                         invalidDiamondArgs.size() > 1 ?
2637                                                 DiamondInvalidArgs(invalidDiamondArgs, fragment) :
2638                                                 DiamondInvalidArg(invalidDiamondArgs, fragment)));
2639                     }
2640                     // For <>(){}, inferred types must also be accessible.
2641                     for (Type t : clazztype.getTypeArguments()) {
2642                         rs.checkAccessibleType(env, t);
2643                     }
2644                 }
2645 
2646                 // If we already errored, be careful to avoid a further avalanche. ErrorType answers
2647                 // false for isInterface call even when the original type is an interface.
2648                 boolean implementing = clazztype.tsym.isInterface() ||
2649                         clazztype.isErroneous() && !clazztype.getOriginalType().hasTag(NONE) &&
2650                         clazztype.getOriginalType().tsym.isInterface();
2651 
2652                 if (implementing) {
2653                     cdef.implementing = List.of(clazz);
2654                 } else {
2655                     cdef.extending = clazz;
2656                 }
2657 
2658                 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2659                     isSerializable(clazztype)) {
2660                     localEnv.info.isSerializable = true;
2661                 }
2662 
2663                 attribStat(cdef, localEnv);
2664 
2665                 List<Type> finalargtypes;
2666                 // If an outer instance is given,
2667                 // prefix it to the constructor arguments
2668                 // and delete it from the new expression
2669                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
2670                     finalargtypes = argtypes.prepend(tree.encl.type);
2671                 } else {
2672                     finalargtypes = argtypes;
2673                 }
2674 
2675                 // Reassign clazztype and recompute constructor. As this necessarily involves
2676                 // another attribution pass for deferred types in the case of <>, replicate
2677                 // them. Original arguments have right decorations already.
2678                 if (isDiamond && pkind.contains(KindSelector.POLY)) {
2679                     finalargtypes = finalargtypes.map(deferredAttr.deferredCopier);
2680                 }
2681 
2682                 clazztype = clazztype.hasTag(ERROR) ? types.createErrorType(cdef.sym.type)
2683                                                     : cdef.sym.type;
2684                 Symbol sym = tree.constructor = rs.resolveConstructor(
2685                         tree.pos(), localEnv, clazztype, finalargtypes, typeargtypes);
2686                 Assert.check(!sym.kind.isResolutionError());
2687                 tree.constructor = sym;
2688                 tree.constructorType = checkId(tree,
2689                         clazztype,
2690                         tree.constructor,
2691                         localEnv,
2692                         new ResultInfo(pkind, newMethodTemplate(syms.voidType, finalargtypes, typeargtypes), CheckMode.NO_TREE_UPDATE));
2693             }
2694             Type owntype = (tree.constructor != null && tree.constructor.kind == MTH) ?
2695                                 clazztype : types.createErrorType(tree.type);
2696             result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK));
2697             chk.validate(tree.typeargs, localEnv);
2698         }
2699 
2700         CheckContext diamondContext(JCNewClass clazz, TypeSymbol tsym, CheckContext checkContext) {
2701             return new Check.NestedCheckContext(checkContext) {
2702                 @Override
2703                 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
2704                     enclosingContext.report(clazz.clazz,
2705                             diags.fragment(Fragments.CantApplyDiamond1(Fragments.Diamond(tsym), details)));
2706                 }
2707             };
2708         }
2709 
2710     /** Make an attributed null check tree.
2711      */
2712     public JCExpression makeNullCheck(JCExpression arg) {
2713         // optimization: new Outer() can never be null; skip null check
2714         if (arg.getTag() == NEWCLASS)
2715             return arg;
2716         // optimization: X.this is never null; skip null check
2717         Name name = TreeInfo.name(arg);
2718         if (name == names._this || name == names._super) return arg;
2719 
2720         JCTree.Tag optag = NULLCHK;
2721         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
2722         tree.operator = operators.resolveUnary(arg, optag, arg.type);
2723         tree.type = arg.type;
2724         return tree;
2725     }
2726 
2727     public void visitNewArray(JCNewArray tree) {
2728         Type owntype = types.createErrorType(tree.type);
2729         Env<AttrContext> localEnv = env.dup(tree);
2730         Type elemtype;
2731         if (tree.elemtype != null) {
2732             elemtype = attribType(tree.elemtype, localEnv);
2733             chk.validate(tree.elemtype, localEnv);
2734             owntype = elemtype;
2735             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
2736                 attribExpr(l.head, localEnv, syms.intType);
2737                 owntype = new ArrayType(owntype, syms.arrayClass);
2738             }
2739         } else {
2740             // we are seeing an untyped aggregate { ... }
2741             // this is allowed only if the prototype is an array
2742             if (pt().hasTag(ARRAY)) {
2743                 elemtype = types.elemtype(pt());
2744             } else {
2745                 if (!pt().hasTag(ERROR) &&
2746                         (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
2747                     log.error(tree.pos(),
2748                               Errors.IllegalInitializerForType(pt()));
2749                 }
2750                 elemtype = types.createErrorType(pt());
2751             }
2752         }
2753         if (tree.elems != null) {
2754             attribExprs(tree.elems, localEnv, elemtype);
2755             owntype = new ArrayType(elemtype, syms.arrayClass);
2756         }
2757         if (!types.isReifiable(elemtype))
2758             log.error(tree.pos(), Errors.GenericArrayCreation);
2759         result = check(tree, owntype, KindSelector.VAL, resultInfo);
2760     }
2761 
2762     /*
2763      * A lambda expression can only be attributed when a target-type is available.
2764      * In addition, if the target-type is that of a functional interface whose
2765      * descriptor contains inference variables in argument position the lambda expression
2766      * is 'stuck' (see DeferredAttr).
2767      */
2768     @Override
2769     public void visitLambda(final JCLambda that) {
2770         boolean wrongContext = false;
2771         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2772             if (pt().hasTag(NONE) && (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
2773                 //lambda only allowed in assignment or method invocation/cast context
2774                 log.error(that.pos(), Errors.UnexpectedLambda);
2775             }
2776             resultInfo = recoveryInfo;
2777             wrongContext = true;
2778         }
2779         //create an environment for attribution of the lambda expression
2780         final Env<AttrContext> localEnv = lambdaEnv(that, env);
2781         boolean needsRecovery =
2782                 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
2783         try {
2784             if (needsRecovery && isSerializable(pt())) {
2785                 localEnv.info.isSerializable = true;
2786                 localEnv.info.isLambda = true;
2787             }
2788             List<Type> explicitParamTypes = null;
2789             if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
2790                 //attribute lambda parameters
2791                 attribStats(that.params, localEnv);
2792                 explicitParamTypes = TreeInfo.types(that.params);
2793             }
2794 
2795             TargetInfo targetInfo = getTargetInfo(that, resultInfo, explicitParamTypes);
2796             Type currentTarget = targetInfo.target;
2797             Type lambdaType = targetInfo.descriptor;
2798 
2799             if (currentTarget.tsym != null && ((ClassSymbol)currentTarget.tsym).isSealed()) {
2800                 log.error(that, Errors.CantInheritFromSealed(currentTarget.tsym));
2801             }
2802 
2803             if (currentTarget.isErroneous()) {
2804                 result = that.type = currentTarget;
2805                 return;
2806             }
2807 
2808             setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext);
2809 
2810             if (lambdaType.hasTag(FORALL)) {
2811                 //lambda expression target desc cannot be a generic method
2812                 Fragment msg = Fragments.InvalidGenericLambdaTarget(lambdaType,
2813                                                                     kindName(currentTarget.tsym),
2814                                                                     currentTarget.tsym);
2815                 resultInfo.checkContext.report(that, diags.fragment(msg));
2816                 result = that.type = types.createErrorType(pt());
2817                 return;
2818             }
2819 
2820             if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
2821                 //add param type info in the AST
2822                 List<Type> actuals = lambdaType.getParameterTypes();
2823                 List<JCVariableDecl> params = that.params;
2824 
2825                 boolean arityMismatch = false;
2826 
2827                 while (params.nonEmpty()) {
2828                     if (actuals.isEmpty()) {
2829                         //not enough actuals to perform lambda parameter inference
2830                         arityMismatch = true;
2831                     }
2832                     //reset previously set info
2833                     Type argType = arityMismatch ?
2834                             syms.errType :
2835                             actuals.head;
2836                     if (params.head.isImplicitlyTyped()) {
2837                         setSyntheticVariableType(params.head, argType);
2838                     }
2839                     params.head.sym = null;
2840                     actuals = actuals.isEmpty() ?
2841                             actuals :
2842                             actuals.tail;
2843                     params = params.tail;
2844                 }
2845 
2846                 //attribute lambda parameters
2847                 attribStats(that.params, localEnv);
2848 
2849                 if (arityMismatch) {
2850                     resultInfo.checkContext.report(that, diags.fragment(Fragments.IncompatibleArgTypesInLambda));
2851                         result = that.type = types.createErrorType(currentTarget);
2852                         return;
2853                 }
2854             }
2855 
2856             //from this point on, no recovery is needed; if we are in assignment context
2857             //we will be able to attribute the whole lambda body, regardless of errors;
2858             //if we are in a 'check' method context, and the lambda is not compatible
2859             //with the target-type, it will be recovered anyway in Attr.checkId
2860             needsRecovery = false;
2861 
2862             ResultInfo bodyResultInfo = localEnv.info.returnResult =
2863                     lambdaBodyResult(that, lambdaType, resultInfo);
2864 
2865             if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
2866                 attribTree(that.getBody(), localEnv, bodyResultInfo);
2867             } else {
2868                 JCBlock body = (JCBlock)that.body;
2869                 if (body == breakTree &&
2870                         resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
2871                     breakTreeFound(copyEnv(localEnv));
2872                 }
2873                 attribStats(body.stats, localEnv);
2874             }
2875 
2876             result = check(that, currentTarget, KindSelector.VAL, resultInfo);
2877 
2878             boolean isSpeculativeRound =
2879                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2880 
2881             preFlow(that);
2882             flow.analyzeLambda(env, that, make, isSpeculativeRound);
2883 
2884             that.type = currentTarget; //avoids recovery at this stage
2885             checkLambdaCompatible(that, lambdaType, resultInfo.checkContext);
2886 
2887             if (!isSpeculativeRound) {
2888                 //add thrown types as bounds to the thrown types free variables if needed:
2889                 if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) {
2890                     List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make);
2891                     if(!checkExConstraints(inferredThrownTypes, lambdaType.getThrownTypes(), resultInfo.checkContext.inferenceContext())) {
2892                         log.error(that, Errors.IncompatibleThrownTypesInMref(lambdaType.getThrownTypes()));
2893                     }
2894                 }
2895 
2896                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget);
2897             }
2898             result = wrongContext ? that.type = types.createErrorType(pt())
2899                                   : check(that, currentTarget, KindSelector.VAL, resultInfo);
2900         } catch (Types.FunctionDescriptorLookupError ex) {
2901             JCDiagnostic cause = ex.getDiagnostic();
2902             resultInfo.checkContext.report(that, cause);
2903             result = that.type = types.createErrorType(pt());
2904             return;
2905         } catch (Throwable t) {
2906             //when an unexpected exception happens, avoid attempts to attribute the same tree again
2907             //as that would likely cause the same exception again.
2908             needsRecovery = false;
2909             throw t;
2910         } finally {
2911             localEnv.info.scope.leave();
2912             if (needsRecovery) {
2913                 attribTree(that, env, recoveryInfo);
2914             }
2915         }
2916     }
2917     //where
2918         class TargetInfo {
2919             Type target;
2920             Type descriptor;
2921 
2922             public TargetInfo(Type target, Type descriptor) {
2923                 this.target = target;
2924                 this.descriptor = descriptor;
2925             }
2926         }
2927 
2928         TargetInfo getTargetInfo(JCPolyExpression that, ResultInfo resultInfo, List<Type> explicitParamTypes) {
2929             Type lambdaType;
2930             Type currentTarget = resultInfo.pt;
2931             if (resultInfo.pt != Type.recoveryType) {
2932                 /* We need to adjust the target. If the target is an
2933                  * intersection type, for example: SAM & I1 & I2 ...
2934                  * the target will be updated to SAM
2935                  */
2936                 currentTarget = targetChecker.visit(currentTarget, that);
2937                 if (!currentTarget.isIntersection()) {
2938                     if (explicitParamTypes != null) {
2939                         currentTarget = infer.instantiateFunctionalInterface(that,
2940                                 currentTarget, explicitParamTypes, resultInfo.checkContext);
2941                     }
2942                     currentTarget = types.removeWildcards(currentTarget);
2943                     lambdaType = types.findDescriptorType(currentTarget);
2944                 } else {
2945                     IntersectionClassType ict = (IntersectionClassType)currentTarget;
2946                     ListBuffer<Type> components = new ListBuffer<>();
2947                     for (Type bound : ict.getExplicitComponents()) {
2948                         if (explicitParamTypes != null) {
2949                             try {
2950                                 bound = infer.instantiateFunctionalInterface(that,
2951                                         bound, explicitParamTypes, resultInfo.checkContext);
2952                             } catch (FunctionDescriptorLookupError t) {
2953                                 // do nothing
2954                             }
2955                         }
2956                         bound = types.removeWildcards(bound);
2957                         components.add(bound);
2958                     }
2959                     currentTarget = types.makeIntersectionType(components.toList());
2960                     currentTarget.tsym.flags_field |= INTERFACE;
2961                     lambdaType = types.findDescriptorType(currentTarget);
2962                 }
2963 
2964             } else {
2965                 currentTarget = Type.recoveryType;
2966                 lambdaType = fallbackDescriptorType(that);
2967             }
2968             if (that.hasTag(LAMBDA) && lambdaType.hasTag(FORALL)) {
2969                 //lambda expression target desc cannot be a generic method
2970                 Fragment msg = Fragments.InvalidGenericLambdaTarget(lambdaType,
2971                                                                     kindName(currentTarget.tsym),
2972                                                                     currentTarget.tsym);
2973                 resultInfo.checkContext.report(that, diags.fragment(msg));
2974                 currentTarget = types.createErrorType(pt());
2975             }
2976             return new TargetInfo(currentTarget, lambdaType);
2977         }
2978 
2979         void preFlow(JCLambda tree) {
2980             new PostAttrAnalyzer() {
2981                 @Override
2982                 public void scan(JCTree tree) {
2983                     if (tree == null ||
2984                             (tree.type != null &&
2985                             tree.type == Type.stuckType)) {
2986                         //don't touch stuck expressions!
2987                         return;
2988                     }
2989                     super.scan(tree);
2990                 }
2991 
2992                 @Override
2993                 public void visitClassDef(JCClassDecl that) {
2994                     // or class declaration trees!
2995                 }
2996 
2997                 public void visitLambda(JCLambda that) {
2998                     // or lambda expressions!
2999                 }
3000             }.scan(tree.body);
3001         }
3002 
3003         Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
3004 
3005             @Override
3006             public Type visitClassType(ClassType t, DiagnosticPosition pos) {
3007                 return t.isIntersection() ?
3008                         visitIntersectionClassType((IntersectionClassType)t, pos) : t;
3009             }
3010 
3011             public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
3012                 types.findDescriptorSymbol(makeNotionalInterface(ict, pos));
3013                 return ict;
3014             }
3015 
3016             private TypeSymbol makeNotionalInterface(IntersectionClassType ict, DiagnosticPosition pos) {
3017                 ListBuffer<Type> targs = new ListBuffer<>();
3018                 ListBuffer<Type> supertypes = new ListBuffer<>();
3019                 for (Type i : ict.interfaces_field) {
3020                     if (i.isParameterized()) {
3021                         targs.appendList(i.tsym.type.allparams());
3022                     }
3023                     supertypes.append(i.tsym.type);
3024                 }
3025                 IntersectionClassType notionalIntf = types.makeIntersectionType(supertypes.toList());
3026                 notionalIntf.allparams_field = targs.toList();
3027                 notionalIntf.tsym.flags_field |= INTERFACE;
3028                 return notionalIntf.tsym;
3029             }
3030         };
3031 
3032         private Type fallbackDescriptorType(JCExpression tree) {
3033             switch (tree.getTag()) {
3034                 case LAMBDA:
3035                     JCLambda lambda = (JCLambda)tree;
3036                     List<Type> argtypes = List.nil();
3037                     for (JCVariableDecl param : lambda.params) {
3038                         argtypes = param.vartype != null && param.vartype.type != null ?
3039                                 argtypes.append(param.vartype.type) :
3040                                 argtypes.append(syms.errType);
3041                     }
3042                     return new MethodType(argtypes, Type.recoveryType,
3043                             List.of(syms.throwableType), syms.methodClass);
3044                 case REFERENCE:
3045                     return new MethodType(List.nil(), Type.recoveryType,
3046                             List.of(syms.throwableType), syms.methodClass);
3047                 default:
3048                     Assert.error("Cannot get here!");
3049             }
3050             return null;
3051         }
3052 
3053         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
3054                 final InferenceContext inferenceContext, final Type... ts) {
3055             checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
3056         }
3057 
3058         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
3059                 final InferenceContext inferenceContext, final List<Type> ts) {
3060             if (inferenceContext.free(ts)) {
3061                 inferenceContext.addFreeTypeListener(ts,
3062                         solvedContext -> checkAccessibleTypes(pos, env, solvedContext, solvedContext.asInstTypes(ts)));
3063             } else {
3064                 for (Type t : ts) {
3065                     rs.checkAccessibleType(env, t);
3066                 }
3067             }
3068         }
3069 
3070         /**
3071          * Lambda/method reference have a special check context that ensures
3072          * that i.e. a lambda return type is compatible with the expected
3073          * type according to both the inherited context and the assignment
3074          * context.
3075          */
3076         class FunctionalReturnContext extends Check.NestedCheckContext {
3077 
3078             FunctionalReturnContext(CheckContext enclosingContext) {
3079                 super(enclosingContext);
3080             }
3081 
3082             @Override
3083             public boolean compatible(Type found, Type req, Warner warn) {
3084                 //return type must be compatible in both current context and assignment context
3085                 return chk.basicHandler.compatible(inferenceContext().asUndetVar(found), inferenceContext().asUndetVar(req), warn);
3086             }
3087 
3088             @Override
3089             public void report(DiagnosticPosition pos, JCDiagnostic details) {
3090                 enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleRetTypeInLambda(details)));
3091             }
3092         }
3093 
3094         class ExpressionLambdaReturnContext extends FunctionalReturnContext {
3095 
3096             JCExpression expr;
3097             boolean expStmtExpected;
3098 
3099             ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
3100                 super(enclosingContext);
3101                 this.expr = expr;
3102             }
3103 
3104             @Override
3105             public void report(DiagnosticPosition pos, JCDiagnostic details) {
3106                 if (expStmtExpected) {
3107                     enclosingContext.report(pos, diags.fragment(Fragments.StatExprExpected));
3108                 } else {
3109                     super.report(pos, details);
3110                 }
3111             }
3112 
3113             @Override
3114             public boolean compatible(Type found, Type req, Warner warn) {
3115                 //a void return is compatible with an expression statement lambda
3116                 if (req.hasTag(VOID)) {
3117                     expStmtExpected = true;
3118                     return TreeInfo.isExpressionStatement(expr);
3119                 } else {
3120                     return super.compatible(found, req, warn);
3121                 }
3122             }
3123         }
3124 
3125         ResultInfo lambdaBodyResult(JCLambda that, Type descriptor, ResultInfo resultInfo) {
3126             FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
3127                     new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
3128                     new FunctionalReturnContext(resultInfo.checkContext);
3129 
3130             return descriptor.getReturnType() == Type.recoveryType ?
3131                     recoveryInfo :
3132                     new ResultInfo(KindSelector.VAL,
3133                             descriptor.getReturnType(), funcContext);
3134         }
3135 
3136         /**
3137         * Lambda compatibility. Check that given return types, thrown types, parameter types
3138         * are compatible with the expected functional interface descriptor. This means that:
3139         * (i) parameter types must be identical to those of the target descriptor; (ii) return
3140         * types must be compatible with the return type of the expected descriptor.
3141         */
3142         void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) {
3143             Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
3144 
3145             //return values have already been checked - but if lambda has no return
3146             //values, we must ensure that void/value compatibility is correct;
3147             //this amounts at checking that, if a lambda body can complete normally,
3148             //the descriptor's return type must be void
3149             if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
3150                     !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
3151                 Fragment msg =
3152                         Fragments.IncompatibleRetTypeInLambda(Fragments.MissingRetVal(returnType));
3153                 checkContext.report(tree,
3154                                     diags.fragment(msg));
3155             }
3156 
3157             List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes());
3158             if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
3159                 checkContext.report(tree, diags.fragment(Fragments.IncompatibleArgTypesInLambda));
3160             }
3161         }
3162 
3163         /* Map to hold 'fake' clinit methods. If a lambda is used to initialize a
3164          * static field and that lambda has type annotations, these annotations will
3165          * also be stored at these fake clinit methods.
3166          *
3167          * LambdaToMethod also use fake clinit methods so they can be reused.
3168          * Also as LTM is a phase subsequent to attribution, the methods from
3169          * clinits can be safely removed by LTM to save memory.
3170          */
3171         private Map<ClassSymbol, MethodSymbol> clinits = new HashMap<>();
3172 
3173         public MethodSymbol removeClinit(ClassSymbol sym) {
3174             return clinits.remove(sym);
3175         }
3176 
3177         /* This method returns an environment to be used to attribute a lambda
3178          * expression.
3179          *
3180          * The owner of this environment is a method symbol. If the current owner
3181          * is not a method, for example if the lambda is used to initialize
3182          * a field, then if the field is:
3183          *
3184          * - an instance field, we use the first constructor.
3185          * - a static field, we create a fake clinit method.
3186          */
3187         public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
3188             Env<AttrContext> lambdaEnv;
3189             Symbol owner = env.info.scope.owner;
3190             if (owner.kind == VAR && owner.owner.kind == TYP) {
3191                 //field initializer
3192                 ClassSymbol enclClass = owner.enclClass();
3193                 Symbol newScopeOwner = env.info.scope.owner;
3194                 /* if the field isn't static, then we can get the first constructor
3195                  * and use it as the owner of the environment. This is what
3196                  * LTM code is doing to look for type annotations so we are fine.
3197                  */
3198                 if ((owner.flags() & STATIC) == 0) {
3199                     for (Symbol s : enclClass.members_field.getSymbolsByName(names.init)) {
3200                         newScopeOwner = s;
3201                         break;
3202                     }
3203                 } else {
3204                     /* if the field is static then we need to create a fake clinit
3205                      * method, this method can later be reused by LTM.
3206                      */
3207                     MethodSymbol clinit = clinits.get(enclClass);
3208                     if (clinit == null) {
3209                         Type clinitType = new MethodType(List.nil(),
3210                                 syms.voidType, List.nil(), syms.methodClass);
3211                         clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE,
3212                                 names.clinit, clinitType, enclClass);
3213                         clinit.params = List.nil();
3214                         clinits.put(enclClass, clinit);
3215                     }
3216                     newScopeOwner = clinit;
3217                 }
3218                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(newScopeOwner)));
3219             } else {
3220                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
3221             }
3222             lambdaEnv.info.yieldResult = null;
3223             return lambdaEnv;
3224         }
3225 
3226     @Override
3227     public void visitReference(final JCMemberReference that) {
3228         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
3229             if (pt().hasTag(NONE) && (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
3230                 //method reference only allowed in assignment or method invocation/cast context
3231                 log.error(that.pos(), Errors.UnexpectedMref);
3232             }
3233             result = that.type = types.createErrorType(pt());
3234             return;
3235         }
3236         final Env<AttrContext> localEnv = env.dup(that);
3237         try {
3238             //attribute member reference qualifier - if this is a constructor
3239             //reference, the expected kind must be a type
3240             Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
3241 
3242             if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3243                 exprType = chk.checkConstructorRefType(that.expr, exprType);
3244                 if (!exprType.isErroneous() &&
3245                     exprType.isRaw() &&
3246                     that.typeargs != null) {
3247                     log.error(that.expr.pos(),
3248                               Errors.InvalidMref(Kinds.kindName(that.getMode()),
3249                                                  Fragments.MrefInferAndExplicitParams));
3250                     exprType = types.createErrorType(exprType);
3251                 }
3252             }
3253 
3254             if (exprType.isErroneous()) {
3255                 //if the qualifier expression contains problems,
3256                 //give up attribution of method reference
3257                 result = that.type = exprType;
3258                 return;
3259             }
3260 
3261             if (TreeInfo.isStaticSelector(that.expr, names)) {
3262                 //if the qualifier is a type, validate it; raw warning check is
3263                 //omitted as we don't know at this stage as to whether this is a
3264                 //raw selector (because of inference)
3265                 chk.validate(that.expr, env, false);
3266             } else {
3267                 Symbol lhsSym = TreeInfo.symbol(that.expr);
3268                 localEnv.info.selectSuper = lhsSym != null && lhsSym.name == names._super;
3269             }
3270             //attrib type-arguments
3271             List<Type> typeargtypes = List.nil();
3272             if (that.typeargs != null) {
3273                 typeargtypes = attribTypes(that.typeargs, localEnv);
3274             }
3275 
3276             boolean isTargetSerializable =
3277                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3278                     isSerializable(pt());
3279             TargetInfo targetInfo = getTargetInfo(that, resultInfo, null);
3280             Type currentTarget = targetInfo.target;
3281             Type desc = targetInfo.descriptor;
3282 
3283             setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
3284             List<Type> argtypes = desc.getParameterTypes();
3285             Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
3286 
3287             if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
3288                 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
3289             }
3290 
3291             Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
3292             List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
3293             try {
3294                 refResult = rs.resolveMemberReference(localEnv, that, that.expr.type,
3295                         that.name, argtypes, typeargtypes, targetInfo.descriptor, referenceCheck,
3296                         resultInfo.checkContext.inferenceContext(), rs.basicReferenceChooser);
3297             } finally {
3298                 resultInfo.checkContext.inferenceContext().rollback(saved_undet);
3299             }
3300 
3301             Symbol refSym = refResult.fst;
3302             Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
3303 
3304             /** this switch will need to go away and be replaced by the new RESOLUTION_TARGET testing
3305              *  JDK-8075541
3306              */
3307             if (refSym.kind != MTH) {
3308                 boolean targetError;
3309                 switch (refSym.kind) {
3310                     case ABSENT_MTH:
3311                     case MISSING_ENCL:
3312                         targetError = false;
3313                         break;
3314                     case WRONG_MTH:
3315                     case WRONG_MTHS:
3316                     case AMBIGUOUS:
3317                     case HIDDEN:
3318                     case STATICERR:
3319                         targetError = true;
3320                         break;
3321                     default:
3322                         Assert.error("unexpected result kind " + refSym.kind);
3323                         targetError = false;
3324                 }
3325 
3326                 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol())
3327                         .getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
3328                                 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
3329 
3330                 JCDiagnostic diag = diags.create(log.currentSource(), that,
3331                         targetError ?
3332                             Fragments.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag) :
3333                             Errors.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag));
3334 
3335                 if (targetError && currentTarget == Type.recoveryType) {
3336                     //a target error doesn't make sense during recovery stage
3337                     //as we don't know what actual parameter types are
3338                     result = that.type = currentTarget;
3339                     return;
3340                 } else {
3341                     if (targetError) {
3342                         resultInfo.checkContext.report(that, diag);
3343                     } else {
3344                         log.report(diag);
3345                     }
3346                     result = that.type = types.createErrorType(currentTarget);
3347                     return;
3348                 }
3349             }
3350 
3351             that.sym = refSym.isConstructor() ? refSym.baseSymbol() : refSym;
3352             that.kind = lookupHelper.referenceKind(that.sym);
3353             that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
3354 
3355             if (desc.getReturnType() == Type.recoveryType) {
3356                 // stop here
3357                 result = that.type = currentTarget;
3358                 return;
3359             }
3360 
3361             if (!env.info.isSpeculative && that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3362                 Type enclosingType = exprType.getEnclosingType();
3363                 if (enclosingType != null && enclosingType.hasTag(CLASS)) {
3364                     // Check for the existence of an apropriate outer instance
3365                     rs.resolveImplicitThis(that.pos(), env, exprType);
3366                 }
3367             }
3368 
3369             if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
3370 
3371                 if (that.getMode() == ReferenceMode.INVOKE &&
3372                         TreeInfo.isStaticSelector(that.expr, names) &&
3373                         that.kind.isUnbound() &&
3374                         lookupHelper.site.isRaw()) {
3375                     chk.checkRaw(that.expr, localEnv);
3376                 }
3377 
3378                 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
3379                         exprType.getTypeArguments().nonEmpty()) {
3380                     //static ref with class type-args
3381                     log.error(that.expr.pos(),
3382                               Errors.InvalidMref(Kinds.kindName(that.getMode()),
3383                                                  Fragments.StaticMrefWithTargs));
3384                     result = that.type = types.createErrorType(currentTarget);
3385                     return;
3386                 }
3387 
3388                 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
3389                     // Check that super-qualified symbols are not abstract (JLS)
3390                     rs.checkNonAbstract(that.pos(), that.sym);
3391                 }
3392 
3393                 if (isTargetSerializable) {
3394                     chk.checkAccessFromSerializableElement(that, true);
3395                 }
3396             }
3397 
3398             ResultInfo checkInfo =
3399                     resultInfo.dup(newMethodTemplate(
3400                         desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
3401                         that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes),
3402                         new FunctionalReturnContext(resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
3403 
3404             Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
3405 
3406             if (that.kind.isUnbound() &&
3407                     resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
3408                 //re-generate inference constraints for unbound receiver
3409                 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) {
3410                     //cannot happen as this has already been checked - we just need
3411                     //to regenerate the inference constraints, as that has been lost
3412                     //as a result of the call to inferenceContext.save()
3413                     Assert.error("Can't get here");
3414                 }
3415             }
3416 
3417             if (!refType.isErroneous()) {
3418                 refType = types.createMethodTypeWithReturn(refType,
3419                         adjustMethodReturnType(refSym, lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
3420             }
3421 
3422             //go ahead with standard method reference compatibility check - note that param check
3423             //is a no-op (as this has been taken care during method applicability)
3424             boolean isSpeculativeRound =
3425                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
3426 
3427             that.type = currentTarget; //avoids recovery at this stage
3428             checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
3429             if (!isSpeculativeRound) {
3430                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget);
3431             }
3432             result = check(that, currentTarget, KindSelector.VAL, resultInfo);
3433         } catch (Types.FunctionDescriptorLookupError ex) {
3434             JCDiagnostic cause = ex.getDiagnostic();
3435             resultInfo.checkContext.report(that, cause);
3436             result = that.type = types.createErrorType(pt());
3437             return;
3438         }
3439     }
3440     //where
3441         ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
3442             //if this is a constructor reference, the expected kind must be a type
3443             return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ?
3444                                   KindSelector.VAL_TYP : KindSelector.TYP,
3445                                   Type.noType);
3446         }
3447 
3448 
3449     @SuppressWarnings("fallthrough")
3450     void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
3451         InferenceContext inferenceContext = checkContext.inferenceContext();
3452         Type returnType = inferenceContext.asUndetVar(descriptor.getReturnType());
3453 
3454         Type resType;
3455         switch (tree.getMode()) {
3456             case NEW:
3457                 if (!tree.expr.type.isRaw()) {
3458                     resType = tree.expr.type;
3459                     break;
3460                 }
3461             default:
3462                 resType = refType.getReturnType();
3463         }
3464 
3465         Type incompatibleReturnType = resType;
3466 
3467         if (returnType.hasTag(VOID)) {
3468             incompatibleReturnType = null;
3469         }
3470 
3471         if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
3472             if (resType.isErroneous() ||
3473                     new FunctionalReturnContext(checkContext).compatible(resType, returnType,
3474                             checkContext.checkWarner(tree, resType, returnType))) {
3475                 incompatibleReturnType = null;
3476             }
3477         }
3478 
3479         if (incompatibleReturnType != null) {
3480             Fragment msg =
3481                     Fragments.IncompatibleRetTypeInMref(Fragments.InconvertibleTypes(resType, descriptor.getReturnType()));
3482             checkContext.report(tree, diags.fragment(msg));
3483         } else {
3484             if (inferenceContext.free(refType)) {
3485                 // we need to wait for inference to finish and then replace inference vars in the referent type
3486                 inferenceContext.addFreeTypeListener(List.of(refType),
3487                         instantiatedContext -> {
3488                             tree.referentType = instantiatedContext.asInstType(refType);
3489                         });
3490             } else {
3491                 tree.referentType = refType;
3492             }
3493         }
3494 
3495         if (!speculativeAttr) {
3496             if (!checkExConstraints(refType.getThrownTypes(), descriptor.getThrownTypes(), inferenceContext)) {
3497                 log.error(tree, Errors.IncompatibleThrownTypesInMref(refType.getThrownTypes()));
3498             }
3499         }
3500     }
3501 
3502     boolean checkExConstraints(
3503             List<Type> thrownByFuncExpr,
3504             List<Type> thrownAtFuncType,
3505             InferenceContext inferenceContext) {
3506         /** 18.2.5: Otherwise, let E1, ..., En be the types in the function type's throws clause that
3507          *  are not proper types
3508          */
3509         List<Type> nonProperList = thrownAtFuncType.stream()
3510                 .filter(e -> inferenceContext.free(e)).collect(List.collector());
3511         List<Type> properList = thrownAtFuncType.diff(nonProperList);
3512 
3513         /** Let X1,...,Xm be the checked exception types that the lambda body can throw or
3514          *  in the throws clause of the invocation type of the method reference's compile-time
3515          *  declaration
3516          */
3517         List<Type> checkedList = thrownByFuncExpr.stream()
3518                 .filter(e -> chk.isChecked(e)).collect(List.collector());
3519 
3520         /** If n = 0 (the function type's throws clause consists only of proper types), then
3521          *  if there exists some i (1 <= i <= m) such that Xi is not a subtype of any proper type
3522          *  in the throws clause, the constraint reduces to false; otherwise, the constraint
3523          *  reduces to true
3524          */
3525         ListBuffer<Type> uncaughtByProperTypes = new ListBuffer<>();
3526         for (Type checked : checkedList) {
3527             boolean isSubtype = false;
3528             for (Type proper : properList) {
3529                 if (types.isSubtype(checked, proper)) {
3530                     isSubtype = true;
3531                     break;
3532                 }
3533             }
3534             if (!isSubtype) {
3535                 uncaughtByProperTypes.add(checked);
3536             }
3537         }
3538 
3539         if (nonProperList.isEmpty() && !uncaughtByProperTypes.isEmpty()) {
3540             return false;
3541         }
3542 
3543         /** If n > 0, the constraint reduces to a set of subtyping constraints:
3544          *  for all i (1 <= i <= m), if Xi is not a subtype of any proper type in the
3545          *  throws clause, then the constraints include, for all j (1 <= j <= n), <Xi <: Ej>
3546          */
3547         List<Type> nonProperAsUndet = inferenceContext.asUndetVars(nonProperList);
3548         uncaughtByProperTypes.forEach(checkedEx -> {
3549             nonProperAsUndet.forEach(nonProper -> {
3550                 types.isSubtype(checkedEx, nonProper);
3551             });
3552         });
3553 
3554         /** In addition, for all j (1 <= j <= n), the constraint reduces to the bound throws Ej
3555          */
3556         nonProperAsUndet.stream()
3557                 .filter(t -> t.hasTag(UNDETVAR))
3558                 .forEach(t -> ((UndetVar)t).setThrow());
3559         return true;
3560     }
3561 
3562     /**
3563      * Set functional type info on the underlying AST. Note: as the target descriptor
3564      * might contain inference variables, we might need to register an hook in the
3565      * current inference context.
3566      */
3567     private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
3568             final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
3569         if (checkContext.inferenceContext().free(descriptorType)) {
3570             checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType),
3571                     inferenceContext -> setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
3572                     inferenceContext.asInstType(primaryTarget), checkContext));
3573         } else {
3574             if (pt.hasTag(CLASS)) {
3575                 fExpr.target = primaryTarget;
3576             }
3577             if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3578                     pt != Type.recoveryType) {
3579                 //check that functional interface class is well-formed
3580                 try {
3581                     /* Types.makeFunctionalInterfaceClass() may throw an exception
3582                      * when it's executed post-inference. See the listener code
3583                      * above.
3584                      */
3585                     ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
3586                             names.empty, fExpr.target, ABSTRACT);
3587                     if (csym != null) {
3588                         chk.checkImplementations(env.tree, csym, csym);
3589                         try {
3590                             //perform an additional functional interface check on the synthetic class,
3591                             //as there may be spurious errors for raw targets - because of existing issues
3592                             //with membership and inheritance (see JDK-8074570).
3593                             csym.flags_field |= INTERFACE;
3594                             types.findDescriptorType(csym.type);
3595                         } catch (FunctionDescriptorLookupError err) {
3596                             resultInfo.checkContext.report(fExpr,
3597                                     diags.fragment(Fragments.NoSuitableFunctionalIntfInst(fExpr.target)));
3598                         }
3599                     }
3600                 } catch (Types.FunctionDescriptorLookupError ex) {
3601                     JCDiagnostic cause = ex.getDiagnostic();
3602                     resultInfo.checkContext.report(env.tree, cause);
3603                 }
3604             }
3605         }
3606     }
3607 
3608     public void visitParens(JCParens tree) {
3609         Type owntype = attribTree(tree.expr, env, resultInfo);
3610         result = check(tree, owntype, pkind(), resultInfo);
3611         Symbol sym = TreeInfo.symbol(tree);
3612         if (sym != null && sym.kind.matches(KindSelector.TYP_PCK))
3613             log.error(tree.pos(), Errors.IllegalParenthesizedExpression);
3614     }
3615 
3616     public void visitAssign(JCAssign tree) {
3617         Type owntype = attribTree(tree.lhs, env.dup(tree), varAssignmentInfo);
3618         Type capturedType = capture(owntype);
3619         attribExpr(tree.rhs, env, owntype);
3620         result = check(tree, capturedType, KindSelector.VAL, resultInfo);
3621     }
3622 
3623     public void visitAssignop(JCAssignOp tree) {
3624         // Attribute arguments.
3625         Type owntype = attribTree(tree.lhs, env, varAssignmentInfo);
3626         Type operand = attribExpr(tree.rhs, env);
3627         // Find operator.
3628         Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), owntype, operand);
3629         if (operator != operators.noOpSymbol &&
3630                 !owntype.isErroneous() &&
3631                 !operand.isErroneous()) {
3632             chk.checkDivZero(tree.rhs.pos(), operator, operand);
3633             chk.checkCastable(tree.rhs.pos(),
3634                               operator.type.getReturnType(),
3635                               owntype);
3636         }
3637         result = check(tree, owntype, KindSelector.VAL, resultInfo);
3638     }
3639 
3640     public void visitUnary(JCUnary tree) {
3641         // Attribute arguments.
3642         Type argtype = (tree.getTag().isIncOrDecUnaryOp())
3643             ? attribTree(tree.arg, env, varAssignmentInfo)
3644             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
3645 
3646         // Find operator.
3647         Symbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype);
3648         Type owntype = types.createErrorType(tree.type);
3649         if (operator != operators.noOpSymbol &&
3650                 !argtype.isErroneous()) {
3651             owntype = (tree.getTag().isIncOrDecUnaryOp())
3652                 ? tree.arg.type
3653                 : operator.type.getReturnType();
3654             int opc = ((OperatorSymbol)operator).opcode;
3655 
3656             // If the argument is constant, fold it.
3657             if (argtype.constValue() != null) {
3658                 Type ctype = cfolder.fold1(opc, argtype);
3659                 if (ctype != null) {
3660                     owntype = cfolder.coerce(ctype, owntype);
3661                 }
3662             }
3663         }
3664         result = check(tree, owntype, KindSelector.VAL, resultInfo);
3665     }
3666 
3667     public void visitBinary(JCBinary tree) {
3668         // Attribute arguments.
3669         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
3670         // If e = "x && y", then, include x.T in y;  If e = "x || y", then, include x.F in y
3671         List<BindingSymbol> matchBindings;
3672         switch (tree.getTag()) {
3673             case AND:
3674                 matchBindings = matchBindingsComputer.getMatchBindings(tree.lhs, true);
3675                 break;
3676             case OR:
3677                 matchBindings = matchBindingsComputer.getMatchBindings(tree.lhs, false);
3678                 break;
3679             default:
3680                 matchBindings = List.nil();
3681                 break;
3682         }
3683         Env<AttrContext> rhsEnv = bindingEnv(env, matchBindings);
3684         Type right;
3685         try {
3686             right = chk.checkNonVoid(tree.rhs.pos(), attribExpr(tree.rhs, rhsEnv));
3687         } finally {
3688             rhsEnv.info.scope.leave();
3689         }
3690 
3691         // Find operator.
3692         Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag(), left, right);
3693         Type owntype = types.createErrorType(tree.type);
3694         if (operator != operators.noOpSymbol &&
3695                 !left.isErroneous() &&
3696                 !right.isErroneous()) {
3697             owntype = operator.type.getReturnType();
3698             int opc = ((OperatorSymbol)operator).opcode;
3699             // If both arguments are constants, fold them.
3700             if (left.constValue() != null && right.constValue() != null) {
3701                 Type ctype = cfolder.fold2(opc, left, right);
3702                 if (ctype != null) {
3703                     owntype = cfolder.coerce(ctype, owntype);
3704                 }
3705             }
3706 
3707             // Check that argument types of a reference ==, != are
3708             // castable to each other, (JLS 15.21).  Note: unboxing
3709             // comparisons will not have an acmp* opc at this point.
3710             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
3711                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
3712                     log.error(tree.pos(), Errors.IncomparableTypes(left, right));
3713                 }
3714             }
3715 
3716             chk.checkDivZero(tree.rhs.pos(), operator, right);
3717         }
3718         result = check(tree, owntype, KindSelector.VAL, resultInfo);
3719     }
3720 
3721     public void visitTypeCast(final JCTypeCast tree) {
3722         Type clazztype = attribType(tree.clazz, env);
3723         chk.validate(tree.clazz, env, false);
3724         //a fresh environment is required for 292 inference to work properly ---
3725         //see Infer.instantiatePolymorphicSignatureInstance()
3726         Env<AttrContext> localEnv = env.dup(tree);
3727         //should we propagate the target type?
3728         final ResultInfo castInfo;
3729         JCExpression expr = TreeInfo.skipParens(tree.expr);
3730         boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
3731         if (isPoly) {
3732             //expression is a poly - we need to propagate target type info
3733             castInfo = new ResultInfo(KindSelector.VAL, clazztype,
3734                                       new Check.NestedCheckContext(resultInfo.checkContext) {
3735                 @Override
3736                 public boolean compatible(Type found, Type req, Warner warn) {
3737                     return types.isCastable(found, req, warn);
3738                 }
3739             });
3740         } else {
3741             //standalone cast - target-type info is not propagated
3742             castInfo = unknownExprInfo;
3743         }
3744         Type exprtype = attribTree(tree.expr, localEnv, castInfo);
3745         Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3746         if (exprtype.constValue() != null)
3747             owntype = cfolder.coerce(exprtype, owntype);
3748         result = check(tree, capture(owntype), KindSelector.VAL, resultInfo);
3749         if (!isPoly)
3750             chk.checkRedundantCast(localEnv, tree);
3751     }
3752 
3753     public void visitTypeTest(JCInstanceOf tree) {
3754         Type exprtype = chk.checkNullOrRefType(
3755                 tree.expr.pos(), attribExpr(tree.expr, env));
3756         Type clazztype;
3757         if (tree.pattern.getTag() == BINDINGPATTERN) {
3758             attribTree(tree.pattern, env, unknownExprInfo);
3759             clazztype = tree.pattern.type;
3760             if (!clazztype.hasTag(TYPEVAR)) {
3761                 JCBindingPattern pattern = (JCBindingPattern) tree.pattern;
3762                 clazztype = chk.checkClassOrArrayType(pattern.vartype.pos(), clazztype);
3763             }
3764         } else {
3765             clazztype = attribType(tree.pattern, env);
3766             if (!clazztype.hasTag(TYPEVAR)) {
3767                 clazztype = chk.checkClassOrArrayType(tree.pattern.pos(), clazztype);
3768             }
3769             if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
3770                 log.error(tree.pattern.pos(), Errors.IllegalGenericTypeForInstof);
3771                 clazztype = types.createErrorType(clazztype);
3772             }
3773             chk.validate(tree.pattern, env, false);
3774         }
3775         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3776         result = check(tree, syms.booleanType, KindSelector.VAL, resultInfo);
3777     }
3778 
3779     public void visitBindingPattern(JCBindingPattern tree) {
3780         if (tree.vartype != null) {
3781             ResultInfo varInfo = new ResultInfo(KindSelector.TYP, resultInfo.pt, resultInfo.checkContext);
3782             tree.type = attribTree(tree.vartype, env, varInfo);
3783         } else {
3784             tree.type = resultInfo.pt;
3785         }
3786         VarSymbol v = tree.symbol = new BindingSymbol(tree.name, tree.vartype != null ? tree.vartype.type : (tree.type.hasTag(BOT) ? syms.objectType : tree.type), env.info.scope.owner);
3787         if (chk.checkUnique(tree.pos(), v, env.info.scope)) {
3788             chk.checkTransparentVar(tree.pos(), v, env.info.scope);
3789             // env.info.scope.enter(v); // we inject into scopes expressly at various points.
3790         }
3791         result = tree.type;
3792     }
3793 
3794     public void visitIndexed(JCArrayAccess tree) {
3795         Type owntype = types.createErrorType(tree.type);
3796         Type atype = attribExpr(tree.indexed, env);
3797         attribExpr(tree.index, env, syms.intType);
3798         if (types.isArray(atype))
3799             owntype = types.elemtype(atype);
3800         else if (!atype.hasTag(ERROR))
3801             log.error(tree.pos(), Errors.ArrayReqButFound(atype));
3802         if (!pkind().contains(KindSelector.VAL))
3803             owntype = capture(owntype);
3804         result = check(tree, owntype, KindSelector.VAR, resultInfo);
3805     }
3806 
3807     public void visitIdent(JCIdent tree) {
3808         Symbol sym;
3809 
3810         // Find symbol
3811         if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
3812             // If we are looking for a method, the prototype `pt' will be a
3813             // method type with the type of the call's arguments as parameters.
3814             env.info.pendingResolutionPhase = null;
3815             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
3816         } else if (tree.sym != null && tree.sym.kind != VAR) {
3817             sym = tree.sym;
3818         } else {
3819             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
3820         }
3821         tree.sym = sym;
3822 
3823         // (1) Also find the environment current for the class where
3824         //     sym is defined (`symEnv').
3825         // Only for pre-tiger versions (1.4 and earlier):
3826         // (2) Also determine whether we access symbol out of an anonymous
3827         //     class in a this or super call.  This is illegal for instance
3828         //     members since such classes don't carry a this$n link.
3829         //     (`noOuterThisPath').
3830         Env<AttrContext> symEnv = env;
3831         boolean noOuterThisPath = false;
3832         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
3833             sym.kind.matches(KindSelector.VAL_MTH) &&
3834             sym.owner.kind == TYP &&
3835             tree.name != names._this && tree.name != names._super) {
3836 
3837             // Find environment in which identifier is defined.
3838             while (symEnv.outer != null &&
3839                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
3840                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
3841                     noOuterThisPath = false;
3842                 symEnv = symEnv.outer;
3843             }
3844         }
3845 
3846         // If symbol is a variable, ...
3847         if (sym.kind == VAR) {
3848             VarSymbol v = (VarSymbol)sym;
3849 
3850             // ..., evaluate its initializer, if it has one, and check for
3851             // illegal forward reference.
3852             checkInit(tree, env, v, false);
3853 
3854             // If we are expecting a variable (as opposed to a value), check
3855             // that the variable is assignable in the current environment.
3856             if (KindSelector.ASG.subset(pkind()))
3857                 checkAssignable(tree.pos(), v, null, env);
3858         }
3859 
3860         // In a constructor body,
3861         // if symbol is a field or instance method, check that it is
3862         // not accessed before the supertype constructor is called.
3863         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
3864             sym.kind.matches(KindSelector.VAL_MTH) &&
3865             sym.owner.kind == TYP &&
3866             (sym.flags() & STATIC) == 0) {
3867             chk.earlyRefError(tree.pos(), sym.kind == VAR ?
3868                                           sym : thisSym(tree.pos(), env));
3869         }
3870         Env<AttrContext> env1 = env;
3871         if (sym.kind != ERR && sym.kind != TYP &&
3872             sym.owner != null && sym.owner != env1.enclClass.sym) {
3873             // If the found symbol is inaccessible, then it is
3874             // accessed through an enclosing instance.  Locate this
3875             // enclosing instance:
3876             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
3877                 env1 = env1.outer;
3878         }
3879 
3880         if (env.info.isSerializable) {
3881             chk.checkAccessFromSerializableElement(tree, env.info.isLambda);
3882         }
3883 
3884         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
3885     }
3886 
3887     public void visitSelect(JCFieldAccess tree) {
3888         // Determine the expected kind of the qualifier expression.
3889         KindSelector skind = KindSelector.NIL;
3890         if (tree.name == names._this || tree.name == names._super ||
3891                 tree.name == names._class)
3892         {
3893             skind = KindSelector.TYP;
3894         } else {
3895             if (pkind().contains(KindSelector.PCK))
3896                 skind = KindSelector.of(skind, KindSelector.PCK);
3897             if (pkind().contains(KindSelector.TYP))
3898                 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
3899             if (pkind().contains(KindSelector.VAL_MTH))
3900                 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
3901         }
3902 
3903         // Attribute the qualifier expression, and determine its symbol (if any).
3904         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
3905         if (!pkind().contains(KindSelector.TYP_PCK))
3906             site = capture(site); // Capture field access
3907 
3908         // don't allow T.class T[].class, etc
3909         if (skind == KindSelector.TYP) {
3910             Type elt = site;
3911             while (elt.hasTag(ARRAY))
3912                 elt = ((ArrayType)elt).elemtype;
3913             if (elt.hasTag(TYPEVAR)) {
3914                 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
3915                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
3916                 tree.sym = tree.type.tsym;
3917                 return ;
3918             }
3919         }
3920 
3921         // If qualifier symbol is a type or `super', assert `selectSuper'
3922         // for the selection. This is relevant for determining whether
3923         // protected symbols are accessible.
3924         Symbol sitesym = TreeInfo.symbol(tree.selected);
3925         boolean selectSuperPrev = env.info.selectSuper;
3926         env.info.selectSuper =
3927             sitesym != null &&
3928             sitesym.name == names._super;
3929 
3930         // Determine the symbol represented by the selection.
3931         env.info.pendingResolutionPhase = null;
3932         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
3933         if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
3934             log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym));
3935             sym = syms.errSymbol;
3936         }
3937         if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
3938             site = capture(site);
3939             sym = selectSym(tree, sitesym, site, env, resultInfo);
3940         }
3941         boolean varArgs = env.info.lastResolveVarargs();
3942         tree.sym = sym;
3943 
3944         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
3945             site = types.skipTypeVars(site, true);
3946         }
3947 
3948         // If that symbol is a variable, ...
3949         if (sym.kind == VAR) {
3950             VarSymbol v = (VarSymbol)sym;
3951 
3952             // ..., evaluate its initializer, if it has one, and check for
3953             // illegal forward reference.
3954             checkInit(tree, env, v, true);
3955 
3956             // If we are expecting a variable (as opposed to a value), check
3957             // that the variable is assignable in the current environment.
3958             if (KindSelector.ASG.subset(pkind()))
3959                 checkAssignable(tree.pos(), v, tree.selected, env);
3960         }
3961 
3962         if (sitesym != null &&
3963                 sitesym.kind == VAR &&
3964                 ((VarSymbol)sitesym).isResourceVariable() &&
3965                 sym.kind == MTH &&
3966                 sym.name.equals(names.close) &&
3967                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
3968                 env.info.lint.isEnabled(LintCategory.TRY)) {
3969             log.warning(LintCategory.TRY, tree, Warnings.TryExplicitCloseCall);
3970         }
3971 
3972         // Disallow selecting a type from an expression
3973         if (isType(sym) && (sitesym == null || !sitesym.kind.matches(KindSelector.TYP_PCK))) {
3974             tree.type = check(tree.selected, pt(),
3975                               sitesym == null ?
3976                                       KindSelector.VAL : sitesym.kind.toSelector(),
3977                               new ResultInfo(KindSelector.TYP_PCK, pt()));
3978         }
3979 
3980         if (isType(sitesym)) {
3981             if (sym.name == names._this) {
3982                 // If `C' is the currently compiled class, check that
3983                 // C.this' does not appear in a call to a super(...)
3984                 if (env.info.isSelfCall &&
3985                     site.tsym == env.enclClass.sym) {
3986                     chk.earlyRefError(tree.pos(), sym);
3987                 }
3988             } else {
3989                 // Check if type-qualified fields or methods are static (JLS)
3990                 if ((sym.flags() & STATIC) == 0 &&
3991                     sym.name != names._super &&
3992                     (sym.kind == VAR || sym.kind == MTH)) {
3993                     rs.accessBase(rs.new StaticError(sym),
3994                               tree.pos(), site, sym.name, true);
3995                 }
3996             }
3997             if (!allowStaticInterfaceMethods && sitesym.isInterface() &&
3998                     sym.isStatic() && sym.kind == MTH) {
3999                 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.pos(), Feature.STATIC_INTERFACE_METHODS_INVOKE.error(sourceName));
4000             }
4001         } else if (sym.kind != ERR &&
4002                    (sym.flags() & STATIC) != 0 &&
4003                    sym.name != names._class) {
4004             // If the qualified item is not a type and the selected item is static, report
4005             // a warning. Make allowance for the class of an array type e.g. Object[].class)
4006             chk.warnStatic(tree, Warnings.StaticNotQualifiedByType(sym.kind.kindName(), sym.owner));
4007         }
4008 
4009         // If we are selecting an instance member via a `super', ...
4010         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
4011 
4012             // Check that super-qualified symbols are not abstract (JLS)
4013             rs.checkNonAbstract(tree.pos(), sym);
4014 
4015             if (site.isRaw()) {
4016                 // Determine argument types for site.
4017                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
4018                 if (site1 != null) site = site1;
4019             }
4020         }
4021 
4022         if (env.info.isSerializable) {
4023             chk.checkAccessFromSerializableElement(tree, env.info.isLambda);
4024         }
4025 
4026         env.info.selectSuper = selectSuperPrev;
4027         result = checkId(tree, site, sym, env, resultInfo);
4028     }
4029     //where
4030         /** Determine symbol referenced by a Select expression,
4031          *
4032          *  @param tree   The select tree.
4033          *  @param site   The type of the selected expression,
4034          *  @param env    The current environment.
4035          *  @param resultInfo The current result.
4036          */
4037         private Symbol selectSym(JCFieldAccess tree,
4038                                  Symbol location,
4039                                  Type site,
4040                                  Env<AttrContext> env,
4041                                  ResultInfo resultInfo) {
4042             DiagnosticPosition pos = tree.pos();
4043             Name name = tree.name;
4044             switch (site.getTag()) {
4045             case PACKAGE:
4046                 return rs.accessBase(
4047                     rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind),
4048                     pos, location, site, name, true);
4049             case ARRAY:
4050             case CLASS:
4051                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
4052                     return rs.resolveQualifiedMethod(
4053                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
4054                 } else if (name == names._this || name == names._super) {
4055                     return rs.resolveSelf(pos, env, site.tsym, name);
4056                 } else if (name == names._class) {
4057                     // In this case, we have already made sure in
4058                     // visitSelect that qualifier expression is a type.
4059                     return syms.getClassField(site, types);
4060                 } else {
4061                     // We are seeing a plain identifier as selector.
4062                     Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind);
4063                         sym = rs.accessBase(sym, pos, location, site, name, true);
4064                     return sym;
4065                 }
4066             case WILDCARD:
4067                 throw new AssertionError(tree);
4068             case TYPEVAR:
4069                 // Normally, site.getUpperBound() shouldn't be null.
4070                 // It should only happen during memberEnter/attribBase
4071                 // when determining the super type which *must* beac
4072                 // done before attributing the type variables.  In
4073                 // other words, we are seeing this illegal program:
4074                 // class B<T> extends A<T.foo> {}
4075                 Symbol sym = (site.getUpperBound() != null)
4076                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
4077                     : null;
4078                 if (sym == null) {
4079                     log.error(pos, Errors.TypeVarCantBeDeref);
4080                     return syms.errSymbol;
4081                 } else {
4082                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
4083                         rs.new AccessError(env, site, sym) :
4084                                 sym;
4085                     rs.accessBase(sym2, pos, location, site, name, true);
4086                     return sym;
4087                 }
4088             case ERROR:
4089                 // preserve identifier names through errors
4090                 return types.createErrorType(name, site.tsym, site).tsym;
4091             default:
4092                 // The qualifier expression is of a primitive type -- only
4093                 // .class is allowed for these.
4094                 if (name == names._class) {
4095                     // In this case, we have already made sure in Select that
4096                     // qualifier expression is a type.
4097                     return syms.getClassField(site, types);
4098                 } else {
4099                     log.error(pos, Errors.CantDeref(site));
4100                     return syms.errSymbol;
4101                 }
4102             }
4103         }
4104 
4105         /** Determine type of identifier or select expression and check that
4106          *  (1) the referenced symbol is not deprecated
4107          *  (2) the symbol's type is safe (@see checkSafe)
4108          *  (3) if symbol is a variable, check that its type and kind are
4109          *      compatible with the prototype and protokind.
4110          *  (4) if symbol is an instance field of a raw type,
4111          *      which is being assigned to, issue an unchecked warning if its
4112          *      type changes under erasure.
4113          *  (5) if symbol is an instance method of a raw type, issue an
4114          *      unchecked warning if its argument types change under erasure.
4115          *  If checks succeed:
4116          *    If symbol is a constant, return its constant type
4117          *    else if symbol is a method, return its result type
4118          *    otherwise return its type.
4119          *  Otherwise return errType.
4120          *
4121          *  @param tree       The syntax tree representing the identifier
4122          *  @param site       If this is a select, the type of the selected
4123          *                    expression, otherwise the type of the current class.
4124          *  @param sym        The symbol representing the identifier.
4125          *  @param env        The current environment.
4126          *  @param resultInfo    The expected result
4127          */
4128         Type checkId(JCTree tree,
4129                      Type site,
4130                      Symbol sym,
4131                      Env<AttrContext> env,
4132                      ResultInfo resultInfo) {
4133             return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
4134                     checkMethodIdInternal(tree, site, sym, env, resultInfo) :
4135                     checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
4136         }
4137 
4138         Type checkMethodIdInternal(JCTree tree,
4139                      Type site,
4140                      Symbol sym,
4141                      Env<AttrContext> env,
4142                      ResultInfo resultInfo) {
4143             if (resultInfo.pkind.contains(KindSelector.POLY)) {
4144                 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
4145                 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
4146                 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
4147                 return owntype;
4148             } else {
4149                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
4150             }
4151         }
4152 
4153         Type checkIdInternal(JCTree tree,
4154                      Type site,
4155                      Symbol sym,
4156                      Type pt,
4157                      Env<AttrContext> env,
4158                      ResultInfo resultInfo) {
4159             if (pt.isErroneous()) {
4160                 return types.createErrorType(site);
4161             }
4162             Type owntype; // The computed type of this identifier occurrence.
4163             switch (sym.kind) {
4164             case TYP:
4165                 // For types, the computed type equals the symbol's type,
4166                 // except for two situations:
4167                 owntype = sym.type;
4168                 if (owntype.hasTag(CLASS)) {
4169                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
4170                     Type ownOuter = owntype.getEnclosingType();
4171 
4172                     // (a) If the symbol's type is parameterized, erase it
4173                     // because no type parameters were given.
4174                     // We recover generic outer type later in visitTypeApply.
4175                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
4176                         owntype = types.erasure(owntype);
4177                     }
4178 
4179                     // (b) If the symbol's type is an inner class, then
4180                     // we have to interpret its outer type as a superclass
4181                     // of the site type. Example:
4182                     //
4183                     // class Tree<A> { class Visitor { ... } }
4184                     // class PointTree extends Tree<Point> { ... }
4185                     // ...PointTree.Visitor...
4186                     //
4187                     // Then the type of the last expression above is
4188                     // Tree<Point>.Visitor.
4189                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
4190                         Type normOuter = site;
4191                         if (normOuter.hasTag(CLASS)) {
4192                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
4193                         }
4194                         if (normOuter == null) // perhaps from an import
4195                             normOuter = types.erasure(ownOuter);
4196                         if (normOuter != ownOuter)
4197                             owntype = new ClassType(
4198                                 normOuter, List.nil(), owntype.tsym,
4199                                 owntype.getMetadata());
4200                     }
4201                 }
4202                 break;
4203             case VAR:
4204                 VarSymbol v = (VarSymbol)sym;
4205 
4206                 if (env.info.enclVar != null
4207                         && v.type.hasTag(NONE)) {
4208                     //self reference to implicitly typed variable declaration
4209                     log.error(TreeInfo.positionFor(v, env.enclClass), Errors.CantInferLocalVarType(v.name, Fragments.LocalSelfRef));
4210                     return v.type = types.createErrorType(v.type);
4211                 }
4212 
4213                 // Test (4): if symbol is an instance field of a raw type,
4214                 // which is being assigned to, issue an unchecked warning if
4215                 // its type changes under erasure.
4216                 if (KindSelector.ASG.subset(pkind()) &&
4217                     v.owner.kind == TYP &&
4218                     (v.flags() & STATIC) == 0 &&
4219                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
4220                     Type s = types.asOuterSuper(site, v.owner);
4221                     if (s != null &&
4222                         s.isRaw() &&
4223                         !types.isSameType(v.type, v.erasure(types))) {
4224                         chk.warnUnchecked(tree.pos(), Warnings.UncheckedAssignToVar(v, s));
4225                     }
4226                 }
4227                 // The computed type of a variable is the type of the
4228                 // variable symbol, taken as a member of the site type.
4229                 owntype = (sym.owner.kind == TYP &&
4230                            sym.name != names._this && sym.name != names._super)
4231                     ? types.memberType(site, sym)
4232                     : sym.type;
4233 
4234                 // If the variable is a constant, record constant value in
4235                 // computed type.
4236                 if (v.getConstValue() != null && isStaticReference(tree))
4237                     owntype = owntype.constType(v.getConstValue());
4238 
4239                 if (resultInfo.pkind == KindSelector.VAL) {
4240                     owntype = capture(owntype); // capture "names as expressions"
4241                 }
4242                 break;
4243             case MTH: {
4244                 owntype = checkMethod(site, sym,
4245                         new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext, resultInfo.checkMode),
4246                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
4247                         resultInfo.pt.getTypeArguments());
4248                 break;
4249             }
4250             case PCK: case ERR:
4251                 owntype = sym.type;
4252                 break;
4253             default:
4254                 throw new AssertionError("unexpected kind: " + sym.kind +
4255                                          " in tree " + tree);
4256             }
4257 
4258             // Emit a `deprecation' warning if symbol is deprecated.
4259             // (for constructors (but not for constructor references), the error
4260             // was given when the constructor was resolved)
4261 
4262             if (sym.name != names.init || tree.hasTag(REFERENCE)) {
4263                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
4264                 chk.checkSunAPI(tree.pos(), sym);
4265                 chk.checkProfile(tree.pos(), sym);
4266             }
4267 
4268             // If symbol is a variable, check that its type and
4269             // kind are compatible with the prototype and protokind.
4270             return check(tree, owntype, sym.kind.toSelector(), resultInfo);
4271         }
4272 
4273         /** Check that variable is initialized and evaluate the variable's
4274          *  initializer, if not yet done. Also check that variable is not
4275          *  referenced before it is defined.
4276          *  @param tree    The tree making up the variable reference.
4277          *  @param env     The current environment.
4278          *  @param v       The variable's symbol.
4279          */
4280         private void checkInit(JCTree tree,
4281                                Env<AttrContext> env,
4282                                VarSymbol v,
4283                                boolean onlyWarning) {
4284             // A forward reference is diagnosed if the declaration position
4285             // of the variable is greater than the current tree position
4286             // and the tree and variable definition occur in the same class
4287             // definition.  Note that writes don't count as references.
4288             // This check applies only to class and instance
4289             // variables.  Local variables follow different scope rules,
4290             // and are subject to definite assignment checking.
4291             Env<AttrContext> initEnv = enclosingInitEnv(env);
4292             if (initEnv != null &&
4293                 (initEnv.info.enclVar == v || v.pos > tree.pos) &&
4294                 v.owner.kind == TYP &&
4295                 v.owner == env.info.scope.owner.enclClass() &&
4296                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
4297                 (!env.tree.hasTag(ASSIGN) ||
4298                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
4299                 if (!onlyWarning || isStaticEnumField(v)) {
4300                     Error errkey = (initEnv.info.enclVar == v) ?
4301                                 Errors.IllegalSelfRef : Errors.IllegalForwardRef;
4302                     log.error(tree.pos(), errkey);
4303                 } else if (useBeforeDeclarationWarning) {
4304                     Warning warnkey = (initEnv.info.enclVar == v) ?
4305                                 Warnings.SelfRef(v) : Warnings.ForwardRef(v);
4306                     log.warning(tree.pos(), warnkey);
4307                 }
4308             }
4309 
4310             v.getConstValue(); // ensure initializer is evaluated
4311 
4312             checkEnumInitializer(tree, env, v);
4313         }
4314 
4315         /**
4316          * Returns the enclosing init environment associated with this env (if any). An init env
4317          * can be either a field declaration env or a static/instance initializer env.
4318          */
4319         Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) {
4320             while (true) {
4321                 switch (env.tree.getTag()) {
4322                     case VARDEF:
4323                         JCVariableDecl vdecl = (JCVariableDecl)env.tree;
4324                         if (vdecl.sym.owner.kind == TYP) {
4325                             //field
4326                             return env;
4327                         }
4328                         break;
4329                     case BLOCK:
4330                         if (env.next.tree.hasTag(CLASSDEF)) {
4331                             //instance/static initializer
4332                             return env;
4333                         }
4334                         break;
4335                     case METHODDEF:
4336                     case CLASSDEF:
4337                     case TOPLEVEL:
4338                         return null;
4339                 }
4340                 Assert.checkNonNull(env.next);
4341                 env = env.next;
4342             }
4343         }
4344 
4345         /**
4346          * Check for illegal references to static members of enum.  In
4347          * an enum type, constructors and initializers may not
4348          * reference its static members unless they are constant.
4349          *
4350          * @param tree    The tree making up the variable reference.
4351          * @param env     The current environment.
4352          * @param v       The variable's symbol.
4353          * @jls 8.9 Enum Types
4354          */
4355         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
4356             // JLS:
4357             //
4358             // "It is a compile-time error to reference a static field
4359             // of an enum type that is not a compile-time constant
4360             // (15.28) from constructors, instance initializer blocks,
4361             // or instance variable initializer expressions of that
4362             // type. It is a compile-time error for the constructors,
4363             // instance initializer blocks, or instance variable
4364             // initializer expressions of an enum constant e to refer
4365             // to itself or to an enum constant of the same type that
4366             // is declared to the right of e."
4367             if (isStaticEnumField(v)) {
4368                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
4369 
4370                 if (enclClass == null || enclClass.owner == null)
4371                     return;
4372 
4373                 // See if the enclosing class is the enum (or a
4374                 // subclass thereof) declaring v.  If not, this
4375                 // reference is OK.
4376                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
4377                     return;
4378 
4379                 // If the reference isn't from an initializer, then
4380                 // the reference is OK.
4381                 if (!Resolve.isInitializer(env))
4382                     return;
4383 
4384                 log.error(tree.pos(), Errors.IllegalEnumStaticRef);
4385             }
4386         }
4387 
4388         /** Is the given symbol a static, non-constant field of an Enum?
4389          *  Note: enum literals should not be regarded as such
4390          */
4391         private boolean isStaticEnumField(VarSymbol v) {
4392             return Flags.isEnum(v.owner) &&
4393                    Flags.isStatic(v) &&
4394                    !Flags.isConstant(v) &&
4395                    v.name != names._class;
4396         }
4397 
4398     /**
4399      * Check that method arguments conform to its instantiation.
4400      **/
4401     public Type checkMethod(Type site,
4402                             final Symbol sym,
4403                             ResultInfo resultInfo,
4404                             Env<AttrContext> env,
4405                             final List<JCExpression> argtrees,
4406                             List<Type> argtypes,
4407                             List<Type> typeargtypes) {
4408         // Test (5): if symbol is an instance method of a raw type, issue
4409         // an unchecked warning if its argument types change under erasure.
4410         if ((sym.flags() & STATIC) == 0 &&
4411             (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
4412             Type s = types.asOuterSuper(site, sym.owner);
4413             if (s != null && s.isRaw() &&
4414                 !types.isSameTypes(sym.type.getParameterTypes(),
4415                                    sym.erasure(types).getParameterTypes())) {
4416                 chk.warnUnchecked(env.tree.pos(), Warnings.UncheckedCallMbrOfRawType(sym, s));
4417             }
4418         }
4419 
4420         if (env.info.defaultSuperCallSite != null) {
4421             for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
4422                 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
4423                         types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
4424                 List<MethodSymbol> icand_sup =
4425                         types.interfaceCandidates(sup, (MethodSymbol)sym);
4426                 if (icand_sup.nonEmpty() &&
4427                         icand_sup.head != sym &&
4428                         icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
4429                     log.error(env.tree.pos(),
4430                               Errors.IllegalDefaultSuperCall(env.info.defaultSuperCallSite, Fragments.OverriddenDefault(sym, sup)));
4431                     break;
4432                 }
4433             }
4434             env.info.defaultSuperCallSite = null;
4435         }
4436 
4437         if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
4438             JCMethodInvocation app = (JCMethodInvocation)env.tree;
4439             if (app.meth.hasTag(SELECT) &&
4440                     !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
4441                 log.error(env.tree.pos(), Errors.IllegalStaticIntfMethCall(site));
4442             }
4443         }
4444 
4445         // Compute the identifier's instantiated type.
4446         // For methods, we need to compute the instance type by
4447         // Resolve.instantiate from the symbol's type as well as
4448         // any type arguments and value arguments.
4449         Warner noteWarner = new Warner();
4450         try {
4451             Type owntype = rs.checkMethod(
4452                     env,
4453                     site,
4454                     sym,
4455                     resultInfo,
4456                     argtypes,
4457                     typeargtypes,
4458                     noteWarner);
4459 
4460             DeferredAttr.DeferredTypeMap<Void> checkDeferredMap =
4461                 deferredAttr.new DeferredTypeMap<>(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
4462 
4463             argtypes = argtypes.map(checkDeferredMap);
4464 
4465             if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
4466                 chk.warnUnchecked(env.tree.pos(), Warnings.UncheckedMethInvocationApplied(kindName(sym),
4467                         sym.name,
4468                         rs.methodArguments(sym.type.getParameterTypes()),
4469                         rs.methodArguments(argtypes.map(checkDeferredMap)),
4470                         kindName(sym.location()),
4471                         sym.location()));
4472                 if (resultInfo.pt != Infer.anyPoly ||
4473                         !owntype.hasTag(METHOD) ||
4474                         !owntype.isPartial()) {
4475                     //if this is not a partially inferred method type, erase return type. Otherwise,
4476                     //erasure is carried out in PartiallyInferredMethodType.check().
4477                     owntype = new MethodType(owntype.getParameterTypes(),
4478                             types.erasure(owntype.getReturnType()),
4479                             types.erasure(owntype.getThrownTypes()),
4480                             syms.methodClass);
4481                 }
4482             }
4483 
4484             PolyKind pkind = (sym.type.hasTag(FORALL) &&
4485                  sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
4486                  PolyKind.POLY : PolyKind.STANDALONE;
4487             TreeInfo.setPolyKind(env.tree, pkind);
4488 
4489             return (resultInfo.pt == Infer.anyPoly) ?
4490                     owntype :
4491                     chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
4492                             resultInfo.checkContext.inferenceContext());
4493         } catch (Infer.InferenceException ex) {
4494             //invalid target type - propagate exception outwards or report error
4495             //depending on the current check context
4496             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
4497             return types.createErrorType(site);
4498         } catch (Resolve.InapplicableMethodException ex) {
4499             final JCDiagnostic diag = ex.getDiagnostic();
4500             Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
4501                 @Override
4502                 protected Pair<Symbol, JCDiagnostic> errCandidate() {
4503                     return new Pair<>(sym, diag);
4504                 }
4505             };
4506             List<Type> argtypes2 = argtypes.map(
4507                     rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
4508             JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
4509                     env.tree, sym, site, sym.name, argtypes2, typeargtypes);
4510             log.report(errDiag);
4511             return types.createErrorType(site);
4512         }
4513     }
4514 
4515     public void visitLiteral(JCLiteral tree) {
4516         result = check(tree, litType(tree.typetag).constType(tree.value),
4517                 KindSelector.VAL, resultInfo);
4518     }
4519     //where
4520     /** Return the type of a literal with given type tag.
4521      */
4522     Type litType(TypeTag tag) {
4523         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
4524     }
4525 
4526     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
4527         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
4528     }
4529 
4530     public void visitTypeArray(JCArrayTypeTree tree) {
4531         Type etype = attribType(tree.elemtype, env);
4532         Type type = new ArrayType(etype, syms.arrayClass);
4533         result = check(tree, type, KindSelector.TYP, resultInfo);
4534     }
4535 
4536     /** Visitor method for parameterized types.
4537      *  Bound checking is left until later, since types are attributed
4538      *  before supertype structure is completely known
4539      */
4540     public void visitTypeApply(JCTypeApply tree) {
4541         Type owntype = types.createErrorType(tree.type);
4542 
4543         // Attribute functor part of application and make sure it's a class.
4544         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
4545 
4546         // Attribute type parameters
4547         List<Type> actuals = attribTypes(tree.arguments, env);
4548 
4549         if (clazztype.hasTag(CLASS)) {
4550             List<Type> formals = clazztype.tsym.type.getTypeArguments();
4551             if (actuals.isEmpty()) //diamond
4552                 actuals = formals;
4553 
4554             if (actuals.length() == formals.length()) {
4555                 List<Type> a = actuals;
4556                 List<Type> f = formals;
4557                 while (a.nonEmpty()) {
4558                     a.head = a.head.withTypeVar(f.head);
4559                     a = a.tail;
4560                     f = f.tail;
4561                 }
4562                 // Compute the proper generic outer
4563                 Type clazzOuter = clazztype.getEnclosingType();
4564                 if (clazzOuter.hasTag(CLASS)) {
4565                     Type site;
4566                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
4567                     if (clazz.hasTag(IDENT)) {
4568                         site = env.enclClass.sym.type;
4569                     } else if (clazz.hasTag(SELECT)) {
4570                         site = ((JCFieldAccess) clazz).selected.type;
4571                     } else throw new AssertionError(""+tree);
4572                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
4573                         if (site.hasTag(CLASS))
4574                             site = types.asOuterSuper(site, clazzOuter.tsym);
4575                         if (site == null)
4576                             site = types.erasure(clazzOuter);
4577                         clazzOuter = site;
4578                     }
4579                 }
4580                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
4581                                         clazztype.getMetadata());
4582             } else {
4583                 if (formals.length() != 0) {
4584                     log.error(tree.pos(),
4585                               Errors.WrongNumberTypeArgs(Integer.toString(formals.length())));
4586                 } else {
4587                     log.error(tree.pos(), Errors.TypeDoesntTakeParams(clazztype.tsym));
4588                 }
4589                 owntype = types.createErrorType(tree.type);
4590             }
4591         }
4592         result = check(tree, owntype, KindSelector.TYP, resultInfo);
4593     }
4594 
4595     public void visitTypeUnion(JCTypeUnion tree) {
4596         ListBuffer<Type> multicatchTypes = new ListBuffer<>();
4597         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
4598         for (JCExpression typeTree : tree.alternatives) {
4599             Type ctype = attribType(typeTree, env);
4600             ctype = chk.checkType(typeTree.pos(),
4601                           chk.checkClassType(typeTree.pos(), ctype),
4602                           syms.throwableType);
4603             if (!ctype.isErroneous()) {
4604                 //check that alternatives of a union type are pairwise
4605                 //unrelated w.r.t. subtyping
4606                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
4607                     for (Type t : multicatchTypes) {
4608                         boolean sub = types.isSubtype(ctype, t);
4609                         boolean sup = types.isSubtype(t, ctype);
4610                         if (sub || sup) {
4611                             //assume 'a' <: 'b'
4612                             Type a = sub ? ctype : t;
4613                             Type b = sub ? t : ctype;
4614                             log.error(typeTree.pos(), Errors.MulticatchTypesMustBeDisjoint(a, b));
4615                         }
4616                     }
4617                 }
4618                 multicatchTypes.append(ctype);
4619                 if (all_multicatchTypes != null)
4620                     all_multicatchTypes.append(ctype);
4621             } else {
4622                 if (all_multicatchTypes == null) {
4623                     all_multicatchTypes = new ListBuffer<>();
4624                     all_multicatchTypes.appendList(multicatchTypes);
4625                 }
4626                 all_multicatchTypes.append(ctype);
4627             }
4628         }
4629         Type t = check(tree, types.lub(multicatchTypes.toList()),
4630                 KindSelector.TYP, resultInfo.dup(CheckMode.NO_TREE_UPDATE));
4631         if (t.hasTag(CLASS)) {
4632             List<Type> alternatives =
4633                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
4634             t = new UnionClassType((ClassType) t, alternatives);
4635         }
4636         tree.type = result = t;
4637     }
4638 
4639     public void visitTypeIntersection(JCTypeIntersection tree) {
4640         attribTypes(tree.bounds, env);
4641         tree.type = result = checkIntersection(tree, tree.bounds);
4642     }
4643 
4644     public void visitTypeParameter(JCTypeParameter tree) {
4645         TypeVar typeVar = (TypeVar) tree.type;
4646 
4647         if (tree.annotations != null && tree.annotations.nonEmpty()) {
4648             annotate.annotateTypeParameterSecondStage(tree, tree.annotations);
4649         }
4650 
4651         if (!typeVar.getUpperBound().isErroneous()) {
4652             //fixup type-parameter bound computed in 'attribTypeVariables'
4653             typeVar.setUpperBound(checkIntersection(tree, tree.bounds));
4654         }
4655     }
4656 
4657     Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
4658         Set<Type> boundSet = new HashSet<>();
4659         if (bounds.nonEmpty()) {
4660             // accept class or interface or typevar as first bound.
4661             bounds.head.type = checkBase(bounds.head.type, syms.unknownSymbol, bounds.head, env, false, false, false);
4662             boundSet.add(types.erasure(bounds.head.type));
4663             if (bounds.head.type.isErroneous()) {
4664                 return bounds.head.type;
4665             }
4666             else if (bounds.head.type.hasTag(TYPEVAR)) {
4667                 // if first bound was a typevar, do not accept further bounds.
4668                 if (bounds.tail.nonEmpty()) {
4669                     log.error(bounds.tail.head.pos(),
4670                               Errors.TypeVarMayNotBeFollowedByOtherBounds);
4671                     return bounds.head.type;
4672                 }
4673             } else {
4674                 // if first bound was a class or interface, accept only interfaces
4675                 // as further bounds.
4676                 for (JCExpression bound : bounds.tail) {
4677                     bound.type = checkBase(bound.type, syms.unknownSymbol, bound, env, false, true, false);
4678                     if (bound.type.isErroneous()) {
4679                         bounds = List.of(bound);
4680                     }
4681                     else if (bound.type.hasTag(CLASS)) {
4682                         chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
4683                     }
4684                 }
4685             }
4686         }
4687 
4688         if (bounds.length() == 0) {
4689             return syms.objectType;
4690         } else if (bounds.length() == 1) {
4691             return bounds.head.type;
4692         } else {
4693             Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
4694             // ... the variable's bound is a class type flagged COMPOUND
4695             // (see comment for TypeVar.bound).
4696             // In this case, generate a class tree that represents the
4697             // bound class, ...
4698             JCExpression extending;
4699             List<JCExpression> implementing;
4700             if (!bounds.head.type.isInterface()) {
4701                 extending = bounds.head;
4702                 implementing = bounds.tail;
4703             } else {
4704                 extending = null;
4705                 implementing = bounds;
4706             }
4707             JCClassDecl cd = make.at(tree).ClassDef(
4708                 make.Modifiers(PUBLIC | ABSTRACT),
4709                 names.empty, List.nil(),
4710                 extending, implementing, List.nil());
4711 
4712             ClassSymbol c = (ClassSymbol)owntype.tsym;
4713             Assert.check((c.flags() & COMPOUND) != 0);
4714             cd.sym = c;
4715             c.sourcefile = env.toplevel.sourcefile;
4716 
4717             // ... and attribute the bound class
4718             c.flags_field |= UNATTRIBUTED;
4719             Env<AttrContext> cenv = enter.classEnv(cd, env);
4720             typeEnvs.put(c, cenv);
4721             attribClass(c);
4722             return owntype;
4723         }
4724     }
4725 
4726     public void visitWildcard(JCWildcard tree) {
4727         //- System.err.println("visitWildcard("+tree+");");//DEBUG
4728         Type type = (tree.kind.kind == BoundKind.UNBOUND)
4729             ? syms.objectType
4730             : attribType(tree.inner, env);
4731         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
4732                                               tree.kind.kind,
4733                                               syms.boundClass),
4734                 KindSelector.TYP, resultInfo);
4735     }
4736 
4737     public void visitAnnotation(JCAnnotation tree) {
4738         Assert.error("should be handled in annotate");
4739     }
4740 
4741     public void visitAnnotatedType(JCAnnotatedType tree) {
4742         attribAnnotationTypes(tree.annotations, env);
4743         Type underlyingType = attribType(tree.underlyingType, env);
4744         Type annotatedType = underlyingType.annotatedType(Annotations.TO_BE_SET);
4745 
4746         if (!env.info.isNewClass)
4747             annotate.annotateTypeSecondStage(tree, tree.annotations, annotatedType);
4748         result = tree.type = annotatedType;
4749     }
4750 
4751     public void visitErroneous(JCErroneous tree) {
4752         if (tree.errs != null)
4753             for (JCTree err : tree.errs)
4754                 attribTree(err, env, new ResultInfo(KindSelector.ERR, pt()));
4755         result = tree.type = syms.errType;
4756     }
4757 
4758     /** Default visitor method for all other trees.
4759      */
4760     public void visitTree(JCTree tree) {
4761         throw new AssertionError();
4762     }
4763 
4764     /**
4765      * Attribute an env for either a top level tree or class or module declaration.
4766      */
4767     public void attrib(Env<AttrContext> env) {
4768         switch (env.tree.getTag()) {
4769             case MODULEDEF:
4770                 attribModule(env.tree.pos(), ((JCModuleDecl)env.tree).sym);
4771                 break;
4772             case TOPLEVEL:
4773                 attribTopLevel(env);
4774                 break;
4775             case PACKAGEDEF:
4776                 attribPackage(env.tree.pos(), ((JCPackageDecl) env.tree).packge);
4777                 break;
4778             default:
4779                 attribClass(env.tree.pos(), env.enclClass.sym);
4780         }
4781     }
4782 
4783     /**
4784      * Attribute a top level tree. These trees are encountered when the
4785      * package declaration has annotations.
4786      */
4787     public void attribTopLevel(Env<AttrContext> env) {
4788         JCCompilationUnit toplevel = env.toplevel;
4789         try {
4790             annotate.flush();
4791         } catch (CompletionFailure ex) {
4792             chk.completionError(toplevel.pos(), ex);
4793         }
4794     }
4795 
4796     public void attribPackage(DiagnosticPosition pos, PackageSymbol p) {
4797         try {
4798             annotate.flush();
4799             attribPackage(p);
4800         } catch (CompletionFailure ex) {
4801             chk.completionError(pos, ex);
4802         }
4803     }
4804 
4805     void attribPackage(PackageSymbol p) {
4806         Env<AttrContext> env = typeEnvs.get(p);
4807         chk.checkDeprecatedAnnotation(((JCPackageDecl) env.tree).pid.pos(), p);
4808     }
4809 
4810     public void attribModule(DiagnosticPosition pos, ModuleSymbol m) {
4811         try {
4812             annotate.flush();
4813             attribModule(m);
4814         } catch (CompletionFailure ex) {
4815             chk.completionError(pos, ex);
4816         }
4817     }
4818 
4819     void attribModule(ModuleSymbol m) {
4820         // Get environment current at the point of module definition.
4821         Env<AttrContext> env = enter.typeEnvs.get(m);
4822         attribStat(env.tree, env);
4823     }
4824 
4825     /** Main method: attribute class definition associated with given class symbol.
4826      *  reporting completion failures at the given position.
4827      *  @param pos The source position at which completion errors are to be
4828      *             reported.
4829      *  @param c   The class symbol whose definition will be attributed.
4830      */
4831     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
4832         try {
4833             annotate.flush();
4834             attribClass(c);
4835         } catch (CompletionFailure ex) {
4836             chk.completionError(pos, ex);
4837         }
4838     }
4839 
4840     /** Attribute class definition associated with given class symbol.
4841      *  @param c   The class symbol whose definition will be attributed.
4842      */
4843     void attribClass(ClassSymbol c) throws CompletionFailure {
4844         if (c.type.hasTag(ERROR)) return;
4845 
4846         // Check for cycles in the inheritance graph, which can arise from
4847         // ill-formed class files.
4848         chk.checkNonCyclic(null, c.type);
4849 
4850         Type st = types.supertype(c.type);
4851         if ((c.flags_field & Flags.COMPOUND) == 0) {
4852             // First, attribute superclass.
4853             if (st.hasTag(CLASS))
4854                 attribClass((ClassSymbol)st.tsym);
4855 
4856             // Next attribute owner, if it is a class.
4857             if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
4858                 attribClass((ClassSymbol)c.owner);
4859         }
4860 
4861         // The previous operations might have attributed the current class
4862         // if there was a cycle. So we test first whether the class is still
4863         // UNATTRIBUTED.
4864         if ((c.flags_field & UNATTRIBUTED) != 0) {
4865             c.flags_field &= ~UNATTRIBUTED;
4866 
4867             // Get environment current at the point of class definition.
4868             Env<AttrContext> env = typeEnvs.get(c);
4869 
4870             // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
4871             // because the annotations were not available at the time the env was created. Therefore,
4872             // we look up the environment chain for the first enclosing environment for which the
4873             // lint value is set. Typically, this is the parent env, but might be further if there
4874             // are any envs created as a result of TypeParameter nodes.
4875             Env<AttrContext> lintEnv = env;
4876             while (lintEnv.info.lint == null)
4877                 lintEnv = lintEnv.next;
4878 
4879             // Having found the enclosing lint value, we can initialize the lint value for this class
4880             env.info.lint = lintEnv.info.lint.augment(c);
4881 
4882             Lint prevLint = chk.setLint(env.info.lint);
4883             JavaFileObject prev = log.useSource(c.sourcefile);
4884             ResultInfo prevReturnRes = env.info.returnResult;
4885 
4886             try {
4887                 deferredLintHandler.flush(env.tree);
4888                 env.info.returnResult = null;
4889                 // java.lang.Enum may not be subclassed by a non-enum
4890                 if (st.tsym == syms.enumSym &&
4891                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
4892                     log.error(env.tree.pos(), Errors.EnumNoSubclassing);
4893 
4894                 // Enums may not be extended by source-level classes
4895                 if (st.tsym != null &&
4896                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
4897                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
4898                     log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
4899                 }
4900 
4901                 if (isSerializable(c.type)) {
4902                     env.info.isSerializable = true;
4903                 }
4904 
4905                 attribClassBody(env, c);
4906 
4907                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
4908                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
4909                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
4910                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
4911             } finally {
4912                 env.info.returnResult = prevReturnRes;
4913                 log.useSource(prev);
4914                 chk.setLint(prevLint);
4915             }
4916 
4917         }
4918     }
4919 
4920     public void visitImport(JCImport tree) {
4921         // nothing to do
4922     }
4923 
4924     public void visitModuleDef(JCModuleDecl tree) {
4925         tree.sym.completeUsesProvides();
4926         ModuleSymbol msym = tree.sym;
4927         Lint lint = env.outer.info.lint = env.outer.info.lint.augment(msym);
4928         Lint prevLint = chk.setLint(lint);
4929         chk.checkModuleName(tree);
4930         chk.checkDeprecatedAnnotation(tree, msym);
4931 
4932         try {
4933             deferredLintHandler.flush(tree.pos());
4934         } finally {
4935             chk.setLint(prevLint);
4936         }
4937     }
4938 
4939     /** Finish the attribution of a class. */
4940     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
4941         JCClassDecl tree = (JCClassDecl)env.tree;
4942         Assert.check(c == tree.sym);
4943 
4944         // Validate type parameters, supertype and interfaces.
4945         attribStats(tree.typarams, env);
4946         if (!c.isAnonymous()) {
4947             //already checked if anonymous
4948             chk.validate(tree.typarams, env);
4949             chk.validate(tree.extending, env);
4950             chk.validate(tree.implementing, env);
4951         }
4952 
4953         c.markAbstractIfNeeded(types);
4954 
4955         // If this is a non-abstract class, check that it has no abstract
4956         // methods or unimplemented methods of an implemented interface.
4957         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
4958             chk.checkAllDefined(tree.pos(), c);
4959         }
4960 
4961         if ((c.flags() & ANNOTATION) != 0) {
4962             if (tree.implementing.nonEmpty())
4963                 log.error(tree.implementing.head.pos(),
4964                           Errors.CantExtendIntfAnnotation);
4965             if (tree.typarams.nonEmpty()) {
4966                 log.error(tree.typarams.head.pos(),
4967                           Errors.IntfAnnotationCantHaveTypeParams(c));
4968             }
4969 
4970             // If this annotation type has a @Repeatable, validate
4971             Attribute.Compound repeatable = c.getAnnotationTypeMetadata().getRepeatable();
4972             // If this annotation type has a @Repeatable, validate
4973             if (repeatable != null) {
4974                 // get diagnostic position for error reporting
4975                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
4976                 Assert.checkNonNull(cbPos);
4977 
4978                 chk.validateRepeatable(c, repeatable, cbPos);
4979             }
4980         } else {
4981             // Check that all extended classes and interfaces
4982             // are compatible (i.e. no two define methods with same arguments
4983             // yet different return types).  (JLS 8.4.6.3)
4984             chk.checkCompatibleSupertypes(tree.pos(), c.type);
4985             if (allowDefaultMethods) {
4986                 chk.checkDefaultMethodClashes(tree.pos(), c.type);
4987             }
4988         }
4989 
4990         // Check that class does not import the same parameterized interface
4991         // with two different argument lists.
4992         chk.checkClassBounds(tree.pos(), c.type);
4993 
4994         tree.type = c.type;
4995 
4996         for (List<JCTypeParameter> l = tree.typarams;
4997              l.nonEmpty(); l = l.tail) {
4998              Assert.checkNonNull(env.info.scope.findFirst(l.head.name));
4999         }
5000 
5001         // Check that a generic class doesn't extend Throwable
5002         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
5003             log.error(tree.extending.pos(), Errors.GenericThrowable);
5004 
5005         // Check that all methods which implement some
5006         // method conform to the method they implement.
5007         chk.checkImplementations(tree);
5008 
5009         //check that a resource implementing AutoCloseable cannot throw InterruptedException
5010         checkAutoCloseable(tree.pos(), env, c.type);
5011 
5012         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
5013             // Attribute declaration
5014             attribStat(l.head, env);
5015             // Check that declarations in inner classes are not static (JLS 8.1.2)
5016             // Make an exception for static constants.
5017             if (c.owner.kind != PCK &&
5018                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
5019                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
5020                 Symbol sym = null;
5021                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
5022                 if (sym == null ||
5023                     sym.kind != VAR ||
5024                     ((VarSymbol) sym).getConstValue() == null)
5025                     log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
5026             }
5027         }
5028 
5029         // Check for cycles among non-initial constructors.
5030         chk.checkCyclicConstructors(tree);
5031 
5032         // Check for cycles among annotation elements.
5033         chk.checkNonCyclicElements(tree);
5034 
5035         // Check for proper use of serialVersionUID
5036         if (env.info.lint.isEnabled(LintCategory.SERIAL)
5037                 && isSerializable(c.type)
5038                 && (c.flags() & (Flags.ENUM | Flags.INTERFACE)) == 0
5039                 && !c.isAnonymous()) {
5040             checkSerialVersionUID(tree, c);
5041         }
5042         if (allowTypeAnnos) {
5043             // Correctly organize the postions of the type annotations
5044             typeAnnotations.organizeTypeAnnotationsBodies(tree);
5045 
5046             // Check type annotations applicability rules
5047             validateTypeAnnotations(tree, false);
5048         }
5049     }
5050         // where
5051         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
5052         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
5053             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
5054                 if (types.isSameType(al.head.annotationType.type, t))
5055                     return al.head.pos();
5056             }
5057 
5058             return null;
5059         }
5060 
5061         /** check if a type is a subtype of Serializable, if that is available. */
5062         boolean isSerializable(Type t) {
5063             try {
5064                 syms.serializableType.complete();
5065             }
5066             catch (CompletionFailure e) {
5067                 return false;
5068             }
5069             return types.isSubtype(t, syms.serializableType);
5070         }
5071 
5072         /** Check that an appropriate serialVersionUID member is defined. */
5073         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
5074 
5075             // check for presence of serialVersionUID
5076             VarSymbol svuid = null;
5077             for (Symbol sym : c.members().getSymbolsByName(names.serialVersionUID)) {
5078                 if (sym.kind == VAR) {
5079                     svuid = (VarSymbol)sym;
5080                     break;
5081                 }
5082             }
5083 
5084             if (svuid == null) {
5085                 log.warning(LintCategory.SERIAL,
5086                         tree.pos(), Warnings.MissingSVUID(c));
5087                 return;
5088             }
5089 
5090             // check that it is static final
5091             if ((svuid.flags() & (STATIC | FINAL)) !=
5092                 (STATIC | FINAL))
5093                 log.warning(LintCategory.SERIAL,
5094                         TreeInfo.diagnosticPositionFor(svuid, tree), Warnings.ImproperSVUID(c));
5095 
5096             // check that it is long
5097             else if (!svuid.type.hasTag(LONG))
5098                 log.warning(LintCategory.SERIAL,
5099                         TreeInfo.diagnosticPositionFor(svuid, tree), Warnings.LongSVUID(c));
5100 
5101             // check constant
5102             else if (svuid.getConstValue() == null)
5103                 log.warning(LintCategory.SERIAL,
5104                         TreeInfo.diagnosticPositionFor(svuid, tree), Warnings.ConstantSVUID(c));
5105         }
5106 
5107     private Type capture(Type type) {
5108         return types.capture(type);
5109     }
5110 
5111     private void setSyntheticVariableType(JCVariableDecl tree, Type type) {
5112         if (type.isErroneous()) {
5113             tree.vartype = make.at(Position.NOPOS).Erroneous();
5114         } else {
5115             tree.vartype = make.at(Position.NOPOS).Type(type);
5116         }
5117     }
5118 
5119     public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
5120         tree.accept(new TypeAnnotationsValidator(sigOnly));
5121     }
5122     //where
5123     private final class TypeAnnotationsValidator extends TreeScanner {
5124 
5125         private final boolean sigOnly;
5126         public TypeAnnotationsValidator(boolean sigOnly) {
5127             this.sigOnly = sigOnly;
5128         }
5129 
5130         public void visitAnnotation(JCAnnotation tree) {
5131             chk.validateTypeAnnotation(tree, false);
5132             super.visitAnnotation(tree);
5133         }
5134         public void visitAnnotatedType(JCAnnotatedType tree) {
5135             if (!tree.underlyingType.type.isErroneous()) {
5136                 super.visitAnnotatedType(tree);
5137             }
5138         }
5139         public void visitTypeParameter(JCTypeParameter tree) {
5140             chk.validateTypeAnnotations(tree.annotations, true);
5141             scan(tree.bounds);
5142             // Don't call super.
5143             // This is needed because above we call validateTypeAnnotation with
5144             // false, which would forbid annotations on type parameters.
5145             // super.visitTypeParameter(tree);
5146         }
5147         public void visitMethodDef(JCMethodDecl tree) {
5148             if (tree.recvparam != null &&
5149                     !tree.recvparam.vartype.type.isErroneous()) {
5150                 checkForDeclarationAnnotations(tree.recvparam.mods.annotations,
5151                         tree.recvparam.vartype.type.tsym);
5152             }
5153             if (tree.restype != null && tree.restype.type != null) {
5154                 validateAnnotatedType(tree.restype, tree.restype.type);
5155             }
5156             if (sigOnly) {
5157                 scan(tree.mods);
5158                 scan(tree.restype);
5159                 scan(tree.typarams);
5160                 scan(tree.recvparam);
5161                 scan(tree.params);
5162                 scan(tree.thrown);
5163             } else {
5164                 scan(tree.defaultValue);
5165                 scan(tree.body);
5166             }
5167         }
5168         public void visitVarDef(final JCVariableDecl tree) {
5169             //System.err.println("validateTypeAnnotations.visitVarDef " + tree);
5170             if (tree.sym != null && tree.sym.type != null && !tree.isImplicitlyTyped())
5171                 validateAnnotatedType(tree.vartype, tree.sym.type);
5172             scan(tree.mods);
5173             scan(tree.vartype);
5174             if (!sigOnly) {
5175                 scan(tree.init);
5176             }
5177         }
5178         public void visitTypeCast(JCTypeCast tree) {
5179             if (tree.clazz != null && tree.clazz.type != null)
5180                 validateAnnotatedType(tree.clazz, tree.clazz.type);
5181             super.visitTypeCast(tree);
5182         }
5183         public void visitTypeTest(JCInstanceOf tree) {
5184             if (tree.pattern != null && !(tree.pattern instanceof JCPattern) && tree.pattern.type != null)
5185                 validateAnnotatedType(tree.pattern, tree.pattern.type);
5186             super.visitTypeTest(tree);
5187         }
5188         public void visitNewClass(JCNewClass tree) {
5189             if (tree.clazz != null && tree.clazz.type != null) {
5190                 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
5191                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
5192                             tree.clazz.type.tsym);
5193                 }
5194                 if (tree.def != null) {
5195                     checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym);
5196                 }
5197 
5198                 validateAnnotatedType(tree.clazz, tree.clazz.type);
5199             }
5200             super.visitNewClass(tree);
5201         }
5202         public void visitNewArray(JCNewArray tree) {
5203             if (tree.elemtype != null && tree.elemtype.type != null) {
5204                 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
5205                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
5206                             tree.elemtype.type.tsym);
5207                 }
5208                 validateAnnotatedType(tree.elemtype, tree.elemtype.type);
5209             }
5210             super.visitNewArray(tree);
5211         }
5212         public void visitClassDef(JCClassDecl tree) {
5213             //System.err.println("validateTypeAnnotations.visitClassDef " + tree);
5214             if (sigOnly) {
5215                 scan(tree.mods);
5216                 scan(tree.typarams);
5217                 scan(tree.extending);
5218                 scan(tree.implementing);
5219             }
5220             for (JCTree member : tree.defs) {
5221                 if (member.hasTag(Tag.CLASSDEF)) {
5222                     continue;
5223                 }
5224                 scan(member);
5225             }
5226         }
5227         public void visitBlock(JCBlock tree) {
5228             if (!sigOnly) {
5229                 scan(tree.stats);
5230             }
5231         }
5232 
5233         /* I would want to model this after
5234          * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
5235          * and override visitSelect and visitTypeApply.
5236          * However, we only set the annotated type in the top-level type
5237          * of the symbol.
5238          * Therefore, we need to override each individual location where a type
5239          * can occur.
5240          */
5241         private void validateAnnotatedType(final JCTree errtree, final Type type) {
5242             //System.err.println("Attr.validateAnnotatedType: " + errtree + " type: " + type);
5243 
5244             if (type.isPrimitiveOrVoid()) {
5245                 return;
5246             }
5247 
5248             JCTree enclTr = errtree;
5249             Type enclTy = type;
5250 
5251             boolean repeat = true;
5252             while (repeat) {
5253                 if (enclTr.hasTag(TYPEAPPLY)) {
5254                     List<Type> tyargs = enclTy.getTypeArguments();
5255                     List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments();
5256                     if (trargs.length() > 0) {
5257                         // Nothing to do for diamonds
5258                         if (tyargs.length() == trargs.length()) {
5259                             for (int i = 0; i < tyargs.length(); ++i) {
5260                                 validateAnnotatedType(trargs.get(i), tyargs.get(i));
5261                             }
5262                         }
5263                         // If the lengths don't match, it's either a diamond
5264                         // or some nested type that redundantly provides
5265                         // type arguments in the tree.
5266                     }
5267 
5268                     // Look at the clazz part of a generic type
5269                     enclTr = ((JCTree.JCTypeApply)enclTr).clazz;
5270                 }
5271 
5272                 if (enclTr.hasTag(SELECT)) {
5273                     enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression();
5274                     if (enclTy != null &&
5275                             !enclTy.hasTag(NONE)) {
5276                         enclTy = enclTy.getEnclosingType();
5277                     }
5278                 } else if (enclTr.hasTag(ANNOTATED_TYPE)) {
5279                     JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr;
5280                     if (enclTy == null || enclTy.hasTag(NONE)) {
5281                         if (at.getAnnotations().size() == 1) {
5282                             log.error(at.underlyingType.pos(), Errors.CantTypeAnnotateScoping1(at.getAnnotations().head.attribute));
5283                         } else {
5284                             ListBuffer<Attribute.Compound> comps = new ListBuffer<>();
5285                             for (JCAnnotation an : at.getAnnotations()) {
5286                                 comps.add(an.attribute);
5287                             }
5288                             log.error(at.underlyingType.pos(), Errors.CantTypeAnnotateScoping(comps.toList()));
5289                         }
5290                         repeat = false;
5291                     }
5292                     enclTr = at.underlyingType;
5293                     // enclTy doesn't need to be changed
5294                 } else if (enclTr.hasTag(IDENT)) {
5295                     repeat = false;
5296                 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) {
5297                     JCWildcard wc = (JCWildcard) enclTr;
5298                     if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD ||
5299                             wc.getKind() == JCTree.Kind.SUPER_WILDCARD) {
5300                         validateAnnotatedType(wc.getBound(), wc.getBound().type);
5301                     } else {
5302                         // Nothing to do for UNBOUND
5303                     }
5304                     repeat = false;
5305                 } else if (enclTr.hasTag(TYPEARRAY)) {
5306                     JCArrayTypeTree art = (JCArrayTypeTree) enclTr;
5307                     validateAnnotatedType(art.getType(), art.elemtype.type);
5308                     repeat = false;
5309                 } else if (enclTr.hasTag(TYPEUNION)) {
5310                     JCTypeUnion ut = (JCTypeUnion) enclTr;
5311                     for (JCTree t : ut.getTypeAlternatives()) {
5312                         validateAnnotatedType(t, t.type);
5313                     }
5314                     repeat = false;
5315                 } else if (enclTr.hasTag(TYPEINTERSECTION)) {
5316                     JCTypeIntersection it = (JCTypeIntersection) enclTr;
5317                     for (JCTree t : it.getBounds()) {
5318                         validateAnnotatedType(t, t.type);
5319                     }
5320                     repeat = false;
5321                 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE ||
5322                            enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
5323                     repeat = false;
5324                 } else {
5325                     Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() +
5326                             " within: "+ errtree + " with kind: " + errtree.getKind());
5327                 }
5328             }
5329         }
5330 
5331         private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
5332                 Symbol sym) {
5333             // Ensure that no declaration annotations are present.
5334             // Note that a tree type might be an AnnotatedType with
5335             // empty annotations, if only declaration annotations were given.
5336             // This method will raise an error for such a type.
5337             for (JCAnnotation ai : annotations) {
5338                 if (!ai.type.isErroneous() &&
5339                         typeAnnotations.annotationTargetType(ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
5340                     log.error(ai.pos(), Errors.AnnotationTypeNotApplicableToType(ai.type));
5341                 }
5342             }
5343         }
5344     }
5345 
5346     // <editor-fold desc="post-attribution visitor">
5347 
5348     /**
5349      * Handle missing types/symbols in an AST. This routine is useful when
5350      * the compiler has encountered some errors (which might have ended up
5351      * terminating attribution abruptly); if the compiler is used in fail-over
5352      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
5353      * prevents NPE to be progagated during subsequent compilation steps.
5354      */
5355     public void postAttr(JCTree tree) {
5356         new PostAttrAnalyzer().scan(tree);
5357     }
5358 
5359     class PostAttrAnalyzer extends TreeScanner {
5360 
5361         private void initTypeIfNeeded(JCTree that) {
5362             if (that.type == null) {
5363                 if (that.hasTag(METHODDEF)) {
5364                     that.type = dummyMethodType((JCMethodDecl)that);
5365                 } else {
5366                     that.type = syms.unknownType;
5367                 }
5368             }
5369         }
5370 
5371         /* Construct a dummy method type. If we have a method declaration,
5372          * and the declared return type is void, then use that return type
5373          * instead of UNKNOWN to avoid spurious error messages in lambda
5374          * bodies (see:JDK-8041704).
5375          */
5376         private Type dummyMethodType(JCMethodDecl md) {
5377             Type restype = syms.unknownType;
5378             if (md != null && md.restype != null && md.restype.hasTag(TYPEIDENT)) {
5379                 JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype;
5380                 if (prim.typetag == VOID)
5381                     restype = syms.voidType;
5382             }
5383             return new MethodType(List.nil(), restype,
5384                                   List.nil(), syms.methodClass);
5385         }
5386         private Type dummyMethodType() {
5387             return dummyMethodType(null);
5388         }
5389 
5390         @Override
5391         public void scan(JCTree tree) {
5392             if (tree == null) return;
5393             if (tree instanceof JCExpression) {
5394                 initTypeIfNeeded(tree);
5395             }
5396             super.scan(tree);
5397         }
5398 
5399         @Override
5400         public void visitIdent(JCIdent that) {
5401             if (that.sym == null) {
5402                 that.sym = syms.unknownSymbol;
5403             }
5404         }
5405 
5406         @Override
5407         public void visitSelect(JCFieldAccess that) {
5408             if (that.sym == null) {
5409                 that.sym = syms.unknownSymbol;
5410             }
5411             super.visitSelect(that);
5412         }
5413 
5414         @Override
5415         public void visitClassDef(JCClassDecl that) {
5416             initTypeIfNeeded(that);
5417             if (that.sym == null) {
5418                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
5419             }
5420             super.visitClassDef(that);
5421         }
5422 
5423         @Override
5424         public void visitMethodDef(JCMethodDecl that) {
5425             initTypeIfNeeded(that);
5426             if (that.sym == null) {
5427                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
5428             }
5429             super.visitMethodDef(that);
5430         }
5431 
5432         @Override
5433         public void visitVarDef(JCVariableDecl that) {
5434             initTypeIfNeeded(that);
5435             if (that.sym == null) {
5436                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
5437                 that.sym.adr = 0;
5438             }
5439             if (that.vartype == null) {
5440                 that.vartype = make.at(Position.NOPOS).Erroneous();
5441             }
5442             super.visitVarDef(that);
5443         }
5444 
5445         @Override
5446         public void visitBindingPattern(JCBindingPattern that) {
5447             //initTypeIfNeeded(that);
5448             if (that.symbol == null) {
5449                 that.symbol = new BindingSymbol(that.name, that.type, syms.noSymbol);
5450                 that.symbol.adr = 0;
5451             }
5452             super.visitBindingPattern(that);
5453         }
5454 
5455         @Override
5456         public void visitNewClass(JCNewClass that) {
5457             if (that.constructor == null) {
5458                 that.constructor = new MethodSymbol(0, names.init,
5459                         dummyMethodType(), syms.noSymbol);
5460             }
5461             if (that.constructorType == null) {
5462                 that.constructorType = syms.unknownType;
5463             }
5464             super.visitNewClass(that);
5465         }
5466 
5467         @Override
5468         public void visitAssignop(JCAssignOp that) {
5469             if (that.operator == null) {
5470                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
5471                         -1, syms.noSymbol);
5472             }
5473             super.visitAssignop(that);
5474         }
5475 
5476         @Override
5477         public void visitBinary(JCBinary that) {
5478             if (that.operator == null) {
5479                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
5480                         -1, syms.noSymbol);
5481             }
5482             super.visitBinary(that);
5483         }
5484 
5485         @Override
5486         public void visitUnary(JCUnary that) {
5487             if (that.operator == null) {
5488                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
5489                         -1, syms.noSymbol);
5490             }
5491             super.visitUnary(that);
5492         }
5493 
5494         @Override
5495         public void visitReference(JCMemberReference that) {
5496             super.visitReference(that);
5497             if (that.sym == null) {
5498                 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
5499                         syms.noSymbol);
5500             }
5501         }
5502     }
5503     // </editor-fold>
5504 
5505     public void setPackageSymbols(JCExpression pid, Symbol pkg) {
5506         new TreeScanner() {
5507             Symbol packge = pkg;
5508             @Override
5509             public void visitIdent(JCIdent that) {
5510                 that.sym = packge;
5511             }
5512 
5513             @Override
5514             public void visitSelect(JCFieldAccess that) {
5515                 that.sym = packge;
5516                 packge = packge.owner;
5517                 super.visitSelect(that);
5518             }
5519         }.scan(pid);
5520     }
5521 
5522 }