< prev index next >

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

Print this page

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

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

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

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




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

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

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






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

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

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

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

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

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

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

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





























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




2605                 return new ClassType(restype.getEnclosingType(),
2606                         List.of(new WildcardType(types.erasure(qualifierType),
2607                                 BoundKind.EXTENDS,
2608                                 syms.boundClass)),
2609                         restype.tsym,
2610                         restype.getMetadata());

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

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








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

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

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

2957                 }
2958 
2959                 // If we already errored, be careful to avoid a further avalanche. ErrorType answers
2960                 // false for isInterface call even when the original type is an interface.
2961                 boolean implementing = clazztype.tsym.isInterface() ||
2962                         clazztype.isErroneous() && !clazztype.getOriginalType().hasTag(NONE) &&
2963                         clazztype.getOriginalType().tsym.isInterface();
2964 
2965                 if (implementing) {
2966                     cdef.implementing = List.of(clazz);
2967                 } else {
2968                     cdef.extending = clazz;
2969                 }
2970 
2971                 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2972                     rs.isSerializable(clazztype)) {
2973                     localEnv.info.isSerializable = true;
2974                 }
2975 
2976                 attribStat(cdef, localEnv);

3009             result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK));
3010             chk.validate(tree.typeargs, localEnv);
3011         }
3012 
3013         CheckContext diamondContext(JCNewClass clazz, TypeSymbol tsym, CheckContext checkContext) {
3014             return new Check.NestedCheckContext(checkContext) {
3015                 @Override
3016                 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
3017                     enclosingContext.report(clazz.clazz,
3018                             diags.fragment(Fragments.CantApplyDiamond1(Fragments.Diamond(tsym), details)));
3019                 }
3020             };
3021         }
3022 
3023     /** Make an attributed null check tree.
3024      */
3025     public JCExpression makeNullCheck(JCExpression arg) {
3026         // optimization: new Outer() can never be null; skip null check
3027         if (arg.getTag() == NEWCLASS)
3028             return arg;



3029         // optimization: X.this is never null; skip null check
3030         Name name = TreeInfo.name(arg);
3031         if (name == names._this || name == names._super) return arg;
3032 
3033         JCTree.Tag optag = NULLCHK;
3034         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
3035         tree.operator = operators.resolveUnary(arg, optag, arg.type);
3036         tree.type = arg.type;
3037         return tree;
3038     }
3039 
3040     public void visitNewArray(JCNewArray tree) {
3041         Type owntype = types.createErrorType(tree.type);
3042         Env<AttrContext> localEnv = env.dup(tree);
3043         Type elemtype;
3044         if (tree.elemtype != null) {
3045             elemtype = attribType(tree.elemtype, localEnv);
3046             chk.validate(tree.elemtype, localEnv);
3047             owntype = elemtype;
3048             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {

4023         if (operator != operators.noOpSymbol &&
4024                 !left.isErroneous() &&
4025                 !right.isErroneous()) {
4026             owntype = operator.type.getReturnType();
4027             int opc = operator.opcode;
4028             // If both arguments are constants, fold them.
4029             if (left.constValue() != null && right.constValue() != null) {
4030                 Type ctype = cfolder.fold2(opc, left, right);
4031                 if (ctype != null) {
4032                     owntype = cfolder.coerce(ctype, owntype);
4033                 }
4034             }
4035 
4036             // Check that argument types of a reference ==, != are
4037             // castable to each other, (JLS 15.21).  Note: unboxing
4038             // comparisons will not have an acmp* opc at this point.
4039             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
4040                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
4041                     log.error(tree.pos(), Errors.IncomparableTypes(left, right));
4042                 }

4043             }
4044 
4045             chk.checkDivZero(tree.rhs.pos(), operator, right);
4046         }
4047         result = check(tree, owntype, KindSelector.VAL, resultInfo);
4048     }
4049 
4050     public void visitTypeCast(final JCTypeCast tree) {
4051         Type clazztype = attribType(tree.clazz, env);
4052         chk.validate(tree.clazz, env, false);
4053         //a fresh environment is required for 292 inference to work properly ---
4054         //see Infer.instantiatePolymorphicSignatureInstance()
4055         Env<AttrContext> localEnv = env.dup(tree);
4056         //should we propagate the target type?
4057         final ResultInfo castInfo;
4058         JCExpression expr = TreeInfo.skipParens(tree.expr);
4059         boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
4060         if (isPoly) {
4061             //expression is a poly - we need to propagate target type info
4062             castInfo = new ResultInfo(KindSelector.VAL, clazztype,

4258     }
4259 
4260     public void visitSelect(JCFieldAccess tree) {
4261         // Determine the expected kind of the qualifier expression.
4262         KindSelector skind = KindSelector.NIL;
4263         if (tree.name == names._this || tree.name == names._super ||
4264                 tree.name == names._class)
4265         {
4266             skind = KindSelector.TYP;
4267         } else {
4268             if (pkind().contains(KindSelector.PCK))
4269                 skind = KindSelector.of(skind, KindSelector.PCK);
4270             if (pkind().contains(KindSelector.TYP))
4271                 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4272             if (pkind().contains(KindSelector.VAL_MTH))
4273                 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4274         }
4275 
4276         // Attribute the qualifier expression, and determine its symbol (if any).
4277         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));










4278         if (!pkind().contains(KindSelector.TYP_PCK))
4279             site = capture(site); // Capture field access
4280 
4281         // don't allow T.class T[].class, etc
4282         if (skind == KindSelector.TYP) {
4283             Type elt = site;
4284             while (elt.hasTag(ARRAY))
4285                 elt = ((ArrayType)elt).elemtype;
4286             if (elt.hasTag(TYPEVAR)) {
4287                 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4288                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4289                 tree.sym = tree.type.tsym;
4290                 return ;
4291             }
4292         }
4293 
4294         // If qualifier symbol is a type or `super', assert `selectSuper'
4295         // for the selection. This is relevant for determining whether
4296         // protected symbols are accessible.
4297         Symbol sitesym = TreeInfo.symbol(tree.selected);

4298         boolean selectSuperPrev = env.info.selectSuper;
4299         env.info.selectSuper =
4300             sitesym != null &&
4301             sitesym.name == names._super;
4302 
4303         // Determine the symbol represented by the selection.
4304         env.info.pendingResolutionPhase = null;
4305         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
4306         if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
4307             log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym));
4308             sym = syms.errSymbol;
4309         }
4310         if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
4311             site = capture(site);
4312             sym = selectSym(tree, sitesym, site, env, resultInfo);
4313         }
4314         boolean varArgs = env.info.lastResolveVarargs();
4315         tree.sym = sym;
4316 
4317         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {

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

4417                                  Env<AttrContext> env,
4418                                  ResultInfo resultInfo) {
4419             DiagnosticPosition pos = tree.pos();
4420             Name name = tree.name;
4421             switch (site.getTag()) {
4422             case PACKAGE:
4423                 return rs.accessBase(
4424                     rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind),
4425                     pos, location, site, name, true);
4426             case ARRAY:
4427             case CLASS:
4428                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
4429                     return rs.resolveQualifiedMethod(
4430                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
4431                 } else if (name == names._this || name == names._super) {
4432                     return rs.resolveSelf(pos, env, site.tsym, name);
4433                 } else if (name == names._class) {
4434                     // In this case, we have already made sure in
4435                     // visitSelect that qualifier expression is a type.
4436                     return syms.getClassField(site, types);


4437                 } else {
4438                     // We are seeing a plain identifier as selector.
4439                     Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind);
4440                         sym = rs.accessBase(sym, pos, location, site, name, true);
4441                     return sym;
4442                 }
4443             case WILDCARD:
4444                 throw new AssertionError(tree);
4445             case TYPEVAR:
4446                 // Normally, site.getUpperBound() shouldn't be null.
4447                 // It should only happen during memberEnter/attribBase
4448                 // when determining the super type which *must* be
4449                 // done before attributing the type variables.  In
4450                 // other words, we are seeing this illegal program:
4451                 // class B<T> extends A<T.foo> {}
4452                 Symbol sym = (site.getUpperBound() != null)
4453                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
4454                     : null;
4455                 if (sym == null) {
4456                     log.error(pos, Errors.TypeVarCantBeDeref);

4520             if (resultInfo.pkind.contains(KindSelector.POLY)) {
4521                 return attrRecover.recoverMethodInvocation(tree, site, sym, env, resultInfo);
4522             } else {
4523                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
4524             }
4525         }
4526 
4527         Type checkIdInternal(JCTree tree,
4528                      Type site,
4529                      Symbol sym,
4530                      Type pt,
4531                      Env<AttrContext> env,
4532                      ResultInfo resultInfo) {
4533             if (pt.isErroneous()) {
4534                 return types.createErrorType(site);
4535             }
4536             Type owntype; // The computed type of this identifier occurrence.
4537             switch (sym.kind) {
4538             case TYP:
4539                 // For types, the computed type equals the symbol's type,
4540                 // except for two situations:
4541                 owntype = sym.type;
4542                 if (owntype.hasTag(CLASS)) {

4543                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
4544                     Type ownOuter = owntype.getEnclosingType();
4545 
4546                     // (a) If the symbol's type is parameterized, erase it







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

4870             //depending on the current check context
4871             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
4872             return types.createErrorType(site);
4873         } catch (Resolve.InapplicableMethodException ex) {
4874             final JCDiagnostic diag = ex.getDiagnostic();
4875             Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
4876                 @Override
4877                 protected Pair<Symbol, JCDiagnostic> errCandidate() {
4878                     return new Pair<>(sym, diag);
4879                 }
4880             };
4881             List<Type> argtypes2 = argtypes.map(
4882                     rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
4883             JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
4884                     env.tree, sym, site, sym.name, argtypes2, typeargtypes);
4885             log.report(errDiag);
4886             return types.createErrorType(site);
4887         }
4888     }
4889 




























