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