< prev index next >

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

Print this page

 107     final Analyzer analyzer;
 108     final DeferredAttr deferredAttr;
 109     final Check chk;
 110     final Flow flow;
 111     final MemberEnter memberEnter;
 112     final TypeEnter typeEnter;
 113     final TreeMaker make;
 114     final ConstFold cfolder;
 115     final Enter enter;
 116     final Target target;
 117     final Types types;
 118     final Preview preview;
 119     final JCDiagnostic.Factory diags;
 120     final TypeAnnotations typeAnnotations;
 121     final TypeEnvs typeEnvs;
 122     final Dependencies dependencies;
 123     final Annotate annotate;
 124     final ArgumentAttr argumentAttr;
 125     final MatchBindingsComputer matchBindingsComputer;
 126     final AttrRecover attrRecover;

 127 
 128     public static Attr instance(Context context) {
 129         Attr instance = context.get(attrKey);
 130         if (instance == null)
 131             instance = new Attr(context);
 132         return instance;
 133     }
 134 
 135     @SuppressWarnings("this-escape")
 136     protected Attr(Context context) {
 137         context.put(attrKey, this);
 138 
 139         names = Names.instance(context);
 140         log = Log.instance(context);
 141         lintMapper = LintMapper.instance(context);
 142         syms = Symtab.instance(context);
 143         rs = Resolve.instance(context);
 144         operators = Operators.instance(context);
 145         chk = Check.instance(context);
 146         flow = Flow.instance(context);
 147         memberEnter = MemberEnter.instance(context);
 148         typeEnter = TypeEnter.instance(context);
 149         make = TreeMaker.instance(context);
 150         enter = Enter.instance(context);
 151         infer = Infer.instance(context);
 152         analyzer = Analyzer.instance(context);
 153         deferredAttr = DeferredAttr.instance(context);
 154         cfolder = ConstFold.instance(context);
 155         target = Target.instance(context);
 156         types = Types.instance(context);
 157         preview = Preview.instance(context);
 158         diags = JCDiagnostic.Factory.instance(context);
 159         annotate = Annotate.instance(context);
 160         typeAnnotations = TypeAnnotations.instance(context);
 161         typeEnvs = TypeEnvs.instance(context);
 162         dependencies = Dependencies.instance(context);
 163         argumentAttr = ArgumentAttr.instance(context);
 164         matchBindingsComputer = MatchBindingsComputer.instance(context);
 165         attrRecover = AttrRecover.instance(context);

 166 
 167         Options options = Options.instance(context);
 168 
 169         Source source = Source.instance(context);
 170         allowReifiableTypesInInstanceof = Feature.REIFIABLE_TYPES_INSTANCEOF.allowedInSource(source);
 171         allowRecords = Feature.RECORDS.allowedInSource(source);
 172         allowPatternSwitch = (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH)) &&
 173                              Feature.PATTERN_SWITCH.allowedInSource(source);
 174         allowUnconditionalPatternsInstanceOf =
 175                              Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.allowedInSource(source);
 176         sourceName = source.name;
 177         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
 178 
 179         statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
 180         varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
 181         unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
 182         methodAttrInfo = new MethodAttrInfo();
 183         unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
 184         unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
 185         recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
 186         initBlockType = new MethodType(List.nil(), syms.voidType, List.nil(), syms.methodClass);


 187     }
 188 
 189     /** Switch: reifiable types in instanceof enabled?
 190      */
 191     boolean allowReifiableTypesInInstanceof;
 192 
 193     /** Are records allowed
 194      */
 195     private final boolean allowRecords;
 196 
 197     /** Are patterns in switch allowed
 198      */
 199     private final boolean allowPatternSwitch;
 200 
 201     /** Are unconditional patterns in instanceof allowed
 202      */
 203     private final boolean allowUnconditionalPatternsInstanceOf;
 204 




 205     /**
 206      * Switch: warn about use of variable before declaration?
 207      * RFE: 6425594
 208      */
 209     boolean useBeforeDeclarationWarning;
 210 
 211     /**
 212      * Switch: name of source level; used for error reporting.
 213      */
 214     String sourceName;
 215 
 216     /** Check kind and type of given tree against protokind and prototype.
 217      *  If check succeeds, store type in tree and return it.
 218      *  If check fails, store errType in tree and return it.
 219      *  No checks are performed if the prototype is a method type.
 220      *  It is not necessary in this case since we know that kind and type
 221      *  are correct.
 222      *
 223      *  @param tree     The tree whose kind and type is checked
 224      *  @param found    The computed type of the tree

 278               owner.kind == VAR ||           // i.e. we are in a variable initializer
 279               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
 280              &&
 281              v.owner == owner.owner
 282              &&
 283              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
 284         boolean insideCompactConstructor = env.enclMethod != null && TreeInfo.isCompactConstructor(env.enclMethod);
 285         return isAssignable & !insideCompactConstructor;
 286     }
 287 
 288     /** Check that variable can be assigned to.
 289      *  @param pos    The current source code position.
 290      *  @param v      The assigned variable
 291      *  @param base   If the variable is referred to in a Select, the part
 292      *                to the left of the `.', null otherwise.
 293      *  @param env    The current environment.
 294      */
 295     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
 296         if (v.name == names._this) {
 297             log.error(pos, Errors.CantAssignValToThis);
 298             return;
 299         }
 300         if ((v.flags() & FINAL) != 0 &&
 301             ((v.flags() & HASINIT) != 0
 302              ||
 303              !((base == null ||
 304                TreeInfo.isThisQualifier(base)) &&
 305                isAssignableAsBlankFinal(v, env)))) {
 306             if (v.isResourceVariable()) { //TWR resource
 307                 log.error(pos, Errors.TryResourceMayNotBeAssigned(v));
 308             } else {
 309                 log.error(pos, Errors.CantAssignValToVar(Flags.toSource(v.flags() & (STATIC | FINAL)), v));
 310             }
 311             return;
 312         }
 313 
 314         // Check instance field assignments that appear in constructor prologues
 315         if (rs.isEarlyReference(env, base, v)) {
 316 
 317             // Field may not be inherited from a superclass
 318             if (v.owner != env.enclClass.sym) {
 319                 log.error(pos, Errors.CantRefBeforeCtorCalled(v));
 320                 return;
 321             }
 322 
 323             // Field may not have an initializer
 324             if ((v.flags() & HASINIT) != 0) {
 325                 log.error(pos, Errors.CantAssignInitializedBeforeCtorCalled(v));
 326                 return;
 327             }
 328         }
 329     }
 330 
 331     /** Does tree represent a static reference to an identifier?
 332      *  It is assumed that tree is either a SELECT or an IDENT.
 333      *  We have to weed out selects from non-type names here.
 334      *  @param tree    The candidate tree.
 335      */
 336     boolean isStaticReference(JCTree tree) {
 337         if (tree.hasTag(SELECT)) {
 338             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
 339             if (lsym == null || lsym.kind != TYP) {
 340                 return false;
 341             }
 342         }
 343         return true;
 344     }
 345 
 346     /** Is this symbol a type?
 347      */

