< prev index next >

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

Print this page

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

  48 import com.sun.tools.javac.code.TypeMetadata.Annotations;
  49 import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError;
  50 import com.sun.tools.javac.comp.ArgumentAttr.LocalCacheContext;
  51 import com.sun.tools.javac.comp.Check.CheckContext;
  52 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
  53 import com.sun.tools.javac.comp.MatchBindingsComputer.MatchBindings;
  54 import com.sun.tools.javac.jvm.*;
  55 
  56 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond;
  57 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArg;
  58 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArgs;
  59 
  60 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  61 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  62 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
  63 import com.sun.tools.javac.tree.*;
  64 import com.sun.tools.javac.tree.JCTree.*;
  65 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
  66 import com.sun.tools.javac.util.*;
  67 import com.sun.tools.javac.util.DefinedBy.Api;

 149         infer = Infer.instance(context);
 150         analyzer = Analyzer.instance(context);
 151         deferredAttr = DeferredAttr.instance(context);
 152         cfolder = ConstFold.instance(context);
 153         target = Target.instance(context);
 154         types = Types.instance(context);
 155         preview = Preview.instance(context);
 156         diags = JCDiagnostic.Factory.instance(context);
 157         annotate = Annotate.instance(context);
 158         typeAnnotations = TypeAnnotations.instance(context);
 159         deferredLintHandler = DeferredLintHandler.instance(context);
 160         typeEnvs = TypeEnvs.instance(context);
 161         dependencies = Dependencies.instance(context);
 162         argumentAttr = ArgumentAttr.instance(context);
 163         matchBindingsComputer = MatchBindingsComputer.instance(context);
 164         attrRecover = AttrRecover.instance(context);
 165 
 166         Options options = Options.instance(context);
 167 
 168         Source source = Source.instance(context);

 169         allowReifiableTypesInInstanceof = Feature.REIFIABLE_TYPES_INSTANCEOF.allowedInSource(source);
 170         allowRecords = Feature.RECORDS.allowedInSource(source);
 171         allowPatternSwitch = (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH)) &&
 172                              Feature.PATTERN_SWITCH.allowedInSource(source);
 173         allowUnconditionalPatternsInstanceOf = (preview.isEnabled() || !preview.isPreview(Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF)) &&
 174                                      Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.allowedInSource(source);
 175         sourceName = source.name;
 176         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
 177 
 178         statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
 179         varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
 180         unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
 181         methodAttrInfo = new MethodAttrInfo();
 182         unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
 183         unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
 184         recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
 185     }
 186 




 187     /** Switch: reifiable types in instanceof enabled?
 188      */
 189     boolean allowReifiableTypesInInstanceof;
 190 
 191     /** Are records allowed
 192      */
 193     private final boolean allowRecords;
 194 
 195     /** Are patterns in switch allowed
 196      */
 197     private final boolean allowPatternSwitch;
 198 
 199     /** Are unconditional patterns in instanceof allowed
 200      */
 201     private final boolean allowUnconditionalPatternsInstanceOf;
 202 
 203     /**
 204      * Switch: warn about use of variable before declaration?
 205      * RFE: 6425594
 206      */

 255             found;
 256         }
 257         if (resultInfo.checkMode.updateTreeType()) {
 258             tree.type = owntype;
 259         }
 260         return owntype;
 261     }
 262 
 263     /** Is given blank final variable assignable, i.e. in a scope where it
 264      *  may be assigned to even though it is final?
 265      *  @param v      The blank final variable.
 266      *  @param env    The current environment.
 267      */
 268     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
 269         Symbol owner = env.info.scope.owner;
 270            // owner refers to the innermost variable, method or
 271            // initializer block declaration at this point.
 272         boolean isAssignable =
 273             v.owner == owner
 274             ||
 275             ((owner.name == names.init ||    // i.e. we are in a constructor
 276               owner.kind == VAR ||           // i.e. we are in a variable initializer
 277               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
 278              &&
 279              v.owner == owner.owner
 280              &&
 281              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
 282         boolean insideCompactConstructor = env.enclMethod != null && TreeInfo.isCompactConstructor(env.enclMethod);
 283         return isAssignable & !insideCompactConstructor;
 284     }
 285 
 286     /** Check that variable can be assigned to.
 287      *  @param pos    The current source code position.
 288      *  @param v      The assigned variable
 289      *  @param base   If the variable is referred to in a Select, the part
 290      *                to the left of the `.', null otherwise.
 291      *  @param env    The current environment.
 292      */
 293     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
 294         if (v.name == names._this) {
 295             log.error(pos, Errors.CantAssignValToThis);

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

1054                         log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.MethodMustBePublic));
1055                     }
1056                     if (!types.isSameType(tree.sym.type.getReturnType(), recordComponent.get().type)) {
1057                         log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym,
1058                                 Fragments.AccessorReturnTypeDoesntMatch(tree.sym, recordComponent.get())));
1059                     }
1060                     if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1061                         log.error(tree,
1062                                 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodCantThrowException));
1063                     }
1064                     if (!tree.typarams.isEmpty()) {
1065                         log.error(tree,
1066                                 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeGeneric));
1067                     }
1068                     if (tree.sym.isStatic()) {
1069                         log.error(tree,
1070                                 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeStatic));
1071                     }
1072                 }
1073 
1074                 if (tree.name == names.init) {
1075                     // if this a constructor other than the canonical one
1076                     if ((tree.sym.flags_field & RECORD) == 0) {
1077                         JCMethodInvocation app = TreeInfo.firstConstructorCall(tree);
1078                         if (app == null ||
1079                                 TreeInfo.name(app.meth) != names._this ||
1080                                 !checkFirstConstructorStat(app, tree, false)) {
1081                             log.error(tree, Errors.FirstStatementMustBeCallToAnotherConstructor(env.enclClass.sym));
1082                         }
1083                     } else {
1084                         // but if it is the canonical:
1085 
1086                         /* if user generated, then it shouldn't:
1087                          *     - have an accessibility stricter than that of the record type
1088                          *     - explicitly invoke any other constructor
1089                          */
1090                         if ((tree.sym.flags_field & GENERATEDCONSTR) == 0) {
1091                             if (Check.protection(m.flags()) > Check.protection(env.enclClass.sym.flags())) {
1092                                 log.error(tree,
1093                                         (env.enclClass.sym.flags() & AccessFlags) == 0 ?
1094                                             Errors.InvalidCanonicalConstructorInRecord(

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






1205                     }
1206                     if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1207                         List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1208                         List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1209                         if (!initParamNames.equals(recordComponentNames)) {
1210                             log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1211                                     Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1212                         }
1213                         if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1214                             log.error(tree,
1215                                     Errors.InvalidCanonicalConstructorInRecord(
1216                                             TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical,
1217                                             env.enclClass.sym.name,
1218                                             Fragments.ThrowsClauseNotAllowedForCanonicalConstructor(
1219                                                     TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical)));
1220                         }
1221                     }
1222                 }
1223 
1224                 // Attribute all type annotations in the body

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



1292             if (tree.init != null) {
1293                 if ((v.flags_field & FINAL) == 0 ||
1294                     !memberEnter.needsLazyConstValue(tree.init)) {
1295                     // Not a compile-time constant
1296                     // Attribute initializer in a new environment
1297                     // with the declared variable as owner.
1298                     // Check that initializer conforms to variable's declared type.
1299                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1300                     initEnv.info.lint = lint;
1301                     // In order to catch self-references, we set the variable's
1302                     // declaration position to maximal possible value, effectively
1303                     // marking the variable as undefined.
1304                     initEnv.info.enclVar = v;
1305                     attribExpr(tree.init, initEnv, v.type);
1306                     if (tree.isImplicitlyTyped()) {
1307                         //fixup local variable type
1308                         v.type = chk.checkLocalVarType(tree, tree.init.type, tree.name);
1309                     }
1310                 }
1311                 if (tree.isImplicitlyTyped()) {
1312                     setSyntheticVariableType(tree, v.type);
1313                 }
1314             }
1315             result = tree.type = v.type;
1316             if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1317                 if (isNonArgsMethodInObject(v.name)) {
1318                     log.error(tree, Errors.IllegalRecordComponentName(v));
1319                 }
1320             }
1321         }
1322         finally {
1323             chk.setLint(prevLint);
1324         }
1325     }
1326 
1327     private boolean isNonArgsMethodInObject(Name name) {
1328         for (Symbol s : syms.objectType.tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) {
1329             if (s.type.getParameterTypes().isEmpty()) {
1330                 return true;
1331             }
1332         }
1333         return false;

1334     }
1335 
1336     Fragment canInferLocalVarType(JCVariableDecl tree) {
1337         LocalInitScanner lis = new LocalInitScanner();
1338         lis.scan(tree.init);
1339         return lis.badInferenceMsg;
1340     }
1341 
1342     static class LocalInitScanner extends TreeScanner {
1343         Fragment badInferenceMsg = null;
1344         boolean needsTarget = true;
1345 
1346         @Override
1347         public void visitNewArray(JCNewArray tree) {
1348             if (tree.elemtype == null && needsTarget) {
1349                 badInferenceMsg = Fragments.LocalArrayMissingTarget;
1350             }
1351         }
1352 
1353         @Override

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

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

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

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) {

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




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

2601             } else if (msym != null &&
2602                     msym.owner == syms.arrayClass &&
2603                     methodName == names.clone &&
2604                     types.isArray(qualifierType)) {
2605                 // as a special case, array.clone() has a result that is
2606                 // the same as static type of the array being cloned
2607                 return qualifierType;
2608             } else {
2609                 return restype;
2610             }
2611         }
2612 
2613         /** Check that given application node appears as first statement
2614          *  in a constructor call.
2615          *  @param tree          The application node
2616          *  @param enclMethod    The enclosing method of the application.
2617          *  @param error         Should an error be issued?
2618          */
2619         boolean checkFirstConstructorStat(JCMethodInvocation tree, JCMethodDecl enclMethod, boolean error) {
2620             if (enclMethod != null && enclMethod.name == names.init) {
2621                 JCBlock body = enclMethod.body;
2622                 if (body.stats.head.hasTag(EXEC) &&
2623                     ((JCExpressionStatement) body.stats.head).expr == tree)
2624                     return true;
2625             }
2626             if (error) {
2627                 log.error(tree.pos(),
2628                         Errors.CallMustBeFirstStmtInCtor(TreeInfo.name(tree.meth)));
2629             }
2630             return false;
2631         }
2632 
2633         /** Obtain a method type with given argument types.
2634          */
2635         Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
2636             MethodType mt = new MethodType(argtypes, restype, List.nil(), syms.methodClass);
2637             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
2638         }
2639 
2640     public void visitNewClass(final JCNewClass tree) {

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










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

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

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



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

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



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

3488          *
3489          * The owner of this environment is a method symbol. If the current owner
3490          * is not a method, for example if the lambda is used to initialize
3491          * a field, then if the field is:
3492          *
3493          * - an instance field, we use the first constructor.
3494          * - a static field, we create a fake clinit method.
3495          */
3496         public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
3497             Env<AttrContext> lambdaEnv;
3498             Symbol owner = env.info.scope.owner;
3499             if (owner.kind == VAR && owner.owner.kind == TYP) {
3500                 //field initializer
3501                 ClassSymbol enclClass = owner.enclClass();
3502                 Symbol newScopeOwner = env.info.scope.owner;
3503                 /* if the field isn't static, then we can get the first constructor
3504                  * and use it as the owner of the environment. This is what
3505                  * LTM code is doing to look for type annotations so we are fine.
3506                  */
3507                 if ((owner.flags() & STATIC) == 0) {
3508                     for (Symbol s : enclClass.members_field.getSymbolsByName(names.init)) {

3509                         newScopeOwner = s;
3510                         break;
3511                     }
3512                 } else {
3513                     /* if the field is static then we need to create a fake clinit
3514                      * method, this method can later be reused by LTM.
3515                      */
3516                     MethodSymbol clinit = clinits.get(enclClass);
3517                     if (clinit == null) {
3518                         Type clinitType = new MethodType(List.nil(),
3519                                 syms.voidType, List.nil(), syms.methodClass);
3520                         clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE,
3521                                 names.clinit, clinitType, enclClass);
3522                         clinit.params = List.nil();
3523                         clinits.put(enclClass, clinit);
3524                     }
3525                     newScopeOwner = clinit;
3526                 }
3527                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(newScopeOwner)));
3528             } else {

3551 
3552             if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3553                 exprType = chk.checkConstructorRefType(that.expr, exprType);
3554                 if (!exprType.isErroneous() &&
3555                     exprType.isRaw() &&
3556                     that.typeargs != null) {
3557                     log.error(that.expr.pos(),
3558                               Errors.InvalidMref(Kinds.kindName(that.getMode()),
3559                                                  Fragments.MrefInferAndExplicitParams));
3560                     exprType = types.createErrorType(exprType);
3561                 }
3562             }
3563 
3564             if (exprType.isErroneous()) {
3565                 //if the qualifier expression contains problems,
3566                 //give up attribution of method reference
3567                 result = that.type = exprType;
3568                 return;
3569             }
3570 

