< prev index next >

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

Print this page

 307                 log.error(pos, Errors.CantAssignValToVar(Flags.toSource(v.flags() & (STATIC | FINAL)), v));
 308             }
 309             return;
 310         }
 311 
 312         // Check instance field assignments that appear in constructor prologues
 313         if (rs.isEarlyReference(env, base, v)) {
 314 
 315             // Field may not be inherited from a superclass
 316             if (v.owner != env.enclClass.sym) {
 317                 log.error(pos, Errors.CantRefBeforeCtorCalled(v));
 318                 return;
 319             }
 320 
 321             // Field may not have an initializer
 322             if ((v.flags() & HASINIT) != 0) {
 323                 log.error(pos, Errors.CantAssignInitializedBeforeCtorCalled(v));
 324                 return;
 325             }
 326         }










 327     }
 328 
 329     /** Does tree represent a static reference to an identifier?
 330      *  It is assumed that tree is either a SELECT or an IDENT.
 331      *  We have to weed out selects from non-type names here.
 332      *  @param tree    The candidate tree.
 333      */
 334     boolean isStaticReference(JCTree tree) {
 335         if (tree.hasTag(SELECT)) {
 336             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
 337             if (lsym == null || lsym.kind != TYP) {
 338                 return false;
 339             }
 340         }
 341         return true;
 342     }
 343 
 344     /** Is this symbol a type?
 345      */
 346     static boolean isType(Symbol sym) {

1184                 }
1185                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1186                     log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract);
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(

1298         chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1299 
1300         try {
1301             v.getConstValue(); // ensure compile-time constant initializer is evaluated
1302             deferredLintHandler.flush(tree.pos(), lint);
1303             chk.checkDeprecatedAnnotation(tree.pos(), v);
1304 
1305             if (tree.init != null) {
1306                 if ((v.flags_field & FINAL) == 0 ||
1307                     !memberEnter.needsLazyConstValue(tree.init)) {
1308                     // Not a compile-time constant
1309                     // Attribute initializer in a new environment
1310                     // with the declared variable as owner.
1311                     // Check that initializer conforms to variable's declared type.
1312                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1313                     initEnv.info.lint = lint;
1314                     // In order to catch self-references, we set the variable's
1315                     // declaration position to maximal possible value, effectively
1316                     // marking the variable as undefined.
1317                     initEnv.info.enclVar = v;
1318                     attribExpr(tree.init, initEnv, v.type);
1319                     if (tree.isImplicitlyTyped()) {
1320                         //fixup local variable type
1321                         v.type = chk.checkLocalVarType(tree, tree.init.type, tree.name);









1322                     }
1323                 }
1324                 if (tree.isImplicitlyTyped()) {
1325                     setSyntheticVariableType(tree, v.type);
1326                 }
1327             }
1328             result = tree.type = v.type;
1329             if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1330                 if (isNonArgsMethodInObject(v.name)) {
1331                     log.error(tree, Errors.IllegalRecordComponentName(v));
1332                 }
1333             }
1334         }
1335         finally {
1336             chk.setLint(prevLint);
1337         }
1338     }
1339 
1340     private boolean isNonArgsMethodInObject(Name name) {
1341         for (Symbol s : syms.objectType.tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) {

1410             }
1411         }
1412     }
1413 
1414     public void visitSkip(JCSkip tree) {
1415         result = null;
1416     }
1417 
1418     public void visitBlock(JCBlock tree) {
1419         if (env.info.scope.owner.kind == TYP || env.info.scope.owner.kind == ERR) {
1420             // Block is a static or instance initializer;
1421             // let the owner of the environment be a freshly
1422             // created BLOCK-method.
1423             Symbol fakeOwner =
1424                 new MethodSymbol(tree.flags | BLOCK |
1425                     env.info.scope.owner.flags() & STRICTFP, names.empty, null,
1426                     env.info.scope.owner);
1427             final Env<AttrContext> localEnv =
1428                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1429 
1430             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;




1431             // Attribute all type annotations in the block
1432             annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
1433             annotate.flush();
1434             attribStats(tree.stats, localEnv);
1435 
1436             {
1437                 // Store init and clinit type annotations with the ClassSymbol
1438                 // to allow output in Gen.normalizeDefs.
1439                 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1440                 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1441                 if ((tree.flags & STATIC) != 0) {
1442                     cs.appendClassInitTypeAttributes(tas);
1443                 } else {
1444                     cs.appendInitTypeAttributes(tas);
1445                 }
1446             }
1447         } else {
1448             // Create a new local environment with a local scope.
1449             Env<AttrContext> localEnv =
1450                 env.dup(tree, env.info.dup(env.info.scope.dup()));

1919     // where
1920     /** Return the selected enumeration constant symbol, or null. */
1921     private Symbol enumConstant(JCTree tree, Type enumType) {
1922         if (tree.hasTag(IDENT)) {
1923             JCIdent ident = (JCIdent)tree;
1924             Name name = ident.name;
1925             for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1926                 if (sym.kind == VAR) {
1927                     Symbol s = ident.sym = sym;
1928                     ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1929                     ident.type = s.type;
1930                     return ((s.flags_field & Flags.ENUM) == 0)
1931                         ? null : s;
1932                 }
1933             }
1934         }
1935         return null;
1936     }
1937 
1938     public void visitSynchronized(JCSynchronized tree) {
1939         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1940         if (env.info.lint.isEnabled(LintCategory.SYNCHRONIZATION) && isValueBased(tree.lock.type)) {


1941             log.warning(LintCategory.SYNCHRONIZATION, tree.pos(), Warnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
1942         }
1943         attribStat(tree.body, env);
1944         result = null;
1945     }
1946         // where
1947         private boolean isValueBased(Type t) {
1948             return t != null && t.tsym != null && (t.tsym.flags() & VALUE_BASED) != 0;
1949         }
1950 
1951 
1952     public void visitTry(JCTry tree) {
1953         // Create a new local environment with a local
1954         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1955         try {
1956             boolean isTryWithResource = tree.resources.nonEmpty();
1957             // Create a nested environment for attributing the try block if needed
1958             Env<AttrContext> tryEnv = isTryWithResource ?
1959                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1960                 localEnv;
1961             try {
1962                 // Attribute resource declarations
1963                 for (JCTree resource : tree.resources) {
1964                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1965                         @Override
1966                         public void report(DiagnosticPosition pos, JCDiagnostic details) {
1967                             chk.basicHandler.report(pos, diags.fragment(Fragments.TryNotApplicableToType(details)));
1968                         }
1969                     };
1970                     ResultInfo twrResult =
1971                         new ResultInfo(KindSelector.VAR,

4386     }
4387 
4388     public void visitSelect(JCFieldAccess tree) {
4389         // Determine the expected kind of the qualifier expression.
4390         KindSelector skind = KindSelector.NIL;
4391         if (tree.name == names._this || tree.name == names._super ||
4392                 tree.name == names._class)
4393         {
4394             skind = KindSelector.TYP;
4395         } else {
4396             if (pkind().contains(KindSelector.PCK))
4397                 skind = KindSelector.of(skind, KindSelector.PCK);
4398             if (pkind().contains(KindSelector.TYP))
4399                 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4400             if (pkind().contains(KindSelector.VAL_MTH))
4401                 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4402         }
4403 
4404         // Attribute the qualifier expression, and determine its symbol (if any).
4405         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));

4406         if (!pkind().contains(KindSelector.TYP_PCK))
4407             site = capture(site); // Capture field access
4408 
4409         // don't allow T.class T[].class, etc
4410         if (skind == KindSelector.TYP) {
4411             Type elt = site;
4412             while (elt.hasTag(ARRAY))
4413                 elt = ((ArrayType)elt).elemtype;
4414             if (elt.hasTag(TYPEVAR)) {
4415                 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4416                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4417                 tree.sym = tree.type.tsym;
4418                 return ;
4419             }
4420         }
4421 
4422         // If qualifier symbol is a type or `super', assert `selectSuper'
4423         // for the selection. This is relevant for determining whether
4424         // protected symbols are accessible.
4425         Symbol sitesym = TreeInfo.symbol(tree.selected);

5468                                                       .filter(s -> s.tsym.isSealed())
5469                                                       .map(s -> (ClassSymbol) s.tsym)
5470                                                       .collect(List.collector());
5471 
5472                 if (sealedSupers.isEmpty()) {
5473                     if ((c.flags_field & Flags.NON_SEALED) != 0) {
5474                         boolean hasErrorSuper = false;
5475 
5476                         hasErrorSuper |= types.directSupertypes(c.type)
5477                                               .stream()
5478                                               .anyMatch(s -> s.tsym.kind == Kind.ERR);
5479 
5480                         ClassType ct = (ClassType) c.type;
5481 
5482                         hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5483 
5484                         if (!hasErrorSuper) {
5485                             log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5486                         }
5487                     }
5488                 } else {
5489                     if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5490                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5491                     }
5492 
5493                     if (!c.type.isCompound()) {
5494                         for (ClassSymbol supertypeSym : sealedSupers) {
5495                             if (!supertypeSym.isPermittedSubclass(c.type.tsym)) {
5496                                 log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5497                             }
5498                         }
5499                         if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5500                             log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5501                                     c.isInterface() ?
5502                                             Errors.NonSealedOrSealedExpected :
5503                                             Errors.NonSealedSealedOrFinalExpected);
5504                         }
5505                     }
5506                 }
5507 
5508                 deferredLintHandler.flush(env.tree, env.info.lint);
5509                 env.info.returnResult = null;
5510                 // java.lang.Enum may not be subclassed by a non-enum
5511                 if (st.tsym == syms.enumSym &&
5512                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5513                     log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5514 
5515                 // Enums may not be extended by source-level classes
5516                 if (st.tsym != null &&
5517                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5518                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5519                     log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5520                 }
5521 
5522                 if (rs.isSerializable(c.type)) {
5523                     env.info.isSerializable = true;
5524                 }
5525 





5526                 attribClassBody(env, c);
5527 
5528                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5529                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5530                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5531                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5532 
5533                 if (c.isImplicit()) {
5534                     chk.checkHasMain(env.tree.pos(), c);
5535                 }
5536             } finally {
5537                 env.info.returnResult = prevReturnRes;
5538                 log.useSource(prev);
5539                 chk.setLint(prevLint);
5540             }
5541 
5542         }
5543     }
5544 
5545     public void visitImport(JCImport tree) {

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

 307                 log.error(pos, Errors.CantAssignValToVar(Flags.toSource(v.flags() & (STATIC | FINAL)), v));
 308             }
 309             return;
 310         }
 311 
 312         // Check instance field assignments that appear in constructor prologues
 313         if (rs.isEarlyReference(env, base, v)) {
 314 
 315             // Field may not be inherited from a superclass
 316             if (v.owner != env.enclClass.sym) {
 317                 log.error(pos, Errors.CantRefBeforeCtorCalled(v));
 318                 return;
 319             }
 320 
 321             // Field may not have an initializer
 322             if ((v.flags() & HASINIT) != 0) {
 323                 log.error(pos, Errors.CantAssignInitializedBeforeCtorCalled(v));
 324                 return;
 325             }
 326         }
 327 
 328         if (!env.info.ctorPrologue &&
 329                 v.owner.isValueClass() &&
 330                 v.owner.kind == TYP &&
 331                 v.owner == env.enclClass.sym &&
 332                 (v.flags() & STATIC) == 0 &&
 333                 (base == null ||
 334                         TreeInfo.isExplicitThisReference(types, (ClassType)env.enclClass.type, base))) {
 335             log.error(pos, Errors.CantRefAfterCtorCalled(v));
 336         }
 337     }
 338 
 339     /** Does tree represent a static reference to an identifier?
 340      *  It is assumed that tree is either a SELECT or an IDENT.
 341      *  We have to weed out selects from non-type names here.
 342      *  @param tree    The candidate tree.
 343      */
 344     boolean isStaticReference(JCTree tree) {
 345         if (tree.hasTag(SELECT)) {
 346             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
 347             if (lsym == null || lsym.kind != TYP) {
 348                 return false;
 349             }
 350         }
 351         return true;
 352     }
 353 
 354     /** Is this symbol a type?
 355      */
 356     static boolean isType(Symbol sym) {

1194                 }
1195                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1196                     log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract);
1197             } else {
1198                 if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1199                     if ((owner.flags() & INTERFACE) != 0) {
1200                         log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1201                     } else {
1202                         log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1203                     }
1204                 } else if ((tree.mods.flags & NATIVE) != 0) {
1205                     log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1206                 }
1207                 // Add an implicit super() call unless an explicit call to
1208                 // super(...) or this(...) is given
1209                 // or we are compiling class java.lang.Object.
1210                 if (isConstructor && owner.type != syms.objectType) {
1211                     if (!TreeInfo.hasAnyConstructorCall(tree)) {
1212                         JCStatement supCall = make.at(tree.body.pos).Exec(make.Apply(List.nil(),
1213                                 make.Ident(names._super), make.Idents(List.nil())));
1214                         if (owner.isValueClass()) {
1215                             tree.body.stats = tree.body.stats.append(supCall);
1216                         } else {
1217                             tree.body.stats = tree.body.stats.prepend(supCall);
1218                         }
1219                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1220                             (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1221                             TreeInfo.hasConstructorCall(tree, names._super)) {
1222                         // enum constructors are not allowed to call super
1223                         // directly, so make sure there aren't any super calls
1224                         // in enum constructors, except in the compiler
1225                         // generated one.
1226                         log.error(tree.body.stats.head.pos(),
1227                                   Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1228                     }
1229                     if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1230                         List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1231                         List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1232                         if (!initParamNames.equals(recordComponentNames)) {
1233                             log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1234                                     Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1235                         }
1236                         if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1237                             log.error(tree,
1238                                     Errors.InvalidCanonicalConstructorInRecord(

1312         chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1313 
1314         try {
1315             v.getConstValue(); // ensure compile-time constant initializer is evaluated
1316             deferredLintHandler.flush(tree.pos(), lint);
1317             chk.checkDeprecatedAnnotation(tree.pos(), v);
1318 
1319             if (tree.init != null) {
1320                 if ((v.flags_field & FINAL) == 0 ||
1321                     !memberEnter.needsLazyConstValue(tree.init)) {
1322                     // Not a compile-time constant
1323                     // Attribute initializer in a new environment
1324                     // with the declared variable as owner.
1325                     // Check that initializer conforms to variable's declared type.
1326                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1327                     initEnv.info.lint = lint;
1328                     // In order to catch self-references, we set the variable's
1329                     // declaration position to maximal possible value, effectively
1330                     // marking the variable as undefined.
1331                     initEnv.info.enclVar = v;
1332                     boolean previousCtorPrologue = initEnv.info.ctorPrologue;
1333                     try {
1334                         if (v.owner.kind == TYP && v.owner.isValueClass() && !v.isStatic()) {
1335                             // strict instance initializer in a value class
1336                             initEnv.info.ctorPrologue = true;
1337                         }
1338                         attribExpr(tree.init, initEnv, v.type);
1339                         if (tree.isImplicitlyTyped()) {
1340                             //fixup local variable type
1341                             v.type = chk.checkLocalVarType(tree, tree.init.type, tree.name);
1342                         }
1343                     } finally {
1344                         initEnv.info.ctorPrologue = previousCtorPrologue;
1345                     }
1346                 }
1347                 if (tree.isImplicitlyTyped()) {
1348                     setSyntheticVariableType(tree, v.type);
1349                 }
1350             }
1351             result = tree.type = v.type;
1352             if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1353                 if (isNonArgsMethodInObject(v.name)) {
1354                     log.error(tree, Errors.IllegalRecordComponentName(v));
1355                 }
1356             }
1357         }
1358         finally {
1359             chk.setLint(prevLint);
1360         }
1361     }
1362 
1363     private boolean isNonArgsMethodInObject(Name name) {
1364         for (Symbol s : syms.objectType.tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) {

1433             }
1434         }
1435     }
1436 
1437     public void visitSkip(JCSkip tree) {
1438         result = null;
1439     }
1440 
1441     public void visitBlock(JCBlock tree) {
1442         if (env.info.scope.owner.kind == TYP || env.info.scope.owner.kind == ERR) {
1443             // Block is a static or instance initializer;
1444             // let the owner of the environment be a freshly
1445             // created BLOCK-method.
1446             Symbol fakeOwner =
1447                 new MethodSymbol(tree.flags | BLOCK |
1448                     env.info.scope.owner.flags() & STRICTFP, names.empty, null,
1449                     env.info.scope.owner);
1450             final Env<AttrContext> localEnv =
1451                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1452 
1453             if ((tree.flags & STATIC) != 0) {
1454                 localEnv.info.staticLevel++;
1455             } else {
1456                 localEnv.info.instanceInitializerBlock = true;
1457             }
1458             // Attribute all type annotations in the block
1459             annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
1460             annotate.flush();
1461             attribStats(tree.stats, localEnv);
1462 
1463             {
1464                 // Store init and clinit type annotations with the ClassSymbol
1465                 // to allow output in Gen.normalizeDefs.
1466                 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1467                 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1468                 if ((tree.flags & STATIC) != 0) {
1469                     cs.appendClassInitTypeAttributes(tas);
1470                 } else {
1471                     cs.appendInitTypeAttributes(tas);
1472                 }
1473             }
1474         } else {
1475             // Create a new local environment with a local scope.
1476             Env<AttrContext> localEnv =
1477                 env.dup(tree, env.info.dup(env.info.scope.dup()));

1946     // where
1947     /** Return the selected enumeration constant symbol, or null. */
1948     private Symbol enumConstant(JCTree tree, Type enumType) {
1949         if (tree.hasTag(IDENT)) {
1950             JCIdent ident = (JCIdent)tree;
1951             Name name = ident.name;
1952             for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1953                 if (sym.kind == VAR) {
1954                     Symbol s = ident.sym = sym;
1955                     ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1956                     ident.type = s.type;
1957                     return ((s.flags_field & Flags.ENUM) == 0)
1958                         ? null : s;
1959                 }
1960             }
1961         }
1962         return null;
1963     }
1964 
1965     public void visitSynchronized(JCSynchronized tree) {
1966         boolean identityType = chk.checkIdentityType(tree.pos(), attribExpr(tree.lock, env));
1967         if (env.info.lint.isEnabled(LintCategory.SYNCHRONIZATION) &&
1968                 identityType &&
1969                 isValueBased(tree.lock.type)) {
1970             log.warning(LintCategory.SYNCHRONIZATION, tree.pos(), Warnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
1971         }
1972         attribStat(tree.body, env);
1973         result = null;
1974     }
1975         // where
1976         private boolean isValueBased(Type t) {
1977             return t != null && t.tsym != null && (t.tsym.flags() & VALUE_BASED) != 0;
1978         }
1979 

1980     public void visitTry(JCTry tree) {
1981         // Create a new local environment with a local
1982         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1983         try {
1984             boolean isTryWithResource = tree.resources.nonEmpty();
1985             // Create a nested environment for attributing the try block if needed
1986             Env<AttrContext> tryEnv = isTryWithResource ?
1987                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1988                 localEnv;
1989             try {
1990                 // Attribute resource declarations
1991                 for (JCTree resource : tree.resources) {
1992                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1993                         @Override
1994                         public void report(DiagnosticPosition pos, JCDiagnostic details) {
1995                             chk.basicHandler.report(pos, diags.fragment(Fragments.TryNotApplicableToType(details)));
1996                         }
1997                     };
1998                     ResultInfo twrResult =
1999                         new ResultInfo(KindSelector.VAR,

4414     }
4415 
4416     public void visitSelect(JCFieldAccess tree) {
4417         // Determine the expected kind of the qualifier expression.
4418         KindSelector skind = KindSelector.NIL;
4419         if (tree.name == names._this || tree.name == names._super ||
4420                 tree.name == names._class)
4421         {
4422             skind = KindSelector.TYP;
4423         } else {
4424             if (pkind().contains(KindSelector.PCK))
4425                 skind = KindSelector.of(skind, KindSelector.PCK);
4426             if (pkind().contains(KindSelector.TYP))
4427                 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4428             if (pkind().contains(KindSelector.VAL_MTH))
4429                 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4430         }
4431 
4432         // Attribute the qualifier expression, and determine its symbol (if any).
4433         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4434         Assert.check(site == tree.selected.type);
4435         if (!pkind().contains(KindSelector.TYP_PCK))
4436             site = capture(site); // Capture field access
4437 
4438         // don't allow T.class T[].class, etc
4439         if (skind == KindSelector.TYP) {
4440             Type elt = site;
4441             while (elt.hasTag(ARRAY))
4442                 elt = ((ArrayType)elt).elemtype;
4443             if (elt.hasTag(TYPEVAR)) {
4444                 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4445                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4446                 tree.sym = tree.type.tsym;
4447                 return ;
4448             }
4449         }
4450 
4451         // If qualifier symbol is a type or `super', assert `selectSuper'
4452         // for the selection. This is relevant for determining whether
4453         // protected symbols are accessible.
4454         Symbol sitesym = TreeInfo.symbol(tree.selected);

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

5682                         sym.kind != VAR ||
5683                         sym.getConstValue() == null)
5684                     log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
5685             }
5686         }
5687 
5688         // Check for proper placement of super()/this() calls.
5689         chk.checkSuperInitCalls(tree);
5690 
5691         // Check for cycles among non-initial constructors.
5692         chk.checkCyclicConstructors(tree);
5693 
5694         // Check for cycles among annotation elements.
5695         chk.checkNonCyclicElements(tree);
5696 
5697         // Check for proper use of serialVersionUID and other
5698         // serialization-related fields and methods
5699         if (env.info.lint.isEnabled(LintCategory.SERIAL)
5700                 && rs.isSerializable(c.type)
5701                 && !c.isAnonymous()) {
5702             chk.checkSerialStructure(env, tree, c);
5703         }
5704         // Correctly organize the positions of the type annotations
5705         typeAnnotations.organizeTypeAnnotationsBodies(tree);
5706 
5707         // Check type annotations applicability rules
5708         validateTypeAnnotations(tree, false);
5709     }
5710         // where
5711         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
5712         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
5713             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
5714                 if (types.isSameType(al.head.annotationType.type, t))
5715                     return al.head.pos();
5716             }
5717 
5718             return null;
5719         }
5720 
5721     private Type capture(Type type) {
5722         return types.capture(type);
< prev index next >