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 scope.
1004         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1005         // Attribute resource declarations
1006         ListBuffer<VarSymbol> resourceVars = ListBuffer.lb();
1007         for (JCTree resource : tree.resources) {
1008             if (resource.getTag() == JCTree.VARDEF) {
1009                 attribStat(resource, localEnv);
1010                 chk.checkType(resource, resource.type, syms.autoCloseableType, "arm.not.applicable.to.type");
1011                 VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource);
1012                 var.setData(ElementKind.RESOURCE_VARIABLE);
1013                 resourceVars.append(var);
1014             } else {
1015                 attribExpr(resource, localEnv, syms.autoCloseableType, "arm.not.applicable.to.type");
1016             }
1017         }
1018         // Attribute body
1019         attribStat(tree.body, localEnv.dup(tree, localEnv.info.dup()));
1020 
1021         //remove arm resource vars from local scope - such variables cannot be
1022         //accessed from catch/finally clauses
1023         for (VarSymbol resourceVar : resourceVars) {
1024             localEnv.info.scope.remove(resourceVar);
1025         }
1026 
1027         // Attribute catch clauses
1028         for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1029             JCCatch c = l.head;
1030             Env<AttrContext> catchEnv =
1031                 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
1032             Type ctype = attribStat(c.param, catchEnv);
1033             if (TreeInfo.isMultiCatch(c)) {
1034                 //check that multi-catch parameter is marked as final
1035                 if ((c.param.sym.flags() & FINAL) == 0) {
1036                     log.error(c.param.pos(), "multicatch.param.must.be.final", c.param.sym);
1037                 }
1038                 c.param.sym.flags_field = c.param.sym.flags() | DISJOINT;
1039             }
1040             if (c.param.type.tsym.kind == Kinds.VAR) {
1041                 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
1042             }
1043             chk.checkType(c.param.vartype.pos(),
1044                           chk.checkClassType(c.param.vartype.pos(), ctype),
1045                           syms.throwableType);
1046             attribStat(c.body, catchEnv);
1047             catchEnv.info.scope.leave();
1048         }
1049 
1050         // Attribute finalizer
1051         if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1052 
1053         localEnv.info.scope.leave();
1054         result = null;
1055     }
1056 
1057     public void visitConditional(JCConditional tree) {
1058         attribExpr(tree.cond, env, syms.booleanType);
1059         attribExpr(tree.truepart, env);
1060         attribExpr(tree.falsepart, env);
1061         result = check(tree,
1062                        capture(condType(tree.pos(), tree.cond.type,
1063                                         tree.truepart.type, tree.falsepart.type)),
1064                        VAL, pkind, pt);
1065     }
1066     //where
1067         /** Compute the type of a conditional expression, after
1068          *  checking that it exists. See Spec 15.25.
1069          *
1070          *  @param pos      The source position to be used for
1071          *                  error diagnostics.
1072          *  @param condtype The type of the expression's condition.
1073          *  @param thentype The type of the expression's then-part.
1074          *  @param elsetype The type of the expression's else-part.
1075          */
1076         private Type condType(DiagnosticPosition pos,
1077                               Type condtype,
1078                               Type thentype,
1079                               Type elsetype) {
1080             Type ctype = condType1(pos, condtype, thentype, elsetype);
1081 
1082             // If condition and both arms are numeric constants,
1083             // evaluate at compile-time.
1084             return ((condtype.constValue() != null) &&
1085                     (thentype.constValue() != null) &&
1086                     (elsetype.constValue() != null))
1087                 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
1088                 : ctype;
1089         }
1090         /** Compute the type of a conditional expression, after
1091          *  checking that it exists.  Does not take into
1092          *  account the special case where condition and both arms
1093          *  are constants.
1094          *
1095          *  @param pos      The source position to be used for error
1096          *                  diagnostics.
1097          *  @param condtype The type of the expression's condition.
1098          *  @param thentype The type of the expression's then-part.
1099          *  @param elsetype The type of the expression's else-part.
1100          */
1101         private Type condType1(DiagnosticPosition pos, Type condtype,
1102                                Type thentype, Type elsetype) {
1103             // If same type, that is the result
1104             if (types.isSameType(thentype, elsetype))
1105                 return thentype.baseType();
1106 
1107             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
1108                 ? thentype : types.unboxedType(thentype);
1109             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
1110                 ? elsetype : types.unboxedType(elsetype);
1111 
1112             // Otherwise, if both arms can be converted to a numeric
1113             // type, return the least numeric type that fits both arms
1114             // (i.e. return larger of the two, or return int if one
1115             // arm is short, the other is char).
1116             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
1117                 // If one arm has an integer subrange type (i.e., byte,
1118                 // short, or char), and the other is an integer constant
1119                 // that fits into the subrange, return the subrange type.
1120                 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
1121                     types.isAssignable(elseUnboxed, thenUnboxed))
1122                     return thenUnboxed.baseType();
1123                 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
1124                     types.isAssignable(thenUnboxed, elseUnboxed))
1125                     return elseUnboxed.baseType();
1126 
1127                 for (int i = BYTE; i < VOID; i++) {
1128                     Type candidate = syms.typeOfTag[i];
1129                     if (types.isSubtype(thenUnboxed, candidate) &&
1130                         types.isSubtype(elseUnboxed, candidate))
1131                         return candidate;
1132                 }
1133             }
1134 
1135             // Those were all the cases that could result in a primitive
1136             if (allowBoxing) {
1137                 if (thentype.isPrimitive())
1138                     thentype = types.boxedClass(thentype).type;
1139                 if (elsetype.isPrimitive())
1140                     elsetype = types.boxedClass(elsetype).type;
1141             }
1142 
1143             if (types.isSubtype(thentype, elsetype))
1144                 return elsetype.baseType();
1145             if (types.isSubtype(elsetype, thentype))
1146                 return thentype.baseType();
1147 
1148             if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
1149                 log.error(pos, "neither.conditional.subtype",
1150                           thentype, elsetype);
1151                 return thentype.baseType();
1152             }
1153 
1154             // both are known to be reference types.  The result is
1155             // lub(thentype,elsetype). This cannot fail, as it will
1156             // always be possible to infer "Object" if nothing better.
1157             return types.lub(thentype.baseType(), elsetype.baseType());
1158         }
1159 
1160     public void visitIf(JCIf tree) {
1161         attribExpr(tree.cond, env, syms.booleanType);
1162         attribStat(tree.thenpart, env);
1163         if (tree.elsepart != null)
1164             attribStat(tree.elsepart, env);
1165         chk.checkEmptyIf(tree);
1166         result = null;
1167     }
1168 
1169     public void visitExec(JCExpressionStatement tree) {
1170         attribExpr(tree.expr, env);
1171         result = null;
1172     }
1173 
1174     public void visitBreak(JCBreak tree) {
1175         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1176         result = null;
1177     }
1178 
1179     public void visitContinue(JCContinue tree) {
1180         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1181         result = null;
1182     }
1183     //where
1184         /** Return the target of a break or continue statement, if it exists,
1185          *  report an error if not.
1186          *  Note: The target of a labelled break or continue is the
1187          *  (non-labelled) statement tree referred to by the label,
1188          *  not the tree representing the labelled statement itself.
1189          *
1190          *  @param pos     The position to be used for error diagnostics
1191          *  @param tag     The tag of the jump statement. This is either
1192          *                 Tree.BREAK or Tree.CONTINUE.
1193          *  @param label   The label of the jump statement, or null if no
1194          *                 label is given.
1195          *  @param env     The environment current at the jump statement.
1196          */
1197         private JCTree findJumpTarget(DiagnosticPosition pos,
1198                                     int tag,
1199                                     Name label,
1200                                     Env<AttrContext> env) {
1201             // Search environments outwards from the point of jump.
1202             Env<AttrContext> env1 = env;
1203             LOOP:
1204             while (env1 != null) {
1205                 switch (env1.tree.getTag()) {
1206                 case JCTree.LABELLED:
1207                     JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
1208                     if (label == labelled.label) {
1209                         // If jump is a continue, check that target is a loop.
1210                         if (tag == JCTree.CONTINUE) {
1211                             if (labelled.body.getTag() != JCTree.DOLOOP &&
1212                                 labelled.body.getTag() != JCTree.WHILELOOP &&
1213                                 labelled.body.getTag() != JCTree.FORLOOP &&
1214                                 labelled.body.getTag() != JCTree.FOREACHLOOP)
1215                                 log.error(pos, "not.loop.label", label);
1216                             // Found labelled statement target, now go inwards
1217                             // to next non-labelled tree.
1218                             return TreeInfo.referencedStatement(labelled);
1219                         } else {
1220                             return labelled;
1221                         }
1222                     }
1223                     break;
1224                 case JCTree.DOLOOP:
1225                 case JCTree.WHILELOOP:
1226                 case JCTree.FORLOOP:
1227                 case JCTree.FOREACHLOOP:
1228                     if (label == null) return env1.tree;
1229                     break;
1230                 case JCTree.SWITCH:
1231                     if (label == null && tag == JCTree.BREAK) return env1.tree;
1232                     break;
1233                 case JCTree.METHODDEF:
1234                 case JCTree.CLASSDEF:
1235                     break LOOP;
1236                 default:
1237                 }
1238                 env1 = env1.next;
1239             }
1240             if (label != null)
1241                 log.error(pos, "undef.label", label);
1242             else if (tag == JCTree.CONTINUE)
1243                 log.error(pos, "cont.outside.loop");
1244             else
1245                 log.error(pos, "break.outside.switch.loop");
1246             return null;
1247         }
1248 
1249     public void visitReturn(JCReturn tree) {
1250         // Check that there is an enclosing method which is
1251         // nested within than the enclosing class.
1252         if (env.enclMethod == null ||
1253             env.enclMethod.sym.owner != env.enclClass.sym) {
1254             log.error(tree.pos(), "ret.outside.meth");
1255 
1256         } else {
1257             // Attribute return expression, if it exists, and check that
1258             // it conforms to result type of enclosing method.
1259             Symbol m = env.enclMethod.sym;
1260             if (m.type.getReturnType().tag == VOID) {
1261                 if (tree.expr != null)
1262                     log.error(tree.expr.pos(),
1263                               "cant.ret.val.from.meth.decl.void");
1264             } else if (tree.expr == null) {
1265                 log.error(tree.pos(), "missing.ret.val");
1266             } else {
1267                 attribExpr(tree.expr, env, m.type.getReturnType());
1268             }
1269         }
1270         result = null;
1271     }
1272 
1273     public void visitThrow(JCThrow tree) {
1274         attribExpr(tree.expr, env, syms.throwableType);
1275         result = null;
1276     }
1277 
1278     public void visitAssert(JCAssert tree) {
1279         attribExpr(tree.cond, env, syms.booleanType);
1280         if (tree.detail != null) {
1281             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
1282         }
1283         result = null;
1284     }
1285 
1286      /** Visitor method for method invocations.
1287      *  NOTE: The method part of an application will have in its type field
1288      *        the return type of the method, not the method's type itself!
1289      */
1290     public void visitApply(JCMethodInvocation tree) {
1291         // The local environment of a method application is
1292         // a new environment nested in the current one.
1293         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1294 
1295         // The types of the actual method arguments.
1296         List<Type> argtypes;
1297 
1298         // The types of the actual method type arguments.
1299         List<Type> typeargtypes = null;
1300         boolean typeargtypesNonRefOK = false;
1301 
1302         Name methName = TreeInfo.name(tree.meth);
1303 
1304         boolean isConstructorCall =
1305             methName == names._this || methName == names._super;
1306 
1307         if (isConstructorCall) {
1308             // We are seeing a ...this(...) or ...super(...) call.
1309             // Check that this is the first statement in a constructor.
1310             if (checkFirstConstructorStat(tree, env)) {
1311 
1312                 // Record the fact
1313                 // that this is a constructor call (using isSelfCall).
1314                 localEnv.info.isSelfCall = true;
1315 
1316                 // Attribute arguments, yielding list of argument types.
1317                 argtypes = attribArgs(tree.args, localEnv);
1318                 typeargtypes = attribTypes(tree.typeargs, localEnv);
1319 
1320                 // Variable `site' points to the class in which the called
1321                 // constructor is defined.
1322                 Type site = env.enclClass.sym.type;
1323                 if (methName == names._super) {
1324                     if (site == syms.objectType) {
1325                         log.error(tree.meth.pos(), "no.superclass", site);
1326                         site = types.createErrorType(syms.objectType);
1327                     } else {
1328                         site = types.supertype(site);
1329                     }
1330                 }
1331 
1332                 if (site.tag == CLASS) {
1333                     Type encl = site.getEnclosingType();
1334                     while (encl != null && encl.tag == TYPEVAR)
1335                         encl = encl.getUpperBound();
1336                     if (encl.tag == CLASS) {
1337                         // we are calling a nested class
1338 
1339                         if (tree.meth.getTag() == JCTree.SELECT) {
1340                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
1341 
1342                             // We are seeing a prefixed call, of the form
1343                             //     <expr>.super(...).
1344                             // Check that the prefix expression conforms
1345                             // to the outer instance type of the class.
1346                             chk.checkRefType(qualifier.pos(),
1347                                              attribExpr(qualifier, localEnv,
1348                                                         encl));
1349                         } else if (methName == names._super) {
1350                             // qualifier omitted; check for existence
1351                             // of an appropriate implicit qualifier.
1352                             rs.resolveImplicitThis(tree.meth.pos(),
1353                                                    localEnv, site);
1354                         }
1355                     } else if (tree.meth.getTag() == JCTree.SELECT) {
1356                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
1357                                   site.tsym);
1358                     }
1359 
1360                     // if we're calling a java.lang.Enum constructor,
1361                     // prefix the implicit String and int parameters
1362                     if (site.tsym == syms.enumSym && allowEnums)
1363                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
1364 
1365                     // Resolve the called constructor under the assumption
1366                     // that we are referring to a superclass instance of the
1367                     // current instance (JLS ???).
1368                     boolean selectSuperPrev = localEnv.info.selectSuper;
1369                     localEnv.info.selectSuper = true;
1370                     localEnv.info.varArgs = false;
1371                     Symbol sym = rs.resolveConstructor(
1372                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
1373                     localEnv.info.selectSuper = selectSuperPrev;
1374 
1375                     // Set method symbol to resolved constructor...
1376                     TreeInfo.setSymbol(tree.meth, sym);
1377 
1378                     // ...and check that it is legal in the current context.
1379                     // (this will also set the tree's type)
1380                     Type mpt = newMethTemplate(argtypes, typeargtypes);
1381                     checkId(tree.meth, site, sym, localEnv, MTH,
1382                             mpt, tree.varargsElement != null);
1383                 }
1384                 // Otherwise, `site' is an error type and we do nothing
1385             }
1386             result = tree.type = syms.voidType;
1387         } else {
1388             // Otherwise, we are seeing a regular method call.
1389             // Attribute the arguments, yielding list of argument types, ...
1390             argtypes = attribArgs(tree.args, localEnv);
1391             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
1392 
1393             // ... and attribute the method using as a prototype a methodtype
1394             // whose formal argument types is exactly the list of actual
1395             // arguments (this will also set the method symbol).
1396             Type mpt = newMethTemplate(argtypes, typeargtypes);
1397             localEnv.info.varArgs = false;
1398             Type mtype = attribExpr(tree.meth, localEnv, mpt);
1399             if (localEnv.info.varArgs)
1400                 assert mtype.isErroneous() || tree.varargsElement != null;
1401 
1402             // Compute the result type.
1403             Type restype = mtype.getReturnType();
1404             assert restype.tag != WILDCARD : mtype;
1405 
1406             // as a special case, array.clone() has a result that is
1407             // the same as static type of the array being cloned
1408             if (tree.meth.getTag() == JCTree.SELECT &&
1409                 allowCovariantReturns &&
1410                 methName == names.clone &&
1411                 types.isArray(((JCFieldAccess) tree.meth).selected.type))
1412                 restype = ((JCFieldAccess) tree.meth).selected.type;
1413 
1414             // as a special case, x.getClass() has type Class<? extends |X|>
1415             if (allowGenerics &&
1416                 methName == names.getClass && tree.args.isEmpty()) {
1417                 Type qualifier = (tree.meth.getTag() == JCTree.SELECT)
1418                     ? ((JCFieldAccess) tree.meth).selected.type
1419                     : env.enclClass.sym.type;
1420                 restype = new
1421                     ClassType(restype.getEnclosingType(),
1422                               List.<Type>of(new WildcardType(types.erasure(qualifier),
1423                                                                BoundKind.EXTENDS,
1424                                                                syms.boundClass)),
1425                               restype.tsym);
1426             }
1427 
1428             // as a special case, MethodHandle.<T>invoke(abc) and InvokeDynamic.<T>foo(abc)
1429             // has type <T>, and T can be a primitive type.
1430             if (tree.meth.getTag() == JCTree.SELECT && !typeargtypes.isEmpty()) {
1431               Type selt = ((JCFieldAccess) tree.meth).selected.type;
1432               if ((selt == syms.methodHandleType && methName == names.invoke) || selt == syms.invokeDynamicType) {
1433                   assert types.isSameType(restype, typeargtypes.head) : mtype;
1434                   typeargtypesNonRefOK = true;
1435               }
1436             }
1437 
1438             if (!typeargtypesNonRefOK) {
1439                 chk.checkRefTypes(tree.typeargs, typeargtypes);
1440             }
1441 
1442             // Check that value of resulting type is admissible in the
1443             // current context.  Also, capture the return type
1444             result = check(tree, capture(restype), VAL, pkind, pt);
1445         }
1446         chk.validate(tree.typeargs, localEnv);
1447     }
1448     //where
1449         /** Check that given application node appears as first statement
1450          *  in a constructor call.
1451          *  @param tree   The application node
1452          *  @param env    The environment current at the application.
1453          */
1454         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
1455             JCMethodDecl enclMethod = env.enclMethod;
1456             if (enclMethod != null && enclMethod.name == names.init) {
1457                 JCBlock body = enclMethod.body;
1458                 if (body.stats.head.getTag() == JCTree.EXEC &&
1459                     ((JCExpressionStatement) body.stats.head).expr == tree)
1460                     return true;
1461             }
1462             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
1463                       TreeInfo.name(tree.meth));
1464             return false;
1465         }
1466 
1467         /** Obtain a method type with given argument types.
1468          */
1469         Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) {
1470             MethodType mt = new MethodType(argtypes, null, null, syms.methodClass);
1471             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
1472         }
1473 
1474     public void visitNewClass(JCNewClass tree) {
1475         Type owntype = types.createErrorType(tree.type);
1476 
1477         // The local environment of a class creation is
1478         // a new environment nested in the current one.
1479         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1480 
1481         // The anonymous inner class definition of the new expression,
1482         // if one is defined by it.
1483         JCClassDecl cdef = tree.def;
1484 
1485         // If enclosing class is given, attribute it, and
1486         // complete class name to be fully qualified
1487         JCExpression clazz = tree.clazz; // Class field following new
1488         JCExpression clazzid =          // Identifier in class field
1489             (clazz.getTag() == JCTree.TYPEAPPLY)
1490             ? ((JCTypeApply) clazz).clazz
1491             : clazz;
1492 
1493         JCExpression clazzid1 = clazzid; // The same in fully qualified form
1494 
1495         if (tree.encl != null) {
1496             // We are seeing a qualified new, of the form
1497             //    <expr>.new C <...> (...) ...
1498             // In this case, we let clazz stand for the name of the
1499             // allocated class C prefixed with the type of the qualifier
1500             // expression, so that we can
1501             // resolve it with standard techniques later. I.e., if
1502             // <expr> has type T, then <expr>.new C <...> (...)
1503             // yields a clazz T.C.
1504             Type encltype = chk.checkRefType(tree.encl.pos(),
1505                                              attribExpr(tree.encl, env));
1506             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
1507                                                  ((JCIdent) clazzid).name);
1508             if (clazz.getTag() == JCTree.TYPEAPPLY)
1509                 clazz = make.at(tree.pos).
1510                     TypeApply(clazzid1,
1511                               ((JCTypeApply) clazz).arguments);
1512             else
1513                 clazz = clazzid1;
1514         }
1515 
1516         // Attribute clazz expression and store
1517         // symbol + type back into the attributed tree.
1518         Type clazztype = attribType(clazz, env);
1519         Pair<Scope,Scope> mapping = getSyntheticScopeMapping(clazztype);
1520         if (!TreeInfo.isDiamond(tree)) {
1521             clazztype = chk.checkClassType(
1522                 tree.clazz.pos(), clazztype, true);
1523         }
1524         chk.validate(clazz, localEnv);
1525         if (tree.encl != null) {
1526             // We have to work in this case to store
1527             // symbol + type back into the attributed tree.
1528             tree.clazz.type = clazztype;
1529             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
1530             clazzid.type = ((JCIdent) clazzid).sym.type;
1531             if (!clazztype.isErroneous()) {
1532                 if (cdef != null && clazztype.tsym.isInterface()) {
1533                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
1534                 } else if (clazztype.tsym.isStatic()) {
1535                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
1536                 }
1537             }
1538         } else if (!clazztype.tsym.isInterface() &&
1539                    clazztype.getEnclosingType().tag == CLASS) {
1540             // Check for the existence of an apropos outer instance
1541             rs.resolveImplicitThis(tree.pos(), env, clazztype);
1542         }
1543 
1544         // Attribute constructor arguments.
1545         List<Type> argtypes = attribArgs(tree.args, localEnv);
1546         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
1547 
1548         if (TreeInfo.isDiamond(tree)) {
1549             clazztype = attribDiamond(localEnv, tree, clazztype, mapping, argtypes, typeargtypes, true);
1550             clazz.type = clazztype;
1551         }
1552 
1553         // If we have made no mistakes in the class type...
1554         if (clazztype.tag == CLASS) {
1555             // Enums may not be instantiated except implicitly
1556             if (allowEnums &&
1557                 (clazztype.tsym.flags_field&Flags.ENUM) != 0 &&
1558                 (env.tree.getTag() != JCTree.VARDEF ||
1559                  (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 ||
1560                  ((JCVariableDecl) env.tree).init != tree))
1561                 log.error(tree.pos(), "enum.cant.be.instantiated");
1562             // Check that class is not abstract
1563             if (cdef == null &&
1564                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
1565                 log.error(tree.pos(), "abstract.cant.be.instantiated",
1566                           clazztype.tsym);
1567             } else if (cdef != null && clazztype.tsym.isInterface()) {
1568                 // Check that no constructor arguments are given to
1569                 // anonymous classes implementing an interface
1570                 if (!argtypes.isEmpty())
1571                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
1572 
1573                 if (!typeargtypes.isEmpty())
1574                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
1575 
1576                 // Error recovery: pretend no arguments were supplied.
1577                 argtypes = List.nil();
1578                 typeargtypes = List.nil();
1579             }
1580 
1581             // Resolve the called constructor under the assumption
1582             // that we are referring to a superclass instance of the
1583             // current instance (JLS ???).
1584             else {
1585                 localEnv.info.selectSuper = cdef != null;
1586                 localEnv.info.varArgs = false;
1587                 tree.constructor = rs.resolveConstructor(
1588                     tree.pos(), localEnv, clazztype, argtypes, typeargtypes);
1589                 tree.constructorType = checkMethod(clazztype,
1590                                                 tree.constructor,
1591                                                 localEnv,
1592                                                 tree.args,
1593                                                 argtypes,
1594                                                 typeargtypes,
1595                                                 localEnv.info.varArgs);
1596                 if (localEnv.info.varArgs)
1597                     assert tree.constructorType.isErroneous() || tree.varargsElement != null;
1598             }
1599 
1600             if (cdef != null) {
1601                 // We are seeing an anonymous class instance creation.
1602                 // In this case, the class instance creation
1603                 // expression
1604                 //
1605                 //    E.new <typeargs1>C<typargs2>(args) { ... }
1606                 //
1607                 // is represented internally as
1608                 //
1609                 //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
1610                 //
1611                 // This expression is then *transformed* as follows:
1612                 //
1613                 // (1) add a STATIC flag to the class definition
1614                 //     if the current environment is static
1615                 // (2) add an extends or implements clause
1616                 // (3) add a constructor.
1617                 //
1618                 // For instance, if C is a class, and ET is the type of E,
1619                 // the expression
1620                 //
1621                 //    E.new <typeargs1>C<typargs2>(args) { ... }
1622                 //
1623                 // is translated to (where X is a fresh name and typarams is the
1624                 // parameter list of the super constructor):
1625                 //
1626                 //   new <typeargs1>X(<*nullchk*>E, args) where
1627                 //     X extends C<typargs2> {
1628                 //       <typarams> X(ET e, args) {
1629                 //         e.<typeargs1>super(args)
1630                 //       }
1631                 //       ...
1632                 //     }
1633                 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC;
1634 
1635                 if (clazztype.tsym.isInterface()) {
1636                     cdef.implementing = List.of(clazz);
1637                 } else {
1638                     cdef.extending = clazz;
1639                 }
1640 
1641                 attribStat(cdef, localEnv);
1642 
1643                 // If an outer instance is given,
1644                 // prefix it to the constructor arguments
1645                 // and delete it from the new expression
1646                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
1647                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
1648                     argtypes = argtypes.prepend(tree.encl.type);
1649                     tree.encl = null;
1650                 }
1651 
1652                 // Reassign clazztype and recompute constructor.
1653                 clazztype = cdef.sym.type;
1654                 Symbol sym = rs.resolveConstructor(
1655                     tree.pos(), localEnv, clazztype, argtypes,
1656                     typeargtypes, true, tree.varargsElement != null);
1657                 assert sym.kind < AMBIGUOUS || tree.constructor.type.isErroneous();
1658                 tree.constructor = sym;
1659                 if (tree.constructor.kind > ERRONEOUS) {
1660                     tree.constructorType =  syms.errType;
1661                 }
1662                 else {
1663                     tree.constructorType = checkMethod(clazztype,
1664                             tree.constructor,
1665                             localEnv,
1666                             tree.args,
1667                             argtypes,
1668                             typeargtypes,
1669                             localEnv.info.varArgs);
1670                 }
1671             }
1672 
1673             if (tree.constructor != null && tree.constructor.kind == MTH)
1674                 owntype = clazztype;
1675         }
1676         result = check(tree, owntype, VAL, pkind, pt);
1677         chk.validate(tree.typeargs, localEnv);
1678     }
1679 
1680     Type attribDiamond(Env<AttrContext> env,
1681                         JCNewClass tree,
1682                         Type clazztype,
1683                         Pair<Scope, Scope> mapping,
1684                         List<Type> argtypes,
1685                         List<Type> typeargtypes,
1686                         boolean reportErrors) {
1687         if (clazztype.isErroneous() || mapping == erroneousMapping) {
1688             //if the type of the instance creation expression is erroneous,
1689             //or something prevented us to form a valid mapping, return the
1690             //(possibly erroneous) type unchanged
1691             return clazztype;
1692         }
1693         else if (clazztype.isInterface()) {
1694             //if the type of the instance creation expression is an interface
1695             //skip the method resolution step (JLS 15.12.2.7). The type to be
1696             //inferred is of the kind <X1,X2, ... Xn>C<X1,X2, ... Xn>
1697             clazztype = new ForAll(clazztype.tsym.type.allparams(),
1698                     clazztype.tsym.type);
1699         } else {
1700             //if the type of the instance creation expression is a class type
1701             //apply method resolution inference (JLS 15.12.2.7). The return type
1702             //of the resolved constructor will be a partially instantiated type
1703             ((ClassSymbol) clazztype.tsym).members_field = mapping.snd;
1704             Symbol constructor;
1705             try {
1706                 constructor = rs.resolveDiamond(tree.pos(),
1707                         env,
1708                         clazztype.tsym.type,
1709                         argtypes,
1710                         typeargtypes, reportErrors);
1711             } finally {
1712                 ((ClassSymbol) clazztype.tsym).members_field = mapping.fst;
1713             }
1714             if (constructor.kind == MTH) {
1715                 ClassType ct = new ClassType(clazztype.getEnclosingType(),
1716                         clazztype.tsym.type.getTypeArguments(),
1717                         clazztype.tsym);
1718                 clazztype = checkMethod(ct,
1719                         constructor,
1720                         env,
1721                         tree.args,
1722                         argtypes,
1723                         typeargtypes,
1724                         env.info.varArgs).getReturnType();
1725             } else {
1726                 clazztype = syms.errType;
1727             }
1728         }
1729         if (clazztype.tag == FORALL && !pt.isErroneous()) {
1730             //if the resolved constructor's return type has some uninferred
1731             //type-variables, infer them using the expected type and declared
1732             //bounds (JLS 15.12.2.8).
1733             try {
1734                 clazztype = infer.instantiateExpr((ForAll) clazztype,
1735                         pt.tag == NONE ? syms.objectType : pt,
1736                         Warner.noWarnings);
1737             } catch (Infer.InferenceException ex) {
1738                 //an error occurred while inferring uninstantiated type-variables
1739                 //we need to optionally report an error
1740                 if (reportErrors) {
1741                     log.error(tree.clazz.pos(),
1742                             "cant.apply.diamond.1",
1743                             diags.fragment("diamond", clazztype.tsym),
1744                             ex.diagnostic);
1745                 }
1746             }
1747         }
1748         if (reportErrors) {
1749             clazztype = chk.checkClassType(tree.clazz.pos(),
1750                     clazztype,
1751                     true);
1752             if (clazztype.tag == CLASS) {
1753                 List<Type> invalidDiamondArgs = chk.checkDiamond((ClassType)clazztype);
1754                 if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
1755                     //one or more types inferred in the previous steps is either a
1756                     //captured type or an intersection type --- we need to report an error.
1757                     String subkey = invalidDiamondArgs.size() > 1 ?
1758                         "diamond.invalid.args" :
1759                         "diamond.invalid.arg";
1760                     //The error message is of the kind:
1761                     //
1762                     //cannot infer type arguments for {clazztype}<>;
1763                     //reason: {subkey}
1764                     //
1765                     //where subkey is a fragment of the kind:
1766                     //
1767                     //type argument(s) {invalidDiamondArgs} inferred for {clazztype}<> is not allowed in this context
1768                     log.error(tree.clazz.pos(),
1769                                 "cant.apply.diamond.1",
1770                                 diags.fragment("diamond", clazztype.tsym),
1771                                 diags.fragment(subkey,
1772                                                invalidDiamondArgs,
1773                                                diags.fragment("diamond", clazztype.tsym)));
1774                 }
1775             }
1776         }
1777         return clazztype;
1778     }
1779 
1780     /** Creates a synthetic scope containing fake generic constructors.
1781      *  Assuming that the original scope contains a constructor of the kind:
1782      *  Foo(X x, Y y), where X,Y are class type-variables declared in Foo,
1783      *  the synthetic scope is added a generic constructor of the kind:
1784      *  <X,Y>Foo<X,Y>(X x, Y y). This is crucial in order to enable diamond
1785      *  inference. The inferred return type of the synthetic constructor IS
1786      *  the inferred type for the diamond operator.
1787      */
1788     private Pair<Scope, Scope> getSyntheticScopeMapping(Type ctype) {
1789         if (ctype.tag != CLASS) {
1790             return erroneousMapping;
1791         }
1792         Pair<Scope, Scope> mapping =
1793                 new Pair<Scope, Scope>(ctype.tsym.members(), new Scope(ctype.tsym));
1794         List<Type> typevars = ctype.tsym.type.getTypeArguments();
1795         for (Scope.Entry e = mapping.fst.lookup(names.init);
1796                 e.scope != null;
1797                 e = e.next()) {
1798             MethodSymbol newConstr = (MethodSymbol) e.sym.clone(ctype.tsym);
1799             newConstr.name = names.init;
1800             List<Type> oldTypeargs = List.nil();
1801             if (newConstr.type.tag == FORALL) {
1802                 oldTypeargs = ((ForAll) newConstr.type).tvars;
1803             }
1804             newConstr.type = new MethodType(newConstr.type.getParameterTypes(),
1805                     new ClassType(ctype.getEnclosingType(), ctype.tsym.type.getTypeArguments(), ctype.tsym),
1806                     newConstr.type.getThrownTypes(),
1807                     syms.methodClass);
1808             newConstr.type = new ForAll(typevars.prependList(oldTypeargs), newConstr.type);
1809             mapping.snd.enter(newConstr);
1810         }
1811         return mapping;
1812     }
1813 
1814     private final Pair<Scope,Scope> erroneousMapping = new Pair<Scope,Scope>(null, null);
1815 
1816     /** Make an attributed null check tree.
1817      */
1818     public JCExpression makeNullCheck(JCExpression arg) {
1819         // optimization: X.this is never null; skip null check
1820         Name name = TreeInfo.name(arg);
1821         if (name == names._this || name == names._super) return arg;
1822 
1823         int optag = JCTree.NULLCHK;
1824         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
1825         tree.operator = syms.nullcheck;
1826         tree.type = arg.type;
1827         return tree;
1828     }
1829 
1830     public void visitNewArray(JCNewArray tree) {
1831         Type owntype = types.createErrorType(tree.type);
1832         Type elemtype;
1833         if (tree.elemtype != null) {
1834             elemtype = attribType(tree.elemtype, env);
1835             chk.validate(tree.elemtype, env);
1836             owntype = elemtype;
1837             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
1838                 attribExpr(l.head, env, syms.intType);
1839                 owntype = new ArrayType(owntype, syms.arrayClass);
1840             }
1841         } else {
1842             // we are seeing an untyped aggregate { ... }
1843             // this is allowed only if the prototype is an array
1844             if (pt.tag == ARRAY) {
1845                 elemtype = types.elemtype(pt);
1846             } else {
1847                 if (pt.tag != ERROR) {
1848                     log.error(tree.pos(), "illegal.initializer.for.type",
1849                               pt);
1850                 }
1851                 elemtype = types.createErrorType(pt);
1852             }
1853         }
1854         if (tree.elems != null) {
1855             attribExprs(tree.elems, env, elemtype);
1856             owntype = new ArrayType(elemtype, syms.arrayClass);
1857         }
1858         if (!types.isReifiable(elemtype))
1859             log.error(tree.pos(), "generic.array.creation");
1860         result = check(tree, owntype, VAL, pkind, pt);
1861     }
1862 
1863     public void visitParens(JCParens tree) {
1864         Type owntype = attribTree(tree.expr, env, pkind, pt);
1865         result = check(tree, owntype, pkind, pkind, pt);
1866         Symbol sym = TreeInfo.symbol(tree);
1867         if (sym != null && (sym.kind&(TYP|PCK)) != 0)
1868             log.error(tree.pos(), "illegal.start.of.type");
1869     }
1870 
1871     public void visitAssign(JCAssign tree) {
1872         Type owntype = attribTree(tree.lhs, env.dup(tree), VAR, Type.noType);
1873         Type capturedType = capture(owntype);
1874         attribExpr(tree.rhs, env, owntype);
1875         result = check(tree, capturedType, VAL, pkind, pt);
1876     }
1877 
1878     public void visitAssignop(JCAssignOp tree) {
1879         // Attribute arguments.
1880         Type owntype = attribTree(tree.lhs, env, VAR, Type.noType);
1881         Type operand = attribExpr(tree.rhs, env);
1882         // Find operator.
1883         Symbol operator = tree.operator = rs.resolveBinaryOperator(
1884             tree.pos(), tree.getTag() - JCTree.ASGOffset, env,
1885             owntype, operand);
1886 
1887         if (operator.kind == MTH) {
1888             chk.checkOperator(tree.pos(),
1889                               (OperatorSymbol)operator,
1890                               tree.getTag() - JCTree.ASGOffset,
1891                               owntype,
1892                               operand);
1893             chk.checkDivZero(tree.rhs.pos(), operator, operand);
1894             chk.checkCastable(tree.rhs.pos(),
1895                               operator.type.getReturnType(),
1896                               owntype);
1897         }
1898         result = check(tree, owntype, VAL, pkind, pt);
1899     }
1900 
1901     public void visitUnary(JCUnary tree) {
1902         // Attribute arguments.
1903         Type argtype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
1904             ? attribTree(tree.arg, env, VAR, Type.noType)
1905             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
1906 
1907         // Find operator.
1908         Symbol operator = tree.operator =
1909             rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype);
1910 
1911         Type owntype = types.createErrorType(tree.type);
1912         if (operator.kind == MTH) {
1913             owntype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC)
1914                 ? tree.arg.type
1915                 : operator.type.getReturnType();
1916             int opc = ((OperatorSymbol)operator).opcode;
1917 
1918             // If the argument is constant, fold it.
1919             if (argtype.constValue() != null) {
1920                 Type ctype = cfolder.fold1(opc, argtype);
1921                 if (ctype != null) {
1922                     owntype = cfolder.coerce(ctype, owntype);
1923 
1924                     // Remove constant types from arguments to
1925                     // conserve space. The parser will fold concatenations
1926                     // of string literals; the code here also
1927                     // gets rid of intermediate results when some of the
1928                     // operands are constant identifiers.
1929                     if (tree.arg.type.tsym == syms.stringType.tsym) {
1930                         tree.arg.type = syms.stringType;
1931                     }
1932                 }
1933             }
1934         }
1935         result = check(tree, owntype, VAL, pkind, pt);
1936     }
1937 
1938     public void visitBinary(JCBinary tree) {
1939         // Attribute arguments.
1940         Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
1941         Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));
1942 
1943         // Find operator.
1944         Symbol operator = tree.operator =
1945             rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);
1946 
1947         Type owntype = types.createErrorType(tree.type);
1948         if (operator.kind == MTH) {
1949             owntype = operator.type.getReturnType();
1950             int opc = chk.checkOperator(tree.lhs.pos(),
1951                                         (OperatorSymbol)operator,
1952                                         tree.getTag(),
1953                                         left,
1954                                         right);
1955 
1956             // If both arguments are constants, fold them.
1957             if (left.constValue() != null && right.constValue() != null) {
1958                 Type ctype = cfolder.fold2(opc, left, right);
1959                 if (ctype != null) {
1960                     owntype = cfolder.coerce(ctype, owntype);
1961 
1962                     // Remove constant types from arguments to
1963                     // conserve space. The parser will fold concatenations
1964                     // of string literals; the code here also
1965                     // gets rid of intermediate results when some of the
1966                     // operands are constant identifiers.
1967                     if (tree.lhs.type.tsym == syms.stringType.tsym) {
1968                         tree.lhs.type = syms.stringType;
1969                     }
1970                     if (tree.rhs.type.tsym == syms.stringType.tsym) {
1971                         tree.rhs.type = syms.stringType;
1972                     }
1973                 }
1974             }
1975 
1976             // Check that argument types of a reference ==, != are
1977             // castable to each other, (JLS???).
1978             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
1979                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
1980                     log.error(tree.pos(), "incomparable.types", left, right);
1981                 }
1982             }
1983 
1984             chk.checkDivZero(tree.rhs.pos(), operator, right);
1985         }
1986         result = check(tree, owntype, VAL, pkind, pt);
1987     }
1988 
1989     public void visitTypeCast(JCTypeCast tree) {
1990         Type clazztype = attribType(tree.clazz, env);
1991         chk.validate(tree.clazz, env);
1992         Type exprtype = attribExpr(tree.expr, env, Infer.anyPoly);
1993         Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
1994         if (exprtype.constValue() != null)
1995             owntype = cfolder.coerce(exprtype, owntype);
1996         result = check(tree, capture(owntype), VAL, pkind, pt);
1997     }
1998 
1999     public void visitTypeTest(JCInstanceOf tree) {
2000         Type exprtype = chk.checkNullOrRefType(
2001             tree.expr.pos(), attribExpr(tree.expr, env));
2002         Type clazztype = chk.checkReifiableReferenceType(
2003             tree.clazz.pos(), attribType(tree.clazz, env));
2004         chk.validate(tree.clazz, env);
2005         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
2006         result = check(tree, syms.booleanType, VAL, pkind, pt);
2007     }
2008 
2009     public void visitIndexed(JCArrayAccess tree) {
2010         Type owntype = types.createErrorType(tree.type);
2011         Type atype = attribExpr(tree.indexed, env);
2012         attribExpr(tree.index, env, syms.intType);
2013         if (types.isArray(atype))
2014             owntype = types.elemtype(atype);
2015         else if (atype.tag != ERROR)
2016             log.error(tree.pos(), "array.req.but.found", atype);
2017         if ((pkind & VAR) == 0) owntype = capture(owntype);
2018         result = check(tree, owntype, VAR, pkind, pt);
2019     }
2020 
2021     public void visitIdent(JCIdent tree) {
2022         Symbol sym;
2023         boolean varArgs = false;
2024 
2025         // Find symbol
2026         if (pt.tag == METHOD || pt.tag == FORALL) {
2027             // If we are looking for a method, the prototype `pt' will be a
2028             // method type with the type of the call's arguments as parameters.
2029             env.info.varArgs = false;
2030             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt.getParameterTypes(), pt.getTypeArguments());
2031             varArgs = env.info.varArgs;
2032         } else if (tree.sym != null && tree.sym.kind != VAR) {
2033             sym = tree.sym;
2034         } else {
2035             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind);
2036         }
2037         tree.sym = sym;
2038 
2039         // (1) Also find the environment current for the class where
2040         //     sym is defined (`symEnv').
2041         // Only for pre-tiger versions (1.4 and earlier):
2042         // (2) Also determine whether we access symbol out of an anonymous
2043         //     class in a this or super call.  This is illegal for instance
2044         //     members since such classes don't carry a this$n link.
2045         //     (`noOuterThisPath').
2046         Env<AttrContext> symEnv = env;
2047         boolean noOuterThisPath = false;
2048         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
2049             (sym.kind & (VAR | MTH | TYP)) != 0 &&
2050             sym.owner.kind == TYP &&
2051             tree.name != names._this && tree.name != names._super) {
2052 
2053             // Find environment in which identifier is defined.
2054             while (symEnv.outer != null &&
2055                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
2056                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
2057                     noOuterThisPath = !allowAnonOuterThis;
2058                 symEnv = symEnv.outer;
2059             }
2060         }
2061 
2062         // If symbol is a variable, ...
2063         if (sym.kind == VAR) {
2064             VarSymbol v = (VarSymbol)sym;
2065 
2066             // ..., evaluate its initializer, if it has one, and check for
2067             // illegal forward reference.
2068             checkInit(tree, env, v, false);
2069 
2070             // If symbol is a local variable accessed from an embedded
2071             // inner class check that it is final.
2072             if (v.owner.kind == MTH &&
2073                 v.owner != env.info.scope.owner &&
2074                 (v.flags_field & FINAL) == 0) {
2075                 log.error(tree.pos(),
2076                           "local.var.accessed.from.icls.needs.final",
2077                           v);
2078             }
2079 
2080             // If we are expecting a variable (as opposed to a value), check
2081             // that the variable is assignable in the current environment.
2082             if (pkind == VAR)
2083                 checkAssignable(tree.pos(), v, null, env);
2084         }
2085 
2086         // In a constructor body,
2087         // if symbol is a field or instance method, check that it is
2088         // not accessed before the supertype constructor is called.
2089         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
2090             (sym.kind & (VAR | MTH)) != 0 &&
2091             sym.owner.kind == TYP &&
2092             (sym.flags() & STATIC) == 0) {
2093             chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env));
2094         }
2095         Env<AttrContext> env1 = env;
2096         if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) {
2097             // If the found symbol is inaccessible, then it is
2098             // accessed through an enclosing instance.  Locate this
2099             // enclosing instance:
2100             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
2101                 env1 = env1.outer;
2102         }
2103         result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, varArgs);
2104     }
2105 
2106     public void visitSelect(JCFieldAccess tree) {
2107         // Determine the expected kind of the qualifier expression.
2108         int skind = 0;
2109         if (tree.name == names._this || tree.name == names._super ||
2110             tree.name == names._class)
2111         {
2112             skind = TYP;
2113         } else {
2114             if ((pkind & PCK) != 0) skind = skind | PCK;
2115             if ((pkind & TYP) != 0) skind = skind | TYP | PCK;
2116             if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP;
2117         }
2118 
2119         // Attribute the qualifier expression, and determine its symbol (if any).
2120         Type site = attribTree(tree.selected, env, skind, Infer.anyPoly);
2121         if ((pkind & (PCK | TYP)) == 0)
2122             site = capture(site); // Capture field access
2123 
2124         // don't allow T.class T[].class, etc
2125         if (skind == TYP) {
2126             Type elt = site;
2127             while (elt.tag == ARRAY)
2128                 elt = ((ArrayType)elt).elemtype;
2129             if (elt.tag == TYPEVAR) {
2130                 log.error(tree.pos(), "type.var.cant.be.deref");
2131                 result = types.createErrorType(tree.type);
2132                 return;
2133             }
2134         }
2135 
2136         // If qualifier symbol is a type or `super', assert `selectSuper'
2137         // for the selection. This is relevant for determining whether
2138         // protected symbols are accessible.
2139         Symbol sitesym = TreeInfo.symbol(tree.selected);
2140         boolean selectSuperPrev = env.info.selectSuper;
2141         env.info.selectSuper =
2142             sitesym != null &&
2143             sitesym.name == names._super;
2144 
2145         // If selected expression is polymorphic, strip
2146         // type parameters and remember in env.info.tvars, so that
2147         // they can be added later (in Attr.checkId and Infer.instantiateMethod).
2148         if (tree.selected.type.tag == FORALL) {
2149             ForAll pstype = (ForAll)tree.selected.type;
2150             env.info.tvars = pstype.tvars;
2151             site = tree.selected.type = pstype.qtype;
2152         }
2153 
2154         // Determine the symbol represented by the selection.
2155         env.info.varArgs = false;
2156         Symbol sym = selectSym(tree, site, env, pt, pkind);
2157         if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) {
2158             site = capture(site);
2159             sym = selectSym(tree, site, env, pt, pkind);
2160         }
2161         boolean varArgs = env.info.varArgs;
2162         tree.sym = sym;
2163 
2164         if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) {
2165             while (site.tag == TYPEVAR) site = site.getUpperBound();
2166             site = capture(site);
2167         }
2168 
2169         // If that symbol is a variable, ...
2170         if (sym.kind == VAR) {
2171             VarSymbol v = (VarSymbol)sym;
2172 
2173             // ..., evaluate its initializer, if it has one, and check for
2174             // illegal forward reference.
2175             checkInit(tree, env, v, true);
2176 
2177             // If we are expecting a variable (as opposed to a value), check
2178             // that the variable is assignable in the current environment.
2179             if (pkind == VAR)
2180                 checkAssignable(tree.pos(), v, tree.selected, env);
2181         }
2182 
2183         if (sitesym != null &&
2184                 sitesym.kind == VAR &&
2185                 ((VarSymbol)sitesym).isResourceVariable() &&
2186                 sym.kind == MTH &&
2187                 sym.name == names.close &&
2188                 env.info.lint.isEnabled(Lint.LintCategory.ARM)) {
2189             log.warning(tree, "arm.explicit.close.call");
2190         }
2191 
2192         // Disallow selecting a type from an expression
2193         if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) {
2194             tree.type = check(tree.selected, pt,
2195                               sitesym == null ? VAL : sitesym.kind, TYP|PCK, pt);
2196         }
2197 
2198         if (isType(sitesym)) {
2199             if (sym.name == names._this) {
2200                 // If `C' is the currently compiled class, check that
2201                 // C.this' does not appear in a call to a super(...)
2202                 if (env.info.isSelfCall &&
2203                     site.tsym == env.enclClass.sym) {
2204                     chk.earlyRefError(tree.pos(), sym);
2205                 }
2206             } else {
2207                 // Check if type-qualified fields or methods are static (JLS)
2208                 if ((sym.flags() & STATIC) == 0 &&
2209                     sym.name != names._super &&
2210                     (sym.kind == VAR || sym.kind == MTH)) {
2211                     rs.access(rs.new StaticError(sym),
2212                               tree.pos(), site, sym.name, true);
2213                 }
2214             }
2215         } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) {
2216             // If the qualified item is not a type and the selected item is static, report
2217             // a warning. Make allowance for the class of an array type e.g. Object[].class)
2218             chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner);
2219         }
2220 
2221         // If we are selecting an instance member via a `super', ...
2222         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
2223 
2224             // Check that super-qualified symbols are not abstract (JLS)
2225             rs.checkNonAbstract(tree.pos(), sym);
2226 
2227             if (site.isRaw()) {
2228                 // Determine argument types for site.
2229                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
2230                 if (site1 != null) site = site1;
2231             }
2232         }
2233 
2234         env.info.selectSuper = selectSuperPrev;
2235         result = checkId(tree, site, sym, env, pkind, pt, varArgs);
2236         env.info.tvars = List.nil();
2237     }
2238     //where
2239         /** Determine symbol referenced by a Select expression,
2240          *
2241          *  @param tree   The select tree.
2242          *  @param site   The type of the selected expression,
2243          *  @param env    The current environment.
2244          *  @param pt     The current prototype.
2245          *  @param pkind  The expected kind(s) of the Select expression.
2246          */
2247         private Symbol selectSym(JCFieldAccess tree,
2248                                  Type site,
2249                                  Env<AttrContext> env,
2250                                  Type pt,
2251                                  int pkind) {
2252             DiagnosticPosition pos = tree.pos();
2253             Name name = tree.name;
2254 
2255             switch (site.tag) {
2256             case PACKAGE:
2257                 return rs.access(
2258                     rs.findIdentInPackage(env, site.tsym, name, pkind),
2259                     pos, site, name, true);
2260             case ARRAY:
2261             case CLASS:
2262                 if (pt.tag == METHOD || pt.tag == FORALL) {
2263                     return rs.resolveQualifiedMethod(
2264                         pos, env, site, name, pt.getParameterTypes(), pt.getTypeArguments());
2265                 } else if (name == names._this || name == names._super) {
2266                     return rs.resolveSelf(pos, env, site.tsym, name);
2267                 } else if (name == names._class) {
2268                     // In this case, we have already made sure in
2269                     // visitSelect that qualifier expression is a type.
2270                     Type t = syms.classType;
2271                     List<Type> typeargs = allowGenerics
2272                         ? List.of(types.erasure(site))
2273                         : List.<Type>nil();
2274                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
2275                     return new VarSymbol(
2276                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
2277                 } else {
2278                     // We are seeing a plain identifier as selector.
2279                     Symbol sym = rs.findIdentInType(env, site, name, pkind);
2280                     if ((pkind & ERRONEOUS) == 0)
2281                         sym = rs.access(sym, pos, site, name, true);
2282                     return sym;
2283                 }
2284             case WILDCARD:
2285                 throw new AssertionError(tree);
2286             case TYPEVAR:
2287                 // Normally, site.getUpperBound() shouldn't be null.
2288                 // It should only happen during memberEnter/attribBase
2289                 // when determining the super type which *must* be
2290                 // done before attributing the type variables.  In
2291                 // other words, we are seeing this illegal program:
2292                 // class B<T> extends A<T.foo> {}
2293                 Symbol sym = (site.getUpperBound() != null)
2294                     ? selectSym(tree, capture(site.getUpperBound()), env, pt, pkind)
2295                     : null;
2296                 if (sym == null) {
2297                     log.error(pos, "type.var.cant.be.deref");
2298                     return syms.errSymbol;
2299                 } else {
2300                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
2301                         rs.new AccessError(env, site, sym) :
2302                                 sym;
2303                     rs.access(sym2, pos, site, name, true);
2304                     return sym;
2305                 }
2306             case ERROR:
2307                 // preserve identifier names through errors
2308                 return types.createErrorType(name, site.tsym, site).tsym;
2309             default:
2310                 // The qualifier expression is of a primitive type -- only
2311                 // .class is allowed for these.
2312                 if (name == names._class) {
2313                     // In this case, we have already made sure in Select that
2314                     // qualifier expression is a type.
2315                     Type t = syms.classType;
2316                     Type arg = types.boxedClass(site).type;
2317                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
2318                     return new VarSymbol(
2319                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
2320                 } else {
2321                     log.error(pos, "cant.deref", site);
2322                     return syms.errSymbol;
2323                 }
2324             }
2325         }
2326 
2327         /** Determine type of identifier or select expression and check that
2328          *  (1) the referenced symbol is not deprecated
2329          *  (2) the symbol's type is safe (@see checkSafe)
2330          *  (3) if symbol is a variable, check that its type and kind are
2331          *      compatible with the prototype and protokind.
2332          *  (4) if symbol is an instance field of a raw type,
2333          *      which is being assigned to, issue an unchecked warning if its
2334          *      type changes under erasure.
2335          *  (5) if symbol is an instance method of a raw type, issue an
2336          *      unchecked warning if its argument types change under erasure.
2337          *  If checks succeed:
2338          *    If symbol is a constant, return its constant type
2339          *    else if symbol is a method, return its result type
2340          *    otherwise return its type.
2341          *  Otherwise return errType.
2342          *
2343          *  @param tree       The syntax tree representing the identifier
2344          *  @param site       If this is a select, the type of the selected
2345          *                    expression, otherwise the type of the current class.
2346          *  @param sym        The symbol representing the identifier.
2347          *  @param env        The current environment.
2348          *  @param pkind      The set of expected kinds.
2349          *  @param pt         The expected type.
2350          */
2351         Type checkId(JCTree tree,
2352                      Type site,
2353                      Symbol sym,
2354                      Env<AttrContext> env,
2355                      int pkind,
2356                      Type pt,
2357                      boolean useVarargs) {
2358             if (pt.isErroneous()) return types.createErrorType(site);
2359             Type owntype; // The computed type of this identifier occurrence.
2360             switch (sym.kind) {
2361             case TYP:
2362                 // For types, the computed type equals the symbol's type,
2363                 // except for two situations:
2364                 owntype = sym.type;
2365                 if (owntype.tag == CLASS) {
2366                     Type ownOuter = owntype.getEnclosingType();
2367 
2368                     // (a) If the symbol's type is parameterized, erase it
2369                     // because no type parameters were given.
2370                     // We recover generic outer type later in visitTypeApply.
2371                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
2372                         owntype = types.erasure(owntype);
2373                     }
2374 
2375                     // (b) If the symbol's type is an inner class, then
2376                     // we have to interpret its outer type as a superclass
2377                     // of the site type. Example:
2378                     //
2379                     // class Tree<A> { class Visitor { ... } }
2380                     // class PointTree extends Tree<Point> { ... }
2381                     // ...PointTree.Visitor...
2382                     //
2383                     // Then the type of the last expression above is
2384                     // Tree<Point>.Visitor.
2385                     else if (ownOuter.tag == CLASS && site != ownOuter) {
2386                         Type normOuter = site;
2387                         if (normOuter.tag == CLASS)
2388                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
2389                         if (normOuter == null) // perhaps from an import
2390                             normOuter = types.erasure(ownOuter);
2391                         if (normOuter != ownOuter)
2392                             owntype = new ClassType(
2393                                 normOuter, List.<Type>nil(), owntype.tsym);
2394                     }
2395                 }
2396                 break;
2397             case VAR:
2398                 VarSymbol v = (VarSymbol)sym;
2399                 // Test (4): if symbol is an instance field of a raw type,
2400                 // which is being assigned to, issue an unchecked warning if
2401                 // its type changes under erasure.
2402                 if (allowGenerics &&
2403                     pkind == VAR &&
2404                     v.owner.kind == TYP &&
2405                     (v.flags() & STATIC) == 0 &&
2406                     (site.tag == CLASS || site.tag == TYPEVAR)) {
2407                     Type s = types.asOuterSuper(site, v.owner);
2408                     if (s != null &&
2409                         s.isRaw() &&
2410                         !types.isSameType(v.type, v.erasure(types))) {
2411                         chk.warnUnchecked(tree.pos(),
2412                                           "unchecked.assign.to.var",
2413                                           v, s);
2414                     }
2415                 }
2416                 // The computed type of a variable is the type of the
2417                 // variable symbol, taken as a member of the site type.
2418                 owntype = (sym.owner.kind == TYP &&
2419                            sym.name != names._this && sym.name != names._super)
2420                     ? types.memberType(site, sym)
2421                     : sym.type;
2422 
2423                 if (env.info.tvars.nonEmpty()) {
2424                     Type owntype1 = new ForAll(env.info.tvars, owntype);
2425                     for (List<Type> l = env.info.tvars; l.nonEmpty(); l = l.tail)
2426                         if (!owntype.contains(l.head)) {
2427                             log.error(tree.pos(), "undetermined.type", owntype1);
2428                             owntype1 = types.createErrorType(owntype1);
2429                         }
2430                     owntype = owntype1;
2431                 }
2432 
2433                 // If the variable is a constant, record constant value in
2434                 // computed type.
2435                 if (v.getConstValue() != null && isStaticReference(tree))
2436                     owntype = owntype.constType(v.getConstValue());
2437 
2438                 if (pkind == VAL) {
2439                     owntype = capture(owntype); // capture "names as expressions"
2440                 }
2441                 break;
2442             case MTH: {
2443                 JCMethodInvocation app = (JCMethodInvocation)env.tree;
2444                 owntype = checkMethod(site, sym, env, app.args,
2445                                       pt.getParameterTypes(), pt.getTypeArguments(),
2446                                       env.info.varArgs);
2447                 break;
2448             }
2449             case PCK: case ERR:
2450                 owntype = sym.type;
2451                 break;
2452             default:
2453                 throw new AssertionError("unexpected kind: " + sym.kind +
2454                                          " in tree " + tree);
2455             }
2456 
2457             // Test (1): emit a `deprecation' warning if symbol is deprecated.
2458             // (for constructors, the error was given when the constructor was
2459             // resolved)
2460             if (sym.name != names.init &&
2461                 (sym.flags() & DEPRECATED) != 0 &&
2462                 (env.info.scope.owner.flags() & DEPRECATED) == 0 &&
2463                 sym.outermostClass() != env.info.scope.owner.outermostClass())
2464                 chk.warnDeprecated(tree.pos(), sym);
2465 
2466             if ((sym.flags() & PROPRIETARY) != 0) {
2467                 if (enableSunApiLintControl)
2468                   chk.warnSunApi(tree.pos(), "sun.proprietary", sym);
2469                 else
2470                   log.strictWarning(tree.pos(), "sun.proprietary", sym);
2471             }
2472 
2473             // Test (3): if symbol is a variable, check that its type and
2474             // kind are compatible with the prototype and protokind.
2475             return check(tree, owntype, sym.kind, pkind, pt);
2476         }
2477 
2478         /** Check that variable is initialized and evaluate the variable's
2479          *  initializer, if not yet done. Also check that variable is not
2480          *  referenced before it is defined.
2481          *  @param tree    The tree making up the variable reference.
2482          *  @param env     The current environment.
2483          *  @param v       The variable's symbol.
2484          */
2485         private void checkInit(JCTree tree,
2486                                Env<AttrContext> env,
2487                                VarSymbol v,
2488                                boolean onlyWarning) {
2489 //          System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " +
2490 //                             tree.pos + " " + v.pos + " " +
2491 //                             Resolve.isStatic(env));//DEBUG
2492 
2493             // A forward reference is diagnosed if the declaration position
2494             // of the variable is greater than the current tree position
2495             // and the tree and variable definition occur in the same class
2496             // definition.  Note that writes don't count as references.
2497             // This check applies only to class and instance
2498             // variables.  Local variables follow different scope rules,
2499             // and are subject to definite assignment checking.
2500             if ((env.info.enclVar == v || v.pos > tree.pos) &&
2501                 v.owner.kind == TYP &&
2502                 canOwnInitializer(env.info.scope.owner) &&
2503                 v.owner == env.info.scope.owner.enclClass() &&
2504                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
2505                 (env.tree.getTag() != JCTree.ASSIGN ||
2506                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
2507                 String suffix = (env.info.enclVar == v) ?
2508                                 "self.ref" : "forward.ref";
2509                 if (!onlyWarning || isStaticEnumField(v)) {
2510                     log.error(tree.pos(), "illegal." + suffix);
2511                 } else if (useBeforeDeclarationWarning) {
2512                     log.warning(tree.pos(), suffix, v);
2513                 }
2514             }
2515 
2516             v.getConstValue(); // ensure initializer is evaluated
2517 
2518             checkEnumInitializer(tree, env, v);
2519         }
2520 
2521         /**
2522          * Check for illegal references to static members of enum.  In
2523          * an enum type, constructors and initializers may not
2524          * reference its static members unless they are constant.
2525          *
2526          * @param tree    The tree making up the variable reference.
2527          * @param env     The current environment.
2528          * @param v       The variable's symbol.
2529          * @see JLS 3rd Ed. (8.9 Enums)
2530          */
2531         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
2532             // JLS 3rd Ed.:
2533             //
2534             // "It is a compile-time error to reference a static field
2535             // of an enum type that is not a compile-time constant
2536             // (15.28) from constructors, instance initializer blocks,
2537             // or instance variable initializer expressions of that
2538             // type. It is a compile-time error for the constructors,
2539             // instance initializer blocks, or instance variable
2540             // initializer expressions of an enum constant e to refer
2541             // to itself or to an enum constant of the same type that
2542             // is declared to the right of e."
2543             if (isStaticEnumField(v)) {
2544                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
2545 
2546                 if (enclClass == null || enclClass.owner == null)
2547                     return;
2548 
2549                 // See if the enclosing class is the enum (or a
2550                 // subclass thereof) declaring v.  If not, this
2551                 // reference is OK.
2552                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
2553                     return;
2554 
2555                 // If the reference isn't from an initializer, then
2556                 // the reference is OK.
2557                 if (!Resolve.isInitializer(env))
2558                     return;
2559 
2560                 log.error(tree.pos(), "illegal.enum.static.ref");
2561             }
2562         }
2563 
2564         /** Is the given symbol a static, non-constant field of an Enum?
2565          *  Note: enum literals should not be regarded as such
2566          */
2567         private boolean isStaticEnumField(VarSymbol v) {
2568             return Flags.isEnum(v.owner) &&
2569                    Flags.isStatic(v) &&
2570                    !Flags.isConstant(v) &&
2571                    v.name != names._class;
2572         }
2573 
2574         /** Can the given symbol be the owner of code which forms part
2575          *  if class initialization? This is the case if the symbol is
2576          *  a type or field, or if the symbol is the synthetic method.
2577          *  owning a block.
2578          */
2579         private boolean canOwnInitializer(Symbol sym) {
2580             return
2581                 (sym.kind & (VAR | TYP)) != 0 ||
2582                 (sym.kind == MTH && (sym.flags() & BLOCK) != 0);
2583         }
2584 
2585     Warner noteWarner = new Warner();
2586 
2587     /**
2588      * Check that method arguments conform to its instantation.
2589      **/
2590     public Type checkMethod(Type site,
2591                             Symbol sym,
2592                             Env<AttrContext> env,
2593                             final List<JCExpression> argtrees,
2594                             List<Type> argtypes,
2595                             List<Type> typeargtypes,
2596                             boolean useVarargs) {
2597         // Test (5): if symbol is an instance method of a raw type, issue
2598         // an unchecked warning if its argument types change under erasure.
2599         if (allowGenerics &&
2600             (sym.flags() & STATIC) == 0 &&
2601             (site.tag == CLASS || site.tag == TYPEVAR)) {
2602             Type s = types.asOuterSuper(site, sym.owner);
2603             if (s != null && s.isRaw() &&
2604                 !types.isSameTypes(sym.type.getParameterTypes(),
2605                                    sym.erasure(types).getParameterTypes())) {
2606                 chk.warnUnchecked(env.tree.pos(),
2607                                   "unchecked.call.mbr.of.raw.type",
2608                                   sym, s);
2609             }
2610         }
2611 
2612         // Compute the identifier's instantiated type.
2613         // For methods, we need to compute the instance type by
2614         // Resolve.instantiate from the symbol's type as well as
2615         // any type arguments and value arguments.
2616         noteWarner.warned = false;
2617         Type owntype = rs.instantiate(env,
2618                                       site,
2619                                       sym,
2620                                       argtypes,
2621                                       typeargtypes,
2622                                       true,
2623                                       useVarargs,
2624                                       noteWarner);
2625         boolean warned = noteWarner.warned;
2626 
2627         // If this fails, something went wrong; we should not have
2628         // found the identifier in the first place.
2629         if (owntype == null) {
2630             if (!pt.isErroneous())
2631                 log.error(env.tree.pos(),
2632                           "internal.error.cant.instantiate",
2633                           sym, site,
2634                           Type.toString(pt.getParameterTypes()));
2635             owntype = types.createErrorType(site);
2636         } else {
2637             // System.out.println("call   : " + env.tree);
2638             // System.out.println("method : " + owntype);
2639             // System.out.println("actuals: " + argtypes);
2640             List<Type> formals = owntype.getParameterTypes();
2641             Type last = useVarargs ? formals.last() : null;
2642             if (sym.name==names.init &&
2643                 sym.owner == syms.enumSym)
2644                 formals = formals.tail.tail;
2645             List<JCExpression> args = argtrees;
2646             while (formals.head != last) {
2647                 JCTree arg = args.head;
2648                 Warner warn = chk.convertWarner(arg.pos(), arg.type, formals.head);
2649                 assertConvertible(arg, arg.type, formals.head, warn);
2650                 warned |= warn.warned;
2651                 args = args.tail;
2652                 formals = formals.tail;
2653             }
2654             if (useVarargs) {
2655                 Type varArg = types.elemtype(last);
2656                 while (args.tail != null) {
2657                     JCTree arg = args.head;
2658                     Warner warn = chk.convertWarner(arg.pos(), arg.type, varArg);
2659                     assertConvertible(arg, arg.type, varArg, warn);
2660                     warned |= warn.warned;
2661                     args = args.tail;
2662                 }
2663             } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
2664                 // non-varargs call to varargs method
2665                 Type varParam = owntype.getParameterTypes().last();
2666                 Type lastArg = argtypes.last();
2667                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
2668                     !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
2669                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
2670                                 types.elemtype(varParam),
2671                                 varParam);
2672             }
2673 
2674             if (warned && sym.type.tag == FORALL) {
2675                 chk.warnUnchecked(env.tree.pos(),
2676                                   "unchecked.meth.invocation.applied",
2677                                   kindName(sym),
2678                                   sym.name,
2679                                   rs.methodArguments(sym.type.getParameterTypes()),
2680                                   rs.methodArguments(argtypes),
2681                                   kindName(sym.location()),
2682                                   sym.location());
2683                 owntype = new MethodType(owntype.getParameterTypes(),
2684                                          types.erasure(owntype.getReturnType()),
2685                                          owntype.getThrownTypes(),
2686                                          syms.methodClass);
2687             }
2688             if (useVarargs) {
2689                 JCTree tree = env.tree;
2690                 Type argtype = owntype.getParameterTypes().last();
2691                 if (owntype.getReturnType().tag != FORALL || warned) {
2692                     chk.checkVararg(env.tree.pos(), owntype.getParameterTypes(), sym, env);
2693                 }
2694                 Type elemtype = types.elemtype(argtype);
2695                 switch (tree.getTag()) {
2696                 case JCTree.APPLY:
2697                     ((JCMethodInvocation) tree).varargsElement = elemtype;
2698                     break;
2699                 case JCTree.NEWCLASS:
2700                     ((JCNewClass) tree).varargsElement = elemtype;
2701                     break;
2702                 default:
2703                     throw new AssertionError(""+tree);
2704                 }
2705             }
2706         }
2707         return owntype;
2708     }
2709 
2710     private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
2711         if (types.isConvertible(actual, formal, warn))
2712             return;
2713 
2714         if (formal.isCompound()
2715             && types.isSubtype(actual, types.supertype(formal))
2716             && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
2717             return;
2718 
2719         if (false) {
2720             // TODO: make assertConvertible work
2721             chk.typeError(tree.pos(), diags.fragment("incompatible.types"), actual, formal);
2722             throw new AssertionError("Tree: " + tree
2723                                      + " actual:" + actual
2724                                      + " formal: " + formal);
2725         }
2726     }
2727 
2728     public void visitLiteral(JCLiteral tree) {
2729         result = check(
2730             tree, litType(tree.typetag).constType(tree.value), VAL, pkind, pt);
2731     }
2732     //where
2733     /** Return the type of a literal with given type tag.
2734      */
2735     Type litType(int tag) {
2736         return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag];
2737     }
2738 
2739     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
2740         result = check(tree, syms.typeOfTag[tree.typetag], TYP, pkind, pt);
2741     }
2742 
2743     public void visitTypeArray(JCArrayTypeTree tree) {
2744         Type etype = attribType(tree.elemtype, env);
2745         Type type = new ArrayType(etype, syms.arrayClass);
2746         result = check(tree, type, TYP, pkind, pt);
2747     }
2748 
2749     /** Visitor method for parameterized types.
2750      *  Bound checking is left until later, since types are attributed
2751      *  before supertype structure is completely known
2752      */
2753     public void visitTypeApply(JCTypeApply tree) {
2754         Type owntype = types.createErrorType(tree.type);
2755 
2756         // Attribute functor part of application and make sure it's a class.
2757         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
2758 
2759         // Attribute type parameters
2760         List<Type> actuals = attribTypes(tree.arguments, env);
2761 
2762         if (clazztype.tag == CLASS) {
2763             List<Type> formals = clazztype.tsym.type.getTypeArguments();
2764 
2765             if (actuals.length() == formals.length() || actuals.length() == 0) {
2766                 List<Type> a = actuals;
2767                 List<Type> f = formals;
2768                 while (a.nonEmpty()) {
2769                     a.head = a.head.withTypeVar(f.head);
2770                     a = a.tail;
2771                     f = f.tail;
2772                 }
2773                 // Compute the proper generic outer
2774                 Type clazzOuter = clazztype.getEnclosingType();
2775                 if (clazzOuter.tag == CLASS) {
2776                     Type site;
2777                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
2778                     if (clazz.getTag() == JCTree.IDENT) {
2779                         site = env.enclClass.sym.type;
2780                     } else if (clazz.getTag() == JCTree.SELECT) {
2781                         site = ((JCFieldAccess) clazz).selected.type;
2782                     } else throw new AssertionError(""+tree);
2783                     if (clazzOuter.tag == CLASS && site != clazzOuter) {
2784                         if (site.tag == CLASS)
2785                             site = types.asOuterSuper(site, clazzOuter.tsym);
2786                         if (site == null)
2787                             site = types.erasure(clazzOuter);
2788                         clazzOuter = site;
2789                     }
2790                 }
2791                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym);
2792             } else {
2793                 if (formals.length() != 0) {
2794                     log.error(tree.pos(), "wrong.number.type.args",
2795                               Integer.toString(formals.length()));
2796                 } else {
2797                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
2798                 }
2799                 owntype = types.createErrorType(tree.type);
2800             }
2801         }
2802         result = check(tree, owntype, TYP, pkind, pt);
2803     }
2804 
2805     public void visitTypeDisjoint(JCTypeDisjoint tree) {
2806         List<Type> componentTypes = attribTypes(tree.components, env);
2807         tree.type = result = check(tree, types.lub(componentTypes), TYP, pkind, pt);
2808     }
2809 
2810     public void visitTypeParameter(JCTypeParameter tree) {
2811         TypeVar a = (TypeVar)tree.type;
2812         Set<Type> boundSet = new HashSet<Type>();
2813         if (a.bound.isErroneous())
2814             return;
2815         List<Type> bs = types.getBounds(a);
2816         if (tree.bounds.nonEmpty()) {
2817             // accept class or interface or typevar as first bound.
2818             Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false);
2819             boundSet.add(types.erasure(b));
2820             if (b.isErroneous()) {
2821                 a.bound = b;
2822             }
2823             else if (b.tag == TYPEVAR) {
2824                 // if first bound was a typevar, do not accept further bounds.
2825                 if (tree.bounds.tail.nonEmpty()) {
2826                     log.error(tree.bounds.tail.head.pos(),
2827                               "type.var.may.not.be.followed.by.other.bounds");
2828                     log.unrecoverableError = true;
2829                     tree.bounds = List.of(tree.bounds.head);
2830                     a.bound = bs.head;
2831                 }
2832             } else {
2833                 // if first bound was a class or interface, accept only interfaces
2834                 // as further bounds.
2835                 for (JCExpression bound : tree.bounds.tail) {
2836                     bs = bs.tail;
2837                     Type i = checkBase(bs.head, bound, env, false, true, false);
2838                     if (i.isErroneous())
2839                         a.bound = i;
2840                     else if (i.tag == CLASS)
2841                         chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet);
2842                 }
2843             }
2844         }
2845         bs = types.getBounds(a);
2846 
2847         // in case of multiple bounds ...
2848         if (bs.length() > 1) {
2849             // ... the variable's bound is a class type flagged COMPOUND
2850             // (see comment for TypeVar.bound).
2851             // In this case, generate a class tree that represents the
2852             // bound class, ...
2853             JCTree extending;
2854             List<JCExpression> implementing;
2855             if ((bs.head.tsym.flags() & INTERFACE) == 0) {
2856                 extending = tree.bounds.head;
2857                 implementing = tree.bounds.tail;
2858             } else {
2859                 extending = null;
2860                 implementing = tree.bounds;
2861             }
2862             JCClassDecl cd = make.at(tree.pos).ClassDef(
2863                 make.Modifiers(PUBLIC | ABSTRACT),
2864                 tree.name, List.<JCTypeParameter>nil(),
2865                 extending, implementing, List.<JCTree>nil());
2866 
2867             ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym;
2868             assert (c.flags() & COMPOUND) != 0;
2869             cd.sym = c;
2870             c.sourcefile = env.toplevel.sourcefile;
2871 
2872             // ... and attribute the bound class
2873             c.flags_field |= UNATTRIBUTED;
2874             Env<AttrContext> cenv = enter.classEnv(cd, env);
2875             enter.typeEnvs.put(c, cenv);
2876         }
2877     }
2878 
2879 
2880     public void visitWildcard(JCWildcard tree) {
2881         //- System.err.println("visitWildcard("+tree+");");//DEBUG
2882         Type type = (tree.kind.kind == BoundKind.UNBOUND)
2883             ? syms.objectType
2884             : attribType(tree.inner, env);
2885         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
2886                                               tree.kind.kind,
2887                                               syms.boundClass),
2888                        TYP, pkind, pt);
2889     }
2890 
2891     public void visitAnnotation(JCAnnotation tree) {
2892         log.error(tree.pos(), "annotation.not.valid.for.type", pt);
2893         result = tree.type = syms.errType;
2894     }
2895 
2896     public void visitAnnotatedType(JCAnnotatedType tree) {
2897         result = tree.type = attribType(tree.getUnderlyingType(), env);
2898     }
2899 
2900     public void visitErroneous(JCErroneous tree) {
2901         if (tree.errs != null)
2902             for (JCTree err : tree.errs)
2903                 attribTree(err, env, ERR, pt);
2904         result = tree.type = syms.errType;
2905     }
2906 
2907     /** Default visitor method for all other trees.
2908      */
2909     public void visitTree(JCTree tree) {
2910         throw new AssertionError();
2911     }
2912 
2913     /** Main method: attribute class definition associated with given class symbol.
2914      *  reporting completion failures at the given position.
2915      *  @param pos The source position at which completion errors are to be
2916      *             reported.
2917      *  @param c   The class symbol whose definition will be attributed.
2918      */
2919     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
2920         try {
2921             annotate.flush();
2922             attribClass(c);
2923         } catch (CompletionFailure ex) {
2924             chk.completionError(pos, ex);
2925         }
2926     }
2927 
2928     /** Attribute class definition associated with given class symbol.
2929      *  @param c   The class symbol whose definition will be attributed.
2930      */
2931     void attribClass(ClassSymbol c) throws CompletionFailure {
2932         if (c.type.tag == ERROR) return;
2933 
2934         // Check for cycles in the inheritance graph, which can arise from
2935         // ill-formed class files.
2936         chk.checkNonCyclic(null, c.type);
2937 
2938         Type st = types.supertype(c.type);
2939         if ((c.flags_field & Flags.COMPOUND) == 0) {
2940             // First, attribute superclass.
2941             if (st.tag == CLASS)
2942                 attribClass((ClassSymbol)st.tsym);
2943 
2944             // Next attribute owner, if it is a class.
2945             if (c.owner.kind == TYP && c.owner.type.tag == CLASS)
2946                 attribClass((ClassSymbol)c.owner);
2947         }
2948 
2949         // The previous operations might have attributed the current class
2950         // if there was a cycle. So we test first whether the class is still
2951         // UNATTRIBUTED.
2952         if ((c.flags_field & UNATTRIBUTED) != 0) {
2953             c.flags_field &= ~UNATTRIBUTED;
2954 
2955             // Get environment current at the point of class definition.
2956             Env<AttrContext> env = enter.typeEnvs.get(c);
2957 
2958             // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized,
2959             // because the annotations were not available at the time the env was created. Therefore,
2960             // we look up the environment chain for the first enclosing environment for which the
2961             // lint value is set. Typically, this is the parent env, but might be further if there
2962             // are any envs created as a result of TypeParameter nodes.
2963             Env<AttrContext> lintEnv = env;
2964             while (lintEnv.info.lint == null)
2965                 lintEnv = lintEnv.next;
2966 
2967             // Having found the enclosing lint value, we can initialize the lint value for this class
2968             env.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags());
2969 
2970             Lint prevLint = chk.setLint(env.info.lint);
2971             JavaFileObject prev = log.useSource(c.sourcefile);
2972 
2973             try {
2974                 // java.lang.Enum may not be subclassed by a non-enum
2975                 if (st.tsym == syms.enumSym &&
2976                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
2977                     log.error(env.tree.pos(), "enum.no.subclassing");
2978 
2979                 // Enums may not be extended by source-level classes
2980                 if (st.tsym != null &&
2981                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
2982                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) &&
2983                     !target.compilerBootstrap(c)) {
2984                     log.error(env.tree.pos(), "enum.types.not.extensible");
2985                 }
2986                 attribClassBody(env, c);
2987 
2988                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
2989             } finally {
2990                 log.useSource(prev);
2991                 chk.setLint(prevLint);
2992             }
2993 
2994         }
2995     }
2996 
2997     public void visitImport(JCImport tree) {
2998         // nothing to do
2999     }
3000 
3001     /** Finish the attribution of a class. */
3002     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
3003         JCClassDecl tree = (JCClassDecl)env.tree;
3004         assert c == tree.sym;
3005 
3006         // Validate annotations
3007         chk.validateAnnotations(tree.mods.annotations, c);
3008 
3009         // Validate type parameters, supertype and interfaces.
3010         attribBounds(tree.typarams);
3011         if (!c.isAnonymous()) {
3012             //already checked if anonymous
3013             chk.validate(tree.typarams, env);
3014             chk.validate(tree.extending, env);
3015             chk.validate(tree.implementing, env);
3016         }
3017 
3018         // If this is a non-abstract class, check that it has no abstract
3019         // methods or unimplemented methods of an implemented interface.
3020         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
3021             if (!relax)
3022                 chk.checkAllDefined(tree.pos(), c);
3023         }
3024 
3025         if ((c.flags() & ANNOTATION) != 0) {
3026             if (tree.implementing.nonEmpty())
3027                 log.error(tree.implementing.head.pos(),
3028                           "cant.extend.intf.annotation");
3029             if (tree.typarams.nonEmpty())
3030                 log.error(tree.typarams.head.pos(),
3031                           "intf.annotation.cant.have.type.params");
3032         } else {
3033             // Check that all extended classes and interfaces
3034             // are compatible (i.e. no two define methods with same arguments
3035             // yet different return types).  (JLS 8.4.6.3)
3036             chk.checkCompatibleSupertypes(tree.pos(), c.type);
3037         }
3038 
3039         // Check that class does not import the same parameterized interface
3040         // with two different argument lists.
3041         chk.checkClassBounds(tree.pos(), c.type);
3042 
3043         tree.type = c.type;
3044 
3045         boolean assertsEnabled = false;
3046         assert assertsEnabled = true;
3047         if (assertsEnabled) {
3048             for (List<JCTypeParameter> l = tree.typarams;
3049                  l.nonEmpty(); l = l.tail)
3050                 assert env.info.scope.lookup(l.head.name).scope != null;
3051         }
3052 
3053         // Check that a generic class doesn't extend Throwable
3054         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
3055             log.error(tree.extending.pos(), "generic.throwable");
3056 
3057         // Check that all methods which implement some
3058         // method conform to the method they implement.
3059         chk.checkImplementations(tree);
3060 
3061         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3062             // Attribute declaration
3063             attribStat(l.head, env);
3064             // Check that declarations in inner classes are not static (JLS 8.1.2)
3065             // Make an exception for static constants.
3066             if (c.owner.kind != PCK &&
3067                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
3068                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
3069                 Symbol sym = null;
3070                 if (l.head.getTag() == JCTree.VARDEF) sym = ((JCVariableDecl) l.head).sym;
3071                 if (sym == null ||
3072                     sym.kind != VAR ||
3073                     ((VarSymbol) sym).getConstValue() == null)
3074                     log.error(l.head.pos(), "icls.cant.have.static.decl");
3075             }
3076         }
3077 
3078         // Check for cycles among non-initial constructors.
3079         chk.checkCyclicConstructors(tree);
3080 
3081         // Check for cycles among annotation elements.
3082         chk.checkNonCyclicElements(tree);
3083 
3084         // Check for proper use of serialVersionUID
3085         if (env.info.lint.isEnabled(Lint.LintCategory.SERIAL) &&
3086             isSerializable(c) &&
3087             (c.flags() & Flags.ENUM) == 0 &&
3088             (c.flags() & ABSTRACT) == 0) {
3089             checkSerialVersionUID(tree, c);
3090         }
3091 
3092         // Check type annotations applicability rules
3093         validateTypeAnnotations(tree);
3094     }
3095         // where
3096         /** check if a class is a subtype of Serializable, if that is available. */
3097         private boolean isSerializable(ClassSymbol c) {
3098             try {
3099                 syms.serializableType.complete();
3100             }
3101             catch (CompletionFailure e) {
3102                 return false;
3103             }
3104             return types.isSubtype(c.type, syms.serializableType);
3105         }
3106 
3107         /** Check that an appropriate serialVersionUID member is defined. */
3108         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
3109 
3110             // check for presence of serialVersionUID
3111             Scope.Entry e = c.members().lookup(names.serialVersionUID);
3112             while (e.scope != null && e.sym.kind != VAR) e = e.next();
3113             if (e.scope == null) {
3114                 log.warning(tree.pos(), "missing.SVUID", c);
3115                 return;
3116             }
3117 
3118             // check that it is static final
3119             VarSymbol svuid = (VarSymbol)e.sym;
3120             if ((svuid.flags() & (STATIC | FINAL)) !=
3121                 (STATIC | FINAL))
3122                 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
3123 
3124             // check that it is long
3125             else if (svuid.type.tag != TypeTags.LONG)
3126                 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
3127 
3128             // check constant
3129             else if (svuid.getConstValue() == null)
3130                 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
3131         }
3132 
3133     private Type capture(Type type) {
3134         return types.capture(type);
3135     }
3136 
3137     private void validateTypeAnnotations(JCTree tree) {
3138         tree.accept(typeAnnotationsValidator);
3139     }
3140     //where
3141     private final JCTree.Visitor typeAnnotationsValidator =
3142         new TreeScanner() {
3143         public void visitAnnotation(JCAnnotation tree) {
3144             if (tree instanceof JCTypeAnnotation) {
3145                 chk.validateTypeAnnotation((JCTypeAnnotation)tree, false);
3146             }
3147             super.visitAnnotation(tree);
3148         }
3149         public void visitTypeParameter(JCTypeParameter tree) {
3150             chk.validateTypeAnnotations(tree.annotations, true);
3151             // don't call super. skip type annotations
3152             scan(tree.bounds);
3153         }
3154         public void visitMethodDef(JCMethodDecl tree) {
3155             // need to check static methods
3156             if ((tree.sym.flags() & Flags.STATIC) != 0) {
3157                 for (JCTypeAnnotation a : tree.receiverAnnotations) {
3158                     if (chk.isTypeAnnotation(a, false))
3159                         log.error(a.pos(), "annotation.type.not.applicable");
3160                 }
3161             }
3162             super.visitMethodDef(tree);
3163         }
3164     };
3165 }