3571             if (TreeInfo.isStaticSelector(that.expr, names)) {




3572                 //if the qualifier is a type, validate it; raw warning check is
3573                 //omitted as we don't know at this stage as to whether this is a
3574                 //raw selector (because of inference)
3575                 chk.validate(that.expr, env, false);
3576             } else {
3577                 Symbol lhsSym = TreeInfo.symbol(that.expr);
3578                 localEnv.info.selectSuper = lhsSym != null && lhsSym.name == names._super;
3579             }
3580             //attrib type-arguments
3581             List<Type> typeargtypes = List.nil();
3582             if (that.typeargs != null) {
3583                 typeargtypes = attribTypes(that.typeargs, localEnv);
3584             }
3585 
3586             boolean isTargetSerializable =
3587                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3588                     rs.isSerializable(pt());
3589             TargetInfo targetInfo = getTargetInfo(that, resultInfo, null);
3590             Type currentTarget = targetInfo.target;
3591             Type desc = targetInfo.descriptor;
3592 
3593             setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
3594             List<Type> argtypes = desc.getParameterTypes();
3595             Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
3596 
3597             if (resultInfo.checkContext.inferenceContext().free(argtypes)) {

3641                         targetError ?
3642                             Fragments.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag) :
3643                             Errors.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag));
3644 
3645                 if (targetError && currentTarget == Type.recoveryType) {
3646                     //a target error doesn't make sense during recovery stage
3647                     //as we don't know what actual parameter types are
3648                     result = that.type = currentTarget;
3649                     return;
3650                 } else {
3651                     if (targetError) {
3652                         resultInfo.checkContext.report(that, diag);
3653                     } else {
3654                         log.report(diag);
3655                     }
3656                     result = that.type = types.createErrorType(currentTarget);
3657                     return;
3658                 }
3659             }
3660 
3661             that.sym = refSym.isConstructor() ? refSym.baseSymbol() : refSym;
3662             that.kind = lookupHelper.referenceKind(that.sym);
3663             that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
3664 
3665             if (desc.getReturnType() == Type.recoveryType) {
3666                 // stop here
3667                 result = that.type = currentTarget;
3668                 return;
3669             }
3670 
3671             if (!env.info.attributionMode.isSpeculative && that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3672                 Type enclosingType = exprType.getEnclosingType();
3673                 if (enclosingType != null && enclosingType.hasTag(CLASS)) {
3674                     // Check for the existence of an appropriate outer instance
3675                     rs.resolveImplicitThis(that.pos(), env, exprType);
3676                 }
3677             }
3678 
3679             if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
3680 
3681                 if (that.getMode() == ReferenceMode.INVOKE &&

4325     }
4326 
4327     public void visitSelect(JCFieldAccess tree) {
4328         // Determine the expected kind of the qualifier expression.
4329         KindSelector skind = KindSelector.NIL;
4330         if (tree.name == names._this || tree.name == names._super ||
4331                 tree.name == names._class)
4332         {
4333             skind = KindSelector.TYP;
4334         } else {
4335             if (pkind().contains(KindSelector.PCK))
4336                 skind = KindSelector.of(skind, KindSelector.PCK);
4337             if (pkind().contains(KindSelector.TYP))
4338                 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4339             if (pkind().contains(KindSelector.VAL_MTH))
4340                 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4341         }
4342 
4343         // Attribute the qualifier expression, and determine its symbol (if any).
4344         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));