4890     public void visitLiteral(JCLiteral tree) {
4891         result = check(tree, litType(tree.typetag).constType(tree.value),
4892                 KindSelector.VAL, resultInfo);
4893     }
4894     //where
4895     /** Return the type of a literal with given type tag.
4896      */
4897     Type litType(TypeTag tag) {
4898         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
4899     }
4900 
4901     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
4902         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
4903     }
4904 
4905     public void visitTypeArray(JCArrayTypeTree tree) {
4906         Type etype = attribType(tree.elemtype, env);
4907         Type type = new ArrayType(etype, syms.arrayClass);
4908         result = check(tree, type, KindSelector.TYP, resultInfo);
4909     }

4936                 }
4937                 // Compute the proper generic outer
4938                 Type clazzOuter = clazztype.getEnclosingType();
4939                 if (clazzOuter.hasTag(CLASS)) {
4940                     Type site;
4941                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
4942                     if (clazz.hasTag(IDENT)) {
4943                         site = env.enclClass.sym.type;
4944                     } else if (clazz.hasTag(SELECT)) {
4945                         site = ((JCFieldAccess) clazz).selected.type;
4946                     } else throw new AssertionError(""+tree);
4947                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
4948                         if (site.hasTag(CLASS))
4949                             site = types.asOuterSuper(site, clazzOuter.tsym);
4950                         if (site == null)
4951                             site = types.erasure(clazzOuter);
4952                         clazzOuter = site;
4953                     }
4954                 }
4955                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
4956                                         clazztype.getMetadata());
4957             } else {
4958                 if (formals.length() != 0) {
4959                     log.error(tree.pos(),
4960                               Errors.WrongNumberTypeArgs(Integer.toString(formals.length())));
4961                 } else {
4962                     log.error(tree.pos(), Errors.TypeDoesntTakeParams(clazztype.tsym));
4963                 }
4964                 owntype = types.createErrorType(tree.type);
4965             }
4966         }
4967         result = check(tree, owntype, KindSelector.TYP, resultInfo);
4968     }
4969 
4970     public void visitTypeUnion(JCTypeUnion tree) {
4971         ListBuffer<Type> multicatchTypes = new ListBuffer<>();
4972         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
4973         for (JCExpression typeTree : tree.alternatives) {
4974             Type ctype = attribType(typeTree, env);
4975             ctype = chk.checkType(typeTree.pos(),
4976                           chk.checkClassType(typeTree.pos(), ctype),

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

5220 
5221         try {
5222             deferredLintHandler.flush(env.tree.pos());
5223             attrib.accept(env);
5224         } finally {
5225             log.useSource(prev);
5226             chk.setLint(prevLint);
5227         }
5228     }
5229 
5230     /** Main method: attribute class definition associated with given class symbol.
5231      *  reporting completion failures at the given position.
5232      *  @param pos The source position at which completion errors are to be
5233      *             reported.
5234      *  @param c   The class symbol whose definition will be attributed.
5235      */
5236     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
5237         try {
5238             annotate.flush();
5239             attribClass(c);





5240         } catch (CompletionFailure ex) {
5241             chk.completionError(pos, ex);
5242         }
5243     }
5244 
5245     /** Attribute class definition associated with given class symbol.
5246      *  @param c   The class symbol whose definition will be attributed.
5247      */
5248     void attribClass(ClassSymbol c) throws CompletionFailure {
5249         if (c.type.hasTag(ERROR)) return;
5250 
5251         // Check for cycles in the inheritance graph, which can arise from
5252         // ill-formed class files.
5253         chk.checkNonCyclic(null, c.type);
5254 
5255         Type st = types.supertype(c.type);
5256         if ((c.flags_field & Flags.COMPOUND) == 0 &&
5257             (c.flags_field & Flags.SUPER_OWNER_ATTRIBUTED) == 0) {
5258             // First, attribute superclass.
5259             if (st.hasTag(CLASS))

5340                                                   .filter(s -> s.tsym.isSealed())
5341                                                   .map(s -> (ClassSymbol) s.tsym)
5342                                                   .collect(List.collector());
5343 
5344             if (sealedSupers.isEmpty()) {
5345                 if ((c.flags_field & Flags.NON_SEALED) != 0) {
5346                     boolean hasErrorSuper = false;
5347 
5348                     hasErrorSuper |= types.directSupertypes(c.type)
5349                                           .stream()
5350                                           .anyMatch(s -> s.tsym.kind == Kind.ERR);
5351 
5352                     ClassType ct = (ClassType) c.type;
5353 
5354                     hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5355 
5356                     if (!hasErrorSuper) {
5357                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5358                     }
5359                 }
5360             } else {
5361                 if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5362                     log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5363                 }
5364 
5365                 if (!c.type.isCompound()) {
5366                     for (ClassSymbol supertypeSym : sealedSupers) {
5367                         if (!supertypeSym.permitted.contains(c.type.tsym)) {
5368                             log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5369                         }
5370                     }
5371                     if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5372                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5373                                 c.isInterface() ?
5374                                         Errors.NonSealedOrSealedExpected :
5375                                         Errors.NonSealedSealedOrFinalExpected);
5376                     }
5377                 }
5378             }
5379 
5380             // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,

