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