4345         if (!pkind().contains(KindSelector.TYP_PCK))
4346             site = capture(site); // Capture field access
4347 
4348         // don't allow T.class T[].class, etc
4349         if (skind == KindSelector.TYP) {
4350             Type elt = site;
4351             while (elt.hasTag(ARRAY))
4352                 elt = ((ArrayType)elt).elemtype;
4353             if (elt.hasTag(TYPEVAR)) {
4354                 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4355                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4356                 tree.sym = tree.type.tsym;
4357                 return ;
4358             }
4359         }
4360 
4361         // If qualifier symbol is a type or `super', assert `selectSuper'
4362         // for the selection. This is relevant for determining whether
4363         // protected symbols are accessible.
4364         Symbol sitesym = TreeInfo.symbol(tree.selected);
4365         boolean selectSuperPrev = env.info.selectSuper;
4366         env.info.selectSuper =
4367             sitesym != null &&
4368             sitesym.name == names._super;
4369 
4370         // Determine the symbol represented by the selection.
4371         env.info.pendingResolutionPhase = null;
4372         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
4373         if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
4374             log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym));
4375             sym = syms.errSymbol;
4376         }
4377         if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {

4441         } else if (sym.kind != ERR &&
4442                    (sym.flags() & STATIC) != 0 &&
4443                    sym.name != names._class) {
4444             // If the qualified item is not a type and the selected item is static, report
4445             // a warning. Make allowance for the class of an array type e.g. Object[].class)
4446             if (!sym.owner.isAnonymous()) {
4447                 chk.warnStatic(tree, Warnings.StaticNotQualifiedByType(sym.kind.kindName(), sym.owner));
4448             } else {
4449                 chk.warnStatic(tree, Warnings.StaticNotQualifiedByType2(sym.kind.kindName()));
4450             }
4451         }
4452 
4453         // If we are selecting an instance member via a `super', ...
4454         if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
4455 
4456             // Check that super-qualified symbols are not abstract (JLS)
4457             rs.checkNonAbstract(tree.pos(), sym);
4458 
4459             if (site.isRaw()) {
4460                 // Determine argument types for site.
4461                 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
4462                 if (site1 != null) site = site1;
4463             }
4464         }
4465 
4466         if (env.info.isSerializable) {
4467             chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4468         }
4469 
4470         env.info.selectSuper = selectSuperPrev;
4471         result = checkId(tree, site, sym, env, resultInfo);
4472     }
4473     //where
4474         /** Determine symbol referenced by a Select expression,
4475          *
4476          *  @param tree   The select tree.
4477          *  @param site   The type of the selected expression,
4478          *  @param env    The current environment.
4479          *  @param resultInfo The current result.
4480          */
4481         private Symbol selectSym(JCFieldAccess tree,

4484                                  Env<AttrContext> env,
4485                                  ResultInfo resultInfo) {
4486             DiagnosticPosition pos = tree.pos();
4487             Name name = tree.name;
4488             switch (site.getTag()) {
4489             case PACKAGE:
4490                 return rs.accessBase(
4491                     rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind),
4492                     pos, location, site, name, true);
4493             case ARRAY:
4494             case CLASS:
4495                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
4496                     return rs.resolveQualifiedMethod(
4497                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
4498                 } else if (name == names._this || name == names._super) {
4499                     return rs.resolveSelf(pos, env, site.tsym, name);
4500                 } else if (name == names._class) {
4501                     // In this case, we have already made sure in
4502                     // visitSelect that qualifier expression is a type.
4503                     return syms.getClassField(site, types);


4504                 } else {
4505                     // We are seeing a plain identifier as selector.
4506                     Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind);
4507                         sym = rs.accessBase(sym, pos, location, site, name, true);
4508                     return sym;
4509                 }
4510             case WILDCARD:
4511                 throw new AssertionError(tree);
4512             case TYPEVAR:
4513                 // Normally, site.getUpperBound() shouldn't be null.
4514                 // It should only happen during memberEnter/attribBase
4515                 // when determining the supertype which *must* be
4516                 // done before attributing the type variables.  In
4517                 // other words, we are seeing this illegal program:
4518                 // class B<T> extends A<T.foo> {}
4519                 Symbol sym = (site.getUpperBound() != null)
4520                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
4521                     : null;
4522                 if (sym == null) {
4523                     log.error(pos, Errors.TypeVarCantBeDeref);

4587             if (resultInfo.pkind.contains(KindSelector.POLY)) {
4588                 return attrRecover.recoverMethodInvocation(tree, site, sym, env, resultInfo);
4589             } else {
4590                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
4591             }
4592         }
4593 
4594         Type checkIdInternal(JCTree tree,
4595                      Type site,
4596                      Symbol sym,
4597                      Type pt,
4598                      Env<AttrContext> env,
4599                      ResultInfo resultInfo) {
4600             if (pt.isErroneous()) {
4601                 return types.createErrorType(site);
4602             }
4603             Type owntype; // The computed type of this identifier occurrence.
4604             switch (sym.kind) {
4605             case TYP:
4606                 // For types, the computed type equals the symbol's type,
4607                 // except for two situations:
4608                 owntype = sym.type;
4609                 if (owntype.hasTag(CLASS)) {



4610                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
4611                     Type ownOuter = owntype.getEnclosingType();
4612 
4613                     // (a) If the symbol's type is parameterized, erase it







4614                     // because no type parameters were given.
4615                     // We recover generic outer type later in visitTypeApply.
4616                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
4617                         owntype = types.erasure(owntype);
4618                     }
4619 
4620                     // (b) If the symbol's type is an inner class, then
4621                     // we have to interpret its outer type as a superclass
4622                     // of the site type. Example:
4623                     //
4624                     // class Tree<A> { class Visitor { ... } }
4625                     // class PointTree extends Tree<Point> { ... }
4626                     // ...PointTree.Visitor...
4627                     //
4628                     // Then the type of the last expression above is
4629                     // Tree<Point>.Visitor.
4630                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
4631                         Type normOuter = site;
4632                         if (normOuter.hasTag(CLASS)) {
4633                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
4634                         }
4635                         if (normOuter == null) // perhaps from an import
4636                             normOuter = types.erasure(ownOuter);
4637                         if (normOuter != ownOuter)
4638                             owntype = new ClassType(
4639                                 normOuter, List.nil(), owntype.tsym,
4640                                 owntype.getMetadata());
4641                     }
4642                 }
4643                 break;
4644             case VAR:
4645                 VarSymbol v = (VarSymbol)sym;
4646 
4647                 if (env.info.enclVar != null
4648                         && v.type.hasTag(NONE)) {
4649                     //self reference to implicitly typed variable declaration
4650                     log.error(TreeInfo.positionFor(v, env.enclClass), Errors.CantInferLocalVarType(v.name, Fragments.LocalSelfRef));
4651                     return v.type = types.createErrorType(v.type);
4652                 }
4653 
4654                 // Test (4): if symbol is an instance field of a raw type,
4655                 // which is being assigned to, issue an unchecked warning if
4656                 // its type changes under erasure.
4657                 if (KindSelector.ASG.subset(pkind()) &&
4658                     v.owner.kind == TYP &&
4659                     (v.flags() & STATIC) == 0 &&
4660                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {

4683                 break;
4684             case MTH: {
4685                 owntype = checkMethod(site, sym,
4686                         new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext, resultInfo.checkMode),
4687                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
4688                         resultInfo.pt.getTypeArguments());
4689                 break;
4690             }
4691             case PCK: case ERR:
4692                 owntype = sym.type;
4693                 break;
4694             default:
4695                 throw new AssertionError("unexpected kind: " + sym.kind +
4696                                          " in tree " + tree);
4697             }
4698 
4699             // Emit a `deprecation' warning if symbol is deprecated.
4700             // (for constructors (but not for constructor references), the error
4701             // was given when the constructor was resolved)
4702 
4703             if (sym.name != names.init || tree.hasTag(REFERENCE)) {
4704                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
4705                 chk.checkSunAPI(tree.pos(), sym);
4706                 chk.checkProfile(tree.pos(), sym);
4707                 chk.checkPreview(tree.pos(), env.info.scope.owner, sym);
4708             }
4709 
4710             // If symbol is a variable, check that its type and
4711             // kind are compatible with the prototype and protokind.
4712             return check(tree, owntype, sym.kind.toSelector(), resultInfo);
4713         }
4714 
4715         /** Check that variable is initialized and evaluate the variable's
4716          *  initializer, if not yet done. Also check that variable is not
4717          *  referenced before it is defined.
4718          *  @param tree    The tree making up the variable reference.
4719          *  @param env     The current environment.
4720          *  @param v       The variable's symbol.
4721          */
4722         private void checkInit(JCTree tree,
4723                                Env<AttrContext> env,

4937             //depending on the current check context
4938             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
4939             return types.createErrorType(site);
4940         } catch (Resolve.InapplicableMethodException ex) {
4941             final JCDiagnostic diag = ex.getDiagnostic();
4942             Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
4943                 @Override
4944                 protected Pair<Symbol, JCDiagnostic> errCandidate() {
4945                     return new Pair<>(sym, diag);
4946                 }
4947             };
4948             List<Type> argtypes2 = argtypes.map(
4949                     rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
4950             JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
4951                     env.tree, sym, site, sym.name, argtypes2, typeargtypes);
4952             log.report(errDiag);
4953             return types.createErrorType(site);
4954         }
4955     }
4956 































4957     public void visitLiteral(JCLiteral tree) {
4958         result = check(tree, litType(tree.typetag).constType(tree.value),
4959                 KindSelector.VAL, resultInfo);
4960     }
4961     //where
4962     /** Return the type of a literal with given type tag.
4963      */
4964     Type litType(TypeTag tag) {
4965         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
4966     }
4967 
4968     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
4969         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
4970     }
4971 
4972     public void visitTypeArray(JCArrayTypeTree tree) {
4973         Type etype = attribType(tree.elemtype, env);
4974         Type type = new ArrayType(etype, syms.arrayClass);
4975         result = check(tree, type, KindSelector.TYP, resultInfo);
4976     }