1102                          *     - have an accessibility stricter than that of the record type
1103                          *     - explicitly invoke any other constructor
1104                          */
1105                         if ((tree.sym.flags_field & GENERATEDCONSTR) == 0) {
1106                             if (Check.protection(m.flags()) > Check.protection(env.enclClass.sym.flags())) {
1107                                 log.error(tree,
1108                                         (env.enclClass.sym.flags() & AccessFlags) == 0 ?
1109                                             Errors.InvalidCanonicalConstructorInRecord(
1110                                                 Fragments.Canonical,
1111                                                 env.enclClass.sym.name,
1112                                                 Fragments.CanonicalMustNotHaveStrongerAccess("package")
1113                                             ) :
1114                                             Errors.InvalidCanonicalConstructorInRecord(
1115                                                     Fragments.Canonical,
1116                                                     env.enclClass.sym.name,
1117                                                     Fragments.CanonicalMustNotHaveStrongerAccess(asFlagSet(env.enclClass.sym.flags() & AccessFlags))
1118                                             )
1119                                 );
1120                             }
1121 
1122                             if (TreeInfo.hasAnyConstructorCall(tree)) {
1123                                 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1124                                         Fragments.Canonical, env.enclClass.sym.name,
1125                                         Fragments.CanonicalMustNotContainExplicitConstructorInvocation));
1126                             }
1127                         }
1128 
1129                         // also we want to check that no type variables have been defined
1130                         if (!tree.typarams.isEmpty()) {
1131                             log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1132                                     Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalMustNotDeclareTypeVariables));
1133                         }
1134 
1135                         /* and now we need to check that the constructor's arguments are exactly the same as those of the
1136                          * record components
1137                          */
1138                         List<? extends RecordComponent> recordComponents = env.enclClass.sym.getRecordComponents();
1139                         List<Type> recordFieldTypes = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.type);
1140                         for (JCVariableDecl param: tree.params) {
1141                             boolean paramIsVarArgs = (param.sym.flags_field & VARARGS) != 0;
1142                             if (!types.isSameType(param.type, recordFieldTypes.head) ||

1180                 if (tree.defaultValue != null) {
1181                     if ((owner.flags() & ANNOTATION) == 0)
1182                         log.error(tree.pos(),
1183                                   Errors.DefaultAllowedInIntfAnnotationMember);
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(
1225                                             TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical,
1226                                             env.enclClass.sym.name,
1227                                             Fragments.ThrowsClauseNotAllowedForCanonicalConstructor(
1228                                                     TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical)));
1229                         }
1230                     }
1231                 }
1232 
1233                 // Attribute all type annotations in the body
1234                 annotate.queueScanTreeAndTypeAnnotate(tree.body, localEnv, m);
1235                 annotate.flush();
1236 
1237                 // Start of constructor prologue (if not in java.lang.Object constructor)
1238                 localEnv.info.ctorPrologue = isConstructor && owner.type != syms.objectType;
1239 
1240                 // Attribute method body.
1241                 attribStat(tree.body, localEnv);




























1242             }
1243 
1244             localEnv.info.scope.leave();
1245             result = tree.type = m.type;
1246         } finally {
1247             chk.setLint(prevLint);
1248             chk.setMethod(prevMethod);
1249             env.info.ctorPrologue = ctorProloguePrev;
1250         }
1251     }
1252 




















































































































































































































































































