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         enableSunApiLintControl = options.get("enableSunApiLintControl") != null;
 126     }
 127 
 128     /** Switch: relax some constraints for retrofit mode.
 129      */
 130     boolean relax;
 131 
 132     /** Switch: support generics?
 133      */
 134     boolean allowGenerics;
 135 
 136     /** Switch: allow variable-arity methods.
 137      */
 138     boolean allowVarargs;
 139 
 140     /** Switch: support enums?
 141      */
 142     boolean allowEnums;
 143 
 144     /** Switch: support boxing and unboxing?
 145      */
 146     boolean allowBoxing;
 147 
 148     /** Switch: support covariant result types?
 149      */
 150     boolean allowCovariantReturns;
 151 
 152     /** Switch: allow references to surrounding object from anonymous
 153      * objects during constructor call?
 154      */
 155     boolean allowAnonOuterThis;
 156 
 157     /**
 158      * Switch: warn about use of variable before declaration?
 159      * RFE: 6425594
 160      */
 161     boolean useBeforeDeclarationWarning;
 162 
 163     /**
 164      * Switch: allow lint infrastructure to control proprietary
 165      * API warnings.
 166      */
 167     boolean enableSunApiLintControl;
 168 
 169     /**
 170      * Switch: allow strings in switch?
 171      */
 172     boolean allowStringsInSwitch;
 173 
 174     /**
 175      * Switch: name of source level; used for error reporting.
 176      */
 177     String sourceName;
 178 
 179     /** Check kind and type of given tree against protokind and prototype.
 180      *  If check succeeds, store type in tree and return it.
 181      *  If check fails, store errType in tree and return it.
 182      *  No checks are performed if the prototype is a method type.
 183      *  It is not necessary in this case since we know that kind and type
 184      *  are correct.
 185      *
 186      *  @param tree     The tree whose kind and type is checked
 187      *  @param owntype  The computed type of the tree
 188      *  @param ownkind  The computed kind of the tree
 189      *  @param pkind    The expected kind (or: protokind) of the tree
 190      *  @param pt       The expected type (or: prototype) of the tree
 191      */
 192     Type check(JCTree tree, Type owntype, int ownkind, int pkind, Type pt) {
 193         if (owntype.tag != ERROR && pt.tag != METHOD && pt.tag != FORALL) {
 194             if ((ownkind & ~pkind) == 0) {
 195                 owntype = chk.checkType(tree.pos(), owntype, pt, errKey);
 196             } else {
 197                 log.error(tree.pos(), "unexpected.type",
 198                           kindNames(pkind),
 199                           kindName(ownkind));
 200                 owntype = types.createErrorType(owntype);
 201             }
 202         }
 203         tree.type = owntype;
 204         return owntype;
 205     }
 206 
 207     /** Is given blank final variable assignable, i.e. in a scope where it
 208      *  may be assigned to even though it is final?
 209      *  @param v      The blank final variable.
 210      *  @param env    The current environment.
 211      */
 212     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
 213         Symbol owner = env.info.scope.owner;
 214            // owner refers to the innermost variable, method or
 215            // initializer block declaration at this point.
 216         return
 217             v.owner == owner
 218             ||
 219             ((owner.name == names.init ||    // i.e. we are in a constructor
 220               owner.kind == VAR ||           // i.e. we are in a variable initializer
 221               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
 222              &&
 223              v.owner == owner.owner
 224              &&
 225              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
 226     }
 227 
 228     /** Check that variable can be assigned to.
 229      *  @param pos    The current source code position.
 230      *  @param v      The assigned varaible
 231      *  @param base   If the variable is referred to in a Select, the part
 232      *                to the left of the `.', null otherwise.
 233      *  @param env    The current environment.
 234      */
 235     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
 236         if ((v.flags() & FINAL) != 0 &&
 237             ((v.flags() & HASINIT) != 0
 238              ||
 239              !((base == null ||
 240                (base.getTag() == JCTree.IDENT && TreeInfo.name(base) == names._this)) &&
 241                isAssignableAsBlankFinal(v, env)))) {
 242             if (v.isResourceVariable()) { //TWR resource
 243                 log.error(pos, "twr.resource.may.not.be.assigned", v);
 244             } else {
 245                 log.error(pos, "cant.assign.val.to.final.var", v);
 246             }
 247         }
 248     }
 249 
 250     /** Does tree represent a static reference to an identifier?
 251      *  It is assumed that tree is either a SELECT or an IDENT.
 252      *  We have to weed out selects from non-type names here.
 253      *  @param tree    The candidate tree.
 254      */
 255     boolean isStaticReference(JCTree tree) {
 256         if (tree.getTag() == JCTree.SELECT) {
 257             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
 258             if (lsym == null || lsym.kind != TYP) {
 259                 return false;
 260             }
 261         }
 262         return true;
 263     }
 264 
 265     /** Is this symbol a type?
 266      */
 267     static boolean isType(Symbol sym) {
 268         return sym != null && sym.kind == TYP;
 269     }
 270 
 271     /** The current `this' symbol.
 272      *  @param env    The current environment.
 273      */
 274     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
 275         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
 276     }
 277 
 278     /** Attribute a parsed identifier.
 279      * @param tree Parsed identifier name
 280      * @param topLevel The toplevel to use
 281      */
 282     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
 283         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
 284         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
 285                                            syms.errSymbol.name,
 286                                            null, null, null, null);
 287         localEnv.enclClass.sym = syms.errSymbol;
 288         return tree.accept(identAttributer, localEnv);
 289     }
 290     // where
 291         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
 292         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
 293             @Override
 294             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
 295                 Symbol site = visit(node.getExpression(), env);
 296                 if (site.kind == ERR)
 297                     return site;
 298                 Name name = (Name)node.getIdentifier();
 299                 if (site.kind == PCK) {
 300                     env.toplevel.packge = (PackageSymbol)site;
 301                     return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK);
 302                 } else {
 303                     env.enclClass.sym = (ClassSymbol)site;
 304                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
 305                 }
 306             }
 307 
 308             @Override
 309             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
 310                 return rs.findIdent(env, (Name)node.getName(), TYP | PCK);
 311             }
 312         }
 313 
 314     public Type coerce(Type etype, Type ttype) {
 315         return cfolder.coerce(etype, ttype);
 316     }
 317 
 318     public Type attribType(JCTree node, TypeSymbol sym) {
 319         Env<AttrContext> env = enter.typeEnvs.get(sym);
 320         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
 321         return attribTree(node, localEnv, Kinds.TYP, Type.noType);
 322     }
 323 
 324     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
 325         breakTree = tree;
 326         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
 327         try {
 328             attribExpr(expr, env);
 329         } catch (BreakAttr b) {
 330             return b.env;
 331         } finally {
 332             breakTree = null;
 333             log.useSource(prev);
 334         }
 335         return env;
 336     }
 337 
 338     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
 339         breakTree = tree;
 340         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
 341         try {
 342             attribStat(stmt, env);
 343         } catch (BreakAttr b) {
 344             return b.env;
 345         } finally {
 346             breakTree = null;
 347             log.useSource(prev);
 348         }
 349         return env;
 350     }
 351 
 352     private JCTree breakTree = null;
 353 
 354     private static class BreakAttr extends RuntimeException {
 355         static final long serialVersionUID = -6924771130405446405L;
 356         private Env<AttrContext> env;
 357         private BreakAttr(Env<AttrContext> env) {
 358             this.env = env;
 359         }
 360     }
 361 
 362 
 363 /* ************************************************************************
 364  * Visitor methods
 365  *************************************************************************/
 366 
 367     /** Visitor argument: the current environment.
 368      */
 369     Env<AttrContext> env;
 370 
 371     /** Visitor argument: the currently expected proto-kind.
 372      */
 373     int pkind;
 374 
 375     /** Visitor argument: the currently expected proto-type.
 376      */
 377     Type pt;
 378 
 379     /** Visitor argument: the error key to be generated when a type error occurs
 380      */
 381     String errKey;
 382 
 383     /** Visitor result: the computed type.
 384      */
 385     Type result;
 386 
 387     /** Visitor method: attribute a tree, catching any completion failure
 388      *  exceptions. Return the tree's type.
 389      *
 390      *  @param tree    The tree to be visited.
 391      *  @param env     The environment visitor argument.
 392      *  @param pkind   The protokind visitor argument.
 393      *  @param pt      The prototype visitor argument.
 394      */
 395     Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt) {
 396         return attribTree(tree, env, pkind, pt, "incompatible.types");
 397     }
 398 
 399     Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt, String errKey) {
 400         Env<AttrContext> prevEnv = this.env;
 401         int prevPkind = this.pkind;
 402         Type prevPt = this.pt;
 403         String prevErrKey = this.errKey;
 404         try {
 405             this.env = env;
 406             this.pkind = pkind;
 407             this.pt = pt;
 408             this.errKey = errKey;
 409             tree.accept(this);
 410             if (tree == breakTree)
 411                 throw new BreakAttr(env);
 412             return result;
 413         } catch (CompletionFailure ex) {
 414             tree.type = syms.errType;
 415             return chk.completionError(tree.pos(), ex);
 416         } finally {
 417             this.env = prevEnv;
 418             this.pkind = prevPkind;
 419             this.pt = prevPt;
 420             this.errKey = prevErrKey;
 421         }
 422     }
 423 
 424     /** Derived visitor method: attribute an expression tree.
 425      */
 426     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
 427         return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType);
 428     }
 429 
 430     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt, String key) {
 431         return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType, key);
 432     }
 433 
 434     /** Derived visitor method: attribute an expression tree with
 435      *  no constraints on the computed type.
 436      */
 437     Type attribExpr(JCTree tree, Env<AttrContext> env) {
 438         return attribTree(tree, env, VAL, Type.noType);
 439     }
 440 
 441     /** Derived visitor method: attribute a type tree.
 442      */
 443     Type attribType(JCTree tree, Env<AttrContext> env) {
 444         Type result = attribType(tree, env, Type.noType);
 445         return result;
 446     }
 447 
 448     /** Derived visitor method: attribute a type tree.
 449      */
 450     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
 451         Type result = attribTree(tree, env, TYP, pt);
 452         return result;
 453     }
 454 
 455     /** Derived visitor method: attribute a statement or definition tree.
 456      */
 457     public Type attribStat(JCTree tree, Env<AttrContext> env) {
 458         return attribTree(tree, env, NIL, Type.noType);
 459     }
 460 
 461     /** Attribute a list of expressions, returning a list of types.
 462      */
 463     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
 464         ListBuffer<Type> ts = new ListBuffer<Type>();
 465         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
 466             ts.append(attribExpr(l.head, env, pt));
 467         return ts.toList();
 468     }
 469 
 470     /** Attribute a list of statements, returning nothing.
 471      */
 472     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
 473         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
 474             attribStat(l.head, env);
 475     }
 476 
 477     /** Attribute the arguments in a method call, returning a list of types.
 478      */
 479     List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) {
 480         ListBuffer<Type> argtypes = new ListBuffer<Type>();
 481         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
 482             argtypes.append(chk.checkNonVoid(
 483                 l.head.pos(), types.upperBound(attribTree(l.head, env, VAL, Infer.anyPoly))));
 484         return argtypes.toList();
 485     }
 486 
 487     /** Attribute a type argument list, returning a list of types.
 488      *  Caller is responsible for calling checkRefTypes.
 489      */
 490     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
 491         ListBuffer<Type> argtypes = new ListBuffer<Type>();
 492         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
 493             argtypes.append(attribType(l.head, env));
 494         return argtypes.toList();
 495     }
 496 
 497     /** Attribute a type argument list, returning a list of types.
 498      *  Check that all the types are references.
 499      */
 500     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
 501         List<Type> types = attribAnyTypes(trees, env);
 502         return chk.checkRefTypes(trees, types);
 503     }
 504 
 505     /**
 506      * Attribute type variables (of generic classes or methods).
 507      * Compound types are attributed later in attribBounds.
 508      * @param typarams the type variables to enter
 509      * @param env      the current environment
 510      */
 511     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
 512         for (JCTypeParameter tvar : typarams) {
 513             TypeVar a = (TypeVar)tvar.type;
 514             a.tsym.flags_field |= UNATTRIBUTED;
 515             a.bound = Type.noType;
 516             if (!tvar.bounds.isEmpty()) {
 517                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
 518                 for (JCExpression bound : tvar.bounds.tail)
 519                     bounds = bounds.prepend(attribType(bound, env));
 520                 types.setBounds(a, bounds.reverse());
 521             } else {
 522                 // if no bounds are given, assume a single bound of
 523                 // java.lang.Object.
 524                 types.setBounds(a, List.of(syms.objectType));
 525             }
 526             a.tsym.flags_field &= ~UNATTRIBUTED;
 527         }
 528         for (JCTypeParameter tvar : typarams)
 529             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
 530         attribStats(typarams, env);
 531     }
 532 
 533     void attribBounds(List<JCTypeParameter> typarams) {
 534         for (JCTypeParameter typaram : typarams) {
 535             Type bound = typaram.type.getUpperBound();
 536             if (bound != null && bound.tsym instanceof ClassSymbol) {
 537                 ClassSymbol c = (ClassSymbol)bound.tsym;
 538                 if ((c.flags_field & COMPOUND) != 0) {
 539                     assert (c.flags_field & UNATTRIBUTED) != 0 : c;
 540                     attribClass(typaram.pos(), c);
 541                 }
 542             }
 543         }
 544     }
 545 
 546     /**
 547      * Attribute the type references in a list of annotations.
 548      */
 549     void attribAnnotationTypes(List<JCAnnotation> annotations,
 550                                Env<AttrContext> env) {
 551         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
 552             JCAnnotation a = al.head;
 553             attribType(a.annotationType, env);
 554         }
 555     }
 556 
 557     /** Attribute type reference in an `extends' or `implements' clause.
 558      *  Supertypes of anonymous inner classes are usually already attributed.
 559      *
 560      *  @param tree              The tree making up the type reference.
 561      *  @param env               The environment current at the reference.
 562      *  @param classExpected     true if only a class is expected here.
 563      *  @param interfaceExpected true if only an interface is expected here.
 564      */
 565     Type attribBase(JCTree tree,
 566                     Env<AttrContext> env,
 567                     boolean classExpected,
 568                     boolean interfaceExpected,
 569                     boolean checkExtensible) {
 570         Type t = tree.type != null ?
 571             tree.type :
 572             attribType(tree, env);
 573         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
 574     }
 575     Type checkBase(Type t,
 576                    JCTree tree,
 577                    Env<AttrContext> env,
 578                    boolean classExpected,
 579                    boolean interfaceExpected,
 580                    boolean checkExtensible) {
 581         if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) {
 582             // check that type variable is already visible
 583             if (t.getUpperBound() == null) {
 584                 log.error(tree.pos(), "illegal.forward.ref");
 585                 return types.createErrorType(t);
 586             }
 587         } else {
 588             t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics);
 589         }
 590         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
 591             log.error(tree.pos(), "intf.expected.here");
 592             // return errType is necessary since otherwise there might
 593             // be undetected cycles which cause attribution to loop
 594             return types.createErrorType(t);
 595         } else if (checkExtensible &&
 596                    classExpected &&
 597                    (t.tsym.flags() & INTERFACE) != 0) {
 598             log.error(tree.pos(), "no.intf.expected.here");
 599             return types.createErrorType(t);
 600         }
 601         if (checkExtensible &&
 602             ((t.tsym.flags() & FINAL) != 0)) {
 603             log.error(tree.pos(),
 604                       "cant.inherit.from.final", t.tsym);
 605         }
 606         chk.checkNonCyclic(tree.pos(), t);
 607         return t;
 608     }
 609 
 610     public void visitClassDef(JCClassDecl tree) {
 611         // Local classes have not been entered yet, so we need to do it now:
 612         if ((env.info.scope.owner.kind & (VAR | MTH)) != 0)
 613             enter.classEnter(tree, env);
 614 
 615         ClassSymbol c = tree.sym;
 616         if (c == null) {
 617             // exit in case something drastic went wrong during enter.
 618             result = null;
 619         } else {
 620             // make sure class has been completed:
 621             c.complete();
 622 
 623             // If this class appears as an anonymous class
 624             // in a superclass constructor call where
 625             // no explicit outer instance is given,
 626             // disable implicit outer instance from being passed.
 627             // (This would be an illegal access to "this before super").
 628             if (env.info.isSelfCall &&
 629                 env.tree.getTag() == JCTree.NEWCLASS &&
 630                 ((JCNewClass) env.tree).encl == null)
 631             {
 632                 c.flags_field |= NOOUTERTHIS;
 633             }
 634             attribClass(tree.pos(), c);
 635             result = tree.type = c.type;
 636         }
 637     }
 638 
 639     public void visitMethodDef(JCMethodDecl tree) {
 640         MethodSymbol m = tree.sym;
 641 
 642         Lint lint = env.info.lint.augment(m.attributes_field, m.flags());
 643         Lint prevLint = chk.setLint(lint);
 644         try {
 645             chk.checkDeprecatedAnnotation(tree.pos(), m);
 646 
 647             attribBounds(tree.typarams);
 648 
 649             // If we override any other methods, check that we do so properly.
 650             // JLS ???
 651             chk.checkOverride(tree, m);
 652 
 653             // Create a new environment with local scope
 654             // for attributing the method.
 655             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
 656 
 657             localEnv.info.lint = lint;
 658 
 659             // Enter all type parameters into the local method scope.
 660             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
 661                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
 662 
 663             ClassSymbol owner = env.enclClass.sym;
 664             if ((owner.flags() & ANNOTATION) != 0 &&
 665                 tree.params.nonEmpty())
 666                 log.error(tree.params.head.pos(),
 667                           "intf.annotation.members.cant.have.params");
 668 
 669             // Attribute all value parameters.
 670             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
 671                 attribStat(l.head, localEnv);
 672             }
 673 
 674             chk.checkVarargMethodDecl(tree);
 675 
 676             // Check that type parameters are well-formed.
 677             chk.validate(tree.typarams, localEnv);
 678             if ((owner.flags() & ANNOTATION) != 0 &&
 679                 tree.typarams.nonEmpty())
 680                 log.error(tree.typarams.head.pos(),
 681                           "intf.annotation.members.cant.have.type.params");
 682 
 683             // Check that result type is well-formed.
 684             chk.validate(tree.restype, localEnv);
 685             if ((owner.flags() & ANNOTATION) != 0)
 686                 chk.validateAnnotationType(tree.restype);
 687 
 688             if ((owner.flags() & ANNOTATION) != 0)
 689                 chk.validateAnnotationMethod(tree.pos(), m);
 690 
 691             // Check that all exceptions mentioned in the throws clause extend
 692             // java.lang.Throwable.
 693             if ((owner.flags() & ANNOTATION) != 0 && tree.thrown.nonEmpty())
 694                 log.error(tree.thrown.head.pos(),
 695                           "throws.not.allowed.in.intf.annotation");
 696             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
 697                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
 698 
 699             if (tree.body == null) {
 700                 // Empty bodies are only allowed for
 701                 // abstract, native, or interface methods, or for methods
 702                 // in a retrofit signature class.
 703                 if ((owner.flags() & INTERFACE) == 0 &&
 704                     (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 &&
 705                     !relax)
 706                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
 707                 if (tree.defaultValue != null) {
 708                     if ((owner.flags() & ANNOTATION) == 0)
 709                         log.error(tree.pos(),
 710                                   "default.allowed.in.intf.annotation.member");
 711                 }
 712             } else if ((owner.flags() & INTERFACE) != 0) {
 713                 log.error(tree.body.pos(), "intf.meth.cant.have.body");
 714             } else if ((tree.mods.flags & ABSTRACT) != 0) {
 715                 log.error(tree.pos(), "abstract.meth.cant.have.body");
 716             } else if ((tree.mods.flags & NATIVE) != 0) {
 717                 log.error(tree.pos(), "native.meth.cant.have.body");
 718             } else {
 719                 // Add an implicit super() call unless an explicit call to
 720                 // super(...) or this(...) is given
 721                 // or we are compiling class java.lang.Object.
 722                 if (tree.name == names.init && owner.type != syms.objectType) {
 723                     JCBlock body = tree.body;
 724                     if (body.stats.isEmpty() ||
 725                         !TreeInfo.isSelfCall(body.stats.head)) {
 726                         body.stats = body.stats.
 727                             prepend(memberEnter.SuperCall(make.at(body.pos),
 728                                                           List.<Type>nil(),
 729                                                           List.<JCVariableDecl>nil(),
 730                                                           false));
 731                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
 732                                (tree.mods.flags & GENERATEDCONSTR) == 0 &&
 733                                TreeInfo.isSuperCall(body.stats.head)) {
 734                         // enum constructors are not allowed to call super
 735                         // directly, so make sure there aren't any super calls
 736                         // in enum constructors, except in the compiler
 737                         // generated one.
 738                         log.error(tree.body.stats.head.pos(),
 739                                   "call.to.super.not.allowed.in.enum.ctor",
 740                                   env.enclClass.sym);
 741                     }
 742                 }
 743 
 744                 // Attribute method body.
 745                 attribStat(tree.body, localEnv);
 746             }
 747             localEnv.info.scope.leave();
 748             result = tree.type = m.type;
 749             chk.validateAnnotations(tree.mods.annotations, m);
 750         }
 751         finally {
 752             chk.setLint(prevLint);
 753         }
 754     }
 755 
 756     public void visitVarDef(JCVariableDecl tree) {
 757         // Local variables have not been entered yet, so we need to do it now:
 758         if (env.info.scope.owner.kind == MTH) {
 759             if (tree.sym != null) {
 760                 // parameters have already been entered
 761                 env.info.scope.enter(tree.sym);
 762             } else {
 763                 memberEnter.memberEnter(tree, env);
 764                 annotate.flush();
 765             }
 766         }
 767 
 768         VarSymbol v = tree.sym;
 769         Lint lint = env.info.lint.augment(v.attributes_field, v.flags());
 770         Lint prevLint = chk.setLint(lint);
 771 
 772         // Check that the variable's declared type is well-formed.
 773         chk.validate(tree.vartype, env);
 774 
 775         try {
 776             chk.checkDeprecatedAnnotation(tree.pos(), v);
 777 
 778             if (tree.init != null) {
 779                 if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS) {
 780                     // In this case, `v' is final.  Ensure that it's initializer is
 781                     // evaluated.
 782                     v.getConstValue(); // ensure initializer is evaluated
 783                 } else {
 784                     // Attribute initializer in a new environment
 785                     // with the declared variable as owner.
 786                     // Check that initializer conforms to variable's declared type.
 787                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
 788                     initEnv.info.lint = lint;
 789                     // In order to catch self-references, we set the variable's
 790                     // declaration position to maximal possible value, effectively
 791                     // marking the variable as undefined.
 792                     initEnv.info.enclVar = v;
 793                     attribExpr(tree.init, initEnv, v.type);
 794                 }
 795             }
 796             result = tree.type = v.type;
 797             chk.validateAnnotations(tree.mods.annotations, v);
 798         }
 799         finally {
 800             chk.setLint(prevLint);
 801         }
 802     }
 803 
 804     public void visitSkip(JCSkip tree) {
 805         result = null;
 806     }
 807 
 808     public void visitBlock(JCBlock tree) {
 809         if (env.info.scope.owner.kind == TYP) {
 810             // Block is a static or instance initializer;
 811             // let the owner of the environment be a freshly
 812             // created BLOCK-method.
 813             Env<AttrContext> localEnv =
 814                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
 815             localEnv.info.scope.owner =
 816                 new MethodSymbol(tree.flags | BLOCK, names.empty, null,
 817                                  env.info.scope.owner);
 818             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
 819             attribStats(tree.stats, localEnv);
 820         } else {
 821             // Create a new local environment with a local scope.
 822             Env<AttrContext> localEnv =
 823                 env.dup(tree, env.info.dup(env.info.scope.dup()));
 824             attribStats(tree.stats, localEnv);
 825             localEnv.info.scope.leave();
 826         }
 827         result = null;
 828     }
 829 
 830     public void visitDoLoop(JCDoWhileLoop tree) {
 831         attribStat(tree.body, env.dup(tree));
 832         attribExpr(tree.cond, env, syms.booleanType);
 833         result = null;
 834     }
 835 
 836     public void visitWhileLoop(JCWhileLoop tree) {
 837         attribExpr(tree.cond, env, syms.booleanType);
 838         attribStat(tree.body, env.dup(tree));
 839         result = null;
 840     }
 841 
 842     public void visitForLoop(JCForLoop tree) {
 843         Env<AttrContext> loopEnv =
 844             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
 845         attribStats(tree.init, loopEnv);
 846         if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
 847         loopEnv.tree = tree; // before, we were not in loop!
 848         attribStats(tree.step, loopEnv);
 849         attribStat(tree.body, loopEnv);
 850         loopEnv.info.scope.leave();
 851         result = null;
 852     }
 853 
 854     public void visitForeachLoop(JCEnhancedForLoop tree) {
 855         Env<AttrContext> loopEnv =
 856             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
 857         attribStat(tree.var, loopEnv);
 858         Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv));
 859         chk.checkNonVoid(tree.pos(), exprType);
 860         Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
 861         if (elemtype == null) {
 862             // or perhaps expr implements Iterable<T>?
 863             Type base = types.asSuper(exprType, syms.iterableType.tsym);
 864             if (base == null) {
 865                 log.error(tree.expr.pos(), "foreach.not.applicable.to.type");
 866                 elemtype = types.createErrorType(exprType);
 867             } else {
 868                 List<Type> iterableParams = base.allparams();
 869                 elemtype = iterableParams.isEmpty()
 870                     ? syms.objectType
 871                     : types.upperBound(iterableParams.head);
 872             }
 873         }
 874         chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
 875         loopEnv.tree = tree; // before, we were not in loop!
 876         attribStat(tree.body, loopEnv);
 877         loopEnv.info.scope.leave();
 878         result = null;
 879     }
 880 
 881     public void visitLabelled(JCLabeledStatement tree) {
 882         // Check that label is not used in an enclosing statement
 883         Env<AttrContext> env1 = env;
 884         while (env1 != null && env1.tree.getTag() != JCTree.CLASSDEF) {
 885             if (env1.tree.getTag() == JCTree.LABELLED &&
 886                 ((JCLabeledStatement) env1.tree).label == tree.label) {
 887                 log.error(tree.pos(), "label.already.in.use",
 888                           tree.label);
 889                 break;
 890             }
 891             env1 = env1.next;
 892         }
 893 
 894         attribStat(tree.body, env.dup(tree));
 895         result = null;
 896     }
 897 
 898     public void visitSwitch(JCSwitch tree) {
 899         Type seltype = attribExpr(tree.selector, env);
 900 
 901         Env<AttrContext> switchEnv =
 902             env.dup(tree, env.info.dup(env.info.scope.dup()));
 903 
 904         boolean enumSwitch =
 905             allowEnums &&
 906             (seltype.tsym.flags() & Flags.ENUM) != 0;
 907         boolean stringSwitch = false;
 908         if (types.isSameType(seltype, syms.stringType)) {
 909             if (allowStringsInSwitch) {
 910                 stringSwitch = true;
 911             } else {
 912                 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
 913             }
 914         }
 915         if (!enumSwitch && !stringSwitch)
 916             seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
 917 
 918         // Attribute all cases and
 919         // check that there are no duplicate case labels or default clauses.
 920         Set<Object> labels = new HashSet<Object>(); // The set of case labels.
 921         boolean hasDefault = false;      // Is there a default label?
 922         for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
 923             JCCase c = l.head;
 924             Env<AttrContext> caseEnv =
 925                 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
 926             if (c.pat != null) {
 927                 if (enumSwitch) {
 928                     Symbol sym = enumConstant(c.pat, seltype);
 929                     if (sym == null) {
 930                         log.error(c.pat.pos(), "enum.const.req");
 931                     } else if (!labels.add(sym)) {
 932                         log.error(c.pos(), "duplicate.case.label");
 933                     }
 934                 } else {
 935                     Type pattype = attribExpr(c.pat, switchEnv, seltype);
 936                     if (pattype.tag != ERROR) {
 937                         if (pattype.constValue() == null) {
 938                             log.error(c.pat.pos(),
 939                                       (stringSwitch ? "string.const.req" : "const.expr.req"));
 940                         } else if (labels.contains(pattype.constValue())) {
 941                             log.error(c.pos(), "duplicate.case.label");
 942                         } else {
 943                             labels.add(pattype.constValue());
 944                         }
 945                     }
 946                 }
 947             } else if (hasDefault) {
 948                 log.error(c.pos(), "duplicate.default.label");
 949             } else {
 950                 hasDefault = true;
 951             }
 952             attribStats(c.stats, caseEnv);
 953             caseEnv.info.scope.leave();
 954             addVars(c.stats, switchEnv.info.scope);
 955         }
 956 
 957         switchEnv.info.scope.leave();
 958         result = null;
 959     }
 960     // where
 961         /** Add any variables defined in stats to the switch scope. */
 962         private static void addVars(List<JCStatement> stats, Scope switchScope) {
 963             for (;stats.nonEmpty(); stats = stats.tail) {
 964                 JCTree stat = stats.head;
 965                 if (stat.getTag() == JCTree.VARDEF)
 966                     switchScope.enter(((JCVariableDecl) stat).sym);
 967             }
 968         }
 969     // where
 970     /** Return the selected enumeration constant symbol, or null. */
 971     private Symbol enumConstant(JCTree tree, Type enumType) {
 972         if (tree.getTag() != JCTree.IDENT) {
 973             log.error(tree.pos(), "enum.label.must.be.unqualified.enum");
 974             return syms.errSymbol;
 975         }
 976         JCIdent ident = (JCIdent)tree;
 977         Name name = ident.name;
 978         for (Scope.Entry e = enumType.tsym.members().lookup(name);
 979              e.scope != null; e = e.next()) {
 980             if (e.sym.kind == VAR) {
 981                 Symbol s = ident.sym = e.sym;
 982                 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
 983                 ident.type = s.type;
 984                 return ((s.flags_field & Flags.ENUM) == 0)
 985                     ? null : s;
 986             }
 987         }
 988         return null;
 989     }
 990 
 991     public void visitSynchronized(JCSynchronized tree) {
 992         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
 993         attribStat(tree.body, env);
 994         result = null;
 995     }
 996 
 997     public void visitTry(JCTry tree) {
 998         // Create a new local environment with a local
 999         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1000         boolean isTryWithResource = tree.resources.nonEmpty();
1001         // Create a nested environment for attributing the try block if needed
1002         Env<AttrContext> tryEnv = isTryWithResource ?
1003             env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1004             localEnv;
1005         // Attribute resource declarations
1006         for (JCTree resource : tree.resources) {
1007             if (resource.getTag() == JCTree.VARDEF) {
1008                 attribStat(resource, tryEnv);
1009                 chk.checkType(resource, resource.type, syms.autoCloseableType, "twr.not.applicable.to.type");
1010                 VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource);
1011                 var.setData(ElementKind.RESOURCE_VARIABLE);
1012             } else {
1013                 attribExpr(resource, tryEnv, syms.autoCloseableType, "twr.not.applicable.to.type");
1014             }
1015         }
1016         // Attribute body
1017         attribStat(tree.body, tryEnv);
1018         if (isTryWithResource)
1019             tryEnv.info.scope.leave();
1020 
1021         // Attribute catch clauses
1022         for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1023             JCCatch c = l.head;
1024             Env<AttrContext> catchEnv =
1025                 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
1026             Type ctype = attribStat(c.param, catchEnv);
1027             if (TreeInfo.isMultiCatch(c)) {
1028                 //check that multi-catch parameter is marked as final
1029                 if ((c.param.sym.flags() & FINAL) == 0) {
1030                     log.error(c.param.pos(), "multicatch.param.must.be.final", c.param.sym);
1031                 }
1032                 c.param.sym.flags_field = c.param.sym.flags() | DISJOINT;
1033             }
1034             if (c.param.type.tsym.kind == Kinds.VAR) {
1035                 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
1036             }
1037             chk.checkType(c.param.vartype.pos(),
1038                           chk.checkClassType(c.param.vartype.pos(), ctype),
1039                           syms.throwableType);
1040             attribStat(c.body, catchEnv);
1041             catchEnv.info.scope.leave();
1042         }
1043 
1044         // Attribute finalizer
1045         if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1046 
1047         localEnv.info.scope.leave();
1048         result = null;
1049     }
1050 
1051     public void visitConditional(JCConditional tree) {
1052         attribExpr(tree.cond, env, syms.booleanType);
1053         attribExpr(tree.truepart, env);
1054         attribExpr(tree.falsepart, env);
1055         result = check(tree,
1056                        capture(condType(tree.pos(), tree.cond.type,
1057                                         tree.truepart.type, tree.falsepart.type)),
1058                        VAL, pkind, pt);
1059     }
1060     //where
1061         /** Compute the type of a conditional expression, after
1062          *  checking that it exists. See Spec 15.25.
1063          *
1064          *  @param pos      The source position to be used for
1065          *                  error diagnostics.
1066          *  @param condtype The type of the expression's condition.
1067          *  @param thentype The type of the expression's then-part.
1068          *  @param elsetype The type of the expression's else-part.
1069          */
1070         private Type condType(DiagnosticPosition pos,
1071                               Type condtype,
1072                               Type thentype,
1073                               Type elsetype) {
1074             Type ctype = condType1(pos, condtype, thentype, elsetype);
1075 
1076             // If condition and both arms are numeric constants,
1077             // evaluate at compile-time.
1078             return ((condtype.constValue() != null) &&
1079                     (thentype.constValue() != null) &&
1080                     (elsetype.constValue() != null))
1081                 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype)
1082                 : ctype;
1083         }
1084         /** Compute the type of a conditional expression, after
1085          *  checking that it exists.  Does not take into
1086          *  account the special case where condition and both arms
1087          *  are constants.
1088          *
1089          *  @param pos      The source position to be used for error
1090          *                  diagnostics.
1091          *  @param condtype The type of the expression's condition.
1092          *  @param thentype The type of the expression's then-part.
1093          *  @param elsetype The type of the expression's else-part.
1094          */
1095         private Type condType1(DiagnosticPosition pos, Type condtype,
1096                                Type thentype, Type elsetype) {
1097             // If same type, that is the result
1098             if (types.isSameType(thentype, elsetype))
1099                 return thentype.baseType();
1100 
1101             Type thenUnboxed = (!allowBoxing || thentype.isPrimitive())
1102                 ? thentype : types.unboxedType(thentype);
1103             Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive())
1104                 ? elsetype : types.unboxedType(elsetype);
1105 
1106             // Otherwise, if both arms can be converted to a numeric
1107             // type, return the least numeric type that fits both arms
1108             // (i.e. return larger of the two, or return int if one
1109             // arm is short, the other is char).
1110             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
1111                 // If one arm has an integer subrange type (i.e., byte,
1112                 // short, or char), and the other is an integer constant
1113                 // that fits into the subrange, return the subrange type.
1114                 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT &&
1115                     types.isAssignable(elseUnboxed, thenUnboxed))
1116                     return thenUnboxed.baseType();
1117                 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT &&
1118                     types.isAssignable(thenUnboxed, elseUnboxed))
1119                     return elseUnboxed.baseType();
1120 
1121                 for (int i = BYTE; i < VOID; i++) {
1122                     Type candidate = syms.typeOfTag[i];
1123                     if (types.isSubtype(thenUnboxed, candidate) &&
1124                         types.isSubtype(elseUnboxed, candidate))
1125                         return candidate;
1126                 }
1127             }
1128 
1129             // Those were all the cases that could result in a primitive
1130             if (allowBoxing) {
1131                 if (thentype.isPrimitive())
1132                     thentype = types.boxedClass(thentype).type;
1133                 if (elsetype.isPrimitive())
1134                     elsetype = types.boxedClass(elsetype).type;
1135             }
1136 
1137             if (types.isSubtype(thentype, elsetype))
1138                 return elsetype.baseType();
1139             if (types.isSubtype(elsetype, thentype))
1140                 return thentype.baseType();
1141 
1142             if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) {
1143                 log.error(pos, "neither.conditional.subtype",
1144                           thentype, elsetype);
1145                 return thentype.baseType();
1146             }
1147 
1148             // both are known to be reference types.  The result is
1149             // lub(thentype,elsetype). This cannot fail, as it will
1150             // always be possible to infer "Object" if nothing better.
1151             return types.lub(thentype.baseType(), elsetype.baseType());
1152         }
1153 
1154     public void visitIf(JCIf tree) {
1155         attribExpr(tree.cond, env, syms.booleanType);
1156         attribStat(tree.thenpart, env);
1157         if (tree.elsepart != null)
1158             attribStat(tree.elsepart, env);
1159         chk.checkEmptyIf(tree);
1160         result = null;
1161     }
1162 
1163     public void visitExec(JCExpressionStatement tree) {
1164         attribExpr(tree.expr, env);
1165         result = null;
1166     }
1167 
1168     public void visitBreak(JCBreak tree) {
1169         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1170         result = null;
1171     }
1172 
1173     public void visitContinue(JCContinue tree) {
1174         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
1175         result = null;
1176     }
1177     //where
1178         /** Return the target of a break or continue statement, if it exists,
1179          *  report an error if not.
1180          *  Note: The target of a labelled break or continue is the
1181          *  (non-labelled) statement tree referred to by the label,
1182          *  not the tree representing the labelled statement itself.
1183          *
1184          *  @param pos     The position to be used for error diagnostics
1185          *  @param tag     The tag of the jump statement. This is either
1186          *                 Tree.BREAK or Tree.CONTINUE.
1187          *  @param label   The label of the jump statement, or null if no
1188          *                 label is given.
1189          *  @param env     The environment current at the jump statement.
1190          */
1191         private JCTree findJumpTarget(DiagnosticPosition pos,
1192                                     int tag,
1193                                     Name label,
1194                                     Env<AttrContext> env) {
1195             // Search environments outwards from the point of jump.
1196             Env<AttrContext> env1 = env;
1197             LOOP:
1198             while (env1 != null) {
1199                 switch (env1.tree.getTag()) {
1200                 case JCTree.LABELLED:
1201                     JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
1202                     if (label == labelled.label) {
1203                         // If jump is a continue, check that target is a loop.
1204                         if (tag == JCTree.CONTINUE) {
1205                             if (labelled.body.getTag() != JCTree.DOLOOP &&
1206                                 labelled.body.getTag() != JCTree.WHILELOOP &&
1207                                 labelled.body.getTag() != JCTree.FORLOOP &&
1208                                 labelled.body.getTag() != JCTree.FOREACHLOOP)
1209                                 log.error(pos, "not.loop.label", label);
1210                             // Found labelled statement target, now go inwards
1211                             // to next non-labelled tree.
1212                             return TreeInfo.referencedStatement(labelled);
1213                         } else {
1214                             return labelled;
1215                         }
1216                     }
1217                     break;
1218                 case JCTree.DOLOOP:
1219                 case JCTree.WHILELOOP:
1220                 case JCTree.FORLOOP:
1221                 case JCTree.FOREACHLOOP:
1222                     if (label == null) return env1.tree;
1223                     break;
1224                 case JCTree.SWITCH:
1225                     if (label == null && tag == JCTree.BREAK) return env1.tree;
1226                     break;
1227                 case JCTree.METHODDEF:
1228                 case JCTree.CLASSDEF:
1229                     break LOOP;
1230                 default:
1231                 }
1232                 env1 = env1.next;
1233             }
1234             if (label != null)
1235                 log.error(pos, "undef.label", label);
1236             else if (tag == JCTree.CONTINUE)
1237                 log.error(pos, "cont.outside.loop");
1238             else
1239                 log.error(pos, "break.outside.switch.loop");
1240             return null;
1241         }
1242 
1243     public void visitReturn(JCReturn tree) {
1244         // Check that there is an enclosing method which is
1245         // nested within than the enclosing class.
1246         if (env.enclMethod == null ||
1247             env.enclMethod.sym.owner != env.enclClass.sym) {
1248             log.error(tree.pos(), "ret.outside.meth");
1249 
1250         } else {
1251             // Attribute return expression, if it exists, and check that
1252             // it conforms to result type of enclosing method.
1253             Symbol m = env.enclMethod.sym;
1254             if (m.type.getReturnType().tag == VOID) {
1255                 if (tree.expr != null)
1256                     log.error(tree.expr.pos(),
1257                               "cant.ret.val.from.meth.decl.void");
1258             } else if (tree.expr == null) {
1259                 log.error(tree.pos(), "missing.ret.val");
1260             } else {
1261                 attribExpr(tree.expr, env, m.type.getReturnType());
1262             }
1263         }
1264         result = null;
1265     }
1266 
1267     public void visitThrow(JCThrow tree) {
1268         attribExpr(tree.expr, env, syms.throwableType);
1269         result = null;
1270     }
1271 
1272     public void visitAssert(JCAssert tree) {
1273         attribExpr(tree.cond, env, syms.booleanType);
1274         if (tree.detail != null) {
1275             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
1276         }
1277         result = null;
1278     }
1279 
1280      /** Visitor method for method invocations.
1281      *  NOTE: The method part of an application will have in its type field
1282      *        the return type of the method, not the method's type itself!
1283      */
1284     public void visitApply(JCMethodInvocation tree) {
1285         // The local environment of a method application is
1286         // a new environment nested in the current one.
1287         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
1288 
1289         // The types of the actual method arguments.
1290         List<Type> argtypes;
1291 
1292         // The types of the actual method type arguments.
1293         List<Type> typeargtypes = null;
1294         boolean typeargtypesNonRefOK = false;
1295 
1296         Name methName = TreeInfo.name(tree.meth);
1297 
1298         boolean isConstructorCall =
1299             methName == names._this || methName == names._super;
1300 
1301         if (isConstructorCall) {
1302             // We are seeing a ...this(...) or ...super(...) call.
1303             // Check that this is the first statement in a constructor.
1304             if (checkFirstConstructorStat(tree, env)) {
1305 
1306                 // Record the fact
1307                 // that this is a constructor call (using isSelfCall).
1308                 localEnv.info.isSelfCall = true;
1309 
1310                 // Attribute arguments, yielding list of argument types.
1311                 argtypes = attribArgs(tree.args, localEnv);
1312                 typeargtypes = attribTypes(tree.typeargs, localEnv);
1313 
1314                 // Variable `site' points to the class in which the called
1315                 // constructor is defined.
1316                 Type site = env.enclClass.sym.type;
1317                 if (methName == names._super) {
1318                     if (site == syms.objectType) {
1319                         log.error(tree.meth.pos(), "no.superclass", site);
1320                         site = types.createErrorType(syms.objectType);
1321                     } else {
1322                         site = types.supertype(site);
1323                     }
1324                 }
1325 
1326                 if (site.tag == CLASS) {
1327                     Type encl = site.getEnclosingType();
1328                     while (encl != null && encl.tag == TYPEVAR)
1329                         encl = encl.getUpperBound();
1330                     if (encl.tag == CLASS) {
1331                         // we are calling a nested class
1332 
1333                         if (tree.meth.getTag() == JCTree.SELECT) {
1334                             JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
1335 
1336                             // We are seeing a prefixed call, of the form
1337                             //     <expr>.super(...).
1338                             // Check that the prefix expression conforms
1339                             // to the outer instance type of the class.
1340                             chk.checkRefType(qualifier.pos(),
1341                                              attribExpr(qualifier, localEnv,
1342                                                         encl));
1343                         } else if (methName == names._super) {
1344                             // qualifier omitted; check for existence
1345                             // of an appropriate implicit qualifier.
1346                             rs.resolveImplicitThis(tree.meth.pos(),
1347                                                    localEnv, site);
1348                         }
1349                     } else if (tree.meth.getTag() == JCTree.SELECT) {
1350                         log.error(tree.meth.pos(), "illegal.qual.not.icls",
1351                                   site.tsym);
1352                     }
1353 
1354                     // if we're calling a java.lang.Enum constructor,
1355                     // prefix the implicit String and int parameters
1356                     if (site.tsym == syms.enumSym && allowEnums)
1357                         argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
1358 
1359                     // Resolve the called constructor under the assumption
1360                     // that we are referring to a superclass instance of the
1361                     // current instance (JLS ???).
1362                     boolean selectSuperPrev = localEnv.info.selectSuper;
1363                     localEnv.info.selectSuper = true;
1364                     localEnv.info.varArgs = false;
1365                     Symbol sym = rs.resolveConstructor(
1366                         tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
1367                     localEnv.info.selectSuper = selectSuperPrev;
1368 
1369                     // Set method symbol to resolved constructor...
1370                     TreeInfo.setSymbol(tree.meth, sym);
1371 
1372                     // ...and check that it is legal in the current context.
1373                     // (this will also set the tree's type)
1374                     Type mpt = newMethTemplate(argtypes, typeargtypes);
1375                     checkId(tree.meth, site, sym, localEnv, MTH,
1376                             mpt, tree.varargsElement != null);
1377                 }
1378                 // Otherwise, `site' is an error type and we do nothing
1379             }
1380             result = tree.type = syms.voidType;
1381         } else {
1382             // Otherwise, we are seeing a regular method call.
1383             // Attribute the arguments, yielding list of argument types, ...
1384             argtypes = attribArgs(tree.args, localEnv);
1385             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
1386 
1387             // ... and attribute the method using as a prototype a methodtype
1388             // whose formal argument types is exactly the list of actual
1389             // arguments (this will also set the method symbol).
1390             Type mpt = newMethTemplate(argtypes, typeargtypes);
1391             localEnv.info.varArgs = false;
1392             Type mtype = attribExpr(tree.meth, localEnv, mpt);
1393             if (localEnv.info.varArgs)
1394                 assert mtype.isErroneous() || tree.varargsElement != null;
1395 
1396             // Compute the result type.
1397             Type restype = mtype.getReturnType();
1398             assert restype.tag != WILDCARD : mtype;
1399 
1400             // as a special case, array.clone() has a result that is
1401             // the same as static type of the array being cloned
1402             if (tree.meth.getTag() == JCTree.SELECT &&
1403                 allowCovariantReturns &&
1404                 methName == names.clone &&
1405                 types.isArray(((JCFieldAccess) tree.meth).selected.type))
1406                 restype = ((JCFieldAccess) tree.meth).selected.type;
1407 
1408             // as a special case, x.getClass() has type Class<? extends |X|>
1409             if (allowGenerics &&
1410                 methName == names.getClass && tree.args.isEmpty()) {
1411                 Type qualifier = (tree.meth.getTag() == JCTree.SELECT)
1412                     ? ((JCFieldAccess) tree.meth).selected.type
1413                     : env.enclClass.sym.type;
1414                 restype = new
1415                     ClassType(restype.getEnclosingType(),
1416                               List.<Type>of(new WildcardType(types.erasure(qualifier),
1417                                                                BoundKind.EXTENDS,
1418                                                                syms.boundClass)),
1419                               restype.tsym);
1420             }
1421 
1422             // as a special case, MethodHandle.<T>invoke(abc) and InvokeDynamic.<T>foo(abc)
1423             // has type <T>, and T can be a primitive type.
1424             if (tree.meth.getTag() == JCTree.SELECT && !typeargtypes.isEmpty()) {
1425               JCFieldAccess mfield = (JCFieldAccess) tree.meth;
1426               if ((mfield.selected.type.tsym != null &&
1427                    (mfield.selected.type.tsym.flags() & POLYMORPHIC_SIGNATURE) != 0)
1428                   ||
1429                   (mfield.sym != null &&
1430                    (mfield.sym.flags() & POLYMORPHIC_SIGNATURE) != 0)) {
1431                   assert types.isSameType(restype, typeargtypes.head) : mtype;
1432                   assert mfield.selected.type == syms.methodHandleType
1433                       || mfield.selected.type == syms.invokeDynamicType;
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.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
2188                 env.info.lint.isEnabled(Lint.LintCategory.ARM)) {
2189             log.warning(tree, "twr.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 }