5003                 }
5004                 // Compute the proper generic outer
5005                 Type clazzOuter = clazztype.getEnclosingType();
5006                 if (clazzOuter.hasTag(CLASS)) {
5007                     Type site;
5008                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
5009                     if (clazz.hasTag(IDENT)) {
5010                         site = env.enclClass.sym.type;
5011                     } else if (clazz.hasTag(SELECT)) {
5012                         site = ((JCFieldAccess) clazz).selected.type;
5013                     } else throw new AssertionError(""+tree);
5014                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
5015                         if (site.hasTag(CLASS))
5016                             site = types.asOuterSuper(site, clazzOuter.tsym);
5017                         if (site == null)
5018                             site = types.erasure(clazzOuter);
5019                         clazzOuter = site;
5020                     }
5021                 }
5022                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
5023                                         clazztype.getMetadata());
5024             } else {
5025                 if (formals.length() != 0) {
5026                     log.error(tree.pos(),
5027                               Errors.WrongNumberTypeArgs(Integer.toString(formals.length())));
5028                 } else {
5029                     log.error(tree.pos(), Errors.TypeDoesntTakeParams(clazztype.tsym));
5030                 }
5031                 owntype = types.createErrorType(tree.type);
5032             }
5033         }
5034         result = check(tree, owntype, KindSelector.TYP, resultInfo);
5035     }
5036 
5037     public void visitTypeUnion(JCTypeUnion tree) {
5038         ListBuffer<Type> multicatchTypes = new ListBuffer<>();
5039         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
5040         for (JCExpression typeTree : tree.alternatives) {
5041             Type ctype = attribType(typeTree, env);
5042             ctype = chk.checkType(typeTree.pos(),
5043                           chk.checkClassType(typeTree.pos(), ctype),

5130         if (bounds.length() == 0) {
5131             return syms.objectType;
5132         } else if (bounds.length() == 1) {
5133             return bounds.head.type;
5134         } else {
5135             Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
5136             // ... the variable's bound is a class type flagged COMPOUND
5137             // (see comment for TypeVar.bound).
5138             // In this case, generate a class tree that represents the
5139             // bound class, ...
5140             JCExpression extending;
5141             List<JCExpression> implementing;
5142             if (!bounds.head.type.isInterface()) {
5143                 extending = bounds.head;
5144                 implementing = bounds.tail;
5145             } else {
5146                 extending = null;
5147                 implementing = bounds;
5148             }
5149             JCClassDecl cd = make.at(tree).ClassDef(
5150                 make.Modifiers(PUBLIC | ABSTRACT),
5151                 names.empty, List.nil(),
5152                 extending, implementing, List.nil());
5153 
5154             ClassSymbol c = (ClassSymbol)owntype.tsym;
5155             Assert.check((c.flags() & COMPOUND) != 0);
5156             cd.sym = c;
5157             c.sourcefile = env.toplevel.sourcefile;
5158 
5159             // ... and attribute the bound class
5160             c.flags_field |= UNATTRIBUTED;
5161             Env<AttrContext> cenv = enter.classEnv(cd, env);
5162             typeEnvs.put(c, cenv);
5163             attribClass(c);
5164             return owntype;
5165         }
5166     }
5167 
5168     public void visitWildcard(JCWildcard tree) {
5169         //- System.err.println("visitWildcard("+tree+");");//DEBUG
5170         Type type = (tree.kind.kind == BoundKind.UNBOUND)
5171             ? syms.objectType
5172             : attribType(tree.inner, env);
5173         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
5174                                               tree.kind.kind,
5175                                               syms.boundClass),
5176                 KindSelector.TYP, resultInfo);
5177     }
5178 
5179     public void visitAnnotation(JCAnnotation tree) {
5180         Assert.error("should be handled in annotate");
5181     }
5182 
5183     @Override
5184     public void visitModifiers(JCModifiers tree) {
5185         //error recovery only:
5186         Assert.check(resultInfo.pkind == KindSelector.ERR);
5187 
5188         attribAnnotationTypes(tree.annotations, env);
5189     }
5190 
5191     public void visitAnnotatedType(JCAnnotatedType tree) {
5192         attribAnnotationTypes(tree.annotations, env);
5193         Type underlyingType = attribType(tree.underlyingType, env);

5271 
5272         try {
5273             deferredLintHandler.flush(env.tree.pos());
5274             attrib.accept(env);
5275         } finally {
5276             log.useSource(prev);
5277             chk.setLint(prevLint);
5278         }
5279     }
5280 
5281     /** Main method: attribute class definition associated with given class symbol.
5282      *  reporting completion failures at the given position.
5283      *  @param pos The source position at which completion errors are to be
5284      *             reported.
5285      *  @param c   The class symbol whose definition will be attributed.
5286      */
5287     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
5288         try {
5289             annotate.flush();
5290             attribClass(c);





5291         } catch (CompletionFailure ex) {
5292             chk.completionError(pos, ex);
5293         }
5294     }
5295 
5296     /** Attribute class definition associated with given class symbol.
5297      *  @param c   The class symbol whose definition will be attributed.
5298      */
5299     void attribClass(ClassSymbol c) throws CompletionFailure {
5300         if (c.type.hasTag(ERROR)) return;
5301 
5302         // Check for cycles in the inheritance graph, which can arise from
5303         // ill-formed class files.
5304         chk.checkNonCyclic(null, c.type);
5305 
5306         Type st = types.supertype(c.type);
5307         if ((c.flags_field & Flags.COMPOUND) == 0 &&
5308             (c.flags_field & Flags.SUPER_OWNER_ATTRIBUTED) == 0) {
5309             // First, attribute superclass.
5310             if (st.hasTag(CLASS))

5391                                                   .filter(s -> s.tsym.isSealed())
5392                                                   .map(s -> (ClassSymbol) s.tsym)
5393                                                   .collect(List.collector());
5394 
5395             if (sealedSupers.isEmpty()) {
5396                 if ((c.flags_field & Flags.NON_SEALED) != 0) {
5397                     boolean hasErrorSuper = false;
5398 
5399                     hasErrorSuper |= types.directSupertypes(c.type)
5400                                           .stream()
5401                                           .anyMatch(s -> s.tsym.kind == Kind.ERR);
5402 
5403                     ClassType ct = (ClassType) c.type;
5404 
5405                     hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5406 
5407                     if (!hasErrorSuper) {
5408                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5409                     }
5410                 }
5411             } else {
5412                 if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5413                     log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5414                 }
5415 
5416                 if (!c.type.isCompound()) {
5417                     for (ClassSymbol supertypeSym : sealedSupers) {
5418                         if (!supertypeSym.permitted.contains(c.type.tsym)) {
5419                             log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5420                         }
5421                     }
5422                     if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5423                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5424                                 c.isInterface() ?
5425                                         Errors.NonSealedOrSealedExpected :
5426                                         Errors.NonSealedSealedOrFinalExpected);
5427                     }
5428                 }
5429             }
5430 
5431             // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,

