src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java
author Dusan Balek <dbalek@netbeans.org>
Fri, 25 Aug 2017 16:36:44 +0200
changeset 5960 9b58471932b6
parent 5954 f453b3a76796
permissions -rw-r--r--
Issue #271310 - NullPointerException at com.sun.tools.javac.comp.Attr.enclosingInitEnv - fixed.
     1 /*
     2  * Copyright (c) 1999, 2017, 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 
    30 import javax.lang.model.element.ElementKind;
    31 import javax.tools.JavaFileObject;
    32 
    33 import com.sun.source.tree.IdentifierTree;
    34 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
    35 import com.sun.source.tree.MemberSelectTree;
    36 import com.sun.source.tree.TreeVisitor;
    37 import com.sun.source.util.SimpleTreeVisitor;
    38 import com.sun.tools.javac.code.*;
    39 import com.sun.tools.javac.code.Lint.LintCategory;
    40 import com.sun.tools.javac.code.Scope.WriteableScope;
    41 import com.sun.tools.javac.code.Symbol.*;
    42 import com.sun.tools.javac.code.Type.*;
    43 import com.sun.tools.javac.code.TypeMetadata.Annotations;
    44 import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError;
    45 import com.sun.tools.javac.comp.ArgumentAttr.LocalCacheContext;
    46 import com.sun.tools.javac.comp.Check.CheckContext;
    47 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
    48 import com.sun.tools.javac.jvm.*;
    49 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond;
    50 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArg;
    51 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArgs;
    52 import com.sun.tools.javac.resources.CompilerProperties.Errors;
    53 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
    54 import com.sun.tools.javac.tree.*;
    55 import com.sun.tools.javac.tree.JCTree.*;
    56 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
    57 import com.sun.tools.javac.util.*;
    58 import com.sun.tools.javac.util.DefinedBy.Api;
    59 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    60 import com.sun.tools.javac.util.JCDiagnostic.Fragment;
    61 import com.sun.tools.javac.util.List;
    62 
    63 import static com.sun.tools.javac.code.Flags.*;
    64 import static com.sun.tools.javac.code.Flags.ANNOTATION;
    65 import static com.sun.tools.javac.code.Flags.BLOCK;
    66 import static com.sun.tools.javac.code.Kinds.*;
    67 import static com.sun.tools.javac.code.Kinds.Kind.*;
    68 import static com.sun.tools.javac.code.TypeTag.*;
    69 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
    70 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    71 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
    72 
    73 /** This is the main context-dependent analysis phase in GJC. It
    74  *  encompasses name resolution, type checking and constant folding as
    75  *  subtasks. Some subtasks involve auxiliary classes.
    76  *  @see Check
    77  *  @see Resolve
    78  *  @see ConstFold
    79  *  @see Infer
    80  *
    81  *  <p><b>This is NOT part of any supported API.
    82  *  If you write code that depends on this, you do so at your own risk.
    83  *  This code and its internal interfaces are subject to change or
    84  *  deletion without notice.</b>
    85  */
    86 public class Attr extends JCTree.Visitor {
    87     protected static final Context.Key<Attr> attrKey = new Context.Key<>();
    88 
    89     final Names names;
    90     final Log log;
    91     final Symtab syms;
    92     final Resolve rs;
    93     final Operators operators;
    94     final Infer infer;
    95     final Analyzer analyzer;
    96     final DeferredAttr deferredAttr;
    97     final Check chk;
    98     final Flow flow;
    99     final MemberEnter memberEnter;
   100     final TypeEnter typeEnter;
   101     final TreeMaker make;
   102     final ConstFold cfolder;
   103     final Enter enter;
   104     final Target target;
   105     final Types types;
   106     final JCDiagnostic.Factory diags;
   107     final TypeAnnotations typeAnnotations;
   108     final DeferredLintHandler deferredLintHandler;
   109     final TypeEnvs typeEnvs;
   110     final Dependencies dependencies;
   111     final Annotate annotate;
   112     final ArgumentAttr argumentAttr;
   113     private final boolean isBackgroundCompilation;
   114 
   115     public static Attr instance(Context context) {
   116         Attr instance = context.get(attrKey);
   117         if (instance == null)
   118             instance = new Attr(context);
   119         return instance;
   120     }
   121 
   122     protected Attr(Context context) {
   123         context.put(attrKey, this);
   124 
   125         names = Names.instance(context);
   126         log = Log.instance(context);
   127         syms = Symtab.instance(context);
   128         rs = Resolve.instance(context);
   129         operators = Operators.instance(context);
   130         chk = Check.instance(context);
   131         flow = Flow.instance(context);
   132         memberEnter = MemberEnter.instance(context);
   133         typeEnter = TypeEnter.instance(context);
   134         make = TreeMaker.instance(context);
   135         enter = Enter.instance(context);
   136         infer = Infer.instance(context);
   137         analyzer = Analyzer.instance(context);
   138         deferredAttr = DeferredAttr.instance(context);
   139         cfolder = ConstFold.instance(context);
   140         target = Target.instance(context);
   141         types = Types.instance(context);
   142         diags = JCDiagnostic.Factory.instance(context);
   143         annotate = Annotate.instance(context);
   144         typeAnnotations = TypeAnnotations.instance(context);
   145         deferredLintHandler = DeferredLintHandler.instance(context);
   146         typeEnvs = TypeEnvs.instance(context);
   147         dependencies = Dependencies.instance(context);
   148         argumentAttr = ArgumentAttr.instance(context);
   149 
   150         Options options = Options.instance(context);
   151 
   152         Source source = Source.instance(context);
   153         allowStringsInSwitch = source.allowStringsInSwitch();
   154         allowPoly = source.allowPoly();
   155         allowTypeAnnos = source.allowTypeAnnotations();
   156         allowLambda = source.allowLambda();
   157         allowDefaultMethods = source.allowDefaultMethods();
   158         allowStaticInterfaceMethods = source.allowStaticInterfaceMethods();
   159         sourceName = source.name;
   160         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
   161 
   162         statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
   163         varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
   164         unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
   165         methodAttrInfo = new MethodAttrInfo();
   166         unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
   167         unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
   168         recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
   169 
   170         isBackgroundCompilation = options.get("backgroundCompilation") != null;     //NOI18N
   171     }
   172 
   173     /** Switch: support target-typing inference
   174      */
   175     boolean allowPoly;
   176 
   177     /** Switch: support type annotations.
   178      */
   179     boolean allowTypeAnnos;
   180 
   181     /** Switch: support lambda expressions ?
   182      */
   183     boolean allowLambda;
   184 
   185     /** Switch: support default methods ?
   186      */
   187     boolean allowDefaultMethods;
   188 
   189     /** Switch: static interface methods enabled?
   190      */
   191     boolean allowStaticInterfaceMethods;
   192 
   193     /**
   194      * Switch: warn about use of variable before declaration?
   195      * RFE: 6425594
   196      */
   197     boolean useBeforeDeclarationWarning;
   198 
   199     /**
   200      * Switch: allow strings in switch?
   201      */
   202     boolean allowStringsInSwitch;
   203 
   204     /**
   205      * Switch: name of source level; used for error reporting.
   206      */
   207     String sourceName;
   208 
   209     /** Check kind and type of given tree against protokind and prototype.
   210      *  If check succeeds, store type in tree and return it.
   211      *  If check fails, store errType in tree and return it.
   212      *  No checks are performed if the prototype is a method type.
   213      *  It is not necessary in this case since we know that kind and type
   214      *  are correct.
   215      *
   216      *  @param tree     The tree whose kind and type is checked
   217      *  @param found    The computed type of the tree
   218      *  @param ownkind  The computed kind of the tree
   219      *  @param resultInfo  The expected result of the tree
   220      */
   221     Type check(final JCTree tree,
   222                final Type found,
   223                final KindSelector ownkind,
   224                final ResultInfo resultInfo) {
   225         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
   226         Type owntype;
   227         boolean shouldCheck = !found.hasTag(ERROR) &&
   228                 !resultInfo.pt.hasTag(METHOD) &&
   229                 !resultInfo.pt.hasTag(FORALL);
   230         if (shouldCheck && !ownkind.subset(resultInfo.pkind)) {
   231             log.error(tree.pos(), "unexpected.type",
   232             resultInfo.pkind.kindNames(),
   233             ownkind.kindNames());
   234             owntype = types.createErrorType(found);
   235         } else if (allowPoly && inferenceContext.free(found)) {
   236             //delay the check if there are inference variables in the found type
   237             //this means we are dealing with a partially inferred poly expression
   238             owntype = shouldCheck ? resultInfo.pt : found;
   239             if (resultInfo.checkMode.installPostInferenceHook()) {
   240                 inferenceContext.addFreeTypeListener(List.of(found),
   241                         instantiatedContext -> {
   242                             ResultInfo pendingResult =
   243                                     resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
   244                             check(tree, inferenceContext.asInstType(found), ownkind, pendingResult);
   245                         });
   246             }
   247         } else {
   248             owntype = shouldCheck ?
   249             resultInfo.check(tree, found) :
   250             found;
   251         }
   252         if (resultInfo.checkMode.updateTreeType()) {
   253             tree.type = owntype;
   254         }
   255         return owntype;
   256     }
   257 
   258     /** Is given blank final variable assignable, i.e. in a scope where it
   259      *  may be assigned to even though it is final?
   260      *  @param v      The blank final variable.
   261      *  @param env    The current environment.
   262      */
   263     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
   264         Symbol owner = env.info.scope.owner;
   265            // owner refers to the innermost variable, method or
   266            // initializer block declaration at this point.
   267         return
   268             v.owner == owner
   269             ||
   270             ((owner.name == names.init ||    // i.e. we are in a constructor
   271               owner.kind == VAR ||           // i.e. we are in a variable initializer
   272               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
   273              &&
   274              v.owner == owner.owner
   275              &&
   276              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
   277     }
   278 
   279     /** Check that variable can be assigned to.
   280      *  @param pos    The current source code position.
   281      *  @param v      The assigned variable
   282      *  @param base   If the variable is referred to in a Select, the part
   283      *                to the left of the `.', null otherwise.
   284      *  @param env    The current environment.
   285      */
   286     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
   287         if (v.name == names._this) {
   288             log.error(pos, Errors.CantAssignValToThis);
   289         } else if ((v.flags() & FINAL) != 0 &&
   290             ((v.flags() & HASINIT) != 0
   291              ||
   292              !((base == null ||
   293                (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) &&
   294                isAssignableAsBlankFinal(v, env)))) {
   295             if (v.isResourceVariable()) { //TWR resource
   296                 log.error(pos, "try.resource.may.not.be.assigned", v);
   297             } else {
   298                 log.error(pos, "cant.assign.val.to.final.var", v);
   299             }
   300         }
   301     }
   302 
   303     /** Does tree represent a static reference to an identifier?
   304      *  It is assumed that tree is either a SELECT or an IDENT.
   305      *  We have to weed out selects from non-type names here.
   306      *  @param tree    The candidate tree.
   307      */
   308     boolean isStaticReference(JCTree tree) {
   309         if (tree.hasTag(SELECT)) {
   310             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
   311             if (lsym == null || lsym.kind != TYP) {
   312                 return false;
   313             }
   314         }
   315         return true;
   316     }
   317 
   318     /** Is this symbol a type?
   319      */
   320     static boolean isType(Symbol sym) {
   321         return sym != null && sym.kind == TYP;
   322     }
   323 
   324     /** The current `this' symbol.
   325      *  @param env    The current environment.
   326      */
   327     Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
   328         return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
   329     }
   330 
   331     /** Attribute a parsed identifier.
   332      * @param tree Parsed identifier name
   333      * @param topLevel The toplevel to use
   334      */
   335     public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
   336         Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
   337         localEnv.enclClass = make.ClassDef(make.Modifiers(0),
   338                                            syms.errSymbol.name,
   339                                            null, null, null, null);
   340         localEnv.enclClass.sym = syms.errSymbol;
   341         return attribIdent(tree, localEnv);
   342     }
   343 
   344     /** Attribute a parsed identifier.
   345      * @param tree Parsed identifier name
   346      * @param env The env to use
   347      */
   348     public Symbol attribIdent(JCTree tree, Env<AttrContext> env) {
   349         return tree.accept(identAttributer, env);
   350     }
   351     // where
   352         private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
   353         private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
   354             @Override @DefinedBy(Api.COMPILER_TREE)
   355             public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
   356                 Symbol site = visit(node.getExpression(), env);
   357                 if (!site.kind.isValid())
   358                     return site;
   359                 Name name = (Name)node.getIdentifier();
   360                 if (site.kind == PCK) {
   361                     env.toplevel.packge = (PackageSymbol)site;
   362                     return rs.findIdentInPackage(env, (TypeSymbol)site, name,
   363                             KindSelector.TYP_PCK);
   364                 } else {
   365                     env.enclClass.sym = (ClassSymbol)site;
   366                     return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
   367                 }
   368             }
   369 
   370             @Override @DefinedBy(Api.COMPILER_TREE)
   371             public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
   372                 return rs.findIdent(env, (Name)node.getName(), KindSelector.TYP_PCK);
   373             }
   374         }
   375 
   376     public Type coerce(Type etype, Type ttype) {
   377         return cfolder.coerce(etype, ttype);
   378     }
   379 
   380     public Type attribType(JCTree node, TypeSymbol sym) {
   381         Env<AttrContext> env = typeEnvs.get(sym);
   382         Env<AttrContext> localEnv = env.dup(node, env.info.dup());
   383         return attribTree(node, localEnv, unknownTypeInfo);
   384     }
   385 
   386     public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
   387         // Attribute qualifying package or class.
   388         JCFieldAccess s = (JCFieldAccess)tree.qualid;
   389         return attribTree(s.selected, env,
   390                           new ResultInfo(tree.staticImport ?
   391                                          KindSelector.TYP : KindSelector.TYP_PCK,
   392                        Type.noType));
   393     }
   394 
   395     public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
   396         Env<AttrContext> localEnv = env.dup(env.tree, env.info.dup(env.info.scope.dupUnshared()));
   397         breakTree = tree;
   398         try {
   399             attribExpr(expr, localEnv);
   400         } catch (BreakAttr b) {
   401             return b.env;
   402         } catch (AssertionError ae) {
   403             if (ae.getCause() instanceof BreakAttr) {
   404                 return ((BreakAttr)(ae.getCause())).env;
   405             } else {
   406                 throw ae;
   407             }
   408         } finally {
   409             breakTree = null;
   410         }
   411         return localEnv;
   412     }
   413 
   414     public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
   415         Env<AttrContext> localEnv = env.dup(env.tree, env.info.dup(env.info.scope.dupUnshared()));
   416         breakTree = tree;
   417         try {
   418             attribStat(stmt, localEnv);
   419         } catch (BreakAttr b) {
   420             return b.env;
   421         } catch (AssertionError ae) {
   422             if (ae.getCause() instanceof BreakAttr) {
   423                 return ((BreakAttr)(ae.getCause())).env;
   424             } else {
   425                 throw ae;
   426             }
   427         } finally {
   428             breakTree = null;
   429         }
   430         return localEnv;
   431     }
   432 
   433     private JCTree breakTree = null;
   434 
   435     public static class BreakAttr extends RuntimeException {
   436         static final long serialVersionUID = -6924771130405446405L;
   437         private final Env<AttrContext> env;
   438         private final Type result;
   439         private BreakAttr(Env<AttrContext> env, Type result) {
   440             this.env = env;
   441             this.result = result;
   442         }
   443     }
   444 
   445     /**
   446      * Mode controlling behavior of Attr.Check
   447      */
   448     enum CheckMode {
   449 
   450         NORMAL,
   451 
   452         /**
   453          * Mode signalling 'fake check' - skip tree update. A side-effect of this mode is
   454          * that the captured var cache in {@code InferenceContext} will be used in read-only
   455          * mode when performing inference checks.
   456          */
   457         NO_TREE_UPDATE {
   458             @Override
   459             public boolean updateTreeType() {
   460                 return false;
   461             }
   462         },
   463         /**
   464          * Mode signalling that caller will manage free types in tree decorations.
   465          */
   466         NO_INFERENCE_HOOK {
   467             @Override
   468             public boolean installPostInferenceHook() {
   469                 return false;
   470             }
   471         };
   472 
   473         public boolean updateTreeType() {
   474             return true;
   475         }
   476         public boolean installPostInferenceHook() {
   477             return true;
   478         }
   479     }
   480 
   481 
   482     class ResultInfo {
   483         final KindSelector pkind;
   484         final Type pt;
   485         final CheckContext checkContext;
   486         final CheckMode checkMode;
   487 
   488         ResultInfo(KindSelector pkind, Type pt) {
   489             this(pkind, pt, chk.basicHandler, CheckMode.NORMAL);
   490         }
   491 
   492         ResultInfo(KindSelector pkind, Type pt, CheckMode checkMode) {
   493             this(pkind, pt, chk.basicHandler, checkMode);
   494         }
   495 
   496         protected ResultInfo(KindSelector pkind,
   497                              Type pt, CheckContext checkContext) {
   498             this(pkind, pt, checkContext, CheckMode.NORMAL);
   499         }
   500 
   501         protected ResultInfo(KindSelector pkind,
   502                              Type pt, CheckContext checkContext, CheckMode checkMode) {
   503             this.pkind = pkind;
   504             this.pt = pt;
   505             this.checkContext = checkContext;
   506             this.checkMode = checkMode;
   507         }
   508 
   509         /**
   510          * Should {@link Attr#attribTree} use the {@ArgumentAttr} visitor instead of this one?
   511          * @param tree The tree to be type-checked.
   512          * @return true if {@ArgumentAttr} should be used.
   513          */
   514         protected boolean needsArgumentAttr(JCTree tree) { return false; }
   515 
   516         protected Type check(final DiagnosticPosition pos, final Type found) {
   517             return chk.checkType(pos, found, pt, checkContext);
   518         }
   519 
   520         protected ResultInfo dup(Type newPt) {
   521             return new ResultInfo(pkind, newPt, checkContext, checkMode);
   522         }
   523 
   524         protected ResultInfo dup(CheckContext newContext) {
   525             return new ResultInfo(pkind, pt, newContext, checkMode);
   526         }
   527 
   528         protected ResultInfo dup(Type newPt, CheckContext newContext) {
   529             return new ResultInfo(pkind, newPt, newContext, checkMode);
   530         }
   531 
   532         protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) {
   533             return new ResultInfo(pkind, newPt, newContext, newMode);
   534         }
   535 
   536         protected ResultInfo dup(CheckMode newMode) {
   537             return new ResultInfo(pkind, pt, checkContext, newMode);
   538         }
   539 
   540         @Override
   541         public String toString() {
   542             if (pt != null) {
   543                 return pt.toString();
   544             } else {
   545                 return "";
   546             }
   547         }
   548     }
   549 
   550     class MethodAttrInfo extends ResultInfo {
   551         public MethodAttrInfo() {
   552             this(chk.basicHandler);
   553         }
   554 
   555         public MethodAttrInfo(CheckContext checkContext) {
   556             super(KindSelector.VAL, Infer.anyPoly, checkContext);
   557         }
   558 
   559         @Override
   560         protected boolean needsArgumentAttr(JCTree tree) {
   561             return true;
   562         }
   563 
   564         protected ResultInfo dup(Type newPt) {
   565             throw new IllegalStateException();
   566         }
   567 
   568         protected ResultInfo dup(CheckContext newContext) {
   569             return new MethodAttrInfo(newContext);
   570         }
   571 
   572         protected ResultInfo dup(Type newPt, CheckContext newContext) {
   573             throw new IllegalStateException();
   574         }
   575 
   576         protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) {
   577             throw new IllegalStateException();
   578         }
   579 
   580         protected ResultInfo dup(CheckMode newMode) {
   581             throw new IllegalStateException();
   582         }
   583     }
   584 
   585     class RecoveryInfo extends ResultInfo {
   586 
   587         public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
   588             this(deferredAttrContext, Type.recoveryType);
   589         }
   590         
   591         public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext, final Type pt) {
   592             super(KindSelector.VAL, pt, new Check.NestedCheckContext(chk.basicHandler) {
   593                 @Override
   594                 public DeferredAttr.DeferredAttrContext deferredAttrContext() {
   595                     return deferredAttrContext;
   596                 }
   597                 @Override
   598                 public boolean compatible(Type found, Type req, Warner warn) {
   599                     return true;
   600                 }
   601                 @Override
   602                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
   603                     chk.basicHandler.report(pos, details);
   604                 }
   605             });
   606         }
   607     }
   608 
   609     final ResultInfo statInfo;
   610     final ResultInfo varAssignmentInfo;
   611     final ResultInfo methodAttrInfo;
   612     final ResultInfo unknownExprInfo;
   613     final ResultInfo unknownTypeInfo;
   614     final ResultInfo unknownTypeExprInfo;
   615     final ResultInfo recoveryInfo;
   616 
   617     Type pt() {
   618         return resultInfo.pt;
   619     }
   620 
   621     KindSelector pkind() {
   622         return resultInfo.pkind;
   623     }
   624 
   625 /* ************************************************************************
   626  * Visitor methods
   627  *************************************************************************/
   628 
   629     /** Visitor argument: the current environment.
   630      */
   631     Env<AttrContext> env;
   632 
   633     /** Visitor argument: the currently expected attribution result.
   634      */
   635     ResultInfo resultInfo;
   636 
   637     /** Visitor result: the computed type.
   638      */
   639     Type result;
   640 
   641     /** Visitor method: attribute a tree, catching any completion failure
   642      *  exceptions. Return the tree's type.
   643      *
   644      *  @param tree    The tree to be visited.
   645      *  @param env     The environment visitor argument.
   646      *  @param resultInfo   The result info visitor argument.
   647      */
   648     Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
   649         Env<AttrContext> prevEnv = this.env;
   650         ResultInfo prevResult = this.resultInfo;
   651         try {
   652             this.env = env;
   653             this.resultInfo = resultInfo;
   654             try {
   655                 if (resultInfo.needsArgumentAttr(tree)) {
   656                     result = argumentAttr.attribArg(tree, env);
   657                 } else {
   658                     tree.accept(this);
   659                 }
   660             } catch (Resolve.InapplicableMethodException ime) {
   661                 if (tree != breakTree ||
   662                         resultInfo.checkContext.deferredAttrContext().mode != AttrMode.CHECK) {
   663                     throw ime;
   664                 }
   665             }
   666             if (tree == breakTree &&
   667                     resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
   668                 throw new BreakAttr(copyEnv(env), result);
   669             }
   670             return result;
   671         } catch (CompletionFailure ex) {
   672             tree.type = syms.errType;
   673             return chk.completionError(tree.pos(), ex);
   674         } finally {
   675             this.env = prevEnv;
   676             this.resultInfo = prevResult;
   677         }
   678     }
   679 
   680     Env<AttrContext> copyEnv(Env<AttrContext> env) {
   681         Env<AttrContext> newEnv =
   682                 env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
   683         if (newEnv.outer != null) {
   684             newEnv.outer = copyEnv(newEnv.outer);
   685         }
   686         return newEnv;
   687     }
   688 
   689     WriteableScope copyScope(WriteableScope sc) {
   690         WriteableScope newScope = WriteableScope.create(sc.owner);
   691         List<Symbol> elemsList = List.nil();
   692         for (Symbol sym : sc.getSymbols()) {
   693             elemsList = elemsList.prepend(sym);
   694         }
   695         for (Symbol s : elemsList) {
   696             newScope.enter(s);
   697         }
   698         return newScope;
   699     }
   700 
   701     /** Derived visitor method: attribute an expression tree.
   702      */
   703     public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
   704         return attribTree(tree, env, new ResultInfo(KindSelector.VAL, pt != null && !pt.hasTag(ERROR) ? pt : Type.noType));
   705     }
   706 
   707     /** Derived visitor method: attribute an expression tree with
   708      *  no constraints on the computed type.
   709      */
   710     public Type attribExpr(JCTree tree, Env<AttrContext> env) {
   711         return attribTree(tree, env, unknownExprInfo);
   712     }
   713 
   714     /** Derived visitor method: attribute a type tree.
   715      */
   716     public Type attribType(JCTree tree, Env<AttrContext> env) {
   717         Type result = attribType(tree, env, Type.noType);
   718         return result;
   719     }
   720 
   721     /** Derived visitor method: attribute a type tree.
   722      */
   723     Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
   724         Type result = attribTree(tree, env, new ResultInfo(KindSelector.TYP, pt));
   725         return result;
   726     }
   727 
   728     /** Derived visitor method: attribute a statement or definition tree.
   729      */
   730     public Type attribStat(JCTree tree, Env<AttrContext> env) {
   731         Env<AttrContext> analyzeEnv = analyzer.copyEnvIfNeeded(tree, env);
   732         boolean baCatched = false;
   733         try {
   734             return attribTree(tree, env, statInfo);
   735         } catch (BreakAttr ba) {
   736             baCatched = true;
   737             throw ba;
   738         } finally {
   739             if (!baCatched) {
   740                 analyzer.analyzeIfNeeded(tree, analyzeEnv);
   741             }
   742         }
   743     }
   744 
   745     /** Attribute a list of expressions, returning a list of types.
   746      */
   747     List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
   748         ListBuffer<Type> ts = new ListBuffer<>();
   749         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   750             ts.append(attribExpr(l.head, env, pt));
   751         return ts.toList();
   752     }
   753 
   754     /** Attribute a list of statements, returning nothing.
   755      */
   756     <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
   757         for (List<T> l = trees; l.nonEmpty(); l = l.tail)
   758             attribStat(l.head, env);
   759     }
   760 
   761     /** Attribute the arguments in a method call, returning the method kind.
   762      */
   763     KindSelector attribArgs(KindSelector initialKind, List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) {
   764         KindSelector kind = initialKind;
   765         for (JCExpression arg : trees) {
   766             try {
   767                 Type argtype = chk.checkNonVoid(arg, attribTree(arg, env, allowPoly ? methodAttrInfo : unknownExprInfo));
   768                 if (argtype.hasTag(DEFERRED)) {
   769                     kind = KindSelector.of(KindSelector.POLY, kind);
   770                 }
   771                 argtypes.append(argtype);
   772             } catch (BreakAttr ba) {
   773                 if (ba.result != null && !ba.result.hasTag(PACKAGE) && !ba.result.hasTag(METHOD) && env.tree == ba.env.tree) {
   774                     argtypes.append(chk.checkNonVoid(arg, ba.result));
   775                 }
   776                 throw ba;
   777             }
   778         }
   779         return kind;
   780     }
   781 
   782     /** Attribute a type argument list, returning a list of types.
   783      *  Caller is responsible for calling checkRefTypes.
   784      */
   785     List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
   786         ListBuffer<Type> argtypes = new ListBuffer<>();
   787         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
   788             argtypes.append(attribType(l.head, env));
   789         return argtypes.toList();
   790     }
   791 
   792     /** Attribute a type argument list, returning a list of types.
   793      *  Check that all the types are references.
   794      */
   795     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
   796         List<Type> types = attribAnyTypes(trees, env);
   797         return chk.checkRefTypes(trees, types);
   798     }
   799 
   800     /**
   801      * Attribute type variables (of generic classes or methods).
   802      * Compound types are attributed later in attribBounds.
   803      * @param typarams the type variables to enter
   804      * @param env      the current environment
   805      */
   806     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) {
   807         for (JCTypeParameter tvar : typarams) {
   808             TypeVar a = (TypeVar)tvar.type;
   809             a.tsym.flags_field |= UNATTRIBUTED;
   810             a.bound = Type.noType;
   811             if (!tvar.bounds.isEmpty()) {
   812                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
   813                 for (JCExpression bound : tvar.bounds.tail)
   814                     bounds = bounds.prepend(attribType(bound, env));
   815                 types.setBounds(a, bounds.reverse());
   816             } else {
   817                 // if no bounds are given, assume a single bound of
   818                 // java.lang.Object.
   819                 types.setBounds(a, List.of(syms.objectType));
   820             }
   821             a.tsym.flags_field &= ~UNATTRIBUTED;
   822         }
   823         for (JCTypeParameter tvar : typarams) {
   824             chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
   825         }
   826     }
   827 
   828     /**
   829      * Attribute the type references in a list of annotations.
   830      */
   831     void attribAnnotationTypes(List<JCAnnotation> annotations,
   832                                Env<AttrContext> env) {
   833         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   834             JCAnnotation a = al.head;
   835             attribType(a.annotationType, env);
   836         }
   837     }
   838 
   839     /**
   840      * Attribute a "lazy constant value".
   841      *  @param env         The env for the const value
   842      *  @param variable    The initializer for the const value
   843      *  @param type        The expected type, or null
   844      *  @see VarSymbol#setLazyConstValue
   845      */
   846     public Object attribLazyConstantValue(Env<AttrContext> env,
   847                                       JCVariableDecl variable,
   848                                       Type type) {
   849 
   850         DiagnosticPosition prevLintPos
   851                 = deferredLintHandler.setPos(variable.pos());
   852 
   853         final JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
   854         try {
   855             if (variable.init == null) {
   856                 return null;
   857             }
   858             Type itype = attribExpr(variable.init, env, type);
   859             if (itype.constValue() != null) {
   860                 return coerce(itype, type).constValue();
   861             } else {
   862                 return null;
   863             }
   864         } finally {
   865             log.useSource(prevSource);
   866             deferredLintHandler.setPos(prevLintPos);
   867         }
   868     }
   869 
   870     /** Attribute type reference in an `extends' or `implements' clause.
   871      *  Supertypes of anonymous inner classes are usually already attributed.
   872      *
   873      *  @param tree              The tree making up the type reference.
   874      *  @param env               The environment current at the reference.
   875      *  @param classExpected     true if only a class is expected here.
   876      *  @param interfaceExpected true if only an interface is expected here.
   877      */
   878     Type attribBase(JCTree tree,
   879                     Env<AttrContext> env,
   880                     boolean classExpected,
   881                     boolean interfaceExpected,
   882                     boolean checkExtensible) {
   883         Type t = tree.type != null ?
   884             tree.type :
   885             attribType(tree, env);
   886         return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
   887     }
   888     Type checkBase(Type t,
   889                    JCTree tree,
   890                    Env<AttrContext> env,
   891                    boolean classExpected,
   892                    boolean interfaceExpected,
   893                    boolean checkExtensible) {
   894         final DiagnosticPosition pos = tree.hasTag(TYPEAPPLY) ?
   895                 (((JCTypeApply) tree).clazz).pos() : tree.pos();
   896         if (t.tsym.isAnonymous()) {
   897             log.error(pos, "cant.inherit.from.anon");
   898             return types.createErrorType(t);
   899         }
   900         if (t.isErroneous())
   901             return t;
   902         if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
   903             // check that type variable is already visible
   904             if (t.getUpperBound() == null) {
   905                 log.error(pos, "illegal.forward.ref");
   906                 return types.createErrorType(t);
   907             }
   908         } else {
   909             t = chk.checkClassType(pos, t, checkExtensible);
   910         }
   911         if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
   912             log.error(pos, "intf.expected.here");
   913             // return errType is necessary since otherwise there might
   914             // be undetected cycles which cause attribution to loop
   915             return types.createErrorType(t);
   916         } else if (checkExtensible &&
   917                    classExpected &&
   918                    (t.tsym.flags() & INTERFACE) != 0) {
   919             log.error(pos, "no.intf.expected.here");
   920             return types.createErrorType(t);
   921         }
   922         if (checkExtensible &&
   923             ((t.tsym.flags() & FINAL) != 0)) {
   924             log.error(pos,
   925                       "cant.inherit.from.final", t.tsym);
   926         }
   927         chk.checkNonCyclic(pos, t);
   928         return t;
   929     }
   930 
   931     Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
   932         Assert.check((env.enclClass.sym.flags() & ENUM) != 0 || env.enclClass.sym.kind == ERR);
   933         id.type = env.info.scope.owner.enclClass().type;
   934         id.sym = env.info.scope.owner.enclClass();
   935         return id.type;
   936     }
   937 
   938     public void visitClassDef(JCClassDecl tree) {
   939         Optional<ArgumentAttr.LocalCacheContext> localCacheContext =
   940                 Optional.ofNullable(env.info.isSpeculative ?
   941                         argumentAttr.withLocalCacheContext() : null);
   942         try {
   943             // Local and anonymous classes have not been entered yet, so we need to
   944             // do it now.
   945             if (env.info.scope.owner.kind.matches(KindSelector.VAL_MTH)
   946                     && (env.info.scope.owner.kind != ERR || tree.sym == null)) {
   947                 enter.classEnter(tree, env);
   948             } else {
   949                 // If this class declaration is part of a class level annotation,
   950                 // as in @MyAnno(new Object() {}) class MyClass {}, enter it in
   951                 // order to simplify later steps and allow for sensible error
   952                 // messages.
   953                 if (env.tree.hasTag(NEWCLASS) && TreeInfo.isInAnnotation(env, tree))
   954                     enter.classEnter(tree, env);
   955             }
   956 
   957             ClassSymbol c = tree.sym;
   958             if (c == null) {
   959                 // exit in case something drastic went wrong during enter.
   960                 result = null;
   961             } else {
   962                 // make sure class has been completed:
   963                 c.complete();
   964 
   965                 // If this class appears as an anonymous class
   966                 // in a superclass constructor call
   967                 // disable implicit outer instance from being passed.
   968                 // (This would be an illegal access to "this before super").
   969                 if (env.info.isSelfCall &&
   970                         env.tree.hasTag(NEWCLASS)) {
   971                     c.flags_field |= NOOUTERTHIS;
   972                 }
   973                 attribClass(tree.pos(), c);
   974                 result = tree.type = c.type;
   975             }
   976         } finally {
   977             localCacheContext.ifPresent(LocalCacheContext::leave);
   978         }
   979     }
   980 
   981     public void visitMethodDef(JCMethodDecl tree) {
   982         MethodSymbol m = tree.sym;
   983         if (m == null) {
   984             // exit in case something drastic went wrong during enter.
   985             result = null;
   986             return;
   987         }
   988         boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
   989 
   990         Lint lint = env.info.lint.augment(m);
   991         Lint prevLint = chk.setLint(lint);
   992         MethodSymbol prevMethod = chk.setMethod(m);
   993         try {
   994             deferredLintHandler.flush(tree.pos());
   995             chk.checkDeprecatedAnnotation(tree.pos(), m);
   996 
   997 
   998             // Create a new environment with local scope
   999             // for attributing the method.
  1000             Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
  1001             localEnv.info.lint = lint;
  1002 
  1003             attribStats(tree.typarams, localEnv);
  1004 
  1005             // If we override any other methods, check that we do so properly.
  1006             // JLS ???
  1007             if (m.isStatic()) {
  1008                 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
  1009             } else {
  1010                 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
  1011             }
  1012             chk.checkOverride(env, tree, m);
  1013 
  1014             if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
  1015                 log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location());
  1016             }
  1017 
  1018             // Enter all type parameters into the local method scope.
  1019             for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
  1020                 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
  1021 
  1022             ClassSymbol owner = env.enclClass.sym;
  1023             if ((owner.flags() & ANNOTATION) != 0 &&
  1024                     (tree.params.nonEmpty() ||
  1025                     tree.recvparam != null))
  1026                 log.error(tree.params.nonEmpty() ?
  1027                         tree.params.head.pos() :
  1028                         tree.recvparam.pos(),
  1029                         "intf.annotation.members.cant.have.params");
  1030 
  1031             // Attribute all value parameters.
  1032             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
  1033                 attribStat(l.head, localEnv);
  1034             }
  1035 
  1036             chk.checkVarargsMethodDecl(localEnv, tree);
  1037 
  1038             // Check that type parameters are well-formed.
  1039             chk.validate(tree.typarams, localEnv);
  1040 
  1041             // Check that result type is well-formed.
  1042             if (tree.restype != null && !tree.restype.type.hasTag(VOID))
  1043                 chk.validate(tree.restype, localEnv);
  1044 
  1045             // Check that receiver type is well-formed.
  1046             if (tree.recvparam != null) {
  1047                 // Use a new environment to check the receiver parameter.
  1048                 // Otherwise I get "might not have been initialized" errors.
  1049                 // Is there a better way?
  1050                 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
  1051                 attribType(tree.recvparam, newEnv);
  1052                 chk.validate(tree.recvparam, newEnv);
  1053             }
  1054 
  1055             // annotation method checks
  1056             if ((owner.flags() & ANNOTATION) != 0) {
  1057                 // annotation method cannot have throws clause
  1058                 if (tree.thrown.nonEmpty()) {
  1059                     log.error(tree.thrown.head.pos(),
  1060                             "throws.not.allowed.in.intf.annotation");
  1061                 }
  1062                 // annotation method cannot declare type-parameters
  1063                 if (tree.typarams.nonEmpty()) {
  1064                     log.error(tree.typarams.head.pos(),
  1065                             "intf.annotation.members.cant.have.type.params");
  1066                 }
  1067                 // validate annotation method's return type (could be an annotation type)
  1068                 chk.validateAnnotationType(tree.restype);
  1069                 // ensure that annotation method does not clash with members of Object/Annotation
  1070                 chk.validateAnnotationMethod(tree.pos(), m);
  1071             }
  1072 
  1073             for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
  1074                 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
  1075 
  1076             if (tree.body == null) {
  1077                 // Empty bodies are only allowed for
  1078                 // abstract, native, or interface methods, or for methods
  1079                 // in a retrofit signature class.
  1080                 if (tree.defaultValue != null) {
  1081                     if ((owner.flags() & ANNOTATION) == 0)
  1082                         log.error(tree.pos(),
  1083                                   "default.allowed.in.intf.annotation.member");
  1084                 }
  1085                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
  1086                     log.error(tree.pos(), "missing.meth.body.or.decl.abstract");
  1087             } else {
  1088                 if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
  1089                     if ((owner.flags() & INTERFACE) != 0) {
  1090                         log.error(tree.body.pos(), "intf.meth.cant.have.body");
  1091                     } else {
  1092                         log.error(tree.pos(), "abstract.meth.cant.have.body");
  1093                     }
  1094                 } else if ((tree.mods.flags & NATIVE) != 0) {
  1095                     log.error(tree.pos(), "native.meth.cant.have.body");
  1096                 }
  1097                 // Add an implicit super() call unless an explicit call to
  1098                 // super(...) or this(...) is given
  1099                 // or we are compiling class java.lang.Object.
  1100                 if (tree.name == names.init && !owner.type.isErroneous() && owner.type != syms.objectType) {
  1101                     JCBlock body = tree.body;
  1102                     if (body.stats.isEmpty() ||
  1103                             !TreeInfo.isSelfCall(body.stats.head)) {
  1104                         body.stats = body.stats.
  1105                                 prepend(typeEnter.SuperCall(make.at(body.pos),
  1106                                         List.nil(),
  1107                                         List.nil(),
  1108                                         false));
  1109                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
  1110                             (tree.mods.flags & GENERATEDCONSTR) == 0 &&
  1111                             TreeInfo.isSuperCall(body.stats.head)) {
  1112                         // enum constructors are not allowed to call super
  1113                         // directly, so make sure there aren't any super calls
  1114                         // in enum constructors, except in the compiler
  1115                         // generated one.
  1116                         log.error(tree.body.stats.head.pos(),
  1117                                 "call.to.super.not.allowed.in.enum.ctor",
  1118                                 env.enclClass.sym);
  1119                     }
  1120                 }
  1121 
  1122                 if (!isBackgroundCompilation) {
  1123                     tree.localEnv = dupLocalEnv(localEnv);
  1124                 }
  1125 
  1126                 // Attribute all type annotations in the body
  1127                 annotate.queueScanTreeAndTypeAnnotate(tree.body, localEnv, m, null);
  1128                 annotate.flush();
  1129 
  1130                 // Attribute method body.
  1131                 attribStat(tree.body, localEnv);
  1132             }
  1133 
  1134             localEnv.info.scope.leave();
  1135             result = tree.type = m.type;
  1136         } finally {
  1137             chk.setLint(prevLint);
  1138             chk.setMethod(prevMethod);
  1139         }
  1140     }
  1141 
  1142     public void visitVarDef(JCVariableDecl tree) {
  1143         // Local variables have not been entered yet, so we need to do it now:
  1144         if (env.info.scope.owner.kind == MTH) {
  1145             if (tree.sym != null) {
  1146                 // parameters have already been entered
  1147                 env.info.scope.enter(tree.sym);
  1148             } else {
  1149                 try {
  1150                     annotate.blockAnnotations();
  1151                     memberEnter.memberEnter(tree, env);
  1152                 } finally {
  1153                     annotate.unblockAnnotations();
  1154                 }
  1155             }
  1156         } else {
  1157             if (tree.init != null) {
  1158                 // Field initializer expression need to be entered.
  1159                 annotate.queueScanTreeAndTypeAnnotate(tree.init, env, tree.sym, tree.pos());
  1160                 annotate.flush();
  1161             }
  1162         }
  1163 
  1164         VarSymbol v = tree.sym;
  1165         if (v == null) {
  1166             // exit in case something drastic went wrong during enter.
  1167             result = null;
  1168             return;
  1169         }
  1170         Lint lint = env.info.lint.augment(v);
  1171         Lint prevLint = chk.setLint(lint);
  1172 
  1173         // Check that the variable's declared type is well-formed.
  1174         boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
  1175                 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
  1176                 (tree.sym.flags() & PARAMETER) != 0;
  1177         chk.validate(tree.vartype, env, !isImplicitLambdaParameter);
  1178 
  1179         try {
  1180             v.getConstValue(); // ensure compile-time constant initializer is evaluated
  1181             deferredLintHandler.flush(tree.pos());
  1182             chk.checkDeprecatedAnnotation(tree.pos(), v);
  1183 
  1184             if (tree.init != null) {
  1185                 if ((v.flags_field & FINAL) == 0 ||
  1186                     !memberEnter.needsLazyConstValue(tree.init)) {
  1187                     // Not a compile-time constant
  1188                     // Attribute initializer in a new environment
  1189                     // with the declared variable as owner.
  1190                     // Check that initializer conforms to variable's declared type.
  1191                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
  1192                     initEnv.info.lint = lint;
  1193                     // In order to catch self-references, we set the variable's
  1194                     // declaration position to maximal possible value, effectively
  1195                     // marking the variable as undefined.
  1196                     initEnv.info.enclVar = v;
  1197                     attribExpr(tree.init, initEnv, v.type);
  1198                 }
  1199             }
  1200             result = tree.type = v.type;
  1201         }
  1202         finally {
  1203             chk.setLint(prevLint);
  1204         }
  1205     }
  1206 
  1207     public void visitSkip(JCSkip tree) {
  1208         result = null;
  1209     }
  1210 
  1211     public void visitBlock(JCBlock tree) {
  1212         if (env.info.scope != null && env.info.scope.owner != null && (env.info.scope.owner.kind == TYP || env.info.scope.owner.kind == ERR)) {
  1213             // Block is a static or instance initializer;
  1214             // let the owner of the environment be a freshly
  1215             // created BLOCK-method.
  1216             Symbol fakeOwner =
  1217                 new MethodSymbol(tree.flags | BLOCK |
  1218                     env.info.scope.owner.flags() & STRICTFP, names.empty, null,
  1219                     env.info.scope.owner);
  1220             final Env<AttrContext> localEnv =
  1221                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
  1222 
  1223             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
  1224             // Attribute all type annotations in the block
  1225             annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
  1226             annotate.flush();
  1227             attribStats(tree.stats, localEnv);
  1228 
  1229             {
  1230                 // Store init and clinit type annotations with the ClassSymbol
  1231                 // to allow output in Gen.normalizeDefs.
  1232                 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
  1233                 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
  1234                 if ((tree.flags & STATIC) != 0) {
  1235                     cs.appendClassInitTypeAttributes(tas);
  1236                 } else {
  1237                     cs.appendInitTypeAttributes(tas);
  1238                 }
  1239             }
  1240         } else {
  1241             // Create a new local environment with a local scope.
  1242             Env<AttrContext> localEnv =
  1243                 env.dup(tree, env.info.dup((env.info.scope != null ? env.info.scope : WriteableScope.create(syms.noSymbol)).dup()));
  1244             try {
  1245                 attribStats(tree.stats, localEnv);
  1246             } finally {
  1247                 localEnv.info.scope.leave();
  1248             }
  1249         }
  1250         result = null;
  1251     }
  1252 
  1253     public void visitDoLoop(JCDoWhileLoop tree) {
  1254         attribStat(tree.body, env.dup(tree));
  1255         attribExpr(tree.cond, env, syms.booleanType);
  1256         result = null;
  1257     }
  1258 
  1259     public void visitWhileLoop(JCWhileLoop tree) {
  1260         attribExpr(tree.cond, env, syms.booleanType);
  1261         attribStat(tree.body, env.dup(tree));
  1262         result = null;
  1263     }
  1264 
  1265     public void visitForLoop(JCForLoop tree) {
  1266         Env<AttrContext> loopEnv =
  1267             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1268         try {
  1269             attribStats(tree.init, loopEnv);
  1270             if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType);
  1271             loopEnv.tree = tree; // before, we were not in loop!
  1272             attribStats(tree.step, loopEnv);
  1273             attribStat(tree.body, loopEnv);
  1274             result = null;
  1275         }
  1276         finally {
  1277             loopEnv.info.scope.leave();
  1278         }
  1279     }
  1280 
  1281     public void visitForeachLoop(JCEnhancedForLoop tree) {
  1282         Env<AttrContext> loopEnv =
  1283             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
  1284         try {
  1285             //the Formal Parameter of a for-each loop is not in the scope when
  1286             //attributing the for-each expression; we mimick this by attributing
  1287             //the for-each expression first (against original scope).
  1288             Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
  1289             attribStat(tree.var, loopEnv);
  1290             chk.checkNonVoid(tree.pos(), exprType);
  1291             Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
  1292             if (elemtype == null) {
  1293                 // or perhaps expr implements Iterable<T>?
  1294                 Type base = types.asSuper(exprType, syms.iterableType.tsym);
  1295                 if (base == null) {
  1296                     log.error(tree.expr.pos(),
  1297                             "foreach.not.applicable.to.type",
  1298                             exprType,
  1299                             diags.fragment("type.req.array.or.iterable"));
  1300                     elemtype = types.createErrorType(exprType);
  1301                 } else {
  1302                     List<Type> iterableParams = base.allparams();
  1303                     elemtype = iterableParams.isEmpty()
  1304                         ? syms.objectType
  1305                         : types.wildUpperBound(iterableParams.head);
  1306                 }
  1307             }
  1308             if (tree.var.sym != null)
  1309                 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
  1310             loopEnv.tree = tree; // before, we were not in loop!
  1311             attribStat(tree.body, loopEnv);
  1312             result = null;
  1313         }
  1314         finally {
  1315             loopEnv.info.scope.leave();
  1316         }
  1317     }
  1318 
  1319     public void visitLabelled(JCLabeledStatement tree) {
  1320         // Check that label is not used in an enclosing statement
  1321         Env<AttrContext> env1 = env;
  1322         while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
  1323             if (env1.tree.hasTag(LABELLED) &&
  1324                 ((JCLabeledStatement) env1.tree).label == tree.label) {
  1325                 log.error(tree.pos(), "label.already.in.use",
  1326                           tree.label);
  1327                 break;
  1328             }
  1329             env1 = env1.next;
  1330         }
  1331 
  1332         attribStat(tree.body, env.dup(tree));
  1333         result = null;
  1334     }
  1335 
  1336     public void visitSwitch(JCSwitch tree) {
  1337         Type seltype = attribExpr(tree.selector, env);
  1338 
  1339         Env<AttrContext> switchEnv =
  1340             env.dup(tree, env.info.dup(env.info.scope.dup()));
  1341 
  1342         try {
  1343 
  1344             boolean enumSwitch = seltype.tsym != null && (seltype.tsym.flags() & Flags.ENUM) != 0;
  1345             boolean stringSwitch = types.isSameType(seltype, syms.stringType);
  1346             if (stringSwitch && !allowStringsInSwitch) {
  1347                 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.selector.pos(), "string.switch.not.supported.in.source", sourceName);
  1348             }
  1349             if (!enumSwitch && !stringSwitch)
  1350                 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType);
  1351 
  1352             // Attribute all cases and
  1353             // check that there are no duplicate case labels or default clauses.
  1354             Set<Object> labels = new HashSet<>(); // The set of case labels.
  1355             boolean hasDefault = false;      // Is there a default label?
  1356             for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
  1357                 JCCase c = l.head;
  1358                 if (c.pat != null) {
  1359                     if (enumSwitch) {
  1360                         Symbol sym = enumConstant(c.pat, seltype);
  1361                         if (sym == null) {
  1362                             log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum");
  1363                         } else if (!labels.add(sym)) {
  1364                             log.error(c.pos(), "duplicate.case.label");
  1365                         }
  1366                     } else {
  1367                         Type pattype = attribExpr(c.pat, switchEnv, seltype);
  1368                         if (!pattype.hasTag(ERROR)) {
  1369                             if (pattype.constValue() == null) {
  1370                                 log.error(c.pat.pos(),
  1371                                           (stringSwitch ? "string.const.req" : "const.expr.req"));
  1372                             } else if (!labels.add(pattype.constValue())) {
  1373                                 log.error(c.pos(), "duplicate.case.label");
  1374                             }
  1375                         }
  1376                     }
  1377                 } else if (hasDefault) {
  1378                     log.error(c.pos(), "duplicate.default.label");
  1379                 } else {
  1380                     hasDefault = true;
  1381                 }
  1382                 if (c == breakTree &&
  1383                         resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK)
  1384                     throw new BreakAttr(env, null);
  1385                 Env<AttrContext> caseEnv =
  1386                     switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup()));
  1387                 boolean baCatched = false;
  1388                 try {
  1389                     attribStats(c.stats, caseEnv);
  1390                 } catch (BreakAttr ba) {
  1391                     baCatched = true;
  1392                     throw ba;
  1393                 } finally {
  1394                     caseEnv.info.scope.leave();
  1395                     if (!baCatched) {
  1396                         addVars(c.stats, switchEnv.info.scope);
  1397                     }
  1398                 }
  1399             }
  1400 
  1401             result = null;
  1402         }
  1403         finally {
  1404             switchEnv.info.scope.leave();
  1405         }
  1406     }
  1407     // where
  1408         /** Add any variables defined in stats to the switch scope. */
  1409         private static void addVars(List<JCStatement> stats, WriteableScope switchScope) {
  1410             for (;stats.nonEmpty(); stats = stats.tail) {
  1411                 JCTree stat = stats.head;
  1412                 if (stat.hasTag(VARDEF) && ((JCVariableDecl) stat).sym != null)
  1413                     switchScope.enter(((JCVariableDecl) stat).sym);
  1414             }
  1415         }
  1416     // where
  1417     /** Return the selected enumeration constant symbol, or null. */
  1418     private Symbol enumConstant(JCTree tree, Type enumType) {
  1419         if (tree.hasTag(IDENT)) {
  1420             JCIdent ident = (JCIdent)tree;
  1421             Name name = ident.name;
  1422             for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
  1423                 if (sym.kind == VAR) {
  1424                     Symbol s = ident.sym = sym;
  1425                     ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
  1426                     ident.type = s.type;
  1427                     return ((s.flags_field & Flags.ENUM) == 0)
  1428                         ? null : s;
  1429                 }
  1430             }
  1431         }
  1432         return null;
  1433     }
  1434 
  1435     public void visitSynchronized(JCSynchronized tree) {
  1436         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
  1437         attribStat(tree.body, env);
  1438         result = null;
  1439     }
  1440 
  1441     public void visitTry(JCTry tree) {
  1442         // Create a new local environment with a local
  1443         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
  1444         try {
  1445             boolean isTryWithResource = tree.resources.nonEmpty();
  1446             // Create a nested environment for attributing the try block if needed
  1447             Env<AttrContext> tryEnv = isTryWithResource ?
  1448                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
  1449                 localEnv;
  1450             try {
  1451                 // Attribute resource declarations
  1452                 for (JCTree resource : tree.resources) {
  1453                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
  1454                         @Override
  1455                         public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1456                             chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details));
  1457                         }
  1458                     };
  1459                     ResultInfo twrResult =
  1460                         new ResultInfo(KindSelector.VAR,
  1461                                        syms.autoCloseableType,
  1462                                        twrContext);
  1463                     if (resource.hasTag(VARDEF)) {
  1464                         attribStat(resource, tryEnv);
  1465                         twrResult.check(resource, resource.type);
  1466 
  1467                         //check that resource type cannot throw InterruptedException
  1468                         checkAutoCloseable(resource.pos(), localEnv, resource.type);
  1469 
  1470                         VarSymbol var = ((JCVariableDecl) resource).sym;
  1471                         var.setData(ElementKind.RESOURCE_VARIABLE);
  1472                     } else {
  1473                         attribTree(resource, tryEnv, twrResult);
  1474                     }
  1475                 }
  1476                 // Attribute body
  1477                 attribStat(tree.body, tryEnv);
  1478             } finally {
  1479                 if (isTryWithResource)
  1480                     tryEnv.info.scope.leave();
  1481             }
  1482 
  1483             // Attribute catch clauses
  1484             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1485                 JCCatch c = l.head;
  1486                 Env<AttrContext> catchEnv =
  1487                     localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
  1488                 try {
  1489                     Type ctype = attribStat(c.param, catchEnv);
  1490                     if (TreeInfo.isMultiCatch(c)) {
  1491                         //multi-catch parameter is implicitly marked as final
  1492                         c.param.sym.flags_field |= FINAL | UNION;
  1493                     }
  1494                     if (c.param.sym.kind == VAR) {
  1495                         c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
  1496                     }
  1497                     chk.checkType(c.param.vartype.pos(),
  1498                                   chk.checkClassType(c.param.vartype.pos(), ctype),
  1499                                   syms.throwableType);
  1500                     attribStat(c.body, catchEnv);
  1501                 } finally {
  1502                     catchEnv.info.scope.leave();
  1503                 }
  1504             }
  1505 
  1506             // Attribute finalizer
  1507             if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
  1508             result = null;
  1509         }
  1510         finally {
  1511             localEnv.info.scope.leave();
  1512         }
  1513     }
  1514 
  1515     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
  1516         if (!resource.isErroneous() &&
  1517             types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
  1518             !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
  1519             Symbol close = syms.noSymbol;
  1520             Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
  1521             try {
  1522                 close = rs.resolveQualifiedMethod(pos,
  1523                         env,
  1524                         types.skipTypeVars(resource, false),
  1525                         names.close,
  1526                         List.nil(),
  1527                         List.nil());
  1528             }
  1529             finally {
  1530                 log.popDiagnosticHandler(discardHandler);
  1531             }
  1532             if (close.kind == MTH &&
  1533                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
  1534                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
  1535                     env.info.lint.isEnabled(LintCategory.TRY)) {
  1536                 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource);
  1537             }
  1538         }
  1539     }
  1540 
  1541     public void visitConditional(JCConditional tree) {
  1542         Type condtype = attribExpr(tree.cond, env, syms.booleanType);
  1543 
  1544         tree.polyKind = (!allowPoly ||
  1545                 pt().hasTag(NONE) && pt() != Type.recoveryType && pt() != Infer.anyPoly ||
  1546                 isBooleanOrNumeric(env, tree)) ?
  1547                 PolyKind.STANDALONE : PolyKind.POLY;
  1548 
  1549         if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
  1550             //this means we are returning a poly conditional from void-compatible lambda expression
  1551             resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void"));
  1552             tree.polyKind = PolyKind.STANDALONE;
  1553         }
  1554 
  1555         ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
  1556                 unknownExprInfo :
  1557                 resultInfo.dup(conditionalContext(resultInfo.checkContext));
  1558 
  1559         Type truetype = attribTree(tree.truepart, env, condInfo);
  1560         Type falsetype = attribTree(tree.falsepart, env, condInfo);
  1561 
  1562         Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt();
  1563         if (condtype.constValue() != null &&
  1564                 truetype.constValue() != null &&
  1565                 falsetype.constValue() != null &&
  1566                 !owntype.hasTag(NONE)) {
  1567             //constant folding
  1568             owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
  1569         }
  1570         result = check(tree, owntype, KindSelector.VAL, resultInfo);
  1571     }
  1572     //where
  1573         private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
  1574             switch (tree.getTag()) {
  1575                 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
  1576                               ((JCLiteral)tree).typetag == BOOLEAN ||
  1577                               ((JCLiteral)tree).typetag == BOT;
  1578                 case LAMBDA: case REFERENCE: return false;
  1579                 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
  1580                 case CONDEXPR:
  1581                     JCConditional condTree = (JCConditional)tree;
  1582                     return isBooleanOrNumeric(env, condTree.truepart) &&
  1583                             isBooleanOrNumeric(env, condTree.falsepart);
  1584                 case APPLY:
  1585                     JCMethodInvocation speculativeMethodTree =
  1586                             (JCMethodInvocation)deferredAttr.attribSpeculative(
  1587                                     tree, env, unknownExprInfo,
  1588                                     argumentAttr.withLocalCacheContext());
  1589                     Symbol msym = TreeInfo.symbol(speculativeMethodTree.meth);
  1590                     Type receiverType = speculativeMethodTree.meth.hasTag(IDENT) ?
  1591                             env.enclClass.type :
  1592                             ((JCFieldAccess)speculativeMethodTree.meth).selected.type;
  1593                     Type owntype = types.memberType(receiverType, msym).getReturnType();
  1594                     return primitiveOrBoxed(owntype);
  1595                 case NEWCLASS:
  1596                     JCExpression className =
  1597                             removeClassParams.translate(((JCNewClass)tree).clazz);
  1598                     JCExpression speculativeNewClassTree =
  1599                             (JCExpression)deferredAttr.attribSpeculative(
  1600                                     className, env, unknownTypeInfo,
  1601                                     argumentAttr.withLocalCacheContext());
  1602                     return primitiveOrBoxed(speculativeNewClassTree.type);
  1603                 default:
  1604                     Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo,
  1605                             argumentAttr.withLocalCacheContext()).type;
  1606                     return primitiveOrBoxed(speculativeType);
  1607             }
  1608         }
  1609         //where
  1610             boolean primitiveOrBoxed(Type t) {
  1611                 return (!t.hasTag(TYPEVAR) && types.unboxedTypeOrType(t).isPrimitive());
  1612             }
  1613 
  1614             TreeTranslator removeClassParams = new TreeTranslator() {
  1615                 @Override
  1616                 public void visitTypeApply(JCTypeApply tree) {
  1617                     result = translate(tree.clazz);
  1618                 }
  1619             };
  1620 
  1621         CheckContext conditionalContext(CheckContext checkContext) {
  1622             return new Check.NestedCheckContext(checkContext) {
  1623                 //this will use enclosing check context to check compatibility of
  1624                 //subexpression against target type; if we are in a method check context,
  1625                 //depending on whether boxing is allowed, we could have incompatibilities
  1626                 @Override
  1627                 public void report(DiagnosticPosition pos, JCDiagnostic details) {
  1628                     enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details));
  1629                 }
  1630             };
  1631         }
  1632 
  1633         /** Compute the type of a conditional expression, after
  1634          *  checking that it exists.  See JLS 15.25. Does not take into
  1635          *  account the special case where condition and both arms
  1636          *  are constants.
  1637          *
  1638          *  @param pos      The source position to be used for error
  1639          *                  diagnostics.
  1640          *  @param thentype The type of the expression's then-part.
  1641          *  @param elsetype The type of the expression's else-part.
  1642          */
  1643         Type condType(DiagnosticPosition pos,
  1644                                Type thentype, Type elsetype) {
  1645             // If same type, that is the result
  1646             if (types.isSameType(thentype, elsetype))
  1647                 return thentype.baseType();
  1648 
  1649             Type thenUnboxed = (thentype.isPrimitive())
  1650                 ? thentype : types.unboxedType(thentype);
  1651             Type elseUnboxed = (elsetype.isPrimitive())
  1652                 ? elsetype : types.unboxedType(elsetype);
  1653 
  1654             // Otherwise, if both arms can be converted to a numeric
  1655             // type, return the least numeric type that fits both arms
  1656             // (i.e. return larger of the two, or return int if one
  1657             // arm is short, the other is char).
  1658             if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) {
  1659                 // If one arm has an integer subrange type (i.e., byte,
  1660                 // short, or char), and the other is an integer constant
  1661                 // that fits into the subrange, return the subrange type.
  1662                 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) &&
  1663                     elseUnboxed.hasTag(INT) &&
  1664                     types.isAssignable(elseUnboxed, thenUnboxed)) {
  1665                     return thenUnboxed.baseType();
  1666                 }
  1667                 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) &&
  1668                     thenUnboxed.hasTag(INT) &&
  1669                     types.isAssignable(thenUnboxed, elseUnboxed)) {
  1670                     return elseUnboxed.baseType();
  1671                 }
  1672 
  1673                 for (TypeTag tag : primitiveTags) {
  1674                     Type candidate = syms.typeOfTag[tag.ordinal()];
  1675                     if (types.isSubtype(thenUnboxed, candidate) &&
  1676                         types.isSubtype(elseUnboxed, candidate)) {
  1677                         return candidate;
  1678                     }
  1679                 }
  1680             }
  1681 
  1682             // Those were all the cases that could result in a primitive
  1683             if (thentype.isPrimitive())
  1684                 thentype = types.boxedClass(thentype).type;
  1685             if (elsetype.isPrimitive())
  1686                 elsetype = types.boxedClass(elsetype).type;
  1687 
  1688             if (types.isSubtype(thentype, elsetype))
  1689                 return elsetype.baseType();
  1690             if (types.isSubtype(elsetype, thentype))
  1691                 return thentype.baseType();
  1692 
  1693             if (thentype.hasTag(VOID) || elsetype.hasTag(VOID)) {
  1694                 log.error(pos, "neither.conditional.subtype",
  1695                           thentype, elsetype);
  1696                 return thentype.baseType();
  1697             }
  1698 
  1699             // both are known to be reference types.  The result is
  1700             // lub(thentype,elsetype). This cannot fail, as it will
  1701             // always be possible to infer "Object" if nothing better.
  1702             return types.lub(thentype.baseType(), elsetype.baseType());
  1703         }
  1704 
  1705     final static TypeTag[] primitiveTags = new TypeTag[]{
  1706         BYTE,
  1707         CHAR,
  1708         SHORT,
  1709         INT,
  1710         LONG,
  1711         FLOAT,
  1712         DOUBLE,
  1713         BOOLEAN,
  1714     };
  1715 
  1716     public void visitIf(JCIf tree) {
  1717         attribExpr(tree.cond, env, syms.booleanType);
  1718         attribStat(tree.thenpart, env);
  1719         if (tree.elsepart != null)
  1720             attribStat(tree.elsepart, env);
  1721         chk.checkEmptyIf(tree);
  1722         result = null;
  1723     }
  1724 
  1725     public void visitExec(JCExpressionStatement tree) {
  1726         //a fresh environment is required for 292 inference to work properly ---
  1727         //see Infer.instantiatePolymorphicSignatureInstance()
  1728         Env<AttrContext> localEnv = env.dup(tree);
  1729         attribExpr(tree.expr, localEnv);
  1730         result = null;
  1731     }
  1732 
  1733     public void visitBreak(JCBreak tree) {
  1734         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1735         result = null;
  1736     }
  1737 
  1738     public void visitContinue(JCContinue tree) {
  1739         tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
  1740         result = null;
  1741     }
  1742     //where
  1743         /** Return the target of a break or continue statement, if it exists,
  1744          *  report an error if not.
  1745          *  Note: The target of a labelled break or continue is the
  1746          *  (non-labelled) statement tree referred to by the label,
  1747          *  not the tree representing the labelled statement itself.
  1748          *
  1749          *  @param pos     The position to be used for error diagnostics
  1750          *  @param tag     The tag of the jump statement. This is either
  1751          *                 Tree.BREAK or Tree.CONTINUE.
  1752          *  @param label   The label of the jump statement, or null if no
  1753          *                 label is given.
  1754          *  @param env     The environment current at the jump statement.
  1755          */
  1756         private JCTree findJumpTarget(DiagnosticPosition pos,
  1757                                     JCTree.Tag tag,
  1758                                     Name label,
  1759                                     Env<AttrContext> env) {
  1760             // Search environments outwards from the point of jump.
  1761             Env<AttrContext> env1 = env;
  1762             LOOP:
  1763             while (env1 != null) {
  1764                 switch (env1.tree.getTag()) {
  1765                     case LABELLED:
  1766                         JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
  1767                         if (label == labelled.label) {
  1768                             // If jump is a continue, check that target is a loop.
  1769                             if (tag == CONTINUE) {
  1770                                 if (!labelled.body.hasTag(DOLOOP) &&
  1771                                         !labelled.body.hasTag(WHILELOOP) &&
  1772                                         !labelled.body.hasTag(FORLOOP) &&
  1773                                         !labelled.body.hasTag(FOREACHLOOP))
  1774                                     log.error(pos, "not.loop.label", label);
  1775                                 // Found labelled statement target, now go inwards
  1776                                 // to next non-labelled tree.
  1777                                 return TreeInfo.referencedStatement(labelled);
  1778                             } else {
  1779                                 return labelled;
  1780                             }
  1781                         }
  1782                         break;
  1783                     case DOLOOP:
  1784                     case WHILELOOP:
  1785                     case FORLOOP:
  1786                     case FOREACHLOOP:
  1787                         if (label == null) return env1.tree;
  1788                         break;
  1789                     case SWITCH:
  1790                         if (label == null && tag == BREAK) return env1.tree;
  1791                         break;
  1792                     case LAMBDA:
  1793                     case METHODDEF:
  1794                     case CLASSDEF:
  1795                         break LOOP;
  1796                     default:
  1797                 }
  1798                 env1 = env1.next;
  1799             }
  1800             if (label != null)
  1801                 log.error(pos, "undef.label", label);
  1802             else if (tag == CONTINUE)
  1803                 log.error(pos, "cont.outside.loop");
  1804             else
  1805                 log.error(pos, "break.outside.switch.loop");
  1806             return null;
  1807         }
  1808 
  1809     public void visitReturn(JCReturn tree) {
  1810         // Check that there is an enclosing method which is
  1811         // nested within than the enclosing class.
  1812         if (env.info.returnResult == null) {
  1813             log.error(tree.pos(), "ret.outside.meth");
  1814         } else {
  1815             // Attribute return expression, if it exists, and check that
  1816             // it conforms to result type of enclosing method.
  1817             if (tree.expr != null) {
  1818                 if (env.info.returnResult.pt.hasTag(VOID)) {
  1819                     env.info.returnResult.checkContext.report(tree.expr.pos(),
  1820                               diags.fragment("unexpected.ret.val"));
  1821                 }
  1822                 attribTree(tree.expr, env, env.info.returnResult);
  1823             } else if (!env.info.returnResult.pt.hasTag(VOID) &&
  1824                     !env.info.returnResult.pt.hasTag(NONE)) {
  1825                 env.info.returnResult.checkContext.report(tree.pos(),
  1826                               diags.fragment("missing.ret.val"));
  1827             }
  1828         }
  1829         result = null;
  1830     }
  1831 
  1832     public void visitThrow(JCThrow tree) {
  1833         Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType);
  1834         if (allowPoly) {
  1835             chk.checkType(tree, owntype, syms.throwableType);
  1836         }
  1837         result = null;
  1838     }
  1839 
  1840     public void visitAssert(JCAssert tree) {
  1841         attribExpr(tree.cond, env, syms.booleanType);
  1842         if (tree.detail != null) {
  1843             chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
  1844         }
  1845         result = null;
  1846     }
  1847 
  1848      /** Visitor method for method invocations.
  1849      *  NOTE: The method part of an application will have in its type field
  1850      *        the return type of the method, not the method's type itself!
  1851      */
  1852     public void visitApply(JCMethodInvocation tree) {
  1853         // The local environment of a method application is
  1854         // a new environment nested in the current one.
  1855         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  1856 
  1857         // The types of the actual method arguments.
  1858         List<Type> argtypes = null;
  1859 
  1860         // The types of the actual method type arguments.
  1861         List<Type> typeargtypes = null;
  1862 
  1863         Name methName = TreeInfo.name(tree.meth);
  1864 
  1865         boolean isConstructorCall =
  1866             methName == names._this || methName == names._super;
  1867 
  1868         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
  1869         if (isConstructorCall) {
  1870             // We are seeing a ...this(...) or ...super(...) call.
  1871             // Check that this is the first statement in a constructor.
  1872             checkFirstConstructorStat(tree, env);
  1873 
  1874             // Record the fact
  1875             // that this is a constructor call (using isSelfCall).
  1876             localEnv.info.isSelfCall = true;
  1877 
  1878             // Attribute arguments, yielding list of argument types.
  1879             KindSelector kind = attribArgs(KindSelector.MTH, tree.args, localEnv, argtypesBuf);
  1880             argtypes = argtypesBuf.toList();
  1881             typeargtypes = attribTypes(tree.typeargs, localEnv);
  1882 
  1883             // Variable `site' points to the class in which the called
  1884             // constructor is defined.
  1885             Type site = env.enclClass.sym.type;
  1886             if (methName == names._super) {
  1887                 if (site == syms.objectType) {
  1888                     log.error(tree.meth.pos(), "no.superclass", site);
  1889                     site = types.createErrorType(syms.objectType);
  1890                 } else {
  1891                     site = types.supertype(site);
  1892                 }
  1893             }
  1894 
  1895             if (site.hasTag(CLASS) || site.hasTag(ERROR)) {
  1896                 Type encl = site.getEnclosingType();
  1897                 while (encl != null && encl.hasTag(TYPEVAR))
  1898                     encl = encl.getUpperBound();
  1899                 if (encl.hasTag(CLASS)) {
  1900                     // we are calling a nested class
  1901 
  1902                     if (tree.meth.hasTag(SELECT)) {
  1903                         JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
  1904 
  1905                         // We are seeing a prefixed call, of the form
  1906                         //     <expr>.super(...).
  1907                         // Check that the prefix expression conforms
  1908                         // to the outer instance type of the class.
  1909                         chk.checkRefType(qualifier.pos(),
  1910                                          attribExpr(qualifier, localEnv,
  1911                                                     encl));
  1912                     } else if (methName == names._super) {
  1913                         // qualifier omitted; check for existence
  1914                         // of an appropriate implicit qualifier.
  1915                         rs.resolveImplicitThis(tree.meth.pos(),
  1916                                                localEnv, site, true);
  1917                     }
  1918                 } else if (tree.meth.hasTag(SELECT)) {
  1919                     log.error(tree.meth.pos(), "illegal.qual.not.icls",
  1920                               site.tsym);
  1921                 }
  1922 
  1923                 // if we're calling a java.lang.Enum constructor,
  1924                 // prefix the implicit String and int parameters
  1925                 if (site.tsym == syms.enumSym)
  1926                     argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
  1927 
  1928                 // Resolve the called constructor under the assumption
  1929                 // that we are referring to a superclass instance of the
  1930                 // current instance (JLS ???).
  1931                 boolean selectSuperPrev = localEnv.info.selectSuper;
  1932                 localEnv.info.selectSuper = true;
  1933                 localEnv.info.pendingResolutionPhase = null;
  1934                 Symbol sym = rs.resolveConstructor(
  1935                     tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
  1936                 localEnv.info.selectSuper = selectSuperPrev;
  1937 
  1938                 // Set method symbol to resolved constructor...
  1939                 TreeInfo.setSymbol(tree.meth, sym);
  1940 
  1941                 // ...and check that it is legal in the current context.
  1942                 // (this will also set the tree's type)
  1943                 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1944                 checkId(tree.meth, site, sym, localEnv,
  1945                         new ResultInfo(kind, mpt));
  1946             }
  1947             result = tree.type = syms.voidType;
  1948         } else {
  1949             // Otherwise, we are seeing a regular method call.
  1950             // Attribute the arguments, yielding list of argument types, ...
  1951             KindSelector kind;
  1952             try {
  1953                 kind = attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
  1954             } catch (BreakAttr bae) {
  1955                 argtypes = argtypesBuf.toList();
  1956                 typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1957                 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1958                 localEnv.info.pendingResolutionPhase = null;
  1959                 attribTree(tree.meth, localEnv, new ResultInfo(KindSelector.VAL_POLY, mpt, resultInfo.checkContext));
  1960                 throw bae;
  1961             }
  1962             argtypes = argtypesBuf.toList();
  1963             typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
  1964 
  1965             // ... and attribute the method using as a prototype a methodtype
  1966             // whose formal argument types is exactly the list of actual
  1967             // arguments (this will also set the method symbol).
  1968             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
  1969             localEnv.info.pendingResolutionPhase = null;
  1970             Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
  1971 
  1972             // Compute the result type.
  1973             Type restype = mtype.getReturnType();
  1974             if (restype.hasTag(WILDCARD))
  1975                 throw new AssertionError(mtype);
  1976 
  1977             Type qualifier = (tree.meth.hasTag(SELECT))
  1978                     ? ((JCFieldAccess) tree.meth).selected.type
  1979                     : env.enclClass.sym.type;
  1980             Symbol msym = TreeInfo.symbol(tree.meth);
  1981             restype = adjustMethodReturnType(msym, qualifier, methName, argtypes, restype);
  1982 
  1983             chk.checkRefTypes(tree.typeargs, typeargtypes);
  1984 
  1985             // Check that value of resulting type is admissible in the
  1986             // current context.  Also, capture the return type
  1987             Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true);
  1988             result = check(tree, capturedRes, KindSelector.VAL, resultInfo);
  1989         }
  1990         chk.validate(tree.typeargs, localEnv);
  1991     }
  1992     //where
  1993         Type adjustMethodReturnType(Symbol msym, Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
  1994             if (msym != null &&
  1995                     msym.owner == syms.objectType.tsym &&
  1996                     methodName == names.getClass &&
  1997                     argtypes.isEmpty()) {
  1998                 // as a special case, x.getClass() has type Class<? extends |X|>
  1999                 return new ClassType(restype.getEnclosingType(),
  2000                         List.of(new WildcardType(types.erasure(qualifierType),
  2001                                 BoundKind.EXTENDS,
  2002                                 syms.boundClass)),
  2003                         restype.tsym,
  2004                         restype.getMetadata());
  2005             } else if (msym != null &&
  2006                     msym.owner == syms.arrayClass &&
  2007                     methodName == names.clone &&
  2008                     types.isArray(qualifierType)) {
  2009                 // as a special case, array.clone() has a result that is
  2010                 // the same as static type of the array being cloned
  2011                 return qualifierType;
  2012             } else {
  2013                 return restype;
  2014             }
  2015         }
  2016 
  2017         /** Check that given application node appears as first statement
  2018          *  in a constructor call.
  2019          *  @param tree   The application node
  2020          *  @param env    The environment current at the application.
  2021          */
  2022         boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) {
  2023             JCMethodDecl enclMethod = env.enclMethod;
  2024             if (enclMethod != null && enclMethod.name == names.init) {
  2025                 JCBlock body = enclMethod.body;
  2026                 if (body.stats.head.hasTag(EXEC) &&
  2027                     ((JCExpressionStatement) body.stats.head).expr == tree)
  2028                     return true;
  2029             }
  2030             log.error(tree.pos(),"call.must.be.first.stmt.in.ctor",
  2031                       TreeInfo.name(tree.meth));
  2032             return false;
  2033         }
  2034 
  2035         /** Obtain a method type with given argument types.
  2036          */
  2037         Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
  2038             MethodType mt = new MethodType(argtypes, restype, List.nil(), syms.methodClass);
  2039             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
  2040         }
  2041 
  2042     public void visitNewClass(final JCNewClass tree) {
  2043         Type owntype = types.createErrorType(tree.type);
  2044 
  2045         // The local environment of a class creation is
  2046         // a new environment nested in the current one.
  2047         Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
  2048 
  2049         // The anonymous inner class definition of the new expression,
  2050         // if one is defined by it.
  2051         JCClassDecl cdef = tree.def;
  2052 
  2053         // If enclosing class is given, attribute it, and
  2054         // complete class name to be fully qualified
  2055         JCExpression clazz = tree.clazz; // Class field following new
  2056         JCExpression clazzid;            // Identifier in class field
  2057         JCAnnotatedType annoclazzid;     // Annotated type enclosing clazzid
  2058         annoclazzid = null;
  2059 
  2060         if (clazz.hasTag(TYPEAPPLY)) {
  2061             clazzid = ((JCTypeApply) clazz).clazz;
  2062             if (clazzid.hasTag(ANNOTATED_TYPE)) {
  2063                 annoclazzid = (JCAnnotatedType) clazzid;
  2064                 clazzid = annoclazzid.underlyingType;
  2065             }
  2066         } else {
  2067             if (clazz.hasTag(ANNOTATED_TYPE)) {
  2068                 annoclazzid = (JCAnnotatedType) clazz;
  2069                 clazzid = annoclazzid.underlyingType;
  2070             } else {
  2071                 clazzid = clazz;
  2072             }
  2073         }
  2074 
  2075         JCExpression clazzid1 = clazzid; // The same in fully qualified form
  2076 
  2077         if (tree.encl != null) {
  2078             // We are seeing a qualified new, of the form
  2079             //    <expr>.new C <...> (...) ...
  2080             // In this case, we let clazz stand for the name of the
  2081             // allocated class C prefixed with the type of the qualifier
  2082             // expression, so that we can
  2083             // resolve it with standard techniques later. I.e., if
  2084             // <expr> has type T, then <expr>.new C <...> (...)
  2085             // yields a clazz T.C.
  2086             Type encltype = chk.checkRefType(tree.encl.pos(),
  2087                                              attribExpr(tree.encl, env));
  2088             // TODO 308: in <expr>.new C, do we also want to add the type annotations
  2089             // from expr to the combined type, or not? Yes, do this.
  2090             clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
  2091                                                  ((JCIdent) clazzid).name);
  2092 
  2093             EndPosTable endPosTable = this.env.toplevel.endPositions;
  2094             endPosTable.storeEnd(clazzid1, tree.getEndPosition(endPosTable));
  2095             if (clazz.hasTag(ANNOTATED_TYPE)) {
  2096                 JCAnnotatedType annoType = (JCAnnotatedType) clazz;
  2097                 List<JCAnnotation> annos = annoType.annotations;
  2098 
  2099                 if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
  2100                     clazzid1 = make.at(tree.pos).
  2101                         TypeApply(clazzid1,
  2102                                   ((JCTypeApply) clazz).arguments);
  2103                 }
  2104 
  2105                 clazzid1 = make.at(tree.pos).
  2106                     AnnotatedType(annos, clazzid1);
  2107             } else if (clazz.hasTag(TYPEAPPLY)) {
  2108                 clazzid1 = make.at(tree.pos).
  2109                     TypeApply(clazzid1,
  2110                               ((JCTypeApply) clazz).arguments);
  2111             }
  2112 
  2113             clazz = clazzid1;
  2114         }
  2115 
  2116         // Attribute clazz expression and store
  2117         // symbol + type back into the attributed tree.
  2118         Type clazztype;
  2119 
  2120         try {
  2121             env.info.isNewClass = true;
  2122             clazztype = TreeInfo.isEnumInit(env.tree) ?
  2123                 attribIdentAsEnumType(env, (JCIdent)clazz) :
  2124                 attribType(clazz, env);
  2125         } finally {
  2126             env.info.isNewClass = false;
  2127         }
  2128 
  2129         clazztype = chk.checkDiamond(tree, clazztype);
  2130         chk.validate(clazz, localEnv);
  2131         if (tree.encl != null) {
  2132             // We have to work in this case to store
  2133             // symbol + type back into the attributed tree.
  2134             tree.clazz.type = clazztype;
  2135             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
  2136             clazzid.type = ((JCIdent) clazzid).sym.type;
  2137             if (annoclazzid != null) {
  2138                 annoclazzid.type = clazzid.type;
  2139             }
  2140             if (!clazztype.isErroneous()) {
  2141                 if (cdef != null && clazztype.tsym.isInterface()) {
  2142                     log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new");
  2143                 } else if (clazztype.tsym.isStatic()) {
  2144                     log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym);
  2145                 }
  2146             }
  2147         } else if (!clazztype.tsym.isInterface() &&
  2148                    clazztype.getEnclosingType().hasTag(CLASS)) {
  2149             // Check for the existence of an apropos outer instance
  2150             rs.resolveImplicitThis(tree.pos(), env, clazztype);
  2151         }
  2152 
  2153         // Attribute constructor arguments.
  2154         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
  2155         final KindSelector pkind =
  2156             attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
  2157         List<Type> argtypes = argtypesBuf.toList();
  2158         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
  2159 
  2160         // If we have made no mistakes in the class type...
  2161         boolean wasError = clazztype.hasTag(ERROR);
  2162         if (clazztype.hasTag(CLASS) || wasError) {
  2163             // Enums may not be instantiated except implicitly
  2164             if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 &&
  2165                 (!env.tree.hasTag(VARDEF) ||
  2166                  (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 ||
  2167                  ((JCVariableDecl) env.tree).init != tree))
  2168                 log.error(tree.pos(), "enum.cant.be.instantiated");
  2169 
  2170             boolean isSpeculativeDiamondInferenceRound = TreeInfo.isDiamond(tree) &&
  2171                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2172             boolean skipNonDiamondPath = false;
  2173             // Check that class is not abstract
  2174             if (cdef == null && !isSpeculativeDiamondInferenceRound && // class body may be nulled out in speculative tree copy
  2175                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
  2176                 log.error(tree.pos(), "abstract.cant.be.instantiated",
  2177                           clazztype.tsym);
  2178                 skipNonDiamondPath = true;
  2179             } else if (cdef != null && clazztype.tsym.isInterface()) {
  2180                 // Check that no constructor arguments are given to
  2181                 // anonymous classes implementing an interface
  2182                 if (!argtypes.isEmpty())
  2183                     log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args");
  2184 
  2185                 if (!typeargtypes.isEmpty())
  2186                     log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs");
  2187 
  2188                 // Error recovery: pretend no arguments were supplied.
  2189                 argtypes = List.nil();
  2190                 typeargtypes = List.nil();
  2191                 skipNonDiamondPath = true;
  2192             }
  2193             if (TreeInfo.isDiamond(tree) && !wasError) {
  2194                 ClassType site = new ClassType(clazztype.getEnclosingType(),
  2195                             clazztype.tsym.type.getTypeArguments(),
  2196                                                clazztype.tsym,
  2197                                                clazztype.getMetadata());
  2198 
  2199                 Env<AttrContext> diamondEnv = localEnv.dup(tree);
  2200                 diamondEnv.info.selectSuper = cdef != null;
  2201                 diamondEnv.info.pendingResolutionPhase = null;
  2202 
  2203                 //if the type of the instance creation expression is a class type
  2204                 //apply method resolution inference (JLS 15.12.2.7). The return type
  2205                 //of the resolved constructor will be a partially instantiated type
  2206                 Symbol constructor = rs.resolveDiamond(tree.pos(),
  2207                             diamondEnv,
  2208                             site,
  2209                             argtypes,
  2210                             typeargtypes);
  2211                 tree.constructor = constructor.baseSymbol();
  2212 
  2213                 final TypeSymbol csym = clazztype.tsym;
  2214                 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes),
  2215                         diamondContext(tree, csym, resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
  2216                 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
  2217                 constructorType = checkId(tree, site,
  2218                         constructor,
  2219                         diamondEnv,
  2220                         diamondResult);
  2221 
  2222                 tree.clazz.type = types.createErrorType(clazztype);
  2223                 if (!constructorType.isErroneous()) {
  2224                     tree.clazz.type = clazz.type = constructorType.getReturnType();
  2225                     tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
  2226                 } else if (errArgs(tree.args)) {
  2227                     Symbol s = null;
  2228                     for (Symbol sym : site.tsym.members().getSymbolsByName(names.init)) {
  2229                         if (s == null || sym.asType().getParameterTypes().isEmpty())
  2230                             s = sym;
  2231                     }
  2232                     if (s != null) {
  2233                         List<Type> atypes = s.asType().getParameterTypes();
  2234                         constructor = rs.resolveDiamond(tree.pos(),
  2235                             diamondEnv,
  2236                             site,
  2237                             atypes,
  2238                             typeargtypes);
  2239                         diamondResult = new ResultInfo(KindSelector.MTH, newMethodTemplate(resultInfo.pt, atypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) {
  2240                             @Override
  2241                             public void report(DiagnosticPosition _unused, JCDiagnostic details) {
  2242                             }
  2243                         });
  2244                         constructorType = checkId(tree, site,
  2245                                 constructor,
  2246                                 diamondEnv,
  2247                                 diamondResult);
  2248                         if (!constructorType.isErroneous())
  2249                             tree.clazz.type = constructorType.getReturnType();
  2250                     }
  2251                 }
  2252                 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
  2253             }
  2254 
  2255             // Resolve the called constructor under the assumption
  2256             // that we are referring to a superclass instance of the
  2257             // current instance (JLS ???).
  2258             else if (!skipNonDiamondPath) {
  2259                 //the following code alters some of the fields in the current
  2260                 //AttrContext - hence, the current context must be dup'ed in
  2261                 //order to avoid downstream failures
  2262                 Env<AttrContext> rsEnv = localEnv.dup(tree);
  2263                 rsEnv.info.selectSuper = cdef != null;
  2264                 rsEnv.info.pendingResolutionPhase = null;
  2265                 tree.constructor = rs.resolveConstructor(
  2266                     tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
  2267                 if (cdef == null) { //do not check twice!
  2268                     tree.constructorType = checkId(tree,
  2269                             clazztype,
  2270                             tree.constructor,
  2271                             rsEnv,
  2272                             new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes), CheckMode.NO_TREE_UPDATE));
  2273                     if (rsEnv.info.lastResolveVarargs())
  2274                         Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);                    
  2275                     Env<AttrContext> enclosing;
  2276                     if (tree.constructor.kind == MTH && tree.constructor.type.isErroneous() && ((enclosing = enter.getEnv(tree.constructor.enclClass())) == null || enclosing.toplevel != env.toplevel)) {
  2277                         log.error(tree, "type.error", tree.constructor);
  2278                     }
  2279                 }
  2280             }
  2281 
  2282             if (cdef != null) {
  2283                 visitAnonymousClassDefinition(tree, clazz, clazztype, cdef, localEnv, argtypes, typeargtypes, pkind);
  2284                 return;
  2285             }
  2286 
  2287             if (tree.constructor != null && tree.constructor.kind == MTH)
  2288                 owntype = wasError ? types.createErrorType(clazztype) : clazztype;
  2289         }
  2290         result = check(tree, owntype, KindSelector.VAL, resultInfo);
  2291         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
  2292         if (tree.constructorType != null && inferenceContext.free(tree.constructorType)) {
  2293             //we need to wait for inference to finish and then replace inference vars in the constructor type
  2294             inferenceContext.addFreeTypeListener(List.of(tree.constructorType),
  2295                     instantiatedContext -> {
  2296                         tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
  2297                     });
  2298         }
  2299         chk.validate(tree.typeargs, localEnv);
  2300     }
  2301     //where
  2302     private boolean errArgs(List<JCExpression> args) {
  2303         for (JCExpression arg : args) {
  2304             if (arg.hasTag(Tag.ERRONEOUS))
  2305                 return true;
  2306         }
  2307         return false;
  2308     }
  2309 
  2310         // where
  2311         private void visitAnonymousClassDefinition(JCNewClass tree, JCExpression clazz, Type clazztype,
  2312                                                    JCClassDecl cdef, Env<AttrContext> localEnv,
  2313                                                    List<Type> argtypes, List<Type> typeargtypes,
  2314                                                    KindSelector pkind) {
  2315             // We are seeing an anonymous class instance creation.
  2316             // In this case, the class instance creation
  2317             // expression
  2318             //
  2319             //    E.new <typeargs1>C<typargs2>(args) { ... }
  2320             //
  2321             // is represented internally as
  2322             //
  2323             //    E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } )  .
  2324             //
  2325             // This expression is then *transformed* as follows:
  2326             //
  2327             // (1) add an extends or implements clause
  2328             // (2) add a constructor.
  2329             //
  2330             // For instance, if C is a class, and ET is the type of E,
  2331             // the expression
  2332             //
  2333             //    E.new <typeargs1>C<typargs2>(args) { ... }
  2334             //
  2335             // is translated to (where X is a fresh name and typarams is the
  2336             // parameter list of the super constructor):
  2337             //
  2338             //   new <typeargs1>X(<*nullchk*>E, args) where
  2339             //     X extends C<typargs2> {
  2340             //       <typarams> X(ET e, args) {
  2341             //         e.<typeargs1>super(args)
  2342             //       }
  2343             //       ...
  2344             //     }
  2345             InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
  2346             final boolean isDiamond = TreeInfo.isDiamond(tree);
  2347             if (isDiamond
  2348                     && ((tree.constructorType != null && inferenceContext.free(tree.constructorType))
  2349                     || (tree.clazz.type != null && inferenceContext.free(tree.clazz.type)))) {
  2350                 final ResultInfo resultInfoForClassDefinition = this.resultInfo;
  2351                 inferenceContext.addFreeTypeListener(List.of(tree.constructorType, tree.clazz.type),
  2352                         instantiatedContext -> {
  2353                             tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
  2354                             tree.clazz.type = clazz.type = instantiatedContext.asInstType(clazz.type);
  2355                             ResultInfo prevResult = this.resultInfo;
  2356                             try {
  2357                                 this.resultInfo = resultInfoForClassDefinition;
  2358                                 visitAnonymousClassDefinition(tree, clazz, clazz.type, cdef,
  2359                                                             localEnv, argtypes, typeargtypes, pkind);
  2360                             } finally {
  2361                                 this.resultInfo = prevResult;
  2362                             }
  2363                         });
  2364             } else {
  2365                 if (isDiamond && clazztype.hasTag(CLASS)) {
  2366                     List<Type> invalidDiamondArgs = chk.checkDiamondDenotable((ClassType)clazztype);
  2367                     if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
  2368                         // One or more types inferred in the previous steps is non-denotable.
  2369                         Fragment fragment = Diamond(clazztype.tsym);
  2370                         log.error(tree.clazz.pos(),
  2371                                 Errors.CantApplyDiamond1(
  2372                                         fragment,
  2373                                         invalidDiamondArgs.size() > 1 ?
  2374                                                 DiamondInvalidArgs(invalidDiamondArgs, fragment) :
  2375                                                 DiamondInvalidArg(invalidDiamondArgs, fragment)));
  2376                     }
  2377                     // For <>(){}, inferred types must also be accessible.
  2378                     for (Type t : clazztype.getTypeArguments()) {
  2379                         rs.checkAccessibleType(env, t);
  2380                     }
  2381                 }
  2382 
  2383                 // If we already errored, be careful to avoid a further avalanche. ErrorType answers
  2384                 // false for isInterface call even when the original type is an interface.
  2385                 boolean implementing = clazztype.tsym.isInterface() ||
  2386                         clazztype.isErroneous() && !clazztype.getOriginalType().hasTag(NONE) && clazztype.getOriginalType().tsym.isInterface();
  2387 
  2388                 if (implementing) {
  2389                     cdef.implementing = List.of(clazz);
  2390                 } else {
  2391                     cdef.extending = clazz;
  2392                 }
  2393 
  2394                 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
  2395                     isSerializable(clazztype)) {
  2396                     localEnv.info.isSerializable = true;
  2397                 }
  2398 
  2399                 attribStat(cdef, localEnv);
  2400 
  2401                 JCExpression clazzCopy = new TreeCopier<JCTree>(make) {
  2402                     @Override
  2403                     public <T extends JCTree> T copy(T tree, JCTree p) {
  2404                         T t = super.copy(tree, p);
  2405                         if (t != null) {
  2406                             t.pos = Position.NOPOS;
  2407                             t.type = tree.type;
  2408                         }
  2409                         return t;
  2410                     }
  2411 
  2412                     @Override public JCTree visitIdentifier(IdentifierTree node, JCTree p) {
  2413                         JCIdent result = (JCIdent) super.visitIdentifier(node, p);
  2414 
  2415                         result.sym = ((JCIdent) node).sym;
  2416 
  2417                         return result;
  2418                     }
  2419 
  2420                     @Override public JCTree visitMemberSelect(MemberSelectTree node, JCTree p) {
  2421                         JCFieldAccess result = (JCFieldAccess) super.visitMemberSelect(node, p);
  2422 
  2423                         result.sym = ((JCFieldAccess) node).sym;
  2424 
  2425                         return result;
  2426                     }
  2427                 }.copy(clazz);
  2428                 if (clazztype.tsym.isInterface()) {
  2429                     cdef.implementing = List.of(clazzCopy);
  2430                 } else {
  2431                     cdef.extending = clazzCopy;
  2432                 }
  2433 
  2434                 List<Type> finalargtypes;
  2435                 // If an outer instance is given,
  2436                 // prefix it to the constructor arguments
  2437                 // "encl" will be cleared in TransTypes
  2438                 if (tree.encl != null && !clazztype.tsym.isInterface()) {
  2439                     tree.args = tree.args.prepend(makeNullCheck(tree.encl));
  2440                     finalargtypes = argtypes.prepend(tree.encl.type);
  2441                 } else {
  2442                     finalargtypes = argtypes;
  2443                 }
  2444 
  2445                 // Reassign clazztype and recompute constructor. As this necessarily involves
  2446                 // another attribution pass for deferred types in the case of <>, replicate
  2447                 // them. Original arguments have right decorations already.
  2448                 if (isDiamond && pkind.contains(KindSelector.POLY)) {
  2449                     finalargtypes = finalargtypes.map(deferredAttr.deferredCopier);
  2450                 }
  2451 
  2452                 clazztype = cdef.sym.type;
  2453                 Symbol sym = tree.constructor = rs.resolveConstructor(
  2454                         tree.pos(), localEnv, clazztype, finalargtypes, typeargtypes);
  2455                 Assert.check(!sym.kind.isResolutionError());
  2456                 tree.constructor = sym;
  2457                 tree.constructorType = checkId(tree,
  2458                         clazztype,
  2459                         tree.constructor,
  2460                         localEnv,
  2461                         new ResultInfo(pkind, newMethodTemplate(syms.voidType, finalargtypes, typeargtypes), CheckMode.NO_TREE_UPDATE));
  2462             }
  2463             Type owntype = (tree.constructor != null && tree.constructor.kind == MTH) ?
  2464                                 clazztype : types.createErrorType(tree.type);
  2465             result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK));
  2466             chk.validate(tree.typeargs, localEnv);
  2467         }
  2468 
  2469         CheckContext diamondContext(JCNewClass clazz, TypeSymbol tsym, CheckContext checkContext) {
  2470             return new Check.NestedCheckContext(checkContext) {
  2471                 @Override
  2472                 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
  2473                     enclosingContext.report(clazz.clazz,
  2474                             diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", tsym), details));
  2475                 }
  2476             };
  2477         }
  2478 
  2479     /** Make an attributed null check tree.
  2480      */
  2481     public JCExpression makeNullCheck(JCExpression arg) {
  2482         // optimization: new Outer() can never be null; skip null check
  2483         if (arg.getTag() == NEWCLASS)
  2484             return arg;
  2485         // optimization: X.this is never null; skip null check
  2486         Name name = TreeInfo.name(arg);
  2487         if (name == names._this || name == names._super) return arg;
  2488 
  2489         JCTree.Tag optag = NULLCHK;
  2490         JCUnary tree = make.at(Position.NOPOS).Unary(optag, arg);
  2491         tree.operator = operators.resolveUnary(arg, optag, arg.type);
  2492         tree.type = arg.type;
  2493         return tree;
  2494     }
  2495 
  2496     public void visitNewArray(JCNewArray tree) {
  2497         Type owntype = types.createErrorType(tree.type);
  2498         Env<AttrContext> localEnv = env.dup(tree);
  2499         Type elemtype;
  2500         if (tree.elemtype != null) {
  2501             elemtype = attribType(tree.elemtype, localEnv);
  2502             chk.validate(tree.elemtype, localEnv);
  2503             owntype = elemtype;
  2504             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  2505                 attribExpr(l.head, localEnv, syms.intType);
  2506                 owntype = new ArrayType(owntype, syms.arrayClass);
  2507             }
  2508         } else {
  2509             // we are seeing an untyped aggregate { ... }
  2510             // this is allowed only if the prototype is an array
  2511             if (pt().hasTag(ARRAY)) {
  2512                 elemtype = types.elemtype(pt());
  2513             } else {
  2514                 if (!pt().hasTag(ERROR)) {
  2515                     log.error(tree.pos(), "illegal.initializer.for.type",
  2516                               pt());
  2517                 }
  2518                 elemtype = types.createErrorType(pt());
  2519             }
  2520         }
  2521         if (tree.elems != null) {
  2522             attribExprs(tree.elems, localEnv, elemtype);
  2523             owntype = new ArrayType(elemtype, syms.arrayClass);
  2524         }
  2525         if (!types.isReifiable(elemtype))
  2526             log.error(tree.pos(), "generic.array.creation");
  2527         result = check(tree, owntype, KindSelector.VAL, resultInfo);
  2528     }
  2529 
  2530     /*
  2531      * A lambda expression can only be attributed when a target-type is available.
  2532      * In addition, if the target-type is that of a functional interface whose
  2533      * descriptor contains inference variables in argument position the lambda expression
  2534      * is 'stuck' (see DeferredAttr).
  2535      */
  2536     @Override
  2537     public void visitLambda(final JCLambda that) {
  2538         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2539             if (pt().hasTag(NONE)) {
  2540                 //lambda only allowed in assignment or method invocation/cast context
  2541                 log.error(that.pos(), "unexpected.lambda");
  2542             }
  2543         }
  2544         //create an environment for attribution of the lambda expression
  2545         final Env<AttrContext> localEnv = lambdaEnv(that, env);
  2546         boolean needsRecovery = resultInfo != recoveryInfo &&
  2547                 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
  2548         Type currentTarget = null;
  2549         try {
  2550             if (needsRecovery && isSerializable(pt())) {
  2551                 localEnv.info.isSerializable = true;
  2552                 localEnv.info.isLambda = true;
  2553             }
  2554             List<Type> explicitParamTypes = null;
  2555             if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
  2556                 //attribute lambda parameters
  2557                 attribStats(that.params, localEnv);
  2558                 explicitParamTypes = TreeInfo.types(that.params);
  2559             }
  2560 
  2561             if (pt().hasTag(NONE) && pt() != Type.recoveryType) {
  2562                 resultInfo = recoveryInfo;
  2563             }
  2564             TargetInfo targetInfo = getTargetInfo(that, resultInfo, explicitParamTypes);
  2565             currentTarget = targetInfo.target;
  2566             Type lambdaType = targetInfo.descriptor;
  2567 
  2568             if (currentTarget.isErroneous()) {
  2569                 result = that.type = currentTarget;
  2570                 return;
  2571             }
  2572 
  2573             setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext);
  2574 
  2575             if (lambdaType.hasTag(FORALL)) {
  2576                 //lambda expression target desc cannot be a generic method
  2577                 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
  2578                         lambdaType, kindName(currentTarget.tsym), currentTarget.tsym));
  2579                 result = that.type = types.createErrorType(pt());
  2580                 return;
  2581             }
  2582 
  2583             if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
  2584                 //add param type info in the AST
  2585                 List<Type> actuals = lambdaType.getParameterTypes();
  2586                 List<JCVariableDecl> params = that.params;
  2587 
  2588                 boolean arityMismatch = false;
  2589 
  2590                 while (params.nonEmpty()) {
  2591                     if (actuals.isEmpty()) {
  2592                         //not enough actuals to perform lambda parameter inference
  2593                         arityMismatch = true;
  2594                     }
  2595                     //reset previously set info
  2596                     Type argType = arityMismatch ?
  2597                             syms.errType :
  2598                             actuals.head;
  2599                     params.head.vartype = make.at(Position.NOPOS).Type(argType);
  2600                     params.head.sym = null;
  2601                     actuals = actuals.isEmpty() ?
  2602                             actuals :
  2603                             actuals.tail;
  2604                     params = params.tail;
  2605                 }
  2606 
  2607                 //attribute lambda parameters
  2608                 attribStats(that.params, localEnv);
  2609 
  2610                 if (arityMismatch) {
  2611                     resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda"));
  2612                         result = that.type = types.createErrorType(currentTarget);
  2613                         return;
  2614                 }
  2615             }
  2616 
  2617             //from this point on, no recovery is needed; if we are in assignment context
  2618             //we will be able to attribute the whole lambda body, regardless of errors;
  2619             //if we are in a 'check' method context, and the lambda is not compatible
  2620             //with the target-type, it will be recovered anyway in Attr.checkId
  2621             needsRecovery = false;
  2622 
  2623             ResultInfo bodyResultInfo = localEnv.info.returnResult =
  2624                     lambdaBodyResult(that, lambdaType, resultInfo);
  2625 
  2626             if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
  2627                 attribTree(that.getBody(), localEnv, bodyResultInfo);
  2628             } else {
  2629                 JCBlock body = (JCBlock)that.body;
  2630                 if (body == breakTree &&
  2631                         resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
  2632                     throw new BreakAttr(copyEnv(localEnv), null);
  2633                 }
  2634                 attribStats(body.stats, localEnv);
  2635             }
  2636 
  2637             result = check(that, currentTarget, KindSelector.VAL, resultInfo);
  2638 
  2639             boolean isSpeculativeRound =
  2640                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  2641 
  2642             preFlow(that);
  2643             flow.analyzeLambda(env, that, make, isSpeculativeRound);
  2644 
  2645             that.type = currentTarget; //avoids recovery at this stage
  2646             checkLambdaCompatible(that, lambdaType, resultInfo.checkContext);
  2647 
  2648             if (!isSpeculativeRound) {
  2649                 //add thrown types as bounds to the thrown types free variables if needed:
  2650                 if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) {
  2651                     List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make);
  2652                     List<Type> thrownTypes = resultInfo.checkContext.inferenceContext().asUndetVars(lambdaType.getThrownTypes());
  2653 
  2654                     chk.unhandled(inferredThrownTypes, thrownTypes);
  2655 
  2656                     //18.2.5: "In addition, for all j (1 <= j <= n), the constraint reduces to the bound throws Ej"
  2657                     thrownTypes.stream()
  2658                             .filter(t -> t.hasTag(UNDETVAR))
  2659                             .forEach(t -> ((UndetVar)t).setThrow());
  2660                 }
  2661 
  2662                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget);
  2663             }
  2664             result = check(that, currentTarget, KindSelector.VAL, resultInfo);
  2665         } catch (Types.FunctionDescriptorLookupError ex) {
  2666             JCDiagnostic cause = ex.getDiagnostic();
  2667             resultInfo.checkContext.report(that, cause);
  2668             result = that.type = types.createErrorType(pt());
  2669             return;
  2670         } catch (BreakAttr ba) {
  2671             if (currentTarget != null) {
  2672                 check(that, currentTarget, KindSelector.VAL, resultInfo);
  2673             }
  2674             needsRecovery = false;
  2675             throw ba;
  2676         } catch (Throwable t) {
  2677             //when an unexpected exception happens, avoid attempts to attribute the same tree again
  2678             //as that would likely cause the same exception again.
  2679             needsRecovery = false;
  2680             throw t;
  2681         } finally {
  2682             localEnv.info.scope.leave();
  2683             if (needsRecovery) {
  2684                 attribTree(that, env, recoveryInfo);
  2685             }
  2686         }
  2687     }
  2688     //where
  2689         class TargetInfo {
  2690             Type target;
  2691             Type descriptor;
  2692 
  2693             public TargetInfo(Type target, Type descriptor) {
  2694                 this.target = target;
  2695                 this.descriptor = descriptor;
  2696             }
  2697         }
  2698 
  2699         TargetInfo getTargetInfo(JCPolyExpression that, ResultInfo resultInfo, List<Type> explicitParamTypes) {
  2700             Type lambdaType;
  2701             Type currentTarget = resultInfo.pt;
  2702             if (resultInfo.pt != Type.recoveryType) {
  2703                 /* We need to adjust the target. If the target is an
  2704                  * intersection type, for example: SAM & I1 & I2 ...
  2705                  * the target will be updated to SAM
  2706                  */
  2707                 currentTarget = targetChecker.visit(currentTarget, that);
  2708                 if (explicitParamTypes != null) {
  2709                     currentTarget = infer.instantiateFunctionalInterface(that,
  2710                             currentTarget, explicitParamTypes, resultInfo.checkContext);
  2711                 }
  2712                 currentTarget = types.removeWildcards(currentTarget);
  2713                 lambdaType = types.findDescriptorType(currentTarget);
  2714             } else {
  2715                 currentTarget = Type.recoveryType;
  2716                 lambdaType = fallbackDescriptorType(that);
  2717             }
  2718             if (that.hasTag(LAMBDA) && lambdaType.hasTag(FORALL)) {
  2719                 //lambda expression target desc cannot be a generic method
  2720                 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target",
  2721                         lambdaType, kindName(currentTarget.tsym), currentTarget.tsym));
  2722                 currentTarget = types.createErrorType(pt());
  2723             }
  2724             return new TargetInfo(currentTarget, lambdaType);
  2725         }
  2726 
  2727         void preFlow(JCLambda tree) {
  2728             new PostAttrAnalyzer() {
  2729                 @Override
  2730                 public void scan(JCTree tree) {
  2731                     if (tree == null ||
  2732                             (tree.type != null &&
  2733                             tree.type == Type.stuckType)) {
  2734                         //don't touch stuck expressions!
  2735                         return;
  2736                     }
  2737                     super.scan(tree);
  2738                 }
  2739             }.scan(tree);
  2740         }
  2741 
  2742         Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
  2743 
  2744             @Override
  2745             public Type visitClassType(ClassType t, DiagnosticPosition pos) {
  2746                 return t.isIntersection() ?
  2747                         visitIntersectionClassType((IntersectionClassType)t, pos) : t;
  2748             }
  2749 
  2750             public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
  2751                 Symbol desc = types.findDescriptorSymbol(makeNotionalInterface(ict));
  2752                 Type target = null;
  2753                 for (Type bound : ict.getExplicitComponents()) {
  2754                     TypeSymbol boundSym = bound.tsym;
  2755                     if (types.isFunctionalInterface(boundSym) &&
  2756                             types.findDescriptorSymbol(boundSym) == desc) {
  2757                         target = bound;
  2758                     } else if (!boundSym.isInterface() || (boundSym.flags() & ANNOTATION) != 0) {
  2759                         //bound must be an interface
  2760                         reportIntersectionError(pos, "not.an.intf.component", boundSym);
  2761                     }
  2762                 }
  2763                 return target != null ?
  2764                         target :
  2765                         ict.getExplicitComponents().head; //error recovery
  2766             }
  2767 
  2768             private TypeSymbol makeNotionalInterface(IntersectionClassType ict) {
  2769                 ListBuffer<Type> targs = new ListBuffer<>();
  2770                 ListBuffer<Type> supertypes = new ListBuffer<>();
  2771                 for (Type i : ict.interfaces_field) {
  2772                     if (i.isParameterized()) {
  2773                         targs.appendList(i.tsym.type.allparams());
  2774                     }
  2775                     supertypes.append(i.tsym.type);
  2776                 }
  2777                 IntersectionClassType notionalIntf = types.makeIntersectionType(supertypes.toList());
  2778                 notionalIntf.allparams_field = targs.toList();
  2779                 notionalIntf.tsym.flags_field |= INTERFACE;
  2780                 return notionalIntf.tsym;
  2781             }
  2782 
  2783             private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) {
  2784                 resultInfo.checkContext.report(pos, diags.fragment("bad.intersection.target.for.functional.expr",
  2785                         diags.fragment(key, args)));
  2786             }
  2787         };
  2788 
  2789         private Type fallbackDescriptorType(JCExpression tree) {
  2790             switch (tree.getTag()) {
  2791                 case LAMBDA:
  2792                     JCLambda lambda = (JCLambda)tree;
  2793                     List<Type> argtypes = List.nil();
  2794                     for (JCVariableDecl param : lambda.params) {
  2795                         argtypes = param.vartype != null ?
  2796                                 argtypes.append(param.vartype.type) :
  2797                                 argtypes.append(syms.errType);
  2798                     }
  2799                     return new MethodType(argtypes, Type.recoveryType,
  2800                             List.of(syms.throwableType), syms.methodClass);
  2801                 case REFERENCE:
  2802                     return new MethodType(List.nil(), Type.recoveryType,
  2803                             List.of(syms.throwableType), syms.methodClass);
  2804                 default:
  2805                     Assert.error("Cannot get here!");
  2806             }
  2807             return null;
  2808         }
  2809 
  2810         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
  2811                 final InferenceContext inferenceContext, final Type... ts) {
  2812             checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
  2813         }
  2814 
  2815         private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
  2816                 final InferenceContext inferenceContext, final List<Type> ts) {
  2817             if (inferenceContext.free(ts)) {
  2818                 inferenceContext.addFreeTypeListener(ts,
  2819                         solvedContext -> checkAccessibleTypes(pos, env, solvedContext, solvedContext.asInstTypes(ts)));
  2820             } else {
  2821                 for (Type t : ts) {
  2822                     rs.checkAccessibleType(env, t);
  2823                 }
  2824             }
  2825         }
  2826 
  2827         /**
  2828          * Lambda/method reference have a special check context that ensures
  2829          * that i.e. a lambda return type is compatible with the expected
  2830          * type according to both the inherited context and the assignment
  2831          * context.
  2832          */
  2833         class FunctionalReturnContext extends Check.NestedCheckContext {
  2834 
  2835             FunctionalReturnContext(CheckContext enclosingContext) {
  2836                 super(enclosingContext);
  2837             }
  2838 
  2839             @Override
  2840             public boolean compatible(Type found, Type req, Warner warn) {
  2841                 //return type must be compatible in both current context and assignment context
  2842                 return chk.basicHandler.compatible(inferenceContext().asUndetVar(found), inferenceContext().asUndetVar(req), warn);
  2843             }
  2844 
  2845             @Override
  2846             public void report(DiagnosticPosition pos, JCDiagnostic details) {
  2847                 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details));
  2848             }
  2849         }
  2850 
  2851         class ExpressionLambdaReturnContext extends FunctionalReturnContext {
  2852 
  2853             JCExpression expr;
  2854             boolean expStmtExpected;
  2855 
  2856             ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
  2857                 super(enclosingContext);
  2858                 this.expr = expr;
  2859             }
  2860 
  2861             @Override
  2862             public void report(DiagnosticPosition pos, JCDiagnostic details) {
  2863                 if (expStmtExpected) {
  2864                     enclosingContext.report(pos, diags.fragment(Fragments.StatExprExpected));
  2865                 } else {
  2866                     super.report(pos, details);
  2867                 }
  2868             }
  2869 
  2870             @Override
  2871             public boolean compatible(Type found, Type req, Warner warn) {
  2872                 //a void return is compatible with an expression statement lambda
  2873                 if (req.hasTag(VOID)) {
  2874                     expStmtExpected = true;
  2875                     return TreeInfo.isExpressionStatement(expr, names);
  2876                 } else {
  2877                     return super.compatible(found, req, warn);
  2878                 }
  2879             }
  2880         }
  2881 
  2882         ResultInfo lambdaBodyResult(JCLambda that, Type descriptor, ResultInfo resultInfo) {
  2883             FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
  2884                     new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
  2885                     new FunctionalReturnContext(resultInfo.checkContext);
  2886 
  2887             return descriptor.getReturnType() == Type.recoveryType ?
  2888                     recoveryInfo :
  2889                     new ResultInfo(KindSelector.VAL,
  2890                             descriptor.getReturnType(), funcContext);
  2891         }
  2892 
  2893         /**
  2894         * Lambda compatibility. Check that given return types, thrown types, parameter types
  2895         * are compatible with the expected functional interface descriptor. This means that:
  2896         * (i) parameter types must be identical to those of the target descriptor; (ii) return
  2897         * types must be compatible with the return type of the expected descriptor.
  2898         */
  2899         void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) {
  2900             Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
  2901 
  2902             //return values have already been checked - but if lambda has no return
  2903             //values, we must ensure that void/value compatibility is correct;
  2904             //this amounts at checking that, if a lambda body can complete normally,
  2905             //the descriptor's return type must be void
  2906             if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
  2907                     !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
  2908                 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda",
  2909                         diags.fragment("missing.ret.val", returnType)));
  2910             }
  2911 
  2912             List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes());
  2913             if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
  2914                 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
  2915             }
  2916         }
  2917 
  2918         /* Map to hold 'fake' clinit methods. If a lambda is used to initialize a
  2919          * static field and that lambda has type annotations, these annotations will
  2920          * also be stored at these fake clinit methods.
  2921          *
  2922          * LambdaToMethod also use fake clinit methods so they can be reused.
  2923          * Also as LTM is a phase subsequent to attribution, the methods from
  2924          * clinits can be safely removed by LTM to save memory.
  2925          */
  2926         private Map<ClassSymbol, MethodSymbol> clinits = new HashMap<>();
  2927 
  2928         public MethodSymbol removeClinit(ClassSymbol sym) {
  2929             return clinits.remove(sym);
  2930         }
  2931 
  2932         /* This method returns an environment to be used to attribute a lambda
  2933          * expression.
  2934          *
  2935          * The owner of this environment is a method symbol. If the current owner
  2936          * is not a method, for example if the lambda is used to initialize
  2937          * a field, then if the field is:
  2938          *
  2939          * - an instance field, we use the first constructor.
  2940          * - a static field, we create a fake clinit method.
  2941          */
  2942         public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
  2943             Env<AttrContext> lambdaEnv;
  2944             Symbol owner = env.info.scope.owner;
  2945             if (owner.kind == VAR && owner.owner.kind == TYP) {
  2946                 //field initializer
  2947                 ClassSymbol enclClass = owner.enclClass();
  2948                 Symbol newScopeOwner = env.info.scope.owner;
  2949                 /* if the field isn't static, then we can get the first constructor
  2950                  * and use it as the owner of the environment. This is what
  2951                  * LTM code is doing to look for type annotations so we are fine.
  2952                  */
  2953                 if ((owner.flags() & STATIC) == 0) {
  2954                     for (Symbol s : enclClass.members_field.getSymbolsByName(names.init)) {
  2955                         newScopeOwner = s;
  2956                         break;
  2957                     }
  2958                 } else {
  2959                     /* if the field is static then we need to create a fake clinit
  2960                      * method, this method can later be reused by LTM.
  2961                      */
  2962                     MethodSymbol clinit = clinits.get(enclClass);
  2963                     if (clinit == null) {
  2964                         Type clinitType = new MethodType(List.nil(),
  2965                                 syms.voidType, List.nil(), syms.methodClass);
  2966                         clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE,
  2967                                 names.clinit, clinitType, enclClass);
  2968                         clinit.params = List.nil();
  2969                         clinits.put(enclClass, clinit);
  2970                     }
  2971                     newScopeOwner = clinit;
  2972                 }
  2973                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(newScopeOwner)));
  2974             } else {
  2975                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
  2976             }
  2977             return lambdaEnv;
  2978         }
  2979 
  2980     @Override
  2981     public void visitReference(final JCMemberReference that) {
  2982         if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
  2983             if (pt().hasTag(NONE)) {
  2984                 //method reference only allowed in assignment or method invocation/cast context
  2985                 log.error(that.pos(), "unexpected.mref");
  2986             }
  2987             result = that.type = types.createErrorType(pt());
  2988             return;
  2989         }
  2990         final Env<AttrContext> localEnv = env.dup(that);
  2991         try {
  2992             //attribute member reference qualifier - if this is a constructor
  2993             //reference, the expected kind must be a type
  2994             Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
  2995 
  2996             if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
  2997                 exprType = chk.checkConstructorRefType(that.expr, exprType);
  2998                 if (!exprType.isErroneous() &&
  2999                     exprType.isRaw() &&
  3000                     that.typeargs != null) {
  3001                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  3002                         diags.fragment("mref.infer.and.explicit.params"));
  3003                     exprType = types.createErrorType(exprType);
  3004                 }
  3005             }
  3006 
  3007             if (exprType.isErroneous()) {
  3008                 //if the qualifier expression contains problems,
  3009                 //give up attribution of method reference
  3010                 result = that.type = exprType;
  3011                 return;
  3012             }
  3013 
  3014             if (TreeInfo.isStaticSelector(that.expr, names)) {
  3015                 //if the qualifier is a type, validate it; raw warning check is
  3016                 //omitted as we don't know at this stage as to whether this is a
  3017                 //raw selector (because of inference)
  3018                 chk.validate(that.expr, env, false);
  3019             } else {
  3020                 Symbol lhsSym = TreeInfo.symbol(that.expr);
  3021                 localEnv.info.selectSuper = lhsSym != null && lhsSym.name == names._super;
  3022             }
  3023             //attrib type-arguments
  3024             List<Type> typeargtypes = List.nil();
  3025             if (that.typeargs != null) {
  3026                 typeargtypes = attribTypes(that.typeargs, localEnv);
  3027             }
  3028 
  3029             boolean isTargetSerializable =
  3030                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
  3031                     isSerializable(pt());
  3032             TargetInfo targetInfo = getTargetInfo(that, resultInfo, null);
  3033             Type currentTarget = targetInfo.target;
  3034             Type desc = targetInfo.descriptor;
  3035 
  3036             setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
  3037             List<Type> argtypes = desc.getParameterTypes();
  3038             Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
  3039 
  3040             if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
  3041                 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
  3042             }
  3043 
  3044             Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
  3045             List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
  3046             try {
  3047                 refResult = rs.resolveMemberReference(localEnv, that, that.expr.type,
  3048                         that.name, argtypes, typeargtypes, referenceCheck,
  3049                         resultInfo.checkContext.inferenceContext(), rs.basicReferenceChooser);
  3050             } finally {
  3051                 resultInfo.checkContext.inferenceContext().rollback(saved_undet);
  3052             }
  3053 
  3054             Symbol refSym = refResult.fst;
  3055             Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
  3056 
  3057             /** this switch will need to go away and be replaced by the new RESOLUTION_TARGET testing
  3058              *  JDK-8075541
  3059              */
  3060             if (refSym.kind != MTH) {
  3061                 boolean targetError;
  3062                 switch (refSym.kind) {
  3063                     case ABSENT_MTH:
  3064                     case MISSING_ENCL:
  3065                         targetError = false;
  3066                         break;
  3067                     case WRONG_MTH:
  3068                     case WRONG_MTHS:
  3069                     case AMBIGUOUS:
  3070                     case HIDDEN:
  3071                     case STATICERR:
  3072                         targetError = true;
  3073                         break;
  3074                     default:
  3075                         Assert.error("unexpected result kind " + refSym.kind);
  3076                         targetError = false;
  3077                 }
  3078 
  3079                 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol()).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
  3080                                 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
  3081 
  3082                 JCDiagnostic.DiagnosticType diagKind = targetError ?
  3083                         JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR;
  3084 
  3085                 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that,
  3086                         "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag);
  3087 
  3088                 if (targetError && currentTarget == Type.recoveryType) {
  3089                     //a target error doesn't make sense during recovery stage
  3090                     //as we don't know what actual parameter types are
  3091                     result = that.type = currentTarget;
  3092                     return;
  3093                 } else {
  3094                     if (targetError) {
  3095                         resultInfo.checkContext.report(that, diag);
  3096                     } else {
  3097                         log.report(diag);
  3098                     }
  3099                     result = that.type = types.createErrorType(currentTarget);
  3100                     return;
  3101                 }
  3102             }
  3103 
  3104             that.sym = refSym.baseSymbol();
  3105             that.kind = lookupHelper.referenceKind(that.sym);
  3106             that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
  3107 
  3108             if (desc.getReturnType() == Type.recoveryType) {
  3109                 // stop here
  3110                 result = that.type = currentTarget;
  3111                 return;
  3112             }
  3113 
  3114             if (!env.info.isSpeculative && that.getMode() == JCMemberReference.ReferenceMode.NEW) {
  3115                 Type enclosingType = exprType.getEnclosingType();
  3116                 if (enclosingType != null && enclosingType.hasTag(CLASS)) {
  3117                     // Check for the existence of an apropriate outer instance
  3118                     rs.resolveImplicitThis(that.pos(), env, exprType);
  3119                 }
  3120             }
  3121 
  3122             if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
  3123 
  3124                 if (that.getMode() == ReferenceMode.INVOKE &&
  3125                         TreeInfo.isStaticSelector(that.expr, names) &&
  3126                         that.kind.isUnbound() &&
  3127                         !desc.getParameterTypes().head.isParameterized()) {
  3128                     chk.checkRaw(that.expr, localEnv);
  3129                 }
  3130 
  3131                 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
  3132                         exprType.getTypeArguments().nonEmpty()) {
  3133                     //static ref with class type-args
  3134                     log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()),
  3135                             diags.fragment("static.mref.with.targs"));
  3136                     result = that.type = types.createErrorType(currentTarget);
  3137                     return;
  3138                 }
  3139 
  3140                 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
  3141                     // Check that super-qualified symbols are not abstract (JLS)
  3142                     rs.checkNonAbstract(that.pos(), that.sym);
  3143                 }
  3144 
  3145                 if (isTargetSerializable) {
  3146                     chk.checkAccessFromSerializableElement(that, true);
  3147                 }
  3148             }
  3149 
  3150             ResultInfo checkInfo =
  3151                     resultInfo.dup(newMethodTemplate(
  3152                         desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
  3153                         that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes),
  3154                         new FunctionalReturnContext(resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
  3155 
  3156             Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
  3157 
  3158             if (that.kind.isUnbound() &&
  3159                     resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
  3160                 //re-generate inference constraints for unbound receiver
  3161                 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) {
  3162                     //cannot happen as this has already been checked - we just need
  3163                     //to regenerate the inference constraints, as that has been lost
  3164                     //as a result of the call to inferenceContext.save()
  3165                     Assert.error("Can't get here");
  3166                 }
  3167             }
  3168 
  3169             if (!refType.isErroneous()) {
  3170                 refType = types.createMethodTypeWithReturn(refType,
  3171                         adjustMethodReturnType(refSym, lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
  3172             }
  3173 
  3174             //go ahead with standard method reference compatibility check - note that param check
  3175             //is a no-op (as this has been taken care during method applicability)
  3176             boolean isSpeculativeRound =
  3177                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
  3178 
  3179             that.type = currentTarget; //avoids recovery at this stage
  3180             checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
  3181             if (!isSpeculativeRound) {
  3182                 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget);
  3183             }
  3184             result = check(that, currentTarget, KindSelector.VAL, resultInfo);
  3185         } catch (Types.FunctionDescriptorLookupError ex) {
  3186             JCDiagnostic cause = ex.getDiagnostic();
  3187             resultInfo.checkContext.report(that, cause);
  3188             result = that.type = types.createErrorType(pt());
  3189             return;
  3190         }
  3191     }
  3192     //where
  3193         ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
  3194             //if this is a constructor reference, the expected kind must be a type
  3195             return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ?
  3196                                   KindSelector.VAL_TYP : KindSelector.TYP,
  3197                                   Type.noType);
  3198         }
  3199 
  3200 
  3201     @SuppressWarnings("fallthrough")
  3202     void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
  3203         InferenceContext inferenceContext = checkContext.inferenceContext();
  3204         Type returnType = inferenceContext.asUndetVar(descriptor.getReturnType());
  3205 
  3206         Type resType;
  3207         switch (tree.getMode()) {
  3208             case NEW:
  3209                 if (!tree.expr.type.isRaw()) {
  3210                     resType = tree.expr.type;
  3211                     break;
  3212                 }
  3213             default:
  3214                 resType = refType.getReturnType();
  3215         }
  3216 
  3217         Type incompatibleReturnType = resType;
  3218 
  3219         if (returnType.hasTag(VOID)) {
  3220             incompatibleReturnType = null;
  3221         }
  3222 
  3223         if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
  3224             if (resType.isErroneous() ||
  3225                     new FunctionalReturnContext(checkContext).compatible(resType, returnType,
  3226                             checkContext.checkWarner(tree, resType, returnType))) {
  3227                 incompatibleReturnType = null;
  3228             }
  3229         }
  3230 
  3231         if (incompatibleReturnType != null) {
  3232             checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref",
  3233                     diags.fragment("inconvertible.types", resType, descriptor.getReturnType())));
  3234         } else {
  3235             if (inferenceContext.free(refType)) {
  3236                 // we need to wait for inference to finish and then replace inference vars in the referent type
  3237                 inferenceContext.addFreeTypeListener(List.of(refType),
  3238                         instantiatedContext -> {
  3239                             tree.referentType = instantiatedContext.asInstType(refType);
  3240                         });
  3241             } else {
  3242                 tree.referentType = refType;
  3243             }
  3244         }
  3245 
  3246         if (!speculativeAttr) {
  3247             List<Type> thrownTypes = inferenceContext.asUndetVars(descriptor.getThrownTypes());
  3248             if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) {
  3249                 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes());
  3250             }
  3251             //18.2.5: "In addition, for all j (1 <= j <= n), the constraint reduces to the bound throws Ej"
  3252             thrownTypes.stream()
  3253                     .filter(t -> t.hasTag(UNDETVAR))
  3254                     .forEach(t -> ((UndetVar)t).setThrow());
  3255         }
  3256     }
  3257 
  3258     /**
  3259      * Set functional type info on the underlying AST. Note: as the target descriptor
  3260      * might contain inference variables, we might need to register an hook in the
  3261      * current inference context.
  3262      */
  3263     private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
  3264             final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
  3265         if (checkContext.inferenceContext().free(descriptorType)) {
  3266             checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType),
  3267                     inferenceContext -> setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
  3268                     inferenceContext.asInstType(primaryTarget), checkContext));
  3269         } else {
  3270             ListBuffer<Type> targets = new ListBuffer<>();
  3271             if (pt.hasTag(CLASS)) {
  3272                 if (pt.isCompound()) {
  3273                     targets.append(types.removeWildcards(primaryTarget)); //this goes first
  3274                     for (Type t : ((IntersectionClassType)pt()).interfaces_field) {
  3275                         if (t != primaryTarget) {
  3276                             targets.append(types.removeWildcards(t));
  3277                         }
  3278                     }
  3279                 } else {
  3280                     targets.append(types.removeWildcards(primaryTarget));
  3281                 }
  3282             }
  3283             fExpr.targets = targets.toList();
  3284             if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
  3285                     pt != Type.recoveryType) {
  3286                 //check that functional interface class is well-formed
  3287                 try {
  3288                     /* Types.makeFunctionalInterfaceClass() may throw an exception
  3289                      * when it's executed post-inference. See the listener code
  3290                      * above.
  3291                      */
  3292                     ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
  3293                             names.empty, List.of(fExpr.targets.head), ABSTRACT);
  3294                     if (csym != null) {
  3295                         chk.checkImplementations(env.tree, csym, csym);
  3296                         try {
  3297                             //perform an additional functional interface check on the synthetic class,
  3298                             //as there may be spurious errors for raw targets - because of existing issues
  3299                             //with membership and inheritance (see JDK-8074570).
  3300                             csym.flags_field |= INTERFACE;
  3301                             types.findDescriptorType(csym.type);
  3302                         } catch (FunctionDescriptorLookupError err) {
  3303                             resultInfo.checkContext.report(fExpr,
  3304                                     diags.fragment(Fragments.NoSuitableFunctionalIntfInst(fExpr.targets.head)));
  3305                         }
  3306                     }
  3307                 } catch (Types.FunctionDescriptorLookupError ex) {
  3308                     JCDiagnostic cause = ex.getDiagnostic();
  3309                     resultInfo.checkContext.report(env.tree, cause);
  3310                 }
  3311             }
  3312         }
  3313     }
  3314 
  3315     public void visitParens(JCParens tree) {
  3316         Type owntype = attribTree(tree.expr, env, resultInfo);
  3317         result = check(tree, owntype, pkind(), resultInfo);
  3318         Symbol sym = TreeInfo.symbol(tree);
  3319         if (sym != null && sym.kind.matches(KindSelector.TYP_PCK))
  3320             log.error(tree.pos(), "illegal.start.of.type");
  3321     }
  3322 
  3323     public void visitAssign(JCAssign tree) {
  3324         Type owntype = attribTree(tree.lhs, env.dup(tree), varAssignmentInfo);
  3325         Type capturedType = capture(owntype);
  3326         attribExpr(tree.rhs, env, owntype);
  3327         result = check(tree, capturedType, KindSelector.VAL, resultInfo);
  3328     }
  3329 
  3330     public void visitAssignop(JCAssignOp tree) {
  3331         // Attribute arguments.
  3332         Type owntype = attribTree(tree.lhs, env, varAssignmentInfo);
  3333         Type operand = attribExpr(tree.rhs, env);
  3334         // Find operator.
  3335         Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), owntype, operand);
  3336         if (operator != operators.noOpSymbol &&
  3337                 !owntype.isErroneous() &&
  3338                 !operand.isErroneous()) {
  3339             chk.checkDivZero(tree.rhs.pos(), operator, operand);
  3340             chk.checkCastable(tree.rhs.pos(),
  3341                               operator.type.getReturnType(),
  3342                               owntype);
  3343         }
  3344         result = check(tree, owntype, KindSelector.VAL, resultInfo);
  3345     }
  3346 
  3347     public void visitUnary(JCUnary tree) {
  3348         // Attribute arguments.
  3349         Type argtype = (tree.getTag().isIncOrDecUnaryOp())
  3350             ? attribTree(tree.arg, env, varAssignmentInfo)
  3351             : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
  3352 
  3353         // Find operator.
  3354         Symbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype);
  3355         Type owntype = types.createErrorType(tree.type);
  3356         if (operator != operators.noOpSymbol &&
  3357                 !argtype.isErroneous()) {
  3358             owntype = (tree.getTag().isIncOrDecUnaryOp())
  3359                 ? tree.arg.type
  3360                 : operator.type.getReturnType();
  3361             int opc = ((OperatorSymbol)operator).opcode;
  3362 
  3363             // If the argument is constant, fold it.
  3364             if (argtype.constValue() != null) {
  3365                 Type ctype = cfolder.fold1(opc, argtype);
  3366                 if (ctype != null) {
  3367                     owntype = cfolder.coerce(ctype, owntype);
  3368                 }
  3369             }
  3370         }
  3371         result = check(tree, owntype, KindSelector.VAL, resultInfo);
  3372     }
  3373 
  3374     public void visitBinary(JCBinary tree) {
  3375         boolean baCatched = false;
  3376         try {
  3377             // Attribute arguments.
  3378             Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
  3379             Type right = chk.checkNonVoid(tree.rhs.pos(), attribExpr(tree.rhs, env));
  3380             // Find operator.
  3381             Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag(), left, right);
  3382             Type owntype = types.createErrorType(tree.type);
  3383             if (operator != operators.noOpSymbol &&
  3384                     !left.isErroneous() &&
  3385                     !right.isErroneous()) {
  3386                 owntype = operator.type.getReturnType();
  3387                 int opc = ((OperatorSymbol)operator).opcode;
  3388                 // If both arguments are constants, fold them.
  3389                 if (left.constValue() != null && right.constValue() != null) {
  3390                     Type ctype = cfolder.fold2(opc, left, right);
  3391                     if (ctype != null) {
  3392                         owntype = cfolder.coerce(ctype, owntype);
  3393                     }
  3394                 }
  3395 
  3396                 // Check that argument types of a reference ==, != are
  3397                 // castable to each other, (JLS 15.21).  Note: unboxing
  3398                 // comparisons will not have an acmp* opc at this point.
  3399                 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
  3400                     if (!types.isCastable(left, right, new Warner(tree.pos()))) {
  3401                         log.error(tree.pos(), "incomparable.types", left, right);
  3402                     }
  3403                 }
  3404 
  3405                 chk.checkDivZero(tree.rhs.pos(), operator, right);
  3406             }
  3407             result = check(tree, owntype, KindSelector.VAL, resultInfo);
  3408         } catch (BreakAttr ba) {
  3409             baCatched = true;
  3410             throw ba;
  3411         } finally {
  3412             if ((baCatched || result.isErroneous()) && tree.hasTag(BITAND)) {
  3413                 //error recovery
  3414                 TreeScanner treeCleaner = new TreeScanner() {
  3415                     public void scan(JCTree node) {
  3416                         super.scan(node);
  3417                         if (node != null)
  3418                             node.type = null;
  3419                     }
  3420                     public void visitClassDef(JCClassDecl node) {
  3421                         node.sym = null;
  3422                         super.visitClassDef(node);
  3423                     }
  3424                     public void visitMethodDef(JCMethodDecl node) {
  3425                         node.sym = null;
  3426                         super.visitMethodDef(node);
  3427                     }
  3428                     public void visitVarDef(JCVariableDecl node) {
  3429                         node.sym = null;
  3430                         super.visitVarDef(node);
  3431                     }
  3432                     public void visitNewClass(JCNewClass node) {
  3433                         node.constructor = null;
  3434                         super.visitNewClass(node);
  3435                     }
  3436                     public void visitAssignop(JCAssignOp node) {
  3437                         node.operator = null;
  3438                         super.visitAssignop(node);
  3439                     }
  3440                     public void visitUnary(JCUnary node) {
  3441                         node.operator = null;
  3442                         super.visitUnary(node);
  3443                     }
  3444                     public void visitBinary(JCBinary node) {
  3445                         node.operator = null;
  3446                         super.visitBinary(node);
  3447                     }
  3448                     public void visitSelect(JCFieldAccess node) {
  3449                         node.sym = null;
  3450                         super.visitSelect(node);
  3451                     }
  3452                     public void visitIdent(JCIdent node) {
  3453                         node.sym = null;
  3454                         super.visitIdent(node);
  3455                     }
  3456                     public void visitAnnotation(JCAnnotation node) {
  3457                         node.attribute = null;
  3458                         super.visitAnnotation(node);
  3459                     }
  3460                 };
  3461                 // attribTree will change the 'result', save it:
  3462                 Type saveResult = this.result;
  3463                 treeCleaner.scan(tree.lhs);
  3464                 attribTree(tree.lhs, env, new ResultInfo(KindSelector.VAL_TYP , Type.noType));
  3465                 treeCleaner.scan(tree.rhs);
  3466                 attribTree(tree.rhs, env, new ResultInfo(KindSelector.VAL_TYP , Type.noType));                
  3467                 this.result = saveResult;
  3468                 List<JCExpression> bounds = collectIntersectionBounds(tree);
  3469                 if (bounds != null) {
  3470                     Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
  3471                     try {
  3472                         Type owntype = checkIntersection(tree, bounds);
  3473                         if (!owntype.isErroneous()) {
  3474                             tree.type = result = owntype;
  3475                         }
  3476                     } finally {
  3477                         log.popDiagnosticHandler(discardHandler);
  3478                     }
  3479                 }
  3480             }
  3481         }
  3482     }
  3483     
  3484     private List<JCExpression> collectIntersectionBounds(JCTree tree) {
  3485         if (tree.hasTag(BITAND)) {
  3486             List<JCExpression> left = collectIntersectionBounds(((JCBinary)tree).lhs);
  3487             if (left != null) {
  3488                 List<JCExpression> right = collectIntersectionBounds(((JCBinary)tree).rhs);
  3489                 if (right != null) {
  3490                     return left.appendList(right);
  3491                 }
  3492             }
  3493         } else if (tree instanceof JCExpression && tree.type != null) {
  3494             return List.of((JCExpression)tree);
  3495         }
  3496         return null;
  3497     }
  3498 
  3499     public void visitTypeCast(final JCTypeCast tree) {
  3500         Type clazztype = attribType(tree.clazz, env);
  3501         chk.validate(tree.clazz, env, false);
  3502         //a fresh environment is required for 292 inference to work properly ---
  3503         //see Infer.instantiatePolymorphicSignatureInstance()
  3504         Env<AttrContext> localEnv = env.dup(tree);
  3505         //should we propagate the target type?
  3506         final ResultInfo castInfo;
  3507         JCExpression expr = TreeInfo.skipParens(tree.expr);
  3508         boolean isPoly = expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE);
  3509         if (isPoly) {
  3510             //expression is a poly - we need to propagate target type info
  3511             castInfo = new ResultInfo(KindSelector.VAL, clazztype,
  3512                                       new Check.NestedCheckContext(resultInfo.checkContext) {
  3513                 @Override
  3514                 public boolean compatible(Type found, Type req, Warner warn) {
  3515                     return types.isCastable(found, req, warn);
  3516                 }
  3517             });
  3518         } else {
  3519             //standalone cast - target-type info is not propagated
  3520             castInfo = unknownExprInfo;
  3521         }
  3522         Type exprtype = attribTree(tree.expr, localEnv, castInfo);
  3523         Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  3524         if (exprtype.constValue() != null)
  3525             owntype = cfolder.coerce(exprtype, owntype);
  3526         result = check(tree, capture(owntype), KindSelector.VAL, resultInfo);
  3527         if (!isPoly)
  3528             chk.checkRedundantCast(localEnv, tree);
  3529     }
  3530 
  3531     public void visitTypeTest(JCInstanceOf tree) {
  3532         Type exprtype = chk.checkNullOrRefType(
  3533                 tree.expr.pos(), attribExpr(tree.expr, env));
  3534         Type clazztype = attribType(tree.clazz, env);
  3535         if (!clazztype.hasTag(TYPEVAR)) {
  3536             clazztype = chk.checkClassOrArrayType(tree.clazz.pos(), clazztype);
  3537         }
  3538         if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
  3539             log.error(tree.clazz.pos(), "illegal.generic.type.for.instof");
  3540             clazztype = types.createErrorType(clazztype);
  3541         }
  3542         chk.validate(tree.clazz, env, false);
  3543         chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
  3544         result = check(tree, syms.booleanType, KindSelector.VAL, resultInfo);
  3545     }
  3546 
  3547     public void visitIndexed(JCArrayAccess tree) {
  3548         Type owntype = types.createErrorType(tree.type);
  3549         Type atype = attribExpr(tree.indexed, env);
  3550         attribExpr(tree.index, env, syms.intType);
  3551         if (types.isArray(atype))
  3552             owntype = types.elemtype(atype);
  3553         else if (!atype.hasTag(ERROR))
  3554             log.error(tree.pos(), "array.req.but.found", atype);
  3555         if (!pkind().contains(KindSelector.VAL))
  3556             owntype = capture(owntype);
  3557         result = check(tree, owntype, KindSelector.VAR, resultInfo);
  3558     }
  3559 
  3560     public void visitIdent(JCIdent tree) {
  3561         Symbol sym;
  3562 
  3563         // Find symbol
  3564         if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
  3565             // If we are looking for a method, the prototype `pt' will be a
  3566             // method type with the type of the call's arguments as parameters.
  3567             env.info.pendingResolutionPhase = null;
  3568             sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
  3569         } else if (tree.sym != null && tree.sym.kind != VAR) {
  3570             sym = tree.sym;
  3571         } else {
  3572             sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
  3573         }
  3574         tree.sym = sym;
  3575 
  3576         // (1) Also find the environment current for the class where
  3577         //     sym is defined (`symEnv').
  3578         // Only for pre-tiger versions (1.4 and earlier):
  3579         // (2) Also determine whether we access symbol out of an anonymous
  3580         //     class in a this or super call.  This is illegal for instance
  3581         //     members since such classes don't carry a this$n link.
  3582         //     (`noOuterThisPath').
  3583         Env<AttrContext> symEnv = env;
  3584         boolean noOuterThisPath = false;
  3585         if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
  3586             sym.kind.matches(KindSelector.VAL_MTH) &&
  3587             sym.owner.kind == TYP &&
  3588             tree.name != names._this && tree.name != names._super) {
  3589 
  3590             // Find environment in which identifier is defined.
  3591             while (symEnv.outer != null &&
  3592                    !sym.isMemberOf(symEnv.enclClass.sym, types)) {
  3593                 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0)
  3594                     noOuterThisPath = false;
  3595                 symEnv = symEnv.outer;
  3596             }
  3597         }
  3598 
  3599         // If symbol is a variable, ...
  3600         if (sym.kind == VAR) {
  3601             VarSymbol v = (VarSymbol)sym;
  3602 
  3603             // ..., evaluate its initializer, if it has one, and check for
  3604             // illegal forward reference.
  3605             checkInit(tree, env, v, false);
  3606 
  3607             // If we are expecting a variable (as opposed to a value), check
  3608             // that the variable is assignable in the current environment.
  3609             if (KindSelector.ASG.subset(pkind()))
  3610                 checkAssignable(tree.pos(), v, null, env);
  3611         }
  3612 
  3613         // In a constructor body,
  3614         // if symbol is a field or instance method, check that it is
  3615         // not accessed before the supertype constructor is called.
  3616         if ((symEnv.info.isSelfCall || noOuterThisPath) &&
  3617             sym.kind.matches(KindSelector.VAL_MTH) &&
  3618             sym.owner.kind == TYP &&
  3619             (sym.flags() & STATIC) == 0) {
  3620             chk.earlyRefError(tree.pos(), sym.kind == VAR ?
  3621                                           sym : thisSym(tree.pos(), env));
  3622         }
  3623         Env<AttrContext> env1 = env;
  3624         if (sym.kind != ERR && sym.kind != TYP &&
  3625             sym.owner != null && sym.owner != env1.enclClass.sym) {
  3626             // If the found symbol is inaccessible, then it is
  3627             // accessed through an enclosing instance.  Locate this
  3628             // enclosing instance:
  3629             while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
  3630                 env1 = env1.outer;
  3631         }
  3632 
  3633         if (env.info.isSerializable) {
  3634             chk.checkAccessFromSerializableElement(tree, env.info.isLambda);
  3635         }
  3636 
  3637         result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
  3638     }
  3639 
  3640     public void visitSelect(JCFieldAccess tree) {
  3641         // Determine the expected kind of the qualifier expression.
  3642         KindSelector skind = KindSelector.NIL;
  3643         if (tree.name == names._this || tree.name == names._super ||
  3644                 tree.name == names._class)
  3645         {
  3646             skind = KindSelector.TYP;
  3647         } else if (tree.name == names.error) {
  3648             skind = KindSelector.ERR;
  3649         } else {
  3650             if (pkind().contains(KindSelector.PCK))
  3651                 skind = KindSelector.of(skind, KindSelector.PCK);
  3652             if (pkind().contains(KindSelector.TYP))
  3653                 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
  3654             if (pkind().contains(KindSelector.VAL_MTH))
  3655                 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
  3656         }
  3657 
  3658         // Attribute the qualifier expression, and determine its symbol (if any).
  3659         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
  3660         if (!pkind().contains(KindSelector.TYP_PCK))
  3661             site = capture(site); // Capture field access
  3662 
  3663         // don't allow T.class T[].class, etc
  3664         if (skind == KindSelector.TYP) {
  3665             Type elt = site;
  3666             while (elt.hasTag(ARRAY))
  3667                 elt = ((ArrayType)elt).elemtype;
  3668             if (elt.hasTag(TYPEVAR)) {
  3669                 log.error(tree.pos(), "type.var.cant.be.deref");
  3670                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
  3671                 tree.sym = tree.type.tsym;
  3672                 return ;
  3673             }
  3674         }
  3675 
  3676         // If qualifier symbol is a type or `super', assert `selectSuper'
  3677         // for the selection. This is relevant for determining whether
  3678         // protected symbols are accessible.
  3679         Symbol sitesym = TreeInfo.symbol(tree.selected);
  3680         boolean selectSuperPrev = env.info.selectSuper;
  3681         env.info.selectSuper =
  3682             sitesym != null &&
  3683             sitesym.name == names._super;
  3684 
  3685         // Determine the symbol represented by the selection.
  3686         env.info.pendingResolutionPhase = null;
  3687         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
  3688         if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
  3689             log.error(tree.selected.pos(), "not.encl.class", site.tsym);
  3690             sym = syms.errSymbol;
  3691         }
  3692         if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
  3693             site = capture(site);
  3694             sym = selectSym(tree, sitesym, site, env, resultInfo);
  3695         }
  3696         boolean varArgs = env.info.lastResolveVarargs();
  3697         tree.sym = sym;
  3698 
  3699         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
  3700             site = types.skipTypeVars(site, true);
  3701         }
  3702 
  3703         // If that symbol is a variable, ...
  3704         if (sym.kind == VAR) {
  3705             VarSymbol v = (VarSymbol)sym;
  3706 
  3707             // ..., evaluate its initializer, if it has one, and check for
  3708             // illegal forward reference.
  3709             checkInit(tree, env, v, true);
  3710 
  3711             // If we are expecting a variable (as opposed to a value), check
  3712             // that the variable is assignable in the current environment.
  3713             if (KindSelector.ASG.subset(pkind()))
  3714                 checkAssignable(tree.pos(), v, tree.selected, env);
  3715         }
  3716 
  3717         if (sitesym != null &&
  3718                 sitesym.kind == VAR &&
  3719                 ((VarSymbol)sitesym).isResourceVariable() &&
  3720                 sym.kind == MTH &&
  3721                 sym.name.equals(names.close) &&
  3722                 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) &&
  3723                 env.info.lint.isEnabled(LintCategory.TRY)) {
  3724             log.warning(LintCategory.TRY, tree, "try.explicit.close.call");
  3725         }
  3726 
  3727         // Disallow selecting a type from an expression
  3728         if (isType(sym) && (sitesym == null || !sitesym.kind.matches(KindSelector.TYP_PCK))) {
  3729             tree.type = check(tree.selected, pt(),
  3730                               sitesym == null ?
  3731                                       KindSelector.VAL : sitesym.kind.toSelector(),
  3732                               new ResultInfo(KindSelector.TYP_PCK, pt()));
  3733         }
  3734 
  3735         if (isType(sitesym)) {
  3736             if (sym.name == names._this) {
  3737                 // If `C' is the currently compiled class, check that
  3738                 // C.this' does not appear in a call to a super(...)
  3739                 if (env.info.isSelfCall &&
  3740                     site.tsym == env.enclClass.sym) {
  3741                     chk.earlyRefError(tree.pos(), sym);
  3742                 }
  3743             } else {
  3744                 // Check if type-qualified fields or methods are static (JLS)
  3745                 if ((sym.flags() & STATIC) == 0 &&
  3746                     sym.name != names._super &&
  3747                     (sym.kind == VAR || sym.kind == MTH)) {
  3748                     rs.accessBase(rs.new StaticError(sym),
  3749                               tree.pos(), site, sym.name, true);
  3750                 }
  3751             }
  3752             if (!allowStaticInterfaceMethods && sitesym.isInterface() &&
  3753                     sym.isStatic() && sym.kind == MTH) {
  3754                 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.pos(), "static.intf.method.invoke.not.supported.in.source", sourceName);
  3755             }
  3756         } else if (sym.kind != ERR &&
  3757                    (sym.flags() & STATIC) != 0 &&
  3758                    sym.name != names._class) {
  3759             // If the qualified item is not a type and the selected item is static, report
  3760             // a warning. Make allowance for the class of an array type e.g. Object[].class)
  3761             chk.warnStatic(tree, "static.not.qualified.by.type",
  3762                            sym.kind.kindName(), sym.owner);
  3763         }
  3764 
  3765         // If we are selecting an instance member via a `super', ...
  3766         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
  3767 
  3768             // Check that super-qualified symbols are not abstract (JLS)
  3769             rs.checkNonAbstract(tree.pos(), sym);
  3770 
  3771             if (site.isRaw()) {
  3772                 // Determine argument types for site.
  3773                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
  3774                 if (site1 != null) site = site1;
  3775             }
  3776         }
  3777 
  3778         if (env.info.isSerializable) {
  3779             chk.checkAccessFromSerializableElement(tree, env.info.isLambda);
  3780         }
  3781 
  3782         env.info.selectSuper = selectSuperPrev;
  3783         result = checkId(tree, site, sym, env, resultInfo);
  3784     }
  3785     //where
  3786         /** Determine symbol referenced by a Select expression,
  3787          *
  3788          *  @param tree   The select tree.
  3789          *  @param site   The type of the selected expression,
  3790          *  @param env    The current environment.
  3791          *  @param resultInfo The current result.
  3792          */
  3793         private Symbol selectSym(JCFieldAccess tree,
  3794                                  Symbol location,
  3795                                  Type site,
  3796                                  Env<AttrContext> env,
  3797                                  ResultInfo resultInfo) {
  3798             DiagnosticPosition pos = tree.pos();
  3799             Name name = tree.name;
  3800             switch (site.getTag()) {
  3801             case PACKAGE:
  3802                 return rs.accessBase(
  3803                     rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind),
  3804                     pos, location, site, name, true);
  3805             case ARRAY:
  3806             case CLASS:
  3807                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
  3808                     return rs.resolveQualifiedMethod(
  3809                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
  3810                 } else if (name == names._this || name == names._super) {
  3811                     return rs.resolveSelf(pos, env, site.tsym, name);
  3812                 } else if (name == names._class) {
  3813                     // In this case, we have already made sure in
  3814                     // visitSelect that qualifier expression is a type.
  3815                     Type t = syms.classType;
  3816                     List<Type> typeargs = List.of(types.erasure(site));
  3817                     t = new ClassType(t.getEnclosingType(), typeargs, t.tsym);
  3818                     return new VarSymbol(
  3819                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3820                 } else {
  3821                     // We are seeing a plain identifier as selector.
  3822                     Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind);
  3823                         sym = rs.accessBase(sym, pos, location, site, name, true);
  3824                     return sym;
  3825                 }
  3826             case WILDCARD:
  3827                 throw new AssertionError(tree);
  3828             case TYPEVAR:
  3829                 // Normally, site.getUpperBound() shouldn't be null.
  3830                 // It should only happen during memberEnter/attribBase
  3831                 // when determining the super type which *must* beac
  3832                 // done before attributing the type variables.  In
  3833                 // other words, we are seeing this illegal program:
  3834                 // class B<T> extends A<T.foo> {}
  3835                 Symbol sym = (site.getUpperBound() != null)
  3836                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
  3837                     : null;
  3838                 if (sym == null) {
  3839                     log.error(pos, "type.var.cant.be.deref");
  3840                     return syms.errSymbol;
  3841                 } else {
  3842                     Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ?
  3843                         rs.new AccessError(env, site, sym) :
  3844                                 sym;
  3845                     rs.accessBase(sym2, pos, location, site, name, true);
  3846                     return sym;
  3847                 }
  3848             case ERROR:
  3849                 // preserve identifier names through errors
  3850                 return types.createErrorType(name, site.tsym, site).tsym;
  3851             default:
  3852                 // The qualifier expression is of a primitive type -- only
  3853                 // .class is allowed for these.
  3854                 if (name == names._class) {
  3855                     // In this case, we have already made sure in Select that
  3856                     // qualifier expression is a type.
  3857                     Type t = syms.classType;
  3858                     Type arg = types.boxedClass(site).type;
  3859                     t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym);
  3860                     return new VarSymbol(
  3861                         STATIC | PUBLIC | FINAL, names._class, t, site.tsym);
  3862                 } else {
  3863                     log.error(pos, "cant.deref", site);
  3864                     return syms.errSymbol;
  3865                 }
  3866             }
  3867         }
  3868 
  3869         /** Determine type of identifier or select expression and check that
  3870          *  (1) the referenced symbol is not deprecated
  3871          *  (2) the symbol's type is safe (@see checkSafe)
  3872          *  (3) if symbol is a variable, check that its type and kind are
  3873          *      compatible with the prototype and protokind.
  3874          *  (4) if symbol is an instance field of a raw type,
  3875          *      which is being assigned to, issue an unchecked warning if its
  3876          *      type changes under erasure.
  3877          *  (5) if symbol is an instance method of a raw type, issue an
  3878          *      unchecked warning if its argument types change under erasure.
  3879          *  If checks succeed:
  3880          *    If symbol is a constant, return its constant type
  3881          *    else if symbol is a method, return its result type
  3882          *    otherwise return its type.
  3883          *  Otherwise return errType.
  3884          *
  3885          *  @param tree       The syntax tree representing the identifier
  3886          *  @param site       If this is a select, the type of the selected
  3887          *                    expression, otherwise the type of the current class.
  3888          *  @param sym        The symbol representing the identifier.
  3889          *  @param env        The current environment.
  3890          *  @param resultInfo    The expected result
  3891          */
  3892         Type checkId(JCTree tree,
  3893                      Type site,
  3894                      Symbol sym,
  3895                      Env<AttrContext> env,
  3896                      ResultInfo resultInfo) {
  3897             return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
  3898                     checkMethodId(tree, site, sym, env, resultInfo) :
  3899                     checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
  3900         }
  3901 
  3902         Type checkMethodId(JCTree tree,
  3903                      Type site,
  3904                      Symbol sym,
  3905                      Env<AttrContext> env,
  3906                      ResultInfo resultInfo) {
  3907             boolean isPolymorhicSignature =
  3908                 (sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) != 0;
  3909             return isPolymorhicSignature ?
  3910                     checkSigPolyMethodId(tree, site, sym, env, resultInfo) :
  3911                     checkMethodIdInternal(tree, site, sym, env, resultInfo);
  3912         }
  3913 
  3914         Type checkSigPolyMethodId(JCTree tree,
  3915                      Type site,
  3916                      Symbol sym,
  3917                      Env<AttrContext> env,
  3918                      ResultInfo resultInfo) {
  3919             //recover original symbol for signature polymorphic methods
  3920             checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo);
  3921             env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC;
  3922             return sym.type;
  3923         }
  3924 
  3925         Type checkMethodIdInternal(JCTree tree,
  3926                      Type site,
  3927                      Symbol sym,
  3928                      Env<AttrContext> env,
  3929                      ResultInfo resultInfo) {
  3930             if (resultInfo.pkind.contains(KindSelector.POLY)) {
  3931                 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase));
  3932                 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo);
  3933                 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
  3934                 return owntype;
  3935             } else {
  3936                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
  3937             }
  3938         }
  3939 
  3940         Type checkIdInternal(JCTree tree,
  3941                      Type site,
  3942                      Symbol sym,
  3943                      Type pt,
  3944                      Env<AttrContext> env,
  3945                      ResultInfo resultInfo) {
  3946             if (pt.isErroneous()) {
  3947                 return tree.type = types.createErrorType(site);
  3948             }
  3949             Type owntype; // The computed type of this identifier occurrence.
  3950             switch (sym.kind) {
  3951             case TYP:
  3952                 // For types, the computed type equals the symbol's type,
  3953                 // except for two situations:
  3954                 owntype = sym.type;
  3955                 if (owntype.hasTag(CLASS)) {
  3956                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
  3957                     Type ownOuter = owntype.getEnclosingType();
  3958 
  3959                     // (a) If the symbol's type is parameterized, erase it
  3960                     // because no type parameters were given.
  3961                     // We recover generic outer type later in visitTypeApply.
  3962                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
  3963                         owntype = types.erasure(owntype);
  3964                     }
  3965 
  3966                     // (b) If the symbol's type is an inner class, then
  3967                     // we have to interpret its outer type as a superclass
  3968                     // of the site type. Example:
  3969                     //
  3970                     // class Tree<A> { class Visitor { ... } }
  3971                     // class PointTree extends Tree<Point> { ... }
  3972                     // ...PointTree.Visitor...
  3973                     //
  3974                     // Then the type of the last expression above is
  3975                     // Tree<Point>.Visitor.
  3976                     else if (ownOuter != null && ownOuter.hasTag(CLASS) && site != ownOuter) {
  3977                         Type normOuter = site;
  3978                         if (normOuter.hasTag(CLASS)) {
  3979                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
  3980                         }
  3981                         if (normOuter == null) // perhaps from an import
  3982                             normOuter = types.erasure(ownOuter);
  3983                         if (normOuter != ownOuter)
  3984                             owntype = new ClassType(
  3985                                 normOuter, List.nil(), owntype.tsym,
  3986                                 owntype.getMetadata());
  3987                     }
  3988                 }
  3989                 break;
  3990             case VAR:
  3991                 VarSymbol v = (VarSymbol)sym;
  3992                 // Test (4): if symbol is an instance field of a raw type,
  3993                 // which is being assigned to, issue an unchecked warning if
  3994                 // its type changes under erasure.
  3995                 if (KindSelector.ASG.subset(pkind()) &&
  3996                     v.owner.kind == TYP &&
  3997                     (v.flags() & STATIC) == 0 &&
  3998                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  3999                     Type s = types.asOuterSuper(site, v.owner);
  4000                     if (s != null &&
  4001                         s.isRaw() &&
  4002                         !types.isSameType(v.type, v.erasure(types))) {
  4003                         chk.warnUnchecked(tree.pos(),
  4004                                           "unchecked.assign.to.var",
  4005                                           v, s);
  4006                     }
  4007                 }
  4008                 // The computed type of a variable is the type of the
  4009                 // variable symbol, taken as a member of the site type.
  4010                 owntype = (sym.owner.kind == TYP &&
  4011                            sym.name != names._this && sym.name != names._super)
  4012                     ? types.memberType(site, sym)
  4013                     : sym.type;
  4014 
  4015                 // If the variable is a constant, record constant value in
  4016                 // computed type.
  4017                 if (v.getConstValue() != null && isStaticReference(tree))
  4018                     owntype = owntype.constType(v.getConstValue());
  4019 
  4020                 if (resultInfo.pkind == KindSelector.VAL) {
  4021                     owntype = capture(owntype); // capture "names as expressions"
  4022                 }
  4023                 break;
  4024             case MTH: {
  4025                 owntype = checkMethod(site, sym,
  4026                         new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext, resultInfo.checkMode),
  4027                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
  4028                         resultInfo.pt.getTypeArguments());
  4029                 break;
  4030             }
  4031             case PCK: case ERR:
  4032                 owntype = sym.type;
  4033                 break;
  4034             default:
  4035                 throw new AssertionError("unexpected kind: " + sym.kind +
  4036                                          " in tree " + tree);
  4037             }
  4038 
  4039             // Emit a `deprecation' warning if symbol is deprecated.
  4040             // (for constructors (but not for constructor references), the error
  4041             // was given when the constructor was resolved)
  4042 
  4043             if (sym.name != names.init || tree.hasTag(REFERENCE)) {
  4044                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
  4045                 chk.checkSunAPI(tree.pos(), sym);
  4046                 chk.checkProfile(tree.pos(), sym);
  4047             }
  4048             
  4049             Env<AttrContext> enclosing;            
  4050             if (owntype.isErroneous() && (sym.kind == MTH || sym.kind == VAR) && ((enclosing = enter.getEnv(sym.enclClass())) == null || enclosing.toplevel != env.toplevel)) {
  4051                 log.error(tree, "type.error", sym);
  4052             }
  4053 
  4054             // If symbol is a variable, check that its type and
  4055             // kind are compatible with the prototype and protokind.
  4056             return check(tree, owntype, sym.kind.toSelector(), resultInfo);
  4057         }
  4058 
  4059         /** Check that variable is initialized and evaluate the variable's
  4060          *  initializer, if not yet done. Also check that variable is not
  4061          *  referenced before it is defined.
  4062          *  @param tree    The tree making up the variable reference.
  4063          *  @param env     The current environment.
  4064          *  @param v       The variable's symbol.
  4065          */
  4066         private void checkInit(JCTree tree,
  4067                                Env<AttrContext> env,
  4068                                VarSymbol v,
  4069                                boolean onlyWarning) {
  4070             // A forward reference is diagnosed if the declaration position
  4071             // of the variable is greater than the current tree position
  4072             // and the tree and variable definition occur in the same class
  4073             // definition.  Note that writes don't count as references.
  4074             // This check applies only to class and instance
  4075             // variables.  Local variables follow different scope rules,
  4076             // and are subject to definite assignment checking.
  4077             Env<AttrContext> initEnv = enclosingInitEnv(env);
  4078             if (initEnv != null &&
  4079                 (initEnv.info.enclVar == v || v.pos > tree.pos) &&
  4080                 v.owner.kind == TYP &&
  4081                 v.owner == env.info.scope.owner.enclClass() &&
  4082                 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
  4083                 (!env.tree.hasTag(ASSIGN) ||
  4084                  TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
  4085                 String suffix = (initEnv.info.enclVar == v) ?
  4086                                 "self.ref" : "forward.ref";
  4087                 if (!onlyWarning || isStaticEnumField(v)) {
  4088                     log.error(tree.pos(), "illegal." + suffix);
  4089                 } else if (useBeforeDeclarationWarning) {
  4090                     log.warning(tree.pos(), suffix, v);
  4091                 }
  4092             }
  4093 
  4094             v.getConstValue(); // ensure initializer is evaluated
  4095 
  4096             checkEnumInitializer(tree, env, v);
  4097         }
  4098 
  4099         /**
  4100          * Returns the enclosing init environment associated with this env (if any). An init env
  4101          * can be either a field declaration env or a static/instance initializer env.
  4102          */
  4103         Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) {
  4104             while (true) {
  4105                 switch (env.tree.getTag()) {
  4106                     case VARDEF:
  4107                         JCVariableDecl vdecl = (JCVariableDecl)env.tree;
  4108                         if (vdecl.sym != null && vdecl.sym.owner != null && vdecl.sym.owner.kind == TYP) {
  4109                             //field
  4110                             return env;
  4111                         }
  4112                         break;
  4113                     case BLOCK:
  4114                         if (env.next.tree.hasTag(CLASSDEF)) {
  4115                             //instance/static initializer
  4116                             return env;
  4117                         }
  4118                         break;
  4119                     case METHODDEF:
  4120                     case CLASSDEF:
  4121                     case TOPLEVEL:
  4122                         return null;
  4123                 }
  4124                 Assert.checkNonNull(env.next);
  4125                 env = env.next;
  4126             }
  4127         }
  4128 
  4129         /**
  4130          * Check for illegal references to static members of enum.  In
  4131          * an enum type, constructors and initializers may not
  4132          * reference its static members unless they are constant.
  4133          *
  4134          * @param tree    The tree making up the variable reference.
  4135          * @param env     The current environment.
  4136          * @param v       The variable's symbol.
  4137          * @jls  section 8.9 Enums
  4138          */
  4139         private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
  4140             // JLS:
  4141             //
  4142             // "It is a compile-time error to reference a static field
  4143             // of an enum type that is not a compile-time constant
  4144             // (15.28) from constructors, instance initializer blocks,
  4145             // or instance variable initializer expressions of that
  4146             // type. It is a compile-time error for the constructors,
  4147             // instance initializer blocks, or instance variable
  4148             // initializer expressions of an enum constant e to refer
  4149             // to itself or to an enum constant of the same type that
  4150             // is declared to the right of e."
  4151             if (isStaticEnumField(v)) {
  4152                 ClassSymbol enclClass = env.info.scope.owner.enclClass();
  4153 
  4154                 if (enclClass == null || enclClass.owner == null)
  4155                     return;
  4156 
  4157                 // See if the enclosing class is the enum (or a
  4158                 // subclass thereof) declaring v.  If not, this
  4159                 // reference is OK.
  4160                 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
  4161                     return;
  4162 
  4163                 // If the reference isn't from an initializer, then
  4164                 // the reference is OK.
  4165                 if (!Resolve.isInitializer(env))
  4166                     return;
  4167 
  4168                 log.error(tree.pos(), "illegal.enum.static.ref");
  4169             }
  4170         }
  4171 
  4172         /** Is the given symbol a static, non-constant field of an Enum?
  4173          *  Note: enum literals should not be regarded as such
  4174          */
  4175         private boolean isStaticEnumField(VarSymbol v) {
  4176             return Flags.isEnum(v.owner) &&
  4177                    Flags.isStatic(v) &&
  4178                    !Flags.isConstant(v) &&
  4179                    v.name != names._class;
  4180         }
  4181 
  4182     /**
  4183      * Check that method arguments conform to its instantiation.
  4184      **/
  4185     public Type checkMethod(Type site,
  4186                             final Symbol sym,
  4187                             ResultInfo resultInfo,
  4188                             Env<AttrContext> env,
  4189                             final List<JCExpression> argtrees,
  4190                             List<Type> argtypes,
  4191                             List<Type> typeargtypes) {
  4192         // Test (5): if symbol is an instance method of a raw type, issue
  4193         // an unchecked warning if its argument types change under erasure.
  4194         if ((sym.flags() & STATIC) == 0 &&
  4195             (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
  4196             Type s = types.asOuterSuper(site, sym.owner);
  4197             if (s != null && s.isRaw() &&
  4198                 !types.isSameTypes(sym.type.getParameterTypes(),
  4199                                    sym.erasure(types).getParameterTypes())) {
  4200                 chk.warnUnchecked(env.tree.pos(),
  4201                                   "unchecked.call.mbr.of.raw.type",
  4202                                   sym, s);
  4203             }
  4204         }
  4205 
  4206         if (env.info.defaultSuperCallSite != null) {
  4207             for (Type sup : types.interfaces(env.enclClass.sym.type).prepend(types.supertype((env.enclClass.sym.type)))) {
  4208                 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
  4209                         types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
  4210                 List<MethodSymbol> icand_sup =
  4211                         types.interfaceCandidates(sup, (MethodSymbol)sym);
  4212                 if (icand_sup.nonEmpty() &&
  4213                         icand_sup.head != sym &&
  4214                         icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
  4215                     log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite,
  4216                         diags.fragment("overridden.default", sym, sup));
  4217                     break;
  4218                 }
  4219             }
  4220             env.info.defaultSuperCallSite = null;
  4221         }
  4222 
  4223         if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
  4224             JCMethodInvocation app = (JCMethodInvocation)env.tree;
  4225             if (app.meth.hasTag(SELECT) &&
  4226                     !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
  4227                 log.error(env.tree.pos(), "illegal.static.intf.meth.call", site);
  4228             }
  4229         }
  4230 
  4231         // Compute the identifier's instantiated type.
  4232         // For methods, we need to compute the instance type by
  4233         // Resolve.instantiate from the symbol's type as well as
  4234         // any type arguments and value arguments.
  4235         Warner noteWarner = new Warner();
  4236         try {
  4237             Type owntype = rs.checkMethod(
  4238                     env,
  4239                     site,
  4240                     sym,
  4241                     resultInfo,
  4242                     argtypes,
  4243                     typeargtypes,
  4244                     noteWarner);
  4245 
  4246             DeferredAttr.DeferredTypeMap checkDeferredMap =
  4247                 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
  4248 
  4249             argtypes = argtypes.map(checkDeferredMap);
  4250 
  4251             if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  4252                 chk.warnUnchecked(env.tree.pos(),
  4253                         "unchecked.meth.invocation.applied",
  4254                         kindName(sym),
  4255                         sym.name,
  4256                         rs.methodArguments(sym.type.getParameterTypes()),
  4257                         rs.methodArguments(argtypes.map(checkDeferredMap)),
  4258                         kindName(sym.location()),
  4259                         sym.location());
  4260                 if (resultInfo.pt != Infer.anyPoly ||
  4261                         !owntype.hasTag(METHOD) ||
  4262                         !owntype.isPartial()) {
  4263                     //if this is not a partially inferred method type, erase return type. Otherwise,
  4264                     //erasure is carried out in PartiallyInferredMethodType.check().
  4265                     owntype = new MethodType(owntype.getParameterTypes(),
  4266                             types.erasure(owntype.getReturnType()),
  4267                             types.erasure(owntype.getThrownTypes()),
  4268                             syms.methodClass);
  4269                 }
  4270             }
  4271 
  4272             PolyKind pkind = (sym.type.hasTag(FORALL) &&
  4273                  sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
  4274                  PolyKind.POLY : PolyKind.STANDALONE;
  4275             TreeInfo.setPolyKind(env.tree, pkind);
  4276 
  4277             return (resultInfo.pt == Infer.anyPoly) ?
  4278                     owntype :
  4279                     chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
  4280                             resultInfo.checkContext.inferenceContext());
  4281         } catch (Infer.InferenceException ex) {
  4282             //invalid target type - propagate exception outwards or report error
  4283             //depending on the current check context
  4284             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
  4285             return types.createErrorType(sym.type);
  4286         } catch (Resolve.InapplicableMethodException ex) {
  4287             final JCDiagnostic diag = ex.getDiagnostic();
  4288             Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
  4289                 @Override
  4290                 protected Pair<Symbol, JCDiagnostic> errCandidate() {
  4291                     return new Pair<>(sym, diag);
  4292                 }
  4293             };
  4294             List<Type> argtypes2 = argtypes.map(
  4295                     rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
  4296             JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
  4297                     env.tree, sym, site, sym.name, argtypes2, typeargtypes);
  4298             log.report(errDiag);
  4299             return types.createErrorType(site);
  4300         }
  4301     }
  4302 
  4303     public void visitLiteral(JCLiteral tree) {
  4304         result = check(tree, litType(tree.typetag).constType(tree.value),
  4305                 KindSelector.VAL, resultInfo);
  4306     }
  4307     //where
  4308     /** Return the type of a literal with given type tag.
  4309      */
  4310     Type litType(TypeTag tag) {
  4311         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
  4312     }
  4313 
  4314     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
  4315         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
  4316     }
  4317 
  4318     public void visitTypeArray(JCArrayTypeTree tree) {
  4319         Type etype = attribType(tree.elemtype, env);
  4320         Type type = new ArrayType(etype, syms.arrayClass);
  4321         result = check(tree, type, KindSelector.TYP, resultInfo);
  4322     }
  4323 
  4324     /** Visitor method for parameterized types.
  4325      *  Bound checking is left until later, since types are attributed
  4326      *  before supertype structure is completely known
  4327      */
  4328     public void visitTypeApply(JCTypeApply tree) {
  4329         Type owntype = types.createErrorType(tree.type);
  4330 
  4331         // Attribute functor part of application and make sure it's a class.
  4332         Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
  4333 
  4334         // Attribute type parameters
  4335         List<Type> actuals = attribTypes(tree.arguments, env);
  4336 
  4337         if (clazztype.hasTag(CLASS)) {
  4338             List<Type> formals = clazztype.tsym.type.getTypeArguments();
  4339             if (actuals.isEmpty()) //diamond
  4340                 actuals = formals;
  4341 
  4342             if (actuals.length() == formals.length()) {
  4343                 List<Type> a = actuals;
  4344                 List<Type> f = formals;
  4345                 while (a.nonEmpty()) {
  4346                     a.head = a.head.withTypeVar(f.head);
  4347                     a = a.tail;
  4348                     f = f.tail;
  4349                 }
  4350                 // Compute the proper generic outer
  4351                 Type clazzOuter = clazztype.getEnclosingType();
  4352                 if (clazzOuter.hasTag(CLASS)) {
  4353                     Type site;
  4354                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
  4355                     if (clazz.hasTag(IDENT)) {
  4356                         site = env.enclClass.sym.type;
  4357                     } else if (clazz.hasTag(SELECT)) {
  4358                         site = ((JCFieldAccess) clazz).selected.type;
  4359                     } else throw new AssertionError(""+tree);
  4360                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
  4361                         if (site.hasTag(CLASS))
  4362                             site = types.asOuterSuper(site, clazzOuter.tsym);
  4363                         if (site == null)
  4364                             site = types.erasure(clazzOuter);
  4365                         clazzOuter = site;
  4366                     }
  4367                 }
  4368                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
  4369                                         clazztype.getMetadata());
  4370             } else {
  4371                 if (formals.length() != 0) {
  4372                     log.error(tree.pos(), "wrong.number.type.args",
  4373                               Integer.toString(formals.length()));
  4374                 } else {
  4375                     log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym);
  4376                 }
  4377                 owntype = types.createErrorType(tree.type);
  4378             }
  4379         }
  4380         result = check(tree, owntype, KindSelector.TYP, resultInfo);
  4381     }
  4382 
  4383     public void visitTypeUnion(JCTypeUnion tree) {
  4384         ListBuffer<Type> multicatchTypes = new ListBuffer<>();
  4385         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
  4386         for (JCExpression typeTree : tree.alternatives) {
  4387             Type ctype = attribType(typeTree, env);
  4388             ctype = chk.checkType(typeTree.pos(),
  4389                           chk.checkClassType(typeTree.pos(), ctype),
  4390                           syms.throwableType);
  4391             if (!ctype.isErroneous()) {
  4392                 //check that alternatives of a union type are pairwise
  4393                 //unrelated w.r.t. subtyping
  4394                 if (chk.intersects(ctype,  multicatchTypes.toList())) {
  4395                     for (Type t : multicatchTypes) {
  4396                         boolean sub = types.isSubtype(ctype, t);
  4397                         boolean sup = types.isSubtype(t, ctype);
  4398                         if (sub || sup) {
  4399                             //assume 'a' <: 'b'
  4400                             Type a = sub ? ctype : t;
  4401                             Type b = sub ? t : ctype;
  4402                             log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b);
  4403                         }
  4404                     }
  4405                 }
  4406                 multicatchTypes.append(ctype);
  4407                 if (all_multicatchTypes != null)
  4408                     all_multicatchTypes.append(ctype);
  4409             } else {
  4410                 if (all_multicatchTypes == null) {
  4411                     all_multicatchTypes = new ListBuffer<>();
  4412                     all_multicatchTypes.appendList(multicatchTypes);
  4413                 }
  4414                 all_multicatchTypes.append(ctype);
  4415             }
  4416         }
  4417         Type t = check(tree, types.lub(multicatchTypes.toList()),
  4418                 KindSelector.TYP, resultInfo.dup(CheckMode.NO_TREE_UPDATE));
  4419         if (t.hasTag(CLASS)) {
  4420             List<Type> alternatives =
  4421                 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
  4422             t = new UnionClassType((ClassType) t, alternatives);
  4423         }
  4424         tree.type = result = t;
  4425     }
  4426 
  4427     public void visitTypeIntersection(JCTypeIntersection tree) {
  4428         attribTypes(tree.bounds, env);
  4429         tree.type = result = checkIntersection(tree, tree.bounds);
  4430     }
  4431 
  4432     public void visitTypeParameter(JCTypeParameter tree) {
  4433         TypeVar typeVar = (TypeVar) tree.type;
  4434 
  4435         if (tree.annotations != null && tree.annotations.nonEmpty()) {
  4436             annotate.annotateTypeParameterSecondStage(tree, tree.annotations);
  4437         }
  4438 
  4439         if (!typeVar.bound.isErroneous()) {
  4440             //fixup type-parameter bound computed in 'attribTypeVariables'
  4441             typeVar.bound = checkIntersection(tree, tree.bounds);
  4442         }
  4443     }
  4444 
  4445     Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
  4446         Set<Type> boundSet = new HashSet<>();
  4447         if (bounds.nonEmpty()) {
  4448             // accept class or interface or typevar as first bound.
  4449             bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
  4450             boundSet.add(types.erasure(bounds.head.type));
  4451             if (bounds.head.type.isErroneous()) {
  4452                 return bounds.head.type;
  4453             }
  4454             else if (bounds.head.type.hasTag(TYPEVAR)) {
  4455                 // if first bound was a typevar, do not accept further bounds.
  4456                 if (bounds.tail.nonEmpty()) {
  4457                     log.error(bounds.tail.head.pos(),
  4458                               "type.var.may.not.be.followed.by.other.bounds");
  4459                     return bounds.head.type;
  4460                 }
  4461             } else {
  4462                 // if first bound was a class or interface, accept only interfaces
  4463                 // as further bounds.
  4464                 for (JCExpression bound : bounds.tail) {
  4465                     bound.type = checkBase(bound.type, bound, env, false, true, false);
  4466                     if (bound.type.isErroneous()) {
  4467                         bounds = List.of(bound);
  4468                     }
  4469                     else if (bound.type.hasTag(CLASS)) {
  4470                         chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
  4471                     }
  4472                 }
  4473             }
  4474         }
  4475 
  4476         if (bounds.length() == 0) {
  4477             return syms.objectType;
  4478         } else if (bounds.length() == 1) {
  4479             return bounds.head.type;
  4480         } else {
  4481             Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
  4482             // ... the variable's bound is a class type flagged COMPOUND
  4483             // (see comment for TypeVar.bound).
  4484             // In this case, generate a class tree that represents the
  4485             // bound class, ...
  4486             JCExpression extending;
  4487             List<JCExpression> implementing;
  4488             if (!bounds.head.type.isInterface()) {
  4489                 extending = bounds.head;
  4490                 implementing = bounds.tail;
  4491             } else {
  4492                 extending = null;
  4493                 implementing = bounds;
  4494             }
  4495             JCClassDecl cd = make.at(tree).ClassDef(
  4496                 make.Modifiers(PUBLIC | ABSTRACT),
  4497                 names.empty, List.nil(),
  4498                 extending, implementing, List.nil());
  4499 
  4500             ClassSymbol c = (ClassSymbol)owntype.tsym;
  4501             Assert.check((c.flags() & COMPOUND) != 0);
  4502             cd.sym = c;
  4503             c.sourcefile = env.toplevel.sourcefile;
  4504 
  4505             // ... and attribute the bound class
  4506             c.flags_field |= UNATTRIBUTED;
  4507             Env<AttrContext> cenv = enter.classEnv(cd, env);
  4508             typeEnvs.put(c, cenv);
  4509             attribClass(c);
  4510             return owntype;
  4511         }
  4512     }
  4513 
  4514     public void visitWildcard(JCWildcard tree) {
  4515         //- System.err.println("visitWildcard("+tree+");");//DEBUG
  4516         Type type = (tree.kind.kind == BoundKind.UNBOUND)
  4517             ? syms.objectType
  4518             : attribType(tree.inner, env);
  4519         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
  4520                                               tree.kind.kind,
  4521                                               syms.boundClass),
  4522                 KindSelector.TYP, resultInfo);
  4523     }
  4524 
  4525     public void visitAnnotation(JCAnnotation tree) {
  4526         Assert.error("should be handled in annotate");
  4527     }
  4528 
  4529     public void visitAnnotatedType(JCAnnotatedType tree) {
  4530         attribAnnotationTypes(tree.annotations, env);
  4531         Type underlyingType = attribType(tree.underlyingType, env);
  4532         Type annotatedType = underlyingType.annotatedType(Annotations.TO_BE_SET);
  4533 
  4534         if (!env.info.isNewClass)
  4535             annotate.annotateTypeSecondStage(tree, tree.annotations, annotatedType);
  4536         result = tree.type = annotatedType;
  4537     }
  4538 
  4539     public void visitErroneous(JCErroneous tree) {
  4540         if (tree.errs != null)
  4541             for (JCTree err : tree.errs) {
  4542                 try {
  4543                     attribTree(err, env, new ResultInfo(KindSelector.ERR, pt()));
  4544                 } catch (AssertionError ae) {
  4545                     //ignore
  4546                 }
  4547             }
  4548         result = tree.type = syms.errType;
  4549     }
  4550 
  4551     /** Default visitor method for all other trees.
  4552      */
  4553     public void visitTree(JCTree tree) {
  4554         throw new AssertionError();
  4555     }
  4556 
  4557     /**
  4558      * Attribute an env for either a top level tree or class or module declaration.
  4559      */
  4560     public void attrib(Env<AttrContext> env) {
  4561         switch (env.tree.getTag()) {
  4562             case MODULEDEF:
  4563                 attribModule(env.tree.pos(), ((JCModuleDecl)env.tree).sym);
  4564                 break;
  4565             case TOPLEVEL:
  4566                 attribTopLevel(env);
  4567                 break;
  4568             case PACKAGEDEF:
  4569                 attribPackage(env.tree.pos(), ((JCPackageDecl) env.tree).packge);
  4570                 break;
  4571             default:
  4572                 attribClass(env.tree.pos(), env.enclClass.sym);
  4573         }
  4574     }
  4575 
  4576     /**
  4577      * Attribute a top level tree. These trees are encountered when the
  4578      * package declaration has annotations.
  4579      */
  4580     public void attribTopLevel(Env<AttrContext> env) {
  4581         JCCompilationUnit toplevel = env.toplevel;
  4582         try {
  4583             annotate.flush();
  4584         } catch (CompletionFailure ex) {
  4585             chk.completionError(toplevel.pos(), ex);
  4586         }
  4587     }
  4588 
  4589     public void attribPackage(DiagnosticPosition pos, PackageSymbol p) {
  4590         try {
  4591             annotate.flush();
  4592             attribPackage(p);
  4593         } catch (CompletionFailure ex) {
  4594             chk.completionError(pos, ex);
  4595         }
  4596     }
  4597 
  4598     void attribPackage(PackageSymbol p) {
  4599         Env<AttrContext> env = typeEnvs.get(p);
  4600         chk.checkDeprecatedAnnotation(((JCPackageDecl) env.tree).pid.pos(), p);
  4601     }
  4602 
  4603     public void attribModule(DiagnosticPosition pos, ModuleSymbol m) {
  4604         try {
  4605             annotate.flush();
  4606             attribModule(m);
  4607         } catch (CompletionFailure ex) {
  4608             chk.completionError(pos, ex);
  4609         }
  4610     }
  4611 
  4612     void attribModule(ModuleSymbol m) {
  4613         // Get environment current at the point of module definition.
  4614         Env<AttrContext> env = enter.typeEnvs.get(m);
  4615         attribStat(env.tree, env);
  4616     }
  4617 
  4618     /** Main method: attribute class definition associated with given class symbol.
  4619      *  reporting completion failures at the given position.
  4620      *  @param pos The source position at which completion errors are to be
  4621      *             reported.
  4622      *  @param c   The class symbol whose definition will be attributed.
  4623      */
  4624     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
  4625         try {
  4626             annotate.flush();
  4627             attribClass(c);
  4628         } catch (CompletionFailure ex) {
  4629             chk.completionError(pos, ex);
  4630         }
  4631     }
  4632 
  4633     /** Attribute class definition associated with given class symbol.
  4634      *  @param c   The class symbol whose definition will be attributed.
  4635      */
  4636     void attribClass(ClassSymbol c) throws CompletionFailure {
  4637         // Check for cycles in the inheritance graph, which can arise from
  4638         // ill-formed class files.
  4639         chk.checkNonCyclic(null, c.type);
  4640 
  4641         Type st = types.supertype(c.type);
  4642         if ((c.flags_field & Flags.COMPOUND) == 0) {
  4643             // First, attribute superclass.
  4644             if (st.hasTag(CLASS))
  4645                 attribClass((ClassSymbol)st.tsym);
  4646 
  4647             // Next attribute owner, if it is a class.
  4648             if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
  4649                 attribClass((ClassSymbol)c.owner);
  4650         }
  4651 
  4652         // The previous operations might have attributed the current class
  4653         // if there was a cycle. So we test first whether the class is still
  4654         // UNATTRIBUTED.
  4655         if ((c.flags_field & UNATTRIBUTED) != 0) {
  4656             c.flags_field &= ~UNATTRIBUTED;
  4657 
  4658             // Get environment current at the point of class definition.
  4659             Env<AttrContext> env = typeEnvs.get(c);
  4660             if (env == null) {
  4661                 return;
  4662             }
  4663 
  4664             // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
  4665             // because the annotations were not available at the time the env was created. Therefore,
  4666             // we look up the environment chain for the first enclosing environment for which the
  4667             // lint value is set. Typically, this is the parent env, but might be further if there
  4668             // are any envs created as a result of TypeParameter nodes.
  4669             Env<AttrContext> lintEnv = env;
  4670             while (lintEnv.info.lint == null)
  4671                 lintEnv = lintEnv.next;
  4672 
  4673             // Having found the enclosing lint value, we can initialize the lint value for this class
  4674             env.info.lint = lintEnv.info.lint.augment(c);
  4675 
  4676             Lint prevLint = chk.setLint(env.info.lint);
  4677             JavaFileObject prev = log.useSource(c.sourcefile);
  4678             ResultInfo prevReturnRes = env.info.returnResult;
  4679 
  4680             try {
  4681                 deferredLintHandler.flush(env.tree);
  4682                 env.info.returnResult = null;
  4683                 // java.lang.Enum may not be subclassed by a non-enum
  4684                 if (st.tsym == syms.enumSym &&
  4685                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
  4686                     log.error(env.tree.pos(), "enum.no.subclassing");
  4687 
  4688                 // Enums may not be extended by source-level classes
  4689                 if (st.tsym != null &&
  4690                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
  4691                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
  4692                     log.error(env.tree.pos(), "enum.types.not.extensible");
  4693                 }
  4694 
  4695                 if (isSerializable(c.type)) {
  4696                     env.info.isSerializable = true;
  4697                 }
  4698 
  4699                 attribClassBody(env, c);
  4700 
  4701                 deferredLintHandler.flush(env.tree.pos());
  4702                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
  4703                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
  4704                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
  4705                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
  4706             } finally {
  4707                 env.info.returnResult = prevReturnRes;
  4708                 log.useSource(prev);
  4709                 chk.setLint(prevLint);
  4710             }
  4711 
  4712         }
  4713     }
  4714 
  4715     public void visitImport(JCImport tree) {
  4716         // nothing to do
  4717     }
  4718 
  4719     public void visitModuleDef(JCModuleDecl tree) {
  4720         tree.sym.completeUsesProvides();
  4721         ModuleSymbol msym = tree.sym;
  4722         Lint lint = env.outer.info.lint = env.outer.info.lint.augment(msym);
  4723         Lint prevLint = chk.setLint(lint);
  4724         chk.checkModuleName(tree);
  4725         chk.checkDeprecatedAnnotation(tree, msym);
  4726 
  4727         try {
  4728             deferredLintHandler.flush(tree.pos());
  4729         } finally {
  4730             chk.setLint(prevLint);
  4731         }
  4732     }
  4733 
  4734     /** Finish the attribution of a class. */
  4735     private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
  4736         JCClassDecl tree = (JCClassDecl)env.tree;
  4737 
  4738         if (c != tree.sym)
  4739             Assert.error("c = " + c + " tree.sym = " + tree.sym + " tree = " + tree);
  4740 
  4741         // Validate type parameters, supertype and interfaces.
  4742         attribStats(tree.typarams, env);
  4743         if (!c.isAnonymous()) {
  4744             //already checked if anonymous
  4745             chk.validate(tree.typarams, env);
  4746             chk.validate(tree.extending, env);
  4747             chk.validate(tree.implementing, env);
  4748         }
  4749 
  4750         c.markAbstractIfNeeded(types);
  4751 
  4752         // If this is a non-abstract class, check that it has no abstract
  4753         // methods or unimplemented methods of an implemented interface.
  4754         if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
  4755             chk.checkAllDefined(tree.pos(), c);
  4756         }
  4757 
  4758         if ((c.flags() & ANNOTATION) != 0) {
  4759             if (tree.implementing.nonEmpty())
  4760                 log.error(tree.implementing.head.pos(),
  4761                           "cant.extend.intf.annotation");
  4762             if (tree.typarams.nonEmpty())
  4763                 log.error(tree.typarams.head.pos(),
  4764                           "intf.annotation.cant.have.type.params");
  4765 
  4766             // If this annotation type has a @Repeatable, validate
  4767             Attribute.Compound repeatable = c.getAnnotationTypeMetadata().getRepeatable();
  4768             // If this annotation type has a @Repeatable, validate
  4769             if (repeatable != null) {
  4770                 // get diagnostic position for error reporting
  4771                 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
  4772                 Assert.checkNonNull(cbPos);
  4773 
  4774                 chk.validateRepeatable(c, repeatable, cbPos);
  4775             }
  4776         } else {
  4777             // Check that all extended classes and interfaces
  4778             // are compatible (i.e. no two define methods with same arguments
  4779             // yet different return types).  (JLS 8.4.6.3)
  4780             chk.checkCompatibleSupertypes(tree.pos(), c.type);
  4781             if (allowDefaultMethods) {
  4782                 chk.checkDefaultMethodClashes(tree.pos(), c.type);
  4783             }
  4784         }
  4785 
  4786         // Check that class does not import the same parameterized interface
  4787         // with two different argument lists.
  4788         chk.checkClassBounds(tree.pos(), c.type);
  4789 
  4790         tree.type = c.type;
  4791 
  4792         for (List<JCTypeParameter> l = tree.typarams;
  4793              l.nonEmpty(); l = l.tail) {
  4794              Assert.checkNonNull(env.info.scope.findFirst(l.head.name));
  4795         }
  4796 
  4797         // Check that a generic class doesn't extend Throwable
  4798         if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
  4799             log.error(tree.extending.pos(), "generic.throwable");
  4800 
  4801         // Check that all methods which implement some
  4802         // method conform to the method they implement.
  4803         DiagnosticPosition prevPos = deferredLintHandler.setPos(tree.pos());
  4804         try {
  4805             chk.checkImplementations(tree);
  4806         } finally {
  4807             deferredLintHandler.setPos(prevPos);
  4808         }
  4809 
  4810         //check that a resource implementing AutoCloseable cannot throw InterruptedException
  4811         checkAutoCloseable(tree.pos(), env, c.type);
  4812 
  4813         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  4814             // Attribute declaration
  4815             attribStat(l.head, env);
  4816             // Check that declarations in inner classes are not static (JLS 8.1.2)
  4817             // Make an exception for static constants.
  4818             if (c.owner.kind != PCK &&
  4819                 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
  4820                 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
  4821                 Symbol sym = null;
  4822                 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
  4823                 if (sym == null ||
  4824                     sym.kind != VAR ||
  4825                     ((VarSymbol) sym).getConstValue() == null) {
  4826                     // Check that enum type is not local. If so, 'Enum types must not be local' is already reported
  4827                     // and there is no need for reporting static declaration in an inner class
  4828                     if (c.owner.kind != MTH || (c.flags() & ENUM) == 0)
  4829                         log.error(l.head.pos(), "icls.cant.have.static.decl", c);
  4830                 }
  4831             }
  4832         }
  4833 
  4834         // Check for cycles among non-initial constructors.
  4835         chk.checkCyclicConstructors(tree);
  4836 
  4837         // Check for cycles among annotation elements.
  4838         chk.checkNonCyclicElements(tree);
  4839 
  4840         // Check for proper use of serialVersionUID
  4841         if (env.info.lint.isEnabled(LintCategory.SERIAL)
  4842                 && isSerializable(c.type)
  4843                 && (c.flags() & Flags.ENUM) == 0
  4844                 && !c.isAnonymous()
  4845                 && checkForSerial(c)) {
  4846             checkSerialVersionUID(tree, c);
  4847         }
  4848         if (allowTypeAnnos) {
  4849             // Correctly organize the postions of the type annotations
  4850             typeAnnotations.organizeTypeAnnotationsBodies(tree);
  4851 
  4852             // Check type annotations applicability rules
  4853             validateTypeAnnotations(tree, false);
  4854         }
  4855     }
  4856         // where
  4857         boolean checkForSerial(ClassSymbol c) {
  4858             if ((c.flags() & ABSTRACT) == 0) {
  4859                 return true;
  4860             } else {
  4861                 return c.members().anyMatch(anyNonAbstractOrDefaultMethod);
  4862             }
  4863         }
  4864 
  4865         public static final Filter<Symbol> anyNonAbstractOrDefaultMethod = s ->
  4866                 s.kind == MTH && (s.flags() & (DEFAULT | ABSTRACT)) != ABSTRACT;
  4867 
  4868         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
  4869         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
  4870             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
  4871                 if (types.isSameType(al.head.annotationType.type, t))
  4872                     return al.head.pos();
  4873             }
  4874 
  4875             return null;
  4876         }
  4877 
  4878         /** check if a type is a subtype of Serializable, if that is available. */
  4879         boolean isSerializable(Type t) {
  4880             try {
  4881                 syms.serializableType.complete();
  4882             }
  4883             catch (CompletionFailure e) {
  4884                 return false;
  4885             }
  4886             return types.isSubtype(t, syms.serializableType);
  4887         }
  4888 
  4889         /** Check that an appropriate serialVersionUID member is defined. */
  4890         private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) {
  4891 
  4892             // check for presence of serialVersionUID
  4893             VarSymbol svuid = null;
  4894             for (Symbol sym : c.members().getSymbolsByName(names.serialVersionUID)) {
  4895                 if (sym.kind == VAR) {
  4896                     svuid = (VarSymbol)sym;
  4897                     break;
  4898                 }
  4899             }
  4900 
  4901             if (svuid == null) {
  4902                 log.warning(LintCategory.SERIAL,
  4903                         tree.pos(), "missing.SVUID", c);
  4904                 return;
  4905             }
  4906 
  4907             // check that it is static final
  4908             if ((svuid.flags() & (STATIC | FINAL)) !=
  4909                 (STATIC | FINAL))
  4910                 log.warning(LintCategory.SERIAL,
  4911                         TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c);
  4912 
  4913             // check that it is long
  4914             else if (!svuid.type.hasTag(LONG))
  4915                 log.warning(LintCategory.SERIAL,
  4916                         TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c);
  4917 
  4918             // check constant
  4919             else if (svuid.getConstValue() == null)
  4920                 log.warning(LintCategory.SERIAL,
  4921                         TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c);
  4922         }
  4923 
  4924     private Type capture(Type type) {
  4925         return types.capture(type);
  4926     }
  4927 
  4928     public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
  4929         tree.accept(new TypeAnnotationsValidator(sigOnly));
  4930     }
  4931     //where
  4932     private final class TypeAnnotationsValidator extends TreeScanner {
  4933 
  4934         private final boolean sigOnly;
  4935         public TypeAnnotationsValidator(boolean sigOnly) {
  4936             this.sigOnly = sigOnly;
  4937         }
  4938 
  4939         public void visitAnnotation(JCAnnotation tree) {
  4940             chk.validateTypeAnnotation(tree, false);
  4941             super.visitAnnotation(tree);
  4942         }
  4943         public void visitAnnotatedType(JCAnnotatedType tree) {
  4944             if (!tree.underlyingType.type.isErroneous()) {
  4945                 super.visitAnnotatedType(tree);
  4946             }
  4947         }
  4948         public void visitTypeParameter(JCTypeParameter tree) {
  4949             chk.validateTypeAnnotations(tree.annotations, true);
  4950             scan(tree.bounds);
  4951             // Don't call super.
  4952             // This is needed because above we call validateTypeAnnotation with
  4953             // false, which would forbid annotations on type parameters.
  4954             // super.visitTypeParameter(tree);
  4955         }
  4956         public void visitMethodDef(JCMethodDecl tree) {
  4957             if (tree.recvparam != null &&
  4958                     !tree.recvparam.vartype.type.isErroneous()) {
  4959                 checkForDeclarationAnnotations(tree.recvparam.mods.annotations,
  4960                         tree.recvparam.vartype.type.tsym);
  4961             }
  4962             if (tree.restype != null && tree.restype.type != null) {
  4963                 validateAnnotatedType(tree.restype, tree.restype.type);
  4964             }
  4965             if (sigOnly) {
  4966                 scan(tree.mods);
  4967                 scan(tree.restype);
  4968                 scan(tree.typarams);
  4969                 scan(tree.recvparam);
  4970                 scan(tree.params);
  4971                 scan(tree.thrown);
  4972             } else {
  4973                 scan(tree.defaultValue);
  4974                 scan(tree.body);
  4975             }
  4976         }
  4977         public void visitVarDef(final JCVariableDecl tree) {
  4978             //System.err.println("validateTypeAnnotations.visitVarDef " + tree);
  4979             if (tree.sym != null && tree.sym.type != null && !tree.sym.type.isErroneous())
  4980                 validateAnnotatedType(tree.vartype, tree.sym.type);
  4981             scan(tree.mods);
  4982             scan(tree.vartype);
  4983             if (!sigOnly) {
  4984                 scan(tree.init);
  4985             }
  4986         }
  4987         public void visitTypeCast(JCTypeCast tree) {
  4988             if (tree.clazz != null && tree.clazz.type != null)
  4989                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4990             super.visitTypeCast(tree);
  4991         }
  4992         public void visitTypeTest(JCInstanceOf tree) {
  4993             if (tree.clazz != null && tree.clazz.type != null)
  4994                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  4995             super.visitTypeTest(tree);
  4996         }
  4997         public void visitNewClass(JCNewClass tree) {
  4998             if (tree.clazz != null && tree.clazz.type != null) {
  4999                 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
  5000                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
  5001                             tree.clazz.type.tsym);
  5002                 }
  5003                 if (tree.def != null) {
  5004                     checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym);
  5005                 }
  5006 
  5007                 validateAnnotatedType(tree.clazz, tree.clazz.type);
  5008             }
  5009             super.visitNewClass(tree);
  5010         }
  5011         public void visitNewArray(JCNewArray tree) {
  5012             if (tree.elemtype != null && tree.elemtype.type != null) {
  5013                 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
  5014                     checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
  5015                             tree.elemtype.type.tsym);
  5016                 }
  5017                 validateAnnotatedType(tree.elemtype, tree.elemtype.type);
  5018             }
  5019             super.visitNewArray(tree);
  5020         }
  5021         public void visitClassDef(JCClassDecl tree) {
  5022             //System.err.println("validateTypeAnnotations.visitClassDef " + tree);
  5023             if (sigOnly) {
  5024                 scan(tree.mods);
  5025                 scan(tree.typarams);
  5026                 scan(tree.extending);
  5027                 scan(tree.implementing);
  5028             }
  5029             for (JCTree member : tree.defs) {
  5030                 if (member.hasTag(Tag.CLASSDEF)) {
  5031                     continue;
  5032                 }
  5033                 scan(member);
  5034             }
  5035         }
  5036         public void visitBlock(JCBlock tree) {
  5037             if (!sigOnly) {
  5038                 scan(tree.stats);
  5039             }
  5040         }
  5041 
  5042         /* I would want to model this after
  5043          * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
  5044          * and override visitSelect and visitTypeApply.
  5045          * However, we only set the annotated type in the top-level type
  5046          * of the symbol.
  5047          * Therefore, we need to override each individual location where a type
  5048          * can occur.
  5049          */
  5050         private void validateAnnotatedType(final JCTree errtree, final Type type) {
  5051             //System.err.println("Attr.validateAnnotatedType: " + errtree + " type: " + type);
  5052 
  5053             if (type.isPrimitiveOrVoid() || type.isErroneous()) {
  5054                 return;
  5055             }
  5056 
  5057             JCTree enclTr = errtree;
  5058             Type enclTy = type;
  5059 
  5060             boolean repeat = true;
  5061             while (repeat) {
  5062                 if (enclTr == null) {
  5063                     Assert.error("Unexpected null tree within: "+ errtree + " with kind: " + errtree.getKind());
  5064                 }
  5065                 if (enclTr.hasTag(TYPEAPPLY)) {
  5066                     List<Type> tyargs = enclTy.getTypeArguments();
  5067                     List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments();
  5068                     if (trargs.length() > 0) {
  5069                         // Nothing to do for diamonds
  5070                         if (tyargs.length() == trargs.length()) {
  5071                             for (int i = 0; i < tyargs.length(); ++i) {
  5072                                 validateAnnotatedType(trargs.get(i), tyargs.get(i));
  5073                             }
  5074                         }
  5075                         // If the lengths don't match, it's either a diamond
  5076                         // or some nested type that redundantly provides
  5077                         // type arguments in the tree.
  5078                     }
  5079 
  5080                     // Look at the clazz part of a generic type
  5081                     enclTr = ((JCTree.JCTypeApply)enclTr).clazz;
  5082                 }
  5083 
  5084                 if (enclTr.hasTag(SELECT)) {
  5085                     enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression();
  5086                     if (enclTy != null &&
  5087                             !enclTy.hasTag(NONE)) {
  5088                         enclTy = enclTy.getEnclosingType();
  5089                     }
  5090                 } else if (enclTr.hasTag(ANNOTATED_TYPE)) {
  5091                     JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr;
  5092                     if (enclTy == null || enclTy.hasTag(NONE)) {
  5093                         if (at.getAnnotations().size() == 1) {
  5094                             log.error(at.underlyingType.pos(), "cant.type.annotate.scoping.1", at.getAnnotations().head.attribute);
  5095                         } else {
  5096                             ListBuffer<Attribute.Compound> comps = new ListBuffer<>();
  5097                             for (JCAnnotation an : at.getAnnotations()) {
  5098                                 comps.add(an.attribute);
  5099                             }
  5100                             log.error(at.underlyingType.pos(), "cant.type.annotate.scoping", comps.toList());
  5101                         }
  5102                         repeat = false;
  5103                     }
  5104                     enclTr = at.underlyingType;
  5105                     // enclTy doesn't need to be changed
  5106                 } else if (enclTr.hasTag(IDENT)) {
  5107                     repeat = false;
  5108                 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) {
  5109                     JCWildcard wc = (JCWildcard) enclTr;
  5110                     if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD) {
  5111                         validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy).getExtendsBound());
  5112                     } else if (wc.getKind() == JCTree.Kind.SUPER_WILDCARD) {
  5113                         validateAnnotatedType(wc.getBound(), ((WildcardType)enclTy).getSuperBound());
  5114                     } else {
  5115                         // Nothing to do for UNBOUND
  5116                     }
  5117                     repeat = false;
  5118                 } else if (enclTr.hasTag(TYPEARRAY)) {
  5119                     JCArrayTypeTree art = (JCArrayTypeTree) enclTr;
  5120                     validateAnnotatedType(art.getType(), ((ArrayType)enclTy).getComponentType());
  5121                     repeat = false;
  5122                 } else if (enclTr.hasTag(TYPEUNION)) {
  5123                     JCTypeUnion ut = (JCTypeUnion) enclTr;
  5124                     for (JCTree t : ut.getTypeAlternatives()) {
  5125                         validateAnnotatedType(t, t.type);
  5126                     }
  5127                     repeat = false;
  5128                 } else if (enclTr.hasTag(TYPEINTERSECTION)) {
  5129                     JCTypeIntersection it = (JCTypeIntersection) enclTr;
  5130                     for (JCTree t : it.getBounds()) {
  5131                         validateAnnotatedType(t, t.type);
  5132                     }
  5133                     repeat = false;
  5134                 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE ||
  5135                            enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
  5136                     repeat = false;
  5137                 } else if (enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
  5138                     repeat = false;
  5139                 } else {
  5140                     Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() +
  5141                             " within: "+ errtree + " with kind: " + errtree.getKind());
  5142                 }
  5143             }
  5144         }
  5145 
  5146         private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
  5147                 Symbol sym) {
  5148             // Ensure that no declaration annotations are present.
  5149             // Note that a tree type might be an AnnotatedType with
  5150             // empty annotations, if only declaration annotations were given.
  5151             // This method will raise an error for such a type.
  5152             for (JCAnnotation ai : annotations) {
  5153                 if (!ai.type.isErroneous() &&
  5154                         typeAnnotations.annotationTargetType(ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
  5155                     log.error(ai.pos(), Errors.AnnotationTypeNotApplicableToType(ai.type));
  5156                 }
  5157             }
  5158         }
  5159     }
  5160 
  5161     public Env<AttrContext> dupLocalEnv(Env<AttrContext> localEnv) {
  5162         return localEnv.dup(localEnv.tree, localEnv.info.dup(localEnv.info.scope.dupUnshared()));
  5163     }
  5164 
  5165 // <editor-fold desc="post-attribution visitor">
  5166 
  5167     /**
  5168      * Handle missing types/symbols in an AST. This routine is useful when
  5169      * the compiler has encountered some errors (which might have ended up
  5170      * terminating attribution abruptly); if the compiler is used in fail-over
  5171      * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
  5172      * prevents NPE to be progagated during subsequent compilation steps.
  5173      */
  5174     public void postAttr(JCTree tree) {
  5175         new PostAttrAnalyzer().scan(tree);
  5176     }
  5177 
  5178     class PostAttrAnalyzer extends TreeScanner {
  5179 
  5180         private void initTypeIfNeeded(JCTree that) {
  5181             if (that.type == null) {
  5182                 if (that.hasTag(METHODDEF)) {
  5183                     that.type = dummyMethodType((JCMethodDecl)that);
  5184                 } else {
  5185                     that.type = syms.unknownType;
  5186                 }
  5187             }
  5188         }
  5189 
  5190         /* Construct a dummy method type. If we have a method declaration,
  5191          * and the declared return type is void, then use that return type
  5192          * instead of UNKNOWN to avoid spurious error messages in lambda
  5193          * bodies (see:JDK-8041704).
  5194          */
  5195         private Type dummyMethodType(JCMethodDecl md) {
  5196             Type restype = syms.unknownType;
  5197             if (md != null && md.restype != null && md.restype.hasTag(TYPEIDENT)) {
  5198                 JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype;
  5199                 if (prim.typetag == VOID)
  5200                     restype = syms.voidType;
  5201             }
  5202             return new MethodType(List.nil(), restype,
  5203                                   List.nil(), syms.methodClass);
  5204         }
  5205         private Type dummyMethodType() {
  5206             return dummyMethodType(null);
  5207         }
  5208 
  5209         @Override
  5210         public void scan(JCTree tree) {
  5211             if (tree == null) return;
  5212             if (tree instanceof JCExpression) {
  5213                 initTypeIfNeeded(tree);
  5214             }
  5215             super.scan(tree);
  5216         }
  5217 
  5218         @Override
  5219         public void visitIdent(JCIdent that) {
  5220             if (that.sym == null) {
  5221                 that.sym = syms.unknownSymbol;
  5222             }
  5223         }
  5224 
  5225         @Override
  5226         public void visitSelect(JCFieldAccess that) {
  5227             if (that.sym == null) {
  5228                 that.sym = syms.unknownSymbol;
  5229             }
  5230             super.visitSelect(that);
  5231         }
  5232 
  5233         @Override
  5234         public void visitClassDef(JCClassDecl that) {
  5235             initTypeIfNeeded(that);
  5236             if (that.sym == null) {
  5237                 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
  5238             }
  5239             super.visitClassDef(that);
  5240         }
  5241         
  5242         private boolean inMethodParams = false;
  5243 
  5244         @Override
  5245         public void visitMethodDef(JCMethodDecl that) {
  5246             initTypeIfNeeded(that);
  5247             if (that.sym == null) {
  5248                 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
  5249             }
  5250             scan(that.mods);
  5251             scan(that.restype);
  5252             scan(that.typarams);
  5253             try {
  5254                 inMethodParams = true;
  5255                 scan(that.recvparam);
  5256                 scan(that.params);
  5257             } finally {
  5258                 inMethodParams = false;
  5259             }
  5260             scan(that.thrown);
  5261             scan(that.defaultValue);
  5262             scan(that.body);
  5263         }
  5264 
  5265         @Override
  5266         public void visitVarDef(JCVariableDecl that) {
  5267             initTypeIfNeeded(that);
  5268             if (that.sym == null) {
  5269                 that.sym = new VarSymbol(inMethodParams ? Flags.PARAMETER : 0, that.name, that.type, syms.noSymbol);
  5270                 that.sym.adr = 0;
  5271             }
  5272             if (that.vartype == null) {
  5273                 that.vartype = make.Erroneous();
  5274             }
  5275             super.visitVarDef(that);
  5276         }
  5277 
  5278         @Override
  5279         public void visitNewClass(JCNewClass that) {
  5280             if (that.constructor == null) {
  5281                 that.constructor = new MethodSymbol(0, names.init,
  5282                         dummyMethodType(), syms.noSymbol);
  5283             }
  5284             if (that.constructorType == null) {
  5285                 that.constructorType = syms.unknownType;
  5286             }
  5287             super.visitNewClass(that);
  5288         }
  5289 
  5290         @Override
  5291         public void visitAssignop(JCAssignOp that) {
  5292             if (that.operator == null) {
  5293                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
  5294                         -1, syms.noSymbol);
  5295             }
  5296             super.visitAssignop(that);
  5297         }
  5298 
  5299         @Override
  5300         public void visitBinary(JCBinary that) {
  5301             if (that.operator == null) {
  5302                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
  5303                         -1, syms.noSymbol);
  5304             }
  5305             super.visitBinary(that);
  5306         }
  5307 
  5308         @Override
  5309         public void visitUnary(JCUnary that) {
  5310             if (that.operator == null) {
  5311                 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
  5312                         -1, syms.noSymbol);
  5313             }
  5314             super.visitUnary(that);
  5315         }
  5316 
  5317         @Override
  5318         public void visitLambda(JCLambda that) {
  5319             super.visitLambda(that);
  5320             if (that.targets == null) {
  5321                 that.targets = List.nil();
  5322             }
  5323         }
  5324 
  5325         @Override
  5326         public void visitReference(JCMemberReference that) {
  5327             super.visitReference(that);
  5328             if (that.sym == null) {
  5329                 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
  5330                         syms.noSymbol);
  5331             }
  5332             if (that.targets == null) {
  5333                 that.targets = List.nil();
  5334             }
  5335         }
  5336 
  5337         @Override
  5338         public void visitErroneous(JCErroneous tree) {
  5339             scan(tree.errs);
  5340         }
  5341     }
  5342     // </editor-fold>
  5343 
  5344     public void setPackageSymbols(JCExpression pid, Symbol pkg) {
  5345         new TreeScanner() {
  5346             Symbol packge = pkg;
  5347             @Override
  5348             public void visitIdent(JCIdent that) {
  5349                 that.sym = packge;
  5350             }
  5351 
  5352             @Override
  5353             public void visitSelect(JCFieldAccess that) {
  5354                 that.sym = packge;
  5355                 packge = packge.owner;
  5356                 super.visitSelect(that);
  5357             }
  5358         }.scan(pid);
  5359     }
  5360 
  5361 }