< prev index next >

src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java

Print this page

 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,

4352     }
4353 
4354     public void visitSelect(JCFieldAccess tree) {
4355         // Determine the expected kind of the qualifier expression.
4356         KindSelector skind = KindSelector.NIL;
4357         if (tree.name == names._this || tree.name == names._super ||
4358                 tree.name == names._class)
4359         {
4360             skind = KindSelector.TYP;
4361         } else {
4362             if (pkind().contains(KindSelector.PCK))
4363                 skind = KindSelector.of(skind, KindSelector.PCK);
4364             if (pkind().contains(KindSelector.TYP))
4365                 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4366             if (pkind().contains(KindSelector.VAL_MTH))
4367                 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4368         }
4369 
4370         // Attribute the qualifier expression, and determine its symbol (if any).
4371         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));

4372         if (!pkind().contains(KindSelector.TYP_PCK))
4373             site = capture(site); // Capture field access
4374 
4375         // don't allow T.class T[].class, etc
4376         if (skind == KindSelector.TYP) {
4377             Type elt = site;
4378             while (elt.hasTag(ARRAY))
4379                 elt = ((ArrayType)elt).elemtype;
4380             if (elt.hasTag(TYPEVAR)) {
4381                 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4382                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4383                 tree.sym = tree.type.tsym;
4384                 return ;
4385             }
4386         }
4387 
4388         // If qualifier symbol is a type or `super', assert `selectSuper'
4389         // for the selection. This is relevant for determining whether
4390         // protected symbols are accessible.
4391         Symbol sitesym = TreeInfo.symbol(tree.selected);