5446 
5447             try {
5448                 deferredLintHandler.flush(env.tree);
5449                 env.info.returnResult = null;
5450                 // java.lang.Enum may not be subclassed by a non-enum
5451                 if (st.tsym == syms.enumSym &&
5452                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5453                     log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5454 
5455                 // Enums may not be extended by source-level classes
5456                 if (st.tsym != null &&
5457                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5458                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5459                     log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5460                 }
5461 
5462                 if (rs.isSerializable(c.type)) {
5463                     env.info.isSerializable = true;
5464                 }
5465 





5466                 attribClassBody(env, c);
5467 
5468                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5469                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5470                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5471                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5472             } finally {
5473                 env.info.returnResult = prevReturnRes;
5474                 log.useSource(prev);
5475                 chk.setLint(prevLint);
5476             }
5477 
5478         }
5479     }
5480 
5481     public void visitImport(JCImport tree) {
5482         // nothing to do
5483     }
5484 
5485     public void visitModuleDef(JCModuleDecl tree) {

  28 import java.util.*;
  29 import java.util.function.BiConsumer;
  30 import java.util.function.Consumer;
  31 import java.util.stream.Stream;
  32 
  33 import javax.lang.model.element.ElementKind;
  34 import javax.tools.JavaFileObject;
  35 
  36 import com.sun.source.tree.CaseTree;
  37 import com.sun.source.tree.IdentifierTree;
  38 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
  39 import com.sun.source.tree.MemberSelectTree;
  40 import com.sun.source.tree.TreeVisitor;
  41 import com.sun.source.util.SimpleTreeVisitor;
  42 import com.sun.tools.javac.code.*;
  43 import com.sun.tools.javac.code.Lint.LintCategory;
  44 import com.sun.tools.javac.code.Scope.WriteableScope;
  45 import com.sun.tools.javac.code.Source.Feature;
  46 import com.sun.tools.javac.code.Symbol.*;
  47 import com.sun.tools.javac.code.Type.*;
  48 import com.sun.tools.javac.code.Type.ClassType.Flavor;
  49 import com.sun.tools.javac.code.TypeMetadata.Annotations;
  50 import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError;
  51 import com.sun.tools.javac.comp.ArgumentAttr.LocalCacheContext;
  52 import com.sun.tools.javac.comp.Check.CheckContext;
  53 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
  54 import com.sun.tools.javac.comp.MatchBindingsComputer.MatchBindings;
  55 import com.sun.tools.javac.jvm.*;
  56 
  57 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond;
  58 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArg;
  59 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArgs;
  60 
  61 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  62 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  63 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
  64 import com.sun.tools.javac.tree.*;
  65 import com.sun.tools.javac.tree.JCTree.*;
  66 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
  67 import com.sun.tools.javac.util.*;
  68 import com.sun.tools.javac.util.DefinedBy.Api;

 150         infer = Infer.instance(context);
 151         analyzer = Analyzer.instance(context);
 152         deferredAttr = DeferredAttr.instance(context);
 153         cfolder = ConstFold.instance(context);
 154         target = Target.instance(context);
 155         types = Types.instance(context);
 156         preview = Preview.instance(context);
 157         diags = JCDiagnostic.Factory.instance(context);
 158         annotate = Annotate.instance(context);
 159         typeAnnotations = TypeAnnotations.instance(context);
 160         deferredLintHandler = DeferredLintHandler.instance(context);
 161         typeEnvs = TypeEnvs.instance(context);
 162         dependencies = Dependencies.instance(context);
 163         argumentAttr = ArgumentAttr.instance(context);
 164         matchBindingsComputer = MatchBindingsComputer.instance(context);
 165         attrRecover = AttrRecover.instance(context);
 166 
 167         Options options = Options.instance(context);
 168 
 169         Source source = Source.instance(context);
 170         allowPrimitiveClasses = Feature.PRIMITIVE_CLASSES.allowedInSource(source) && options.isSet("enablePrimitiveClasses");
 171         allowReifiableTypesInInstanceof = Feature.REIFIABLE_TYPES_INSTANCEOF.allowedInSource(source);
 172         allowRecords = Feature.RECORDS.allowedInSource(source);
 173         allowPatternSwitch = (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH)) &&
 174                              Feature.PATTERN_SWITCH.allowedInSource(source);
 175         allowUnconditionalPatternsInstanceOf = (preview.isEnabled() || !preview.isPreview(Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF)) &&
 176                                      Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.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: allow primitive classes ?
 190      */
 191     boolean allowPrimitiveClasses;
 192 
 193     /** Switch: reifiable types in instanceof enabled?
 194      */
 195     boolean allowReifiableTypesInInstanceof;
 196 
 197     /** Are records allowed
 198      */
 199     private final boolean allowRecords;
 200 
 201     /** Are patterns in switch allowed
 202      */
 203     private final boolean allowPatternSwitch;
 204 
 205     /** Are unconditional patterns in instanceof allowed
 206      */
 207     private final boolean allowUnconditionalPatternsInstanceOf;
 208 
 209     /**
 210      * Switch: warn about use of variable before declaration?
 211      * RFE: 6425594
 212      */

 261             found;
 262         }
 263         if (resultInfo.checkMode.updateTreeType()) {
 264             tree.type = owntype;
 265         }
 266         return owntype;
 267     }
 268 
 269     /** Is given blank final variable assignable, i.e. in a scope where it
 270      *  may be assigned to even though it is final?
 271      *  @param v      The blank final variable.
 272      *  @param env    The current environment.
 273      */
 274     boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
 275         Symbol owner = env.info.scope.owner;
 276            // owner refers to the innermost variable, method or
 277            // initializer block declaration at this point.
 278         boolean isAssignable =
 279             v.owner == owner
 280             ||
 281             ((names.isInitOrVNew(owner.name) ||    // i.e. we are in a constructor
 282               owner.kind == VAR ||           // i.e. we are in a variable initializer
 283               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
 284              &&
 285              v.owner == owner.owner
 286              &&
 287              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
 288         boolean insideCompactConstructor = env.enclMethod != null && TreeInfo.isCompactConstructor(env.enclMethod);
 289         return isAssignable & !insideCompactConstructor;
 290     }
 291 
 292     /** Check that variable can be assigned to.
 293      *  @param pos    The current source code position.
 294      *  @param v      The assigned variable
 295      *  @param base   If the variable is referred to in a Select, the part
 296      *                to the left of the `.', null otherwise.
 297      *  @param env    The current environment.
 298      */
 299     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
 300         if (v.name == names._this) {
 301             log.error(pos, Errors.CantAssignValToThis);

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

1060                         log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.MethodMustBePublic));
1061                     }
1062                     if (!types.isSameType(tree.sym.type.getReturnType(), recordComponent.get().type)) {
1063                         log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym,
1064                                 Fragments.AccessorReturnTypeDoesntMatch(tree.sym, recordComponent.get())));
1065                     }
1066                     if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1067                         log.error(tree,
1068                                 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodCantThrowException));
1069                     }
1070                     if (!tree.typarams.isEmpty()) {
1071                         log.error(tree,
1072                                 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeGeneric));
1073                     }
1074                     if (tree.sym.isStatic()) {
1075                         log.error(tree,
1076                                 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeStatic));
1077                     }
1078                 }
1079 
1080                 if (names.isInitOrVNew(tree.name)) {
1081                     // if this a constructor other than the canonical one
1082                     if ((tree.sym.flags_field & RECORD) == 0) {
1083                         JCMethodInvocation app = TreeInfo.firstConstructorCall(tree);
1084                         if (app == null ||
1085                                 TreeInfo.name(app.meth) != names._this ||
1086                                 !checkFirstConstructorStat(app, tree, false)) {
1087                             log.error(tree, Errors.FirstStatementMustBeCallToAnotherConstructor(env.enclClass.sym));
1088                         }
1089                     } else {
1090                         // but if it is the canonical:
1091 
1092                         /* if user generated, then it shouldn't:
1093                          *     - have an accessibility stricter than that of the record type
1094                          *     - explicitly invoke any other constructor
1095                          */
1096                         if ((tree.sym.flags_field & GENERATEDCONSTR) == 0) {
1097                             if (Check.protection(m.flags()) > Check.protection(env.enclClass.sym.flags())) {
1098                                 log.error(tree,
1099                                         (env.enclClass.sym.flags() & AccessFlags) == 0 ?
1100                                             Errors.InvalidCanonicalConstructorInRecord(

1175                 if (tree.defaultValue != null) {
1176                     if ((owner.flags() & ANNOTATION) == 0)
1177                         log.error(tree.pos(),
1178                                   Errors.DefaultAllowedInIntfAnnotationMember);
1179                 }
1180                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1181                     log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract);
1182             } else {
1183                 if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1184                     if ((owner.flags() & INTERFACE) != 0) {
1185                         log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1186                     } else {
1187                         log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1188                     }
1189                 } else if ((tree.mods.flags & NATIVE) != 0) {
1190                     log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1191                 }
1192                 // Add an implicit super() call unless an explicit call to
1193                 // super(...) or this(...) is given
1194                 // or we are compiling class java.lang.Object.
1195                 if (names.isInitOrVNew(tree.name) && owner.type != syms.objectType) {
1196                     JCBlock body = tree.body;
1197                     if (body.stats.isEmpty() ||
1198                             TreeInfo.getConstructorInvocationName(body.stats, names, true) == names.empty) {
1199                         JCStatement supCall = make.at(body.pos).Exec(make.Apply(List.nil(),
1200                                 make.Ident(names._super), make.Idents(List.nil())));
1201                         body.stats = body.stats.prepend(supCall);
1202                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1203                             (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1204                             TreeInfo.isSuperCall(body.stats.head)) {
1205                         // enum constructors are not allowed to call super
1206                         // directly, so make sure there aren't any super calls
1207                         // in enum constructors, except in the compiler
1208                         // generated one.
1209                         log.error(tree.body.stats.head.pos(),
1210                                   Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1211                     } else if ((env.enclClass.sym.flags() & VALUE_CLASS) != 0 &&
1212                         (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1213                         TreeInfo.isSuperCall(body.stats.head)) {
1214                         // value constructors are not allowed to call super directly,
1215                         // but tolerate compiler generated ones, these are ignored during code generation
1216                         log.error(tree.body.stats.head.pos(), Errors.CallToSuperNotAllowedInValueCtor);
1217                     }
1218                     if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1219                         List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1220                         List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1221                         if (!initParamNames.equals(recordComponentNames)) {
1222                             log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1223                                     Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1224                         }
1225                         if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1226                             log.error(tree,
1227                                     Errors.InvalidCanonicalConstructorInRecord(
1228                                             TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical,
1229                                             env.enclClass.sym.name,
1230                                             Fragments.ThrowsClauseNotAllowedForCanonicalConstructor(
1231                                                     TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical)));
1232                         }
1233                     }
1234                 }
1235 
1236                 // Attribute all type annotations in the body

1284                 annotate.queueScanTreeAndTypeAnnotate(tree.init, env, tree.sym, tree.pos());
1285                 annotate.flush();
1286             }
1287         }
1288 
1289         VarSymbol v = tree.sym;
1290         Lint lint = env.info.lint.augment(v);
1291         Lint prevLint = chk.setLint(lint);
1292 
1293         // Check that the variable's declared type is well-formed.
1294         boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
1295                 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
1296                 (tree.sym.flags() & PARAMETER) != 0;
1297         chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1298 
1299         try {
1300             v.getConstValue(); // ensure compile-time constant initializer is evaluated
1301             deferredLintHandler.flush(tree.pos());
1302             chk.checkDeprecatedAnnotation(tree.pos(), v);
1303 
1304             /* Don't want constant propagation/folding for instance fields of primitive classes,
1305                as these can undergo updates via copy on write.
1306             */
1307             if (tree.init != null) {
1308                 if ((v.flags_field & FINAL) == 0 || ((v.flags_field & STATIC) == 0 && v.owner.isValueClass()) ||
1309                     !memberEnter.needsLazyConstValue(tree.init)) {
1310                     // Not a compile-time constant
1311                     // Attribute initializer in a new environment
1312                     // with the declared variable as owner.
1313                     // Check that initializer conforms to variable's declared type.
1314                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1315                     initEnv.info.lint = lint;
1316                     // In order to catch self-references, we set the variable's
1317                     // declaration position to maximal possible value, effectively
1318                     // marking the variable as undefined.
1319                     initEnv.info.enclVar = v;
1320                     attribExpr(tree.init, initEnv, v.type);
1321                     if (tree.isImplicitlyTyped()) {
1322                         //fixup local variable type
1323                         v.type = chk.checkLocalVarType(tree, tree.init.type, tree.name);
1324                     }
1325                 }
1326                 if (tree.isImplicitlyTyped()) {
1327                     setSyntheticVariableType(tree, v.type);
1328                 }
1329             }
1330             result = tree.type = v.type;
1331             if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1332                 if (isNonArgsMethodInObject(v.name)) {
1333                     log.error(tree, Errors.IllegalRecordComponentName(v));
1334                 }
1335             }
1336         }
1337         finally {
1338             chk.setLint(prevLint);
1339         }
1340     }
1341 
1342     private boolean isNonArgsMethodInObject(Name name) {
1343         for (Symbol s : syms.objectType.tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) {
1344             if (s.type.getParameterTypes().isEmpty()) {
1345                 return true;
1346             }
1347         }
1348         // isValueObject is not included in Object yet so we need a work around
1349         return name == names.isValueObject;
1350     }
1351 
1352     Fragment canInferLocalVarType(JCVariableDecl tree) {
1353         LocalInitScanner lis = new LocalInitScanner();
1354         lis.scan(tree.init);
1355         return lis.badInferenceMsg;
1356     }
1357 
1358     static class LocalInitScanner extends TreeScanner {
1359         Fragment badInferenceMsg = null;
1360         boolean needsTarget = true;
1361 
1362         @Override
1363         public void visitNewArray(JCNewArray tree) {
1364             if (tree.elemtype == null && needsTarget) {
1365                 badInferenceMsg = Fragments.LocalArrayMissingTarget;
1366             }
1367         }
1368 
1369         @Override

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

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

1947                     chk.checkType(c.param.vartype.pos(),
1948                                   chk.checkClassType(c.param.vartype.pos(), ctype),
1949                                   syms.throwableType);
1950                     attribStat(c.body, catchEnv);
1951                 } finally {
1952                     catchEnv.info.scope.leave();
1953                 }
1954             }
1955 
1956             // Attribute finalizer
1957             if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1958             result = null;
1959         }
1960         finally {
1961             localEnv.info.scope.leave();
1962         }
1963     }
1964 
1965     void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
1966         if (!resource.isErroneous() &&
1967             types.asSuper(resource.referenceProjectionOrSelf(), syms.autoCloseableType.tsym) != null &&
1968             !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
1969             Symbol close = syms.noSymbol;
1970             Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
1971             try {
1972                 close = rs.resolveQualifiedMethod(pos,
1973                         env,
1974                         types.skipTypeVars(resource, false),
1975                         names.close,
1976                         List.nil(),
1977                         List.nil());
1978             }
1979             finally {
1980                 log.popDiagnosticHandler(discardHandler);
1981             }
1982             if (close.kind == MTH &&
1983                     close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
1984                     chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
1985                     env.info.lint.isEnabled(LintCategory.TRY)) {
1986                 log.warning(LintCategory.TRY, pos, Warnings.TryResourceThrowsInterruptedExc(resource));
1987             }

2136             if (unboxedTypes.stream().allMatch(t -> t.isPrimitive())) {
2137                 // If one arm has an integer subrange type (i.e., byte,
2138                 // short, or char), and the other is an integer constant
2139                 // that fits into the subrange, return the subrange type.
2140                 for (Type type : unboxedTypes) {
2141                     if (!type.getTag().isStrictSubRangeOf(INT)) {
2142                         continue;
2143                     }
2144                     if (unboxedTypes.stream().filter(t -> t != type).allMatch(t -> t.hasTag(INT) && types.isAssignable(t, type)))
2145                         return type.baseType();
2146                 }
2147 
2148                 for (TypeTag tag : primitiveTags) {
2149                     Type candidate = syms.typeOfTag[tag.ordinal()];
2150                     if (unboxedTypes.stream().allMatch(t -> types.isSubtype(t, candidate))) {
2151                         return candidate;
2152                     }
2153                 }
2154             }
2155 
2156             // Those were all the cases that could result in a primitive. See if primitive boxing and primitive
2157             // value conversions bring about a convergence.
2158             condTypes = condTypes.stream()
2159                                  .map(t -> t.isPrimitive() ? types.boxedClass(t).type
2160                                          : t.isReferenceProjection() ? t.valueProjection() : t)
2161                                  .collect(List.collector());
2162 
2163             for (Type type : condTypes) {
2164                 if (condTypes.stream().filter(t -> t != type).allMatch(t -> types.isAssignable(t, type)))
2165                     return type.baseType();
2166             }
2167 
2168             Iterator<DiagnosticPosition> posIt = positions.iterator();
2169 
2170             condTypes = condTypes.stream()
2171                                  .map(t -> chk.checkNonVoid(posIt.next(), allowPrimitiveClasses && t.isPrimitiveClass() ? t.referenceProjection() : t))
2172                                  .collect(List.collector());
2173 
2174             // both are known to be reference types (or projections).  The result is
2175             // lub(thentype,elsetype). This cannot fail, as it will
2176             // always be possible to infer "Object" if nothing better.
2177             return types.lub(condTypes.stream()
2178                         .map(t -> t.baseType())
2179                         .filter(t -> !t.hasTag(BOT))
2180                         .collect(List.collector()));
2181         }
2182 
2183     static final TypeTag[] primitiveTags = new TypeTag[]{
2184         BYTE,
2185         CHAR,
2186         SHORT,
2187         INT,
2188         LONG,
2189         FLOAT,
2190         DOUBLE,
2191         BOOLEAN,
2192     };
2193 
2194     Env<AttrContext> bindingEnv(Env<AttrContext> env, List<BindingSymbol> bindings) {

2593                     : env.enclClass.sym.type;
2594             Symbol msym = TreeInfo.symbol(tree.meth);
2595             restype = adjustMethodReturnType(msym, qualifier, methName, argtypes, restype);
2596 
2597             chk.checkRefTypes(tree.typeargs, typeargtypes);
2598 
2599             // Check that value of resulting type is admissible in the
2600             // current context.  Also, capture the return type
2601             Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true);
2602             result = check(tree, capturedRes, KindSelector.VAL, resultInfo);
2603         }
2604         chk.validate(tree.typeargs, localEnv);
2605     }
2606     //where
2607         Type adjustMethodReturnType(Symbol msym, Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
2608             if (msym != null &&
2609                     (msym.owner == syms.objectType.tsym || msym.owner.isInterface()) &&
2610                     methodName == names.getClass &&
2611                     argtypes.isEmpty()) {
2612                 // as a special case, x.getClass() has type Class<? extends |X|>
2613                 // Special treatment for primitive classes: Given an expression v of type V where
2614                 // V is a primitive class, v.getClass() is typed to be Class<? extends |V.ref|>
2615                 Type wcb = types.erasure(allowPrimitiveClasses && qualifierType.isPrimitiveClass() ?
2616                                          qualifierType.referenceProjection() : qualifierType.baseType());
2617                 return new ClassType(restype.getEnclosingType(),
2618                         List.of(new WildcardType(wcb,
2619                                 BoundKind.EXTENDS,
2620                                 syms.boundClass)),
2621                         restype.tsym,
2622                         restype.getMetadata(),
2623                         restype.getFlavor());
2624             } else if (msym != null &&
2625                     msym.owner == syms.arrayClass &&
2626                     methodName == names.clone &&
2627                     types.isArray(qualifierType)) {
2628                 // as a special case, array.clone() has a result that is
2629                 // the same as static type of the array being cloned
2630                 return qualifierType;
2631             } else {
2632                 return restype;
2633             }
2634         }
2635 
2636         /** Check that given application node appears as first statement
2637          *  in a constructor call.
2638          *  @param tree          The application node
2639          *  @param enclMethod    The enclosing method of the application.
2640          *  @param error         Should an error be issued?
2641          */
2642         boolean checkFirstConstructorStat(JCMethodInvocation tree, JCMethodDecl enclMethod, boolean error) {
2643             if (enclMethod != null && names.isInitOrVNew(enclMethod.name)) {
2644                 JCBlock body = enclMethod.body;
2645                 if (body.stats.head.hasTag(EXEC) &&
2646                     ((JCExpressionStatement) body.stats.head).expr == tree)
2647                     return true;
2648             }
2649             if (error) {
2650                 log.error(tree.pos(),
2651                         Errors.CallMustBeFirstStmtInCtor(TreeInfo.name(tree.meth)));
2652             }
2653             return false;
2654         }
2655 
2656         /** Obtain a method type with given argument types.
2657          */
2658         Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
2659             MethodType mt = new MethodType(argtypes, restype, List.nil(), syms.methodClass);
2660             return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
2661         }
2662 
2663     public void visitNewClass(final JCNewClass tree) {

2772         }
2773 
2774         // Attribute constructor arguments.
2775         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2776         final KindSelector pkind =
2777             attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
2778         List<Type> argtypes = argtypesBuf.toList();
2779         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
2780 
2781         if (clazztype.hasTag(CLASS) || clazztype.hasTag(ERROR)) {
2782             // Enums may not be instantiated except implicitly
2783             if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 &&
2784                 (!env.tree.hasTag(VARDEF) ||
2785                  (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 ||
2786                  ((JCVariableDecl) env.tree).init != tree))
2787                 log.error(tree.pos(), Errors.EnumCantBeInstantiated);
2788 
2789             boolean isSpeculativeDiamondInferenceRound = TreeInfo.isDiamond(tree) &&
2790                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2791             boolean skipNonDiamondPath = false;
2792             // Check that it is an instantiation of a class and not a projection type
2793             if (allowPrimitiveClasses) {
2794                 if (clazz.hasTag(SELECT)) {
2795                     JCFieldAccess fieldAccess = (JCFieldAccess) clazz;
2796                     if (fieldAccess.selected.type.isPrimitiveClass() &&
2797                             (fieldAccess.name == names.ref || fieldAccess.name == names.val)) {
2798                         log.error(tree.pos(), Errors.ProjectionCantBeInstantiated);
2799                     }
2800                 }
2801             }
2802             // Check that class is not abstract
2803             if (cdef == null && !isSpeculativeDiamondInferenceRound && // class body may be nulled out in speculative tree copy
2804                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
2805                 log.error(tree.pos(),
2806                           Errors.AbstractCantBeInstantiated(clazztype.tsym));
2807                 skipNonDiamondPath = true;
2808             } else if (cdef != null && clazztype.tsym.isInterface()) {
2809                 // Check that no constructor arguments are given to
2810                 // anonymous classes implementing an interface
2811                 if (!argtypes.isEmpty())
2812                     log.error(tree.args.head.pos(), Errors.AnonClassImplIntfNoArgs);
2813 
2814                 if (!typeargtypes.isEmpty())
2815                     log.error(tree.typeargs.head.pos(), Errors.AnonClassImplIntfNoTypeargs);
2816 
2817                 // Error recovery: pretend no arguments were supplied.
2818                 argtypes = List.nil();
2819                 typeargtypes = List.nil();
2820                 skipNonDiamondPath = true;
2821             }
2822             if (TreeInfo.isDiamond(tree)) {
2823                 ClassType site = new ClassType(clazztype.getEnclosingType(),
2824                             clazztype.tsym.type.getTypeArguments(),
2825                                                clazztype.tsym,
2826                                                clazztype.getMetadata(),
2827                                                clazztype.getFlavor());
2828 
2829                 Env<AttrContext> diamondEnv = localEnv.dup(tree);
2830                 diamondEnv.info.selectSuper = cdef != null || tree.classDeclRemoved();
2831                 diamondEnv.info.pendingResolutionPhase = null;
2832 
2833                 //if the type of the instance creation expression is a class type
2834                 //apply method resolution inference (JLS 15.12.2.7). The return type
2835                 //of the resolved constructor will be a partially instantiated type
2836                 Symbol constructor = rs.resolveDiamond(tree.pos(),
2837                             diamondEnv,
2838                             site,
2839                             argtypes,
2840                             typeargtypes);
2841                 tree.constructor = constructor.baseSymbol();
2842 
2843                 final TypeSymbol csym = clazztype.tsym;
2844                 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes),
2845                         diamondContext(tree, csym, resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
2846                 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
2847                 constructorType = checkId(tree, site,

2961                                 this.resultInfo = prevResult;
2962                             }
2963                         });
2964             } else {
2965                 if (isDiamond && clazztype.hasTag(CLASS)) {
2966                     List<Type> invalidDiamondArgs = chk.checkDiamondDenotable((ClassType)clazztype);
2967                     if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
2968                         // One or more types inferred in the previous steps is non-denotable.
2969                         Fragment fragment = Diamond(clazztype.tsym);
2970                         log.error(tree.clazz.pos(),
2971                                 Errors.CantApplyDiamond1(
2972                                         fragment,
2973                                         invalidDiamondArgs.size() > 1 ?
2974                                                 DiamondInvalidArgs(invalidDiamondArgs, fragment) :
2975                                                 DiamondInvalidArg(invalidDiamondArgs, fragment)));
2976                     }
2977                     // For <>(){}, inferred types must also be accessible.
2978                     for (Type t : clazztype.getTypeArguments()) {
2979                         rs.checkAccessibleType(env, t);
2980                     }
2981                     if (allowPrimitiveClasses) {
2982                         chk.checkParameterizationByPrimitiveClass(tree, clazztype);
2983                     }
2984                 }
2985 
2986                 // If we already errored, be careful to avoid a further avalanche. ErrorType answers
2987                 // false for isInterface call even when the original type is an interface.
2988                 boolean implementing = clazztype.tsym.isInterface() ||
2989                         clazztype.isErroneous() && !clazztype.getOriginalType().hasTag(NONE) &&
2990                         clazztype.getOriginalType().tsym.isInterface();
2991 
2992                 if (implementing) {
2993                     cdef.implementing = List.of(clazz);
2994                 } else {
2995                     cdef.extending = clazz;
2996                 }
2997 
2998                 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2999                     rs.isSerializable(clazztype)) {
3000                     localEnv.info.isSerializable = true;
3001                 }
3002 
3003                 attribStat(cdef, localEnv);

