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