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.at(tree.pos()).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.at(tree.pos()).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);
5495 .filter(s -> s.tsym.isSealed())
5496 .map(s -> (ClassSymbol) s.tsym)
5497 .collect(List.collector());
5498
5499 if (sealedSupers.isEmpty()) {
5500 if ((c.flags_field & Flags.NON_SEALED) != 0) {
5501 boolean hasErrorSuper = false;
5502
5503 hasErrorSuper |= types.directSupertypes(c.type)
5504 .stream()
5505 .anyMatch(s -> s.tsym.kind == Kind.ERR);
5506
5507 ClassType ct = (ClassType) c.type;
5508
5509 hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5510
5511 if (!hasErrorSuper) {
5512 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5513 }
5514 }
5515 } else {
5516 if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5517 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5518 }
5519
5520 if (!c.type.isCompound()) {
5521 for (ClassSymbol supertypeSym : sealedSupers) {
5522 if (!supertypeSym.isPermittedSubclass(c.type.tsym)) {
5523 log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5524 }
5525 }
5526 if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5527 log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5528 c.isInterface() ?
5529 Errors.NonSealedOrSealedExpected :
5530 Errors.NonSealedSealedOrFinalExpected);
5531 }
5532 }
5533 }
5534
5535 env.info.returnResult = null;
5536 // java.lang.Enum may not be subclassed by a non-enum
5537 if (st.tsym == syms.enumSym &&
5538 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5539 log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5540
5541 // Enums may not be extended by source-level classes
5542 if (st.tsym != null &&
5543 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5544 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5545 log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5546 }
5547
5548 if (rs.isSerializable(c.type)) {
5549 env.info.isSerializable = true;
5550 }
5551
5552 attribClassBody(env, c);
5553
5554 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5555 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5556 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5557 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5558
5559 if (c.isImplicit()) {
5560 chk.checkHasMain(env.tree.pos(), c);
5561 }
5562 } finally {
5563 env.info.returnResult = prevReturnRes;
5564 log.useSource(prev);
5565 chk.setLint(prevLint);
5566 }
5567
5568 }
5569 }
5570
5571 public void visitImport(JCImport tree) {
5674 sym.kind != VAR ||
5675 sym.getConstValue() == null)
5676 log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
5677 }
5678 }
5679
5680 // Check for proper placement of super()/this() calls.
5681 chk.checkSuperInitCalls(tree);
5682
5683 // Check for cycles among non-initial constructors.
5684 chk.checkCyclicConstructors(tree);
5685
5686 // Check for cycles among annotation elements.
5687 chk.checkNonCyclicElements(tree);
5688
5689 // Check for proper use of serialVersionUID and other
5690 // serialization-related fields and methods
5691 if (env.info.lint.isEnabled(LintCategory.SERIAL)
5692 && rs.isSerializable(c.type)
5693 && !c.isAnonymous()) {
5694 chk.checkSerialStructure(tree, c);
5695 }
5696 // Correctly organize the positions of the type annotations
5697 typeAnnotations.organizeTypeAnnotationsBodies(tree);
5698
5699 // Check type annotations applicability rules
5700 validateTypeAnnotations(tree, false);
5701 }
5702 // where
5703 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
5704 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
5705 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
5706 if (types.isSameType(al.head.annotationType.type, t))
5707 return al.head.pos();
5708 }
5709
5710 return null;
5711 }
5712
5713 private Type capture(Type type) {
5714 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 boolean isIndexed = false;
1360
1361 @Override
1362 public void visitIndexed(JCArrayAccess tree) {
1363 boolean previousIsIndexed = isIndexed;
1364 try {
1365 isIndexed = true;
1366 scan(tree.indexed);
1367 } finally {
1368 isIndexed = previousIsIndexed;
1369 }
1370 scan(tree.index);
1371 if (mode == PrologueVisitorMode.SUPER_CONSTRUCTOR && isInstanceField(tree.indexed)) {
1372 localProxyVarsGen.addFieldReadInPrologue(localEnv.enclMethod, TreeInfo.symbolFor(tree.indexed));
1373 }
1374 }
1375
1376 @Override
1377 public void visitSelect(JCFieldAccess tree) {
1378 SelectScanner ss = new SelectScanner();
1379 ss.scan(tree);
1380 if (ss.scanLater == null) {
1381 analyzeSymbol(tree);
1382 } else {
1383 boolean prevLhs = isInLHS;
1384 try {
1385 isInLHS = false;
1386 scan(ss.scanLater);
1387 } finally {
1388 isInLHS = prevLhs;
1389 }
1390 }
1391 if (mode == PrologueVisitorMode.SUPER_CONSTRUCTOR) {
1392 for (JCTree subtree : ss.selectorTrees) {
1393 if (isInstanceField(subtree)) {
1394 // we need to add a proxy for this one
1395 localProxyVarsGen.addFieldReadInPrologue(localEnv.enclMethod, TreeInfo.symbolFor(subtree));
1396 }
1397 }
1398 }
1399 }
1400
1401 boolean isInstanceField(JCTree tree) {
1402 Symbol sym = TreeInfo.symbolFor(tree);
1403 return (sym != null &&
1404 !sym.isStatic() &&
1405 sym.kind == VAR &&
1406 sym.owner.kind == TYP &&
1407 sym.name != names._this &&
1408 sym.name != names._super &&
1409 isEarlyReference(localEnv, tree, sym));
1410 }
1411
1412 @Override
1413 public void visitNewClass(JCNewClass tree) {
1414 super.visitNewClass(tree);
1415 checkNewClassAndMethRefs(tree, tree.type);
1416 }
1417
1418 @Override
1419 public void visitReference(JCMemberReference tree) {
1420 super.visitReference(tree);
1421 if (tree.getMode() == JCMemberReference.ReferenceMode.NEW) {
1422 checkNewClassAndMethRefs(tree, tree.expr.type);
1423 }
1424 }
1425
1426 void checkNewClassAndMethRefs(JCTree tree, Type t) {
1427 if (t.tsym.isEnclosedBy(localEnv.enclClass.sym) &&
1428 !t.tsym.isStatic() &&
1429 !t.tsym.isDirectlyOrIndirectlyLocal()) {
1430 reportPrologueError(tree, t.getEnclosingType().tsym);
1431 }
1432 }
1433
1434 /* if a symbol is in the LHS of an assignment expression we won't consider it as a candidate
1435 * for a proxy local variable later on
1436 */
1437 boolean isInLHS = false;
1438
1439 @Override
1440 public void visitAssign(JCAssign tree) {
1441 boolean previousIsInLHS = isInLHS;
1442 try {
1443 isInLHS = true;
1444 scan(tree.lhs);
1445 } finally {
1446 isInLHS = previousIsInLHS;
1447 }
1448 scan(tree.rhs);
1449 }
1450
1451 @Override
1452 public void visitMethodDef(JCMethodDecl tree) {
1453 // ignore any declarative part, mainly to avoid scanning receiver parameters
1454 scan(tree.body);
1455 }
1456
1457 void analyzeSymbol(JCTree tree) {
1458 Symbol sym = TreeInfo.symbolFor(tree);
1459 // make sure that there is a symbol and it is not static
1460 if (sym == null || sym.isStatic()) {
1461 return;
1462 }
1463 if (isInLHS && !insideLambdaOrClassDef) {
1464 // Check instance field assignments that appear in constructor prologues
1465 if (isEarlyReference(localEnv, tree, sym)) {
1466 // Field may not be inherited from a superclass
1467 if (sym.owner != localEnv.enclClass.sym) {
1468 reportPrologueError(tree, sym);
1469 return;
1470 }
1471 // Field may not have an initializer
1472 if ((sym.flags() & HASINIT) != 0) {
1473 if (!localEnv.enclClass.sym.isValueClass() || !sym.type.hasTag(ARRAY) || !isIndexed) {
1474 reportPrologueError(tree, sym, true);
1475 }
1476 return;
1477 }
1478 // cant reference an instance field before a this constructor
1479 if (allowValueClasses && mode == PrologueVisitorMode.THIS_CONSTRUCTOR) {
1480 reportPrologueError(tree, sym);
1481 return;
1482 }
1483 }
1484 return;
1485 }
1486 tree = TreeInfo.skipParens(tree);
1487 if (sym.kind == VAR && sym.owner.kind == TYP) {
1488 if (sym.name == names._this || sym.name == names._super) {
1489 // are we seeing something like `this` or `CurrentClass.this` or `SuperClass.super::foo`?
1490 if (TreeInfo.isExplicitThisReference(
1491 types,
1492 (ClassType)localEnv.enclClass.sym.type,
1493 tree)) {
1494 reportPrologueError(tree, sym);
1495 }
1496 } else if (sym.kind == VAR && sym.owner.kind == TYP) { // now fields only
1497 if (sym.owner != localEnv.enclClass.sym) {
1498 if (localEnv.enclClass.sym.isSubClass(sym.owner, types) &&
1499 sym.isInheritedIn(localEnv.enclClass.sym, types)) {
1500 /* if we are dealing with a field that doesn't belong to the current class, but the
1501 * field is inherited, this is an error. Unless, the super class is also an outer
1502 * class and the field's qualifier refers to the outer class
1503 */
1504 if (tree.hasTag(IDENT) ||
1505 TreeInfo.isExplicitThisReference(
1506 types,
1507 (ClassType)localEnv.enclClass.sym.type,
1508 ((JCFieldAccess)tree).selected)) {
1509 reportPrologueError(tree, sym);
1510 }
1511 }
1512 } else if (isEarlyReference(localEnv, tree, sym)) {
1513 /* now this is a `proper` instance field of the current class
1514 * references to fields of identity classes which happen to have initializers are
1515 * not allowed in the prologue
1516 */
1517 if (insideLambdaOrClassDef ||
1518 (!localEnv.enclClass.sym.isValueClass() && (sym.flags_field & HASINIT) != 0))
1519 reportPrologueError(tree, sym);
1520 // we will need to generate a proxy for this field later on
1521 if (!isInLHS) {
1522 if (!allowValueClasses) {
1523 reportPrologueError(tree, sym);
1524 } else {
1525 if (mode == PrologueVisitorMode.THIS_CONSTRUCTOR) {
1526 reportPrologueError(tree, sym);
1527 } else if (mode == PrologueVisitorMode.SUPER_CONSTRUCTOR) {
1528 localProxyVarsGen.addFieldReadInPrologue(localEnv.enclMethod, sym);
1529 }
1530 /* we do nothing in warnings only mode, as in that mode we are simulating what
1531 * the compiler would do in case the constructor code would be in the prologue
1532 * phase
1533 */
1534 }
1535 }
1536 }
1537 }
1538 }
1539 }
1540
1541 /**
1542 * Determine if the symbol appearance constitutes an early reference to the current class.
1543 *
1544 * <p>
1545 * This means the symbol is an instance field, or method, of the current class and it appears
1546 * in an early initialization context of it (i.e., one of its constructor prologues).
1547 *
1548 * @param env The current environment
1549 * @param tree the AST referencing the variable
1550 * @param sym The symbol
1551 */
1552 private boolean isEarlyReference(Env<AttrContext> env, JCTree tree, Symbol sym) {
1553 if ((sym.flags() & STATIC) == 0 &&
1554 (sym.kind == VAR || sym.kind == MTH) &&
1555 sym.isMemberOf(env.enclClass.sym, types)) {
1556 // Allow "Foo.this.x" when "Foo" is (also) an outer class, as this refers to the outer instance
1557 if (tree instanceof JCFieldAccess fa) {
1558 return TreeInfo.isExplicitThisReference(types, (ClassType)env.enclClass.type, fa.selected);
1559 } else if (currentClassSym != env.enclClass.sym) {
1560 /* so we are inside a class, CI, in the prologue of an outer class, CO, and the symbol being
1561 * analyzed has no qualifier. So if the symbol is a member of CI the reference is allowed,
1562 * otherwise it is not.
1563 * It could be that the reference to CI's member happens inside CI's own prologue, but that
1564 * will be checked separately, when CI's prologue is analyzed.
1565 */
1566 return !sym.isMemberOf(currentClassSym, types);
1567 }
1568 return true;
1569 }
1570 return false;
1571 }
1572
1573 /* scanner for a select expression, anything that is not a select or identifier
1574 * will be stored for further analysis
1575 */
1576 class SelectScanner extends DeferredAttr.FilterScanner {
1577 JCTree scanLater;
1578 java.util.List<JCTree> selectorTrees = new ArrayList<>();
1579
1580 SelectScanner() {
1581 super(Set.of(IDENT, SELECT, PARENS));
1582 }
1583
1584 @Override
1585 public void visitSelect(JCFieldAccess tree) {
1586 super.visitSelect(tree);
1587 selectorTrees.add(tree.selected);
1588 }
1589
1590 @Override
1591 void skip(JCTree tree) {
1592 scanLater = tree;
1593 }
1594 }
1595 }
1596
1597 public void visitVarDef(JCVariableDecl tree) {
1598 // Local variables have not been entered yet, so we need to do it now:
1599 if (env.info.scope.owner.kind == MTH || env.info.scope.owner.kind == VAR) {
1600 if (tree.sym != null) {
1601 // parameters have already been entered
1602 env.info.scope.enter(tree.sym);
1603 } else {
1604 if (tree.isImplicitlyTyped() && (tree.getModifiers().flags & PARAMETER) == 0) {
1605 if (tree.init == null) {
1606 //cannot use 'var' without initializer
1607 log.error(tree, Errors.CantInferLocalVarType(tree.name, Fragments.LocalMissingInit));
1608 tree.vartype = make.at(tree.pos()).Erroneous();
1609 } else {
1610 Fragment msg = canInferLocalVarType(tree);
1611 if (msg != null) {
1612 //cannot use 'var' with initializer which require an explicit target
1613 //(e.g. lambda, method reference, array initializer).
1614 log.error(tree, Errors.CantInferLocalVarType(tree.name, msg));
1615 tree.vartype = make.at(tree.pos()).Erroneous();
1616 }
1637 (tree.sym.flags() & PARAMETER) != 0;
1638 chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1639
1640 try {
1641 v.getConstValue(); // ensure compile-time constant initializer is evaluated
1642 chk.checkDeprecatedAnnotation(tree.pos(), v);
1643
1644 if (tree.init != null) {
1645 if ((v.flags_field & FINAL) == 0 ||
1646 !memberEnter.needsLazyConstValue(tree.init)) {
1647 // Not a compile-time constant
1648 // Attribute initializer in a new environment
1649 // with the declared variable as owner.
1650 // Check that initializer conforms to variable's declared type.
1651 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1652 initEnv.info.lint = lint;
1653 // In order to catch self-references, we set the variable's
1654 // declaration position to maximal possible value, effectively
1655 // marking the variable as undefined.
1656 initEnv.info.enclVar = v;
1657 boolean previousCtorPrologue = initEnv.info.ctorPrologue;
1658 try {
1659 if (v.owner.kind == TYP && !v.isStatic() && v.isStrict()) {
1660 // strict instance initializer in a value class
1661 initEnv.info.ctorPrologue = true;
1662 }
1663 attribExpr(tree.init, initEnv, v.type);
1664 if (tree.isImplicitlyTyped()) {
1665 //fixup local variable type
1666 v.type = chk.checkLocalVarType(tree, tree.init.type, tree.name);
1667 }
1668 if (allowValueClasses && v.owner.kind == TYP && !v.isStatic()) {
1669 // strict field initializers are inlined in constructor's prologues
1670 CtorPrologueVisitor ctorPrologueVisitor = new CtorPrologueVisitor(initEnv,
1671 !v.isStrict() ? PrologueVisitorMode.WARNINGS_ONLY : PrologueVisitorMode.SUPER_CONSTRUCTOR);
1672 ctorPrologueVisitor.scan(tree.init);
1673 }
1674 } finally {
1675 initEnv.info.ctorPrologue = previousCtorPrologue;
1676 }
1677 }
1678 if (tree.isImplicitlyTyped()) {
1679 setSyntheticVariableType(tree, v.type);
1680 }
1681 }
1682 result = tree.type = v.type;
1683 if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1684 if (isNonArgsMethodInObject(v.name)) {
1685 log.error(tree, Errors.IllegalRecordComponentName(v));
1686 }
1687 }
1688 chk.checkRequiresIdentity(tree, env.info.lint);
1689 }
1690 finally {
1691 chk.setLint(prevLint);
1692 }
1693 }
1694
1695 private void doQueueScanTreeAndTypeAnnotateForVarInit(JCVariableDecl tree, Env<AttrContext> env) {
1776 }
1777 }
1778 }
1779
1780 public void visitSkip(JCSkip tree) {
1781 result = null;
1782 }
1783
1784 public void visitBlock(JCBlock tree) {
1785 if (env.info.scope.owner.kind == TYP || env.info.scope.owner.kind == ERR) {
1786 // Block is a static or instance initializer;
1787 // let the owner of the environment be a freshly
1788 // created BLOCK-method.
1789 Symbol fakeOwner =
1790 new MethodSymbol(tree.flags | BLOCK |
1791 env.info.scope.owner.flags() & STRICTFP, names.empty, initBlockType,
1792 env.info.scope.owner);
1793 final Env<AttrContext> localEnv =
1794 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1795
1796 if ((tree.flags & STATIC) != 0) {
1797 localEnv.info.staticLevel++;
1798 } else {
1799 localEnv.info.instanceInitializerBlock = true;
1800 }
1801 // Attribute all type annotations in the block
1802 annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner);
1803 annotate.flush();
1804 attribStats(tree.stats, localEnv);
1805
1806 {
1807 // Store init and clinit type annotations with the ClassSymbol
1808 // to allow output in Gen.normalizeDefs.
1809 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1810 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1811 if ((tree.flags & STATIC) != 0) {
1812 cs.appendClassInitTypeAttributes(tas);
1813 } else {
1814 cs.appendInitTypeAttributes(tas);
1815 }
1816 }
1817 } else {
1818 // Create a new local environment with a local scope.
1819 Env<AttrContext> localEnv =
1820 env.dup(tree, env.info.dup(env.info.scope.dup()));
2293 // where
2294 /** Return the selected enumeration constant symbol, or null. */
2295 private Symbol enumConstant(JCTree tree, Type enumType) {
2296 if (tree.hasTag(IDENT)) {
2297 JCIdent ident = (JCIdent)tree;
2298 Name name = ident.name;
2299 for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
2300 if (sym.kind == VAR) {
2301 Symbol s = ident.sym = sym;
2302 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
2303 ident.type = s.type;
2304 return ((s.flags_field & Flags.ENUM) == 0)
2305 ? null : s;
2306 }
2307 }
2308 }
2309 return null;
2310 }
2311
2312 public void visitSynchronized(JCSynchronized tree) {
2313 boolean identityType = chk.checkIdentityType(tree.pos(), attribExpr(tree.lock, env));
2314 if (identityType && tree.lock.type != null && tree.lock.type.isValueBased()) {
2315 log.warning(tree.pos(), LintWarnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
2316 }
2317 attribStat(tree.body, env);
2318 result = null;
2319 }
2320
2321 public void visitTry(JCTry tree) {
2322 // Create a new local environment with a local
2323 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
2324 try {
2325 boolean isTryWithResource = tree.resources.nonEmpty();
2326 // Create a nested environment for attributing the try block if needed
2327 Env<AttrContext> tryEnv = isTryWithResource ?
2328 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
2329 localEnv;
2330 try {
2331 // Attribute resource declarations
2332 for (JCTree resource : tree.resources) {
2333 CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
2334 @Override
4746 }
4747
4748 public void visitSelect(JCFieldAccess tree) {
4749 // Determine the expected kind of the qualifier expression.
4750 KindSelector skind = KindSelector.NIL;
4751 if (tree.name == names._this || tree.name == names._super ||
4752 tree.name == names._class)
4753 {
4754 skind = KindSelector.TYP;
4755 } else {
4756 if (pkind().contains(KindSelector.PCK))
4757 skind = KindSelector.of(skind, KindSelector.PCK);
4758 if (pkind().contains(KindSelector.TYP))
4759 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4760 if (pkind().contains(KindSelector.VAL_MTH))
4761 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4762 }
4763
4764 // Attribute the qualifier expression, and determine its symbol (if any).
4765 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4766 Assert.check(site == tree.selected.type);
4767 if (!pkind().contains(KindSelector.TYP_PCK))
4768 site = capture(site); // Capture field access
4769
4770 // don't allow T.class T[].class, etc
4771 if (skind == KindSelector.TYP) {
4772 Type elt = site;
4773 while (elt.hasTag(ARRAY))
4774 elt = ((ArrayType)elt).elemtype;
4775 if (elt.hasTag(TYPEVAR)) {
4776 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4777 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4778 tree.sym = tree.type.tsym;
4779 return ;
4780 }
4781 }
4782
4783 // If qualifier symbol is a type or `super', assert `selectSuper'
4784 // for the selection. This is relevant for determining whether
4785 // protected symbols are accessible.
4786 Symbol sitesym = TreeInfo.symbol(tree.selected);
5859 .filter(s -> s.tsym.isSealed())
5860 .map(s -> (ClassSymbol) s.tsym)
5861 .collect(List.collector());
5862
5863 if (sealedSupers.isEmpty()) {
5864 if ((c.flags_field & Flags.NON_SEALED) != 0) {
5865 boolean hasErrorSuper = false;
5866
5867 hasErrorSuper |= types.directSupertypes(c.type)
5868 .stream()
5869 .anyMatch(s -> s.tsym.kind == Kind.ERR);
5870
5871 ClassType ct = (ClassType) c.type;
5872
5873 hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5874
5875 if (!hasErrorSuper) {
5876 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5877 }
5878 }
5879 } else if ((c.flags_field & Flags.COMPOUND) == 0) {
5880 if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5881 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5882 }
5883
5884 if (!c.type.isCompound()) {
5885 for (ClassSymbol supertypeSym : sealedSupers) {
5886 if (!supertypeSym.isPermittedSubclass(c.type.tsym)) {
5887 log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5888 }
5889 }
5890 if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5891 log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5892 c.isInterface() ?
5893 Errors.NonSealedOrSealedExpected :
5894 Errors.NonSealedSealedOrFinalExpected);
5895 }
5896 }
5897 }
5898
5899 env.info.returnResult = null;
5900 // java.lang.Enum may not be subclassed by a non-enum
5901 if (st.tsym == syms.enumSym &&
5902 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5903 log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5904
5905 // Enums may not be extended by source-level classes
5906 if (st.tsym != null &&
5907 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5908 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5909 log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5910 }
5911
5912 if (rs.isSerializable(c.type)) {
5913 env.info.isSerializable = true;
5914 }
5915
5916 if (c.isValueClass()) {
5917 Assert.check(env.tree.hasTag(CLASSDEF));
5918 chk.checkConstraintsOfValueClass((JCClassDecl) env.tree, c);
5919 }
5920
5921 attribClassBody(env, c);
5922
5923 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5924 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5925 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5926 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5927
5928 if (c.isImplicit()) {
5929 chk.checkHasMain(env.tree.pos(), c);
5930 }
5931 } finally {
5932 env.info.returnResult = prevReturnRes;
5933 log.useSource(prev);
5934 chk.setLint(prevLint);
5935 }
5936
5937 }
5938 }
5939
5940 public void visitImport(JCImport tree) {
6043 sym.kind != VAR ||
6044 sym.getConstValue() == null)
6045 log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
6046 }
6047 }
6048
6049 // Check for proper placement of super()/this() calls.
6050 chk.checkSuperInitCalls(tree);
6051
6052 // Check for cycles among non-initial constructors.
6053 chk.checkCyclicConstructors(tree);
6054
6055 // Check for cycles among annotation elements.
6056 chk.checkNonCyclicElements(tree);
6057
6058 // Check for proper use of serialVersionUID and other
6059 // serialization-related fields and methods
6060 if (env.info.lint.isEnabled(LintCategory.SERIAL)
6061 && rs.isSerializable(c.type)
6062 && !c.isAnonymous()) {
6063 chk.checkSerialStructure(env, tree, c);
6064 }
6065 // Correctly organize the positions of the type annotations
6066 typeAnnotations.organizeTypeAnnotationsBodies(tree);
6067
6068 // Check type annotations applicability rules
6069 validateTypeAnnotations(tree, false);
6070 }
6071 // where
6072 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
6073 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
6074 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
6075 if (types.isSameType(al.head.annotationType.type, t))
6076 return al.head.pos();
6077 }
6078
6079 return null;
6080 }
6081
6082 private Type capture(Type type) {
6083 return types.capture(type);
|