< 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) {

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




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

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









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

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




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

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


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

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

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

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





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

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

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

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

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

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

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

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

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

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