< prev index next >

src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java

Print this page

  26 package com.sun.tools.javac.comp;
  27 
  28 import java.util.*;
  29 import java.util.function.BiConsumer;
  30 
  31 import javax.lang.model.element.ElementKind;
  32 import javax.tools.JavaFileObject;
  33 
  34 import com.sun.source.tree.CaseTree;
  35 import com.sun.source.tree.IdentifierTree;
  36 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
  37 import com.sun.source.tree.MemberSelectTree;
  38 import com.sun.source.tree.TreeVisitor;
  39 import com.sun.source.util.SimpleTreeVisitor;
  40 import com.sun.tools.javac.code.*;
  41 import com.sun.tools.javac.code.Lint.LintCategory;
  42 import com.sun.tools.javac.code.Scope.WriteableScope;
  43 import com.sun.tools.javac.code.Source.Feature;
  44 import com.sun.tools.javac.code.Symbol.*;
  45 import com.sun.tools.javac.code.Type.*;

  46 import com.sun.tools.javac.code.TypeMetadata.Annotations;
  47 import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError;
  48 import com.sun.tools.javac.comp.ArgumentAttr.LocalCacheContext;
  49 import com.sun.tools.javac.comp.Check.CheckContext;
  50 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
  51 import com.sun.tools.javac.comp.MatchBindingsComputer.MatchBindings;
  52 import com.sun.tools.javac.jvm.*;
  53 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond;
  54 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArg;
  55 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArgs;
  56 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  57 import com.sun.tools.javac.resources.CompilerProperties.Fragments;

  58 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
  59 import com.sun.tools.javac.tree.*;
  60 import com.sun.tools.javac.tree.JCTree.*;
  61 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
  62 import com.sun.tools.javac.util.*;
  63 import com.sun.tools.javac.util.DefinedBy.Api;
  64 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  65 import com.sun.tools.javac.util.JCDiagnostic.Error;
  66 import com.sun.tools.javac.util.JCDiagnostic.Fragment;
  67 import com.sun.tools.javac.util.JCDiagnostic.Warning;
  68 import com.sun.tools.javac.util.List;
  69 
  70 import static com.sun.tools.javac.code.Flags.*;
  71 import static com.sun.tools.javac.code.Flags.ANNOTATION;
  72 import static com.sun.tools.javac.code.Flags.BLOCK;
  73 import static com.sun.tools.javac.code.Kinds.*;
  74 import static com.sun.tools.javac.code.Kinds.Kind.*;
  75 import static com.sun.tools.javac.code.TypeTag.*;
  76 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
  77 import static com.sun.tools.javac.tree.JCTree.Tag.*;

 150         types = Types.instance(context);
 151         preview = Preview.instance(context);
 152         diags = JCDiagnostic.Factory.instance(context);
 153         annotate = Annotate.instance(context);
 154         typeAnnotations = TypeAnnotations.instance(context);
 155         deferredLintHandler = DeferredLintHandler.instance(context);
 156         typeEnvs = TypeEnvs.instance(context);
 157         dependencies = Dependencies.instance(context);
 158         argumentAttr = ArgumentAttr.instance(context);
 159         matchBindingsComputer = MatchBindingsComputer.instance(context);
 160         attrRecover = AttrRecover.instance(context);
 161 
 162         Options options = Options.instance(context);
 163 
 164         Source source = Source.instance(context);
 165         allowPoly = Feature.POLY.allowedInSource(source);
 166         allowTypeAnnos = Feature.TYPE_ANNOTATIONS.allowedInSource(source);
 167         allowLambda = Feature.LAMBDA.allowedInSource(source);
 168         allowDefaultMethods = Feature.DEFAULT_METHODS.allowedInSource(source);
 169         allowStaticInterfaceMethods = Feature.STATIC_INTERFACE_METHODS.allowedInSource(source);

 170         allowReifiableTypesInInstanceof = Feature.REIFIABLE_TYPES_INSTANCEOF.allowedInSource(source);
 171         allowRecords = Feature.RECORDS.allowedInSource(source);
 172         allowPatternSwitch = (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH)) &&
 173                              Feature.PATTERN_SWITCH.allowedInSource(source);
 174         sourceName = source.name;
 175         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
 176 
 177         statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
 178         varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
 179         unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
 180         methodAttrInfo = new MethodAttrInfo();
 181         unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
 182         unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
 183         recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
 184     }
 185 
 186     /** Switch: support target-typing inference
 187      */
 188     boolean allowPoly;
 189 
 190     /** Switch: support type annotations.
 191      */
 192     boolean allowTypeAnnos;
 193 
 194     /** Switch: support lambda expressions ?
 195      */
 196     boolean allowLambda;
 197 
 198     /** Switch: support default methods ?
 199      */
 200     boolean allowDefaultMethods;
 201 




 202     /** Switch: static interface methods enabled?
 203      */
 204     boolean allowStaticInterfaceMethods;
 205 
 206     /** Switch: reifiable types in instanceof enabled?
 207      */
 208     boolean allowReifiableTypesInInstanceof;
 209 
 210     /** Are records allowed
 211      */
 212     private final boolean allowRecords;
 213 
 214     /** Are patterns in switch allowed
 215      */
 216     private final boolean allowPatternSwitch;
 217 
 218     /**
 219      * Switch: warn about use of variable before declaration?
 220      * RFE: 6425594
 221      */

 300 
 301     /** Check that variable can be assigned to.
 302      *  @param pos    The current source code position.
 303      *  @param v      The assigned variable
 304      *  @param base   If the variable is referred to in a Select, the part
 305      *                to the left of the `.', null otherwise.
 306      *  @param env    The current environment.
 307      */
 308     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
 309         if (v.name == names._this) {
 310             log.error(pos, Errors.CantAssignValToThis);
 311         } else if ((v.flags() & FINAL) != 0 &&
 312             ((v.flags() & HASINIT) != 0
 313              ||
 314              !((base == null ||
 315                TreeInfo.isThisQualifier(base)) &&
 316                isAssignableAsBlankFinal(v, env)))) {
 317             if (v.isResourceVariable()) { //TWR resource
 318                 log.error(pos, Errors.TryResourceMayNotBeAssigned(v));
 319             } else {
 320                 log.error(pos, Errors.CantAssignValToFinalVar(v));










 321             }
 322         }
 323     }
 324 
 325     /** Does tree represent a static reference to an identifier?
 326      *  It is assumed that tree is either a SELECT or an IDENT.
 327      *  We have to weed out selects from non-type names here.
 328      *  @param tree    The candidate tree.
 329      */
 330     boolean isStaticReference(JCTree tree) {
 331         if (tree.hasTag(SELECT)) {
 332             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
 333             if (lsym == null || lsym.kind != TYP) {
 334                 return false;
 335             }
 336         }
 337         return true;
 338     }
 339 
 340     /** Is this symbol a type?

 797     /** Attribute a type argument list, returning a list of types.
 798      *  Check that all the types are references.
 799      */
 800     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
 801         List<Type> types = attribAnyTypes(trees, env);
 802         return chk.checkRefTypes(trees, types);
 803     }
 804 
 805     /**
 806      * Attribute type variables (of generic classes or methods).
 807      * Compound types are attributed later in attribBounds.
 808      * @param typarams the type variables to enter
 809      * @param env      the current environment
 810      */
 811     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env, boolean checkCyclic) {
 812         for (JCTypeParameter tvar : typarams) {
 813             TypeVar a = (TypeVar)tvar.type;
 814             a.tsym.flags_field |= UNATTRIBUTED;
 815             a.setUpperBound(Type.noType);
 816             if (!tvar.bounds.isEmpty()) {
 817                 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
 818                 for (JCExpression bound : tvar.bounds.tail)
 819                     bounds = bounds.prepend(attribType(bound, env));
 820                 types.setBounds(a, bounds.reverse());
 821             } else {
 822                 // if no bounds are given, assume a single bound of
 823                 // java.lang.Object.
 824                 types.setBounds(a, List.of(syms.objectType));
 825             }
 826             a.tsym.flags_field &= ~UNATTRIBUTED;
 827         }
 828         if (checkCyclic) {
 829             for (JCTypeParameter tvar : typarams) {
 830                 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
 831             }
 832         }
 833     }
 834 
 835     /**
 836      * Attribute the type references in a list of annotations.
 837      */
 838     void attribAnnotationTypes(List<JCAnnotation> annotations,
 839                                Env<AttrContext> env) {

1181                         log.error(tree.pos(),
1182                                   Errors.DefaultAllowedInIntfAnnotationMember);
1183                 }
1184                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1185                     log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract);
1186             } else if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1187                 if ((owner.flags() & INTERFACE) != 0) {
1188                     log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1189                 } else {
1190                     log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1191                 }
1192             } else if ((tree.mods.flags & NATIVE) != 0) {
1193                 log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1194             } else {
1195                 // Add an implicit super() call unless an explicit call to
1196                 // super(...) or this(...) is given
1197                 // or we are compiling class java.lang.Object.
1198                 if (tree.name == names.init && owner.type != syms.objectType) {
1199                     JCBlock body = tree.body;
1200                     if (body.stats.isEmpty() ||
1201                             TreeInfo.getConstructorInvocationName(body.stats, names) == names.empty) {
1202                         JCStatement supCall = make.at(body.pos).Exec(make.Apply(List.nil(),
1203                                 make.Ident(names._super), make.Idents(List.nil())));
1204                         body.stats = body.stats.prepend(supCall);
1205                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1206                             (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1207                             TreeInfo.isSuperCall(body.stats.head)) {
1208                         // enum constructors are not allowed to call super
1209                         // directly, so make sure there aren't any super calls
1210                         // in enum constructors, except in the compiler
1211                         // generated one.
1212                         log.error(tree.body.stats.head.pos(),
1213                                   Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));






1214                     }
1215                     if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1216                         List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1217                         List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1218                         if (!initParamNames.equals(recordComponentNames)) {
1219                             log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1220                                     Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1221                         }
1222                         if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1223                             log.error(tree,
1224                                     Errors.InvalidCanonicalConstructorInRecord(
1225                                             TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical,
1226                                             env.enclClass.sym.name,
1227                                             Fragments.ThrowsClauseNotAllowedForCanonicalConstructor(
1228                                                     TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical)));
1229                         }
1230                     }
1231                 }






