107 final Analyzer analyzer;
108 final DeferredAttr deferredAttr;
109 final Check chk;
110 final Flow flow;
111 final MemberEnter memberEnter;
112 final TypeEnter typeEnter;
113 final TreeMaker make;
114 final ConstFold cfolder;
115 final Enter enter;
116 final Target target;
117 final Types types;
118 final Preview preview;
119 final JCDiagnostic.Factory diags;
120 final TypeAnnotations typeAnnotations;
121 final TypeEnvs typeEnvs;
122 final Dependencies dependencies;
123 final Annotate annotate;
124 final ArgumentAttr argumentAttr;
125 final MatchBindingsComputer matchBindingsComputer;
126 final AttrRecover attrRecover;
127
128 public static Attr instance(Context context) {
129 Attr instance = context.get(attrKey);
130 if (instance == null)
131 instance = new Attr(context);
132 return instance;
133 }
134
135 @SuppressWarnings("this-escape")
136 protected Attr(Context context) {
137 context.put(attrKey, this);
138
139 names = Names.instance(context);
140 log = Log.instance(context);
141 lintMapper = LintMapper.instance(context);
142 syms = Symtab.instance(context);
143 rs = Resolve.instance(context);
144 operators = Operators.instance(context);
145 chk = Check.instance(context);
146 flow = Flow.instance(context);
147 memberEnter = MemberEnter.instance(context);
148 typeEnter = TypeEnter.instance(context);
149 make = TreeMaker.instance(context);
150 enter = Enter.instance(context);
151 infer = Infer.instance(context);
152 analyzer = Analyzer.instance(context);
153 deferredAttr = DeferredAttr.instance(context);
154 cfolder = ConstFold.instance(context);
155 target = Target.instance(context);
156 types = Types.instance(context);
157 preview = Preview.instance(context);
158 diags = JCDiagnostic.Factory.instance(context);
159 annotate = Annotate.instance(context);
160 typeAnnotations = TypeAnnotations.instance(context);
161 typeEnvs = TypeEnvs.instance(context);
162 dependencies = Dependencies.instance(context);
163 argumentAttr = ArgumentAttr.instance(context);
164 matchBindingsComputer = MatchBindingsComputer.instance(context);
165 attrRecover = AttrRecover.instance(context);
166
167 Options options = Options.instance(context);
168
169 Source source = Source.instance(context);
170 allowReifiableTypesInInstanceof = Feature.REIFIABLE_TYPES_INSTANCEOF.allowedInSource(source);
171 allowRecords = Feature.RECORDS.allowedInSource(source);
172 allowPatternSwitch = (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH)) &&
173 Feature.PATTERN_SWITCH.allowedInSource(source);
174 allowUnconditionalPatternsInstanceOf =
175 Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.allowedInSource(source);
176 sourceName = source.name;
177 useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
178
179 statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
180 varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
181 unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
182 methodAttrInfo = new MethodAttrInfo();
183 unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
184 unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
185 recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
186 initBlockType = new MethodType(List.nil(), syms.voidType, List.nil(), syms.methodClass);
187 }
188
189 /** Switch: reifiable types in instanceof enabled?
190 */
191 boolean allowReifiableTypesInInstanceof;
192
193 /** Are records allowed
194 */
195 private final boolean allowRecords;
196
197 /** Are patterns in switch allowed
198 */
199 private final boolean allowPatternSwitch;
200
201 /** Are unconditional patterns in instanceof allowed
202 */
203 private final boolean allowUnconditionalPatternsInstanceOf;
204
205 /**
206 * Switch: warn about use of variable before declaration?
207 * RFE: 6425594
208 */
209 boolean useBeforeDeclarationWarning;
210
211 /**
212 * Switch: name of source level; used for error reporting.
213 */
214 String sourceName;
215
216 /** Check kind and type of given tree against protokind and prototype.
217 * If check succeeds, store type in tree and return it.
218 * If check fails, store errType in tree and return it.
219 * No checks are performed if the prototype is a method type.
220 * It is not necessary in this case since we know that kind and type
221 * are correct.
222 *
223 * @param tree The tree whose kind and type is checked
224 * @param found The computed type of the tree
278 owner.kind == VAR || // i.e. we are in a variable initializer
279 (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block
280 &&
281 v.owner == owner.owner
282 &&
283 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
284 boolean insideCompactConstructor = env.enclMethod != null && TreeInfo.isCompactConstructor(env.enclMethod);
285 return isAssignable & !insideCompactConstructor;
286 }
287
288 /** Check that variable can be assigned to.
289 * @param pos The current source code position.
290 * @param v The assigned variable
291 * @param base If the variable is referred to in a Select, the part
292 * to the left of the `.', null otherwise.
293 * @param env The current environment.
294 */
295 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
296 if (v.name == names._this) {
297 log.error(pos, Errors.CantAssignValToThis);
298 return;
299 }
300 if ((v.flags() & FINAL) != 0 &&
301 ((v.flags() & HASINIT) != 0
302 ||
303 !((base == null ||
304 TreeInfo.isThisQualifier(base)) &&
305 isAssignableAsBlankFinal(v, env)))) {
306 if (v.isResourceVariable()) { //TWR resource
307 log.error(pos, Errors.TryResourceMayNotBeAssigned(v));
308 } else {
309 log.error(pos, Errors.CantAssignValToVar(Flags.toSource(v.flags() & (STATIC | FINAL)), v));
310 }
311 return;
312 }
313
314 // Check instance field assignments that appear in constructor prologues
315 if (rs.isEarlyReference(env, base, v)) {
316
317 // Field may not be inherited from a superclass
318 if (v.owner != env.enclClass.sym) {
319 log.error(pos, Errors.CantRefBeforeCtorCalled(v));
320 return;
321 }
322
323 // Field may not have an initializer
324 if ((v.flags() & HASINIT) != 0) {
325 log.error(pos, Errors.CantAssignInitializedBeforeCtorCalled(v));
326 return;
327 }
328 }
329 }
330
331 /** Does tree represent a static reference to an identifier?
332 * It is assumed that tree is either a SELECT or an IDENT.
333 * We have to weed out selects from non-type names here.
334 * @param tree The candidate tree.
335 */
336 boolean isStaticReference(JCTree tree) {
337 if (tree.hasTag(SELECT)) {
338 Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
339 if (lsym == null || lsym.kind != TYP) {
340 return false;
341 }
342 }
343 return true;
344 }
345
346 /** Is this symbol a type?
347 */
1102 * - have an accessibility stricter than that of the record type
1103 * - explicitly invoke any other constructor
1104 */
1105 if ((tree.sym.flags_field & GENERATEDCONSTR) == 0) {
1106 if (Check.protection(m.flags()) > Check.protection(env.enclClass.sym.flags())) {
1107 log.error(tree,
1108 (env.enclClass.sym.flags() & AccessFlags) == 0 ?
1109 Errors.InvalidCanonicalConstructorInRecord(
1110 Fragments.Canonical,
1111 env.enclClass.sym.name,
1112 Fragments.CanonicalMustNotHaveStrongerAccess("package")
1113 ) :
1114 Errors.InvalidCanonicalConstructorInRecord(
1115 Fragments.Canonical,
1116 env.enclClass.sym.name,
1117 Fragments.CanonicalMustNotHaveStrongerAccess(asFlagSet(env.enclClass.sym.flags() & AccessFlags))
1118 )
1119 );
1120 }
1121
1122 if (TreeInfo.hasAnyConstructorCall(tree)) {
1123 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1124 Fragments.Canonical, env.enclClass.sym.name,
1125 Fragments.CanonicalMustNotContainExplicitConstructorInvocation));
1126 }
1127 }
1128
1129 // also we want to check that no type variables have been defined
1130 if (!tree.typarams.isEmpty()) {
1131 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1132 Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalMustNotDeclareTypeVariables));
1133 }
1134
1135 /* and now we need to check that the constructor's arguments are exactly the same as those of the
1136 * record components
1137 */
1138 List<? extends RecordComponent> recordComponents = env.enclClass.sym.getRecordComponents();
1139 List<Type> recordFieldTypes = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.type);
1140 for (JCVariableDecl param: tree.params) {
1141 boolean paramIsVarArgs = (param.sym.flags_field & VARARGS) != 0;
1142 if (!types.isSameType(param.type, recordFieldTypes.head) ||
1180 if (tree.defaultValue != null) {
1181 if ((owner.flags() & ANNOTATION) == 0)
1182 log.error(tree.pos(),
1183 Errors.DefaultAllowedInIntfAnnotationMember);
1184 }
1185 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1186 log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract(tree.sym, owner));
1187 } else {
1188 if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1189 if ((owner.flags() & INTERFACE) != 0) {
1190 log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1191 } else {
1192 log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1193 }
1194 } else if ((tree.mods.flags & NATIVE) != 0) {
1195 log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1196 }
1197 // Add an implicit super() call unless an explicit call to
1198 // super(...) or this(...) is given
1199 // or we are compiling class java.lang.Object.
1200 if (isConstructor && owner.type != syms.objectType) {
1201 if (!TreeInfo.hasAnyConstructorCall(tree)) {
1202 JCStatement supCall = make.at(tree.body.pos).Exec(make.Apply(List.nil(),
1203 make.Ident(names._super), make.Idents(List.nil())));
1204 tree.body.stats = tree.body.stats.prepend(supCall);
1205 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1206 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1207 TreeInfo.hasConstructorCall(tree, names._super)) {
1208 // enum constructors are not allowed to call super
1209 // directly, so make sure there aren't any super calls
1210 // in enum constructors, except in the compiler
1211 // generated one.
1212 log.error(tree.body.stats.head.pos(),
1213 Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1214 }
1215 if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1216 List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1217 List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1218 if (!initParamNames.equals(recordComponentNames)) {
1219 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1220 Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1221 }
1222 if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1223 log.error(tree,
1224 Errors.InvalidCanonicalConstructorInRecord(
1225 TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical,
1226 env.enclClass.sym.name,
1227 Fragments.ThrowsClauseNotAllowedForCanonicalConstructor(
1228 TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical)));
1229 }
1230 }
1231 }
1232
1233 // Attribute all type annotations in the body
1234 annotate.queueScanTreeAndTypeAnnotate(tree.body, localEnv, m);
1235 annotate.flush();
1236
1237 // Start of constructor prologue (if not in java.lang.Object constructor)
1238 localEnv.info.ctorPrologue = isConstructor && owner.type != syms.objectType;
1239
1240 // Attribute method body.
1241 attribStat(tree.body, localEnv);
1242 }
1243
1244 localEnv.info.scope.leave();
1245 result = tree.type = m.type;
1246 } finally {
1247 chk.setLint(prevLint);
1248 chk.setMethod(prevMethod);
1249 env.info.ctorPrologue = ctorProloguePrev;
1250 }
1251 }
1252
1253 public void visitVarDef(JCVariableDecl tree) {
1254 // Local variables have not been entered yet, so we need to do it now:
1255 if (env.info.scope.owner.kind == MTH || env.info.scope.owner.kind == VAR) {
1256 if (tree.sym != null) {
1257 // parameters have already been entered
1258 env.info.scope.enter(tree.sym);
1259 } else {
1260 if (tree.isImplicitlyTyped() && (tree.getModifiers().flags & PARAMETER) == 0) {
1261 if (tree.init == null) {
1262 //cannot use 'var' without initializer
1263 log.error(tree, Errors.CantInferLocalVarType(tree.name, Fragments.LocalMissingInit));
1264 tree.vartype = make.at(tree.pos()).Erroneous();
1265 } else {
1266 Fragment msg = canInferLocalVarType(tree);
1267 if (msg != null) {
1268 //cannot use 'var' with initializer which require an explicit target
1269 //(e.g. lambda, method reference, array initializer).
1270 log.error(tree, Errors.CantInferLocalVarType(tree.name, msg));
1271 tree.vartype = make.at(tree.pos()).Erroneous();
1272 }
1293 (tree.sym.flags() & PARAMETER) != 0;
1294 chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1295
1296 try {
1297 v.getConstValue(); // ensure compile-time constant initializer is evaluated
1298 chk.checkDeprecatedAnnotation(tree.pos(), v);
1299
1300 if (tree.init != null) {
1301 if ((v.flags_field & FINAL) == 0 ||
1302 !memberEnter.needsLazyConstValue(tree.init)) {
1303 // Not a compile-time constant
1304 // Attribute initializer in a new environment
1305 // with the declared variable as owner.
1306 // Check that initializer conforms to variable's declared type.
1307 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1308 initEnv.info.lint = lint;
1309 // In order to catch self-references, we set the variable's
1310 // declaration position to maximal possible value, effectively
1311 // marking the variable as undefined.
1312 initEnv.info.enclVar = v;
1313 attribExpr(tree.init, initEnv, v.type);
1314 if (tree.isImplicitlyTyped()) {
1315 //fixup local variable type
1316 v.type = chk.checkLocalVarType(tree, tree.init.type, tree.name);
1317 }
1318 }
1319 if (tree.isImplicitlyTyped()) {
1320 setSyntheticVariableType(tree, v.type);
1321 }
1322 }
1323 result = tree.type = v.type;
1324 if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1325 if (isNonArgsMethodInObject(v.name)) {
1326 log.error(tree, Errors.IllegalRecordComponentName(v));
1327 }
1328 }
1329 chk.checkRequiresIdentity(tree, env.info.lint);
1330 }
1331 finally {
1332 chk.setLint(prevLint);
1333 }
1334 }
1335
1336 private void doQueueScanTreeAndTypeAnnotateForVarInit(JCVariableDecl tree, Env<AttrContext> env) {
1417 }
1418 }
1419 }
1420
1421 public void visitSkip(JCSkip tree) {
1422 result = null;
1423 }
1424
1425 public void visitBlock(JCBlock tree) {
1426 if (env.info.scope.owner.kind == TYP || env.info.scope.owner.kind == ERR) {
1427 // Block is a static or instance initializer;
1428 // let the owner of the environment be a freshly
1429 // created BLOCK-method.
1430 Symbol fakeOwner =
1431 new MethodSymbol(tree.flags | BLOCK |
1432 env.info.scope.owner.flags() & STRICTFP, names.empty, initBlockType,
1433 env.info.scope.owner);
1434 final Env<AttrContext> localEnv =
1435 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1436
1437 if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
1438 // Attribute all type annotations in the block
1439 annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner);
1440 annotate.flush();
1441 attribStats(tree.stats, localEnv);
1442
1443 {
1444 // Store init and clinit type annotations with the ClassSymbol
1445 // to allow output in Gen.normalizeDefs.
1446 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1447 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1448 if ((tree.flags & STATIC) != 0) {
1449 cs.appendClassInitTypeAttributes(tas);
1450 } else {
1451 cs.appendInitTypeAttributes(tas);
1452 }
1453 }
1454 } else {
1455 // Create a new local environment with a local scope.
1456 Env<AttrContext> localEnv =
1457 env.dup(tree, env.info.dup(env.info.scope.dup()));
1930 // where
1931 /** Return the selected enumeration constant symbol, or null. */
1932 private Symbol enumConstant(JCTree tree, Type enumType) {
1933 if (tree.hasTag(IDENT)) {
1934 JCIdent ident = (JCIdent)tree;
1935 Name name = ident.name;
1936 for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1937 if (sym.kind == VAR) {
1938 Symbol s = ident.sym = sym;
1939 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1940 ident.type = s.type;
1941 return ((s.flags_field & Flags.ENUM) == 0)
1942 ? null : s;
1943 }
1944 }
1945 }
1946 return null;
1947 }
1948
1949 public void visitSynchronized(JCSynchronized tree) {
1950 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1951 if (tree.lock.type != null && tree.lock.type.isValueBased()) {
1952 log.warning(tree.pos(), LintWarnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
1953 }
1954 attribStat(tree.body, env);
1955 result = null;
1956 }
1957
1958 public void visitTry(JCTry tree) {
1959 // Create a new local environment with a local
1960 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1961 try {
1962 boolean isTryWithResource = tree.resources.nonEmpty();
1963 // Create a nested environment for attributing the try block if needed
1964 Env<AttrContext> tryEnv = isTryWithResource ?
1965 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1966 localEnv;
1967 try {
1968 // Attribute resource declarations
1969 for (JCTree resource : tree.resources) {
1970 CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1971 @Override
4376 }
4377
4378 public void visitSelect(JCFieldAccess tree) {
4379 // Determine the expected kind of the qualifier expression.
4380 KindSelector skind = KindSelector.NIL;
4381 if (tree.name == names._this || tree.name == names._super ||
4382 tree.name == names._class)
4383 {
4384 skind = KindSelector.TYP;
4385 } else {
4386 if (pkind().contains(KindSelector.PCK))
4387 skind = KindSelector.of(skind, KindSelector.PCK);
4388 if (pkind().contains(KindSelector.TYP))
4389 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4390 if (pkind().contains(KindSelector.VAL_MTH))
4391 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4392 }
4393
4394 // Attribute the qualifier expression, and determine its symbol (if any).
4395 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4396 if (!pkind().contains(KindSelector.TYP_PCK))
4397 site = capture(site); // Capture field access
4398
4399 // don't allow T.class T[].class, etc
4400 if (skind == KindSelector.TYP) {
4401 Type elt = site;
4402 while (elt.hasTag(ARRAY))
4403 elt = ((ArrayType)elt).elemtype;
4404 if (elt.hasTag(TYPEVAR)) {
4405 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4406 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4407 tree.sym = tree.type.tsym;
4408 return ;
4409 }
4410 }
4411
4412 // If qualifier symbol is a type or `super', assert `selectSuper'
4413 // for the selection. This is relevant for determining whether
4414 // protected symbols are accessible.
4415 Symbol sitesym = TreeInfo.symbol(tree.selected);
5487 .filter(s -> s.tsym.isSealed())
5488 .map(s -> (ClassSymbol) s.tsym)
5489 .collect(List.collector());
5490
5491 if (sealedSupers.isEmpty()) {
5492 if ((c.flags_field & Flags.NON_SEALED) != 0) {
5493 boolean hasErrorSuper = false;
5494
5495 hasErrorSuper |= types.directSupertypes(c.type)
5496 .stream()
5497 .anyMatch(s -> s.tsym.kind == Kind.ERR);
5498
5499 ClassType ct = (ClassType) c.type;
5500
5501 hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5502
5503 if (!hasErrorSuper) {
5504 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5505 }
5506 }
5507 } else {
5508 if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5509 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5510 }
5511
5512 if (!c.type.isCompound()) {
5513 for (ClassSymbol supertypeSym : sealedSupers) {
5514 if (!supertypeSym.isPermittedSubclass(c.type.tsym)) {
5515 log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5516 }
5517 }
5518 if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5519 log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5520 c.isInterface() ?
5521 Errors.NonSealedOrSealedExpected :
5522 Errors.NonSealedSealedOrFinalExpected);
5523 }
5524 }
5525 }
5526
5527 env.info.returnResult = null;
5528 // java.lang.Enum may not be subclassed by a non-enum
5529 if (st.tsym == syms.enumSym &&
5530 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5531 log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5532
5533 // Enums may not be extended by source-level classes
5534 if (st.tsym != null &&
5535 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5536 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5537 log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5538 }
5539
5540 if (rs.isSerializable(c.type)) {
5541 env.info.isSerializable = true;
5542 }
5543
5544 attribClassBody(env, c);
5545
5546 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5547 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5548 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5549 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5550
5551 if (c.isImplicit()) {
5552 chk.checkHasMain(env.tree.pos(), c);
5553 }
5554 } finally {
5555 env.info.returnResult = prevReturnRes;
5556 log.useSource(prev);
5557 chk.setLint(prevLint);
5558 }
5559
5560 }
5561 }
5562
5563 public void visitImport(JCImport tree) {
5666 sym.kind != VAR ||
5667 sym.getConstValue() == null)
5668 log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
5669 }
5670 }
5671
5672 // Check for proper placement of super()/this() calls.
5673 chk.checkSuperInitCalls(tree);
5674
5675 // Check for cycles among non-initial constructors.
5676 chk.checkCyclicConstructors(tree);
5677
5678 // Check for cycles among annotation elements.
5679 chk.checkNonCyclicElements(tree);
5680
5681 // Check for proper use of serialVersionUID and other
5682 // serialization-related fields and methods
5683 if (env.info.lint.isEnabled(LintCategory.SERIAL)
5684 && rs.isSerializable(c.type)
5685 && !c.isAnonymous()) {
5686 chk.checkSerialStructure(tree, c);
5687 }
5688 // Correctly organize the positions of the type annotations
5689 typeAnnotations.organizeTypeAnnotationsBodies(tree);
5690
5691 // Check type annotations applicability rules
5692 validateTypeAnnotations(tree, false);
5693 }
5694 // where
5695 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
5696 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
5697 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
5698 if (types.isSameType(al.head.annotationType.type, t))
5699 return al.head.pos();
5700 }
5701
5702 return null;
5703 }
5704
5705 private Type capture(Type type) {
5706 return types.capture(type);
|
107 final Analyzer analyzer;
108 final DeferredAttr deferredAttr;
109 final Check chk;
110 final Flow flow;
111 final MemberEnter memberEnter;
112 final TypeEnter typeEnter;
113 final TreeMaker make;
114 final ConstFold cfolder;
115 final Enter enter;
116 final Target target;
117 final Types types;
118 final Preview preview;
119 final JCDiagnostic.Factory diags;
120 final TypeAnnotations typeAnnotations;
121 final TypeEnvs typeEnvs;
122 final Dependencies dependencies;
123 final Annotate annotate;
124 final ArgumentAttr argumentAttr;
125 final MatchBindingsComputer matchBindingsComputer;
126 final AttrRecover attrRecover;
127 final LocalProxyVarsGen localProxyVarsGen;
128
129 public static Attr instance(Context context) {
130 Attr instance = context.get(attrKey);
131 if (instance == null)
132 instance = new Attr(context);
133 return instance;
134 }
135
136 @SuppressWarnings("this-escape")
137 protected Attr(Context context) {
138 context.put(attrKey, this);
139
140 names = Names.instance(context);
141 log = Log.instance(context);
142 lintMapper = LintMapper.instance(context);
143 syms = Symtab.instance(context);
144 rs = Resolve.instance(context);
145 operators = Operators.instance(context);
146 chk = Check.instance(context);
147 flow = Flow.instance(context);
148 memberEnter = MemberEnter.instance(context);
149 typeEnter = TypeEnter.instance(context);
150 make = TreeMaker.instance(context);
151 enter = Enter.instance(context);
152 infer = Infer.instance(context);
153 analyzer = Analyzer.instance(context);
154 deferredAttr = DeferredAttr.instance(context);
155 cfolder = ConstFold.instance(context);
156 target = Target.instance(context);
157 types = Types.instance(context);
158 preview = Preview.instance(context);
159 diags = JCDiagnostic.Factory.instance(context);
160 annotate = Annotate.instance(context);
161 typeAnnotations = TypeAnnotations.instance(context);
162 typeEnvs = TypeEnvs.instance(context);
163 dependencies = Dependencies.instance(context);
164 argumentAttr = ArgumentAttr.instance(context);
165 matchBindingsComputer = MatchBindingsComputer.instance(context);
166 attrRecover = AttrRecover.instance(context);
167 localProxyVarsGen = LocalProxyVarsGen.instance(context);
168
169 Options options = Options.instance(context);
170
171 Source source = Source.instance(context);
172 allowReifiableTypesInInstanceof = Feature.REIFIABLE_TYPES_INSTANCEOF.allowedInSource(source);
173 allowRecords = Feature.RECORDS.allowedInSource(source);
174 allowPatternSwitch = (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH)) &&
175 Feature.PATTERN_SWITCH.allowedInSource(source);
176 allowUnconditionalPatternsInstanceOf =
177 Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.allowedInSource(source);
178 sourceName = source.name;
179 useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
180
181 statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
182 varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
183 unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
184 methodAttrInfo = new MethodAttrInfo();
185 unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
186 unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
187 recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
188 initBlockType = new MethodType(List.nil(), syms.voidType, List.nil(), syms.methodClass);
189 allowValueClasses = (!preview.isPreview(Feature.VALUE_CLASSES) || preview.isEnabled()) &&
190 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
286 owner.kind == VAR || // i.e. we are in a variable initializer
287 (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block
288 &&
289 v.owner == owner.owner
290 &&
291 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
292 boolean insideCompactConstructor = env.enclMethod != null && TreeInfo.isCompactConstructor(env.enclMethod);
293 return isAssignable & !insideCompactConstructor;
294 }
295
296 /** Check that variable can be assigned to.
297 * @param pos The current source code position.
298 * @param v The assigned variable
299 * @param base If the variable is referred to in a Select, the part
300 * to the left of the `.', null otherwise.
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 } else if ((v.flags() & FINAL) != 0 &&
307 ((v.flags() & HASINIT) != 0
308 ||
309 !((base == null ||
310 TreeInfo.isThisQualifier(base)) &&
311 isAssignableAsBlankFinal(v, env)))) {
312 if (v.isResourceVariable()) { //TWR resource
313 log.error(pos, Errors.TryResourceMayNotBeAssigned(v));
314 } else {
315 log.error(pos, Errors.CantAssignValToVar(Flags.toSource(v.flags() & (STATIC | FINAL)), v));
316 }
317 }
318 }
319
320 /** Does tree represent a static reference to an identifier?
321 * It is assumed that tree is either a SELECT or an IDENT.
322 * We have to weed out selects from non-type names here.
323 * @param tree The candidate tree.
324 */
325 boolean isStaticReference(JCTree tree) {
326 if (tree.hasTag(SELECT)) {
327 Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
328 if (lsym == null || lsym.kind != TYP) {
329 return false;
330 }
331 }
332 return true;
333 }
334
335 /** Is this symbol a type?
336 */
1091 * - have an accessibility stricter than that of the record type
1092 * - explicitly invoke any other constructor
1093 */
1094 if ((tree.sym.flags_field & GENERATEDCONSTR) == 0) {
1095 if (Check.protection(m.flags()) > Check.protection(env.enclClass.sym.flags())) {
1096 log.error(tree,
1097 (env.enclClass.sym.flags() & AccessFlags) == 0 ?
1098 Errors.InvalidCanonicalConstructorInRecord(
1099 Fragments.Canonical,
1100 env.enclClass.sym.name,
1101 Fragments.CanonicalMustNotHaveStrongerAccess("package")
1102 ) :
1103 Errors.InvalidCanonicalConstructorInRecord(
1104 Fragments.Canonical,
1105 env.enclClass.sym.name,
1106 Fragments.CanonicalMustNotHaveStrongerAccess(asFlagSet(env.enclClass.sym.flags() & AccessFlags))
1107 )
1108 );
1109 }
1110
1111 if (!allowValueClasses && TreeInfo.hasAnyConstructorCall(tree)) {
1112 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1113 Fragments.Canonical, env.enclClass.sym.name,
1114 Fragments.CanonicalMustNotContainExplicitConstructorInvocation));
1115 }
1116 }
1117
1118 // also we want to check that no type variables have been defined
1119 if (!tree.typarams.isEmpty()) {
1120 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1121 Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalMustNotDeclareTypeVariables));
1122 }
1123
1124 /* and now we need to check that the constructor's arguments are exactly the same as those of the
1125 * record components
1126 */
1127 List<? extends RecordComponent> recordComponents = env.enclClass.sym.getRecordComponents();
1128 List<Type> recordFieldTypes = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.type);
1129 for (JCVariableDecl param: tree.params) {
1130 boolean paramIsVarArgs = (param.sym.flags_field & VARARGS) != 0;
1131 if (!types.isSameType(param.type, recordFieldTypes.head) ||
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(tree.sym, owner));
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 boolean addedSuperInIdentityClass = false;
1190 if (isConstructor && owner.type != syms.objectType) {
1191 if (!TreeInfo.hasAnyConstructorCall(tree)) {
1192 JCStatement supCall = make.at(tree.body.pos).Exec(make.Apply(List.nil(),
1193 make.Ident(names._super), make.Idents(List.nil())));
1194 if (allowValueClasses && (owner.isValueClass() || owner.hasStrict() || ((owner.flags_field & RECORD) != 0))) {
1195 tree.body.stats = tree.body.stats.append(supCall);
1196 } else {
1197 tree.body.stats = tree.body.stats.prepend(supCall);
1198 addedSuperInIdentityClass = true;
1199 }
1200 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1201 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1202 TreeInfo.hasConstructorCall(tree, names._super)) {
1203 // enum constructors are not allowed to call super
1204 // directly, so make sure there aren't any super calls
1205 // in enum constructors, except in the compiler
1206 // generated one.
1207 log.error(tree.body.stats.head.pos(),
1208 Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1209 }
1210 if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1211 List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1212 List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1213 if (!initParamNames.equals(recordComponentNames)) {
1214 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1215 Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1216 }
1217 if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1218 log.error(tree,
1219 Errors.InvalidCanonicalConstructorInRecord(
1220 TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical,
1221 env.enclClass.sym.name,
1222 Fragments.ThrowsClauseNotAllowedForCanonicalConstructor(
1223 TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical)));
1224 }
1225 }
1226 }
1227
1228 // Attribute all type annotations in the body
1229 annotate.queueScanTreeAndTypeAnnotate(tree.body, localEnv, m);
1230 annotate.flush();
1231
1232 // Start of constructor prologue (if not in java.lang.Object constructor)
1233 localEnv.info.ctorPrologue = isConstructor && owner.type != syms.objectType;
1234
1235 // Attribute method body.
1236 attribStat(tree.body, localEnv);
1237 if (localEnv.info.ctorPrologue) {
1238 boolean thisInvocation = false;
1239 ListBuffer<JCTree> prologueCode = new ListBuffer<>();
1240 for (JCTree stat : tree.body.stats) {
1241 prologueCode.add(stat);
1242 /* gather all the stats in the body until a `super` or `this` constructor invocation is found,
1243 * including the constructor invocation, that way we don't need to worry in the visitor below if
1244 * if we are dealing or not with prologue code
1245 */
1246 if (stat instanceof JCExpressionStatement expStmt &&
1247 expStmt.expr instanceof JCMethodInvocation mi &&
1248 TreeInfo.isConstructorCall(mi)) {
1249 thisInvocation = TreeInfo.name(mi.meth) == names._this;
1250 if (!addedSuperInIdentityClass || !allowValueClasses) {
1251 break;
1252 }
1253 }
1254 }
1255 if (!prologueCode.isEmpty()) {
1256 CtorPrologueVisitor ctorPrologueVisitor = new CtorPrologueVisitor(localEnv,
1257 addedSuperInIdentityClass && allowValueClasses ?
1258 PrologueVisitorMode.WARNINGS_ONLY :
1259 thisInvocation ?
1260 PrologueVisitorMode.THIS_CONSTRUCTOR :
1261 PrologueVisitorMode.SUPER_CONSTRUCTOR);
1262 ctorPrologueVisitor.scan(prologueCode.toList());
1263 }
1264 }
1265 }
1266
1267 localEnv.info.scope.leave();
1268 result = tree.type = m.type;
1269 } finally {
1270 chk.setLint(prevLint);
1271 chk.setMethod(prevMethod);
1272 env.info.ctorPrologue = ctorProloguePrev;
1273 }
1274 }
1275
1276 enum PrologueVisitorMode {
1277 WARNINGS_ONLY,
1278 SUPER_CONSTRUCTOR,
1279 THIS_CONSTRUCTOR
1280 }
1281
1282 class CtorPrologueVisitor extends TreeScanner {
1283 Env<AttrContext> localEnv;
1284 PrologueVisitorMode mode;
1285
1286 CtorPrologueVisitor(Env<AttrContext> localEnv, PrologueVisitorMode mode) {
1287 this.localEnv = localEnv;
1288 currentClassSym = localEnv.enclClass.sym;
1289 this.mode = mode;
1290 }
1291
1292 boolean insideLambdaOrClassDef = false;
1293
1294 @Override
1295 public void visitLambda(JCLambda lambda) {
1296 boolean previousInsideLambdaOrClassDef = insideLambdaOrClassDef;
1297 try {
1298 insideLambdaOrClassDef = true;
1299 super.visitLambda(lambda);
1300 } finally {
1301 insideLambdaOrClassDef = previousInsideLambdaOrClassDef;
1302 }
1303 }
1304
1305 ClassSymbol currentClassSym;
1306
1307 @Override
1308 public void visitClassDef(JCClassDecl classDecl) {
1309 boolean previousInsideLambdaOrClassDef = insideLambdaOrClassDef;
1310 ClassSymbol previousClassSym = currentClassSym;
1311 try {
1312 insideLambdaOrClassDef = true;
1313 currentClassSym = classDecl.sym;
1314 super.visitClassDef(classDecl);
1315 } finally {
1316 insideLambdaOrClassDef = previousInsideLambdaOrClassDef;
1317 currentClassSym = previousClassSym;
1318 }
1319 }
1320
1321 private void reportPrologueError(JCTree tree, Symbol sym) {
1322 reportPrologueError(tree, sym, false);
1323 }
1324
1325 private void reportPrologueError(JCTree tree, Symbol sym, boolean hasInit) {
1326 preview.checkSourceLevel(tree, Feature.FLEXIBLE_CONSTRUCTORS);
1327 if (mode != PrologueVisitorMode.WARNINGS_ONLY) {
1328 if (hasInit) {
1329 log.error(tree, Errors.CantAssignInitializedBeforeCtorCalled(sym));
1330 } else {
1331 log.error(tree, Errors.CantRefBeforeCtorCalled(sym));
1332 }
1333 } else if (allowValueClasses) {
1334 // issue lint warning
1335 log.warning(tree, LintWarnings.WouldNotBeAllowedInPrologue(sym));
1336 }
1337 }
1338
1339 @Override
1340 public void visitApply(JCMethodInvocation tree) {
1341 super.visitApply(tree);
1342 Name name = TreeInfo.name(tree.meth);
1343 boolean isConstructorCall = name == names._this || name == names._super;
1344 Symbol msym = TreeInfo.symbolFor(tree.meth);
1345 // is this an instance method call or an illegal constructor invocation like: `this.super()`?
1346 if (msym != null && // for erroneous invocations msym can be null, ignore those
1347 (!isConstructorCall ||
1348 isConstructorCall && tree.meth.hasTag(SELECT))) {
1349 if (isEarlyReference(localEnv, tree.meth, msym))
1350 reportPrologueError(tree.meth, msym);
1351 }
1352 }
1353
1354 @Override
1355 public void visitIdent(JCIdent tree) {
1356 analyzeSymbol(tree);
1357 }
1358
1359 boolean isIndexed = false;
1360
1361 @Override
1362 public void visitIndexed(JCArrayAccess tree) {
1363 boolean previousIsIndexed = isIndexed;
1364 try {
1365 isIndexed = true;
1366 scan(tree.indexed);
1367 } finally {
1368 isIndexed = previousIsIndexed;
1369 }
1370 scan(tree.index);
1371 if (mode == PrologueVisitorMode.SUPER_CONSTRUCTOR && isInstanceField(tree.indexed)) {
1372 localProxyVarsGen.addFieldReadInPrologue(localEnv.enclMethod, TreeInfo.symbolFor(tree.indexed));
1373 }
1374 }
1375
1376 @Override
1377 public void visitSelect(JCFieldAccess tree) {
1378 SelectScanner ss = new SelectScanner();
1379 ss.scan(tree);
1380 if (ss.scanLater == null) {
1381 analyzeSymbol(tree);
1382 } else {
1383 boolean prevLhs = isInLHS;
1384 try {
1385 isInLHS = false;
1386 scan(ss.scanLater);
1387 } finally {
1388 isInLHS = prevLhs;
1389 }
1390 }
1391 if (mode == PrologueVisitorMode.SUPER_CONSTRUCTOR) {
1392 for (JCTree subtree : ss.selectorTrees) {
1393 if (isInstanceField(subtree)) {
1394 // we need to add a proxy for this one
1395 localProxyVarsGen.addFieldReadInPrologue(localEnv.enclMethod, TreeInfo.symbolFor(subtree));
1396 }
1397 }
1398 }
1399 }
1400
1401 boolean isInstanceField(JCTree tree) {
1402 Symbol sym = TreeInfo.symbolFor(tree);
1403 return (sym != null &&
1404 !sym.isStatic() &&
1405 sym.kind == VAR &&
1406 sym.owner.kind == TYP &&
1407 sym.name != names._this &&
1408 sym.name != names._super &&
1409 isEarlyReference(localEnv, tree, sym));
1410 }
1411
1412 @Override
1413 public void visitNewClass(JCNewClass tree) {
1414 super.visitNewClass(tree);
1415 checkNewClassAndMethRefs(tree, tree.type);
1416 }
1417
1418 @Override
1419 public void visitReference(JCMemberReference tree) {
1420 super.visitReference(tree);
1421 if (tree.getMode() == JCMemberReference.ReferenceMode.NEW) {
1422 checkNewClassAndMethRefs(tree, tree.expr.type);
1423 }
1424 }
1425
1426 void checkNewClassAndMethRefs(JCTree tree, Type t) {
1427 if (t.tsym.isEnclosedBy(localEnv.enclClass.sym) &&
1428 !t.tsym.isStatic() &&
1429 !t.tsym.isDirectlyOrIndirectlyLocal()) {
1430 reportPrologueError(tree, t.getEnclosingType().tsym);
1431 }
1432 }
1433
1434 /* if a symbol is in the LHS of an assignment expression we won't consider it as a candidate
1435 * for a proxy local variable later on
1436 */
1437 boolean isInLHS = false;
1438
1439 @Override
1440 public void visitAssign(JCAssign tree) {
1441 boolean previousIsInLHS = isInLHS;
1442 try {
1443 isInLHS = true;
1444 scan(tree.lhs);
1445 } finally {
1446 isInLHS = previousIsInLHS;
1447 }
1448 scan(tree.rhs);
1449 }
1450
1451 @Override
1452 public void visitMethodDef(JCMethodDecl tree) {
1453 // ignore any declarative part, mainly to avoid scanning receiver parameters
1454 scan(tree.body);
1455 }
1456
1457 void analyzeSymbol(JCTree tree) {
1458 Symbol sym = TreeInfo.symbolFor(tree);
1459 // make sure that there is a symbol and it is not static
1460 if (sym == null || sym.isStatic()) {
1461 return;
1462 }
1463 if (isInLHS && !insideLambdaOrClassDef) {
1464 // Check instance field assignments that appear in constructor prologues
1465 if (isEarlyReference(localEnv, tree, sym)) {
1466 // Field may not be inherited from a superclass
1467 if (sym.owner != localEnv.enclClass.sym) {
1468 reportPrologueError(tree, sym);
1469 return;
1470 }
1471 // Field may not have an initializer
1472 if ((sym.flags() & HASINIT) != 0) {
1473 if (!localEnv.enclClass.sym.isValueClass() || !sym.type.hasTag(ARRAY) || !isIndexed) {
1474 reportPrologueError(tree, sym, true);
1475 }
1476 return;
1477 }
1478 // cant reference an instance field before a this constructor
1479 if (allowValueClasses && mode == PrologueVisitorMode.THIS_CONSTRUCTOR) {
1480 reportPrologueError(tree, sym);
1481 return;
1482 }
1483 }
1484 return;
1485 }
1486 tree = TreeInfo.skipParens(tree);
1487 if (sym.kind == VAR && sym.owner.kind == TYP) {
1488 if (sym.name == names._this || sym.name == names._super) {
1489 // are we seeing something like `this` or `CurrentClass.this` or `SuperClass.super::foo`?
1490 if (TreeInfo.isExplicitThisReference(
1491 types,
1492 (ClassType)localEnv.enclClass.sym.type,
1493 tree)) {
1494 reportPrologueError(tree, sym);
1495 }
1496 } else if (sym.kind == VAR && sym.owner.kind == TYP) { // now fields only
1497 if (sym.owner != localEnv.enclClass.sym) {
1498 if (localEnv.enclClass.sym.isSubClass(sym.owner, types) &&
1499 sym.isInheritedIn(localEnv.enclClass.sym, types)) {
1500 /* if we are dealing with a field that doesn't belong to the current class, but the
1501 * field is inherited, this is an error. Unless, the super class is also an outer
1502 * class and the field's qualifier refers to the outer class
1503 */
1504 if (tree.hasTag(IDENT) ||
1505 TreeInfo.isExplicitThisReference(
1506 types,
1507 (ClassType)localEnv.enclClass.sym.type,
1508 ((JCFieldAccess)tree).selected)) {
1509 reportPrologueError(tree, sym);
1510 }
1511 }
1512 } else if (isEarlyReference(localEnv, tree, sym)) {
1513 /* now this is a `proper` instance field of the current class
1514 * references to fields of identity classes which happen to have initializers are
1515 * not allowed in the prologue
1516 */
1517 if (insideLambdaOrClassDef ||
1518 (!localEnv.enclClass.sym.isValueClass() && (sym.flags_field & HASINIT) != 0))
1519 reportPrologueError(tree, sym);
1520 // we will need to generate a proxy for this field later on
1521 if (!isInLHS) {
1522 if (!allowValueClasses) {
1523 reportPrologueError(tree, sym);
1524 } else {
1525 if (mode == PrologueVisitorMode.THIS_CONSTRUCTOR) {
1526 reportPrologueError(tree, sym);
1527 } else if (mode == PrologueVisitorMode.SUPER_CONSTRUCTOR) {
1528 localProxyVarsGen.addFieldReadInPrologue(localEnv.enclMethod, sym);
1529 }
1530 /* we do nothing in warnings only mode, as in that mode we are simulating what
1531 * the compiler would do in case the constructor code would be in the prologue
1532 * phase
1533 */
1534 }
1535 }
1536 }
1537 }
1538 }
1539 }
1540
1541 /**
1542 * Determine if the symbol appearance constitutes an early reference to the current class.
1543 *
1544 * <p>
1545 * This means the symbol is an instance field, or method, of the current class and it appears
1546 * in an early initialization context of it (i.e., one of its constructor prologues).
1547 *
1548 * @param env The current environment
1549 * @param tree the AST referencing the variable
1550 * @param sym The symbol
1551 */
1552 private boolean isEarlyReference(Env<AttrContext> env, JCTree tree, Symbol sym) {
1553 if ((sym.flags() & STATIC) == 0 &&
1554 (sym.kind == VAR || sym.kind == MTH) &&
1555 sym.isMemberOf(env.enclClass.sym, types)) {
1556 // Allow "Foo.this.x" when "Foo" is (also) an outer class, as this refers to the outer instance
1557 if (tree instanceof JCFieldAccess fa) {
1558 return TreeInfo.isExplicitThisReference(types, (ClassType)env.enclClass.type, fa.selected);
1559 } else if (currentClassSym != env.enclClass.sym) {
1560 /* so we are inside a class, CI, in the prologue of an outer class, CO, and the symbol being
1561 * analyzed has no qualifier. So if the symbol is a member of CI the reference is allowed,
1562 * otherwise it is not.
1563 * It could be that the reference to CI's member happens inside CI's own prologue, but that
1564 * will be checked separately, when CI's prologue is analyzed.
1565 */
1566 return !sym.isMemberOf(currentClassSym, types);
1567 }
1568 return true;
1569 }
1570 return false;
1571 }
1572
1573 /* scanner for a select expression, anything that is not a select or identifier
1574 * will be stored for further analysis
1575 */
1576 class SelectScanner extends DeferredAttr.FilterScanner {
1577 JCTree scanLater;
1578 java.util.List<JCTree> selectorTrees = new ArrayList<>();
1579
1580 SelectScanner() {
1581 super(Set.of(IDENT, SELECT, PARENS));
1582 }
1583
1584 @Override
1585 public void visitSelect(JCFieldAccess tree) {
1586 super.visitSelect(tree);
1587 selectorTrees.add(tree.selected);
1588 }
1589
1590 @Override
1591 void skip(JCTree tree) {
1592 scanLater = tree;
1593 }
1594 }
1595 }
1596
1597 public void visitVarDef(JCVariableDecl tree) {
1598 // Local variables have not been entered yet, so we need to do it now:
1599 if (env.info.scope.owner.kind == MTH || env.info.scope.owner.kind == VAR) {
1600 if (tree.sym != null) {
1601 // parameters have already been entered
1602 env.info.scope.enter(tree.sym);
1603 } else {
1604 if (tree.isImplicitlyTyped() && (tree.getModifiers().flags & PARAMETER) == 0) {
1605 if (tree.init == null) {
1606 //cannot use 'var' without initializer
1607 log.error(tree, Errors.CantInferLocalVarType(tree.name, Fragments.LocalMissingInit));
1608 tree.vartype = make.at(tree.pos()).Erroneous();
1609 } else {
1610 Fragment msg = canInferLocalVarType(tree);
1611 if (msg != null) {
1612 //cannot use 'var' with initializer which require an explicit target
1613 //(e.g. lambda, method reference, array initializer).
1614 log.error(tree, Errors.CantInferLocalVarType(tree.name, msg));
1615 tree.vartype = make.at(tree.pos()).Erroneous();
1616 }
1637 (tree.sym.flags() & PARAMETER) != 0;
1638 chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1639
1640 try {
1641 v.getConstValue(); // ensure compile-time constant initializer is evaluated
1642 chk.checkDeprecatedAnnotation(tree.pos(), v);
1643
1644 if (tree.init != null) {
1645 if ((v.flags_field & FINAL) == 0 ||
1646 !memberEnter.needsLazyConstValue(tree.init)) {
1647 // Not a compile-time constant
1648 // Attribute initializer in a new environment
1649 // with the declared variable as owner.
1650 // Check that initializer conforms to variable's declared type.
1651 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1652 initEnv.info.lint = lint;
1653 // In order to catch self-references, we set the variable's
1654 // declaration position to maximal possible value, effectively
1655 // marking the variable as undefined.
1656 initEnv.info.enclVar = v;
1657 boolean previousCtorPrologue = initEnv.info.ctorPrologue;
1658 try {
1659 if (v.owner.kind == TYP && !v.isStatic() && v.isStrict()) {
1660 // strict instance initializer in a value class
1661 initEnv.info.ctorPrologue = true;
1662 }
1663 attribExpr(tree.init, initEnv, v.type);
1664 if (tree.isImplicitlyTyped()) {
1665 //fixup local variable type
1666 v.type = chk.checkLocalVarType(tree, tree.init.type, tree.name);
1667 }
1668 if (allowValueClasses && v.owner.kind == TYP && !v.isStatic()) {
1669 // strict field initializers are inlined in constructor's prologues
1670 CtorPrologueVisitor ctorPrologueVisitor = new CtorPrologueVisitor(initEnv,
1671 !v.isStrict() ? PrologueVisitorMode.WARNINGS_ONLY : PrologueVisitorMode.SUPER_CONSTRUCTOR);
1672 ctorPrologueVisitor.scan(tree.init);
1673 }
1674 } finally {
1675 initEnv.info.ctorPrologue = previousCtorPrologue;
1676 }
1677 }
1678 if (tree.isImplicitlyTyped()) {
1679 setSyntheticVariableType(tree, v.type);
1680 }
1681 }
1682 result = tree.type = v.type;
1683 if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1684 if (isNonArgsMethodInObject(v.name)) {
1685 log.error(tree, Errors.IllegalRecordComponentName(v));
1686 }
1687 }
1688 chk.checkRequiresIdentity(tree, env.info.lint);
1689 }
1690 finally {
1691 chk.setLint(prevLint);
1692 }
1693 }
1694
1695 private void doQueueScanTreeAndTypeAnnotateForVarInit(JCVariableDecl tree, Env<AttrContext> env) {
1776 }
1777 }
1778 }
1779
1780 public void visitSkip(JCSkip tree) {
1781 result = null;
1782 }
1783
1784 public void visitBlock(JCBlock tree) {
1785 if (env.info.scope.owner.kind == TYP || env.info.scope.owner.kind == ERR) {
1786 // Block is a static or instance initializer;
1787 // let the owner of the environment be a freshly
1788 // created BLOCK-method.
1789 Symbol fakeOwner =
1790 new MethodSymbol(tree.flags | BLOCK |
1791 env.info.scope.owner.flags() & STRICTFP, names.empty, initBlockType,
1792 env.info.scope.owner);
1793 final Env<AttrContext> localEnv =
1794 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1795
1796 if ((tree.flags & STATIC) != 0) {
1797 localEnv.info.staticLevel++;
1798 } else {
1799 localEnv.info.instanceInitializerBlock = true;
1800 }
1801 // Attribute all type annotations in the block
1802 annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner);
1803 annotate.flush();
1804 attribStats(tree.stats, localEnv);
1805
1806 {
1807 // Store init and clinit type annotations with the ClassSymbol
1808 // to allow output in Gen.normalizeDefs.
1809 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1810 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1811 if ((tree.flags & STATIC) != 0) {
1812 cs.appendClassInitTypeAttributes(tas);
1813 } else {
1814 cs.appendInitTypeAttributes(tas);
1815 }
1816 }
1817 } else {
1818 // Create a new local environment with a local scope.
1819 Env<AttrContext> localEnv =
1820 env.dup(tree, env.info.dup(env.info.scope.dup()));
2293 // where
2294 /** Return the selected enumeration constant symbol, or null. */
2295 private Symbol enumConstant(JCTree tree, Type enumType) {
2296 if (tree.hasTag(IDENT)) {
2297 JCIdent ident = (JCIdent)tree;
2298 Name name = ident.name;
2299 for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
2300 if (sym.kind == VAR) {
2301 Symbol s = ident.sym = sym;
2302 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
2303 ident.type = s.type;
2304 return ((s.flags_field & Flags.ENUM) == 0)
2305 ? null : s;
2306 }
2307 }
2308 }
2309 return null;
2310 }
2311
2312 public void visitSynchronized(JCSynchronized tree) {
2313 boolean identityType = chk.checkIdentityType(tree.pos(), attribExpr(tree.lock, env));
2314 if (identityType && tree.lock.type != null && tree.lock.type.isValueBased()) {
2315 log.warning(tree.pos(), LintWarnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
2316 }
2317 attribStat(tree.body, env);
2318 result = null;
2319 }
2320
2321 public void visitTry(JCTry tree) {
2322 // Create a new local environment with a local
2323 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
2324 try {
2325 boolean isTryWithResource = tree.resources.nonEmpty();
2326 // Create a nested environment for attributing the try block if needed
2327 Env<AttrContext> tryEnv = isTryWithResource ?
2328 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
2329 localEnv;
2330 try {
2331 // Attribute resource declarations
2332 for (JCTree resource : tree.resources) {
2333 CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
2334 @Override
4739 }
4740
4741 public void visitSelect(JCFieldAccess tree) {
4742 // Determine the expected kind of the qualifier expression.
4743 KindSelector skind = KindSelector.NIL;
4744 if (tree.name == names._this || tree.name == names._super ||
4745 tree.name == names._class)
4746 {
4747 skind = KindSelector.TYP;
4748 } else {
4749 if (pkind().contains(KindSelector.PCK))
4750 skind = KindSelector.of(skind, KindSelector.PCK);
4751 if (pkind().contains(KindSelector.TYP))
4752 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4753 if (pkind().contains(KindSelector.VAL_MTH))
4754 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4755 }
4756
4757 // Attribute the qualifier expression, and determine its symbol (if any).
4758 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4759 Assert.check(site == tree.selected.type);
4760 if (!pkind().contains(KindSelector.TYP_PCK))
4761 site = capture(site); // Capture field access
4762
4763 // don't allow T.class T[].class, etc
4764 if (skind == KindSelector.TYP) {
4765 Type elt = site;
4766 while (elt.hasTag(ARRAY))
4767 elt = ((ArrayType)elt).elemtype;
4768 if (elt.hasTag(TYPEVAR)) {
4769 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4770 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4771 tree.sym = tree.type.tsym;
4772 return ;
4773 }
4774 }
4775
4776 // If qualifier symbol is a type or `super', assert `selectSuper'
4777 // for the selection. This is relevant for determining whether
4778 // protected symbols are accessible.
4779 Symbol sitesym = TreeInfo.symbol(tree.selected);
5851 .filter(s -> s.tsym.isSealed())
5852 .map(s -> (ClassSymbol) s.tsym)
5853 .collect(List.collector());
5854
5855 if (sealedSupers.isEmpty()) {
5856 if ((c.flags_field & Flags.NON_SEALED) != 0) {
5857 boolean hasErrorSuper = false;
5858
5859 hasErrorSuper |= types.directSupertypes(c.type)
5860 .stream()
5861 .anyMatch(s -> s.tsym.kind == Kind.ERR);
5862
5863 ClassType ct = (ClassType) c.type;
5864
5865 hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5866
5867 if (!hasErrorSuper) {
5868 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5869 }
5870 }
5871 } else if ((c.flags_field & Flags.COMPOUND) == 0) {
5872 if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5873 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5874 }
5875
5876 if (!c.type.isCompound()) {
5877 for (ClassSymbol supertypeSym : sealedSupers) {
5878 if (!supertypeSym.isPermittedSubclass(c.type.tsym)) {
5879 log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5880 }
5881 }
5882 if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5883 log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5884 c.isInterface() ?
5885 Errors.NonSealedOrSealedExpected :
5886 Errors.NonSealedSealedOrFinalExpected);
5887 }
5888 }
5889 }
5890
5891 env.info.returnResult = null;
5892 // java.lang.Enum may not be subclassed by a non-enum
5893 if (st.tsym == syms.enumSym &&
5894 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5895 log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5896
5897 // Enums may not be extended by source-level classes
5898 if (st.tsym != null &&
5899 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5900 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5901 log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5902 }
5903
5904 if (rs.isSerializable(c.type)) {
5905 env.info.isSerializable = true;
5906 }
5907
5908 if (c.isValueClass()) {
5909 Assert.check(env.tree.hasTag(CLASSDEF));
5910 chk.checkConstraintsOfValueClass((JCClassDecl) env.tree, c);
5911 }
5912
5913 attribClassBody(env, c);
5914
5915 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5916 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5917 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5918 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5919
5920 if (c.isImplicit()) {
5921 chk.checkHasMain(env.tree.pos(), c);
5922 }
5923 } finally {
5924 env.info.returnResult = prevReturnRes;
5925 log.useSource(prev);
5926 chk.setLint(prevLint);
5927 }
5928
5929 }
5930 }
5931
5932 public void visitImport(JCImport tree) {
6035 sym.kind != VAR ||
6036 sym.getConstValue() == null)
6037 log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
6038 }
6039 }
6040
6041 // Check for proper placement of super()/this() calls.
6042 chk.checkSuperInitCalls(tree);
6043
6044 // Check for cycles among non-initial constructors.
6045 chk.checkCyclicConstructors(tree);
6046
6047 // Check for cycles among annotation elements.
6048 chk.checkNonCyclicElements(tree);
6049
6050 // Check for proper use of serialVersionUID and other
6051 // serialization-related fields and methods
6052 if (env.info.lint.isEnabled(LintCategory.SERIAL)
6053 && rs.isSerializable(c.type)
6054 && !c.isAnonymous()) {
6055 chk.checkSerialStructure(env, tree, c);
6056 }
6057 // Correctly organize the positions of the type annotations
6058 typeAnnotations.organizeTypeAnnotationsBodies(tree);
6059
6060 // Check type annotations applicability rules
6061 validateTypeAnnotations(tree, false);
6062 }
6063 // where
6064 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
6065 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
6066 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
6067 if (types.isSameType(al.head.annotationType.type, t))
6068 return al.head.pos();
6069 }
6070
6071 return null;
6072 }
6073
6074 private Type capture(Type type) {
6075 return types.capture(type);
|