163 dependencies = Dependencies.instance(context);
164 argumentAttr = ArgumentAttr.instance(context);
165 matchBindingsComputer = MatchBindingsComputer.instance(context);
166 attrRecover = AttrRecover.instance(context);
167
168 Options options = Options.instance(context);
169
170 Source source = Source.instance(context);
171 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 captureMRefReturnType = Source.Feature.CAPTURE_MREF_RETURN_TYPE.allowedInSource(source);
180
181 statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
182 varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
183 unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
184 methodAttrInfo = new MethodAttrInfo();
185 unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
186 unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
187 recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
188 initBlockType = new MethodType(List.nil(), syms.voidType, List.nil(), syms.methodClass);
189 }
190
191 /** Switch: reifiable types in instanceof enabled?
192 */
193 boolean allowReifiableTypesInInstanceof;
194
195 /** Are records allowed
196 */
197 private final boolean allowRecords;
198
199 /** Are patterns in switch allowed
200 */
201 private final boolean allowPatternSwitch;
202
203 /** Are unconditional patterns in instanceof allowed
204 */
205 private final boolean allowUnconditionalPatternsInstanceOf;
206
207 /**
208 * Switch: warn about use of variable before declaration?
209 * RFE: 6425594
210 */
211 boolean useBeforeDeclarationWarning;
212
213 /**
214 * Switch: name of source level; used for error reporting.
215 */
216 String sourceName;
217
218 /** Check kind and type of given tree against protokind and prototype.
219 * If check succeeds, store type in tree and return it.
220 * If check fails, store errType in tree and return it.
221 * No checks are performed if the prototype is a method type.
222 * It is not necessary in this case since we know that kind and type
223 * are correct.
224 *
225 * @param tree The tree whose kind and type is checked
226 * @param found The computed type of the tree
295 * @param env The current environment.
296 */
297 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
298 if (v.name == names._this) {
299 log.error(pos, Errors.CantAssignValToThis);
300 return;
301 }
302 if ((v.flags() & FINAL) != 0 &&
303 ((v.flags() & HASINIT) != 0
304 ||
305 !((base == null ||
306 TreeInfo.isThisQualifier(base)) &&
307 isAssignableAsBlankFinal(v, env)))) {
308 if (v.isResourceVariable()) { //TWR resource
309 log.error(pos, Errors.TryResourceMayNotBeAssigned(v));
310 } else {
311 log.error(pos, Errors.CantAssignValToVar(Flags.toSource(v.flags() & (STATIC | FINAL)), v));
312 }
313 return;
314 }
315
316 // Check instance field assignments that appear in constructor prologues
317 if (rs.isEarlyReference(env, base, v)) {
318
319 // Field may not be inherited from a superclass
320 if (v.owner != env.enclClass.sym) {
321 log.error(pos, Errors.CantRefBeforeCtorCalled(v));
322 return;
323 }
324
325 // Field may not have an initializer
326 if ((v.flags() & HASINIT) != 0) {
327 log.error(pos, Errors.CantAssignInitializedBeforeCtorCalled(v));
328 return;
329 }
330 }
331 }
332
333 /** Does tree represent a static reference to an identifier?
334 * It is assumed that tree is either a SELECT or an IDENT.
335 * We have to weed out selects from non-type names here.
336 * @param tree The candidate tree.
337 */
338 boolean isStaticReference(JCTree tree) {
339 if (tree.hasTag(SELECT)) {
340 Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
341 if (lsym == null || lsym.kind != TYP) {
342 return false;
343 }
344 }
345 return true;
346 }
347
348 /** Is this symbol a type?
349 */
350 static boolean isType(Symbol sym) {
610 }
611 @Override
612 public boolean compatible(Type found, Type req, Warner warn) {
613 return true;
614 }
615 @Override
616 public void report(DiagnosticPosition pos, JCDiagnostic details) {
617 boolean needsReport = pt == Type.recoveryType ||
618 (details.getDiagnosticPosition() != null &&
619 details.getDiagnosticPosition().getTree().hasTag(LAMBDA));
620 if (needsReport) {
621 chk.basicHandler.report(pos, details);
622 }
623 }
624 });
625 }
626 }
627
628 final ResultInfo statInfo;
629 final ResultInfo varAssignmentInfo;
630 final ResultInfo methodAttrInfo;
631 final ResultInfo unknownExprInfo;
632 final ResultInfo unknownTypeInfo;
633 final ResultInfo unknownTypeExprInfo;
634 final ResultInfo recoveryInfo;
635 final MethodType initBlockType;
636
637 Type pt() {
638 return resultInfo.pt;
639 }
640
641 KindSelector pkind() {
642 return resultInfo.pkind;
643 }
644
645 /* ************************************************************************
646 * Visitor methods
647 *************************************************************************/
648
649 /** Visitor argument: the current environment.
938 if (checkExtensible &&
939 ((t.tsym.flags() & FINAL) != 0)) {
940 log.error(pos,
941 Errors.CantInheritFromFinal(t.tsym));
942 }
943 chk.checkNonCyclic(pos, t);
944 return t;
945 }
946
947 Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
948 Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
949 id.type = env.info.scope.owner.enclClass().type;
950 id.sym = env.info.scope.owner.enclClass();
951 return id.type;
952 }
953
954 public void visitClassDef(JCClassDecl tree) {
955 Optional<ArgumentAttr.LocalCacheContext> localCacheContext =
956 Optional.ofNullable(env.info.attributionMode.isSpeculative ?
957 argumentAttr.withLocalCacheContext() : null);
958 boolean ctorProloguePrev = env.info.ctorPrologue;
959 try {
960 // Local and anonymous classes have not been entered yet, so we need to
961 // do it now.
962 if (env.info.scope.owner.kind.matches(KindSelector.VAL_MTH)) {
963 enter.classEnter(tree, env);
964 } else {
965 // If this class declaration is part of a class level annotation,
966 // as in @MyAnno(new Object() {}) class MyClass {}, enter it in
967 // order to simplify later steps and allow for sensible error
968 // messages.
969 if (env.tree.hasTag(NEWCLASS) && TreeInfo.isInAnnotation(env, tree))
970 enter.classEnter(tree, env);
971 }
972
973 ClassSymbol c = tree.sym;
974 if (c == null) {
975 // exit in case something drastic went wrong during enter.
976 result = null;
977 } else {
978 // make sure class has been completed:
979 c.complete();
980
981 // If a class declaration appears in a constructor prologue,
982 // that means it's either a local class or an anonymous class.
983 // Either way, there is no immediately enclosing instance.
984 if (ctorProloguePrev) {
985 c.flags_field |= NOOUTERTHIS;
986 }
987 attribClass(tree.pos(), c);
988 result = tree.type = c.type;
989 }
990 } finally {
991 localCacheContext.ifPresent(LocalCacheContext::leave);
992 env.info.ctorPrologue = ctorProloguePrev;
993 }
994 }
995
996 public void visitMethodDef(JCMethodDecl tree) {
997 MethodSymbol m = tree.sym;
998 boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
999
1000 Lint lint = env.info.lint.augment(m);
1001 Lint prevLint = chk.setLint(lint);
1002 boolean ctorProloguePrev = env.info.ctorPrologue;
1003 Assert.check(!env.info.ctorPrologue);
1004 MethodSymbol prevMethod = chk.setMethod(m);
1005 try {
1006 chk.checkDeprecatedAnnotation(tree.pos(), m);
1007
1008
1009 // Create a new environment with local scope
1010 // for attributing the method.
1011 Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
1012 localEnv.info.lint = lint;
1013
1014 attribStats(tree.typarams, localEnv);
1015
1016 // If we override any other methods, check that we do so properly.
1017 // JLS ???
1018 if (m.isStatic()) {
1019 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
1020 } else {
1021 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
1022 }
1023 chk.checkOverride(env, tree, m);
1108 * - have an accessibility stricter than that of the record type
1109 * - explicitly invoke any other constructor
1110 */
1111 if ((tree.sym.flags_field & GENERATEDCONSTR) == 0) {
1112 if (Check.protection(m.flags()) > Check.protection(env.enclClass.sym.flags())) {
1113 log.error(tree,
1114 (env.enclClass.sym.flags() & AccessFlags) == 0 ?
1115 Errors.InvalidCanonicalConstructorInRecord(
1116 Fragments.Canonical,
1117 env.enclClass.sym.name,
1118 Fragments.CanonicalMustNotHaveStrongerAccess("package")
1119 ) :
1120 Errors.InvalidCanonicalConstructorInRecord(
1121 Fragments.Canonical,
1122 env.enclClass.sym.name,
1123 Fragments.CanonicalMustNotHaveStrongerAccess(asFlagSet(env.enclClass.sym.flags() & AccessFlags))
1124 )
1125 );
1126 }
1127
1128 if (TreeInfo.hasAnyConstructorCall(tree)) {
1129 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1130 Fragments.Canonical, env.enclClass.sym.name,
1131 Fragments.CanonicalMustNotContainExplicitConstructorInvocation));
1132 }
1133 }
1134
1135 // also we want to check that no type variables have been defined
1136 if (!tree.typarams.isEmpty()) {
1137 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1138 Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalMustNotDeclareTypeVariables));
1139 }
1140
1141 /* and now we need to check that the constructor's arguments are exactly the same as those of the
1142 * record components
1143 */
1144 List<? extends RecordComponent> recordComponents = env.enclClass.sym.getRecordComponents();
1145 List<Type> recordFieldTypes = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.type);
1146 for (JCVariableDecl param: tree.params) {
1147 boolean paramIsVarArgs = (param.sym.flags_field & VARARGS) != 0;
1148 if (!types.isSameType(param.type, recordFieldTypes.head) ||
1190 }
1191 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1192 log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract(tree.sym, owner));
1193 } else {
1194 if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1195 if ((owner.flags() & INTERFACE) != 0) {
1196 log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1197 } else {
1198 log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1199 }
1200 } else if ((tree.mods.flags & NATIVE) != 0) {
1201 log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1202 }
1203 // Add an implicit super() call unless an explicit call to
1204 // super(...) or this(...) is given
1205 // or we are compiling class java.lang.Object.
1206 if (isConstructor && owner.type != syms.objectType) {
1207 if (!TreeInfo.hasAnyConstructorCall(tree)) {
1208 JCStatement supCall = make.at(tree.body.pos).Exec(make.Apply(List.nil(),
1209 make.Ident(names._super), make.Idents(List.nil())));
1210 tree.body.stats = tree.body.stats.prepend(supCall);
1211 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1212 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1213 TreeInfo.hasConstructorCall(tree, names._super)) {
1214 // enum constructors are not allowed to call super
1215 // directly, so make sure there aren't any super calls
1216 // in enum constructors, except in the compiler
1217 // generated one.
1218 log.error(tree.body.stats.head.pos(),
1219 Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1220 }
1221 if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1222 List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1223 List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1224 if (!initParamNames.equals(recordComponentNames)) {
1225 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1226 Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1227 }
1228 if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1229 log.error(tree,
1230 Errors.InvalidCanonicalConstructorInRecord(
1231 TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical,
1232 env.enclClass.sym.name,
1233 Fragments.ThrowsClauseNotAllowedForCanonicalConstructor(
1234 TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical)));
1235 }
1236 }
1237 }
1238
1239 // Attribute all type annotations in the body
1240 annotate.queueScanTreeAndTypeAnnotate(tree.body, localEnv, m);
1241 annotate.flush();
1242
1243 // Start of constructor prologue (if not in java.lang.Object constructor)
1244 localEnv.info.ctorPrologue = isConstructor && owner.type != syms.objectType;
1245
1246 // Attribute method body.
1247 attribStat(tree.body, localEnv);
1248 }
1249
1250 localEnv.info.scope.leave();
1251 result = tree.type = m.type;
1252 } finally {
1253 chk.setLint(prevLint);
1254 chk.setMethod(prevMethod);
1255 env.info.ctorPrologue = ctorProloguePrev;
1256 }
1257 }
1258
1259 public void visitVarDef(JCVariableDecl tree) {
1260 // Local variables have not been entered yet, so we need to do it now:
1261 if (env.info.scope.owner.kind == MTH || env.info.scope.owner.kind == VAR) {
1262 if (tree.sym != null) {
1263 // parameters have already been entered
1264 env.info.scope.enter(tree.sym);
1265 } else {
1266 if (tree.isImplicitlyTyped() && (tree.getModifiers().flags & PARAMETER) == 0 && tree.type == null) {
1267 if (tree.init == null) {
1268 //cannot use 'var' without initializer
1269 log.error(tree, Errors.CantInferLocalVarType(tree.name, Fragments.LocalMissingInit));
1270 tree.type = syms.errType;
1271 } else {
1272 Fragment msg = canInferLocalVarType(tree);
1273 if (msg != null) {
1274 //cannot use 'var' with initializer which require an explicit target
1275 //(e.g. lambda, method reference, array initializer).
1300 (tree.sym.flags() & PARAMETER) != 0;
1301 chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1302
1303 try {
1304 v.getConstValue(); // ensure compile-time constant initializer is evaluated
1305 chk.checkDeprecatedAnnotation(tree.pos(), v);
1306
1307 if (tree.init != null) {
1308 if ((v.flags_field & FINAL) == 0 ||
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 setupImplicitlyTypedVariable(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 chk.checkRequiresIdentity(tree, env.info.lint);
1337 }
1338 finally {
1339 chk.setLint(prevLint);
1340 }
1341 }
1342
1343 private void doQueueScanTreeAndTypeAnnotateForVarInit(JCVariableDecl tree, Env<AttrContext> env) {
1938 // where
1939 /** Return the selected enumeration constant symbol, or null. */
1940 private Symbol enumConstant(JCTree tree, Type enumType) {
1941 if (tree.hasTag(IDENT)) {
1942 JCIdent ident = (JCIdent)tree;
1943 Name name = ident.name;
1944 for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1945 if (sym.kind == VAR) {
1946 Symbol s = ident.sym = sym;
1947 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1948 ident.type = s.type;
1949 return ((s.flags_field & Flags.ENUM) == 0)
1950 ? null : s;
1951 }
1952 }
1953 }
1954 return null;
1955 }
1956
1957 public void visitSynchronized(JCSynchronized tree) {
1958 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1959 if (tree.lock.type != null && tree.lock.type.isValueBased()) {
1960 log.warning(tree.pos(), LintWarnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
1961 }
1962 attribStat(tree.body, env);
1963 result = null;
1964 }
1965
1966 public void visitTry(JCTry tree) {
1967 // Create a new local environment with a local
1968 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1969 try {
1970 boolean isTryWithResource = tree.resources.nonEmpty();
1971 // Create a nested environment for attributing the try block if needed
1972 Env<AttrContext> tryEnv = isTryWithResource ?
1973 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1974 localEnv;
1975 try {
1976 // Attribute resource declarations
1977 for (JCTree resource : tree.resources) {
1978 CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1979 @Override
2557
2558 // The types of the actual method arguments.
2559 List<Type> argtypes;
2560
2561 // The types of the actual method type arguments.
2562 List<Type> typeargtypes = null;
2563
2564 Name methName = TreeInfo.name(tree.meth);
2565
2566 boolean isConstructorCall =
2567 methName == names._this || methName == names._super;
2568
2569 ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2570 if (isConstructorCall) {
2571
2572 // Attribute arguments, yielding list of argument types.
2573 KindSelector kind = attribArgs(KindSelector.MTH, tree.args, localEnv, argtypesBuf);
2574 argtypes = argtypesBuf.toList();
2575 typeargtypes = attribTypes(tree.typeargs, localEnv);
2576
2577 // Done with this()/super() parameters. End of constructor prologue.
2578 env.info.ctorPrologue = false;
2579
2580 // Variable `site' points to the class in which the called
2581 // constructor is defined.
2582 Type site = env.enclClass.sym.type;
2583 if (methName == names._super) {
2584 if (site == syms.objectType) {
2585 log.error(tree.meth.pos(), Errors.NoSuperclass(site));
2586 site = types.createErrorType(syms.objectType);
2587 } else {
2588 site = types.supertype(site);
2589 }
2590 }
2591
2592 if (site.hasTag(CLASS)) {
2593 Type encl = site.getEnclosingType();
2594 while (encl != null && encl.hasTag(TYPEVAR))
2595 encl = encl.getUpperBound();
2596 if (encl.hasTag(CLASS)) {
2597 // we are calling a nested class
2598
3581 * a synthetic method symbol owner is created.
3582 */
3583 public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
3584 Env<AttrContext> lambdaEnv;
3585 Symbol owner = env.info.scope.owner;
3586 if (owner.kind == VAR && owner.owner.kind == TYP) {
3587 // If the lambda is nested in a field initializer, we need to create a fake init method.
3588 // Uniqueness of this symbol is not important (as e.g. annotations will be added on the
3589 // init symbol's owner).
3590 ClassSymbol enclClass = owner.enclClass();
3591 Name initName = owner.isStatic() ? names.clinit : names.init;
3592 MethodSymbol initSym = new MethodSymbol(BLOCK | (owner.isStatic() ? STATIC : 0) | SYNTHETIC | PRIVATE,
3593 initName, initBlockType, enclClass);
3594 initSym.params = List.nil();
3595 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(initSym)));
3596 } else {
3597 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
3598 }
3599 lambdaEnv.info.yieldResult = null;
3600 lambdaEnv.info.isLambda = true;
3601 return lambdaEnv;
3602 }
3603
3604 @Override
3605 public void visitReference(final JCMemberReference that) {
3606 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
3607 if (pt().hasTag(NONE) && (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
3608 //method reference only allowed in assignment or method invocation/cast context
3609 log.error(that.pos(), Errors.UnexpectedMref);
3610 }
3611 result = that.type = types.createErrorType(pt());
3612 return;
3613 }
3614 final Env<AttrContext> localEnv = env.dup(that);
3615 try {
3616 //attribute member reference qualifier - if this is a constructor
3617 //reference, the expected kind must be a type
3618 Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
3619
3620 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3981 }
3982 }
3983
3984 public void visitParens(JCParens tree) {
3985 Type owntype = attribTree(tree.expr, env, resultInfo);
3986 result = check(tree, owntype, pkind(), resultInfo);
3987 Symbol sym = TreeInfo.symbol(tree);
3988 if (sym != null && sym.kind.matches(KindSelector.TYP_PCK) && sym.kind != Kind.ERR)
3989 log.error(tree.pos(), Errors.IllegalParenthesizedExpression);
3990 }
3991
3992 public void visitAssign(JCAssign tree) {
3993 Type owntype = attribTree(tree.lhs, env.dup(tree), varAssignmentInfo);
3994 Type capturedType = capture(owntype);
3995 attribExpr(tree.rhs, env, owntype);
3996 result = check(tree, capturedType, KindSelector.VAL, resultInfo);
3997 }
3998
3999 public void visitAssignop(JCAssignOp tree) {
4000 // Attribute arguments.
4001 Type owntype = attribTree(tree.lhs, env, varAssignmentInfo);
4002 Type operand = attribExpr(tree.rhs, env);
4003 // Find operator.
4004 Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), owntype, operand);
4005 if (operator != operators.noOpSymbol &&
4006 !owntype.isErroneous() &&
4007 !operand.isErroneous()) {
4008 chk.checkDivZero(tree.rhs.pos(), operator, operand);
4009 chk.checkCastable(tree.rhs.pos(),
4010 operator.type.getReturnType(),
4011 owntype);
4012 switch (tree.getTag()) {
4013 case SL_ASG, SR_ASG, USR_ASG -> { } // we only use (at most) the lower 6 bits, so any integral type is OK
4014 default -> chk.checkLossOfPrecision(tree.rhs.pos(), operand, owntype);
4015 }
4016 chk.checkOutOfRangeShift(tree.rhs.pos(), operator, operand);
4017 }
4018 result = check(tree, owntype, KindSelector.VAL, resultInfo);
4019 }
4020
4021 public void visitUnary(JCUnary tree) {
4022 // Attribute arguments.
4023 Type argtype = (tree.getTag().isIncOrDecUnaryOp())
4024 ? attribTree(tree.arg, env, varAssignmentInfo)
4025 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
4026
4027 // Find operator.
4028 OperatorSymbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype);
4029 Type owntype = types.createErrorType(tree.type);
4030 if (operator != operators.noOpSymbol &&
4031 !argtype.isErroneous()) {
4032 owntype = (tree.getTag().isIncOrDecUnaryOp())
4033 ? tree.arg.type
4034 : operator.type.getReturnType();
4035 int opc = operator.opcode;
4036
4037 // If the argument is constant, fold it.
4038 if (argtype.constValue() != null) {
4039 Type ctype = cfolder.fold1(opc, argtype);
4040 if (ctype != null) {
4041 owntype = cfolder.coerce(ctype, owntype);
4042 }
4043 }
4044 }
4401 result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
4402 }
4403
4404 public void visitSelect(JCFieldAccess tree) {
4405 // Determine the expected kind of the qualifier expression.
4406 KindSelector skind = KindSelector.NIL;
4407 if (tree.name == names._this || tree.name == names._super ||
4408 tree.name == names._class)
4409 {
4410 skind = KindSelector.TYP;
4411 } else {
4412 if (pkind().contains(KindSelector.PCK))
4413 skind = KindSelector.of(skind, KindSelector.PCK);
4414 if (pkind().contains(KindSelector.TYP))
4415 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4416 if (pkind().contains(KindSelector.VAL_MTH))
4417 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4418 }
4419
4420 // Attribute the qualifier expression, and determine its symbol (if any).
4421 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4422 if (!pkind().contains(KindSelector.TYP_PCK))
4423 site = capture(site); // Capture field access
4424
4425 // don't allow T.class T[].class, etc
4426 if (skind == KindSelector.TYP) {
4427 Type elt = site;
4428 while (elt.hasTag(ARRAY))
4429 elt = ((ArrayType)elt).elemtype;
4430 if (elt.hasTag(TYPEVAR)) {
4431 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4432 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4433 tree.sym = tree.type.tsym;
4434 return ;
4435 }
4436 }
4437
4438 // If qualifier symbol is a type or `super', assert `selectSuper'
4439 // for the selection. This is relevant for determining whether
4440 // protected symbols are accessible.
4441 Symbol sitesym = TreeInfo.symbol(tree.selected);
4442 boolean selectSuperPrev = env.info.selectSuper;
4443 env.info.selectSuper =
4444 sitesym != null &&
4445 sitesym.name == names._super;
4446
4447 // Determine the symbol represented by the selection.
4448 env.info.pendingResolutionPhase = null;
4449 Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
4450 if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
4451 log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym));
4452 sym = syms.errSymbol;
4453 }
4454 if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
4455 site = capture(site);
4456 sym = selectSym(tree, sitesym, site, env, resultInfo);
4457 }
4458 boolean varArgs = env.info.lastResolveVarargs();
4459 tree.sym = sym;
4460
4461 if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
4462 site = types.skipTypeVars(site, true);
4463 }
4464
4465 // If that symbol is a variable, ...
4466 if (sym.kind == VAR) {
4467 VarSymbol v = (VarSymbol)sym;
4468
4469 // ..., evaluate its initializer, if it has one, and check for
4470 // illegal forward reference.
4471 checkInit(tree, env, v, true);
4472
4473 // If we are expecting a variable (as opposed to a value), check
4474 // that the variable is assignable in the current environment.
4475 if (KindSelector.ASG.subset(pkind()))
4476 checkAssignable(tree.pos(), v, tree.selected, env);
4518 // If we are selecting an instance member via a `super', ...
4519 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
4520
4521 // Check that super-qualified symbols are not abstract (JLS)
4522 rs.checkNonAbstract(tree.pos(), sym);
4523
4524 if (site.isRaw()) {
4525 // Determine argument types for site.
4526 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
4527 if (site1 != null) site = site1;
4528 }
4529 }
4530
4531 if (env.info.isSerializable) {
4532 chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4533 }
4534
4535 env.info.selectSuper = selectSuperPrev;
4536 result = checkId(tree, site, sym, env, resultInfo);
4537 }
4538 //where
4539 /** Determine symbol referenced by a Select expression,
4540 *
4541 * @param tree The select tree.
4542 * @param site The type of the selected expression,
4543 * @param env The current environment.
4544 * @param resultInfo The current result.
4545 */
4546 private Symbol selectSym(JCFieldAccess tree,
4547 Symbol location,
4548 Type site,
4549 Env<AttrContext> env,
4550 ResultInfo resultInfo) {
4551 DiagnosticPosition pos = tree.pos();
4552 Name name = tree.name;
4553 switch (site.getTag()) {
4554 case PACKAGE:
4555 return rs.accessBase(
4556 rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind),
4557 pos, location, site, name, true);
4558 case ARRAY:
4559 case CLASS:
4560 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
4561 return rs.resolveQualifiedMethod(
4562 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
4563 } else if (name == names._this || name == names._super) {
4564 return rs.resolveSelf(pos, env, site.tsym, tree);
4565 } else if (name == names._class) {
4566 // In this case, we have already made sure in
4567 // visitSelect that qualifier expression is a type.
4568 return syms.getClassField(site, types);
4569 } else {
4570 // We are seeing a plain identifier as selector.
4571 Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind);
4572 sym = rs.accessBase(sym, pos, location, site, name, true);
4573 return sym;
4574 }
4575 case WILDCARD:
4576 throw new AssertionError(tree);
4577 case TYPEVAR:
4578 // Normally, site.getUpperBound() shouldn't be null.
4579 // It should only happen during memberEnter/attribBase
4580 // when determining the supertype which *must* be
4581 // done before attributing the type variables. In
4582 // other words, we are seeing this illegal program:
4583 // class B<T> extends A<T.foo> {}
4584 Symbol sym = (site.getUpperBound() != null)
4585 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
4586 : null;
4587 if (sym == null) {
4588 log.error(pos, Errors.TypeVarCantBeDeref);
4589 return syms.errSymbol;
4590 } else {
4591 // JLS 4.9 specifies the members are derived by inheritance.
4592 // We skip inducing a whole class by filtering members that
4593 // can never be inherited:
4594 Symbol sym2;
4595 if (sym.isPrivate()) {
4596 // Private members
4597 sym2 = rs.new AccessError(env, site, sym);
4598 } else if (sym.owner.isInterface() && sym.kind == MTH && (sym.flags() & STATIC) != 0) {
4599 // Interface static methods
4600 sym2 = rs.new SymbolNotFoundError(ABSENT_MTH);
4601 } else {
4602 sym2 = sym;
4603 }
4604 rs.accessBase(sym2, pos, location, site, name, true);
4605 return sym;
5701 sym.kind != VAR ||
5702 sym.getConstValue() == null)
5703 log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
5704 }
5705 }
5706
5707 // Check for proper placement of super()/this() calls.
5708 chk.checkSuperInitCalls(tree);
5709
5710 // Check for cycles among non-initial constructors.
5711 chk.checkCyclicConstructors(tree);
5712
5713 // Check for cycles among annotation elements.
5714 chk.checkNonCyclicElements(tree);
5715
5716 // Check for proper use of serialVersionUID and other
5717 // serialization-related fields and methods
5718 if (env.info.lint.isEnabled(LintCategory.SERIAL)
5719 && rs.isSerializable(c.type)
5720 && !c.isAnonymous()) {
5721 chk.checkSerialStructure(tree, c);
5722 }
5723 // Correctly organize the positions of the type annotations
5724 typeAnnotations.organizeTypeAnnotationsBodies(tree);
5725
5726 // Check type annotations applicability rules
5727 validateTypeAnnotations(tree, false);
5728 }
5729 // where
5730 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
5731 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
5732 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
5733 if (types.isSameType(al.head.annotationType.type, t))
5734 return al.head.pos();
5735 }
5736
5737 return null;
5738 }
5739
5740 private Type capture(Type type) {
5741 return types.capture(type);
|
163 dependencies = Dependencies.instance(context);
164 argumentAttr = ArgumentAttr.instance(context);
165 matchBindingsComputer = MatchBindingsComputer.instance(context);
166 attrRecover = AttrRecover.instance(context);
167
168 Options options = Options.instance(context);
169
170 Source source = Source.instance(context);
171 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 captureMRefReturnType = Source.Feature.CAPTURE_MREF_RETURN_TYPE.allowedInSource(source);
180
181 statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
182 varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
183 varAssignmentOpInfo = new ResultInfo(KindSelector.of(KindSelector.VAL, KindSelector.ASG), Type.noType);
184 unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
185 methodAttrInfo = new MethodAttrInfo();
186 unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
187 unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
188 recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
189 initBlockType = new MethodType(List.nil(), syms.voidType, List.nil(), syms.methodClass);
190 allowValueClasses = preview.isEnabled() && Feature.VALUE_CLASSES.allowedInSource(source);
191 }
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 /** Are value classes allowed
210 */
211 private final boolean allowValueClasses;
212
213 /**
214 * Switch: warn about use of variable before declaration?
215 * RFE: 6425594
216 */
217 boolean useBeforeDeclarationWarning;
218
219 /**
220 * Switch: name of source level; used for error reporting.
221 */
222 String sourceName;
223
224 /** Check kind and type of given tree against protokind and prototype.
225 * If check succeeds, store type in tree and return it.
226 * If check fails, store errType in tree and return it.
227 * No checks are performed if the prototype is a method type.
228 * It is not necessary in this case since we know that kind and type
229 * are correct.
230 *
231 * @param tree The tree whose kind and type is checked
232 * @param found The computed type of the tree
301 * @param env The current environment.
302 */
303 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
304 if (v.name == names._this) {
305 log.error(pos, Errors.CantAssignValToThis);
306 return;
307 }
308 if ((v.flags() & FINAL) != 0 &&
309 ((v.flags() & HASINIT) != 0
310 ||
311 !((base == null ||
312 TreeInfo.isThisQualifier(base)) &&
313 isAssignableAsBlankFinal(v, env)))) {
314 if (v.isResourceVariable()) { //TWR resource
315 log.error(pos, Errors.TryResourceMayNotBeAssigned(v));
316 } else {
317 log.error(pos, Errors.CantAssignValToVar(Flags.toSource(v.flags() & (STATIC | FINAL)), v));
318 }
319 return;
320 }
321 }
322
323 /** Does tree represent a static reference to an identifier?
324 * It is assumed that tree is either a SELECT or an IDENT.
325 * We have to weed out selects from non-type names here.
326 * @param tree The candidate tree.
327 */
328 boolean isStaticReference(JCTree tree) {
329 if (tree.hasTag(SELECT)) {
330 Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
331 if (lsym == null || lsym.kind != TYP) {
332 return false;
333 }
334 }
335 return true;
336 }
337
338 /** Is this symbol a type?
339 */
340 static boolean isType(Symbol sym) {
600 }
601 @Override
602 public boolean compatible(Type found, Type req, Warner warn) {
603 return true;
604 }
605 @Override
606 public void report(DiagnosticPosition pos, JCDiagnostic details) {
607 boolean needsReport = pt == Type.recoveryType ||
608 (details.getDiagnosticPosition() != null &&
609 details.getDiagnosticPosition().getTree().hasTag(LAMBDA));
610 if (needsReport) {
611 chk.basicHandler.report(pos, details);
612 }
613 }
614 });
615 }
616 }
617
618 final ResultInfo statInfo;
619 final ResultInfo varAssignmentInfo;
620 final ResultInfo varAssignmentOpInfo;
621 final ResultInfo methodAttrInfo;
622 final ResultInfo unknownExprInfo;
623 final ResultInfo unknownTypeInfo;
624 final ResultInfo unknownTypeExprInfo;
625 final ResultInfo recoveryInfo;
626 final MethodType initBlockType;
627
628 Type pt() {
629 return resultInfo.pt;
630 }
631
632 KindSelector pkind() {
633 return resultInfo.pkind;
634 }
635
636 /* ************************************************************************
637 * Visitor methods
638 *************************************************************************/
639
640 /** Visitor argument: the current environment.
929 if (checkExtensible &&
930 ((t.tsym.flags() & FINAL) != 0)) {
931 log.error(pos,
932 Errors.CantInheritFromFinal(t.tsym));
933 }
934 chk.checkNonCyclic(pos, t);
935 return t;
936 }
937
938 Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
939 Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
940 id.type = env.info.scope.owner.enclClass().type;
941 id.sym = env.info.scope.owner.enclClass();
942 return id.type;
943 }
944
945 public void visitClassDef(JCClassDecl tree) {
946 Optional<ArgumentAttr.LocalCacheContext> localCacheContext =
947 Optional.ofNullable(env.info.attributionMode.isSpeculative ?
948 argumentAttr.withLocalCacheContext() : null);
949 EarlyConstructionContext earlyConstructionPrev = env.info.earlyContext;
950 try {
951 env.info.earlyContext = earlyConstructionPrev.nested(true);
952 // Local and anonymous classes have not been entered yet, so we need to
953 // do it now.
954 if (env.info.scope.owner.kind.matches(KindSelector.VAL_MTH)) {
955 enter.classEnter(tree, env);
956 } else {
957 // If this class declaration is part of a class level annotation,
958 // as in @MyAnno(new Object() {}) class MyClass {}, enter it in
959 // order to simplify later steps and allow for sensible error
960 // messages.
961 if (env.tree.hasTag(NEWCLASS) && TreeInfo.isInAnnotation(env, tree))
962 enter.classEnter(tree, env);
963 }
964
965 ClassSymbol c = tree.sym;
966 if (c == null) {
967 // exit in case something drastic went wrong during enter.
968 result = null;
969 } else {
970 // make sure class has been completed:
971 c.complete();
972
973 // If a class declaration appears in a constructor prologue,
974 // that means it's either a local class or an anonymous class.
975 // Either way, there is no immediately enclosing instance.
976 if (earlyConstructionPrev.ctorPrologue()) {
977 c.flags_field |= NOOUTERTHIS;
978 }
979 attribClass(tree.pos(), c);
980 result = tree.type = c.type;
981 }
982 } finally {
983 localCacheContext.ifPresent(LocalCacheContext::leave);
984 env.info.earlyContext = earlyConstructionPrev;
985 }
986 }
987
988 public void visitMethodDef(JCMethodDecl tree) {
989 MethodSymbol m = tree.sym;
990 boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
991
992 Lint lint = env.info.lint.augment(m);
993 Lint prevLint = chk.setLint(lint);
994 EarlyConstructionContext earlyConstructionPrev = env.info.earlyContext;
995 Assert.check(!earlyConstructionPrev.ctorPrologue());
996 MethodSymbol prevMethod = chk.setMethod(m);
997 try {
998 chk.checkDeprecatedAnnotation(tree.pos(), m);
999
1000
1001 // Create a new environment with local scope
1002 // for attributing the method.
1003 Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
1004 localEnv.info.lint = lint;
1005
1006 attribStats(tree.typarams, localEnv);
1007
1008 // If we override any other methods, check that we do so properly.
1009 // JLS ???
1010 if (m.isStatic()) {
1011 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
1012 } else {
1013 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
1014 }
1015 chk.checkOverride(env, tree, m);
1100 * - have an accessibility stricter than that of the record type
1101 * - explicitly invoke any other constructor
1102 */
1103 if ((tree.sym.flags_field & GENERATEDCONSTR) == 0) {
1104 if (Check.protection(m.flags()) > Check.protection(env.enclClass.sym.flags())) {
1105 log.error(tree,
1106 (env.enclClass.sym.flags() & AccessFlags) == 0 ?
1107 Errors.InvalidCanonicalConstructorInRecord(
1108 Fragments.Canonical,
1109 env.enclClass.sym.name,
1110 Fragments.CanonicalMustNotHaveStrongerAccess("package")
1111 ) :
1112 Errors.InvalidCanonicalConstructorInRecord(
1113 Fragments.Canonical,
1114 env.enclClass.sym.name,
1115 Fragments.CanonicalMustNotHaveStrongerAccess(asFlagSet(env.enclClass.sym.flags() & AccessFlags))
1116 )
1117 );
1118 }
1119
1120 if ((!allowValueClasses || TreeInfo.isCompactConstructor(tree)) &&
1121 TreeInfo.hasAnyConstructorCall(tree)) {
1122 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1123 Fragments.Canonical, env.enclClass.sym.name,
1124 Fragments.CanonicalMustNotContainExplicitConstructorInvocation));
1125 }
1126 }
1127
1128 // also we want to check that no type variables have been defined
1129 if (!tree.typarams.isEmpty()) {
1130 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1131 Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalMustNotDeclareTypeVariables));
1132 }
1133
1134 /* and now we need to check that the constructor's arguments are exactly the same as those of the
1135 * record components
1136 */
1137 List<? extends RecordComponent> recordComponents = env.enclClass.sym.getRecordComponents();
1138 List<Type> recordFieldTypes = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.type);
1139 for (JCVariableDecl param: tree.params) {
1140 boolean paramIsVarArgs = (param.sym.flags_field & VARARGS) != 0;
1141 if (!types.isSameType(param.type, recordFieldTypes.head) ||
1183 }
1184 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1185 log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract(tree.sym, owner));
1186 } else {
1187 if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1188 if ((owner.flags() & INTERFACE) != 0) {
1189 log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1190 } else {
1191 log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1192 }
1193 } else if ((tree.mods.flags & NATIVE) != 0) {
1194 log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1195 }
1196 // Add an implicit super() call unless an explicit call to
1197 // super(...) or this(...) is given
1198 // or we are compiling class java.lang.Object.
1199 if (isConstructor && owner.type != syms.objectType) {
1200 if (!TreeInfo.hasAnyConstructorCall(tree)) {
1201 JCStatement supCall = make.at(tree.body.pos).Exec(make.Apply(List.nil(),
1202 make.Ident(names._super), make.Idents(List.nil())));
1203 if (allowValueClasses && (owner.isValueClass() || owner.isRecord())) {
1204 tree.body.stats = tree.body.stats.append(supCall);
1205 } else {
1206 tree.body.stats = tree.body.stats.prepend(supCall);
1207 }
1208 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1209 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1210 TreeInfo.hasConstructorCall(tree, names._super)) {
1211 // enum constructors are not allowed to call super
1212 // directly, so make sure there aren't any super calls
1213 // in enum constructors, except in the compiler
1214 // generated one.
1215 log.error(tree.body.stats.head.pos(),
1216 Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1217 }
1218 if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1219 List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1220 List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1221 if (!initParamNames.equals(recordComponentNames)) {
1222 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1223 Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1224 }
1225 if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1226 log.error(tree,
1227 Errors.InvalidCanonicalConstructorInRecord(
1228 TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical,
1229 env.enclClass.sym.name,
1230 Fragments.ThrowsClauseNotAllowedForCanonicalConstructor(
1231 TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical)));
1232 }
1233 }
1234 }
1235
1236 // Attribute all type annotations in the body
1237 annotate.queueScanTreeAndTypeAnnotate(tree.body, localEnv, m);
1238 annotate.flush();
1239
1240 // Start of constructor prologue (if not in java.lang.Object constructor)
1241 if (isConstructor && owner.type != syms.objectType) {
1242 boolean hasThisConstructorCall = TreeInfo.hasConstructorCall(tree, names._this);
1243 localEnv.info.earlyContext = EarlyConstructionContext.of(owner,
1244 hasThisConstructorCall && allowValueClasses);
1245 }
1246
1247 // Attribute method body.
1248 attribStat(tree.body, localEnv);
1249 }
1250
1251 localEnv.info.scope.leave();
1252 result = tree.type = m.type;
1253 } finally {
1254 chk.setLint(prevLint);
1255 chk.setMethod(prevMethod);
1256 env.info.earlyContext = earlyConstructionPrev;
1257 }
1258 }
1259
1260 public void visitVarDef(JCVariableDecl tree) {
1261 // Local variables have not been entered yet, so we need to do it now:
1262 if (env.info.scope.owner.kind == MTH || env.info.scope.owner.kind == VAR) {
1263 if (tree.sym != null) {
1264 // parameters have already been entered
1265 env.info.scope.enter(tree.sym);
1266 } else {
1267 if (tree.isImplicitlyTyped() && (tree.getModifiers().flags & PARAMETER) == 0 && tree.type == null) {
1268 if (tree.init == null) {
1269 //cannot use 'var' without initializer
1270 log.error(tree, Errors.CantInferLocalVarType(tree.name, Fragments.LocalMissingInit));
1271 tree.type = syms.errType;
1272 } else {
1273 Fragment msg = canInferLocalVarType(tree);
1274 if (msg != null) {
1275 //cannot use 'var' with initializer which require an explicit target
1276 //(e.g. lambda, method reference, array initializer).
1301 (tree.sym.flags() & PARAMETER) != 0;
1302 chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1303
1304 try {
1305 v.getConstValue(); // ensure compile-time constant initializer is evaluated
1306 chk.checkDeprecatedAnnotation(tree.pos(), v);
1307
1308 if (tree.init != null) {
1309 if ((v.flags_field & FINAL) == 0 ||
1310 !memberEnter.needsLazyConstValue(tree.init)) {
1311 // Not a compile-time constant
1312 // Attribute initializer in a new environment
1313 // with the declared variable as owner.
1314 // Check that initializer conforms to variable's declared type.
1315 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1316 initEnv.info.lint = lint;
1317 // In order to catch self-references, we set the variable's
1318 // declaration position to maximal possible value, effectively
1319 // marking the variable as undefined.
1320 initEnv.info.enclVar = v;
1321 EarlyConstructionContext previousEarlyConstruction = initEnv.info.earlyContext;
1322 try {
1323 if (v.isStrictInstance() && allowValueClasses) {
1324 // instance strict field init occur in early construction context
1325 initEnv.info.earlyContext = EarlyConstructionContext.of((ClassSymbol)v.owner, false);
1326 }
1327 attribExpr(tree.init, initEnv, v.type);
1328 if (tree.isImplicitlyTyped()) {
1329 //fixup local variable type
1330 v.type = chk.checkLocalVarType(tree, tree.init.type, tree.name);
1331 }
1332 } finally {
1333 initEnv.info.earlyContext = previousEarlyConstruction;
1334 }
1335 }
1336 if (tree.isImplicitlyTyped()) {
1337 setupImplicitlyTypedVariable(tree, v.type);
1338 }
1339 }
1340 result = tree.type = v.type;
1341 if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1342 if (isNonArgsMethodInObject(v.name)) {
1343 log.error(tree, Errors.IllegalRecordComponentName(v));
1344 }
1345 }
1346 chk.checkRequiresIdentity(tree, env.info.lint);
1347 }
1348 finally {
1349 chk.setLint(prevLint);
1350 }
1351 }
1352
1353 private void doQueueScanTreeAndTypeAnnotateForVarInit(JCVariableDecl tree, Env<AttrContext> env) {
1948 // where
1949 /** Return the selected enumeration constant symbol, or null. */
1950 private Symbol enumConstant(JCTree tree, Type enumType) {
1951 if (tree.hasTag(IDENT)) {
1952 JCIdent ident = (JCIdent)tree;
1953 Name name = ident.name;
1954 for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1955 if (sym.kind == VAR) {
1956 Symbol s = ident.sym = sym;
1957 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1958 ident.type = s.type;
1959 return ((s.flags_field & Flags.ENUM) == 0)
1960 ? null : s;
1961 }
1962 }
1963 }
1964 return null;
1965 }
1966
1967 public void visitSynchronized(JCSynchronized tree) {
1968 boolean identityType = chk.checkIdentityType(tree.pos(), attribExpr(tree.lock, env));
1969 if (identityType && tree.lock.type != null && tree.lock.type.isValueBased()) {
1970 log.warning(tree.pos(), LintWarnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
1971 }
1972 attribStat(tree.body, env);
1973 result = null;
1974 }
1975
1976 public void visitTry(JCTry tree) {
1977 // Create a new local environment with a local
1978 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1979 try {
1980 boolean isTryWithResource = tree.resources.nonEmpty();
1981 // Create a nested environment for attributing the try block if needed
1982 Env<AttrContext> tryEnv = isTryWithResource ?
1983 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1984 localEnv;
1985 try {
1986 // Attribute resource declarations
1987 for (JCTree resource : tree.resources) {
1988 CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1989 @Override
2567
2568 // The types of the actual method arguments.
2569 List<Type> argtypes;
2570
2571 // The types of the actual method type arguments.
2572 List<Type> typeargtypes = null;
2573
2574 Name methName = TreeInfo.name(tree.meth);
2575
2576 boolean isConstructorCall =
2577 methName == names._this || methName == names._super;
2578
2579 ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2580 if (isConstructorCall) {
2581
2582 // Attribute arguments, yielding list of argument types.
2583 KindSelector kind = attribArgs(KindSelector.MTH, tree.args, localEnv, argtypesBuf);
2584 argtypes = argtypesBuf.toList();
2585 typeargtypes = attribTypes(tree.typeargs, localEnv);
2586
2587 // End of constructor prologue. Done with this()/super() parameters.
2588 env.info.earlyContext = EarlyConstructionContext.NONE;
2589
2590 // Variable `site' points to the class in which the called
2591 // constructor is defined.
2592 Type site = env.enclClass.sym.type;
2593 if (methName == names._super) {
2594 if (site == syms.objectType) {
2595 log.error(tree.meth.pos(), Errors.NoSuperclass(site));
2596 site = types.createErrorType(syms.objectType);
2597 } else {
2598 site = types.supertype(site);
2599 }
2600 }
2601
2602 if (site.hasTag(CLASS)) {
2603 Type encl = site.getEnclosingType();
2604 while (encl != null && encl.hasTag(TYPEVAR))
2605 encl = encl.getUpperBound();
2606 if (encl.hasTag(CLASS)) {
2607 // we are calling a nested class
2608
3591 * a synthetic method symbol owner is created.
3592 */
3593 public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
3594 Env<AttrContext> lambdaEnv;
3595 Symbol owner = env.info.scope.owner;
3596 if (owner.kind == VAR && owner.owner.kind == TYP) {
3597 // If the lambda is nested in a field initializer, we need to create a fake init method.
3598 // Uniqueness of this symbol is not important (as e.g. annotations will be added on the
3599 // init symbol's owner).
3600 ClassSymbol enclClass = owner.enclClass();
3601 Name initName = owner.isStatic() ? names.clinit : names.init;
3602 MethodSymbol initSym = new MethodSymbol(BLOCK | (owner.isStatic() ? STATIC : 0) | SYNTHETIC | PRIVATE,
3603 initName, initBlockType, enclClass);
3604 initSym.params = List.nil();
3605 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(initSym)));
3606 } else {
3607 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
3608 }
3609 lambdaEnv.info.yieldResult = null;
3610 lambdaEnv.info.isLambda = true;
3611 lambdaEnv.info.earlyContext = lambdaEnv.info.earlyContext.nested(false);
3612 return lambdaEnv;
3613 }
3614
3615 @Override
3616 public void visitReference(final JCMemberReference that) {
3617 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
3618 if (pt().hasTag(NONE) && (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
3619 //method reference only allowed in assignment or method invocation/cast context
3620 log.error(that.pos(), Errors.UnexpectedMref);
3621 }
3622 result = that.type = types.createErrorType(pt());
3623 return;
3624 }
3625 final Env<AttrContext> localEnv = env.dup(that);
3626 try {
3627 //attribute member reference qualifier - if this is a constructor
3628 //reference, the expected kind must be a type
3629 Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
3630
3631 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3992 }
3993 }
3994
3995 public void visitParens(JCParens tree) {
3996 Type owntype = attribTree(tree.expr, env, resultInfo);
3997 result = check(tree, owntype, pkind(), resultInfo);
3998 Symbol sym = TreeInfo.symbol(tree);
3999 if (sym != null && sym.kind.matches(KindSelector.TYP_PCK) && sym.kind != Kind.ERR)
4000 log.error(tree.pos(), Errors.IllegalParenthesizedExpression);
4001 }
4002
4003 public void visitAssign(JCAssign tree) {
4004 Type owntype = attribTree(tree.lhs, env.dup(tree), varAssignmentInfo);
4005 Type capturedType = capture(owntype);
4006 attribExpr(tree.rhs, env, owntype);
4007 result = check(tree, capturedType, KindSelector.VAL, resultInfo);
4008 }
4009
4010 public void visitAssignop(JCAssignOp tree) {
4011 // Attribute arguments.
4012 Type owntype = attribTree(tree.lhs, env, varAssignmentOpInfo);
4013 Type operand = attribExpr(tree.rhs, env);
4014 // Find operator.
4015 Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), owntype, operand);
4016 if (operator != operators.noOpSymbol &&
4017 !owntype.isErroneous() &&
4018 !operand.isErroneous()) {
4019 chk.checkDivZero(tree.rhs.pos(), operator, operand);
4020 chk.checkCastable(tree.rhs.pos(),
4021 operator.type.getReturnType(),
4022 owntype);
4023 switch (tree.getTag()) {
4024 case SL_ASG, SR_ASG, USR_ASG -> { } // we only use (at most) the lower 6 bits, so any integral type is OK
4025 default -> chk.checkLossOfPrecision(tree.rhs.pos(), operand, owntype);
4026 }
4027 chk.checkOutOfRangeShift(tree.rhs.pos(), operator, operand);
4028 }
4029 result = check(tree, owntype, KindSelector.VAL, resultInfo);
4030 }
4031
4032 public void visitUnary(JCUnary tree) {
4033 // Attribute arguments.
4034 Type argtype = (tree.getTag().isIncOrDecUnaryOp())
4035 ? attribTree(tree.arg, env, varAssignmentOpInfo)
4036 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
4037
4038 // Find operator.
4039 OperatorSymbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype);
4040 Type owntype = types.createErrorType(tree.type);
4041 if (operator != operators.noOpSymbol &&
4042 !argtype.isErroneous()) {
4043 owntype = (tree.getTag().isIncOrDecUnaryOp())
4044 ? tree.arg.type
4045 : operator.type.getReturnType();
4046 int opc = operator.opcode;
4047
4048 // If the argument is constant, fold it.
4049 if (argtype.constValue() != null) {
4050 Type ctype = cfolder.fold1(opc, argtype);
4051 if (ctype != null) {
4052 owntype = cfolder.coerce(ctype, owntype);
4053 }
4054 }
4055 }
4412 result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
4413 }
4414
4415 public void visitSelect(JCFieldAccess tree) {
4416 // Determine the expected kind of the qualifier expression.
4417 KindSelector skind = KindSelector.NIL;
4418 if (tree.name == names._this || tree.name == names._super ||
4419 tree.name == names._class)
4420 {
4421 skind = KindSelector.TYP;
4422 } else {
4423 if (pkind().contains(KindSelector.PCK))
4424 skind = KindSelector.of(skind, KindSelector.PCK);
4425 if (pkind().contains(KindSelector.TYP))
4426 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4427 if (pkind().contains(KindSelector.VAL_MTH))
4428 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4429 }
4430
4431 // Attribute the qualifier expression, and determine its symbol (if any).
4432 Type site;
4433 EarlyConstructionContext earlyConstructionPrev = env.info.earlyContext;
4434 JCTree earlyFieldQualifier = earlyFieldQualifier(tree);
4435 try {
4436 if (earlyFieldQualifier != null) {
4437 // if we're seeing a likely field access, and qualifier is this/super,
4438 // pretend we're not in early construction context. This allows Resolve
4439 // to skip premature checks against this/super
4440 env.info.earlyContext = EarlyConstructionContext.NONE;
4441 }
4442 site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4443 } finally {
4444 env.info.earlyContext = earlyConstructionPrev;
4445 }
4446 Assert.check(site == tree.selected.type);
4447 if (!pkind().contains(KindSelector.TYP_PCK))
4448 site = capture(site); // Capture field access
4449
4450 // don't allow T.class T[].class, etc
4451 if (skind == KindSelector.TYP) {
4452 Type elt = site;
4453 while (elt.hasTag(ARRAY))
4454 elt = ((ArrayType)elt).elemtype;
4455 if (elt.hasTag(TYPEVAR)) {
4456 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4457 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4458 tree.sym = tree.type.tsym;
4459 return ;
4460 }
4461 }
4462
4463 // If qualifier symbol is a type or `super', assert `selectSuper'
4464 // for the selection. This is relevant for determining whether
4465 // protected symbols are accessible.
4466 Symbol sitesym = TreeInfo.symbol(tree.selected);
4467 boolean selectSuperPrev = env.info.selectSuper;
4468 env.info.selectSuper =
4469 sitesym != null &&
4470 sitesym.name == names._super;
4471
4472 // Determine the symbol represented by the selection.
4473 env.info.pendingResolutionPhase = null;
4474 Symbol sym;
4475 sym = selectSym(tree, sitesym, site, env, resultInfo, earlyFieldQualifier);
4476 if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
4477 log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym));
4478 sym = syms.errSymbol;
4479 }
4480 if (sym.exists() && !isType(sym) &&
4481 tree.name != names._this && tree.name != names._super &&
4482 pkind().contains(KindSelector.TYP_PCK)) {
4483 site = capture(site);
4484 sym = selectSym(tree, sitesym, site, env, resultInfo, earlyFieldQualifier);
4485 }
4486 boolean varArgs = env.info.lastResolveVarargs();
4487 tree.sym = sym;
4488
4489 if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
4490 site = types.skipTypeVars(site, true);
4491 }
4492
4493 // If that symbol is a variable, ...
4494 if (sym.kind == VAR) {
4495 VarSymbol v = (VarSymbol)sym;
4496
4497 // ..., evaluate its initializer, if it has one, and check for
4498 // illegal forward reference.
4499 checkInit(tree, env, v, true);
4500
4501 // If we are expecting a variable (as opposed to a value), check
4502 // that the variable is assignable in the current environment.
4503 if (KindSelector.ASG.subset(pkind()))
4504 checkAssignable(tree.pos(), v, tree.selected, env);
4546 // If we are selecting an instance member via a `super', ...
4547 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
4548
4549 // Check that super-qualified symbols are not abstract (JLS)
4550 rs.checkNonAbstract(tree.pos(), sym);
4551
4552 if (site.isRaw()) {
4553 // Determine argument types for site.
4554 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
4555 if (site1 != null) site = site1;
4556 }
4557 }
4558
4559 if (env.info.isSerializable) {
4560 chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4561 }
4562
4563 env.info.selectSuper = selectSuperPrev;
4564 result = checkId(tree, site, sym, env, resultInfo);
4565 }
4566
4567 private JCTree earlyFieldQualifier(JCFieldAccess tree) {
4568 boolean methodSelect = resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL);
4569 if (!methodSelect &&
4570 (TreeInfo.isThisOrSelectorDotThis(tree.selected) ||
4571 TreeInfo.isSuperOrSelectorDotSuper(tree.selected))) {
4572 return tree.selected;
4573 }
4574 return null;
4575 }
4576
4577 //where
4578 /** Determine symbol referenced by a Select expression,
4579 *
4580 * @param tree The select tree.
4581 * @param site The type of the selected expression,
4582 * @param env The current environment.
4583 * @param resultInfo The current result.
4584 */
4585 private Symbol selectSym(JCFieldAccess tree,
4586 Symbol location,
4587 Type site,
4588 Env<AttrContext> env,
4589 ResultInfo resultInfo,
4590 JCTree earlyFieldQualifier) {
4591 DiagnosticPosition pos = tree.pos();
4592 Name name = tree.name;
4593 switch (site.getTag()) {
4594 case PACKAGE:
4595 return rs.accessBase(
4596 rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind),
4597 pos, location, site, name, true);
4598 case ARRAY:
4599 case CLASS:
4600 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
4601 return rs.resolveQualifiedMethod(
4602 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
4603 } else if (name == names._this || name == names._super) {
4604 Symbol sym = rs.resolveSelf(pos, env, site.tsym, tree);
4605 return rs.accessBase(sym, pos, env.enclClass.sym.type, name, true);
4606 } else if (name == names._class) {
4607 // In this case, we have already made sure in
4608 // visitSelect that qualifier expression is a type.
4609 return syms.getClassField(site, types);
4610 } else {
4611 // We are seeing a plain identifier as selector.
4612 Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind, earlyFieldQualifier);
4613 sym = rs.accessBase(sym, pos, location, site, name, true);
4614 return sym;
4615 }
4616 case WILDCARD:
4617 throw new AssertionError(tree);
4618 case TYPEVAR:
4619 // Normally, site.getUpperBound() shouldn't be null.
4620 // It should only happen during memberEnter/attribBase
4621 // when determining the supertype which *must* be
4622 // done before attributing the type variables. In
4623 // other words, we are seeing this illegal program:
4624 // class B<T> extends A<T.foo> {}
4625 Symbol sym = (site.getUpperBound() != null)
4626 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo, earlyFieldQualifier)
4627 : null;
4628 if (sym == null) {
4629 log.error(pos, Errors.TypeVarCantBeDeref);
4630 return syms.errSymbol;
4631 } else {
4632 // JLS 4.9 specifies the members are derived by inheritance.
4633 // We skip inducing a whole class by filtering members that
4634 // can never be inherited:
4635 Symbol sym2;
4636 if (sym.isPrivate()) {
4637 // Private members
4638 sym2 = rs.new AccessError(env, site, sym);
4639 } else if (sym.owner.isInterface() && sym.kind == MTH && (sym.flags() & STATIC) != 0) {
4640 // Interface static methods
4641 sym2 = rs.new SymbolNotFoundError(ABSENT_MTH);
4642 } else {
4643 sym2 = sym;
4644 }
4645 rs.accessBase(sym2, pos, location, site, name, true);
4646 return sym;
5742 sym.kind != VAR ||
5743 sym.getConstValue() == null)
5744 log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
5745 }
5746 }
5747
5748 // Check for proper placement of super()/this() calls.
5749 chk.checkSuperInitCalls(tree);
5750
5751 // Check for cycles among non-initial constructors.
5752 chk.checkCyclicConstructors(tree);
5753
5754 // Check for cycles among annotation elements.
5755 chk.checkNonCyclicElements(tree);
5756
5757 // Check for proper use of serialVersionUID and other
5758 // serialization-related fields and methods
5759 if (env.info.lint.isEnabled(LintCategory.SERIAL)
5760 && rs.isSerializable(c.type)
5761 && !c.isAnonymous()) {
5762 chk.checkSerialStructure(env, tree, c);
5763 }
5764 // Correctly organize the positions of the type annotations
5765 typeAnnotations.organizeTypeAnnotationsBodies(tree);
5766
5767 // Check type annotations applicability rules
5768 validateTypeAnnotations(tree, false);
5769 }
5770 // where
5771 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
5772 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
5773 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
5774 if (types.isSameType(al.head.annotationType.type, t))
5775 return al.head.pos();
5776 }
5777
5778 return null;
5779 }
5780
5781 private Type capture(Type type) {
5782 return types.capture(type);
|