1232 
1233                 // Attribute all type annotations in the body
1234                 annotate.queueScanTreeAndTypeAnnotate(tree.body, localEnv, m, null);
1235                 annotate.flush();
1236 
1237                 // Attribute method body.
1238                 attribStat(tree.body, localEnv);
1239             }
1240 
1241             localEnv.info.scope.leave();
1242             result = tree.type = m.type;
1243         } finally {
1244             chk.setLint(prevLint);
1245             chk.setMethod(prevMethod);
1246         }
1247     }
1248 
1249     public void visitVarDef(JCVariableDecl tree) {
1250         // Local variables have not been entered yet, so we need to do it now:
1251         if (env.info.scope.owner.kind == MTH || env.info.scope.owner.kind == VAR) {

1281                 annotate.queueScanTreeAndTypeAnnotate(tree.init, env, tree.sym, tree.pos());
1282                 annotate.flush();
1283             }
1284         }
1285 
1286         VarSymbol v = tree.sym;
1287         Lint lint = env.info.lint.augment(v);
1288         Lint prevLint = chk.setLint(lint);
1289 
1290         // Check that the variable's declared type is well-formed.
1291         boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
1292                 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
1293                 (tree.sym.flags() & PARAMETER) != 0;
1294         chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1295 
1296         try {
1297             v.getConstValue(); // ensure compile-time constant initializer is evaluated
1298             deferredLintHandler.flush(tree.pos());
1299             chk.checkDeprecatedAnnotation(tree.pos(), v);
1300 



1301             if (tree.init != null) {
1302                 if ((v.flags_field & FINAL) == 0 ||
1303                     !memberEnter.needsLazyConstValue(tree.init)) {
1304                     // Not a compile-time constant
1305                     // Attribute initializer in a new environment
1306                     // with the declared variable as owner.
1307                     // Check that initializer conforms to variable's declared type.
1308                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1309                     initEnv.info.lint = lint;
1310                     // In order to catch self-references, we set the variable's
1311                     // declaration position to maximal possible value, effectively
1312                     // marking the variable as undefined.
1313                     initEnv.info.enclVar = v;
1314                     attribExpr(tree.init, initEnv, v.type);
1315                     if (tree.isImplicitlyTyped()) {
1316                         //fixup local variable type
1317                         v.type = chk.checkLocalVarType(tree, tree.init.type.baseType(), tree.name);
1318                     }
1319                 }
1320                 if (tree.isImplicitlyTyped()) {
1321                     setSyntheticVariableType(tree, v.type);
1322                 }

1406             }
1407         }
1408     }
1409 
1410     public void visitSkip(JCSkip tree) {
1411         result = null;
1412     }
1413 
1414     public void visitBlock(JCBlock tree) {
1415         if (env.info.scope.owner.kind == TYP || env.info.scope.owner.kind == ERR) {
1416             // Block is a static or instance initializer;
1417             // let the owner of the environment be a freshly
1418             // created BLOCK-method.
1419             Symbol fakeOwner =
1420                 new MethodSymbol(tree.flags | BLOCK |
1421                     env.info.scope.owner.flags() & STRICTFP, names.empty, null,
1422                     env.info.scope.owner);
1423             final Env<AttrContext> localEnv =
1424                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1425 
1426             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;




1427             // Attribute all type annotations in the block
1428             annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
1429             annotate.flush();
1430             attribStats(tree.stats, localEnv);
1431 
1432             {
1433                 // Store init and clinit type annotations with the ClassSymbol
1434                 // to allow output in Gen.normalizeDefs.
1435                 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1436                 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1437                 if ((tree.flags & STATIC) != 0) {
1438                     cs.appendClassInitTypeAttributes(tas);
1439                 } else {
1440                     cs.appendInitTypeAttributes(tas);
1441                 }
1442             }
1443         } else {
1444             // Create a new local environment with a local scope.
1445             Env<AttrContext> localEnv =
1446                 env.dup(tree, env.info.dup(env.info.scope.dup()));

1471         // include condition's bindings when true in the body:
1472         Env<AttrContext> whileEnv = bindingEnv(env, condBindings.bindingsWhenTrue);
1473         try {
1474             attribStat(tree.body, whileEnv.dup(tree));
1475         } finally {
1476             whileEnv.info.scope.leave();
1477         }
1478         if (!breaksOutOf(tree, tree.body)) {
1479             //include condition's bindings when false after the while, if cannot get out of the loop
1480             condBindings.bindingsWhenFalse.forEach(env.info.scope::enter);
1481             condBindings.bindingsWhenFalse.forEach(BindingSymbol::preserveBinding);
1482         }
1483         result = null;
1484     }
1485 
1486     private boolean breaksOutOf(JCTree loop, JCTree body) {
1487         preFlow(body);
1488         return flow.breaksOutOf(env, loop, body, make);
1489     }
1490 

































1491     public void visitForLoop(JCForLoop tree) {
1492         Env<AttrContext> loopEnv =
1493             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1494         MatchBindings condBindings = MatchBindingsComputer.EMPTY;
1495         try {
1496             attribStats(tree.init, loopEnv);
1497             if (tree.cond != null) {
1498                 attribExpr(tree.cond, loopEnv, syms.booleanType);
1499                 // include condition's bindings when true in the body and step:
1500                 condBindings = matchBindings;
1501             }
1502             Env<AttrContext> bodyEnv = bindingEnv(loopEnv, condBindings.bindingsWhenTrue);
1503             try {
1504                 bodyEnv.tree = tree; // before, we were not in loop!
1505                 attribStats(tree.step, bodyEnv);
1506                 attribStat(tree.body, bodyEnv);
1507             } finally {
1508                 bodyEnv.info.scope.leave();
1509             }
1510             result = null;

1514         }
1515         if (!breaksOutOf(tree, tree.body)) {
1516             //include condition's body when false after the while, if cannot get out of the loop
1517             condBindings.bindingsWhenFalse.forEach(env.info.scope::enter);
1518             condBindings.bindingsWhenFalse.forEach(BindingSymbol::preserveBinding);
1519         }
1520     }
1521 
1522     public void visitForeachLoop(JCEnhancedForLoop tree) {
1523         Env<AttrContext> loopEnv =
1524             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1525         try {
1526             //the Formal Parameter of a for-each loop is not in the scope when
1527             //attributing the for-each expression; we mimic this by attributing
1528             //the for-each expression first (against original scope).
1529             Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
1530             chk.checkNonVoid(tree.pos(), exprType);
1531             Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
1532             if (elemtype == null) {
1533                 // or perhaps expr implements Iterable<T>?
1534                 Type base = types.asSuper(exprType, syms.iterableType.tsym);
1535                 if (base == null) {
1536                     log.error(tree.expr.pos(),
1537                               Errors.ForeachNotApplicableToType(exprType,
1538                                                                 Fragments.TypeReqArrayOrIterable));
1539                     elemtype = types.createErrorType(exprType);
1540                 } else {
1541                     List<Type> iterableParams = base.allparams();
1542                     elemtype = iterableParams.isEmpty()
1543                         ? syms.objectType
1544                         : types.wildUpperBound(iterableParams.head);
1545 
1546                     // Check the return type of the method iterator().
1547                     // This is the bare minimum we need to verify to make sure code generation doesn't crash.
1548                     Symbol iterSymbol = rs.resolveInternalMethod(tree.pos(),
1549                             loopEnv, types.skipTypeVars(exprType, false), names.iterator, List.nil(), List.nil());
1550                     if (types.asSuper(iterSymbol.type.getReturnType(), syms.iteratorType.tsym) == null) {
1551                         log.error(tree.pos(),
1552                                 Errors.ForeachNotApplicableToType(exprType, Fragments.TypeReqArrayOrIterable));
1553                     }
1554                 }
1555             }
1556             if (tree.var.isImplicitlyTyped()) {
1557                 Type inferredType = chk.checkLocalVarType(tree.var, elemtype, tree.var.name);
1558                 setSyntheticVariableType(tree.var, inferredType);
1559             }
1560             attribStat(tree.var, loopEnv);
1561             chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
1562             loopEnv.tree = tree; // before, we were not in loop!
1563             attribStat(tree.body, loopEnv);
1564             result = null;
1565         }
1566         finally {
1567             loopEnv.info.scope.leave();
1568         }
1569     }
1570 

1842     // where
1843     /** Return the selected enumeration constant symbol, or null. */
1844     private Symbol enumConstant(JCTree tree, Type enumType) {
1845         if (tree.hasTag(IDENT)) {
1846             JCIdent ident = (JCIdent)tree;
1847             Name name = ident.name;
1848             for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1849                 if (sym.kind == VAR) {
1850                     Symbol s = ident.sym = sym;
1851                     ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1852                     ident.type = s.type;
1853                     return ((s.flags_field & Flags.ENUM) == 0)
1854                         ? null : s;
1855                 }
1856             }
1857         }
1858         return null;
1859     }
1860 
1861     public void visitSynchronized(JCSynchronized tree) {
1862         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1863         if (env.info.lint.isEnabled(LintCategory.SYNCHRONIZATION) && isValueBased(tree.lock.type)) {
1864             log.warning(LintCategory.SYNCHRONIZATION, tree.pos(), Warnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
1865         }
1866         attribStat(tree.body, env);
1867         result = null;
1868     }
1869         // where
1870         private boolean isValueBased(Type t) {
1871             return t != null && t.tsym != null && (t.tsym.flags() & VALUE_BASED) != 0;
1872         }
1873 
1874 
1875     public void visitTry(JCTry tree) {
1876         // Create a new local environment with a local
1877         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1878         try {
1879             boolean isTryWithResource = tree.resources.nonEmpty();
1880             // Create a nested environment for attributing the try block if needed
1881             Env<AttrContext> tryEnv = isTryWithResource ?
1882                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :

1931                     chk.checkType(c.param.vartype.pos(),
1932                                   chk.checkClassType(c.param.vartype.pos(), ctype),
1933                                   syms.throwableType);
1934                     attribStat(c.body, catchEnv);
1935                 } finally {
1936                     catchEnv.info.scope.leave();
1937                 }
1938             }
1939 
1940             // Attribute finalizer
1941             if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1942             result = null;
1943         }
1944         finally {
1945             localEnv.info.scope.leave();
1946         }
1947     }
1948 
1949     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
1950         if (!resource.isErroneous() &&
1951             types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
1952             !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
1953             Symbol close = syms.noSymbol;
1954             Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
1955             try {
1956                 close = rs.resolveQualifiedMethod(pos,
1957                         env,
1958                         types.skipTypeVars(resource, false),
1959                         names.close,
1960                         List.nil(),
1961                         List.nil());
1962             }
1963             finally {
1964                 log.popDiagnosticHandler(discardHandler);
1965             }
1966             if (close.kind == MTH &&
1967                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
1968                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
1969                     env.info.lint.isEnabled(LintCategory.TRY)) {
1970                 log.warning(LintCategory.TRY, pos, Warnings.TryResourceThrowsInterruptedExc(resource));
1971             }

2121             if (unboxedTypes.stream().allMatch(t -> t.isPrimitive())) {
2122                 // If one arm has an integer subrange type (i.e., byte,
2123                 // short, or char), and the other is an integer constant
2124                 // that fits into the subrange, return the subrange type.
2125                 for (Type type : unboxedTypes) {
2126                     if (!type.getTag().isStrictSubRangeOf(INT)) {
2127                         continue;
2128                     }
2129                     if (unboxedTypes.stream().filter(t -> t != type).allMatch(t -> t.hasTag(INT) && types.isAssignable(t, type)))
2130                         return type.baseType();
2131                 }
2132 
2133                 for (TypeTag tag : primitiveTags) {
2134                     Type candidate = syms.typeOfTag[tag.ordinal()];
2135                     if (unboxedTypes.stream().allMatch(t -> types.isSubtype(t, candidate))) {
2136                         return candidate;
2137                     }
2138                 }
2139             }
2140 
2141             // Those were all the cases that could result in a primitive

2142             condTypes = condTypes.stream()
2143                                  .map(t -> t.isPrimitive() ? types.boxedClass(t).type : t)

2144                                  .collect(List.collector());
2145 
2146             for (Type type : condTypes) {
2147                 if (condTypes.stream().filter(t -> t != type).allMatch(t -> types.isAssignable(t, type)))
2148                     return type.baseType();
2149             }
2150 
2151             Iterator<DiagnosticPosition> posIt = positions.iterator();
2152 
2153             condTypes = condTypes.stream()
2154                                  .map(t -> chk.checkNonVoid(posIt.next(), t))
2155                                  .collect(List.collector());
2156 
2157             // both are known to be reference types.  The result is
2158             // lub(thentype,elsetype). This cannot fail, as it will
2159             // always be possible to infer "Object" if nothing better.
2160             return types.lub(condTypes.stream()
2161                         .map(t -> t.baseType())
2162                         .filter(t -> !t.hasTag(BOT))
2163                         .collect(List.collector()));
2164         }
2165 
2166     static final TypeTag[] primitiveTags = new TypeTag[]{
2167         BYTE,
2168         CHAR,
2169         SHORT,
2170         INT,
2171         LONG,
2172         FLOAT,
2173         DOUBLE,
2174         BOOLEAN,
2175     };
2176 
2177     Env<AttrContext> bindingEnv(Env<AttrContext> env, List<BindingSymbol> bindings) {

2564             // ... and attribute the method using as a prototype a methodtype
2565             // whose formal argument types is exactly the list of actual
2566             // arguments (this will also set the method symbol).
2567             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
2568             localEnv.info.pendingResolutionPhase = null;
2569             Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
2570 
2571             // Compute the result type.
2572             Type restype = mtype.getReturnType();
2573             if (restype.hasTag(WILDCARD))
2574                 throw new AssertionError(mtype);
2575 
2576             Type qualifier = (tree.meth.hasTag(SELECT))
2577                     ? ((JCFieldAccess) tree.meth).selected.type
2578                     : env.enclClass.sym.type;
2579             Symbol msym = TreeInfo.symbol(tree.meth);
2580             restype = adjustMethodReturnType(msym, qualifier, methName, argtypes, restype);
2581 
2582             chk.checkRefTypes(tree.typeargs, typeargtypes);
2583 





























2584             // Check that value of resulting type is admissible in the
2585             // current context.  Also, capture the return type
2586             Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true);
2587             result = check(tree, capturedRes, KindSelector.VAL, resultInfo);
2588         }
2589         chk.validate(tree.typeargs, localEnv);
2590     }
2591     //where
2592         Type adjustMethodReturnType(Symbol msym, Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
2593             if (msym != null &&
2594                     (msym.owner == syms.objectType.tsym || msym.owner.isInterface()) &&
2595                     methodName == names.getClass &&
2596                     argtypes.isEmpty()) {
2597                 // as a special case, x.getClass() has type Class<? extends |X|>




2598                 return new ClassType(restype.getEnclosingType(),
2599                         List.of(new WildcardType(types.erasure(qualifierType),
2600                                 BoundKind.EXTENDS,
2601                                 syms.boundClass)),
2602                         restype.tsym,
2603                         restype.getMetadata());

2604             } else if (msym != null &&
2605                     msym.owner == syms.arrayClass &&
2606                     methodName == names.clone &&
2607                     types.isArray(qualifierType)) {
2608                 // as a special case, array.clone() has a result that is
2609                 // the same as static type of the array being cloned
2610                 return qualifierType;
2611             } else {
2612                 return restype;
2613             }
2614         }
2615 
2616         /** Check that given application node appears as first statement
2617          *  in a constructor call.
2618          *  @param tree          The application node
2619          *  @param enclMethod    The enclosing method of the application.
2620          *  @param error         Should an error be issued?
2621          */
2622         boolean checkFirstConstructorStat(JCMethodInvocation tree, JCMethodDecl enclMethod, boolean error) {
2623             if (enclMethod != null && enclMethod.name == names.init) {

2706                 clazzid1 = make.at(tree.pos).
2707                     AnnotatedType(annos, clazzid1);
2708             } else if (clazz.hasTag(TYPEAPPLY)) {
2709                 clazzid1 = make.at(tree.pos).
2710                     TypeApply(clazzid1,
2711                               ((JCTypeApply) clazz).arguments);
2712             }
2713 
2714             clazz = clazzid1;
2715         }
2716 
2717         // Attribute clazz expression and store
2718         // symbol + type back into the attributed tree.
2719         Type clazztype;
2720 
2721         try {
2722             env.info.isNewClass = true;
2723             clazztype = TreeInfo.isEnumInit(env.tree) ?
2724                 attribIdentAsEnumType(env, (JCIdent)clazz) :
2725                 attribType(clazz, env);



2726         } finally {
2727             env.info.isNewClass = false;
2728         }
2729 
2730         clazztype = chk.checkDiamond(tree, clazztype);
2731         chk.validate(clazz, localEnv);
2732         if (tree.encl != null) {
2733             // We have to work in this case to store
2734             // symbol + type back into the attributed tree.
2735             tree.clazz.type = clazztype;
2736             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
2737             clazzid.type = ((JCIdent) clazzid).sym.type;
2738             if (annoclazzid != null) {
2739                 annoclazzid.type = clazzid.type;
2740             }
2741             if (!clazztype.isErroneous()) {
2742                 if (cdef != null && clazztype.tsym.isInterface()) {
2743                     log.error(tree.encl.pos(), Errors.AnonClassImplIntfNoQualForNew);
2744                 } else if (clazztype.tsym.isStatic()) {
2745                     log.error(tree.encl.pos(), Errors.QualifiedNewOfStaticClass(clazztype.tsym));

2752         }
2753 
2754         // Attribute constructor arguments.
2755         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2756         final KindSelector pkind =
2757             attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
2758         List<Type> argtypes = argtypesBuf.toList();
2759         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
2760 
2761         if (clazztype.hasTag(CLASS) || clazztype.hasTag(ERROR)) {
2762             // Enums may not be instantiated except implicitly
2763             if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 &&
2764                 (!env.tree.hasTag(VARDEF) ||
2765                  (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 ||
2766                  ((JCVariableDecl) env.tree).init != tree))
2767                 log.error(tree.pos(), Errors.EnumCantBeInstantiated);
2768 
2769             boolean isSpeculativeDiamondInferenceRound = TreeInfo.isDiamond(tree) &&
2770                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2771             boolean skipNonDiamondPath = false;








2772             // Check that class is not abstract
2773             if (cdef == null && !isSpeculativeDiamondInferenceRound && // class body may be nulled out in speculative tree copy
2774                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
2775                 log.error(tree.pos(),
2776                           Errors.AbstractCantBeInstantiated(clazztype.tsym));
2777                 skipNonDiamondPath = true;
2778             } else if (cdef != null && clazztype.tsym.isInterface()) {
2779                 // Check that no constructor arguments are given to
2780                 // anonymous classes implementing an interface
2781                 if (!argtypes.isEmpty())
2782                     log.error(tree.args.head.pos(), Errors.AnonClassImplIntfNoArgs);
2783 
2784                 if (!typeargtypes.isEmpty())
2785                     log.error(tree.typeargs.head.pos(), Errors.AnonClassImplIntfNoTypeargs);
2786 
2787                 // Error recovery: pretend no arguments were supplied.
2788                 argtypes = List.nil();
2789                 typeargtypes = List.nil();
2790                 skipNonDiamondPath = true;
2791             }
2792             if (TreeInfo.isDiamond(tree)) {
2793                 ClassType site = new ClassType(clazztype.getEnclosingType(),
2794                             clazztype.tsym.type.getTypeArguments(),
2795                                                clazztype.tsym,
2796                                                clazztype.getMetadata());

2797 
2798                 Env<AttrContext> diamondEnv = localEnv.dup(tree);
2799                 diamondEnv.info.selectSuper = cdef != null || tree.classDeclRemoved();
2800                 diamondEnv.info.pendingResolutionPhase = null;
2801 
2802                 //if the type of the instance creation expression is a class type
2803                 //apply method resolution inference (JLS 15.12.2.7). The return type
2804                 //of the resolved constructor will be a partially instantiated type
2805                 Symbol constructor = rs.resolveDiamond(tree.pos(),
2806                             diamondEnv,
2807                             site,
2808                             argtypes,
2809                             typeargtypes);
2810                 tree.constructor = constructor.baseSymbol();
2811 
2812                 final TypeSymbol csym = clazztype.tsym;
2813                 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes),
2814                         diamondContext(tree, csym, resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
2815                 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
2816                 constructorType = checkId(tree, site,

2923                                 this.resultInfo = prevResult;
2924                             }
2925                         });
2926             } else {
2927                 if (isDiamond && clazztype.hasTag(CLASS)) {
2928                     List<Type> invalidDiamondArgs = chk.checkDiamondDenotable((ClassType)clazztype);
2929                     if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
2930                         // One or more types inferred in the previous steps is non-denotable.
2931                         Fragment fragment = Diamond(clazztype.tsym);
2932                         log.error(tree.clazz.pos(),
2933                                 Errors.CantApplyDiamond1(
2934                                         fragment,
2935                                         invalidDiamondArgs.size() > 1 ?
2936                                                 DiamondInvalidArgs(invalidDiamondArgs, fragment) :
2937                                                 DiamondInvalidArg(invalidDiamondArgs, fragment)));
2938                     }
2939                     // For <>(){}, inferred types must also be accessible.
2940                     for (Type t : clazztype.getTypeArguments()) {
2941                         rs.checkAccessibleType(env, t);
2942                     }

2943                 }
2944 
2945                 // If we already errored, be careful to avoid a further avalanche. ErrorType answers
2946                 // false for isInterface call even when the original type is an interface.
2947                 boolean implementing = clazztype.tsym.isInterface() ||
2948                         clazztype.isErroneous() && !clazztype.getOriginalType().hasTag(NONE) &&
2949                         clazztype.getOriginalType().tsym.isInterface();
2950 
2951                 if (implementing) {
2952                     cdef.implementing = List.of(clazz);
2953                 } else {
2954                     cdef.extending = clazz;
2955                 }
2956 
2957                 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2958                     rs.isSerializable(clazztype)) {
2959                     localEnv.info.isSerializable = true;
2960                 }
2961 
2962                 attribStat(cdef, localEnv);