5395 
5396             try {
5397                 deferredLintHandler.flush(env.tree);
5398                 env.info.returnResult = null;
5399                 // java.lang.Enum may not be subclassed by a non-enum
5400                 if (st.tsym == syms.enumSym &&
5401                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5402                     log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5403 
5404                 // Enums may not be extended by source-level classes
5405                 if (st.tsym != null &&
5406                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5407                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5408                     log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5409                 }
5410 
5411                 if (rs.isSerializable(c.type)) {
5412                     env.info.isSerializable = true;
5413                 }
5414 





5415                 attribClassBody(env, c);
5416 
5417                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5418                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5419                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5420                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5421             } finally {
5422                 env.info.returnResult = prevReturnRes;
5423                 log.useSource(prev);
5424                 chk.setLint(prevLint);
5425             }
5426 
5427         }
5428     }
5429 
5430     public void visitImport(JCImport tree) {
5431         // nothing to do
5432     }
5433 
5434     public void visitModuleDef(JCModuleDecl tree) {

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

 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         allowPoly = Feature.POLY.allowedInSource(source);
 170         allowTypeAnnos = Feature.TYPE_ANNOTATIONS.allowedInSource(source);
 171         allowLambda = Feature.LAMBDA.allowedInSource(source);
 172         allowDefaultMethods = Feature.DEFAULT_METHODS.allowedInSource(source);
 173         allowStaticInterfaceMethods = Feature.STATIC_INTERFACE_METHODS.allowedInSource(source);
 174         allowPrimitiveClasses = Feature.PRIMITIVE_CLASSES.allowedInSource(source);
 175         allowReifiableTypesInInstanceof = Feature.REIFIABLE_TYPES_INSTANCEOF.allowedInSource(source);
 176         allowRecords = Feature.RECORDS.allowedInSource(source);
 177         allowPatternSwitch = (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH)) &&
 178                              Feature.PATTERN_SWITCH.allowedInSource(source);
 179         sourceName = source.name;
 180         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
 181 
 182         statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
 183         varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
 184         unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
 185         methodAttrInfo = new MethodAttrInfo();
 186         unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
 187         unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
 188         recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
 189     }
 190 
 191     /** Switch: support target-typing inference
 192      */
 193     boolean allowPoly;
 194 
 195     /** Switch: support type annotations.
 196      */
 197     boolean allowTypeAnnos;
 198 
 199     /** Switch: support lambda expressions ?
 200      */
 201     boolean allowLambda;
 202 
 203     /** Switch: support default methods ?
 204      */
 205     boolean allowDefaultMethods;
 206 
 207     /** Switch: allow primitive classes ?
 208      */
 209     boolean allowPrimitiveClasses;
 210 
 211     /** Switch: static interface methods enabled?
 212      */
 213     boolean allowStaticInterfaceMethods;
 214 
 215     /** Switch: reifiable types in instanceof enabled?
 216      */
 217     boolean allowReifiableTypesInInstanceof;
 218 
 219     /** Are records allowed
 220      */
 221     private final boolean allowRecords;
 222 
 223     /** Are patterns in switch allowed
 224      */
 225     private final boolean allowPatternSwitch;
 226 
 227     /**
 228      * Switch: warn about use of variable before declaration?
 229      * RFE: 6425594
 230      */

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

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

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

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

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

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

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