5447                                                       .filter(s -> s.tsym.isSealed())
5448                                                       .map(s -> (ClassSymbol) s.tsym)
5449                                                       .collect(List.collector());
5450 
5451                 if (sealedSupers.isEmpty()) {
5452                     if ((c.flags_field & Flags.NON_SEALED) != 0) {
5453                         boolean hasErrorSuper = false;
5454 
5455                         hasErrorSuper |= types.directSupertypes(c.type)
5456                                               .stream()
5457                                               .anyMatch(s -> s.tsym.kind == Kind.ERR);
5458 
5459                         ClassType ct = (ClassType) c.type;
5460 
5461                         hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5462 
5463                         if (!hasErrorSuper) {
5464                             log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5465                         }
5466                     }
5467                 } else {
5468                     if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5469                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5470                     }
5471 
5472                     if (!c.type.isCompound()) {
5473                         for (ClassSymbol supertypeSym : sealedSupers) {
5474                             if (!supertypeSym.isPermittedSubclass(c.type.tsym)) {
5475                                 log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5476                             }
5477                         }
5478                         if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5479                             log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5480                                     c.isInterface() ?
5481                                             Errors.NonSealedOrSealedExpected :
5482                                             Errors.NonSealedSealedOrFinalExpected);
5483                         }
5484                     }
5485                 }
5486 
5487                 deferredLintHandler.flush(env.tree, env.info.lint);
5488                 env.info.returnResult = null;
5489                 // java.lang.Enum may not be subclassed by a non-enum
5490                 if (st.tsym == syms.enumSym &&
5491                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5492                     log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5493 
5494                 // Enums may not be extended by source-level classes
5495                 if (st.tsym != null &&
5496                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5497                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5498                     log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5499                 }
5500 
5501                 if (rs.isSerializable(c.type)) {
5502                     env.info.isSerializable = true;
5503                 }
5504 





5505                 attribClassBody(env, c);
5506 
5507                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5508                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5509                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5510                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5511 
5512                 if (c.isImplicit()) {
5513                     chk.checkHasMain(env.tree.pos(), c);
5514                 }
5515             } finally {
5516                 env.info.returnResult = prevReturnRes;
5517                 log.useSource(prev);
5518                 chk.setLint(prevLint);
5519             }
5520 
5521         }
5522     }
5523 
5524     public void visitImport(JCImport tree) {

5627                         sym.kind != VAR ||
5628                         sym.getConstValue() == null)
5629                     log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
5630             }
5631         }
5632 
5633         // Check for proper placement of super()/this() calls.
5634         chk.checkSuperInitCalls(tree);
5635 
5636         // Check for cycles among non-initial constructors.
5637         chk.checkCyclicConstructors(tree);
5638 
5639         // Check for cycles among annotation elements.
5640         chk.checkNonCyclicElements(tree);
5641 
5642         // Check for proper use of serialVersionUID and other
5643         // serialization-related fields and methods
5644         if (env.info.lint.isEnabled(LintCategory.SERIAL)
5645                 && rs.isSerializable(c.type)
5646                 && !c.isAnonymous()) {
5647             chk.checkSerialStructure(tree, c);
5648         }
5649         // Correctly organize the positions of the type annotations
5650         typeAnnotations.organizeTypeAnnotationsBodies(tree);
5651 
5652         // Check type annotations applicability rules
5653         validateTypeAnnotations(tree, false);
5654     }
5655         // where
5656         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
5657         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
5658             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
5659                 if (types.isSameType(al.head.annotationType.type, t))
5660                     return al.head.pos();
5661             }
5662 
5663             return null;
5664         }
5665 
5666     private Type capture(Type type) {
5667         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,

4380     }
4381 
4382     public void visitSelect(JCFieldAccess tree) {
4383         // Determine the expected kind of the qualifier expression.
4384         KindSelector skind = KindSelector.NIL;
4385         if (tree.name == names._this || tree.name == names._super ||
4386                 tree.name == names._class)
4387         {
4388             skind = KindSelector.TYP;
4389         } else {
4390             if (pkind().contains(KindSelector.PCK))
4391                 skind = KindSelector.of(skind, KindSelector.PCK);
4392             if (pkind().contains(KindSelector.TYP))
4393                 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4394             if (pkind().contains(KindSelector.VAL_MTH))
4395                 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4396         }
4397 
4398         // Attribute the qualifier expression, and determine its symbol (if any).
4399         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4400         Assert.check(site == tree.selected.type);
4401         if (!pkind().contains(KindSelector.TYP_PCK))
4402             site = capture(site); // Capture field access
4403 
4404         // don't allow T.class T[].class, etc
4405         if (skind == KindSelector.TYP) {
4406             Type elt = site;
4407             while (elt.hasTag(ARRAY))
4408                 elt = ((ArrayType)elt).elemtype;
4409             if (elt.hasTag(TYPEVAR)) {
4410                 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4411                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4412                 tree.sym = tree.type.tsym;
4413                 return ;
4414             }
4415         }
4416 
4417         // If qualifier symbol is a type or `super', assert `selectSuper'
4418         // for the selection. This is relevant for determining whether
4419         // protected symbols are accessible.
4420         Symbol sitesym = TreeInfo.symbol(tree.selected);

5476                                                       .filter(s -> s.tsym.isSealed())
5477                                                       .map(s -> (ClassSymbol) s.tsym)
5478                                                       .collect(List.collector());
5479 
5480                 if (sealedSupers.isEmpty()) {
5481                     if ((c.flags_field & Flags.NON_SEALED) != 0) {
5482                         boolean hasErrorSuper = false;
5483 
5484                         hasErrorSuper |= types.directSupertypes(c.type)
5485                                               .stream()
5486                                               .anyMatch(s -> s.tsym.kind == Kind.ERR);
5487 
5488                         ClassType ct = (ClassType) c.type;
5489 
5490                         hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5491 
5492                         if (!hasErrorSuper) {
5493                             log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5494                         }
5495                     }
5496                 } else if ((c.flags_field & Flags.COMPOUND) == 0) {
5497                     if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5498                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5499                     }
5500 
5501                     if (!c.type.isCompound()) {
5502                         for (ClassSymbol supertypeSym : sealedSupers) {
5503                             if (!supertypeSym.isPermittedSubclass(c.type.tsym)) {
5504                                 log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5505                             }
5506                         }
5507                         if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5508                             log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5509                                     c.isInterface() ?
5510                                             Errors.NonSealedOrSealedExpected :
5511                                             Errors.NonSealedSealedOrFinalExpected);
5512                         }
5513                     }
5514                 }
5515 
5516                 deferredLintHandler.flush(env.tree, env.info.lint);
5517                 env.info.returnResult = null;
5518                 // java.lang.Enum may not be subclassed by a non-enum
5519                 if (st.tsym == syms.enumSym &&
5520                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5521                     log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5522 
5523                 // Enums may not be extended by source-level classes
5524                 if (st.tsym != null &&
5525                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5526                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5527                     log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5528                 }
5529 
5530                 if (rs.isSerializable(c.type)) {
5531                     env.info.isSerializable = true;
5532                 }
5533 
5534                 if (c.isValueClass()) {
5535                     Assert.check(env.tree.hasTag(CLASSDEF));
5536                     chk.checkConstraintsOfValueClass((JCClassDecl) env.tree, c);
5537                 }
5538 
5539                 attribClassBody(env, c);
5540 
5541                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5542                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5543                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5544                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5545 
5546                 if (c.isImplicit()) {
5547                     chk.checkHasMain(env.tree.pos(), c);
5548                 }
5549             } finally {
5550                 env.info.returnResult = prevReturnRes;
5551                 log.useSource(prev);
5552                 chk.setLint(prevLint);
5553             }
5554 
5555         }
5556     }
5557 
5558     public void visitImport(JCImport tree) {

5661                         sym.kind != VAR ||
5662                         sym.getConstValue() == null)
5663                     log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
5664             }
5665         }
5666 
5667         // Check for proper placement of super()/this() calls.
5668         chk.checkSuperInitCalls(tree);
5669 
5670         // Check for cycles among non-initial constructors.
5671         chk.checkCyclicConstructors(tree);
5672 
5673         // Check for cycles among annotation elements.
5674         chk.checkNonCyclicElements(tree);
5675 
5676         // Check for proper use of serialVersionUID and other
5677         // serialization-related fields and methods
5678         if (env.info.lint.isEnabled(LintCategory.SERIAL)
5679                 && rs.isSerializable(c.type)
5680                 && !c.isAnonymous()) {
5681             chk.checkSerialStructure(env, tree, c);
5682         }
5683         // Correctly organize the positions of the type annotations
5684         typeAnnotations.organizeTypeAnnotationsBodies(tree);
5685 
5686         // Check type annotations applicability rules
5687         validateTypeAnnotations(tree, false);
5688     }
5689         // where
5690         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
5691         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
5692             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
5693                 if (types.isSameType(al.head.annotationType.type, t))
5694                     return al.head.pos();
5695             }
5696 
5697             return null;
5698         }
5699 
5700     private Type capture(Type type) {
5701         return types.capture(type);
< prev index next >