2995             result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK));
2996             chk.validate(tree.typeargs, localEnv);
2997         }
2998 
2999         CheckContext diamondContext(JCNewClass clazz, TypeSymbol tsym, CheckContext checkContext) {
3000             return new Check.NestedCheckContext(checkContext) {
3001                 @Override
3002                 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
3003                     enclosingContext.report(clazz.clazz,
3004                             diags.fragment(Fragments.CantApplyDiamond1(Fragments.Diamond(tsym), details)));
3005                 }
3006             };
3007         }
3008 
3009     /** Make an attributed null check tree.
3010      */
3011     public JCExpression makeNullCheck(JCExpression arg) {
3012         // optimization: new Outer() can never be null; skip null check
3013         if (arg.getTag() == NEWCLASS)
3014             return arg;



3015         // optimization: X.this is never null; skip null check
3016         Name name = TreeInfo.name(arg);
3017         if (name == names._this || name == names._super) return arg;
3018 
3019         JCTree.Tag optag = NULLCHK;
3020         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
3021         tree.operator = operators.resolveUnary(arg, optag, arg.type);
3022         tree.type = arg.type;
3023         return tree;
3024     }
3025 
3026     public void visitNewArray(JCNewArray tree) {
3027         Type owntype = types.createErrorType(tree.type);
3028         Env<AttrContext> localEnv = env.dup(tree);
3029         Type elemtype;
3030         if (tree.elemtype != null) {
3031             elemtype = attribType(tree.elemtype, localEnv);
3032             chk.validate(tree.elemtype, localEnv);
3033             owntype = elemtype;
3034             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {

4009         if (operator != operators.noOpSymbol &&
4010                 !left.isErroneous() &&
4011                 !right.isErroneous()) {
4012             owntype = operator.type.getReturnType();
4013             int opc = ((OperatorSymbol)operator).opcode;
4014             // If both arguments are constants, fold them.
4015             if (left.constValue() != null && right.constValue() != null) {
4016                 Type ctype = cfolder.fold2(opc, left, right);
4017                 if (ctype != null) {
4018                     owntype = cfolder.coerce(ctype, owntype);
4019                 }
4020             }
4021 
4022             // Check that argument types of a reference ==, != are
4023             // castable to each other, (JLS 15.21).  Note: unboxing
4024             // comparisons will not have an acmp* opc at this point.
4025             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
4026                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
4027                     log.error(tree.pos(), Errors.IncomparableTypes(left, right));
4028                 }

4029             }
4030 
4031             chk.checkDivZero(tree.rhs.pos(), operator, right);
4032         }
4033         result = check(tree, owntype, KindSelector.VAL, resultInfo);
4034     }
4035 
4036     public void visitTypeCast(final JCTypeCast tree) {
4037         Type clazztype = attribType(tree.clazz, env);
4038         chk.validate(tree.clazz, env, false);
4039         //a fresh environment is required for 292 inference to work properly ---
4040         //see Infer.instantiatePolymorphicSignatureInstance()
4041         Env<AttrContext> localEnv = env.dup(tree);
4042         //should we propagate the target type?
4043         final ResultInfo castInfo;
4044         JCExpression expr = TreeInfo.skipParens(tree.expr);
4045         boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
4046         if (isPoly) {
4047             //expression is a poly - we need to propagate target type info
4048             castInfo = new ResultInfo(KindSelector.VAL, clazztype,

4244     }
4245 
4246     public void visitSelect(JCFieldAccess tree) {
4247         // Determine the expected kind of the qualifier expression.
4248         KindSelector skind = KindSelector.NIL;
4249         if (tree.name == names._this || tree.name == names._super ||
4250                 tree.name == names._class)
4251         {
4252             skind = KindSelector.TYP;
4253         } else {
4254             if (pkind().contains(KindSelector.PCK))
4255                 skind = KindSelector.of(skind, KindSelector.PCK);
4256             if (pkind().contains(KindSelector.TYP))
4257                 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4258             if (pkind().contains(KindSelector.VAL_MTH))
4259                 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4260         }
4261 
4262         // Attribute the qualifier expression, and determine its symbol (if any).
4263         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));










4264         if (!pkind().contains(KindSelector.TYP_PCK))
4265             site = capture(site); // Capture field access
4266 
4267         // don't allow T.class T[].class, etc
4268         if (skind == KindSelector.TYP) {
4269             Type elt = site;
4270             while (elt.hasTag(ARRAY))
4271                 elt = ((ArrayType)elt).elemtype;
4272             if (elt.hasTag(TYPEVAR)) {
4273                 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4274                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4275                 tree.sym = tree.type.tsym;
4276                 return ;
4277             }
4278         }
4279 
4280         // If qualifier symbol is a type or `super', assert `selectSuper'
4281         // for the selection. This is relevant for determining whether
4282         // protected symbols are accessible.
4283         Symbol sitesym = TreeInfo.symbol(tree.selected);

4284         boolean selectSuperPrev = env.info.selectSuper;
4285         env.info.selectSuper =
4286             sitesym != null &&
4287             sitesym.name == names._super;
4288 
4289         // Determine the symbol represented by the selection.
4290         env.info.pendingResolutionPhase = null;
4291         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
4292         if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
4293             log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym));
4294             sym = syms.errSymbol;
4295         }
4296         if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
4297             site = capture(site);
4298             sym = selectSym(tree, sitesym, site, env, resultInfo);
4299         }
4300         boolean varArgs = env.info.lastResolveVarargs();
4301         tree.sym = sym;
4302 
4303         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {

4359             if (!allowStaticInterfaceMethods && sitesym.isInterface() &&
4360                     sym.isStatic() && sym.kind == MTH) {
4361                 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.pos(), Feature.STATIC_INTERFACE_METHODS_INVOKE.error(sourceName));
4362             }
4363         } else if (sym.kind != ERR &&
4364                    (sym.flags() & STATIC) != 0 &&
4365                    sym.name != names._class) {
4366             // If the qualified item is not a type and the selected item is static, report
4367             // a warning. Make allowance for the class of an array type e.g. Object[].class)
4368             chk.warnStatic(tree, Warnings.StaticNotQualifiedByType(sym.kind.kindName(), sym.owner));
4369         }
4370 
4371         // If we are selecting an instance member via a `super', ...
4372         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
4373 
4374             // Check that super-qualified symbols are not abstract (JLS)
4375             rs.checkNonAbstract(tree.pos(), sym);
4376 
4377             if (site.isRaw()) {
4378                 // Determine argument types for site.
4379                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
4380                 if (site1 != null) site = site1;
4381             }
4382         }
4383 
4384         if (env.info.isSerializable) {
4385             chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4386         }
4387 
4388         env.info.selectSuper = selectSuperPrev;
4389         result = checkId(tree, site, sym, env, resultInfo);
4390     }
4391     //where
4392         /** Determine symbol referenced by a Select expression,
4393          *
4394          *  @param tree   The select tree.
4395          *  @param site   The type of the selected expression,
4396          *  @param env    The current environment.
4397          *  @param resultInfo The current result.
4398          */
4399         private Symbol selectSym(JCFieldAccess tree,

4402                                  Env<AttrContext> env,
4403                                  ResultInfo resultInfo) {
4404             DiagnosticPosition pos = tree.pos();
4405             Name name = tree.name;
4406             switch (site.getTag()) {
4407             case PACKAGE:
4408                 return rs.accessBase(
4409                     rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind),
4410                     pos, location, site, name, true);
4411             case ARRAY:
4412             case CLASS:
4413                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
4414                     return rs.resolveQualifiedMethod(
4415                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
4416                 } else if (name == names._this || name == names._super) {
4417                     return rs.resolveSelf(pos, env, site.tsym, name);
4418                 } else if (name == names._class) {
4419                     // In this case, we have already made sure in
4420                     // visitSelect that qualifier expression is a type.
4421                     return syms.getClassField(site, types);


4422                 } else {
4423                     // We are seeing a plain identifier as selector.
4424                     Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind);
4425                         sym = rs.accessBase(sym, pos, location, site, name, true);
4426                     return sym;
4427                 }
4428             case WILDCARD:
4429                 throw new AssertionError(tree);
4430             case TYPEVAR:
4431                 // Normally, site.getUpperBound() shouldn't be null.
4432                 // It should only happen during memberEnter/attribBase
4433                 // when determining the super type which *must* be
4434                 // done before attributing the type variables.  In
4435                 // other words, we are seeing this illegal program:
4436                 // class B<T> extends A<T.foo> {}
4437                 Symbol sym = (site.getUpperBound() != null)
4438                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
4439                     : null;
4440                 if (sym == null) {
4441                     log.error(pos, Errors.TypeVarCantBeDeref);

4505             if (resultInfo.pkind.contains(KindSelector.POLY)) {
4506                 return attrRecover.recoverMethodInvocation(tree, site, sym, env, resultInfo);
4507             } else {
4508                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
4509             }
4510         }
4511 
4512         Type checkIdInternal(JCTree tree,
4513                      Type site,
4514                      Symbol sym,
4515                      Type pt,
4516                      Env<AttrContext> env,
4517                      ResultInfo resultInfo) {
4518             if (pt.isErroneous()) {
4519                 return types.createErrorType(site);
4520             }
4521             Type owntype; // The computed type of this identifier occurrence.
4522             switch (sym.kind) {
4523             case TYP:
4524                 // For types, the computed type equals the symbol's type,
4525                 // except for two situations:
4526                 owntype = sym.type;
4527                 if (owntype.hasTag(CLASS)) {

4528                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
4529                     Type ownOuter = owntype.getEnclosingType();
4530 
4531                     // (a) If the symbol's type is parameterized, erase it







4532                     // because no type parameters were given.
4533                     // We recover generic outer type later in visitTypeApply.
4534                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
4535                         owntype = types.erasure(owntype);
4536                     }
4537 
4538                     // (b) If the symbol's type is an inner class, then
4539                     // we have to interpret its outer type as a superclass
4540                     // of the site type. Example:
4541                     //
4542                     // class Tree<A> { class Visitor { ... } }
4543                     // class PointTree extends Tree<Point> { ... }
4544                     // ...PointTree.Visitor...
4545                     //
4546                     // Then the type of the last expression above is
4547                     // Tree<Point>.Visitor.
4548                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
4549                         Type normOuter = site;
4550                         if (normOuter.hasTag(CLASS)) {
4551                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
4552                         }
4553                         if (normOuter == null) // perhaps from an import
4554                             normOuter = types.erasure(ownOuter);
4555                         if (normOuter != ownOuter)
4556                             owntype = new ClassType(
4557                                 normOuter, List.nil(), owntype.tsym,
4558                                 owntype.getMetadata());
4559                     }
4560                 }
4561                 break;
4562             case VAR:
4563                 VarSymbol v = (VarSymbol)sym;
4564 
4565                 if (env.info.enclVar != null
4566                         && v.type.hasTag(NONE)) {
4567                     //self reference to implicitly typed variable declaration
4568                     log.error(TreeInfo.positionFor(v, env.enclClass), Errors.CantInferLocalVarType(v.name, Fragments.LocalSelfRef));
4569                     return v.type = types.createErrorType(v.type);
4570                 }
4571 
4572                 // Test (4): if symbol is an instance field of a raw type,
4573                 // which is being assigned to, issue an unchecked warning if
4574                 // its type changes under erasure.
4575                 if (KindSelector.ASG.subset(pkind()) &&
4576                     v.owner.kind == TYP &&
4577                     (v.flags() & STATIC) == 0 &&
4578                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {

4855             //depending on the current check context
4856             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
4857             return types.createErrorType(site);
4858         } catch (Resolve.InapplicableMethodException ex) {
4859             final JCDiagnostic diag = ex.getDiagnostic();
4860             Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
4861                 @Override
4862                 protected Pair<Symbol, JCDiagnostic> errCandidate() {
4863                     return new Pair<>(sym, diag);
4864                 }
4865             };
4866             List<Type> argtypes2 = argtypes.map(
4867                     rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
4868             JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
4869                     env.tree, sym, site, sym.name, argtypes2, typeargtypes);
4870             log.report(errDiag);
4871             return types.createErrorType(site);
4872         }
4873     }
4874 




