2588             // ... and attribute the method using as a prototype a methodtype
2589             // whose formal argument types is exactly the list of actual
2590             // arguments (this will also set the method symbol).
2591             Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
2592             localEnv.info.pendingResolutionPhase = null;
2593             Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
2594 
2595             // Compute the result type.
2596             Type restype = mtype.getReturnType();
2597             if (restype.hasTag(WILDCARD))
2598                 throw new AssertionError(mtype);
2599 
2600             Type qualifier = (tree.meth.hasTag(SELECT))
2601                     ? ((JCFieldAccess) tree.meth).selected.type
2602                     : env.enclClass.sym.type;
2603             Symbol msym = TreeInfo.symbol(tree.meth);
2604             restype = adjustMethodReturnType(msym, qualifier, methName, argtypes, restype);
2605 
2606             chk.checkRefTypes(tree.typeargs, typeargtypes);
2607 
2608             final Symbol symbol = TreeInfo.symbol(tree.meth);
2609             if (symbol != null) {
2610                 /* Is this an ill-conceived attempt to invoke jlO methods not available on value class types ??
2611                  */
2612                 boolean superCallOnValueReceiver = env.enclClass.sym.type.isValueClass()
2613                         && (tree.meth.hasTag(SELECT))
2614                         && ((JCFieldAccess)tree.meth).selected.hasTag(IDENT)
2615                         && TreeInfo.name(((JCFieldAccess)tree.meth).selected) == names._super;
2616                 if (qualifier.isValueClass() || superCallOnValueReceiver) {
2617                     int argSize = argtypes.size();
2618                     Name name = symbol.name;
2619                     switch (name.toString()) {
2620                         case "wait":
2621                             if (argSize == 0
2622                                     || (types.isConvertible(argtypes.head, syms.longType) &&
2623                                     (argSize == 1 || (argSize == 2 && types.isConvertible(argtypes.tail.head, syms.intType))))) {
2624                                 log.error(tree.pos(), Errors.ValueClassDoesNotSupport(name));
2625                             }
2626                             break;
2627                         case "notify":
2628                         case "notifyAll":
2629                         case "finalize":
2630                             if (argSize == 0)
2631                                 log.error(tree.pos(), Errors.ValueClassDoesNotSupport(name));
2632                             break;
2633                     }
2634                 }
2635             }
2636 
2637             // Check that value of resulting type is admissible in the
2638             // current context.  Also, capture the return type
2639             Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true);
2640             result = check(tree, capturedRes, KindSelector.VAL, resultInfo);
2641         }
2642         chk.validate(tree.typeargs, localEnv);
2643     }
2644     //where
2645         Type adjustMethodReturnType(Symbol msym, Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
2646             if (msym != null &&
2647                     (msym.owner == syms.objectType.tsym || msym.owner.isInterface()) &&
2648                     methodName == names.getClass &&
2649                     argtypes.isEmpty()) {
2650                 // as a special case, x.getClass() has type Class<? extends |X|>
2651                 // Special treatment for primitive classes: Given an expression v of type V where
2652                 // V is a primitive class, v.getClass() is typed to be Class<? extends |V.ref|>
2653                 Type wcb = types.erasure(qualifierType.isPrimitiveClass() ?
2654                                                 qualifierType.referenceProjection() : qualifierType);
2655                 return new ClassType(restype.getEnclosingType(),
2656                         List.of(new WildcardType(wcb,
2657                                 BoundKind.EXTENDS,
2658                                 syms.boundClass)),
2659                         restype.tsym,
2660                         restype.getMetadata(),
2661                         restype.getFlavor());
2662             } else if (msym != null &&
2663                     msym.owner == syms.arrayClass &&
2664                     methodName == names.clone &&
2665                     types.isArray(qualifierType)) {
2666                 // as a special case, array.clone() has a result that is
2667                 // the same as static type of the array being cloned
2668                 return qualifierType;
2669             } else {
2670                 return restype;
2671             }
2672         }
2673 
2674         /** Check that given application node appears as first statement
2675          *  in a constructor call.
2676          *  @param tree          The application node
2677          *  @param enclMethod    The enclosing method of the application.
2678          *  @param error         Should an error be issued?
2679          */
2680         boolean checkFirstConstructorStat(JCMethodInvocation tree, JCMethodDecl enclMethod, boolean error) {
2681             if (enclMethod != null && enclMethod.name == names.init) {

2810         }
2811 
2812         // Attribute constructor arguments.
2813         ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2814         final KindSelector pkind =
2815             attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
2816         List<Type> argtypes = argtypesBuf.toList();
2817         List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
2818 
2819         if (clazztype.hasTag(CLASS) || clazztype.hasTag(ERROR)) {
2820             // Enums may not be instantiated except implicitly
2821             if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 &&
2822                 (!env.tree.hasTag(VARDEF) ||
2823                  (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 ||
2824                  ((JCVariableDecl) env.tree).init != tree))
2825                 log.error(tree.pos(), Errors.EnumCantBeInstantiated);
2826 
2827             boolean isSpeculativeDiamondInferenceRound = TreeInfo.isDiamond(tree) &&
2828                     resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2829             boolean skipNonDiamondPath = false;
2830             // Check that it is an instantiation of a class and not a projection type
2831             if (clazz.hasTag(SELECT)) {
2832                 JCFieldAccess fieldAccess = (JCFieldAccess) clazz;
2833                 if (fieldAccess.selected.type.isPrimitiveClass() &&
2834                         (fieldAccess.name == names.ref || fieldAccess.name == names.val)) {
2835                     log.error(tree.pos(), Errors.ProjectionCantBeInstantiated);
2836                 }
2837             }
2838             // Check that class is not abstract
2839             if (cdef == null && !isSpeculativeDiamondInferenceRound && // class body may be nulled out in speculative tree copy
2840                 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
2841                 log.error(tree.pos(),
2842                           Errors.AbstractCantBeInstantiated(clazztype.tsym));
2843                 skipNonDiamondPath = true;
2844             } else if (cdef != null && clazztype.tsym.isInterface()) {
2845                 // Check that no constructor arguments are given to
2846                 // anonymous classes implementing an interface
2847                 if (!argtypes.isEmpty())
2848                     log.error(tree.args.head.pos(), Errors.AnonClassImplIntfNoArgs);
2849 
2850                 if (!typeargtypes.isEmpty())
2851                     log.error(tree.typeargs.head.pos(), Errors.AnonClassImplIntfNoTypeargs);
2852 
2853                 // Error recovery: pretend no arguments were supplied.
2854                 argtypes = List.nil();
2855                 typeargtypes = List.nil();
2856                 skipNonDiamondPath = true;
2857             }
2858             if (TreeInfo.isDiamond(tree)) {
2859                 ClassType site = new ClassType(clazztype.getEnclosingType(),
2860                             clazztype.tsym.type.getTypeArguments(),
2861                                                clazztype.tsym,
2862                                                clazztype.getMetadata(),
2863                                                clazztype.getFlavor());
2864 
2865                 Env<AttrContext> diamondEnv = localEnv.dup(tree);
2866                 diamondEnv.info.selectSuper = cdef != null || tree.classDeclRemoved();
2867                 diamondEnv.info.pendingResolutionPhase = null;
2868 
2869                 //if the type of the instance creation expression is a class type
2870                 //apply method resolution inference (JLS 15.12.2.7). The return type
2871                 //of the resolved constructor will be a partially instantiated type
2872                 Symbol constructor = rs.resolveDiamond(tree.pos(),
2873                             diamondEnv,
2874                             site,
2875                             argtypes,
2876                             typeargtypes);
2877                 tree.constructor = constructor.baseSymbol();
2878 
2879                 final TypeSymbol csym = clazztype.tsym;
2880                 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes),
2881                         diamondContext(tree, csym, resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
2882                 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
2883                 constructorType = checkId(tree, site,

2997                                 this.resultInfo = prevResult;
2998                             }
2999                         });
3000             } else {
3001                 if (isDiamond && clazztype.hasTag(CLASS)) {
3002                     List<Type> invalidDiamondArgs = chk.checkDiamondDenotable((ClassType)clazztype);
3003                     if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
3004                         // One or more types inferred in the previous steps is non-denotable.
3005                         Fragment fragment = Diamond(clazztype.tsym);
3006                         log.error(tree.clazz.pos(),
3007                                 Errors.CantApplyDiamond1(
3008                                         fragment,
3009                                         invalidDiamondArgs.size() > 1 ?
3010                                                 DiamondInvalidArgs(invalidDiamondArgs, fragment) :
3011                                                 DiamondInvalidArg(invalidDiamondArgs, fragment)));
3012                     }
3013                     // For <>(){}, inferred types must also be accessible.
3014                     for (Type t : clazztype.getTypeArguments()) {
3015                         rs.checkAccessibleType(env, t);
3016                     }
3017                     chk.checkParameterizationByPrimitiveClass(tree, clazztype);
3018                 }
3019 
3020                 // If we already errored, be careful to avoid a further avalanche. ErrorType answers
3021                 // false for isInterface call even when the original type is an interface.
3022                 boolean implementing = clazztype.tsym.isInterface() ||
3023                         clazztype.isErroneous() && !clazztype.getOriginalType().hasTag(NONE) &&
3024                         clazztype.getOriginalType().tsym.isInterface();
3025 
3026                 if (implementing) {
3027                     cdef.implementing = List.of(clazz);
3028                 } else {
3029                     cdef.extending = clazz;
3030                 }
3031 
3032                 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3033                     rs.isSerializable(clazztype)) {
3034                     localEnv.info.isSerializable = true;
3035                 }
3036 
3037                 attribStat(cdef, localEnv);

