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