29 import java.util.function.BiConsumer;
30 import java.util.function.Consumer;
31 import java.util.stream.Stream;
32
33 import javax.lang.model.element.ElementKind;
34 import javax.tools.JavaFileObject;
35
36 import com.sun.source.tree.CaseTree;
37 import com.sun.source.tree.EnhancedForLoopTree;
38 import com.sun.source.tree.IdentifierTree;
39 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
40 import com.sun.source.tree.MemberSelectTree;
41 import com.sun.source.tree.TreeVisitor;
42 import com.sun.source.util.SimpleTreeVisitor;
43 import com.sun.tools.javac.code.*;
44 import com.sun.tools.javac.code.Lint.LintCategory;
45 import com.sun.tools.javac.code.Scope.WriteableScope;
46 import com.sun.tools.javac.code.Source.Feature;
47 import com.sun.tools.javac.code.Symbol.*;
48 import com.sun.tools.javac.code.Type.*;
49 import com.sun.tools.javac.code.TypeMetadata.Annotations;
50 import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError;
51 import com.sun.tools.javac.comp.ArgumentAttr.LocalCacheContext;
52 import com.sun.tools.javac.comp.Check.CheckContext;
53 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
54 import com.sun.tools.javac.comp.MatchBindingsComputer.MatchBindings;
55 import com.sun.tools.javac.jvm.*;
56
57 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond;
58 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArg;
59 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArgs;
60
61 import com.sun.tools.javac.resources.CompilerProperties.Errors;
62 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
63 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
64 import com.sun.tools.javac.tree.*;
65 import com.sun.tools.javac.tree.JCTree.*;
66 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
67 import com.sun.tools.javac.util.*;
68 import com.sun.tools.javac.util.DefinedBy.Api;
150 infer = Infer.instance(context);
151 analyzer = Analyzer.instance(context);
152 deferredAttr = DeferredAttr.instance(context);
153 cfolder = ConstFold.instance(context);
154 target = Target.instance(context);
155 types = Types.instance(context);
156 preview = Preview.instance(context);
157 diags = JCDiagnostic.Factory.instance(context);
158 annotate = Annotate.instance(context);
159 typeAnnotations = TypeAnnotations.instance(context);
160 deferredLintHandler = DeferredLintHandler.instance(context);
161 typeEnvs = TypeEnvs.instance(context);
162 dependencies = Dependencies.instance(context);
163 argumentAttr = ArgumentAttr.instance(context);
164 matchBindingsComputer = MatchBindingsComputer.instance(context);
165 attrRecover = AttrRecover.instance(context);
166
167 Options options = Options.instance(context);
168
169 Source source = Source.instance(context);
170 allowReifiableTypesInInstanceof = Feature.REIFIABLE_TYPES_INSTANCEOF.allowedInSource(source);
171 allowRecords = Feature.RECORDS.allowedInSource(source);
172 allowPatternSwitch = (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH)) &&
173 Feature.PATTERN_SWITCH.allowedInSource(source);
174 allowUnconditionalPatternsInstanceOf = (preview.isEnabled() || !preview.isPreview(Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF)) &&
175 Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.allowedInSource(source);
176 sourceName = source.name;
177 useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
178
179 statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
180 varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
181 unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
182 methodAttrInfo = new MethodAttrInfo();
183 unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
184 unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
185 recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
186 }
187
188 /** Switch: reifiable types in instanceof enabled?
189 */
190 boolean allowReifiableTypesInInstanceof;
191
192 /** Are records allowed
193 */
194 private final boolean allowRecords;
195
196 /** Are patterns in switch allowed
197 */
198 private final boolean allowPatternSwitch;
199
200 /** Are unconditional patterns in instanceof allowed
201 */
202 private final boolean allowUnconditionalPatternsInstanceOf;
203
204 /**
205 * Switch: warn about use of variable before declaration?
206 * RFE: 6425594
207 */
256 found;
257 }
258 if (resultInfo.checkMode.updateTreeType()) {
259 tree.type = owntype;
260 }
261 return owntype;
262 }
263
264 /** Is given blank final variable assignable, i.e. in a scope where it
265 * may be assigned to even though it is final?
266 * @param v The blank final variable.
267 * @param env The current environment.
268 */
269 boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
270 Symbol owner = env.info.scope.owner;
271 // owner refers to the innermost variable, method or
272 // initializer block declaration at this point.
273 boolean isAssignable =
274 v.owner == owner
275 ||
276 ((owner.name == names.init || // i.e. we are in a constructor
277 owner.kind == VAR || // i.e. we are in a variable initializer
278 (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block
279 &&
280 v.owner == owner.owner
281 &&
282 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
283 boolean insideCompactConstructor = env.enclMethod != null && TreeInfo.isCompactConstructor(env.enclMethod);
284 return isAssignable & !insideCompactConstructor;
285 }
286
287 /** Check that variable can be assigned to.
288 * @param pos The current source code position.
289 * @param v The assigned variable
290 * @param base If the variable is referred to in a Select, the part
291 * to the left of the `.', null otherwise.
292 * @param env The current environment.
293 */
294 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
295 if (v.name == names._this) {
296 log.error(pos, Errors.CantAssignValToThis);
783 /** Attribute a type argument list, returning a list of types.
784 * Check that all the types are references.
785 */
786 List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
787 List<Type> types = attribAnyTypes(trees, env);
788 return chk.checkRefTypes(trees, types);
789 }
790
791 /**
792 * Attribute type variables (of generic classes or methods).
793 * Compound types are attributed later in attribBounds.
794 * @param typarams the type variables to enter
795 * @param env the current environment
796 */
797 void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env, boolean checkCyclic) {
798 for (JCTypeParameter tvar : typarams) {
799 TypeVar a = (TypeVar)tvar.type;
800 a.tsym.flags_field |= UNATTRIBUTED;
801 a.setUpperBound(Type.noType);
802 if (!tvar.bounds.isEmpty()) {
803 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
804 for (JCExpression bound : tvar.bounds.tail)
805 bounds = bounds.prepend(attribType(bound, env));
806 types.setBounds(a, bounds.reverse());
807 } else {
808 // if no bounds are given, assume a single bound of
809 // java.lang.Object.
810 types.setBounds(a, List.of(syms.objectType));
811 }
812 a.tsym.flags_field &= ~UNATTRIBUTED;
813 }
814 if (checkCyclic) {
815 for (JCTypeParameter tvar : typarams) {
816 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
817 }
818 }
819 }
820
821 /**
822 * Attribute the type references in a list of annotations.
823 */
824 void attribAnnotationTypes(List<JCAnnotation> annotations,
825 Env<AttrContext> env) {
1055 log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.MethodMustBePublic));
1056 }
1057 if (!types.isSameType(tree.sym.type.getReturnType(), recordComponent.get().type)) {
1058 log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym,
1059 Fragments.AccessorReturnTypeDoesntMatch(tree.sym, recordComponent.get())));
1060 }
1061 if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1062 log.error(tree,
1063 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodCantThrowException));
1064 }
1065 if (!tree.typarams.isEmpty()) {
1066 log.error(tree,
1067 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeGeneric));
1068 }
1069 if (tree.sym.isStatic()) {
1070 log.error(tree,
1071 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeStatic));
1072 }
1073 }
1074
1075 if (tree.name == names.init) {
1076 // if this a constructor other than the canonical one
1077 if ((tree.sym.flags_field & RECORD) == 0) {
1078 JCMethodInvocation app = TreeInfo.firstConstructorCall(tree);
1079 if (app == null ||
1080 TreeInfo.name(app.meth) != names._this ||
1081 !checkFirstConstructorStat(app, tree, false)) {
1082 log.error(tree, Errors.FirstStatementMustBeCallToAnotherConstructor(env.enclClass.sym));
1083 }
1084 } else {
1085 // but if it is the canonical:
1086
1087 /* if user generated, then it shouldn't:
1088 * - have an accessibility stricter than that of the record type
1089 * - explicitly invoke any other constructor
1090 */
1091 if ((tree.sym.flags_field & GENERATEDCONSTR) == 0) {
1092 if (Check.protection(m.flags()) > Check.protection(env.enclClass.sym.flags())) {
1093 log.error(tree,
1094 (env.enclClass.sym.flags() & AccessFlags) == 0 ?
1095 Errors.InvalidCanonicalConstructorInRecord(
1170 if (tree.defaultValue != null) {
1171 if ((owner.flags() & ANNOTATION) == 0)
1172 log.error(tree.pos(),
1173 Errors.DefaultAllowedInIntfAnnotationMember);
1174 }
1175 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1176 log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract);
1177 } else {
1178 if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1179 if ((owner.flags() & INTERFACE) != 0) {
1180 log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1181 } else {
1182 log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1183 }
1184 } else if ((tree.mods.flags & NATIVE) != 0) {
1185 log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1186 }
1187 // Add an implicit super() call unless an explicit call to
1188 // super(...) or this(...) is given
1189 // or we are compiling class java.lang.Object.
1190 if (tree.name == names.init && owner.type != syms.objectType) {
1191 JCBlock body = tree.body;
1192 if (body.stats.isEmpty() ||
1193 TreeInfo.getConstructorInvocationName(body.stats, names) == names.empty) {
1194 JCStatement supCall = make.at(body.pos).Exec(make.Apply(List.nil(),
1195 make.Ident(names._super), make.Idents(List.nil())));
1196 body.stats = body.stats.prepend(supCall);
1197 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1198 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1199 TreeInfo.isSuperCall(body.stats.head)) {
1200 // enum constructors are not allowed to call super
1201 // directly, so make sure there aren't any super calls
1202 // in enum constructors, except in the compiler
1203 // generated one.
1204 log.error(tree.body.stats.head.pos(),
1205 Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1206 }
1207 if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1208 List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1209 List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1210 if (!initParamNames.equals(recordComponentNames)) {
1211 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1212 Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1213 }
1214 if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1215 log.error(tree,
1216 Errors.InvalidCanonicalConstructorInRecord(
1217 TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical,
1218 env.enclClass.sym.name,
1219 Fragments.ThrowsClauseNotAllowedForCanonicalConstructor(
1220 TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical)));
1221 }
1222 }
1223 }
1224
1225 // Attribute all type annotations in the body
1273 annotate.queueScanTreeAndTypeAnnotate(tree.init, env, tree.sym, tree.pos());
1274 annotate.flush();
1275 }
1276 }
1277
1278 VarSymbol v = tree.sym;
1279 Lint lint = env.info.lint.augment(v);
1280 Lint prevLint = chk.setLint(lint);
1281
1282 // Check that the variable's declared type is well-formed.
1283 boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
1284 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
1285 (tree.sym.flags() & PARAMETER) != 0;
1286 chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1287
1288 try {
1289 v.getConstValue(); // ensure compile-time constant initializer is evaluated
1290 deferredLintHandler.flush(tree.pos());
1291 chk.checkDeprecatedAnnotation(tree.pos(), v);
1292
1293 if (tree.init != null) {
1294 if ((v.flags_field & FINAL) == 0 ||
1295 !memberEnter.needsLazyConstValue(tree.init)) {
1296 // Not a compile-time constant
1297 // Attribute initializer in a new environment
1298 // with the declared variable as owner.
1299 // Check that initializer conforms to variable's declared type.
1300 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1301 initEnv.info.lint = lint;
1302 // In order to catch self-references, we set the variable's
1303 // declaration position to maximal possible value, effectively
1304 // marking the variable as undefined.
1305 initEnv.info.enclVar = v;
1306 attribExpr(tree.init, initEnv, v.type);
1307 if (tree.isImplicitlyTyped()) {
1308 //fixup local variable type
1309 v.type = chk.checkLocalVarType(tree, tree.init.type, tree.name);
1310 }
1311 }
1312 if (tree.isImplicitlyTyped()) {
1313 setSyntheticVariableType(tree, v.type);
1314 }
1315 }
1316 result = tree.type = v.type;
1317 if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1318 if (isNonArgsMethodInObject(v.name)) {
1319 log.error(tree, Errors.IllegalRecordComponentName(v));
1320 }
1321 }
1322 }
1323 finally {
1324 chk.setLint(prevLint);
1325 }
1326 }
1327
1328 private boolean isNonArgsMethodInObject(Name name) {
1329 for (Symbol s : syms.objectType.tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) {
1330 if (s.type.getParameterTypes().isEmpty()) {
1331 return true;
1332 }
1333 }
1334 return false;
1335 }
1336
1337 Fragment canInferLocalVarType(JCVariableDecl tree) {
1338 LocalInitScanner lis = new LocalInitScanner();
1339 lis.scan(tree.init);
1340 return lis.badInferenceMsg;
1341 }
1342
1343 static class LocalInitScanner extends TreeScanner {
1344 Fragment badInferenceMsg = null;
1345 boolean needsTarget = true;
1346
1347 @Override
1348 public void visitNewArray(JCNewArray tree) {
1349 if (tree.elemtype == null && needsTarget) {
1350 badInferenceMsg = Fragments.LocalArrayMissingTarget;
1351 }
1352 }
1353
1354 @Override
1507 if (!breaksOutOf(tree, tree.body)) {
1508 //include condition's body when false after the while, if cannot get out of the loop
1509 condBindings.bindingsWhenFalse.forEach(env.info.scope::enter);
1510 condBindings.bindingsWhenFalse.forEach(BindingSymbol::preserveBinding);
1511 }
1512 }
1513
1514 public void visitForeachLoop(JCEnhancedForLoop tree) {
1515 Env<AttrContext> loopEnv =
1516 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1517
1518 try {
1519 //the Formal Parameter of a for-each loop is not in the scope when
1520 //attributing the for-each expression; we mimic this by attributing
1521 //the for-each expression first (against original scope).
1522 Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
1523 chk.checkNonVoid(tree.pos(), exprType);
1524 tree.elementType = types.elemtype(exprType); // perhaps expr is an array?
1525 if (tree.elementType == null) {
1526 // or perhaps expr implements Iterable<T>?
1527 Type base = types.asSuper(exprType, syms.iterableType.tsym);
1528 if (base == null) {
1529 log.error(tree.expr.pos(),
1530 Errors.ForeachNotApplicableToType(exprType,
1531 Fragments.TypeReqArrayOrIterable));
1532 tree.elementType = types.createErrorType(exprType);
1533 } else {
1534 List<Type> iterableParams = base.allparams();
1535 tree.elementType = iterableParams.isEmpty()
1536 ? syms.objectType
1537 : types.wildUpperBound(iterableParams.head);
1538
1539 // Check the return type of the method iterator().
1540 // This is the bare minimum we need to verify to make sure code generation doesn't crash.
1541 Symbol iterSymbol = rs.resolveInternalMethod(tree.pos(),
1542 loopEnv, types.skipTypeVars(exprType, false), names.iterator, List.nil(), List.nil());
1543 if (types.asSuper(iterSymbol.type.getReturnType(), syms.iteratorType.tsym) == null) {
1544 log.error(tree.pos(),
1545 Errors.ForeachNotApplicableToType(exprType, Fragments.TypeReqArrayOrIterable));
1546 }
1547 }
1548 }
1549 if (tree.varOrRecordPattern instanceof JCVariableDecl jcVariableDecl) {
1550 if (jcVariableDecl.isImplicitlyTyped()) {
1551 Type inferredType = chk.checkLocalVarType(jcVariableDecl, tree.elementType, jcVariableDecl.name);
1552 setSyntheticVariableType(jcVariableDecl, inferredType);
1553 }
1554 attribStat(jcVariableDecl, loopEnv);
1555 chk.checkType(tree.expr.pos(), tree.elementType, jcVariableDecl.sym.type);
1556
1557 loopEnv.tree = tree; // before, we were not in loop!
1558 attribStat(tree.body, loopEnv);
1559 } else {
1560 Assert.check(tree.getDeclarationKind() == EnhancedForLoopTree.DeclarationKind.PATTERN);
1561 JCRecordPattern jcRecordPattern = (JCRecordPattern) tree.varOrRecordPattern;
1562
1563 attribExpr(jcRecordPattern, loopEnv, tree.elementType);
1865 // where
1866 /** Return the selected enumeration constant symbol, or null. */
1867 private Symbol enumConstant(JCTree tree, Type enumType) {
1868 if (tree.hasTag(IDENT)) {
1869 JCIdent ident = (JCIdent)tree;
1870 Name name = ident.name;
1871 for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1872 if (sym.kind == VAR) {
1873 Symbol s = ident.sym = sym;
1874 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1875 ident.type = s.type;
1876 return ((s.flags_field & Flags.ENUM) == 0)
1877 ? null : s;
1878 }
1879 }
1880 }
1881 return null;
1882 }
1883
1884 public void visitSynchronized(JCSynchronized tree) {
1885 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1886 if (env.info.lint.isEnabled(LintCategory.SYNCHRONIZATION) && isValueBased(tree.lock.type)) {
1887 log.warning(LintCategory.SYNCHRONIZATION, tree.pos(), Warnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
1888 }
1889 attribStat(tree.body, env);
1890 result = null;
1891 }
1892 // where
1893 private boolean isValueBased(Type t) {
1894 return t != null && t.tsym != null && (t.tsym.flags() & VALUE_BASED) != 0;
1895 }
1896
1897
1898 public void visitTry(JCTry tree) {
1899 // Create a new local environment with a local
1900 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1901 try {
1902 boolean isTryWithResource = tree.resources.nonEmpty();
1903 // Create a nested environment for attributing the try block if needed
1904 Env<AttrContext> tryEnv = isTryWithResource ?
1905 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1956 chk.checkType(c.param.vartype.pos(),
1957 chk.checkClassType(c.param.vartype.pos(), ctype),
1958 syms.throwableType);
1959 attribStat(c.body, catchEnv);
1960 } finally {
1961 catchEnv.info.scope.leave();
1962 }
1963 }
1964
1965 // Attribute finalizer
1966 if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1967 result = null;
1968 }
1969 finally {
1970 localEnv.info.scope.leave();
1971 }
1972 }
1973
1974 void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
1975 if (!resource.isErroneous() &&
1976 types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
1977 !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
1978 Symbol close = syms.noSymbol;
1979 Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
1980 try {
1981 close = rs.resolveQualifiedMethod(pos,
1982 env,
1983 types.skipTypeVars(resource, false),
1984 names.close,
1985 List.nil(),
1986 List.nil());
1987 }
1988 finally {
1989 log.popDiagnosticHandler(discardHandler);
1990 }
1991 if (close.kind == MTH &&
1992 close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
1993 chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
1994 env.info.lint.isEnabled(LintCategory.TRY)) {
1995 log.warning(LintCategory.TRY, pos, Warnings.TryResourceThrowsInterruptedExc(resource));
1996 }
2145 if (unboxedTypes.stream().allMatch(t -> t.isPrimitive())) {
2146 // If one arm has an integer subrange type (i.e., byte,
2147 // short, or char), and the other is an integer constant
2148 // that fits into the subrange, return the subrange type.
2149 for (Type type : unboxedTypes) {
2150 if (!type.getTag().isStrictSubRangeOf(INT)) {
2151 continue;
2152 }
2153 if (unboxedTypes.stream().filter(t -> t != type).allMatch(t -> t.hasTag(INT) && types.isAssignable(t, type)))
2154 return type.baseType();
2155 }
2156
2157 for (TypeTag tag : primitiveTags) {
2158 Type candidate = syms.typeOfTag[tag.ordinal()];
2159 if (unboxedTypes.stream().allMatch(t -> types.isSubtype(t, candidate))) {
2160 return candidate;
2161 }
2162 }
2163 }
2164
2165 // Those were all the cases that could result in a primitive
2166 condTypes = condTypes.stream()
2167 .map(t -> t.isPrimitive() ? types.boxedClass(t).type : 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))
2179 .collect(List.collector());
2180
2181 // both are known to be reference types. 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) {
2600 : env.enclClass.sym.type;
2601 Symbol msym = TreeInfo.symbol(tree.meth);
2602 restype = adjustMethodReturnType(msym, qualifier, methName, argtypes, restype);
2603
2604 chk.checkRefTypes(tree.typeargs, typeargtypes);
2605
2606 // Check that value of resulting type is admissible in the
2607 // current context. Also, capture the return type
2608 Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true);
2609 result = check(tree, capturedRes, KindSelector.VAL, resultInfo);
2610 }
2611 chk.validate(tree.typeargs, localEnv);
2612 }
2613 //where
2614 Type adjustMethodReturnType(Symbol msym, Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
2615 if (msym != null &&
2616 (msym.owner == syms.objectType.tsym || msym.owner.isInterface()) &&
2617 methodName == names.getClass &&
2618 argtypes.isEmpty()) {
2619 // as a special case, x.getClass() has type Class<? extends |X|>
2620 return new ClassType(restype.getEnclosingType(),
2621 List.of(new WildcardType(types.erasure(qualifierType.baseType()),
2622 BoundKind.EXTENDS,
2623 syms.boundClass)),
2624 restype.tsym,
2625 restype.getMetadata());
2626 } else if (msym != null &&
2627 msym.owner == syms.arrayClass &&
2628 methodName == names.clone &&
2629 types.isArray(qualifierType)) {
2630 // as a special case, array.clone() has a result that is
2631 // the same as static type of the array being cloned
2632 return qualifierType;
2633 } else {
2634 return restype;
2635 }
2636 }
2637
2638 /** Check that given application node appears as first statement
2639 * in a constructor call.
2640 * @param tree The application node
2641 * @param enclMethod The enclosing method of the application.
2642 * @param error Should an error be issued?
2643 */
2644 boolean checkFirstConstructorStat(JCMethodInvocation tree, JCMethodDecl enclMethod, boolean error) {
2645 if (enclMethod != null && enclMethod.name == names.init) {
2646 JCBlock body = enclMethod.body;
2647 if (body.stats.head.hasTag(EXEC) &&
2648 ((JCExpressionStatement) body.stats.head).expr == tree)
2649 return true;
2650 }
2651 if (error) {
2652 log.error(tree.pos(),
2653 Errors.CallMustBeFirstStmtInCtor(TreeInfo.name(tree.meth)));
2654 }
2655 return false;
2656 }
2657
2658 /** Obtain a method type with given argument types.
2659 */
2660 Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
2661 MethodType mt = new MethodType(argtypes, restype, List.nil(), syms.methodClass);
2662 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
2663 }
2664
2665 public void visitNewClass(final JCNewClass tree) {
2774 }
2775
2776 // Attribute constructor arguments.
2777 ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2778 final KindSelector pkind =
2779 attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
2780 List<Type> argtypes = argtypesBuf.toList();
2781 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
2782
2783 if (clazztype.hasTag(CLASS) || clazztype.hasTag(ERROR)) {
2784 // Enums may not be instantiated except implicitly
2785 if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 &&
2786 (!env.tree.hasTag(VARDEF) ||
2787 (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 ||
2788 ((JCVariableDecl) env.tree).init != tree))
2789 log.error(tree.pos(), Errors.EnumCantBeInstantiated);
2790
2791 boolean isSpeculativeDiamondInferenceRound = TreeInfo.isDiamond(tree) &&
2792 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2793 boolean skipNonDiamondPath = false;
2794 // Check that class is not abstract
2795 if (cdef == null && !isSpeculativeDiamondInferenceRound && // class body may be nulled out in speculative tree copy
2796 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
2797 log.error(tree.pos(),
2798 Errors.AbstractCantBeInstantiated(clazztype.tsym));
2799 skipNonDiamondPath = true;
2800 } else if (cdef != null && clazztype.tsym.isInterface()) {
2801 // Check that no constructor arguments are given to
2802 // anonymous classes implementing an interface
2803 if (!argtypes.isEmpty())
2804 log.error(tree.args.head.pos(), Errors.AnonClassImplIntfNoArgs);
2805
2806 if (!typeargtypes.isEmpty())
2807 log.error(tree.typeargs.head.pos(), Errors.AnonClassImplIntfNoTypeargs);
2808
2809 // Error recovery: pretend no arguments were supplied.
2810 argtypes = List.nil();
2811 typeargtypes = List.nil();
2812 skipNonDiamondPath = true;
2813 }
2814 if (TreeInfo.isDiamond(tree)) {
2815 ClassType site = new ClassType(clazztype.getEnclosingType(),
2816 clazztype.tsym.type.getTypeArguments(),
2817 clazztype.tsym,
2818 clazztype.getMetadata());
2819
2820 Env<AttrContext> diamondEnv = localEnv.dup(tree);
2821 diamondEnv.info.selectSuper = cdef != null || tree.classDeclRemoved();
2822 diamondEnv.info.pendingResolutionPhase = null;
2823
2824 //if the type of the instance creation expression is a class type
2825 //apply method resolution inference (JLS 15.12.2.7). The return type
2826 //of the resolved constructor will be a partially instantiated type
2827 Symbol constructor = rs.resolveDiamond(tree.pos(),
2828 diamondEnv,
2829 site,
2830 argtypes,
2831 typeargtypes);
2832 tree.constructor = constructor.baseSymbol();
2833
2834 final TypeSymbol csym = clazztype.tsym;
2835 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes),
2836 diamondContext(tree, csym, resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
2837 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
2838 constructorType = checkId(tree, site,
2952 this.resultInfo = prevResult;
2953 }
2954 });
2955 } else {
2956 if (isDiamond && clazztype.hasTag(CLASS)) {
2957 List<Type> invalidDiamondArgs = chk.checkDiamondDenotable((ClassType)clazztype);
2958 if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
2959 // One or more types inferred in the previous steps is non-denotable.
2960 Fragment fragment = Diamond(clazztype.tsym);
2961 log.error(tree.clazz.pos(),
2962 Errors.CantApplyDiamond1(
2963 fragment,
2964 invalidDiamondArgs.size() > 1 ?
2965 DiamondInvalidArgs(invalidDiamondArgs, fragment) :
2966 DiamondInvalidArg(invalidDiamondArgs, fragment)));
2967 }
2968 // For <>(){}, inferred types must also be accessible.
2969 for (Type t : clazztype.getTypeArguments()) {
2970 rs.checkAccessibleType(env, t);
2971 }
2972 }
2973
2974 // If we already errored, be careful to avoid a further avalanche. ErrorType answers
2975 // false for isInterface call even when the original type is an interface.
2976 boolean implementing = clazztype.tsym.isInterface() ||
2977 clazztype.isErroneous() && !clazztype.getOriginalType().hasTag(NONE) &&
2978 clazztype.getOriginalType().tsym.isInterface();
2979
2980 if (implementing) {
2981 cdef.implementing = List.of(clazz);
2982 } else {
2983 cdef.extending = clazz;
2984 }
2985
2986 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
2987 rs.isSerializable(clazztype)) {
2988 localEnv.info.isSerializable = true;
2989 }
2990
2991 attribStat(cdef, localEnv);
3024 result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK));
3025 chk.validate(tree.typeargs, localEnv);
3026 }
3027
3028 CheckContext diamondContext(JCNewClass clazz, TypeSymbol tsym, CheckContext checkContext) {
3029 return new Check.NestedCheckContext(checkContext) {
3030 @Override
3031 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
3032 enclosingContext.report(clazz.clazz,
3033 diags.fragment(Fragments.CantApplyDiamond1(Fragments.Diamond(tsym), details)));
3034 }
3035 };
3036 }
3037
3038 /** Make an attributed null check tree.
3039 */
3040 public JCExpression makeNullCheck(JCExpression arg) {
3041 // optimization: new Outer() can never be null; skip null check
3042 if (arg.getTag() == NEWCLASS)
3043 return arg;
3044 // optimization: X.this is never null; skip null check
3045 Name name = TreeInfo.name(arg);
3046 if (name == names._this || name == names._super) return arg;
3047
3048 JCTree.Tag optag = NULLCHK;
3049 JCUnary tree = make.at(arg.pos).Unary(optag, arg);
3050 tree.operator = operators.resolveUnary(arg, optag, arg.type);
3051 tree.type = arg.type;
3052 return tree;
3053 }
3054
3055 public void visitNewArray(JCNewArray tree) {
3056 Type owntype = types.createErrorType(tree.type);
3057 Env<AttrContext> localEnv = env.dup(tree);
3058 Type elemtype;
3059 if (tree.elemtype != null) {
3060 elemtype = attribType(tree.elemtype, localEnv);
3061 chk.validate(tree.elemtype, localEnv);
3062 owntype = elemtype;
3063 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
3513 *
3514 * The owner of this environment is a method symbol. If the current owner
3515 * is not a method, for example if the lambda is used to initialize
3516 * a field, then if the field is:
3517 *
3518 * - an instance field, we use the first constructor.
3519 * - a static field, we create a fake clinit method.
3520 */
3521 public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
3522 Env<AttrContext> lambdaEnv;
3523 Symbol owner = env.info.scope.owner;
3524 if (owner.kind == VAR && owner.owner.kind == TYP) {
3525 //field initializer
3526 ClassSymbol enclClass = owner.enclClass();
3527 Symbol newScopeOwner = env.info.scope.owner;
3528 /* if the field isn't static, then we can get the first constructor
3529 * and use it as the owner of the environment. This is what
3530 * LTM code is doing to look for type annotations so we are fine.
3531 */
3532 if ((owner.flags() & STATIC) == 0) {
3533 for (Symbol s : enclClass.members_field.getSymbolsByName(names.init)) {
3534 newScopeOwner = s;
3535 break;
3536 }
3537 } else {
3538 /* if the field is static then we need to create a fake clinit
3539 * method, this method can later be reused by LTM.
3540 */
3541 MethodSymbol clinit = clinits.get(enclClass);
3542 if (clinit == null) {
3543 Type clinitType = new MethodType(List.nil(),
3544 syms.voidType, List.nil(), syms.methodClass);
3545 clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE,
3546 names.clinit, clinitType, enclClass);
3547 clinit.params = List.nil();
3548 clinits.put(enclClass, clinit);
3549 }
3550 newScopeOwner = clinit;
3551 }
3552 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(newScopeOwner)));
3553 } else {
3576
3577 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3578 exprType = chk.checkConstructorRefType(that.expr, exprType);
3579 if (!exprType.isErroneous() &&
3580 exprType.isRaw() &&
3581 that.typeargs != null) {
3582 log.error(that.expr.pos(),
3583 Errors.InvalidMref(Kinds.kindName(that.getMode()),
3584 Fragments.MrefInferAndExplicitParams));
3585 exprType = types.createErrorType(exprType);
3586 }
3587 }
3588
3589 if (exprType.isErroneous()) {
3590 //if the qualifier expression contains problems,
3591 //give up attribution of method reference
3592 result = that.type = exprType;
3593 return;
3594 }
3595
3596 if (TreeInfo.isStaticSelector(that.expr, names)) {
3597 //if the qualifier is a type, validate it; raw warning check is
3598 //omitted as we don't know at this stage as to whether this is a
3599 //raw selector (because of inference)
3600 chk.validate(that.expr, env, false);
3601 } else {
3602 Symbol lhsSym = TreeInfo.symbol(that.expr);
3603 localEnv.info.selectSuper = lhsSym != null && lhsSym.name == names._super;
3604 }
3605 //attrib type-arguments
3606 List<Type> typeargtypes = List.nil();
3607 if (that.typeargs != null) {
3608 typeargtypes = attribTypes(that.typeargs, localEnv);
3609 }
3610
3611 boolean isTargetSerializable =
3612 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3613 rs.isSerializable(pt());
3614 TargetInfo targetInfo = getTargetInfo(that, resultInfo, null);
3615 Type currentTarget = targetInfo.target;
3616 Type desc = targetInfo.descriptor;
3617
3618 setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
3619 List<Type> argtypes = desc.getParameterTypes();
3620 Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
3621
3622 if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
3666 targetError ?
3667 Fragments.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag) :
3668 Errors.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag));
3669
3670 if (targetError && currentTarget == Type.recoveryType) {
3671 //a target error doesn't make sense during recovery stage
3672 //as we don't know what actual parameter types are
3673 result = that.type = currentTarget;
3674 return;
3675 } else {
3676 if (targetError) {
3677 resultInfo.checkContext.report(that, diag);
3678 } else {
3679 log.report(diag);
3680 }
3681 result = that.type = types.createErrorType(currentTarget);
3682 return;
3683 }
3684 }
3685
3686 that.sym = refSym.isConstructor() ? refSym.baseSymbol() : refSym;
3687 that.kind = lookupHelper.referenceKind(that.sym);
3688 that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
3689
3690 if (desc.getReturnType() == Type.recoveryType) {
3691 // stop here
3692 result = that.type = currentTarget;
3693 return;
3694 }
3695
3696 if (!env.info.attributionMode.isSpeculative && that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3697 Type enclosingType = exprType.getEnclosingType();
3698 if (enclosingType != null && enclosingType.hasTag(CLASS)) {
3699 // Check for the existence of an appropriate outer instance
3700 rs.resolveImplicitThis(that.pos(), env, exprType);
3701 }
3702 }
3703
3704 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
3705
3706 if (that.getMode() == ReferenceMode.INVOKE &&
4344 }
4345
4346 public void visitSelect(JCFieldAccess tree) {
4347 // Determine the expected kind of the qualifier expression.
4348 KindSelector skind = KindSelector.NIL;
4349 if (tree.name == names._this || tree.name == names._super ||
4350 tree.name == names._class)
4351 {
4352 skind = KindSelector.TYP;
4353 } else {
4354 if (pkind().contains(KindSelector.PCK))
4355 skind = KindSelector.of(skind, KindSelector.PCK);
4356 if (pkind().contains(KindSelector.TYP))
4357 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4358 if (pkind().contains(KindSelector.VAL_MTH))
4359 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4360 }
4361
4362 // Attribute the qualifier expression, and determine its symbol (if any).
4363 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4364 if (!pkind().contains(KindSelector.TYP_PCK))
4365 site = capture(site); // Capture field access
4366
4367 // don't allow T.class T[].class, etc
4368 if (skind == KindSelector.TYP) {
4369 Type elt = site;
4370 while (elt.hasTag(ARRAY))
4371 elt = ((ArrayType)elt).elemtype;
4372 if (elt.hasTag(TYPEVAR)) {
4373 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4374 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4375 tree.sym = tree.type.tsym;
4376 return ;
4377 }
4378 }
4379
4380 // If qualifier symbol is a type or `super', assert `selectSuper'
4381 // for the selection. This is relevant for determining whether
4382 // protected symbols are accessible.
4383 Symbol sitesym = TreeInfo.symbol(tree.selected);
4384 boolean selectSuperPrev = env.info.selectSuper;
4385 env.info.selectSuper =
4386 sitesym != null &&
4387 sitesym.name == names._super;
4388
4389 // Determine the symbol represented by the selection.
4390 env.info.pendingResolutionPhase = null;
4391 Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
4392 if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
4393 log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym));
4394 sym = syms.errSymbol;
4395 }
4396 if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
4460 } else if (sym.kind != ERR &&
4461 (sym.flags() & STATIC) != 0 &&
4462 sym.name != names._class) {
4463 // If the qualified item is not a type and the selected item is static, report
4464 // a warning. Make allowance for the class of an array type e.g. Object[].class)
4465 if (!sym.owner.isAnonymous()) {
4466 chk.warnStatic(tree, Warnings.StaticNotQualifiedByType(sym.kind.kindName(), sym.owner));
4467 } else {
4468 chk.warnStatic(tree, Warnings.StaticNotQualifiedByType2(sym.kind.kindName()));
4469 }
4470 }
4471
4472 // If we are selecting an instance member via a `super', ...
4473 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
4474
4475 // Check that super-qualified symbols are not abstract (JLS)
4476 rs.checkNonAbstract(tree.pos(), sym);
4477
4478 if (site.isRaw()) {
4479 // Determine argument types for site.
4480 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
4481 if (site1 != null) site = site1;
4482 }
4483 }
4484
4485 if (env.info.isSerializable) {
4486 chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4487 }
4488
4489 env.info.selectSuper = selectSuperPrev;
4490 result = checkId(tree, site, sym, env, resultInfo);
4491 }
4492 //where
4493 /** Determine symbol referenced by a Select expression,
4494 *
4495 * @param tree The select tree.
4496 * @param site The type of the selected expression,
4497 * @param env The current environment.
4498 * @param resultInfo The current result.
4499 */
4500 private Symbol selectSym(JCFieldAccess tree,
4503 Env<AttrContext> env,
4504 ResultInfo resultInfo) {
4505 DiagnosticPosition pos = tree.pos();
4506 Name name = tree.name;
4507 switch (site.getTag()) {
4508 case PACKAGE:
4509 return rs.accessBase(
4510 rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind),
4511 pos, location, site, name, true);
4512 case ARRAY:
4513 case CLASS:
4514 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
4515 return rs.resolveQualifiedMethod(
4516 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
4517 } else if (name == names._this || name == names._super) {
4518 return rs.resolveSelf(pos, env, site.tsym, name);
4519 } else if (name == names._class) {
4520 // In this case, we have already made sure in
4521 // visitSelect that qualifier expression is a type.
4522 return syms.getClassField(site, types);
4523 } else {
4524 // We are seeing a plain identifier as selector.
4525 Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind);
4526 sym = rs.accessBase(sym, pos, location, site, name, true);
4527 return sym;
4528 }
4529 case WILDCARD:
4530 throw new AssertionError(tree);
4531 case TYPEVAR:
4532 // Normally, site.getUpperBound() shouldn't be null.
4533 // It should only happen during memberEnter/attribBase
4534 // when determining the supertype which *must* be
4535 // done before attributing the type variables. In
4536 // other words, we are seeing this illegal program:
4537 // class B<T> extends A<T.foo> {}
4538 Symbol sym = (site.getUpperBound() != null)
4539 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
4540 : null;
4541 if (sym == null) {
4542 log.error(pos, Errors.TypeVarCantBeDeref);
4606 if (resultInfo.pkind.contains(KindSelector.POLY)) {
4607 return attrRecover.recoverMethodInvocation(tree, site, sym, env, resultInfo);
4608 } else {
4609 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
4610 }
4611 }
4612
4613 Type checkIdInternal(JCTree tree,
4614 Type site,
4615 Symbol sym,
4616 Type pt,
4617 Env<AttrContext> env,
4618 ResultInfo resultInfo) {
4619 if (pt.isErroneous()) {
4620 return types.createErrorType(site);
4621 }
4622 Type owntype; // The computed type of this identifier occurrence.
4623 switch (sym.kind) {
4624 case TYP:
4625 // For types, the computed type equals the symbol's type,
4626 // except for two situations:
4627 owntype = sym.type;
4628 if (owntype.hasTag(CLASS)) {
4629 chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
4630 Type ownOuter = owntype.getEnclosingType();
4631
4632 // (a) 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 // (b) 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());
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 tree.type = 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))) {
4702 break;
4703 case MTH: {
4704 owntype = checkMethod(site, sym,
4705 new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext, resultInfo.checkMode),
4706 env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
4707 resultInfo.pt.getTypeArguments());
4708 break;
4709 }
4710 case PCK: case ERR:
4711 owntype = sym.type;
4712 break;
4713 default:
4714 throw new AssertionError("unexpected kind: " + sym.kind +
4715 " in tree " + tree);
4716 }
4717
4718 // Emit a `deprecation' warning if symbol is deprecated.
4719 // (for constructors (but not for constructor references), the error
4720 // was given when the constructor was resolved)
4721
4722 if (sym.name != names.init || tree.hasTag(REFERENCE)) {
4723 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
4724 chk.checkSunAPI(tree.pos(), sym);
4725 chk.checkProfile(tree.pos(), sym);
4726 chk.checkPreview(tree.pos(), env.info.scope.owner, sym);
4727 }
4728
4729 // If symbol is a variable, check that its type and
4730 // kind are compatible with the prototype and protokind.
4731 return check(tree, owntype, sym.kind.toSelector(), resultInfo);
4732 }
4733
4734 /** Check that variable is initialized and evaluate the variable's
4735 * initializer, if not yet done. Also check that variable is not
4736 * referenced before it is defined.
4737 * @param tree The tree making up the variable reference.
4738 * @param env The current environment.
4739 * @param v The variable's symbol.
4740 */
4741 private void checkInit(JCTree tree,
4742 Env<AttrContext> env,
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 visitLiteral(JCLiteral tree) {
4977 result = check(tree, litType(tree.typetag).constType(tree.value),
4978 KindSelector.VAL, resultInfo);
4979 }
4980 //where
4981 /** Return the type of a literal with given type tag.
4982 */
4983 Type litType(TypeTag tag) {
4984 return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
4985 }
4986
4987 public void visitTypeIdent(JCPrimitiveTypeTree tree) {
4988 result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
4989 }
4990
4991 public void visitTypeArray(JCArrayTypeTree tree) {
4992 Type etype = attribType(tree.elemtype, env);
4993 Type type = new ArrayType(etype, syms.arrayClass);
4994 result = check(tree, type, KindSelector.TYP, resultInfo);
4995 }
5022 }
5023 // Compute the proper generic outer
5024 Type clazzOuter = clazztype.getEnclosingType();
5025 if (clazzOuter.hasTag(CLASS)) {
5026 Type site;
5027 JCExpression clazz = TreeInfo.typeIn(tree.clazz);
5028 if (clazz.hasTag(IDENT)) {
5029 site = env.enclClass.sym.type;
5030 } else if (clazz.hasTag(SELECT)) {
5031 site = ((JCFieldAccess) clazz).selected.type;
5032 } else throw new AssertionError(""+tree);
5033 if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
5034 if (site.hasTag(CLASS))
5035 site = types.asOuterSuper(site, clazzOuter.tsym);
5036 if (site == null)
5037 site = types.erasure(clazzOuter);
5038 clazzOuter = site;
5039 }
5040 }
5041 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
5042 clazztype.getMetadata());
5043 } else {
5044 if (formals.length() != 0) {
5045 log.error(tree.pos(),
5046 Errors.WrongNumberTypeArgs(Integer.toString(formals.length())));
5047 } else {
5048 log.error(tree.pos(), Errors.TypeDoesntTakeParams(clazztype.tsym));
5049 }
5050 owntype = types.createErrorType(tree.type);
5051 }
5052 }
5053 result = check(tree, owntype, KindSelector.TYP, resultInfo);
5054 }
5055
5056 public void visitTypeUnion(JCTypeUnion tree) {
5057 ListBuffer<Type> multicatchTypes = new ListBuffer<>();
5058 ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
5059 for (JCExpression typeTree : tree.alternatives) {
5060 Type ctype = attribType(typeTree, env);
5061 ctype = chk.checkType(typeTree.pos(),
5062 chk.checkClassType(typeTree.pos(), ctype),
5149 if (bounds.length() == 0) {
5150 return syms.objectType;
5151 } else if (bounds.length() == 1) {
5152 return bounds.head.type;
5153 } else {
5154 Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
5155 // ... the variable's bound is a class type flagged COMPOUND
5156 // (see comment for TypeVar.bound).
5157 // In this case, generate a class tree that represents the
5158 // bound class, ...
5159 JCExpression extending;
5160 List<JCExpression> implementing;
5161 if (!bounds.head.type.isInterface()) {
5162 extending = bounds.head;
5163 implementing = bounds.tail;
5164 } else {
5165 extending = null;
5166 implementing = bounds;
5167 }
5168 JCClassDecl cd = make.at(tree).ClassDef(
5169 make.Modifiers(PUBLIC | ABSTRACT),
5170 names.empty, List.nil(),
5171 extending, implementing, List.nil());
5172
5173 ClassSymbol c = (ClassSymbol)owntype.tsym;
5174 Assert.check((c.flags() & COMPOUND) != 0);
5175 cd.sym = c;
5176 c.sourcefile = env.toplevel.sourcefile;
5177
5178 // ... and attribute the bound class
5179 c.flags_field |= UNATTRIBUTED;
5180 Env<AttrContext> cenv = enter.classEnv(cd, env);
5181 typeEnvs.put(c, cenv);
5182 attribClass(c);
5183 return owntype;
5184 }
5185 }
5186
5187 public void visitWildcard(JCWildcard tree) {
5188 //- System.err.println("visitWildcard("+tree+");");//DEBUG
5189 Type type = (tree.kind.kind == BoundKind.UNBOUND)
5190 ? syms.objectType
5191 : attribType(tree.inner, env);
5192 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
5193 tree.kind.kind,
5194 syms.boundClass),
5195 KindSelector.TYP, resultInfo);
5196 }
5197
5198 public void visitAnnotation(JCAnnotation tree) {
5199 Assert.error("should be handled in annotate");
5200 }
5201
5202 @Override
5203 public void visitModifiers(JCModifiers tree) {
5204 //error recovery only:
5205 Assert.check(resultInfo.pkind == KindSelector.ERR);
5206
5207 attribAnnotationTypes(tree.annotations, env);
5208 }
5209
5210 public void visitAnnotatedType(JCAnnotatedType tree) {
5211 attribAnnotationTypes(tree.annotations, env);
5212 Type underlyingType = attribType(tree.underlyingType, env);
5290
5291 try {
5292 deferredLintHandler.flush(env.tree.pos());
5293 attrib.accept(env);
5294 } finally {
5295 log.useSource(prev);
5296 chk.setLint(prevLint);
5297 }
5298 }
5299
5300 /** Main method: attribute class definition associated with given class symbol.
5301 * reporting completion failures at the given position.
5302 * @param pos The source position at which completion errors are to be
5303 * reported.
5304 * @param c The class symbol whose definition will be attributed.
5305 */
5306 public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
5307 try {
5308 annotate.flush();
5309 attribClass(c);
5310 } catch (CompletionFailure ex) {
5311 chk.completionError(pos, ex);
5312 }
5313 }
5314
5315 /** Attribute class definition associated with given class symbol.
5316 * @param c The class symbol whose definition will be attributed.
5317 */
5318 void attribClass(ClassSymbol c) throws CompletionFailure {
5319 if (c.type.hasTag(ERROR)) return;
5320
5321 // Check for cycles in the inheritance graph, which can arise from
5322 // ill-formed class files.
5323 chk.checkNonCyclic(null, c.type);
5324
5325 Type st = types.supertype(c.type);
5326 if ((c.flags_field & Flags.COMPOUND) == 0 &&
5327 (c.flags_field & Flags.SUPER_OWNER_ATTRIBUTED) == 0) {
5328 // First, attribute superclass.
5329 if (st.hasTag(CLASS))
5410 .filter(s -> s.tsym.isSealed())
5411 .map(s -> (ClassSymbol) s.tsym)
5412 .collect(List.collector());
5413
5414 if (sealedSupers.isEmpty()) {
5415 if ((c.flags_field & Flags.NON_SEALED) != 0) {
5416 boolean hasErrorSuper = false;
5417
5418 hasErrorSuper |= types.directSupertypes(c.type)
5419 .stream()
5420 .anyMatch(s -> s.tsym.kind == Kind.ERR);
5421
5422 ClassType ct = (ClassType) c.type;
5423
5424 hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5425
5426 if (!hasErrorSuper) {
5427 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5428 }
5429 }
5430 } else {
5431 if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5432 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5433 }
5434
5435 if (!c.type.isCompound()) {
5436 for (ClassSymbol supertypeSym : sealedSupers) {
5437 if (!supertypeSym.permitted.contains(c.type.tsym)) {
5438 log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5439 }
5440 }
5441 if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5442 log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5443 c.isInterface() ?
5444 Errors.NonSealedOrSealedExpected :
5445 Errors.NonSealedSealedOrFinalExpected);
5446 }
5447 }
5448 }
5449
5450 // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
5465
5466 try {
5467 deferredLintHandler.flush(env.tree);
5468 env.info.returnResult = null;
5469 // java.lang.Enum may not be subclassed by a non-enum
5470 if (st.tsym == syms.enumSym &&
5471 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5472 log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5473
5474 // Enums may not be extended by source-level classes
5475 if (st.tsym != null &&
5476 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5477 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5478 log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5479 }
5480
5481 if (rs.isSerializable(c.type)) {
5482 env.info.isSerializable = true;
5483 }
5484
5485 attribClassBody(env, c);
5486
5487 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5488 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5489 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5490 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5491 } finally {
5492 env.info.returnResult = prevReturnRes;
5493 log.useSource(prev);
5494 chk.setLint(prevLint);
5495 }
5496
5497 }
5498 }
5499
5500 public void visitImport(JCImport tree) {
5501 // nothing to do
5502 }
5503
5504 public void visitModuleDef(JCModuleDecl tree) {
|
29 import java.util.function.BiConsumer;
30 import java.util.function.Consumer;
31 import java.util.stream.Stream;
32
33 import javax.lang.model.element.ElementKind;
34 import javax.tools.JavaFileObject;
35
36 import com.sun.source.tree.CaseTree;
37 import com.sun.source.tree.EnhancedForLoopTree;
38 import com.sun.source.tree.IdentifierTree;
39 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
40 import com.sun.source.tree.MemberSelectTree;
41 import com.sun.source.tree.TreeVisitor;
42 import com.sun.source.util.SimpleTreeVisitor;
43 import com.sun.tools.javac.code.*;
44 import com.sun.tools.javac.code.Lint.LintCategory;
45 import com.sun.tools.javac.code.Scope.WriteableScope;
46 import com.sun.tools.javac.code.Source.Feature;
47 import com.sun.tools.javac.code.Symbol.*;
48 import com.sun.tools.javac.code.Type.*;
49 import com.sun.tools.javac.code.Type.ClassType.Flavor;
50 import com.sun.tools.javac.code.TypeMetadata.Annotations;
51 import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError;
52 import com.sun.tools.javac.comp.ArgumentAttr.LocalCacheContext;
53 import com.sun.tools.javac.comp.Check.CheckContext;
54 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
55 import com.sun.tools.javac.comp.MatchBindingsComputer.MatchBindings;
56 import com.sun.tools.javac.jvm.*;
57
58 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond;
59 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArg;
60 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArgs;
61
62 import com.sun.tools.javac.resources.CompilerProperties.Errors;
63 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
64 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
65 import com.sun.tools.javac.tree.*;
66 import com.sun.tools.javac.tree.JCTree.*;
67 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
68 import com.sun.tools.javac.util.*;
69 import com.sun.tools.javac.util.DefinedBy.Api;
151 infer = Infer.instance(context);
152 analyzer = Analyzer.instance(context);
153 deferredAttr = DeferredAttr.instance(context);
154 cfolder = ConstFold.instance(context);
155 target = Target.instance(context);
156 types = Types.instance(context);
157 preview = Preview.instance(context);
158 diags = JCDiagnostic.Factory.instance(context);
159 annotate = Annotate.instance(context);
160 typeAnnotations = TypeAnnotations.instance(context);
161 deferredLintHandler = DeferredLintHandler.instance(context);
162 typeEnvs = TypeEnvs.instance(context);
163 dependencies = Dependencies.instance(context);
164 argumentAttr = ArgumentAttr.instance(context);
165 matchBindingsComputer = MatchBindingsComputer.instance(context);
166 attrRecover = AttrRecover.instance(context);
167
168 Options options = Options.instance(context);
169
170 Source source = Source.instance(context);
171 allowPrimitiveClasses = Feature.PRIMITIVE_CLASSES.allowedInSource(source) && options.isSet("enablePrimitiveClasses");
172 allowReifiableTypesInInstanceof = Feature.REIFIABLE_TYPES_INSTANCEOF.allowedInSource(source);
173 allowRecords = Feature.RECORDS.allowedInSource(source);
174 allowPatternSwitch = (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH)) &&
175 Feature.PATTERN_SWITCH.allowedInSource(source);
176 allowUnconditionalPatternsInstanceOf = (preview.isEnabled() || !preview.isPreview(Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF)) &&
177 Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.allowedInSource(source);
178 sourceName = source.name;
179 useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
180
181 statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
182 varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
183 unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
184 methodAttrInfo = new MethodAttrInfo();
185 unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
186 unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
187 recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
188 }
189
190 /** Switch: allow primitive classes ?
191 */
192 boolean allowPrimitiveClasses;
193
194 /** Switch: reifiable types in instanceof enabled?
195 */
196 boolean allowReifiableTypesInInstanceof;
197
198 /** Are records allowed
199 */
200 private final boolean allowRecords;
201
202 /** Are patterns in switch allowed
203 */
204 private final boolean allowPatternSwitch;
205
206 /** Are unconditional patterns in instanceof allowed
207 */
208 private final boolean allowUnconditionalPatternsInstanceOf;
209
210 /**
211 * Switch: warn about use of variable before declaration?
212 * RFE: 6425594
213 */
262 found;
263 }
264 if (resultInfo.checkMode.updateTreeType()) {
265 tree.type = owntype;
266 }
267 return owntype;
268 }
269
270 /** Is given blank final variable assignable, i.e. in a scope where it
271 * may be assigned to even though it is final?
272 * @param v The blank final variable.
273 * @param env The current environment.
274 */
275 boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
276 Symbol owner = env.info.scope.owner;
277 // owner refers to the innermost variable, method or
278 // initializer block declaration at this point.
279 boolean isAssignable =
280 v.owner == owner
281 ||
282 ((names.isInitOrVNew(owner.name) || // i.e. we are in a constructor
283 owner.kind == VAR || // i.e. we are in a variable initializer
284 (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block
285 &&
286 v.owner == owner.owner
287 &&
288 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
289 boolean insideCompactConstructor = env.enclMethod != null && TreeInfo.isCompactConstructor(env.enclMethod);
290 return isAssignable & !insideCompactConstructor;
291 }
292
293 /** Check that variable can be assigned to.
294 * @param pos The current source code position.
295 * @param v The assigned variable
296 * @param base If the variable is referred to in a Select, the part
297 * to the left of the `.', null otherwise.
298 * @param env The current environment.
299 */
300 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
301 if (v.name == names._this) {
302 log.error(pos, Errors.CantAssignValToThis);
789 /** Attribute a type argument list, returning a list of types.
790 * Check that all the types are references.
791 */
792 List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
793 List<Type> types = attribAnyTypes(trees, env);
794 return chk.checkRefTypes(trees, types);
795 }
796
797 /**
798 * Attribute type variables (of generic classes or methods).
799 * Compound types are attributed later in attribBounds.
800 * @param typarams the type variables to enter
801 * @param env the current environment
802 */
803 void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env, boolean checkCyclic) {
804 for (JCTypeParameter tvar : typarams) {
805 TypeVar a = (TypeVar)tvar.type;
806 a.tsym.flags_field |= UNATTRIBUTED;
807 a.setUpperBound(Type.noType);
808 if (!tvar.bounds.isEmpty()) {
809 List<Type> bounds = List.of(chk.checkRefType(tvar.bounds.head, attribType(tvar.bounds.head, env), false));
810 for (JCExpression bound : tvar.bounds.tail)
811 bounds = bounds.prepend(chk.checkRefType(bound, attribType(bound, env), false));
812 types.setBounds(a, bounds.reverse());
813 } else {
814 // if no bounds are given, assume a single bound of
815 // java.lang.Object.
816 types.setBounds(a, List.of(syms.objectType));
817 }
818 a.tsym.flags_field &= ~UNATTRIBUTED;
819 }
820 if (checkCyclic) {
821 for (JCTypeParameter tvar : typarams) {
822 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
823 }
824 }
825 }
826
827 /**
828 * Attribute the type references in a list of annotations.
829 */
830 void attribAnnotationTypes(List<JCAnnotation> annotations,
831 Env<AttrContext> env) {
1061 log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.MethodMustBePublic));
1062 }
1063 if (!types.isSameType(tree.sym.type.getReturnType(), recordComponent.get().type)) {
1064 log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym,
1065 Fragments.AccessorReturnTypeDoesntMatch(tree.sym, recordComponent.get())));
1066 }
1067 if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1068 log.error(tree,
1069 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodCantThrowException));
1070 }
1071 if (!tree.typarams.isEmpty()) {
1072 log.error(tree,
1073 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeGeneric));
1074 }
1075 if (tree.sym.isStatic()) {
1076 log.error(tree,
1077 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeStatic));
1078 }
1079 }
1080
1081 if (names.isInitOrVNew(tree.name)) {
1082 // if this a constructor other than the canonical one
1083 if ((tree.sym.flags_field & RECORD) == 0) {
1084 JCMethodInvocation app = TreeInfo.firstConstructorCall(tree);
1085 if (app == null ||
1086 TreeInfo.name(app.meth) != names._this ||
1087 !checkFirstConstructorStat(app, tree, false)) {
1088 log.error(tree, Errors.FirstStatementMustBeCallToAnotherConstructor(env.enclClass.sym));
1089 }
1090 } else {
1091 // but if it is the canonical:
1092
1093 /* if user generated, then it shouldn't:
1094 * - have an accessibility stricter than that of the record type
1095 * - explicitly invoke any other constructor
1096 */
1097 if ((tree.sym.flags_field & GENERATEDCONSTR) == 0) {
1098 if (Check.protection(m.flags()) > Check.protection(env.enclClass.sym.flags())) {
1099 log.error(tree,
1100 (env.enclClass.sym.flags() & AccessFlags) == 0 ?
1101 Errors.InvalidCanonicalConstructorInRecord(
1176 if (tree.defaultValue != null) {
1177 if ((owner.flags() & ANNOTATION) == 0)
1178 log.error(tree.pos(),
1179 Errors.DefaultAllowedInIntfAnnotationMember);
1180 }
1181 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1182 log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract);
1183 } else {
1184 if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1185 if ((owner.flags() & INTERFACE) != 0) {
1186 log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1187 } else {
1188 log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1189 }
1190 } else if ((tree.mods.flags & NATIVE) != 0) {
1191 log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1192 }
1193 // Add an implicit super() call unless an explicit call to
1194 // super(...) or this(...) is given
1195 // or we are compiling class java.lang.Object.
1196 if (names.isInitOrVNew(tree.name) && owner.type != syms.objectType) {
1197 JCBlock body = tree.body;
1198 if (body.stats.isEmpty() ||
1199 TreeInfo.getConstructorInvocationName(body.stats, names, true) == names.empty) {
1200 JCStatement supCall = make.at(body.pos).Exec(make.Apply(List.nil(),
1201 make.Ident(names._super), make.Idents(List.nil())));
1202 body.stats = body.stats.prepend(supCall);
1203 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1204 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1205 TreeInfo.isSuperCall(body.stats.head)) {
1206 // enum constructors are not allowed to call super
1207 // directly, so make sure there aren't any super calls
1208 // in enum constructors, except in the compiler
1209 // generated one.
1210 log.error(tree.body.stats.head.pos(),
1211 Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1212 } else if ((env.enclClass.sym.flags() & VALUE_CLASS) != 0 &&
1213 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1214 TreeInfo.isSuperCall(body.stats.head)) {
1215 // value constructors are not allowed to call super directly,
1216 // but tolerate compiler generated ones, these are ignored during code generation
1217 log.error(tree.body.stats.head.pos(), Errors.CallToSuperNotAllowedInValueCtor);
1218 }
1219 if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1220 List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1221 List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1222 if (!initParamNames.equals(recordComponentNames)) {
1223 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1224 Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1225 }
1226 if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1227 log.error(tree,
1228 Errors.InvalidCanonicalConstructorInRecord(
1229 TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical,
1230 env.enclClass.sym.name,
1231 Fragments.ThrowsClauseNotAllowedForCanonicalConstructor(
1232 TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical)));
1233 }
1234 }
1235 }
1236
1237 // Attribute all type annotations in the body
1285 annotate.queueScanTreeAndTypeAnnotate(tree.init, env, tree.sym, tree.pos());
1286 annotate.flush();
1287 }
1288 }
1289
1290 VarSymbol v = tree.sym;
1291 Lint lint = env.info.lint.augment(v);
1292 Lint prevLint = chk.setLint(lint);
1293
1294 // Check that the variable's declared type is well-formed.
1295 boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
1296 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
1297 (tree.sym.flags() & PARAMETER) != 0;
1298 chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1299
1300 try {
1301 v.getConstValue(); // ensure compile-time constant initializer is evaluated
1302 deferredLintHandler.flush(tree.pos());
1303 chk.checkDeprecatedAnnotation(tree.pos(), v);
1304
1305 /* Don't want constant propagation/folding for instance fields of primitive classes,
1306 as these can undergo updates via copy on write.
1307 */
1308 if (tree.init != null) {
1309 if ((v.flags_field & FINAL) == 0 || ((v.flags_field & STATIC) == 0 && v.owner.isValueClass()) ||
1310 !memberEnter.needsLazyConstValue(tree.init)) {
1311 // Not a compile-time constant
1312 // Attribute initializer in a new environment
1313 // with the declared variable as owner.
1314 // Check that initializer conforms to variable's declared type.
1315 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1316 initEnv.info.lint = lint;
1317 // In order to catch self-references, we set the variable's
1318 // declaration position to maximal possible value, effectively
1319 // marking the variable as undefined.
1320 initEnv.info.enclVar = v;
1321 attribExpr(tree.init, initEnv, v.type);
1322 if (tree.isImplicitlyTyped()) {
1323 //fixup local variable type
1324 v.type = chk.checkLocalVarType(tree, tree.init.type, tree.name);
1325 }
1326 }
1327 if (tree.isImplicitlyTyped()) {
1328 setSyntheticVariableType(tree, v.type);
1329 }
1330 }
1331 result = tree.type = v.type;
1332 if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1333 if (isNonArgsMethodInObject(v.name)) {
1334 log.error(tree, Errors.IllegalRecordComponentName(v));
1335 }
1336 }
1337 }
1338 finally {
1339 chk.setLint(prevLint);
1340 }
1341 }
1342
1343 private boolean isNonArgsMethodInObject(Name name) {
1344 for (Symbol s : syms.objectType.tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) {
1345 if (s.type.getParameterTypes().isEmpty()) {
1346 return true;
1347 }
1348 }
1349 // isValueObject is not included in Object yet so we need a work around
1350 return name == names.isValueObject;
1351 }
1352
1353 Fragment canInferLocalVarType(JCVariableDecl tree) {
1354 LocalInitScanner lis = new LocalInitScanner();
1355 lis.scan(tree.init);
1356 return lis.badInferenceMsg;
1357 }
1358
1359 static class LocalInitScanner extends TreeScanner {
1360 Fragment badInferenceMsg = null;
1361 boolean needsTarget = true;
1362
1363 @Override
1364 public void visitNewArray(JCNewArray tree) {
1365 if (tree.elemtype == null && needsTarget) {
1366 badInferenceMsg = Fragments.LocalArrayMissingTarget;
1367 }
1368 }
1369
1370 @Override
1523 if (!breaksOutOf(tree, tree.body)) {
1524 //include condition's body when false after the while, if cannot get out of the loop
1525 condBindings.bindingsWhenFalse.forEach(env.info.scope::enter);
1526 condBindings.bindingsWhenFalse.forEach(BindingSymbol::preserveBinding);
1527 }
1528 }
1529
1530 public void visitForeachLoop(JCEnhancedForLoop tree) {
1531 Env<AttrContext> loopEnv =
1532 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1533
1534 try {
1535 //the Formal Parameter of a for-each loop is not in the scope when
1536 //attributing the for-each expression; we mimic this by attributing
1537 //the for-each expression first (against original scope).
1538 Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
1539 chk.checkNonVoid(tree.pos(), exprType);
1540 tree.elementType = types.elemtype(exprType); // perhaps expr is an array?
1541 if (tree.elementType == null) {
1542 // or perhaps expr implements Iterable<T>?
1543 Type base = types.asSuper(exprType.referenceProjectionOrSelf(), syms.iterableType.tsym);
1544 if (base == null) {
1545 log.error(tree.expr.pos(),
1546 Errors.ForeachNotApplicableToType(exprType,
1547 Fragments.TypeReqArrayOrIterable));
1548 tree.elementType = types.createErrorType(exprType);
1549 } else {
1550 List<Type> iterableParams = base.allparams();
1551 tree.elementType = iterableParams.isEmpty()
1552 ? syms.objectType
1553 : types.wildUpperBound(iterableParams.head);
1554
1555 // Check the return type of the method iterator().
1556 // This is the bare minimum we need to verify to make sure code generation doesn't crash.
1557 Symbol iterSymbol = rs.resolveInternalMethod(tree.pos(),
1558 loopEnv, types.skipTypeVars(exprType, false), names.iterator, List.nil(), List.nil());
1559 if (types.asSuper(iterSymbol.type.getReturnType().referenceProjectionOrSelf(), syms.iteratorType.tsym) == null) {
1560 log.error(tree.pos(),
1561 Errors.ForeachNotApplicableToType(exprType, Fragments.TypeReqArrayOrIterable));
1562 }
1563 }
1564 }
1565 if (tree.varOrRecordPattern instanceof JCVariableDecl jcVariableDecl) {
1566 if (jcVariableDecl.isImplicitlyTyped()) {
1567 Type inferredType = chk.checkLocalVarType(jcVariableDecl, tree.elementType, jcVariableDecl.name);
1568 setSyntheticVariableType(jcVariableDecl, inferredType);
1569 }
1570 attribStat(jcVariableDecl, loopEnv);
1571 chk.checkType(tree.expr.pos(), tree.elementType, jcVariableDecl.sym.type);
1572
1573 loopEnv.tree = tree; // before, we were not in loop!
1574 attribStat(tree.body, loopEnv);
1575 } else {
1576 Assert.check(tree.getDeclarationKind() == EnhancedForLoopTree.DeclarationKind.PATTERN);
1577 JCRecordPattern jcRecordPattern = (JCRecordPattern) tree.varOrRecordPattern;
1578
1579 attribExpr(jcRecordPattern, loopEnv, tree.elementType);
1881 // where
1882 /** Return the selected enumeration constant symbol, or null. */
1883 private Symbol enumConstant(JCTree tree, Type enumType) {
1884 if (tree.hasTag(IDENT)) {
1885 JCIdent ident = (JCIdent)tree;
1886 Name name = ident.name;
1887 for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1888 if (sym.kind == VAR) {
1889 Symbol s = ident.sym = sym;
1890 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1891 ident.type = s.type;
1892 return ((s.flags_field & Flags.ENUM) == 0)
1893 ? null : s;
1894 }
1895 }
1896 }
1897 return null;
1898 }
1899
1900 public void visitSynchronized(JCSynchronized tree) {
1901 chk.checkIdentityType(tree.pos(), attribExpr(tree.lock, env));
1902 if (env.info.lint.isEnabled(LintCategory.SYNCHRONIZATION) && isValueBased(tree.lock.type)) {
1903 log.warning(LintCategory.SYNCHRONIZATION, tree.pos(), Warnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
1904 }
1905 attribStat(tree.body, env);
1906 result = null;
1907 }
1908 // where
1909 private boolean isValueBased(Type t) {
1910 return t != null && t.tsym != null && (t.tsym.flags() & VALUE_BASED) != 0;
1911 }
1912
1913
1914 public void visitTry(JCTry tree) {
1915 // Create a new local environment with a local
1916 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1917 try {
1918 boolean isTryWithResource = tree.resources.nonEmpty();
1919 // Create a nested environment for attributing the try block if needed
1920 Env<AttrContext> tryEnv = isTryWithResource ?
1921 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1972 chk.checkType(c.param.vartype.pos(),
1973 chk.checkClassType(c.param.vartype.pos(), ctype),
1974 syms.throwableType);
1975 attribStat(c.body, catchEnv);
1976 } finally {
1977 catchEnv.info.scope.leave();
1978 }
1979 }
1980
1981 // Attribute finalizer
1982 if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1983 result = null;
1984 }
1985 finally {
1986 localEnv.info.scope.leave();
1987 }
1988 }
1989
1990 void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
1991 if (!resource.isErroneous() &&
1992 types.asSuper(resource.referenceProjectionOrSelf(), syms.autoCloseableType.tsym) != null &&
1993 !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
1994 Symbol close = syms.noSymbol;
1995 Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
1996 try {
1997 close = rs.resolveQualifiedMethod(pos,
1998 env,
1999 types.skipTypeVars(resource, false),
2000 names.close,
2001 List.nil(),
2002 List.nil());
2003 }
2004 finally {
2005 log.popDiagnosticHandler(discardHandler);
2006 }
2007 if (close.kind == MTH &&
2008 close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
2009 chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
2010 env.info.lint.isEnabled(LintCategory.TRY)) {
2011 log.warning(LintCategory.TRY, pos, Warnings.TryResourceThrowsInterruptedExc(resource));
2012 }
2161 if (unboxedTypes.stream().allMatch(t -> t.isPrimitive())) {
2162 // If one arm has an integer subrange type (i.e., byte,
2163 // short, or char), and the other is an integer constant
2164 // that fits into the subrange, return the subrange type.
2165 for (Type type : unboxedTypes) {
2166 if (!type.getTag().isStrictSubRangeOf(INT)) {
2167 continue;
2168 }
2169 if (unboxedTypes.stream().filter(t -> t != type).allMatch(t -> t.hasTag(INT) && types.isAssignable(t, type)))
2170 return type.baseType();
2171 }
2172
2173 for (TypeTag tag : primitiveTags) {
2174 Type candidate = syms.typeOfTag[tag.ordinal()];
2175 if (unboxedTypes.stream().allMatch(t -> types.isSubtype(t, candidate))) {
2176 return candidate;
2177 }
2178 }
2179 }
2180
2181 // Those were all the cases that could result in a primitive. See if primitive boxing and primitive
2182 // value conversions bring about a convergence.
2183 condTypes = condTypes.stream()
2184 .map(t -> t.isPrimitive() ? types.boxedClass(t).type
2185 : t.isReferenceProjection() ? t.valueProjection() : t)
2186 .collect(List.collector());
2187
2188 for (Type type : condTypes) {
2189 if (condTypes.stream().filter(t -> t != type).allMatch(t -> types.isAssignable(t, type)))
2190 return type.baseType();
2191 }
2192
2193 Iterator<DiagnosticPosition> posIt = positions.iterator();
2194
2195 condTypes = condTypes.stream()
2196 .map(t -> chk.checkNonVoid(posIt.next(), allowPrimitiveClasses && t.isPrimitiveClass() ? t.referenceProjection() : t))
2197 .collect(List.collector());
2198
2199 // both are known to be reference types (or projections). The result is
2200 // lub(thentype,elsetype). This cannot fail, as it will
2201 // always be possible to infer "Object" if nothing better.
2202 return types.lub(condTypes.stream()
2203 .map(t -> t.baseType())
2204 .filter(t -> !t.hasTag(BOT))
2205 .collect(List.collector()));
2206 }
2207
2208 static final TypeTag[] primitiveTags = new TypeTag[]{
2209 BYTE,
2210 CHAR,
2211 SHORT,
2212 INT,
2213 LONG,
2214 FLOAT,
2215 DOUBLE,
2216 BOOLEAN,
2217 };
2218
2219 Env<AttrContext> bindingEnv(Env<AttrContext> env, List<BindingSymbol> bindings) {
2618 : env.enclClass.sym.type;
2619 Symbol msym = TreeInfo.symbol(tree.meth);
2620 restype = adjustMethodReturnType(msym, qualifier, methName, argtypes, restype);
2621
2622 chk.checkRefTypes(tree.typeargs, typeargtypes);
2623
2624 // Check that value of resulting type is admissible in the
2625 // current context. Also, capture the return type
2626 Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true);
2627 result = check(tree, capturedRes, KindSelector.VAL, resultInfo);
2628 }
2629 chk.validate(tree.typeargs, localEnv);
2630 }
2631 //where
2632 Type adjustMethodReturnType(Symbol msym, Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
2633 if (msym != null &&
2634 (msym.owner == syms.objectType.tsym || msym.owner.isInterface()) &&
2635 methodName == names.getClass &&
2636 argtypes.isEmpty()) {
2637 // as a special case, x.getClass() has type Class<? extends |X|>
2638 // Special treatment for primitive classes: Given an expression v of type V where
2639 // V is a primitive class, v.getClass() is typed to be Class<? extends |V.ref|>
2640 Type wcb = types.erasure(allowPrimitiveClasses && qualifierType.isPrimitiveClass() ?
2641 qualifierType.referenceProjection() : qualifierType.baseType());
2642 return new ClassType(restype.getEnclosingType(),
2643 List.of(new WildcardType(wcb,
2644 BoundKind.EXTENDS,
2645 syms.boundClass)),
2646 restype.tsym,
2647 restype.getMetadata(),
2648 restype.getFlavor());
2649 } else if (msym != null &&
2650 msym.owner == syms.arrayClass &&
2651 methodName == names.clone &&
2652 types.isArray(qualifierType)) {
2653 // as a special case, array.clone() has a result that is
2654 // the same as static type of the array being cloned
2655 return qualifierType;
2656 } else {
2657 return restype;
2658 }
2659 }
2660
2661 /** Check that given application node appears as first statement
2662 * in a constructor call.
2663 * @param tree The application node
2664 * @param enclMethod The enclosing method of the application.
2665 * @param error Should an error be issued?
2666 */
2667 boolean checkFirstConstructorStat(JCMethodInvocation tree, JCMethodDecl enclMethod, boolean error) {
2668 if (enclMethod != null && names.isInitOrVNew(enclMethod.name)) {
2669 JCBlock body = enclMethod.body;
2670 if (body.stats.head.hasTag(EXEC) &&
2671 ((JCExpressionStatement) body.stats.head).expr == tree)
2672 return true;
2673 }
2674 if (error) {
2675 log.error(tree.pos(),
2676 Errors.CallMustBeFirstStmtInCtor(TreeInfo.name(tree.meth)));
2677 }
2678 return false;
2679 }
2680
2681 /** Obtain a method type with given argument types.
2682 */
2683 Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
2684 MethodType mt = new MethodType(argtypes, restype, List.nil(), syms.methodClass);
2685 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
2686 }
2687
2688 public void visitNewClass(final JCNewClass tree) {
2797 }
2798
2799 // Attribute constructor arguments.
2800 ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2801 final KindSelector pkind =
2802 attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
2803 List<Type> argtypes = argtypesBuf.toList();
2804 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
2805
2806 if (clazztype.hasTag(CLASS) || clazztype.hasTag(ERROR)) {
2807 // Enums may not be instantiated except implicitly
2808 if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 &&
2809 (!env.tree.hasTag(VARDEF) ||
2810 (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 ||
2811 ((JCVariableDecl) env.tree).init != tree))
2812 log.error(tree.pos(), Errors.EnumCantBeInstantiated);
2813
2814 boolean isSpeculativeDiamondInferenceRound = TreeInfo.isDiamond(tree) &&
2815 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2816 boolean skipNonDiamondPath = false;
2817 // Check that it is an instantiation of a class and not a projection type
2818 if (allowPrimitiveClasses) {
2819 if (clazz.hasTag(SELECT)) {
2820 JCFieldAccess fieldAccess = (JCFieldAccess) clazz;
2821 if (fieldAccess.selected.type.isPrimitiveClass() &&
2822 (fieldAccess.name == names.ref || fieldAccess.name == names.val)) {
2823 log.error(tree.pos(), Errors.ProjectionCantBeInstantiated);
2824 }
2825 }
2826 }
2827 // Check that class is not abstract
2828 if (cdef == null && !isSpeculativeDiamondInferenceRound && // class body may be nulled out in speculative tree copy
2829 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
2830 log.error(tree.pos(),
2831 Errors.AbstractCantBeInstantiated(clazztype.tsym));
2832 skipNonDiamondPath = true;
2833 } else if (cdef != null && clazztype.tsym.isInterface()) {
2834 // Check that no constructor arguments are given to
2835 // anonymous classes implementing an interface
2836 if (!argtypes.isEmpty())
2837 log.error(tree.args.head.pos(), Errors.AnonClassImplIntfNoArgs);
2838
2839 if (!typeargtypes.isEmpty())
2840 log.error(tree.typeargs.head.pos(), Errors.AnonClassImplIntfNoTypeargs);
2841
2842 // Error recovery: pretend no arguments were supplied.
2843 argtypes = List.nil();
2844 typeargtypes = List.nil();
2845 skipNonDiamondPath = true;
2846 }
2847 if (TreeInfo.isDiamond(tree)) {
2848 ClassType site = new ClassType(clazztype.getEnclosingType(),
2849 clazztype.tsym.type.getTypeArguments(),
2850 clazztype.tsym,
2851 clazztype.getMetadata(),
2852 clazztype.getFlavor());
2853
2854 Env<AttrContext> diamondEnv = localEnv.dup(tree);
2855 diamondEnv.info.selectSuper = cdef != null || tree.classDeclRemoved();
2856 diamondEnv.info.pendingResolutionPhase = null;
2857
2858 //if the type of the instance creation expression is a class type
2859 //apply method resolution inference (JLS 15.12.2.7). The return type
2860 //of the resolved constructor will be a partially instantiated type
2861 Symbol constructor = rs.resolveDiamond(tree.pos(),
2862 diamondEnv,
2863 site,
2864 argtypes,
2865 typeargtypes);
2866 tree.constructor = constructor.baseSymbol();
2867
2868 final TypeSymbol csym = clazztype.tsym;
2869 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes),
2870 diamondContext(tree, csym, resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
2871 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
2872 constructorType = checkId(tree, site,
2986 this.resultInfo = prevResult;
2987 }
2988 });
2989 } else {
2990 if (isDiamond && clazztype.hasTag(CLASS)) {
2991 List<Type> invalidDiamondArgs = chk.checkDiamondDenotable((ClassType)clazztype);
2992 if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
2993 // One or more types inferred in the previous steps is non-denotable.
2994 Fragment fragment = Diamond(clazztype.tsym);
2995 log.error(tree.clazz.pos(),
2996 Errors.CantApplyDiamond1(
2997 fragment,
2998 invalidDiamondArgs.size() > 1 ?
2999 DiamondInvalidArgs(invalidDiamondArgs, fragment) :
3000 DiamondInvalidArg(invalidDiamondArgs, fragment)));
3001 }
3002 // For <>(){}, inferred types must also be accessible.
3003 for (Type t : clazztype.getTypeArguments()) {
3004 rs.checkAccessibleType(env, t);
3005 }
3006 if (allowPrimitiveClasses) {
3007 chk.checkParameterizationByPrimitiveClass(tree, clazztype);
3008 }
3009 }
3010
3011 // If we already errored, be careful to avoid a further avalanche. ErrorType answers
3012 // false for isInterface call even when the original type is an interface.
3013 boolean implementing = clazztype.tsym.isInterface() ||
3014 clazztype.isErroneous() && !clazztype.getOriginalType().hasTag(NONE) &&
3015 clazztype.getOriginalType().tsym.isInterface();
3016
3017 if (implementing) {
3018 cdef.implementing = List.of(clazz);
3019 } else {
3020 cdef.extending = clazz;
3021 }
3022
3023 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3024 rs.isSerializable(clazztype)) {
3025 localEnv.info.isSerializable = true;
3026 }
3027
3028 attribStat(cdef, localEnv);
3061 result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK));
3062 chk.validate(tree.typeargs, localEnv);
3063 }
3064
3065 CheckContext diamondContext(JCNewClass clazz, TypeSymbol tsym, CheckContext checkContext) {
3066 return new Check.NestedCheckContext(checkContext) {
3067 @Override
3068 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
3069 enclosingContext.report(clazz.clazz,
3070 diags.fragment(Fragments.CantApplyDiamond1(Fragments.Diamond(tsym), details)));
3071 }
3072 };
3073 }
3074
3075 /** Make an attributed null check tree.
3076 */
3077 public JCExpression makeNullCheck(JCExpression arg) {
3078 // optimization: new Outer() can never be null; skip null check
3079 if (arg.getTag() == NEWCLASS)
3080 return arg;
3081 // Likewise arg can't be null if it is a primitive class instance.
3082 if (allowPrimitiveClasses && arg.type.isPrimitiveClass())
3083 return arg;
3084 // optimization: X.this is never null; skip null check
3085 Name name = TreeInfo.name(arg);
3086 if (name == names._this || name == names._super) return arg;
3087
3088 JCTree.Tag optag = NULLCHK;
3089 JCUnary tree = make.at(arg.pos).Unary(optag, arg);
3090 tree.operator = operators.resolveUnary(arg, optag, arg.type);
3091 tree.type = arg.type;
3092 return tree;
3093 }
3094
3095 public void visitNewArray(JCNewArray tree) {
3096 Type owntype = types.createErrorType(tree.type);
3097 Env<AttrContext> localEnv = env.dup(tree);
3098 Type elemtype;
3099 if (tree.elemtype != null) {
3100 elemtype = attribType(tree.elemtype, localEnv);
3101 chk.validate(tree.elemtype, localEnv);
3102 owntype = elemtype;
3103 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
3553 *
3554 * The owner of this environment is a method symbol. If the current owner
3555 * is not a method, for example if the lambda is used to initialize
3556 * a field, then if the field is:
3557 *
3558 * - an instance field, we use the first constructor.
3559 * - a static field, we create a fake clinit method.
3560 */
3561 public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
3562 Env<AttrContext> lambdaEnv;
3563 Symbol owner = env.info.scope.owner;
3564 if (owner.kind == VAR && owner.owner.kind == TYP) {
3565 //field initializer
3566 ClassSymbol enclClass = owner.enclClass();
3567 Symbol newScopeOwner = env.info.scope.owner;
3568 /* if the field isn't static, then we can get the first constructor
3569 * and use it as the owner of the environment. This is what
3570 * LTM code is doing to look for type annotations so we are fine.
3571 */
3572 if ((owner.flags() & STATIC) == 0) {
3573 Name constructorName = owner.isConcreteValueClass() ? names.vnew : names.init;
3574 for (Symbol s : enclClass.members_field.getSymbolsByName(constructorName)) {
3575 newScopeOwner = s;
3576 break;
3577 }
3578 } else {
3579 /* if the field is static then we need to create a fake clinit
3580 * method, this method can later be reused by LTM.
3581 */
3582 MethodSymbol clinit = clinits.get(enclClass);
3583 if (clinit == null) {
3584 Type clinitType = new MethodType(List.nil(),
3585 syms.voidType, List.nil(), syms.methodClass);
3586 clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE,
3587 names.clinit, clinitType, enclClass);
3588 clinit.params = List.nil();
3589 clinits.put(enclClass, clinit);
3590 }
3591 newScopeOwner = clinit;
3592 }
3593 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(newScopeOwner)));
3594 } else {
3617
3618 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3619 exprType = chk.checkConstructorRefType(that.expr, exprType);
3620 if (!exprType.isErroneous() &&
3621 exprType.isRaw() &&
3622 that.typeargs != null) {
3623 log.error(that.expr.pos(),
3624 Errors.InvalidMref(Kinds.kindName(that.getMode()),
3625 Fragments.MrefInferAndExplicitParams));
3626 exprType = types.createErrorType(exprType);
3627 }
3628 }
3629
3630 if (exprType.isErroneous()) {
3631 //if the qualifier expression contains problems,
3632 //give up attribution of method reference
3633 result = that.type = exprType;
3634 return;
3635 }
3636
3637 Symbol lhsSym = TreeInfo.symbol(that.expr);
3638 if (TreeInfo.isStaticSelector(that.expr, names)) {
3639 // TODO - a bit hacky but...
3640 if (lhsSym != null && lhsSym.isConcreteValueClass() && that.name == names.init) {
3641 that.name = names.vnew;
3642 }
3643 //if the qualifier is a type, validate it; raw warning check is
3644 //omitted as we don't know at this stage as to whether this is a
3645 //raw selector (because of inference)
3646 chk.validate(that.expr, env, false);
3647 } else {
3648 localEnv.info.selectSuper = lhsSym != null && lhsSym.name == names._super;
3649 }
3650 //attrib type-arguments
3651 List<Type> typeargtypes = List.nil();
3652 if (that.typeargs != null) {
3653 typeargtypes = attribTypes(that.typeargs, localEnv);
3654 }
3655
3656 boolean isTargetSerializable =
3657 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3658 rs.isSerializable(pt());
3659 TargetInfo targetInfo = getTargetInfo(that, resultInfo, null);
3660 Type currentTarget = targetInfo.target;
3661 Type desc = targetInfo.descriptor;
3662
3663 setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
3664 List<Type> argtypes = desc.getParameterTypes();
3665 Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
3666
3667 if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
3711 targetError ?
3712 Fragments.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag) :
3713 Errors.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag));
3714
3715 if (targetError && currentTarget == Type.recoveryType) {
3716 //a target error doesn't make sense during recovery stage
3717 //as we don't know what actual parameter types are
3718 result = that.type = currentTarget;
3719 return;
3720 } else {
3721 if (targetError) {
3722 resultInfo.checkContext.report(that, diag);
3723 } else {
3724 log.report(diag);
3725 }
3726 result = that.type = types.createErrorType(currentTarget);
3727 return;
3728 }
3729 }
3730
3731 that.sym = refSym.isInitOrVNew() ? refSym.baseSymbol() : refSym;
3732 that.kind = lookupHelper.referenceKind(that.sym);
3733 that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
3734
3735 if (desc.getReturnType() == Type.recoveryType) {
3736 // stop here
3737 result = that.type = currentTarget;
3738 return;
3739 }
3740
3741 if (!env.info.attributionMode.isSpeculative && that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3742 Type enclosingType = exprType.getEnclosingType();
3743 if (enclosingType != null && enclosingType.hasTag(CLASS)) {
3744 // Check for the existence of an appropriate outer instance
3745 rs.resolveImplicitThis(that.pos(), env, exprType);
3746 }
3747 }
3748
3749 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
3750
3751 if (that.getMode() == ReferenceMode.INVOKE &&
4389 }
4390
4391 public void visitSelect(JCFieldAccess tree) {
4392 // Determine the expected kind of the qualifier expression.
4393 KindSelector skind = KindSelector.NIL;
4394 if (tree.name == names._this || tree.name == names._super ||
4395 tree.name == names._class)
4396 {
4397 skind = KindSelector.TYP;
4398 } else {
4399 if (pkind().contains(KindSelector.PCK))
4400 skind = KindSelector.of(skind, KindSelector.PCK);
4401 if (pkind().contains(KindSelector.TYP))
4402 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4403 if (pkind().contains(KindSelector.VAL_MTH))
4404 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4405 }
4406
4407 // Attribute the qualifier expression, and determine its symbol (if any).
4408 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4409 Assert.check(site == tree.selected.type);
4410 if (allowPrimitiveClasses && tree.name == names._class && site.isPrimitiveClass()) {
4411 /* JDK-8269956: Where a reflective (class) literal is needed, the unqualified Point.class is
4412 * always the "primary" mirror - representing the primitive reference runtime type - thereby
4413 * always matching the behavior of Object::getClass
4414 */
4415 if (!tree.selected.hasTag(SELECT) || ((JCFieldAccess) tree.selected).name != names.val) {
4416 tree.selected.setType(site = site.referenceProjection());
4417 }
4418 }
4419 if (!pkind().contains(KindSelector.TYP_PCK))
4420 site = capture(site); // Capture field access
4421
4422 // don't allow T.class T[].class, etc
4423 if (skind == KindSelector.TYP) {
4424 Type elt = site;
4425 while (elt.hasTag(ARRAY))
4426 elt = ((ArrayType)elt).elemtype;
4427 if (elt.hasTag(TYPEVAR)) {
4428 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4429 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4430 tree.sym = tree.type.tsym;
4431 return;
4432 }
4433 }
4434
4435 // If qualifier symbol is a type or `super', assert `selectSuper'
4436 // for the selection. This is relevant for determining whether
4437 // protected symbols are accessible.
4438 Symbol sitesym = TreeInfo.symbol(tree.selected);
4439 boolean selectSuperPrev = env.info.selectSuper;
4440 env.info.selectSuper =
4441 sitesym != null &&
4442 sitesym.name == names._super;
4443
4444 // Determine the symbol represented by the selection.
4445 env.info.pendingResolutionPhase = null;
4446 Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
4447 if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
4448 log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym));
4449 sym = syms.errSymbol;
4450 }
4451 if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
4515 } else if (sym.kind != ERR &&
4516 (sym.flags() & STATIC) != 0 &&
4517 sym.name != names._class) {
4518 // If the qualified item is not a type and the selected item is static, report
4519 // a warning. Make allowance for the class of an array type e.g. Object[].class)
4520 if (!sym.owner.isAnonymous()) {
4521 chk.warnStatic(tree, Warnings.StaticNotQualifiedByType(sym.kind.kindName(), sym.owner));
4522 } else {
4523 chk.warnStatic(tree, Warnings.StaticNotQualifiedByType2(sym.kind.kindName()));
4524 }
4525 }
4526
4527 // If we are selecting an instance member via a `super', ...
4528 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
4529
4530 // Check that super-qualified symbols are not abstract (JLS)
4531 rs.checkNonAbstract(tree.pos(), sym);
4532
4533 if (site.isRaw()) {
4534 // Determine argument types for site.
4535 Type site1 = types.asSuper(env.enclClass.sym.type.referenceProjectionOrSelf(), site.tsym);
4536 if (site1 != null) site = site1;
4537 }
4538 }
4539
4540 if (env.info.isSerializable) {
4541 chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4542 }
4543
4544 env.info.selectSuper = selectSuperPrev;
4545 result = checkId(tree, site, sym, env, resultInfo);
4546 }
4547 //where
4548 /** Determine symbol referenced by a Select expression,
4549 *
4550 * @param tree The select tree.
4551 * @param site The type of the selected expression,
4552 * @param env The current environment.
4553 * @param resultInfo The current result.
4554 */
4555 private Symbol selectSym(JCFieldAccess tree,
4558 Env<AttrContext> env,
4559 ResultInfo resultInfo) {
4560 DiagnosticPosition pos = tree.pos();
4561 Name name = tree.name;
4562 switch (site.getTag()) {
4563 case PACKAGE:
4564 return rs.accessBase(
4565 rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind),
4566 pos, location, site, name, true);
4567 case ARRAY:
4568 case CLASS:
4569 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
4570 return rs.resolveQualifiedMethod(
4571 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
4572 } else if (name == names._this || name == names._super) {
4573 return rs.resolveSelf(pos, env, site.tsym, name);
4574 } else if (name == names._class) {
4575 // In this case, we have already made sure in
4576 // visitSelect that qualifier expression is a type.
4577 return syms.getClassField(site, types);
4578 } else if (allowPrimitiveClasses && site.isPrimitiveClass() && isType(location) && resultInfo.pkind.contains(KindSelector.TYP) && (name == names.ref || name == names.val)) {
4579 return site.tsym;
4580 } else {
4581 // We are seeing a plain identifier as selector.
4582 Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind);
4583 sym = rs.accessBase(sym, pos, location, site, name, true);
4584 return sym;
4585 }
4586 case WILDCARD:
4587 throw new AssertionError(tree);
4588 case TYPEVAR:
4589 // Normally, site.getUpperBound() shouldn't be null.
4590 // It should only happen during memberEnter/attribBase
4591 // when determining the supertype which *must* be
4592 // done before attributing the type variables. In
4593 // other words, we are seeing this illegal program:
4594 // class B<T> extends A<T.foo> {}
4595 Symbol sym = (site.getUpperBound() != null)
4596 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
4597 : null;
4598 if (sym == null) {
4599 log.error(pos, Errors.TypeVarCantBeDeref);
4663 if (resultInfo.pkind.contains(KindSelector.POLY)) {
4664 return attrRecover.recoverMethodInvocation(tree, site, sym, env, resultInfo);
4665 } else {
4666 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
4667 }
4668 }
4669
4670 Type checkIdInternal(JCTree tree,
4671 Type site,
4672 Symbol sym,
4673 Type pt,
4674 Env<AttrContext> env,
4675 ResultInfo resultInfo) {
4676 if (pt.isErroneous()) {
4677 return types.createErrorType(site);
4678 }
4679 Type owntype; // The computed type of this identifier occurrence.
4680 switch (sym.kind) {
4681 case TYP:
4682 // For types, the computed type equals the symbol's type,
4683 // except for three situations:
4684 owntype = sym.type;
4685 if (owntype.hasTag(CLASS)) {
4686 if (allowPrimitiveClasses) {
4687 Assert.check(owntype.getFlavor() != Flavor.X_Typeof_X);
4688 }
4689 chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
4690 Type ownOuter = owntype.getEnclosingType();
4691
4692 // (a) If symbol is a primitive class and its reference projection
4693 // is requested via the .ref notation, then adjust the computed type to
4694 // reflect this.
4695 if (allowPrimitiveClasses && owntype.isPrimitiveClass() && tree.hasTag(SELECT) && ((JCFieldAccess) tree).name == names.ref) {
4696 owntype = new ClassType(owntype.getEnclosingType(), owntype.getTypeArguments(), (TypeSymbol)sym, owntype.getMetadata(), Flavor.L_TypeOf_Q);
4697 }
4698
4699 // (b) If the symbol's type is parameterized, erase it
4700 // because no type parameters were given.
4701 // We recover generic outer type later in visitTypeApply.
4702 if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
4703 owntype = types.erasure(owntype);
4704 }
4705
4706 // (c) If the symbol's type is an inner class, then
4707 // we have to interpret its outer type as a superclass
4708 // of the site type. Example:
4709 //
4710 // class Tree<A> { class Visitor { ... } }
4711 // class PointTree extends Tree<Point> { ... }
4712 // ...PointTree.Visitor...
4713 //
4714 // Then the type of the last expression above is
4715 // Tree<Point>.Visitor.
4716 else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
4717 Type normOuter = site;
4718 if (normOuter.hasTag(CLASS)) {
4719 normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
4720 }
4721 if (normOuter == null) // perhaps from an import
4722 normOuter = types.erasure(ownOuter);
4723 if (normOuter != ownOuter)
4724 owntype = new ClassType(
4725 normOuter, List.nil(), owntype.tsym,
4726 owntype.getMetadata(), owntype.getFlavor());
4727 }
4728 }
4729 break;
4730 case VAR:
4731 VarSymbol v = (VarSymbol)sym;
4732
4733 if (env.info.enclVar != null
4734 && v.type.hasTag(NONE)) {
4735 //self reference to implicitly typed variable declaration
4736 log.error(TreeInfo.positionFor(v, env.enclClass), Errors.CantInferLocalVarType(v.name, Fragments.LocalSelfRef));
4737 return tree.type = v.type = types.createErrorType(v.type);
4738 }
4739
4740 // Test (4): if symbol is an instance field of a raw type,
4741 // which is being assigned to, issue an unchecked warning if
4742 // its type changes under erasure.
4743 if (KindSelector.ASG.subset(pkind()) &&
4744 v.owner.kind == TYP &&
4745 (v.flags() & STATIC) == 0 &&
4746 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
4769 break;
4770 case MTH: {
4771 owntype = checkMethod(site, sym,
4772 new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext, resultInfo.checkMode),
4773 env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
4774 resultInfo.pt.getTypeArguments());
4775 break;
4776 }
4777 case PCK: case ERR:
4778 owntype = sym.type;
4779 break;
4780 default:
4781 throw new AssertionError("unexpected kind: " + sym.kind +
4782 " in tree " + tree);
4783 }
4784
4785 // Emit a `deprecation' warning if symbol is deprecated.
4786 // (for constructors (but not for constructor references), the error
4787 // was given when the constructor was resolved)
4788
4789 if (!names.isInitOrVNew(sym.name) || tree.hasTag(REFERENCE)) {
4790 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
4791 chk.checkSunAPI(tree.pos(), sym);
4792 chk.checkProfile(tree.pos(), sym);
4793 chk.checkPreview(tree.pos(), env.info.scope.owner, sym);
4794 }
4795
4796 // If symbol is a variable, check that its type and
4797 // kind are compatible with the prototype and protokind.
4798 return check(tree, owntype, sym.kind.toSelector(), resultInfo);
4799 }
4800
4801 /** Check that variable is initialized and evaluate the variable's
4802 * initializer, if not yet done. Also check that variable is not
4803 * referenced before it is defined.
4804 * @param tree The tree making up the variable reference.
4805 * @param env The current environment.
4806 * @param v The variable's symbol.
4807 */
4808 private void checkInit(JCTree tree,
4809 Env<AttrContext> env,
5023 //depending on the current check context
5024 resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
5025 return types.createErrorType(site);
5026 } catch (Resolve.InapplicableMethodException ex) {
5027 final JCDiagnostic diag = ex.getDiagnostic();
5028 Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
5029 @Override
5030 protected Pair<Symbol, JCDiagnostic> errCandidate() {
5031 return new Pair<>(sym, diag);
5032 }
5033 };
5034 List<Type> argtypes2 = argtypes.map(
5035 rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
5036 JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
5037 env.tree, sym, site, sym.name, argtypes2, typeargtypes);
5038 log.report(errDiag);
5039 return types.createErrorType(site);
5040 }
5041 }
5042
5043 public void visitDefaultValue(JCDefaultValue tree) {
5044 if (!allowPrimitiveClasses) {
5045 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.pos(),
5046 Feature.PRIMITIVE_CLASSES.error(sourceName));
5047 }
5048
5049 // Attribute the qualifier expression, and determine its symbol (if any).
5050 Type site = attribTree(tree.clazz, env, new ResultInfo(KindSelector.TYP_PCK, Type.noType));
5051 if (!pkind().contains(KindSelector.TYP_PCK))
5052 site = capture(site); // Capture field access
5053 if (!allowPrimitiveClasses) {
5054 result = types.createErrorType(names._default, site.tsym, site);
5055 } else {
5056 Symbol sym = switch (site.getTag()) {
5057 case WILDCARD -> throw new AssertionError(tree);
5058 case PACKAGE -> {
5059 log.error(tree.pos, Errors.CantResolveLocation(Kinds.KindName.CLASS, site.tsym.getQualifiedName(), null, null,
5060 Fragments.Location(Kinds.typeKindName(env.enclClass.type), env.enclClass.type, null)));
5061 yield syms.errSymbol;
5062 }
5063 case ERROR -> types.createErrorType(names._default, site.tsym, site).tsym;
5064 default -> new VarSymbol(STATIC, names._default, site, site.tsym);
5065 };
5066
5067 if (site.hasTag(TYPEVAR) && sym.kind != ERR) {
5068 site = types.skipTypeVars(site, true);
5069 }
5070 result = checkId(tree, site, sym, env, resultInfo);
5071 }
5072 }
5073
5074 public void visitLiteral(JCLiteral tree) {
5075 result = check(tree, litType(tree.typetag).constType(tree.value),
5076 KindSelector.VAL, resultInfo);
5077 }
5078 //where
5079 /** Return the type of a literal with given type tag.
5080 */
5081 Type litType(TypeTag tag) {
5082 return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
5083 }
5084
5085 public void visitTypeIdent(JCPrimitiveTypeTree tree) {
5086 result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
5087 }
5088
5089 public void visitTypeArray(JCArrayTypeTree tree) {
5090 Type etype = attribType(tree.elemtype, env);
5091 Type type = new ArrayType(etype, syms.arrayClass);
5092 result = check(tree, type, KindSelector.TYP, resultInfo);
5093 }
5120 }
5121 // Compute the proper generic outer
5122 Type clazzOuter = clazztype.getEnclosingType();
5123 if (clazzOuter.hasTag(CLASS)) {
5124 Type site;
5125 JCExpression clazz = TreeInfo.typeIn(tree.clazz);
5126 if (clazz.hasTag(IDENT)) {
5127 site = env.enclClass.sym.type;
5128 } else if (clazz.hasTag(SELECT)) {
5129 site = ((JCFieldAccess) clazz).selected.type;
5130 } else throw new AssertionError(""+tree);
5131 if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
5132 if (site.hasTag(CLASS))
5133 site = types.asOuterSuper(site, clazzOuter.tsym);
5134 if (site == null)
5135 site = types.erasure(clazzOuter);
5136 clazzOuter = site;
5137 }
5138 }
5139 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
5140 clazztype.getMetadata(), clazztype.getFlavor());
5141 } else {
5142 if (formals.length() != 0) {
5143 log.error(tree.pos(),
5144 Errors.WrongNumberTypeArgs(Integer.toString(formals.length())));
5145 } else {
5146 log.error(tree.pos(), Errors.TypeDoesntTakeParams(clazztype.tsym));
5147 }
5148 owntype = types.createErrorType(tree.type);
5149 }
5150 }
5151 result = check(tree, owntype, KindSelector.TYP, resultInfo);
5152 }
5153
5154 public void visitTypeUnion(JCTypeUnion tree) {
5155 ListBuffer<Type> multicatchTypes = new ListBuffer<>();
5156 ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
5157 for (JCExpression typeTree : tree.alternatives) {
5158 Type ctype = attribType(typeTree, env);
5159 ctype = chk.checkType(typeTree.pos(),
5160 chk.checkClassType(typeTree.pos(), ctype),
5247 if (bounds.length() == 0) {
5248 return syms.objectType;
5249 } else if (bounds.length() == 1) {
5250 return bounds.head.type;
5251 } else {
5252 Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
5253 // ... the variable's bound is a class type flagged COMPOUND
5254 // (see comment for TypeVar.bound).
5255 // In this case, generate a class tree that represents the
5256 // bound class, ...
5257 JCExpression extending;
5258 List<JCExpression> implementing;
5259 if (!bounds.head.type.isInterface()) {
5260 extending = bounds.head;
5261 implementing = bounds.tail;
5262 } else {
5263 extending = null;
5264 implementing = bounds;
5265 }
5266 JCClassDecl cd = make.at(tree).ClassDef(
5267 make.Modifiers(PUBLIC | ABSTRACT | (extending != null && TreeInfo.symbol(extending).isPrimitiveClass() ? PRIMITIVE_CLASS : 0)),
5268 names.empty, List.nil(),
5269 extending, implementing, List.nil());
5270
5271 ClassSymbol c = (ClassSymbol)owntype.tsym;
5272 Assert.check((c.flags() & COMPOUND) != 0);
5273 cd.sym = c;
5274 c.sourcefile = env.toplevel.sourcefile;
5275
5276 // ... and attribute the bound class
5277 c.flags_field |= UNATTRIBUTED;
5278 Env<AttrContext> cenv = enter.classEnv(cd, env);
5279 typeEnvs.put(c, cenv);
5280 attribClass(c);
5281 return owntype;
5282 }
5283 }
5284
5285 public void visitWildcard(JCWildcard tree) {
5286 //- System.err.println("visitWildcard("+tree+");");//DEBUG
5287 Type type = (tree.kind.kind == BoundKind.UNBOUND)
5288 ? syms.objectType
5289 : attribType(tree.inner, env);
5290 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type, false),
5291 tree.kind.kind,
5292 syms.boundClass),
5293 KindSelector.TYP, resultInfo);
5294 }
5295
5296 public void visitAnnotation(JCAnnotation tree) {
5297 Assert.error("should be handled in annotate");
5298 }
5299
5300 @Override
5301 public void visitModifiers(JCModifiers tree) {
5302 //error recovery only:
5303 Assert.check(resultInfo.pkind == KindSelector.ERR);
5304
5305 attribAnnotationTypes(tree.annotations, env);
5306 }
5307
5308 public void visitAnnotatedType(JCAnnotatedType tree) {
5309 attribAnnotationTypes(tree.annotations, env);
5310 Type underlyingType = attribType(tree.underlyingType, env);
5388
5389 try {
5390 deferredLintHandler.flush(env.tree.pos());
5391 attrib.accept(env);
5392 } finally {
5393 log.useSource(prev);
5394 chk.setLint(prevLint);
5395 }
5396 }
5397
5398 /** Main method: attribute class definition associated with given class symbol.
5399 * reporting completion failures at the given position.
5400 * @param pos The source position at which completion errors are to be
5401 * reported.
5402 * @param c The class symbol whose definition will be attributed.
5403 */
5404 public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
5405 try {
5406 annotate.flush();
5407 attribClass(c);
5408 if (allowPrimitiveClasses && c.type.isPrimitiveClass()) {
5409 final Env<AttrContext> env = typeEnvs.get(c);
5410 if (env != null && env.tree != null && env.tree.hasTag(CLASSDEF))
5411 chk.checkNonCyclicMembership((JCClassDecl)env.tree);
5412 }
5413 } catch (CompletionFailure ex) {
5414 chk.completionError(pos, ex);
5415 }
5416 }
5417
5418 /** Attribute class definition associated with given class symbol.
5419 * @param c The class symbol whose definition will be attributed.
5420 */
5421 void attribClass(ClassSymbol c) throws CompletionFailure {
5422 if (c.type.hasTag(ERROR)) return;
5423
5424 // Check for cycles in the inheritance graph, which can arise from
5425 // ill-formed class files.
5426 chk.checkNonCyclic(null, c.type);
5427
5428 Type st = types.supertype(c.type);
5429 if ((c.flags_field & Flags.COMPOUND) == 0 &&
5430 (c.flags_field & Flags.SUPER_OWNER_ATTRIBUTED) == 0) {
5431 // First, attribute superclass.
5432 if (st.hasTag(CLASS))
5513 .filter(s -> s.tsym.isSealed())
5514 .map(s -> (ClassSymbol) s.tsym)
5515 .collect(List.collector());
5516
5517 if (sealedSupers.isEmpty()) {
5518 if ((c.flags_field & Flags.NON_SEALED) != 0) {
5519 boolean hasErrorSuper = false;
5520
5521 hasErrorSuper |= types.directSupertypes(c.type)
5522 .stream()
5523 .anyMatch(s -> s.tsym.kind == Kind.ERR);
5524
5525 ClassType ct = (ClassType) c.type;
5526
5527 hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5528
5529 if (!hasErrorSuper) {
5530 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5531 }
5532 }
5533 } else if ((c.flags_field & Flags.COMPOUND) == 0) {
5534 if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5535 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5536 }
5537
5538 if (!c.type.isCompound()) {
5539 for (ClassSymbol supertypeSym : sealedSupers) {
5540 if (!supertypeSym.permitted.contains(c.type.tsym)) {
5541 log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5542 }
5543 }
5544 if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5545 log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5546 c.isInterface() ?
5547 Errors.NonSealedOrSealedExpected :
5548 Errors.NonSealedSealedOrFinalExpected);
5549 }
5550 }
5551 }
5552
5553 // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
5568
5569 try {
5570 deferredLintHandler.flush(env.tree);
5571 env.info.returnResult = null;
5572 // java.lang.Enum may not be subclassed by a non-enum
5573 if (st.tsym == syms.enumSym &&
5574 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5575 log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5576
5577 // Enums may not be extended by source-level classes
5578 if (st.tsym != null &&
5579 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5580 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5581 log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5582 }
5583
5584 if (rs.isSerializable(c.type)) {
5585 env.info.isSerializable = true;
5586 }
5587
5588 if (c.isValueClass()) {
5589 Assert.check(env.tree.hasTag(CLASSDEF));
5590 chk.checkConstraintsOfValueClass(env.tree.pos(), c);
5591 }
5592
5593 attribClassBody(env, c);
5594
5595 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5596 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5597 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5598 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5599 } finally {
5600 env.info.returnResult = prevReturnRes;
5601 log.useSource(prev);
5602 chk.setLint(prevLint);
5603 }
5604
5605 }
5606 }
5607
5608 public void visitImport(JCImport tree) {
5609 // nothing to do
5610 }
5611
5612 public void visitModuleDef(JCModuleDecl tree) {
|