< prev index next >

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

Print this page

 288      *  @param v      The assigned variable
 289      *  @param base   If the variable is referred to in a Select, the part
 290      *                to the left of the `.', null otherwise.
 291      *  @param env    The current environment.
 292      */
 293     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
 294         if (v.name == names._this) {
 295             log.error(pos, Errors.CantAssignValToThis);
 296         } else if ((v.flags() & FINAL) != 0 &&
 297             ((v.flags() & HASINIT) != 0
 298              ||
 299              !((base == null ||
 300                TreeInfo.isThisQualifier(base)) &&
 301                isAssignableAsBlankFinal(v, env)))) {
 302             if (v.isResourceVariable()) { //TWR resource
 303                 log.error(pos, Errors.TryResourceMayNotBeAssigned(v));
 304             } else {
 305                 log.error(pos, Errors.CantAssignValToVar(Flags.toSource(v.flags() & (STATIC | FINAL)), v));
 306             }
 307         }











 308     }
 309 
 310     /** Does tree represent a static reference to an identifier?
 311      *  It is assumed that tree is either a SELECT or an IDENT.
 312      *  We have to weed out selects from non-type names here.
 313      *  @param tree    The candidate tree.
 314      */
 315     boolean isStaticReference(JCTree tree) {
 316         if (tree.hasTag(SELECT)) {
 317             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
 318             if (lsym == null || lsym.kind != TYP) {
 319                 return false;
 320             }
 321         }
 322         return true;
 323     }
 324 
 325     /** Is this symbol a type?
 326      */
 327     static boolean isType(Symbol sym) {

1172                 }
1173                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1174                     log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract);
1175             } else {
1176                 if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1177                     if ((owner.flags() & INTERFACE) != 0) {
1178                         log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1179                     } else {
1180                         log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1181                     }
1182                 } else if ((tree.mods.flags & NATIVE) != 0) {
1183                     log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1184                 }
1185                 // Add an implicit super() call unless an explicit call to
1186                 // super(...) or this(...) is given
1187                 // or we are compiling class java.lang.Object.
1188                 if (isConstructor && owner.type != syms.objectType) {
1189                     if (!TreeInfo.hasAnyConstructorCall(tree)) {
1190                         JCStatement supCall = make.at(tree.body.pos).Exec(make.Apply(List.nil(),
1191                                 make.Ident(names._super), make.Idents(List.nil())));
1192                         tree.body.stats = tree.body.stats.prepend(supCall);




1193                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1194                             (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1195                             TreeInfo.hasConstructorCall(tree, names._super)) {
1196                         // enum constructors are not allowed to call super
1197                         // directly, so make sure there aren't any super calls
1198                         // in enum constructors, except in the compiler
1199                         // generated one.
1200                         log.error(tree.body.stats.head.pos(),
1201                                   Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1202                     }
1203                     if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1204                         List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1205                         List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1206                         if (!initParamNames.equals(recordComponentNames)) {
1207                             log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1208                                     Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1209                         }
1210                         if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1211                             log.error(tree,
1212                                     Errors.InvalidCanonicalConstructorInRecord(

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









1310                     }
1311                 }
1312                 if (tree.isImplicitlyTyped()) {
1313                     setSyntheticVariableType(tree, v.type);
1314                 }
1315             }
1316             result = tree.type = v.type;
1317             if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1318                 if (isNonArgsMethodInObject(v.name)) {
1319                     log.error(tree, Errors.IllegalRecordComponentName(v));
1320                 }
1321             }
1322         }
1323         finally {
1324             chk.setLint(prevLint);
1325         }
1326     }
1327 
1328     private boolean isNonArgsMethodInObject(Name name) {
1329         for (Symbol s : syms.objectType.tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) {

1398             }
1399         }
1400     }
1401 
1402     public void visitSkip(JCSkip tree) {
1403         result = null;
1404     }
1405 
1406     public void visitBlock(JCBlock tree) {
1407         if (env.info.scope.owner.kind == TYP || env.info.scope.owner.kind == ERR) {
1408             // Block is a static or instance initializer;
1409             // let the owner of the environment be a freshly
1410             // created BLOCK-method.
1411             Symbol fakeOwner =
1412                 new MethodSymbol(tree.flags | BLOCK |
1413                     env.info.scope.owner.flags() & STRICTFP, names.empty, null,
1414                     env.info.scope.owner);
1415             final Env<AttrContext> localEnv =
1416                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1417 
1418             if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++;




1419             // Attribute all type annotations in the block
1420             annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner, null);
1421             annotate.flush();
1422             attribStats(tree.stats, localEnv);
1423 
1424             {
1425                 // Store init and clinit type annotations with the ClassSymbol
1426                 // to allow output in Gen.normalizeDefs.
1427                 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1428                 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1429                 if ((tree.flags & STATIC) != 0) {
1430                     cs.appendClassInitTypeAttributes(tas);
1431                 } else {
1432                     cs.appendInitTypeAttributes(tas);
1433                 }
1434             }
1435         } else {
1436             // Create a new local environment with a local scope.
1437             Env<AttrContext> localEnv =
1438                 env.dup(tree, env.info.dup(env.info.scope.dup()));

1907     // where
1908     /** Return the selected enumeration constant symbol, or null. */
1909     private Symbol enumConstant(JCTree tree, Type enumType) {
1910         if (tree.hasTag(IDENT)) {
1911             JCIdent ident = (JCIdent)tree;
1912             Name name = ident.name;
1913             for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1914                 if (sym.kind == VAR) {
1915                     Symbol s = ident.sym = sym;
1916                     ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1917                     ident.type = s.type;
1918                     return ((s.flags_field & Flags.ENUM) == 0)
1919                         ? null : s;
1920                 }
1921             }
1922         }
1923         return null;
1924     }
1925 
1926     public void visitSynchronized(JCSynchronized tree) {
1927         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1928         if (env.info.lint.isEnabled(LintCategory.SYNCHRONIZATION) && isValueBased(tree.lock.type)) {


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

4366     }
4367 
4368     public void visitSelect(JCFieldAccess tree) {
4369         // Determine the expected kind of the qualifier expression.
4370         KindSelector skind = KindSelector.NIL;
4371         if (tree.name == names._this || tree.name == names._super ||
4372                 tree.name == names._class)
4373         {
4374             skind = KindSelector.TYP;
4375         } else {
4376             if (pkind().contains(KindSelector.PCK))
4377                 skind = KindSelector.of(skind, KindSelector.PCK);
4378             if (pkind().contains(KindSelector.TYP))
4379                 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4380             if (pkind().contains(KindSelector.VAL_MTH))
4381                 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4382         }
4383 
4384         // Attribute the qualifier expression, and determine its symbol (if any).
4385         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));

4386         if (!pkind().contains(KindSelector.TYP_PCK))
4387             site = capture(site); // Capture field access
4388 
4389         // don't allow T.class T[].class, etc
4390         if (skind == KindSelector.TYP) {
4391             Type elt = site;
4392             while (elt.hasTag(ARRAY))
4393                 elt = ((ArrayType)elt).elemtype;
4394             if (elt.hasTag(TYPEVAR)) {
4395                 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4396                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4397                 tree.sym = tree.type.tsym;
4398                 return ;
4399             }
4400         }
4401 
4402         // If qualifier symbol is a type or `super', assert `selectSuper'
4403         // for the selection. This is relevant for determining whether
4404         // protected symbols are accessible.
4405         Symbol sitesym = TreeInfo.symbol(tree.selected);

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





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

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

 288      *  @param v      The assigned variable
 289      *  @param base   If the variable is referred to in a Select, the part
 290      *                to the left of the `.', null otherwise.
 291      *  @param env    The current environment.
 292      */
 293     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
 294         if (v.name == names._this) {
 295             log.error(pos, Errors.CantAssignValToThis);
 296         } else if ((v.flags() & FINAL) != 0 &&
 297             ((v.flags() & HASINIT) != 0
 298              ||
 299              !((base == null ||
 300                TreeInfo.isThisQualifier(base)) &&
 301                isAssignableAsBlankFinal(v, env)))) {
 302             if (v.isResourceVariable()) { //TWR resource
 303                 log.error(pos, Errors.TryResourceMayNotBeAssigned(v));
 304             } else {
 305                 log.error(pos, Errors.CantAssignValToVar(Flags.toSource(v.flags() & (STATIC | FINAL)), v));
 306             }
 307         }
 308 
 309         if (!env.info.ctorPrologue &&
 310                 v.owner.isValueClass() &&
 311                 !env.info.instanceInitializerBlock && // it is OK instance initializer blocks will go after super() anyways
 312                 v.owner.kind == TYP &&
 313                 v.owner == env.enclClass.sym &&
 314                 (v.flags() & STATIC) == 0 &&
 315                 (base == null ||
 316                         TreeInfo.isExplicitThisReference(types, (ClassType)env.enclClass.type, base))) {
 317             log.error(pos, Errors.CantRefAfterCtorCalled(v));
 318         }
 319     }
 320 
 321     /** Does tree represent a static reference to an identifier?
 322      *  It is assumed that tree is either a SELECT or an IDENT.
 323      *  We have to weed out selects from non-type names here.
 324      *  @param tree    The candidate tree.
 325      */
 326     boolean isStaticReference(JCTree tree) {
 327         if (tree.hasTag(SELECT)) {
 328             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
 329             if (lsym == null || lsym.kind != TYP) {
 330                 return false;
 331             }
 332         }
 333         return true;
 334     }
 335 
 336     /** Is this symbol a type?
 337      */
 338     static boolean isType(Symbol sym) {

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

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

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

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

1969     public void visitTry(JCTry tree) {
1970         // Create a new local environment with a local
1971         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1972         try {
1973             boolean isTryWithResource = tree.resources.nonEmpty();
1974             // Create a nested environment for attributing the try block if needed
1975             Env<AttrContext> tryEnv = isTryWithResource ?
1976                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1977                 localEnv;
1978             try {
1979                 // Attribute resource declarations
1980                 for (JCTree resource : tree.resources) {
1981                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1982                         @Override
1983                         public void report(DiagnosticPosition pos, JCDiagnostic details) {
1984                             chk.basicHandler.report(pos, diags.fragment(Fragments.TryNotApplicableToType(details)));
1985                         }
1986                     };
1987                     ResultInfo twrResult =
1988                         new ResultInfo(KindSelector.VAR,

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

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

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