< 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 

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

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

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

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

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

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






























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




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

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

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



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

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











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

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

2839                     tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
2840                 if (cdef == null) { //do not check twice!
2841                     tree.constructorType = checkId(tree,
2842                             clazztype,
2843                             tree.constructor,
2844                             rsEnv,
2845                             new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes), CheckMode.NO_TREE_UPDATE));
2846                     if (rsEnv.info.lastResolveVarargs())
2847                         Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
2848                 }
2849             }
2850 
2851             if (cdef != null) {
2852                 visitAnonymousClassDefinition(tree, clazz, clazztype, cdef, localEnv, argtypes, typeargtypes, pkind);
2853                 return;
2854             }
2855 
2856             if (tree.constructor != null && tree.constructor.kind == MTH)
2857                 owntype = clazztype;
2858         }




2859         result = check(tree, owntype, KindSelector.VAL, resultInfo);
2860         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
2861         if (tree.constructorType != null && inferenceContext.free(tree.constructorType)) {
2862             //we need to wait for inference to finish and then replace inference vars in the constructor type
2863             inferenceContext.addFreeTypeListener(List.of(tree.constructorType),
2864                     instantiatedContext -> {
2865                         tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
2866                     });
2867         }
2868         chk.validate(tree.typeargs, localEnv);
2869     }
2870 
2871         // where
2872         private void visitAnonymousClassDefinition(JCNewClass tree, JCExpression clazz, Type clazztype,
2873                                                    JCClassDecl cdef, Env<AttrContext> localEnv,
2874                                                    List<Type> argtypes, List<Type> typeargtypes,
2875                                                    KindSelector pkind) {
2876             // We are seeing an anonymous class instance creation.
2877             // In this case, the class instance creation
2878             // expression

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

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

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



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

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

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

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










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

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

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

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


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

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

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



























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

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




























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

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

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

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





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

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

5352 
5353             try {
5354                 deferredLintHandler.flush(env.tree);
5355                 env.info.returnResult = null;
5356                 // java.lang.Enum may not be subclassed by a non-enum
5357                 if (st.tsym == syms.enumSym &&
5358                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5359                     log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5360 
5361                 // Enums may not be extended by source-level classes
5362                 if (st.tsym != null &&
5363                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5364                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5365                     log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5366                 }
5367 
5368                 if (isSerializable(c.type)) {
5369                     env.info.isSerializable = true;
5370                 }
5371 








5372                 attribClassBody(env, c);
5373 
5374                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5375                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5376                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5377                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5378             } finally {
5379                 env.info.returnResult = prevReturnRes;
5380                 log.useSource(prev);
5381                 chk.setLint(prevLint);
5382             }
5383 
5384         }
5385     }
5386 
5387     public void visitImport(JCImport tree) {
5388         // nothing to do
5389     }
5390 
5391     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 && v.owner.isPrimitiveClass()) {
 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() & PRIMITIVE_CLASS) != 0 &&