4875     public void visitLiteral(JCLiteral tree) {
4876         result = check(tree, litType(tree.typetag).constType(tree.value),
4877                 KindSelector.VAL, resultInfo);
4878     }
4879     //where
4880     /** Return the type of a literal with given type tag.
4881      */
4882     Type litType(TypeTag tag) {
4883         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
4884     }
4885 
4886     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
4887         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
4888     }
4889 
4890     public void visitTypeArray(JCArrayTypeTree tree) {
4891         Type etype = attribType(tree.elemtype, env);
4892         Type type = new ArrayType(etype, syms.arrayClass);
4893         result = check(tree, type, KindSelector.TYP, resultInfo);
4894     }

4921                 }
4922                 // Compute the proper generic outer
4923                 Type clazzOuter = clazztype.getEnclosingType();
4924                 if (clazzOuter.hasTag(CLASS)) {
4925                     Type site;
4926                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
4927                     if (clazz.hasTag(IDENT)) {
4928                         site = env.enclClass.sym.type;
4929                     } else if (clazz.hasTag(SELECT)) {
4930                         site = ((JCFieldAccess) clazz).selected.type;
4931                     } else throw new AssertionError(""+tree);
4932                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
4933                         if (site.hasTag(CLASS))
4934                             site = types.asOuterSuper(site, clazzOuter.tsym);
4935                         if (site == null)
4936                             site = types.erasure(clazzOuter);
4937                         clazzOuter = site;
4938                     }
4939                 }
4940                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
4941                                         clazztype.getMetadata());
4942             } else {
4943                 if (formals.length() != 0) {
4944                     log.error(tree.pos(),
4945                               Errors.WrongNumberTypeArgs(Integer.toString(formals.length())));
4946                 } else {
4947                     log.error(tree.pos(), Errors.TypeDoesntTakeParams(clazztype.tsym));
4948                 }
4949                 owntype = types.createErrorType(tree.type);
4950             }
4951         }
4952         result = check(tree, owntype, KindSelector.TYP, resultInfo);
4953     }
4954 
4955     public void visitTypeUnion(JCTypeUnion tree) {
4956         ListBuffer<Type> multicatchTypes = new ListBuffer<>();
4957         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
4958         for (JCExpression typeTree : tree.alternatives) {
4959             Type ctype = attribType(typeTree, env);
4960             ctype = chk.checkType(typeTree.pos(),
4961                           chk.checkClassType(typeTree.pos(), ctype),

5048         if (bounds.length() == 0) {
5049             return syms.objectType;
5050         } else if (bounds.length() == 1) {
5051             return bounds.head.type;
5052         } else {
5053             Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
5054             // ... the variable's bound is a class type flagged COMPOUND
5055             // (see comment for TypeVar.bound).
5056             // In this case, generate a class tree that represents the
5057             // bound class, ...
5058             JCExpression extending;
5059             List<JCExpression> implementing;
5060             if (!bounds.head.type.isInterface()) {
5061                 extending = bounds.head;
5062                 implementing = bounds.tail;
5063             } else {
5064                 extending = null;
5065                 implementing = bounds;
5066             }
5067             JCClassDecl cd = make.at(tree).ClassDef(
5068                 make.Modifiers(PUBLIC | ABSTRACT),
5069                 names.empty, List.nil(),
5070                 extending, implementing, List.nil());
5071 
5072             ClassSymbol c = (ClassSymbol)owntype.tsym;
5073             Assert.check((c.flags() & COMPOUND) != 0);
5074             cd.sym = c;
5075             c.sourcefile = env.toplevel.sourcefile;
5076 
5077             // ... and attribute the bound class
5078             c.flags_field |= UNATTRIBUTED;
5079             Env<AttrContext> cenv = enter.classEnv(cd, env);
5080             typeEnvs.put(c, cenv);
5081             attribClass(c);
5082             return owntype;
5083         }
5084     }
5085 
5086     public void visitWildcard(JCWildcard tree) {
5087         //- System.err.println("visitWildcard("+tree+");");//DEBUG
5088         Type type = (tree.kind.kind == BoundKind.UNBOUND)
5089             ? syms.objectType
5090             : attribType(tree.inner, env);
5091         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
5092                                               tree.kind.kind,
5093                                               syms.boundClass),
5094                 KindSelector.TYP, resultInfo);
5095     }
5096 
5097     public void visitAnnotation(JCAnnotation tree) {
5098         Assert.error("should be handled in annotate");
5099     }
5100 
5101     @Override
5102     public void visitModifiers(JCModifiers tree) {
5103         //error recovery only:
5104         Assert.check(resultInfo.pkind == KindSelector.ERR);
5105 
5106         attribAnnotationTypes(tree.annotations, env);
5107     }
5108 
5109     public void visitAnnotatedType(JCAnnotatedType tree) {
5110         attribAnnotationTypes(tree.annotations, env);
5111         Type underlyingType = attribType(tree.underlyingType, env);

5186             chk.completionError(pos, ex);
5187         }
5188     }
5189 
5190     void attribModule(ModuleSymbol m) {
5191         // Get environment current at the point of module definition.
5192         Env<AttrContext> env = enter.typeEnvs.get(m);
5193         attribStat(env.tree, env);
5194     }
5195 
5196     /** Main method: attribute class definition associated with given class symbol.
5197      *  reporting completion failures at the given position.
5198      *  @param pos The source position at which completion errors are to be
5199      *             reported.
5200      *  @param c   The class symbol whose definition will be attributed.
5201      */
5202     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
5203         try {
5204             annotate.flush();
5205             attribClass(c);





5206         } catch (CompletionFailure ex) {
5207             chk.completionError(pos, ex);
5208         }
5209     }
5210 
5211     /** Attribute class definition associated with given class symbol.
5212      *  @param c   The class symbol whose definition will be attributed.
5213      */
5214     void attribClass(ClassSymbol c) throws CompletionFailure {
5215         if (c.type.hasTag(ERROR)) return;
5216 
5217         // Check for cycles in the inheritance graph, which can arise from
5218         // ill-formed class files.
5219         chk.checkNonCyclic(null, c.type);
5220 
5221         Type st = types.supertype(c.type);
5222         if ((c.flags_field & Flags.COMPOUND) == 0 &&
5223             (c.flags_field & Flags.SUPER_OWNER_ATTRIBUTED) == 0) {
5224             // First, attribute superclass.
5225             if (st.hasTag(CLASS))

5306                                                   .filter(s -> s.tsym.isSealed())
5307                                                   .map(s -> (ClassSymbol) s.tsym)
5308                                                   .collect(List.collector());
5309 
5310             if (sealedSupers.isEmpty()) {
5311                 if ((c.flags_field & Flags.NON_SEALED) != 0) {
5312                     boolean hasErrorSuper = false;
5313 
5314                     hasErrorSuper |= types.directSupertypes(c.type)
5315                                           .stream()
5316                                           .anyMatch(s -> s.tsym.kind == Kind.ERR);
5317 
5318                     ClassType ct = (ClassType) c.type;
5319 
5320                     hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5321 
5322                     if (!hasErrorSuper) {
5323                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5324                     }
5325                 }
5326             } else {
5327                 if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5328                     log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5329                 }
5330 
5331                 if (!c.type.isCompound()) {
5332                     for (ClassSymbol supertypeSym : sealedSupers) {
5333                         if (!supertypeSym.permitted.contains(c.type.tsym)) {
5334                             log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5335                         }
5336                     }
5337                     if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5338                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5339                                 c.isInterface() ?
5340                                         Errors.NonSealedOrSealedExpected :
5341                                         Errors.NonSealedSealedOrFinalExpected);
5342                     }
5343                 }
5344             }
5345 
5346             // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,