3036             result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK));
3037             chk.validate(tree.typeargs, localEnv);
3038         }
3039 
3040         CheckContext diamondContext(JCNewClass clazz, TypeSymbol tsym, CheckContext checkContext) {
3041             return new Check.NestedCheckContext(checkContext) {
3042                 @Override
3043                 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
3044                     enclosingContext.report(clazz.clazz,
3045                             diags.fragment(Fragments.CantApplyDiamond1(Fragments.Diamond(tsym), details)));
3046                 }
3047             };
3048         }
3049 
3050     /** Make an attributed null check tree.
3051      */
3052     public JCExpression makeNullCheck(JCExpression arg) {
3053         // optimization: new Outer() can never be null; skip null check
3054         if (arg.getTag() == NEWCLASS)
3055             return arg;
3056         // Likewise arg can't be null if it is a primitive class instance.
3057         if (allowPrimitiveClasses && arg.type.isPrimitiveClass())
3058             return arg;
3059         // optimization: X.this is never null; skip null check
3060         Name name = TreeInfo.name(arg);
3061         if (name == names._this || name == names._super) return arg;
3062 
3063         JCTree.Tag optag = NULLCHK;
3064         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
3065         tree.operator = operators.resolveUnary(arg, optag, arg.type);
3066         tree.type = arg.type;
3067         return tree;
3068     }
3069 
3070     public void visitNewArray(JCNewArray tree) {
3071         Type owntype = types.createErrorType(tree.type);
3072         Env<AttrContext> localEnv = env.dup(tree);
3073         Type elemtype;
3074         if (tree.elemtype != null) {
3075             elemtype = attribType(tree.elemtype, localEnv);
3076             chk.validate(tree.elemtype, localEnv);
3077             owntype = elemtype;
3078             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {

3528          *
3529          * The owner of this environment is a method symbol. If the current owner
3530          * is not a method, for example if the lambda is used to initialize
3531          * a field, then if the field is:
3532          *
3533          * - an instance field, we use the first constructor.
3534          * - a static field, we create a fake clinit method.
3535          */
3536         public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
3537             Env<AttrContext> lambdaEnv;
3538             Symbol owner = env.info.scope.owner;
3539             if (owner.kind == VAR && owner.owner.kind == TYP) {
3540                 //field initializer
3541                 ClassSymbol enclClass = owner.enclClass();
3542                 Symbol newScopeOwner = env.info.scope.owner;
3543                 /* if the field isn't static, then we can get the first constructor
3544                  * and use it as the owner of the environment. This is what
3545                  * LTM code is doing to look for type annotations so we are fine.
3546                  */
3547                 if ((owner.flags() & STATIC) == 0) {
3548                     Name constructorName = owner.isConcreteValueClass() ? names.vnew : names.init;
3549                     for (Symbol s : enclClass.members_field.getSymbolsByName(constructorName)) {
3550                         newScopeOwner = s;
3551                         break;
3552                     }
3553                 } else {
3554                     /* if the field is static then we need to create a fake clinit
3555                      * method, this method can later be reused by LTM.
3556                      */
3557                     MethodSymbol clinit = clinits.get(enclClass);
3558                     if (clinit == null) {
3559                         Type clinitType = new MethodType(List.nil(),
3560                                 syms.voidType, List.nil(), syms.methodClass);
3561                         clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE,
3562                                 names.clinit, clinitType, enclClass);
3563                         clinit.params = List.nil();
3564                         clinits.put(enclClass, clinit);
3565                     }
3566                     newScopeOwner = clinit;
3567                 }
3568                 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(newScopeOwner)));
3569             } else {

3592 
3593             if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3594                 exprType = chk.checkConstructorRefType(that.expr, exprType);
3595                 if (!exprType.isErroneous() &&
3596                     exprType.isRaw() &&
3597                     that.typeargs != null) {
3598                     log.error(that.expr.pos(),
3599                               Errors.InvalidMref(Kinds.kindName(that.getMode()),
3600                                                  Fragments.MrefInferAndExplicitParams));
3601                     exprType = types.createErrorType(exprType);
3602                 }
3603             }
3604 
3605             if (exprType.isErroneous()) {
3606                 //if the qualifier expression contains problems,
3607                 //give up attribution of method reference
3608                 result = that.type = exprType;
3609                 return;
3610             }
3611 
3612             Symbol lhsSym = TreeInfo.symbol(that.expr);
3613             if (TreeInfo.isStaticSelector(that.expr, names)) {
3614                 // TODO - a bit hacky but...
3615                 if (lhsSym != null && lhsSym.isConcreteValueClass() && that.name == names.init) {
3616                     that.name = names.vnew;
3617                 }
3618                 //if the qualifier is a type, validate it; raw warning check is
3619                 //omitted as we don't know at this stage as to whether this is a
3620                 //raw selector (because of inference)
3621                 chk.validate(that.expr, env, false);
3622             } else {

3623                 localEnv.info.selectSuper = lhsSym != null && lhsSym.name == names._super;
3624             }
3625             //attrib type-arguments
3626             List<Type> typeargtypes = List.nil();
3627             if (that.typeargs != null) {
3628                 typeargtypes = attribTypes(that.typeargs, localEnv);
3629             }
3630 
3631             boolean isTargetSerializable =
3632                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3633                     rs.isSerializable(pt());
3634             TargetInfo targetInfo = getTargetInfo(that, resultInfo, null);
3635             Type currentTarget = targetInfo.target;
3636             Type desc = targetInfo.descriptor;
3637 
3638             setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
3639             List<Type> argtypes = desc.getParameterTypes();
3640             Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
3641 
3642             if (resultInfo.checkContext.inferenceContext().free(argtypes)) {

3686                         targetError ?
3687                             Fragments.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag) :
3688                             Errors.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag));
3689 
3690                 if (targetError && currentTarget == Type.recoveryType) {
3691                     //a target error doesn't make sense during recovery stage
3692                     //as we don't know what actual parameter types are
3693                     result = that.type = currentTarget;
3694                     return;
3695                 } else {
3696                     if (targetError) {
3697                         resultInfo.checkContext.report(that, diag);
3698                     } else {
3699                         log.report(diag);
3700                     }
3701                     result = that.type = types.createErrorType(currentTarget);
3702                     return;
3703                 }
3704             }
3705 
3706             that.sym = refSym.isInitOrVNew() ? refSym.baseSymbol() : refSym;
3707             that.kind = lookupHelper.referenceKind(that.sym);
3708             that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
3709 
3710             if (desc.getReturnType() == Type.recoveryType) {
3711                 // stop here
3712                 result = that.type = currentTarget;
3713                 return;
3714             }
3715 
3716             if (!env.info.attributionMode.isSpeculative && that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3717                 Type enclosingType = exprType.getEnclosingType();
3718                 if (enclosingType != null && enclosingType.hasTag(CLASS)) {
3719                     // Check for the existence of an appropriate outer instance
3720                     rs.resolveImplicitThis(that.pos(), env, exprType);
3721                 }
3722             }
3723 
3724             if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
3725 
3726                 if (that.getMode() == ReferenceMode.INVOKE &&

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

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

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

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

4750                 break;
4751             case MTH: {
4752                 owntype = checkMethod(site, sym,
4753                         new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext, resultInfo.checkMode),
4754                         env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
4755                         resultInfo.pt.getTypeArguments());
4756                 break;
4757             }
4758             case PCK: case ERR:
4759                 owntype = sym.type;
4760                 break;
4761             default:
4762                 throw new AssertionError("unexpected kind: " + sym.kind +
4763                                          " in tree " + tree);
4764             }
4765 
4766             // Emit a `deprecation' warning if symbol is deprecated.
4767             // (for constructors (but not for constructor references), the error
4768             // was given when the constructor was resolved)
4769 
4770             if (!names.isInitOrVNew(sym.name) || tree.hasTag(REFERENCE)) {
4771                 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
4772                 chk.checkSunAPI(tree.pos(), sym);
4773                 chk.checkProfile(tree.pos(), sym);
4774                 chk.checkPreview(tree.pos(), env.info.scope.owner, sym);
4775             }
4776 
4777             // If symbol is a variable, check that its type and
4778             // kind are compatible with the prototype and protokind.
4779             return check(tree, owntype, sym.kind.toSelector(), resultInfo);
4780         }
4781 
4782         /** Check that variable is initialized and evaluate the variable's
4783          *  initializer, if not yet done. Also check that variable is not
4784          *  referenced before it is defined.
4785          *  @param tree    The tree making up the variable reference.
4786          *  @param env     The current environment.
4787          *  @param v       The variable's symbol.
4788          */
4789         private void checkInit(JCTree tree,
4790                                Env<AttrContext> env,

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

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

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

5369 
5370         try {
5371             deferredLintHandler.flush(env.tree.pos());
5372             attrib.accept(env);
5373         } finally {
5374             log.useSource(prev);
5375             chk.setLint(prevLint);
5376         }
5377     }
5378 
5379     /** Main method: attribute class definition associated with given class symbol.
5380      *  reporting completion failures at the given position.
5381      *  @param pos The source position at which completion errors are to be
5382      *             reported.
5383      *  @param c   The class symbol whose definition will be attributed.
5384      */
5385     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
5386         try {
5387             annotate.flush();
5388             attribClass(c);
5389             if (allowPrimitiveClasses && c.type.isPrimitiveClass()) {
5390                 final Env<AttrContext> env = typeEnvs.get(c);
5391                 if (env != null && env.tree != null && env.tree.hasTag(CLASSDEF))
5392                     chk.checkNonCyclicMembership((JCClassDecl)env.tree);
5393             }
5394         } catch (CompletionFailure ex) {
5395             chk.completionError(pos, ex);
5396         }
5397     }
5398 
5399     /** Attribute class definition associated with given class symbol.
5400      *  @param c   The class symbol whose definition will be attributed.
5401      */
5402     void attribClass(ClassSymbol c) throws CompletionFailure {
5403         if (c.type.hasTag(ERROR)) return;
5404 
5405         // Check for cycles in the inheritance graph, which can arise from
5406         // ill-formed class files.
5407         chk.checkNonCyclic(null, c.type);
5408 
5409         Type st = types.supertype(c.type);
5410         if ((c.flags_field & Flags.COMPOUND) == 0 &&
5411             (c.flags_field & Flags.SUPER_OWNER_ATTRIBUTED) == 0) {
5412             // First, attribute superclass.
5413             if (st.hasTag(CLASS))

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

5549 
5550             try {
5551                 deferredLintHandler.flush(env.tree);
5552                 env.info.returnResult = null;
5553                 // java.lang.Enum may not be subclassed by a non-enum
5554                 if (st.tsym == syms.enumSym &&
5555                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5556                     log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5557 
5558                 // Enums may not be extended by source-level classes
5559                 if (st.tsym != null &&
5560                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5561                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5562                     log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5563                 }
5564 
5565                 if (rs.isSerializable(c.type)) {
5566                     env.info.isSerializable = true;
5567                 }
5568 
5569                 if (c.isValueClass()) {
5570                     Assert.check(env.tree.hasTag(CLASSDEF));
5571                     chk.checkConstraintsOfValueClass(env.tree.pos(), c);
5572                 }
5573 
5574                 attribClassBody(env, c);
5575 
5576                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5577                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5578                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5579                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5580             } finally {
5581                 env.info.returnResult = prevReturnRes;
5582                 log.useSource(prev);
5583                 chk.setLint(prevLint);
5584             }
5585 
5586         }
5587     }
5588 
5589     public void visitImport(JCImport tree) {
5590         // nothing to do
5591     }
5592 
5593     public void visitModuleDef(JCModuleDecl tree) {
< prev index next >