1232                         (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1233                         TreeInfo.isSuperCall(body.stats.head)) {
1234                         // primitive constructors are not allowed to call super directly,
1235                         // but tolerate compiler generated ones
1236                         log.error(tree.body.stats.head.pos(), Errors.CallToSuperNotAllowedInPrimitiveCtor);
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 && v.owner.isPrimitiveClass()) ||
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 || !sym.owner.isPrimitiveClass()) {
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                     // withfield always evaluates to the primitive value type.
1552                     capturedType = capture(ownType.asValueType());
1553                 }
1554             }
1555             result = check(tree, capturedType, KindSelector.VAL, resultInfo);
1556         } finally {
1557             env.info.inWithField = inWithField;
1558         }
1559     }
1560 
1561     public void visitForLoop(JCForLoop tree) {
1562         Env<AttrContext> loopEnv =
1563             env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1564         MatchBindings condBindings = MatchBindingsComputer.EMPTY;
1565         try {
1566             attribStats(tree.init, loopEnv);
1567             if (tree.cond != null) {
1568                 attribExpr(tree.cond, loopEnv, syms.booleanType);
1569                 // include condition's bindings when true in the body and step:
1570                 condBindings = matchBindings;
1571             }
1572             Env<AttrContext> bodyEnv = bindingEnv(loopEnv, condBindings.bindingsWhenTrue);
1573             try {
1574                 bodyEnv.tree = tree; // before, we were not in loop!
1575                 attribStats(tree.step, bodyEnv);
1576                 attribStat(tree.body, bodyEnv);
1577             } finally {
1578                 bodyEnv.info.scope.leave();
1579             }
1580             result = null;

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

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.isPrimitiveReferenceType() ? t.asValueType() : 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 = env.enclClass.sym.isPrimitiveClass()
2660                         && (tree.meth.hasTag(SELECT))
2661                         && ((JCFieldAccess)tree.meth).selected.hasTag(IDENT)
2662                         && TreeInfo.name(((JCFieldAccess)tree.meth).selected) == names._super;
2663                 if (qualifier.tsym.isPrimitiveClass() || 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 "clone":
2677                         case "finalize":
2678                             if (argSize == 0)
2679                                 log.error(tree.pos(), Errors.PrimitiveClassDoesNotSupport(name));
2680                             break;
2681                     }
2682                 }
2683             }
2684 
2685             // Check that value of resulting type is admissible in the
2686             // current context.  Also, capture the return type
2687             Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true);
2688             result = check(tree, capturedRes, KindSelector.VAL, resultInfo);
2689         }
2690         chk.validate(tree.typeargs, localEnv);
2691     }
2692     //where
2693         Type adjustMethodReturnType(Symbol msym, Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
2694             if (msym != null &&
2695                     (msym.owner == syms.objectType.tsym || msym.owner.isInterface()) &&
2696                     methodName == names.getClass &&
2697                     argtypes.isEmpty()) {
2698                 // as a special case, x.getClass() has type Class<? extends |X|>
2699                 // Special treatment for primitive classes: Given an expression v of type V where
2700                 // V is a primitive class, v.getClass() is typed to be Class<? extends |V.ref|>
2701                 Type wcb = types.erasure(qualifierType.isPrimitiveClass() ?
2702                                                 qualifierType.referenceProjection() : qualifierType);
2703                 return new ClassType(restype.getEnclosingType(),
2704                         List.of(new WildcardType(wcb,
2705                                 BoundKind.EXTENDS,
2706                                 syms.boundClass)),
2707                         restype.tsym,
2708                         restype.getMetadata(),
2709                         restype.getFlavor());
2710             } else if (msym != null &&
2711                     msym.owner == syms.arrayClass &&
2712                     methodName == names.clone &&
2713                     types.isArray(qualifierType)) {
2714                 // as a special case, array.clone() has a result that is
2715                 // the same as static type of the array being cloned
2716                 return qualifierType;
2717             } else {
2718                 return restype;
2719             }
2720         }
2721 
2722         /** Check that given application node appears as first statement
2723          *  in a constructor call.
2724          *  @param tree          The application node
2725          *  @param enclMethod    The enclosing method of the application.
2726          *  @param error         Should an error be issued?
2727          */
2728         boolean checkFirstConstructorStat(JCMethodInvocation tree, JCMethodDecl enclMethod, boolean error) {
2729             if (enclMethod != null && enclMethod.name == names.init) {

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

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

2961                     tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
2962                 if (cdef == null) { //do not check twice!
2963                     tree.constructorType = checkId(tree,
2964                             clazztype,
2965                             tree.constructor,
2966                             rsEnv,
2967                             new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes), CheckMode.NO_TREE_UPDATE));
2968                     if (rsEnv.info.lastResolveVarargs())
2969                         Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
2970                 }
2971             }
2972 
2973             if (cdef != null) {
2974                 visitAnonymousClassDefinition(tree, clazz, clazztype, cdef, localEnv, argtypes, typeargtypes, pkind);
2975                 return;
2976             }
2977 
2978             if (tree.constructor != null && tree.constructor.kind == MTH)
2979                 owntype = clazztype;
2980         }
2981         // For primitive classes construction always returns the value type.
2982         if (owntype.tsym.isPrimitiveClass()) {
2983             owntype = owntype.asValueType();
2984         }
2985         result = check(tree, owntype, KindSelector.VAL, resultInfo);
2986         InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
2987         if (tree.constructorType != null && inferenceContext.free(tree.constructorType)) {
2988             //we need to wait for inference to finish and then replace inference vars in the constructor type
2989             inferenceContext.addFreeTypeListener(List.of(tree.constructorType),
2990                     instantiatedContext -> {
2991                         tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
2992                     });
2993         }
2994         chk.validate(tree.typeargs, localEnv);
2995     }
2996 
2997         // where
2998         private void visitAnonymousClassDefinition(JCNewClass tree, JCExpression clazz, Type clazztype,
2999                                                    JCClassDecl cdef, Env<AttrContext> localEnv,
3000                                                    List<Type> argtypes, List<Type> typeargtypes,
3001                                                    KindSelector pkind) {
3002             // We are seeing an anonymous class instance creation.
3003             // In this case, the class instance creation
3004             // expression

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

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

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

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

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

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

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

5026             //depending on the current check context
5027             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
5028             return types.createErrorType(site);
5029         } catch (Resolve.InapplicableMethodException ex) {
5030             final JCDiagnostic diag = ex.getDiagnostic();
5031             Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
5032                 @Override
5033                 protected Pair<Symbol, JCDiagnostic> errCandidate() {
5034                     return new Pair<>(sym, diag);
5035                 }
5036             };
5037             List<Type> argtypes2 = argtypes.map(
5038                     rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
5039             JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
5040                     env.tree, sym, site, sym.name, argtypes2, typeargtypes);
5041             log.report(errDiag);
5042             return types.createErrorType(site);
5043         }
5044     }
5045 
5046     public void visitDefaultValue(JCDefaultValue tree) {
5047         if (!allowPrimitiveClasses) {
5048             log.error(DiagnosticFlag.SOURCE_LEVEL, tree.pos(),
5049                     Feature.PRIMITIVE_CLASSES.error(sourceName));
5050         }
5051 
5052         // Attribute the qualifier expression, and determine its symbol (if any).
5053         Type site = attribTree(tree.clazz, env, new ResultInfo(KindSelector.TYP_PCK, Type.noType));
5054         if (!pkind().contains(KindSelector.TYP_PCK))
5055             site = capture(site); // Capture field access
5056 
5057         Symbol sym = switch (site.getTag()) {
5058                 case WILDCARD -> throw new AssertionError(tree);
5059                 case PACKAGE -> {
5060                     log.error(tree.pos, Errors.CantResolveLocation(Kinds.KindName.CLASS, site.tsym.getQualifiedName(), null, null,
5061                             Fragments.Location(Kinds.typeKindName(env.enclClass.type), env.enclClass.type, null)));
5062                     yield syms.errSymbol;
5063                 }
5064                 case ERROR -> types.createErrorType(names._default, site.tsym, site).tsym;
5065                 default -> new VarSymbol(STATIC, names._default, site, site.tsym);
5066         };
5067 
5068         if (site.hasTag(TYPEVAR) && sym.kind != ERR) {
5069             site = types.skipTypeVars(site, true);
5070         }
5071         result = checkId(tree, site, sym, env, resultInfo);
5072     }
5073 
5074     public void visitLiteral(JCLiteral tree) {
5075         result = check(tree, litType(tree.typetag).constType(tree.value),
5076                 KindSelector.VAL, resultInfo);
5077     }
5078     //where
5079     /** Return the type of a literal with given type tag.
5080      */
5081     Type litType(TypeTag tag) {
5082         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
5083     }
5084 
5085     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
5086         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
5087     }
5088 
5089     public void visitTypeArray(JCArrayTypeTree tree) {
5090         Type etype = attribType(tree.elemtype, env);
5091         Type type = new ArrayType(etype, syms.arrayClass);
5092         result = check(tree, type, KindSelector.TYP, resultInfo);
5093     }

