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