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                TreeInfo.isThisQualifier(base)) &&
 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.setUpperBound(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 || tree.classDeclRemoved();
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                     if (params.head.isImplicitlyTyped()) {
2566                         setSyntheticVariableType(params.head, argType);
2567                     }
2568                     params.head.sym = null;
2569                     actuals = actuals.isEmpty() ?
2570                             actuals :
2571                             actuals.tail;
2572                     params = params.tail;
2573                 }
2574 
2575                 //attribute lambda parameters
2576                 attribStats(that.params, localEnv);
2577 
2578                 if (arityMismatch) {
2579                     resultInfo.checkContext.report(that, diags.fragment(Fragments.IncompatibleArgTypesInLambda));
2580                         result = that.type = types.createErrorType(currentTarget);
2581                         return;
2582                 }
2583             }
2584 
2585             //from this point on, no recovery is needed; if we are in assignment context
2586             //we will be able to attribute the whole lambda body, regardless of errors;
2587             //if we are in a 'check' method context, and the lambda is not compatible
2588             //with the target-type, it will be recovered anyway in Attr.checkId
2589             needsRecovery = false;
2590 
2591             ResultInfo bodyResultInfo = localEnv.info.returnResult =
2592                     lambdaBodyResult(that, lambdaType, resultInfo);
2593 
2594             if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
2595                 attribTree(that.getBody(), localEnv, bodyResultInfo);
2596             } else {
2597                 JCBlock body = (JCBlock)that.body;
2598                 attribStats(body.stats, localEnv);
2599             }
2600 
2601             result = check(that, currentTarget, KindSelector.VAL, resultInfo);
2602 
2603             boolean isSpeculativeRound =
2604                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2605 
2606             preFlow(that);
2607             flow.analyzeLambda(env, that, make, isSpeculativeRound);
2608 
2609             that.type = currentTarget; //avoids recovery at this stage
2610             checkLambdaCompatible(that, lambdaType, resultInfo.checkContext);
2611 
2612             if (!isSpeculativeRound) {
2613                 //add thrown types as bounds to the thrown types free variables if needed:
2614                 if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) {
2615                     List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make);
2616                     if(!checkExConstraints(inferredThrownTypes, lambdaType.getThrownTypes(), resultInfo.checkContext.inferenceContext())) {
2617                         log.error(that, Errors.IncompatibleThrownTypesInMref(lambdaType.getThrownTypes()));
2618                     }
2619                 }
2620 
2621                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget);
2622             }
2623             result = check(that, currentTarget, KindSelector.VAL, resultInfo);
2624         } catch (Types.FunctionDescriptorLookupError ex) {
2625             JCDiagnostic cause = ex.getDiagnostic();
2626             resultInfo.checkContext.report(that, cause);
2627             result = that.type = types.createErrorType(pt());
2628             return;
2629         } catch (Throwable t) {
2630             //when an unexpected exception happens, avoid attempts to attribute the same tree again
2631             //as that would likely cause the same exception again.
2632             needsRecovery = false;
2633             throw t;
2634         } finally {
2635             localEnv.info.scope.leave();
2636             if (needsRecovery) {
2637                 attribTree(that, env, recoveryInfo);
2638             }
2639         }
2640     }
2641     //where
2642         class TargetInfo {
2643             Type target;
2644             Type descriptor;
2645 
2646             public TargetInfo(Type target, Type descriptor) {
2647                 this.target = target;
2648                 this.descriptor = descriptor;
2649             }
2650         }
2651 
2652         TargetInfo getTargetInfo(JCPolyExpression that, ResultInfo resultInfo, List<Type> explicitParamTypes) {
2653             Type lambdaType;
2654             Type currentTarget = resultInfo.pt;
2655             if (resultInfo.pt != Type.recoveryType) {
2656                 /* We need to adjust the target. If the target is an
2657                  * intersection type, for example: SAM & I1 & I2 ...
2658                  * the target will be updated to SAM
2659                  */
2660                 currentTarget = targetChecker.visit(currentTarget, that);
2661                 if (!currentTarget.isIntersection()) {
2662                     if (explicitParamTypes != null) {
2663                         currentTarget = infer.instantiateFunctionalInterface(that,
2664                                 currentTarget, explicitParamTypes, resultInfo.checkContext);
2665                     }
2666                     currentTarget = types.removeWildcards(currentTarget);
2667                     lambdaType = types.findDescriptorType(currentTarget);
2668                 } else {
2669                     IntersectionClassType ict = (IntersectionClassType)currentTarget;
2670                     ListBuffer<Type> components = new ListBuffer<>();
2671                     for (Type bound : ict.getExplicitComponents()) {
2672                         if (explicitParamTypes != null) {
2673                             try {
2674                                 bound = infer.instantiateFunctionalInterface(that,
2675                                         bound, explicitParamTypes, resultInfo.checkContext);
2676                             } catch (FunctionDescriptorLookupError t) {
2677                                 // do nothing
2678                             }
2679                         }
2680                         bound = types.removeWildcards(bound);
2681                         components.add(bound);
2682                     }
2683                     currentTarget = types.makeIntersectionType(components.toList());
2684                     currentTarget.tsym.flags_field |= INTERFACE;
2685                     lambdaType = types.findDescriptorType(currentTarget);
2686                 }
2687 
2688             } else {
2689                 currentTarget = Type.recoveryType;
2690                 lambdaType = fallbackDescriptorType(that);
2691             }
2692             if (that.hasTag(LAMBDA) && lambdaType.hasTag(FORALL)) {
2693                 //lambda expression target desc cannot be a generic method
2694                 Fragment msg = Fragments.InvalidGenericLambdaTarget(lambdaType,
2695                                                                     kindName(currentTarget.tsym),
2696                                                                     currentTarget.tsym);
2697                 resultInfo.checkContext.report(that, diags.fragment(msg));
2698                 currentTarget = types.createErrorType(pt());
2699             }
2700             return new TargetInfo(currentTarget, lambdaType);
2701         }
2702 
2703         void preFlow(JCLambda tree) {
2704             new PostAttrAnalyzer() {
2705                 @Override
2706                 public void scan(JCTree tree) {
2707                     if (tree == null ||
2708                             (tree.type != null &&
2709                             tree.type == Type.stuckType)) {
2710                         //don't touch stuck expressions!
2711                         return;
2712                     }
2713                     super.scan(tree);
2714                 }
2715             }.scan(tree);
2716         }
2717 
2718         Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
2719 
2720             @Override
2721             public Type visitClassType(ClassType t, DiagnosticPosition pos) {
2722                 return t.isIntersection() ?
2723                         visitIntersectionClassType((IntersectionClassType)t, pos) : t;
2724             }
2725 
2726             public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
2727                 types.findDescriptorSymbol(makeNotionalInterface(ict, pos));
2728                 return ict;
2729             }
2730 
2731             private TypeSymbol makeNotionalInterface(IntersectionClassType ict, DiagnosticPosition pos) {
2732                 ListBuffer<Type> targs = new ListBuffer<>();
2733                 ListBuffer<Type> supertypes = new ListBuffer<>();
2734                 for (Type i : ict.interfaces_field) {
2735                     if (i.isParameterized()) {
2736                         targs.appendList(i.tsym.type.allparams());
2737                     }
2738                     supertypes.append(i.tsym.type);
2739                 }
2740                 IntersectionClassType notionalIntf = types.makeIntersectionType(supertypes.toList());
2741                 notionalIntf.allparams_field = targs.toList();
2742                 notionalIntf.tsym.flags_field |= INTERFACE;
2743                 return notionalIntf.tsym;
2744             }
2745         };
2746 
2747         private Type fallbackDescriptorType(JCExpression tree) {
2748             switch (tree.getTag()) {
2749                 case LAMBDA:
2750                     JCLambda lambda = (JCLambda)tree;
2751                     List<Type> argtypes = List.nil();
2752                     for (JCVariableDecl param : lambda.params) {
2753                         argtypes = param.vartype != null ?
2754                                 argtypes.append(param.vartype.type) :
2755                                 argtypes.append(syms.errType);
2756                     }
2757                     return new MethodType(argtypes, Type.recoveryType,
2758                             List.of(syms.throwableType), syms.methodClass);
2759                 case REFERENCE:
2760                     return new MethodType(List.nil(), Type.recoveryType,
2761                             List.of(syms.throwableType), syms.methodClass);
2762                 default:
2763                     Assert.error("Cannot get here!");
2764             }
2765             return null;
2766         }
2767 
2768         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
2769                 final InferenceContext inferenceContext, final Type... ts) {
2770             checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
2771         }
2772 
2773         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
2774                 final InferenceContext inferenceContext, final List<Type> ts) {
2775             if (inferenceContext.free(ts)) {
2776                 inferenceContext.addFreeTypeListener(ts,
2777                         solvedContext -> checkAccessibleTypes(pos, env, solvedContext, solvedContext.asInstTypes(ts)));
2778             } else {
2779                 for (Type t : ts) {
2780                     rs.checkAccessibleType(env, t);
2781                 }
2782             }
2783         }
2784 
2785         /**
2786          * Lambda/method reference have a special check context that ensures
2787          * that i.e. a lambda return type is compatible with the expected
2788          * type according to both the inherited context and the assignment
2789          * context.
2790          */
2791         class FunctionalReturnContext extends Check.NestedCheckContext {
2792 
2793             FunctionalReturnContext(CheckContext enclosingContext) {
2794                 super(enclosingContext);
2795             }
2796 
2797             @Override
2798             public boolean compatible(Type found, Type req, Warner warn) {
2799                 //return type must be compatible in both current context and assignment context
2800                 return chk.basicHandler.compatible(inferenceContext().asUndetVar(found), inferenceContext().asUndetVar(req), warn);
2801             }
2802 
2803             @Override
2804             public void report(DiagnosticPosition pos, JCDiagnostic details) {
2805                 enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleRetTypeInLambda(details)));
2806             }
2807         }
2808 
2809         class ExpressionLambdaReturnContext extends FunctionalReturnContext {
2810 
2811             JCExpression expr;
2812             boolean expStmtExpected;
2813 
2814             ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
2815                 super(enclosingContext);
2816                 this.expr = expr;
2817             }
2818 
2819             @Override
2820             public void report(DiagnosticPosition pos, JCDiagnostic details) {
2821                 if (expStmtExpected) {
2822                     enclosingContext.report(pos, diags.fragment(Fragments.StatExprExpected));
2823                 } else {
2824                     super.report(pos, details);
2825                 }
2826             }
2827 
2828             @Override
2829             public boolean compatible(Type found, Type req, Warner warn) {
2830                 //a void return is compatible with an expression statement lambda
2831                 if (req.hasTag(VOID)) {
2832                     expStmtExpected = true;
2833                     return TreeInfo.isExpressionStatement(expr);
2834                 } else {
2835                     return super.compatible(found, req, warn);
2836                 }
2837             }
2838         }
2839 
2840         ResultInfo lambdaBodyResult(JCLambda that, Type descriptor, ResultInfo resultInfo) {
2841             FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
2842                     new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
2843                     new FunctionalReturnContext(resultInfo.checkContext);
2844 
2845             return descriptor.getReturnType() == Type.recoveryType ?
2846                     recoveryInfo :
2847                     new ResultInfo(KindSelector.VAL,
2848                             descriptor.getReturnType(), funcContext);
2849         }
2850 
2851         /**
2852         * Lambda compatibility. Check that given return types, thrown types, parameter types
2853         * are compatible with the expected functional interface descriptor. This means that:
2854         * (i) parameter types must be identical to those of the target descriptor; (ii) return
2855         * types must be compatible with the return type of the expected descriptor.
2856         */
2857         void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) {
2858             Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
2859 
2860             //return values have already been checked - but if lambda has no return
2861             //values, we must ensure that void/value compatibility is correct;
2862             //this amounts at checking that, if a lambda body can complete normally,
2863             //the descriptor's return type must be void
2864             if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
2865                     !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
2866                 Fragment msg =
2867                         Fragments.IncompatibleRetTypeInLambda(Fragments.MissingRetVal(returnType));
2868                 checkContext.report(tree,
2869                                     diags.fragment(msg));
2870             }
2871 
2872             List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes());
2873             if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
2874                 checkContext.report(tree, diags.fragment(Fragments.IncompatibleArgTypesInLambda));
2875             }
2876         }
2877 
2878         /* Map to hold 'fake' clinit methods. If a lambda is used to initialize a
2879          * static field and that lambda has type annotations, these annotations will
2880          * also be stored at these fake clinit methods.
2881          *
2882          * LambdaToMethod also use fake clinit methods so they can be reused.
2883          * Also as LTM is a phase subsequent to attribution, the methods from
2884          * clinits can be safely removed by LTM to save memory.
2885          */
2886         private Map<ClassSymbol, MethodSymbol> clinits = new HashMap<>();
2887 
2888         public MethodSymbol removeClinit(ClassSymbol sym) {
2889             return clinits.remove(sym);
2890         }
2891 
2892         /* This method returns an environment to be used to attribute a lambda
2893          * expression.
2894          *
2895          * The owner of this environment is a method symbol. If the current owner
2896          * is not a method, for example if the lambda is used to initialize
2897          * a field, then if the field is:
2898          *
2899          * - an instance field, we use the first constructor.
2900          * - a static field, we create a fake clinit method.
2901          */
2902         public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
2903             Env<AttrContext> lambdaEnv;
2904             Symbol owner = env.info.scope.owner;
2905             if (owner.kind == VAR && owner.owner.kind == TYP) {
2906                 //field initializer
2907                 ClassSymbol enclClass = owner.enclClass();
2908                 Symbol newScopeOwner = env.info.scope.owner;
2909                 /* if the field isn't static, then we can get the first constructor
2910                  * and use it as the owner of the environment. This is what
2911                  * LTM code is doing to look for type annotations so we are fine.
2912                  */
2913                 if ((owner.flags() & STATIC) == 0) {
2914                     for (Symbol s : enclClass.members_field.getSymbolsByName(names.init)) {
2915                         newScopeOwner = s;
2916                         break;
2917                     }
2918                 } else {
2919                     /* if the field is static then we need to create a fake clinit
2920                      * method, this method can later be reused by LTM.
2921                      */
2922                     MethodSymbol clinit = clinits.get(enclClass);
2923                     if (clinit == null) {
2924                         Type clinitType = new MethodType(List.nil(),
2925                                 syms.voidType, List.nil(), syms.methodClass);
2926                         clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE,
2927                                 names.clinit, clinitType, enclClass);
2928                         clinit.params = List.nil();
2929                         clinits.put(enclClass, clinit);
2930                     }
2931                     newScopeOwner = clinit;
2932                 }
2933                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(newScopeOwner)));
2934             } else {
2935                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
2936             }
2937             return lambdaEnv;
2938         }
2939 
2940     @Override
2941     public void visitReference(final JCMemberReference that) {
2942         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
2943             if (pt().hasTag(NONE) && (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
2944                 //method reference only allowed in assignment or method invocation/cast context
2945                 log.error(that.pos(), Errors.UnexpectedMref);
2946             }
2947             result = that.type = types.createErrorType(pt());
2948             return;
2949         }
2950         final Env<AttrContext> localEnv = env.dup(that);
2951         try {
2952             //attribute member reference qualifier - if this is a constructor
2953             //reference, the expected kind must be a type
2954             Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
2955 
2956             if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
2957                 exprType = chk.checkConstructorRefType(that.expr, exprType);
2958                 if (!exprType.isErroneous() &&
2959                     exprType.isRaw() &&
2960                     that.typeargs != null) {
2961                     log.error(that.expr.pos(),
2962                               Errors.InvalidMref(Kinds.kindName(that.getMode()),
2963                                                  Fragments.MrefInferAndExplicitParams));
2964                     exprType = types.createErrorType(exprType);
2965                 }
2966             }
2967 
2968             if (exprType.isErroneous()) {
2969                 //if the qualifier expression contains problems,
2970                 //give up attribution of method reference
2971                 result = that.type = exprType;
2972                 return;
2973             }
2974 
2975             if (TreeInfo.isStaticSelector(that.expr, names)) {
2976                 //if the qualifier is a type, validate it; raw warning check is
2977                 //omitted as we don't know at this stage as to whether this is a
2978                 //raw selector (because of inference)
2979                 chk.validate(that.expr, env, false);
2980             } else {
2981                 Symbol lhsSym = TreeInfo.symbol(that.expr);
2982                 localEnv.info.selectSuper = lhsSym != null && lhsSym.name == names._super;
2983             }
2984             //attrib type-arguments
2985             List<Type> typeargtypes = List.nil();
2986             if (that.typeargs != null) {
2987                 typeargtypes = attribTypes(that.typeargs, localEnv);
2988             }
2989 
2990             boolean isTargetSerializable =
2991                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2992                     isSerializable(pt());
2993             TargetInfo targetInfo = getTargetInfo(that, resultInfo, null);
2994             Type currentTarget = targetInfo.target;
2995             Type desc = targetInfo.descriptor;
2996 
2997             setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
2998             List<Type> argtypes = desc.getParameterTypes();
2999             Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
3000 
3001             if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
3002                 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
3003             }
3004 
3005             Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
3006             List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
3007             try {
3008                 refResult = rs.resolveMemberReference(localEnv, that, that.expr.type,
3009                         that.name, argtypes, typeargtypes, targetInfo.descriptor, referenceCheck,
3010                         resultInfo.checkContext.inferenceContext(), rs.basicReferenceChooser);
3011             } finally {
3012                 resultInfo.checkContext.inferenceContext().rollback(saved_undet);
3013             }
3014 
3015             Symbol refSym = refResult.fst;
3016             Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
3017 
3018             /** this switch will need to go away and be replaced by the new RESOLUTION_TARGET testing
3019              *  JDK-8075541
3020              */
3021             if (refSym.kind != MTH) {
3022                 boolean targetError;
3023                 switch (refSym.kind) {
3024                     case ABSENT_MTH:
3025                     case MISSING_ENCL:
3026                         targetError = false;
3027                         break;
3028                     case WRONG_MTH:
3029                     case WRONG_MTHS:
3030                     case AMBIGUOUS:
3031                     case HIDDEN:
3032                     case STATICERR:
3033                         targetError = true;
3034                         break;
3035                     default:
3036                         Assert.error("unexpected result kind " + refSym.kind);
3037                         targetError = false;
3038                 }
3039 
3040                 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol())
3041                         .getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
3042                                 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
3043 
3044                 JCDiagnostic diag = diags.create(log.currentSource(), that,
3045                         targetError ?
3046                             Fragments.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag) :
3047                             Errors.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag));
3048 
3049                 if (targetError && currentTarget == Type.recoveryType) {
3050                     //a target error doesn't make sense during recovery stage
3051                     //as we don't know what actual parameter types are
3052                     result = that.type = currentTarget;
3053                     return;
3054                 } else {
3055                     if (targetError) {
3056                         resultInfo.checkContext.report(that, diag);
3057                     } else {
3058                         log.report(diag);
3059                     }
3060                     result = that.type = types.createErrorType(currentTarget);
3061                     return;
3062                 }
3063             }
3064 
3065             that.sym = refSym.isConstructor() ? refSym.baseSymbol() : refSym;
3066             that.kind = lookupHelper.referenceKind(that.sym);
3067             that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
3068 
3069             if (desc.getReturnType() == Type.recoveryType) {
3070                 // stop here
3071                 result = that.type = currentTarget;
3072                 return;
3073             }
3074 
3075             if (!env.info.isSpeculative && that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3076                 Type enclosingType = exprType.getEnclosingType();
3077                 if (enclosingType != null && enclosingType.hasTag(CLASS)) {
3078                     // Check for the existence of an apropriate outer instance
3079                     rs.resolveImplicitThis(that.pos(), env, exprType);
3080                 }
3081             }
3082 
3083             if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
3084 
3085                 if (that.getMode() == ReferenceMode.INVOKE &&
3086                         TreeInfo.isStaticSelector(that.expr, names) &&
3087                         that.kind.isUnbound() &&
3088                         lookupHelper.site.isRaw()) {
3089                     chk.checkRaw(that.expr, localEnv);
3090                 }
3091 
3092                 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
3093                         exprType.getTypeArguments().nonEmpty()) {
3094                     //static ref with class type-args
3095                     log.error(that.expr.pos(),
3096                               Errors.InvalidMref(Kinds.kindName(that.getMode()),
3097                                                  Fragments.StaticMrefWithTargs));
3098                     result = that.type = types.createErrorType(currentTarget);
3099                     return;
3100                 }
3101 
3102                 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
3103                     // Check that super-qualified symbols are not abstract (JLS)
3104                     rs.checkNonAbstract(that.pos(), that.sym);
3105                 }
3106 
3107                 if (isTargetSerializable) {
3108                     chk.checkAccessFromSerializableElement(that, true);
3109                 }
3110             }
3111 
3112             ResultInfo checkInfo =
3113                     resultInfo.dup(newMethodTemplate(
3114                         desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
3115                         that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes),
3116                         new FunctionalReturnContext(resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
3117 
3118             Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
3119 
3120             if (that.kind.isUnbound() &&
3121                     resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
3122                 //re-generate inference constraints for unbound receiver
3123                 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) {
3124                     //cannot happen as this has already been checked - we just need
3125                     //to regenerate the inference constraints, as that has been lost
3126                     //as a result of the call to inferenceContext.save()
3127                     Assert.error("Can't get here");
3128                 }
3129             }
3130 
3131             if (!refType.isErroneous()) {
3132                 refType = types.createMethodTypeWithReturn(refType,
3133                         adjustMethodReturnType(refSym, lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
3134             }
3135 
3136             //go ahead with standard method reference compatibility check - note that param check
3137             //is a no-op (as this has been taken care during method applicability)
3138             boolean isSpeculativeRound =
3139                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
3140 
3141             that.type = currentTarget; //avoids recovery at this stage
3142             checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
3143             if (!isSpeculativeRound) {
3144                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget);
3145             }
3146             result = check(that, currentTarget, KindSelector.VAL, resultInfo);
3147         } catch (Types.FunctionDescriptorLookupError ex) {
3148             JCDiagnostic cause = ex.getDiagnostic();
3149             resultInfo.checkContext.report(that, cause);
3150             result = that.type = types.createErrorType(pt());
3151             return;
3152         }
3153     }
3154     //where
3155         ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
3156             //if this is a constructor reference, the expected kind must be a type
3157             return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ?
3158                                   KindSelector.VAL_TYP : KindSelector.TYP,
3159                                   Type.noType);
3160         }
3161 
3162 
3163     @SuppressWarnings("fallthrough")
3164     void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
3165         InferenceContext inferenceContext = checkContext.inferenceContext();
3166         Type returnType = inferenceContext.asUndetVar(descriptor.getReturnType());
3167 
3168         Type resType;
3169         switch (tree.getMode()) {
3170             case NEW:
3171                 if (!tree.expr.type.isRaw()) {
3172                     resType = tree.expr.type;
3173                     break;
3174                 }
3175             default:
3176                 resType = refType.getReturnType();
3177         }
3178 
3179         Type incompatibleReturnType = resType;
3180 
3181         if (returnType.hasTag(VOID)) {
3182             incompatibleReturnType = null;
3183         }
3184 
3185         if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
3186             if (resType.isErroneous() ||
3187                     new FunctionalReturnContext(checkContext).compatible(resType, returnType,
3188                             checkContext.checkWarner(tree, resType, returnType))) {
3189                 incompatibleReturnType = null;
3190             }
3191         }
3192 
3193         if (incompatibleReturnType != null) {
3194             Fragment msg =
3195                     Fragments.IncompatibleRetTypeInMref(Fragments.InconvertibleTypes(resType, descriptor.getReturnType()));
3196             checkContext.report(tree, diags.fragment(msg));
3197         } else {
3198             if (inferenceContext.free(refType)) {
3199                 // we need to wait for inference to finish and then replace inference vars in the referent type
3200                 inferenceContext.addFreeTypeListener(List.of(refType),
3201                         instantiatedContext -> {
3202                             tree.referentType = instantiatedContext.asInstType(refType);
3203                         });
3204             } else {
3205                 tree.referentType = refType;
3206             }
3207         }
3208 
3209         if (!speculativeAttr) {
3210             if (!checkExConstraints(refType.getThrownTypes(), descriptor.getThrownTypes(), inferenceContext)) {
3211                 log.error(tree, Errors.IncompatibleThrownTypesInMref(refType.getThrownTypes()));
3212             }
3213         }
3214     }
3215 
3216     boolean checkExConstraints(
3217             List<Type> thrownByFuncExpr,
3218             List<Type> thrownAtFuncType,
3219             InferenceContext inferenceContext) {
3220         /** 18.2.5: Otherwise, let E1, ..., En be the types in the function type's throws clause that
3221          *  are not proper types
3222          */
3223         List<Type> nonProperList = thrownAtFuncType.stream()
3224                 .filter(e -> inferenceContext.free(e)).collect(List.collector());
3225         List<Type> properList = thrownAtFuncType.diff(nonProperList);
3226 
3227         /** Let X1,...,Xm be the checked exception types that the lambda body can throw or
3228          *  in the throws clause of the invocation type of the method reference's compile-time
3229          *  declaration
3230          */
3231         List<Type> checkedList = thrownByFuncExpr.stream()
3232                 .filter(e -> chk.isChecked(e)).collect(List.collector());
3233 
3234         /** If n = 0 (the function type's throws clause consists only of proper types), then
3235          *  if there exists some i (1 <= i <= m) such that Xi is not a subtype of any proper type
3236          *  in the throws clause, the constraint reduces to false; otherwise, the constraint
3237          *  reduces to true
3238          */
3239         ListBuffer<Type> uncaughtByProperTypes = new ListBuffer<>();
3240         for (Type checked : checkedList) {
3241             boolean isSubtype = false;
3242             for (Type proper : properList) {
3243                 if (types.isSubtype(checked, proper)) {
3244                     isSubtype = true;
3245                     break;
3246                 }
3247             }
3248             if (!isSubtype) {
3249                 uncaughtByProperTypes.add(checked);
3250             }
3251         }
3252 
3253         if (nonProperList.isEmpty() && !uncaughtByProperTypes.isEmpty()) {
3254             return false;
3255         }
3256 
3257         /** If n > 0, the constraint reduces to a set of subtyping constraints:
3258          *  for all i (1 <= i <= m), if Xi is not a subtype of any proper type in the
3259          *  throws clause, then the constraints include, for all j (1 <= j <= n), <Xi <: Ej>
3260          */
3261         List<Type> nonProperAsUndet = inferenceContext.asUndetVars(nonProperList);
3262         uncaughtByProperTypes.forEach(checkedEx -> {
3263             nonProperAsUndet.forEach(nonProper -> {
3264                 types.isSubtype(checkedEx, nonProper);
3265             });
3266         });
3267 
3268         /** In addition, for all j (1 <= j <= n), the constraint reduces to the bound throws Ej
3269          */
3270         nonProperAsUndet.stream()
3271                 .filter(t -> t.hasTag(UNDETVAR))
3272                 .forEach(t -> ((UndetVar)t).setThrow());
3273         return true;
3274     }
3275 
3276     /**
3277      * Set functional type info on the underlying AST. Note: as the target descriptor
3278      * might contain inference variables, we might need to register an hook in the
3279      * current inference context.
3280      */
3281     private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
3282             final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
3283         if (checkContext.inferenceContext().free(descriptorType)) {
3284             checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType),
3285                     inferenceContext -> setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
3286                     inferenceContext.asInstType(primaryTarget), checkContext));
3287         } else {
3288             if (pt.hasTag(CLASS)) {
3289                 fExpr.target = primaryTarget;
3290             }
3291             if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3292                     pt != Type.recoveryType) {
3293                 //check that functional interface class is well-formed
3294                 try {
3295                     /* Types.makeFunctionalInterfaceClass() may throw an exception
3296                      * when it's executed post-inference. See the listener code
3297                      * above.
3298                      */
3299                     ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
3300                             names.empty, fExpr.target, ABSTRACT);
3301                     if (csym != null) {
3302                         chk.checkImplementations(env.tree, csym, csym);
3303                         try {
3304                             //perform an additional functional interface check on the synthetic class,
3305                             //as there may be spurious errors for raw targets - because of existing issues
3306                             //with membership and inheritance (see JDK-8074570).
3307                             csym.flags_field |= INTERFACE;
3308                             types.findDescriptorType(csym.type);
3309                         } catch (FunctionDescriptorLookupError err) {
3310                             resultInfo.checkContext.report(fExpr,
3311                                     diags.fragment(Fragments.NoSuitableFunctionalIntfInst(fExpr.target)));
3312                         }
3313                     }
3314                 } catch (Types.FunctionDescriptorLookupError ex) {
3315                     JCDiagnostic cause = ex.getDiagnostic();
3316                     resultInfo.checkContext.report(env.tree, cause);
3317                 }
3318             }
3319         }
3320     }
3321 
3322     public void visitParens(JCParens tree) {
3323         Type owntype = attribTree(tree.expr, env, resultInfo);
3324         result = check(tree, owntype, pkind(), resultInfo);
3325         Symbol sym = TreeInfo.symbol(tree);
3326         if (sym != null && sym.kind.matches(KindSelector.TYP_PCK))
3327             log.error(tree.pos(), Errors.IllegalParenthesizedExpression);
3328     }
3329 
3330     public void visitAssign(JCAssign tree) {
3331         Type owntype = attribTree(tree.lhs, env.dup(tree), varAssignmentInfo);
3332         Type capturedType = capture(owntype);
3333         attribExpr(tree.rhs, env, owntype);
3334         result = check(tree, capturedType, KindSelector.VAL, resultInfo);
3335     }
3336 
3337     public void visitAssignop(JCAssignOp tree) {
3338         // Attribute arguments.
3339         Type owntype = attribTree(tree.lhs, env, varAssignmentInfo);
3340         Type operand = attribExpr(tree.rhs, env);
3341         // Find operator.
3342         Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), owntype, operand);
3343         if (operator != operators.noOpSymbol &&
3344                 !owntype.isErroneous() &&
3345                 !operand.isErroneous()) {
3346             chk.checkDivZero(tree.rhs.pos(), operator, operand);
3347             chk.checkCastable(tree.rhs.pos(),
3348                               operator.type.getReturnType(),
3349                               owntype);
3350         }
3351         result = check(tree, owntype, KindSelector.VAL, resultInfo);
3352     }
3353 
3354     public void visitUnary(JCUnary tree) {
3355         // Attribute arguments.
3356         Type argtype = (tree.getTag().isIncOrDecUnaryOp())
3357             ? attribTree(tree.arg, env, varAssignmentInfo)
3358             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
3359 
3360         // Find operator.
3361         Symbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype);
3362         Type owntype = types.createErrorType(tree.type);
3363         if (operator != operators.noOpSymbol &&
3364                 !argtype.isErroneous()) {
3365             owntype = (tree.getTag().isIncOrDecUnaryOp())
3366                 ? tree.arg.type
3367                 : operator.type.getReturnType();
3368             int opc = ((OperatorSymbol)operator).opcode;
3369 
3370             // If the argument is constant, fold it.
3371             if (argtype.constValue() != null) {
3372                 Type ctype = cfolder.fold1(opc, argtype);
3373                 if (ctype != null) {
3374                     owntype = cfolder.coerce(ctype, owntype);
3375                 }
3376             }
3377         }
3378         result = check(tree, owntype, KindSelector.VAL, resultInfo);
3379     }
3380 
3381     public void visitBinary(JCBinary tree) {
3382         // Attribute arguments.
3383         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
3384         Type right = chk.checkNonVoid(tree.rhs.pos(), attribExpr(tree.rhs, env));
3385         // Find operator.
3386         Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag(), left, right);
3387         Type owntype = types.createErrorType(tree.type);
3388         if (operator != operators.noOpSymbol &&
3389                 !left.isErroneous() &&
3390                 !right.isErroneous()) {
3391             owntype = operator.type.getReturnType();
3392             int opc = ((OperatorSymbol)operator).opcode;
3393             // If both arguments are constants, fold them.
3394             if (left.constValue() != null && right.constValue() != null) {
3395                 Type ctype = cfolder.fold2(opc, left, right);
3396                 if (ctype != null) {
3397                     owntype = cfolder.coerce(ctype, owntype);
3398                 }
3399             }
3400 
3401             // Check that argument types of a reference ==, != are
3402             // castable to each other, (JLS 15.21).  Note: unboxing
3403             // comparisons will not have an acmp* opc at this point.
3404             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
3405                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
3406                     log.error(tree.pos(), Errors.IncomparableTypes(left, right));
3407                 }
3408             }
3409 
3410             chk.checkDivZero(tree.rhs.pos(), operator, right);
3411         }
3412         result = check(tree, owntype, KindSelector.VAL, resultInfo);
3413     }
3414 
3415     public void visitTypeCast(final JCTypeCast tree) {
3416         Type clazztype = attribType(tree.clazz, env);
3417         chk.validate(tree.clazz, env, false);
3418         //a fresh environment is required for 292 inference to work properly ---
3419         //see Infer.instantiatePolymorphicSignatureInstance()
3420         Env<AttrContext> localEnv = env.dup(tree);
3421         //should we propagate the target type?
3422         final ResultInfo castInfo;
3423         JCExpression expr = TreeInfo.skipParens(tree.expr);
3424         boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
3425         if (isPoly) {
3426             //expression is a poly - we need to propagate target type info
3427             castInfo = new ResultInfo(KindSelector.VAL, clazztype,
3428                                       new Check.NestedCheckContext(resultInfo.checkContext) {
3429                 @Override
3430                 public boolean compatible(Type found, Type req, Warner warn) {
3431                     return types.isCastable(found, req, warn);
3432                 }
3433             });
3434         } else {
3435             //standalone cast - target-type info is not propagated
3436             castInfo = unknownExprInfo;
3437         }
3438         Type exprtype = attribTree(tree.expr, localEnv, castInfo);
3439         Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3440         if (exprtype.constValue() != null)
3441             owntype = cfolder.coerce(exprtype, owntype);
3442         result = check(tree, capture(owntype), KindSelector.VAL, resultInfo);
3443         if (!isPoly)
3444             chk.checkRedundantCast(localEnv, tree);
3445     }
3446 
3447     public void visitTypeTest(JCInstanceOf tree) {
3448         Type exprtype = chk.checkNullOrRefType(
3449                 tree.expr.pos(), attribExpr(tree.expr, env));
3450         Type clazztype = attribType(tree.clazz, env);
3451         if (!clazztype.hasTag(TYPEVAR)) {
3452             clazztype = chk.checkClassOrArrayType(tree.clazz.pos(), clazztype);
3453         }
3454         if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
3455             log.error(tree.clazz.pos(), Errors.IllegalGenericTypeForInstof);
3456             clazztype = types.createErrorType(clazztype);
3457         }
3458         chk.validate(tree.clazz, env, false);
3459         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
3460         result = check(tree, syms.booleanType, KindSelector.VAL, resultInfo);
3461     }
3462 
3463     public void visitIndexed(JCArrayAccess tree) {
3464         Type owntype = types.createErrorType(tree.type);
3465         Type atype = attribExpr(tree.indexed, env);
3466         attribExpr(tree.index, env, syms.intType);
3467         if (types.isArray(atype))
3468             owntype = types.elemtype(atype);
3469         else if (!atype.hasTag(ERROR))
3470             log.error(tree.pos(), Errors.ArrayReqButFound(atype));
3471         if (!pkind().contains(KindSelector.VAL))
3472             owntype = capture(owntype);
3473         result = check(tree, owntype, KindSelector.VAR, resultInfo);
3474     }
3475 
3476     public void visitIdent(JCIdent tree) {
3477         Symbol sym;
3478 
3479         // Find symbol
3480         if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
3481             // If we are looking for a method, the prototype `pt' will be a
3482             // method type with the type of the call's arguments as parameters.
3483             env.info.pendingResolutionPhase = null;
3484             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
3485         } else if (tree.sym != null && tree.sym.kind != VAR) {
3486             sym = tree.sym;
3487         } else {
3488             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
3489         }
3490         tree.sym = sym;
3491 
3492         // (1) Also find the environment current for the class where
3493         //     sym is defined (`symEnv').
3494         // Only for pre-tiger versions (1.4 and earlier):
3495         // (2) Also determine whether we access symbol out of an anonymous
3496         //     class in a this or super call.  This is illegal for instance
3497         //     members since such classes don't carry a this$n link.
3498         //     (`noOuterThisPath').
3499         Env<AttrContext> symEnv = env;
3500         boolean noOuterThisPath = false;
3501         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
3502             sym.kind.matches(KindSelector.VAL_MTH) &&
3503             sym.owner.kind == TYP &&
3504             tree.name != names._this && tree.name != names._super) {
3505 
3506             // Find environment in which identifier is defined.
3507             while (symEnv.outer != null &&
3508                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
3509                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
3510                     noOuterThisPath = false;
3511                 symEnv = symEnv.outer;
3512             }
3513         }
3514 
3515         // If symbol is a variable, ...
3516         if (sym.kind == VAR) {
3517             VarSymbol v = (VarSymbol)sym;
3518 
3519             // ..., evaluate its initializer, if it has one, and check for
3520             // illegal forward reference.
3521             checkInit(tree, env, v, false);
3522 
3523             // If we are expecting a variable (as opposed to a value), check
3524             // that the variable is assignable in the current environment.
3525             if (KindSelector.ASG.subset(pkind()))
3526                 checkAssignable(tree.pos(), v, null, env);
3527         }
3528 
3529         // In a constructor body,
3530         // if symbol is a field or instance method, check that it is
3531         // not accessed before the supertype constructor is called.
3532         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
3533             sym.kind.matches(KindSelector.VAL_MTH) &&
3534             sym.owner.kind == TYP &&
3535             (sym.flags() & STATIC) == 0) {
3536             chk.earlyRefError(tree.pos(), sym.kind == VAR ?
3537                                           sym : thisSym(tree.pos(), env));
3538         }
3539         Env<AttrContext> env1 = env;
3540         if (sym.kind != ERR && sym.kind != TYP &&
3541             sym.owner != null && sym.owner != env1.enclClass.sym) {
3542             // If the found symbol is inaccessible, then it is
3543             // accessed through an enclosing instance.  Locate this
3544             // enclosing instance:
3545             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
3546                 env1 = env1.outer;
3547         }
3548 
3549         if (env.info.isSerializable) {
3550             chk.checkAccessFromSerializableElement(tree, env.info.isLambda);
3551         }
3552 
3553         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
3554     }
3555 
3556     public void visitSelect(JCFieldAccess tree) {
3557         // Determine the expected kind of the qualifier expression.
3558         KindSelector skind = KindSelector.NIL;
3559         if (tree.name == names._this || tree.name == names._super ||
3560                 tree.name == names._class)
3561         {
3562             skind = KindSelector.TYP;
3563         } else {
3564             if (pkind().contains(KindSelector.PCK))
3565                 skind = KindSelector.of(skind, KindSelector.PCK);
3566             if (pkind().contains(KindSelector.TYP))
3567                 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
3568             if (pkind().contains(KindSelector.VAL_MTH))
3569                 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
3570         }
3571 
3572         // Attribute the qualifier expression, and determine its symbol (if any).
3573         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
3574         if (!pkind().contains(KindSelector.TYP_PCK))
3575             site = capture(site); // Capture field access
3576 
3577         // don't allow T.class T[].class, etc
3578         if (skind == KindSelector.TYP) {
3579             Type elt = site;
3580             while (elt.hasTag(ARRAY))
3581                 elt = ((ArrayType)elt).elemtype;
3582             if (elt.hasTag(TYPEVAR)) {
3583                 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
3584                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
3585                 tree.sym = tree.type.tsym;
3586                 return ;
3587             }
3588         }
3589 
3590         // If qualifier symbol is a type or `super', assert `selectSuper'
3591         // for the selection. This is relevant for determining whether
3592         // protected symbols are accessible.
3593         Symbol sitesym = TreeInfo.symbol(tree.selected);
3594         boolean selectSuperPrev = env.info.selectSuper;
3595         env.info.selectSuper =
3596             sitesym != null &&
3597             sitesym.name == names._super;
3598 
3599         // Determine the symbol represented by the selection.
3600         env.info.pendingResolutionPhase = null;
3601         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
3602         if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
3603             log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym));
3604             sym = syms.errSymbol;
3605         }
3606         if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
3607             site = capture(site);
3608             sym = selectSym(tree, sitesym, site, env, resultInfo);
3609         }
3610         boolean varArgs = env.info.lastResolveVarargs();
3611         tree.sym = sym;
3612 
3613         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
3614             site = types.skipTypeVars(site, true);
3615         }
3616 
3617         // If that symbol is a variable, ...
3618         if (sym.kind == VAR) {
3619             VarSymbol v = (VarSymbol)sym;
3620 
3621             // ..., evaluate its initializer, if it has one, and check for
3622             // illegal forward reference.
3623             checkInit(tree, env, v, true);
3624 
3625             // If we are expecting a variable (as opposed to a value), check
3626             // that the variable is assignable in the current environment.
3627             if (KindSelector.ASG.subset(pkind()))
3628                 checkAssignable(tree.pos(), v, tree.selected, env);
3629         }
3630 
3631         if (sitesym != null &&
3632                 sitesym.kind == VAR &&
3633                 ((VarSymbol)sitesym).isResourceVariable() &&
3634                 sym.kind == MTH &&
3635                 sym.name.equals(names.close) &&
3636                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
3637                 env.info.lint.isEnabled(LintCategory.TRY)) {
3638             log.warning(LintCategory.TRY, tree, Warnings.TryExplicitCloseCall);
3639         }
3640 
3641         // Disallow selecting a type from an expression
3642         if (isType(sym) && (sitesym == null || !sitesym.kind.matches(KindSelector.TYP_PCK))) {
3643             tree.type = check(tree.selected, pt(),
3644                               sitesym == null ?
3645                                       KindSelector.VAL : sitesym.kind.toSelector(),
3646                               new ResultInfo(KindSelector.TYP_PCK, pt()));
3647         }
3648 
3649         if (isType(sitesym)) {
3650             if (sym.name == names._this) {
3651                 // If `C' is the currently compiled class, check that
3652                 // C.this' does not appear in a call to a super(...)
3653                 if (env.info.isSelfCall &&
3654                     site.tsym == env.enclClass.sym) {
3655                     chk.earlyRefError(tree.pos(), sym);
3656                 }
3657             } else {
3658                 // Check if type-qualified fields or methods are static (JLS)
3659                 if ((sym.flags() & STATIC) == 0 &&
3660                     sym.name != names._super &&
3661                     (sym.kind == VAR || sym.kind == MTH)) {
3662                     rs.accessBase(rs.new StaticError(sym),
3663                               tree.pos(), site, sym.name, true);
3664                 }
3665             }
3666             if (!allowStaticInterfaceMethods && sitesym.isInterface() &&
3667                     sym.isStatic() && sym.kind == MTH) {
3668                 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.pos(), Feature.STATIC_INTERFACE_METHODS_INVOKE.error(sourceName));
3669             }
3670         } else if (sym.kind != ERR &&
3671                    (sym.flags() & STATIC) != 0 &&
3672                    sym.name != names._class) {
3673             // If the qualified item is not a type and the selected item is static, report
3674             // a warning. Make allowance for the class of an array type e.g. Object[].class)
3675             chk.warnStatic(tree, Warnings.StaticNotQualifiedByType(sym.kind.kindName(), sym.owner));
3676         }
3677 
3678         // If we are selecting an instance member via a `super', ...
3679         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
3680 
3681             // Check that super-qualified symbols are not abstract (JLS)
3682             rs.checkNonAbstract(tree.pos(), sym);
3683 
3684             if (site.isRaw()) {
3685                 // Determine argument types for site.
3686                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
3687                 if (site1 != null) site = site1;
3688             }
3689         }
3690 
3691         if (env.info.isSerializable) {
3692             chk.checkAccessFromSerializableElement(tree, env.info.isLambda);
3693         }
3694 
3695         env.info.selectSuper = selectSuperPrev;
3696         result = checkId(tree, site, sym, env, resultInfo);
3697     }
3698     //where
3699         /** Determine symbol referenced by a Select expression,
3700          *
3701          *  @param tree   The select tree.
3702          *  @param site   The type of the selected expression,
3703          *  @param env    The current environment.
3704          *  @param resultInfo The current result.
3705          */
3706         private Symbol selectSym(JCFieldAccess tree,
3707                                  Symbol location,
3708                                  Type site,
3709                                  Env<AttrContext> env,
3710                                  ResultInfo resultInfo) {
3711             DiagnosticPosition pos = tree.pos();
3712             Name name = tree.name;
3713             switch (site.getTag()) {
3714             case PACKAGE:
3715                 return rs.accessBase(
3716                     rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
3717                     pos, location, site, name, true);
3718             case ARRAY:
3719             case CLASS:
3720                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
3721                     return rs.resolveQualifiedMethod(
3722                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
3723                 } else if (name == names._this || name == names._super) {
3724                     return rs.resolveSelf(pos, env, site.tsym, name);
3725                 } else if (name == names._class) {
3726                     // In this case, we have already made sure in
3727                     // visitSelect that qualifier expression is a type.
3728                     return syms.getClassField(site, types);
3729                 } else {
3730                     // We are seeing a plain identifier as selector.
3731                     Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
3732                         sym = rs.accessBase(sym, pos, location, site, name, true);
3733                     return sym;
3734                 }
3735             case WILDCARD:
3736                 throw new AssertionError(tree);
3737             case TYPEVAR:
3738                 // Normally, site.getUpperBound() shouldn't be null.
3739                 // It should only happen during memberEnter/attribBase
3740                 // when determining the super type which *must* beac
3741                 // done before attributing the type variables.  In
3742                 // other words, we are seeing this illegal program:
3743                 // class B<T> extends A<T.foo> {}
3744                 Symbol sym = (site.getUpperBound() != null)
3745                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
3746                     : null;
3747                 if (sym == null) {
3748                     log.error(pos, Errors.TypeVarCantBeDeref);
3749                     return syms.errSymbol;
3750                 } else {
3751                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
3752                         rs.new AccessError(env, site, sym) :
3753                                 sym;
3754                     rs.accessBase(sym2, pos, location, site, name, true);
3755                     return sym;
3756                 }
3757             case ERROR:
3758                 // preserve identifier names through errors
3759                 return types.createErrorType(name, site.tsym, site).tsym;
3760             default:
3761                 // The qualifier expression is of a primitive type -- only
3762                 // .class is allowed for these.
3763                 if (name == names._class) {
3764                     // In this case, we have already made sure in Select that
3765                     // qualifier expression is a type.
3766                     return syms.getClassField(site, types);
3767                 } else {
3768                     log.error(pos, Errors.CantDeref(site));
3769                     return syms.errSymbol;
3770                 }
3771             }
3772         }
3773 
3774         /** Determine type of identifier or select expression and check that
3775          *  (1) the referenced symbol is not deprecated
3776          *  (2) the symbol's type is safe (@see checkSafe)
3777          *  (3) if symbol is a variable, check that its type and kind are
3778          *      compatible with the prototype and protokind.
3779          *  (4) if symbol is an instance field of a raw type,
3780          *      which is being assigned to, issue an unchecked warning if its
3781          *      type changes under erasure.
3782          *  (5) if symbol is an instance method of a raw type, issue an
3783          *      unchecked warning if its argument types change under erasure.
3784          *  If checks succeed:
3785          *    If symbol is a constant, return its constant type
3786          *    else if symbol is a method, return its result type
3787          *    otherwise return its type.
3788          *  Otherwise return errType.
3789          *
3790          *  @param tree       The syntax tree representing the identifier
3791          *  @param site       If this is a select, the type of the selected
3792          *                    expression, otherwise the type of the current class.
3793          *  @param sym        The symbol representing the identifier.
3794          *  @param env        The current environment.
3795          *  @param resultInfo    The expected result
3796          */
3797         Type checkId(JCTree tree,
3798                      Type site,
3799                      Symbol sym,
3800                      Env<AttrContext> env,
3801                      ResultInfo resultInfo) {
3802             return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
3803                     checkMethodIdInternal(tree, site, sym, env, resultInfo) :
3804                     checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3805         }
3806 
3807         Type checkMethodIdInternal(JCTree tree,
3808                      Type site,
3809                      Symbol sym,
3810                      Env<AttrContext> env,
3811                      ResultInfo resultInfo) {
3812             if (resultInfo.pkind.contains(KindSelector.POLY)) {
3813                 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
3814                 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
3815                 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
3816                 return owntype;
3817             } else {
3818                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
3819             }
3820         }
3821 
3822         Type checkIdInternal(JCTree tree,
3823                      Type site,
3824                      Symbol sym,
3825                      Type pt,
3826                      Env<AttrContext> env,
3827                      ResultInfo resultInfo) {
3828             if (pt.isErroneous()) {
3829                 return types.createErrorType(site);
3830             }
3831             Type owntype; // The computed type of this identifier occurrence.
3832             switch (sym.kind) {
3833             case TYP:
3834                 // For types, the computed type equals the symbol's type,
3835                 // except for two situations:
3836                 owntype = sym.type;
3837                 if (owntype.hasTag(CLASS)) {
3838                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
3839                     Type ownOuter = owntype.getEnclosingType();
3840 
3841                     // (a) If the symbol's type is parameterized, erase it
3842                     // because no type parameters were given.
3843                     // We recover generic outer type later in visitTypeApply.
3844                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
3845                         owntype = types.erasure(owntype);
3846                     }
3847 
3848                     // (b) If the symbol's type is an inner class, then
3849                     // we have to interpret its outer type as a superclass
3850                     // of the site type. Example:
3851                     //
3852                     // class Tree<A> { class Visitor { ... } }
3853                     // class PointTree extends Tree<Point> { ... }
3854                     // ...PointTree.Visitor...
3855                     //
3856                     // Then the type of the last expression above is
3857                     // Tree<Point>.Visitor.
3858                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
3859                         Type normOuter = site;
3860                         if (normOuter.hasTag(CLASS)) {
3861                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
3862                         }
3863                         if (normOuter == null) // perhaps from an import
3864                             normOuter = types.erasure(ownOuter);
3865                         if (normOuter != ownOuter)
3866                             owntype = new ClassType(
3867                                 normOuter, List.nil(), owntype.tsym,
3868                                 owntype.getMetadata());
3869                     }
3870                 }
3871                 break;
3872             case VAR:
3873                 VarSymbol v = (VarSymbol)sym;
3874 
3875                 if (env.info.enclVar != null
3876                         && v.type.hasTag(NONE)) {
3877                     //self reference to implicitly typed variable declaration
3878                     log.error(TreeInfo.positionFor(v, env.enclClass), Errors.CantInferLocalVarType(v.name, Fragments.LocalSelfRef));
3879                     return v.type = types.createErrorType(v.type);
3880                 }
3881 
3882                 // Test (4): if symbol is an instance field of a raw type,
3883                 // which is being assigned to, issue an unchecked warning if
3884                 // its type changes under erasure.
3885                 if (KindSelector.ASG.subset(pkind()) &&
3886                     v.owner.kind == TYP &&
3887                     (v.flags() & STATIC) == 0 &&
3888                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
3889                     Type s = types.asOuterSuper(site, v.owner);
3890                     if (s != null &&
3891                         s.isRaw() &&
3892                         !types.isSameType(v.type, v.erasure(types))) {
3893                         chk.warnUnchecked(tree.pos(), Warnings.UncheckedAssignToVar(v, s));
3894                     }
3895                 }
3896                 // The computed type of a variable is the type of the
3897                 // variable symbol, taken as a member of the site type.
3898                 owntype = (sym.owner.kind == TYP &&
3899                            sym.name != names._this && sym.name != names._super)
3900                     ? types.memberType(site, sym)
3901                     : sym.type;
3902 
3903                 // If the variable is a constant, record constant value in
3904                 // computed type.
3905                 if (v.getConstValue() != null && isStaticReference(tree))
3906                     owntype = owntype.constType(v.getConstValue());
3907 
3908                 if (resultInfo.pkind == KindSelector.VAL) {
3909                     owntype = capture(owntype); // capture "names as expressions"
3910                 }
3911                 break;
3912             case MTH: {
3913                 owntype = checkMethod(site, sym,
3914                         new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext, resultInfo.checkMode),
3915                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
3916                         resultInfo.pt.getTypeArguments());
3917                 break;
3918             }
3919             case PCK: case ERR:
3920                 owntype = sym.type;
3921                 break;
3922             default:
3923                 throw new AssertionError("unexpected kind: " + sym.kind +
3924                                          " in tree " + tree);
3925             }
3926 
3927             // Emit a `deprecation' warning if symbol is deprecated.
3928             // (for constructors (but not for constructor references), the error
3929             // was given when the constructor was resolved)
3930 
3931             if (sym.name != names.init || tree.hasTag(REFERENCE)) {
3932                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
3933                 chk.checkSunAPI(tree.pos(), sym);
3934                 chk.checkProfile(tree.pos(), sym);
3935             }
3936 
3937             // If symbol is a variable, check that its type and
3938             // kind are compatible with the prototype and protokind.
3939             return check(tree, owntype, sym.kind.toSelector(), resultInfo);
3940         }
3941 
3942         /** Check that variable is initialized and evaluate the variable's
3943          *  initializer, if not yet done. Also check that variable is not
3944          *  referenced before it is defined.
3945          *  @param tree    The tree making up the variable reference.
3946          *  @param env     The current environment.
3947          *  @param v       The variable's symbol.
3948          */
3949         private void checkInit(JCTree tree,
3950                                Env<AttrContext> env,
3951                                VarSymbol v,
3952                                boolean onlyWarning) {
3953             // A forward reference is diagnosed if the declaration position
3954             // of the variable is greater than the current tree position
3955             // and the tree and variable definition occur in the same class
3956             // definition.  Note that writes don't count as references.
3957             // This check applies only to class and instance
3958             // variables.  Local variables follow different scope rules,
3959             // and are subject to definite assignment checking.
3960             Env<AttrContext> initEnv = enclosingInitEnv(env);
3961             if (initEnv != null &&
3962                 (initEnv.info.enclVar == v || v.pos > tree.pos) &&
3963                 v.owner.kind == TYP &&
3964                 v.owner == env.info.scope.owner.enclClass() &&
3965                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
3966                 (!env.tree.hasTag(ASSIGN) ||
3967                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
3968                 if (!onlyWarning || isStaticEnumField(v)) {
3969                     Error errkey = (initEnv.info.enclVar == v) ?
3970                                 Errors.IllegalSelfRef : Errors.IllegalForwardRef;
3971                     log.error(tree.pos(), errkey);
3972                 } else if (useBeforeDeclarationWarning) {
3973                     Warning warnkey = (initEnv.info.enclVar == v) ?
3974                                 Warnings.SelfRef(v) : Warnings.ForwardRef(v);
3975                     log.warning(tree.pos(), warnkey);
3976                 }
3977             }
3978 
3979             v.getConstValue(); // ensure initializer is evaluated
3980 
3981             checkEnumInitializer(tree, env, v);
3982         }
3983 
3984         /**
3985          * Returns the enclosing init environment associated with this env (if any). An init env
3986          * can be either a field declaration env or a static/instance initializer env.
3987          */
3988         Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) {
3989             while (true) {
3990                 switch (env.tree.getTag()) {
3991                     case VARDEF:
3992                         JCVariableDecl vdecl = (JCVariableDecl)env.tree;
3993                         if (vdecl.sym.owner.kind == TYP) {
3994                             //field
3995                             return env;
3996                         }
3997                         break;
3998                     case BLOCK:
3999                         if (env.next.tree.hasTag(CLASSDEF)) {
4000                             //instance/static initializer
4001                             return env;
4002                         }
4003                         break;
4004                     case METHODDEF:
4005                     case CLASSDEF:
4006                     case TOPLEVEL:
4007                         return null;
4008                 }
4009                 Assert.checkNonNull(env.next);
4010                 env = env.next;
4011             }
4012         }
4013 
4014         /**
4015          * Check for illegal references to static members of enum.  In
4016          * an enum type, constructors and initializers may not
4017          * reference its static members unless they are constant.
4018          *
4019          * @param tree    The tree making up the variable reference.
4020          * @param env     The current environment.
4021          * @param v       The variable's symbol.
4022          * @jls  section 8.9 Enums
4023          */
4024         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
4025             // JLS:
4026             //
4027             // "It is a compile-time error to reference a static field
4028             // of an enum type that is not a compile-time constant
4029             // (15.28) from constructors, instance initializer blocks,
4030             // or instance variable initializer expressions of that
4031             // type. It is a compile-time error for the constructors,
4032             // instance initializer blocks, or instance variable
4033             // initializer expressions of an enum constant e to refer
4034             // to itself or to an enum constant of the same type that
4035             // is declared to the right of e."
4036             if (isStaticEnumField(v)) {
4037                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
4038 
4039                 if (enclClass == null || enclClass.owner == null)
4040                     return;
4041 
4042                 // See if the enclosing class is the enum (or a
4043                 // subclass thereof) declaring v.  If not, this
4044                 // reference is OK.
4045                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
4046                     return;
4047 
4048                 // If the reference isn't from an initializer, then
4049                 // the reference is OK.
4050                 if (!Resolve.isInitializer(env))
4051                     return;
4052 
4053                 log.error(tree.pos(), Errors.IllegalEnumStaticRef);
4054             }
4055         }
4056 
4057         /** Is the given symbol a static, non-constant field of an Enum?
4058          *  Note: enum literals should not be regarded as such
4059          */
4060         private boolean isStaticEnumField(VarSymbol v) {
4061             return Flags.isEnum(v.owner) &&
4062                    Flags.isStatic(v) &&
4063                    !Flags.isConstant(v) &&
4064                    v.name != names._class;
4065         }
4066 
4067     /**
4068      * Check that method arguments conform to its instantiation.
4069      **/
4070     public Type checkMethod(Type site,
4071                             final Symbol sym,
4072                             ResultInfo resultInfo,
4073                             Env<AttrContext> env,
4074                             final List<JCExpression> argtrees,
4075                             List<Type> argtypes,
4076                             List<Type> typeargtypes) {
4077         // Test (5): if symbol is an instance method of a raw type, issue
4078         // an unchecked warning if its argument types change under erasure.
4079         if ((sym.flags() & STATIC) == 0 &&
4080             (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
4081             Type s = types.asOuterSuper(site, sym.owner);
4082             if (s != null && s.isRaw() &&
4083                 !types.isSameTypes(sym.type.getParameterTypes(),
4084                                    sym.erasure(types).getParameterTypes())) {
4085                 chk.warnUnchecked(env.tree.pos(), Warnings.UncheckedCallMbrOfRawType(sym, s));
4086             }
4087         }
4088 
4089         if (env.info.defaultSuperCallSite != null) {
4090             for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
4091                 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
4092                         types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
4093                 List<MethodSymbol> icand_sup =
4094                         types.interfaceCandidates(sup, (MethodSymbol)sym);
4095                 if (icand_sup.nonEmpty() &&
4096                         icand_sup.head != sym &&
4097                         icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
4098                     log.error(env.tree.pos(),
4099                               Errors.IllegalDefaultSuperCall(env.info.defaultSuperCallSite, Fragments.OverriddenDefault(sym, sup)));
4100                     break;
4101                 }
4102             }
4103             env.info.defaultSuperCallSite = null;
4104         }
4105 
4106         if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
4107             JCMethodInvocation app = (JCMethodInvocation)env.tree;
4108             if (app.meth.hasTag(SELECT) &&
4109                     !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
4110                 log.error(env.tree.pos(), Errors.IllegalStaticIntfMethCall(site));
4111             }
4112         }
4113 
4114         // Compute the identifier's instantiated type.
4115         // For methods, we need to compute the instance type by
4116         // Resolve.instantiate from the symbol's type as well as
4117         // any type arguments and value arguments.
4118         Warner noteWarner = new Warner();
4119         try {
4120             Type owntype = rs.checkMethod(
4121                     env,
4122                     site,
4123                     sym,
4124                     resultInfo,
4125                     argtypes,
4126                     typeargtypes,
4127                     noteWarner);
4128 
4129             DeferredAttr.DeferredTypeMap checkDeferredMap =
4130                 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
4131 
4132             argtypes = argtypes.map(checkDeferredMap);
4133 
4134             if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
4135                 chk.warnUnchecked(env.tree.pos(), Warnings.UncheckedMethInvocationApplied(kindName(sym),
4136                         sym.name,
4137                         rs.methodArguments(sym.type.getParameterTypes()),
4138                         rs.methodArguments(argtypes.map(checkDeferredMap)),
4139                         kindName(sym.location()),
4140                         sym.location()));
4141                 if (resultInfo.pt != Infer.anyPoly ||
4142                         !owntype.hasTag(METHOD) ||
4143                         !owntype.isPartial()) {
4144                     //if this is not a partially inferred method type, erase return type. Otherwise,
4145                     //erasure is carried out in PartiallyInferredMethodType.check().
4146                     owntype = new MethodType(owntype.getParameterTypes(),
4147                             types.erasure(owntype.getReturnType()),
4148                             types.erasure(owntype.getThrownTypes()),
4149                             syms.methodClass);
4150                 }
4151             }
4152 
4153             PolyKind pkind = (sym.type.hasTag(FORALL) &&
4154                  sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
4155                  PolyKind.POLY : PolyKind.STANDALONE;
4156             TreeInfo.setPolyKind(env.tree, pkind);
4157 
4158             return (resultInfo.pt == Infer.anyPoly) ?
4159                     owntype :
4160                     chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
4161                             resultInfo.checkContext.inferenceContext());
4162         } catch (Infer.InferenceException ex) {
4163             //invalid target type - propagate exception outwards or report error
4164             //depending on the current check context
4165             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
4166             return types.createErrorType(site);
4167         } catch (Resolve.InapplicableMethodException ex) {
4168             final JCDiagnostic diag = ex.getDiagnostic();
4169             Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
4170                 @Override
4171                 protected Pair<Symbol, JCDiagnostic> errCandidate() {
4172                     return new Pair<>(sym, diag);
4173                 }
4174             };
4175             List<Type> argtypes2 = argtypes.map(
4176                     rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
4177             JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
4178                     env.tree, sym, site, sym.name, argtypes2, typeargtypes);
4179             log.report(errDiag);
4180             return types.createErrorType(site);
4181         }
4182     }
4183 
4184     public void visitLiteral(JCLiteral tree) {
4185         result = check(tree, litType(tree.typetag).constType(tree.value),
4186                 KindSelector.VAL, resultInfo);
4187     }
4188     //where
4189     /** Return the type of a literal with given type tag.
4190      */
4191     Type litType(TypeTag tag) {
4192         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
4193     }
4194 
4195     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
4196         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
4197     }
4198 
4199     public void visitTypeArray(JCArrayTypeTree tree) {
4200         Type etype = attribType(tree.elemtype, env);
4201         Type type = new ArrayType(etype, syms.arrayClass);
4202         result = check(tree, type, KindSelector.TYP, resultInfo);
4203     }
4204 
4205     /** Visitor method for parameterized types.
4206      *  Bound checking is left until later, since types are attributed
4207      *  before supertype structure is completely known
4208      */
4209     public void visitTypeApply(JCTypeApply tree) {
4210         Type owntype = types.createErrorType(tree.type);
4211 
4212         // Attribute functor part of application and make sure it's a class.
4213         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
4214 
4215         // Attribute type parameters
4216         List<Type> actuals = attribTypes(tree.arguments, env);
4217 
4218         if (clazztype.hasTag(CLASS)) {
4219             List<Type> formals = clazztype.tsym.type.getTypeArguments();
4220             if (actuals.isEmpty()) //diamond
4221                 actuals = formals;
4222 
4223             if (actuals.length() == formals.length()) {
4224                 List<Type> a = actuals;
4225                 List<Type> f = formals;
4226                 while (a.nonEmpty()) {
4227                     a.head = a.head.withTypeVar(f.head);
4228                     a = a.tail;
4229                     f = f.tail;
4230                 }
4231                 // Compute the proper generic outer
4232                 Type clazzOuter = clazztype.getEnclosingType();
4233                 if (clazzOuter.hasTag(CLASS)) {
4234                     Type site;
4235                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
4236                     if (clazz.hasTag(IDENT)) {
4237                         site = env.enclClass.sym.type;
4238                     } else if (clazz.hasTag(SELECT)) {
4239                         site = ((JCFieldAccess) clazz).selected.type;
4240                     } else throw new AssertionError(""+tree);
4241                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
4242                         if (site.hasTag(CLASS))
4243                             site = types.asOuterSuper(site, clazzOuter.tsym);
4244                         if (site == null)
4245                             site = types.erasure(clazzOuter);
4246                         clazzOuter = site;
4247                     }
4248                 }
4249                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
4250                                         clazztype.getMetadata());
4251             } else {
4252                 if (formals.length() != 0) {
4253                     log.error(tree.pos(),
4254                               Errors.WrongNumberTypeArgs(Integer.toString(formals.length())));
4255                 } else {
4256                     log.error(tree.pos(), Errors.TypeDoesntTakeParams(clazztype.tsym));
4257                 }
4258                 owntype = types.createErrorType(tree.type);
4259             }
4260         }
4261         result = check(tree, owntype, KindSelector.TYP, resultInfo);
4262     }
4263 
4264     public void visitTypeUnion(JCTypeUnion tree) {
4265         ListBuffer<Type> multicatchTypes = new ListBuffer<>();
4266         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
4267         for (JCExpression typeTree : tree.alternatives) {
4268             Type ctype = attribType(typeTree, env);
4269             ctype = chk.checkType(typeTree.pos(),
4270                           chk.checkClassType(typeTree.pos(), ctype),
4271                           syms.throwableType);
4272             if (!ctype.isErroneous()) {
4273                 //check that alternatives of a union type are pairwise
4274                 //unrelated w.r.t. subtyping
4275                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
4276                     for (Type t : multicatchTypes) {
4277                         boolean sub = types.isSubtype(ctype, t);
4278                         boolean sup = types.isSubtype(t, ctype);
4279                         if (sub || sup) {
4280                             //assume 'a' <: 'b'
4281                             Type a = sub ? ctype : t;
4282                             Type b = sub ? t : ctype;
4283                             log.error(typeTree.pos(), Errors.MulticatchTypesMustBeDisjoint(a, b));
4284                         }
4285                     }
4286                 }
4287                 multicatchTypes.append(ctype);
4288                 if (all_multicatchTypes != null)
4289                     all_multicatchTypes.append(ctype);
4290             } else {
4291                 if (all_multicatchTypes == null) {
4292                     all_multicatchTypes = new ListBuffer<>();
4293                     all_multicatchTypes.appendList(multicatchTypes);
4294                 }
4295                 all_multicatchTypes.append(ctype);
4296             }
4297         }
4298         Type t = check(tree, types.lub(multicatchTypes.toList()),
4299                 KindSelector.TYP, resultInfo.dup(CheckMode.NO_TREE_UPDATE));
4300         if (t.hasTag(CLASS)) {
4301             List<Type> alternatives =
4302                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
4303             t = new UnionClassType((ClassType) t, alternatives);
4304         }
4305         tree.type = result = t;
4306     }
4307 
4308     public void visitTypeIntersection(JCTypeIntersection tree) {
4309         attribTypes(tree.bounds, env);
4310         tree.type = result = checkIntersection(tree, tree.bounds);
4311     }
4312 
4313     public void visitTypeParameter(JCTypeParameter tree) {
4314         TypeVar typeVar = (TypeVar) tree.type;
4315 
4316         if (tree.annotations != null && tree.annotations.nonEmpty()) {
4317             annotate.annotateTypeParameterSecondStage(tree, tree.annotations);
4318         }
4319 
4320         if (!typeVar.getUpperBound().isErroneous()) {
4321             //fixup type-parameter bound computed in 'attribTypeVariables'
4322             typeVar.setUpperBound(checkIntersection(tree, tree.bounds));
4323         }
4324     }
4325 
4326     Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
4327         Set<Type> boundSet = new HashSet<>();
4328         if (bounds.nonEmpty()) {
4329             // accept class or interface or typevar as first bound.
4330             bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
4331             boundSet.add(types.erasure(bounds.head.type));
4332             if (bounds.head.type.isErroneous()) {
4333                 return bounds.head.type;
4334             }
4335             else if (bounds.head.type.hasTag(TYPEVAR)) {
4336                 // if first bound was a typevar, do not accept further bounds.
4337                 if (bounds.tail.nonEmpty()) {
4338                     log.error(bounds.tail.head.pos(),
4339                               Errors.TypeVarMayNotBeFollowedByOtherBounds);
4340                     return bounds.head.type;
4341                 }
4342             } else {
4343                 // if first bound was a class or interface, accept only interfaces
4344                 // as further bounds.
4345                 for (JCExpression bound : bounds.tail) {
4346                     bound.type = checkBase(bound.type, bound, env, false, true, false);
4347                     if (bound.type.isErroneous()) {
4348                         bounds = List.of(bound);
4349                     }
4350                     else if (bound.type.hasTag(CLASS)) {
4351                         chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
4352                     }
4353                 }
4354             }
4355         }
4356 
4357         if (bounds.length() == 0) {
4358             return syms.objectType;
4359         } else if (bounds.length() == 1) {
4360             return bounds.head.type;
4361         } else {
4362             Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
4363             // ... the variable's bound is a class type flagged COMPOUND
4364             // (see comment for TypeVar.bound).
4365             // In this case, generate a class tree that represents the
4366             // bound class, ...
4367             JCExpression extending;
4368             List<JCExpression> implementing;
4369             if (!bounds.head.type.isInterface()) {
4370                 extending = bounds.head;
4371                 implementing = bounds.tail;
4372             } else {
4373                 extending = null;
4374                 implementing = bounds;
4375             }
4376             JCClassDecl cd = make.at(tree).ClassDef(
4377                 make.Modifiers(PUBLIC | ABSTRACT),
4378                 names.empty, List.nil(),
4379                 extending, implementing, List.nil());
4380 
4381             ClassSymbol c = (ClassSymbol)owntype.tsym;
4382             Assert.check((c.flags() & COMPOUND) != 0);
4383             cd.sym = c;
4384             c.sourcefile = env.toplevel.sourcefile;
4385 
4386             // ... and attribute the bound class
4387             c.flags_field |= UNATTRIBUTED;
4388             Env<AttrContext> cenv = enter.classEnv(cd, env);
4389             typeEnvs.put(c, cenv);
4390             attribClass(c);
4391             return owntype;
4392         }
4393     }
4394 
4395     public void visitWildcard(JCWildcard tree) {
4396         //- System.err.println("visitWildcard("+tree+");");//DEBUG
4397         Type type = (tree.kind.kind == BoundKind.UNBOUND)
4398             ? syms.objectType
4399             : attribType(tree.inner, env);
4400         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
4401                                               tree.kind.kind,
4402                                               syms.boundClass),
4403                 KindSelector.TYP, resultInfo);
4404     }
4405 
4406     public void visitAnnotation(JCAnnotation tree) {
4407         Assert.error("should be handled in annotate");
4408     }
4409 
4410     public void visitAnnotatedType(JCAnnotatedType tree) {
4411         attribAnnotationTypes(tree.annotations, env);
4412         Type underlyingType = attribType(tree.underlyingType, env);
4413         Type annotatedType = underlyingType.annotatedType(Annotations.TO_BE_SET);
4414 
4415         if (!env.info.isNewClass)
4416             annotate.annotateTypeSecondStage(tree, tree.annotations, annotatedType);
4417         result = tree.type = annotatedType;
4418     }
4419 
4420     public void visitErroneous(JCErroneous tree) {
4421         if (tree.errs != null)
4422             for (JCTree err : tree.errs)
4423                 attribTree(err, env, new ResultInfo(KindSelector.ERR, pt()));
4424         result = tree.type = syms.errType;
4425     }
4426 
4427     /** Default visitor method for all other trees.
4428      */
4429     public void visitTree(JCTree tree) {
4430         throw new AssertionError();
4431     }
4432 
4433     /**
4434      * Attribute an env for either a top level tree or class or module declaration.
4435      */
4436     public void attrib(Env<AttrContext> env) {
4437         switch (env.tree.getTag()) {
4438             case MODULEDEF:
4439                 attribModule(env.tree.pos(), ((JCModuleDecl)env.tree).sym);
4440                 break;
4441             case TOPLEVEL:
4442                 attribTopLevel(env);
4443                 break;
4444             case PACKAGEDEF:
4445                 attribPackage(env.tree.pos(), ((JCPackageDecl) env.tree).packge);
4446                 break;
4447             default:
4448                 attribClass(env.tree.pos(), env.enclClass.sym);
4449         }
4450     }
4451 
4452     /**
4453      * Attribute a top level tree. These trees are encountered when the
4454      * package declaration has annotations.
4455      */
4456     public void attribTopLevel(Env<AttrContext> env) {
4457         JCCompilationUnit toplevel = env.toplevel;
4458         try {
4459             annotate.flush();
4460         } catch (CompletionFailure ex) {
4461             chk.completionError(toplevel.pos(), ex);
4462         }
4463     }
4464 
4465     public void attribPackage(DiagnosticPosition pos, PackageSymbol p) {
4466         try {
4467             annotate.flush();
4468             attribPackage(p);
4469         } catch (CompletionFailure ex) {
4470             chk.completionError(pos, ex);
4471         }
4472     }
4473 
4474     void attribPackage(PackageSymbol p) {
4475         Env<AttrContext> env = typeEnvs.get(p);
4476         chk.checkDeprecatedAnnotation(((JCPackageDecl) env.tree).pid.pos(), p);
4477     }
4478 
4479     public void attribModule(DiagnosticPosition pos, ModuleSymbol m) {
4480         try {
4481             annotate.flush();
4482             attribModule(m);
4483         } catch (CompletionFailure ex) {
4484             chk.completionError(pos, ex);
4485         }
4486     }
4487 
4488     void attribModule(ModuleSymbol m) {
4489         // Get environment current at the point of module definition.
4490         Env<AttrContext> env = enter.typeEnvs.get(m);
4491         attribStat(env.tree, env);
4492     }
4493 
4494     /** Main method: attribute class definition associated with given class symbol.
4495      *  reporting completion failures at the given position.
4496      *  @param pos The source position at which completion errors are to be
4497      *             reported.
4498      *  @param c   The class symbol whose definition will be attributed.
4499      */
4500     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
4501         try {
4502             annotate.flush();
4503             attribClass(c);
4504         } catch (CompletionFailure ex) {
4505             chk.completionError(pos, ex);
4506         }
4507     }
4508 
4509     /** Attribute class definition associated with given class symbol.
4510      *  @param c   The class symbol whose definition will be attributed.
4511      */
4512     void attribClass(ClassSymbol c) throws CompletionFailure {
4513         if (c.type.hasTag(ERROR)) return;
4514 
4515         // Check for cycles in the inheritance graph, which can arise from
4516         // ill-formed class files.
4517         chk.checkNonCyclic(null, c.type);
4518 
4519         Type st = types.supertype(c.type);
4520         if ((c.flags_field & Flags.COMPOUND) == 0) {
4521             // First, attribute superclass.
4522             if (st.hasTag(CLASS))
4523                 attribClass((ClassSymbol)st.tsym);
4524 
4525             // Next attribute owner, if it is a class.
4526             if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
4527                 attribClass((ClassSymbol)c.owner);
4528         }
4529 
4530         // The previous operations might have attributed the current class
4531         // if there was a cycle. So we test first whether the class is still
4532         // UNATTRIBUTED.
4533         if ((c.flags_field & UNATTRIBUTED) != 0) {
4534             c.flags_field &= ~UNATTRIBUTED;
4535 
4536             // Get environment current at the point of class definition.
4537             Env<AttrContext> env = typeEnvs.get(c);
4538 
4539             // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
4540             // because the annotations were not available at the time the env was created. Therefore,
4541             // we look up the environment chain for the first enclosing environment for which the
4542             // lint value is set. Typically, this is the parent env, but might be further if there
4543             // are any envs created as a result of TypeParameter nodes.
4544             Env<AttrContext> lintEnv = env;
4545             while (lintEnv.info.lint == null)
4546                 lintEnv = lintEnv.next;
4547 
4548             // Having found the enclosing lint value, we can initialize the lint value for this class
4549             env.info.lint = lintEnv.info.lint.augment(c);
4550 
4551             Lint prevLint = chk.setLint(env.info.lint);
4552             JavaFileObject prev = log.useSource(c.sourcefile);
4553             ResultInfo prevReturnRes = env.info.returnResult;
4554 
4555             try {
4556                 deferredLintHandler.flush(env.tree);
4557                 env.info.returnResult = null;
4558                 // java.lang.Enum may not be subclassed by a non-enum
4559                 if (st.tsym == syms.enumSym &&
4560                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
4561                     log.error(env.tree.pos(), Errors.EnumNoSubclassing);
4562 
4563                 // Enums may not be extended by source-level classes
4564                 if (st.tsym != null &&
4565                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
4566                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
4567                     log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
4568                 }
4569 
4570                 if (isSerializable(c.type)) {
4571                     env.info.isSerializable = true;
4572                 }
4573 
4574                 attribClassBody(env, c);
4575 
4576                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
4577                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
4578                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
4579                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
4580             } finally {
4581                 env.info.returnResult = prevReturnRes;
4582                 log.useSource(prev);
4583                 chk.setLint(prevLint);
4584             }
4585 
4586         }
4587     }
4588 
4589     public void visitImport(JCImport tree) {
4590         // nothing to do
4591     }
4592 
4593     public void visitModuleDef(JCModuleDecl tree) {
4594         tree.sym.completeUsesProvides();
4595         ModuleSymbol msym = tree.sym;
4596         Lint lint = env.outer.info.lint = env.outer.info.lint.augment(msym);
4597         Lint prevLint = chk.setLint(lint);
4598         chk.checkModuleName(tree);
4599         chk.checkDeprecatedAnnotation(tree, msym);
4600 
4601         try {
4602             deferredLintHandler.flush(tree.pos());
4603         } finally {
4604             chk.setLint(prevLint);
4605         }
4606     }
4607 
4608     /** Finish the attribution of a class. */
4609     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
4610         JCClassDecl tree = (JCClassDecl)env.tree;
4611         Assert.check(c == tree.sym);
4612 
4613         // Validate type parameters, supertype and interfaces.
4614         attribStats(tree.typarams, env);
4615         if (!c.isAnonymous()) {
4616             //already checked if anonymous
4617             chk.validate(tree.typarams, env);
4618             chk.validate(tree.extending, env);
4619             chk.validate(tree.implementing, env);
4620         }
4621 
4622         c.markAbstractIfNeeded(types);
4623 
4624         // If this is a non-abstract class, check that it has no abstract
4625         // methods or unimplemented methods of an implemented interface.
4626         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
4627             chk.checkAllDefined(tree.pos(), c);
4628         }
4629 
4630         if ((c.flags() & ANNOTATION) != 0) {
4631             if (tree.implementing.nonEmpty())
4632                 log.error(tree.implementing.head.pos(),
4633                           Errors.CantExtendIntfAnnotation);
4634             if (tree.typarams.nonEmpty()) {
4635                 log.error(tree.typarams.head.pos(),
4636                           Errors.IntfAnnotationCantHaveTypeParams(c));
4637             }
4638 
4639             // If this annotation type has a @Repeatable, validate
4640             Attribute.Compound repeatable = c.getAnnotationTypeMetadata().getRepeatable();
4641             // If this annotation type has a @Repeatable, validate
4642             if (repeatable != null) {
4643                 // get diagnostic position for error reporting
4644                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
4645                 Assert.checkNonNull(cbPos);
4646 
4647                 chk.validateRepeatable(c, repeatable, cbPos);
4648             }
4649         } else {
4650             // Check that all extended classes and interfaces
4651             // are compatible (i.e. no two define methods with same arguments
4652             // yet different return types).  (JLS 8.4.6.3)
4653             chk.checkCompatibleSupertypes(tree.pos(), c.type);
4654             if (allowDefaultMethods) {
4655                 chk.checkDefaultMethodClashes(tree.pos(), c.type);
4656             }
4657         }
4658 
4659         // Check that class does not import the same parameterized interface
4660         // with two different argument lists.
4661         chk.checkClassBounds(tree.pos(), c.type);
4662 
4663         tree.type = c.type;
4664 
4665         for (List<JCTypeParameter> l = tree.typarams;
4666              l.nonEmpty(); l = l.tail) {
4667              Assert.checkNonNull(env.info.scope.findFirst(l.head.name));
4668         }
4669 
4670         // Check that a generic class doesn't extend Throwable
4671         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
4672             log.error(tree.extending.pos(), Errors.GenericThrowable);
4673 
4674         // Check that all methods which implement some
4675         // method conform to the method they implement.
4676         chk.checkImplementations(tree);
4677 
4678         //check that a resource implementing AutoCloseable cannot throw InterruptedException
4679         checkAutoCloseable(tree.pos(), env, c.type);
4680 
4681         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
4682             // Attribute declaration
4683             attribStat(l.head, env);
4684             // Check that declarations in inner classes are not static (JLS 8.1.2)
4685             // Make an exception for static constants.
4686             if (c.owner.kind != PCK &&
4687                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
4688                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
4689                 Symbol sym = null;
4690                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
4691                 if (sym == null ||
4692                     sym.kind != VAR ||
4693                     ((VarSymbol) sym).getConstValue() == null)
4694                     log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
4695             }
4696         }
4697 
4698         // Check for cycles among non-initial constructors.
4699         chk.checkCyclicConstructors(tree);
4700 
4701         // Check for cycles among annotation elements.
4702         chk.checkNonCyclicElements(tree);
4703 
4704         // Check for proper use of serialVersionUID
4705         if (env.info.lint.isEnabled(LintCategory.SERIAL)
4706                 && isSerializable(c.type)
4707                 && (c.flags() & (Flags.ENUM | Flags.INTERFACE)) == 0
4708                 && !c.isAnonymous()) {
4709             checkSerialVersionUID(tree, c);
4710         }
4711         if (allowTypeAnnos) {
4712             // Correctly organize the postions of the type annotations
4713             typeAnnotations.organizeTypeAnnotationsBodies(tree);
4714 
4715             // Check type annotations applicability rules
4716             validateTypeAnnotations(tree, false);
4717         }
4718     }
4719         // where
4720         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
4721         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
4722             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
4723                 if (types.isSameType(al.head.annotationType.type, t))
4724                     return al.head.pos();
4725             }
4726 
4727             return null;
4728         }
4729 
4730         /** check if a type is a subtype of Serializable, if that is available. */
4731         boolean isSerializable(Type t) {
4732             try {
4733                 syms.serializableType.complete();
4734             }
4735             catch (CompletionFailure e) {
4736                 return false;
4737             }
4738             return types.isSubtype(t, syms.serializableType);
4739         }
4740 
4741         /** Check that an appropriate serialVersionUID member is defined. */
4742         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
4743 
4744             // check for presence of serialVersionUID
4745             VarSymbol svuid = null;
4746             for (Symbol sym : c.members().getSymbolsByName(names.serialVersionUID)) {
4747                 if (sym.kind == VAR) {
4748                     svuid = (VarSymbol)sym;
4749                     break;
4750                 }
4751             }
4752 
4753             if (svuid == null) {
4754                 log.warning(LintCategory.SERIAL,
4755                         tree.pos(), Warnings.MissingSVUID(c));
4756                 return;
4757             }
4758 
4759             // check that it is static final
4760             if ((svuid.flags() & (STATIC | FINAL)) !=
4761                 (STATIC | FINAL))
4762                 log.warning(LintCategory.SERIAL,
4763                         TreeInfo.diagnosticPositionFor(svuid, tree), Warnings.ImproperSVUID(c));
4764 
4765             // check that it is long
4766             else if (!svuid.type.hasTag(LONG))
4767                 log.warning(LintCategory.SERIAL,
4768                         TreeInfo.diagnosticPositionFor(svuid, tree), Warnings.LongSVUID(c));
4769 
4770             // check constant
4771             else if (svuid.getConstValue() == null)
4772                 log.warning(LintCategory.SERIAL,
4773                         TreeInfo.diagnosticPositionFor(svuid, tree), Warnings.ConstantSVUID(c));
4774         }
4775 
4776     private Type capture(Type type) {
4777         return types.capture(type);
4778     }
4779 
4780     private void setSyntheticVariableType(JCVariableDecl tree, Type type) {
4781         if (type.isErroneous()) {
4782             tree.vartype = make.at(Position.NOPOS).Erroneous();
4783         } else {
4784             tree.vartype = make.at(Position.NOPOS).Type(type);
4785         }
4786     }
4787 
4788     public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
4789         tree.accept(new TypeAnnotationsValidator(sigOnly));
4790     }
4791     //where
4792     private final class TypeAnnotationsValidator extends TreeScanner {
4793 
4794         private final boolean sigOnly;
4795         public TypeAnnotationsValidator(boolean sigOnly) {
4796             this.sigOnly = sigOnly;
4797         }
4798 
4799         public void visitAnnotation(JCAnnotation tree) {
4800             chk.validateTypeAnnotation(tree, false);
4801             super.visitAnnotation(tree);
4802         }
4803         public void visitAnnotatedType(JCAnnotatedType tree) {
4804             if (!tree.underlyingType.type.isErroneous()) {
4805                 super.visitAnnotatedType(tree);
4806             }
4807         }
4808         public void visitTypeParameter(JCTypeParameter tree) {
4809             chk.validateTypeAnnotations(tree.annotations, true);
4810             scan(tree.bounds);
4811             // Don't call super.
4812             // This is needed because above we call validateTypeAnnotation with
4813             // false, which would forbid annotations on type parameters.
4814             // super.visitTypeParameter(tree);
4815         }
4816         public void visitMethodDef(JCMethodDecl tree) {
4817             if (tree.recvparam != null &&
4818                     !tree.recvparam.vartype.type.isErroneous()) {
4819                 checkForDeclarationAnnotations(tree.recvparam.mods.annotations,
4820                         tree.recvparam.vartype.type.tsym);
4821             }
4822             if (tree.restype != null && tree.restype.type != null) {
4823                 validateAnnotatedType(tree.restype, tree.restype.type);
4824             }
4825             if (sigOnly) {
4826                 scan(tree.mods);
4827                 scan(tree.restype);
4828                 scan(tree.typarams);
4829                 scan(tree.recvparam);
4830                 scan(tree.params);
4831                 scan(tree.thrown);
4832             } else {
4833                 scan(tree.defaultValue);
4834                 scan(tree.body);
4835             }
4836         }
4837         public void visitVarDef(final JCVariableDecl tree) {
4838             //System.err.println("validateTypeAnnotations.visitVarDef " + tree);
4839             if (tree.sym != null && tree.sym.type != null && !tree.isImplicitlyTyped())
4840                 validateAnnotatedType(tree.vartype, tree.sym.type);
4841             scan(tree.mods);
4842             scan(tree.vartype);
4843             if (!sigOnly) {
4844                 scan(tree.init);
4845             }
4846         }
4847         public void visitTypeCast(JCTypeCast tree) {
4848             if (tree.clazz != null && tree.clazz.type != null)
4849                 validateAnnotatedType(tree.clazz, tree.clazz.type);
4850             super.visitTypeCast(tree);
4851         }
4852         public void visitTypeTest(JCInstanceOf tree) {
4853             if (tree.clazz != null && tree.clazz.type != null)
4854                 validateAnnotatedType(tree.clazz, tree.clazz.type);
4855             super.visitTypeTest(tree);
4856         }
4857         public void visitNewClass(JCNewClass tree) {
4858             if (tree.clazz != null && tree.clazz.type != null) {
4859                 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
4860                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
4861                             tree.clazz.type.tsym);
4862                 }
4863                 if (tree.def != null) {
4864                     checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym);
4865                 }
4866 
4867                 validateAnnotatedType(tree.clazz, tree.clazz.type);
4868             }
4869             super.visitNewClass(tree);
4870         }
4871         public void visitNewArray(JCNewArray tree) {
4872             if (tree.elemtype != null && tree.elemtype.type != null) {
4873                 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
4874                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
4875                             tree.elemtype.type.tsym);
4876                 }
4877                 validateAnnotatedType(tree.elemtype, tree.elemtype.type);
4878             }
4879             super.visitNewArray(tree);
4880         }
4881         public void visitClassDef(JCClassDecl tree) {
4882             //System.err.println("validateTypeAnnotations.visitClassDef " + tree);
4883             if (sigOnly) {
4884                 scan(tree.mods);
4885                 scan(tree.typarams);
4886                 scan(tree.extending);
4887                 scan(tree.implementing);
4888             }
4889             for (JCTree member : tree.defs) {
4890                 if (member.hasTag(Tag.CLASSDEF)) {
4891                     continue;
4892                 }
4893                 scan(member);
4894             }
4895         }
4896         public void visitBlock(JCBlock tree) {
4897             if (!sigOnly) {
4898                 scan(tree.stats);
4899             }
4900         }
4901 
4902         /* I would want to model this after
4903          * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
4904          * and override visitSelect and visitTypeApply.
4905          * However, we only set the annotated type in the top-level type
4906          * of the symbol.
4907          * Therefore, we need to override each individual location where a type
4908          * can occur.
4909          */
4910         private void validateAnnotatedType(final JCTree errtree, final Type type) {
4911             //System.err.println("Attr.validateAnnotatedType: " + errtree + " type: " + type);
4912 
4913             if (type.isPrimitiveOrVoid()) {
4914                 return;
4915             }
4916 
4917             JCTree enclTr = errtree;
4918             Type enclTy = type;
4919 
4920             boolean repeat = true;
4921             while (repeat) {
4922                 if (enclTr.hasTag(TYPEAPPLY)) {
4923                     List<Type> tyargs = enclTy.getTypeArguments();
4924                     List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments();
4925                     if (trargs.length() > 0) {
4926                         // Nothing to do for diamonds
4927                         if (tyargs.length() == trargs.length()) {
4928                             for (int i = 0; i < tyargs.length(); ++i) {
4929                                 validateAnnotatedType(trargs.get(i), tyargs.get(i));
4930                             }
4931                         }
4932                         // If the lengths don't match, it's either a diamond
4933                         // or some nested type that redundantly provides
4934                         // type arguments in the tree.
4935                     }
4936 
4937                     // Look at the clazz part of a generic type
4938                     enclTr = ((JCTree.JCTypeApply)enclTr).clazz;
4939                 }
4940 
4941                 if (enclTr.hasTag(SELECT)) {
4942                     enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression();
4943                     if (enclTy != null &&
4944                             !enclTy.hasTag(NONE)) {
4945                         enclTy = enclTy.getEnclosingType();
4946                     }
4947                 } else if (enclTr.hasTag(ANNOTATED_TYPE)) {
4948                     JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr;
4949                     if (enclTy == null || enclTy.hasTag(NONE)) {
4950                         if (at.getAnnotations().size() == 1) {
4951                             log.error(at.underlyingType.pos(), Errors.CantTypeAnnotateScoping1(at.getAnnotations().head.attribute));
4952                         } else {
4953                             ListBuffer<Attribute.Compound> comps = new ListBuffer<>();
4954                             for (JCAnnotation an : at.getAnnotations()) {
4955                                 comps.add(an.attribute);
4956                             }
4957                             log.error(at.underlyingType.pos(), Errors.CantTypeAnnotateScoping(comps.toList()));
4958                         }
4959                         repeat = false;
4960                     }
4961                     enclTr = at.underlyingType;
4962                     // enclTy doesn't need to be changed
4963                 } else if (enclTr.hasTag(IDENT)) {
4964                     repeat = false;
4965                 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) {
4966                     JCWildcard wc = (JCWildcard) enclTr;
4967                     if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD ||
4968                             wc.getKind() == JCTree.Kind.SUPER_WILDCARD) {
4969                         validateAnnotatedType(wc.getBound(), wc.getBound().type);
4970                     } else {
4971                         // Nothing to do for UNBOUND
4972                     }
4973                     repeat = false;
4974                 } else if (enclTr.hasTag(TYPEARRAY)) {
4975                     JCArrayTypeTree art = (JCArrayTypeTree) enclTr;
4976                     validateAnnotatedType(art.getType(), art.elemtype.type);
4977                     repeat = false;
4978                 } else if (enclTr.hasTag(TYPEUNION)) {
4979                     JCTypeUnion ut = (JCTypeUnion) enclTr;
4980                     for (JCTree t : ut.getTypeAlternatives()) {
4981                         validateAnnotatedType(t, t.type);
4982                     }
4983                     repeat = false;
4984                 } else if (enclTr.hasTag(TYPEINTERSECTION)) {
4985                     JCTypeIntersection it = (JCTypeIntersection) enclTr;
4986                     for (JCTree t : it.getBounds()) {
4987                         validateAnnotatedType(t, t.type);
4988                     }
4989                     repeat = false;
4990                 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE ||
4991                            enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
4992                     repeat = false;
4993                 } else {
4994                     Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() +
4995                             " within: "+ errtree + " with kind: " + errtree.getKind());
4996                 }
4997             }
4998         }
4999 
5000         private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
5001                 Symbol sym) {
5002             // Ensure that no declaration annotations are present.
5003             // Note that a tree type might be an AnnotatedType with
5004             // empty annotations, if only declaration annotations were given.
5005             // This method will raise an error for such a type.
5006             for (JCAnnotation ai : annotations) {
5007                 if (!ai.type.isErroneous() &&
5008                         typeAnnotations.annotationTargetType(ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
5009                     log.error(ai.pos(), Errors.AnnotationTypeNotApplicableToType(ai.type));
5010                 }
5011             }
5012         }
5013     }
5014 
5015     // <editor-fold desc="post-attribution visitor">
5016 
5017     /**
5018      * Handle missing types/symbols in an AST. This routine is useful when
5019      * the compiler has encountered some errors (which might have ended up
5020      * terminating attribution abruptly); if the compiler is used in fail-over
5021      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
5022      * prevents NPE to be progagated during subsequent compilation steps.
5023      */
5024     public void postAttr(JCTree tree) {
5025         new PostAttrAnalyzer().scan(tree);
5026     }
5027 
5028     class PostAttrAnalyzer extends TreeScanner {
5029 
5030         private void initTypeIfNeeded(JCTree that) {
5031             if (that.type == null) {
5032                 if (that.hasTag(METHODDEF)) {
5033                     that.type = dummyMethodType((JCMethodDecl)that);
5034                 } else {
5035                     that.type = syms.unknownType;
5036                 }
5037             }
5038         }
5039 
5040         /* Construct a dummy method type. If we have a method declaration,
5041          * and the declared return type is void, then use that return type
5042          * instead of UNKNOWN to avoid spurious error messages in lambda
5043          * bodies (see:JDK-8041704).
5044          */
5045         private Type dummyMethodType(JCMethodDecl md) {
5046             Type restype = syms.unknownType;
5047             if (md != null && md.restype != null && md.restype.hasTag(TYPEIDENT)) {
5048                 JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype;
5049                 if (prim.typetag == VOID)
5050                     restype = syms.voidType;
5051             }
5052             return new MethodType(List.nil(), restype,
5053                                   List.nil(), syms.methodClass);
5054         }
5055         private Type dummyMethodType() {
5056             return dummyMethodType(null);
5057         }
5058 
5059         @Override
5060         public void scan(JCTree tree) {
5061             if (tree == null) return;
5062             if (tree instanceof JCExpression) {
5063                 initTypeIfNeeded(tree);
5064             }
5065             super.scan(tree);
5066         }
5067 
5068         @Override
5069         public void visitIdent(JCIdent that) {
5070             if (that.sym == null) {
5071                 that.sym = syms.unknownSymbol;
5072             }
5073         }
5074 
5075         @Override
5076         public void visitSelect(JCFieldAccess that) {
5077             if (that.sym == null) {
5078                 that.sym = syms.unknownSymbol;
5079             }
5080             super.visitSelect(that);
5081         }
5082 
5083         @Override
5084         public void visitClassDef(JCClassDecl that) {
5085             initTypeIfNeeded(that);
5086             if (that.sym == null) {
5087                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
5088             }
5089             super.visitClassDef(that);
5090         }
5091 
5092         @Override
5093         public void visitMethodDef(JCMethodDecl that) {
5094             initTypeIfNeeded(that);
5095             if (that.sym == null) {
5096                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
5097             }
5098             super.visitMethodDef(that);
5099         }
5100 
5101         @Override
5102         public void visitVarDef(JCVariableDecl that) {
5103             initTypeIfNeeded(that);
5104             if (that.sym == null) {
5105                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
5106                 that.sym.adr = 0;
5107             }
5108             if (that.vartype == null) {
5109                 that.vartype = make.at(Position.NOPOS).Erroneous();
5110             }
5111             super.visitVarDef(that);
5112         }
5113 
5114         @Override
5115         public void visitNewClass(JCNewClass that) {
5116             if (that.constructor == null) {
5117                 that.constructor = new MethodSymbol(0, names.init,
5118                         dummyMethodType(), syms.noSymbol);
5119             }
5120             if (that.constructorType == null) {
5121                 that.constructorType = syms.unknownType;
5122             }
5123             super.visitNewClass(that);
5124         }
5125 
5126         @Override
5127         public void visitAssignop(JCAssignOp that) {
5128             if (that.operator == null) {
5129                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
5130                         -1, syms.noSymbol);
5131             }
5132             super.visitAssignop(that);
5133         }
5134 
5135         @Override
5136         public void visitBinary(JCBinary that) {
5137             if (that.operator == null) {
5138                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
5139                         -1, syms.noSymbol);
5140             }
5141             super.visitBinary(that);
5142         }
5143 
5144         @Override
5145         public void visitUnary(JCUnary that) {
5146             if (that.operator == null) {
5147                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
5148                         -1, syms.noSymbol);
5149             }
5150             super.visitUnary(that);
5151         }
5152 
5153         @Override
5154         public void visitLambda(JCLambda that) {
5155             super.visitLambda(that);
5156             if (that.target == null) {
5157                 that.target = syms.unknownType;
5158             }
5159         }
5160 
5161         @Override
5162         public void visitReference(JCMemberReference that) {
5163             super.visitReference(that);
5164             if (that.sym == null) {
5165                 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
5166                         syms.noSymbol);
5167             }
5168             if (that.target == null) {
5169                 that.target = syms.unknownType;
5170             }
5171         }
5172     }
5173     // </editor-fold>
5174 
5175     public void setPackageSymbols(JCExpression pid, Symbol pkg) {
5176         new TreeScanner() {
5177             Symbol packge = pkg;
5178             @Override
5179             public void visitIdent(JCIdent that) {
5180                 that.sym = packge;
5181             }
5182 
5183             @Override
5184             public void visitSelect(JCFieldAccess that) {
5185                 that.sym = packge;
5186                 packge = packge.owner;
5187                 super.visitSelect(that);
5188             }
5189         }.scan(pid);
5190     }
5191 
5192 }