5361 
5362             try {
5363                 deferredLintHandler.flush(env.tree);
5364                 env.info.returnResult = null;
5365                 // java.lang.Enum may not be subclassed by a non-enum
5366                 if (st.tsym == syms.enumSym &&
5367                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5368                     log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5369 
5370                 // Enums may not be extended by source-level classes
5371                 if (st.tsym != null &&
5372                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5373                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5374                     log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5375                 }
5376 
5377                 if (rs.isSerializable(c.type)) {
5378                     env.info.isSerializable = true;
5379                 }
5380 








5381                 attribClassBody(env, c);
5382 
5383                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5384                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5385                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5386                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5387             } finally {
5388                 env.info.returnResult = prevReturnRes;
5389                 log.useSource(prev);
5390                 chk.setLint(prevLint);
5391             }
5392 
5393         }
5394     }
5395 
5396     public void visitImport(JCImport tree) {
5397         // nothing to do
5398     }
5399 
5400     public void visitModuleDef(JCModuleDecl tree) {

  26 package com.sun.tools.javac.comp;
  27 
  28 import java.util.*;
  29 import java.util.function.BiConsumer;
  30 
  31 import javax.lang.model.element.ElementKind;
  32 import javax.tools.JavaFileObject;
  33 
  34 import com.sun.source.tree.CaseTree;
  35 import com.sun.source.tree.IdentifierTree;
  36 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
  37 import com.sun.source.tree.MemberSelectTree;
  38 import com.sun.source.tree.TreeVisitor;
  39 import com.sun.source.util.SimpleTreeVisitor;
  40 import com.sun.tools.javac.code.*;
  41 import com.sun.tools.javac.code.Lint.LintCategory;
  42 import com.sun.tools.javac.code.Scope.WriteableScope;
  43 import com.sun.tools.javac.code.Source.Feature;
  44 import com.sun.tools.javac.code.Symbol.*;
  45 import com.sun.tools.javac.code.Type.*;
  46 import com.sun.tools.javac.code.Type.ClassType.Flavor;
  47 import com.sun.tools.javac.code.TypeMetadata.Annotations;
  48 import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError;
  49 import com.sun.tools.javac.comp.ArgumentAttr.LocalCacheContext;
  50 import com.sun.tools.javac.comp.Check.CheckContext;
  51 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
  52 import com.sun.tools.javac.comp.MatchBindingsComputer.MatchBindings;
  53 import com.sun.tools.javac.jvm.*;
  54 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond;
  55 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArg;
  56 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArgs;
  57 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  58 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  59 import com.sun.tools.javac.resources.CompilerProperties.Notes;
  60 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
  61 import com.sun.tools.javac.tree.*;
  62 import com.sun.tools.javac.tree.JCTree.*;
  63 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
  64 import com.sun.tools.javac.util.*;
  65 import com.sun.tools.javac.util.DefinedBy.Api;
  66 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  67 import com.sun.tools.javac.util.JCDiagnostic.Error;
  68 import com.sun.tools.javac.util.JCDiagnostic.Fragment;
  69 import com.sun.tools.javac.util.JCDiagnostic.Warning;
  70 import com.sun.tools.javac.util.List;
  71 
  72 import static com.sun.tools.javac.code.Flags.*;
  73 import static com.sun.tools.javac.code.Flags.ANNOTATION;
  74 import static com.sun.tools.javac.code.Flags.BLOCK;
  75 import static com.sun.tools.javac.code.Kinds.*;
  76 import static com.sun.tools.javac.code.Kinds.Kind.*;
  77 import static com.sun.tools.javac.code.TypeTag.*;
  78 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
  79 import static com.sun.tools.javac.tree.JCTree.Tag.*;

 152         types = Types.instance(context);
 153         preview = Preview.instance(context);
 154         diags = JCDiagnostic.Factory.instance(context);
 155         annotate = Annotate.instance(context);
 156         typeAnnotations = TypeAnnotations.instance(context);
 157         deferredLintHandler = DeferredLintHandler.instance(context);
 158         typeEnvs = TypeEnvs.instance(context);
 159         dependencies = Dependencies.instance(context);
 160         argumentAttr = ArgumentAttr.instance(context);
 161         matchBindingsComputer = MatchBindingsComputer.instance(context);
 162         attrRecover = AttrRecover.instance(context);
 163 
 164         Options options = Options.instance(context);
 165 
 166         Source source = Source.instance(context);
 167         allowPoly = Feature.POLY.allowedInSource(source);
 168         allowTypeAnnos = Feature.TYPE_ANNOTATIONS.allowedInSource(source);
 169         allowLambda = Feature.LAMBDA.allowedInSource(source);
 170         allowDefaultMethods = Feature.DEFAULT_METHODS.allowedInSource(source);
 171         allowStaticInterfaceMethods = Feature.STATIC_INTERFACE_METHODS.allowedInSource(source);
 172         allowPrimitiveClasses = Feature.PRIMITIVE_CLASSES.allowedInSource(source);
 173         allowReifiableTypesInInstanceof = Feature.REIFIABLE_TYPES_INSTANCEOF.allowedInSource(source);
 174         allowRecords = Feature.RECORDS.allowedInSource(source);
 175         allowPatternSwitch = (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH)) &&
 176                              Feature.PATTERN_SWITCH.allowedInSource(source);
 177         sourceName = source.name;
 178         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
 179 
 180         statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
 181         varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
 182         unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
 183         methodAttrInfo = new MethodAttrInfo();
 184         unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
 185         unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
 186         recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
 187     }
 188 
 189     /** Switch: support target-typing inference
 190      */
 191     boolean allowPoly;
 192 
 193     /** Switch: support type annotations.
 194      */
 195     boolean allowTypeAnnos;
 196 
 197     /** Switch: support lambda expressions ?
 198      */
 199     boolean allowLambda;
 200 
 201     /** Switch: support default methods ?
 202      */
 203     boolean allowDefaultMethods;
 204 
 205     /** Switch: allow primitive classes ?
 206      */
 207     boolean allowPrimitiveClasses;
 208 
 209     /** Switch: static interface methods enabled?
 210      */
 211     boolean allowStaticInterfaceMethods;
 212 
 213     /** Switch: reifiable types in instanceof enabled?
 214      */
 215     boolean allowReifiableTypesInInstanceof;
 216 
 217     /** Are records allowed
 218      */
 219     private final boolean allowRecords;
 220 
 221     /** Are patterns in switch allowed
 222      */
 223     private final boolean allowPatternSwitch;
 224 
 225     /**
 226      * Switch: warn about use of variable before declaration?
 227      * RFE: 6425594
 228      */

 307 
 308     /** Check that variable can be assigned to.
 309      *  @param pos    The current source code position.
 310      *  @param v      The assigned variable
 311      *  @param base   If the variable is referred to in a Select, the part
 312      *                to the left of the `.', null otherwise.
 313      *  @param env    The current environment.
 314      */
 315     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
 316         if (v.name == names._this) {
 317             log.error(pos, Errors.CantAssignValToThis);
 318         } else if ((v.flags() & FINAL) != 0 &&
 319             ((v.flags() & HASINIT) != 0
 320              ||
 321              !((base == null ||
 322                TreeInfo.isThisQualifier(base)) &&
 323                isAssignableAsBlankFinal(v, env)))) {
 324             if (v.isResourceVariable()) { //TWR resource
 325                 log.error(pos, Errors.TryResourceMayNotBeAssigned(v));
 326             } else {
 327                 boolean complain = true;
 328                 /* Allow updates to instance fields of primitive classes by any method in the same nest via the
 329                    withfield operator -This does not result in mutation of final fields; the code generator
 330                    would implement `copy on write' semantics via the opcode `withfield'.
 331                 */
 332                 if (env.info.inWithField && v.getKind() == ElementKind.FIELD && (v.flags() & STATIC) == 0 && types.isPrimitiveClass(v.owner.type)) {
 333                     if (env.enclClass.sym.outermostClass() == v.owner.outermostClass())
 334                         complain = false;
 335                 }
 336                 if (complain)
 337                     log.error(pos, Errors.CantAssignValToFinalVar(v));
 338             }
 339         }
 340     }
 341 
 342     /** Does tree represent a static reference to an identifier?
 343      *  It is assumed that tree is either a SELECT or an IDENT.
 344      *  We have to weed out selects from non-type names here.
 345      *  @param tree    The candidate tree.
 346      */
 347     boolean isStaticReference(JCTree tree) {
 348         if (tree.hasTag(SELECT)) {
 349             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
 350             if (lsym == null || lsym.kind != TYP) {
 351                 return false;
 352             }
 353         }
 354         return true;
 355     }
 356 
 357     /** Is this symbol a type?

 814     /** Attribute a type argument list, returning a list of types.
 815      *  Check that all the types are references.
 816      */
 817     List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
 818         List<Type> types = attribAnyTypes(trees, env);
 819         return chk.checkRefTypes(trees, types);
 820     }
 821 
 822     /**
 823      * Attribute type variables (of generic classes or methods).
 824      * Compound types are attributed later in attribBounds.
 825      * @param typarams the type variables to enter
 826      * @param env      the current environment
 827      */
 828     void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env, boolean checkCyclic) {
 829         for (JCTypeParameter tvar : typarams) {
 830             TypeVar a = (TypeVar)tvar.type;
 831             a.tsym.flags_field |= UNATTRIBUTED;
 832             a.setUpperBound(Type.noType);
 833             if (!tvar.bounds.isEmpty()) {
 834                 List<Type> bounds = List.of(chk.checkRefType(tvar.bounds.head, attribType(tvar.bounds.head, env), false));
 835                 for (JCExpression bound : tvar.bounds.tail)
 836                     bounds = bounds.prepend(chk.checkRefType(bound, attribType(bound, env), false));
 837                 types.setBounds(a, bounds.reverse());
 838             } else {
 839                 // if no bounds are given, assume a single bound of
 840                 // java.lang.Object.
 841                 types.setBounds(a, List.of(syms.objectType));
 842             }
 843             a.tsym.flags_field &= ~UNATTRIBUTED;
 844         }
 845         if (checkCyclic) {
 846             for (JCTypeParameter tvar : typarams) {
 847                 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
 848             }
 849         }
 850     }
 851 
 852     /**
 853      * Attribute the type references in a list of annotations.
 854      */
 855     void attribAnnotationTypes(List<JCAnnotation> annotations,
 856                                Env<AttrContext> env) {

1198                         log.error(tree.pos(),
1199                                   Errors.DefaultAllowedInIntfAnnotationMember);
1200                 }
1201                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1202                     log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract);
1203             } else if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1204                 if ((owner.flags() & INTERFACE) != 0) {
1205                     log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1206                 } else {
1207                     log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1208                 }
1209             } else if ((tree.mods.flags & NATIVE) != 0) {
1210                 log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1211             } else {
1212                 // Add an implicit super() call unless an explicit call to
1213                 // super(...) or this(...) is given
1214                 // or we are compiling class java.lang.Object.
1215                 if (tree.name == names.init && owner.type != syms.objectType) {
1216                     JCBlock body = tree.body;
1217                     if (body.stats.isEmpty() ||
1218                             TreeInfo.getConstructorInvocationName(body.stats, names, true) == names.empty) {
1219                         JCStatement supCall = make.at(body.pos).Exec(make.Apply(List.nil(),
1220                                 make.Ident(names._super), make.Idents(List.nil())));
1221                         body.stats = body.stats.prepend(supCall);
1222                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1223                             (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1224                             TreeInfo.isSuperCall(body.stats.head)) {
1225                         // enum constructors are not allowed to call super
1226                         // directly, so make sure there aren't any super calls
1227                         // in enum constructors, except in the compiler
1228                         // generated one.
1229                         log.error(tree.body.stats.head.pos(),
1230                                   Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1231                     } else if ((env.enclClass.sym.flags() & VALUE_CLASS) != 0 &&
1232                         (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1233                         TreeInfo.isSuperCall(body.stats.head)) {
1234                         // value constructors are not allowed to call super directly,
1235                         // but tolerate compiler generated ones, these are ignored during code generation
1236                         log.error(tree.body.stats.head.pos(), Errors.CallToSuperNotAllowedInValueCtor);
1237                     }
1238                     if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1239                         List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1240                         List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1241                         if (!initParamNames.equals(recordComponentNames)) {
1242                             log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1243                                     Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1244                         }
1245                         if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1246                             log.error(tree,
1247                                     Errors.InvalidCanonicalConstructorInRecord(
1248                                             TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical,
1249                                             env.enclClass.sym.name,
1250                                             Fragments.ThrowsClauseNotAllowedForCanonicalConstructor(
1251                                                     TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical)));
1252                         }
1253                     }
1254                 }
1255                 if (m.isConstructor() && m.type.getParameterTypes().size() == 0) {
1256                     if ((owner.type == syms.objectType) ||
1257                             (tree.body.stats.size() == 1 && TreeInfo.getConstructorInvocationName(tree.body.stats, names, false) == names._super)) {
1258                         m.flags_field |= EMPTYNOARGCONSTR;
1259                     }
1260                 }
1261 
1262                 // Attribute all type annotations in the body
1263                 annotate.queueScanTreeAndTypeAnnotate(tree.body, localEnv, m, null);
1264                 annotate.flush();
1265 
1266                 // Attribute method body.
1267                 attribStat(tree.body, localEnv);
1268             }
1269 
1270             localEnv.info.scope.leave();
1271             result = tree.type = m.type;
1272         } finally {
1273             chk.setLint(prevLint);
1274             chk.setMethod(prevMethod);
1275         }
1276     }
1277 
1278     public void visitVarDef(JCVariableDecl tree) {
1279         // Local variables have not been entered yet, so we need to do it now:
1280         if (env.info.scope.owner.kind == MTH || env.info.scope.owner.kind == VAR) {

1310                 annotate.queueScanTreeAndTypeAnnotate(tree.init, env, tree.sym, tree.pos());
1311                 annotate.flush();
1312             }
1313         }
1314 
1315         VarSymbol v = tree.sym;
1316         Lint lint = env.info.lint.augment(v);
1317         Lint prevLint = chk.setLint(lint);
1318 
1319         // Check that the variable's declared type is well-formed.
1320         boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
1321                 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
1322                 (tree.sym.flags() & PARAMETER) != 0;
1323         chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1324 
1325         try {
1326             v.getConstValue(); // ensure compile-time constant initializer is evaluated
1327             deferredLintHandler.flush(tree.pos());
1328             chk.checkDeprecatedAnnotation(tree.pos(), v);
1329 
1330             /* Don't want constant propagation/folding for instance fields of primitive classes,
1331                as these can undergo updates via copy on write.
1332             */
1333             if (tree.init != null) {
1334                 if ((v.flags_field & FINAL) == 0 || ((v.flags_field & STATIC) == 0 && types.isPrimitiveClass(v.owner.type)) ||
1335                     !memberEnter.needsLazyConstValue(tree.init)) {
1336                     // Not a compile-time constant
1337                     // Attribute initializer in a new environment
1338                     // with the declared variable as owner.
1339                     // Check that initializer conforms to variable's declared type.
1340                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1341                     initEnv.info.lint = lint;
1342                     // In order to catch self-references, we set the variable's
1343                     // declaration position to maximal possible value, effectively
1344                     // marking the variable as undefined.
1345                     initEnv.info.enclVar = v;
1346                     attribExpr(tree.init, initEnv, v.type);
1347                     if (tree.isImplicitlyTyped()) {
1348                         //fixup local variable type
1349                         v.type = chk.checkLocalVarType(tree, tree.init.type.baseType(), tree.name);
1350                     }
1351                 }
1352                 if (tree.isImplicitlyTyped()) {
1353                     setSyntheticVariableType(tree, v.type);
1354                 }

1438             }
1439         }
1440     }
1441 
1442     public void visitSkip(JCSkip tree) {
1443         result = null;
1444     }
1445 
1446     public void visitBlock(JCBlock tree) {
1447         if (env.info.scope.owner.kind == TYP || env.info.scope.owner.kind == ERR) {
1448             // Block is a static or instance initializer;
1449             // let the owner of the environment be a freshly
1450             // created BLOCK-method.
1451             Symbol fakeOwner =
1452                 new MethodSymbol(tree.flags | BLOCK |
1453                     env.info.scope.owner.flags() & STRICTFP, names.empty, null,
1454                     env.info.scope.owner);
1455             final Env<AttrContext> localEnv =
1456                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1457 
1458             if ((tree.flags & STATIC) != 0)
1459                 localEnv.info.staticLevel++;
1460             else if (tree.stats.size() > 0)
1461                 env.info.scope.owner.flags_field |= HASINITBLOCK;
1462 
1463             // Attribute all type annotations in the block
1464             annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
1465             annotate.flush();
1466             attribStats(tree.stats, localEnv);
1467 
1468             {
1469                 // Store init and clinit type annotations with the ClassSymbol
1470                 // to allow output in Gen.normalizeDefs.
1471                 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1472                 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1473                 if ((tree.flags & STATIC) != 0) {
1474                     cs.appendClassInitTypeAttributes(tas);
1475                 } else {
1476                     cs.appendInitTypeAttributes(tas);
1477                 }
1478             }
1479         } else {
1480             // Create a new local environment with a local scope.
1481             Env<AttrContext> localEnv =
1482                 env.dup(tree, env.info.dup(env.info.scope.dup()));

1507         // include condition's bindings when true in the body:
1508         Env<AttrContext> whileEnv = bindingEnv(env, condBindings.bindingsWhenTrue);
1509         try {
1510             attribStat(tree.body, whileEnv.dup(tree));
1511         } finally {
1512             whileEnv.info.scope.leave();
1513         }
1514         if (!breaksOutOf(tree, tree.body)) {
1515             //include condition's bindings when false after the while, if cannot get out of the loop
1516             condBindings.bindingsWhenFalse.forEach(env.info.scope::enter);
1517             condBindings.bindingsWhenFalse.forEach(BindingSymbol::preserveBinding);
1518         }
1519         result = null;
1520     }
1521 
1522     private boolean breaksOutOf(JCTree loop, JCTree body) {
1523         preFlow(body);
1524         return flow.breaksOutOf(env, loop, body, make);
1525     }
1526 
1527     public void visitWithField(JCWithField tree) {
1528         boolean inWithField = env.info.inWithField;
1529         try {
1530             env.info.inWithField = true;
1531             Type fieldtype = attribTree(tree.field, env.dup(tree), varAssignmentInfo);
1532             attribExpr(tree.value, env, fieldtype);
1533             Type capturedType = syms.errType;
1534             if (tree.field.type != null && !tree.field.type.isErroneous()) {
1535                 final Symbol sym = TreeInfo.symbol(tree.field);
1536                 if (sym == null || sym.kind != VAR || sym.owner.kind != TYP ||
1537                         (sym.flags() & STATIC) != 0 || !types.isPrimitiveClass(sym.owner.type)) {
1538                     log.error(tree.field.pos(), Errors.PrimitiveClassInstanceFieldExpectedHere);
1539                 } else {
1540                     Type ownType = sym.owner.type;
1541                     switch(tree.field.getTag()) {
1542                         case IDENT:
1543                             JCIdent ident = (JCIdent) tree.field;
1544                             ownType = ident.sym.owner.type;
1545                             break;
1546                         case SELECT:
1547                             JCFieldAccess fieldAccess = (JCFieldAccess) tree.field;
1548                             ownType = fieldAccess.selected.type;
1549                             break;
1550                     }
1551                     capturedType = capture(ownType);
1552                 }
1553             }
1554             result = check(tree, capturedType, KindSelector.VAL, resultInfo);
1555         } finally {
1556             env.info.inWithField = inWithField;
1557         }
1558     }
1559 
1560     public void visitForLoop(JCForLoop tree) {
1561         Env<AttrContext> loopEnv =
1562             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1563         MatchBindings condBindings = MatchBindingsComputer.EMPTY;
1564         try {
1565             attribStats(tree.init, loopEnv);
1566             if (tree.cond != null) {
1567                 attribExpr(tree.cond, loopEnv, syms.booleanType);
1568                 // include condition's bindings when true in the body and step:
1569                 condBindings = matchBindings;
1570             }
1571             Env<AttrContext> bodyEnv = bindingEnv(loopEnv, condBindings.bindingsWhenTrue);
1572             try {
1573                 bodyEnv.tree = tree; // before, we were not in loop!
1574                 attribStats(tree.step, bodyEnv);
1575                 attribStat(tree.body, bodyEnv);
1576             } finally {
1577                 bodyEnv.info.scope.leave();
1578             }
1579             result = null;

1583         }
1584         if (!breaksOutOf(tree, tree.body)) {
1585             //include condition's body when false after the while, if cannot get out of the loop
1586             condBindings.bindingsWhenFalse.forEach(env.info.scope::enter);
1587             condBindings.bindingsWhenFalse.forEach(BindingSymbol::preserveBinding);
1588         }
1589     }
1590 
1591     public void visitForeachLoop(JCEnhancedForLoop tree) {
1592         Env<AttrContext> loopEnv =
1593             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1594         try {
1595             //the Formal Parameter of a for-each loop is not in the scope when
1596             //attributing the for-each expression; we mimic this by attributing
1597             //the for-each expression first (against original scope).
1598             Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
1599             chk.checkNonVoid(tree.pos(), exprType);
1600             Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
1601             if (elemtype == null) {
1602                 // or perhaps expr implements Iterable<T>?
1603                 Type base = types.asSuper(exprType.referenceProjectionOrSelf(), syms.iterableType.tsym);
1604                 if (base == null) {
1605                     log.error(tree.expr.pos(),
1606                               Errors.ForeachNotApplicableToType(exprType,
1607                                                                 Fragments.TypeReqArrayOrIterable));
1608                     elemtype = types.createErrorType(exprType);
1609                 } else {
1610                     List<Type> iterableParams = base.allparams();
1611                     elemtype = iterableParams.isEmpty()
1612                         ? syms.objectType
1613                         : types.wildUpperBound(iterableParams.head);
1614 
1615                     // Check the return type of the method iterator().
1616                     // This is the bare minimum we need to verify to make sure code generation doesn't crash.
1617                     Symbol iterSymbol = rs.resolveInternalMethod(tree.pos(),
1618                             loopEnv, types.skipTypeVars(exprType, false), names.iterator, List.nil(), List.nil());
1619                     if (types.asSuper(iterSymbol.type.getReturnType().referenceProjectionOrSelf(), syms.iteratorType.tsym) == null) {
1620                         log.error(tree.pos(),
1621                                 Errors.ForeachNotApplicableToType(exprType, Fragments.TypeReqArrayOrIterable));
1622                     }
1623                 }
1624             }
1625             if (tree.var.isImplicitlyTyped()) {
1626                 Type inferredType = chk.checkLocalVarType(tree.var, elemtype, tree.var.name);
1627                 setSyntheticVariableType(tree.var, inferredType);
1628             }
1629             attribStat(tree.var, loopEnv);
1630             chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
1631             loopEnv.tree = tree; // before, we were not in loop!
1632             attribStat(tree.body, loopEnv);
1633             result = null;
1634         }
1635         finally {
1636             loopEnv.info.scope.leave();
1637         }
1638     }
1639 

1911     // where
1912     /** Return the selected enumeration constant symbol, or null. */
1913     private Symbol enumConstant(JCTree tree, Type enumType) {
1914         if (tree.hasTag(IDENT)) {
1915             JCIdent ident = (JCIdent)tree;
1916             Name name = ident.name;
1917             for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1918                 if (sym.kind == VAR) {
1919                     Symbol s = ident.sym = sym;
1920                     ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1921                     ident.type = s.type;
1922                     return ((s.flags_field & Flags.ENUM) == 0)
1923                         ? null : s;
1924                 }
1925             }
1926         }
1927         return null;
1928     }
1929 
1930     public void visitSynchronized(JCSynchronized tree) {
1931         chk.checkIdentityType(tree.pos(), attribExpr(tree.lock, env));
1932         if (env.info.lint.isEnabled(LintCategory.SYNCHRONIZATION) && isValueBased(tree.lock.type)) {
1933             log.warning(LintCategory.SYNCHRONIZATION, tree.pos(), Warnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
1934         }
1935         attribStat(tree.body, env);
1936         result = null;
1937     }
1938         // where
1939         private boolean isValueBased(Type t) {
1940             return t != null && t.tsym != null && (t.tsym.flags() & VALUE_BASED) != 0;
1941         }
1942 
1943 
1944     public void visitTry(JCTry tree) {
1945         // Create a new local environment with a local
1946         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1947         try {
1948             boolean isTryWithResource = tree.resources.nonEmpty();
1949             // Create a nested environment for attributing the try block if needed
1950             Env<AttrContext> tryEnv = isTryWithResource ?
1951                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :

2000                     chk.checkType(c.param.vartype.pos(),
2001                                   chk.checkClassType(c.param.vartype.pos(), ctype),
2002                                   syms.throwableType);
2003                     attribStat(c.body, catchEnv);
2004                 } finally {
2005                     catchEnv.info.scope.leave();
2006                 }
2007             }
2008 
2009             // Attribute finalizer
2010             if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
2011             result = null;
2012         }
2013         finally {
2014             localEnv.info.scope.leave();
2015         }
2016     }
2017 
2018     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
2019         if (!resource.isErroneous() &&
2020             types.asSuper(resource.referenceProjectionOrSelf(), syms.autoCloseableType.tsym) != null &&
2021             !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
2022             Symbol close = syms.noSymbol;
2023             Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
2024             try {
2025                 close = rs.resolveQualifiedMethod(pos,
2026                         env,
2027                         types.skipTypeVars(resource, false),
2028                         names.close,
2029                         List.nil(),
2030                         List.nil());
2031             }
2032             finally {
2033                 log.popDiagnosticHandler(discardHandler);
2034             }
2035             if (close.kind == MTH &&
2036                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
2037                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
2038                     env.info.lint.isEnabled(LintCategory.TRY)) {
2039                 log.warning(LintCategory.TRY, pos, Warnings.TryResourceThrowsInterruptedExc(resource));
2040             }

2190             if (unboxedTypes.stream().allMatch(t -> t.isPrimitive())) {
2191                 // If one arm has an integer subrange type (i.e., byte,
2192                 // short, or char), and the other is an integer constant
2193                 // that fits into the subrange, return the subrange type.
2194                 for (Type type : unboxedTypes) {
2195                     if (!type.getTag().isStrictSubRangeOf(INT)) {
2196                         continue;
2197                     }
2198                     if (unboxedTypes.stream().filter(t -> t != type).allMatch(t -> t.hasTag(INT) && types.isAssignable(t, type)))
2199                         return type.baseType();
2200                 }
2201 
2202                 for (TypeTag tag : primitiveTags) {
2203                     Type candidate = syms.typeOfTag[tag.ordinal()];
2204                     if (unboxedTypes.stream().allMatch(t -> types.isSubtype(t, candidate))) {
2205                         return candidate;
2206                     }
2207                 }
2208             }
2209 
2210             // Those were all the cases that could result in a primitive. See if primitive boxing and primitive
2211             // value conversions bring about a convergence.
2212             condTypes = condTypes.stream()
2213                                  .map(t -> t.isPrimitive() ? types.boxedClass(t).type
2214                                          : t.isReferenceProjection() ? t.valueProjection() : t)
2215                                  .collect(List.collector());
2216 
2217             for (Type type : condTypes) {
2218                 if (condTypes.stream().filter(t -> t != type).allMatch(t -> types.isAssignable(t, type)))
2219                     return type.baseType();
2220             }
2221 
2222             Iterator<DiagnosticPosition> posIt = positions.iterator();
2223 
2224             condTypes = condTypes.stream()
2225                                  .map(t -> chk.checkNonVoid(posIt.next(), t.isPrimitiveClass() ? t.referenceProjection() : t))
2226                                  .collect(List.collector());
2227 
2228             // both are known to be reference types (or projections).  The result is
2229             // lub(thentype,elsetype). This cannot fail, as it will
2230             // always be possible to infer "Object" if nothing better.
2231             return types.lub(condTypes.stream()
2232                         .map(t -> t.baseType())
2233                         .filter(t -> !t.hasTag(BOT))
2234                         .collect(List.collector()));
2235         }
2236 
2237     static final TypeTag[] primitiveTags = new TypeTag[]{
2238         BYTE,
2239         CHAR,
2240         SHORT,
2241         INT,
2242         LONG,
2243         FLOAT,
2244         DOUBLE,
2245         BOOLEAN,
2246     };
2247 
2248     Env<AttrContext> bindingEnv(Env<AttrContext> env, List<BindingSymbol> bindings) {

2635             // ... and attribute the method using as a prototype a methodtype
2636             // whose formal argument types is exactly the list of actual
2637             // arguments (this will also set the method symbol).
2638             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
2639             localEnv.info.pendingResolutionPhase = null;
2640             Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
2641 
2642             // Compute the result type.
2643             Type restype = mtype.getReturnType();
2644             if (restype.hasTag(WILDCARD))
2645                 throw new AssertionError(mtype);
2646 
2647             Type qualifier = (tree.meth.hasTag(SELECT))
2648                     ? ((JCFieldAccess) tree.meth).selected.type
2649                     : env.enclClass.sym.type;
2650             Symbol msym = TreeInfo.symbol(tree.meth);
2651             restype = adjustMethodReturnType(msym, qualifier, methName, argtypes, restype);
2652 
2653             chk.checkRefTypes(tree.typeargs, typeargtypes);
2654 
2655             final Symbol symbol = TreeInfo.symbol(tree.meth);
2656             if (symbol != null) {
2657                 /* Is this an ill conceived attempt to invoke jlO methods not available on primitive class types ??
2658                  */
2659                 boolean superCallOnPrimitiveReceiver = types.isPrimitiveClass(env.enclClass.sym.type)
2660                         && (tree.meth.hasTag(SELECT))
2661                         && ((JCFieldAccess)tree.meth).selected.hasTag(IDENT)
2662                         && TreeInfo.name(((JCFieldAccess)tree.meth).selected) == names._super;
2663                 if (types.isPrimitiveClass(qualifier) || superCallOnPrimitiveReceiver) {
2664                     int argSize = argtypes.size();
2665                     Name name = symbol.name;
2666                     switch (name.toString()) {
2667                         case "wait":
2668                             if (argSize == 0
2669                                     || (types.isConvertible(argtypes.head, syms.longType) &&
2670                                     (argSize == 1 || (argSize == 2 && types.isConvertible(argtypes.tail.head, syms.intType))))) {
2671                                 log.error(tree.pos(), Errors.PrimitiveClassDoesNotSupport(name));
2672                             }
2673                             break;
2674                         case "notify":
2675                         case "notifyAll":
2676                         case "finalize":
2677                             if (argSize == 0)
2678                                 log.error(tree.pos(), Errors.PrimitiveClassDoesNotSupport(name));
2679                             break;
2680                     }
2681                 }
2682             }
2683 
2684             // Check that value of resulting type is admissible in the
2685             // current context.  Also, capture the return type
2686             Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true);
2687             result = check(tree, capturedRes, KindSelector.VAL, resultInfo);
2688         }
2689         chk.validate(tree.typeargs, localEnv);
2690     }
2691     //where
2692         Type adjustMethodReturnType(Symbol msym, Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
2693             if (msym != null &&
2694                     (msym.owner == syms.objectType.tsym || msym.owner.isInterface()) &&
2695                     methodName == names.getClass &&
2696                     argtypes.isEmpty()) {
2697                 // as a special case, x.getClass() has type Class<? extends |X|>
2698                 // Special treatment for primitive classes: Given an expression v of type V where
2699                 // V is a primitive class, v.getClass() is typed to be Class<? extends |V.ref|>
2700                 Type wcb = types.erasure(qualifierType.isPrimitiveClass() ?
2701                                                 qualifierType.referenceProjection() : qualifierType);
2702                 return new ClassType(restype.getEnclosingType(),
2703                         List.of(new WildcardType(wcb,
2704                                 BoundKind.EXTENDS,
2705                                 syms.boundClass)),
2706                         restype.tsym,
2707                         restype.getMetadata(),
2708                         restype.getFlavor());
2709             } else if (msym != null &&
2710                     msym.owner == syms.arrayClass &&
2711                     methodName == names.clone &&
2712                     types.isArray(qualifierType)) {
2713                 // as a special case, array.clone() has a result that is
2714                 // the same as static type of the array being cloned
2715                 return qualifierType;
2716             } else {
2717                 return restype;
2718             }
2719         }
2720 
2721         /** Check that given application node appears as first statement
2722          *  in a constructor call.
2723          *  @param tree          The application node
2724          *  @param enclMethod    The enclosing method of the application.
2725          *  @param error         Should an error be issued?
2726          */
2727         boolean checkFirstConstructorStat(JCMethodInvocation tree, JCMethodDecl enclMethod, boolean error) {
2728             if (enclMethod != null && enclMethod.name == names.init) {

2811                 clazzid1 = make.at(tree.pos).
2812                     AnnotatedType(annos, clazzid1);
2813             } else if (clazz.hasTag(TYPEAPPLY)) {
2814                 clazzid1 = make.at(tree.pos).
2815                     TypeApply(clazzid1,
2816                               ((JCTypeApply) clazz).arguments);
2817             }
2818 
2819             clazz = clazzid1;
2820         }
2821 
2822         // Attribute clazz expression and store
2823         // symbol + type back into the attributed tree.
2824         Type clazztype;
2825 
2826         try {
2827             env.info.isNewClass = true;
2828             clazztype = TreeInfo.isEnumInit(env.tree) ?
2829                 attribIdentAsEnumType(env, (JCIdent)clazz) :
2830                 attribType(clazz, env);
2831             if (clazztype.tsym == syms.objectType.tsym && cdef == null && !tree.classDeclRemoved()) {
2832                 log.note(tree.pos(), Notes.CantInstantiateObjectDirectly);
2833             }
2834         } finally {
2835             env.info.isNewClass = false;
2836         }
2837 
2838         clazztype = chk.checkDiamond(tree, clazztype);
2839         chk.validate(clazz, localEnv);
2840         if (tree.encl != null) {
2841             // We have to work in this case to store
2842             // symbol + type back into the attributed tree.
2843             tree.clazz.type = clazztype;
2844             TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
2845             clazzid.type = ((JCIdent) clazzid).sym.type;
2846             if (annoclazzid != null) {
2847                 annoclazzid.type = clazzid.type;
2848             }
2849             if (!clazztype.isErroneous()) {
2850                 if (cdef != null && clazztype.tsym.isInterface()) {
2851                     log.error(tree.encl.pos(), Errors.AnonClassImplIntfNoQualForNew);
2852                 } else if (clazztype.tsym.isStatic()) {
2853                     log.error(tree.encl.pos(), Errors.QualifiedNewOfStaticClass(clazztype.tsym));

2860         }
2861 
2862         // Attribute constructor arguments.
2863         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2864         final KindSelector pkind =
2865             attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
2866         List<Type> argtypes = argtypesBuf.toList();
2867         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
2868 
2869         if (clazztype.hasTag(CLASS) || clazztype.hasTag(ERROR)) {
2870             // Enums may not be instantiated except implicitly
2871             if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 &&
2872                 (!env.tree.hasTag(VARDEF) ||
2873                  (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 ||
2874                  ((JCVariableDecl) env.tree).init != tree))
2875                 log.error(tree.pos(), Errors.EnumCantBeInstantiated);
2876 
2877             boolean isSpeculativeDiamondInferenceRound = TreeInfo.isDiamond(tree) &&
2878                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2879             boolean skipNonDiamondPath = false;
2880             // Check that it is an instantiation of a class and not a projection type
2881             if (clazz.hasTag(SELECT)) {
2882                 JCFieldAccess fieldAccess = (JCFieldAccess) clazz;
2883                 if (fieldAccess.selected.type.isPrimitiveClass() &&
2884                         (fieldAccess.name == names.ref || fieldAccess.name == names.val)) {
2885                     log.error(tree.pos(), Errors.ProjectionCantBeInstantiated);
2886                 }
2887             }
2888             // Check that class is not abstract
2889             if (cdef == null && !isSpeculativeDiamondInferenceRound && // class body may be nulled out in speculative tree copy
2890                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
2891                 log.error(tree.pos(),
2892                           Errors.AbstractCantBeInstantiated(clazztype.tsym));
2893                 skipNonDiamondPath = true;
2894             } else if (cdef != null && clazztype.tsym.isInterface()) {
2895                 // Check that no constructor arguments are given to
2896                 // anonymous classes implementing an interface
2897                 if (!argtypes.isEmpty())
2898                     log.error(tree.args.head.pos(), Errors.AnonClassImplIntfNoArgs);
2899 
2900                 if (!typeargtypes.isEmpty())
2901                     log.error(tree.typeargs.head.pos(), Errors.AnonClassImplIntfNoTypeargs);
2902 
2903                 // Error recovery: pretend no arguments were supplied.
2904                 argtypes = List.nil();
2905                 typeargtypes = List.nil();
2906                 skipNonDiamondPath = true;
2907             }
2908             if (TreeInfo.isDiamond(tree)) {
2909                 ClassType site = new ClassType(clazztype.getEnclosingType(),
2910                             clazztype.tsym.type.getTypeArguments(),
2911                                                clazztype.tsym,
2912                                                clazztype.getMetadata(),
2913                                                clazztype.getFlavor());
2914 
2915                 Env<AttrContext> diamondEnv = localEnv.dup(tree);
2916                 diamondEnv.info.selectSuper = cdef != null || tree.classDeclRemoved();
2917                 diamondEnv.info.pendingResolutionPhase = null;
2918 
2919                 //if the type of the instance creation expression is a class type
2920                 //apply method resolution inference (JLS 15.12.2.7). The return type
2921                 //of the resolved constructor will be a partially instantiated type
2922                 Symbol constructor = rs.resolveDiamond(tree.pos(),
2923                             diamondEnv,
2924                             site,
2925                             argtypes,
2926                             typeargtypes);
2927                 tree.constructor = constructor.baseSymbol();
2928 
2929                 final TypeSymbol csym = clazztype.tsym;
2930                 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes),
2931                         diamondContext(tree, csym, resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
2932                 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
2933                 constructorType = checkId(tree, site,

3040                                 this.resultInfo = prevResult;
3041                             }
3042                         });
3043             } else {
3044                 if (isDiamond && clazztype.hasTag(CLASS)) {
3045                     List<Type> invalidDiamondArgs = chk.checkDiamondDenotable((ClassType)clazztype);
3046                     if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
3047                         // One or more types inferred in the previous steps is non-denotable.
3048                         Fragment fragment = Diamond(clazztype.tsym);
3049                         log.error(tree.clazz.pos(),
3050                                 Errors.CantApplyDiamond1(
3051                                         fragment,
3052                                         invalidDiamondArgs.size() > 1 ?
3053                                                 DiamondInvalidArgs(invalidDiamondArgs, fragment) :
3054                                                 DiamondInvalidArg(invalidDiamondArgs, fragment)));
3055                     }
3056                     // For <>(){}, inferred types must also be accessible.
3057                     for (Type t : clazztype.getTypeArguments()) {
3058                         rs.checkAccessibleType(env, t);
3059                     }
3060                     chk.checkParameterizationByPrimitiveClass(tree, clazztype);
3061                 }
3062 
3063                 // If we already errored, be careful to avoid a further avalanche. ErrorType answers
3064                 // false for isInterface call even when the original type is an interface.
3065                 boolean implementing = clazztype.tsym.isInterface() ||
3066                         clazztype.isErroneous() && !clazztype.getOriginalType().hasTag(NONE) &&
3067                         clazztype.getOriginalType().tsym.isInterface();
3068 
3069                 if (implementing) {
3070                     cdef.implementing = List.of(clazz);
3071                 } else {
3072                     cdef.extending = clazz;
3073                 }
3074 
3075                 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3076                     rs.isSerializable(clazztype)) {
3077                     localEnv.info.isSerializable = true;
3078                 }
3079 
3080                 attribStat(cdef, localEnv);

