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