1 /*
   2  * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.tools.javac.comp;
  27 
  28 import java.util.*;
  29 import java.util.Set;
  30 import javax.lang.model.element.ElementKind;
  31 import javax.tools.JavaFileObject;
  32 
  33 import com.sun.tools.javac.code.*;
  34 import com.sun.tools.javac.jvm.*;
  35 import com.sun.tools.javac.tree.*;
  36 import com.sun.tools.javac.util.*;
  37 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  38 import com.sun.tools.javac.util.List;
  39 
  40 import com.sun.tools.javac.jvm.Target;
  41 import com.sun.tools.javac.code.Lint.LintCategory;
  42 import com.sun.tools.javac.code.Symbol.*;
  43 import com.sun.tools.javac.tree.JCTree.*;
  44 import com.sun.tools.javac.code.Type.*;
  45 
  46 import com.sun.source.tree.IdentifierTree;
  47 import com.sun.source.tree.MemberSelectTree;
  48 import com.sun.source.tree.TreeVisitor;
  49 import com.sun.source.util.SimpleTreeVisitor;
  50 
  51 import static com.sun.tools.javac.code.Flags.*;
  52 import static com.sun.tools.javac.code.Kinds.*;
  53 import static com.sun.tools.javac.code.TypeTags.*;
  54 
  55 /** This is the main context-dependent analysis phase in GJC. It
  56  *  encompasses name resolution, type checking and constant folding as
  57  *  subtasks. Some subtasks involve auxiliary classes.
  58  *  @see Check
  59  *  @see Resolve
  60  *  @see ConstFold
  61  *  @see Infer
  62  *
  63  *  <p><b>This is NOT part of any supported API.
  64  *  If you write code that depends on this, you do so at your own risk.
  65  *  This code and its internal interfaces are subject to change or
  66  *  deletion without notice.</b>
  67  */
  68 public class Attr extends JCTree.Visitor {
  69     protected static final Context.Key<Attr> attrKey =
  70         new Context.Key<Attr>();
  71 
  72     final Names names;
  73     final Log log;
  74     final Symtab syms;
  75     final Resolve rs;
  76     final Infer infer;
  77     final Check chk;
  78     final MemberEnter memberEnter;
  79     final TreeMaker make;
  80     final ConstFold cfolder;
  81     final Enter enter;
  82     final Target target;
  83     final Types types;
  84     final JCDiagnostic.Factory diags;
  85     final Annotate annotate;
  86     final DeferredLintHandler deferredLintHandler;
  87 
  88     public static Attr instance(Context context) {
  89         Attr instance = context.get(attrKey);
  90         if (instance == null)
  91             instance = new Attr(context);
  92         return instance;
  93     }
  94 
  95     protected Attr(Context context) {
  96         context.put(attrKey, this);
  97 
  98         names = Names.instance(context);
  99         log = Log.instance(context);
 100         syms = Symtab.instance(context);
 101         rs = Resolve.instance(context);
 102         chk = Check.instance(context);
 103         memberEnter = MemberEnter.instance(context);
 104         make = TreeMaker.instance(context);
 105         enter = Enter.instance(context);
 106         infer = Infer.instance(context);
 107         cfolder = ConstFold.instance(context);
 108         target = Target.instance(context);
 109         types = Types.instance(context);
 110         diags = JCDiagnostic.Factory.instance(context);
 111         annotate = Annotate.instance(context);
 112         deferredLintHandler = DeferredLintHandler.instance(context);
 113 
 114         Options options = Options.instance(context);
 115 
 116         Source source = Source.instance(context);
 117         allowGenerics = source.allowGenerics();
 118         allowVarargs = source.allowVarargs();
 119         allowEnums = source.allowEnums();
 120         allowBoxing = source.allowBoxing();
 121         allowCovariantReturns = source.allowCovariantReturns();
 122         allowAnonOuterThis = source.allowAnonOuterThis();
 123         allowStringsInSwitch = source.allowStringsInSwitch();
 124         sourceName = source.name;
 125         relax = (options.isSet("-retrofit") ||
 126                  options.isSet("-relax"));
 127         findDiamonds = options.get("findDiamond") != null &&
 128                  source.allowDiamond();
 129         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
 130     }
 131 
 132     /** Switch: relax some constraints for retrofit mode.
 133      */
 134     boolean relax;
 135 
 136     /** Switch: support generics?
 137      */
 138     boolean allowGenerics;
 139 
 140     /** Switch: allow variable-arity methods.
 141      */
 142     boolean allowVarargs;
 143 
 144     /** Switch: support enums?
 145      */
 146     boolean allowEnums;
 147 
 148     /** Switch: support boxing and unboxing?
 149      */
 150     boolean allowBoxing;
 151 
 152     /** Switch: support covariant result types?
 153      */
 154     boolean allowCovariantReturns;
 155 
 156     /** Switch: allow references to surrounding object from anonymous
 157      * objects during constructor call?
 158      */
 159     boolean allowAnonOuterThis;
 160 
 161     /** Switch: generates a warning if diamond can be safely applied
 162      *  to a given new expression
 163      */
 164     boolean findDiamonds;
 165 
 166     /**
 167      * Internally enables/disables diamond finder feature
 168      */
 169     static final boolean allowDiamondFinder = true;
 170 
 171     /**
 172      * Switch: warn about use of variable before declaration?
 173      * RFE: 6425594
 174      */
 175     boolean useBeforeDeclarationWarning;
 176 
 177     /**
 178      * Switch: allow strings in switch?
 179      */
 180     boolean allowStringsInSwitch;
 181 
 182     /**
 183      * Switch: name of source level; used for error reporting.
 184      */
 185     String sourceName;
 186 
 187     /** Check kind and type of given tree against protokind and prototype.
 188      *  If check succeeds, store type in tree and return it.
 189      *  If check fails, store errType in tree and return it.
 190      *  No checks are performed if the prototype is a method type.
 191      *  It is not necessary in this case since we know that kind and type
 192      *  are correct.
 193      *
 194      *  @param tree     The tree whose kind and type is checked
 195      *  @param owntype  The computed type of the tree
 196      *  @param ownkind  The computed kind of the tree
 197      *  @param pkind    The expected kind (or: protokind) of the tree
 198      *  @param pt       The expected type (or: prototype) of the tree
 199      */
 200     Type check(JCTree tree, Type owntype, int ownkind, int pkind, Type pt) {
 201         if (owntype.tag != ERROR && pt.tag != METHOD && pt.tag != FORALL) {
 202             if ((ownkind & ~pkind) == 0) {
 203                 owntype = chk.checkType(tree.pos(), owntype, pt, errKey);
 204             } else {
 205                 log.error(tree.pos(), "unexpected.type",
 206                           kindNames(pkind),
 207                           kindName(ownkind));
 208                 owntype = types.createErrorType(owntype);
 209             }
 210         }
 211         tree.type = owntype;
 212         return owntype;
 213     }
 214 
 215     /** Is given blank final variable assignable, i.e. in a scope where it
 216      *  may be assigned to even though it is final?
 217      *  @param v      The blank final variable.
 218      *  @param env    The current environment.
 219      */
 220     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
 221         Symbol owner = env.info.scope.owner;
 222            // owner refers to the innermost variable, method or
 223            // initializer block declaration at this point.
 224         return
 225             v.owner == owner
 226             ||
 227             ((owner.name == names.init ||    // i.e. we are in a constructor
 228               owner.kind == VAR ||           // i.e. we are in a variable initializer
 229               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
 230              &&
 231              v.owner == owner.owner
 232              &&
 233              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
 234     }
 235 
 236     /** Check that variable can be assigned to.
 237      *  @param pos    The current source code position.
 238      *  @param v      The assigned varaible
 239      *  @param base   If the variable is referred to in a Select, the part
 240      *                to the left of the `.', null otherwise.
 241      *  @param env    The current environment.
 242      */
 243     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
 244         if ((v.flags() & FINAL) != 0 &&
 245             ((v.flags() & HASINIT) != 0
 246              ||
 247              !((base == null ||
 248                (base.getTag() == JCTree.IDENT && TreeInfo.name(base) == names._this)) &&
 249                isAssignableAsBlankFinal(v, env)))) {
 250             if (v.isResourceVariable()) { //TWR resource
 251                 log.error(pos, "try.resource.may.not.be.assigned", v);
 252             } else {
 253                 log.error(pos, "cant.assign.val.to.final.var", v);
 254             }
 255         } else if ((v.flags() & EFFECTIVELY_FINAL) != 0) {
 256             v.flags_field &= ~EFFECTIVELY_FINAL;
 257         }
 258     }
 259 
 260     /** Does tree represent a static reference to an identifier?
 261      *  It is assumed that tree is either a SELECT or an IDENT.
 262      *  We have to weed out selects from non-type names here.
 263      *  @param tree    The candidate tree.
 264      */
 265     boolean isStaticReference(JCTree tree) {
 266         if (tree.getTag() == JCTree.SELECT) {
 267             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
 268             if (lsym == null || lsym.kind != TYP) {
 269                 return false;
 270             }
 271         }
 272         return true;
 273     }
 274 
 275     /** Is this symbol a type?
 276      */
 277     static boolean isType(Symbol sym) {
 278         return sym != null && sym.kind == TYP;
 279     }
 280 
 281     /** The current `this' symbol.
 282      *  @param env    The current environment.
 283      */
 284     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
 285         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
 286     }
 287 
 288     /** Attribute a parsed identifier.
 289      * @param tree Parsed identifier name
 290      * @param topLevel The toplevel to use
 291      */
 292     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
 293         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
 294         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
 295                                            syms.errSymbol.name,
 296                                            null, null, null, null);
 297         localEnv.enclClass.sym = syms.errSymbol;
 298         return tree.accept(identAttributer, localEnv);
 299     }
 300     // where
 301         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
 302         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
 303             @Override
 304             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
 305                 Symbol site = visit(node.getExpression(), env);
 306                 if (site.kind == ERR)
 307                     return site;
 308                 Name name = (Name)node.getIdentifier();
 309                 if (site.kind == PCK) {
 310                     env.toplevel.packge = (PackageSymbol)site;
 311                     return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
 312                 } else {
 313                     env.enclClass.sym = (ClassSymbol)site;
 314                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
 315                 }
 316             }
 317 
 318             @Override
 319             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
 320                 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
 321             }
 322         }
 323 
 324     public Type coerce(Type etype, Type ttype) {
 325         return cfolder.coerce(etype, ttype);
 326     }
 327 
 328     public Type attribType(JCTree node, TypeSymbol sym) {
 329         Env<AttrContext> env = enter.typeEnvs.get(sym);
 330         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
 331         return attribTree(node, localEnv, Kinds.TYP, Type.noType);
 332     }
 333 
 334     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
 335         breakTree = tree;
 336         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
 337         try {
 338             attribExpr(expr, env);
 339         } catch (BreakAttr b) {
 340             return b.env;
 341         } catch (AssertionError ae) {
 342             if (ae.getCause() instanceof BreakAttr) {
 343                 return ((BreakAttr)(ae.getCause())).env;
 344             } else {
 345                 throw ae;
 346             }
 347         } finally {
 348             breakTree = null;
 349             log.useSource(prev);
 350         }
 351         return env;
 352     }
 353 
 354     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
 355         breakTree = tree;
 356         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
 357         try {
 358             attribStat(stmt, env);
 359         } catch (BreakAttr b) {
 360             return b.env;
 361         } catch (AssertionError ae) {
 362             if (ae.getCause() instanceof BreakAttr) {
 363                 return ((BreakAttr)(ae.getCause())).env;
 364             } else {
 365                 throw ae;
 366             }
 367         } finally {
 368             breakTree = null;
 369             log.useSource(prev);
 370         }
 371         return env;
 372     }
 373 
 374     private JCTree breakTree = null;
 375 
 376     private static class BreakAttr extends RuntimeException {
 377         static final long serialVersionUID = -6924771130405446405L;
 378         private Env<AttrContext> env;
 379         private BreakAttr(Env<AttrContext> env) {
 380             this.env = env;
 381         }
 382     }
 383 
 384 
 385 /* ************************************************************************
 386  * Visitor methods
 387  *************************************************************************/
 388 
 389     /** Visitor argument: the current environment.
 390      */
 391     Env<AttrContext> env;
 392 
 393     /** Visitor argument: the currently expected proto-kind.
 394      */
 395     int pkind;
 396 
 397     /** Visitor argument: the currently expected proto-type.
 398      */
 399     Type pt;
 400 
 401     /** Visitor argument: the error key to be generated when a type error occurs
 402      */
 403     String errKey;
 404 
 405     /** Visitor result: the computed type.
 406      */
 407     Type result;
 408 
 409     /** Visitor method: attribute a tree, catching any completion failure
 410      *  exceptions. Return the tree's type.
 411      *
 412      *  @param tree    The tree to be visited.
 413      *  @param env     The environment visitor argument.
 414      *  @param pkind   The protokind visitor argument.
 415      *  @param pt      The prototype visitor argument.
 416      */
 417     Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt) {
 418         return attribTree(tree, env, pkind, pt, "incompatible.types");
 419     }
 420 
 421     Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt, String errKey) {
 422         Env<AttrContext> prevEnv = this.env;
 423         int prevPkind = this.pkind;
 424         Type prevPt = this.pt;
 425         String prevErrKey = this.errKey;
 426         try {
 427             this.env = env;
 428             this.pkind = pkind;
 429             this.pt = pt;
 430             this.errKey = errKey;
 431             tree.accept(this);
 432             if (tree == breakTree)
 433                 throw new BreakAttr(env);
 434             return result;
 435         } catch (CompletionFailure ex) {
 436             tree.type = syms.errType;
 437             return chk.completionError(tree.pos(), ex);
 438         } finally {
 439             this.env = prevEnv;
 440             this.pkind = prevPkind;
 441             this.pt = prevPt;
 442             this.errKey = prevErrKey;
 443         }
 444     }
 445 
 446     /** Derived visitor method: attribute an expression tree.
 447      */
 448     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
 449         return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType);
 450     }
 451 
 452     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt, String key) {
 453         return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType, key);
 454     }
 455 
 456     /** Derived visitor method: attribute an expression tree with
 457      *  no constraints on the computed type.
 458      */
 459     Type attribExpr(JCTree tree, Env<AttrContext> env) {
 460         return attribTree(tree, env, VAL, Type.noType);
 461     }
 462 
 463     /** Derived visitor method: attribute a type tree.
 464      */
 465     Type attribType(JCTree tree, Env<AttrContext> env) {
 466         Type result = attribType(tree, env, Type.noType);
 467         return result;
 468     }
 469 
 470     /** Derived visitor method: attribute a type tree.
 471      */
 472     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
 473         Type result = attribTree(tree, env, TYP, pt);
 474         return result;
 475     }
 476 
 477     /** Derived visitor method: attribute a statement or definition tree.
 478      */
 479     public Type attribStat(JCTree tree, Env<AttrContext> env) {
 480         return attribTree(tree, env, NIL, Type.noType);
 481     }
 482 
 483     /** Attribute a list of expressions, returning a list of types.
 484      */
 485     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
 486         ListBuffer<Type> ts = new ListBuffer<Type>();
 487         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
 488             ts.append(attribExpr(l.head, env, pt));
 489         return ts.toList();
 490     }
 491 
 492     /** Attribute a list of statements, returning nothing.
 493      */
 494     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
 495         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
 496             attribStat(l.head, env);
 497     }
 498 
 499     /** Attribute the arguments in a method call, returning a list of types.
 500      */
 501     List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
 502         ListBuffer<Type> argtypes = new ListBuffer<Type>();
 503         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
 504             argtypes.append(chk.checkNonVoid(
 505                 l.head.pos(), types.upperBound(attribTree(l.head, env, VAL, Infer.anyPoly))));
 506         return argtypes.toList();
 507     }
 508 
 509     /** Attribute a type argument list, returning a list of types.
 510      *  Caller is responsible for calling checkRefTypes.
 511      */
 512     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
 513         ListBuffer<Type> argtypes = new ListBuffer<Type>();
 514         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
 515             argtypes.append(attribType(l.head, env));
 516         return argtypes.toList();
 517     }
 518 
 519     /** Attribute a type argument list, returning a list of types.
 520      *  Check that all the types are references.
 521      */
 522     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
 523         List<Type> types = attribAnyTypes(trees, env);
 524         return chk.checkRefTypes(trees, types);
 525     }
 526 
 527     /**
 528      * Attribute type variables (of generic classes or methods).
 529      * Compound types are attributed later in attribBounds.
 530      * @param typarams the type variables to enter
 531      * @param env      the current environment
 532      */
 533     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
 534         for (JCTypeParameter tvar : typarams) {
 535             TypeVar a = (TypeVar)tvar.type;
 536             a.tsym.flags_field |= UNATTRIBUTED;
 537             a.bound = Type.noType;
 538             if (!tvar.bounds.isEmpty()) {
 539                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
 540                 for (JCExpression bound : tvar.bounds.tail)
 541                     bounds = bounds.prepend(attribType(bound, env));
 542                 types.setBounds(a, bounds.reverse());
 543             } else {
 544                 // if no bounds are given, assume a single bound of
 545                 // java.lang.Object.
 546                 types.setBounds(a, List.of(syms.objectType));
 547             }
 548             a.tsym.flags_field &= ~UNATTRIBUTED;
 549         }
 550         for (JCTypeParameter tvar : typarams)
 551             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
 552         attribStats(typarams, env);
 553     }
 554 
 555     void attribBounds(List<JCTypeParameter> typarams) {
 556         for (JCTypeParameter typaram : typarams) {
 557             Type bound = typaram.type.getUpperBound();
 558             if (bound != null && bound.tsym instanceof ClassSymbol) {
 559                 ClassSymbol c = (ClassSymbol)bound.tsym;
 560                 if ((c.flags_field & COMPOUND) != 0) {
 561                     Assert.check((c.flags_field & UNATTRIBUTED) != 0, c);
 562                     attribClass(typaram.pos(), c);
 563                 }
 564             }
 565         }
 566     }
 567 
 568     /**
 569      * Attribute the type references in a list of annotations.
 570      */
 571     void attribAnnotationTypes(List<JCAnnotation> annotations,
 572                                Env<AttrContext> env) {
 573         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
 574             JCAnnotation a = al.head;
 575             attribType(a.annotationType, env);
 576         }
 577     }
 578 
 579     /**
 580      * Attribute a "lazy constant value".
 581      *  @param env         The env for the const value
 582      *  @param initializer The initializer for the const value
 583      *  @param type        The expected type, or null
 584      *  @see VarSymbol#setlazyConstValue
 585      */
 586     public Object attribLazyConstantValue(Env<AttrContext> env,
 587                                       JCTree.JCExpression initializer,
 588                                       Type type) {
 589 
 590         // in case no lint value has been set up for this env, scan up
 591         // env stack looking for smallest enclosing env for which it is set.
 592         Env<AttrContext> lintEnv = env;
 593         while (lintEnv.info.lint == null)
 594             lintEnv = lintEnv.next;
 595 
 596         // Having found the enclosing lint value, we can initialize the lint value for this class
 597         env.info.lint = lintEnv.info.lint.augment(env.info.enclVar.attributes_field, env.info.enclVar.flags());
 598 
 599         Lint prevLint = chk.setLint(env.info.lint);
 600         JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
 601 
 602         try {
 603             Type itype = attribExpr(initializer, env, type);
 604             if (itype.constValue() != null)
 605                 return coerce(itype, type).constValue();
 606             else
 607                 return null;
 608         } finally {
 609             env.info.lint = prevLint;
 610             log.useSource(prevSource);
 611         }
 612     }
 613 
 614     /** Attribute type reference in an `extends' or `implements' clause.
 615      *  Supertypes of anonymous inner classes are usually already attributed.
 616      *
 617      *  @param tree              The tree making up the type reference.
 618      *  @param env               The environment current at the reference.
 619      *  @param classExpected     true if only a class is expected here.
 620      *  @param interfaceExpected true if only an interface is expected here.
 621      */
 622     Type attribBase(JCTree tree,
 623                     Env<AttrContext> env,
 624                     boolean classExpected,
 625                     boolean interfaceExpected,
 626                     boolean checkExtensible) {
 627         Type t = tree.type != null ?
 628             tree.type :
 629             attribType(tree, env);
 630         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
 631     }
 632     Type checkBase(Type t,
 633                    JCTree tree,
 634                    Env<AttrContext> env,
 635                    boolean classExpected,
 636                    boolean interfaceExpected,
 637                    boolean checkExtensible) {
 638         if (t.isErroneous())
 639             return t;
 640         if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) {
 641             // check that type variable is already visible
 642             if (t.getUpperBound() == null) {
 643                 log.error(tree.pos(), "illegal.forward.ref");
 644                 return types.createErrorType(t);
 645             }
 646         } else {
 647             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
 648         }
 649         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
 650             log.error(tree.pos(), "intf.expected.here");
 651             // return errType is necessary since otherwise there might
 652             // be undetected cycles which cause attribution to loop
 653             return types.createErrorType(t);
 654         } else if (checkExtensible &&
 655                    classExpected &&
 656                    (t.tsym.flags() & INTERFACE) != 0) {
 657                 log.error(tree.pos(), "no.intf.expected.here");
 658             return types.createErrorType(t);
 659         }
 660         if (checkExtensible &&
 661             ((t.tsym.flags() & FINAL) != 0)) {
 662             log.error(tree.pos(),
 663                       "cant.inherit.from.final", t.tsym);
 664         }
 665         chk.checkNonCyclic(tree.pos(), t);
 666         return t;
 667     }
 668 
 669     public void visitClassDef(JCClassDecl tree) {
 670         // Local classes have not been entered yet, so we need to do it now:
 671         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
 672             enter.classEnter(tree, env);
 673 
 674         ClassSymbol c = tree.sym;
 675         if (c == null) {
 676             // exit in case something drastic went wrong during enter.
 677             result = null;
 678         } else {
 679             // make sure class has been completed:
 680             c.complete();
 681 
 682             // If this class appears as an anonymous class
 683             // in a superclass constructor call where
 684             // no explicit outer instance is given,
 685             // disable implicit outer instance from being passed.
 686             // (This would be an illegal access to "this before super").
 687             if (env.info.isSelfCall &&
 688                 env.tree.getTag() == JCTree.NEWCLASS &&
 689                 ((JCNewClass) env.tree).encl == null)
 690             {
 691                 c.flags_field |= NOOUTERTHIS;
 692             }
 693             attribClass(tree.pos(), c);
 694             result = tree.type = c.type;
 695         }
 696     }
 697 
 698     public void visitMethodDef(JCMethodDecl tree) {
 699         MethodSymbol m = tree.sym;
 700 
 701         Lint lint = env.info.lint.augment(m.attributes_field, m.flags());
 702         Lint prevLint = chk.setLint(lint);
 703         MethodSymbol prevMethod = chk.setMethod(m);
 704         try {
 705             deferredLintHandler.flush(tree.pos());
 706             chk.checkDeprecatedAnnotation(tree.pos(), m);
 707 
 708             attribBounds(tree.typarams);
 709 
 710             // If we override any other methods, check that we do so properly.
 711             // JLS ???
 712             if (m.isStatic()) {
 713                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
 714             } else {
 715                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
 716             }
 717             chk.checkOverride(tree, m);
 718 
 719             // Create a new environment with local scope
 720             // for attributing the method.
 721             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
 722 
 723             localEnv.info.lint = lint;
 724 
 725             // Enter all type parameters into the local method scope.
 726             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
 727                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
 728 
 729             ClassSymbol owner = env.enclClass.sym;
 730             if ((owner.flags() & ANNOTATION) != 0 &&
 731                 tree.params.nonEmpty())
 732                 log.error(tree.params.head.pos(),
 733                           "intf.annotation.members.cant.have.params");
 734 
 735             // Attribute all value parameters.
 736             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
 737                 attribStat(l.head, localEnv);
 738             }
 739 
 740             chk.checkVarargsMethodDecl(localEnv, tree);
 741 
 742             // Check that type parameters are well-formed.
 743             chk.validate(tree.typarams, localEnv);
 744 
 745             // Check that result type is well-formed.
 746             chk.validate(tree.restype, localEnv);
 747 
 748             // annotation method checks
 749             if ((owner.flags() & ANNOTATION) != 0) {
 750                 // annotation method cannot have throws clause
 751                 if (tree.thrown.nonEmpty()) {
 752                     log.error(tree.thrown.head.pos(),
 753                             "throws.not.allowed.in.intf.annotation");
 754                 }
 755                 // annotation method cannot declare type-parameters
 756                 if (tree.typarams.nonEmpty()) {
 757                     log.error(tree.typarams.head.pos(),
 758                             "intf.annotation.members.cant.have.type.params");
 759                 }
 760                 // validate annotation method's return type (could be an annotation type)
 761                 chk.validateAnnotationType(tree.restype);
 762                 // ensure that annotation method does not clash with members of Object/Annotation
 763                 chk.validateAnnotationMethod(tree.pos(), m);
 764 
 765                 if (tree.defaultValue != null) {
 766                     // if default value is an annotation, check it is a well-formed
 767                     // annotation value (e.g. no duplicate values, no missing values, etc.)
 768                     chk.validateAnnotationTree(tree.defaultValue);
 769                 }
 770             }
 771 
 772             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
 773                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
 774 
 775             if (tree.body == null) {
 776                 // Empty bodies are only allowed for
 777                 // abstract, native, or interface methods, or for methods
 778                 // in a retrofit signature class.
 779                 if ((owner.flags() & INTERFACE) == 0 &&
 780                     (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
 781                     !relax)
 782                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
 783                 if (tree.defaultValue != null) {
 784                     if ((owner.flags() & ANNOTATION) == 0)
 785                         log.error(tree.pos(),
 786                                   "default.allowed.in.intf.annotation.member");
 787                 }
 788             } else if ((owner.flags() & INTERFACE) != 0) {
 789                 log.error(tree.body.pos(), "intf.meth.cant.have.body");
 790             } else if ((tree.mods.flags & ABSTRACT) != 0) {
 791                 log.error(tree.pos(), "abstract.meth.cant.have.body");
 792             } else if ((tree.mods.flags & NATIVE) != 0) {
 793                 log.error(tree.pos(), "native.meth.cant.have.body");
 794             } else {
 795                 // Add an implicit super() call unless an explicit call to
 796                 // super(...) or this(...) is given
 797                 // or we are compiling class java.lang.Object.
 798                 if (tree.name == names.init && owner.type != syms.objectType) {
 799                     JCBlock body = tree.body;
 800                     if (body.stats.isEmpty() ||
 801                         !TreeInfo.isSelfCall(body.stats.head)) {
 802                         body.stats = body.stats.
 803                             prepend(memberEnter.SuperCall(make.at(body.pos),
 804                                                           List.<Type>nil(),
 805                                                           List.<JCVariableDecl>nil(),
 806                                                           false));
 807                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
 808                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
 809                                TreeInfo.isSuperCall(body.stats.head)) {
 810                         // enum constructors are not allowed to call super
 811                         // directly, so make sure there aren't any super calls
 812                         // in enum constructors, except in the compiler
 813                         // generated one.
 814                         log.error(tree.body.stats.head.pos(),
 815                                   "call.to.super.not.allowed.in.enum.ctor",
 816                                   env.enclClass.sym);
 817                     }
 818                 }
 819 
 820                 // Attribute method body.
 821                 attribStat(tree.body, localEnv);
 822             }
 823             localEnv.info.scope.leave();
 824             result = tree.type = m.type;
 825             chk.validateAnnotations(tree.mods.annotations, m);
 826         }
 827         finally {
 828             chk.setLint(prevLint);
 829             chk.setMethod(prevMethod);
 830         }
 831     }
 832 
 833     public void visitVarDef(JCVariableDecl tree) {
 834         // Local variables have not been entered yet, so we need to do it now:
 835         if (env.info.scope.owner.kind == MTH) {
 836             if (tree.sym != null) {
 837                 // parameters have already been entered
 838                 env.info.scope.enter(tree.sym);
 839             } else {
 840                 memberEnter.memberEnter(tree, env);
 841                 annotate.flush();
 842             }
 843             tree.sym.flags_field |= EFFECTIVELY_FINAL;
 844         }
 845 
 846         VarSymbol v = tree.sym;
 847         Lint lint = env.info.lint.augment(v.attributes_field, v.flags());
 848         Lint prevLint = chk.setLint(lint);
 849 
 850         // Check that the variable's declared type is well-formed.
 851         chk.validate(tree.vartype, env);
 852         deferredLintHandler.flush(tree.pos());
 853 
 854         try {
 855             chk.checkDeprecatedAnnotation(tree.pos(), v);
 856 
 857             if (tree.init != null) {
 858                 if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS) {
 859                     // In this case, `v' is final.  Ensure that it's initializer is
 860                     // evaluated.
 861                     v.getConstValue(); // ensure initializer is evaluated
 862                 } else {
 863                     // Attribute initializer in a new environment
 864                     // with the declared variable as owner.
 865                     // Check that initializer conforms to variable's declared type.
 866                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
 867                     initEnv.info.lint = lint;
 868                     // In order to catch self-references, we set the variable's
 869                     // declaration position to maximal possible value, effectively
 870                     // marking the variable as undefined.
 871                     initEnv.info.enclVar = v;
 872                     attribExpr(tree.init, initEnv, v.type);
 873                 }
 874             }
 875             result = tree.type = v.type;
 876             chk.validateAnnotations(tree.mods.annotations, v);
 877         }
 878         finally {
 879             chk.setLint(prevLint);
 880         }
 881     }
 882 
 883     public void visitSkip(JCSkip tree) {
 884         result = null;
 885     }
 886 
 887     public void visitBlock(JCBlock tree) {
 888         if (env.info.scope.owner.kind == TYP) {
 889             // Block is a static or instance initializer;
 890             // let the owner of the environment be a freshly
 891             // created BLOCK-method.
 892             Env<AttrContext> localEnv =
 893                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
 894             localEnv.info.scope.owner =
 895                 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
 896                                  env.info.scope.owner);
 897             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
 898             attribStats(tree.stats, localEnv);
 899         } else {
 900             // Create a new local environment with a local scope.
 901             Env<AttrContext> localEnv =
 902                 env.dup(tree, env.info.dup(env.info.scope.dup()));
 903             attribStats(tree.stats, localEnv);
 904             localEnv.info.scope.leave();
 905         }
 906         result = null;
 907     }
 908 
 909     public void visitDoLoop(JCDoWhileLoop tree) {
 910         attribStat(tree.body, env.dup(tree));
 911         attribExpr(tree.cond, env, syms.booleanType);
 912         result = null;
 913     }
 914 
 915     public void visitWhileLoop(JCWhileLoop tree) {
 916         attribExpr(tree.cond, env, syms.booleanType);
 917         attribStat(tree.body, env.dup(tree));
 918         result = null;
 919     }
 920 
 921     public void visitForLoop(JCForLoop tree) {
 922         Env<AttrContext> loopEnv =
 923             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
 924         attribStats(tree.init, loopEnv);
 925         if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
 926         loopEnv.tree = tree; // before, we were not in loop!
 927         attribStats(tree.step, loopEnv);
 928         attribStat(tree.body, loopEnv);
 929         loopEnv.info.scope.leave();
 930         result = null;
 931     }
 932 
 933     public void visitForeachLoop(JCEnhancedForLoop tree) {
 934         Env<AttrContext> loopEnv =
 935             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
 936         attribStat(tree.var, loopEnv);
 937         Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
 938         chk.checkNonVoid(tree.pos(), exprType);
 939         Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
 940         if (elemtype == null) {
 941             // or perhaps expr implements Iterable<T>?
 942             Type base = types.asSuper(exprType, syms.iterableType.tsym);
 943             if (base == null) {
 944                 log.error(tree.expr.pos(),
 945                         "foreach.not.applicable.to.type",
 946                         exprType,
 947                         diags.fragment("type.req.array.or.iterable"));
 948                 elemtype = types.createErrorType(exprType);
 949             } else {
 950                 List<Type> iterableParams = base.allparams();
 951                 elemtype = iterableParams.isEmpty()
 952                     ? syms.objectType
 953                     : types.upperBound(iterableParams.head);
 954             }
 955         }
 956         chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
 957         loopEnv.tree = tree; // before, we were not in loop!
 958         attribStat(tree.body, loopEnv);
 959         loopEnv.info.scope.leave();
 960         result = null;
 961     }
 962 
 963     public void visitLabelled(JCLabeledStatement tree) {
 964         // Check that label is not used in an enclosing statement
 965         Env<AttrContext> env1 = env;
 966         while (env1 != null && env1.tree.getTag() != JCTree.CLASSDEF) {
 967             if (env1.tree.getTag() == JCTree.LABELLED &&
 968                 ((JCLabeledStatement) env1.tree).label == tree.label) {
 969                 log.error(tree.pos(), "label.already.in.use",
 970                           tree.label);
 971                 break;
 972             }
 973             env1 = env1.next;
 974         }
 975 
 976         attribStat(tree.body, env.dup(tree));
 977         result = null;
 978     }
 979 
 980     public void visitSwitch(JCSwitch tree) {
 981         Type seltype = attribExpr(tree.selector, env);
 982 
 983         Env<AttrContext> switchEnv =
 984             env.dup(tree, env.info.dup(env.info.scope.dup()));
 985 
 986         boolean enumSwitch =
 987             allowEnums &&
 988             (seltype.tsym.flags() & Flags.ENUM) != 0;
 989         boolean stringSwitch = false;
 990         if (types.isSameType(seltype, syms.stringType)) {
 991             if (allowStringsInSwitch) {
 992                 stringSwitch = true;
 993             } else {
 994                 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
 995             }
 996         }
 997         if (!enumSwitch && !stringSwitch)
 998             seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
 999 
1000         // Attribute all cases and
1001         // check that there are no duplicate case labels or default clauses.
1002         Set<Object> labels = new HashSet<Object>(); // The set of case labels.
1003         boolean hasDefault = false;      // Is there a default label?
1004         for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
1005             JCCase c = l.head;
1006             Env<AttrContext> caseEnv =
1007                 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
1008             if (c.pat != null) {
1009                 if (enumSwitch) {
1010                     Symbol sym = enumConstant(c.pat, seltype);
1011                     if (sym == null) {
1012                         log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
1013                     } else if (!labels.add(sym)) {
1014                         log.error(c.pos(), "duplicate.case.label");
1015                     }
1016                 } else {
1017                     Type pattype = attribExpr(c.pat, switchEnv, seltype);
1018                     if (pattype.tag != ERROR) {
1019                         if (pattype.constValue() == null) {
1020                             log.error(c.pat.pos(),
1021                                       (stringSwitch ? "string.const.req" : "const.expr.req"));
1022                         } else if (labels.contains(pattype.constValue())) {
1023                             log.error(c.pos(), "duplicate.case.label");
1024                         } else {
1025                             labels.add(pattype.constValue());
1026                         }
1027                     }
1028                 }
1029             } else if (hasDefault) {
1030                 log.error(c.pos(), "duplicate.default.label");
1031             } else {
1032                 hasDefault = true;
1033             }
1034             attribStats(c.stats, caseEnv);
1035             caseEnv.info.scope.leave();
1036             addVars(c.stats, switchEnv.info.scope);
1037         }
1038 
1039         switchEnv.info.scope.leave();
1040         result = null;
1041     }
1042     // where
1043         /** Add any variables defined in stats to the switch scope. */
1044         private static void addVars(List<JCStatement> stats, Scope switchScope) {
1045             for (;stats.nonEmpty(); stats = stats.tail) {
1046                 JCTree stat = stats.head;
1047                 if (stat.getTag() == JCTree.VARDEF)
1048                     switchScope.enter(((JCVariableDecl) stat).sym);
1049             }
1050         }
1051     // where
1052     /** Return the selected enumeration constant symbol, or null. */
1053     private Symbol enumConstant(JCTree tree, Type enumType) {
1054         if (tree.getTag() != JCTree.IDENT) {
1055             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
1056             return syms.errSymbol;
1057         }
1058         JCIdent ident = (JCIdent)tree;
1059         Name name = ident.name;
1060         for (Scope.Entry e = enumType.tsym.members().lookup(name);
1061              e.scope != null; e = e.next()) {
1062             if (e.sym.kind == VAR) {
1063                 Symbol s = ident.sym = e.sym;
1064                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1065                 ident.type = s.type;
1066                 return ((s.flags_field & Flags.ENUM) == 0)
1067                     ? null : s;
1068             }
1069         }
1070         return null;
1071     }
1072 
1073     public void visitSynchronized(JCSynchronized tree) {
1074         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1075         attribStat(tree.body, env);
1076         result = null;
1077     }
1078 
1079     public void visitTry(JCTry tree) {
1080         // Create a new local environment with a local
1081         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1082         boolean isTryWithResource = tree.resources.nonEmpty();
1083         // Create a nested environment for attributing the try block if needed
1084         Env<AttrContext> tryEnv = isTryWithResource ?
1085             env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1086             localEnv;
1087         // Attribute resource declarations
1088         for (JCTree resource : tree.resources) {
1089             if (resource.getTag() == JCTree.VARDEF) {
1090                 attribStat(resource, tryEnv);
1091                 chk.checkType(resource, resource.type, syms.autoCloseableType, "try.not.applicable.to.type");
1092 
1093                 //check that resource type cannot throw InterruptedException
1094                 checkAutoCloseable(resource.pos(), localEnv, resource.type);
1095 
1096                 VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource);
1097                 var.setData(ElementKind.RESOURCE_VARIABLE);
1098             } else {
1099                 attribExpr(resource, tryEnv, syms.autoCloseableType, "try.not.applicable.to.type");
1100             }
1101         }
1102         // Attribute body
1103         attribStat(tree.body, tryEnv);
1104         if (isTryWithResource)
1105             tryEnv.info.scope.leave();
1106 
1107         // Attribute catch clauses
1108         for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1109             JCCatch c = l.head;
1110             Env<AttrContext> catchEnv =
1111                 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
1112             Type ctype = attribStat(c.param, catchEnv);
1113             if (TreeInfo.isMultiCatch(c)) {
1114                 //multi-catch parameter is implicitly marked as final
1115                 c.param.sym.flags_field |= FINAL | DISJUNCTION;
1116             }
1117             if (c.param.sym.kind == Kinds.VAR) {
1118                 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
1119             }
1120             chk.checkType(c.param.vartype.pos(),
1121                           chk.checkClassType(c.param.vartype.pos(), ctype),
1122                           syms.throwableType);
1123             attribStat(c.body, catchEnv);
1124             catchEnv.info.scope.leave();
1125         }
1126 
1127         // Attribute finalizer
1128         if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1129 
1130         localEnv.info.scope.leave();
1131         result = null;
1132     }
1133 
1134     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
1135         if (!resource.isErroneous() &&
1136                 types.asSuper(resource, syms.autoCloseableType.tsym) != null) {
1137             Symbol close = syms.noSymbol;
1138             boolean prevDeferDiags = log.deferDiagnostics;
1139             Queue<JCDiagnostic> prevDeferredDiags = log.deferredDiagnostics;
1140             try {
1141                 log.deferDiagnostics = true;
1142                 log.deferredDiagnostics = ListBuffer.lb();
1143                 close = rs.resolveQualifiedMethod(pos,
1144                         env,
1145                         resource,
1146                         names.close,
1147                         List.<Type>nil(),
1148                         List.<Type>nil());
1149             }
1150             finally {
1151                 log.deferDiagnostics = prevDeferDiags;
1152                 log.deferredDiagnostics = prevDeferredDiags;
1153             }
1154             if (close.kind == MTH &&
1155                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
1156                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
1157                     env.info.lint.isEnabled(LintCategory.TRY)) {
1158                 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
1159             }
1160         }
1161     }
1162 
1163     public void visitConditional(JCConditional tree) {
1164         attribExpr(tree.cond, env, syms.booleanType);
1165         attribExpr(tree.truepart, env);
1166         attribExpr(tree.falsepart, env);
1167         result = check(tree,
1168                        capture(condType(tree.pos(), tree.cond.type,
1169                                         tree.truepart.type, tree.falsepart.type)),
1170                        VAL, pkind, pt);
1171     }
1172     //where
1173         /** Compute the type of a conditional expression, after
1174          *  checking that it exists. See Spec 15.25.
1175          *
1176          *  @param pos      The source position to be used for
1177          *                  error diagnostics.
1178          *  @param condtype The type of the expression's condition.
1179          *  @param thentype The type of the expression's then-part.
1180          *  @param elsetype The type of the expression's else-part.
1181          */
1182         private Type condType(DiagnosticPosition pos,
1183                               Type condtype,
1184                               Type thentype,
1185                               Type elsetype) {
1186             Type ctype = condType1(pos, condtype, thentype, elsetype);
1187 
1188             // If condition and both arms are numeric constants,
1189             // evaluate at compile-time.
1190             return ((condtype.constValue() != null) &&
1191                     (thentype.constValue() != null) &&
1192                     (elsetype.constValue() != null))
1193                 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
1194                 : ctype;
1195         }
1196         /** Compute the type of a conditional expression, after
1197          *  checking that it exists.  Does not take into
1198          *  account the special case where condition and both arms
1199          *  are constants.
1200          *
1201          *  @param pos      The source position to be used for error
1202          *                  diagnostics.
1203          *  @param condtype The type of the expression's condition.
1204          *  @param thentype The type of the expression's then-part.
1205          *  @param elsetype The type of the expression's else-part.
1206          */
1207         private Type condType1(DiagnosticPosition pos, Type condtype,
1208                                Type thentype, Type elsetype) {
1209             // If same type, that is the result
1210             if (types.isSameType(thentype, elsetype))
1211                 return thentype.baseType();
1212 
1213             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
1214                 ? thentype : types.unboxedType(thentype);
1215             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
1216                 ? elsetype : types.unboxedType(elsetype);
1217 
1218             // Otherwise, if both arms can be converted to a numeric
1219             // type, return the least numeric type that fits both arms
1220             // (i.e. return larger of the two, or return int if one
1221             // arm is short, the other is char).
1222             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
1223                 // If one arm has an integer subrange type (i.e., byte,
1224                 // short, or char), and the other is an integer constant
1225                 // that fits into the subrange, return the subrange type.
1226                 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
1227                     types.isAssignable(elseUnboxed, thenUnboxed))
1228                     return thenUnboxed.baseType();
1229                 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
1230                     types.isAssignable(thenUnboxed, elseUnboxed))
1231                     return elseUnboxed.baseType();
1232 
1233                 for (int i = BYTE; i < VOID; i++) {
1234                     Type candidate = syms.typeOfTag[i];
1235                     if (types.isSubtype(thenUnboxed, candidate) &&
1236                         types.isSubtype(elseUnboxed, candidate))
1237                         return candidate;
1238                 }
1239             }
1240 
1241             // Those were all the cases that could result in a primitive
1242             if (allowBoxing) {
1243                 if (thentype.isPrimitive())
1244                     thentype = types.boxedClass(thentype).type;
1245                 if (elsetype.isPrimitive())
1246                     elsetype = types.boxedClass(elsetype).type;
1247             }
1248 
1249             if (types.isSubtype(thentype, elsetype))
1250                 return elsetype.baseType();
1251             if (types.isSubtype(elsetype, thentype))
1252                 return thentype.baseType();
1253 
1254             if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
1255                 log.error(pos, "neither.conditional.subtype",
1256                           thentype, elsetype);
1257                 return thentype.baseType();
1258             }
1259 
1260             // both are known to be reference types.  The result is
1261             // lub(thentype,elsetype). This cannot fail, as it will
1262             // always be possible to infer "Object" if nothing better.
1263             return types.lub(thentype.baseType(), elsetype.baseType());
1264         }
1265 
1266     public void visitIf(JCIf tree) {
1267         attribExpr(tree.cond, env, syms.booleanType);
1268         attribStat(tree.thenpart, env);
1269         if (tree.elsepart != null)
1270             attribStat(tree.elsepart, env);
1271         chk.checkEmptyIf(tree);
1272         result = null;
1273     }
1274 
1275     public void visitExec(JCExpressionStatement tree) {
1276         //a fresh environment is required for 292 inference to work properly ---
1277         //see Infer.instantiatePolymorphicSignatureInstance()
1278         Env<AttrContext> localEnv = env.dup(tree);
1279         attribExpr(tree.expr, localEnv);
1280         result = null;
1281     }
1282 
1283     public void visitBreak(JCBreak tree) {
1284         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1285         result = null;
1286     }
1287 
1288     public void visitContinue(JCContinue tree) {
1289         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1290         result = null;
1291     }
1292     //where
1293         /** Return the target of a break or continue statement, if it exists,
1294          *  report an error if not.
1295          *  Note: The target of a labelled break or continue is the
1296          *  (non-labelled) statement tree referred to by the label,
1297          *  not the tree representing the labelled statement itself.
1298          *
1299          *  @param pos     The position to be used for error diagnostics
1300          *  @param tag     The tag of the jump statement. This is either
1301          *                 Tree.BREAK or Tree.CONTINUE.
1302          *  @param label   The label of the jump statement, or null if no
1303          *                 label is given.
1304          *  @param env     The environment current at the jump statement.
1305          */
1306         private JCTree findJumpTarget(DiagnosticPosition pos,
1307                                     int tag,
1308                                     Name label,
1309                                     Env<AttrContext> env) {
1310             // Search environments outwards from the point of jump.
1311             Env<AttrContext> env1 = env;
1312             LOOP:
1313             while (env1 != null) {
1314                 switch (env1.tree.getTag()) {
1315                 case JCTree.LABELLED:
1316                     JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
1317                     if (label == labelled.label) {
1318                         // If jump is a continue, check that target is a loop.
1319                         if (tag == JCTree.CONTINUE) {
1320                             if (labelled.body.getTag() != JCTree.DOLOOP &&
1321                                 labelled.body.getTag() != JCTree.WHILELOOP &&
1322                                 labelled.body.getTag() != JCTree.FORLOOP &&
1323                                 labelled.body.getTag() != JCTree.FOREACHLOOP)
1324                                 log.error(pos, "not.loop.label", label);
1325                             // Found labelled statement target, now go inwards
1326                             // to next non-labelled tree.
1327                             return TreeInfo.referencedStatement(labelled);
1328                         } else {
1329                             return labelled;
1330                         }
1331                     }
1332                     break;
1333                 case JCTree.DOLOOP:
1334                 case JCTree.WHILELOOP:
1335                 case JCTree.FORLOOP:
1336                 case JCTree.FOREACHLOOP:
1337                     if (label == null) return env1.tree;
1338                     break;
1339                 case JCTree.SWITCH:
1340                     if (label == null && tag == JCTree.BREAK) return env1.tree;
1341                     break;
1342                 case JCTree.METHODDEF:
1343                 case JCTree.CLASSDEF:
1344                     break LOOP;
1345                 default:
1346                 }
1347                 env1 = env1.next;
1348             }
1349             if (label != null)
1350                 log.error(pos, "undef.label", label);
1351             else if (tag == JCTree.CONTINUE)
1352                 log.error(pos, "cont.outside.loop");
1353             else
1354                 log.error(pos, "break.outside.switch.loop");
1355             return null;
1356         }
1357 
1358     public void visitReturn(JCReturn tree) {
1359         // Check that there is an enclosing method which is
1360         // nested within than the enclosing class.
1361         if (env.enclMethod == null ||
1362             env.enclMethod.sym.owner != env.enclClass.sym) {
1363             log.error(tree.pos(), "ret.outside.meth");
1364 
1365         } else {
1366             // Attribute return expression, if it exists, and check that
1367             // it conforms to result type of enclosing method.
1368             Symbol m = env.enclMethod.sym;
1369             if (m.type.getReturnType().tag == VOID) {
1370                 if (tree.expr != null)
1371                     log.error(tree.expr.pos(),
1372                               "cant.ret.val.from.meth.decl.void");
1373             } else if (tree.expr == null) {
1374                 log.error(tree.pos(), "missing.ret.val");
1375             } else {
1376                 attribExpr(tree.expr, env, m.type.getReturnType());
1377             }
1378         }
1379         result = null;
1380     }
1381 
1382     public void visitThrow(JCThrow tree) {
1383         attribExpr(tree.expr, env, syms.throwableType);
1384         result = null;
1385     }
1386 
1387     public void visitAssert(JCAssert tree) {
1388         attribExpr(tree.cond, env, syms.booleanType);
1389         if (tree.detail != null) {
1390             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
1391         }
1392         result = null;
1393     }
1394 
1395      /** Visitor method for method invocations.
1396      *  NOTE: The method part of an application will have in its type field
1397      *        the return type of the method, not the method's type itself!
1398      */
1399     public void visitApply(JCMethodInvocation tree) {
1400         // The local environment of a method application is
1401         // a new environment nested in the current one.
1402         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1403 
1404         // The types of the actual method arguments.
1405         List<Type> argtypes;
1406 
1407         // The types of the actual method type arguments.
1408         List<Type> typeargtypes = null;
1409 
1410         Name methName = TreeInfo.name(tree.meth);
1411 
1412         boolean isConstructorCall =
1413             methName == names._this || methName == names._super;
1414 
1415         if (isConstructorCall) {
1416             // We are seeing a ...this(...) or ...super(...) call.
1417             // Check that this is the first statement in a constructor.
1418             if (checkFirstConstructorStat(tree, env)) {
1419 
1420                 // Record the fact
1421                 // that this is a constructor call (using isSelfCall).
1422                 localEnv.info.isSelfCall = true;
1423 
1424                 // Attribute arguments, yielding list of argument types.
1425                 argtypes = attribArgs(tree.args, localEnv);
1426                 typeargtypes = attribTypes(tree.typeargs, localEnv);
1427 
1428                 // Variable `site' points to the class in which the called
1429                 // constructor is defined.
1430                 Type site = env.enclClass.sym.type;
1431                 if (methName == names._super) {
1432                     if (site == syms.objectType) {
1433                         log.error(tree.meth.pos(), "no.superclass", site);
1434                         site = types.createErrorType(syms.objectType);
1435                     } else {
1436                         site = types.supertype(site);
1437                     }
1438                 }
1439 
1440                 if (site.tag == CLASS) {
1441                     Type encl = site.getEnclosingType();
1442                     while (encl != null && encl.tag == TYPEVAR)
1443                         encl = encl.getUpperBound();
1444                     if (encl.tag == CLASS) {
1445                         // we are calling a nested class
1446 
1447                         if (tree.meth.getTag() == JCTree.SELECT) {
1448                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
1449 
1450                             // We are seeing a prefixed call, of the form
1451                             //     <expr>.super(...).
1452                             // Check that the prefix expression conforms
1453                             // to the outer instance type of the class.
1454                             chk.checkRefType(qualifier.pos(),
1455                                              attribExpr(qualifier, localEnv,
1456                                                         encl));
1457                         } else if (methName == names._super) {
1458                             // qualifier omitted; check for existence
1459                             // of an appropriate implicit qualifier.
1460                             rs.resolveImplicitThis(tree.meth.pos(),
1461                                                    localEnv, site, true);
1462                         }
1463                     } else if (tree.meth.getTag() == JCTree.SELECT) {
1464                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
1465                                   site.tsym);
1466                     }
1467 
1468                     // if we're calling a java.lang.Enum constructor,
1469                     // prefix the implicit String and int parameters
1470                     if (site.tsym == syms.enumSym && allowEnums)
1471                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
1472 
1473                     // Resolve the called constructor under the assumption
1474                     // that we are referring to a superclass instance of the
1475                     // current instance (JLS ???).
1476                     boolean selectSuperPrev = localEnv.info.selectSuper;
1477                     localEnv.info.selectSuper = true;
1478                     localEnv.info.varArgs = false;
1479                     Symbol sym = rs.resolveConstructor(
1480                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
1481                     localEnv.info.selectSuper = selectSuperPrev;
1482 
1483                     // Set method symbol to resolved constructor...
1484                     TreeInfo.setSymbol(tree.meth, sym);
1485 
1486                     // ...and check that it is legal in the current context.
1487                     // (this will also set the tree's type)
1488                     Type mpt = newMethTemplate(argtypes, typeargtypes);
1489                     checkId(tree.meth, site, sym, localEnv, MTH,
1490                             mpt, tree.varargsElement != null);
1491                 }
1492                 // Otherwise, `site' is an error type and we do nothing
1493             }
1494             result = tree.type = syms.voidType;
1495         } else {
1496             // Otherwise, we are seeing a regular method call.
1497             // Attribute the arguments, yielding list of argument types, ...
1498             argtypes = attribArgs(tree.args, localEnv);
1499             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
1500 
1501             // ... and attribute the method using as a prototype a methodtype
1502             // whose formal argument types is exactly the list of actual
1503             // arguments (this will also set the method symbol).
1504             Type mpt = newMethTemplate(argtypes, typeargtypes);
1505             localEnv.info.varArgs = false;
1506             Type mtype = attribExpr(tree.meth, localEnv, mpt);
1507             if (localEnv.info.varArgs)
1508                 Assert.check(mtype.isErroneous() || tree.varargsElement != null);
1509 
1510             // Compute the result type.
1511             Type restype = mtype.getReturnType();
1512             if (restype.tag == WILDCARD)
1513                 throw new AssertionError(mtype);
1514 
1515             // as a special case, array.clone() has a result that is
1516             // the same as static type of the array being cloned
1517             if (tree.meth.getTag() == JCTree.SELECT &&
1518                 allowCovariantReturns &&
1519                 methName == names.clone &&
1520                 types.isArray(((JCFieldAccess) tree.meth).selected.type))
1521                 restype = ((JCFieldAccess) tree.meth).selected.type;
1522 
1523             // as a special case, x.getClass() has type Class<? extends |X|>
1524             if (allowGenerics &&
1525                 methName == names.getClass && tree.args.isEmpty()) {
1526                 Type qualifier = (tree.meth.getTag() == JCTree.SELECT)
1527                     ? ((JCFieldAccess) tree.meth).selected.type
1528                     : env.enclClass.sym.type;
1529                 restype = new
1530                     ClassType(restype.getEnclosingType(),
1531                               List.<Type>of(new WildcardType(types.erasure(qualifier),
1532                                                                BoundKind.EXTENDS,
1533                                                                syms.boundClass)),
1534                               restype.tsym);
1535             }
1536 
1537             chk.checkRefTypes(tree.typeargs, typeargtypes);
1538 
1539             // Check that value of resulting type is admissible in the
1540             // current context.  Also, capture the return type
1541             result = check(tree, capture(restype), VAL, pkind, pt);
1542         }
1543         chk.validate(tree.typeargs, localEnv);
1544     }
1545     //where
1546         /** Check that given application node appears as first statement
1547          *  in a constructor call.
1548          *  @param tree   The application node
1549          *  @param env    The environment current at the application.
1550          */
1551         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
1552             JCMethodDecl enclMethod = env.enclMethod;
1553             if (enclMethod != null && enclMethod.name == names.init) {
1554                 JCBlock body = enclMethod.body;
1555                 if (body.stats.head.getTag() == JCTree.EXEC &&
1556                     ((JCExpressionStatement) body.stats.head).expr == tree)
1557                     return true;
1558             }
1559             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
1560                       TreeInfo.name(tree.meth));
1561             return false;
1562         }
1563 
1564         /** Obtain a method type with given argument types.
1565          */
1566         Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) {
1567             MethodType mt = new MethodType(argtypes, null, null, syms.methodClass);
1568             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
1569         }
1570 
1571     public void visitNewClass(JCNewClass tree) {
1572         Type owntype = types.createErrorType(tree.type);
1573 
1574         // The local environment of a class creation is
1575         // a new environment nested in the current one.
1576         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1577 
1578         // The anonymous inner class definition of the new expression,
1579         // if one is defined by it.
1580         JCClassDecl cdef = tree.def;
1581 
1582         // If enclosing class is given, attribute it, and
1583         // complete class name to be fully qualified
1584         JCExpression clazz = tree.clazz; // Class field following new
1585         JCExpression clazzid =          // Identifier in class field
1586             (clazz.getTag() == JCTree.TYPEAPPLY)
1587             ? ((JCTypeApply) clazz).clazz
1588             : clazz;
1589 
1590         JCExpression clazzid1 = clazzid; // The same in fully qualified form
1591 
1592         if (tree.encl != null) {
1593             // We are seeing a qualified new, of the form
1594             //    <expr>.new C <...> (...) ...
1595             // In this case, we let clazz stand for the name of the
1596             // allocated class C prefixed with the type of the qualifier
1597             // expression, so that we can
1598             // resolve it with standard techniques later. I.e., if
1599             // <expr> has type T, then <expr>.new C <...> (...)
1600             // yields a clazz T.C.
1601             Type encltype = chk.checkRefType(tree.encl.pos(),
1602                                              attribExpr(tree.encl, env));
1603             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
1604                                                  ((JCIdent) clazzid).name);
1605             if (clazz.getTag() == JCTree.TYPEAPPLY)
1606                 clazz = make.at(tree.pos).
1607                     TypeApply(clazzid1,
1608                               ((JCTypeApply) clazz).arguments);
1609             else
1610                 clazz = clazzid1;
1611         }
1612 
1613         // Attribute clazz expression and store
1614         // symbol + type back into the attributed tree.
1615         Type clazztype = attribType(clazz, env);
1616         Pair<Scope,Scope> mapping = getSyntheticScopeMapping(clazztype);
1617         clazztype = chk.checkDiamond(tree, clazztype);
1618         chk.validate(clazz, localEnv);
1619         if (tree.encl != null) {
1620             // We have to work in this case to store
1621             // symbol + type back into the attributed tree.
1622             tree.clazz.type = clazztype;
1623             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
1624             clazzid.type = ((JCIdent) clazzid).sym.type;
1625             if (!clazztype.isErroneous()) {
1626                 if (cdef != null && clazztype.tsym.isInterface()) {
1627                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
1628                 } else if (clazztype.tsym.isStatic()) {
1629                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
1630                 }
1631             }
1632         } else if (!clazztype.tsym.isInterface() &&
1633                    clazztype.getEnclosingType().tag == CLASS) {
1634             // Check for the existence of an apropos outer instance
1635             rs.resolveImplicitThis(tree.pos(), env, clazztype);
1636         }
1637 
1638         // Attribute constructor arguments.
1639         List<Type> argtypes = attribArgs(tree.args, localEnv);
1640         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
1641 
1642         if (TreeInfo.isDiamond(tree) && !clazztype.isErroneous()) {
1643             clazztype = attribDiamond(localEnv, tree, clazztype, mapping, argtypes, typeargtypes);
1644             clazz.type = clazztype;
1645         } else if (allowDiamondFinder &&
1646                 tree.def == null &&
1647                 !clazztype.isErroneous() &&
1648                 clazztype.getTypeArguments().nonEmpty() &&
1649                 findDiamonds) {
1650             boolean prevDeferDiags = log.deferDiagnostics;
1651             Queue<JCDiagnostic> prevDeferredDiags = log.deferredDiagnostics;
1652             Type inferred = null;
1653             try {
1654                 //disable diamond-related diagnostics
1655                 log.deferDiagnostics = true;
1656                 log.deferredDiagnostics = ListBuffer.lb();
1657                 inferred = attribDiamond(localEnv,
1658                         tree,
1659                         clazztype,
1660                         mapping,
1661                         argtypes,
1662                         typeargtypes);
1663             }
1664             finally {
1665                 log.deferDiagnostics = prevDeferDiags;
1666                 log.deferredDiagnostics = prevDeferredDiags;
1667             }
1668             if (inferred != null &&
1669                     !inferred.isErroneous() &&
1670                     inferred.tag == CLASS &&
1671                     types.isAssignable(inferred, pt.tag == NONE ? clazztype : pt, Warner.noWarnings)) {
1672                 String key = types.isSameType(clazztype, inferred) ?
1673                     "diamond.redundant.args" :
1674                     "diamond.redundant.args.1";
1675                 log.warning(tree.clazz.pos(), key, clazztype, inferred);
1676             }
1677         }
1678 
1679         // If we have made no mistakes in the class type...
1680         if (clazztype.tag == CLASS) {
1681             // Enums may not be instantiated except implicitly
1682             if (allowEnums &&
1683                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
1684                 (env.tree.getTag() != JCTree.VARDEF ||
1685                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
1686                  ((JCVariableDecl) env.tree).init != tree))
1687                 log.error(tree.pos(), "enum.cant.be.instantiated");
1688             // Check that class is not abstract
1689             if (cdef == null &&
1690                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
1691                 log.error(tree.pos(), "abstract.cant.be.instantiated",
1692                           clazztype.tsym);
1693             } else if (cdef != null && clazztype.tsym.isInterface()) {
1694                 // Check that no constructor arguments are given to
1695                 // anonymous classes implementing an interface
1696                 if (!argtypes.isEmpty())
1697                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
1698 
1699                 if (!typeargtypes.isEmpty())
1700                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
1701 
1702                 // Error recovery: pretend no arguments were supplied.
1703                 argtypes = List.nil();
1704                 typeargtypes = List.nil();
1705             }
1706 
1707             // Resolve the called constructor under the assumption
1708             // that we are referring to a superclass instance of the
1709             // current instance (JLS ???).
1710             else {
1711                 localEnv.info.selectSuper = cdef != null;
1712                 localEnv.info.varArgs = false;
1713                 tree.constructor = rs.resolveConstructor(
1714                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
1715                 tree.constructorType = tree.constructor.type.isErroneous() ?
1716                     syms.errType :
1717                     checkMethod(clazztype,
1718                         tree.constructor,
1719                         localEnv,
1720                         tree.args,
1721                         argtypes,
1722                         typeargtypes,
1723                         localEnv.info.varArgs);
1724                 if (localEnv.info.varArgs)
1725                     Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
1726             }
1727 
1728             if (cdef != null) {
1729                 // We are seeing an anonymous class instance creation.
1730                 // In this case, the class instance creation
1731                 // expression
1732                 //
1733                 //    E.new <typeargs1>C<typargs2>(args) { ... }
1734                 //
1735                 // is represented internally as
1736                 //
1737                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
1738                 //
1739                 // This expression is then *transformed* as follows:
1740                 //
1741                 // (1) add a STATIC flag to the class definition
1742                 //     if the current environment is static
1743                 // (2) add an extends or implements clause
1744                 // (3) add a constructor.
1745                 //
1746                 // For instance, if C is a class, and ET is the type of E,
1747                 // the expression
1748                 //
1749                 //    E.new <typeargs1>C<typargs2>(args) { ... }
1750                 //
1751                 // is translated to (where X is a fresh name and typarams is the
1752                 // parameter list of the super constructor):
1753                 //
1754                 //   new <typeargs1>X(<*nullchk*>E, args) where
1755                 //     X extends C<typargs2> {
1756                 //       <typarams> X(ET e, args) {
1757                 //         e.<typeargs1>super(args)
1758                 //       }
1759                 //       ...
1760                 //     }
1761                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
1762 
1763                 if (clazztype.tsym.isInterface()) {
1764                     cdef.implementing = List.of(clazz);
1765                 } else {
1766                     cdef.extending = clazz;
1767                 }
1768 
1769                 attribStat(cdef, localEnv);
1770 
1771                 // If an outer instance is given,
1772                 // prefix it to the constructor arguments
1773                 // and delete it from the new expression
1774                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
1775                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
1776                     argtypes = argtypes.prepend(tree.encl.type);
1777                     tree.encl = null;
1778                 }
1779 
1780                 // Reassign clazztype and recompute constructor.
1781                 clazztype = cdef.sym.type;
1782                 Symbol sym = rs.resolveConstructor(
1783                     tree.pos(), localEnv, clazztype, argtypes,
1784                     typeargtypes, true, tree.varargsElement != null);
1785                 Assert.check(sym.kind < AMBIGUOUS || tree.constructor.type.isErroneous());
1786                 tree.constructor = sym;
1787                 if (tree.constructor.kind > ERRONEOUS) {
1788                     tree.constructorType =  syms.errType;
1789                 }
1790                 else {
1791                     tree.constructorType = checkMethod(clazztype,
1792                             tree.constructor,
1793                             localEnv,
1794                             tree.args,
1795                             argtypes,
1796                             typeargtypes,
1797                             localEnv.info.varArgs);
1798                 }
1799             }
1800 
1801             if (tree.constructor != null && tree.constructor.kind == MTH)
1802                 owntype = clazztype;
1803         }
1804         result = check(tree, owntype, VAL, pkind, pt);
1805         chk.validate(tree.typeargs, localEnv);
1806     }
1807 
1808     Type attribDiamond(Env<AttrContext> env,
1809                         JCNewClass tree,
1810                         Type clazztype,
1811                         Pair<Scope, Scope> mapping,
1812                         List<Type> argtypes,
1813                         List<Type> typeargtypes) {
1814         if (clazztype.isErroneous() ||
1815                 clazztype.isInterface() ||
1816                 mapping == erroneousMapping) {
1817             //if the type of the instance creation expression is erroneous,
1818             //or if it's an interface, or if something prevented us to form a valid
1819             //mapping, return the (possibly erroneous) type unchanged
1820             return clazztype;
1821         }
1822 
1823         //dup attribution environment and augment the set of inference variables
1824         Env<AttrContext> localEnv = env.dup(tree);
1825         localEnv.info.tvars = clazztype.tsym.type.getTypeArguments();
1826 
1827         //if the type of the instance creation expression is a class type
1828         //apply method resolution inference (JLS 15.12.2.7). The return type
1829         //of the resolved constructor will be a partially instantiated type
1830         ((ClassSymbol) clazztype.tsym).members_field = mapping.snd;
1831         Symbol constructor;
1832         try {
1833             constructor = rs.resolveDiamond(tree.pos(),
1834                     localEnv,
1835                     clazztype.tsym.type,
1836                     argtypes,
1837                     typeargtypes);
1838         } finally {
1839             ((ClassSymbol) clazztype.tsym).members_field = mapping.fst;
1840         }
1841         if (constructor.kind == MTH) {
1842             ClassType ct = new ClassType(clazztype.getEnclosingType(),
1843                     clazztype.tsym.type.getTypeArguments(),
1844                     clazztype.tsym);
1845             clazztype = checkMethod(ct,
1846                     constructor,
1847                     localEnv,
1848                     tree.args,
1849                     argtypes,
1850                     typeargtypes,
1851                     localEnv.info.varArgs).getReturnType();
1852         } else {
1853             clazztype = syms.errType;
1854         }
1855 
1856         if (clazztype.tag == FORALL && !pt.isErroneous()) {
1857             //if the resolved constructor's return type has some uninferred
1858             //type-variables, infer them using the expected type and declared
1859             //bounds (JLS 15.12.2.8).
1860             try {
1861                 clazztype = infer.instantiateExpr((ForAll) clazztype,
1862                         pt.tag == NONE ? syms.objectType : pt,
1863                         Warner.noWarnings);
1864             } catch (Infer.InferenceException ex) {
1865                 //an error occurred while inferring uninstantiated type-variables
1866                 log.error(tree.clazz.pos(),
1867                         "cant.apply.diamond.1",
1868                         diags.fragment("diamond", clazztype.tsym),
1869                         ex.diagnostic);
1870             }
1871         }
1872         return chk.checkClassType(tree.clazz.pos(),
1873                 clazztype,
1874                 true);
1875     }
1876 
1877     /** Creates a synthetic scope containing fake generic constructors.
1878      *  Assuming that the original scope contains a constructor of the kind:
1879      *  Foo(X x, Y y), where X,Y are class type-variables declared in Foo,
1880      *  the synthetic scope is added a generic constructor of the kind:
1881      *  <X,Y>Foo<X,Y>(X x, Y y). This is crucial in order to enable diamond
1882      *  inference. The inferred return type of the synthetic constructor IS
1883      *  the inferred type for the diamond operator.
1884      */
1885     private Pair<Scope, Scope> getSyntheticScopeMapping(Type ctype) {
1886         if (ctype.tag != CLASS) {
1887             return erroneousMapping;
1888         }
1889 
1890         Pair<Scope, Scope> mapping =
1891                 new Pair<Scope, Scope>(ctype.tsym.members(), new Scope(ctype.tsym));
1892 
1893         //for each constructor in the original scope, create a synthetic constructor
1894         //whose return type is the type of the class in which the constructor is
1895         //declared, and insert it into the new scope.
1896         for (Scope.Entry e = mapping.fst.lookup(names.init);
1897                 e.scope != null;
1898                 e = e.next()) {
1899             Type synthRestype = new ClassType(ctype.getEnclosingType(),
1900                         ctype.tsym.type.getTypeArguments(),
1901                         ctype.tsym);
1902             MethodSymbol synhConstr = new MethodSymbol(e.sym.flags(),
1903                     names.init,
1904                     types.createMethodTypeWithReturn(e.sym.type, synthRestype),
1905                     e.sym.owner);
1906             mapping.snd.enter(synhConstr);
1907         }
1908         return mapping;
1909     }
1910 
1911     private final Pair<Scope,Scope> erroneousMapping = new Pair<Scope,Scope>(null, null);
1912 
1913     /** Make an attributed null check tree.
1914      */
1915     public JCExpression makeNullCheck(JCExpression arg) {
1916         // optimization: X.this is never null; skip null check
1917         Name name = TreeInfo.name(arg);
1918         if (name == names._this || name == names._super) return arg;
1919 
1920         int optag = JCTree.NULLCHK;
1921         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
1922         tree.operator = syms.nullcheck;
1923         tree.type = arg.type;
1924         return tree;
1925     }
1926 
1927     public void visitNewArray(JCNewArray tree) {
1928         Type owntype = types.createErrorType(tree.type);
1929         Type elemtype;
1930         if (tree.elemtype != null) {
1931             elemtype = attribType(tree.elemtype, env);
1932             chk.validate(tree.elemtype, env);
1933             owntype = elemtype;
1934             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
1935                 attribExpr(l.head, env, syms.intType);
1936                 owntype = new ArrayType(owntype, syms.arrayClass);
1937             }
1938         } else {
1939             // we are seeing an untyped aggregate { ... }
1940             // this is allowed only if the prototype is an array
1941             if (pt.tag == ARRAY) {
1942                 elemtype = types.elemtype(pt);
1943             } else {
1944                 if (pt.tag != ERROR) {
1945                     log.error(tree.pos(), "illegal.initializer.for.type",
1946                               pt);
1947                 }
1948                 elemtype = types.createErrorType(pt);
1949             }
1950         }
1951         if (tree.elems != null) {
1952             attribExprs(tree.elems, env, elemtype);
1953             owntype = new ArrayType(elemtype, syms.arrayClass);
1954         }
1955         if (!types.isReifiable(elemtype))
1956             log.error(tree.pos(), "generic.array.creation");
1957         result = check(tree, owntype, VAL, pkind, pt);
1958     }
1959 
1960     public void visitParens(JCParens tree) {
1961         Type owntype = attribTree(tree.expr, env, pkind, pt);
1962         result = check(tree, owntype, pkind, pkind, pt);
1963         Symbol sym = TreeInfo.symbol(tree);
1964         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
1965             log.error(tree.pos(), "illegal.start.of.type");
1966     }
1967 
1968     public void visitAssign(JCAssign tree) {
1969         Type owntype = attribTree(tree.lhs, env.dup(tree), VAR, Type.noType);
1970         Type capturedType = capture(owntype);
1971         attribExpr(tree.rhs, env, owntype);
1972         result = check(tree, capturedType, VAL, pkind, pt);
1973     }
1974 
1975     public void visitAssignop(JCAssignOp tree) {
1976         // Attribute arguments.
1977         Type owntype = attribTree(tree.lhs, env, VAR, Type.noType);
1978         Type operand = attribExpr(tree.rhs, env);
1979         // Find operator.
1980         Symbol operator = tree.operator = rs.resolveBinaryOperator(
1981             tree.pos(), tree.getTag() - JCTree.ASGOffset, env,
1982             owntype, operand);
1983 
1984         if (operator.kind == MTH &&
1985                 !owntype.isErroneous() &&
1986                 !operand.isErroneous()) {
1987             chk.checkOperator(tree.pos(),
1988                               (OperatorSymbol)operator,
1989                               tree.getTag() - JCTree.ASGOffset,
1990                               owntype,
1991                               operand);
1992             chk.checkDivZero(tree.rhs.pos(), operator, operand);
1993             chk.checkCastable(tree.rhs.pos(),
1994                               operator.type.getReturnType(),
1995                               owntype);
1996         }
1997         result = check(tree, owntype, VAL, pkind, pt);
1998     }
1999 
2000     public void visitUnary(JCUnary tree) {
2001         // Attribute arguments.
2002         Type argtype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
2003             ? attribTree(tree.arg, env, VAR, Type.noType)
2004             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
2005 
2006         // Find operator.
2007         Symbol operator = tree.operator =
2008             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
2009 
2010         Type owntype = types.createErrorType(tree.type);
2011         if (operator.kind == MTH &&
2012                 !argtype.isErroneous()) {
2013             owntype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
2014                 ? tree.arg.type
2015                 : operator.type.getReturnType();
2016             int opc = ((OperatorSymbol)operator).opcode;
2017 
2018             // If the argument is constant, fold it.
2019             if (argtype.constValue() != null) {
2020                 Type ctype = cfolder.fold1(opc, argtype);
2021                 if (ctype != null) {
2022                     owntype = cfolder.coerce(ctype, owntype);
2023 
2024                     // Remove constant types from arguments to
2025                     // conserve space. The parser will fold concatenations
2026                     // of string literals; the code here also
2027                     // gets rid of intermediate results when some of the
2028                     // operands are constant identifiers.
2029                     if (tree.arg.type.tsym == syms.stringType.tsym) {
2030                         tree.arg.type = syms.stringType;
2031                     }
2032                 }
2033             }
2034         }
2035         result = check(tree, owntype, VAL, pkind, pt);
2036     }
2037 
2038     public void visitBinary(JCBinary tree) {
2039         // Attribute arguments.
2040         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
2041         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
2042 
2043         // Find operator.
2044         Symbol operator = tree.operator =
2045             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
2046 
2047         Type owntype = types.createErrorType(tree.type);
2048         if (operator.kind == MTH &&
2049                 !left.isErroneous() &&
2050                 !right.isErroneous()) {
2051             owntype = operator.type.getReturnType();
2052             int opc = chk.checkOperator(tree.lhs.pos(),
2053                                         (OperatorSymbol)operator,
2054                                         tree.getTag(),
2055                                         left,
2056                                         right);
2057 
2058             // If both arguments are constants, fold them.
2059             if (left.constValue() != null && right.constValue() != null) {
2060                 Type ctype = cfolder.fold2(opc, left, right);
2061                 if (ctype != null) {
2062                     owntype = cfolder.coerce(ctype, owntype);
2063 
2064                     // Remove constant types from arguments to
2065                     // conserve space. The parser will fold concatenations
2066                     // of string literals; the code here also
2067                     // gets rid of intermediate results when some of the
2068                     // operands are constant identifiers.
2069                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
2070                         tree.lhs.type = syms.stringType;
2071                     }
2072                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
2073                         tree.rhs.type = syms.stringType;
2074                     }
2075                 }
2076             }
2077 
2078             // Check that argument types of a reference ==, != are
2079             // castable to each other, (JLS???).
2080             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
2081                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
2082                     log.error(tree.pos(), "incomparable.types", left, right);
2083                 }
2084             }
2085 
2086             chk.checkDivZero(tree.rhs.pos(), operator, right);
2087         }
2088         result = check(tree, owntype, VAL, pkind, pt);
2089     }
2090 
2091     public void visitTypeCast(JCTypeCast tree) {
2092         Type clazztype = attribType(tree.clazz, env);
2093         chk.validate(tree.clazz, env, false);
2094         //a fresh environment is required for 292 inference to work properly ---
2095         //see Infer.instantiatePolymorphicSignatureInstance()
2096         Env<AttrContext> localEnv = env.dup(tree);
2097         Type exprtype = attribExpr(tree.expr, localEnv, Infer.anyPoly);
2098         Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
2099         if (exprtype.constValue() != null)
2100             owntype = cfolder.coerce(exprtype, owntype);
2101         result = check(tree, capture(owntype), VAL, pkind, pt);
2102     }
2103 
2104     public void visitTypeTest(JCInstanceOf tree) {
2105         Type exprtype = chk.checkNullOrRefType(
2106             tree.expr.pos(), attribExpr(tree.expr, env));
2107         Type clazztype = chk.checkReifiableReferenceType(
2108             tree.clazz.pos(), attribType(tree.clazz, env));
2109         chk.validate(tree.clazz, env, false);
2110         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
2111         result = check(tree, syms.booleanType, VAL, pkind, pt);
2112     }
2113 
2114     public void visitIndexed(JCArrayAccess tree) {
2115         Type owntype = types.createErrorType(tree.type);
2116         Type atype = attribExpr(tree.indexed, env);
2117         attribExpr(tree.index, env, syms.intType);
2118         if (types.isArray(atype))
2119             owntype = types.elemtype(atype);
2120         else if (atype.tag != ERROR)
2121             log.error(tree.pos(), "array.req.but.found", atype);
2122         if ((pkind & VAR) == 0) owntype = capture(owntype);
2123         result = check(tree, owntype, VAR, pkind, pt);
2124     }
2125 
2126     public void visitIdent(JCIdent tree) {
2127         Symbol sym;
2128         boolean varArgs = false;
2129 
2130         // Find symbol
2131         if (pt.tag == METHOD || pt.tag == FORALL) {
2132             // If we are looking for a method, the prototype `pt' will be a
2133             // method type with the type of the call's arguments as parameters.
2134             env.info.varArgs = false;
2135             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt.getParameterTypes(), pt.getTypeArguments());
2136             varArgs = env.info.varArgs;
2137         } else if (tree.sym != null && tree.sym.kind != VAR) {
2138             sym = tree.sym;
2139         } else {
2140             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind);
2141         }
2142         tree.sym = sym;
2143 
2144         // (1) Also find the environment current for the class where
2145         //     sym is defined (`symEnv').
2146         // Only for pre-tiger versions (1.4 and earlier):
2147         // (2) Also determine whether we access symbol out of an anonymous
2148         //     class in a this or super call.  This is illegal for instance
2149         //     members since such classes don't carry a this$n link.
2150         //     (`noOuterThisPath').
2151         Env<AttrContext> symEnv = env;
2152         boolean noOuterThisPath = false;
2153         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
2154             (sym.kind & (VAR | MTH | TYP)) != 0 &&
2155             sym.owner.kind == TYP &&
2156             tree.name != names._this && tree.name != names._super) {
2157 
2158             // Find environment in which identifier is defined.
2159             while (symEnv.outer != null &&
2160                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
2161                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
2162                     noOuterThisPath = !allowAnonOuterThis;
2163                 symEnv = symEnv.outer;
2164             }
2165         }
2166 
2167         // If symbol is a variable, ...
2168         if (sym.kind == VAR) {
2169             VarSymbol v = (VarSymbol)sym;
2170 
2171             // ..., evaluate its initializer, if it has one, and check for
2172             // illegal forward reference.
2173             checkInit(tree, env, v, false);
2174 
2175             // If symbol is a local variable accessed from an embedded
2176             // inner class check that it is final.
2177             if (v.owner.kind == MTH &&
2178                 v.owner != env.info.scope.owner &&
2179                 (v.flags_field & FINAL) == 0) {
2180                 log.error(tree.pos(),
2181                           "local.var.accessed.from.icls.needs.final",
2182                           v);
2183             }
2184 
2185             // If we are expecting a variable (as opposed to a value), check
2186             // that the variable is assignable in the current environment.
2187             if (pkind == VAR)
2188                 checkAssignable(tree.pos(), v, null, env);
2189         }
2190 
2191         // In a constructor body,
2192         // if symbol is a field or instance method, check that it is
2193         // not accessed before the supertype constructor is called.
2194         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
2195             (sym.kind & (VAR | MTH)) != 0 &&
2196             sym.owner.kind == TYP &&
2197             (sym.flags() & STATIC) == 0) {
2198             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
2199         }
2200         Env<AttrContext> env1 = env;
2201         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
2202             // If the found symbol is inaccessible, then it is
2203             // accessed through an enclosing instance.  Locate this
2204             // enclosing instance:
2205             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
2206                 env1 = env1.outer;
2207         }
2208         result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, varArgs);
2209     }
2210 
2211     public void visitSelect(JCFieldAccess tree) {
2212         // Determine the expected kind of the qualifier expression.
2213         int skind = 0;
2214         if (tree.name == names._this || tree.name == names._super ||
2215             tree.name == names._class)
2216         {
2217             skind = TYP;
2218         } else {
2219             if ((pkind & PCK) != 0) skind = skind | PCK;
2220             if ((pkind & TYP) != 0) skind = skind | TYP | PCK;
2221             if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
2222         }
2223 
2224         // Attribute the qualifier expression, and determine its symbol (if any).
2225         Type site = attribTree(tree.selected, env, skind, Infer.anyPoly);
2226         if ((pkind & (PCK | TYP)) == 0)
2227             site = capture(site); // Capture field access
2228 
2229         // don't allow T.class T[].class, etc
2230         if (skind == TYP) {
2231             Type elt = site;
2232             while (elt.tag == ARRAY)
2233                 elt = ((ArrayType)elt).elemtype;
2234             if (elt.tag == TYPEVAR) {
2235                 log.error(tree.pos(), "type.var.cant.be.deref");
2236                 result = types.createErrorType(tree.type);
2237                 return;
2238             }
2239         }
2240 
2241         // If qualifier symbol is a type or `super', assert `selectSuper'
2242         // for the selection. This is relevant for determining whether
2243         // protected symbols are accessible.
2244         Symbol sitesym = TreeInfo.symbol(tree.selected);
2245         boolean selectSuperPrev = env.info.selectSuper;
2246         env.info.selectSuper =
2247             sitesym != null &&
2248             sitesym.name == names._super;
2249 
2250         // If selected expression is polymorphic, strip
2251         // type parameters and remember in env.info.tvars, so that
2252         // they can be added later (in Attr.checkId and Infer.instantiateMethod).
2253         if (tree.selected.type.tag == FORALL) {
2254             ForAll pstype = (ForAll)tree.selected.type;
2255             env.info.tvars = pstype.tvars;
2256             site = tree.selected.type = pstype.qtype;
2257         }
2258 
2259         // Determine the symbol represented by the selection.
2260         env.info.varArgs = false;
2261         Symbol sym = selectSym(tree, sitesym, site, env, pt, pkind);
2262         if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) {
2263             site = capture(site);
2264             sym = selectSym(tree, sitesym, site, env, pt, pkind);
2265         }
2266         boolean varArgs = env.info.varArgs;
2267         tree.sym = sym;
2268 
2269         if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) {
2270             while (site.tag == TYPEVAR) site = site.getUpperBound();
2271             site = capture(site);
2272         }
2273 
2274         // If that symbol is a variable, ...
2275         if (sym.kind == VAR) {
2276             VarSymbol v = (VarSymbol)sym;
2277 
2278             // ..., evaluate its initializer, if it has one, and check for
2279             // illegal forward reference.
2280             checkInit(tree, env, v, true);
2281 
2282             // If we are expecting a variable (as opposed to a value), check
2283             // that the variable is assignable in the current environment.
2284             if (pkind == VAR)
2285                 checkAssignable(tree.pos(), v, tree.selected, env);
2286         }
2287 
2288         if (sitesym != null &&
2289                 sitesym.kind == VAR &&
2290                 ((VarSymbol)sitesym).isResourceVariable() &&
2291                 sym.kind == MTH &&
2292                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
2293                 env.info.lint.isEnabled(LintCategory.TRY)) {
2294             log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
2295         }
2296 
2297         // Disallow selecting a type from an expression
2298         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
2299             tree.type = check(tree.selected, pt,
2300                               sitesym == null ? VAL : sitesym.kind, TYP|PCK, pt);
2301         }
2302 
2303         if (isType(sitesym)) {
2304             if (sym.name == names._this) {
2305                 // If `C' is the currently compiled class, check that
2306                 // C.this' does not appear in a call to a super(...)
2307                 if (env.info.isSelfCall &&
2308                     site.tsym == env.enclClass.sym) {
2309                     chk.earlyRefError(tree.pos(), sym);
2310                 }
2311             } else {
2312                 // Check if type-qualified fields or methods are static (JLS)
2313                 if ((sym.flags() & STATIC) == 0 &&
2314                     sym.name != names._super &&
2315                     (sym.kind == VAR || sym.kind == MTH)) {
2316                     rs.access(rs.new StaticError(sym),
2317                               tree.pos(), site, sym.name, true);
2318                 }
2319             }
2320         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
2321             // If the qualified item is not a type and the selected item is static, report
2322             // a warning. Make allowance for the class of an array type e.g. Object[].class)
2323             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
2324         }
2325 
2326         // If we are selecting an instance member via a `super', ...
2327         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
2328 
2329             // Check that super-qualified symbols are not abstract (JLS)
2330             rs.checkNonAbstract(tree.pos(), sym);
2331 
2332             if (site.isRaw()) {
2333                 // Determine argument types for site.
2334                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
2335                 if (site1 != null) site = site1;
2336             }
2337         }
2338 
2339         env.info.selectSuper = selectSuperPrev;
2340         result = checkId(tree, site, sym, env, pkind, pt, varArgs);
2341         env.info.tvars = List.nil();
2342     }
2343     //where
2344         /** Determine symbol referenced by a Select expression,
2345          *
2346          *  @param tree   The select tree.
2347          *  @param site   The type of the selected expression,
2348          *  @param env    The current environment.
2349          *  @param pt     The current prototype.
2350          *  @param pkind  The expected kind(s) of the Select expression.
2351          */
2352         private Symbol selectSym(JCFieldAccess tree,
2353                                      Type site,
2354                                      Env<AttrContext> env,
2355                                      Type pt,
2356                                      int pkind) {
2357             return selectSym(tree, site.tsym, site, env, pt, pkind);
2358         }
2359         private Symbol selectSym(JCFieldAccess tree,
2360                                  Symbol location,
2361                                  Type site,
2362                                  Env<AttrContext> env,
2363                                  Type pt,
2364                                  int pkind) {
2365             DiagnosticPosition pos = tree.pos();
2366             Name name = tree.name;
2367             switch (site.tag) {
2368             case PACKAGE:
2369                 return rs.access(
2370                     rs.findIdentInPackage(env, site.tsym, name, pkind),
2371                     pos, location, site, name, true);
2372             case ARRAY:
2373             case CLASS:
2374                 if (pt.tag == METHOD || pt.tag == FORALL) {
2375                     return rs.resolveQualifiedMethod(
2376                         pos, env, location, site, name, pt.getParameterTypes(), pt.getTypeArguments());
2377                 } else if (name == names._this || name == names._super) {
2378                     return rs.resolveSelf(pos, env, site.tsym, name);
2379                 } else if (name == names._class) {
2380                     // In this case, we have already made sure in
2381                     // visitSelect that qualifier expression is a type.
2382                     Type t = syms.classType;
2383                     List<Type> typeargs = allowGenerics
2384                         ? List.of(types.erasure(site))
2385                         : List.<Type>nil();
2386                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
2387                     return new VarSymbol(
2388                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
2389                 } else {
2390                     // We are seeing a plain identifier as selector.
2391                     Symbol sym = rs.findIdentInType(env, site, name, pkind);
2392                     if ((pkind & ERRONEOUS) == 0)
2393                         sym = rs.access(sym, pos, location, site, name, true);
2394                     return sym;
2395                 }
2396             case WILDCARD:
2397                 throw new AssertionError(tree);
2398             case TYPEVAR:
2399                 // Normally, site.getUpperBound() shouldn't be null.
2400                 // It should only happen during memberEnter/attribBase
2401                 // when determining the super type which *must* beac
2402                 // done before attributing the type variables.  In
2403                 // other words, we are seeing this illegal program:
2404                 // class B<T> extends A<T.foo> {}
2405                 Symbol sym = (site.getUpperBound() != null)
2406                     ? selectSym(tree, location, capture(site.getUpperBound()), env, pt, pkind)
2407                     : null;
2408                 if (sym == null) {
2409                     log.error(pos, "type.var.cant.be.deref");
2410                     return syms.errSymbol;
2411                 } else {
2412                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
2413                         rs.new AccessError(env, site, sym) :
2414                                 sym;
2415                     rs.access(sym2, pos, location, site, name, true);
2416                     return sym;
2417                 }
2418             case ERROR:
2419                 // preserve identifier names through errors
2420                 return types.createErrorType(name, site.tsym, site).tsym;
2421             default:
2422                 // The qualifier expression is of a primitive type -- only
2423                 // .class is allowed for these.
2424                 if (name == names._class) {
2425                     // In this case, we have already made sure in Select that
2426                     // qualifier expression is a type.
2427                     Type t = syms.classType;
2428                     Type arg = types.boxedClass(site).type;
2429                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
2430                     return new VarSymbol(
2431                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
2432                 } else {
2433                     log.error(pos, "cant.deref", site);
2434                     return syms.errSymbol;
2435                 }
2436             }
2437         }
2438 
2439         /** Determine type of identifier or select expression and check that
2440          *  (1) the referenced symbol is not deprecated
2441          *  (2) the symbol's type is safe (@see checkSafe)
2442          *  (3) if symbol is a variable, check that its type and kind are
2443          *      compatible with the prototype and protokind.
2444          *  (4) if symbol is an instance field of a raw type,
2445          *      which is being assigned to, issue an unchecked warning if its
2446          *      type changes under erasure.
2447          *  (5) if symbol is an instance method of a raw type, issue an
2448          *      unchecked warning if its argument types change under erasure.
2449          *  If checks succeed:
2450          *    If symbol is a constant, return its constant type
2451          *    else if symbol is a method, return its result type
2452          *    otherwise return its type.
2453          *  Otherwise return errType.
2454          *
2455          *  @param tree       The syntax tree representing the identifier
2456          *  @param site       If this is a select, the type of the selected
2457          *                    expression, otherwise the type of the current class.
2458          *  @param sym        The symbol representing the identifier.
2459          *  @param env        The current environment.
2460          *  @param pkind      The set of expected kinds.
2461          *  @param pt         The expected type.
2462          */
2463         Type checkId(JCTree tree,
2464                      Type site,
2465                      Symbol sym,
2466                      Env<AttrContext> env,
2467                      int pkind,
2468                      Type pt,
2469                      boolean useVarargs) {
2470             if (pt.isErroneous()) return types.createErrorType(site);
2471             Type owntype; // The computed type of this identifier occurrence.
2472             switch (sym.kind) {
2473             case TYP:
2474                 // For types, the computed type equals the symbol's type,
2475                 // except for two situations:
2476                 owntype = sym.type;
2477                 if (owntype.tag == CLASS) {
2478                     Type ownOuter = owntype.getEnclosingType();
2479 
2480                     // (a) If the symbol's type is parameterized, erase it
2481                     // because no type parameters were given.
2482                     // We recover generic outer type later in visitTypeApply.
2483                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
2484                         owntype = types.erasure(owntype);
2485                     }
2486 
2487                     // (b) If the symbol's type is an inner class, then
2488                     // we have to interpret its outer type as a superclass
2489                     // of the site type. Example:
2490                     //
2491                     // class Tree<A> { class Visitor { ... } }
2492                     // class PointTree extends Tree<Point> { ... }
2493                     // ...PointTree.Visitor...
2494                     //
2495                     // Then the type of the last expression above is
2496                     // Tree<Point>.Visitor.
2497                     else if (ownOuter.tag == CLASS && site != ownOuter) {
2498                         Type normOuter = site;
2499                         if (normOuter.tag == CLASS)
2500                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
2501                         if (normOuter == null) // perhaps from an import
2502                             normOuter = types.erasure(ownOuter);
2503                         if (normOuter != ownOuter)
2504                             owntype = new ClassType(
2505                                 normOuter, List.<Type>nil(), owntype.tsym);
2506                     }
2507                 }
2508                 break;
2509             case VAR:
2510                 VarSymbol v = (VarSymbol)sym;
2511                 // Test (4): if symbol is an instance field of a raw type,
2512                 // which is being assigned to, issue an unchecked warning if
2513                 // its type changes under erasure.
2514                 if (allowGenerics &&
2515                     pkind == VAR &&
2516                     v.owner.kind == TYP &&
2517                     (v.flags() & STATIC) == 0 &&
2518                     (site.tag == CLASS || site.tag == TYPEVAR)) {
2519                     Type s = types.asOuterSuper(site, v.owner);
2520                     if (s != null &&
2521                         s.isRaw() &&
2522                         !types.isSameType(v.type, v.erasure(types))) {
2523                         chk.warnUnchecked(tree.pos(),
2524                                           "unchecked.assign.to.var",
2525                                           v, s);
2526                     }
2527                 }
2528                 // The computed type of a variable is the type of the
2529                 // variable symbol, taken as a member of the site type.
2530                 owntype = (sym.owner.kind == TYP &&
2531                            sym.name != names._this && sym.name != names._super)
2532                     ? types.memberType(site, sym)
2533                     : sym.type;
2534 
2535                 if (env.info.tvars.nonEmpty()) {
2536                     Type owntype1 = new ForAll(env.info.tvars, owntype);
2537                     for (List<Type> l = env.info.tvars; l.nonEmpty(); l = l.tail)
2538                         if (!owntype.contains(l.head)) {
2539                             log.error(tree.pos(), "undetermined.type", owntype1);
2540                             owntype1 = types.createErrorType(owntype1);
2541                         }
2542                     owntype = owntype1;
2543                 }
2544 
2545                 // If the variable is a constant, record constant value in
2546                 // computed type.
2547                 if (v.getConstValue() != null && isStaticReference(tree))
2548                     owntype = owntype.constType(v.getConstValue());
2549 
2550                 if (pkind == VAL) {
2551                     owntype = capture(owntype); // capture "names as expressions"
2552                 }
2553                 break;
2554             case MTH: {
2555                 JCMethodInvocation app = (JCMethodInvocation)env.tree;
2556                 owntype = checkMethod(site, sym, env, app.args,
2557                                       pt.getParameterTypes(), pt.getTypeArguments(),
2558                                       env.info.varArgs);
2559                 break;
2560             }
2561             case PCK: case ERR:
2562                 owntype = sym.type;
2563                 break;
2564             default:
2565                 throw new AssertionError("unexpected kind: " + sym.kind +
2566                                          " in tree " + tree);
2567             }
2568 
2569             // Test (1): emit a `deprecation' warning if symbol is deprecated.
2570             // (for constructors, the error was given when the constructor was
2571             // resolved)
2572 
2573             if (sym.name != names.init) {
2574                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
2575                 chk.checkSunAPI(tree.pos(), sym);
2576             }
2577 
2578             // Test (3): if symbol is a variable, check that its type and
2579             // kind are compatible with the prototype and protokind.
2580             return check(tree, owntype, sym.kind, pkind, pt);
2581         }
2582 
2583         /** Check that variable is initialized and evaluate the variable's
2584          *  initializer, if not yet done. Also check that variable is not
2585          *  referenced before it is defined.
2586          *  @param tree    The tree making up the variable reference.
2587          *  @param env     The current environment.
2588          *  @param v       The variable's symbol.
2589          */
2590         private void checkInit(JCTree tree,
2591                                Env<AttrContext> env,
2592                                VarSymbol v,
2593                                boolean onlyWarning) {
2594 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
2595 //                             tree.pos + " " + v.pos + " " +
2596 //                             Resolve.isStatic(env));//DEBUG
2597 
2598             // A forward reference is diagnosed if the declaration position
2599             // of the variable is greater than the current tree position
2600             // and the tree and variable definition occur in the same class
2601             // definition.  Note that writes don't count as references.
2602             // This check applies only to class and instance
2603             // variables.  Local variables follow different scope rules,
2604             // and are subject to definite assignment checking.
2605             if ((env.info.enclVar == v || v.pos > tree.pos) &&
2606                 v.owner.kind == TYP &&
2607                 canOwnInitializer(env.info.scope.owner) &&
2608                 v.owner == env.info.scope.owner.enclClass() &&
2609                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
2610                 (env.tree.getTag() != JCTree.ASSIGN ||
2611                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
2612                 String suffix = (env.info.enclVar == v) ?
2613                                 "self.ref" : "forward.ref";
2614                 if (!onlyWarning || isStaticEnumField(v)) {
2615                     log.error(tree.pos(), "illegal." + suffix);
2616                 } else if (useBeforeDeclarationWarning) {
2617                     log.warning(tree.pos(), suffix, v);
2618                 }
2619             }
2620 
2621             v.getConstValue(); // ensure initializer is evaluated
2622 
2623             checkEnumInitializer(tree, env, v);
2624         }
2625 
2626         /**
2627          * Check for illegal references to static members of enum.  In
2628          * an enum type, constructors and initializers may not
2629          * reference its static members unless they are constant.
2630          *
2631          * @param tree    The tree making up the variable reference.
2632          * @param env     The current environment.
2633          * @param v       The variable's symbol.
2634          * @see JLS 3rd Ed. (8.9 Enums)
2635          */
2636         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
2637             // JLS 3rd Ed.:
2638             //
2639             // "It is a compile-time error to reference a static field
2640             // of an enum type that is not a compile-time constant
2641             // (15.28) from constructors, instance initializer blocks,
2642             // or instance variable initializer expressions of that
2643             // type. It is a compile-time error for the constructors,
2644             // instance initializer blocks, or instance variable
2645             // initializer expressions of an enum constant e to refer
2646             // to itself or to an enum constant of the same type that
2647             // is declared to the right of e."
2648             if (isStaticEnumField(v)) {
2649                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
2650 
2651                 if (enclClass == null || enclClass.owner == null)
2652                     return;
2653 
2654                 // See if the enclosing class is the enum (or a
2655                 // subclass thereof) declaring v.  If not, this
2656                 // reference is OK.
2657                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
2658                     return;
2659 
2660                 // If the reference isn't from an initializer, then
2661                 // the reference is OK.
2662                 if (!Resolve.isInitializer(env))
2663                     return;
2664 
2665                 log.error(tree.pos(), "illegal.enum.static.ref");
2666             }
2667         }
2668 
2669         /** Is the given symbol a static, non-constant field of an Enum?
2670          *  Note: enum literals should not be regarded as such
2671          */
2672         private boolean isStaticEnumField(VarSymbol v) {
2673             return Flags.isEnum(v.owner) &&
2674                    Flags.isStatic(v) &&
2675                    !Flags.isConstant(v) &&
2676                    v.name != names._class;
2677         }
2678 
2679         /** Can the given symbol be the owner of code which forms part
2680          *  if class initialization? This is the case if the symbol is
2681          *  a type or field, or if the symbol is the synthetic method.
2682          *  owning a block.
2683          */
2684         private boolean canOwnInitializer(Symbol sym) {
2685             return
2686                 (sym.kind & (VAR | TYP)) != 0 ||
2687                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
2688         }
2689 
2690     Warner noteWarner = new Warner();
2691 
2692     /**
2693      * Check that method arguments conform to its instantation.
2694      **/
2695     public Type checkMethod(Type site,
2696                             Symbol sym,
2697                             Env<AttrContext> env,
2698                             final List<JCExpression> argtrees,
2699                             List<Type> argtypes,
2700                             List<Type> typeargtypes,
2701                             boolean useVarargs) {
2702         // Test (5): if symbol is an instance method of a raw type, issue
2703         // an unchecked warning if its argument types change under erasure.
2704         if (allowGenerics &&
2705             (sym.flags() & STATIC) == 0 &&
2706             (site.tag == CLASS || site.tag == TYPEVAR)) {
2707             Type s = types.asOuterSuper(site, sym.owner);
2708             if (s != null && s.isRaw() &&
2709                 !types.isSameTypes(sym.type.getParameterTypes(),
2710                                    sym.erasure(types).getParameterTypes())) {
2711                 chk.warnUnchecked(env.tree.pos(),
2712                                   "unchecked.call.mbr.of.raw.type",
2713                                   sym, s);
2714             }
2715         }
2716 
2717         // Compute the identifier's instantiated type.
2718         // For methods, we need to compute the instance type by
2719         // Resolve.instantiate from the symbol's type as well as
2720         // any type arguments and value arguments.
2721         noteWarner.clear();
2722         Type owntype = rs.instantiate(env,
2723                                       site,
2724                                       sym,
2725                                       argtypes,
2726                                       typeargtypes,
2727                                       true,
2728                                       useVarargs,
2729                                       noteWarner);
2730         boolean warned = noteWarner.hasNonSilentLint(LintCategory.UNCHECKED);
2731 
2732         // If this fails, something went wrong; we should not have
2733         // found the identifier in the first place.
2734         if (owntype == null) {
2735             if (!pt.isErroneous())
2736                 log.error(env.tree.pos(),
2737                           "internal.error.cant.instantiate",
2738                           sym, site,
2739                           Type.toString(pt.getParameterTypes()));
2740             owntype = types.createErrorType(site);
2741         } else {
2742             // System.out.println("call   : " + env.tree);
2743             // System.out.println("method : " + owntype);
2744             // System.out.println("actuals: " + argtypes);
2745             List<Type> formals = owntype.getParameterTypes();
2746             Type last = useVarargs ? formals.last() : null;
2747             if (sym.name==names.init &&
2748                 sym.owner == syms.enumSym)
2749                 formals = formals.tail.tail;
2750             List<JCExpression> args = argtrees;
2751             while (formals.head != last) {
2752                 JCTree arg = args.head;
2753                 Warner warn = chk.convertWarner(arg.pos(), arg.type, formals.head);
2754                 assertConvertible(arg, arg.type, formals.head, warn);
2755                 warned |= warn.hasNonSilentLint(LintCategory.UNCHECKED);
2756                 args = args.tail;
2757                 formals = formals.tail;
2758             }
2759             if (useVarargs) {
2760                 Type varArg = types.elemtype(last);
2761                 while (args.tail != null) {
2762                     JCTree arg = args.head;
2763                     Warner warn = chk.convertWarner(arg.pos(), arg.type, varArg);
2764                     assertConvertible(arg, arg.type, varArg, warn);
2765                     warned |= warn.hasNonSilentLint(LintCategory.UNCHECKED);
2766                     args = args.tail;
2767                 }
2768             } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
2769                 // non-varargs call to varargs method
2770                 Type varParam = owntype.getParameterTypes().last();
2771                 Type lastArg = argtypes.last();
2772                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
2773                     !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
2774                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
2775                                 types.elemtype(varParam),
2776                                 varParam);
2777             }
2778 
2779             if (warned && sym.type.tag == FORALL) {
2780                 chk.warnUnchecked(env.tree.pos(),
2781                                   "unchecked.meth.invocation.applied",
2782                                   kindName(sym),
2783                                   sym.name,
2784                                   rs.methodArguments(sym.type.getParameterTypes()),
2785                                   rs.methodArguments(argtypes),
2786                                   kindName(sym.location()),
2787                                   sym.location());
2788                 owntype = new MethodType(owntype.getParameterTypes(),
2789                                          types.erasure(owntype.getReturnType()),
2790                                          types.erasure(owntype.getThrownTypes()),
2791                                          syms.methodClass);
2792             }
2793             if (useVarargs) {
2794                 JCTree tree = env.tree;
2795                 Type argtype = owntype.getParameterTypes().last();
2796                 if (owntype.getReturnType().tag != FORALL || warned) {
2797                     chk.checkVararg(env.tree.pos(), owntype.getParameterTypes(), sym);
2798                 }
2799                 Type elemtype = types.elemtype(argtype);
2800                 switch (tree.getTag()) {
2801                 case JCTree.APPLY:
2802                     ((JCMethodInvocation) tree).varargsElement = elemtype;
2803                     break;
2804                 case JCTree.NEWCLASS:
2805                     ((JCNewClass) tree).varargsElement = elemtype;
2806                     break;
2807                 default:
2808                     throw new AssertionError(""+tree);
2809                 }
2810             }
2811         }
2812         return owntype;
2813     }
2814 
2815     private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
2816         if (types.isConvertible(actual, formal, warn))
2817             return;
2818 
2819         if (formal.isCompound()
2820             && types.isSubtype(actual, types.supertype(formal))
2821             && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
2822             return;
2823 
2824         if (false) {
2825             // TODO: make assertConvertible work
2826             chk.typeError(tree.pos(), diags.fragment("incompatible.types"), actual, formal);
2827             throw new AssertionError("Tree: " + tree
2828                                      + " actual:" + actual
2829                                      + " formal: " + formal);
2830         }
2831     }
2832 
2833     public void visitLiteral(JCLiteral tree) {
2834         result = check(
2835             tree, litType(tree.typetag).constType(tree.value), VAL, pkind, pt);
2836     }
2837     //where
2838     /** Return the type of a literal with given type tag.
2839      */
2840     Type litType(int tag) {
2841         return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag];
2842     }
2843 
2844     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
2845         result = check(tree, syms.typeOfTag[tree.typetag], TYP, pkind, pt);
2846     }
2847 
2848     public void visitTypeArray(JCArrayTypeTree tree) {
2849         Type etype = attribType(tree.elemtype, env);
2850         Type type = new ArrayType(etype, syms.arrayClass);
2851         result = check(tree, type, TYP, pkind, pt);
2852     }
2853 
2854     /** Visitor method for parameterized types.
2855      *  Bound checking is left until later, since types are attributed
2856      *  before supertype structure is completely known
2857      */
2858     public void visitTypeApply(JCTypeApply tree) {
2859         Type owntype = types.createErrorType(tree.type);
2860 
2861         // Attribute functor part of application and make sure it's a class.
2862         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
2863 
2864         // Attribute type parameters
2865         List<Type> actuals = attribTypes(tree.arguments, env);
2866 
2867         if (clazztype.tag == CLASS) {
2868             List<Type> formals = clazztype.tsym.type.getTypeArguments();
2869 
2870             if (actuals.length() == formals.length() || actuals.length() == 0) {
2871                 List<Type> a = actuals;
2872                 List<Type> f = formals;
2873                 while (a.nonEmpty()) {
2874                     a.head = a.head.withTypeVar(f.head);
2875                     a = a.tail;
2876                     f = f.tail;
2877                 }
2878                 // Compute the proper generic outer
2879                 Type clazzOuter = clazztype.getEnclosingType();
2880                 if (clazzOuter.tag == CLASS) {
2881                     Type site;
2882                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
2883                     if (clazz.getTag() == JCTree.IDENT) {
2884                         site = env.enclClass.sym.type;
2885                     } else if (clazz.getTag() == JCTree.SELECT) {
2886                         site = ((JCFieldAccess) clazz).selected.type;
2887                     } else throw new AssertionError(""+tree);
2888                     if (clazzOuter.tag == CLASS && site != clazzOuter) {
2889                         if (site.tag == CLASS)
2890                             site = types.asOuterSuper(site, clazzOuter.tsym);
2891                         if (site == null)
2892                             site = types.erasure(clazzOuter);
2893                         clazzOuter = site;
2894                     }
2895                 }
2896                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
2897             } else {
2898                 if (formals.length() != 0) {
2899                     log.error(tree.pos(), "wrong.number.type.args",
2900                               Integer.toString(formals.length()));
2901                 } else {
2902                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
2903                 }
2904                 owntype = types.createErrorType(tree.type);
2905             }
2906         }
2907         result = check(tree, owntype, TYP, pkind, pt);
2908     }
2909 
2910     public void visitTypeDisjunction(JCTypeDisjunction tree) {
2911         ListBuffer<Type> multicatchTypes = ListBuffer.lb();
2912         for (JCExpression typeTree : tree.alternatives) {
2913             Type ctype = attribType(typeTree, env);
2914             ctype = chk.checkType(typeTree.pos(),
2915                           chk.checkClassType(typeTree.pos(), ctype),
2916                           syms.throwableType);
2917             if (!ctype.isErroneous()) {
2918                 //check that alternatives of a disjunctive type are pairwise
2919                 //unrelated w.r.t. subtyping
2920                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
2921                     for (Type t : multicatchTypes) {
2922                         boolean sub = types.isSubtype(ctype, t);
2923                         boolean sup = types.isSubtype(t, ctype);
2924                         if (sub || sup) {
2925                             //assume 'a' <: 'b'
2926                             Type a = sub ? ctype : t;
2927                             Type b = sub ? t : ctype;
2928                             log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
2929                         }
2930                     }
2931                 }
2932                 multicatchTypes.append(ctype);
2933             }
2934         }
2935         tree.type = result = check(tree, types.lub(multicatchTypes.toList()), TYP, pkind, pt);
2936     }
2937 
2938     public void visitTypeParameter(JCTypeParameter tree) {
2939         TypeVar a = (TypeVar)tree.type;
2940         Set<Type> boundSet = new HashSet<Type>();
2941         if (a.bound.isErroneous())
2942             return;
2943         List<Type> bs = types.getBounds(a);
2944         if (tree.bounds.nonEmpty()) {
2945             // accept class or interface or typevar as first bound.
2946             Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
2947             boundSet.add(types.erasure(b));
2948             if (b.isErroneous()) {
2949                 a.bound = b;
2950             }
2951             else if (b.tag == TYPEVAR) {
2952                 // if first bound was a typevar, do not accept further bounds.
2953                 if (tree.bounds.tail.nonEmpty()) {
2954                     log.error(tree.bounds.tail.head.pos(),
2955                               "type.var.may.not.be.followed.by.other.bounds");
2956                     tree.bounds = List.of(tree.bounds.head);
2957                     a.bound = bs.head;
2958                 }
2959             } else {
2960                 // if first bound was a class or interface, accept only interfaces
2961                 // as further bounds.
2962                 for (JCExpression bound : tree.bounds.tail) {
2963                     bs = bs.tail;
2964                     Type i = checkBase(bs.head, bound, env, false, true, false);
2965                     if (i.isErroneous())
2966                         a.bound = i;
2967                     else if (i.tag == CLASS)
2968                         chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
2969                 }
2970             }
2971         }
2972         bs = types.getBounds(a);
2973 
2974         // in case of multiple bounds ...
2975         if (bs.length() > 1) {
2976             // ... the variable's bound is a class type flagged COMPOUND
2977             // (see comment for TypeVar.bound).
2978             // In this case, generate a class tree that represents the
2979             // bound class, ...
2980             JCExpression extending;
2981             List<JCExpression> implementing;
2982             if ((bs.head.tsym.flags() & INTERFACE) == 0) {
2983                 extending = tree.bounds.head;
2984                 implementing = tree.bounds.tail;
2985             } else {
2986                 extending = null;
2987                 implementing = tree.bounds;
2988             }
2989             JCClassDecl cd = make.at(tree.pos).ClassDef(
2990                 make.Modifiers(PUBLIC | ABSTRACT),
2991                 tree.name, List.<JCTypeParameter>nil(),
2992                 extending, implementing, List.<JCTree>nil());
2993 
2994             ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
2995             Assert.check((c.flags() & COMPOUND) != 0);
2996             cd.sym = c;
2997             c.sourcefile = env.toplevel.sourcefile;
2998 
2999             // ... and attribute the bound class
3000             c.flags_field |= UNATTRIBUTED;
3001             Env<AttrContext> cenv = enter.classEnv(cd, env);
3002             enter.typeEnvs.put(c, cenv);
3003         }
3004     }
3005 
3006 
3007     public void visitWildcard(JCWildcard tree) {
3008         //- System.err.println("visitWildcard("+tree+");");//DEBUG
3009         Type type = (tree.kind.kind == BoundKind.UNBOUND)
3010             ? syms.objectType
3011             : attribType(tree.inner, env);
3012         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
3013                                               tree.kind.kind,
3014                                               syms.boundClass),
3015                        TYP, pkind, pt);
3016     }
3017 
3018     public void visitAnnotation(JCAnnotation tree) {
3019         log.error(tree.pos(), "annotation.not.valid.for.type", pt);
3020         result = tree.type = syms.errType;
3021     }
3022 
3023     public void visitErroneous(JCErroneous tree) {
3024         if (tree.errs != null)
3025             for (JCTree err : tree.errs)
3026                 attribTree(err, env, ERR, pt);
3027         result = tree.type = syms.errType;
3028     }
3029 
3030     /** Default visitor method for all other trees.
3031      */
3032     public void visitTree(JCTree tree) {
3033         throw new AssertionError();
3034     }
3035 
3036     /**
3037      * Attribute an env for either a top level tree or class declaration.
3038      */
3039     public void attrib(Env<AttrContext> env) {
3040         if (env.tree.getTag() == JCTree.TOPLEVEL)
3041             attribTopLevel(env);
3042         else
3043             attribClass(env.tree.pos(), env.enclClass.sym);
3044     }
3045 
3046     /**
3047      * Attribute a top level tree. These trees are encountered when the
3048      * package declaration has annotations.
3049      */
3050     public void attribTopLevel(Env<AttrContext> env) {
3051         JCCompilationUnit toplevel = env.toplevel;
3052         try {
3053             annotate.flush();
3054             chk.validateAnnotations(toplevel.packageAnnotations, toplevel.packge);
3055         } catch (CompletionFailure ex) {
3056             chk.completionError(toplevel.pos(), ex);
3057         }
3058     }
3059 
3060     /** Main method: attribute class definition associated with given class symbol.
3061      *  reporting completion failures at the given position.
3062      *  @param pos The source position at which completion errors are to be
3063      *             reported.
3064      *  @param c   The class symbol whose definition will be attributed.
3065      */
3066     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
3067         try {
3068             annotate.flush();
3069             attribClass(c);
3070         } catch (CompletionFailure ex) {
3071             chk.completionError(pos, ex);
3072         }
3073     }
3074 
3075     /** Attribute class definition associated with given class symbol.
3076      *  @param c   The class symbol whose definition will be attributed.
3077      */
3078     void attribClass(ClassSymbol c) throws CompletionFailure {
3079         if (c.type.tag == ERROR) return;
3080 
3081         // Check for cycles in the inheritance graph, which can arise from
3082         // ill-formed class files.
3083         chk.checkNonCyclic(null, c.type);
3084 
3085         Type st = types.supertype(c.type);
3086         if ((c.flags_field & Flags.COMPOUND) == 0) {
3087             // First, attribute superclass.
3088             if (st.tag == CLASS)
3089                 attribClass((ClassSymbol)st.tsym);
3090 
3091             // Next attribute owner, if it is a class.
3092             if (c.owner.kind == TYP && c.owner.type.tag == CLASS)
3093                 attribClass((ClassSymbol)c.owner);
3094         }
3095 
3096         // The previous operations might have attributed the current class
3097         // if there was a cycle. So we test first whether the class is still
3098         // UNATTRIBUTED.
3099         if ((c.flags_field & UNATTRIBUTED) != 0) {
3100             c.flags_field &= ~UNATTRIBUTED;
3101 
3102             // Get environment current at the point of class definition.
3103             Env<AttrContext> env = enter.typeEnvs.get(c);
3104 
3105             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
3106             // because the annotations were not available at the time the env was created. Therefore,
3107             // we look up the environment chain for the first enclosing environment for which the
3108             // lint value is set. Typically, this is the parent env, but might be further if there
3109             // are any envs created as a result of TypeParameter nodes.
3110             Env<AttrContext> lintEnv = env;
3111             while (lintEnv.info.lint == null)
3112                 lintEnv = lintEnv.next;
3113 
3114             // Having found the enclosing lint value, we can initialize the lint value for this class
3115             env.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags());
3116 
3117             Lint prevLint = chk.setLint(env.info.lint);
3118             JavaFileObject prev = log.useSource(c.sourcefile);
3119 
3120             try {
3121                 // java.lang.Enum may not be subclassed by a non-enum
3122                 if (st.tsym == syms.enumSym &&
3123                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
3124                     log.error(env.tree.pos(), "enum.no.subclassing");
3125 
3126                 // Enums may not be extended by source-level classes
3127                 if (st.tsym != null &&
3128                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
3129                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
3130                     !target.compilerBootstrap(c)) {
3131                     log.error(env.tree.pos(), "enum.types.not.extensible");
3132                 }
3133                 attribClassBody(env, c);
3134 
3135                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
3136             } finally {
3137                 log.useSource(prev);
3138                 chk.setLint(prevLint);
3139             }
3140 
3141         }
3142     }
3143 
3144     public void visitImport(JCImport tree) {
3145         // nothing to do
3146     }
3147 
3148     /** Finish the attribution of a class. */
3149     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
3150         JCClassDecl tree = (JCClassDecl)env.tree;
3151         Assert.check(c == tree.sym);
3152 
3153         // Validate annotations
3154         chk.validateAnnotations(tree.mods.annotations, c);
3155 
3156         // Validate type parameters, supertype and interfaces.
3157         attribBounds(tree.typarams);
3158         if (!c.isAnonymous()) {
3159             //already checked if anonymous
3160             chk.validate(tree.typarams, env);
3161             chk.validate(tree.extending, env);
3162             chk.validate(tree.implementing, env);
3163         }
3164 
3165         // If this is a non-abstract class, check that it has no abstract
3166         // methods or unimplemented methods of an implemented interface.
3167         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
3168             if (!relax)
3169                 chk.checkAllDefined(tree.pos(), c);
3170         }
3171 
3172         if ((c.flags() & ANNOTATION) != 0) {
3173             if (tree.implementing.nonEmpty())
3174                 log.error(tree.implementing.head.pos(),
3175                           "cant.extend.intf.annotation");
3176             if (tree.typarams.nonEmpty())
3177                 log.error(tree.typarams.head.pos(),
3178                           "intf.annotation.cant.have.type.params");
3179         } else {
3180             // Check that all extended classes and interfaces
3181             // are compatible (i.e. no two define methods with same arguments
3182             // yet different return types).  (JLS 8.4.6.3)
3183             chk.checkCompatibleSupertypes(tree.pos(), c.type);
3184         }
3185 
3186         // Check that class does not import the same parameterized interface
3187         // with two different argument lists.
3188         chk.checkClassBounds(tree.pos(), c.type);
3189 
3190         tree.type = c.type;
3191 
3192         for (List<JCTypeParameter> l = tree.typarams;
3193              l.nonEmpty(); l = l.tail) {
3194              Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope);
3195         }
3196 
3197         // Check that a generic class doesn't extend Throwable
3198         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
3199             log.error(tree.extending.pos(), "generic.throwable");
3200 
3201         // Check that all methods which implement some
3202         // method conform to the method they implement.
3203         chk.checkImplementations(tree);
3204 
3205         //check that a resource implementing AutoCloseable cannot throw InterruptedException
3206         checkAutoCloseable(tree.pos(), env, c.type);
3207 
3208         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3209             // Attribute declaration
3210             attribStat(l.head, env);
3211             // Check that declarations in inner classes are not static (JLS 8.1.2)
3212             // Make an exception for static constants.
3213             if (c.owner.kind != PCK &&
3214                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
3215                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
3216                 Symbol sym = null;
3217                 if (l.head.getTag() == JCTree.VARDEF) sym = ((JCVariableDecl) l.head).sym;
3218                 if (sym == null ||
3219                     sym.kind != VAR ||
3220                     ((VarSymbol) sym).getConstValue() == null)
3221                     log.error(l.head.pos(), "icls.cant.have.static.decl", c);
3222             }
3223         }
3224 
3225         // Check for cycles among non-initial constructors.
3226         chk.checkCyclicConstructors(tree);
3227 
3228         // Check for cycles among annotation elements.
3229         chk.checkNonCyclicElements(tree);
3230 
3231         // Check for proper use of serialVersionUID
3232         if (env.info.lint.isEnabled(LintCategory.SERIAL) &&
3233             isSerializable(c) &&
3234             (c.flags() & Flags.ENUM) == 0 &&
3235             (c.flags() & ABSTRACT) == 0) {
3236             checkSerialVersionUID(tree, c);
3237         }
3238     }
3239         // where
3240         /** check if a class is a subtype of Serializable, if that is available. */
3241         private boolean isSerializable(ClassSymbol c) {
3242             try {
3243                 syms.serializableType.complete();
3244             }
3245             catch (CompletionFailure e) {
3246                 return false;
3247             }
3248             return types.isSubtype(c.type, syms.serializableType);
3249         }
3250 
3251         /** Check that an appropriate serialVersionUID member is defined. */
3252         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
3253 
3254             // check for presence of serialVersionUID
3255             Scope.Entry e = c.members().lookup(names.serialVersionUID);
3256             while (e.scope != null && e.sym.kind != VAR) e = e.next();
3257             if (e.scope == null) {
3258                 log.warning(LintCategory.SERIAL,
3259                         tree.pos(), "missing.SVUID", c);
3260                 return;
3261             }
3262 
3263             // check that it is static final
3264             VarSymbol svuid = (VarSymbol)e.sym;
3265             if ((svuid.flags() & (STATIC | FINAL)) !=
3266                 (STATIC | FINAL))
3267                 log.warning(LintCategory.SERIAL,
3268                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
3269 
3270             // check that it is long
3271             else if (svuid.type.tag != TypeTags.LONG)
3272                 log.warning(LintCategory.SERIAL,
3273                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
3274 
3275             // check constant
3276             else if (svuid.getConstValue() == null)
3277                 log.warning(LintCategory.SERIAL,
3278                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
3279         }
3280 
3281     private Type capture(Type type) {
3282         return types.capture(type);
3283     }
3284 
3285     // <editor-fold desc="post-attribution visitor">
3286 
3287     /**
3288      * Handle missing types/symbols in an AST. This routine is useful when
3289      * the compiler has encountered some errors (which might have ended up
3290      * terminating attribution abruptly); if the compiler is used in fail-over
3291      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
3292      * prevents NPE to be progagated during subsequent compilation steps.
3293      */
3294     public void postAttr(Env<AttrContext> env) {
3295         new PostAttrAnalyzer().scan(env.tree);
3296     }
3297 
3298     class PostAttrAnalyzer extends TreeScanner {
3299 
3300         private void initTypeIfNeeded(JCTree that) {
3301             if (that.type == null) {
3302                 that.type = syms.unknownType;
3303             }
3304         }
3305 
3306         @Override
3307         public void scan(JCTree tree) {
3308             if (tree == null) return;
3309             if (tree instanceof JCExpression) {
3310                 initTypeIfNeeded(tree);
3311             }
3312             super.scan(tree);
3313         }
3314 
3315         @Override
3316         public void visitIdent(JCIdent that) {
3317             if (that.sym == null) {
3318                 that.sym = syms.unknownSymbol;
3319             }
3320         }
3321 
3322         @Override
3323         public void visitSelect(JCFieldAccess that) {
3324             if (that.sym == null) {
3325                 that.sym = syms.unknownSymbol;
3326             }
3327             super.visitSelect(that);
3328         }
3329 
3330         @Override
3331         public void visitClassDef(JCClassDecl that) {
3332             initTypeIfNeeded(that);
3333             if (that.sym == null) {
3334                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
3335             }
3336             super.visitClassDef(that);
3337         }
3338 
3339         @Override
3340         public void visitMethodDef(JCMethodDecl that) {
3341             initTypeIfNeeded(that);
3342             if (that.sym == null) {
3343                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
3344             }
3345             super.visitMethodDef(that);
3346         }
3347 
3348         @Override
3349         public void visitVarDef(JCVariableDecl that) {
3350             initTypeIfNeeded(that);
3351             if (that.sym == null) {
3352                 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
3353                 that.sym.adr = 0;
3354             }
3355             super.visitVarDef(that);
3356         }
3357 
3358         @Override
3359         public void visitNewClass(JCNewClass that) {
3360             if (that.constructor == null) {
3361                 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol);
3362             }
3363             if (that.constructorType == null) {
3364                 that.constructorType = syms.unknownType;
3365             }
3366             super.visitNewClass(that);
3367         }
3368 
3369         @Override
3370         public void visitBinary(JCBinary that) {
3371             if (that.operator == null)
3372                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
3373             super.visitBinary(that);
3374         }
3375 
3376         @Override
3377         public void visitUnary(JCUnary that) {
3378             if (that.operator == null)
3379                 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
3380             super.visitUnary(that);
3381         }
3382     }
3383     // </editor-fold>
3384 }