28 import java.util.*;
29 import java.util.function.BiConsumer;
30 import java.util.function.Consumer;
31 import java.util.stream.Stream;
32
33 import javax.lang.model.element.ElementKind;
34 import javax.tools.JavaFileObject;
35
36 import com.sun.source.tree.CaseTree;
37 import com.sun.source.tree.IdentifierTree;
38 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
39 import com.sun.source.tree.MemberSelectTree;
40 import com.sun.source.tree.TreeVisitor;
41 import com.sun.source.util.SimpleTreeVisitor;
42 import com.sun.tools.javac.code.*;
43 import com.sun.tools.javac.code.Lint.LintCategory;
44 import com.sun.tools.javac.code.Scope.WriteableScope;
45 import com.sun.tools.javac.code.Source.Feature;
46 import com.sun.tools.javac.code.Symbol.*;
47 import com.sun.tools.javac.code.Type.*;
48 import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError;
49 import com.sun.tools.javac.comp.ArgumentAttr.LocalCacheContext;
50 import com.sun.tools.javac.comp.Check.CheckContext;
51 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
52 import com.sun.tools.javac.comp.MatchBindingsComputer.MatchBindings;
53 import com.sun.tools.javac.jvm.*;
54
55 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond;
56 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArg;
57 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArgs;
58
59 import com.sun.tools.javac.resources.CompilerProperties.Errors;
60 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
61 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
62 import com.sun.tools.javac.tree.*;
63 import com.sun.tools.javac.tree.JCTree.*;
64 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
65 import com.sun.tools.javac.util.*;
66 import com.sun.tools.javac.util.DefinedBy.Api;
67 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
149 infer = Infer.instance(context);
150 analyzer = Analyzer.instance(context);
151 deferredAttr = DeferredAttr.instance(context);
152 cfolder = ConstFold.instance(context);
153 target = Target.instance(context);
154 types = Types.instance(context);
155 preview = Preview.instance(context);
156 diags = JCDiagnostic.Factory.instance(context);
157 annotate = Annotate.instance(context);
158 typeAnnotations = TypeAnnotations.instance(context);
159 deferredLintHandler = DeferredLintHandler.instance(context);
160 typeEnvs = TypeEnvs.instance(context);
161 dependencies = Dependencies.instance(context);
162 argumentAttr = ArgumentAttr.instance(context);
163 matchBindingsComputer = MatchBindingsComputer.instance(context);
164 attrRecover = AttrRecover.instance(context);
165
166 Options options = Options.instance(context);
167
168 Source source = Source.instance(context);
169 allowReifiableTypesInInstanceof = Feature.REIFIABLE_TYPES_INSTANCEOF.allowedInSource(source);
170 allowRecords = Feature.RECORDS.allowedInSource(source);
171 allowPatternSwitch = (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH)) &&
172 Feature.PATTERN_SWITCH.allowedInSource(source);
173 allowUnconditionalPatternsInstanceOf =
174 Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.allowedInSource(source);
175 sourceName = source.name;
176 useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
177
178 statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
179 varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
180 unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
181 methodAttrInfo = new MethodAttrInfo();
182 unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
183 unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
184 recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
185 }
186
187 /** Switch: reifiable types in instanceof enabled?
188 */
189 boolean allowReifiableTypesInInstanceof;
190
191 /** Are records allowed
192 */
193 private final boolean allowRecords;
194
195 /** Are patterns in switch allowed
196 */
197 private final boolean allowPatternSwitch;
198
199 /** Are unconditional patterns in instanceof allowed
200 */
201 private final boolean allowUnconditionalPatternsInstanceOf;
202
203 /**
204 * Switch: warn about use of variable before declaration?
205 * RFE: 6425594
206 */
255 found;
256 }
257 if (resultInfo.checkMode.updateTreeType()) {
258 tree.type = owntype;
259 }
260 return owntype;
261 }
262
263 /** Is given blank final variable assignable, i.e. in a scope where it
264 * may be assigned to even though it is final?
265 * @param v The blank final variable.
266 * @param env The current environment.
267 */
268 boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
269 Symbol owner = env.info.scope.owner;
270 // owner refers to the innermost variable, method or
271 // initializer block declaration at this point.
272 boolean isAssignable =
273 v.owner == owner
274 ||
275 ((owner.name == names.init || // i.e. we are in a constructor
276 owner.kind == VAR || // i.e. we are in a variable initializer
277 (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block
278 &&
279 v.owner == owner.owner
280 &&
281 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
282 boolean insideCompactConstructor = env.enclMethod != null && TreeInfo.isCompactConstructor(env.enclMethod);
283 return isAssignable & !insideCompactConstructor;
284 }
285
286 /** Check that variable can be assigned to.
287 * @param pos The current source code position.
288 * @param v The assigned variable
289 * @param base If the variable is referred to in a Select, the part
290 * to the left of the `.', null otherwise.
291 * @param env The current environment.
292 */
293 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
294 if (v.name == names._this) {
295 log.error(pos, Errors.CantAssignValToThis);
782 /** Attribute a type argument list, returning a list of types.
783 * Check that all the types are references.
784 */
785 List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
786 List<Type> types = attribAnyTypes(trees, env);
787 return chk.checkRefTypes(trees, types);
788 }
789
790 /**
791 * Attribute type variables (of generic classes or methods).
792 * Compound types are attributed later in attribBounds.
793 * @param typarams the type variables to enter
794 * @param env the current environment
795 */
796 void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env, boolean checkCyclic) {
797 for (JCTypeParameter tvar : typarams) {
798 TypeVar a = (TypeVar)tvar.type;
799 a.tsym.flags_field |= UNATTRIBUTED;
800 a.setUpperBound(Type.noType);
801 if (!tvar.bounds.isEmpty()) {
802 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
803 for (JCExpression bound : tvar.bounds.tail)
804 bounds = bounds.prepend(attribType(bound, env));
805 types.setBounds(a, bounds.reverse());
806 } else {
807 // if no bounds are given, assume a single bound of
808 // java.lang.Object.
809 types.setBounds(a, List.of(syms.objectType));
810 }
811 a.tsym.flags_field &= ~UNATTRIBUTED;
812 }
813 if (checkCyclic) {
814 for (JCTypeParameter tvar : typarams) {
815 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
816 }
817 }
818 }
819
820 /**
821 * Attribute the type references in a list of annotations.
822 */
823 void attribAnnotationTypes(List<JCAnnotation> annotations,
824 Env<AttrContext> env) {
1054 log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.MethodMustBePublic));
1055 }
1056 if (!types.isSameType(tree.sym.type.getReturnType(), recordComponent.get().type)) {
1057 log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym,
1058 Fragments.AccessorReturnTypeDoesntMatch(tree.sym, recordComponent.get())));
1059 }
1060 if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1061 log.error(tree,
1062 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodCantThrowException));
1063 }
1064 if (!tree.typarams.isEmpty()) {
1065 log.error(tree,
1066 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeGeneric));
1067 }
1068 if (tree.sym.isStatic()) {
1069 log.error(tree,
1070 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeStatic));
1071 }
1072 }
1073
1074 if (tree.name == names.init) {
1075 // if this a constructor other than the canonical one
1076 if ((tree.sym.flags_field & RECORD) == 0) {
1077 JCMethodInvocation app = TreeInfo.firstConstructorCall(tree);
1078 if (app == null ||
1079 TreeInfo.name(app.meth) != names._this ||
1080 !checkFirstConstructorStat(app, tree, false)) {
1081 log.error(tree, Errors.FirstStatementMustBeCallToAnotherConstructor(env.enclClass.sym));
1082 }
1083 } else {
1084 // but if it is the canonical:
1085
1086 /* if user generated, then it shouldn't:
1087 * - have an accessibility stricter than that of the record type
1088 * - explicitly invoke any other constructor
1089 */
1090 if ((tree.sym.flags_field & GENERATEDCONSTR) == 0) {
1091 if (Check.protection(m.flags()) > Check.protection(env.enclClass.sym.flags())) {
1092 log.error(tree,
1093 (env.enclClass.sym.flags() & AccessFlags) == 0 ?
1094 Errors.InvalidCanonicalConstructorInRecord(
1169 if (tree.defaultValue != null) {
1170 if ((owner.flags() & ANNOTATION) == 0)
1171 log.error(tree.pos(),
1172 Errors.DefaultAllowedInIntfAnnotationMember);
1173 }
1174 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1175 log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract);
1176 } else {
1177 if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1178 if ((owner.flags() & INTERFACE) != 0) {
1179 log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1180 } else {
1181 log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1182 }
1183 } else if ((tree.mods.flags & NATIVE) != 0) {
1184 log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1185 }
1186 // Add an implicit super() call unless an explicit call to
1187 // super(...) or this(...) is given
1188 // or we are compiling class java.lang.Object.
1189 if (tree.name == names.init && owner.type != syms.objectType) {
1190 JCBlock body = tree.body;
1191 if (body.stats.isEmpty() ||
1192 TreeInfo.getConstructorInvocationName(body.stats, names) == names.empty) {
1193 JCStatement supCall = make.at(body.pos).Exec(make.Apply(List.nil(),
1194 make.Ident(names._super), make.Idents(List.nil())));
1195 body.stats = body.stats.prepend(supCall);
1196 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1197 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1198 TreeInfo.isSuperCall(body.stats.head)) {
1199 // enum constructors are not allowed to call super
1200 // directly, so make sure there aren't any super calls
1201 // in enum constructors, except in the compiler
1202 // generated one.
1203 log.error(tree.body.stats.head.pos(),
1204 Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1205 }
1206 if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1207 List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1208 List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1209 if (!initParamNames.equals(recordComponentNames)) {
1210 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1211 Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1212 }
1213 if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1214 log.error(tree,
1215 Errors.InvalidCanonicalConstructorInRecord(
1216 TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical,
1217 env.enclClass.sym.name,
1218 Fragments.ThrowsClauseNotAllowedForCanonicalConstructor(
1219 TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical)));
1220 }
1221 }
1222 }
1223
1224 // Attribute all type annotations in the body
1272 annotate.queueScanTreeAndTypeAnnotate(tree.init, env, tree.sym, tree.pos());
1273 annotate.flush();
1274 }
1275 }
1276
1277 VarSymbol v = tree.sym;
1278 Lint lint = env.info.lint.augment(v);
1279 Lint prevLint = chk.setLint(lint);
1280
1281 // Check that the variable's declared type is well-formed.
1282 boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
1283 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
1284 (tree.sym.flags() & PARAMETER) != 0;
1285 chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1286
1287 try {
1288 v.getConstValue(); // ensure compile-time constant initializer is evaluated
1289 deferredLintHandler.flush(tree.pos());
1290 chk.checkDeprecatedAnnotation(tree.pos(), v);
1291
1292 if (tree.init != null) {
1293 if ((v.flags_field & FINAL) == 0 ||
1294 !memberEnter.needsLazyConstValue(tree.init)) {
1295 // Not a compile-time constant
1296 // Attribute initializer in a new environment
1297 // with the declared variable as owner.
1298 // Check that initializer conforms to variable's declared type.
1299 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1300 initEnv.info.lint = lint;
1301 // In order to catch self-references, we set the variable's
1302 // declaration position to maximal possible value, effectively
1303 // marking the variable as undefined.
1304 initEnv.info.enclVar = v;
1305 attribExpr(tree.init, initEnv, v.type);
1306 if (tree.isImplicitlyTyped()) {
1307 //fixup local variable type
1308 v.type = chk.checkLocalVarType(tree, tree.init.type, tree.name);
1309 }
1310 }
1311 if (tree.isImplicitlyTyped()) {
1312 setSyntheticVariableType(tree, v.type);
1313 }
1314 }
1315 result = tree.type = v.type;
1316 if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1317 if (isNonArgsMethodInObject(v.name)) {
1318 log.error(tree, Errors.IllegalRecordComponentName(v));
1319 }
1320 }
1321 }
1322 finally {
1323 chk.setLint(prevLint);
1324 }
1325 }
1326
1327 private boolean isNonArgsMethodInObject(Name name) {
1328 for (Symbol s : syms.objectType.tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) {
1329 if (s.type.getParameterTypes().isEmpty()) {
1330 return true;
1331 }
1332 }
1333 return false;
1334 }
1335
1336 Fragment canInferLocalVarType(JCVariableDecl tree) {
1337 LocalInitScanner lis = new LocalInitScanner();
1338 lis.scan(tree.init);
1339 return lis.badInferenceMsg;
1340 }
1341
1342 static class LocalInitScanner extends TreeScanner {
1343 Fragment badInferenceMsg = null;
1344 boolean needsTarget = true;
1345
1346 @Override
1347 public void visitNewArray(JCNewArray tree) {
1348 if (tree.elemtype == null && needsTarget) {
1349 badInferenceMsg = Fragments.LocalArrayMissingTarget;
1350 }
1351 }
1352
1353 @Override
1530 introducingStatement = labeled;
1531 }
1532
1533 //include condition's body when false after the while, if cannot get out of the loop
1534 bindings.forEach(env.info.scope::enter);
1535 bindings.forEach(BindingSymbol::preserveBinding);
1536 }
1537
1538 public void visitForeachLoop(JCEnhancedForLoop tree) {
1539 Env<AttrContext> loopEnv =
1540 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1541 try {
1542 //the Formal Parameter of a for-each loop is not in the scope when
1543 //attributing the for-each expression; we mimic this by attributing
1544 //the for-each expression first (against original scope).
1545 Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
1546 chk.checkNonVoid(tree.pos(), exprType);
1547 Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
1548 if (elemtype == null) {
1549 // or perhaps expr implements Iterable<T>?
1550 Type base = types.asSuper(exprType, syms.iterableType.tsym);
1551 if (base == null) {
1552 log.error(tree.expr.pos(),
1553 Errors.ForeachNotApplicableToType(exprType,
1554 Fragments.TypeReqArrayOrIterable));
1555 elemtype = types.createErrorType(exprType);
1556 } else {
1557 List<Type> iterableParams = base.allparams();
1558 elemtype = iterableParams.isEmpty()
1559 ? syms.objectType
1560 : types.wildUpperBound(iterableParams.head);
1561
1562 // Check the return type of the method iterator().
1563 // This is the bare minimum we need to verify to make sure code generation doesn't crash.
1564 Symbol iterSymbol = rs.resolveInternalMethod(tree.pos(),
1565 loopEnv, types.skipTypeVars(exprType, false), names.iterator, List.nil(), List.nil());
1566 if (types.asSuper(iterSymbol.type.getReturnType(), syms.iteratorType.tsym) == null) {
1567 log.error(tree.pos(),
1568 Errors.ForeachNotApplicableToType(exprType, Fragments.TypeReqArrayOrIterable));
1569 }
1570 }
1571 }
1572 if (tree.var.isImplicitlyTyped()) {
1573 Type inferredType = chk.checkLocalVarType(tree.var, elemtype, tree.var.name);
1574 setSyntheticVariableType(tree.var, inferredType);
1575 }
1576 attribStat(tree.var, loopEnv);
1577 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
1578 loopEnv.tree = tree; // before, we were not in loop!
1579 attribStat(tree.body, loopEnv);
1580 result = null;
1581 }
1582 finally {
1583 loopEnv.info.scope.leave();
1584 }
1585 }
1586
1892 // where
1893 /** Return the selected enumeration constant symbol, or null. */
1894 private Symbol enumConstant(JCTree tree, Type enumType) {
1895 if (tree.hasTag(IDENT)) {
1896 JCIdent ident = (JCIdent)tree;
1897 Name name = ident.name;
1898 for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1899 if (sym.kind == VAR) {
1900 Symbol s = ident.sym = sym;
1901 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1902 ident.type = s.type;
1903 return ((s.flags_field & Flags.ENUM) == 0)
1904 ? null : s;
1905 }
1906 }
1907 }
1908 return null;
1909 }
1910
1911 public void visitSynchronized(JCSynchronized tree) {
1912 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1913 if (env.info.lint.isEnabled(LintCategory.SYNCHRONIZATION) && isValueBased(tree.lock.type)) {
1914 log.warning(LintCategory.SYNCHRONIZATION, tree.pos(), Warnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
1915 }
1916 attribStat(tree.body, env);
1917 result = null;
1918 }
1919 // where
1920 private boolean isValueBased(Type t) {
1921 return t != null && t.tsym != null && (t.tsym.flags() & VALUE_BASED) != 0;
1922 }
1923
1924
1925 public void visitTry(JCTry tree) {
1926 // Create a new local environment with a local
1927 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1928 try {
1929 boolean isTryWithResource = tree.resources.nonEmpty();
1930 // Create a nested environment for attributing the try block if needed
1931 Env<AttrContext> tryEnv = isTryWithResource ?
1932 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1983 chk.checkType(c.param.vartype.pos(),
1984 chk.checkClassType(c.param.vartype.pos(), ctype),
1985 syms.throwableType);
1986 attribStat(c.body, catchEnv);
1987 } finally {
1988 catchEnv.info.scope.leave();
1989 }
1990 }
1991
1992 // Attribute finalizer
1993 if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
1994 result = null;
1995 }
1996 finally {
1997 localEnv.info.scope.leave();
1998 }
1999 }
2000
2001 void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
2002 if (!resource.isErroneous() &&
2003 types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
2004 !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
2005 Symbol close = syms.noSymbol;
2006 Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
2007 try {
2008 close = rs.resolveQualifiedMethod(pos,
2009 env,
2010 types.skipTypeVars(resource, false),
2011 names.close,
2012 List.nil(),
2013 List.nil());
2014 }
2015 finally {
2016 log.popDiagnosticHandler(discardHandler);
2017 }
2018 if (close.kind == MTH &&
2019 close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
2020 chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
2021 env.info.lint.isEnabled(LintCategory.TRY)) {
2022 log.warning(LintCategory.TRY, pos, Warnings.TryResourceThrowsInterruptedExc(resource));
2023 }
2172 if (unboxedTypes.stream().allMatch(t -> t.isPrimitive())) {
2173 // If one arm has an integer subrange type (i.e., byte,
2174 // short, or char), and the other is an integer constant
2175 // that fits into the subrange, return the subrange type.
2176 for (Type type : unboxedTypes) {
2177 if (!type.getTag().isStrictSubRangeOf(INT)) {
2178 continue;
2179 }
2180 if (unboxedTypes.stream().filter(t -> t != type).allMatch(t -> t.hasTag(INT) && types.isAssignable(t, type)))
2181 return type.baseType();
2182 }
2183
2184 for (TypeTag tag : primitiveTags) {
2185 Type candidate = syms.typeOfTag[tag.ordinal()];
2186 if (unboxedTypes.stream().allMatch(t -> types.isSubtype(t, candidate))) {
2187 return candidate;
2188 }
2189 }
2190 }
2191
2192 // Those were all the cases that could result in a primitive
2193 condTypes = condTypes.stream()
2194 .map(t -> t.isPrimitive() ? types.boxedClass(t).type : t)
2195 .collect(List.collector());
2196
2197 for (Type type : condTypes) {
2198 if (condTypes.stream().filter(t -> t != type).allMatch(t -> types.isAssignable(t, type)))
2199 return type.baseType();
2200 }
2201
2202 Iterator<DiagnosticPosition> posIt = positions.iterator();
2203
2204 condTypes = condTypes.stream()
2205 .map(t -> chk.checkNonVoid(posIt.next(), t))
2206 .collect(List.collector());
2207
2208 // both are known to be reference types. The result is
2209 // lub(thentype,elsetype). This cannot fail, as it will
2210 // always be possible to infer "Object" if nothing better.
2211 return types.lub(condTypes.stream()
2212 .map(t -> t.baseType())
2213 .filter(t -> !t.hasTag(BOT))
2214 .collect(List.collector()));
2215 }
2216
2217 static final TypeTag[] primitiveTags = new TypeTag[]{
2218 BYTE,
2219 CHAR,
2220 SHORT,
2221 INT,
2222 LONG,
2223 FLOAT,
2224 DOUBLE,
2225 BOOLEAN,
2226 };
2227
2228 Env<AttrContext> bindingEnv(Env<AttrContext> env, List<BindingSymbol> bindings) {
2626 : env.enclClass.sym.type;
2627 Symbol msym = TreeInfo.symbol(tree.meth);
2628 restype = adjustMethodReturnType(msym, qualifier, methName, argtypes, restype);
2629
2630 chk.checkRefTypes(tree.typeargs, typeargtypes);
2631
2632 // Check that value of resulting type is admissible in the
2633 // current context. Also, capture the return type
2634 Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true);
2635 result = check(tree, capturedRes, KindSelector.VAL, resultInfo);
2636 }
2637 chk.validate(tree.typeargs, localEnv);
2638 }
2639 //where
2640 Type adjustMethodReturnType(Symbol msym, Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
2641 if (msym != null &&
2642 (msym.owner == syms.objectType.tsym || msym.owner.isInterface()) &&
2643 methodName == names.getClass &&
2644 argtypes.isEmpty()) {
2645 // as a special case, x.getClass() has type Class<? extends |X|>
2646 return new ClassType(restype.getEnclosingType(),
2647 List.of(new WildcardType(types.erasure(qualifierType.baseType()),
2648 BoundKind.EXTENDS,
2649 syms.boundClass)),
2650 restype.tsym,
2651 restype.getMetadata());
2652 } else if (msym != null &&
2653 msym.owner == syms.arrayClass &&
2654 methodName == names.clone &&
2655 types.isArray(qualifierType)) {
2656 // as a special case, array.clone() has a result that is
2657 // the same as static type of the array being cloned
2658 return qualifierType;
2659 } else {
2660 return restype;
2661 }
2662 }
2663
2664 /** Check that given application node appears as first statement
2665 * in a constructor call.
2666 * @param tree The application node
2667 * @param enclMethod The enclosing method of the application.
2668 * @param error Should an error be issued?
2669 */
2670 boolean checkFirstConstructorStat(JCMethodInvocation tree, JCMethodDecl enclMethod, boolean error) {
2671 if (enclMethod != null && enclMethod.name == names.init) {
2672 JCBlock body = enclMethod.body;
2673 if (body.stats.head.hasTag(EXEC) &&
2674 ((JCExpressionStatement) body.stats.head).expr == tree)
2675 return true;
2676 }
2677 if (error) {
2678 log.error(tree.pos(),
2679 Errors.CallMustBeFirstStmtInCtor(TreeInfo.name(tree.meth)));
2680 }
2681 return false;
2682 }
2683
2684 /** Obtain a method type with given argument types.
2685 */
2686 Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
2687 MethodType mt = new MethodType(argtypes, restype, List.nil(), syms.methodClass);
2688 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
2689 }
2690
2691 public void visitNewClass(final JCNewClass tree) {
2800 }
2801
2802 // Attribute constructor arguments.
2803 ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2804 final KindSelector pkind =
2805 attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
2806 List<Type> argtypes = argtypesBuf.toList();
2807 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
2808
2809 if (clazztype.hasTag(CLASS) || clazztype.hasTag(ERROR)) {
2810 // Enums may not be instantiated except implicitly
2811 if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 &&
2812 (!env.tree.hasTag(VARDEF) ||
2813 (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 ||
2814 ((JCVariableDecl) env.tree).init != tree))
2815 log.error(tree.pos(), Errors.EnumCantBeInstantiated);
2816
2817 boolean isSpeculativeDiamondInferenceRound = TreeInfo.isDiamond(tree) &&
2818 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2819 boolean skipNonDiamondPath = false;
2820 // Check that class is not abstract
2821 if (cdef == null && !isSpeculativeDiamondInferenceRound && // class body may be nulled out in speculative tree copy
2822 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
2823 log.error(tree.pos(),
2824 Errors.AbstractCantBeInstantiated(clazztype.tsym));
2825 skipNonDiamondPath = true;
2826 } else if (cdef != null && clazztype.tsym.isInterface()) {
2827 // Check that no constructor arguments are given to
2828 // anonymous classes implementing an interface
2829 if (!argtypes.isEmpty())
2830 log.error(tree.args.head.pos(), Errors.AnonClassImplIntfNoArgs);
2831
2832 if (!typeargtypes.isEmpty())
2833 log.error(tree.typeargs.head.pos(), Errors.AnonClassImplIntfNoTypeargs);
2834
2835 // Error recovery: pretend no arguments were supplied.
2836 argtypes = List.nil();
2837 typeargtypes = List.nil();
2838 skipNonDiamondPath = true;
2839 }
2840 if (TreeInfo.isDiamond(tree)) {
2841 ClassType site = new ClassType(clazztype.getEnclosingType(),
2842 clazztype.tsym.type.getTypeArguments(),
2843 clazztype.tsym,
2844 clazztype.getMetadata());
2845
2846 Env<AttrContext> diamondEnv = localEnv.dup(tree);
2847 diamondEnv.info.selectSuper = cdef != null || tree.classDeclRemoved();
2848 diamondEnv.info.pendingResolutionPhase = null;
2849
2850 //if the type of the instance creation expression is a class type
2851 //apply method resolution inference (JLS 15.12.2.7). The return type
2852 //of the resolved constructor will be a partially instantiated type
2853 Symbol constructor = rs.resolveDiamond(tree.pos(),
2854 diamondEnv,
2855 site,
2856 argtypes,
2857 typeargtypes);
2858 tree.constructor = constructor.baseSymbol();
2859
2860 final TypeSymbol csym = clazztype.tsym;
2861 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes),
2862 diamondContext(tree, csym, resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
2863 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
2864 constructorType = checkId(tree, site,
2978 this.resultInfo = prevResult;
2979 }
2980 });
2981 } else {
2982 if (isDiamond && clazztype.hasTag(CLASS)) {
2983 List<Type> invalidDiamondArgs = chk.checkDiamondDenotable((ClassType)clazztype);
2984 if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
2985 // One or more types inferred in the previous steps is non-denotable.
2986 Fragment fragment = Diamond(clazztype.tsym);
2987 log.error(tree.clazz.pos(),
2988 Errors.CantApplyDiamond1(
2989 fragment,
2990 invalidDiamondArgs.size() > 1 ?
2991 DiamondInvalidArgs(invalidDiamondArgs, fragment) :
2992 DiamondInvalidArg(invalidDiamondArgs, fragment)));
2993 }
2994 // For <>(){}, inferred types must also be accessible.
2995 for (Type t : clazztype.getTypeArguments()) {
2996 rs.checkAccessibleType(env, t);
2997 }
2998 }
2999
3000 // If we already errored, be careful to avoid a further avalanche. ErrorType answers
3001 // false for isInterface call even when the original type is an interface.
3002 boolean implementing = clazztype.tsym.isInterface() ||
3003 clazztype.isErroneous() && !clazztype.getOriginalType().hasTag(NONE) &&
3004 clazztype.getOriginalType().tsym.isInterface();
3005
3006 if (implementing) {
3007 cdef.implementing = List.of(clazz);
3008 } else {
3009 cdef.extending = clazz;
3010 }
3011
3012 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3013 rs.isSerializable(clazztype)) {
3014 localEnv.info.isSerializable = true;
3015 }
3016
3017 attribStat(cdef, localEnv);
3050 result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK));
3051 chk.validate(tree.typeargs, localEnv);
3052 }
3053
3054 CheckContext diamondContext(JCNewClass clazz, TypeSymbol tsym, CheckContext checkContext) {
3055 return new Check.NestedCheckContext(checkContext) {
3056 @Override
3057 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
3058 enclosingContext.report(clazz.clazz,
3059 diags.fragment(Fragments.CantApplyDiamond1(Fragments.Diamond(tsym), details)));
3060 }
3061 };
3062 }
3063
3064 /** Make an attributed null check tree.
3065 */
3066 public JCExpression makeNullCheck(JCExpression arg) {
3067 // optimization: new Outer() can never be null; skip null check
3068 if (arg.getTag() == NEWCLASS)
3069 return arg;
3070 // optimization: X.this is never null; skip null check
3071 Name name = TreeInfo.name(arg);
3072 if (name == names._this || name == names._super) return arg;
3073
3074 JCTree.Tag optag = NULLCHK;
3075 JCUnary tree = make.at(arg.pos).Unary(optag, arg);
3076 tree.operator = operators.resolveUnary(arg, optag, arg.type);
3077 tree.type = arg.type;
3078 return tree;
3079 }
3080
3081 public void visitNewArray(JCNewArray tree) {
3082 Type owntype = types.createErrorType(tree.type);
3083 Env<AttrContext> localEnv = env.dup(tree);
3084 Type elemtype;
3085 if (tree.elemtype != null) {
3086 elemtype = attribType(tree.elemtype, localEnv);
3087 chk.validate(tree.elemtype, localEnv);
3088 owntype = elemtype;
3089 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
3539 *
3540 * The owner of this environment is a method symbol. If the current owner
3541 * is not a method, for example if the lambda is used to initialize
3542 * a field, then if the field is:
3543 *
3544 * - an instance field, we use the first constructor.
3545 * - a static field, we create a fake clinit method.
3546 */
3547 public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
3548 Env<AttrContext> lambdaEnv;
3549 Symbol owner = env.info.scope.owner;
3550 if (owner.kind == VAR && owner.owner.kind == TYP) {
3551 //field initializer
3552 ClassSymbol enclClass = owner.enclClass();
3553 Symbol newScopeOwner = env.info.scope.owner;
3554 /* if the field isn't static, then we can get the first constructor
3555 * and use it as the owner of the environment. This is what
3556 * LTM code is doing to look for type annotations so we are fine.
3557 */
3558 if ((owner.flags() & STATIC) == 0) {
3559 for (Symbol s : enclClass.members_field.getSymbolsByName(names.init)) {
3560 newScopeOwner = s;
3561 break;
3562 }
3563 } else {
3564 /* if the field is static then we need to create a fake clinit
3565 * method, this method can later be reused by LTM.
3566 */
3567 MethodSymbol clinit = clinits.get(enclClass);
3568 if (clinit == null) {
3569 Type clinitType = new MethodType(List.nil(),
3570 syms.voidType, List.nil(), syms.methodClass);
3571 clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE,
3572 names.clinit, clinitType, enclClass);
3573 clinit.params = List.nil();
3574 clinits.put(enclClass, clinit);
3575 }
3576 newScopeOwner = clinit;
3577 }
3578 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(newScopeOwner)));
3579 } else {
3602
3603 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3604 exprType = chk.checkConstructorRefType(that.expr, exprType);
3605 if (!exprType.isErroneous() &&
3606 exprType.isRaw() &&
3607 that.typeargs != null) {
3608 log.error(that.expr.pos(),
3609 Errors.InvalidMref(Kinds.kindName(that.getMode()),
3610 Fragments.MrefInferAndExplicitParams));
3611 exprType = types.createErrorType(exprType);
3612 }
3613 }
3614
3615 if (exprType.isErroneous()) {
3616 //if the qualifier expression contains problems,
3617 //give up attribution of method reference
3618 result = that.type = exprType;
3619 return;
3620 }
3621
3622 if (TreeInfo.isStaticSelector(that.expr, names)) {
3623 //if the qualifier is a type, validate it; raw warning check is
3624 //omitted as we don't know at this stage as to whether this is a
3625 //raw selector (because of inference)
3626 chk.validate(that.expr, env, false);
3627 } else {
3628 Symbol lhsSym = TreeInfo.symbol(that.expr);
3629 localEnv.info.selectSuper = lhsSym != null && lhsSym.name == names._super;
3630 }
3631 //attrib type-arguments
3632 List<Type> typeargtypes = List.nil();
3633 if (that.typeargs != null) {
3634 typeargtypes = attribTypes(that.typeargs, localEnv);
3635 }
3636
3637 boolean isTargetSerializable =
3638 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3639 rs.isSerializable(pt());
3640 TargetInfo targetInfo = getTargetInfo(that, resultInfo, null);
3641 Type currentTarget = targetInfo.target;
3642 Type desc = targetInfo.descriptor;
3643
3644 setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
3645 List<Type> argtypes = desc.getParameterTypes();
3646 Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
3647
3648 if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
3692 targetError ?
3693 Fragments.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag) :
3694 Errors.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag));
3695
3696 if (targetError && currentTarget == Type.recoveryType) {
3697 //a target error doesn't make sense during recovery stage
3698 //as we don't know what actual parameter types are
3699 result = that.type = currentTarget;
3700 return;
3701 } else {
3702 if (targetError) {
3703 resultInfo.checkContext.report(that, diag);
3704 } else {
3705 log.report(diag);
3706 }
3707 result = that.type = types.createErrorType(currentTarget);
3708 return;
3709 }
3710 }
3711
3712 that.sym = refSym.isConstructor() ? refSym.baseSymbol() : refSym;
3713 that.kind = lookupHelper.referenceKind(that.sym);
3714 that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
3715
3716 if (desc.getReturnType() == Type.recoveryType) {
3717 // stop here
3718 result = that.type = currentTarget;
3719 return;
3720 }
3721
3722 if (!env.info.attributionMode.isSpeculative && that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3723 Type enclosingType = exprType.getEnclosingType();
3724 if (enclosingType != null && enclosingType.hasTag(CLASS)) {
3725 // Check for the existence of an appropriate outer instance
3726 rs.resolveImplicitThis(that.pos(), env, exprType);
3727 }
3728 }
3729
3730 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
3731
3732 if (that.getMode() == ReferenceMode.INVOKE &&
4381 }
4382
4383 public void visitSelect(JCFieldAccess tree) {
4384 // Determine the expected kind of the qualifier expression.
4385 KindSelector skind = KindSelector.NIL;
4386 if (tree.name == names._this || tree.name == names._super ||
4387 tree.name == names._class)
4388 {
4389 skind = KindSelector.TYP;
4390 } else {
4391 if (pkind().contains(KindSelector.PCK))
4392 skind = KindSelector.of(skind, KindSelector.PCK);
4393 if (pkind().contains(KindSelector.TYP))
4394 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4395 if (pkind().contains(KindSelector.VAL_MTH))
4396 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4397 }
4398
4399 // Attribute the qualifier expression, and determine its symbol (if any).
4400 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4401 if (!pkind().contains(KindSelector.TYP_PCK))
4402 site = capture(site); // Capture field access
4403
4404 // don't allow T.class T[].class, etc
4405 if (skind == KindSelector.TYP) {
4406 Type elt = site;
4407 while (elt.hasTag(ARRAY))
4408 elt = ((ArrayType)elt).elemtype;
4409 if (elt.hasTag(TYPEVAR)) {
4410 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4411 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4412 tree.sym = tree.type.tsym;
4413 return ;
4414 }
4415 }
4416
4417 // If qualifier symbol is a type or `super', assert `selectSuper'
4418 // for the selection. This is relevant for determining whether
4419 // protected symbols are accessible.
4420 Symbol sitesym = TreeInfo.symbol(tree.selected);
4421 boolean selectSuperPrev = env.info.selectSuper;
4422 env.info.selectSuper =
4423 sitesym != null &&
4424 sitesym.name == names._super;
4425
4426 // Determine the symbol represented by the selection.
4427 env.info.pendingResolutionPhase = null;
4428 Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
4429 if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
4430 log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym));
4431 sym = syms.errSymbol;
4432 }
4433 if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
4497 } else if (sym.kind != ERR &&
4498 (sym.flags() & STATIC) != 0 &&
4499 sym.name != names._class) {
4500 // If the qualified item is not a type and the selected item is static, report
4501 // a warning. Make allowance for the class of an array type e.g. Object[].class)
4502 if (!sym.owner.isAnonymous()) {
4503 chk.warnStatic(tree, Warnings.StaticNotQualifiedByType(sym.kind.kindName(), sym.owner));
4504 } else {
4505 chk.warnStatic(tree, Warnings.StaticNotQualifiedByType2(sym.kind.kindName()));
4506 }
4507 }
4508
4509 // If we are selecting an instance member via a `super', ...
4510 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
4511
4512 // Check that super-qualified symbols are not abstract (JLS)
4513 rs.checkNonAbstract(tree.pos(), sym);
4514
4515 if (site.isRaw()) {
4516 // Determine argument types for site.
4517 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
4518 if (site1 != null) site = site1;
4519 }
4520 }
4521
4522 if (env.info.isSerializable) {
4523 chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4524 }
4525
4526 env.info.selectSuper = selectSuperPrev;
4527 result = checkId(tree, site, sym, env, resultInfo);
4528 }
4529 //where
4530 /** Determine symbol referenced by a Select expression,
4531 *
4532 * @param tree The select tree.
4533 * @param site The type of the selected expression,
4534 * @param env The current environment.
4535 * @param resultInfo The current result.
4536 */
4537 private Symbol selectSym(JCFieldAccess tree,
4540 Env<AttrContext> env,
4541 ResultInfo resultInfo) {
4542 DiagnosticPosition pos = tree.pos();
4543 Name name = tree.name;
4544 switch (site.getTag()) {
4545 case PACKAGE:
4546 return rs.accessBase(
4547 rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind),
4548 pos, location, site, name, true);
4549 case ARRAY:
4550 case CLASS:
4551 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
4552 return rs.resolveQualifiedMethod(
4553 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
4554 } else if (name == names._this || name == names._super) {
4555 return rs.resolveSelf(pos, env, site.tsym, name);
4556 } else if (name == names._class) {
4557 // In this case, we have already made sure in
4558 // visitSelect that qualifier expression is a type.
4559 return syms.getClassField(site, types);
4560 } else {
4561 // We are seeing a plain identifier as selector.
4562 Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind);
4563 sym = rs.accessBase(sym, pos, location, site, name, true);
4564 return sym;
4565 }
4566 case WILDCARD:
4567 throw new AssertionError(tree);
4568 case TYPEVAR:
4569 // Normally, site.getUpperBound() shouldn't be null.
4570 // It should only happen during memberEnter/attribBase
4571 // when determining the supertype which *must* be
4572 // done before attributing the type variables. In
4573 // other words, we are seeing this illegal program:
4574 // class B<T> extends A<T.foo> {}
4575 Symbol sym = (site.getUpperBound() != null)
4576 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
4577 : null;
4578 if (sym == null) {
4579 log.error(pos, Errors.TypeVarCantBeDeref);
4643 if (resultInfo.pkind.contains(KindSelector.POLY)) {
4644 return attrRecover.recoverMethodInvocation(tree, site, sym, env, resultInfo);
4645 } else {
4646 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
4647 }
4648 }
4649
4650 Type checkIdInternal(JCTree tree,
4651 Type site,
4652 Symbol sym,
4653 Type pt,
4654 Env<AttrContext> env,
4655 ResultInfo resultInfo) {
4656 if (pt.isErroneous()) {
4657 return types.createErrorType(site);
4658 }
4659 Type owntype; // The computed type of this identifier occurrence.
4660 switch (sym.kind) {
4661 case TYP:
4662 // For types, the computed type equals the symbol's type,
4663 // except for two situations:
4664 owntype = sym.type;
4665 if (owntype.hasTag(CLASS)) {
4666 chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
4667 Type ownOuter = owntype.getEnclosingType();
4668
4669 // (a) If the symbol's type is parameterized, erase it
4670 // because no type parameters were given.
4671 // We recover generic outer type later in visitTypeApply.
4672 if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
4673 owntype = types.erasure(owntype);
4674 }
4675
4676 // (b) If the symbol's type is an inner class, then
4677 // we have to interpret its outer type as a superclass
4678 // of the site type. Example:
4679 //
4680 // class Tree<A> { class Visitor { ... } }
4681 // class PointTree extends Tree<Point> { ... }
4682 // ...PointTree.Visitor...
4683 //
4684 // Then the type of the last expression above is
4685 // Tree<Point>.Visitor.
4686 else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
4687 Type normOuter = site;
4688 if (normOuter.hasTag(CLASS)) {
4689 normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
4690 }
4691 if (normOuter == null) // perhaps from an import
4692 normOuter = types.erasure(ownOuter);
4693 if (normOuter != ownOuter)
4694 owntype = new ClassType(
4695 normOuter, List.nil(), owntype.tsym,
4696 owntype.getMetadata());
4697 }
4698 }
4699 break;
4700 case VAR:
4701 VarSymbol v = (VarSymbol)sym;
4702
4703 if (env.info.enclVar != null
4704 && v.type.hasTag(NONE)) {
4705 //self reference to implicitly typed variable declaration
4706 log.error(TreeInfo.positionFor(v, env.enclClass), Errors.CantInferLocalVarType(v.name, Fragments.LocalSelfRef));
4707 return tree.type = v.type = types.createErrorType(v.type);
4708 }
4709
4710 // Test (4): if symbol is an instance field of a raw type,
4711 // which is being assigned to, issue an unchecked warning if
4712 // its type changes under erasure.
4713 if (KindSelector.ASG.subset(pkind()) &&
4714 v.owner.kind == TYP &&
4715 (v.flags() & STATIC) == 0 &&
4716 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
4739 break;
4740 case MTH: {
4741 owntype = checkMethod(site, sym,
4742 new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext, resultInfo.checkMode),
4743 env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
4744 resultInfo.pt.getTypeArguments());
4745 break;
4746 }
4747 case PCK: case ERR:
4748 owntype = sym.type;
4749 break;
4750 default:
4751 throw new AssertionError("unexpected kind: " + sym.kind +
4752 " in tree " + tree);
4753 }
4754
4755 // Emit a `deprecation' warning if symbol is deprecated.
4756 // (for constructors (but not for constructor references), the error
4757 // was given when the constructor was resolved)
4758
4759 if (sym.name != names.init || tree.hasTag(REFERENCE)) {
4760 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
4761 chk.checkSunAPI(tree.pos(), sym);
4762 chk.checkProfile(tree.pos(), sym);
4763 chk.checkPreview(tree.pos(), env.info.scope.owner, sym);
4764 }
4765
4766 // If symbol is a variable, check that its type and
4767 // kind are compatible with the prototype and protokind.
4768 return check(tree, owntype, sym.kind.toSelector(), resultInfo);
4769 }
4770
4771 /** Check that variable is initialized and evaluate the variable's
4772 * initializer, if not yet done. Also check that variable is not
4773 * referenced before it is defined.
4774 * @param tree The tree making up the variable reference.
4775 * @param env The current environment.
4776 * @param v The variable's symbol.
4777 */
4778 private void checkInit(JCTree tree,
4779 Env<AttrContext> env,
4993 //depending on the current check context
4994 resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
4995 return types.createErrorType(site);
4996 } catch (Resolve.InapplicableMethodException ex) {
4997 final JCDiagnostic diag = ex.getDiagnostic();
4998 Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
4999 @Override
5000 protected Pair<Symbol, JCDiagnostic> errCandidate() {
5001 return new Pair<>(sym, diag);
5002 }
5003 };
5004 List<Type> argtypes2 = argtypes.map(
5005 rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
5006 JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
5007 env.tree, sym, site, sym.name, argtypes2, typeargtypes);
5008 log.report(errDiag);
5009 return types.createErrorType(site);
5010 }
5011 }
5012
5013 public void visitLiteral(JCLiteral tree) {
5014 result = check(tree, litType(tree.typetag).constType(tree.value),
5015 KindSelector.VAL, resultInfo);
5016 }
5017 //where
5018 /** Return the type of a literal with given type tag.
5019 */
5020 Type litType(TypeTag tag) {
5021 return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
5022 }
5023
5024 public void visitStringTemplate(JCStringTemplate tree) {
5025 JCExpression processor = tree.processor;
5026 Type resultType = syms.stringTemplateType;
5027
5028 if (processor != null) {
5029 resultType = attribTree(processor, env, new ResultInfo(KindSelector.VAL, Type.noType));
5030 resultType = chk.checkProcessorType(processor, resultType, env);
5031 }
5032
5080 }
5081 // Compute the proper generic outer
5082 Type clazzOuter = clazztype.getEnclosingType();
5083 if (clazzOuter.hasTag(CLASS)) {
5084 Type site;
5085 JCExpression clazz = TreeInfo.typeIn(tree.clazz);
5086 if (clazz.hasTag(IDENT)) {
5087 site = env.enclClass.sym.type;
5088 } else if (clazz.hasTag(SELECT)) {
5089 site = ((JCFieldAccess) clazz).selected.type;
5090 } else throw new AssertionError(""+tree);
5091 if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
5092 if (site.hasTag(CLASS))
5093 site = types.asOuterSuper(site, clazzOuter.tsym);
5094 if (site == null)
5095 site = types.erasure(clazzOuter);
5096 clazzOuter = site;
5097 }
5098 }
5099 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
5100 clazztype.getMetadata());
5101 } else {
5102 if (formals.length() != 0) {
5103 log.error(tree.pos(),
5104 Errors.WrongNumberTypeArgs(Integer.toString(formals.length())));
5105 } else {
5106 log.error(tree.pos(), Errors.TypeDoesntTakeParams(clazztype.tsym));
5107 }
5108 owntype = types.createErrorType(tree.type);
5109 }
5110 }
5111 result = check(tree, owntype, KindSelector.TYP, resultInfo);
5112 }
5113
5114 public void visitTypeUnion(JCTypeUnion tree) {
5115 ListBuffer<Type> multicatchTypes = new ListBuffer<>();
5116 ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
5117 for (JCExpression typeTree : tree.alternatives) {
5118 Type ctype = attribType(typeTree, env);
5119 ctype = chk.checkType(typeTree.pos(),
5120 chk.checkClassType(typeTree.pos(), ctype),
5207 if (bounds.length() == 0) {
5208 return syms.objectType;
5209 } else if (bounds.length() == 1) {
5210 return bounds.head.type;
5211 } else {
5212 Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
5213 // ... the variable's bound is a class type flagged COMPOUND
5214 // (see comment for TypeVar.bound).
5215 // In this case, generate a class tree that represents the
5216 // bound class, ...
5217 JCExpression extending;
5218 List<JCExpression> implementing;
5219 if (!bounds.head.type.isInterface()) {
5220 extending = bounds.head;
5221 implementing = bounds.tail;
5222 } else {
5223 extending = null;
5224 implementing = bounds;
5225 }
5226 JCClassDecl cd = make.at(tree).ClassDef(
5227 make.Modifiers(PUBLIC | ABSTRACT),
5228 names.empty, List.nil(),
5229 extending, implementing, List.nil());
5230
5231 ClassSymbol c = (ClassSymbol)owntype.tsym;
5232 Assert.check((c.flags() & COMPOUND) != 0);
5233 cd.sym = c;
5234 c.sourcefile = env.toplevel.sourcefile;
5235
5236 // ... and attribute the bound class
5237 c.flags_field |= UNATTRIBUTED;
5238 Env<AttrContext> cenv = enter.classEnv(cd, env);
5239 typeEnvs.put(c, cenv);
5240 attribClass(c);
5241 return owntype;
5242 }
5243 }
5244
5245 public void visitWildcard(JCWildcard tree) {
5246 //- System.err.println("visitWildcard("+tree+");");//DEBUG
5247 Type type = (tree.kind.kind == BoundKind.UNBOUND)
5248 ? syms.objectType
5249 : attribType(tree.inner, env);
5250 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
5251 tree.kind.kind,
5252 syms.boundClass),
5253 KindSelector.TYP, resultInfo);
5254 }
5255
5256 public void visitAnnotation(JCAnnotation tree) {
5257 Assert.error("should be handled in annotate");
5258 }
5259
5260 @Override
5261 public void visitModifiers(JCModifiers tree) {
5262 //error recovery only:
5263 Assert.check(resultInfo.pkind == KindSelector.ERR);
5264
5265 attribAnnotationTypes(tree.annotations, env);
5266 }
5267
5268 public void visitAnnotatedType(JCAnnotatedType tree) {
5269 attribAnnotationTypes(tree.annotations, env);
5270 Type underlyingType = attribType(tree.underlyingType, env);
5348
5349 try {
5350 deferredLintHandler.flush(env.tree.pos());
5351 attrib.accept(env);
5352 } finally {
5353 log.useSource(prev);
5354 chk.setLint(prevLint);
5355 }
5356 }
5357
5358 /** Main method: attribute class definition associated with given class symbol.
5359 * reporting completion failures at the given position.
5360 * @param pos The source position at which completion errors are to be
5361 * reported.
5362 * @param c The class symbol whose definition will be attributed.
5363 */
5364 public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
5365 try {
5366 annotate.flush();
5367 attribClass(c);
5368 } catch (CompletionFailure ex) {
5369 chk.completionError(pos, ex);
5370 }
5371 }
5372
5373 /** Attribute class definition associated with given class symbol.
5374 * @param c The class symbol whose definition will be attributed.
5375 */
5376 void attribClass(ClassSymbol c) throws CompletionFailure {
5377 if (c.type.hasTag(ERROR)) return;
5378
5379 // Check for cycles in the inheritance graph, which can arise from
5380 // ill-formed class files.
5381 chk.checkNonCyclic(null, c.type);
5382
5383 Type st = types.supertype(c.type);
5384 if ((c.flags_field & Flags.COMPOUND) == 0 &&
5385 (c.flags_field & Flags.SUPER_OWNER_ATTRIBUTED) == 0) {
5386 // First, attribute superclass.
5387 if (st.hasTag(CLASS))
5468 .filter(s -> s.tsym.isSealed())
5469 .map(s -> (ClassSymbol) s.tsym)
5470 .collect(List.collector());
5471
5472 if (sealedSupers.isEmpty()) {
5473 if ((c.flags_field & Flags.NON_SEALED) != 0) {
5474 boolean hasErrorSuper = false;
5475
5476 hasErrorSuper |= types.directSupertypes(c.type)
5477 .stream()
5478 .anyMatch(s -> s.tsym.kind == Kind.ERR);
5479
5480 ClassType ct = (ClassType) c.type;
5481
5482 hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5483
5484 if (!hasErrorSuper) {
5485 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5486 }
5487 }
5488 } else {
5489 if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5490 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5491 }
5492
5493 if (!c.type.isCompound()) {
5494 for (ClassSymbol supertypeSym : sealedSupers) {
5495 if (!supertypeSym.permitted.contains(c.type.tsym)) {
5496 log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5497 }
5498 }
5499 if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5500 log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5501 c.isInterface() ?
5502 Errors.NonSealedOrSealedExpected :
5503 Errors.NonSealedSealedOrFinalExpected);
5504 }
5505 }
5506 }
5507
5508 // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
5523
5524 try {
5525 deferredLintHandler.flush(env.tree);
5526 env.info.returnResult = null;
5527 // java.lang.Enum may not be subclassed by a non-enum
5528 if (st.tsym == syms.enumSym &&
5529 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5530 log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5531
5532 // Enums may not be extended by source-level classes
5533 if (st.tsym != null &&
5534 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5535 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5536 log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5537 }
5538
5539 if (rs.isSerializable(c.type)) {
5540 env.info.isSerializable = true;
5541 }
5542
5543 attribClassBody(env, c);
5544
5545 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5546 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5547 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5548 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5549
5550 if ((c.flags_field & Flags.UNNAMED_CLASS) != 0) {
5551 chk.checkHasMain(env.tree.pos(), c);
5552 }
5553 } finally {
5554 env.info.returnResult = prevReturnRes;
5555 log.useSource(prev);
5556 chk.setLint(prevLint);
5557 }
5558
5559 }
5560 }
5561
5562 public void visitImport(JCImport tree) {
|
28 import java.util.*;
29 import java.util.function.BiConsumer;
30 import java.util.function.Consumer;
31 import java.util.stream.Stream;
32
33 import javax.lang.model.element.ElementKind;
34 import javax.tools.JavaFileObject;
35
36 import com.sun.source.tree.CaseTree;
37 import com.sun.source.tree.IdentifierTree;
38 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
39 import com.sun.source.tree.MemberSelectTree;
40 import com.sun.source.tree.TreeVisitor;
41 import com.sun.source.util.SimpleTreeVisitor;
42 import com.sun.tools.javac.code.*;
43 import com.sun.tools.javac.code.Lint.LintCategory;
44 import com.sun.tools.javac.code.Scope.WriteableScope;
45 import com.sun.tools.javac.code.Source.Feature;
46 import com.sun.tools.javac.code.Symbol.*;
47 import com.sun.tools.javac.code.Type.*;
48 import com.sun.tools.javac.code.Type.ClassType.Flavor;
49 import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError;
50 import com.sun.tools.javac.comp.ArgumentAttr.LocalCacheContext;
51 import com.sun.tools.javac.comp.Check.CheckContext;
52 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
53 import com.sun.tools.javac.comp.MatchBindingsComputer.MatchBindings;
54 import com.sun.tools.javac.jvm.*;
55
56 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond;
57 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArg;
58 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArgs;
59
60 import com.sun.tools.javac.resources.CompilerProperties.Errors;
61 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
62 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
63 import com.sun.tools.javac.tree.*;
64 import com.sun.tools.javac.tree.JCTree.*;
65 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
66 import com.sun.tools.javac.util.*;
67 import com.sun.tools.javac.util.DefinedBy.Api;
68 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
150 infer = Infer.instance(context);
151 analyzer = Analyzer.instance(context);
152 deferredAttr = DeferredAttr.instance(context);
153 cfolder = ConstFold.instance(context);
154 target = Target.instance(context);
155 types = Types.instance(context);
156 preview = Preview.instance(context);
157 diags = JCDiagnostic.Factory.instance(context);
158 annotate = Annotate.instance(context);
159 typeAnnotations = TypeAnnotations.instance(context);
160 deferredLintHandler = DeferredLintHandler.instance(context);
161 typeEnvs = TypeEnvs.instance(context);
162 dependencies = Dependencies.instance(context);
163 argumentAttr = ArgumentAttr.instance(context);
164 matchBindingsComputer = MatchBindingsComputer.instance(context);
165 attrRecover = AttrRecover.instance(context);
166
167 Options options = Options.instance(context);
168
169 Source source = Source.instance(context);
170 allowPrimitiveClasses = Feature.PRIMITIVE_CLASSES.allowedInSource(source) && options.isSet("enablePrimitiveClasses");
171 allowReifiableTypesInInstanceof = Feature.REIFIABLE_TYPES_INSTANCEOF.allowedInSource(source);
172 allowRecords = Feature.RECORDS.allowedInSource(source);
173 allowPatternSwitch = (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH)) &&
174 Feature.PATTERN_SWITCH.allowedInSource(source);
175 allowUnconditionalPatternsInstanceOf =
176 Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.allowedInSource(source);
177 sourceName = source.name;
178 useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
179
180 statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
181 varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
182 unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
183 methodAttrInfo = new MethodAttrInfo();
184 unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
185 unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
186 recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
187 }
188
189 /** Switch: allow primitive classes ?
190 */
191 boolean allowPrimitiveClasses;
192
193 /** Switch: reifiable types in instanceof enabled?
194 */
195 boolean allowReifiableTypesInInstanceof;
196
197 /** Are records allowed
198 */
199 private final boolean allowRecords;
200
201 /** Are patterns in switch allowed
202 */
203 private final boolean allowPatternSwitch;
204
205 /** Are unconditional patterns in instanceof allowed
206 */
207 private final boolean allowUnconditionalPatternsInstanceOf;
208
209 /**
210 * Switch: warn about use of variable before declaration?
211 * RFE: 6425594
212 */
261 found;
262 }
263 if (resultInfo.checkMode.updateTreeType()) {
264 tree.type = owntype;
265 }
266 return owntype;
267 }
268
269 /** Is given blank final variable assignable, i.e. in a scope where it
270 * may be assigned to even though it is final?
271 * @param v The blank final variable.
272 * @param env The current environment.
273 */
274 boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
275 Symbol owner = env.info.scope.owner;
276 // owner refers to the innermost variable, method or
277 // initializer block declaration at this point.
278 boolean isAssignable =
279 v.owner == owner
280 ||
281 ((names.isInitOrVNew(owner.name) || // i.e. we are in a constructor
282 owner.kind == VAR || // i.e. we are in a variable initializer
283 (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block
284 &&
285 v.owner == owner.owner
286 &&
287 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
288 boolean insideCompactConstructor = env.enclMethod != null && TreeInfo.isCompactConstructor(env.enclMethod);
289 return isAssignable & !insideCompactConstructor;
290 }
291
292 /** Check that variable can be assigned to.
293 * @param pos The current source code position.
294 * @param v The assigned variable
295 * @param base If the variable is referred to in a Select, the part
296 * to the left of the `.', null otherwise.
297 * @param env The current environment.
298 */
299 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
300 if (v.name == names._this) {
301 log.error(pos, Errors.CantAssignValToThis);
788 /** Attribute a type argument list, returning a list of types.
789 * Check that all the types are references.
790 */
791 List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
792 List<Type> types = attribAnyTypes(trees, env);
793 return chk.checkRefTypes(trees, types);
794 }
795
796 /**
797 * Attribute type variables (of generic classes or methods).
798 * Compound types are attributed later in attribBounds.
799 * @param typarams the type variables to enter
800 * @param env the current environment
801 */
802 void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env, boolean checkCyclic) {
803 for (JCTypeParameter tvar : typarams) {
804 TypeVar a = (TypeVar)tvar.type;
805 a.tsym.flags_field |= UNATTRIBUTED;
806 a.setUpperBound(Type.noType);
807 if (!tvar.bounds.isEmpty()) {
808 List<Type> bounds = List.of(chk.checkRefType(tvar.bounds.head, attribType(tvar.bounds.head, env), false));
809 for (JCExpression bound : tvar.bounds.tail)
810 bounds = bounds.prepend(chk.checkRefType(bound, attribType(bound, env), false));
811 types.setBounds(a, bounds.reverse());
812 } else {
813 // if no bounds are given, assume a single bound of
814 // java.lang.Object.
815 types.setBounds(a, List.of(syms.objectType));
816 }
817 a.tsym.flags_field &= ~UNATTRIBUTED;
818 }
819 if (checkCyclic) {
820 for (JCTypeParameter tvar : typarams) {
821 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
822 }
823 }
824 }
825
826 /**
827 * Attribute the type references in a list of annotations.
828 */
829 void attribAnnotationTypes(List<JCAnnotation> annotations,
830 Env<AttrContext> env) {
1060 log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.MethodMustBePublic));
1061 }
1062 if (!types.isSameType(tree.sym.type.getReturnType(), recordComponent.get().type)) {
1063 log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym,
1064 Fragments.AccessorReturnTypeDoesntMatch(tree.sym, recordComponent.get())));
1065 }
1066 if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1067 log.error(tree,
1068 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodCantThrowException));
1069 }
1070 if (!tree.typarams.isEmpty()) {
1071 log.error(tree,
1072 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeGeneric));
1073 }
1074 if (tree.sym.isStatic()) {
1075 log.error(tree,
1076 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeStatic));
1077 }
1078 }
1079
1080 if (names.isInitOrVNew(tree.name)) {
1081 // if this a constructor other than the canonical one
1082 if ((tree.sym.flags_field & RECORD) == 0) {
1083 JCMethodInvocation app = TreeInfo.firstConstructorCall(tree);
1084 if (app == null ||
1085 TreeInfo.name(app.meth) != names._this ||
1086 !checkFirstConstructorStat(app, tree, false)) {
1087 log.error(tree, Errors.FirstStatementMustBeCallToAnotherConstructor(env.enclClass.sym));
1088 }
1089 } else {
1090 // but if it is the canonical:
1091
1092 /* if user generated, then it shouldn't:
1093 * - have an accessibility stricter than that of the record type
1094 * - explicitly invoke any other constructor
1095 */
1096 if ((tree.sym.flags_field & GENERATEDCONSTR) == 0) {
1097 if (Check.protection(m.flags()) > Check.protection(env.enclClass.sym.flags())) {
1098 log.error(tree,
1099 (env.enclClass.sym.flags() & AccessFlags) == 0 ?
1100 Errors.InvalidCanonicalConstructorInRecord(
1175 if (tree.defaultValue != null) {
1176 if ((owner.flags() & ANNOTATION) == 0)
1177 log.error(tree.pos(),
1178 Errors.DefaultAllowedInIntfAnnotationMember);
1179 }
1180 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1181 log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract);
1182 } else {
1183 if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1184 if ((owner.flags() & INTERFACE) != 0) {
1185 log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1186 } else {
1187 log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1188 }
1189 } else if ((tree.mods.flags & NATIVE) != 0) {
1190 log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1191 }
1192 // Add an implicit super() call unless an explicit call to
1193 // super(...) or this(...) is given
1194 // or we are compiling class java.lang.Object.
1195 if (names.isInitOrVNew(tree.name) && owner.type != syms.objectType) {
1196 JCBlock body = tree.body;
1197 if (body.stats.isEmpty() ||
1198 TreeInfo.getConstructorInvocationName(body.stats, names, true) == names.empty) {
1199 JCStatement supCall = make.at(body.pos).Exec(make.Apply(List.nil(),
1200 make.Ident(names._super), make.Idents(List.nil())));
1201 body.stats = body.stats.prepend(supCall);
1202 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1203 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1204 TreeInfo.isSuperCall(body.stats.head)) {
1205 // enum constructors are not allowed to call super
1206 // directly, so make sure there aren't any super calls
1207 // in enum constructors, except in the compiler
1208 // generated one.
1209 log.error(tree.body.stats.head.pos(),
1210 Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1211 } else if ((env.enclClass.sym.flags() & VALUE_CLASS) != 0 &&
1212 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1213 TreeInfo.isSuperCall(body.stats.head)) {
1214 // value constructors are not allowed to call super directly,
1215 // but tolerate compiler generated ones, these are ignored during code generation
1216 log.error(tree.body.stats.head.pos(), Errors.CallToSuperNotAllowedInValueCtor);
1217 }
1218 if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1219 List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1220 List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1221 if (!initParamNames.equals(recordComponentNames)) {
1222 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1223 Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1224 }
1225 if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1226 log.error(tree,
1227 Errors.InvalidCanonicalConstructorInRecord(
1228 TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical,
1229 env.enclClass.sym.name,
1230 Fragments.ThrowsClauseNotAllowedForCanonicalConstructor(
1231 TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical)));
1232 }
1233 }
1234 }
1235
1236 // Attribute all type annotations in the body
1284 annotate.queueScanTreeAndTypeAnnotate(tree.init, env, tree.sym, tree.pos());
1285 annotate.flush();
1286 }
1287 }
1288
1289 VarSymbol v = tree.sym;
1290 Lint lint = env.info.lint.augment(v);
1291 Lint prevLint = chk.setLint(lint);
1292
1293 // Check that the variable's declared type is well-formed.
1294 boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
1295 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
1296 (tree.sym.flags() & PARAMETER) != 0;
1297 chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1298
1299 try {
1300 v.getConstValue(); // ensure compile-time constant initializer is evaluated
1301 deferredLintHandler.flush(tree.pos());
1302 chk.checkDeprecatedAnnotation(tree.pos(), v);
1303
1304 /* Don't want constant propagation/folding for instance fields of primitive classes,
1305 as these can undergo updates via copy on write.
1306 */
1307 if (tree.init != null) {
1308 if ((v.flags_field & FINAL) == 0 || ((v.flags_field & STATIC) == 0 && v.owner.isValueClass()) ||
1309 !memberEnter.needsLazyConstValue(tree.init)) {
1310 // Not a compile-time constant
1311 // Attribute initializer in a new environment
1312 // with the declared variable as owner.
1313 // Check that initializer conforms to variable's declared type.
1314 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1315 initEnv.info.lint = lint;
1316 // In order to catch self-references, we set the variable's
1317 // declaration position to maximal possible value, effectively
1318 // marking the variable as undefined.
1319 initEnv.info.enclVar = v;
1320 attribExpr(tree.init, initEnv, v.type);
1321 if (tree.isImplicitlyTyped()) {
1322 //fixup local variable type
1323 v.type = chk.checkLocalVarType(tree, tree.init.type, tree.name);
1324 }
1325 }
1326 if (tree.isImplicitlyTyped()) {
1327 setSyntheticVariableType(tree, v.type);
1328 }
1329 }
1330 result = tree.type = v.type;
1331 if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1332 if (isNonArgsMethodInObject(v.name)) {
1333 log.error(tree, Errors.IllegalRecordComponentName(v));
1334 }
1335 }
1336 }
1337 finally {
1338 chk.setLint(prevLint);
1339 }
1340 }
1341
1342 private boolean isNonArgsMethodInObject(Name name) {
1343 for (Symbol s : syms.objectType.tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) {
1344 if (s.type.getParameterTypes().isEmpty()) {
1345 return true;
1346 }
1347 }
1348 // isValueObject is not included in Object yet so we need a work around
1349 return name == names.isValueObject;
1350 }
1351
1352 Fragment canInferLocalVarType(JCVariableDecl tree) {
1353 LocalInitScanner lis = new LocalInitScanner();
1354 lis.scan(tree.init);
1355 return lis.badInferenceMsg;
1356 }
1357
1358 static class LocalInitScanner extends TreeScanner {
1359 Fragment badInferenceMsg = null;
1360 boolean needsTarget = true;
1361
1362 @Override
1363 public void visitNewArray(JCNewArray tree) {
1364 if (tree.elemtype == null && needsTarget) {
1365 badInferenceMsg = Fragments.LocalArrayMissingTarget;
1366 }
1367 }
1368
1369 @Override
1546 introducingStatement = labeled;
1547 }
1548
1549 //include condition's body when false after the while, if cannot get out of the loop
1550 bindings.forEach(env.info.scope::enter);
1551 bindings.forEach(BindingSymbol::preserveBinding);
1552 }
1553
1554 public void visitForeachLoop(JCEnhancedForLoop tree) {
1555 Env<AttrContext> loopEnv =
1556 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1557 try {
1558 //the Formal Parameter of a for-each loop is not in the scope when
1559 //attributing the for-each expression; we mimic this by attributing
1560 //the for-each expression first (against original scope).
1561 Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
1562 chk.checkNonVoid(tree.pos(), exprType);
1563 Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
1564 if (elemtype == null) {
1565 // or perhaps expr implements Iterable<T>?
1566 Type base = types.asSuper(exprType.referenceProjectionOrSelf(), syms.iterableType.tsym);
1567 if (base == null) {
1568 log.error(tree.expr.pos(),
1569 Errors.ForeachNotApplicableToType(exprType,
1570 Fragments.TypeReqArrayOrIterable));
1571 elemtype = types.createErrorType(exprType);
1572 } else {
1573 List<Type> iterableParams = base.allparams();
1574 elemtype = iterableParams.isEmpty()
1575 ? syms.objectType
1576 : types.wildUpperBound(iterableParams.head);
1577
1578 // Check the return type of the method iterator().
1579 // This is the bare minimum we need to verify to make sure code generation doesn't crash.
1580 Symbol iterSymbol = rs.resolveInternalMethod(tree.pos(),
1581 loopEnv, types.skipTypeVars(exprType, false), names.iterator, List.nil(), List.nil());
1582 if (types.asSuper(iterSymbol.type.getReturnType().referenceProjectionOrSelf(), syms.iteratorType.tsym) == null) {
1583 log.error(tree.pos(),
1584 Errors.ForeachNotApplicableToType(exprType, Fragments.TypeReqArrayOrIterable));
1585 }
1586 }
1587 }
1588 if (tree.var.isImplicitlyTyped()) {
1589 Type inferredType = chk.checkLocalVarType(tree.var, elemtype, tree.var.name);
1590 setSyntheticVariableType(tree.var, inferredType);
1591 }
1592 attribStat(tree.var, loopEnv);
1593 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
1594 loopEnv.tree = tree; // before, we were not in loop!
1595 attribStat(tree.body, loopEnv);
1596 result = null;
1597 }
1598 finally {
1599 loopEnv.info.scope.leave();
1600 }
1601 }
1602
1908 // where
1909 /** Return the selected enumeration constant symbol, or null. */
1910 private Symbol enumConstant(JCTree tree, Type enumType) {
1911 if (tree.hasTag(IDENT)) {
1912 JCIdent ident = (JCIdent)tree;
1913 Name name = ident.name;
1914 for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1915 if (sym.kind == VAR) {
1916 Symbol s = ident.sym = sym;
1917 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1918 ident.type = s.type;
1919 return ((s.flags_field & Flags.ENUM) == 0)
1920 ? null : s;
1921 }
1922 }
1923 }
1924 return null;
1925 }
1926
1927 public void visitSynchronized(JCSynchronized tree) {
1928 chk.checkIdentityType(tree.pos(), attribExpr(tree.lock, env));
1929 if (env.info.lint.isEnabled(LintCategory.SYNCHRONIZATION) && isValueBased(tree.lock.type)) {
1930 log.warning(LintCategory.SYNCHRONIZATION, tree.pos(), Warnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
1931 }
1932 attribStat(tree.body, env);
1933 result = null;
1934 }
1935 // where
1936 private boolean isValueBased(Type t) {
1937 return t != null && t.tsym != null && (t.tsym.flags() & VALUE_BASED) != 0;
1938 }
1939
1940
1941 public void visitTry(JCTry tree) {
1942 // Create a new local environment with a local
1943 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1944 try {
1945 boolean isTryWithResource = tree.resources.nonEmpty();
1946 // Create a nested environment for attributing the try block if needed
1947 Env<AttrContext> tryEnv = isTryWithResource ?
1948 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1999 chk.checkType(c.param.vartype.pos(),
2000 chk.checkClassType(c.param.vartype.pos(), ctype),
2001 syms.throwableType);
2002 attribStat(c.body, catchEnv);
2003 } finally {
2004 catchEnv.info.scope.leave();
2005 }
2006 }
2007
2008 // Attribute finalizer
2009 if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
2010 result = null;
2011 }
2012 finally {
2013 localEnv.info.scope.leave();
2014 }
2015 }
2016
2017 void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) {
2018 if (!resource.isErroneous() &&
2019 types.asSuper(resource.referenceProjectionOrSelf(), syms.autoCloseableType.tsym) != null &&
2020 !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
2021 Symbol close = syms.noSymbol;
2022 Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
2023 try {
2024 close = rs.resolveQualifiedMethod(pos,
2025 env,
2026 types.skipTypeVars(resource, false),
2027 names.close,
2028 List.nil(),
2029 List.nil());
2030 }
2031 finally {
2032 log.popDiagnosticHandler(discardHandler);
2033 }
2034 if (close.kind == MTH &&
2035 close.overrides(syms.autoCloseableClose, resource.tsym, types, true) &&
2036 chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) &&
2037 env.info.lint.isEnabled(LintCategory.TRY)) {
2038 log.warning(LintCategory.TRY, pos, Warnings.TryResourceThrowsInterruptedExc(resource));
2039 }
2188 if (unboxedTypes.stream().allMatch(t -> t.isPrimitive())) {
2189 // If one arm has an integer subrange type (i.e., byte,
2190 // short, or char), and the other is an integer constant
2191 // that fits into the subrange, return the subrange type.
2192 for (Type type : unboxedTypes) {
2193 if (!type.getTag().isStrictSubRangeOf(INT)) {
2194 continue;
2195 }
2196 if (unboxedTypes.stream().filter(t -> t != type).allMatch(t -> t.hasTag(INT) && types.isAssignable(t, type)))
2197 return type.baseType();
2198 }
2199
2200 for (TypeTag tag : primitiveTags) {
2201 Type candidate = syms.typeOfTag[tag.ordinal()];
2202 if (unboxedTypes.stream().allMatch(t -> types.isSubtype(t, candidate))) {
2203 return candidate;
2204 }
2205 }
2206 }
2207
2208 // Those were all the cases that could result in a primitive. See if primitive boxing and primitive
2209 // value conversions bring about a convergence.
2210 condTypes = condTypes.stream()
2211 .map(t -> t.isPrimitive() ? types.boxedClass(t).type
2212 : t.isReferenceProjection() ? t.valueProjection() : t)
2213 .collect(List.collector());
2214
2215 for (Type type : condTypes) {
2216 if (condTypes.stream().filter(t -> t != type).allMatch(t -> types.isAssignable(t, type)))
2217 return type.baseType();
2218 }
2219
2220 Iterator<DiagnosticPosition> posIt = positions.iterator();
2221
2222 condTypes = condTypes.stream()
2223 .map(t -> chk.checkNonVoid(posIt.next(), allowPrimitiveClasses && t.isPrimitiveClass() ? t.referenceProjection() : t))
2224 .collect(List.collector());
2225
2226 // both are known to be reference types (or projections). The result is
2227 // lub(thentype,elsetype). This cannot fail, as it will
2228 // always be possible to infer "Object" if nothing better.
2229 return types.lub(condTypes.stream()
2230 .map(t -> t.baseType())
2231 .filter(t -> !t.hasTag(BOT))
2232 .collect(List.collector()));
2233 }
2234
2235 static final TypeTag[] primitiveTags = new TypeTag[]{
2236 BYTE,
2237 CHAR,
2238 SHORT,
2239 INT,
2240 LONG,
2241 FLOAT,
2242 DOUBLE,
2243 BOOLEAN,
2244 };
2245
2246 Env<AttrContext> bindingEnv(Env<AttrContext> env, List<BindingSymbol> bindings) {
2644 : env.enclClass.sym.type;
2645 Symbol msym = TreeInfo.symbol(tree.meth);
2646 restype = adjustMethodReturnType(msym, qualifier, methName, argtypes, restype);
2647
2648 chk.checkRefTypes(tree.typeargs, typeargtypes);
2649
2650 // Check that value of resulting type is admissible in the
2651 // current context. Also, capture the return type
2652 Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true);
2653 result = check(tree, capturedRes, KindSelector.VAL, resultInfo);
2654 }
2655 chk.validate(tree.typeargs, localEnv);
2656 }
2657 //where
2658 Type adjustMethodReturnType(Symbol msym, Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
2659 if (msym != null &&
2660 (msym.owner == syms.objectType.tsym || msym.owner.isInterface()) &&
2661 methodName == names.getClass &&
2662 argtypes.isEmpty()) {
2663 // as a special case, x.getClass() has type Class<? extends |X|>
2664 // Special treatment for primitive classes: Given an expression v of type V where
2665 // V is a primitive class, v.getClass() is typed to be Class<? extends |V.ref|>
2666 Type wcb = types.erasure(allowPrimitiveClasses && qualifierType.isPrimitiveClass() ?
2667 qualifierType.referenceProjection() : qualifierType.baseType());
2668 return new ClassType(restype.getEnclosingType(),
2669 List.of(new WildcardType(wcb,
2670 BoundKind.EXTENDS,
2671 syms.boundClass)),
2672 restype.tsym,
2673 restype.getMetadata(),
2674 restype.getFlavor());
2675 } else if (msym != null &&
2676 msym.owner == syms.arrayClass &&
2677 methodName == names.clone &&
2678 types.isArray(qualifierType)) {
2679 // as a special case, array.clone() has a result that is
2680 // the same as static type of the array being cloned
2681 return qualifierType;
2682 } else {
2683 return restype;
2684 }
2685 }
2686
2687 /** Check that given application node appears as first statement
2688 * in a constructor call.
2689 * @param tree The application node
2690 * @param enclMethod The enclosing method of the application.
2691 * @param error Should an error be issued?
2692 */
2693 boolean checkFirstConstructorStat(JCMethodInvocation tree, JCMethodDecl enclMethod, boolean error) {
2694 if (enclMethod != null && names.isInitOrVNew(enclMethod.name)) {
2695 JCBlock body = enclMethod.body;
2696 if (body.stats.head.hasTag(EXEC) &&
2697 ((JCExpressionStatement) body.stats.head).expr == tree)
2698 return true;
2699 }
2700 if (error) {
2701 log.error(tree.pos(),
2702 Errors.CallMustBeFirstStmtInCtor(TreeInfo.name(tree.meth)));
2703 }
2704 return false;
2705 }
2706
2707 /** Obtain a method type with given argument types.
2708 */
2709 Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
2710 MethodType mt = new MethodType(argtypes, restype, List.nil(), syms.methodClass);
2711 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
2712 }
2713
2714 public void visitNewClass(final JCNewClass tree) {
2823 }
2824
2825 // Attribute constructor arguments.
2826 ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2827 final KindSelector pkind =
2828 attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
2829 List<Type> argtypes = argtypesBuf.toList();
2830 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
2831
2832 if (clazztype.hasTag(CLASS) || clazztype.hasTag(ERROR)) {
2833 // Enums may not be instantiated except implicitly
2834 if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 &&
2835 (!env.tree.hasTag(VARDEF) ||
2836 (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 ||
2837 ((JCVariableDecl) env.tree).init != tree))
2838 log.error(tree.pos(), Errors.EnumCantBeInstantiated);
2839
2840 boolean isSpeculativeDiamondInferenceRound = TreeInfo.isDiamond(tree) &&
2841 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
2842 boolean skipNonDiamondPath = false;
2843 // Check that it is an instantiation of a class and not a projection type
2844 if (allowPrimitiveClasses) {
2845 if (clazz.hasTag(SELECT)) {
2846 JCFieldAccess fieldAccess = (JCFieldAccess) clazz;
2847 if (fieldAccess.selected.type.isPrimitiveClass() &&
2848 (fieldAccess.name == names.ref || fieldAccess.name == names.val)) {
2849 log.error(tree.pos(), Errors.ProjectionCantBeInstantiated);
2850 }
2851 }
2852 }
2853 // Check that class is not abstract
2854 if (cdef == null && !isSpeculativeDiamondInferenceRound && // class body may be nulled out in speculative tree copy
2855 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
2856 log.error(tree.pos(),
2857 Errors.AbstractCantBeInstantiated(clazztype.tsym));
2858 skipNonDiamondPath = true;
2859 } else if (cdef != null && clazztype.tsym.isInterface()) {
2860 // Check that no constructor arguments are given to
2861 // anonymous classes implementing an interface
2862 if (!argtypes.isEmpty())
2863 log.error(tree.args.head.pos(), Errors.AnonClassImplIntfNoArgs);
2864
2865 if (!typeargtypes.isEmpty())
2866 log.error(tree.typeargs.head.pos(), Errors.AnonClassImplIntfNoTypeargs);
2867
2868 // Error recovery: pretend no arguments were supplied.
2869 argtypes = List.nil();
2870 typeargtypes = List.nil();
2871 skipNonDiamondPath = true;
2872 }
2873 if (TreeInfo.isDiamond(tree)) {
2874 ClassType site = new ClassType(clazztype.getEnclosingType(),
2875 clazztype.tsym.type.getTypeArguments(),
2876 clazztype.tsym,
2877 clazztype.getMetadata(),
2878 clazztype.getFlavor());
2879
2880 Env<AttrContext> diamondEnv = localEnv.dup(tree);
2881 diamondEnv.info.selectSuper = cdef != null || tree.classDeclRemoved();
2882 diamondEnv.info.pendingResolutionPhase = null;
2883
2884 //if the type of the instance creation expression is a class type
2885 //apply method resolution inference (JLS 15.12.2.7). The return type
2886 //of the resolved constructor will be a partially instantiated type
2887 Symbol constructor = rs.resolveDiamond(tree.pos(),
2888 diamondEnv,
2889 site,
2890 argtypes,
2891 typeargtypes);
2892 tree.constructor = constructor.baseSymbol();
2893
2894 final TypeSymbol csym = clazztype.tsym;
2895 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes),
2896 diamondContext(tree, csym, resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
2897 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
2898 constructorType = checkId(tree, site,
3012 this.resultInfo = prevResult;
3013 }
3014 });
3015 } else {
3016 if (isDiamond && clazztype.hasTag(CLASS)) {
3017 List<Type> invalidDiamondArgs = chk.checkDiamondDenotable((ClassType)clazztype);
3018 if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
3019 // One or more types inferred in the previous steps is non-denotable.
3020 Fragment fragment = Diamond(clazztype.tsym);
3021 log.error(tree.clazz.pos(),
3022 Errors.CantApplyDiamond1(
3023 fragment,
3024 invalidDiamondArgs.size() > 1 ?
3025 DiamondInvalidArgs(invalidDiamondArgs, fragment) :
3026 DiamondInvalidArg(invalidDiamondArgs, fragment)));
3027 }
3028 // For <>(){}, inferred types must also be accessible.
3029 for (Type t : clazztype.getTypeArguments()) {
3030 rs.checkAccessibleType(env, t);
3031 }
3032 if (allowPrimitiveClasses) {
3033 chk.checkParameterizationByPrimitiveClass(tree, clazztype);
3034 }
3035 }
3036
3037 // If we already errored, be careful to avoid a further avalanche. ErrorType answers
3038 // false for isInterface call even when the original type is an interface.
3039 boolean implementing = clazztype.tsym.isInterface() ||
3040 clazztype.isErroneous() && !clazztype.getOriginalType().hasTag(NONE) &&
3041 clazztype.getOriginalType().tsym.isInterface();
3042
3043 if (implementing) {
3044 cdef.implementing = List.of(clazz);
3045 } else {
3046 cdef.extending = clazz;
3047 }
3048
3049 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3050 rs.isSerializable(clazztype)) {
3051 localEnv.info.isSerializable = true;
3052 }
3053
3054 attribStat(cdef, localEnv);
3087 result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK));
3088 chk.validate(tree.typeargs, localEnv);
3089 }
3090
3091 CheckContext diamondContext(JCNewClass clazz, TypeSymbol tsym, CheckContext checkContext) {
3092 return new Check.NestedCheckContext(checkContext) {
3093 @Override
3094 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
3095 enclosingContext.report(clazz.clazz,
3096 diags.fragment(Fragments.CantApplyDiamond1(Fragments.Diamond(tsym), details)));
3097 }
3098 };
3099 }
3100
3101 /** Make an attributed null check tree.
3102 */
3103 public JCExpression makeNullCheck(JCExpression arg) {
3104 // optimization: new Outer() can never be null; skip null check
3105 if (arg.getTag() == NEWCLASS)
3106 return arg;
3107 // Likewise arg can't be null if it is a primitive class instance.
3108 if (allowPrimitiveClasses && arg.type.isPrimitiveClass())
3109 return arg;
3110 // optimization: X.this is never null; skip null check
3111 Name name = TreeInfo.name(arg);
3112 if (name == names._this || name == names._super) return arg;
3113
3114 JCTree.Tag optag = NULLCHK;
3115 JCUnary tree = make.at(arg.pos).Unary(optag, arg);
3116 tree.operator = operators.resolveUnary(arg, optag, arg.type);
3117 tree.type = arg.type;
3118 return tree;
3119 }
3120
3121 public void visitNewArray(JCNewArray tree) {
3122 Type owntype = types.createErrorType(tree.type);
3123 Env<AttrContext> localEnv = env.dup(tree);
3124 Type elemtype;
3125 if (tree.elemtype != null) {
3126 elemtype = attribType(tree.elemtype, localEnv);
3127 chk.validate(tree.elemtype, localEnv);
3128 owntype = elemtype;
3129 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
3579 *
3580 * The owner of this environment is a method symbol. If the current owner
3581 * is not a method, for example if the lambda is used to initialize
3582 * a field, then if the field is:
3583 *
3584 * - an instance field, we use the first constructor.
3585 * - a static field, we create a fake clinit method.
3586 */
3587 public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
3588 Env<AttrContext> lambdaEnv;
3589 Symbol owner = env.info.scope.owner;
3590 if (owner.kind == VAR && owner.owner.kind == TYP) {
3591 //field initializer
3592 ClassSymbol enclClass = owner.enclClass();
3593 Symbol newScopeOwner = env.info.scope.owner;
3594 /* if the field isn't static, then we can get the first constructor
3595 * and use it as the owner of the environment. This is what
3596 * LTM code is doing to look for type annotations so we are fine.
3597 */
3598 if ((owner.flags() & STATIC) == 0) {
3599 Name constructorName = owner.isConcreteValueClass() ? names.vnew : names.init;
3600 for (Symbol s : enclClass.members_field.getSymbolsByName(constructorName)) {
3601 newScopeOwner = s;
3602 break;
3603 }
3604 } else {
3605 /* if the field is static then we need to create a fake clinit
3606 * method, this method can later be reused by LTM.
3607 */
3608 MethodSymbol clinit = clinits.get(enclClass);
3609 if (clinit == null) {
3610 Type clinitType = new MethodType(List.nil(),
3611 syms.voidType, List.nil(), syms.methodClass);
3612 clinit = new MethodSymbol(STATIC | SYNTHETIC | PRIVATE,
3613 names.clinit, clinitType, enclClass);
3614 clinit.params = List.nil();
3615 clinits.put(enclClass, clinit);
3616 }
3617 newScopeOwner = clinit;
3618 }
3619 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(newScopeOwner)));
3620 } else {
3643
3644 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3645 exprType = chk.checkConstructorRefType(that.expr, exprType);
3646 if (!exprType.isErroneous() &&
3647 exprType.isRaw() &&
3648 that.typeargs != null) {
3649 log.error(that.expr.pos(),
3650 Errors.InvalidMref(Kinds.kindName(that.getMode()),
3651 Fragments.MrefInferAndExplicitParams));
3652 exprType = types.createErrorType(exprType);
3653 }
3654 }
3655
3656 if (exprType.isErroneous()) {
3657 //if the qualifier expression contains problems,
3658 //give up attribution of method reference
3659 result = that.type = exprType;
3660 return;
3661 }
3662
3663 Symbol lhsSym = TreeInfo.symbol(that.expr);
3664 if (TreeInfo.isStaticSelector(that.expr, names)) {
3665 // TODO - a bit hacky but...
3666 if (lhsSym != null && lhsSym.isConcreteValueClass() && that.name == names.init) {
3667 that.name = names.vnew;
3668 }
3669 //if the qualifier is a type, validate it; raw warning check is
3670 //omitted as we don't know at this stage as to whether this is a
3671 //raw selector (because of inference)
3672 chk.validate(that.expr, env, false);
3673 } else {
3674 localEnv.info.selectSuper = lhsSym != null && lhsSym.name == names._super;
3675 }
3676 //attrib type-arguments
3677 List<Type> typeargtypes = List.nil();
3678 if (that.typeargs != null) {
3679 typeargtypes = attribTypes(that.typeargs, localEnv);
3680 }
3681
3682 boolean isTargetSerializable =
3683 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3684 rs.isSerializable(pt());
3685 TargetInfo targetInfo = getTargetInfo(that, resultInfo, null);
3686 Type currentTarget = targetInfo.target;
3687 Type desc = targetInfo.descriptor;
3688
3689 setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
3690 List<Type> argtypes = desc.getParameterTypes();
3691 Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
3692
3693 if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
3737 targetError ?
3738 Fragments.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag) :
3739 Errors.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag));
3740
3741 if (targetError && currentTarget == Type.recoveryType) {
3742 //a target error doesn't make sense during recovery stage
3743 //as we don't know what actual parameter types are
3744 result = that.type = currentTarget;
3745 return;
3746 } else {
3747 if (targetError) {
3748 resultInfo.checkContext.report(that, diag);
3749 } else {
3750 log.report(diag);
3751 }
3752 result = that.type = types.createErrorType(currentTarget);
3753 return;
3754 }
3755 }
3756
3757 that.sym = refSym.isInitOrVNew() ? refSym.baseSymbol() : refSym;
3758 that.kind = lookupHelper.referenceKind(that.sym);
3759 that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
3760
3761 if (desc.getReturnType() == Type.recoveryType) {
3762 // stop here
3763 result = that.type = currentTarget;
3764 return;
3765 }
3766
3767 if (!env.info.attributionMode.isSpeculative && that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3768 Type enclosingType = exprType.getEnclosingType();
3769 if (enclosingType != null && enclosingType.hasTag(CLASS)) {
3770 // Check for the existence of an appropriate outer instance
3771 rs.resolveImplicitThis(that.pos(), env, exprType);
3772 }
3773 }
3774
3775 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
3776
3777 if (that.getMode() == ReferenceMode.INVOKE &&
4426 }
4427
4428 public void visitSelect(JCFieldAccess tree) {
4429 // Determine the expected kind of the qualifier expression.
4430 KindSelector skind = KindSelector.NIL;
4431 if (tree.name == names._this || tree.name == names._super ||
4432 tree.name == names._class)
4433 {
4434 skind = KindSelector.TYP;
4435 } else {
4436 if (pkind().contains(KindSelector.PCK))
4437 skind = KindSelector.of(skind, KindSelector.PCK);
4438 if (pkind().contains(KindSelector.TYP))
4439 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4440 if (pkind().contains(KindSelector.VAL_MTH))
4441 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4442 }
4443
4444 // Attribute the qualifier expression, and determine its symbol (if any).
4445 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4446 Assert.check(site == tree.selected.type);
4447 if (allowPrimitiveClasses && tree.name == names._class && site.isPrimitiveClass()) {
4448 /* JDK-8269956: Where a reflective (class) literal is needed, the unqualified Point.class is
4449 * always the "primary" mirror - representing the primitive reference runtime type - thereby
4450 * always matching the behavior of Object::getClass
4451 */
4452 if (!tree.selected.hasTag(SELECT) || ((JCFieldAccess) tree.selected).name != names.val) {
4453 tree.selected.setType(site = site.referenceProjection());
4454 }
4455 }
4456 if (!pkind().contains(KindSelector.TYP_PCK))
4457 site = capture(site); // Capture field access
4458
4459 // don't allow T.class T[].class, etc
4460 if (skind == KindSelector.TYP) {
4461 Type elt = site;
4462 while (elt.hasTag(ARRAY))
4463 elt = ((ArrayType)elt).elemtype;
4464 if (elt.hasTag(TYPEVAR)) {
4465 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4466 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4467 tree.sym = tree.type.tsym;
4468 return;
4469 }
4470 }
4471
4472 // If qualifier symbol is a type or `super', assert `selectSuper'
4473 // for the selection. This is relevant for determining whether
4474 // protected symbols are accessible.
4475 Symbol sitesym = TreeInfo.symbol(tree.selected);
4476 boolean selectSuperPrev = env.info.selectSuper;
4477 env.info.selectSuper =
4478 sitesym != null &&
4479 sitesym.name == names._super;
4480
4481 // Determine the symbol represented by the selection.
4482 env.info.pendingResolutionPhase = null;
4483 Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
4484 if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
4485 log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym));
4486 sym = syms.errSymbol;
4487 }
4488 if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
4552 } else if (sym.kind != ERR &&
4553 (sym.flags() & STATIC) != 0 &&
4554 sym.name != names._class) {
4555 // If the qualified item is not a type and the selected item is static, report
4556 // a warning. Make allowance for the class of an array type e.g. Object[].class)
4557 if (!sym.owner.isAnonymous()) {
4558 chk.warnStatic(tree, Warnings.StaticNotQualifiedByType(sym.kind.kindName(), sym.owner));
4559 } else {
4560 chk.warnStatic(tree, Warnings.StaticNotQualifiedByType2(sym.kind.kindName()));
4561 }
4562 }
4563
4564 // If we are selecting an instance member via a `super', ...
4565 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
4566
4567 // Check that super-qualified symbols are not abstract (JLS)
4568 rs.checkNonAbstract(tree.pos(), sym);
4569
4570 if (site.isRaw()) {
4571 // Determine argument types for site.
4572 Type site1 = types.asSuper(env.enclClass.sym.type.referenceProjectionOrSelf(), site.tsym);
4573 if (site1 != null) site = site1;
4574 }
4575 }
4576
4577 if (env.info.isSerializable) {
4578 chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4579 }
4580
4581 env.info.selectSuper = selectSuperPrev;
4582 result = checkId(tree, site, sym, env, resultInfo);
4583 }
4584 //where
4585 /** Determine symbol referenced by a Select expression,
4586 *
4587 * @param tree The select tree.
4588 * @param site The type of the selected expression,
4589 * @param env The current environment.
4590 * @param resultInfo The current result.
4591 */
4592 private Symbol selectSym(JCFieldAccess tree,
4595 Env<AttrContext> env,
4596 ResultInfo resultInfo) {
4597 DiagnosticPosition pos = tree.pos();
4598 Name name = tree.name;
4599 switch (site.getTag()) {
4600 case PACKAGE:
4601 return rs.accessBase(
4602 rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind),
4603 pos, location, site, name, true);
4604 case ARRAY:
4605 case CLASS:
4606 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
4607 return rs.resolveQualifiedMethod(
4608 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
4609 } else if (name == names._this || name == names._super) {
4610 return rs.resolveSelf(pos, env, site.tsym, name);
4611 } else if (name == names._class) {
4612 // In this case, we have already made sure in
4613 // visitSelect that qualifier expression is a type.
4614 return syms.getClassField(site, types);
4615 } else if (allowPrimitiveClasses && site.isPrimitiveClass() && isType(location) && resultInfo.pkind.contains(KindSelector.TYP) && (name == names.ref || name == names.val)) {
4616 return site.tsym;
4617 } else {
4618 // We are seeing a plain identifier as selector.
4619 Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind);
4620 sym = rs.accessBase(sym, pos, location, site, name, true);
4621 return sym;
4622 }
4623 case WILDCARD:
4624 throw new AssertionError(tree);
4625 case TYPEVAR:
4626 // Normally, site.getUpperBound() shouldn't be null.
4627 // It should only happen during memberEnter/attribBase
4628 // when determining the supertype which *must* be
4629 // done before attributing the type variables. In
4630 // other words, we are seeing this illegal program:
4631 // class B<T> extends A<T.foo> {}
4632 Symbol sym = (site.getUpperBound() != null)
4633 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
4634 : null;
4635 if (sym == null) {
4636 log.error(pos, Errors.TypeVarCantBeDeref);
4700 if (resultInfo.pkind.contains(KindSelector.POLY)) {
4701 return attrRecover.recoverMethodInvocation(tree, site, sym, env, resultInfo);
4702 } else {
4703 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
4704 }
4705 }
4706
4707 Type checkIdInternal(JCTree tree,
4708 Type site,
4709 Symbol sym,
4710 Type pt,
4711 Env<AttrContext> env,
4712 ResultInfo resultInfo) {
4713 if (pt.isErroneous()) {
4714 return types.createErrorType(site);
4715 }
4716 Type owntype; // The computed type of this identifier occurrence.
4717 switch (sym.kind) {
4718 case TYP:
4719 // For types, the computed type equals the symbol's type,
4720 // except for three situations:
4721 owntype = sym.type;
4722 if (owntype.hasTag(CLASS)) {
4723 if (allowPrimitiveClasses) {
4724 Assert.check(owntype.getFlavor() != Flavor.X_Typeof_X);
4725 }
4726 chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
4727 Type ownOuter = owntype.getEnclosingType();
4728
4729 // (a) If symbol is a primitive class and its reference projection
4730 // is requested via the .ref notation, then adjust the computed type to
4731 // reflect this.
4732 if (allowPrimitiveClasses && owntype.isPrimitiveClass() && tree.hasTag(SELECT) && ((JCFieldAccess) tree).name == names.ref) {
4733 owntype = new ClassType(owntype.getEnclosingType(), owntype.getTypeArguments(), (TypeSymbol)sym, owntype.getMetadata(), Flavor.L_TypeOf_Q);
4734 }
4735
4736 // (b) If the symbol's type is parameterized, erase it
4737 // because no type parameters were given.
4738 // We recover generic outer type later in visitTypeApply.
4739 if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
4740 owntype = types.erasure(owntype);
4741 }
4742
4743 // (c) If the symbol's type is an inner class, then
4744 // we have to interpret its outer type as a superclass
4745 // of the site type. Example:
4746 //
4747 // class Tree<A> { class Visitor { ... } }
4748 // class PointTree extends Tree<Point> { ... }
4749 // ...PointTree.Visitor...
4750 //
4751 // Then the type of the last expression above is
4752 // Tree<Point>.Visitor.
4753 else if (ownOuter.hasTag(CLASS) && site != ownOuter) {
4754 Type normOuter = site;
4755 if (normOuter.hasTag(CLASS)) {
4756 normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
4757 }
4758 if (normOuter == null) // perhaps from an import
4759 normOuter = types.erasure(ownOuter);
4760 if (normOuter != ownOuter)
4761 owntype = new ClassType(
4762 normOuter, List.nil(), owntype.tsym,
4763 owntype.getMetadata(), owntype.getFlavor());
4764 }
4765 }
4766 break;
4767 case VAR:
4768 VarSymbol v = (VarSymbol)sym;
4769
4770 if (env.info.enclVar != null
4771 && v.type.hasTag(NONE)) {
4772 //self reference to implicitly typed variable declaration
4773 log.error(TreeInfo.positionFor(v, env.enclClass), Errors.CantInferLocalVarType(v.name, Fragments.LocalSelfRef));
4774 return tree.type = v.type = types.createErrorType(v.type);
4775 }
4776
4777 // Test (4): if symbol is an instance field of a raw type,
4778 // which is being assigned to, issue an unchecked warning if
4779 // its type changes under erasure.
4780 if (KindSelector.ASG.subset(pkind()) &&
4781 v.owner.kind == TYP &&
4782 (v.flags() & STATIC) == 0 &&
4783 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
4806 break;
4807 case MTH: {
4808 owntype = checkMethod(site, sym,
4809 new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext, resultInfo.checkMode),
4810 env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
4811 resultInfo.pt.getTypeArguments());
4812 break;
4813 }
4814 case PCK: case ERR:
4815 owntype = sym.type;
4816 break;
4817 default:
4818 throw new AssertionError("unexpected kind: " + sym.kind +
4819 " in tree " + tree);
4820 }
4821
4822 // Emit a `deprecation' warning if symbol is deprecated.
4823 // (for constructors (but not for constructor references), the error
4824 // was given when the constructor was resolved)
4825
4826 if (!names.isInitOrVNew(sym.name) || tree.hasTag(REFERENCE)) {
4827 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
4828 chk.checkSunAPI(tree.pos(), sym);
4829 chk.checkProfile(tree.pos(), sym);
4830 chk.checkPreview(tree.pos(), env.info.scope.owner, sym);
4831 }
4832
4833 // If symbol is a variable, check that its type and
4834 // kind are compatible with the prototype and protokind.
4835 return check(tree, owntype, sym.kind.toSelector(), resultInfo);
4836 }
4837
4838 /** Check that variable is initialized and evaluate the variable's
4839 * initializer, if not yet done. Also check that variable is not
4840 * referenced before it is defined.
4841 * @param tree The tree making up the variable reference.
4842 * @param env The current environment.
4843 * @param v The variable's symbol.
4844 */
4845 private void checkInit(JCTree tree,
4846 Env<AttrContext> env,
5060 //depending on the current check context
5061 resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
5062 return types.createErrorType(site);
5063 } catch (Resolve.InapplicableMethodException ex) {
5064 final JCDiagnostic diag = ex.getDiagnostic();
5065 Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
5066 @Override
5067 protected Pair<Symbol, JCDiagnostic> errCandidate() {
5068 return new Pair<>(sym, diag);
5069 }
5070 };
5071 List<Type> argtypes2 = argtypes.map(
5072 rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
5073 JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
5074 env.tree, sym, site, sym.name, argtypes2, typeargtypes);
5075 log.report(errDiag);
5076 return types.createErrorType(site);
5077 }
5078 }
5079
5080 public void visitDefaultValue(JCDefaultValue tree) {
5081 if (!allowPrimitiveClasses) {
5082 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.pos(),
5083 Feature.PRIMITIVE_CLASSES.error(sourceName));
5084 }
5085
5086 // Attribute the qualifier expression, and determine its symbol (if any).
5087 Type site = attribTree(tree.clazz, env, new ResultInfo(KindSelector.TYP_PCK, Type.noType));
5088 if (!pkind().contains(KindSelector.TYP_PCK))
5089 site = capture(site); // Capture field access
5090 if (!allowPrimitiveClasses) {
5091 result = types.createErrorType(names._default, site.tsym, site);
5092 } else {
5093 Symbol sym = switch (site.getTag()) {
5094 case WILDCARD -> throw new AssertionError(tree);
5095 case PACKAGE -> {
5096 log.error(tree.pos, Errors.CantResolveLocation(Kinds.KindName.CLASS, site.tsym.getQualifiedName(), null, null,
5097 Fragments.Location(Kinds.typeKindName(env.enclClass.type), env.enclClass.type, null)));
5098 yield syms.errSymbol;
5099 }
5100 case ERROR -> types.createErrorType(names._default, site.tsym, site).tsym;
5101 default -> new VarSymbol(STATIC, names._default, site, site.tsym);
5102 };
5103
5104 if (site.hasTag(TYPEVAR) && sym.kind != ERR) {
5105 site = types.skipTypeVars(site, true);
5106 }
5107 result = checkId(tree, site, sym, env, resultInfo);
5108 }
5109 }
5110
5111 public void visitLiteral(JCLiteral tree) {
5112 result = check(tree, litType(tree.typetag).constType(tree.value),
5113 KindSelector.VAL, resultInfo);
5114 }
5115 //where
5116 /** Return the type of a literal with given type tag.
5117 */
5118 Type litType(TypeTag tag) {
5119 return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
5120 }
5121
5122 public void visitStringTemplate(JCStringTemplate tree) {
5123 JCExpression processor = tree.processor;
5124 Type resultType = syms.stringTemplateType;
5125
5126 if (processor != null) {
5127 resultType = attribTree(processor, env, new ResultInfo(KindSelector.VAL, Type.noType));
5128 resultType = chk.checkProcessorType(processor, resultType, env);
5129 }
5130
5178 }
5179 // Compute the proper generic outer
5180 Type clazzOuter = clazztype.getEnclosingType();
5181 if (clazzOuter.hasTag(CLASS)) {
5182 Type site;
5183 JCExpression clazz = TreeInfo.typeIn(tree.clazz);
5184 if (clazz.hasTag(IDENT)) {
5185 site = env.enclClass.sym.type;
5186 } else if (clazz.hasTag(SELECT)) {
5187 site = ((JCFieldAccess) clazz).selected.type;
5188 } else throw new AssertionError(""+tree);
5189 if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
5190 if (site.hasTag(CLASS))
5191 site = types.asOuterSuper(site, clazzOuter.tsym);
5192 if (site == null)
5193 site = types.erasure(clazzOuter);
5194 clazzOuter = site;
5195 }
5196 }
5197 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
5198 clazztype.getMetadata(), clazztype.getFlavor());
5199 } else {
5200 if (formals.length() != 0) {
5201 log.error(tree.pos(),
5202 Errors.WrongNumberTypeArgs(Integer.toString(formals.length())));
5203 } else {
5204 log.error(tree.pos(), Errors.TypeDoesntTakeParams(clazztype.tsym));
5205 }
5206 owntype = types.createErrorType(tree.type);
5207 }
5208 }
5209 result = check(tree, owntype, KindSelector.TYP, resultInfo);
5210 }
5211
5212 public void visitTypeUnion(JCTypeUnion tree) {
5213 ListBuffer<Type> multicatchTypes = new ListBuffer<>();
5214 ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
5215 for (JCExpression typeTree : tree.alternatives) {
5216 Type ctype = attribType(typeTree, env);
5217 ctype = chk.checkType(typeTree.pos(),
5218 chk.checkClassType(typeTree.pos(), ctype),
5305 if (bounds.length() == 0) {
5306 return syms.objectType;
5307 } else if (bounds.length() == 1) {
5308 return bounds.head.type;
5309 } else {
5310 Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
5311 // ... the variable's bound is a class type flagged COMPOUND
5312 // (see comment for TypeVar.bound).
5313 // In this case, generate a class tree that represents the
5314 // bound class, ...
5315 JCExpression extending;
5316 List<JCExpression> implementing;
5317 if (!bounds.head.type.isInterface()) {
5318 extending = bounds.head;
5319 implementing = bounds.tail;
5320 } else {
5321 extending = null;
5322 implementing = bounds;
5323 }
5324 JCClassDecl cd = make.at(tree).ClassDef(
5325 make.Modifiers(PUBLIC | ABSTRACT | (extending != null && TreeInfo.symbol(extending).isPrimitiveClass() ? PRIMITIVE_CLASS : 0)),
5326 names.empty, List.nil(),
5327 extending, implementing, List.nil());
5328
5329 ClassSymbol c = (ClassSymbol)owntype.tsym;
5330 Assert.check((c.flags() & COMPOUND) != 0);
5331 cd.sym = c;
5332 c.sourcefile = env.toplevel.sourcefile;
5333
5334 // ... and attribute the bound class
5335 c.flags_field |= UNATTRIBUTED;
5336 Env<AttrContext> cenv = enter.classEnv(cd, env);
5337 typeEnvs.put(c, cenv);
5338 attribClass(c);
5339 return owntype;
5340 }
5341 }
5342
5343 public void visitWildcard(JCWildcard tree) {
5344 //- System.err.println("visitWildcard("+tree+");");//DEBUG
5345 Type type = (tree.kind.kind == BoundKind.UNBOUND)
5346 ? syms.objectType
5347 : attribType(tree.inner, env);
5348 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type, false),
5349 tree.kind.kind,
5350 syms.boundClass),
5351 KindSelector.TYP, resultInfo);
5352 }
5353
5354 public void visitAnnotation(JCAnnotation tree) {
5355 Assert.error("should be handled in annotate");
5356 }
5357
5358 @Override
5359 public void visitModifiers(JCModifiers tree) {
5360 //error recovery only:
5361 Assert.check(resultInfo.pkind == KindSelector.ERR);
5362
5363 attribAnnotationTypes(tree.annotations, env);
5364 }
5365
5366 public void visitAnnotatedType(JCAnnotatedType tree) {
5367 attribAnnotationTypes(tree.annotations, env);
5368 Type underlyingType = attribType(tree.underlyingType, env);
5446
5447 try {
5448 deferredLintHandler.flush(env.tree.pos());
5449 attrib.accept(env);
5450 } finally {
5451 log.useSource(prev);
5452 chk.setLint(prevLint);
5453 }
5454 }
5455
5456 /** Main method: attribute class definition associated with given class symbol.
5457 * reporting completion failures at the given position.
5458 * @param pos The source position at which completion errors are to be
5459 * reported.
5460 * @param c The class symbol whose definition will be attributed.
5461 */
5462 public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
5463 try {
5464 annotate.flush();
5465 attribClass(c);
5466 if (allowPrimitiveClasses && c.type.isPrimitiveClass()) {
5467 final Env<AttrContext> env = typeEnvs.get(c);
5468 if (env != null && env.tree != null && env.tree.hasTag(CLASSDEF))
5469 chk.checkNonCyclicMembership((JCClassDecl)env.tree);
5470 }
5471 } catch (CompletionFailure ex) {
5472 chk.completionError(pos, ex);
5473 }
5474 }
5475
5476 /** Attribute class definition associated with given class symbol.
5477 * @param c The class symbol whose definition will be attributed.
5478 */
5479 void attribClass(ClassSymbol c) throws CompletionFailure {
5480 if (c.type.hasTag(ERROR)) return;
5481
5482 // Check for cycles in the inheritance graph, which can arise from
5483 // ill-formed class files.
5484 chk.checkNonCyclic(null, c.type);
5485
5486 Type st = types.supertype(c.type);
5487 if ((c.flags_field & Flags.COMPOUND) == 0 &&
5488 (c.flags_field & Flags.SUPER_OWNER_ATTRIBUTED) == 0) {
5489 // First, attribute superclass.
5490 if (st.hasTag(CLASS))
5571 .filter(s -> s.tsym.isSealed())
5572 .map(s -> (ClassSymbol) s.tsym)
5573 .collect(List.collector());
5574
5575 if (sealedSupers.isEmpty()) {
5576 if ((c.flags_field & Flags.NON_SEALED) != 0) {
5577 boolean hasErrorSuper = false;
5578
5579 hasErrorSuper |= types.directSupertypes(c.type)
5580 .stream()
5581 .anyMatch(s -> s.tsym.kind == Kind.ERR);
5582
5583 ClassType ct = (ClassType) c.type;
5584
5585 hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5586
5587 if (!hasErrorSuper) {
5588 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5589 }
5590 }
5591 } else if ((c.flags_field & Flags.COMPOUND) == 0) {
5592 if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5593 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5594 }
5595
5596 if (!c.type.isCompound()) {
5597 for (ClassSymbol supertypeSym : sealedSupers) {
5598 if (!supertypeSym.permitted.contains(c.type.tsym)) {
5599 log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5600 }
5601 }
5602 if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5603 log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5604 c.isInterface() ?
5605 Errors.NonSealedOrSealedExpected :
5606 Errors.NonSealedSealedOrFinalExpected);
5607 }
5608 }
5609 }
5610
5611 // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
5626
5627 try {
5628 deferredLintHandler.flush(env.tree);
5629 env.info.returnResult = null;
5630 // java.lang.Enum may not be subclassed by a non-enum
5631 if (st.tsym == syms.enumSym &&
5632 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5633 log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5634
5635 // Enums may not be extended by source-level classes
5636 if (st.tsym != null &&
5637 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5638 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5639 log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5640 }
5641
5642 if (rs.isSerializable(c.type)) {
5643 env.info.isSerializable = true;
5644 }
5645
5646 if (c.isValueClass()) {
5647 Assert.check(env.tree.hasTag(CLASSDEF));
5648 chk.checkConstraintsOfValueClass(env.tree.pos(), c);
5649 }
5650
5651 attribClassBody(env, c);
5652
5653 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5654 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5655 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5656 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5657
5658 if ((c.flags_field & Flags.UNNAMED_CLASS) != 0) {
5659 chk.checkHasMain(env.tree.pos(), c);
5660 }
5661 } finally {
5662 env.info.returnResult = prevReturnRes;
5663 log.useSource(prev);
5664 chk.setLint(prevLint);
5665 }
5666
5667 }
5668 }
5669
5670 public void visitImport(JCImport tree) {
|