308 log.error(pos, Errors.CantAssignValToVar(Flags.toSource(v.flags() & (STATIC | FINAL)), v));
309 }
310 return;
311 }
312
313 // Check instance field assignments that appear in constructor prologues
314 if (rs.isEarlyReference(env, base, v)) {
315
316 // Field may not be inherited from a superclass
317 if (v.owner != env.enclClass.sym) {
318 log.error(pos, Errors.CantRefBeforeCtorCalled(v));
319 return;
320 }
321
322 // Field may not have an initializer
323 if ((v.flags() & HASINIT) != 0) {
324 log.error(pos, Errors.CantAssignInitializedBeforeCtorCalled(v));
325 return;
326 }
327 }
328 }
329
330 /** Does tree represent a static reference to an identifier?
331 * It is assumed that tree is either a SELECT or an IDENT.
332 * We have to weed out selects from non-type names here.
333 * @param tree The candidate tree.
334 */
335 boolean isStaticReference(JCTree tree) {
336 if (tree.hasTag(SELECT)) {
337 Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
338 if (lsym == null || lsym.kind != TYP) {
339 return false;
340 }
341 }
342 return true;
343 }
344
345 /** Is this symbol a type?
346 */
347 static boolean isType(Symbol sym) {
1185 }
1186 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1187 log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract);
1188 } else {
1189 if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1190 if ((owner.flags() & INTERFACE) != 0) {
1191 log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1192 } else {
1193 log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1194 }
1195 } else if ((tree.mods.flags & NATIVE) != 0) {
1196 log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1197 }
1198 // Add an implicit super() call unless an explicit call to
1199 // super(...) or this(...) is given
1200 // or we are compiling class java.lang.Object.
1201 if (isConstructor && owner.type != syms.objectType) {
1202 if (!TreeInfo.hasAnyConstructorCall(tree)) {
1203 JCStatement supCall = make.at(tree.body.pos).Exec(make.Apply(List.nil(),
1204 make.Ident(names._super), make.Idents(List.nil())));
1205 tree.body.stats = tree.body.stats.prepend(supCall);
1206 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1207 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1208 TreeInfo.hasConstructorCall(tree, names._super)) {
1209 // enum constructors are not allowed to call super
1210 // directly, so make sure there aren't any super calls
1211 // in enum constructors, except in the compiler
1212 // generated one.
1213 log.error(tree.body.stats.head.pos(),
1214 Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1215 }
1216 if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1217 List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1218 List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1219 if (!initParamNames.equals(recordComponentNames)) {
1220 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1221 Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1222 }
1223 if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1224 log.error(tree,
1225 Errors.InvalidCanonicalConstructorInRecord(
1299 chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1300
1301 try {
1302 v.getConstValue(); // ensure compile-time constant initializer is evaluated
1303 deferredLintHandler.flush(tree.pos(), lint);
1304 chk.checkDeprecatedAnnotation(tree.pos(), v);
1305
1306 if (tree.init != null) {
1307 if ((v.flags_field & FINAL) == 0 ||
1308 !memberEnter.needsLazyConstValue(tree.init)) {
1309 // Not a compile-time constant
1310 // Attribute initializer in a new environment
1311 // with the declared variable as owner.
1312 // Check that initializer conforms to variable's declared type.
1313 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1314 initEnv.info.lint = lint;
1315 // In order to catch self-references, we set the variable's
1316 // declaration position to maximal possible value, effectively
1317 // marking the variable as undefined.
1318 initEnv.info.enclVar = v;
1319 attribExpr(tree.init, initEnv, v.type);
1320 if (tree.isImplicitlyTyped()) {
1321 //fixup local variable type
1322 v.type = chk.checkLocalVarType(tree, tree.init.type, tree.name);
1323 }
1324 }
1325 if (tree.isImplicitlyTyped()) {
1326 setSyntheticVariableType(tree, v.type);
1327 }
1328 }
1329 result = tree.type = v.type;
1330 if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1331 if (isNonArgsMethodInObject(v.name)) {
1332 log.error(tree, Errors.IllegalRecordComponentName(v));
1333 }
1334 }
1335 }
1336 finally {
1337 chk.setLint(prevLint);
1338 }
1339 }
1340
1341 private boolean isNonArgsMethodInObject(Name name) {
1342 for (Symbol s : syms.objectType.tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) {
1411 }
1412 }
1413 }
1414
1415 public void visitSkip(JCSkip tree) {
1416 result = null;
1417 }
1418
1419 public void visitBlock(JCBlock tree) {
1420 if (env.info.scope.owner.kind == TYP || env.info.scope.owner.kind == ERR) {
1421 // Block is a static or instance initializer;
1422 // let the owner of the environment be a freshly
1423 // created BLOCK-method.
1424 Symbol fakeOwner =
1425 new MethodSymbol(tree.flags | BLOCK |
1426 env.info.scope.owner.flags() & STRICTFP, names.empty, initBlockType,
1427 env.info.scope.owner);
1428 final Env<AttrContext> localEnv =
1429 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1430
1431 if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;
1432 // Attribute all type annotations in the block
1433 annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
1434 annotate.flush();
1435 attribStats(tree.stats, localEnv);
1436
1437 {
1438 // Store init and clinit type annotations with the ClassSymbol
1439 // to allow output in Gen.normalizeDefs.
1440 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1441 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1442 if ((tree.flags & STATIC) != 0) {
1443 cs.appendClassInitTypeAttributes(tas);
1444 } else {
1445 cs.appendInitTypeAttributes(tas);
1446 }
1447 }
1448 } else {
1449 // Create a new local environment with a local scope.
1450 Env<AttrContext> localEnv =
1451 env.dup(tree, env.info.dup(env.info.scope.dup()));
1920 // where
1921 /** Return the selected enumeration constant symbol, or null. */
1922 private Symbol enumConstant(JCTree tree, Type enumType) {
1923 if (tree.hasTag(IDENT)) {
1924 JCIdent ident = (JCIdent)tree;
1925 Name name = ident.name;
1926 for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1927 if (sym.kind == VAR) {
1928 Symbol s = ident.sym = sym;
1929 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1930 ident.type = s.type;
1931 return ((s.flags_field & Flags.ENUM) == 0)
1932 ? null : s;
1933 }
1934 }
1935 }
1936 return null;
1937 }
1938
1939 public void visitSynchronized(JCSynchronized tree) {
1940 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1941 if (env.info.lint.isEnabled(LintCategory.SYNCHRONIZATION) && isValueBased(tree.lock.type)) {
1942 log.warning(LintCategory.SYNCHRONIZATION, tree.pos(), Warnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
1943 }
1944 attribStat(tree.body, env);
1945 result = null;
1946 }
1947 // where
1948 private boolean isValueBased(Type t) {
1949 return t != null && t.tsym != null && (t.tsym.flags() & VALUE_BASED) != 0;
1950 }
1951
1952
1953 public void visitTry(JCTry tree) {
1954 // Create a new local environment with a local
1955 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1956 try {
1957 boolean isTryWithResource = tree.resources.nonEmpty();
1958 // Create a nested environment for attributing the try block if needed
1959 Env<AttrContext> tryEnv = isTryWithResource ?
1960 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1961 localEnv;
1962 try {
1963 // Attribute resource declarations
1964 for (JCTree resource : tree.resources) {
1965 CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1966 @Override
1967 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1968 chk.basicHandler.report(pos, diags.fragment(Fragments.TryNotApplicableToType(details)));
1969 }
1970 };
1971 ResultInfo twrResult =
1972 new ResultInfo(KindSelector.VAR,
4362 }
4363
4364 public void visitSelect(JCFieldAccess tree) {
4365 // Determine the expected kind of the qualifier expression.
4366 KindSelector skind = KindSelector.NIL;
4367 if (tree.name == names._this || tree.name == names._super ||
4368 tree.name == names._class)
4369 {
4370 skind = KindSelector.TYP;
4371 } else {
4372 if (pkind().contains(KindSelector.PCK))
4373 skind = KindSelector.of(skind, KindSelector.PCK);
4374 if (pkind().contains(KindSelector.TYP))
4375 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4376 if (pkind().contains(KindSelector.VAL_MTH))
4377 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4378 }
4379
4380 // Attribute the qualifier expression, and determine its symbol (if any).
4381 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4382 if (!pkind().contains(KindSelector.TYP_PCK))
4383 site = capture(site); // Capture field access
4384
4385 // don't allow T.class T[].class, etc
4386 if (skind == KindSelector.TYP) {
4387 Type elt = site;
4388 while (elt.hasTag(ARRAY))
4389 elt = ((ArrayType)elt).elemtype;
4390 if (elt.hasTag(TYPEVAR)) {
4391 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4392 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4393 tree.sym = tree.type.tsym;
4394 return ;
4395 }
4396 }
4397
4398 // If qualifier symbol is a type or `super', assert `selectSuper'
4399 // for the selection. This is relevant for determining whether
4400 // protected symbols are accessible.
4401 Symbol sitesym = TreeInfo.symbol(tree.selected);
5457 .filter(s -> s.tsym.isSealed())
5458 .map(s -> (ClassSymbol) s.tsym)
5459 .collect(List.collector());
5460
5461 if (sealedSupers.isEmpty()) {
5462 if ((c.flags_field & Flags.NON_SEALED) != 0) {
5463 boolean hasErrorSuper = false;
5464
5465 hasErrorSuper |= types.directSupertypes(c.type)
5466 .stream()
5467 .anyMatch(s -> s.tsym.kind == Kind.ERR);
5468
5469 ClassType ct = (ClassType) c.type;
5470
5471 hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5472
5473 if (!hasErrorSuper) {
5474 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5475 }
5476 }
5477 } else {
5478 if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5479 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5480 }
5481
5482 if (!c.type.isCompound()) {
5483 for (ClassSymbol supertypeSym : sealedSupers) {
5484 if (!supertypeSym.isPermittedSubclass(c.type.tsym)) {
5485 log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5486 }
5487 }
5488 if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5489 log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5490 c.isInterface() ?
5491 Errors.NonSealedOrSealedExpected :
5492 Errors.NonSealedSealedOrFinalExpected);
5493 }
5494 }
5495 }
5496
5497 deferredLintHandler.flush(env.tree, env.info.lint);
5498 env.info.returnResult = null;
5499 // java.lang.Enum may not be subclassed by a non-enum
5500 if (st.tsym == syms.enumSym &&
5501 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5502 log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5503
5504 // Enums may not be extended by source-level classes
5505 if (st.tsym != null &&
5506 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5507 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5508 log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5509 }
5510
5511 if (rs.isSerializable(c.type)) {
5512 env.info.isSerializable = true;
5513 }
5514
5515 attribClassBody(env, c);
5516
5517 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5518 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5519 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5520 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5521
5522 if (c.isImplicit()) {
5523 chk.checkHasMain(env.tree.pos(), c);
5524 }
5525 } finally {
5526 env.info.returnResult = prevReturnRes;
5527 log.useSource(prev);
5528 chk.setLint(prevLint);
5529 }
5530
5531 }
5532 }
5533
5534 public void visitImport(JCImport tree) {
5637 sym.kind != VAR ||
5638 sym.getConstValue() == null)
5639 log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
5640 }
5641 }
5642
5643 // Check for proper placement of super()/this() calls.
5644 chk.checkSuperInitCalls(tree);
5645
5646 // Check for cycles among non-initial constructors.
5647 chk.checkCyclicConstructors(tree);
5648
5649 // Check for cycles among annotation elements.
5650 chk.checkNonCyclicElements(tree);
5651
5652 // Check for proper use of serialVersionUID and other
5653 // serialization-related fields and methods
5654 if (env.info.lint.isEnabled(LintCategory.SERIAL)
5655 && rs.isSerializable(c.type)
5656 && !c.isAnonymous()) {
5657 chk.checkSerialStructure(tree, c);
5658 }
5659 // Correctly organize the positions of the type annotations
5660 typeAnnotations.organizeTypeAnnotationsBodies(tree);
5661
5662 // Check type annotations applicability rules
5663 validateTypeAnnotations(tree, false);
5664 }
5665 // where
5666 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
5667 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
5668 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
5669 if (types.isSameType(al.head.annotationType.type, t))
5670 return al.head.pos();
5671 }
5672
5673 return null;
5674 }
5675
5676 private Type capture(Type type) {
5677 return types.capture(type);
|
308 log.error(pos, Errors.CantAssignValToVar(Flags.toSource(v.flags() & (STATIC | FINAL)), v));
309 }
310 return;
311 }
312
313 // Check instance field assignments that appear in constructor prologues
314 if (rs.isEarlyReference(env, base, v)) {
315
316 // Field may not be inherited from a superclass
317 if (v.owner != env.enclClass.sym) {
318 log.error(pos, Errors.CantRefBeforeCtorCalled(v));
319 return;
320 }
321
322 // Field may not have an initializer
323 if ((v.flags() & HASINIT) != 0) {
324 log.error(pos, Errors.CantAssignInitializedBeforeCtorCalled(v));
325 return;
326 }
327 }
328
329 if (!env.info.ctorPrologue &&
330 v.owner.isValueClass() &&
331 v.owner.kind == TYP &&
332 v.owner == env.enclClass.sym &&
333 (v.flags() & STATIC) == 0 &&
334 (base == null ||
335 TreeInfo.isExplicitThisReference(types, (ClassType)env.enclClass.type, base))) {
336 log.error(pos, Errors.CantRefAfterCtorCalled(v));
337 }
338 }
339
340 /** Does tree represent a static reference to an identifier?
341 * It is assumed that tree is either a SELECT or an IDENT.
342 * We have to weed out selects from non-type names here.
343 * @param tree The candidate tree.
344 */
345 boolean isStaticReference(JCTree tree) {
346 if (tree.hasTag(SELECT)) {
347 Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
348 if (lsym == null || lsym.kind != TYP) {
349 return false;
350 }
351 }
352 return true;
353 }
354
355 /** Is this symbol a type?
356 */
357 static boolean isType(Symbol sym) {
1195 }
1196 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1197 log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract);
1198 } else {
1199 if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1200 if ((owner.flags() & INTERFACE) != 0) {
1201 log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1202 } else {
1203 log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1204 }
1205 } else if ((tree.mods.flags & NATIVE) != 0) {
1206 log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1207 }
1208 // Add an implicit super() call unless an explicit call to
1209 // super(...) or this(...) is given
1210 // or we are compiling class java.lang.Object.
1211 if (isConstructor && owner.type != syms.objectType) {
1212 if (!TreeInfo.hasAnyConstructorCall(tree)) {
1213 JCStatement supCall = make.at(tree.body.pos).Exec(make.Apply(List.nil(),
1214 make.Ident(names._super), make.Idents(List.nil())));
1215 if (owner.isValueClass()) {
1216 tree.body.stats = tree.body.stats.append(supCall);
1217 } else {
1218 tree.body.stats = tree.body.stats.prepend(supCall);
1219 }
1220 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1221 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1222 TreeInfo.hasConstructorCall(tree, names._super)) {
1223 // enum constructors are not allowed to call super
1224 // directly, so make sure there aren't any super calls
1225 // in enum constructors, except in the compiler
1226 // generated one.
1227 log.error(tree.body.stats.head.pos(),
1228 Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1229 }
1230 if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1231 List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1232 List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1233 if (!initParamNames.equals(recordComponentNames)) {
1234 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1235 Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1236 }
1237 if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1238 log.error(tree,
1239 Errors.InvalidCanonicalConstructorInRecord(
1313 chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1314
1315 try {
1316 v.getConstValue(); // ensure compile-time constant initializer is evaluated
1317 deferredLintHandler.flush(tree.pos(), lint);
1318 chk.checkDeprecatedAnnotation(tree.pos(), v);
1319
1320 if (tree.init != null) {
1321 if ((v.flags_field & FINAL) == 0 ||
1322 !memberEnter.needsLazyConstValue(tree.init)) {
1323 // Not a compile-time constant
1324 // Attribute initializer in a new environment
1325 // with the declared variable as owner.
1326 // Check that initializer conforms to variable's declared type.
1327 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1328 initEnv.info.lint = lint;
1329 // In order to catch self-references, we set the variable's
1330 // declaration position to maximal possible value, effectively
1331 // marking the variable as undefined.
1332 initEnv.info.enclVar = v;
1333 boolean previousCtorPrologue = initEnv.info.ctorPrologue;
1334 try {
1335 if (v.owner.kind == TYP && v.owner.isValueClass() && !v.isStatic()) {
1336 // strict instance initializer in a value class
1337 initEnv.info.ctorPrologue = true;
1338 }
1339 attribExpr(tree.init, initEnv, v.type);
1340 if (tree.isImplicitlyTyped()) {
1341 //fixup local variable type
1342 v.type = chk.checkLocalVarType(tree, tree.init.type, tree.name);
1343 }
1344 } finally {
1345 initEnv.info.ctorPrologue = previousCtorPrologue;
1346 }
1347 }
1348 if (tree.isImplicitlyTyped()) {
1349 setSyntheticVariableType(tree, v.type);
1350 }
1351 }
1352 result = tree.type = v.type;
1353 if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1354 if (isNonArgsMethodInObject(v.name)) {
1355 log.error(tree, Errors.IllegalRecordComponentName(v));
1356 }
1357 }
1358 }
1359 finally {
1360 chk.setLint(prevLint);
1361 }
1362 }
1363
1364 private boolean isNonArgsMethodInObject(Name name) {
1365 for (Symbol s : syms.objectType.tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) {
1434 }
1435 }
1436 }
1437
1438 public void visitSkip(JCSkip tree) {
1439 result = null;
1440 }
1441
1442 public void visitBlock(JCBlock tree) {
1443 if (env.info.scope.owner.kind == TYP || env.info.scope.owner.kind == ERR) {
1444 // Block is a static or instance initializer;
1445 // let the owner of the environment be a freshly
1446 // created BLOCK-method.
1447 Symbol fakeOwner =
1448 new MethodSymbol(tree.flags | BLOCK |
1449 env.info.scope.owner.flags() & STRICTFP, names.empty, initBlockType,
1450 env.info.scope.owner);
1451 final Env<AttrContext> localEnv =
1452 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1453
1454 if ((tree.flags & STATIC) != 0) {
1455 localEnv.info.staticLevel++;
1456 } else {
1457 localEnv.info.instanceInitializerBlock = true;
1458 }
1459 // Attribute all type annotations in the block
1460 annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
1461 annotate.flush();
1462 attribStats(tree.stats, localEnv);
1463
1464 {
1465 // Store init and clinit type annotations with the ClassSymbol
1466 // to allow output in Gen.normalizeDefs.
1467 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1468 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1469 if ((tree.flags & STATIC) != 0) {
1470 cs.appendClassInitTypeAttributes(tas);
1471 } else {
1472 cs.appendInitTypeAttributes(tas);
1473 }
1474 }
1475 } else {
1476 // Create a new local environment with a local scope.
1477 Env<AttrContext> localEnv =
1478 env.dup(tree, env.info.dup(env.info.scope.dup()));
1947 // where
1948 /** Return the selected enumeration constant symbol, or null. */
1949 private Symbol enumConstant(JCTree tree, Type enumType) {
1950 if (tree.hasTag(IDENT)) {
1951 JCIdent ident = (JCIdent)tree;
1952 Name name = ident.name;
1953 for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1954 if (sym.kind == VAR) {
1955 Symbol s = ident.sym = sym;
1956 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1957 ident.type = s.type;
1958 return ((s.flags_field & Flags.ENUM) == 0)
1959 ? null : s;
1960 }
1961 }
1962 }
1963 return null;
1964 }
1965
1966 public void visitSynchronized(JCSynchronized tree) {
1967 boolean identityType = chk.checkIdentityType(tree.pos(), attribExpr(tree.lock, env));
1968 if (env.info.lint.isEnabled(LintCategory.SYNCHRONIZATION) &&
1969 identityType &&
1970 isValueBased(tree.lock.type)) {
1971 log.warning(LintCategory.SYNCHRONIZATION, tree.pos(), Warnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
1972 }
1973 attribStat(tree.body, env);
1974 result = null;
1975 }
1976 // where
1977 private boolean isValueBased(Type t) {
1978 return t != null && t.tsym != null && (t.tsym.flags() & VALUE_BASED) != 0;
1979 }
1980
1981 public void visitTry(JCTry tree) {
1982 // Create a new local environment with a local
1983 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1984 try {
1985 boolean isTryWithResource = tree.resources.nonEmpty();
1986 // Create a nested environment for attributing the try block if needed
1987 Env<AttrContext> tryEnv = isTryWithResource ?
1988 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1989 localEnv;
1990 try {
1991 // Attribute resource declarations
1992 for (JCTree resource : tree.resources) {
1993 CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1994 @Override
1995 public void report(DiagnosticPosition pos, JCDiagnostic details) {
1996 chk.basicHandler.report(pos, diags.fragment(Fragments.TryNotApplicableToType(details)));
1997 }
1998 };
1999 ResultInfo twrResult =
2000 new ResultInfo(KindSelector.VAR,
4390 }
4391
4392 public void visitSelect(JCFieldAccess tree) {
4393 // Determine the expected kind of the qualifier expression.
4394 KindSelector skind = KindSelector.NIL;
4395 if (tree.name == names._this || tree.name == names._super ||
4396 tree.name == names._class)
4397 {
4398 skind = KindSelector.TYP;
4399 } else {
4400 if (pkind().contains(KindSelector.PCK))
4401 skind = KindSelector.of(skind, KindSelector.PCK);
4402 if (pkind().contains(KindSelector.TYP))
4403 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4404 if (pkind().contains(KindSelector.VAL_MTH))
4405 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4406 }
4407
4408 // Attribute the qualifier expression, and determine its symbol (if any).
4409 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4410 Assert.check(site == tree.selected.type);
4411 if (!pkind().contains(KindSelector.TYP_PCK))
4412 site = capture(site); // Capture field access
4413
4414 // don't allow T.class T[].class, etc
4415 if (skind == KindSelector.TYP) {
4416 Type elt = site;
4417 while (elt.hasTag(ARRAY))
4418 elt = ((ArrayType)elt).elemtype;
4419 if (elt.hasTag(TYPEVAR)) {
4420 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4421 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4422 tree.sym = tree.type.tsym;
4423 return ;
4424 }
4425 }
4426
4427 // If qualifier symbol is a type or `super', assert `selectSuper'
4428 // for the selection. This is relevant for determining whether
4429 // protected symbols are accessible.
4430 Symbol sitesym = TreeInfo.symbol(tree.selected);
5486 .filter(s -> s.tsym.isSealed())
5487 .map(s -> (ClassSymbol) s.tsym)
5488 .collect(List.collector());
5489
5490 if (sealedSupers.isEmpty()) {
5491 if ((c.flags_field & Flags.NON_SEALED) != 0) {
5492 boolean hasErrorSuper = false;
5493
5494 hasErrorSuper |= types.directSupertypes(c.type)
5495 .stream()
5496 .anyMatch(s -> s.tsym.kind == Kind.ERR);
5497
5498 ClassType ct = (ClassType) c.type;
5499
5500 hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5501
5502 if (!hasErrorSuper) {
5503 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5504 }
5505 }
5506 } else if ((c.flags_field & Flags.COMPOUND) == 0) {
5507 if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5508 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5509 }
5510
5511 if (!c.type.isCompound()) {
5512 for (ClassSymbol supertypeSym : sealedSupers) {
5513 if (!supertypeSym.isPermittedSubclass(c.type.tsym)) {
5514 log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5515 }
5516 }
5517 if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5518 log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5519 c.isInterface() ?
5520 Errors.NonSealedOrSealedExpected :
5521 Errors.NonSealedSealedOrFinalExpected);
5522 }
5523 }
5524 }
5525
5526 deferredLintHandler.flush(env.tree, env.info.lint);
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 if (c.isValueClass()) {
5545 Assert.check(env.tree.hasTag(CLASSDEF));
5546 chk.checkConstraintsOfValueClass((JCClassDecl) env.tree, c);
5547 }
5548
5549 attribClassBody(env, c);
5550
5551 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5552 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5553 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5554 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5555
5556 if (c.isImplicit()) {
5557 chk.checkHasMain(env.tree.pos(), c);
5558 }
5559 } finally {
5560 env.info.returnResult = prevReturnRes;
5561 log.useSource(prev);
5562 chk.setLint(prevLint);
5563 }
5564
5565 }
5566 }
5567
5568 public void visitImport(JCImport tree) {
5671 sym.kind != VAR ||
5672 sym.getConstValue() == null)
5673 log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
5674 }
5675 }
5676
5677 // Check for proper placement of super()/this() calls.
5678 chk.checkSuperInitCalls(tree);
5679
5680 // Check for cycles among non-initial constructors.
5681 chk.checkCyclicConstructors(tree);
5682
5683 // Check for cycles among annotation elements.
5684 chk.checkNonCyclicElements(tree);
5685
5686 // Check for proper use of serialVersionUID and other
5687 // serialization-related fields and methods
5688 if (env.info.lint.isEnabled(LintCategory.SERIAL)
5689 && rs.isSerializable(c.type)
5690 && !c.isAnonymous()) {
5691 chk.checkSerialStructure(env, tree, c);
5692 }
5693 // Correctly organize the positions of the type annotations
5694 typeAnnotations.organizeTypeAnnotationsBodies(tree);
5695
5696 // Check type annotations applicability rules
5697 validateTypeAnnotations(tree, false);
5698 }
5699 // where
5700 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
5701 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
5702 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
5703 if (types.isSameType(al.head.annotationType.type, t))
5704 return al.head.pos();
5705 }
5706
5707 return null;
5708 }
5709
5710 private Type capture(Type type) {
5711 return types.capture(type);
|