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