5120                 }
5121                 // Compute the proper generic outer
5122                 Type clazzOuter = clazztype.getEnclosingType();
5123                 if (clazzOuter.hasTag(CLASS)) {
5124                     Type site;
5125                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
5126                     if (clazz.hasTag(IDENT)) {
5127                         site = env.enclClass.sym.type;
5128                     } else if (clazz.hasTag(SELECT)) {
5129                         site = ((JCFieldAccess) clazz).selected.type;
5130                     } else throw new AssertionError(""+tree);
5131                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
5132                         if (site.hasTag(CLASS))
5133                             site = types.asOuterSuper(site, clazzOuter.tsym);
5134                         if (site == null)
5135                             site = types.erasure(clazzOuter);
5136                         clazzOuter = site;
5137                     }
5138                 }
5139                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
5140                                         clazztype.getMetadata(), clazztype.getFlavor());
5141             } else {
5142                 if (formals.length() != 0) {
5143                     log.error(tree.pos(),
5144                               Errors.WrongNumberTypeArgs(Integer.toString(formals.length())));
5145                 } else {
5146                     log.error(tree.pos(), Errors.TypeDoesntTakeParams(clazztype.tsym));
5147                 }
5148                 owntype = types.createErrorType(tree.type);
5149             }
5150         }
5151         result = check(tree, owntype, KindSelector.TYP, resultInfo);
5152     }
5153 
5154     public void visitTypeUnion(JCTypeUnion tree) {
5155         ListBuffer<Type> multicatchTypes = new ListBuffer<>();
5156         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
5157         for (JCExpression typeTree : tree.alternatives) {
5158             Type ctype = attribType(typeTree, env);
5159             ctype = chk.checkType(typeTree.pos(),
5160                           chk.checkClassType(typeTree.pos(), ctype),

5247         if (bounds.length() == 0) {
5248             return syms.objectType;
5249         } else if (bounds.length() == 1) {
5250             return bounds.head.type;
5251         } else {
5252             Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
5253             // ... the variable's bound is a class type flagged COMPOUND
5254             // (see comment for TypeVar.bound).
5255             // In this case, generate a class tree that represents the
5256             // bound class, ...
5257             JCExpression extending;
5258             List<JCExpression> implementing;
5259             if (!bounds.head.type.isInterface()) {
5260                 extending = bounds.head;
5261                 implementing = bounds.tail;
5262             } else {
5263                 extending = null;
5264                 implementing = bounds;
5265             }
5266             JCClassDecl cd = make.at(tree).ClassDef(
5267                 make.Modifiers(PUBLIC | ABSTRACT | (extending != null && TreeInfo.symbol(extending).isPrimitiveClass() ? PRIMITIVE_CLASS : 0)),
5268                 names.empty, List.nil(),
5269                 extending, implementing, List.nil());
5270 
5271             ClassSymbol c = (ClassSymbol)owntype.tsym;
5272             Assert.check((c.flags() & COMPOUND) != 0);
5273             cd.sym = c;
5274             c.sourcefile = env.toplevel.sourcefile;
5275 
5276             // ... and attribute the bound class
5277             c.flags_field |= UNATTRIBUTED;
5278             Env<AttrContext> cenv = enter.classEnv(cd, env);
5279             typeEnvs.put(c, cenv);
5280             attribClass(c);
5281             return owntype;
5282         }
5283     }
5284 
5285     public void visitWildcard(JCWildcard tree) {
5286         //- System.err.println("visitWildcard("+tree+");");//DEBUG
5287         Type type = (tree.kind.kind == BoundKind.UNBOUND)
5288             ? syms.objectType
5289             : attribType(tree.inner, env);
5290         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type, false),
5291                                               tree.kind.kind,
5292                                               syms.boundClass),
5293                 KindSelector.TYP, resultInfo);
5294     }
5295 
5296     public void visitAnnotation(JCAnnotation tree) {
5297         Assert.error("should be handled in annotate");
5298     }
5299 
5300     public void visitAnnotatedType(JCAnnotatedType tree) {
5301         attribAnnotationTypes(tree.annotations, env);
5302         Type underlyingType = attribType(tree.underlyingType, env);
5303         Type annotatedType = underlyingType.annotatedType(Annotations.TO_BE_SET);
5304 
5305         if (!env.info.isNewClass)
5306             annotate.annotateTypeSecondStage(tree, tree.annotations, annotatedType);
5307         result = tree.type = annotatedType;
5308     }
5309 
5310     public void visitErroneous(JCErroneous tree) {

5377             chk.completionError(pos, ex);
5378         }
5379     }
5380 
5381     void attribModule(ModuleSymbol m) {
5382         // Get environment current at the point of module definition.
5383         Env<AttrContext> env = enter.typeEnvs.get(m);
5384         attribStat(env.tree, env);
5385     }
5386 
5387     /** Main method: attribute class definition associated with given class symbol.
5388      *  reporting completion failures at the given position.
5389      *  @param pos The source position at which completion errors are to be
5390      *             reported.
5391      *  @param c   The class symbol whose definition will be attributed.
5392      */
5393     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
5394         try {
5395             annotate.flush();
5396             attribClass(c);
5397             if (c.isPrimitiveClass()) {
5398                 final Env<AttrContext> env = typeEnvs.get(c);
5399                 if (env != null && env.tree != null && env.tree.hasTag(CLASSDEF))
5400                     chk.checkNonCyclicMembership((JCClassDecl)env.tree);
5401             }
5402         } catch (CompletionFailure ex) {
5403             chk.completionError(pos, ex);
5404         }
5405     }
5406 
5407     /** Attribute class definition associated with given class symbol.
5408      *  @param c   The class symbol whose definition will be attributed.
5409      */
5410     void attribClass(ClassSymbol c) throws CompletionFailure {
5411         if (c.type.hasTag(ERROR)) return;
5412 
5413         // Check for cycles in the inheritance graph, which can arise from
5414         // ill-formed class files.
5415         chk.checkNonCyclic(null, c.type);
5416 
5417         Type st = types.supertype(c.type);
5418         if ((c.flags_field & Flags.COMPOUND) == 0 &&
5419             (c.flags_field & Flags.SUPER_OWNER_ATTRIBUTED) == 0) {
5420             // First, attribute superclass.
5421             if (st.hasTag(CLASS))

5502                                                   .filter(s -> s.tsym.isSealed())
5503                                                   .map(s -> (ClassSymbol) s.tsym)
5504                                                   .collect(List.collector());
5505 
5506             if (sealedSupers.isEmpty()) {
5507                 if ((c.flags_field & Flags.NON_SEALED) != 0) {
5508                     boolean hasErrorSuper = false;
5509 
5510                     hasErrorSuper |= types.directSupertypes(c.type)
5511                                           .stream()
5512                                           .anyMatch(s -> s.tsym.kind == Kind.ERR);
5513 
5514                     ClassType ct = (ClassType) c.type;
5515 
5516                     hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5517 
5518                     if (!hasErrorSuper) {
5519                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5520                     }
5521                 }
5522             } else if ((c.flags_field & Flags.COMPOUND) == 0) {
5523                 if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5524                     log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5525                 }
5526 
5527                 if (!c.type.isCompound()) {
5528                     for (ClassSymbol supertypeSym : sealedSupers) {
5529                         if (!supertypeSym.permitted.contains(c.type.tsym)) {
5530                             log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5531                         }
5532                     }
5533                     if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5534                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5535                                 c.isInterface() ?
5536                                         Errors.NonSealedOrSealedExpected :
5537                                         Errors.NonSealedSealedOrFinalExpected);
5538                     }
5539                 }
5540             }
5541 
5542             // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,