3113             result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK));
3114             chk.validate(tree.typeargs, localEnv);
3115         }
3116 
3117         CheckContext diamondContext(JCNewClass clazz, TypeSymbol tsym, CheckContext checkContext) {
3118             return new Check.NestedCheckContext(checkContext) {
3119                 @Override
3120                 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
3121                     enclosingContext.report(clazz.clazz,
3122                             diags.fragment(Fragments.CantApplyDiamond1(Fragments.Diamond(tsym), details)));
3123                 }
3124             };
3125         }
3126 
3127     /** Make an attributed null check tree.
3128      */
3129     public JCExpression makeNullCheck(JCExpression arg) {
3130         // optimization: new Outer() can never be null; skip null check
3131         if (arg.getTag() == NEWCLASS)
3132             return arg;
3133         // Likewise arg can't be null if it is a primitive class instance.
3134         if (types.isPrimitiveClass(arg.type))
3135             return arg;
3136         // optimization: X.this is never null; skip null check
3137         Name name = TreeInfo.name(arg);
3138         if (name == names._this || name == names._super) return arg;
3139 
3140         JCTree.Tag optag = NULLCHK;
3141         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
3142         tree.operator = operators.resolveUnary(arg, optag, arg.type);
3143         tree.type = arg.type;
3144         return tree;
3145     }
3146 
3147     public void visitNewArray(JCNewArray tree) {
3148         Type owntype = types.createErrorType(tree.type);
3149         Env<AttrContext> localEnv = env.dup(tree);
3150         Type elemtype;
3151         if (tree.elemtype != null) {
3152             elemtype = attribType(tree.elemtype, localEnv);
3153             chk.validate(tree.elemtype, localEnv);
3154             owntype = elemtype;
3155             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {

4130         if (operator != operators.noOpSymbol &&
4131                 !left.isErroneous() &&
4132                 !right.isErroneous()) {
4133             owntype = operator.type.getReturnType();
4134             int opc = ((OperatorSymbol)operator).opcode;
4135             // If both arguments are constants, fold them.
4136             if (left.constValue() != null && right.constValue() != null) {
4137                 Type ctype = cfolder.fold2(opc, left, right);
4138                 if (ctype != null) {
4139                     owntype = cfolder.coerce(ctype, owntype);
4140                 }
4141             }
4142 
4143             // Check that argument types of a reference ==, != are
4144             // castable to each other, (JLS 15.21).  Note: unboxing
4145             // comparisons will not have an acmp* opc at this point.
4146             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
4147                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
4148                     log.error(tree.pos(), Errors.IncomparableTypes(left, right));
4149                 }
4150                 chk.checkForSuspectClassLiteralComparison(tree, left, right);
4151             }
4152 
4153             chk.checkDivZero(tree.rhs.pos(), operator, right);
4154         }
4155         result = check(tree, owntype, KindSelector.VAL, resultInfo);
4156     }
4157 
4158     public void visitTypeCast(final JCTypeCast tree) {
4159         Type clazztype = attribType(tree.clazz, env);
4160         chk.validate(tree.clazz, env, false);
4161         //a fresh environment is required for 292 inference to work properly ---
4162         //see Infer.instantiatePolymorphicSignatureInstance()
4163         Env<AttrContext> localEnv = env.dup(tree);
4164         //should we propagate the target type?
4165         final ResultInfo castInfo;
4166         JCExpression expr = TreeInfo.skipParens(tree.expr);
4167         boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
4168         if (isPoly) {
4169             //expression is a poly - we need to propagate target type info
4170             castInfo = new ResultInfo(KindSelector.VAL, clazztype,

4366     }
4367 
4368     public void visitSelect(JCFieldAccess tree) {
4369         // Determine the expected kind of the qualifier expression.
4370         KindSelector skind = KindSelector.NIL;
4371         if (tree.name == names._this || tree.name == names._super ||
4372                 tree.name == names._class)
4373         {
4374             skind = KindSelector.TYP;
4375         } else {
4376             if (pkind().contains(KindSelector.PCK))
4377                 skind = KindSelector.of(skind, KindSelector.PCK);
4378             if (pkind().contains(KindSelector.TYP))
4379                 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4380             if (pkind().contains(KindSelector.VAL_MTH))
4381                 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4382         }
4383 
4384         // Attribute the qualifier expression, and determine its symbol (if any).
4385         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4386         Assert.check(site == tree.selected.type);
4387         if (tree.name == names._class && site.isPrimitiveClass()) {
4388             /* JDK-8269956: Where a reflective (class) literal is needed, the unqualified Point.class is
4389              * always the "primary" mirror - representing the primitive reference runtime type - thereby
4390              * always matching the behavior of Object::getClass
4391              */
4392              if (!tree.selected.hasTag(SELECT) || ((JCFieldAccess) tree.selected).name != names.val) {
4393                  tree.selected.setType(site = site.referenceProjection());
4394              }
4395         }
4396         if (!pkind().contains(KindSelector.TYP_PCK))
4397             site = capture(site); // Capture field access
4398 
4399         // don't allow T.class T[].class, etc
4400         if (skind == KindSelector.TYP) {
4401             Type elt = site;
4402             while (elt.hasTag(ARRAY))
4403                 elt = ((ArrayType)elt).elemtype;
4404             if (elt.hasTag(TYPEVAR)) {
4405                 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4406                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4407                 tree.sym = tree.type.tsym;
4408                 return;
4409             }
4410         }
4411 
4412         // If qualifier symbol is a type or `super', assert `selectSuper'
4413         // for the selection. This is relevant for determining whether
4414         // protected symbols are accessible.
4415         Symbol sitesym = TreeInfo.symbol(tree.selected);
4416 
4417         boolean selectSuperPrev = env.info.selectSuper;
4418         env.info.selectSuper =
4419             sitesym != null &&
4420             sitesym.name == names._super;
4421 
4422         // Determine the symbol represented by the selection.
4423         env.info.pendingResolutionPhase = null;
4424         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
4425         if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
4426             log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym));
4427             sym = syms.errSymbol;
4428         }
4429         if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
4430             site = capture(site);
4431             sym = selectSym(tree, sitesym, site, env, resultInfo);
4432         }
4433         boolean varArgs = env.info.lastResolveVarargs();
4434         tree.sym = sym;
4435 
4436         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {

4492             if (!allowStaticInterfaceMethods && sitesym.isInterface() &&
4493                     sym.isStatic() && sym.kind == MTH) {
4494                 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.pos(), Feature.STATIC_INTERFACE_METHODS_INVOKE.error(sourceName));
4495             }
4496         } else if (sym.kind != ERR &&
4497                    (sym.flags() & STATIC) != 0 &&
4498                    sym.name != names._class) {
4499             // If the qualified item is not a type and the selected item is static, report
4500             // a warning. Make allowance for the class of an array type e.g. Object[].class)
4501             chk.warnStatic(tree, Warnings.StaticNotQualifiedByType(sym.kind.kindName(), sym.owner));
4502         }
4503 
4504         // If we are selecting an instance member via a `super', ...
4505         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
4506 
4507             // Check that super-qualified symbols are not abstract (JLS)
4508             rs.checkNonAbstract(tree.pos(), sym);
4509 
4510             if (site.isRaw()) {
4511                 // Determine argument types for site.
4512                 Type site1 = types.asSuper(env.enclClass.sym.type.referenceProjectionOrSelf(), site.tsym);
4513                 if (site1 != null) site = site1;
4514             }
4515         }
4516 
4517         if (env.info.isSerializable) {
4518             chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4519         }
4520 
4521         env.info.selectSuper = selectSuperPrev;
4522         result = checkId(tree, site, sym, env, resultInfo);
4523     }
4524     //where
4525         /** Determine symbol referenced by a Select expression,
4526          *
4527          *  @param tree   The select tree.
4528          *  @param site   The type of the selected expression,
4529          *  @param env    The current environment.
4530          *  @param resultInfo The current result.
4531          */
4532         private Symbol selectSym(JCFieldAccess tree,

4535                                  Env<AttrContext> env,
4536                                  ResultInfo resultInfo) {
4537             DiagnosticPosition pos = tree.pos();
4538             Name name = tree.name;
4539             switch (site.getTag()) {
4540             case PACKAGE:
4541                 return rs.accessBase(
4542                     rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind),
4543                     pos, location, site, name, true);
4544             case ARRAY:
4545             case CLASS:
4546                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
4547                     return rs.resolveQualifiedMethod(
4548                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
4549                 } else if (name == names._this || name == names._super) {
4550                     return rs.resolveSelf(pos, env, site.tsym, name);
4551                 } else if (name == names._class) {
4552                     // In this case, we have already made sure in
4553                     // visitSelect that qualifier expression is a type.
4554                     return syms.getClassField(site, types);
4555                 } else if (site.isPrimitiveClass() && isType(location) && resultInfo.pkind.contains(KindSelector.TYP) && (name == names.ref || name == names.val)) {
4556                     return site.tsym;
4557                 } else {
4558                     // We are seeing a plain identifier as selector.
4559                     Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind);
4560                         sym = rs.accessBase(sym, pos, location, site, name, true);
4561                     return sym;
4562                 }
4563             case WILDCARD:
4564                 throw new AssertionError(tree);
4565             case TYPEVAR:
4566                 // Normally, site.getUpperBound() shouldn't be null.
4567                 // It should only happen during memberEnter/attribBase
4568                 // when determining the super type which *must* be
4569                 // done before attributing the type variables.  In
4570                 // other words, we are seeing this illegal program:
4571                 // class B<T> extends A<T.foo> {}
4572                 Symbol sym = (site.getUpperBound() != null)
4573                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
4574                     : null;
4575                 if (sym == null) {
4576                     log.error(pos, Errors.TypeVarCantBeDeref);

4640             if (resultInfo.pkind.contains(KindSelector.POLY)) {
4641                 return attrRecover.recoverMethodInvocation(tree, site, sym, env, resultInfo);
4642             } else {
4643                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
4644             }
4645         }
4646 
4647         Type checkIdInternal(JCTree tree,
4648                      Type site,
4649                      Symbol sym,
4650                      Type pt,
4651                      Env<AttrContext> env,
4652                      ResultInfo resultInfo) {
4653             if (pt.isErroneous()) {
4654                 return types.createErrorType(site);
4655             }
4656             Type owntype; // The computed type of this identifier occurrence.
4657             switch (sym.kind) {
4658             case TYP:
4659                 // For types, the computed type equals the symbol's type,
4660                 // except for three situations:
4661                 owntype = sym.type;
4662                 if (owntype.hasTag(CLASS)) {
4663                     Assert.check(owntype.getFlavor() != Flavor.X_Typeof_X);
4664                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
4665                     Type ownOuter = owntype.getEnclosingType();
4666 
4667                     // (a) If symbol is a primitive class and its reference projection
4668                     // is requested via the .ref notation, then adjust the computed type to
4669                     // reflect this.
4670                     if (owntype.isPrimitiveClass() && tree.hasTag(SELECT) && ((JCFieldAccess) tree).name == names.ref) {
4671                         owntype = new ClassType(owntype.getEnclosingType(), owntype.getTypeArguments(), (TypeSymbol)sym, owntype.getMetadata(), Flavor.L_TypeOf_Q);
4672                     }
4673 
4674                     // (b) If the symbol's type is parameterized, erase it
4675                     // because no type parameters were given.
4676                     // We recover generic outer type later in visitTypeApply.
4677                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
4678                         owntype = types.erasure(owntype);
4679                     }
4680 
4681                     // (c) If the symbol's type is an inner class, then
4682                     // we have to interpret its outer type as a superclass
4683                     // of the site type. Example:
4684                     //
4685                     // class Tree<A> { class Visitor { ... } }
4686                     // class PointTree extends Tree<Point> { ... }
4687                     // ...PointTree.Visitor...
4688                     //
4689                     // Then the type of the last expression above is
4690                     // Tree<Point>.Visitor.
4691                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
4692                         Type normOuter = site;
4693                         if (normOuter.hasTag(CLASS)) {
4694                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
4695                         }
4696                         if (normOuter == null) // perhaps from an import
4697                             normOuter = types.erasure(ownOuter);
4698                         if (normOuter != ownOuter)
4699                             owntype = new ClassType(
4700                                 normOuter, List.nil(), owntype.tsym,
4701                                 owntype.getMetadata(), owntype.getFlavor());
4702                     }
4703                 }
4704                 break;
4705             case VAR:
4706                 VarSymbol v = (VarSymbol)sym;
4707 
4708                 if (env.info.enclVar != null
4709                         && v.type.hasTag(NONE)) {
4710                     //self reference to implicitly typed variable declaration
4711                     log.error(TreeInfo.positionFor(v, env.enclClass), Errors.CantInferLocalVarType(v.name, Fragments.LocalSelfRef));
4712                     return v.type = types.createErrorType(v.type);
4713                 }
4714 
4715                 // Test (4): if symbol is an instance field of a raw type,
4716                 // which is being assigned to, issue an unchecked warning if
4717                 // its type changes under erasure.
4718                 if (KindSelector.ASG.subset(pkind()) &&
4719                     v.owner.kind == TYP &&
4720                     (v.flags() & STATIC) == 0 &&
4721                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {

4998             //depending on the current check context
4999             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
5000             return types.createErrorType(site);
5001         } catch (Resolve.InapplicableMethodException ex) {
5002             final JCDiagnostic diag = ex.getDiagnostic();
5003             Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
5004                 @Override
5005                 protected Pair<Symbol, JCDiagnostic> errCandidate() {
5006                     return new Pair<>(sym, diag);
5007                 }
5008             };
5009             List<Type> argtypes2 = argtypes.map(
5010                     rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
5011             JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
5012                     env.tree, sym, site, sym.name, argtypes2, typeargtypes);
5013             log.report(errDiag);
5014             return types.createErrorType(site);
5015         }
5016     }
5017 
5018     public void visitDefaultValue(JCDefaultValue tree) {
5019         if (!allowPrimitiveClasses) {
5020             log.error(DiagnosticFlag.SOURCE_LEVEL, tree.pos(),
5021                     Feature.PRIMITIVE_CLASSES.error(sourceName));
5022         }
5023 
5024         // Attribute the qualifier expression, and determine its symbol (if any).
5025         Type site = attribTree(tree.clazz, env, new ResultInfo(KindSelector.TYP_PCK, Type.noType));
5026         if (!pkind().contains(KindSelector.TYP_PCK))
5027             site = capture(site); // Capture field access
5028 
5029         Symbol sym = switch (site.getTag()) {
5030                 case WILDCARD -> throw new AssertionError(tree);
5031                 case PACKAGE -> {
5032                     log.error(tree.pos, Errors.CantResolveLocation(Kinds.KindName.CLASS, site.tsym.getQualifiedName(), null, null,
5033                             Fragments.Location(Kinds.typeKindName(env.enclClass.type), env.enclClass.type, null)));
5034                     yield syms.errSymbol;
5035                 }
5036                 case ERROR -> types.createErrorType(names._default, site.tsym, site).tsym;
5037                 default -> new VarSymbol(STATIC, names._default, site, site.tsym);
5038         };
5039 
5040         if (site.hasTag(TYPEVAR) && sym.kind != ERR) {
5041             site = types.skipTypeVars(site, true);
5042         }
5043         result = checkId(tree, site, sym, env, resultInfo);
5044     }
5045 
5046     public void visitLiteral(JCLiteral tree) {
5047         result = check(tree, litType(tree.typetag).constType(tree.value),
5048                 KindSelector.VAL, resultInfo);
5049     }
5050     //where
5051     /** Return the type of a literal with given type tag.
5052      */
5053     Type litType(TypeTag tag) {
5054         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
5055     }
5056 
5057     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
5058         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
5059     }
5060 
5061     public void visitTypeArray(JCArrayTypeTree tree) {
5062         Type etype = attribType(tree.elemtype, env);
5063         Type type = new ArrayType(etype, syms.arrayClass);
5064         result = check(tree, type, KindSelector.TYP, resultInfo);
5065     }