3070             result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK));
3071             chk.validate(tree.typeargs, localEnv);
3072         }
3073 
3074         CheckContext diamondContext(JCNewClass clazz, TypeSymbol tsym, CheckContext checkContext) {
3075             return new Check.NestedCheckContext(checkContext) {
3076                 @Override
3077                 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
3078                     enclosingContext.report(clazz.clazz,
3079                             diags.fragment(Fragments.CantApplyDiamond1(Fragments.Diamond(tsym), details)));
3080                 }
3081             };
3082         }
3083 
3084     /** Make an attributed null check tree.
3085      */
3086     public JCExpression makeNullCheck(JCExpression arg) {
3087         // optimization: new Outer() can never be null; skip null check
3088         if (arg.getTag() == NEWCLASS)
3089             return arg;
3090         // Likewise arg can't be null if it is a primitive class instance.
3091         if (arg.type.isPrimitiveClass())
3092             return arg;
3093         // optimization: X.this is never null; skip null check
3094         Name name = TreeInfo.name(arg);
3095         if (name == names._this || name == names._super) return arg;
3096 
3097         JCTree.Tag optag = NULLCHK;
3098         JCUnary tree = make.at(arg.pos).Unary(optag, arg);
3099         tree.operator = operators.resolveUnary(arg, optag, arg.type);
3100         tree.type = arg.type;
3101         return tree;
3102     }
3103 
3104     public void visitNewArray(JCNewArray tree) {
3105         Type owntype = types.createErrorType(tree.type);
3106         Env<AttrContext> localEnv = env.dup(tree);
3107         Type elemtype;
3108         if (tree.elemtype != null) {
3109             elemtype = attribType(tree.elemtype, localEnv);
3110             chk.validate(tree.elemtype, localEnv);
3111             owntype = elemtype;
3112             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {

4087         if (operator != operators.noOpSymbol &&
4088                 !left.isErroneous() &&
4089                 !right.isErroneous()) {
4090             owntype = operator.type.getReturnType();
4091             int opc = operator.opcode;
4092             // If both arguments are constants, fold them.
4093             if (left.constValue() != null && right.constValue() != null) {
4094                 Type ctype = cfolder.fold2(opc, left, right);
4095                 if (ctype != null) {
4096                     owntype = cfolder.coerce(ctype, owntype);
4097                 }
4098             }
4099 
4100             // Check that argument types of a reference ==, != are
4101             // castable to each other, (JLS 15.21).  Note: unboxing
4102             // comparisons will not have an acmp* opc at this point.
4103             if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
4104                 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
4105                     log.error(tree.pos(), Errors.IncomparableTypes(left, right));
4106                 }
4107                 chk.checkForSuspectClassLiteralComparison(tree, left, right);
4108             }
4109 
4110             chk.checkDivZero(tree.rhs.pos(), operator, right);
4111         }
4112         result = check(tree, owntype, KindSelector.VAL, resultInfo);
4113     }
4114 
4115     public void visitTypeCast(final JCTypeCast tree) {
4116         Type clazztype = attribType(tree.clazz, env);
4117         chk.validate(tree.clazz, env, false);
4118         //a fresh environment is required for 292 inference to work properly ---
4119         //see Infer.instantiatePolymorphicSignatureInstance()
4120         Env<AttrContext> localEnv = env.dup(tree);
4121         //should we propagate the target type?
4122         final ResultInfo castInfo;
4123         JCExpression expr = TreeInfo.skipParens(tree.expr);
4124         boolean isPoly = allowPoly && (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
4125         if (isPoly) {
4126             //expression is a poly - we need to propagate target type info
4127             castInfo = new ResultInfo(KindSelector.VAL, clazztype,

4323     }
4324 
4325     public void visitSelect(JCFieldAccess tree) {
4326         // Determine the expected kind of the qualifier expression.
4327         KindSelector skind = KindSelector.NIL;
4328         if (tree.name == names._this || tree.name == names._super ||
4329                 tree.name == names._class)
4330         {
4331             skind = KindSelector.TYP;
4332         } else {
4333             if (pkind().contains(KindSelector.PCK))
4334                 skind = KindSelector.of(skind, KindSelector.PCK);
4335             if (pkind().contains(KindSelector.TYP))
4336                 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4337             if (pkind().contains(KindSelector.VAL_MTH))
4338                 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4339         }
4340 
4341         // Attribute the qualifier expression, and determine its symbol (if any).
4342         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4343         Assert.check(site == tree.selected.type);
4344         if (tree.name == names._class && site.isPrimitiveClass()) {
4345             /* JDK-8269956: Where a reflective (class) literal is needed, the unqualified Point.class is
4346              * always the "primary" mirror - representing the primitive reference runtime type - thereby
4347              * always matching the behavior of Object::getClass
4348              */
4349              if (!tree.selected.hasTag(SELECT) || ((JCFieldAccess) tree.selected).name != names.val) {
4350                  tree.selected.setType(site = site.referenceProjection());
4351              }
4352         }
4353         if (!pkind().contains(KindSelector.TYP_PCK))
4354             site = capture(site); // Capture field access
4355 
4356         // don't allow T.class T[].class, etc
4357         if (skind == KindSelector.TYP) {
4358             Type elt = site;
4359             while (elt.hasTag(ARRAY))
4360                 elt = ((ArrayType)elt).elemtype;
4361             if (elt.hasTag(TYPEVAR)) {
4362                 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4363                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4364                 tree.sym = tree.type.tsym;
4365                 return;
4366             }
4367         }
4368 
4369         // If qualifier symbol is a type or `super', assert `selectSuper'
4370         // for the selection. This is relevant for determining whether
4371         // protected symbols are accessible.
4372         Symbol sitesym = TreeInfo.symbol(tree.selected);
4373 
4374         boolean selectSuperPrev = env.info.selectSuper;
4375         env.info.selectSuper =
4376             sitesym != null &&
4377             sitesym.name == names._super;
4378 
4379         // Determine the symbol represented by the selection.
4380         env.info.pendingResolutionPhase = null;
4381         Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
4382         if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
4383             log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym));
4384             sym = syms.errSymbol;
4385         }
4386         if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
4387             site = capture(site);
4388             sym = selectSym(tree, sitesym, site, env, resultInfo);
4389         }
4390         boolean varArgs = env.info.lastResolveVarargs();
4391         tree.sym = sym;
4392 
4393         if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {

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

4493                                  Env<AttrContext> env,
4494                                  ResultInfo resultInfo) {
4495             DiagnosticPosition pos = tree.pos();
4496             Name name = tree.name;
4497             switch (site.getTag()) {
4498             case PACKAGE:
4499                 return rs.accessBase(
4500                     rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind),
4501                     pos, location, site, name, true);
4502             case ARRAY:
4503             case CLASS:
4504                 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
4505                     return rs.resolveQualifiedMethod(
4506                         pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
4507                 } else if (name == names._this || name == names._super) {
4508                     return rs.resolveSelf(pos, env, site.tsym, name);
4509                 } else if (name == names._class) {
4510                     // In this case, we have already made sure in
4511                     // visitSelect that qualifier expression is a type.
4512                     return syms.getClassField(site, types);
4513                 } else if (site.isPrimitiveClass() && isType(location) && resultInfo.pkind.contains(KindSelector.TYP) && (name == names.ref || name == names.val)) {
4514                     return site.tsym;
4515                 } else {
4516                     // We are seeing a plain identifier as selector.
4517                     Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind);
4518                         sym = rs.accessBase(sym, pos, location, site, name, true);
4519                     return sym;
4520                 }
4521             case WILDCARD:
4522                 throw new AssertionError(tree);
4523             case TYPEVAR:
4524                 // Normally, site.getUpperBound() shouldn't be null.
4525                 // It should only happen during memberEnter/attribBase
4526                 // when determining the super type which *must* be
4527                 // done before attributing the type variables.  In
4528                 // other words, we are seeing this illegal program:
4529                 // class B<T> extends A<T.foo> {}
4530                 Symbol sym = (site.getUpperBound() != null)
4531                     ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
4532                     : null;
4533                 if (sym == null) {
4534                     log.error(pos, Errors.TypeVarCantBeDeref);

4598             if (resultInfo.pkind.contains(KindSelector.POLY)) {
4599                 return attrRecover.recoverMethodInvocation(tree, site, sym, env, resultInfo);
4600             } else {
4601                 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
4602             }
4603         }
4604 
4605         Type checkIdInternal(JCTree tree,
4606                      Type site,
4607                      Symbol sym,
4608                      Type pt,
4609                      Env<AttrContext> env,
4610                      ResultInfo resultInfo) {
4611             if (pt.isErroneous()) {
4612                 return types.createErrorType(site);
4613             }
4614             Type owntype; // The computed type of this identifier occurrence.
4615             switch (sym.kind) {
4616             case TYP:
4617                 // For types, the computed type equals the symbol's type,
4618                 // except for three situations:
4619                 owntype = sym.type;
4620                 if (owntype.hasTag(CLASS)) {
4621                     Assert.check(owntype.getFlavor() != Flavor.X_Typeof_X);
4622                     chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
4623                     Type ownOuter = owntype.getEnclosingType();
4624 
4625                     // (a) If symbol is a primitive class and its reference projection
4626                     // is requested via the .ref notation, then adjust the computed type to
4627                     // reflect this.
4628                     if (owntype.isPrimitiveClass() && tree.hasTag(SELECT) && ((JCFieldAccess) tree).name == names.ref) {
4629                         owntype = new ClassType(owntype.getEnclosingType(), owntype.getTypeArguments(), (TypeSymbol)sym, owntype.getMetadata(), Flavor.L_TypeOf_Q);
4630                     }
4631 
4632                     // (b) If the symbol's type is parameterized, erase it
4633                     // because no type parameters were given.
4634                     // We recover generic outer type later in visitTypeApply.
4635                     if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
4636                         owntype = types.erasure(owntype);
4637                     }
4638 
4639                     // (c) If the symbol's type is an inner class, then
4640                     // we have to interpret its outer type as a superclass
4641                     // of the site type. Example:
4642                     //
4643                     // class Tree<A> { class Visitor { ... } }
4644                     // class PointTree extends Tree<Point> { ... }
4645                     // ...PointTree.Visitor...
4646                     //
4647                     // Then the type of the last expression above is
4648                     // Tree<Point>.Visitor.
4649                     else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
4650                         Type normOuter = site;
4651                         if (normOuter.hasTag(CLASS)) {
4652                             normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
4653                         }
4654                         if (normOuter == null) // perhaps from an import
4655                             normOuter = types.erasure(ownOuter);
4656                         if (normOuter != ownOuter)
4657                             owntype = new ClassType(
4658                                 normOuter, List.nil(), owntype.tsym,
4659                                 owntype.getMetadata(), owntype.getFlavor());
4660                     }
4661                 }
4662                 break;
4663             case VAR:
4664                 VarSymbol v = (VarSymbol)sym;
4665 
4666                 if (env.info.enclVar != null
4667                         && v.type.hasTag(NONE)) {
4668                     //self reference to implicitly typed variable declaration
4669                     log.error(TreeInfo.positionFor(v, env.enclClass), Errors.CantInferLocalVarType(v.name, Fragments.LocalSelfRef));
4670                     return v.type = types.createErrorType(v.type);
4671                 }
4672 
4673                 // Test (4): if symbol is an instance field of a raw type,
4674                 // which is being assigned to, issue an unchecked warning if
4675                 // its type changes under erasure.
4676                 if (KindSelector.ASG.subset(pkind()) &&
4677                     v.owner.kind == TYP &&
4678                     (v.flags() & STATIC) == 0 &&
4679                     (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {

4956             //depending on the current check context
4957             resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
4958             return types.createErrorType(site);
4959         } catch (Resolve.InapplicableMethodException ex) {
4960             final JCDiagnostic diag = ex.getDiagnostic();
4961             Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
4962                 @Override
4963                 protected Pair<Symbol, JCDiagnostic> errCandidate() {
4964                     return new Pair<>(sym, diag);
4965                 }
4966             };
4967             List<Type> argtypes2 = argtypes.map(
4968                     rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
4969             JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
4970                     env.tree, sym, site, sym.name, argtypes2, typeargtypes);
4971             log.report(errDiag);
4972             return types.createErrorType(site);
4973         }
4974     }
4975 
4976     public void visitDefaultValue(JCDefaultValue tree) {
4977         if (!allowPrimitiveClasses) {
4978             log.error(DiagnosticFlag.SOURCE_LEVEL, tree.pos(),
4979                     Feature.PRIMITIVE_CLASSES.error(sourceName));
4980         }
4981 
4982         // Attribute the qualifier expression, and determine its symbol (if any).
4983         Type site = attribTree(tree.clazz, env, new ResultInfo(KindSelector.TYP_PCK, Type.noType));
4984         if (!pkind().contains(KindSelector.TYP_PCK))
4985             site = capture(site); // Capture field access
4986 
4987         Symbol sym = switch (site.getTag()) {
4988                 case WILDCARD -> throw new AssertionError(tree);
4989                 case PACKAGE -> {
4990                     log.error(tree.pos, Errors.CantResolveLocation(Kinds.KindName.CLASS, site.tsym.getQualifiedName(), null, null,
4991                             Fragments.Location(Kinds.typeKindName(env.enclClass.type), env.enclClass.type, null)));
4992                     yield syms.errSymbol;
4993                 }
4994                 case ERROR -> types.createErrorType(names._default, site.tsym, site).tsym;
4995                 default -> new VarSymbol(STATIC, names._default, site, site.tsym);
4996         };
4997 
4998         if (site.hasTag(TYPEVAR) && sym.kind != ERR) {
4999             site = types.skipTypeVars(site, true);
5000         }
5001         result = checkId(tree, site, sym, env, resultInfo);
5002     }
5003 
5004     public void visitLiteral(JCLiteral tree) {
5005         result = check(tree, litType(tree.typetag).constType(tree.value),
5006                 KindSelector.VAL, resultInfo);
5007     }
5008     //where
5009     /** Return the type of a literal with given type tag.
5010      */
5011     Type litType(TypeTag tag) {
5012         return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
5013     }
5014 
5015     public void visitTypeIdent(JCPrimitiveTypeTree tree) {
5016         result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
5017     }
5018 
5019     public void visitTypeArray(JCArrayTypeTree tree) {
5020         Type etype = attribType(tree.elemtype, env);
5021         Type type = new ArrayType(etype, syms.arrayClass);
5022         result = check(tree, type, KindSelector.TYP, resultInfo);
5023     }