1253     public void visitVarDef(JCVariableDecl tree) {
1254         // Local variables have not been entered yet, so we need to do it now:
1255         if (env.info.scope.owner.kind == MTH || env.info.scope.owner.kind == VAR) {
1256             if (tree.sym != null) {
1257                 // parameters have already been entered
1258                 env.info.scope.enter(tree.sym);
1259             } else {
1260                 if (tree.isImplicitlyTyped() && (tree.getModifiers().flags & PARAMETER) == 0) {
1261                     if (tree.init == null) {
1262                         //cannot use 'var' without initializer
1263                         log.error(tree, Errors.CantInferLocalVarType(tree.name, Fragments.LocalMissingInit));
1264                         tree.vartype = make.Erroneous();
1265                     } else {
1266                         Fragment msg = canInferLocalVarType(tree);
1267                         if (msg != null) {
1268                             //cannot use 'var' with initializer which require an explicit target
1269                             //(e.g. lambda, method reference, array initializer).
1270                             log.error(tree, Errors.CantInferLocalVarType(tree.name, msg));
1271                             tree.vartype = make.Erroneous();
1272                         }

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















1317                     }
1318                 }
1319                 if (tree.isImplicitlyTyped()) {
1320                     setSyntheticVariableType(tree, v.type);
1321                 }
1322             }
1323             result = tree.type = v.type;
1324             if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1325                 if (isNonArgsMethodInObject(v.name)) {
1326                     log.error(tree, Errors.IllegalRecordComponentName(v));
1327                 }
1328             }
1329             chk.checkRequiresIdentity(tree, env.info.lint);
1330         }
1331         finally {
1332             chk.setLint(prevLint);
1333         }
1334     }
1335 
1336     private void doQueueScanTreeAndTypeAnnotateForVarInit(JCVariableDecl tree, Env<AttrContext> env) {

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




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

1930     // where
1931     /** Return the selected enumeration constant symbol, or null. */
1932     private Symbol enumConstant(JCTree tree, Type enumType) {
1933         if (tree.hasTag(IDENT)) {
1934             JCIdent ident = (JCIdent)tree;
1935             Name name = ident.name;
1936             for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
1937                 if (sym.kind == VAR) {
1938                     Symbol s = ident.sym = sym;
1939                     ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
1940                     ident.type = s.type;
1941                     return ((s.flags_field & Flags.ENUM) == 0)
1942                         ? null : s;
1943                 }
1944             }
1945         }
1946         return null;
1947     }
1948 
1949     public void visitSynchronized(JCSynchronized tree) {
1950         chk.checkRefType(tree.pos(), attribExpr(tree.lock, env));
1951         if (tree.lock.type != null && tree.lock.type.isValueBased()) {
1952             log.warning(tree.pos(), LintWarnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
1953         }
1954         attribStat(tree.body, env);
1955         result = null;
1956     }
1957 
1958     public void visitTry(JCTry tree) {
1959         // Create a new local environment with a local
1960         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
1961         try {
1962             boolean isTryWithResource = tree.resources.nonEmpty();
1963             // Create a nested environment for attributing the try block if needed
1964             Env<AttrContext> tryEnv = isTryWithResource ?
1965                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
1966                 localEnv;
1967             try {
1968                 // Attribute resource declarations
1969                 for (JCTree resource : tree.resources) {
1970                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
1971                         @Override

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

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

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





5542                 attribClassBody(env, c);
5543 
5544                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5545                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5546                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5547                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5548 
5549                 if (c.isImplicit()) {
5550                     chk.checkHasMain(env.tree.pos(), c);
5551                 }
5552             } finally {
5553                 env.info.returnResult = prevReturnRes;
5554                 log.useSource(prev);
5555                 chk.setLint(prevLint);
5556             }
5557 
5558         }
5559     }
5560 
5561     public void visitImport(JCImport tree) {

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

 107     final Analyzer analyzer;
 108     final DeferredAttr deferredAttr;
 109     final Check chk;
 110     final Flow flow;
 111     final MemberEnter memberEnter;
 112     final TypeEnter typeEnter;
 113     final TreeMaker make;
 114     final ConstFold cfolder;
 115     final Enter enter;
 116     final Target target;
 117     final Types types;
 118     final Preview preview;
 119     final JCDiagnostic.Factory diags;
 120     final TypeAnnotations typeAnnotations;
 121     final TypeEnvs typeEnvs;
 122     final Dependencies dependencies;
 123     final Annotate annotate;
 124     final ArgumentAttr argumentAttr;
 125     final MatchBindingsComputer matchBindingsComputer;
 126     final AttrRecover attrRecover;
 127     final LocalProxyVarsGen localProxyVarsGen;
 128 
 129     public static Attr instance(Context context) {
 130         Attr instance = context.get(attrKey);
 131         if (instance == null)
 132             instance = new Attr(context);
 133         return instance;
 134     }
 135 
 136     @SuppressWarnings("this-escape")
 137     protected Attr(Context context) {
 138         context.put(attrKey, this);
 139 
 140         names = Names.instance(context);
 141         log = Log.instance(context);
 142         lintMapper = LintMapper.instance(context);
 143         syms = Symtab.instance(context);
 144         rs = Resolve.instance(context);
 145         operators = Operators.instance(context);
 146         chk = Check.instance(context);
 147         flow = Flow.instance(context);
 148         memberEnter = MemberEnter.instance(context);
 149         typeEnter = TypeEnter.instance(context);
 150         make = TreeMaker.instance(context);
 151         enter = Enter.instance(context);
 152         infer = Infer.instance(context);
 153         analyzer = Analyzer.instance(context);
 154         deferredAttr = DeferredAttr.instance(context);
 155         cfolder = ConstFold.instance(context);
 156         target = Target.instance(context);
 157         types = Types.instance(context);
 158         preview = Preview.instance(context);
 159         diags = JCDiagnostic.Factory.instance(context);
 160         annotate = Annotate.instance(context);
 161         typeAnnotations = TypeAnnotations.instance(context);
 162         typeEnvs = TypeEnvs.instance(context);
 163         dependencies = Dependencies.instance(context);
 164         argumentAttr = ArgumentAttr.instance(context);
 165         matchBindingsComputer = MatchBindingsComputer.instance(context);
 166         attrRecover = AttrRecover.instance(context);
 167         localProxyVarsGen = LocalProxyVarsGen.instance(context);
 168 
 169         Options options = Options.instance(context);
 170 
 171         Source source = Source.instance(context);
 172         allowReifiableTypesInInstanceof = Feature.REIFIABLE_TYPES_INSTANCEOF.allowedInSource(source);
 173         allowRecords = Feature.RECORDS.allowedInSource(source);
 174         allowPatternSwitch = (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH)) &&
 175                              Feature.PATTERN_SWITCH.allowedInSource(source);
 176         allowUnconditionalPatternsInstanceOf =
 177                              Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.allowedInSource(source);
 178         sourceName = source.name;
 179         useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
 180 
 181         statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
 182         varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
 183         unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
 184         methodAttrInfo = new MethodAttrInfo();
 185         unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
 186         unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
 187         recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
 188         initBlockType = new MethodType(List.nil(), syms.voidType, List.nil(), syms.methodClass);
 189         allowValueClasses = (!preview.isPreview(Feature.VALUE_CLASSES) || preview.isEnabled()) &&
 190                 Feature.VALUE_CLASSES.allowedInSource(source);
 191     }
 192 
 193     /** Switch: reifiable types in instanceof enabled?
 194      */
 195     boolean allowReifiableTypesInInstanceof;
 196 
 197     /** Are records allowed
 198      */
 199     private final boolean allowRecords;
 200 
 201     /** Are patterns in switch allowed
 202      */
 203     private final boolean allowPatternSwitch;
 204 
 205     /** Are unconditional patterns in instanceof allowed
 206      */
 207     private final boolean allowUnconditionalPatternsInstanceOf;
 208 
 209     /** Are value classes allowed
 210      */
 211     private final boolean allowValueClasses;
 212 
 213     /**
 214      * Switch: warn about use of variable before declaration?
 215      * RFE: 6425594
 216      */
 217     boolean useBeforeDeclarationWarning;
 218 
 219     /**
 220      * Switch: name of source level; used for error reporting.
 221      */
 222     String sourceName;
 223 
 224     /** Check kind and type of given tree against protokind and prototype.
 225      *  If check succeeds, store type in tree and return it.
 226      *  If check fails, store errType in tree and return it.
 227      *  No checks are performed if the prototype is a method type.
 228      *  It is not necessary in this case since we know that kind and type
 229      *  are correct.
 230      *
 231      *  @param tree     The tree whose kind and type is checked
 232      *  @param found    The computed type of the tree

 286               owner.kind == VAR ||           // i.e. we are in a variable initializer
 287               (owner.flags() & BLOCK) != 0)  // i.e. we are in an initializer block
 288              &&
 289              v.owner == owner.owner
 290              &&
 291              ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
 292         boolean insideCompactConstructor = env.enclMethod != null && TreeInfo.isCompactConstructor(env.enclMethod);
 293         return isAssignable & !insideCompactConstructor;
 294     }
 295 
 296     /** Check that variable can be assigned to.
 297      *  @param pos    The current source code position.
 298      *  @param v      The assigned variable
 299      *  @param base   If the variable is referred to in a Select, the part
 300      *                to the left of the `.', null otherwise.
 301      *  @param env    The current environment.
 302      */
 303     void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
 304         if (v.name == names._this) {
 305             log.error(pos, Errors.CantAssignValToThis);
 306         } else if ((v.flags() & FINAL) != 0 &&


 307             ((v.flags() & HASINIT) != 0
 308              ||
 309              !((base == null ||
 310                TreeInfo.isThisQualifier(base)) &&
 311                isAssignableAsBlankFinal(v, env)))) {
 312             if (v.isResourceVariable()) { //TWR resource
 313                 log.error(pos, Errors.TryResourceMayNotBeAssigned(v));
 314             } else {
 315                 log.error(pos, Errors.CantAssignValToVar(Flags.toSource(v.flags() & (STATIC | FINAL)), v));
 316             }

















 317         }
 318     }
 319 
 320     /** Does tree represent a static reference to an identifier?
 321      *  It is assumed that tree is either a SELECT or an IDENT.
 322      *  We have to weed out selects from non-type names here.
 323      *  @param tree    The candidate tree.
 324      */
 325     boolean isStaticReference(JCTree tree) {
 326         if (tree.hasTag(SELECT)) {
 327             Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
 328             if (lsym == null || lsym.kind != TYP) {
 329                 return false;
 330             }
 331         }
 332         return true;
 333     }
 334 
 335     /** Is this symbol a type?
 336      */

1091                          *     - have an accessibility stricter than that of the record type
1092                          *     - explicitly invoke any other constructor
1093                          */
1094                         if ((tree.sym.flags_field & GENERATEDCONSTR) == 0) {
1095                             if (Check.protection(m.flags()) > Check.protection(env.enclClass.sym.flags())) {
1096                                 log.error(tree,
1097                                         (env.enclClass.sym.flags() & AccessFlags) == 0 ?
1098                                             Errors.InvalidCanonicalConstructorInRecord(
1099                                                 Fragments.Canonical,
1100                                                 env.enclClass.sym.name,
1101                                                 Fragments.CanonicalMustNotHaveStrongerAccess("package")
1102                                             ) :
1103                                             Errors.InvalidCanonicalConstructorInRecord(
1104                                                     Fragments.Canonical,
1105                                                     env.enclClass.sym.name,
1106                                                     Fragments.CanonicalMustNotHaveStrongerAccess(asFlagSet(env.enclClass.sym.flags() & AccessFlags))
1107                                             )
1108                                 );
1109                             }
1110 
1111                             if (!allowValueClasses && TreeInfo.hasAnyConstructorCall(tree)) {
1112                                 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1113                                         Fragments.Canonical, env.enclClass.sym.name,
1114                                         Fragments.CanonicalMustNotContainExplicitConstructorInvocation));
1115                             }
1116                         }
1117 
1118                         // also we want to check that no type variables have been defined
1119                         if (!tree.typarams.isEmpty()) {
1120                             log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1121                                     Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalMustNotDeclareTypeVariables));
1122                         }
1123 
1124                         /* and now we need to check that the constructor's arguments are exactly the same as those of the
1125                          * record components
1126                          */
1127                         List<? extends RecordComponent> recordComponents = env.enclClass.sym.getRecordComponents();
1128                         List<Type> recordFieldTypes = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.type);
1129                         for (JCVariableDecl param: tree.params) {
1130                             boolean paramIsVarArgs = (param.sym.flags_field & VARARGS) != 0;
1131                             if (!types.isSameType(param.type, recordFieldTypes.head) ||

1169                 if (tree.defaultValue != null) {
1170                     if ((owner.flags() & ANNOTATION) == 0)
1171                         log.error(tree.pos(),
1172                                   Errors.DefaultAllowedInIntfAnnotationMember);
1173                 }
1174                 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1175                     log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract);
1176             } else {
1177                 if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1178                     if ((owner.flags() & INTERFACE) != 0) {
1179                         log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1180                     } else {
1181                         log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1182                     }
1183                 } else if ((tree.mods.flags & NATIVE) != 0) {
1184                     log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1185                 }
1186                 // Add an implicit super() call unless an explicit call to
1187                 // super(...) or this(...) is given
1188                 // or we are compiling class java.lang.Object.
1189                 boolean addedSuperInIdentityClass = false;
1190                 if (isConstructor && owner.type != syms.objectType) {
1191                     if (!TreeInfo.hasAnyConstructorCall(tree)) {
1192                         JCStatement supCall = make.at(tree.body.pos).Exec(make.Apply(List.nil(),
1193                                 make.Ident(names._super), make.Idents(List.nil())));
1194                         if (allowValueClasses && (owner.isValueClass() || owner.hasStrict() || ((owner.flags_field & RECORD) != 0))) {
1195                             tree.body.stats = tree.body.stats.append(supCall);
1196                         } else {
1197                             tree.body.stats = tree.body.stats.prepend(supCall);
1198                             addedSuperInIdentityClass = true;
1199                         }
1200                     } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1201                             (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1202                             TreeInfo.hasConstructorCall(tree, names._super)) {
1203                         // enum constructors are not allowed to call super
1204                         // directly, so make sure there aren't any super calls
1205                         // in enum constructors, except in the compiler
1206                         // generated one.
1207                         log.error(tree.body.stats.head.pos(),
1208                                   Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1209                     }
1210                     if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1211                         List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1212                         List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1213                         if (!initParamNames.equals(recordComponentNames)) {
1214                             log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1215                                     Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1216                         }
1217                         if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1218                             log.error(tree,
1219                                     Errors.InvalidCanonicalConstructorInRecord(
1220                                             TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical,
1221                                             env.enclClass.sym.name,
1222                                             Fragments.ThrowsClauseNotAllowedForCanonicalConstructor(
1223                                                     TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical)));
1224                         }
1225                     }
1226                 }
1227 
1228                 // Attribute all type annotations in the body
1229                 annotate.queueScanTreeAndTypeAnnotate(tree.body, localEnv, m);
1230                 annotate.flush();
1231 
1232                 // Start of constructor prologue (if not in java.lang.Object constructor)
1233                 localEnv.info.ctorPrologue = isConstructor && owner.type != syms.objectType;
1234 
1235                 // Attribute method body.
1236                 attribStat(tree.body, localEnv);
1237                 if (localEnv.info.ctorPrologue) {
1238                     boolean thisInvocation = false;
1239                     ListBuffer<JCTree> prologueCode = new ListBuffer<>();
1240                     for (JCTree stat : tree.body.stats) {
1241                         prologueCode.add(stat);
1242                         /* gather all the stats in the body until a `super` or `this` constructor invocation is found,
1243                          * including the constructor invocation, that way we don't need to worry in the visitor below if
1244                          * if we are dealing or not with prologue code
1245                          */
1246                         if (stat instanceof JCExpressionStatement expStmt &&
1247                                 expStmt.expr instanceof JCMethodInvocation mi &&
1248                                 TreeInfo.isConstructorCall(mi)) {
1249                             thisInvocation = TreeInfo.name(mi.meth) == names._this;
1250                             if (!addedSuperInIdentityClass || !allowValueClasses) {
1251                                 break;
1252                             }
1253                         }
1254                     }
1255                     if (!prologueCode.isEmpty()) {
1256                         CtorPrologueVisitor ctorPrologueVisitor = new CtorPrologueVisitor(localEnv,
1257                                 addedSuperInIdentityClass && allowValueClasses ?
1258                                         PrologueVisitorMode.WARNINGS_ONLY :
1259                                         thisInvocation ?
1260                                                 PrologueVisitorMode.THIS_CONSTRUCTOR :
1261                                                 PrologueVisitorMode.SUPER_CONSTRUCTOR);
1262                         ctorPrologueVisitor.scan(prologueCode.toList());
1263                     }
1264                 }
1265             }
1266 
1267             localEnv.info.scope.leave();
1268             result = tree.type = m.type;
1269         } finally {
1270             chk.setLint(prevLint);
1271             chk.setMethod(prevMethod);
1272             env.info.ctorPrologue = ctorProloguePrev;
1273         }
1274     }
1275 
1276     enum PrologueVisitorMode {
1277         WARNINGS_ONLY,
1278         SUPER_CONSTRUCTOR,
1279         THIS_CONSTRUCTOR
1280     }
1281 
1282     class CtorPrologueVisitor extends TreeScanner {
1283         Env<AttrContext> localEnv;
1284         PrologueVisitorMode mode;
1285 
1286         CtorPrologueVisitor(Env<AttrContext> localEnv, PrologueVisitorMode mode) {
1287             this.localEnv = localEnv;
1288             currentClassSym = localEnv.enclClass.sym;
1289             this.mode = mode;
1290         }
1291 
1292         boolean insideLambdaOrClassDef = false;
1293 
1294         @Override
1295         public void visitLambda(JCLambda lambda) {
1296             boolean previousInsideLambdaOrClassDef = insideLambdaOrClassDef;
1297             try {
1298                 insideLambdaOrClassDef = true;
1299                 super.visitLambda(lambda);
1300             } finally {
1301                 insideLambdaOrClassDef = previousInsideLambdaOrClassDef;
1302             }
1303         }
1304 
1305         ClassSymbol currentClassSym;
1306 
1307         @Override
1308         public void visitClassDef(JCClassDecl classDecl) {
1309             boolean previousInsideLambdaOrClassDef = insideLambdaOrClassDef;
1310             ClassSymbol previousClassSym = currentClassSym;
1311             try {
1312                 insideLambdaOrClassDef = true;
1313                 currentClassSym = classDecl.sym;
1314                 super.visitClassDef(classDecl);
1315             } finally {
1316                 insideLambdaOrClassDef = previousInsideLambdaOrClassDef;
1317                 currentClassSym = previousClassSym;
1318             }
1319         }
1320 
1321         private void reportPrologueError(JCTree tree, Symbol sym) {
1322             reportPrologueError(tree, sym, false);
1323         }
1324 
1325         private void reportPrologueError(JCTree tree, Symbol sym, boolean hasInit) {
1326             preview.checkSourceLevel(tree, Feature.FLEXIBLE_CONSTRUCTORS);
1327             if (mode != PrologueVisitorMode.WARNINGS_ONLY) {
1328                 if (hasInit) {
1329                     log.error(tree, Errors.CantAssignInitializedBeforeCtorCalled(sym));
1330                 } else {
1331                     log.error(tree, Errors.CantRefBeforeCtorCalled(sym));
1332                 }
1333             } else if (allowValueClasses) {
1334                 // issue lint warning
1335                 log.warning(tree, LintWarnings.WouldNotBeAllowedInPrologue(sym));
1336             }
1337         }
1338 
1339         @Override
1340         public void visitApply(JCMethodInvocation tree) {
1341             super.visitApply(tree);
1342             Name name = TreeInfo.name(tree.meth);
1343             boolean isConstructorCall = name == names._this || name == names._super;
1344             Symbol msym = TreeInfo.symbolFor(tree.meth);
1345             // is this an instance method call or an illegal constructor invocation like: `this.super()`?
1346             if (msym != null && // for erroneous invocations msym can be null, ignore those
1347                 (!isConstructorCall ||
1348                 isConstructorCall && tree.meth.hasTag(SELECT))) {
1349                 if (isEarlyReference(localEnv, tree.meth, msym))
1350                     reportPrologueError(tree.meth, msym);
1351             }
1352         }
1353 
1354         @Override
1355         public void visitIdent(JCIdent tree) {
1356             analyzeSymbol(tree);
1357         }
1358 
1359         @Override
1360         public void visitSelect(JCFieldAccess tree) {
1361             SelectScanner ss = new SelectScanner();
1362             ss.scan(tree);
1363             if (ss.scanLater == null) {
1364                 analyzeSymbol(tree);
1365             } else {
1366                 boolean prevLhs = isInLHS;
1367                 try {
1368                     isInLHS = false;
1369                     scan(ss.scanLater);
1370                 } finally {
1371                     isInLHS = prevLhs;
1372                 }
1373             }
1374         }
1375 
1376         @Override
1377         public void visitNewClass(JCNewClass tree) {
1378             super.visitNewClass(tree);
1379             checkNewClassAndMethRefs(tree, tree.type);
1380         }
1381 
1382         @Override
1383         public void visitReference(JCMemberReference tree) {
1384             super.visitReference(tree);
1385             if (tree.getMode() == JCMemberReference.ReferenceMode.NEW) {
1386                 checkNewClassAndMethRefs(tree, tree.expr.type);
1387             }
1388         }
1389 
1390         void checkNewClassAndMethRefs(JCTree tree, Type t) {
1391             if (t.tsym.isEnclosedBy(localEnv.enclClass.sym) &&
1392                     !t.tsym.isStatic() &&
1393                     !t.tsym.isDirectlyOrIndirectlyLocal()) {
1394                 reportPrologueError(tree, t.getEnclosingType().tsym);
1395             }
1396         }
1397 
1398         /* if a symbol is in the LHS of an assignment expression we won't consider it as a candidate
1399          * for a proxy local variable later on
1400          */
1401         boolean isInLHS = false;
1402 
1403         @Override
1404         public void visitAssign(JCAssign tree) {
1405             boolean previousIsInLHS = isInLHS;
1406             try {
1407                 isInLHS = true;
1408                 scan(tree.lhs);
1409             } finally {
1410                 isInLHS = previousIsInLHS;
1411             }
1412             scan(tree.rhs);
1413         }
1414 
1415         @Override
1416         public void visitMethodDef(JCMethodDecl tree) {
1417             // ignore any declarative part, mainly to avoid scanning receiver parameters
1418             scan(tree.body);
1419         }
1420 
1421         void analyzeSymbol(JCTree tree) {
1422             Symbol sym = TreeInfo.symbolFor(tree);
1423             // make sure that there is a symbol and it is not static
1424             if (sym == null || sym.isStatic()) {
1425                 return;
1426             }
1427             if (isInLHS && !insideLambdaOrClassDef) {
1428                 // Check instance field assignments that appear in constructor prologues
1429                 if (isEarlyReference(localEnv, tree, sym)) {
1430                     // Field may not be inherited from a superclass
1431                     if (sym.owner != localEnv.enclClass.sym) {
1432                         reportPrologueError(tree, sym);
1433                         return;
1434                     }
1435                     // Field may not have an initializer
1436                     if ((sym.flags() & HASINIT) != 0) {
1437                         reportPrologueError(tree, sym, true);
1438                         return;
1439                     }
1440                     // cant reference an instance field before a this constructor
1441                     if (allowValueClasses && mode == PrologueVisitorMode.THIS_CONSTRUCTOR) {
1442                         reportPrologueError(tree, sym);
1443                         return;
1444                     }
1445                 }
1446                 return;
1447             }
1448             tree = TreeInfo.skipParens(tree);
1449             if (sym.kind == VAR && sym.owner.kind == TYP) {
1450                 if (sym.name == names._this || sym.name == names._super) {
1451                     // are we seeing something like `this` or `CurrentClass.this` or `SuperClass.super::foo`?
1452                     if (TreeInfo.isExplicitThisReference(
1453                             types,
1454                             (ClassType)localEnv.enclClass.sym.type,
1455                             tree)) {
1456                         reportPrologueError(tree, sym);
1457                     }
1458                 } else if (sym.kind == VAR && sym.owner.kind == TYP) { // now fields only
1459                     if (sym.owner != localEnv.enclClass.sym) {
1460                         if (localEnv.enclClass.sym.isSubClass(sym.owner, types) &&
1461                                 sym.isInheritedIn(localEnv.enclClass.sym, types)) {
1462                             /* if we are dealing with a field that doesn't belong to the current class, but the
1463                              * field is inherited, this is an error. Unless, the super class is also an outer
1464                              * class and the field's qualifier refers to the outer class
1465                              */
1466                             if (tree.hasTag(IDENT) ||
1467                                 TreeInfo.isExplicitThisReference(
1468                                         types,
1469                                         (ClassType)localEnv.enclClass.sym.type,
1470                                         ((JCFieldAccess)tree).selected)) {
1471                                 reportPrologueError(tree, sym);
1472                             }
1473                         }
1474                     } else if (isEarlyReference(localEnv, tree, sym)) {
1475                         /* now this is a `proper` instance field of the current class
1476                          * references to fields of identity classes which happen to have initializers are
1477                          * not allowed in the prologue
1478                          */
1479                         if (insideLambdaOrClassDef ||
1480                             (!localEnv.enclClass.sym.isValueClass() && (sym.flags_field & HASINIT) != 0))
1481                             reportPrologueError(tree, sym);
1482                         // we will need to generate a proxy for this field later on
1483                         if (!isInLHS) {
1484                             if (!allowValueClasses) {
1485                                 reportPrologueError(tree, sym);
1486                             } else {
1487                                 if (mode == PrologueVisitorMode.THIS_CONSTRUCTOR) {
1488                                     reportPrologueError(tree, sym);
1489                                 } else if (mode == PrologueVisitorMode.SUPER_CONSTRUCTOR) {
1490                                     localProxyVarsGen.addFieldReadInPrologue(localEnv.enclMethod, sym);
1491                                 }
1492                                 /* we do nothing in warnings only mode, as in that mode we are simulating what
1493                                  * the compiler would do in case the constructor code would be in the prologue
1494                                  * phase
1495                                  */
1496                             }
1497                         }
1498                     }
1499                 }
1500             }
1501         }
1502 
1503         /**
1504          * Determine if the symbol appearance constitutes an early reference to the current class.
1505          *
1506          * <p>
1507          * This means the symbol is an instance field, or method, of the current class and it appears
1508          * in an early initialization context of it (i.e., one of its constructor prologues).
1509          *
1510          * @param env    The current environment
1511          * @param tree   the AST referencing the variable
1512          * @param sym    The symbol
1513          */
1514         private boolean isEarlyReference(Env<AttrContext> env, JCTree tree, Symbol sym) {
1515             if ((sym.flags() & STATIC) == 0 &&
1516                     (sym.kind == VAR || sym.kind == MTH) &&
1517                     sym.isMemberOf(env.enclClass.sym, types)) {
1518                 // Allow "Foo.this.x" when "Foo" is (also) an outer class, as this refers to the outer instance
1519                 if (tree instanceof JCFieldAccess fa) {
1520                     return TreeInfo.isExplicitThisReference(types, (ClassType)env.enclClass.type, fa.selected);
1521                 } else if (currentClassSym != env.enclClass.sym) {
1522                     /* so we are inside a class, CI, in the prologue of an outer class, CO, and the symbol being
1523                      * analyzed has no qualifier. So if the symbol is a member of CI the reference is allowed,
1524                      * otherwise it is not.
1525                      * It could be that the reference to CI's member happens inside CI's own prologue, but that
1526                      * will be checked separately, when CI's prologue is analyzed.
1527                      */
1528                     return !sym.isMemberOf(currentClassSym, types);
1529                 }
1530                 return true;
1531             }
1532             return false;
1533         }
1534 
1535         /* scanner for a select expression, anything that is not a select or identifier
1536          * will be stored for further analysis
1537          */
1538         class SelectScanner extends DeferredAttr.FilterScanner {
1539             JCTree scanLater;
1540 
1541             SelectScanner() {
1542                 super(Set.of(IDENT, SELECT, PARENS));
1543             }
1544 
1545             @Override
1546             void skip(JCTree tree) {
1547                 scanLater = tree;
1548             }
1549         }
1550     }
1551 
1552     public void visitVarDef(JCVariableDecl tree) {
1553         // Local variables have not been entered yet, so we need to do it now:
1554         if (env.info.scope.owner.kind == MTH || env.info.scope.owner.kind == VAR) {
1555             if (tree.sym != null) {
1556                 // parameters have already been entered
1557                 env.info.scope.enter(tree.sym);
1558             } else {
1559                 if (tree.isImplicitlyTyped() && (tree.getModifiers().flags & PARAMETER) == 0) {
1560                     if (tree.init == null) {
1561                         //cannot use 'var' without initializer
1562                         log.error(tree, Errors.CantInferLocalVarType(tree.name, Fragments.LocalMissingInit));
1563                         tree.vartype = make.Erroneous();
1564                     } else {
1565                         Fragment msg = canInferLocalVarType(tree);
1566                         if (msg != null) {
1567                             //cannot use 'var' with initializer which require an explicit target
1568                             //(e.g. lambda, method reference, array initializer).
1569                             log.error(tree, Errors.CantInferLocalVarType(tree.name, msg));
1570                             tree.vartype = make.Erroneous();
1571                         }

1592                 (tree.sym.flags() & PARAMETER) != 0;
1593         chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1594 
1595         try {
1596             v.getConstValue(); // ensure compile-time constant initializer is evaluated
1597             chk.checkDeprecatedAnnotation(tree.pos(), v);
1598 
1599             if (tree.init != null) {
1600                 if ((v.flags_field & FINAL) == 0 ||
1601                     !memberEnter.needsLazyConstValue(tree.init)) {
1602                     // Not a compile-time constant
1603                     // Attribute initializer in a new environment
1604                     // with the declared variable as owner.
1605                     // Check that initializer conforms to variable's declared type.
1606                     Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1607                     initEnv.info.lint = lint;
1608                     // In order to catch self-references, we set the variable's
1609                     // declaration position to maximal possible value, effectively
1610                     // marking the variable as undefined.
1611                     initEnv.info.enclVar = v;
1612                     boolean previousCtorPrologue = initEnv.info.ctorPrologue;
1613                     try {
1614                         if (v.owner.kind == TYP && !v.isStatic() && v.isStrict()) {
1615                             // strict instance initializer in a value class
1616                             initEnv.info.ctorPrologue = true;
1617                         }
1618                         attribExpr(tree.init, initEnv, v.type);
1619                         if (tree.isImplicitlyTyped()) {
1620                             //fixup local variable type
1621                             v.type = chk.checkLocalVarType(tree, tree.init.type, tree.name);
1622                         }
1623                         if (allowValueClasses && v.owner.kind == TYP && !v.isStatic()) {
1624                             // strict field initializers are inlined in constructor's prologues
1625                             CtorPrologueVisitor ctorPrologueVisitor = new CtorPrologueVisitor(initEnv,
1626                                     !v.isStrict() ? PrologueVisitorMode.WARNINGS_ONLY : PrologueVisitorMode.SUPER_CONSTRUCTOR);
1627                             ctorPrologueVisitor.scan(tree.init);
1628                         }
1629                     } finally {
1630                         initEnv.info.ctorPrologue = previousCtorPrologue;
1631                     }
1632                 }
1633                 if (tree.isImplicitlyTyped()) {
1634                     setSyntheticVariableType(tree, v.type);
1635                 }
1636             }
1637             result = tree.type = v.type;
1638             if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1639                 if (isNonArgsMethodInObject(v.name)) {
1640                     log.error(tree, Errors.IllegalRecordComponentName(v));
1641                 }
1642             }
1643             chk.checkRequiresIdentity(tree, env.info.lint);
1644         }
1645         finally {
1646             chk.setLint(prevLint);
1647         }
1648     }
1649 
1650     private void doQueueScanTreeAndTypeAnnotateForVarInit(JCVariableDecl tree, Env<AttrContext> env) {

1731             }
1732         }
1733     }
1734 
1735     public void visitSkip(JCSkip tree) {
1736         result = null;
1737     }
1738 
1739     public void visitBlock(JCBlock tree) {
1740         if (env.info.scope.owner.kind == TYP || env.info.scope.owner.kind == ERR) {
1741             // Block is a static or instance initializer;
1742             // let the owner of the environment be a freshly
1743             // created BLOCK-method.
1744             Symbol fakeOwner =
1745                 new MethodSymbol(tree.flags | BLOCK |
1746                     env.info.scope.owner.flags() & STRICTFP, names.empty, initBlockType,
1747                     env.info.scope.owner);
1748             final Env<AttrContext> localEnv =
1749                 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1750 
1751             if ((tree.flags & STATIC) != 0) {
1752                 localEnv.info.staticLevel++;
1753             } else {
1754                 localEnv.info.instanceInitializerBlock = true;
1755             }
1756             // Attribute all type annotations in the block
1757             annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner);
1758             annotate.flush();
1759             attribStats(tree.stats, localEnv);
1760 
1761             {
1762                 // Store init and clinit type annotations with the ClassSymbol
1763                 // to allow output in Gen.normalizeDefs.
1764                 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1765                 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1766                 if ((tree.flags & STATIC) != 0) {
1767                     cs.appendClassInitTypeAttributes(tas);
1768                 } else {
1769                     cs.appendInitTypeAttributes(tas);
1770                 }
1771             }
1772         } else {
1773             // Create a new local environment with a local scope.
1774             Env<AttrContext> localEnv =
1775                 env.dup(tree, env.info.dup(env.info.scope.dup()));

2248     // where
2249     /** Return the selected enumeration constant symbol, or null. */
2250     private Symbol enumConstant(JCTree tree, Type enumType) {
2251         if (tree.hasTag(IDENT)) {
2252             JCIdent ident = (JCIdent)tree;
2253             Name name = ident.name;
2254             for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
2255                 if (sym.kind == VAR) {
2256                     Symbol s = ident.sym = sym;
2257                     ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
2258                     ident.type = s.type;
2259                     return ((s.flags_field & Flags.ENUM) == 0)
2260                         ? null : s;
2261                 }
2262             }
2263         }
2264         return null;
2265     }
2266 
2267     public void visitSynchronized(JCSynchronized tree) {
2268         boolean identityType = chk.checkIdentityType(tree.pos(), attribExpr(tree.lock, env));
2269         if (identityType && tree.lock.type != null && tree.lock.type.isValueBased()) {
2270             log.warning(tree.pos(), LintWarnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
2271         }
2272         attribStat(tree.body, env);
2273         result = null;
2274     }
2275 
2276     public void visitTry(JCTry tree) {
2277         // Create a new local environment with a local
2278         Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
2279         try {
2280             boolean isTryWithResource = tree.resources.nonEmpty();
2281             // Create a nested environment for attributing the try block if needed
2282             Env<AttrContext> tryEnv = isTryWithResource ?
2283                 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
2284                 localEnv;
2285             try {
2286                 // Attribute resource declarations
2287                 for (JCTree resource : tree.resources) {
2288                     CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
2289                         @Override

4701     }
4702 
4703     public void visitSelect(JCFieldAccess tree) {
4704         // Determine the expected kind of the qualifier expression.
4705         KindSelector skind = KindSelector.NIL;
4706         if (tree.name == names._this || tree.name == names._super ||
4707                 tree.name == names._class)
4708         {
4709             skind = KindSelector.TYP;
4710         } else {
4711             if (pkind().contains(KindSelector.PCK))
4712                 skind = KindSelector.of(skind, KindSelector.PCK);
4713             if (pkind().contains(KindSelector.TYP))
4714                 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4715             if (pkind().contains(KindSelector.VAL_MTH))
4716                 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4717         }
4718 
4719         // Attribute the qualifier expression, and determine its symbol (if any).
4720         Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4721         Assert.check(site == tree.selected.type);
4722         if (!pkind().contains(KindSelector.TYP_PCK))
4723             site = capture(site); // Capture field access
4724 
4725         // don't allow T.class T[].class, etc
4726         if (skind == KindSelector.TYP) {
4727             Type elt = site;
4728             while (elt.hasTag(ARRAY))
4729                 elt = ((ArrayType)elt).elemtype;
4730             if (elt.hasTag(TYPEVAR)) {
4731                 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4732                 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4733                 tree.sym = tree.type.tsym;
4734                 return ;
4735             }
4736         }
4737 
4738         // If qualifier symbol is a type or `super', assert `selectSuper'
4739         // for the selection. This is relevant for determining whether
4740         // protected symbols are accessible.
4741         Symbol sitesym = TreeInfo.symbol(tree.selected);

5804                                                       .filter(s -> s.tsym.isSealed())
5805                                                       .map(s -> (ClassSymbol) s.tsym)
5806                                                       .collect(List.collector());
5807 
5808                 if (sealedSupers.isEmpty()) {
5809                     if ((c.flags_field & Flags.NON_SEALED) != 0) {
5810                         boolean hasErrorSuper = false;
5811 
5812                         hasErrorSuper |= types.directSupertypes(c.type)
5813                                               .stream()
5814                                               .anyMatch(s -> s.tsym.kind == Kind.ERR);
5815 
5816                         ClassType ct = (ClassType) c.type;
5817 
5818                         hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5819 
5820                         if (!hasErrorSuper) {
5821                             log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5822                         }
5823                     }
5824                 } else if ((c.flags_field & Flags.COMPOUND) == 0) {
5825                     if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5826                         log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5827                     }
5828 
5829                     if (!c.type.isCompound()) {
5830                         for (ClassSymbol supertypeSym : sealedSupers) {
5831                             if (!supertypeSym.isPermittedSubclass(c.type.tsym)) {
5832                                 log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5833                             }
5834                         }
5835                         if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5836                             log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5837                                     c.isInterface() ?
5838                                             Errors.NonSealedOrSealedExpected :
5839                                             Errors.NonSealedSealedOrFinalExpected);
5840                         }
5841                     }
5842                 }
5843 
5844                 env.info.returnResult = null;
5845                 // java.lang.Enum may not be subclassed by a non-enum
5846                 if (st.tsym == syms.enumSym &&
5847                     ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5848                     log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5849 
5850                 // Enums may not be extended by source-level classes
5851                 if (st.tsym != null &&
5852                     ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5853                     ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5854                     log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5855                 }
5856 
5857                 if (rs.isSerializable(c.type)) {
5858                     env.info.isSerializable = true;
5859                 }
5860 
5861                 if (c.isValueClass()) {
5862                     Assert.check(env.tree.hasTag(CLASSDEF));
5863                     chk.checkConstraintsOfValueClass((JCClassDecl) env.tree, c);
5864                 }
5865 
5866                 attribClassBody(env, c);
5867 
5868                 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5869                 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5870                 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5871                 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5872 
5873                 if (c.isImplicit()) {
5874                     chk.checkHasMain(env.tree.pos(), c);
5875                 }
5876             } finally {
5877                 env.info.returnResult = prevReturnRes;
5878                 log.useSource(prev);
5879                 chk.setLint(prevLint);
5880             }
5881 
5882         }
5883     }
5884 
5885     public void visitImport(JCImport tree) {

5988                         sym.kind != VAR ||
5989                         sym.getConstValue() == null)
5990                     log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
5991             }
5992         }
5993 
5994         // Check for proper placement of super()/this() calls.
5995         chk.checkSuperInitCalls(tree);
5996 
5997         // Check for cycles among non-initial constructors.
5998         chk.checkCyclicConstructors(tree);
5999 
6000         // Check for cycles among annotation elements.
6001         chk.checkNonCyclicElements(tree);
6002 
6003         // Check for proper use of serialVersionUID and other
6004         // serialization-related fields and methods
6005         if (env.info.lint.isEnabled(LintCategory.SERIAL)
6006                 && rs.isSerializable(c.type)
6007                 && !c.isAnonymous()) {
6008             chk.checkSerialStructure(env, tree, c);
6009         }
6010         // Correctly organize the positions of the type annotations
6011         typeAnnotations.organizeTypeAnnotationsBodies(tree);
6012 
6013         // Check type annotations applicability rules
6014         validateTypeAnnotations(tree, false);
6015     }
6016         // where
6017         /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
6018         private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
6019             for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
6020                 if (types.isSameType(al.head.annotationType.type, t))
6021                     return al.head.pos();
6022             }
6023 
6024             return null;
6025         }
6026 
6027     private Type capture(Type type) {
6028         return types.capture(type);
< prev index next >