5092                 }
5093                 // Compute the proper generic outer
5094                 Type clazzOuter = clazztype.getEnclosingType();
5095                 if (clazzOuter.hasTag(CLASS)) {
5096                     Type site;
5097                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
5098                     if (clazz.hasTag(IDENT)) {
5099                         site = env.enclClass.sym.type;
5100                     } else if (clazz.hasTag(SELECT)) {
5101                         site = ((JCFieldAccess) clazz).selected.type;
5102                     } else throw new AssertionError(""+tree);
5103                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
5104                         if (site.hasTag(CLASS))
5105                             site = types.asOuterSuper(site, clazzOuter.tsym);
5106                         if (site == null)
5107                             site = types.erasure(clazzOuter);
5108                         clazzOuter = site;
5109                     }
5110                 }
5111                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
5112                                         clazztype.getMetadata(), clazztype.getFlavor());
5113             } else {
5114                 if (formals.length() != 0) {
5115                     log.error(tree.pos(),
5116                               Errors.WrongNumberTypeArgs(Integer.toString(formals.length())));
5117                 } else {
5118                     log.error(tree.pos(), Errors.TypeDoesntTakeParams(clazztype.tsym));
5119                 }
5120                 owntype = types.createErrorType(tree.type);
5121             }
5122         }
5123         result = check(tree, owntype, KindSelector.TYP, resultInfo);
5124     }
5125 
5126     public void visitTypeUnion(JCTypeUnion tree) {
5127         ListBuffer<Type> multicatchTypes = new ListBuffer<>();
5128         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
5129         for (JCExpression typeTree : tree.alternatives) {
5130             Type ctype = attribType(typeTree, env);
5131             ctype = chk.checkType(typeTree.pos(),
5132                           chk.checkClassType(typeTree.pos(), ctype),

5219         if (bounds.length() == 0) {
5220             return syms.objectType;
5221         } else if (bounds.length() == 1) {
5222             return bounds.head.type;
5223         } else {
5224             Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
5225             // ... the variable's bound is a class type flagged COMPOUND
5226             // (see comment for TypeVar.bound).
5227             // In this case, generate a class tree that represents the
5228             // bound class, ...
5229             JCExpression extending;
5230             List<JCExpression> implementing;
5231             if (!bounds.head.type.isInterface()) {
5232                 extending = bounds.head;
5233                 implementing = bounds.tail;
5234             } else {
5235                 extending = null;
5236                 implementing = bounds;
5237             }
5238             JCClassDecl cd = make.at(tree).ClassDef(
5239                 make.Modifiers(PUBLIC | ABSTRACT | (extending != null && TreeInfo.symbol(extending).isPrimitiveClass() ? PRIMITIVE_CLASS : 0)),
5240                 names.empty, List.nil(),
5241                 extending, implementing, List.nil());
5242 
5243             ClassSymbol c = (ClassSymbol)owntype.tsym;
5244             Assert.check((c.flags() & COMPOUND) != 0);
5245             cd.sym = c;
5246             c.sourcefile = env.toplevel.sourcefile;
5247 
5248             // ... and attribute the bound class
5249             c.flags_field |= UNATTRIBUTED;
5250             Env<AttrContext> cenv = enter.classEnv(cd, env);
5251             typeEnvs.put(c, cenv);
5252             attribClass(c);
5253             return owntype;
5254         }
5255     }
5256 
5257     public void visitWildcard(JCWildcard tree) {
5258         //- System.err.println("visitWildcard("+tree+");");//DEBUG
5259         Type type = (tree.kind.kind == BoundKind.UNBOUND)
5260             ? syms.objectType
5261             : attribType(tree.inner, env);
5262         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type, false),
5263                                               tree.kind.kind,
5264                                               syms.boundClass),
5265                 KindSelector.TYP, resultInfo);
5266     }
5267 
5268     public void visitAnnotation(JCAnnotation tree) {
5269         Assert.error("should be handled in annotate");
5270     }
5271 
5272     @Override
5273     public void visitModifiers(JCModifiers tree) {
5274         //error recovery only:
5275         Assert.check(resultInfo.pkind == KindSelector.ERR);
5276 
5277         attribAnnotationTypes(tree.annotations, env);
5278     }
5279 
5280     public void visitAnnotatedType(JCAnnotatedType tree) {
5281         attribAnnotationTypes(tree.annotations, env);
5282         Type underlyingType = attribType(tree.underlyingType, env);

5357             chk.completionError(pos, ex);
5358         }
5359     }
5360 
5361     void attribModule(ModuleSymbol m) {
5362         // Get environment current at the point of module definition.
5363         Env<AttrContext> env = enter.typeEnvs.get(m);
5364         attribStat(env.tree, env);
5365     }
5366 
5367     /** Main method: attribute class definition associated with given class symbol.
5368      *  reporting completion failures at the given position.
5369      *  @param pos The source position at which completion errors are to be
5370      *             reported.
5371      *  @param c   The class symbol whose definition will be attributed.
5372      */
5373     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
5374         try {
5375             annotate.flush();
5376             attribClass(c);
5377             if (types.isPrimitiveClass(c.type)) {
5378                 final Env<AttrContext> env = typeEnvs.get(c);
5379                 if (env != null && env.tree != null && env.tree.hasTag(CLASSDEF))
5380                     chk.checkNonCyclicMembership((JCClassDecl)env.tree);
5381             }
5382         } catch (CompletionFailure ex) {
5383             chk.completionError(pos, ex);
5384         }
5385     }
5386 
5387     /** Attribute class definition associated with given class symbol.
5388      *  @param c   The class symbol whose definition will be attributed.
5389      */
5390     void attribClass(ClassSymbol c) throws CompletionFailure {
5391         if (c.type.hasTag(ERROR)) return;
5392 
5393         // Check for cycles in the inheritance graph, which can arise from
5394         // ill-formed class files.
5395         chk.checkNonCyclic(null, c.type);
5396 
5397         Type st = types.supertype(c.type);
5398         if ((c.flags_field & Flags.COMPOUND) == 0 &&
5399             (c.flags_field & Flags.SUPER_OWNER_ATTRIBUTED) == 0) {
5400             // First, attribute superclass.
5401             if (st.hasTag(CLASS))

5482                                                   .filter(s -> s.tsym.isSealed())
5483                                                   .map(s -> (ClassSymbol) s.tsym)
5484                                                   .collect(List.collector());
5485 
5486             if (sealedSupers.isEmpty()) {
5487                 if ((c.flags_field & Flags.NON_SEALED) != 0) {
5488                     boolean hasErrorSuper = false;
5489 
5490                     hasErrorSuper |= types.directSupertypes(c.type)
5491                                           .stream()
5492                                           .anyMatch(s -> s.tsym.kind == Kind.ERR);
5493 
5494                     ClassType ct = (ClassType) c.type;
5495 
5496                     hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5497 
5498                     if (!hasErrorSuper) {
5499                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5500                     }
5501                 }
5502             } else if ((c.flags_field & Flags.COMPOUND) == 0) {
5503                 if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5504                     log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5505                 }
5506 
5507                 if (!c.type.isCompound()) {
5508                     for (ClassSymbol supertypeSym : sealedSupers) {
5509                         if (!supertypeSym.permitted.contains(c.type.tsym)) {
5510                             log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5511                         }
5512                     }
5513                     if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5514                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5515                                 c.isInterface() ?
5516                                         Errors.NonSealedOrSealedExpected :
5517                                         Errors.NonSealedSealedOrFinalExpected);
5518                     }
5519                 }
5520             }
5521 
5522             // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,