5050                 }
5051                 // Compute the proper generic outer
5052                 Type clazzOuter = clazztype.getEnclosingType();
5053                 if (clazzOuter.hasTag(CLASS)) {
5054                     Type site;
5055                     JCExpression clazz = TreeInfo.typeIn(tree.clazz);
5056                     if (clazz.hasTag(IDENT)) {
5057                         site = env.enclClass.sym.type;
5058                     } else if (clazz.hasTag(SELECT)) {
5059                         site = ((JCFieldAccess) clazz).selected.type;
5060                     } else throw new AssertionError(""+tree);
5061                     if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
5062                         if (site.hasTag(CLASS))
5063                             site = types.asOuterSuper(site, clazzOuter.tsym);
5064                         if (site == null)
5065                             site = types.erasure(clazzOuter);
5066                         clazzOuter = site;
5067                     }
5068                 }
5069                 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
5070                                         clazztype.getMetadata(), clazztype.getFlavor());
5071             } else {
5072                 if (formals.length() != 0) {
5073                     log.error(tree.pos(),
5074                               Errors.WrongNumberTypeArgs(Integer.toString(formals.length())));
5075                 } else {
5076                     log.error(tree.pos(), Errors.TypeDoesntTakeParams(clazztype.tsym));
5077                 }
5078                 owntype = types.createErrorType(tree.type);
5079             }
5080         }
5081         result = check(tree, owntype, KindSelector.TYP, resultInfo);
5082     }
5083 
5084     public void visitTypeUnion(JCTypeUnion tree) {
5085         ListBuffer<Type> multicatchTypes = new ListBuffer<>();
5086         ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
5087         for (JCExpression typeTree : tree.alternatives) {
5088             Type ctype = attribType(typeTree, env);
5089             ctype = chk.checkType(typeTree.pos(),
5090                           chk.checkClassType(typeTree.pos(), ctype),

5177         if (bounds.length() == 0) {
5178             return syms.objectType;
5179         } else if (bounds.length() == 1) {
5180             return bounds.head.type;
5181         } else {
5182             Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
5183             // ... the variable's bound is a class type flagged COMPOUND
5184             // (see comment for TypeVar.bound).
5185             // In this case, generate a class tree that represents the
5186             // bound class, ...
5187             JCExpression extending;
5188             List<JCExpression> implementing;
5189             if (!bounds.head.type.isInterface()) {
5190                 extending = bounds.head;
5191                 implementing = bounds.tail;
5192             } else {
5193                 extending = null;
5194                 implementing = bounds;
5195             }
5196             JCClassDecl cd = make.at(tree).ClassDef(
5197                 make.Modifiers(PUBLIC | ABSTRACT | (extending != null && TreeInfo.symbol(extending).isPrimitiveClass() ? PRIMITIVE_CLASS : 0)),
5198                 names.empty, List.nil(),
5199                 extending, implementing, List.nil());
5200 
5201             ClassSymbol c = (ClassSymbol)owntype.tsym;
5202             Assert.check((c.flags() & COMPOUND) != 0);
5203             cd.sym = c;
5204             c.sourcefile = env.toplevel.sourcefile;
5205 
5206             // ... and attribute the bound class
5207             c.flags_field |= UNATTRIBUTED;
5208             Env<AttrContext> cenv = enter.classEnv(cd, env);
5209             typeEnvs.put(c, cenv);
5210             attribClass(c);
5211             return owntype;
5212         }
5213     }
5214 
5215     public void visitWildcard(JCWildcard tree) {
5216         //- System.err.println("visitWildcard("+tree+");");//DEBUG
5217         Type type = (tree.kind.kind == BoundKind.UNBOUND)
5218             ? syms.objectType
5219             : attribType(tree.inner, env);
5220         result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type, false),
5221                                               tree.kind.kind,
5222                                               syms.boundClass),
5223                 KindSelector.TYP, resultInfo);
5224     }
5225 
5226     public void visitAnnotation(JCAnnotation tree) {
5227         Assert.error("should be handled in annotate");
5228     }
5229 
5230     @Override
5231     public void visitModifiers(JCModifiers tree) {
5232         //error recovery only:
5233         Assert.check(resultInfo.pkind == KindSelector.ERR);
5234 
5235         attribAnnotationTypes(tree.annotations, env);
5236     }
5237 
5238     public void visitAnnotatedType(JCAnnotatedType tree) {
5239         attribAnnotationTypes(tree.annotations, env);
5240         Type underlyingType = attribType(tree.underlyingType, env);

5334 
5335         try {
5336             deferredLintHandler.flush(env.tree.pos());
5337             attrib.accept(env);
5338         } finally {
5339             log.useSource(prev);
5340             chk.setLint(prevLint);
5341         }
5342     }
5343 
5344     /** Main method: attribute class definition associated with given class symbol.
5345      *  reporting completion failures at the given position.
5346      *  @param pos The source position at which completion errors are to be
5347      *             reported.
5348      *  @param c   The class symbol whose definition will be attributed.
5349      */
5350     public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
5351         try {
5352             annotate.flush();
5353             attribClass(c);
5354             if (c.type.isPrimitiveClass()) {
5355                 final Env<AttrContext> env = typeEnvs.get(c);
5356                 if (env != null && env.tree != null && env.tree.hasTag(CLASSDEF))
5357                     chk.checkNonCyclicMembership((JCClassDecl)env.tree);
5358             }
5359         } catch (CompletionFailure ex) {
5360             chk.completionError(pos, ex);
5361         }
5362     }
5363 
5364     /** Attribute class definition associated with given class symbol.
5365      *  @param c   The class symbol whose definition will be attributed.
5366      */
5367     void attribClass(ClassSymbol c) throws CompletionFailure {
5368         if (c.type.hasTag(ERROR)) return;
5369 
5370         // Check for cycles in the inheritance graph, which can arise from
5371         // ill-formed class files.
5372         chk.checkNonCyclic(null, c.type);
5373 
5374         Type st = types.supertype(c.type);
5375         if ((c.flags_field & Flags.COMPOUND) == 0 &&
5376             (c.flags_field & Flags.SUPER_OWNER_ATTRIBUTED) == 0) {
5377             // First, attribute superclass.
5378             if (st.hasTag(CLASS))

5459                                                   .filter(s -> s.tsym.isSealed())
5460                                                   .map(s -> (ClassSymbol) s.tsym)
5461                                                   .collect(List.collector());
5462 
5463             if (sealedSupers.isEmpty()) {
5464                 if ((c.flags_field & Flags.NON_SEALED) != 0) {
5465                     boolean hasErrorSuper = false;
5466 
5467                     hasErrorSuper |= types.directSupertypes(c.type)
5468                                           .stream()
5469                                           .anyMatch(s -> s.tsym.kind == Kind.ERR);
5470 
5471                     ClassType ct = (ClassType) c.type;
5472 
5473                     hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5474 
5475                     if (!hasErrorSuper) {
5476                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5477                     }
5478                 }
5479             } else if ((c.flags_field & Flags.COMPOUND) == 0) {
5480                 if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5481                     log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5482                 }
5483 
5484                 if (!c.type.isCompound()) {
5485                     for (ClassSymbol supertypeSym : sealedSupers) {
5486                         if (!supertypeSym.permitted.contains(c.type.tsym)) {
5487                             log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5488                         }
5489                     }
5490                     if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5491                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5492                                 c.isInterface() ?
5493                                         Errors.NonSealedOrSealedExpected :
5494                                         Errors.NonSealedSealedOrFinalExpected);
5495                     }
5496                 }
5497             }
5498 
5499             // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,

5514 
5515             try {
5516                 deferredLintHandler.flush(env.tree);
5517                 env.info.returnResult = null;
5518                 // java.lang.Enum may not be subclassed by a non-enum
5519                 if (st.tsym == syms.enumSym &&
5520                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5521                     log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5522 
5523                 // Enums may not be extended by source-level classes
5524                 if (st.tsym != null &&
5525                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5526                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5527                     log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5528                 }
5529 
5530                 if (rs.isSerializable(c.type)) {
5531                     env.info.isSerializable = true;
5532                 }
5533 
5534                 if (c.isValueClass()) {
5535                     Assert.check(env.tree.hasTag(CLASSDEF));
5536                     chk.checkConstraintsOfValueClass(env.tree.pos(), c);
5537                 }
5538 
5539                 attribClassBody(env, c);
5540 
5541                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5542                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5543                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5544                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5545             } finally {
5546                 env.info.returnResult = prevReturnRes;
5547                 log.useSource(prev);
5548                 chk.setLint(prevLint);
5549             }
5550 
5551         }
5552     }
5553 
5554     public void visitImport(JCImport tree) {
5555         // nothing to do
5556     }
5557 
5558     public void visitModuleDef(JCModuleDecl tree) {
< prev index next >