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