5557 
5558             try {
5559                 deferredLintHandler.flush(env.tree);
5560                 env.info.returnResult = null;
5561                 // java.lang.Enum may not be subclassed by a non-enum
5562                 if (st.tsym == syms.enumSym &&
5563                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5564                     log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5565 
5566                 // Enums may not be extended by source-level classes
5567                 if (st.tsym != null &&
5568                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5569                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5570                     log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5571                 }
5572 
5573                 if (isSerializable(c.type)) {
5574                     env.info.isSerializable = true;
5575                 }
5576 
5577                 if ((c.flags() & (PRIMITIVE_CLASS | ABSTRACT)) == PRIMITIVE_CLASS) { // for non-intersection, concrete primitive classes.
5578                     Assert.check(env.tree.hasTag(CLASSDEF));
5579                     JCClassDecl classDecl = (JCClassDecl) env.tree;
5580                     if (classDecl.extending != null) {
5581                         chk.checkSuperConstraintsOfPrimitiveClass(env.tree.pos(), c);
5582                     }
5583                 }
5584 
5585                 attribClassBody(env, c);
5586 
5587                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5588                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5589                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5590                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5591             } finally {
5592                 env.info.returnResult = prevReturnRes;
5593                 log.useSource(prev);
5594                 chk.setLint(prevLint);
5595             }
5596 
5597         }
5598     }
5599 
5600     public void visitImport(JCImport tree) {
5601         // nothing to do
5602     }
5603 
5604     public void visitModuleDef(JCModuleDecl tree) {
< prev index next >