5537 
5538             try {
5539                 deferredLintHandler.flush(env.tree);
5540                 env.info.returnResult = null;
5541                 // java.lang.Enum may not be subclassed by a non-enum
5542                 if (st.tsym == syms.enumSym &&
5543                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5544                     log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5545 
5546                 // Enums may not be extended by source-level classes
5547                 if (st.tsym != null &&
5548                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5549                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5550                     log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5551                 }
5552 
5553                 if (rs.isSerializable(c.type)) {
5554                     env.info.isSerializable = true;
5555                 }
5556 
5557                 if ((c.flags() & (VALUE_CLASS | ABSTRACT)) == VALUE_CLASS) { // for non-intersection, concrete primitive/value classes.
5558                     Assert.check(env.tree.hasTag(CLASSDEF));
5559                     JCClassDecl classDecl = (JCClassDecl) env.tree;
5560                     if (classDecl.extending != null) {
5561                         chk.checkSuperConstraintsOfValueClass(env.tree.pos(), c);
5562                     }
5563                 }
5564 
5565                 attribClassBody(env, c);
5566 
5567                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5568                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5569                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5570                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5571             } finally {
5572                 env.info.returnResult = prevReturnRes;
5573                 log.useSource(prev);
5574                 chk.setLint(prevLint);
5575             }
5576 
5577         }
5578     }
5579 
5580     public void visitImport(JCImport tree) {
5581         // nothing to do
5582     }
5583 
5584     public void visitModuleDef(JCModuleDecl tree) {
< prev index next >