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