1 /*
2 * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 package com.sun.tools.javac.comp;
27
28 import java.util.*;
29 import java.util.function.BiConsumer;
30 import java.util.function.Consumer;
31 import java.util.stream.Stream;
32
33 import javax.lang.model.element.ElementKind;
34 import javax.tools.JavaFileObject;
35
36 import com.sun.source.tree.CaseTree;
37 import com.sun.source.tree.IdentifierTree;
38 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
39 import com.sun.source.tree.MemberSelectTree;
40 import com.sun.source.tree.TreeVisitor;
41 import com.sun.source.util.SimpleTreeVisitor;
42 import com.sun.tools.javac.code.*;
43 import com.sun.tools.javac.code.Lint.LintCategory;
44 import com.sun.tools.javac.code.LintMapper;
45 import com.sun.tools.javac.code.Scope.WriteableScope;
46 import com.sun.tools.javac.code.Source.Feature;
47 import com.sun.tools.javac.code.Symbol.*;
48 import com.sun.tools.javac.code.Type.*;
49 import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError;
50 import com.sun.tools.javac.comp.ArgumentAttr.LocalCacheContext;
51 import com.sun.tools.javac.comp.Check.CheckContext;
52 import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
53 import com.sun.tools.javac.comp.MatchBindingsComputer.MatchBindings;
54 import com.sun.tools.javac.jvm.*;
55
56 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond;
57 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArg;
58 import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArgs;
59
60 import com.sun.tools.javac.resources.CompilerProperties.Errors;
61 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
62 import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
63 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
64 import com.sun.tools.javac.tree.*;
65 import com.sun.tools.javac.tree.JCTree.*;
66 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
67 import com.sun.tools.javac.util.*;
68 import com.sun.tools.javac.util.DefinedBy.Api;
69 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
70 import com.sun.tools.javac.util.JCDiagnostic.Error;
71 import com.sun.tools.javac.util.JCDiagnostic.Fragment;
72 import com.sun.tools.javac.util.JCDiagnostic.Warning;
73 import com.sun.tools.javac.util.List;
74
75 import static com.sun.tools.javac.code.Flags.*;
76 import static com.sun.tools.javac.code.Flags.ANNOTATION;
77 import static com.sun.tools.javac.code.Flags.BLOCK;
78 import static com.sun.tools.javac.code.Kinds.*;
79 import static com.sun.tools.javac.code.Kinds.Kind.*;
80 import static com.sun.tools.javac.code.TypeTag.*;
81 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
82 import static com.sun.tools.javac.tree.JCTree.Tag.*;
83
84 /** This is the main context-dependent analysis phase in GJC. It
85 * encompasses name resolution, type checking and constant folding as
86 * subtasks. Some subtasks involve auxiliary classes.
87 * @see Check
88 * @see Resolve
89 * @see ConstFold
90 * @see Infer
91 *
92 * <p><b>This is NOT part of any supported API.
93 * If you write code that depends on this, you do so at your own risk.
94 * This code and its internal interfaces are subject to change or
95 * deletion without notice.</b>
96 */
97 public class Attr extends JCTree.Visitor {
98 protected static final Context.Key<Attr> attrKey = new Context.Key<>();
99
100 final Names names;
101 final Log log;
102 final LintMapper lintMapper;
103 final Symtab syms;
104 final Resolve rs;
105 final Operators operators;
106 final Infer infer;
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 final boolean captureMRefReturnType;
129
130 public static Attr instance(Context context) {
131 Attr instance = context.get(attrKey);
132 if (instance == null)
133 instance = new Attr(context);
134 return instance;
135 }
136
137 @SuppressWarnings("this-escape")
138 protected Attr(Context context) {
139 context.put(attrKey, this);
140
141 names = Names.instance(context);
142 log = Log.instance(context);
143 lintMapper = LintMapper.instance(context);
144 syms = Symtab.instance(context);
145 rs = Resolve.instance(context);
146 operators = Operators.instance(context);
147 chk = Check.instance(context);
148 flow = Flow.instance(context);
149 memberEnter = MemberEnter.instance(context);
150 typeEnter = TypeEnter.instance(context);
151 make = TreeMaker.instance(context);
152 enter = Enter.instance(context);
153 infer = Infer.instance(context);
154 analyzer = Analyzer.instance(context);
155 deferredAttr = DeferredAttr.instance(context);
156 cfolder = ConstFold.instance(context);
157 target = Target.instance(context);
158 types = Types.instance(context);
159 preview = Preview.instance(context);
160 diags = JCDiagnostic.Factory.instance(context);
161 annotate = Annotate.instance(context);
162 typeAnnotations = TypeAnnotations.instance(context);
163 typeEnvs = TypeEnvs.instance(context);
164 dependencies = Dependencies.instance(context);
165 argumentAttr = ArgumentAttr.instance(context);
166 matchBindingsComputer = MatchBindingsComputer.instance(context);
167 attrRecover = AttrRecover.instance(context);
168 localProxyVarsGen = LocalProxyVarsGen.instance(context);
169
170 Options options = Options.instance(context);
171
172 Source source = Source.instance(context);
173 allowReifiableTypesInInstanceof = Feature.REIFIABLE_TYPES_INSTANCEOF.allowedInSource(source);
174 allowRecords = Feature.RECORDS.allowedInSource(source);
175 allowPatternSwitch = (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH)) &&
176 Feature.PATTERN_SWITCH.allowedInSource(source);
177 allowUnconditionalPatternsInstanceOf =
178 Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.allowedInSource(source);
179 sourceName = source.name;
180 useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
181 captureMRefReturnType = Source.Feature.ERASE_POLY_SIG_RETURN_TYPE.allowedInSource(source);
182
183 statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
184 varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
185 unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
186 methodAttrInfo = new MethodAttrInfo();
187 unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
188 unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
189 recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
190 initBlockType = new MethodType(List.nil(), syms.voidType, List.nil(), syms.methodClass);
191 allowValueClasses = (!preview.isPreview(Feature.VALUE_CLASSES) || preview.isEnabled()) &&
192 Feature.VALUE_CLASSES.allowedInSource(source);
193 }
194
195 /** Switch: reifiable types in instanceof enabled?
196 */
197 boolean allowReifiableTypesInInstanceof;
198
199 /** Are records allowed
200 */
201 private final boolean allowRecords;
202
203 /** Are patterns in switch allowed
204 */
205 private final boolean allowPatternSwitch;
206
207 /** Are unconditional patterns in instanceof allowed
208 */
209 private final boolean allowUnconditionalPatternsInstanceOf;
210
211 /** Are value classes allowed
212 */
213 private final boolean allowValueClasses;
214
215 /**
216 * Switch: warn about use of variable before declaration?
217 * RFE: 6425594
218 */
219 boolean useBeforeDeclarationWarning;
220
221 /**
222 * Switch: name of source level; used for error reporting.
223 */
224 String sourceName;
225
226 /** Check kind and type of given tree against protokind and prototype.
227 * If check succeeds, store type in tree and return it.
228 * If check fails, store errType in tree and return it.
229 * No checks are performed if the prototype is a method type.
230 * It is not necessary in this case since we know that kind and type
231 * are correct.
232 *
233 * @param tree The tree whose kind and type is checked
234 * @param found The computed type of the tree
235 * @param ownkind The computed kind of the tree
236 * @param resultInfo The expected result of the tree
237 */
238 Type check(final JCTree tree,
239 final Type found,
240 final KindSelector ownkind,
241 final ResultInfo resultInfo) {
242 InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
243 Type owntype;
244 boolean shouldCheck = !found.hasTag(ERROR) &&
245 !resultInfo.pt.hasTag(METHOD) &&
246 !resultInfo.pt.hasTag(FORALL);
247 if (shouldCheck && !ownkind.subset(resultInfo.pkind)) {
248 log.error(tree.pos(),
249 Errors.UnexpectedType(resultInfo.pkind.kindNames(),
250 ownkind.kindNames()));
251 owntype = types.createErrorType(found);
252 } else if (inferenceContext.free(found)) {
253 //delay the check if there are inference variables in the found type
254 //this means we are dealing with a partially inferred poly expression
255 owntype = shouldCheck ? resultInfo.pt : found;
256 if (resultInfo.checkMode.installPostInferenceHook()) {
257 inferenceContext.addFreeTypeListener(List.of(found),
258 instantiatedContext -> {
259 ResultInfo pendingResult =
260 resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
261 check(tree, inferenceContext.asInstType(found), ownkind, pendingResult);
262 });
263 }
264 } else {
265 owntype = shouldCheck ?
266 resultInfo.check(tree, found) :
267 found;
268 }
269 if (resultInfo.checkMode.updateTreeType()) {
270 tree.type = owntype;
271 }
272 return owntype;
273 }
274
275 /** Is given blank final variable assignable, i.e. in a scope where it
276 * may be assigned to even though it is final?
277 * @param v The blank final variable.
278 * @param env The current environment.
279 */
280 boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
281 Symbol owner = env.info.scope.owner;
282 // owner refers to the innermost variable, method or
283 // initializer block declaration at this point.
284 boolean isAssignable =
285 v.owner == owner
286 ||
287 ((owner.name == names.init || // i.e. we are in a constructor
288 owner.kind == VAR || // i.e. we are in a variable initializer
289 (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block
290 &&
291 v.owner == owner.owner
292 &&
293 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
294 boolean insideCompactConstructor = env.enclMethod != null && TreeInfo.isCompactConstructor(env.enclMethod);
295 return isAssignable & !insideCompactConstructor;
296 }
297
298 /** Check that variable can be assigned to.
299 * @param pos The current source code position.
300 * @param v The assigned variable
301 * @param base If the variable is referred to in a Select, the part
302 * to the left of the `.', null otherwise.
303 * @param env The current environment.
304 */
305 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
306 if (v.name == names._this) {
307 log.error(pos, Errors.CantAssignValToThis);
308 } else if ((v.flags() & FINAL) != 0 &&
309 ((v.flags() & HASINIT) != 0
310 ||
311 !((base == null ||
312 TreeInfo.isThisQualifier(base)) &&
313 isAssignableAsBlankFinal(v, env)))) {
314 if (v.isResourceVariable()) { //TWR resource
315 log.error(pos, Errors.TryResourceMayNotBeAssigned(v));
316 } else {
317 log.error(pos, Errors.CantAssignValToVar(Flags.toSource(v.flags() & (STATIC | FINAL)), v));
318 }
319 }
320 }
321
322 /** Does tree represent a static reference to an identifier?
323 * It is assumed that tree is either a SELECT or an IDENT.
324 * We have to weed out selects from non-type names here.
325 * @param tree The candidate tree.
326 */
327 boolean isStaticReference(JCTree tree) {
328 if (tree.hasTag(SELECT)) {
329 Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
330 if (lsym == null || lsym.kind != TYP) {
331 return false;
332 }
333 }
334 return true;
335 }
336
337 /** Is this symbol a type?
338 */
339 static boolean isType(Symbol sym) {
340 return sym != null && sym.kind == TYP;
341 }
342
343 /** Attribute a parsed identifier.
344 * @param tree Parsed identifier name
345 * @param topLevel The toplevel to use
346 */
347 public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
348 Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
349 localEnv.enclClass = make.ClassDef(make.Modifiers(0),
350 syms.errSymbol.name,
351 null, null, null, null);
352 localEnv.enclClass.sym = syms.errSymbol;
353 return attribIdent(tree, localEnv);
354 }
355
356 /** Attribute a parsed identifier.
357 * @param tree Parsed identifier name
358 * @param env The env to use
359 */
360 public Symbol attribIdent(JCTree tree, Env<AttrContext> env) {
361 return tree.accept(identAttributer, env);
362 }
363 // where
364 private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
365 private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
366 @Override @DefinedBy(Api.COMPILER_TREE)
367 public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
368 Symbol site = visit(node.getExpression(), env);
369 if (site.kind == ERR || site.kind == ABSENT_TYP || site.kind == HIDDEN)
370 return site;
371 Name name = (Name)node.getIdentifier();
372 if (site.kind == PCK) {
373 env.toplevel.packge = (PackageSymbol)site;
374 return rs.findIdentInPackage(null, env, (TypeSymbol)site, name,
375 KindSelector.TYP_PCK);
376 } else {
377 env.enclClass.sym = (ClassSymbol)site;
378 return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
379 }
380 }
381
382 @Override @DefinedBy(Api.COMPILER_TREE)
383 public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
384 return rs.findIdent(null, env, (Name)node.getName(), KindSelector.TYP_PCK);
385 }
386 }
387
388 public Type coerce(Type etype, Type ttype) {
389 return cfolder.coerce(etype, ttype);
390 }
391
392 public Type attribType(JCTree node, TypeSymbol sym) {
393 Env<AttrContext> env = typeEnvs.get(sym);
394 Env<AttrContext> localEnv = env.dup(node, env.info.dup());
395 return attribTree(node, localEnv, unknownTypeInfo);
396 }
397
398 public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
399 // Attribute qualifying package or class.
400 JCFieldAccess s = tree.qualid;
401 return attribTree(s.selected, env,
402 new ResultInfo(tree.staticImport ?
403 KindSelector.TYP : KindSelector.TYP_PCK,
404 Type.noType));
405 }
406
407 public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
408 return attribToTree(expr, env, tree, unknownExprInfo);
409 }
410
411 public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
412 return attribToTree(stmt, env, tree, statInfo);
413 }
414
415 private Env<AttrContext> attribToTree(JCTree root, Env<AttrContext> env, JCTree tree, ResultInfo resultInfo) {
416 breakTree = tree;
417 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
418 try {
419 deferredAttr.attribSpeculative(root, env, resultInfo,
420 null, DeferredAttr.AttributionMode.ATTRIB_TO_TREE,
421 argumentAttr.withLocalCacheContext());
422 attrRecover.doRecovery();
423 } catch (BreakAttr b) {
424 return b.env;
425 } catch (AssertionError ae) {
426 if (ae.getCause() instanceof BreakAttr breakAttr) {
427 return breakAttr.env;
428 } else {
429 throw ae;
430 }
431 } finally {
432 breakTree = null;
433 log.useSource(prev);
434 }
435 return env;
436 }
437
438 private JCTree breakTree = null;
439
440 private static class BreakAttr extends RuntimeException {
441 static final long serialVersionUID = -6924771130405446405L;
442 private transient Env<AttrContext> env;
443 private BreakAttr(Env<AttrContext> env) {
444 this.env = env;
445 }
446 }
447
448 /**
449 * Mode controlling behavior of Attr.Check
450 */
451 enum CheckMode {
452
453 NORMAL,
454
455 /**
456 * Mode signalling 'fake check' - skip tree update. A side-effect of this mode is
457 * that the captured var cache in {@code InferenceContext} will be used in read-only
458 * mode when performing inference checks.
459 */
460 NO_TREE_UPDATE {
461 @Override
462 public boolean updateTreeType() {
463 return false;
464 }
465 },
466 /**
467 * Mode signalling that caller will manage free types in tree decorations.
468 */
469 NO_INFERENCE_HOOK {
470 @Override
471 public boolean installPostInferenceHook() {
472 return false;
473 }
474 };
475
476 public boolean updateTreeType() {
477 return true;
478 }
479 public boolean installPostInferenceHook() {
480 return true;
481 }
482 }
483
484
485 class ResultInfo {
486 final KindSelector pkind;
487 final Type pt;
488 final CheckContext checkContext;
489 final CheckMode checkMode;
490
491 ResultInfo(KindSelector pkind, Type pt) {
492 this(pkind, pt, chk.basicHandler, CheckMode.NORMAL);
493 }
494
495 ResultInfo(KindSelector pkind, Type pt, CheckMode checkMode) {
496 this(pkind, pt, chk.basicHandler, checkMode);
497 }
498
499 protected ResultInfo(KindSelector pkind,
500 Type pt, CheckContext checkContext) {
501 this(pkind, pt, checkContext, CheckMode.NORMAL);
502 }
503
504 protected ResultInfo(KindSelector pkind,
505 Type pt, CheckContext checkContext, CheckMode checkMode) {
506 this.pkind = pkind;
507 this.pt = pt;
508 this.checkContext = checkContext;
509 this.checkMode = checkMode;
510 }
511
512 /**
513 * Should {@link Attr#attribTree} use the {@code ArgumentAttr} visitor instead of this one?
514 * @param tree The tree to be type-checked.
515 * @return true if {@code ArgumentAttr} should be used.
516 */
517 protected boolean needsArgumentAttr(JCTree tree) { return false; }
518
519 protected Type check(final DiagnosticPosition pos, final Type found) {
520 return chk.checkType(pos, found, pt, checkContext);
521 }
522
523 protected ResultInfo dup(Type newPt) {
524 return new ResultInfo(pkind, newPt, checkContext, checkMode);
525 }
526
527 protected ResultInfo dup(CheckContext newContext) {
528 return new ResultInfo(pkind, pt, newContext, checkMode);
529 }
530
531 protected ResultInfo dup(Type newPt, CheckContext newContext) {
532 return new ResultInfo(pkind, newPt, newContext, checkMode);
533 }
534
535 protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) {
536 return new ResultInfo(pkind, newPt, newContext, newMode);
537 }
538
539 protected ResultInfo dup(CheckMode newMode) {
540 return new ResultInfo(pkind, pt, checkContext, newMode);
541 }
542
543 @Override
544 public String toString() {
545 if (pt != null) {
546 return pt.toString();
547 } else {
548 return "";
549 }
550 }
551 }
552
553 class MethodAttrInfo extends ResultInfo {
554 public MethodAttrInfo() {
555 this(chk.basicHandler);
556 }
557
558 public MethodAttrInfo(CheckContext checkContext) {
559 super(KindSelector.VAL, Infer.anyPoly, checkContext);
560 }
561
562 @Override
563 protected boolean needsArgumentAttr(JCTree tree) {
564 return true;
565 }
566
567 protected ResultInfo dup(Type newPt) {
568 throw new IllegalStateException();
569 }
570
571 protected ResultInfo dup(CheckContext newContext) {
572 return new MethodAttrInfo(newContext);
573 }
574
575 protected ResultInfo dup(Type newPt, CheckContext newContext) {
576 throw new IllegalStateException();
577 }
578
579 protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) {
580 throw new IllegalStateException();
581 }
582
583 protected ResultInfo dup(CheckMode newMode) {
584 throw new IllegalStateException();
585 }
586 }
587
588 class RecoveryInfo extends ResultInfo {
589
590 public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
591 this(deferredAttrContext, Type.recoveryType);
592 }
593
594 public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext, Type pt) {
595 super(KindSelector.VAL, pt, new Check.NestedCheckContext(chk.basicHandler) {
596 @Override
597 public DeferredAttr.DeferredAttrContext deferredAttrContext() {
598 return deferredAttrContext;
599 }
600 @Override
601 public boolean compatible(Type found, Type req, Warner warn) {
602 return true;
603 }
604 @Override
605 public void report(DiagnosticPosition pos, JCDiagnostic details) {
606 boolean needsReport = pt == Type.recoveryType ||
607 (details.getDiagnosticPosition() != null &&
608 details.getDiagnosticPosition().getTree().hasTag(LAMBDA));
609 if (needsReport) {
610 chk.basicHandler.report(pos, details);
611 }
612 }
613 });
614 }
615 }
616
617 final ResultInfo statInfo;
618 final ResultInfo varAssignmentInfo;
619 final ResultInfo methodAttrInfo;
620 final ResultInfo unknownExprInfo;
621 final ResultInfo unknownTypeInfo;
622 final ResultInfo unknownTypeExprInfo;
623 final ResultInfo recoveryInfo;
624 final MethodType initBlockType;
625
626 Type pt() {
627 return resultInfo.pt;
628 }
629
630 KindSelector pkind() {
631 return resultInfo.pkind;
632 }
633
634 /* ************************************************************************
635 * Visitor methods
636 *************************************************************************/
637
638 /** Visitor argument: the current environment.
639 */
640 Env<AttrContext> env;
641
642 /** Visitor argument: the currently expected attribution result.
643 */
644 ResultInfo resultInfo;
645
646 /** Visitor result: the computed type.
647 */
648 Type result;
649
650 MatchBindings matchBindings = MatchBindingsComputer.EMPTY;
651
652 /** Visitor method: attribute a tree, catching any completion failure
653 * exceptions. Return the tree's type.
654 *
655 * @param tree The tree to be visited.
656 * @param env The environment visitor argument.
657 * @param resultInfo The result info visitor argument.
658 */
659 Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
660 Env<AttrContext> prevEnv = this.env;
661 ResultInfo prevResult = this.resultInfo;
662 try {
663 this.env = env;
664 this.resultInfo = resultInfo;
665 if (resultInfo.needsArgumentAttr(tree)) {
666 result = argumentAttr.attribArg(tree, env);
667 } else {
668 tree.accept(this);
669 }
670 matchBindings = matchBindingsComputer.finishBindings(tree,
671 matchBindings);
672 if (tree == breakTree &&
673 resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
674 breakTreeFound(copyEnv(env));
675 }
676 return result;
677 } catch (CompletionFailure ex) {
678 tree.type = syms.errType;
679 return chk.completionError(tree.pos(), ex);
680 } finally {
681 this.env = prevEnv;
682 this.resultInfo = prevResult;
683 }
684 }
685
686 protected void breakTreeFound(Env<AttrContext> env) {
687 throw new BreakAttr(env);
688 }
689
690 Env<AttrContext> copyEnv(Env<AttrContext> env) {
691 Env<AttrContext> newEnv =
692 env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
693 if (newEnv.outer != null) {
694 newEnv.outer = copyEnv(newEnv.outer);
695 }
696 return newEnv;
697 }
698
699 WriteableScope copyScope(WriteableScope sc) {
700 WriteableScope newScope = WriteableScope.create(sc.owner);
701 List<Symbol> elemsList = List.nil();
702 for (Symbol sym : sc.getSymbols()) {
703 elemsList = elemsList.prepend(sym);
704 }
705 for (Symbol s : elemsList) {
706 newScope.enter(s);
707 }
708 return newScope;
709 }
710
711 /** Derived visitor method: attribute an expression tree.
712 */
713 public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
714 return attribTree(tree, env, new ResultInfo(KindSelector.VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
715 }
716
717 /** Derived visitor method: attribute an expression tree with
718 * no constraints on the computed type.
719 */
720 public Type attribExpr(JCTree tree, Env<AttrContext> env) {
721 return attribTree(tree, env, unknownExprInfo);
722 }
723
724 /** Derived visitor method: attribute a type tree.
725 */
726 public Type attribType(JCTree tree, Env<AttrContext> env) {
727 Type result = attribType(tree, env, Type.noType);
728 return result;
729 }
730
731 /** Derived visitor method: attribute a type tree.
732 */
733 Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
734 Type result = attribTree(tree, env, new ResultInfo(KindSelector.TYP, pt));
735 return result;
736 }
737
738 /** Derived visitor method: attribute a statement or definition tree.
739 */
740 public Type attribStat(JCTree tree, Env<AttrContext> env) {
741 Env<AttrContext> analyzeEnv = analyzer.copyEnvIfNeeded(tree, env);
742 Type result = attribTree(tree, env, statInfo);
743 analyzer.analyzeIfNeeded(tree, analyzeEnv);
744 attrRecover.doRecovery();
745 return result;
746 }
747
748 /** Attribute a list of expressions, returning a list of types.
749 */
750 List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
751 ListBuffer<Type> ts = new ListBuffer<>();
752 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
753 ts.append(attribExpr(l.head, env, pt));
754 return ts.toList();
755 }
756
757 /** Attribute a list of statements, returning nothing.
758 */
759 <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
760 for (List<T> l = trees; l.nonEmpty(); l = l.tail)
761 attribStat(l.head, env);
762 }
763
764 /** Attribute the arguments in a method call, returning the method kind.
765 */
766 KindSelector attribArgs(KindSelector initialKind, List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) {
767 KindSelector kind = initialKind;
768 for (JCExpression arg : trees) {
769 Type argtype = chk.checkNonVoid(arg, attribTree(arg, env, methodAttrInfo));
770 if (argtype.hasTag(DEFERRED)) {
771 kind = KindSelector.of(KindSelector.POLY, kind);
772 }
773 argtypes.append(argtype);
774 }
775 return kind;
776 }
777
778 /** Attribute a type argument list, returning a list of types.
779 * Caller is responsible for calling checkRefTypes.
780 */
781 List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
782 ListBuffer<Type> argtypes = new ListBuffer<>();
783 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
784 argtypes.append(attribType(l.head, env));
785 return argtypes.toList();
786 }
787
788 /** Attribute a type argument list, returning a list of types.
789 * Check that all the types are references.
790 */
791 List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
792 List<Type> types = attribAnyTypes(trees, env);
793 return chk.checkRefTypes(trees, types);
794 }
795
796 /**
797 * Attribute type variables (of generic classes or methods).
798 * Compound types are attributed later in attribBounds.
799 * @param typarams the type variables to enter
800 * @param env the current environment
801 */
802 void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env, boolean checkCyclic) {
803 for (JCTypeParameter tvar : typarams) {
804 TypeVar a = (TypeVar)tvar.type;
805 a.tsym.flags_field |= UNATTRIBUTED;
806 a.setUpperBound(Type.noType);
807 if (!tvar.bounds.isEmpty()) {
808 List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
809 for (JCExpression bound : tvar.bounds.tail)
810 bounds = bounds.prepend(attribType(bound, env));
811 types.setBounds(a, bounds.reverse());
812 } else {
813 // if no bounds are given, assume a single bound of
814 // java.lang.Object.
815 types.setBounds(a, List.of(syms.objectType));
816 }
817 a.tsym.flags_field &= ~UNATTRIBUTED;
818 }
819 if (checkCyclic) {
820 for (JCTypeParameter tvar : typarams) {
821 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
822 }
823 }
824 }
825
826 /**
827 * Attribute the type references in a list of annotations.
828 */
829 void attribAnnotationTypes(List<JCAnnotation> annotations,
830 Env<AttrContext> env) {
831 for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
832 JCAnnotation a = al.head;
833 attribType(a.annotationType, env);
834 }
835 }
836
837 /**
838 * Attribute a "lazy constant value".
839 * @param env The env for the const value
840 * @param variable The initializer for the const value
841 * @param type The expected type, or null
842 * @see VarSymbol#setLazyConstValue
843 */
844 public Object attribLazyConstantValue(Env<AttrContext> env,
845 Env<AttrContext> enclosingEnv,
846 JCVariableDecl variable,
847 Type type) {
848 final JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
849 try {
850 doQueueScanTreeAndTypeAnnotateForVarInit(variable, enclosingEnv);
851 Type itype = attribExpr(variable.init, env, type);
852 if (variable.isImplicitlyTyped()) {
853 //fixup local variable type
854 type = variable.type = variable.sym.type = chk.checkLocalVarType(variable, itype, variable.name);
855 }
856 if (itype.constValue() != null) {
857 return coerce(itype, type).constValue();
858 } else {
859 return null;
860 }
861 } finally {
862 log.useSource(prevSource);
863 }
864 }
865
866 /** Attribute type reference in an `extends', `implements', or 'permits' clause.
867 * Supertypes of anonymous inner classes are usually already attributed.
868 *
869 * @param tree The tree making up the type reference.
870 * @param env The environment current at the reference.
871 * @param classExpected true if only a class is expected here.
872 * @param interfaceExpected true if only an interface is expected here.
873 */
874 Type attribBase(JCTree tree,
875 Env<AttrContext> env,
876 boolean classExpected,
877 boolean interfaceExpected,
878 boolean checkExtensible) {
879 Type t = tree.type != null ?
880 tree.type :
881 attribType(tree, env);
882 try {
883 return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
884 } catch (CompletionFailure ex) {
885 chk.completionError(tree.pos(), ex);
886 return t;
887 }
888 }
889 Type checkBase(Type t,
890 JCTree tree,
891 Env<AttrContext> env,
892 boolean classExpected,
893 boolean interfaceExpected,
894 boolean checkExtensible) {
895 final DiagnosticPosition pos = tree.hasTag(TYPEAPPLY) ?
896 (((JCTypeApply) tree).clazz).pos() : tree.pos();
897 if (t.tsym.isAnonymous()) {
898 log.error(pos, Errors.CantInheritFromAnon);
899 return types.createErrorType(t);
900 }
901 if (t.isErroneous())
902 return t;
903 if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
904 // check that type variable is already visible
905 if (t.getUpperBound() == null) {
906 log.error(pos, Errors.IllegalForwardRef);
907 return types.createErrorType(t);
908 }
909 } else {
910 t = chk.checkClassType(pos, t, checkExtensible);
911 }
912 if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
913 log.error(pos, Errors.IntfExpectedHere);
914 // return errType is necessary since otherwise there might
915 // be undetected cycles which cause attribution to loop
916 return types.createErrorType(t);
917 } else if (checkExtensible &&
918 classExpected &&
919 (t.tsym.flags() & INTERFACE) != 0) {
920 log.error(pos, Errors.NoIntfExpectedHere);
921 return types.createErrorType(t);
922 }
923 if (checkExtensible &&
924 ((t.tsym.flags() & FINAL) != 0)) {
925 log.error(pos,
926 Errors.CantInheritFromFinal(t.tsym));
927 }
928 chk.checkNonCyclic(pos, t);
929 return t;
930 }
931
932 Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
933 Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
934 id.type = env.info.scope.owner.enclClass().type;
935 id.sym = env.info.scope.owner.enclClass();
936 return id.type;
937 }
938
939 public void visitClassDef(JCClassDecl tree) {
940 Optional<ArgumentAttr.LocalCacheContext> localCacheContext =
941 Optional.ofNullable(env.info.attributionMode.isSpeculative ?
942 argumentAttr.withLocalCacheContext() : null);
943 boolean ctorProloguePrev = env.info.ctorPrologue;
944 try {
945 // Local and anonymous classes have not been entered yet, so we need to
946 // do it now.
947 if (env.info.scope.owner.kind.matches(KindSelector.VAL_MTH)) {
948 enter.classEnter(tree, env);
949 } else {
950 // If this class declaration is part of a class level annotation,
951 // as in @MyAnno(new Object() {}) class MyClass {}, enter it in
952 // order to simplify later steps and allow for sensible error
953 // messages.
954 if (env.tree.hasTag(NEWCLASS) && TreeInfo.isInAnnotation(env, tree))
955 enter.classEnter(tree, env);
956 }
957
958 ClassSymbol c = tree.sym;
959 if (c == null) {
960 // exit in case something drastic went wrong during enter.
961 result = null;
962 } else {
963 // make sure class has been completed:
964 c.complete();
965
966 // If a class declaration appears in a constructor prologue,
967 // that means it's either a local class or an anonymous class.
968 // Either way, there is no immediately enclosing instance.
969 if (ctorProloguePrev) {
970 c.flags_field |= NOOUTERTHIS;
971 }
972 attribClass(tree.pos(), c);
973 result = tree.type = c.type;
974 }
975 } finally {
976 localCacheContext.ifPresent(LocalCacheContext::leave);
977 env.info.ctorPrologue = ctorProloguePrev;
978 }
979 }
980
981 public void visitMethodDef(JCMethodDecl tree) {
982 MethodSymbol m = tree.sym;
983 boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
984
985 Lint lint = env.info.lint.augment(m);
986 Lint prevLint = chk.setLint(lint);
987 boolean ctorProloguePrev = env.info.ctorPrologue;
988 Assert.check(!env.info.ctorPrologue);
989 MethodSymbol prevMethod = chk.setMethod(m);
990 try {
991 chk.checkDeprecatedAnnotation(tree.pos(), m);
992
993
994 // Create a new environment with local scope
995 // for attributing the method.
996 Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
997 localEnv.info.lint = lint;
998
999 attribStats(tree.typarams, localEnv);
1000
1001 // If we override any other methods, check that we do so properly.
1002 // JLS ???
1003 if (m.isStatic()) {
1004 chk.checkHideClashes(tree.pos(), env.enclClass.type, m);
1005 } else {
1006 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m);
1007 }
1008 chk.checkOverride(env, tree, m);
1009
1010 if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) {
1011 log.error(tree, Errors.DefaultOverridesObjectMember(m.name, Kinds.kindName(m.location()), m.location()));
1012 }
1013
1014 // Enter all type parameters into the local method scope.
1015 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
1016 localEnv.info.scope.enterIfAbsent(l.head.type.tsym);
1017
1018 ClassSymbol owner = env.enclClass.sym;
1019 if ((owner.flags() & ANNOTATION) != 0 &&
1020 (tree.params.nonEmpty() ||
1021 tree.recvparam != null))
1022 log.error(tree.params.nonEmpty() ?
1023 tree.params.head.pos() :
1024 tree.recvparam.pos(),
1025 Errors.IntfAnnotationMembersCantHaveParams);
1026
1027 // Attribute all value parameters.
1028 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1029 attribStat(l.head, localEnv);
1030 }
1031
1032 chk.checkVarargsMethodDecl(localEnv, tree);
1033
1034 // Check that type parameters are well-formed.
1035 chk.validate(tree.typarams, localEnv);
1036
1037 // Check that result type is well-formed.
1038 if (tree.restype != null && !tree.restype.type.hasTag(VOID)) {
1039 chk.validate(tree.restype, localEnv);
1040 }
1041 chk.checkRequiresIdentity(tree, env.info.lint);
1042
1043 // Check that receiver type is well-formed.
1044 if (tree.recvparam != null) {
1045 // Use a new environment to check the receiver parameter.
1046 // Otherwise I get "might not have been initialized" errors.
1047 // Is there a better way?
1048 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env);
1049 attribType(tree.recvparam, newEnv);
1050 chk.validate(tree.recvparam, newEnv);
1051 }
1052
1053 // Is this method a constructor?
1054 boolean isConstructor = TreeInfo.isConstructor(tree);
1055
1056 if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP) {
1057 // lets find if this method is an accessor
1058 Optional<? extends RecordComponent> recordComponent = env.enclClass.sym.getRecordComponents().stream()
1059 .filter(rc -> rc.accessor == tree.sym && (rc.accessor.flags_field & GENERATED_MEMBER) == 0).findFirst();
1060 if (recordComponent.isPresent()) {
1061 // the method is a user defined accessor lets check that everything is fine
1062 if (!tree.sym.isPublic()) {
1063 log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.MethodMustBePublic));
1064 }
1065 if (!types.isSameType(tree.sym.type.getReturnType(), recordComponent.get().type)) {
1066 log.error(tree, Errors.InvalidAccessorMethodInRecord(env.enclClass.sym,
1067 Fragments.AccessorReturnTypeDoesntMatch(tree.sym, recordComponent.get())));
1068 }
1069 if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1070 log.error(tree,
1071 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodCantThrowException));
1072 }
1073 if (!tree.typarams.isEmpty()) {
1074 log.error(tree,
1075 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeGeneric));
1076 }
1077 if (tree.sym.isStatic()) {
1078 log.error(tree,
1079 Errors.InvalidAccessorMethodInRecord(env.enclClass.sym, Fragments.AccessorMethodMustNotBeStatic));
1080 }
1081 }
1082
1083 if (isConstructor) {
1084 // if this a constructor other than the canonical one
1085 if ((tree.sym.flags_field & RECORD) == 0) {
1086 if (!TreeInfo.hasConstructorCall(tree, names._this)) {
1087 log.error(tree, Errors.NonCanonicalConstructorInvokeAnotherConstructor(env.enclClass.sym));
1088 }
1089 } else {
1090 // but if it is the canonical:
1091
1092 /* if user generated, then it shouldn't:
1093 * - have an accessibility stricter than that of the record type
1094 * - explicitly invoke any other constructor
1095 */
1096 if ((tree.sym.flags_field & GENERATEDCONSTR) == 0) {
1097 if (Check.protection(m.flags()) > Check.protection(env.enclClass.sym.flags())) {
1098 log.error(tree,
1099 (env.enclClass.sym.flags() & AccessFlags) == 0 ?
1100 Errors.InvalidCanonicalConstructorInRecord(
1101 Fragments.Canonical,
1102 env.enclClass.sym.name,
1103 Fragments.CanonicalMustNotHaveStrongerAccess("package")
1104 ) :
1105 Errors.InvalidCanonicalConstructorInRecord(
1106 Fragments.Canonical,
1107 env.enclClass.sym.name,
1108 Fragments.CanonicalMustNotHaveStrongerAccess(asFlagSet(env.enclClass.sym.flags() & AccessFlags))
1109 )
1110 );
1111 }
1112
1113 if ((!allowValueClasses || TreeInfo.isCompactConstructor(tree)) &&
1114 TreeInfo.hasAnyConstructorCall(tree)) {
1115 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1116 Fragments.Canonical, env.enclClass.sym.name,
1117 Fragments.CanonicalMustNotContainExplicitConstructorInvocation));
1118 }
1119 }
1120
1121 // also we want to check that no type variables have been defined
1122 if (!tree.typarams.isEmpty()) {
1123 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1124 Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalMustNotDeclareTypeVariables));
1125 }
1126
1127 /* and now we need to check that the constructor's arguments are exactly the same as those of the
1128 * record components
1129 */
1130 List<? extends RecordComponent> recordComponents = env.enclClass.sym.getRecordComponents();
1131 List<Type> recordFieldTypes = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.type);
1132 for (JCVariableDecl param: tree.params) {
1133 boolean paramIsVarArgs = (param.sym.flags_field & VARARGS) != 0;
1134 if (!types.isSameType(param.type, recordFieldTypes.head) ||
1135 (recordComponents.head.isVarargs() != paramIsVarArgs)) {
1136 log.error(param, Errors.InvalidCanonicalConstructorInRecord(
1137 Fragments.Canonical, env.enclClass.sym.name,
1138 Fragments.TypeMustBeIdenticalToCorrespondingRecordComponentType));
1139 }
1140 recordComponents = recordComponents.tail;
1141 recordFieldTypes = recordFieldTypes.tail;
1142 }
1143 }
1144 }
1145 }
1146
1147 // annotation method checks
1148 if ((owner.flags() & ANNOTATION) != 0) {
1149 // annotation method cannot have throws clause
1150 if (tree.thrown.nonEmpty()) {
1151 log.error(tree.thrown.head.pos(),
1152 Errors.ThrowsNotAllowedInIntfAnnotation);
1153 }
1154 // annotation method cannot declare type-parameters
1155 if (tree.typarams.nonEmpty()) {
1156 log.error(tree.typarams.head.pos(),
1157 Errors.IntfAnnotationMembersCantHaveTypeParams);
1158 }
1159 // validate annotation method's return type (could be an annotation type)
1160 chk.validateAnnotationType(tree.restype);
1161 // ensure that annotation method does not clash with members of Object/Annotation
1162 chk.validateAnnotationMethod(tree.pos(), m);
1163 }
1164
1165 for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail)
1166 chk.checkType(l.head.pos(), l.head.type, syms.throwableType);
1167
1168 if (tree.body == null) {
1169 // Empty bodies are only allowed for
1170 // abstract, native, or interface methods, or for methods
1171 // in a retrofit signature class.
1172 if (tree.defaultValue != null) {
1173 if ((owner.flags() & ANNOTATION) == 0)
1174 log.error(tree.pos(),
1175 Errors.DefaultAllowedInIntfAnnotationMember);
1176 }
1177 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0)
1178 log.error(tree.pos(), Errors.MissingMethBodyOrDeclAbstract(tree.sym, owner));
1179 } else {
1180 if ((tree.sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
1181 if ((owner.flags() & INTERFACE) != 0) {
1182 log.error(tree.body.pos(), Errors.IntfMethCantHaveBody);
1183 } else {
1184 log.error(tree.pos(), Errors.AbstractMethCantHaveBody);
1185 }
1186 } else if ((tree.mods.flags & NATIVE) != 0) {
1187 log.error(tree.pos(), Errors.NativeMethCantHaveBody);
1188 }
1189 // Add an implicit super() call unless an explicit call to
1190 // super(...) or this(...) is given
1191 // or we are compiling class java.lang.Object.
1192 boolean addedSuperInIdentityClass = false;
1193 if (isConstructor && owner.type != syms.objectType) {
1194 if (!TreeInfo.hasAnyConstructorCall(tree)) {
1195 JCStatement supCall = make.at(tree.body.pos).Exec(make.Apply(List.nil(),
1196 make.Ident(names._super), make.Idents(List.nil())));
1197 if (allowValueClasses && (owner.isValueClass() || owner.hasStrict() || ((owner.flags_field & RECORD) != 0))) {
1198 tree.body.stats = tree.body.stats.append(supCall);
1199 } else {
1200 tree.body.stats = tree.body.stats.prepend(supCall);
1201 addedSuperInIdentityClass = true;
1202 }
1203 } else if ((env.enclClass.sym.flags() & ENUM) != 0 &&
1204 (tree.mods.flags & GENERATEDCONSTR) == 0 &&
1205 TreeInfo.hasConstructorCall(tree, names._super)) {
1206 // enum constructors are not allowed to call super
1207 // directly, so make sure there aren't any super calls
1208 // in enum constructors, except in the compiler
1209 // generated one.
1210 log.error(tree.body.stats.head.pos(),
1211 Errors.CallToSuperNotAllowedInEnumCtor(env.enclClass.sym));
1212 }
1213 if (env.enclClass.sym.isRecord() && (tree.sym.flags_field & RECORD) != 0) { // we are seeing the canonical constructor
1214 List<Name> recordComponentNames = TreeInfo.recordFields(env.enclClass).map(vd -> vd.sym.name);
1215 List<Name> initParamNames = tree.sym.params.map(p -> p.name);
1216 if (!initParamNames.equals(recordComponentNames)) {
1217 log.error(tree, Errors.InvalidCanonicalConstructorInRecord(
1218 Fragments.Canonical, env.enclClass.sym.name, Fragments.CanonicalWithNameMismatch));
1219 }
1220 if (tree.sym.type.asMethodType().thrown != null && !tree.sym.type.asMethodType().thrown.isEmpty()) {
1221 log.error(tree,
1222 Errors.InvalidCanonicalConstructorInRecord(
1223 TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical,
1224 env.enclClass.sym.name,
1225 Fragments.ThrowsClauseNotAllowedForCanonicalConstructor(
1226 TreeInfo.isCompactConstructor(tree) ? Fragments.Compact : Fragments.Canonical)));
1227 }
1228 }
1229 }
1230
1231 // Attribute all type annotations in the body
1232 annotate.queueScanTreeAndTypeAnnotate(tree.body, localEnv, m);
1233 annotate.flush();
1234
1235 // Start of constructor prologue (if not in java.lang.Object constructor)
1236 localEnv.info.ctorPrologue = isConstructor && owner.type != syms.objectType;
1237
1238 // Attribute method body.
1239 attribStat(tree.body, localEnv);
1240 if (localEnv.info.ctorPrologue) {
1241 boolean thisInvocation = false;
1242 ListBuffer<JCTree> prologueCode = new ListBuffer<>();
1243 for (JCTree stat : tree.body.stats) {
1244 prologueCode.add(stat);
1245 /* gather all the stats in the body until a `super` or `this` constructor invocation is found,
1246 * including the constructor invocation, that way we don't need to worry in the visitor below if
1247 * if we are dealing or not with prologue code
1248 */
1249 if (stat instanceof JCExpressionStatement expStmt &&
1250 expStmt.expr instanceof JCMethodInvocation mi &&
1251 TreeInfo.isConstructorCall(mi)) {
1252 thisInvocation = TreeInfo.name(mi.meth) == names._this;
1253 if (!addedSuperInIdentityClass || !allowValueClasses) {
1254 break;
1255 }
1256 }
1257 }
1258 if (!prologueCode.isEmpty()) {
1259 CtorPrologueVisitor ctorPrologueVisitor = new CtorPrologueVisitor(localEnv,
1260 addedSuperInIdentityClass && allowValueClasses ?
1261 PrologueVisitorMode.WARNINGS_ONLY :
1262 thisInvocation ?
1263 PrologueVisitorMode.THIS_CONSTRUCTOR :
1264 PrologueVisitorMode.SUPER_CONSTRUCTOR,
1265 false);
1266 ctorPrologueVisitor.scan(prologueCode.toList());
1267 }
1268 }
1269 }
1270
1271 localEnv.info.scope.leave();
1272 result = tree.type = m.type;
1273 } finally {
1274 chk.setLint(prevLint);
1275 chk.setMethod(prevMethod);
1276 env.info.ctorPrologue = ctorProloguePrev;
1277 }
1278 }
1279
1280 enum PrologueVisitorMode {
1281 WARNINGS_ONLY,
1282 SUPER_CONSTRUCTOR,
1283 THIS_CONSTRUCTOR
1284 }
1285
1286 class CtorPrologueVisitor extends TreeScanner {
1287 Env<AttrContext> localEnv;
1288 PrologueVisitorMode mode;
1289 boolean isInitializer;
1290
1291 CtorPrologueVisitor(Env<AttrContext> localEnv, PrologueVisitorMode mode, boolean isInitializer) {
1292 this.localEnv = localEnv;
1293 currentClassSym = localEnv.enclClass.sym;
1294 this.mode = mode;
1295 this.isInitializer = isInitializer;
1296 }
1297
1298 boolean insideLambdaOrClassDef = false;
1299
1300 @Override
1301 public void visitLambda(JCLambda lambda) {
1302 boolean previousInsideLambdaOrClassDef = insideLambdaOrClassDef;
1303 try {
1304 insideLambdaOrClassDef = true;
1305 super.visitLambda(lambda);
1306 } finally {
1307 insideLambdaOrClassDef = previousInsideLambdaOrClassDef;
1308 }
1309 }
1310
1311 ClassSymbol currentClassSym;
1312
1313 @Override
1314 public void visitClassDef(JCClassDecl classDecl) {
1315 boolean previousInsideLambdaOrClassDef = insideLambdaOrClassDef;
1316 ClassSymbol previousClassSym = currentClassSym;
1317 try {
1318 insideLambdaOrClassDef = true;
1319 currentClassSym = classDecl.sym;
1320 super.visitClassDef(classDecl);
1321 } finally {
1322 insideLambdaOrClassDef = previousInsideLambdaOrClassDef;
1323 currentClassSym = previousClassSym;
1324 }
1325 }
1326
1327 private void reportPrologueError(JCTree tree, Symbol sym) {
1328 reportPrologueError(tree, sym, false);
1329 }
1330
1331 private void reportPrologueError(JCTree tree, Symbol sym, boolean hasInit) {
1332 preview.checkSourceLevel(tree, Feature.FLEXIBLE_CONSTRUCTORS);
1333 if (mode != PrologueVisitorMode.WARNINGS_ONLY) {
1334 if (hasInit) {
1335 log.error(tree, Errors.CantAssignInitializedBeforeCtorCalled(sym));
1336 } else {
1337 log.error(tree, Errors.CantRefBeforeCtorCalled(sym));
1338 }
1339 } else if (allowValueClasses) {
1340 // issue lint warning
1341 log.warning(tree, LintWarnings.WouldNotBeAllowedInPrologue(sym));
1342 }
1343 }
1344
1345 @Override
1346 public void visitApply(JCMethodInvocation tree) {
1347 super.visitApply(tree);
1348 Name name = TreeInfo.name(tree.meth);
1349 boolean isConstructorCall = name == names._this || name == names._super;
1350 Symbol msym = TreeInfo.symbolFor(tree.meth);
1351 // is this an instance method call or an illegal constructor invocation like: `this.super()`?
1352 if (msym != null && // for erroneous invocations msym can be null, ignore those
1353 (!isConstructorCall ||
1354 isConstructorCall && tree.meth.hasTag(SELECT))) {
1355 if (isEarlyReference(localEnv, tree.meth, msym))
1356 reportPrologueError(tree.meth, msym);
1357 }
1358 }
1359
1360 @Override
1361 public void visitIdent(JCIdent tree) {
1362 analyzeSymbol(tree);
1363 }
1364
1365 boolean isIndexed = false;
1366
1367 @Override
1368 public void visitIndexed(JCArrayAccess tree) {
1369 boolean previousIsIndexed = isIndexed;
1370 try {
1371 isIndexed = true;
1372 scan(tree.indexed);
1373 } finally {
1374 isIndexed = previousIsIndexed;
1375 }
1376 scan(tree.index);
1377 if (mode == PrologueVisitorMode.SUPER_CONSTRUCTOR && isInstanceField(tree.indexed)) {
1378 localProxyVarsGen.addFieldReadInPrologue(localEnv.enclMethod, TreeInfo.symbolFor(tree.indexed));
1379 }
1380 }
1381
1382 @Override
1383 public void visitSelect(JCFieldAccess tree) {
1384 SelectScanner ss = new SelectScanner();
1385 ss.scan(tree);
1386 if (ss.scanLater == null) {
1387 Symbol sym = TreeInfo.symbolFor(tree);
1388 // if this is a field access
1389 if (sym.kind == VAR && sym.owner.kind == TYP) {
1390 // Type.super.field or super.field expressions are forbidden in early construction contexts
1391 for (JCTree subtree : ss.selectorTrees) {
1392 if (TreeInfo.isSuperOrSelectorDotSuper(subtree)) {
1393 reportPrologueError(tree, sym);
1394 return;
1395 }
1396 }
1397 }
1398 analyzeSymbol(tree);
1399 } else {
1400 boolean prevLhs = isInLHS;
1401 try {
1402 isInLHS = false;
1403 scan(ss.scanLater);
1404 } finally {
1405 isInLHS = prevLhs;
1406 }
1407 }
1408 if (mode == PrologueVisitorMode.SUPER_CONSTRUCTOR) {
1409 for (JCTree subtree : ss.selectorTrees) {
1410 if (isInstanceField(subtree)) {
1411 // we need to add a proxy for this one
1412 localProxyVarsGen.addFieldReadInPrologue(localEnv.enclMethod, TreeInfo.symbolFor(subtree));
1413 }
1414 }
1415 }
1416 }
1417
1418 boolean isInstanceField(JCTree tree) {
1419 Symbol sym = TreeInfo.symbolFor(tree);
1420 return (sym != null &&
1421 !sym.isStatic() &&
1422 sym.kind == VAR &&
1423 sym.owner.kind == TYP &&
1424 sym.name != names._this &&
1425 sym.name != names._super &&
1426 isEarlyReference(localEnv, tree, sym));
1427 }
1428
1429 @Override
1430 public void visitNewClass(JCNewClass tree) {
1431 super.visitNewClass(tree);
1432 checkNewClassAndMethRefs(tree, tree.type);
1433 }
1434
1435 @Override
1436 public void visitReference(JCMemberReference tree) {
1437 super.visitReference(tree);
1438 if (tree.getMode() == JCMemberReference.ReferenceMode.NEW) {
1439 checkNewClassAndMethRefs(tree, tree.expr.type);
1440 }
1441 }
1442
1443 void checkNewClassAndMethRefs(JCTree tree, Type t) {
1444 if (t.tsym.isEnclosedBy(localEnv.enclClass.sym) &&
1445 !t.tsym.isStatic() &&
1446 !t.tsym.isDirectlyOrIndirectlyLocal()) {
1447 reportPrologueError(tree, t.getEnclosingType().tsym);
1448 }
1449 }
1450
1451 /* if a symbol is in the LHS of an assignment expression we won't consider it as a candidate
1452 * for a proxy local variable later on
1453 */
1454 boolean isInLHS = false;
1455
1456 @Override
1457 public void visitAssign(JCAssign tree) {
1458 boolean previousIsInLHS = isInLHS;
1459 try {
1460 isInLHS = true;
1461 scan(tree.lhs);
1462 } finally {
1463 isInLHS = previousIsInLHS;
1464 }
1465 scan(tree.rhs);
1466 }
1467
1468 @Override
1469 public void visitMethodDef(JCMethodDecl tree) {
1470 // ignore any declarative part, mainly to avoid scanning receiver parameters
1471 scan(tree.body);
1472 }
1473
1474 void analyzeSymbol(JCTree tree) {
1475 Symbol sym = TreeInfo.symbolFor(tree);
1476 // make sure that there is a symbol and it is not static
1477 if (sym == null || sym.isStatic()) {
1478 return;
1479 }
1480 if (isInLHS && !insideLambdaOrClassDef) {
1481 // Check instance field assignments that appear in constructor prologues
1482 if (isEarlyReference(localEnv, tree, sym)) {
1483 // Field may not be inherited from a superclass
1484 if (sym.owner != localEnv.enclClass.sym) {
1485 reportPrologueError(tree, sym);
1486 return;
1487 }
1488 // Field may not have an initializer
1489 if ((sym.flags() & HASINIT) != 0) {
1490 if (!localEnv.enclClass.sym.isValueClass() || !sym.type.hasTag(ARRAY) || !isIndexed) {
1491 reportPrologueError(tree, sym, true);
1492 }
1493 return;
1494 }
1495 // cant reference an instance field before a this constructor
1496 if (allowValueClasses && mode == PrologueVisitorMode.THIS_CONSTRUCTOR) {
1497 reportPrologueError(tree, sym);
1498 return;
1499 }
1500 }
1501 return;
1502 }
1503 tree = TreeInfo.skipParens(tree);
1504 if (sym.kind == VAR && sym.owner.kind == TYP) {
1505 if (sym.name == names._this || sym.name == names._super) {
1506 // are we seeing something like `this` or `CurrentClass.this` or `SuperClass.super::foo`?
1507 if (TreeInfo.isExplicitThisReference(
1508 types,
1509 (ClassType)localEnv.enclClass.sym.type,
1510 tree)) {
1511 reportPrologueError(tree, sym);
1512 }
1513 } else if (sym.kind == VAR && sym.owner.kind == TYP) { // now fields only
1514 if (sym.owner != localEnv.enclClass.sym) {
1515 if (localEnv.enclClass.sym.isSubClass(sym.owner, types) &&
1516 sym.isInheritedIn(localEnv.enclClass.sym, types)) {
1517 /* if we are dealing with a field that doesn't belong to the current class, but the
1518 * field is inherited, this is an error. Unless, the super class is also an outer
1519 * class and the field's qualifier refers to the outer class
1520 */
1521 if (tree.hasTag(IDENT) ||
1522 TreeInfo.isExplicitThisReference(
1523 types,
1524 (ClassType)localEnv.enclClass.sym.type,
1525 ((JCFieldAccess)tree).selected)) {
1526 reportPrologueError(tree, sym);
1527 }
1528 }
1529 } else if (isEarlyReference(localEnv, tree, sym)) {
1530 /* now this is a `proper` instance field of the current class
1531 * references to fields of identity classes which happen to have initializers are
1532 * not allowed in the prologue.
1533 * But it is OK for a field with initializer to refer to another field with initializer,
1534 * so no warning or error if we are analyzing a field initializer.
1535 */
1536 if (insideLambdaOrClassDef ||
1537 (!localEnv.enclClass.sym.isValueClass() &&
1538 (sym.flags_field & HASINIT) != 0 &&
1539 !isInitializer))
1540 reportPrologueError(tree, sym);
1541 // we will need to generate a proxy for this field later on
1542 if (!isInLHS) {
1543 if (!allowValueClasses) {
1544 reportPrologueError(tree, sym);
1545 } else {
1546 if (mode == PrologueVisitorMode.THIS_CONSTRUCTOR) {
1547 reportPrologueError(tree, sym);
1548 } else if (mode == PrologueVisitorMode.SUPER_CONSTRUCTOR) {
1549 localProxyVarsGen.addFieldReadInPrologue(localEnv.enclMethod, sym);
1550 }
1551 /* we do nothing in warnings only mode, as in that mode we are simulating what
1552 * the compiler would do in case the constructor code would be in the prologue
1553 * phase
1554 */
1555 }
1556 }
1557 }
1558 }
1559 }
1560 }
1561
1562 /**
1563 * Determine if the symbol appearance constitutes an early reference to the current class.
1564 *
1565 * <p>
1566 * This means the symbol is an instance field, or method, of the current class and it appears
1567 * in an early initialization context of it (i.e., one of its constructor prologues).
1568 *
1569 * @param env The current environment
1570 * @param tree the AST referencing the variable
1571 * @param sym The symbol
1572 */
1573 private boolean isEarlyReference(Env<AttrContext> env, JCTree tree, Symbol sym) {
1574 if ((sym.flags() & STATIC) == 0 &&
1575 (sym.kind == VAR || sym.kind == MTH) &&
1576 sym.isMemberOf(env.enclClass.sym, types)) {
1577 // Allow "Foo.this.x" when "Foo" is (also) an outer class, as this refers to the outer instance
1578 if (tree instanceof JCFieldAccess fa) {
1579 return TreeInfo.isExplicitThisReference(types, (ClassType)env.enclClass.type, fa.selected);
1580 } else if (currentClassSym != env.enclClass.sym) {
1581 /* so we are inside a class, CI, in the prologue of an outer class, CO, and the symbol being
1582 * analyzed has no qualifier. So if the symbol is a member of CI the reference is allowed,
1583 * otherwise it is not.
1584 * It could be that the reference to CI's member happens inside CI's own prologue, but that
1585 * will be checked separately, when CI's prologue is analyzed.
1586 */
1587 return !sym.isMemberOf(currentClassSym, types);
1588 }
1589 return true;
1590 }
1591 return false;
1592 }
1593
1594 /* scanner for a select expression, anything that is not a select or identifier
1595 * will be stored for further analysis
1596 */
1597 class SelectScanner extends DeferredAttr.FilterScanner {
1598 JCTree scanLater;
1599 java.util.List<JCTree> selectorTrees = new ArrayList<>();
1600
1601 SelectScanner() {
1602 super(Set.of(IDENT, SELECT, PARENS));
1603 }
1604
1605 @Override
1606 public void visitSelect(JCFieldAccess tree) {
1607 super.visitSelect(tree);
1608 selectorTrees.add(tree.selected);
1609 }
1610
1611 @Override
1612 void skip(JCTree tree) {
1613 scanLater = tree;
1614 }
1615 }
1616 }
1617
1618 public void visitVarDef(JCVariableDecl tree) {
1619 // Local variables have not been entered yet, so we need to do it now:
1620 if (env.info.scope.owner.kind == MTH || env.info.scope.owner.kind == VAR) {
1621 if (tree.sym != null) {
1622 // parameters have already been entered
1623 env.info.scope.enter(tree.sym);
1624 } else {
1625 if (tree.isImplicitlyTyped() && (tree.getModifiers().flags & PARAMETER) == 0) {
1626 if (tree.init == null) {
1627 //cannot use 'var' without initializer
1628 log.error(tree, Errors.CantInferLocalVarType(tree.name, Fragments.LocalMissingInit));
1629 tree.vartype = make.at(tree.pos()).Erroneous();
1630 } else {
1631 Fragment msg = canInferLocalVarType(tree);
1632 if (msg != null) {
1633 //cannot use 'var' with initializer which require an explicit target
1634 //(e.g. lambda, method reference, array initializer).
1635 log.error(tree, Errors.CantInferLocalVarType(tree.name, msg));
1636 tree.vartype = make.at(tree.pos()).Erroneous();
1637 }
1638 }
1639 }
1640 try {
1641 annotate.blockAnnotations();
1642 memberEnter.memberEnter(tree, env);
1643 } finally {
1644 annotate.unblockAnnotations();
1645 }
1646 }
1647 } else {
1648 doQueueScanTreeAndTypeAnnotateForVarInit(tree, env);
1649 }
1650
1651 VarSymbol v = tree.sym;
1652 Lint lint = env.info.lint.augment(v);
1653 Lint prevLint = chk.setLint(lint);
1654
1655 // Check that the variable's declared type is well-formed.
1656 boolean isImplicitLambdaParameter = env.tree.hasTag(LAMBDA) &&
1657 ((JCLambda)env.tree).paramKind == JCLambda.ParameterKind.IMPLICIT &&
1658 (tree.sym.flags() & PARAMETER) != 0;
1659 chk.validate(tree.vartype, env, !isImplicitLambdaParameter && !tree.isImplicitlyTyped());
1660
1661 try {
1662 v.getConstValue(); // ensure compile-time constant initializer is evaluated
1663 chk.checkDeprecatedAnnotation(tree.pos(), v);
1664
1665 if (tree.init != null) {
1666 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env);
1667 if ((v.flags_field & FINAL) == 0 ||
1668 !memberEnter.needsLazyConstValue(tree.init)) {
1669 // Not a compile-time constant
1670 // Attribute initializer in a new environment
1671 // with the declared variable as owner.
1672 // Check that initializer conforms to variable's declared type.
1673 initEnv.info.lint = lint;
1674 // In order to catch self-references, we set the variable's
1675 // declaration position to maximal possible value, effectively
1676 // marking the variable as undefined.
1677 initEnv.info.enclVar = v;
1678 boolean previousCtorPrologue = initEnv.info.ctorPrologue;
1679 try {
1680 if (v.owner.kind == TYP && !v.isStatic() && v.isStrict()) {
1681 // strict instance initializer in a value class
1682 initEnv.info.ctorPrologue = true;
1683 }
1684 attribExpr(tree.init, initEnv, v.type);
1685 if (tree.isImplicitlyTyped()) {
1686 //fixup local variable type
1687 v.type = chk.checkLocalVarType(tree, tree.init.type, tree.name);
1688 }
1689 } finally {
1690 initEnv.info.ctorPrologue = previousCtorPrologue;
1691 }
1692 }
1693 if (allowValueClasses && v.owner.kind == TYP && !v.isStatic()) {
1694 // strict field initializers are inlined in constructor's prologues
1695 CtorPrologueVisitor ctorPrologueVisitor = new CtorPrologueVisitor(initEnv,
1696 !v.isStrict() ? PrologueVisitorMode.WARNINGS_ONLY : PrologueVisitorMode.SUPER_CONSTRUCTOR,
1697 true);
1698 ctorPrologueVisitor.scan(tree.init);
1699 }
1700 if (tree.isImplicitlyTyped()) {
1701 setSyntheticVariableType(tree, v.type);
1702 }
1703 }
1704 result = tree.type = v.type;
1705 if (env.enclClass.sym.isRecord() && tree.sym.owner.kind == TYP && !v.isStatic()) {
1706 if (isNonArgsMethodInObject(v.name)) {
1707 log.error(tree, Errors.IllegalRecordComponentName(v));
1708 }
1709 }
1710 chk.checkRequiresIdentity(tree, env.info.lint);
1711 }
1712 finally {
1713 chk.setLint(prevLint);
1714 }
1715 }
1716
1717 private void doQueueScanTreeAndTypeAnnotateForVarInit(JCVariableDecl tree, Env<AttrContext> env) {
1718 if (tree.init != null &&
1719 (tree.mods.flags & Flags.FIELD_INIT_TYPE_ANNOTATIONS_QUEUED) == 0 &&
1720 env.info.scope.owner.kind != MTH && env.info.scope.owner.kind != VAR) {
1721 tree.mods.flags |= Flags.FIELD_INIT_TYPE_ANNOTATIONS_QUEUED;
1722 // Field initializer expression need to be entered.
1723 annotate.queueScanTreeAndTypeAnnotate(tree.init, env, tree.sym);
1724 annotate.flush();
1725 }
1726 }
1727
1728 private boolean isNonArgsMethodInObject(Name name) {
1729 for (Symbol s : syms.objectType.tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) {
1730 if (s.type.getParameterTypes().isEmpty()) {
1731 return true;
1732 }
1733 }
1734 return false;
1735 }
1736
1737 Fragment canInferLocalVarType(JCVariableDecl tree) {
1738 LocalInitScanner lis = new LocalInitScanner();
1739 lis.scan(tree.init);
1740 return lis.badInferenceMsg;
1741 }
1742
1743 static class LocalInitScanner extends TreeScanner {
1744 Fragment badInferenceMsg = null;
1745 boolean needsTarget = true;
1746
1747 @Override
1748 public void visitNewArray(JCNewArray tree) {
1749 if (tree.elemtype == null && needsTarget) {
1750 badInferenceMsg = Fragments.LocalArrayMissingTarget;
1751 }
1752 }
1753
1754 @Override
1755 public void visitLambda(JCLambda tree) {
1756 if (needsTarget) {
1757 badInferenceMsg = Fragments.LocalLambdaMissingTarget;
1758 }
1759 }
1760
1761 @Override
1762 public void visitTypeCast(JCTypeCast tree) {
1763 boolean prevNeedsTarget = needsTarget;
1764 try {
1765 needsTarget = false;
1766 super.visitTypeCast(tree);
1767 } finally {
1768 needsTarget = prevNeedsTarget;
1769 }
1770 }
1771
1772 @Override
1773 public void visitReference(JCMemberReference tree) {
1774 if (needsTarget) {
1775 badInferenceMsg = Fragments.LocalMrefMissingTarget;
1776 }
1777 }
1778
1779 @Override
1780 public void visitNewClass(JCNewClass tree) {
1781 boolean prevNeedsTarget = needsTarget;
1782 try {
1783 needsTarget = false;
1784 super.visitNewClass(tree);
1785 } finally {
1786 needsTarget = prevNeedsTarget;
1787 }
1788 }
1789
1790 @Override
1791 public void visitApply(JCMethodInvocation tree) {
1792 boolean prevNeedsTarget = needsTarget;
1793 try {
1794 needsTarget = false;
1795 super.visitApply(tree);
1796 } finally {
1797 needsTarget = prevNeedsTarget;
1798 }
1799 }
1800 }
1801
1802 public void visitSkip(JCSkip tree) {
1803 result = null;
1804 }
1805
1806 public void visitBlock(JCBlock tree) {
1807 if (env.info.scope.owner.kind == TYP || env.info.scope.owner.kind == ERR) {
1808 // Block is a static or instance initializer;
1809 // let the owner of the environment be a freshly
1810 // created BLOCK-method.
1811 Symbol fakeOwner =
1812 new MethodSymbol(tree.flags | BLOCK |
1813 env.info.scope.owner.flags() & STRICTFP, names.empty, initBlockType,
1814 env.info.scope.owner);
1815 final Env<AttrContext> localEnv =
1816 env.dup(tree, env.info.dup(env.info.scope.dupUnshared(fakeOwner)));
1817
1818 if ((tree.flags & STATIC) != 0) {
1819 localEnv.info.staticLevel++;
1820 } else {
1821 localEnv.info.instanceInitializerBlock = true;
1822 }
1823 // Attribute all type annotations in the block
1824 annotate.queueScanTreeAndTypeAnnotate(tree, localEnv, localEnv.info.scope.owner);
1825 annotate.flush();
1826 attribStats(tree.stats, localEnv);
1827
1828 {
1829 // Store init and clinit type annotations with the ClassSymbol
1830 // to allow output in Gen.normalizeDefs.
1831 ClassSymbol cs = (ClassSymbol)env.info.scope.owner;
1832 List<Attribute.TypeCompound> tas = localEnv.info.scope.owner.getRawTypeAttributes();
1833 if ((tree.flags & STATIC) != 0) {
1834 cs.appendClassInitTypeAttributes(tas);
1835 } else {
1836 cs.appendInitTypeAttributes(tas);
1837 }
1838 }
1839 } else {
1840 // Create a new local environment with a local scope.
1841 Env<AttrContext> localEnv =
1842 env.dup(tree, env.info.dup(env.info.scope.dup()));
1843 try {
1844 attribStats(tree.stats, localEnv);
1845 } finally {
1846 localEnv.info.scope.leave();
1847 }
1848 }
1849 result = null;
1850 }
1851
1852 public void visitDoLoop(JCDoWhileLoop tree) {
1853 attribStat(tree.body, env.dup(tree));
1854 attribExpr(tree.cond, env, syms.booleanType);
1855 handleLoopConditionBindings(matchBindings, tree, tree.body);
1856 result = null;
1857 }
1858
1859 public void visitWhileLoop(JCWhileLoop tree) {
1860 attribExpr(tree.cond, env, syms.booleanType);
1861 MatchBindings condBindings = matchBindings;
1862 // include condition's bindings when true in the body:
1863 Env<AttrContext> whileEnv = bindingEnv(env, condBindings.bindingsWhenTrue);
1864 try {
1865 attribStat(tree.body, whileEnv.dup(tree));
1866 } finally {
1867 whileEnv.info.scope.leave();
1868 }
1869 handleLoopConditionBindings(condBindings, tree, tree.body);
1870 result = null;
1871 }
1872
1873 public void visitForLoop(JCForLoop tree) {
1874 Env<AttrContext> loopEnv =
1875 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1876 MatchBindings condBindings = MatchBindingsComputer.EMPTY;
1877 try {
1878 attribStats(tree.init, loopEnv);
1879 if (tree.cond != null) {
1880 attribExpr(tree.cond, loopEnv, syms.booleanType);
1881 // include condition's bindings when true in the body and step:
1882 condBindings = matchBindings;
1883 }
1884 Env<AttrContext> bodyEnv = bindingEnv(loopEnv, condBindings.bindingsWhenTrue);
1885 try {
1886 bodyEnv.tree = tree; // before, we were not in loop!
1887 attribStats(tree.step, bodyEnv);
1888 attribStat(tree.body, bodyEnv);
1889 } finally {
1890 bodyEnv.info.scope.leave();
1891 }
1892 result = null;
1893 }
1894 finally {
1895 loopEnv.info.scope.leave();
1896 }
1897 handleLoopConditionBindings(condBindings, tree, tree.body);
1898 }
1899
1900 /**
1901 * Include condition's bindings when false after the loop, if cannot get out of the loop
1902 */
1903 private void handleLoopConditionBindings(MatchBindings condBindings,
1904 JCStatement loop,
1905 JCStatement loopBody) {
1906 if (condBindings.bindingsWhenFalse.nonEmpty() &&
1907 !breaksTo(env, loop, loopBody)) {
1908 addBindings2Scope(loop, condBindings.bindingsWhenFalse);
1909 }
1910 }
1911
1912 private boolean breaksTo(Env<AttrContext> env, JCTree loop, JCTree body) {
1913 preFlow(body);
1914 return flow.breaksToTree(env, loop, body, make);
1915 }
1916
1917 /**
1918 * Add given bindings to the current scope, unless there's a break to
1919 * an immediately enclosing labeled statement.
1920 */
1921 private void addBindings2Scope(JCStatement introducingStatement,
1922 List<BindingSymbol> bindings) {
1923 if (bindings.isEmpty()) {
1924 return ;
1925 }
1926
1927 var searchEnv = env;
1928 while (searchEnv.tree instanceof JCLabeledStatement labeled &&
1929 labeled.body == introducingStatement) {
1930 if (breaksTo(env, labeled, labeled.body)) {
1931 //breaking to an immediately enclosing labeled statement
1932 return ;
1933 }
1934 searchEnv = searchEnv.next;
1935 introducingStatement = labeled;
1936 }
1937
1938 //include condition's body when false after the while, if cannot get out of the loop
1939 bindings.forEach(env.info.scope::enter);
1940 bindings.forEach(BindingSymbol::preserveBinding);
1941 }
1942
1943 public void visitForeachLoop(JCEnhancedForLoop tree) {
1944 Env<AttrContext> loopEnv =
1945 env.dup(env.tree, env.info.dup(env.info.scope.dup()));
1946 try {
1947 //the Formal Parameter of a for-each loop is not in the scope when
1948 //attributing the for-each expression; we mimic this by attributing
1949 //the for-each expression first (against original scope).
1950 Type exprType = types.cvarUpperBound(attribExpr(tree.expr, loopEnv));
1951 chk.checkNonVoid(tree.pos(), exprType);
1952 Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
1953 if (elemtype == null) {
1954 // or perhaps expr implements Iterable<T>?
1955 Type base = types.asSuper(exprType, syms.iterableType.tsym);
1956 if (base == null) {
1957 log.error(tree.expr.pos(),
1958 Errors.ForeachNotApplicableToType(exprType,
1959 Fragments.TypeReqArrayOrIterable));
1960 elemtype = types.createErrorType(exprType);
1961 } else {
1962 List<Type> iterableParams = base.allparams();
1963 elemtype = iterableParams.isEmpty()
1964 ? syms.objectType
1965 : types.wildUpperBound(iterableParams.head);
1966
1967 // Check the return type of the method iterator().
1968 // This is the bare minimum we need to verify to make sure code generation doesn't crash.
1969 Symbol iterSymbol = rs.resolveInternalMethod(tree.pos(),
1970 loopEnv, types.skipTypeVars(exprType, false), names.iterator, List.nil(), List.nil());
1971 if (types.asSuper(iterSymbol.type.getReturnType(), syms.iteratorType.tsym) == null) {
1972 log.error(tree.pos(),
1973 Errors.ForeachNotApplicableToType(exprType, Fragments.TypeReqArrayOrIterable));
1974 }
1975 }
1976 }
1977 if (tree.var.isImplicitlyTyped()) {
1978 Type inferredType = chk.checkLocalVarType(tree.var, elemtype, tree.var.name);
1979 setSyntheticVariableType(tree.var, inferredType);
1980 }
1981 attribStat(tree.var, loopEnv);
1982 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type);
1983 loopEnv.tree = tree; // before, we were not in loop!
1984 attribStat(tree.body, loopEnv);
1985 result = null;
1986 }
1987 finally {
1988 loopEnv.info.scope.leave();
1989 }
1990 }
1991
1992 public void visitLabelled(JCLabeledStatement tree) {
1993 // Check that label is not used in an enclosing statement
1994 Env<AttrContext> env1 = env;
1995 while (env1 != null && !env1.tree.hasTag(CLASSDEF)) {
1996 if (env1.tree.hasTag(LABELLED) &&
1997 ((JCLabeledStatement) env1.tree).label == tree.label) {
1998 log.error(tree.pos(),
1999 Errors.LabelAlreadyInUse(tree.label));
2000 break;
2001 }
2002 env1 = env1.next;
2003 }
2004
2005 attribStat(tree.body, env.dup(tree));
2006 result = null;
2007 }
2008
2009 public void visitSwitch(JCSwitch tree) {
2010 handleSwitch(tree, tree.selector, tree.cases, (c, caseEnv) -> {
2011 attribStats(c.stats, caseEnv);
2012 });
2013 result = null;
2014 }
2015
2016 public void visitSwitchExpression(JCSwitchExpression tree) {
2017 boolean wrongContext = false;
2018
2019 tree.polyKind = (pt().hasTag(NONE) && pt() != Type.recoveryType && pt() != Infer.anyPoly) ?
2020 PolyKind.STANDALONE : PolyKind.POLY;
2021
2022 if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
2023 //this means we are returning a poly conditional from void-compatible lambda expression
2024 resultInfo.checkContext.report(tree, diags.fragment(Fragments.SwitchExpressionTargetCantBeVoid));
2025 resultInfo = recoveryInfo;
2026 wrongContext = true;
2027 }
2028
2029 ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
2030 unknownExprInfo :
2031 resultInfo.dup(switchExpressionContext(resultInfo.checkContext));
2032
2033 ListBuffer<DiagnosticPosition> caseTypePositions = new ListBuffer<>();
2034 ListBuffer<Type> caseTypes = new ListBuffer<>();
2035
2036 handleSwitch(tree, tree.selector, tree.cases, (c, caseEnv) -> {
2037 caseEnv.info.yieldResult = condInfo;
2038 attribStats(c.stats, caseEnv);
2039 new TreeScanner() {
2040 @Override
2041 public void visitYield(JCYield brk) {
2042 if (brk.target == tree) {
2043 caseTypePositions.append(brk.value != null ? brk.value.pos() : brk.pos());
2044 caseTypes.append(brk.value != null ? brk.value.type : syms.errType);
2045 }
2046 super.visitYield(brk);
2047 }
2048
2049 @Override public void visitClassDef(JCClassDecl tree) {}
2050 @Override public void visitLambda(JCLambda tree) {}
2051 }.scan(c.stats);
2052 });
2053
2054 if (tree.cases.isEmpty()) {
2055 log.error(tree.pos(),
2056 Errors.SwitchExpressionEmpty);
2057 } else if (caseTypes.isEmpty()) {
2058 log.error(tree.pos(),
2059 Errors.SwitchExpressionNoResultExpressions);
2060 }
2061
2062 Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(caseTypePositions.toList(), caseTypes.toList()) : pt();
2063
2064 result = tree.type = wrongContext? types.createErrorType(pt()) : check(tree, owntype, KindSelector.VAL, resultInfo);
2065 }
2066 //where:
2067 CheckContext switchExpressionContext(CheckContext checkContext) {
2068 return new Check.NestedCheckContext(checkContext) {
2069 //this will use enclosing check context to check compatibility of
2070 //subexpression against target type; if we are in a method check context,
2071 //depending on whether boxing is allowed, we could have incompatibilities
2072 @Override
2073 public void report(DiagnosticPosition pos, JCDiagnostic details) {
2074 enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleTypeInSwitchExpression(details)));
2075 }
2076 };
2077 }
2078
2079 private void handleSwitch(JCTree switchTree,
2080 JCExpression selector,
2081 List<JCCase> cases,
2082 BiConsumer<JCCase, Env<AttrContext>> attribCase) {
2083 Type seltype = attribExpr(selector, env);
2084 Type seltypeUnboxed = types.unboxedTypeOrType(seltype);
2085
2086 Env<AttrContext> switchEnv =
2087 env.dup(switchTree, env.info.dup(env.info.scope.dup()));
2088
2089 try {
2090 boolean enumSwitch = (seltype.tsym.flags() & Flags.ENUM) != 0;
2091 boolean stringSwitch = types.isSameType(seltype, syms.stringType);
2092 boolean booleanSwitch = types.isSameType(seltypeUnboxed, syms.booleanType);
2093 boolean errorEnumSwitch = TreeInfo.isErrorEnumSwitch(selector, cases);
2094 boolean intSwitch = types.isAssignable(seltype, syms.intType);
2095 boolean patternSwitch;
2096 if (seltype.isPrimitive() && !intSwitch) {
2097 preview.checkSourceLevel(selector.pos(), Feature.PRIMITIVE_PATTERNS);
2098 patternSwitch = true;
2099 }
2100 if (!enumSwitch && !stringSwitch && !errorEnumSwitch &&
2101 !intSwitch) {
2102 preview.checkSourceLevel(selector.pos(), Feature.PATTERN_SWITCH);
2103 patternSwitch = true;
2104 } else {
2105 patternSwitch = cases.stream()
2106 .flatMap(c -> c.labels.stream())
2107 .anyMatch(l -> l.hasTag(PATTERNCASELABEL) ||
2108 TreeInfo.isNullCaseLabel(l));
2109 }
2110
2111 // Attribute all cases and
2112 // check that there are no duplicate case labels or default clauses.
2113 Set<Object> constants = new HashSet<>(); // The set of case constants.
2114 boolean hasDefault = false; // Is there a default label?
2115 boolean hasUnconditionalPattern = false; // Is there a unconditional pattern?
2116 boolean lastPatternErroneous = false; // Has the last pattern erroneous type?
2117 boolean hasNullPattern = false; // Is there a null pattern?
2118 CaseTree.CaseKind caseKind = null;
2119 boolean wasError = false;
2120 JCCaseLabel unconditionalCaseLabel = null;
2121 for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
2122 JCCase c = l.head;
2123 if (caseKind == null) {
2124 caseKind = c.caseKind;
2125 } else if (caseKind != c.caseKind && !wasError) {
2126 log.error(c.pos(),
2127 Errors.SwitchMixingCaseTypes);
2128 wasError = true;
2129 }
2130 MatchBindings currentBindings = null;
2131 MatchBindings guardBindings = null;
2132 for (List<JCCaseLabel> labels = c.labels; labels.nonEmpty(); labels = labels.tail) {
2133 JCCaseLabel label = labels.head;
2134 if (label instanceof JCConstantCaseLabel constLabel) {
2135 JCExpression expr = constLabel.expr;
2136 if (TreeInfo.isNull(expr)) {
2137 preview.checkSourceLevel(expr.pos(), Feature.CASE_NULL);
2138 if (hasNullPattern) {
2139 log.error(label.pos(), Errors.DuplicateCaseLabel);
2140 }
2141 hasNullPattern = true;
2142 attribExpr(expr, switchEnv, seltype);
2143 matchBindings = new MatchBindings(matchBindings.bindingsWhenTrue, matchBindings.bindingsWhenFalse, true);
2144 } else if (enumSwitch) {
2145 Symbol sym = enumConstant(expr, seltype);
2146 if (sym == null) {
2147 if (allowPatternSwitch) {
2148 attribTree(expr, switchEnv, caseLabelResultInfo(seltype));
2149 Symbol enumSym = TreeInfo.symbol(expr);
2150 if (enumSym == null || !enumSym.isEnum() || enumSym.kind != VAR) {
2151 log.error(expr.pos(), Errors.EnumLabelMustBeEnumConstant);
2152 } else if (!constants.add(enumSym)) {
2153 log.error(label.pos(), Errors.DuplicateCaseLabel);
2154 }
2155 } else {
2156 log.error(expr.pos(), Errors.EnumLabelMustBeUnqualifiedEnum);
2157 }
2158 } else if (!constants.add(sym)) {
2159 log.error(label.pos(), Errors.DuplicateCaseLabel);
2160 }
2161 } else if (errorEnumSwitch) {
2162 //error recovery: the selector is erroneous, and all the case labels
2163 //are identifiers. This could be an enum switch - don't report resolve
2164 //error for the case label:
2165 var prevResolveHelper = rs.basicLogResolveHelper;
2166 try {
2167 rs.basicLogResolveHelper = rs.silentLogResolveHelper;
2168 attribExpr(expr, switchEnv, seltype);
2169 } finally {
2170 rs.basicLogResolveHelper = prevResolveHelper;
2171 }
2172 } else {
2173 Type pattype = attribTree(expr, switchEnv, caseLabelResultInfo(seltype));
2174 if (!pattype.hasTag(ERROR)) {
2175 if (pattype.constValue() == null) {
2176 Symbol s = TreeInfo.symbol(expr);
2177 if (s != null && s.kind == TYP) {
2178 log.error(expr.pos(),
2179 Errors.PatternExpected);
2180 } else if (s == null || !s.isEnum()) {
2181 log.error(expr.pos(),
2182 (stringSwitch ? Errors.StringConstReq
2183 : intSwitch ? Errors.ConstExprReq
2184 : Errors.PatternOrEnumReq));
2185 } else if (!constants.add(s)) {
2186 log.error(label.pos(), Errors.DuplicateCaseLabel);
2187 }
2188 }
2189 else {
2190 boolean isLongFloatDoubleOrBooleanConstant =
2191 pattype.getTag().isInSuperClassesOf(LONG) || pattype.getTag().equals(BOOLEAN);
2192 if (isLongFloatDoubleOrBooleanConstant) {
2193 preview.checkSourceLevel(label.pos(), Feature.PRIMITIVE_PATTERNS);
2194 }
2195 if (!stringSwitch && !intSwitch && !(isLongFloatDoubleOrBooleanConstant && types.isSameType(seltypeUnboxed, pattype))) {
2196 log.error(label.pos(), Errors.ConstantLabelNotCompatible(pattype, seltype));
2197 } else if (!constants.add(pattype.constValue())) {
2198 log.error(c.pos(), Errors.DuplicateCaseLabel);
2199 }
2200 }
2201 }
2202 }
2203 } else if (label instanceof JCDefaultCaseLabel def) {
2204 if (hasDefault) {
2205 log.error(label.pos(), Errors.DuplicateDefaultLabel);
2206 } else if (hasUnconditionalPattern) {
2207 log.error(label.pos(), Errors.UnconditionalPatternAndDefault);
2208 } else if (booleanSwitch && constants.containsAll(Set.of(0, 1))) {
2209 log.error(label.pos(), Errors.DefaultAndBothBooleanValues);
2210 }
2211 hasDefault = true;
2212 matchBindings = MatchBindingsComputer.EMPTY;
2213 } else if (label instanceof JCPatternCaseLabel patternlabel) {
2214 //pattern
2215 JCPattern pat = patternlabel.pat;
2216 attribExpr(pat, switchEnv, seltype);
2217 Type primaryType = TreeInfo.primaryPatternType(pat);
2218
2219 if (primaryType.isPrimitive()) {
2220 preview.checkSourceLevel(pat.pos(), Feature.PRIMITIVE_PATTERNS);
2221 } else if (!primaryType.hasTag(TYPEVAR)) {
2222 primaryType = chk.checkClassOrArrayType(pat.pos(), primaryType);
2223 }
2224 checkCastablePattern(pat.pos(), seltype, primaryType);
2225 Type patternType = types.erasure(primaryType);
2226 JCExpression guard = c.guard;
2227 if (guardBindings == null && guard != null) {
2228 MatchBindings afterPattern = matchBindings;
2229 Env<AttrContext> bodyEnv = bindingEnv(switchEnv, matchBindings.bindingsWhenTrue);
2230 try {
2231 attribExpr(guard, bodyEnv, syms.booleanType);
2232 } finally {
2233 bodyEnv.info.scope.leave();
2234 }
2235
2236 guardBindings = matchBindings;
2237 matchBindings = afterPattern;
2238
2239 if (TreeInfo.isBooleanWithValue(guard, 0)) {
2240 log.error(guard.pos(), Errors.GuardHasConstantExpressionFalse);
2241 }
2242 }
2243 boolean unguarded = TreeInfo.unguardedCase(c) && !pat.hasTag(RECORDPATTERN);
2244 boolean unconditional =
2245 unguarded &&
2246 !patternType.isErroneous() &&
2247 types.isUnconditionallyExact(seltype, patternType);
2248 if (unconditional) {
2249 if (hasUnconditionalPattern) {
2250 log.error(pat.pos(), Errors.DuplicateUnconditionalPattern);
2251 } else if (hasDefault) {
2252 log.error(pat.pos(), Errors.UnconditionalPatternAndDefault);
2253 } else if (booleanSwitch && constants.containsAll(Set.of(0, 1))) {
2254 log.error(pat.pos(), Errors.UnconditionalPatternAndBothBooleanValues);
2255 }
2256 hasUnconditionalPattern = true;
2257 unconditionalCaseLabel = label;
2258 }
2259 lastPatternErroneous = patternType.isErroneous();
2260 } else {
2261 Assert.error();
2262 }
2263 currentBindings = matchBindingsComputer.switchCase(label, currentBindings, matchBindings);
2264 }
2265
2266 if (guardBindings != null) {
2267 currentBindings = matchBindingsComputer.caseGuard(c, currentBindings, guardBindings);
2268 }
2269
2270 Env<AttrContext> caseEnv =
2271 bindingEnv(switchEnv, c, currentBindings.bindingsWhenTrue);
2272 try {
2273 attribCase.accept(c, caseEnv);
2274 } finally {
2275 caseEnv.info.scope.leave();
2276 }
2277 addVars(c.stats, switchEnv.info.scope);
2278
2279 preFlow(c);
2280 c.completesNormally = flow.aliveAfter(caseEnv, c, make);
2281 }
2282 if (patternSwitch) {
2283 chk.checkSwitchCaseStructure(cases);
2284 chk.checkSwitchCaseLabelDominated(unconditionalCaseLabel, cases);
2285 }
2286 if (switchTree.hasTag(SWITCH)) {
2287 ((JCSwitch) switchTree).hasUnconditionalPattern =
2288 hasDefault || hasUnconditionalPattern || lastPatternErroneous;
2289 ((JCSwitch) switchTree).patternSwitch = patternSwitch;
2290 } else if (switchTree.hasTag(SWITCH_EXPRESSION)) {
2291 ((JCSwitchExpression) switchTree).hasUnconditionalPattern =
2292 hasDefault || hasUnconditionalPattern || lastPatternErroneous;
2293 ((JCSwitchExpression) switchTree).patternSwitch = patternSwitch;
2294 } else {
2295 Assert.error(switchTree.getTag().name());
2296 }
2297 } finally {
2298 switchEnv.info.scope.leave();
2299 }
2300 }
2301 // where
2302 private ResultInfo caseLabelResultInfo(Type seltype) {
2303 return new ResultInfo(KindSelector.VAL_TYP,
2304 !seltype.hasTag(ERROR) ? seltype
2305 : Type.noType);
2306 }
2307 /** Add any variables defined in stats to the switch scope. */
2308 private static void addVars(List<JCStatement> stats, WriteableScope switchScope) {
2309 for (;stats.nonEmpty(); stats = stats.tail) {
2310 JCTree stat = stats.head;
2311 if (stat.hasTag(VARDEF))
2312 switchScope.enter(((JCVariableDecl) stat).sym);
2313 }
2314 }
2315 // where
2316 /** Return the selected enumeration constant symbol, or null. */
2317 private Symbol enumConstant(JCTree tree, Type enumType) {
2318 if (tree.hasTag(IDENT)) {
2319 JCIdent ident = (JCIdent)tree;
2320 Name name = ident.name;
2321 for (Symbol sym : enumType.tsym.members().getSymbolsByName(name)) {
2322 if (sym.kind == VAR) {
2323 Symbol s = ident.sym = sym;
2324 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated
2325 ident.type = s.type;
2326 return ((s.flags_field & Flags.ENUM) == 0)
2327 ? null : s;
2328 }
2329 }
2330 }
2331 return null;
2332 }
2333
2334 public void visitSynchronized(JCSynchronized tree) {
2335 boolean identityType = chk.checkIdentityType(tree.pos(), attribExpr(tree.lock, env));
2336 if (identityType && tree.lock.type != null && tree.lock.type.isValueBased()) {
2337 log.warning(tree.pos(), LintWarnings.AttemptToSynchronizeOnInstanceOfValueBasedClass);
2338 }
2339 attribStat(tree.body, env);
2340 result = null;
2341 }
2342
2343 public void visitTry(JCTry tree) {
2344 // Create a new local environment with a local
2345 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
2346 try {
2347 boolean isTryWithResource = tree.resources.nonEmpty();
2348 // Create a nested environment for attributing the try block if needed
2349 Env<AttrContext> tryEnv = isTryWithResource ?
2350 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) :
2351 localEnv;
2352 try {
2353 // Attribute resource declarations
2354 for (JCTree resource : tree.resources) {
2355 CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) {
2356 @Override
2357 public void report(DiagnosticPosition pos, JCDiagnostic details) {
2358 chk.basicHandler.report(pos, diags.fragment(Fragments.TryNotApplicableToType(details)));
2359 }
2360 };
2361 ResultInfo twrResult =
2362 new ResultInfo(KindSelector.VAR,
2363 syms.autoCloseableType,
2364 twrContext);
2365 if (resource.hasTag(VARDEF)) {
2366 attribStat(resource, tryEnv);
2367 twrResult.check(resource, resource.type);
2368
2369 //check that resource type cannot throw InterruptedException
2370 checkAutoCloseable(localEnv, resource, true);
2371
2372 VarSymbol var = ((JCVariableDecl) resource).sym;
2373
2374 var.flags_field |= Flags.FINAL;
2375 var.setData(ElementKind.RESOURCE_VARIABLE);
2376 } else {
2377 attribTree(resource, tryEnv, twrResult);
2378 }
2379 }
2380 // Attribute body
2381 attribStat(tree.body, tryEnv);
2382 } finally {
2383 if (isTryWithResource)
2384 tryEnv.info.scope.leave();
2385 }
2386
2387 // Attribute catch clauses
2388 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
2389 JCCatch c = l.head;
2390 Env<AttrContext> catchEnv =
2391 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup()));
2392 try {
2393 Type ctype = attribStat(c.param, catchEnv);
2394 if (TreeInfo.isMultiCatch(c)) {
2395 //multi-catch parameter is implicitly marked as final
2396 c.param.sym.flags_field |= FINAL | UNION;
2397 }
2398 if (c.param.sym.kind == VAR) {
2399 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER);
2400 }
2401 chk.checkType(c.param.vartype.pos(),
2402 chk.checkClassType(c.param.vartype.pos(), ctype),
2403 syms.throwableType);
2404 attribStat(c.body, catchEnv);
2405 } finally {
2406 catchEnv.info.scope.leave();
2407 }
2408 }
2409
2410 // Attribute finalizer
2411 if (tree.finalizer != null) attribStat(tree.finalizer, localEnv);
2412 result = null;
2413 }
2414 finally {
2415 localEnv.info.scope.leave();
2416 }
2417 }
2418
2419 void checkAutoCloseable(Env<AttrContext> env, JCTree tree, boolean useSite) {
2420 DiagnosticPosition pos = tree.pos();
2421 Type resource = tree.type;
2422 if (!resource.isErroneous() &&
2423 types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
2424 !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
2425 Symbol close = syms.noSymbol;
2426 Log.DiagnosticHandler discardHandler = log.new DiscardDiagnosticHandler();
2427 try {
2428 close = rs.resolveQualifiedMethod(pos,
2429 env,
2430 types.skipTypeVars(resource, false),
2431 names.close,
2432 List.nil(),
2433 List.nil());
2434 }
2435 finally {
2436 log.popDiagnosticHandler(discardHandler);
2437 }
2438 if (close.kind == MTH &&
2439 (useSite || close.owner != syms.autoCloseableType.tsym) &&
2440 ((MethodSymbol)close).binaryOverrides(syms.autoCloseableClose, resource.tsym, types) &&
2441 chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes())) {
2442 if (!useSite && close.owner == resource.tsym) {
2443 log.warning(TreeInfo.diagnosticPositionFor(close, tree),
2444 LintWarnings.TryResourceCanThrowInterruptedExc(resource));
2445 } else {
2446 log.warning(pos, LintWarnings.TryResourceThrowsInterruptedExc(resource));
2447 }
2448 }
2449 }
2450 }
2451
2452 public void visitConditional(JCConditional tree) {
2453 Type condtype = attribExpr(tree.cond, env, syms.booleanType);
2454 MatchBindings condBindings = matchBindings;
2455
2456 tree.polyKind = (pt().hasTag(NONE) && pt() != Type.recoveryType && pt() != Infer.anyPoly ||
2457 isBooleanOrNumeric(env, tree)) ?
2458 PolyKind.STANDALONE : PolyKind.POLY;
2459
2460 if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) {
2461 //this means we are returning a poly conditional from void-compatible lambda expression
2462 resultInfo.checkContext.report(tree, diags.fragment(Fragments.ConditionalTargetCantBeVoid));
2463 result = tree.type = types.createErrorType(resultInfo.pt);
2464 return;
2465 }
2466
2467 ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ?
2468 unknownExprInfo :
2469 resultInfo.dup(conditionalContext(resultInfo.checkContext));
2470
2471
2472 // x ? y : z
2473 // include x's bindings when true in y
2474 // include x's bindings when false in z
2475
2476 Type truetype;
2477 Env<AttrContext> trueEnv = bindingEnv(env, condBindings.bindingsWhenTrue);
2478 try {
2479 truetype = attribTree(tree.truepart, trueEnv, condInfo);
2480 } finally {
2481 trueEnv.info.scope.leave();
2482 }
2483
2484 MatchBindings trueBindings = matchBindings;
2485
2486 Type falsetype;
2487 Env<AttrContext> falseEnv = bindingEnv(env, condBindings.bindingsWhenFalse);
2488 try {
2489 falsetype = attribTree(tree.falsepart, falseEnv, condInfo);
2490 } finally {
2491 falseEnv.info.scope.leave();
2492 }
2493
2494 MatchBindings falseBindings = matchBindings;
2495
2496 Type owntype = (tree.polyKind == PolyKind.STANDALONE) ?
2497 condType(List.of(tree.truepart.pos(), tree.falsepart.pos()),
2498 List.of(truetype, falsetype)) : pt();
2499 if (condtype.constValue() != null &&
2500 truetype.constValue() != null &&
2501 falsetype.constValue() != null &&
2502 !owntype.hasTag(NONE)) {
2503 //constant folding
2504 owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype);
2505 }
2506 result = check(tree, owntype, KindSelector.VAL, resultInfo);
2507 matchBindings = matchBindingsComputer.conditional(tree, condBindings, trueBindings, falseBindings);
2508 }
2509 //where
2510 private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) {
2511 switch (tree.getTag()) {
2512 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) ||
2513 ((JCLiteral)tree).typetag == BOOLEAN ||
2514 ((JCLiteral)tree).typetag == BOT;
2515 case LAMBDA: case REFERENCE: return false;
2516 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr);
2517 case CONDEXPR:
2518 JCConditional condTree = (JCConditional)tree;
2519 return isBooleanOrNumeric(env, condTree.truepart) &&
2520 isBooleanOrNumeric(env, condTree.falsepart);
2521 case APPLY:
2522 JCMethodInvocation speculativeMethodTree =
2523 (JCMethodInvocation)deferredAttr.attribSpeculative(
2524 tree, env, unknownExprInfo,
2525 argumentAttr.withLocalCacheContext());
2526 Symbol msym = TreeInfo.symbol(speculativeMethodTree.meth);
2527 Type receiverType = speculativeMethodTree.meth.hasTag(IDENT) ?
2528 env.enclClass.type :
2529 ((JCFieldAccess)speculativeMethodTree.meth).selected.type;
2530 Type owntype = types.memberType(receiverType, msym).getReturnType();
2531 return primitiveOrBoxed(owntype);
2532 case NEWCLASS:
2533 JCExpression className =
2534 removeClassParams.translate(((JCNewClass)tree).clazz);
2535 JCExpression speculativeNewClassTree =
2536 (JCExpression)deferredAttr.attribSpeculative(
2537 className, env, unknownTypeInfo,
2538 argumentAttr.withLocalCacheContext());
2539 return primitiveOrBoxed(speculativeNewClassTree.type);
2540 default:
2541 Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo,
2542 argumentAttr.withLocalCacheContext()).type;
2543 return primitiveOrBoxed(speculativeType);
2544 }
2545 }
2546 //where
2547 boolean primitiveOrBoxed(Type t) {
2548 return (!t.hasTag(TYPEVAR) && !t.isErroneous() && types.unboxedTypeOrType(t).isPrimitive());
2549 }
2550
2551 TreeTranslator removeClassParams = new TreeTranslator() {
2552 @Override
2553 public void visitTypeApply(JCTypeApply tree) {
2554 result = translate(tree.clazz);
2555 }
2556 };
2557
2558 CheckContext conditionalContext(CheckContext checkContext) {
2559 return new Check.NestedCheckContext(checkContext) {
2560 //this will use enclosing check context to check compatibility of
2561 //subexpression against target type; if we are in a method check context,
2562 //depending on whether boxing is allowed, we could have incompatibilities
2563 @Override
2564 public void report(DiagnosticPosition pos, JCDiagnostic details) {
2565 enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleTypeInConditional(details)));
2566 }
2567 };
2568 }
2569
2570 /** Compute the type of a conditional expression, after
2571 * checking that it exists. See JLS 15.25. Does not take into
2572 * account the special case where condition and both arms
2573 * are constants.
2574 *
2575 * @param pos The source position to be used for error
2576 * diagnostics.
2577 * @param thentype The type of the expression's then-part.
2578 * @param elsetype The type of the expression's else-part.
2579 */
2580 Type condType(List<DiagnosticPosition> positions, List<Type> condTypes) {
2581 if (condTypes.isEmpty()) {
2582 return syms.objectType; //TODO: how to handle?
2583 }
2584 Type first = condTypes.head;
2585 // If same type, that is the result
2586 if (condTypes.tail.stream().allMatch(t -> types.isSameType(first, t)))
2587 return first.baseType();
2588
2589 List<Type> unboxedTypes = condTypes.stream()
2590 .map(t -> t.isPrimitive() ? t : types.unboxedType(t))
2591 .collect(List.collector());
2592
2593 // Otherwise, if both arms can be converted to a numeric
2594 // type, return the least numeric type that fits both arms
2595 // (i.e. return larger of the two, or return int if one
2596 // arm is short, the other is char).
2597 if (unboxedTypes.stream().allMatch(t -> t.isPrimitive())) {
2598 // If one arm has an integer subrange type (i.e., byte,
2599 // short, or char), and the other is an integer constant
2600 // that fits into the subrange, return the subrange type.
2601 for (Type type : unboxedTypes) {
2602 if (!type.getTag().isStrictSubRangeOf(INT)) {
2603 continue;
2604 }
2605 if (unboxedTypes.stream().filter(t -> t != type).allMatch(t -> t.hasTag(INT) && types.isAssignable(t, type)))
2606 return type.baseType();
2607 }
2608
2609 for (TypeTag tag : primitiveTags) {
2610 Type candidate = syms.typeOfTag[tag.ordinal()];
2611 if (unboxedTypes.stream().allMatch(t -> types.isSubtype(t, candidate))) {
2612 return candidate;
2613 }
2614 }
2615 }
2616
2617 // Those were all the cases that could result in a primitive
2618 condTypes = condTypes.stream()
2619 .map(t -> t.isPrimitive() ? types.boxedClass(t).type : t)
2620 .collect(List.collector());
2621
2622 for (Type type : condTypes) {
2623 if (condTypes.stream().filter(t -> t != type).allMatch(t -> types.isAssignable(t, type)))
2624 return type.baseType();
2625 }
2626
2627 Iterator<DiagnosticPosition> posIt = positions.iterator();
2628
2629 condTypes = condTypes.stream()
2630 .map(t -> chk.checkNonVoid(posIt.next(), t))
2631 .collect(List.collector());
2632
2633 // both are known to be reference types. The result is
2634 // lub(thentype,elsetype). This cannot fail, as it will
2635 // always be possible to infer "Object" if nothing better.
2636 return types.lub(condTypes.stream()
2637 .map(t -> t.baseType())
2638 .filter(t -> !t.hasTag(BOT))
2639 .collect(List.collector()));
2640 }
2641
2642 static final TypeTag[] primitiveTags = new TypeTag[]{
2643 BYTE,
2644 CHAR,
2645 SHORT,
2646 INT,
2647 LONG,
2648 FLOAT,
2649 DOUBLE,
2650 BOOLEAN,
2651 };
2652
2653 Env<AttrContext> bindingEnv(Env<AttrContext> env, List<BindingSymbol> bindings) {
2654 return bindingEnv(env, env.tree, bindings);
2655 }
2656
2657 Env<AttrContext> bindingEnv(Env<AttrContext> env, JCTree newTree, List<BindingSymbol> bindings) {
2658 Env<AttrContext> env1 = env.dup(newTree, env.info.dup(env.info.scope.dup()));
2659 bindings.forEach(env1.info.scope::enter);
2660 return env1;
2661 }
2662
2663 public void visitIf(JCIf tree) {
2664 attribExpr(tree.cond, env, syms.booleanType);
2665
2666 // if (x) { y } [ else z ]
2667 // include x's bindings when true in y
2668 // include x's bindings when false in z
2669
2670 MatchBindings condBindings = matchBindings;
2671 Env<AttrContext> thenEnv = bindingEnv(env, condBindings.bindingsWhenTrue);
2672
2673 try {
2674 attribStat(tree.thenpart, thenEnv);
2675 } finally {
2676 thenEnv.info.scope.leave();
2677 }
2678
2679 preFlow(tree.thenpart);
2680 boolean aliveAfterThen = flow.aliveAfter(env, tree.thenpart, make);
2681 boolean aliveAfterElse;
2682
2683 if (tree.elsepart != null) {
2684 Env<AttrContext> elseEnv = bindingEnv(env, condBindings.bindingsWhenFalse);
2685 try {
2686 attribStat(tree.elsepart, elseEnv);
2687 } finally {
2688 elseEnv.info.scope.leave();
2689 }
2690 preFlow(tree.elsepart);
2691 aliveAfterElse = flow.aliveAfter(env, tree.elsepart, make);
2692 } else {
2693 aliveAfterElse = true;
2694 }
2695
2696 chk.checkEmptyIf(tree);
2697
2698 List<BindingSymbol> afterIfBindings = List.nil();
2699
2700 if (aliveAfterThen && !aliveAfterElse) {
2701 afterIfBindings = condBindings.bindingsWhenTrue;
2702 } else if (aliveAfterElse && !aliveAfterThen) {
2703 afterIfBindings = condBindings.bindingsWhenFalse;
2704 }
2705
2706 addBindings2Scope(tree, afterIfBindings);
2707
2708 result = null;
2709 }
2710
2711 void preFlow(JCTree tree) {
2712 attrRecover.doRecovery();
2713 new PostAttrAnalyzer() {
2714 @Override
2715 public void scan(JCTree tree) {
2716 if (tree == null ||
2717 (tree.type != null &&
2718 tree.type == Type.stuckType)) {
2719 //don't touch stuck expressions!
2720 return;
2721 }
2722 super.scan(tree);
2723 }
2724
2725 @Override
2726 public void visitClassDef(JCClassDecl that) {
2727 if (that.sym != null) {
2728 // Method preFlow shouldn't visit class definitions
2729 // that have not been entered and attributed.
2730 // See JDK-8254557 and JDK-8203277 for more details.
2731 super.visitClassDef(that);
2732 }
2733 }
2734
2735 @Override
2736 public void visitLambda(JCLambda that) {
2737 if (that.type != null) {
2738 // Method preFlow shouldn't visit lambda expressions
2739 // that have not been entered and attributed.
2740 // See JDK-8254557 and JDK-8203277 for more details.
2741 super.visitLambda(that);
2742 }
2743 }
2744 }.scan(tree);
2745 }
2746
2747 public void visitExec(JCExpressionStatement tree) {
2748 //a fresh environment is required for 292 inference to work properly ---
2749 //see Infer.instantiatePolymorphicSignatureInstance()
2750 Env<AttrContext> localEnv = env.dup(tree);
2751 attribExpr(tree.expr, localEnv);
2752 result = null;
2753 }
2754
2755 public void visitBreak(JCBreak tree) {
2756 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
2757 result = null;
2758 }
2759
2760 public void visitYield(JCYield tree) {
2761 if (env.info.yieldResult != null) {
2762 attribTree(tree.value, env, env.info.yieldResult);
2763 tree.target = findJumpTarget(tree.pos(), tree.getTag(), names.empty, env);
2764 } else {
2765 log.error(tree.pos(), tree.value.hasTag(PARENS)
2766 ? Errors.NoSwitchExpressionQualify
2767 : Errors.NoSwitchExpression);
2768 attribTree(tree.value, env, unknownExprInfo);
2769 }
2770 result = null;
2771 }
2772
2773 public void visitContinue(JCContinue tree) {
2774 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env);
2775 result = null;
2776 }
2777 //where
2778 /** Return the target of a break, continue or yield statement,
2779 * if it exists, report an error if not.
2780 * Note: The target of a labelled break or continue is the
2781 * (non-labelled) statement tree referred to by the label,
2782 * not the tree representing the labelled statement itself.
2783 *
2784 * @param pos The position to be used for error diagnostics
2785 * @param tag The tag of the jump statement. This is either
2786 * Tree.BREAK or Tree.CONTINUE.
2787 * @param label The label of the jump statement, or null if no
2788 * label is given.
2789 * @param env The environment current at the jump statement.
2790 */
2791 private JCTree findJumpTarget(DiagnosticPosition pos,
2792 JCTree.Tag tag,
2793 Name label,
2794 Env<AttrContext> env) {
2795 Pair<JCTree, Error> jumpTarget = findJumpTargetNoError(tag, label, env);
2796
2797 if (jumpTarget.snd != null) {
2798 log.error(pos, jumpTarget.snd);
2799 }
2800
2801 return jumpTarget.fst;
2802 }
2803 /** Return the target of a break or continue statement, if it exists,
2804 * report an error if not.
2805 * Note: The target of a labelled break or continue is the
2806 * (non-labelled) statement tree referred to by the label,
2807 * not the tree representing the labelled statement itself.
2808 *
2809 * @param tag The tag of the jump statement. This is either
2810 * Tree.BREAK or Tree.CONTINUE.
2811 * @param label The label of the jump statement, or null if no
2812 * label is given.
2813 * @param env The environment current at the jump statement.
2814 */
2815 private Pair<JCTree, JCDiagnostic.Error> findJumpTargetNoError(JCTree.Tag tag,
2816 Name label,
2817 Env<AttrContext> env) {
2818 // Search environments outwards from the point of jump.
2819 Env<AttrContext> env1 = env;
2820 JCDiagnostic.Error pendingError = null;
2821 LOOP:
2822 while (env1 != null) {
2823 switch (env1.tree.getTag()) {
2824 case LABELLED:
2825 JCLabeledStatement labelled = (JCLabeledStatement)env1.tree;
2826 if (label == labelled.label) {
2827 // If jump is a continue, check that target is a loop.
2828 if (tag == CONTINUE) {
2829 if (!labelled.body.hasTag(DOLOOP) &&
2830 !labelled.body.hasTag(WHILELOOP) &&
2831 !labelled.body.hasTag(FORLOOP) &&
2832 !labelled.body.hasTag(FOREACHLOOP)) {
2833 pendingError = Errors.NotLoopLabel(label);
2834 }
2835 // Found labelled statement target, now go inwards
2836 // to next non-labelled tree.
2837 return Pair.of(TreeInfo.referencedStatement(labelled), pendingError);
2838 } else {
2839 return Pair.of(labelled, pendingError);
2840 }
2841 }
2842 break;
2843 case DOLOOP:
2844 case WHILELOOP:
2845 case FORLOOP:
2846 case FOREACHLOOP:
2847 if (label == null) return Pair.of(env1.tree, pendingError);
2848 break;
2849 case SWITCH:
2850 if (label == null && tag == BREAK) return Pair.of(env1.tree, null);
2851 break;
2852 case SWITCH_EXPRESSION:
2853 if (tag == YIELD) {
2854 return Pair.of(env1.tree, null);
2855 } else if (tag == BREAK) {
2856 pendingError = Errors.BreakOutsideSwitchExpression;
2857 } else {
2858 pendingError = Errors.ContinueOutsideSwitchExpression;
2859 }
2860 break;
2861 case LAMBDA:
2862 case METHODDEF:
2863 case CLASSDEF:
2864 break LOOP;
2865 default:
2866 }
2867 env1 = env1.next;
2868 }
2869 if (label != null)
2870 return Pair.of(null, Errors.UndefLabel(label));
2871 else if (pendingError != null)
2872 return Pair.of(null, pendingError);
2873 else if (tag == CONTINUE)
2874 return Pair.of(null, Errors.ContOutsideLoop);
2875 else
2876 return Pair.of(null, Errors.BreakOutsideSwitchLoop);
2877 }
2878
2879 public void visitReturn(JCReturn tree) {
2880 // Check that there is an enclosing method which is
2881 // nested within than the enclosing class.
2882 if (env.info.returnResult == null) {
2883 log.error(tree.pos(), Errors.RetOutsideMeth);
2884 } else if (env.info.yieldResult != null) {
2885 log.error(tree.pos(), Errors.ReturnOutsideSwitchExpression);
2886 if (tree.expr != null) {
2887 attribExpr(tree.expr, env, env.info.yieldResult.pt);
2888 }
2889 } else if (!env.info.isLambda &&
2890 env.enclMethod != null &&
2891 TreeInfo.isCompactConstructor(env.enclMethod)) {
2892 log.error(env.enclMethod,
2893 Errors.InvalidCanonicalConstructorInRecord(Fragments.Compact, env.enclMethod.sym.name, Fragments.CanonicalCantHaveReturnStatement));
2894 } else {
2895 // Attribute return expression, if it exists, and check that
2896 // it conforms to result type of enclosing method.
2897 if (tree.expr != null) {
2898 if (env.info.returnResult.pt.hasTag(VOID)) {
2899 env.info.returnResult.checkContext.report(tree.expr.pos(),
2900 diags.fragment(Fragments.UnexpectedRetVal));
2901 }
2902 attribTree(tree.expr, env, env.info.returnResult);
2903 } else if (!env.info.returnResult.pt.hasTag(VOID) &&
2904 !env.info.returnResult.pt.hasTag(NONE)) {
2905 env.info.returnResult.checkContext.report(tree.pos(),
2906 diags.fragment(Fragments.MissingRetVal(env.info.returnResult.pt)));
2907 }
2908 }
2909 result = null;
2910 }
2911
2912 public void visitThrow(JCThrow tree) {
2913 Type owntype = attribExpr(tree.expr, env, Type.noType);
2914 chk.checkType(tree, owntype, syms.throwableType);
2915 result = null;
2916 }
2917
2918 public void visitAssert(JCAssert tree) {
2919 attribExpr(tree.cond, env, syms.booleanType);
2920 if (tree.detail != null) {
2921 chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env));
2922 }
2923 result = null;
2924 }
2925
2926 /** Visitor method for method invocations.
2927 * NOTE: The method part of an application will have in its type field
2928 * the return type of the method, not the method's type itself!
2929 */
2930 public void visitApply(JCMethodInvocation tree) {
2931 // The local environment of a method application is
2932 // a new environment nested in the current one.
2933 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
2934
2935 // The types of the actual method arguments.
2936 List<Type> argtypes;
2937
2938 // The types of the actual method type arguments.
2939 List<Type> typeargtypes = null;
2940
2941 Name methName = TreeInfo.name(tree.meth);
2942
2943 boolean isConstructorCall =
2944 methName == names._this || methName == names._super;
2945
2946 ListBuffer<Type> argtypesBuf = new ListBuffer<>();
2947 if (isConstructorCall) {
2948
2949 // Attribute arguments, yielding list of argument types.
2950 KindSelector kind = attribArgs(KindSelector.MTH, tree.args, localEnv, argtypesBuf);
2951 argtypes = argtypesBuf.toList();
2952 typeargtypes = attribTypes(tree.typeargs, localEnv);
2953
2954 // Done with this()/super() parameters. End of constructor prologue.
2955 env.info.ctorPrologue = false;
2956
2957 // Variable `site' points to the class in which the called
2958 // constructor is defined.
2959 Type site = env.enclClass.sym.type;
2960 if (methName == names._super) {
2961 if (site == syms.objectType) {
2962 log.error(tree.meth.pos(), Errors.NoSuperclass(site));
2963 site = types.createErrorType(syms.objectType);
2964 } else {
2965 site = types.supertype(site);
2966 }
2967 }
2968
2969 if (site.hasTag(CLASS)) {
2970 Type encl = site.getEnclosingType();
2971 while (encl != null && encl.hasTag(TYPEVAR))
2972 encl = encl.getUpperBound();
2973 if (encl.hasTag(CLASS)) {
2974 // we are calling a nested class
2975
2976 if (tree.meth.hasTag(SELECT)) {
2977 JCTree qualifier = ((JCFieldAccess) tree.meth).selected;
2978
2979 // We are seeing a prefixed call, of the form
2980 // <expr>.super(...).
2981 // Check that the prefix expression conforms
2982 // to the outer instance type of the class.
2983 chk.checkRefType(qualifier.pos(),
2984 attribExpr(qualifier, localEnv,
2985 encl));
2986 }
2987 } else if (tree.meth.hasTag(SELECT)) {
2988 log.error(tree.meth.pos(),
2989 Errors.IllegalQualNotIcls(site.tsym));
2990 attribExpr(((JCFieldAccess) tree.meth).selected, localEnv, site);
2991 }
2992
2993 if (tree.meth.hasTag(IDENT)) {
2994 // non-qualified super(...) call; check whether explicit constructor
2995 // invocation is well-formed. If the super class is an inner class,
2996 // make sure that an appropriate implicit qualifier exists. If the super
2997 // class is a local class, make sure that the current class is defined
2998 // in the same context as the local class.
2999 checkNewInnerClass(tree.meth.pos(), localEnv, site, true);
3000 }
3001
3002 // if we're calling a java.lang.Enum constructor,
3003 // prefix the implicit String and int parameters
3004 if (site.tsym == syms.enumSym)
3005 argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType);
3006
3007 // Resolve the called constructor under the assumption
3008 // that we are referring to a superclass instance of the
3009 // current instance (JLS ???).
3010 boolean selectSuperPrev = localEnv.info.selectSuper;
3011 localEnv.info.selectSuper = true;
3012 localEnv.info.pendingResolutionPhase = null;
3013 Symbol sym = rs.resolveConstructor(
3014 tree.meth.pos(), localEnv, site, argtypes, typeargtypes);
3015 localEnv.info.selectSuper = selectSuperPrev;
3016
3017 // Set method symbol to resolved constructor...
3018 TreeInfo.setSymbol(tree.meth, sym);
3019
3020 // ...and check that it is legal in the current context.
3021 // (this will also set the tree's type)
3022 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
3023 checkId(tree.meth, site, sym, localEnv,
3024 new ResultInfo(kind, mpt));
3025 } else if (site.hasTag(ERROR) && tree.meth.hasTag(SELECT)) {
3026 attribExpr(((JCFieldAccess) tree.meth).selected, localEnv, site);
3027 }
3028 // Otherwise, `site' is an error type and we do nothing
3029 result = tree.type = syms.voidType;
3030 } else {
3031 // Otherwise, we are seeing a regular method call.
3032 // Attribute the arguments, yielding list of argument types, ...
3033 KindSelector kind = attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
3034 argtypes = argtypesBuf.toList();
3035 typeargtypes = attribAnyTypes(tree.typeargs, localEnv);
3036
3037 // ... and attribute the method using as a prototype a methodtype
3038 // whose formal argument types is exactly the list of actual
3039 // arguments (this will also set the method symbol).
3040 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes);
3041 localEnv.info.pendingResolutionPhase = null;
3042 Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(kind, mpt, resultInfo.checkContext));
3043
3044 // Compute the result type.
3045 Type restype = mtype.getReturnType();
3046 if (restype.hasTag(WILDCARD))
3047 throw new AssertionError(mtype);
3048
3049 Type qualifier = (tree.meth.hasTag(SELECT))
3050 ? ((JCFieldAccess) tree.meth).selected.type
3051 : env.enclClass.sym.type;
3052 Symbol msym = TreeInfo.symbol(tree.meth);
3053 restype = adjustMethodReturnType(msym, qualifier, methName, argtypes, restype);
3054
3055 chk.checkRefTypes(tree.typeargs, typeargtypes);
3056
3057 // Check that value of resulting type is admissible in the
3058 // current context. Also, capture the return type
3059 Type capturedRes = resultInfo.checkContext.inferenceContext().cachedCapture(tree, restype, true);
3060 result = check(tree, capturedRes, KindSelector.VAL, resultInfo);
3061 }
3062 chk.checkRequiresIdentity(tree, env.info.lint);
3063 chk.validate(tree.typeargs, localEnv);
3064 }
3065 //where
3066 Type adjustMethodReturnType(Symbol msym, Type qualifierType, Name methodName, List<Type> argtypes, Type restype) {
3067 if (msym != null &&
3068 (msym.owner == syms.objectType.tsym || msym.owner.isInterface()) &&
3069 methodName == names.getClass &&
3070 argtypes.isEmpty()) {
3071 // as a special case, x.getClass() has type Class<? extends |X|>
3072 return new ClassType(restype.getEnclosingType(),
3073 List.of(new WildcardType(types.erasure(qualifierType.baseType()),
3074 BoundKind.EXTENDS,
3075 syms.boundClass)),
3076 restype.tsym,
3077 restype.getMetadata());
3078 } else if (msym != null &&
3079 msym.owner == syms.arrayClass &&
3080 methodName == names.clone &&
3081 types.isArray(qualifierType)) {
3082 // as a special case, array.clone() has a result that is
3083 // the same as static type of the array being cloned
3084 return qualifierType;
3085 } else {
3086 return restype;
3087 }
3088 }
3089
3090 /** Obtain a method type with given argument types.
3091 */
3092 Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) {
3093 MethodType mt = new MethodType(argtypes, restype, List.nil(), syms.methodClass);
3094 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
3095 }
3096
3097 public void visitNewClass(final JCNewClass tree) {
3098 Type owntype = types.createErrorType(tree.type);
3099
3100 // The local environment of a class creation is
3101 // a new environment nested in the current one.
3102 Env<AttrContext> localEnv = env.dup(tree, env.info.dup());
3103
3104 // The anonymous inner class definition of the new expression,
3105 // if one is defined by it.
3106 JCClassDecl cdef = tree.def;
3107
3108 // If enclosing class is given, attribute it, and
3109 // complete class name to be fully qualified
3110 JCExpression clazz = tree.clazz; // Class field following new
3111 JCExpression clazzid; // Identifier in class field
3112 JCAnnotatedType annoclazzid; // Annotated type enclosing clazzid
3113 annoclazzid = null;
3114
3115 if (clazz.hasTag(TYPEAPPLY)) {
3116 clazzid = ((JCTypeApply) clazz).clazz;
3117 if (clazzid.hasTag(ANNOTATED_TYPE)) {
3118 annoclazzid = (JCAnnotatedType) clazzid;
3119 clazzid = annoclazzid.underlyingType;
3120 }
3121 } else {
3122 if (clazz.hasTag(ANNOTATED_TYPE)) {
3123 annoclazzid = (JCAnnotatedType) clazz;
3124 clazzid = annoclazzid.underlyingType;
3125 } else {
3126 clazzid = clazz;
3127 }
3128 }
3129
3130 JCExpression clazzid1 = clazzid; // The same in fully qualified form
3131
3132 if (tree.encl != null) {
3133 // We are seeing a qualified new, of the form
3134 // <expr>.new C <...> (...) ...
3135 // In this case, we let clazz stand for the name of the
3136 // allocated class C prefixed with the type of the qualifier
3137 // expression, so that we can
3138 // resolve it with standard techniques later. I.e., if
3139 // <expr> has type T, then <expr>.new C <...> (...)
3140 // yields a clazz T.C.
3141 Type encltype = chk.checkRefType(tree.encl.pos(),
3142 attribExpr(tree.encl, env));
3143 // TODO 308: in <expr>.new C, do we also want to add the type annotations
3144 // from expr to the combined type, or not? Yes, do this.
3145 clazzid1 = make.at(clazz.pos).Select(make.Type(encltype),
3146 ((JCIdent) clazzid).name);
3147
3148 EndPosTable endPosTable = this.env.toplevel.endPositions;
3149 endPosTable.storeEnd(clazzid1, clazzid.getEndPosition(endPosTable));
3150 if (clazz.hasTag(ANNOTATED_TYPE)) {
3151 JCAnnotatedType annoType = (JCAnnotatedType) clazz;
3152 List<JCAnnotation> annos = annoType.annotations;
3153
3154 if (annoType.underlyingType.hasTag(TYPEAPPLY)) {
3155 clazzid1 = make.at(tree.pos).
3156 TypeApply(clazzid1,
3157 ((JCTypeApply) clazz).arguments);
3158 }
3159
3160 clazzid1 = make.at(tree.pos).
3161 AnnotatedType(annos, clazzid1);
3162 } else if (clazz.hasTag(TYPEAPPLY)) {
3163 clazzid1 = make.at(tree.pos).
3164 TypeApply(clazzid1,
3165 ((JCTypeApply) clazz).arguments);
3166 }
3167
3168 clazz = clazzid1;
3169 }
3170
3171 // Attribute clazz expression and store
3172 // symbol + type back into the attributed tree.
3173 Type clazztype = TreeInfo.isEnumInit(env.tree) ?
3174 attribIdentAsEnumType(env, (JCIdent)clazz) :
3175 attribType(clazz, env);
3176
3177 clazztype = chk.checkDiamond(tree, clazztype);
3178 chk.validate(clazz, localEnv);
3179 if (tree.encl != null) {
3180 // We have to work in this case to store
3181 // symbol + type back into the attributed tree.
3182 tree.clazz.type = clazztype;
3183 TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1));
3184 clazzid.type = ((JCIdent) clazzid).sym.type;
3185 if (annoclazzid != null) {
3186 annoclazzid.type = clazzid.type;
3187 }
3188 if (!clazztype.isErroneous()) {
3189 if (cdef != null && clazztype.tsym.isInterface()) {
3190 log.error(tree.encl.pos(), Errors.AnonClassImplIntfNoQualForNew);
3191 } else if (clazztype.tsym.isStatic()) {
3192 log.error(tree.encl.pos(), Errors.QualifiedNewOfStaticClass(clazztype.tsym));
3193 }
3194 }
3195 } else {
3196 // Check for the existence of an apropos outer instance
3197 checkNewInnerClass(tree.pos(), env, clazztype, false);
3198 }
3199
3200 // Attribute constructor arguments.
3201 ListBuffer<Type> argtypesBuf = new ListBuffer<>();
3202 final KindSelector pkind =
3203 attribArgs(KindSelector.VAL, tree.args, localEnv, argtypesBuf);
3204 List<Type> argtypes = argtypesBuf.toList();
3205 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv);
3206
3207 if (clazztype.hasTag(CLASS) || clazztype.hasTag(ERROR)) {
3208 // Enums may not be instantiated except implicitly
3209 if ((clazztype.tsym.flags_field & Flags.ENUM) != 0 &&
3210 (!env.tree.hasTag(VARDEF) ||
3211 (((JCVariableDecl) env.tree).mods.flags & Flags.ENUM) == 0 ||
3212 ((JCVariableDecl) env.tree).init != tree))
3213 log.error(tree.pos(), Errors.EnumCantBeInstantiated);
3214
3215 boolean isSpeculativeDiamondInferenceRound = TreeInfo.isDiamond(tree) &&
3216 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
3217 boolean skipNonDiamondPath = false;
3218 // Check that class is not abstract
3219 if (cdef == null && !tree.classDeclRemoved() && !isSpeculativeDiamondInferenceRound && // class body may be nulled out in speculative tree copy
3220 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
3221 log.error(tree.pos(),
3222 Errors.AbstractCantBeInstantiated(clazztype.tsym));
3223 skipNonDiamondPath = true;
3224 } else if (cdef != null && clazztype.tsym.isInterface()) {
3225 // Check that no constructor arguments are given to
3226 // anonymous classes implementing an interface
3227 if (!argtypes.isEmpty())
3228 log.error(tree.args.head.pos(), Errors.AnonClassImplIntfNoArgs);
3229
3230 if (!typeargtypes.isEmpty())
3231 log.error(tree.typeargs.head.pos(), Errors.AnonClassImplIntfNoTypeargs);
3232
3233 // Error recovery: pretend no arguments were supplied.
3234 argtypes = List.nil();
3235 typeargtypes = List.nil();
3236 skipNonDiamondPath = true;
3237 }
3238 if (TreeInfo.isDiamond(tree)) {
3239 ClassType site = new ClassType(clazztype.getEnclosingType(),
3240 clazztype.tsym.type.getTypeArguments(),
3241 clazztype.tsym,
3242 clazztype.getMetadata());
3243
3244 Env<AttrContext> diamondEnv = localEnv.dup(tree);
3245 diamondEnv.info.selectSuper = cdef != null || tree.classDeclRemoved();
3246 diamondEnv.info.pendingResolutionPhase = null;
3247
3248 //if the type of the instance creation expression is a class type
3249 //apply method resolution inference (JLS 15.12.2.7). The return type
3250 //of the resolved constructor will be a partially instantiated type
3251 Symbol constructor = rs.resolveDiamond(tree.pos(),
3252 diamondEnv,
3253 site,
3254 argtypes,
3255 typeargtypes);
3256 tree.constructor = constructor.baseSymbol();
3257
3258 final TypeSymbol csym = clazztype.tsym;
3259 ResultInfo diamondResult = new ResultInfo(pkind, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes),
3260 diamondContext(tree, csym, resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
3261 Type constructorType = tree.constructorType = types.createErrorType(clazztype);
3262 constructorType = checkId(tree, site,
3263 constructor,
3264 diamondEnv,
3265 diamondResult);
3266
3267 tree.clazz.type = types.createErrorType(clazztype);
3268 if (!constructorType.isErroneous()) {
3269 tree.clazz.type = clazz.type = constructorType.getReturnType();
3270 tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType);
3271 }
3272 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true);
3273 }
3274
3275 // Resolve the called constructor under the assumption
3276 // that we are referring to a superclass instance of the
3277 // current instance (JLS ???).
3278 else if (!skipNonDiamondPath) {
3279 //the following code alters some of the fields in the current
3280 //AttrContext - hence, the current context must be dup'ed in
3281 //order to avoid downstream failures
3282 Env<AttrContext> rsEnv = localEnv.dup(tree);
3283 rsEnv.info.selectSuper = cdef != null;
3284 rsEnv.info.pendingResolutionPhase = null;
3285 tree.constructor = rs.resolveConstructor(
3286 tree.pos(), rsEnv, clazztype, argtypes, typeargtypes);
3287 if (cdef == null) { //do not check twice!
3288 tree.constructorType = checkId(tree,
3289 clazztype,
3290 tree.constructor,
3291 rsEnv,
3292 new ResultInfo(pkind, newMethodTemplate(syms.voidType, argtypes, typeargtypes), CheckMode.NO_TREE_UPDATE));
3293 if (rsEnv.info.lastResolveVarargs())
3294 Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null);
3295 }
3296 }
3297
3298 chk.checkRequiresIdentity(tree, env.info.lint);
3299
3300 if (cdef != null) {
3301 visitAnonymousClassDefinition(tree, clazz, clazztype, cdef, localEnv, argtypes, typeargtypes, pkind);
3302 return;
3303 }
3304
3305 if (tree.constructor != null && tree.constructor.kind == MTH)
3306 owntype = clazztype;
3307 }
3308 result = check(tree, owntype, KindSelector.VAL, resultInfo);
3309 InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
3310 if (tree.constructorType != null && inferenceContext.free(tree.constructorType)) {
3311 //we need to wait for inference to finish and then replace inference vars in the constructor type
3312 inferenceContext.addFreeTypeListener(List.of(tree.constructorType),
3313 instantiatedContext -> {
3314 tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
3315 });
3316 }
3317 chk.validate(tree.typeargs, localEnv);
3318 }
3319
3320 // where
3321 private void visitAnonymousClassDefinition(JCNewClass tree, JCExpression clazz, Type clazztype,
3322 JCClassDecl cdef, Env<AttrContext> localEnv,
3323 List<Type> argtypes, List<Type> typeargtypes,
3324 KindSelector pkind) {
3325 // We are seeing an anonymous class instance creation.
3326 // In this case, the class instance creation
3327 // expression
3328 //
3329 // E.new <typeargs1>C<typargs2>(args) { ... }
3330 //
3331 // is represented internally as
3332 //
3333 // E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) .
3334 //
3335 // This expression is then *transformed* as follows:
3336 //
3337 // (1) add an extends or implements clause
3338 // (2) add a constructor.
3339 //
3340 // For instance, if C is a class, and ET is the type of E,
3341 // the expression
3342 //
3343 // E.new <typeargs1>C<typargs2>(args) { ... }
3344 //
3345 // is translated to (where X is a fresh name and typarams is the
3346 // parameter list of the super constructor):
3347 //
3348 // new <typeargs1>X(<*nullchk*>E, args) where
3349 // X extends C<typargs2> {
3350 // <typarams> X(ET e, args) {
3351 // e.<typeargs1>super(args)
3352 // }
3353 // ...
3354 // }
3355 InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
3356 Type enclType = clazztype.getEnclosingType();
3357 if (enclType != null &&
3358 enclType.hasTag(CLASS) &&
3359 !chk.checkDenotable((ClassType)enclType)) {
3360 log.error(tree.encl, Errors.EnclosingClassTypeNonDenotable(enclType));
3361 }
3362 final boolean isDiamond = TreeInfo.isDiamond(tree);
3363 if (isDiamond
3364 && ((tree.constructorType != null && inferenceContext.free(tree.constructorType))
3365 || (tree.clazz.type != null && inferenceContext.free(tree.clazz.type)))) {
3366 final ResultInfo resultInfoForClassDefinition = this.resultInfo;
3367 Env<AttrContext> dupLocalEnv = copyEnv(localEnv);
3368 inferenceContext.addFreeTypeListener(List.of(tree.constructorType, tree.clazz.type),
3369 instantiatedContext -> {
3370 tree.constructorType = instantiatedContext.asInstType(tree.constructorType);
3371 tree.clazz.type = clazz.type = instantiatedContext.asInstType(clazz.type);
3372 ResultInfo prevResult = this.resultInfo;
3373 try {
3374 this.resultInfo = resultInfoForClassDefinition;
3375 visitAnonymousClassDefinition(tree, clazz, clazz.type, cdef,
3376 dupLocalEnv, argtypes, typeargtypes, pkind);
3377 } finally {
3378 this.resultInfo = prevResult;
3379 }
3380 });
3381 } else {
3382 if (isDiamond && clazztype.hasTag(CLASS)) {
3383 List<Type> invalidDiamondArgs = chk.checkDiamondDenotable((ClassType)clazztype);
3384 if (!clazztype.isErroneous() && invalidDiamondArgs.nonEmpty()) {
3385 // One or more types inferred in the previous steps is non-denotable.
3386 Fragment fragment = Diamond(clazztype.tsym);
3387 log.error(tree.clazz.pos(),
3388 Errors.CantApplyDiamond1(
3389 fragment,
3390 invalidDiamondArgs.size() > 1 ?
3391 DiamondInvalidArgs(invalidDiamondArgs, fragment) :
3392 DiamondInvalidArg(invalidDiamondArgs, fragment)));
3393 }
3394 // For <>(){}, inferred types must also be accessible.
3395 for (Type t : clazztype.getTypeArguments()) {
3396 rs.checkAccessibleType(env, t);
3397 }
3398 }
3399
3400 // If we already errored, be careful to avoid a further avalanche. ErrorType answers
3401 // false for isInterface call even when the original type is an interface.
3402 boolean implementing = clazztype.tsym.isInterface() ||
3403 clazztype.isErroneous() && !clazztype.getOriginalType().hasTag(NONE) &&
3404 clazztype.getOriginalType().tsym.isInterface();
3405
3406 if (implementing) {
3407 cdef.implementing = List.of(clazz);
3408 } else {
3409 cdef.extending = clazz;
3410 }
3411
3412 if (resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
3413 rs.isSerializable(clazztype)) {
3414 localEnv.info.isSerializable = true;
3415 }
3416
3417 attribStat(cdef, localEnv);
3418
3419 List<Type> finalargtypes;
3420 // If an outer instance is given,
3421 // prefix it to the constructor arguments
3422 // and delete it from the new expression
3423 if (tree.encl != null && !clazztype.tsym.isInterface()) {
3424 finalargtypes = argtypes.prepend(tree.encl.type);
3425 } else {
3426 finalargtypes = argtypes;
3427 }
3428
3429 // Reassign clazztype and recompute constructor. As this necessarily involves
3430 // another attribution pass for deferred types in the case of <>, replicate
3431 // them. Original arguments have right decorations already.
3432 if (isDiamond && pkind.contains(KindSelector.POLY)) {
3433 finalargtypes = finalargtypes.map(deferredAttr.deferredCopier);
3434 }
3435
3436 clazztype = clazztype.hasTag(ERROR) ? types.createErrorType(cdef.sym.type)
3437 : cdef.sym.type;
3438 Symbol sym = tree.constructor = rs.resolveConstructor(
3439 tree.pos(), localEnv, clazztype, finalargtypes, typeargtypes);
3440 Assert.check(!sym.kind.isResolutionError());
3441 tree.constructor = sym;
3442 tree.constructorType = checkId(tree,
3443 clazztype,
3444 tree.constructor,
3445 localEnv,
3446 new ResultInfo(pkind, newMethodTemplate(syms.voidType, finalargtypes, typeargtypes), CheckMode.NO_TREE_UPDATE));
3447 }
3448 Type owntype = (tree.constructor != null && tree.constructor.kind == MTH) ?
3449 clazztype : types.createErrorType(tree.type);
3450 result = check(tree, owntype, KindSelector.VAL, resultInfo.dup(CheckMode.NO_INFERENCE_HOOK));
3451 chk.validate(tree.typeargs, localEnv);
3452 }
3453
3454 CheckContext diamondContext(JCNewClass clazz, TypeSymbol tsym, CheckContext checkContext) {
3455 return new Check.NestedCheckContext(checkContext) {
3456 @Override
3457 public void report(DiagnosticPosition _unused, JCDiagnostic details) {
3458 enclosingContext.report(clazz.clazz,
3459 diags.fragment(Fragments.CantApplyDiamond1(Fragments.Diamond(tsym), details)));
3460 }
3461 };
3462 }
3463
3464 void checkNewInnerClass(DiagnosticPosition pos, Env<AttrContext> env, Type type, boolean isSuper) {
3465 boolean isLocal = type.tsym.owner.kind == VAR || type.tsym.owner.kind == MTH;
3466 if ((type.tsym.flags() & (INTERFACE | ENUM | RECORD)) != 0 ||
3467 (!isLocal && !type.tsym.isInner()) ||
3468 (isSuper && env.enclClass.sym.isAnonymous())) {
3469 // nothing to check
3470 return;
3471 }
3472 Symbol res = isLocal ?
3473 rs.findLocalClassOwner(env, type.tsym) :
3474 rs.findSelfContaining(pos, env, type.getEnclosingType().tsym, isSuper);
3475 if (res.exists()) {
3476 rs.accessBase(res, pos, env.enclClass.sym.type, names._this, true);
3477 } else {
3478 log.error(pos, Errors.EnclClassRequired(type.tsym));
3479 }
3480 }
3481
3482 /** Make an attributed null check tree.
3483 */
3484 public JCExpression makeNullCheck(JCExpression arg) {
3485 // optimization: new Outer() can never be null; skip null check
3486 if (arg.getTag() == NEWCLASS)
3487 return arg;
3488 // optimization: X.this is never null; skip null check
3489 Name name = TreeInfo.name(arg);
3490 if (name == names._this || name == names._super) return arg;
3491
3492 JCTree.Tag optag = NULLCHK;
3493 JCUnary tree = make.at(arg.pos).Unary(optag, arg);
3494 tree.operator = operators.resolveUnary(arg, optag, arg.type);
3495 tree.type = arg.type;
3496 return tree;
3497 }
3498
3499 public void visitNewArray(JCNewArray tree) {
3500 Type owntype = types.createErrorType(tree.type);
3501 Env<AttrContext> localEnv = env.dup(tree);
3502 Type elemtype;
3503 if (tree.elemtype != null) {
3504 elemtype = attribType(tree.elemtype, localEnv);
3505 chk.validate(tree.elemtype, localEnv);
3506 owntype = elemtype;
3507 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
3508 attribExpr(l.head, localEnv, syms.intType);
3509 owntype = new ArrayType(owntype, syms.arrayClass);
3510 }
3511 } else {
3512 // we are seeing an untyped aggregate { ... }
3513 // this is allowed only if the prototype is an array
3514 if (pt().hasTag(ARRAY)) {
3515 elemtype = types.elemtype(pt());
3516 } else {
3517 if (!pt().hasTag(ERROR) &&
3518 (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
3519 log.error(tree.pos(),
3520 Errors.IllegalInitializerForType(pt()));
3521 }
3522 elemtype = types.createErrorType(pt());
3523 }
3524 }
3525 if (tree.elems != null) {
3526 attribExprs(tree.elems, localEnv, elemtype);
3527 owntype = new ArrayType(elemtype, syms.arrayClass);
3528 }
3529 if (!types.isReifiable(elemtype))
3530 log.error(tree.pos(), Errors.GenericArrayCreation);
3531 result = check(tree, owntype, KindSelector.VAL, resultInfo);
3532 }
3533
3534 /*
3535 * A lambda expression can only be attributed when a target-type is available.
3536 * In addition, if the target-type is that of a functional interface whose
3537 * descriptor contains inference variables in argument position the lambda expression
3538 * is 'stuck' (see DeferredAttr).
3539 */
3540 @Override
3541 public void visitLambda(final JCLambda that) {
3542 boolean wrongContext = false;
3543 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
3544 if (pt().hasTag(NONE) && (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
3545 //lambda only allowed in assignment or method invocation/cast context
3546 log.error(that.pos(), Errors.UnexpectedLambda);
3547 }
3548 resultInfo = recoveryInfo;
3549 wrongContext = true;
3550 }
3551 //create an environment for attribution of the lambda expression
3552 final Env<AttrContext> localEnv = lambdaEnv(that, env);
3553 boolean needsRecovery =
3554 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK;
3555 try {
3556 if (needsRecovery && rs.isSerializable(pt())) {
3557 localEnv.info.isSerializable = true;
3558 localEnv.info.isSerializableLambda = true;
3559 }
3560 List<Type> explicitParamTypes = null;
3561 if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) {
3562 //attribute lambda parameters
3563 attribStats(that.params, localEnv);
3564 explicitParamTypes = TreeInfo.types(that.params);
3565 }
3566
3567 TargetInfo targetInfo = getTargetInfo(that, resultInfo, explicitParamTypes);
3568 Type currentTarget = targetInfo.target;
3569 Type lambdaType = targetInfo.descriptor;
3570
3571 if (currentTarget.isErroneous()) {
3572 result = that.type = currentTarget;
3573 return;
3574 }
3575
3576 setFunctionalInfo(localEnv, that, pt(), lambdaType, currentTarget, resultInfo.checkContext);
3577
3578 if (lambdaType.hasTag(FORALL)) {
3579 //lambda expression target desc cannot be a generic method
3580 Fragment msg = Fragments.InvalidGenericLambdaTarget(lambdaType,
3581 kindName(currentTarget.tsym),
3582 currentTarget.tsym);
3583 resultInfo.checkContext.report(that, diags.fragment(msg));
3584 result = that.type = types.createErrorType(pt());
3585 return;
3586 }
3587
3588 if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) {
3589 //add param type info in the AST
3590 List<Type> actuals = lambdaType.getParameterTypes();
3591 List<JCVariableDecl> params = that.params;
3592
3593 boolean arityMismatch = false;
3594
3595 while (params.nonEmpty()) {
3596 if (actuals.isEmpty()) {
3597 //not enough actuals to perform lambda parameter inference
3598 arityMismatch = true;
3599 }
3600 //reset previously set info
3601 Type argType = arityMismatch ?
3602 syms.errType :
3603 actuals.head;
3604 if (params.head.isImplicitlyTyped()) {
3605 setSyntheticVariableType(params.head, argType);
3606 }
3607 params.head.sym = null;
3608 actuals = actuals.isEmpty() ?
3609 actuals :
3610 actuals.tail;
3611 params = params.tail;
3612 }
3613
3614 //attribute lambda parameters
3615 attribStats(that.params, localEnv);
3616
3617 if (arityMismatch) {
3618 resultInfo.checkContext.report(that, diags.fragment(Fragments.IncompatibleArgTypesInLambda));
3619 result = that.type = types.createErrorType(currentTarget);
3620 return;
3621 }
3622 }
3623
3624 //from this point on, no recovery is needed; if we are in assignment context
3625 //we will be able to attribute the whole lambda body, regardless of errors;
3626 //if we are in a 'check' method context, and the lambda is not compatible
3627 //with the target-type, it will be recovered anyway in Attr.checkId
3628 needsRecovery = false;
3629
3630 ResultInfo bodyResultInfo = localEnv.info.returnResult =
3631 lambdaBodyResult(that, lambdaType, resultInfo);
3632
3633 if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
3634 attribTree(that.getBody(), localEnv, bodyResultInfo);
3635 } else {
3636 JCBlock body = (JCBlock)that.body;
3637 if (body == breakTree &&
3638 resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
3639 breakTreeFound(copyEnv(localEnv));
3640 }
3641 attribStats(body.stats, localEnv);
3642 }
3643
3644 result = check(that, currentTarget, KindSelector.VAL, resultInfo);
3645
3646 boolean isSpeculativeRound =
3647 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
3648
3649 preFlow(that);
3650 flow.analyzeLambda(env, that, make, isSpeculativeRound);
3651
3652 that.type = currentTarget; //avoids recovery at this stage
3653 checkLambdaCompatible(that, lambdaType, resultInfo.checkContext);
3654
3655 if (!isSpeculativeRound) {
3656 //add thrown types as bounds to the thrown types free variables if needed:
3657 if (resultInfo.checkContext.inferenceContext().free(lambdaType.getThrownTypes())) {
3658 List<Type> inferredThrownTypes = flow.analyzeLambdaThrownTypes(env, that, make);
3659 if(!checkExConstraints(inferredThrownTypes, lambdaType.getThrownTypes(), resultInfo.checkContext.inferenceContext())) {
3660 log.error(that, Errors.IncompatibleThrownTypesInMref(lambdaType.getThrownTypes()));
3661 }
3662 }
3663
3664 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, currentTarget);
3665 }
3666 result = wrongContext ? that.type = types.createErrorType(pt())
3667 : check(that, currentTarget, KindSelector.VAL, resultInfo);
3668 } catch (Types.FunctionDescriptorLookupError ex) {
3669 JCDiagnostic cause = ex.getDiagnostic();
3670 resultInfo.checkContext.report(that, cause);
3671 result = that.type = types.createErrorType(pt());
3672 return;
3673 } catch (CompletionFailure cf) {
3674 chk.completionError(that.pos(), cf);
3675 } catch (Throwable t) {
3676 //when an unexpected exception happens, avoid attempts to attribute the same tree again
3677 //as that would likely cause the same exception again.
3678 needsRecovery = false;
3679 throw t;
3680 } finally {
3681 localEnv.info.scope.leave();
3682 if (needsRecovery) {
3683 Type prevResult = result;
3684 try {
3685 attribTree(that, env, recoveryInfo);
3686 } finally {
3687 if (result == Type.recoveryType) {
3688 result = prevResult;
3689 }
3690 }
3691 }
3692 }
3693 }
3694 //where
3695 class TargetInfo {
3696 Type target;
3697 Type descriptor;
3698
3699 public TargetInfo(Type target, Type descriptor) {
3700 this.target = target;
3701 this.descriptor = descriptor;
3702 }
3703 }
3704
3705 TargetInfo getTargetInfo(JCPolyExpression that, ResultInfo resultInfo, List<Type> explicitParamTypes) {
3706 Type lambdaType;
3707 Type currentTarget = resultInfo.pt;
3708 if (resultInfo.pt != Type.recoveryType) {
3709 /* We need to adjust the target. If the target is an
3710 * intersection type, for example: SAM & I1 & I2 ...
3711 * the target will be updated to SAM
3712 */
3713 currentTarget = targetChecker.visit(currentTarget, that);
3714 if (!currentTarget.isIntersection()) {
3715 if (explicitParamTypes != null) {
3716 currentTarget = infer.instantiateFunctionalInterface(that,
3717 currentTarget, explicitParamTypes, resultInfo.checkContext);
3718 }
3719 currentTarget = types.removeWildcards(currentTarget);
3720 lambdaType = types.findDescriptorType(currentTarget);
3721 } else {
3722 IntersectionClassType ict = (IntersectionClassType)currentTarget;
3723 ListBuffer<Type> components = new ListBuffer<>();
3724 for (Type bound : ict.getExplicitComponents()) {
3725 if (explicitParamTypes != null) {
3726 try {
3727 bound = infer.instantiateFunctionalInterface(that,
3728 bound, explicitParamTypes, resultInfo.checkContext);
3729 } catch (FunctionDescriptorLookupError t) {
3730 // do nothing
3731 }
3732 }
3733 if (bound.tsym != syms.objectType.tsym && (!bound.isInterface() || (bound.tsym.flags() & ANNOTATION) != 0)) {
3734 // bound must be j.l.Object or an interface, but not an annotation
3735 reportIntersectionError(that, "not.an.intf.component", bound);
3736 }
3737 bound = types.removeWildcards(bound);
3738 components.add(bound);
3739 }
3740 currentTarget = types.makeIntersectionType(components.toList());
3741 currentTarget.tsym.flags_field |= INTERFACE;
3742 lambdaType = types.findDescriptorType(currentTarget);
3743 }
3744
3745 } else {
3746 currentTarget = Type.recoveryType;
3747 lambdaType = fallbackDescriptorType(that);
3748 }
3749 if (that.hasTag(LAMBDA) && lambdaType.hasTag(FORALL)) {
3750 //lambda expression target desc cannot be a generic method
3751 Fragment msg = Fragments.InvalidGenericLambdaTarget(lambdaType,
3752 kindName(currentTarget.tsym),
3753 currentTarget.tsym);
3754 resultInfo.checkContext.report(that, diags.fragment(msg));
3755 currentTarget = types.createErrorType(pt());
3756 }
3757 return new TargetInfo(currentTarget, lambdaType);
3758 }
3759
3760 private void reportIntersectionError(DiagnosticPosition pos, String key, Object... args) {
3761 resultInfo.checkContext.report(pos,
3762 diags.fragment(Fragments.BadIntersectionTargetForFunctionalExpr(diags.fragment(key, args))));
3763 }
3764
3765 void preFlow(JCLambda tree) {
3766 attrRecover.doRecovery();
3767 new PostAttrAnalyzer() {
3768 @Override
3769 public void scan(JCTree tree) {
3770 if (tree == null ||
3771 (tree.type != null &&
3772 tree.type == Type.stuckType)) {
3773 //don't touch stuck expressions!
3774 return;
3775 }
3776 super.scan(tree);
3777 }
3778
3779 @Override
3780 public void visitClassDef(JCClassDecl that) {
3781 // or class declaration trees!
3782 }
3783
3784 public void visitLambda(JCLambda that) {
3785 // or lambda expressions!
3786 }
3787 }.scan(tree.body);
3788 }
3789
3790 Types.MapVisitor<DiagnosticPosition> targetChecker = new Types.MapVisitor<DiagnosticPosition>() {
3791
3792 @Override
3793 public Type visitClassType(ClassType t, DiagnosticPosition pos) {
3794 return t.isIntersection() ?
3795 visitIntersectionClassType((IntersectionClassType)t, pos) : t;
3796 }
3797
3798 public Type visitIntersectionClassType(IntersectionClassType ict, DiagnosticPosition pos) {
3799 types.findDescriptorSymbol(makeNotionalInterface(ict, pos));
3800 return ict;
3801 }
3802
3803 private TypeSymbol makeNotionalInterface(IntersectionClassType ict, DiagnosticPosition pos) {
3804 ListBuffer<Type> targs = new ListBuffer<>();
3805 ListBuffer<Type> supertypes = new ListBuffer<>();
3806 for (Type i : ict.interfaces_field) {
3807 if (i.isParameterized()) {
3808 targs.appendList(i.tsym.type.allparams());
3809 }
3810 supertypes.append(i.tsym.type);
3811 }
3812 IntersectionClassType notionalIntf = types.makeIntersectionType(supertypes.toList());
3813 notionalIntf.allparams_field = targs.toList();
3814 notionalIntf.tsym.flags_field |= INTERFACE;
3815 return notionalIntf.tsym;
3816 }
3817 };
3818
3819 private Type fallbackDescriptorType(JCExpression tree) {
3820 switch (tree.getTag()) {
3821 case LAMBDA:
3822 JCLambda lambda = (JCLambda)tree;
3823 List<Type> argtypes = List.nil();
3824 for (JCVariableDecl param : lambda.params) {
3825 argtypes = param.vartype != null && param.vartype.type != null ?
3826 argtypes.append(param.vartype.type) :
3827 argtypes.append(syms.errType);
3828 }
3829 return new MethodType(argtypes, Type.recoveryType,
3830 List.of(syms.throwableType), syms.methodClass);
3831 case REFERENCE:
3832 return new MethodType(List.nil(), Type.recoveryType,
3833 List.of(syms.throwableType), syms.methodClass);
3834 default:
3835 Assert.error("Cannot get here!");
3836 }
3837 return null;
3838 }
3839
3840 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
3841 final InferenceContext inferenceContext, final Type... ts) {
3842 checkAccessibleTypes(pos, env, inferenceContext, List.from(ts));
3843 }
3844
3845 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env,
3846 final InferenceContext inferenceContext, final List<Type> ts) {
3847 if (inferenceContext.free(ts)) {
3848 inferenceContext.addFreeTypeListener(ts,
3849 solvedContext -> checkAccessibleTypes(pos, env, solvedContext, solvedContext.asInstTypes(ts)));
3850 } else {
3851 for (Type t : ts) {
3852 rs.checkAccessibleType(env, t);
3853 }
3854 }
3855 }
3856
3857 /**
3858 * Lambda/method reference have a special check context that ensures
3859 * that i.e. a lambda return type is compatible with the expected
3860 * type according to both the inherited context and the assignment
3861 * context.
3862 */
3863 class FunctionalReturnContext extends Check.NestedCheckContext {
3864
3865 FunctionalReturnContext(CheckContext enclosingContext) {
3866 super(enclosingContext);
3867 }
3868
3869 @Override
3870 public boolean compatible(Type found, Type req, Warner warn) {
3871 //return type must be compatible in both current context and assignment context
3872 return chk.basicHandler.compatible(inferenceContext().asUndetVar(found), inferenceContext().asUndetVar(req), warn);
3873 }
3874
3875 @Override
3876 public void report(DiagnosticPosition pos, JCDiagnostic details) {
3877 enclosingContext.report(pos, diags.fragment(Fragments.IncompatibleRetTypeInLambda(details)));
3878 }
3879 }
3880
3881 class ExpressionLambdaReturnContext extends FunctionalReturnContext {
3882
3883 JCExpression expr;
3884 boolean expStmtExpected;
3885
3886 ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) {
3887 super(enclosingContext);
3888 this.expr = expr;
3889 }
3890
3891 @Override
3892 public void report(DiagnosticPosition pos, JCDiagnostic details) {
3893 if (expStmtExpected) {
3894 enclosingContext.report(pos, diags.fragment(Fragments.StatExprExpected));
3895 } else {
3896 super.report(pos, details);
3897 }
3898 }
3899
3900 @Override
3901 public boolean compatible(Type found, Type req, Warner warn) {
3902 //a void return is compatible with an expression statement lambda
3903 if (req.hasTag(VOID)) {
3904 expStmtExpected = true;
3905 return TreeInfo.isExpressionStatement(expr);
3906 } else {
3907 return super.compatible(found, req, warn);
3908 }
3909 }
3910 }
3911
3912 ResultInfo lambdaBodyResult(JCLambda that, Type descriptor, ResultInfo resultInfo) {
3913 FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
3914 new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) :
3915 new FunctionalReturnContext(resultInfo.checkContext);
3916
3917 return descriptor.getReturnType() == Type.recoveryType ?
3918 recoveryInfo :
3919 new ResultInfo(KindSelector.VAL,
3920 descriptor.getReturnType(), funcContext);
3921 }
3922
3923 /**
3924 * Lambda compatibility. Check that given return types, thrown types, parameter types
3925 * are compatible with the expected functional interface descriptor. This means that:
3926 * (i) parameter types must be identical to those of the target descriptor; (ii) return
3927 * types must be compatible with the return type of the expected descriptor.
3928 */
3929 void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext) {
3930 Type returnType = checkContext.inferenceContext().asUndetVar(descriptor.getReturnType());
3931
3932 //return values have already been checked - but if lambda has no return
3933 //values, we must ensure that void/value compatibility is correct;
3934 //this amounts at checking that, if a lambda body can complete normally,
3935 //the descriptor's return type must be void
3936 if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally &&
3937 !returnType.hasTag(VOID) && returnType != Type.recoveryType) {
3938 Fragment msg =
3939 Fragments.IncompatibleRetTypeInLambda(Fragments.MissingRetVal(returnType));
3940 checkContext.report(tree,
3941 diags.fragment(msg));
3942 }
3943
3944 List<Type> argTypes = checkContext.inferenceContext().asUndetVars(descriptor.getParameterTypes());
3945 if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) {
3946 checkContext.report(tree, diags.fragment(Fragments.IncompatibleArgTypesInLambda));
3947 }
3948 }
3949
3950 /* This method returns an environment to be used to attribute a lambda
3951 * expression.
3952 *
3953 * The owner of this environment is a method symbol. If the current owner
3954 * is not a method (e.g. if the lambda occurs in a field initializer), then
3955 * a synthetic method symbol owner is created.
3956 */
3957 public Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) {
3958 Env<AttrContext> lambdaEnv;
3959 Symbol owner = env.info.scope.owner;
3960 if (owner.kind == VAR && owner.owner.kind == TYP) {
3961 // If the lambda is nested in a field initializer, we need to create a fake init method.
3962 // Uniqueness of this symbol is not important (as e.g. annotations will be added on the
3963 // init symbol's owner).
3964 ClassSymbol enclClass = owner.enclClass();
3965 Name initName = owner.isStatic() ? names.clinit : names.init;
3966 MethodSymbol initSym = new MethodSymbol(BLOCK | (owner.isStatic() ? STATIC : 0) | SYNTHETIC | PRIVATE,
3967 initName, initBlockType, enclClass);
3968 initSym.params = List.nil();
3969 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared(initSym)));
3970 } else {
3971 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup()));
3972 }
3973 lambdaEnv.info.yieldResult = null;
3974 lambdaEnv.info.isLambda = true;
3975 return lambdaEnv;
3976 }
3977
3978 @Override
3979 public void visitReference(final JCMemberReference that) {
3980 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) {
3981 if (pt().hasTag(NONE) && (env.info.enclVar == null || !env.info.enclVar.type.isErroneous())) {
3982 //method reference only allowed in assignment or method invocation/cast context
3983 log.error(that.pos(), Errors.UnexpectedMref);
3984 }
3985 result = that.type = types.createErrorType(pt());
3986 return;
3987 }
3988 final Env<AttrContext> localEnv = env.dup(that);
3989 try {
3990 //attribute member reference qualifier - if this is a constructor
3991 //reference, the expected kind must be a type
3992 Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that));
3993
3994 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) {
3995 exprType = chk.checkConstructorRefType(that.expr, exprType);
3996 if (!exprType.isErroneous() &&
3997 exprType.isRaw() &&
3998 that.typeargs != null) {
3999 log.error(that.expr.pos(),
4000 Errors.InvalidMref(Kinds.kindName(that.getMode()),
4001 Fragments.MrefInferAndExplicitParams));
4002 exprType = types.createErrorType(exprType);
4003 }
4004 }
4005
4006 if (exprType.isErroneous()) {
4007 //if the qualifier expression contains problems,
4008 //give up attribution of method reference
4009 result = that.type = exprType;
4010 return;
4011 }
4012
4013 if (TreeInfo.isStaticSelector(that.expr, names)) {
4014 //if the qualifier is a type, validate it; raw warning check is
4015 //omitted as we don't know at this stage as to whether this is a
4016 //raw selector (because of inference)
4017 chk.validate(that.expr, env, false);
4018 } else {
4019 Symbol lhsSym = TreeInfo.symbol(that.expr);
4020 localEnv.info.selectSuper = lhsSym != null && lhsSym.name == names._super;
4021 }
4022 //attrib type-arguments
4023 List<Type> typeargtypes = List.nil();
4024 if (that.typeargs != null) {
4025 typeargtypes = attribTypes(that.typeargs, localEnv);
4026 }
4027
4028 boolean isTargetSerializable =
4029 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
4030 rs.isSerializable(pt());
4031 TargetInfo targetInfo = getTargetInfo(that, resultInfo, null);
4032 Type currentTarget = targetInfo.target;
4033 Type desc = targetInfo.descriptor;
4034
4035 setFunctionalInfo(localEnv, that, pt(), desc, currentTarget, resultInfo.checkContext);
4036 List<Type> argtypes = desc.getParameterTypes();
4037 Resolve.MethodCheck referenceCheck = rs.resolveMethodCheck;
4038
4039 if (resultInfo.checkContext.inferenceContext().free(argtypes)) {
4040 referenceCheck = rs.new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
4041 }
4042
4043 Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = null;
4044 List<Type> saved_undet = resultInfo.checkContext.inferenceContext().save();
4045 try {
4046 refResult = rs.resolveMemberReference(localEnv, that, that.expr.type,
4047 that.name, argtypes, typeargtypes, targetInfo.descriptor, referenceCheck,
4048 resultInfo.checkContext.inferenceContext(), rs.basicReferenceChooser);
4049 } finally {
4050 resultInfo.checkContext.inferenceContext().rollback(saved_undet);
4051 }
4052
4053 Symbol refSym = refResult.fst;
4054 Resolve.ReferenceLookupHelper lookupHelper = refResult.snd;
4055
4056 /** this switch will need to go away and be replaced by the new RESOLUTION_TARGET testing
4057 * JDK-8075541
4058 */
4059 if (refSym.kind != MTH) {
4060 boolean targetError;
4061 switch (refSym.kind) {
4062 case ABSENT_MTH:
4063 targetError = false;
4064 break;
4065 case WRONG_MTH:
4066 case WRONG_MTHS:
4067 case AMBIGUOUS:
4068 case HIDDEN:
4069 case STATICERR:
4070 targetError = true;
4071 break;
4072 default:
4073 Assert.error("unexpected result kind " + refSym.kind);
4074 targetError = false;
4075 }
4076
4077 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym.baseSymbol())
4078 .getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT,
4079 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes);
4080
4081 JCDiagnostic diag = diags.create(log.currentSource(), that,
4082 targetError ?
4083 Fragments.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag) :
4084 Errors.InvalidMref(Kinds.kindName(that.getMode()), detailsDiag));
4085
4086 if (targetError && currentTarget == Type.recoveryType) {
4087 //a target error doesn't make sense during recovery stage
4088 //as we don't know what actual parameter types are
4089 result = that.type = currentTarget;
4090 return;
4091 } else {
4092 if (targetError) {
4093 resultInfo.checkContext.report(that, diag);
4094 } else {
4095 log.report(diag);
4096 }
4097 result = that.type = types.createErrorType(currentTarget);
4098 return;
4099 }
4100 }
4101
4102 that.sym = refSym.isConstructor() ? refSym.baseSymbol() : refSym;
4103 that.kind = lookupHelper.referenceKind(that.sym);
4104 that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass());
4105
4106 if (desc.getReturnType() == Type.recoveryType) {
4107 // stop here
4108 result = that.type = currentTarget;
4109 return;
4110 }
4111
4112 if (!env.info.attributionMode.isSpeculative && that.getMode() == JCMemberReference.ReferenceMode.NEW) {
4113 checkNewInnerClass(that.pos(), env, exprType, false);
4114 }
4115
4116 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
4117
4118 if (that.getMode() == ReferenceMode.INVOKE &&
4119 TreeInfo.isStaticSelector(that.expr, names) &&
4120 that.kind.isUnbound() &&
4121 lookupHelper.site.isRaw()) {
4122 chk.checkRaw(that.expr, localEnv);
4123 }
4124
4125 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) &&
4126 exprType.getTypeArguments().nonEmpty()) {
4127 //static ref with class type-args
4128 log.error(that.expr.pos(),
4129 Errors.InvalidMref(Kinds.kindName(that.getMode()),
4130 Fragments.StaticMrefWithTargs));
4131 result = that.type = types.createErrorType(currentTarget);
4132 return;
4133 }
4134
4135 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) {
4136 // Check that super-qualified symbols are not abstract (JLS)
4137 rs.checkNonAbstract(that.pos(), that.sym);
4138 }
4139
4140 if (isTargetSerializable) {
4141 chk.checkAccessFromSerializableElement(that, true);
4142 }
4143 }
4144
4145 ResultInfo checkInfo =
4146 resultInfo.dup(newMethodTemplate(
4147 desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(),
4148 that.kind.isUnbound() ? argtypes.tail : argtypes, typeargtypes),
4149 new FunctionalReturnContext(resultInfo.checkContext), CheckMode.NO_TREE_UPDATE);
4150
4151 Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo);
4152
4153 if (that.kind.isUnbound() &&
4154 resultInfo.checkContext.inferenceContext().free(argtypes.head)) {
4155 //re-generate inference constraints for unbound receiver
4156 if (!types.isSubtype(resultInfo.checkContext.inferenceContext().asUndetVar(argtypes.head), exprType)) {
4157 //cannot happen as this has already been checked - we just need
4158 //to regenerate the inference constraints, as that has been lost
4159 //as a result of the call to inferenceContext.save()
4160 Assert.error("Can't get here");
4161 }
4162 }
4163
4164 if (!refType.isErroneous()) {
4165 refType = types.createMethodTypeWithReturn(refType,
4166 adjustMethodReturnType(refSym, lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType()));
4167 }
4168
4169 //go ahead with standard method reference compatibility check - note that param check
4170 //is a no-op (as this has been taken care during method applicability)
4171 boolean isSpeculativeRound =
4172 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE;
4173
4174 that.type = currentTarget; //avoids recovery at this stage
4175 checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound);
4176 if (!isSpeculativeRound) {
4177 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, currentTarget);
4178 }
4179 chk.checkRequiresIdentity(that, localEnv.info.lint);
4180 result = check(that, currentTarget, KindSelector.VAL, resultInfo);
4181 } catch (Types.FunctionDescriptorLookupError ex) {
4182 JCDiagnostic cause = ex.getDiagnostic();
4183 resultInfo.checkContext.report(that, cause);
4184 result = that.type = types.createErrorType(pt());
4185 return;
4186 }
4187 }
4188 //where
4189 ResultInfo memberReferenceQualifierResult(JCMemberReference tree) {
4190 //if this is a constructor reference, the expected kind must be a type
4191 return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ?
4192 KindSelector.VAL_TYP : KindSelector.TYP,
4193 Type.noType);
4194 }
4195
4196
4197 @SuppressWarnings("fallthrough")
4198 void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) {
4199 InferenceContext inferenceContext = checkContext.inferenceContext();
4200 Type returnType = inferenceContext.asUndetVar(descriptor.getReturnType());
4201
4202 Type resType;
4203 switch (tree.getMode()) {
4204 case NEW:
4205 if (!tree.expr.type.isRaw()) {
4206 resType = tree.expr.type;
4207 break;
4208 }
4209 default:
4210 resType = refType.getReturnType();
4211 }
4212
4213 Type incompatibleReturnType = resType;
4214
4215 if (returnType.hasTag(VOID)) {
4216 incompatibleReturnType = null;
4217 }
4218
4219 if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) {
4220 Type capturedResType = captureMRefReturnType ? types.capture(resType) : resType;
4221 if (resType.isErroneous() ||
4222 new FunctionalReturnContext(checkContext).compatible(capturedResType, returnType,
4223 checkContext.checkWarner(tree, capturedResType, returnType))) {
4224 incompatibleReturnType = null;
4225 }
4226 }
4227
4228 if (incompatibleReturnType != null) {
4229 Fragment msg =
4230 Fragments.IncompatibleRetTypeInMref(Fragments.InconvertibleTypes(resType, descriptor.getReturnType()));
4231 checkContext.report(tree, diags.fragment(msg));
4232 } else {
4233 if (inferenceContext.free(refType)) {
4234 // we need to wait for inference to finish and then replace inference vars in the referent type
4235 inferenceContext.addFreeTypeListener(List.of(refType),
4236 instantiatedContext -> {
4237 tree.referentType = instantiatedContext.asInstType(refType);
4238 });
4239 } else {
4240 tree.referentType = refType;
4241 }
4242 }
4243
4244 if (!speculativeAttr) {
4245 if (!checkExConstraints(refType.getThrownTypes(), descriptor.getThrownTypes(), inferenceContext)) {
4246 log.error(tree, Errors.IncompatibleThrownTypesInMref(refType.getThrownTypes()));
4247 }
4248 }
4249 }
4250
4251 boolean checkExConstraints(
4252 List<Type> thrownByFuncExpr,
4253 List<Type> thrownAtFuncType,
4254 InferenceContext inferenceContext) {
4255 /** 18.2.5: Otherwise, let E1, ..., En be the types in the function type's throws clause that
4256 * are not proper types
4257 */
4258 List<Type> nonProperList = thrownAtFuncType.stream()
4259 .filter(e -> inferenceContext.free(e)).collect(List.collector());
4260 List<Type> properList = thrownAtFuncType.diff(nonProperList);
4261
4262 /** Let X1,...,Xm be the checked exception types that the lambda body can throw or
4263 * in the throws clause of the invocation type of the method reference's compile-time
4264 * declaration
4265 */
4266 List<Type> checkedList = thrownByFuncExpr.stream()
4267 .filter(e -> chk.isChecked(e)).collect(List.collector());
4268
4269 /** If n = 0 (the function type's throws clause consists only of proper types), then
4270 * if there exists some i (1 <= i <= m) such that Xi is not a subtype of any proper type
4271 * in the throws clause, the constraint reduces to false; otherwise, the constraint
4272 * reduces to true
4273 */
4274 ListBuffer<Type> uncaughtByProperTypes = new ListBuffer<>();
4275 for (Type checked : checkedList) {
4276 boolean isSubtype = false;
4277 for (Type proper : properList) {
4278 if (types.isSubtype(checked, proper)) {
4279 isSubtype = true;
4280 break;
4281 }
4282 }
4283 if (!isSubtype) {
4284 uncaughtByProperTypes.add(checked);
4285 }
4286 }
4287
4288 if (nonProperList.isEmpty() && !uncaughtByProperTypes.isEmpty()) {
4289 return false;
4290 }
4291
4292 /** If n > 0, the constraint reduces to a set of subtyping constraints:
4293 * for all i (1 <= i <= m), if Xi is not a subtype of any proper type in the
4294 * throws clause, then the constraints include, for all j (1 <= j <= n), <Xi <: Ej>
4295 */
4296 List<Type> nonProperAsUndet = inferenceContext.asUndetVars(nonProperList);
4297 uncaughtByProperTypes.forEach(checkedEx -> {
4298 nonProperAsUndet.forEach(nonProper -> {
4299 types.isSubtype(checkedEx, nonProper);
4300 });
4301 });
4302
4303 /** In addition, for all j (1 <= j <= n), the constraint reduces to the bound throws Ej
4304 */
4305 nonProperAsUndet.stream()
4306 .filter(t -> t.hasTag(UNDETVAR))
4307 .forEach(t -> ((UndetVar)t).setThrow());
4308 return true;
4309 }
4310
4311 /**
4312 * Set functional type info on the underlying AST. Note: as the target descriptor
4313 * might contain inference variables, we might need to register an hook in the
4314 * current inference context.
4315 */
4316 private void setFunctionalInfo(final Env<AttrContext> env, final JCFunctionalExpression fExpr,
4317 final Type pt, final Type descriptorType, final Type primaryTarget, final CheckContext checkContext) {
4318 if (checkContext.inferenceContext().free(descriptorType)) {
4319 checkContext.inferenceContext().addFreeTypeListener(List.of(pt, descriptorType),
4320 inferenceContext -> setFunctionalInfo(env, fExpr, pt, inferenceContext.asInstType(descriptorType),
4321 inferenceContext.asInstType(primaryTarget), checkContext));
4322 } else {
4323 fExpr.owner = env.info.scope.owner;
4324 if (pt.hasTag(CLASS)) {
4325 fExpr.target = primaryTarget;
4326 }
4327 if (checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK &&
4328 pt != Type.recoveryType) {
4329 //check that functional interface class is well-formed
4330 try {
4331 /* Types.makeFunctionalInterfaceClass() may throw an exception
4332 * when it's executed post-inference. See the listener code
4333 * above.
4334 */
4335 ClassSymbol csym = types.makeFunctionalInterfaceClass(env,
4336 names.empty, fExpr.target, ABSTRACT);
4337 if (csym != null) {
4338 chk.checkImplementations(env.tree, csym, csym);
4339 try {
4340 //perform an additional functional interface check on the synthetic class,
4341 //as there may be spurious errors for raw targets - because of existing issues
4342 //with membership and inheritance (see JDK-8074570).
4343 csym.flags_field |= INTERFACE;
4344 types.findDescriptorType(csym.type);
4345 } catch (FunctionDescriptorLookupError err) {
4346 resultInfo.checkContext.report(fExpr,
4347 diags.fragment(Fragments.NoSuitableFunctionalIntfInst(fExpr.target)));
4348 }
4349 }
4350 } catch (Types.FunctionDescriptorLookupError ex) {
4351 JCDiagnostic cause = ex.getDiagnostic();
4352 resultInfo.checkContext.report(env.tree, cause);
4353 }
4354 }
4355 }
4356 }
4357
4358 public void visitParens(JCParens tree) {
4359 Type owntype = attribTree(tree.expr, env, resultInfo);
4360 result = check(tree, owntype, pkind(), resultInfo);
4361 Symbol sym = TreeInfo.symbol(tree);
4362 if (sym != null && sym.kind.matches(KindSelector.TYP_PCK) && sym.kind != Kind.ERR)
4363 log.error(tree.pos(), Errors.IllegalParenthesizedExpression);
4364 }
4365
4366 public void visitAssign(JCAssign tree) {
4367 Type owntype = attribTree(tree.lhs, env.dup(tree), varAssignmentInfo);
4368 Type capturedType = capture(owntype);
4369 attribExpr(tree.rhs, env, owntype);
4370 result = check(tree, capturedType, KindSelector.VAL, resultInfo);
4371 }
4372
4373 public void visitAssignop(JCAssignOp tree) {
4374 // Attribute arguments.
4375 Type owntype = attribTree(tree.lhs, env, varAssignmentInfo);
4376 Type operand = attribExpr(tree.rhs, env);
4377 // Find operator.
4378 Symbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), owntype, operand);
4379 if (operator != operators.noOpSymbol &&
4380 !owntype.isErroneous() &&
4381 !operand.isErroneous()) {
4382 chk.checkDivZero(tree.rhs.pos(), operator, operand);
4383 chk.checkCastable(tree.rhs.pos(),
4384 operator.type.getReturnType(),
4385 owntype);
4386 chk.checkLossOfPrecision(tree.rhs.pos(), operand, owntype);
4387 }
4388 result = check(tree, owntype, KindSelector.VAL, resultInfo);
4389 }
4390
4391 public void visitUnary(JCUnary tree) {
4392 // Attribute arguments.
4393 Type argtype = (tree.getTag().isIncOrDecUnaryOp())
4394 ? attribTree(tree.arg, env, varAssignmentInfo)
4395 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env));
4396
4397 // Find operator.
4398 OperatorSymbol operator = tree.operator = operators.resolveUnary(tree, tree.getTag(), argtype);
4399 Type owntype = types.createErrorType(tree.type);
4400 if (operator != operators.noOpSymbol &&
4401 !argtype.isErroneous()) {
4402 owntype = (tree.getTag().isIncOrDecUnaryOp())
4403 ? tree.arg.type
4404 : operator.type.getReturnType();
4405 int opc = operator.opcode;
4406
4407 // If the argument is constant, fold it.
4408 if (argtype.constValue() != null) {
4409 Type ctype = cfolder.fold1(opc, argtype);
4410 if (ctype != null) {
4411 owntype = cfolder.coerce(ctype, owntype);
4412 }
4413 }
4414 }
4415 result = check(tree, owntype, KindSelector.VAL, resultInfo);
4416 matchBindings = matchBindingsComputer.unary(tree, matchBindings);
4417 }
4418
4419 public void visitBinary(JCBinary tree) {
4420 // Attribute arguments.
4421 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
4422 // x && y
4423 // include x's bindings when true in y
4424
4425 // x || y
4426 // include x's bindings when false in y
4427
4428 MatchBindings lhsBindings = matchBindings;
4429 List<BindingSymbol> propagatedBindings;
4430 switch (tree.getTag()) {
4431 case AND:
4432 propagatedBindings = lhsBindings.bindingsWhenTrue;
4433 break;
4434 case OR:
4435 propagatedBindings = lhsBindings.bindingsWhenFalse;
4436 break;
4437 default:
4438 propagatedBindings = List.nil();
4439 break;
4440 }
4441 Env<AttrContext> rhsEnv = bindingEnv(env, propagatedBindings);
4442 Type right;
4443 try {
4444 right = chk.checkNonVoid(tree.rhs.pos(), attribExpr(tree.rhs, rhsEnv));
4445 } finally {
4446 rhsEnv.info.scope.leave();
4447 }
4448
4449 matchBindings = matchBindingsComputer.binary(tree, lhsBindings, matchBindings);
4450
4451 // Find operator.
4452 OperatorSymbol operator = tree.operator = operators.resolveBinary(tree, tree.getTag(), left, right);
4453 Type owntype = types.createErrorType(tree.type);
4454 if (operator != operators.noOpSymbol &&
4455 !left.isErroneous() &&
4456 !right.isErroneous()) {
4457 owntype = operator.type.getReturnType();
4458 int opc = operator.opcode;
4459 // If both arguments are constants, fold them.
4460 if (left.constValue() != null && right.constValue() != null) {
4461 Type ctype = cfolder.fold2(opc, left, right);
4462 if (ctype != null) {
4463 owntype = cfolder.coerce(ctype, owntype);
4464 }
4465 }
4466
4467 // Check that argument types of a reference ==, != are
4468 // castable to each other, (JLS 15.21). Note: unboxing
4469 // comparisons will not have an acmp* opc at this point.
4470 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
4471 if (!types.isCastable(left, right, new Warner(tree.pos()))) {
4472 log.error(tree.pos(), Errors.IncomparableTypes(left, right));
4473 }
4474 }
4475
4476 chk.checkDivZero(tree.rhs.pos(), operator, right);
4477 }
4478 result = check(tree, owntype, KindSelector.VAL, resultInfo);
4479 }
4480
4481 public void visitTypeCast(final JCTypeCast tree) {
4482 Type clazztype = attribType(tree.clazz, env);
4483 chk.validate(tree.clazz, env, false);
4484 chk.checkRequiresIdentity(tree, env.info.lint);
4485 //a fresh environment is required for 292 inference to work properly ---
4486 //see Infer.instantiatePolymorphicSignatureInstance()
4487 Env<AttrContext> localEnv = env.dup(tree);
4488 //should we propagate the target type?
4489 final ResultInfo castInfo;
4490 JCExpression expr = TreeInfo.skipParens(tree.expr);
4491 boolean isPoly = (expr.hasTag(LAMBDA) || expr.hasTag(REFERENCE));
4492 if (isPoly) {
4493 //expression is a poly - we need to propagate target type info
4494 castInfo = new ResultInfo(KindSelector.VAL, clazztype,
4495 new Check.NestedCheckContext(resultInfo.checkContext) {
4496 @Override
4497 public boolean compatible(Type found, Type req, Warner warn) {
4498 return types.isCastable(found, req, warn);
4499 }
4500 });
4501 } else {
4502 //standalone cast - target-type info is not propagated
4503 castInfo = unknownExprInfo;
4504 }
4505 Type exprtype = attribTree(tree.expr, localEnv, castInfo);
4506 Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
4507 if (exprtype.constValue() != null)
4508 owntype = cfolder.coerce(exprtype, owntype);
4509 result = check(tree, capture(owntype), KindSelector.VAL, resultInfo);
4510 if (!isPoly)
4511 chk.checkRedundantCast(localEnv, tree);
4512 }
4513
4514 public void visitTypeTest(JCInstanceOf tree) {
4515 Type exprtype = attribExpr(tree.expr, env);
4516 if (exprtype.isPrimitive()) {
4517 preview.checkSourceLevel(tree.expr.pos(), Feature.PRIMITIVE_PATTERNS);
4518 } else {
4519 exprtype = chk.checkNullOrRefType(
4520 tree.expr.pos(), exprtype);
4521 }
4522 Type clazztype;
4523 JCTree typeTree;
4524 if (tree.pattern.getTag() == BINDINGPATTERN ||
4525 tree.pattern.getTag() == RECORDPATTERN) {
4526 attribExpr(tree.pattern, env, exprtype);
4527 clazztype = tree.pattern.type;
4528 if (types.isSubtype(exprtype, clazztype) &&
4529 !exprtype.isErroneous() && !clazztype.isErroneous() &&
4530 tree.pattern.getTag() != RECORDPATTERN) {
4531 if (!allowUnconditionalPatternsInstanceOf) {
4532 log.error(tree.pos(), Feature.UNCONDITIONAL_PATTERN_IN_INSTANCEOF.error(this.sourceName));
4533 }
4534 }
4535 typeTree = TreeInfo.primaryPatternTypeTree((JCPattern) tree.pattern);
4536 } else {
4537 clazztype = attribType(tree.pattern, env);
4538 typeTree = tree.pattern;
4539 chk.validate(typeTree, env, false);
4540 }
4541 if (clazztype.isPrimitive()) {
4542 preview.checkSourceLevel(tree.pattern.pos(), Feature.PRIMITIVE_PATTERNS);
4543 } else {
4544 if (!clazztype.hasTag(TYPEVAR)) {
4545 clazztype = chk.checkClassOrArrayType(typeTree.pos(), clazztype);
4546 }
4547 if (!clazztype.isErroneous() && !types.isReifiable(clazztype)) {
4548 boolean valid = false;
4549 if (allowReifiableTypesInInstanceof) {
4550 valid = checkCastablePattern(tree.expr.pos(), exprtype, clazztype);
4551 } else {
4552 log.error(tree.pos(), Feature.REIFIABLE_TYPES_INSTANCEOF.error(this.sourceName));
4553 allowReifiableTypesInInstanceof = true;
4554 }
4555 if (!valid) {
4556 clazztype = types.createErrorType(clazztype);
4557 }
4558 }
4559 }
4560 chk.checkCastable(tree.expr.pos(), exprtype, clazztype);
4561 result = check(tree, syms.booleanType, KindSelector.VAL, resultInfo);
4562 }
4563
4564 private boolean checkCastablePattern(DiagnosticPosition pos,
4565 Type exprType,
4566 Type pattType) {
4567 Warner warner = new Warner();
4568 // if any type is erroneous, the problem is reported elsewhere
4569 if (exprType.isErroneous() || pattType.isErroneous()) {
4570 return false;
4571 }
4572 if (!types.isCastable(exprType, pattType, warner)) {
4573 chk.basicHandler.report(pos,
4574 diags.fragment(Fragments.InconvertibleTypes(exprType, pattType)));
4575 return false;
4576 } else if ((exprType.isPrimitive() || pattType.isPrimitive()) &&
4577 (!exprType.isPrimitive() || !pattType.isPrimitive() || !types.isSameType(exprType, pattType))) {
4578 preview.checkSourceLevel(pos, Feature.PRIMITIVE_PATTERNS);
4579 return true;
4580 } else if (warner.hasLint(LintCategory.UNCHECKED)) {
4581 log.error(pos,
4582 Errors.InstanceofReifiableNotSafe(exprType, pattType));
4583 return false;
4584 } else {
4585 return true;
4586 }
4587 }
4588
4589 @Override
4590 public void visitAnyPattern(JCAnyPattern tree) {
4591 result = tree.type = resultInfo.pt;
4592 }
4593
4594 public void visitBindingPattern(JCBindingPattern tree) {
4595 Type type;
4596 if (tree.var.vartype != null) {
4597 type = attribType(tree.var.vartype, env);
4598 } else {
4599 type = resultInfo.pt;
4600 }
4601 tree.type = tree.var.type = type;
4602 BindingSymbol v = new BindingSymbol(tree.var.mods.flags, tree.var.name, type, env.info.scope.owner);
4603 v.pos = tree.pos;
4604 tree.var.sym = v;
4605 if (chk.checkUnique(tree.var.pos(), v, env.info.scope)) {
4606 chk.checkTransparentVar(tree.var.pos(), v, env.info.scope);
4607 }
4608 chk.validate(tree.var.vartype, env, true);
4609 if (tree.var.isImplicitlyTyped()) {
4610 setSyntheticVariableType(tree.var, type == Type.noType ? syms.errType
4611 : type);
4612 }
4613 annotate.annotateLater(tree.var.mods.annotations, env, v);
4614 if (!tree.var.isImplicitlyTyped()) {
4615 annotate.queueScanTreeAndTypeAnnotate(tree.var.vartype, env, v);
4616 }
4617 annotate.flush();
4618 result = tree.type;
4619 if (v.isUnnamedVariable()) {
4620 matchBindings = MatchBindingsComputer.EMPTY;
4621 } else {
4622 matchBindings = new MatchBindings(List.of(v), List.nil());
4623 }
4624 chk.checkRequiresIdentity(tree, env.info.lint);
4625 }
4626
4627 @Override
4628 public void visitRecordPattern(JCRecordPattern tree) {
4629 Type site;
4630
4631 if (tree.deconstructor == null) {
4632 log.error(tree.pos(), Errors.DeconstructionPatternVarNotAllowed);
4633 tree.record = syms.errSymbol;
4634 site = tree.type = types.createErrorType(tree.record.type);
4635 } else {
4636 Type type = attribType(tree.deconstructor, env);
4637 if (type.isRaw() && type.tsym.getTypeParameters().nonEmpty()) {
4638 Type inferred = infer.instantiatePatternType(resultInfo.pt, type.tsym);
4639 if (inferred == null) {
4640 log.error(tree.pos(), Errors.PatternTypeCannotInfer);
4641 } else {
4642 type = inferred;
4643 }
4644 }
4645 tree.type = tree.deconstructor.type = type;
4646 site = types.capture(tree.type);
4647 }
4648
4649 List<Type> expectedRecordTypes;
4650 if (site.tsym.kind == Kind.TYP && ((ClassSymbol) site.tsym).isRecord()) {
4651 ClassSymbol record = (ClassSymbol) site.tsym;
4652 expectedRecordTypes = record.getRecordComponents()
4653 .stream()
4654 .map(rc -> types.memberType(site, rc))
4655 .map(t -> types.upward(t, types.captures(t)).baseType())
4656 .collect(List.collector());
4657 tree.record = record;
4658 } else {
4659 log.error(tree.pos(), Errors.DeconstructionPatternOnlyRecords(site.tsym));
4660 expectedRecordTypes = Stream.generate(() -> types.createErrorType(tree.type))
4661 .limit(tree.nested.size())
4662 .collect(List.collector());
4663 tree.record = syms.errSymbol;
4664 }
4665 ListBuffer<BindingSymbol> outBindings = new ListBuffer<>();
4666 List<Type> recordTypes = expectedRecordTypes;
4667 List<JCPattern> nestedPatterns = tree.nested;
4668 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup()));
4669 try {
4670 while (recordTypes.nonEmpty() && nestedPatterns.nonEmpty()) {
4671 attribExpr(nestedPatterns.head, localEnv, recordTypes.head);
4672 checkCastablePattern(nestedPatterns.head.pos(), recordTypes.head, nestedPatterns.head.type);
4673 outBindings.addAll(matchBindings.bindingsWhenTrue);
4674 matchBindings.bindingsWhenTrue.forEach(localEnv.info.scope::enter);
4675 nestedPatterns = nestedPatterns.tail;
4676 recordTypes = recordTypes.tail;
4677 }
4678 if (recordTypes.nonEmpty() || nestedPatterns.nonEmpty()) {
4679 while (nestedPatterns.nonEmpty()) {
4680 attribExpr(nestedPatterns.head, localEnv, Type.noType);
4681 nestedPatterns = nestedPatterns.tail;
4682 }
4683 List<Type> nestedTypes =
4684 tree.nested.stream().map(p -> p.type).collect(List.collector());
4685 log.error(tree.pos(),
4686 Errors.IncorrectNumberOfNestedPatterns(expectedRecordTypes,
4687 nestedTypes));
4688 }
4689 } finally {
4690 localEnv.info.scope.leave();
4691 }
4692 chk.validate(tree.deconstructor, env, true);
4693 result = tree.type;
4694 matchBindings = new MatchBindings(outBindings.toList(), List.nil());
4695 }
4696
4697 public void visitIndexed(JCArrayAccess tree) {
4698 Type owntype = types.createErrorType(tree.type);
4699 Type atype = attribExpr(tree.indexed, env);
4700 attribExpr(tree.index, env, syms.intType);
4701 if (types.isArray(atype))
4702 owntype = types.elemtype(atype);
4703 else if (!atype.hasTag(ERROR))
4704 log.error(tree.pos(), Errors.ArrayReqButFound(atype));
4705 if (!pkind().contains(KindSelector.VAL))
4706 owntype = capture(owntype);
4707 result = check(tree, owntype, KindSelector.VAR, resultInfo);
4708 }
4709
4710 public void visitIdent(JCIdent tree) {
4711 Symbol sym;
4712
4713 // Find symbol
4714 if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) {
4715 // If we are looking for a method, the prototype `pt' will be a
4716 // method type with the type of the call's arguments as parameters.
4717 env.info.pendingResolutionPhase = null;
4718 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments());
4719 } else if (tree.sym != null && tree.sym.kind != VAR) {
4720 sym = tree.sym;
4721 } else {
4722 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind());
4723 }
4724 tree.sym = sym;
4725
4726 // Also find the environment current for the class where
4727 // sym is defined (`symEnv').
4728 Env<AttrContext> symEnv = env;
4729 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class
4730 sym.kind.matches(KindSelector.VAL_MTH) &&
4731 sym.owner.kind == TYP &&
4732 tree.name != names._this && tree.name != names._super) {
4733
4734 // Find environment in which identifier is defined.
4735 while (symEnv.outer != null &&
4736 !sym.isMemberOf(symEnv.enclClass.sym, types)) {
4737 symEnv = symEnv.outer;
4738 }
4739 }
4740
4741 // If symbol is a variable, ...
4742 if (sym.kind == VAR) {
4743 VarSymbol v = (VarSymbol)sym;
4744
4745 // ..., evaluate its initializer, if it has one, and check for
4746 // illegal forward reference.
4747 checkInit(tree, env, v, false);
4748
4749 // If we are expecting a variable (as opposed to a value), check
4750 // that the variable is assignable in the current environment.
4751 if (KindSelector.ASG.subset(pkind()))
4752 checkAssignable(tree.pos(), v, null, env);
4753 }
4754
4755 Env<AttrContext> env1 = env;
4756 if (sym.kind != ERR && sym.kind != TYP &&
4757 sym.owner != null && sym.owner != env1.enclClass.sym) {
4758 // If the found symbol is inaccessible, then it is
4759 // accessed through an enclosing instance. Locate this
4760 // enclosing instance:
4761 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym))
4762 env1 = env1.outer;
4763 }
4764
4765 if (env.info.isSerializable) {
4766 chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4767 }
4768
4769 result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo);
4770 }
4771
4772 public void visitSelect(JCFieldAccess tree) {
4773 // Determine the expected kind of the qualifier expression.
4774 KindSelector skind = KindSelector.NIL;
4775 if (tree.name == names._this || tree.name == names._super ||
4776 tree.name == names._class)
4777 {
4778 skind = KindSelector.TYP;
4779 } else {
4780 if (pkind().contains(KindSelector.PCK))
4781 skind = KindSelector.of(skind, KindSelector.PCK);
4782 if (pkind().contains(KindSelector.TYP))
4783 skind = KindSelector.of(skind, KindSelector.TYP, KindSelector.PCK);
4784 if (pkind().contains(KindSelector.VAL_MTH))
4785 skind = KindSelector.of(skind, KindSelector.VAL, KindSelector.TYP);
4786 }
4787
4788 // Attribute the qualifier expression, and determine its symbol (if any).
4789 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Type.noType));
4790 Assert.check(site == tree.selected.type);
4791 if (!pkind().contains(KindSelector.TYP_PCK))
4792 site = capture(site); // Capture field access
4793
4794 // don't allow T.class T[].class, etc
4795 if (skind == KindSelector.TYP) {
4796 Type elt = site;
4797 while (elt.hasTag(ARRAY))
4798 elt = ((ArrayType)elt).elemtype;
4799 if (elt.hasTag(TYPEVAR)) {
4800 log.error(tree.pos(), Errors.TypeVarCantBeDeref);
4801 result = tree.type = types.createErrorType(tree.name, site.tsym, site);
4802 tree.sym = tree.type.tsym;
4803 return ;
4804 }
4805 }
4806
4807 // If qualifier symbol is a type or `super', assert `selectSuper'
4808 // for the selection. This is relevant for determining whether
4809 // protected symbols are accessible.
4810 Symbol sitesym = TreeInfo.symbol(tree.selected);
4811 boolean selectSuperPrev = env.info.selectSuper;
4812 env.info.selectSuper =
4813 sitesym != null &&
4814 sitesym.name == names._super;
4815
4816 // Determine the symbol represented by the selection.
4817 env.info.pendingResolutionPhase = null;
4818 Symbol sym = selectSym(tree, sitesym, site, env, resultInfo);
4819 if (sym.kind == VAR && sym.name != names._super && env.info.defaultSuperCallSite != null) {
4820 log.error(tree.selected.pos(), Errors.NotEnclClass(site.tsym));
4821 sym = syms.errSymbol;
4822 }
4823 if (sym.exists() && !isType(sym) && pkind().contains(KindSelector.TYP_PCK)) {
4824 site = capture(site);
4825 sym = selectSym(tree, sitesym, site, env, resultInfo);
4826 }
4827 boolean varArgs = env.info.lastResolveVarargs();
4828 tree.sym = sym;
4829
4830 if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) {
4831 site = types.skipTypeVars(site, true);
4832 }
4833
4834 // If that symbol is a variable, ...
4835 if (sym.kind == VAR) {
4836 VarSymbol v = (VarSymbol)sym;
4837
4838 // ..., evaluate its initializer, if it has one, and check for
4839 // illegal forward reference.
4840 checkInit(tree, env, v, true);
4841
4842 // If we are expecting a variable (as opposed to a value), check
4843 // that the variable is assignable in the current environment.
4844 if (KindSelector.ASG.subset(pkind()))
4845 checkAssignable(tree.pos(), v, tree.selected, env);
4846 }
4847
4848 if (sitesym != null &&
4849 sitesym.kind == VAR &&
4850 ((VarSymbol)sitesym).isResourceVariable() &&
4851 sym.kind == MTH &&
4852 sym.name.equals(names.close) &&
4853 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true)) {
4854 log.warning(tree, LintWarnings.TryExplicitCloseCall);
4855 }
4856
4857 // Disallow selecting a type from an expression
4858 if (isType(sym) && (sitesym == null || !sitesym.kind.matches(KindSelector.TYP_PCK))) {
4859 tree.type = check(tree.selected, pt(),
4860 sitesym == null ?
4861 KindSelector.VAL : sitesym.kind.toSelector(),
4862 new ResultInfo(KindSelector.TYP_PCK, pt()));
4863 }
4864
4865 if (isType(sitesym)) {
4866 if (sym.name != names._this && sym.name != names._super) {
4867 // Check if type-qualified fields or methods are static (JLS)
4868 if ((sym.flags() & STATIC) == 0 &&
4869 sym.name != names._super &&
4870 (sym.kind == VAR || sym.kind == MTH)) {
4871 rs.accessBase(rs.new StaticError(sym),
4872 tree.pos(), site, sym.name, true);
4873 }
4874 }
4875 } else if (sym.kind != ERR &&
4876 (sym.flags() & STATIC) != 0 &&
4877 sym.name != names._class) {
4878 // If the qualified item is not a type and the selected item is static, report
4879 // a warning. Make allowance for the class of an array type e.g. Object[].class)
4880 if (!sym.owner.isAnonymous()) {
4881 log.warning(tree, LintWarnings.StaticNotQualifiedByType(sym.kind.kindName(), sym.owner));
4882 } else {
4883 log.warning(tree, LintWarnings.StaticNotQualifiedByType2(sym.kind.kindName()));
4884 }
4885 }
4886
4887 // If we are selecting an instance member via a `super', ...
4888 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) {
4889
4890 // Check that super-qualified symbols are not abstract (JLS)
4891 rs.checkNonAbstract(tree.pos(), sym);
4892
4893 if (site.isRaw()) {
4894 // Determine argument types for site.
4895 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym);
4896 if (site1 != null) site = site1;
4897 }
4898 }
4899
4900 if (env.info.isSerializable) {
4901 chk.checkAccessFromSerializableElement(tree, env.info.isSerializableLambda);
4902 }
4903
4904 env.info.selectSuper = selectSuperPrev;
4905 result = checkId(tree, site, sym, env, resultInfo);
4906 }
4907 //where
4908 /** Determine symbol referenced by a Select expression,
4909 *
4910 * @param tree The select tree.
4911 * @param site The type of the selected expression,
4912 * @param env The current environment.
4913 * @param resultInfo The current result.
4914 */
4915 private Symbol selectSym(JCFieldAccess tree,
4916 Symbol location,
4917 Type site,
4918 Env<AttrContext> env,
4919 ResultInfo resultInfo) {
4920 DiagnosticPosition pos = tree.pos();
4921 Name name = tree.name;
4922 switch (site.getTag()) {
4923 case PACKAGE:
4924 return rs.accessBase(
4925 rs.findIdentInPackage(pos, env, site.tsym, name, resultInfo.pkind),
4926 pos, location, site, name, true);
4927 case ARRAY:
4928 case CLASS:
4929 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) {
4930 return rs.resolveQualifiedMethod(
4931 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments());
4932 } else if (name == names._this || name == names._super) {
4933 return rs.resolveSelf(pos, env, site.tsym, tree);
4934 } else if (name == names._class) {
4935 // In this case, we have already made sure in
4936 // visitSelect that qualifier expression is a type.
4937 return syms.getClassField(site, types);
4938 } else {
4939 // We are seeing a plain identifier as selector.
4940 Symbol sym = rs.findIdentInType(pos, env, site, name, resultInfo.pkind);
4941 sym = rs.accessBase(sym, pos, location, site, name, true);
4942 return sym;
4943 }
4944 case WILDCARD:
4945 throw new AssertionError(tree);
4946 case TYPEVAR:
4947 // Normally, site.getUpperBound() shouldn't be null.
4948 // It should only happen during memberEnter/attribBase
4949 // when determining the supertype which *must* be
4950 // done before attributing the type variables. In
4951 // other words, we are seeing this illegal program:
4952 // class B<T> extends A<T.foo> {}
4953 Symbol sym = (site.getUpperBound() != null)
4954 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo)
4955 : null;
4956 if (sym == null) {
4957 log.error(pos, Errors.TypeVarCantBeDeref);
4958 return syms.errSymbol;
4959 } else {
4960 // JLS 4.9 specifies the members are derived by inheritance.
4961 // We skip inducing a whole class by filtering members that
4962 // can never be inherited:
4963 Symbol sym2;
4964 if (sym.isPrivate()) {
4965 // Private members
4966 sym2 = rs.new AccessError(env, site, sym);
4967 } else if (sym.owner.isInterface() && sym.kind == MTH && (sym.flags() & STATIC) != 0) {
4968 // Interface static methods
4969 sym2 = rs.new SymbolNotFoundError(ABSENT_MTH);
4970 } else {
4971 sym2 = sym;
4972 }
4973 rs.accessBase(sym2, pos, location, site, name, true);
4974 return sym;
4975 }
4976 case ERROR:
4977 // preserve identifier names through errors
4978 return types.createErrorType(name, site.tsym, site).tsym;
4979 default:
4980 // The qualifier expression is of a primitive type -- only
4981 // .class is allowed for these.
4982 if (name == names._class) {
4983 // In this case, we have already made sure in Select that
4984 // qualifier expression is a type.
4985 return syms.getClassField(site, types);
4986 } else {
4987 log.error(pos, Errors.CantDeref(site));
4988 return syms.errSymbol;
4989 }
4990 }
4991 }
4992
4993 /** Determine type of identifier or select expression and check that
4994 * (1) the referenced symbol is not deprecated
4995 * (2) the symbol's type is safe (@see checkSafe)
4996 * (3) if symbol is a variable, check that its type and kind are
4997 * compatible with the prototype and protokind.
4998 * (4) if symbol is an instance field of a raw type,
4999 * which is being assigned to, issue an unchecked warning if its
5000 * type changes under erasure.
5001 * (5) if symbol is an instance method of a raw type, issue an
5002 * unchecked warning if its argument types change under erasure.
5003 * If checks succeed:
5004 * If symbol is a constant, return its constant type
5005 * else if symbol is a method, return its result type
5006 * otherwise return its type.
5007 * Otherwise return errType.
5008 *
5009 * @param tree The syntax tree representing the identifier
5010 * @param site If this is a select, the type of the selected
5011 * expression, otherwise the type of the current class.
5012 * @param sym The symbol representing the identifier.
5013 * @param env The current environment.
5014 * @param resultInfo The expected result
5015 */
5016 Type checkId(JCTree tree,
5017 Type site,
5018 Symbol sym,
5019 Env<AttrContext> env,
5020 ResultInfo resultInfo) {
5021 return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ?
5022 checkMethodIdInternal(tree, site, sym, env, resultInfo) :
5023 checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
5024 }
5025
5026 Type checkMethodIdInternal(JCTree tree,
5027 Type site,
5028 Symbol sym,
5029 Env<AttrContext> env,
5030 ResultInfo resultInfo) {
5031 if (resultInfo.pkind.contains(KindSelector.POLY)) {
5032 return attrRecover.recoverMethodInvocation(tree, site, sym, env, resultInfo);
5033 } else {
5034 return checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo);
5035 }
5036 }
5037
5038 Type checkIdInternal(JCTree tree,
5039 Type site,
5040 Symbol sym,
5041 Type pt,
5042 Env<AttrContext> env,
5043 ResultInfo resultInfo) {
5044 Type owntype; // The computed type of this identifier occurrence.
5045 switch (sym.kind) {
5046 case TYP:
5047 // For types, the computed type equals the symbol's type,
5048 // except for two situations:
5049 owntype = sym.type;
5050 if (owntype.hasTag(CLASS)) {
5051 chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym);
5052 Type ownOuter = owntype.getEnclosingType();
5053
5054 // (a) If the symbol's type is parameterized, erase it
5055 // because no type parameters were given.
5056 // We recover generic outer type later in visitTypeApply.
5057 if (owntype.tsym.type.getTypeArguments().nonEmpty()) {
5058 owntype = types.erasure(owntype);
5059 }
5060
5061 // (b) If the symbol's type is an inner class, then
5062 // we have to interpret its outer type as a superclass
5063 // of the site type. Example:
5064 //
5065 // class Tree<A> { class Visitor { ... } }
5066 // class PointTree extends Tree<Point> { ... }
5067 // ...PointTree.Visitor...
5068 //
5069 // Then the type of the last expression above is
5070 // Tree<Point>.Visitor.
5071 else if ((ownOuter.hasTag(CLASS) || ownOuter.hasTag(TYPEVAR)) && site != ownOuter) {
5072 Type normOuter = types.asEnclosingSuper(site, ownOuter.tsym);
5073 if (normOuter == null) // perhaps from an import
5074 normOuter = types.erasure(ownOuter);
5075 if (normOuter != ownOuter)
5076 owntype = new ClassType(
5077 normOuter, List.nil(), owntype.tsym,
5078 owntype.getMetadata());
5079 }
5080 }
5081 break;
5082 case VAR:
5083 VarSymbol v = (VarSymbol)sym;
5084
5085 if (env.info.enclVar != null
5086 && v.type.hasTag(NONE)) {
5087 //self reference to implicitly typed variable declaration
5088 log.error(TreeInfo.positionFor(v, env.enclClass), Errors.CantInferLocalVarType(v.name, Fragments.LocalSelfRef));
5089 return tree.type = v.type = types.createErrorType(v.type);
5090 }
5091
5092 // Test (4): if symbol is an instance field of a raw type,
5093 // which is being assigned to, issue an unchecked warning if
5094 // its type changes under erasure.
5095 if (KindSelector.ASG.subset(pkind()) &&
5096 v.owner.kind == TYP &&
5097 (v.flags() & STATIC) == 0 &&
5098 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
5099 Type s = types.asOuterSuper(site, v.owner);
5100 if (s != null &&
5101 s.isRaw() &&
5102 !types.isSameType(v.type, v.erasure(types))) {
5103 chk.warnUnchecked(tree.pos(), LintWarnings.UncheckedAssignToVar(v, s));
5104 }
5105 }
5106 // The computed type of a variable is the type of the
5107 // variable symbol, taken as a member of the site type.
5108 owntype = (sym.owner.kind == TYP &&
5109 sym.name != names._this && sym.name != names._super)
5110 ? types.memberType(site, sym)
5111 : sym.type;
5112
5113 // If the variable is a constant, record constant value in
5114 // computed type.
5115 if (v.getConstValue() != null && isStaticReference(tree))
5116 owntype = owntype.constType(v.getConstValue());
5117
5118 if (resultInfo.pkind == KindSelector.VAL) {
5119 owntype = capture(owntype); // capture "names as expressions"
5120 }
5121 break;
5122 case MTH: {
5123 owntype = checkMethod(site, sym,
5124 new ResultInfo(resultInfo.pkind, resultInfo.pt.getReturnType(), resultInfo.checkContext, resultInfo.checkMode),
5125 env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(),
5126 resultInfo.pt.getTypeArguments());
5127 chk.checkRestricted(tree.pos(), sym);
5128 break;
5129 }
5130 case PCK: case ERR:
5131 owntype = sym.type;
5132 break;
5133 default:
5134 throw new AssertionError("unexpected kind: " + sym.kind +
5135 " in tree " + tree);
5136 }
5137
5138 // Emit a `deprecation' warning if symbol is deprecated.
5139 // (for constructors (but not for constructor references), the error
5140 // was given when the constructor was resolved)
5141
5142 if (sym.name != names.init || tree.hasTag(REFERENCE)) {
5143 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym);
5144 chk.checkSunAPI(tree.pos(), sym);
5145 chk.checkProfile(tree.pos(), sym);
5146 chk.checkPreview(tree.pos(), env.info.scope.owner, site, sym);
5147 }
5148
5149 if (pt.isErroneous()) {
5150 owntype = types.createErrorType(owntype);
5151 }
5152
5153 // If symbol is a variable, check that its type and
5154 // kind are compatible with the prototype and protokind.
5155 return check(tree, owntype, sym.kind.toSelector(), resultInfo);
5156 }
5157
5158 /** Check that variable is initialized and evaluate the variable's
5159 * initializer, if not yet done. Also check that variable is not
5160 * referenced before it is defined.
5161 * @param tree The tree making up the variable reference.
5162 * @param env The current environment.
5163 * @param v The variable's symbol.
5164 */
5165 private void checkInit(JCTree tree,
5166 Env<AttrContext> env,
5167 VarSymbol v,
5168 boolean onlyWarning) {
5169 // A forward reference is diagnosed if the declaration position
5170 // of the variable is greater than the current tree position
5171 // and the tree and variable definition occur in the same class
5172 // definition. Note that writes don't count as references.
5173 // This check applies only to class and instance
5174 // variables. Local variables follow different scope rules,
5175 // and are subject to definite assignment checking.
5176 Env<AttrContext> initEnv = enclosingInitEnv(env);
5177 if (initEnv != null &&
5178 (initEnv.info.enclVar == v || v.pos > tree.pos) &&
5179 v.owner.kind == TYP &&
5180 v.owner == env.info.scope.owner.enclClass() &&
5181 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) &&
5182 (!env.tree.hasTag(ASSIGN) ||
5183 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) {
5184 if (!onlyWarning || isStaticEnumField(v)) {
5185 Error errkey = (initEnv.info.enclVar == v) ?
5186 Errors.IllegalSelfRef : Errors.IllegalForwardRef;
5187 log.error(tree.pos(), errkey);
5188 } else if (useBeforeDeclarationWarning) {
5189 Warning warnkey = (initEnv.info.enclVar == v) ?
5190 Warnings.SelfRef(v) : Warnings.ForwardRef(v);
5191 log.warning(tree.pos(), warnkey);
5192 }
5193 }
5194
5195 v.getConstValue(); // ensure initializer is evaluated
5196
5197 checkEnumInitializer(tree, env, v);
5198 }
5199
5200 /**
5201 * Returns the enclosing init environment associated with this env (if any). An init env
5202 * can be either a field declaration env or a static/instance initializer env.
5203 */
5204 Env<AttrContext> enclosingInitEnv(Env<AttrContext> env) {
5205 while (true) {
5206 switch (env.tree.getTag()) {
5207 case VARDEF:
5208 JCVariableDecl vdecl = (JCVariableDecl)env.tree;
5209 if (vdecl.sym.owner.kind == TYP) {
5210 //field
5211 return env;
5212 }
5213 break;
5214 case BLOCK:
5215 if (env.next.tree.hasTag(CLASSDEF)) {
5216 //instance/static initializer
5217 return env;
5218 }
5219 break;
5220 case METHODDEF:
5221 case CLASSDEF:
5222 case TOPLEVEL:
5223 return null;
5224 }
5225 Assert.checkNonNull(env.next);
5226 env = env.next;
5227 }
5228 }
5229
5230 /**
5231 * Check for illegal references to static members of enum. In
5232 * an enum type, constructors and initializers may not
5233 * reference its static members unless they are constant.
5234 *
5235 * @param tree The tree making up the variable reference.
5236 * @param env The current environment.
5237 * @param v The variable's symbol.
5238 * @jls 8.9 Enum Types
5239 */
5240 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) {
5241 // JLS:
5242 //
5243 // "It is a compile-time error to reference a static field
5244 // of an enum type that is not a compile-time constant
5245 // (15.28) from constructors, instance initializer blocks,
5246 // or instance variable initializer expressions of that
5247 // type. It is a compile-time error for the constructors,
5248 // instance initializer blocks, or instance variable
5249 // initializer expressions of an enum constant e to refer
5250 // to itself or to an enum constant of the same type that
5251 // is declared to the right of e."
5252 if (isStaticEnumField(v)) {
5253 ClassSymbol enclClass = env.info.scope.owner.enclClass();
5254
5255 if (enclClass == null || enclClass.owner == null)
5256 return;
5257
5258 // See if the enclosing class is the enum (or a
5259 // subclass thereof) declaring v. If not, this
5260 // reference is OK.
5261 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type))
5262 return;
5263
5264 // If the reference isn't from an initializer, then
5265 // the reference is OK.
5266 if (!Resolve.isInitializer(env))
5267 return;
5268
5269 log.error(tree.pos(), Errors.IllegalEnumStaticRef);
5270 }
5271 }
5272
5273 /** Is the given symbol a static, non-constant field of an Enum?
5274 * Note: enum literals should not be regarded as such
5275 */
5276 private boolean isStaticEnumField(VarSymbol v) {
5277 return Flags.isEnum(v.owner) &&
5278 Flags.isStatic(v) &&
5279 !Flags.isConstant(v) &&
5280 v.name != names._class;
5281 }
5282
5283 /**
5284 * Check that method arguments conform to its instantiation.
5285 **/
5286 public Type checkMethod(Type site,
5287 final Symbol sym,
5288 ResultInfo resultInfo,
5289 Env<AttrContext> env,
5290 final List<JCExpression> argtrees,
5291 List<Type> argtypes,
5292 List<Type> typeargtypes) {
5293 // Test (5): if symbol is an instance method of a raw type, issue
5294 // an unchecked warning if its argument types change under erasure.
5295 if ((sym.flags() & STATIC) == 0 &&
5296 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) {
5297 Type s = types.asOuterSuper(site, sym.owner);
5298 if (s != null && s.isRaw() &&
5299 !types.isSameTypes(sym.type.getParameterTypes(),
5300 sym.erasure(types).getParameterTypes())) {
5301 chk.warnUnchecked(env.tree.pos(), LintWarnings.UncheckedCallMbrOfRawType(sym, s));
5302 }
5303 }
5304
5305 if (env.info.defaultSuperCallSite != null) {
5306 for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) {
5307 if (!sup.tsym.isSubClass(sym.enclClass(), types) ||
5308 types.isSameType(sup, env.info.defaultSuperCallSite)) continue;
5309 List<MethodSymbol> icand_sup =
5310 types.interfaceCandidates(sup, (MethodSymbol)sym);
5311 if (icand_sup.nonEmpty() &&
5312 icand_sup.head != sym &&
5313 icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) {
5314 log.error(env.tree.pos(),
5315 Errors.IllegalDefaultSuperCall(env.info.defaultSuperCallSite, Fragments.OverriddenDefault(sym, sup)));
5316 break;
5317 }
5318 }
5319 env.info.defaultSuperCallSite = null;
5320 }
5321
5322 if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) {
5323 JCMethodInvocation app = (JCMethodInvocation)env.tree;
5324 if (app.meth.hasTag(SELECT) &&
5325 !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) {
5326 log.error(env.tree.pos(), Errors.IllegalStaticIntfMethCall(site));
5327 }
5328 }
5329
5330 // Compute the identifier's instantiated type.
5331 // For methods, we need to compute the instance type by
5332 // Resolve.instantiate from the symbol's type as well as
5333 // any type arguments and value arguments.
5334 Warner noteWarner = new Warner();
5335 try {
5336 Type owntype = rs.checkMethod(
5337 env,
5338 site,
5339 sym,
5340 resultInfo,
5341 argtypes,
5342 typeargtypes,
5343 noteWarner);
5344
5345 DeferredAttr.DeferredTypeMap<Void> checkDeferredMap =
5346 deferredAttr.new DeferredTypeMap<>(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
5347
5348 argtypes = argtypes.map(checkDeferredMap);
5349
5350 if (noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
5351 chk.warnUnchecked(env.tree.pos(), LintWarnings.UncheckedMethInvocationApplied(kindName(sym),
5352 sym.name,
5353 rs.methodArguments(sym.type.getParameterTypes()),
5354 rs.methodArguments(argtypes.map(checkDeferredMap)),
5355 kindName(sym.location()),
5356 sym.location()));
5357 if (resultInfo.pt != Infer.anyPoly ||
5358 !owntype.hasTag(METHOD) ||
5359 !owntype.isPartial()) {
5360 //if this is not a partially inferred method type, erase return type. Otherwise,
5361 //erasure is carried out in PartiallyInferredMethodType.check().
5362 owntype = new MethodType(owntype.getParameterTypes(),
5363 types.erasure(owntype.getReturnType()),
5364 types.erasure(owntype.getThrownTypes()),
5365 syms.methodClass);
5366 }
5367 }
5368
5369 PolyKind pkind = (sym.type.hasTag(FORALL) &&
5370 sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
5371 PolyKind.POLY : PolyKind.STANDALONE;
5372 TreeInfo.setPolyKind(env.tree, pkind);
5373
5374 return (resultInfo.pt == Infer.anyPoly) ?
5375 owntype :
5376 chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(),
5377 resultInfo.checkContext.inferenceContext());
5378 } catch (Infer.InferenceException ex) {
5379 //invalid target type - propagate exception outwards or report error
5380 //depending on the current check context
5381 resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic());
5382 return types.createErrorType(site);
5383 } catch (Resolve.InapplicableMethodException ex) {
5384 final JCDiagnostic diag = ex.getDiagnostic();
5385 Resolve.InapplicableSymbolError errSym = rs.new InapplicableSymbolError(null) {
5386 @Override
5387 protected Pair<Symbol, JCDiagnostic> errCandidate() {
5388 return new Pair<>(sym, diag);
5389 }
5390 };
5391 List<Type> argtypes2 = argtypes.map(
5392 rs.new ResolveDeferredRecoveryMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase));
5393 JCDiagnostic errDiag = errSym.getDiagnostic(JCDiagnostic.DiagnosticType.ERROR,
5394 env.tree, sym, site, sym.name, argtypes2, typeargtypes);
5395 log.report(errDiag);
5396 return types.createErrorType(site);
5397 }
5398 }
5399
5400 public void visitLiteral(JCLiteral tree) {
5401 result = check(tree, litType(tree.typetag).constType(tree.value),
5402 KindSelector.VAL, resultInfo);
5403 }
5404 //where
5405 /** Return the type of a literal with given type tag.
5406 */
5407 Type litType(TypeTag tag) {
5408 return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()];
5409 }
5410
5411 public void visitTypeIdent(JCPrimitiveTypeTree tree) {
5412 result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], KindSelector.TYP, resultInfo);
5413 }
5414
5415 public void visitTypeArray(JCArrayTypeTree tree) {
5416 Type etype = attribType(tree.elemtype, env);
5417 Type type = new ArrayType(etype, syms.arrayClass);
5418 result = check(tree, type, KindSelector.TYP, resultInfo);
5419 }
5420
5421 /** Visitor method for parameterized types.
5422 * Bound checking is left until later, since types are attributed
5423 * before supertype structure is completely known
5424 */
5425 public void visitTypeApply(JCTypeApply tree) {
5426 Type owntype = types.createErrorType(tree.type);
5427
5428 // Attribute functor part of application and make sure it's a class.
5429 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env));
5430
5431 // Attribute type parameters
5432 List<Type> actuals = attribTypes(tree.arguments, env);
5433
5434 if (clazztype.hasTag(CLASS)) {
5435 List<Type> formals = clazztype.tsym.type.getTypeArguments();
5436 if (actuals.isEmpty()) //diamond
5437 actuals = formals;
5438
5439 if (actuals.length() == formals.length()) {
5440 List<Type> a = actuals;
5441 List<Type> f = formals;
5442 while (a.nonEmpty()) {
5443 a.head = a.head.withTypeVar(f.head);
5444 a = a.tail;
5445 f = f.tail;
5446 }
5447 // Compute the proper generic outer
5448 Type clazzOuter = clazztype.getEnclosingType();
5449 if (clazzOuter.hasTag(CLASS)) {
5450 Type site;
5451 JCExpression clazz = TreeInfo.typeIn(tree.clazz);
5452 if (clazz.hasTag(IDENT)) {
5453 site = env.enclClass.sym.type;
5454 } else if (clazz.hasTag(SELECT)) {
5455 site = ((JCFieldAccess) clazz).selected.type;
5456 } else throw new AssertionError(""+tree);
5457 if (clazzOuter.hasTag(CLASS) && site != clazzOuter) {
5458 if (site.hasTag(CLASS) || site.hasTag(TYPEVAR))
5459 site = types.asEnclosingSuper(site, clazzOuter.tsym);
5460 if (site == null)
5461 site = types.erasure(clazzOuter);
5462 clazzOuter = site;
5463 }
5464 }
5465 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym,
5466 clazztype.getMetadata());
5467 } else {
5468 if (formals.length() != 0) {
5469 log.error(tree.pos(),
5470 Errors.WrongNumberTypeArgs(Integer.toString(formals.length())));
5471 } else {
5472 log.error(tree.pos(), Errors.TypeDoesntTakeParams(clazztype.tsym));
5473 }
5474 owntype = types.createErrorType(tree.type);
5475 }
5476 } else if (clazztype.hasTag(ERROR)) {
5477 ErrorType parameterizedErroneous =
5478 new ErrorType(clazztype.getOriginalType(),
5479 clazztype.tsym,
5480 clazztype.getMetadata());
5481
5482 parameterizedErroneous.typarams_field = actuals;
5483 owntype = parameterizedErroneous;
5484 }
5485 result = check(tree, owntype, KindSelector.TYP, resultInfo);
5486 }
5487
5488 public void visitTypeUnion(JCTypeUnion tree) {
5489 ListBuffer<Type> multicatchTypes = new ListBuffer<>();
5490 ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed
5491 for (JCExpression typeTree : tree.alternatives) {
5492 Type ctype = attribType(typeTree, env);
5493 ctype = chk.checkType(typeTree.pos(),
5494 chk.checkClassType(typeTree.pos(), ctype),
5495 syms.throwableType);
5496 if (!ctype.isErroneous()) {
5497 //check that alternatives of a union type are pairwise
5498 //unrelated w.r.t. subtyping
5499 if (chk.intersects(ctype, multicatchTypes.toList())) {
5500 for (Type t : multicatchTypes) {
5501 boolean sub = types.isSubtype(ctype, t);
5502 boolean sup = types.isSubtype(t, ctype);
5503 if (sub || sup) {
5504 //assume 'a' <: 'b'
5505 Type a = sub ? ctype : t;
5506 Type b = sub ? t : ctype;
5507 log.error(typeTree.pos(), Errors.MulticatchTypesMustBeDisjoint(a, b));
5508 }
5509 }
5510 }
5511 multicatchTypes.append(ctype);
5512 if (all_multicatchTypes != null)
5513 all_multicatchTypes.append(ctype);
5514 } else {
5515 if (all_multicatchTypes == null) {
5516 all_multicatchTypes = new ListBuffer<>();
5517 all_multicatchTypes.appendList(multicatchTypes);
5518 }
5519 all_multicatchTypes.append(ctype);
5520 }
5521 }
5522 Type t = check(tree, types.lub(multicatchTypes.toList()),
5523 KindSelector.TYP, resultInfo.dup(CheckMode.NO_TREE_UPDATE));
5524 if (t.hasTag(CLASS)) {
5525 List<Type> alternatives =
5526 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList();
5527 t = new UnionClassType((ClassType) t, alternatives);
5528 }
5529 tree.type = result = t;
5530 }
5531
5532 public void visitTypeIntersection(JCTypeIntersection tree) {
5533 attribTypes(tree.bounds, env);
5534 tree.type = result = checkIntersection(tree, tree.bounds);
5535 }
5536
5537 public void visitTypeParameter(JCTypeParameter tree) {
5538 TypeVar typeVar = (TypeVar) tree.type;
5539
5540 if (tree.annotations != null && tree.annotations.nonEmpty()) {
5541 annotate.annotateTypeParameterSecondStage(tree, tree.annotations);
5542 }
5543
5544 if (!typeVar.getUpperBound().isErroneous()) {
5545 //fixup type-parameter bound computed in 'attribTypeVariables'
5546 typeVar.setUpperBound(checkIntersection(tree, tree.bounds));
5547 }
5548 }
5549
5550 Type checkIntersection(JCTree tree, List<JCExpression> bounds) {
5551 Set<Symbol> boundSet = new HashSet<>();
5552 if (bounds.nonEmpty()) {
5553 // accept class or interface or typevar as first bound.
5554 bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false);
5555 boundSet.add(types.erasure(bounds.head.type).tsym);
5556 if (bounds.head.type.isErroneous()) {
5557 return bounds.head.type;
5558 }
5559 else if (bounds.head.type.hasTag(TYPEVAR)) {
5560 // if first bound was a typevar, do not accept further bounds.
5561 if (bounds.tail.nonEmpty()) {
5562 log.error(bounds.tail.head.pos(),
5563 Errors.TypeVarMayNotBeFollowedByOtherBounds);
5564 return bounds.head.type;
5565 }
5566 } else {
5567 // if first bound was a class or interface, accept only interfaces
5568 // as further bounds.
5569 for (JCExpression bound : bounds.tail) {
5570 bound.type = checkBase(bound.type, bound, env, false, true, false);
5571 if (bound.type.isErroneous()) {
5572 bounds = List.of(bound);
5573 }
5574 else if (bound.type.hasTag(CLASS)) {
5575 chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet);
5576 }
5577 }
5578 }
5579 }
5580
5581 if (bounds.length() == 0) {
5582 return syms.objectType;
5583 } else if (bounds.length() == 1) {
5584 return bounds.head.type;
5585 } else {
5586 Type owntype = types.makeIntersectionType(TreeInfo.types(bounds));
5587 // ... the variable's bound is a class type flagged COMPOUND
5588 // (see comment for TypeVar.bound).
5589 // In this case, generate a class tree that represents the
5590 // bound class, ...
5591 JCExpression extending;
5592 List<JCExpression> implementing;
5593 if (!bounds.head.type.isInterface()) {
5594 extending = bounds.head;
5595 implementing = bounds.tail;
5596 } else {
5597 extending = null;
5598 implementing = bounds;
5599 }
5600 JCClassDecl cd = make.at(tree).ClassDef(
5601 make.Modifiers(PUBLIC | ABSTRACT),
5602 names.empty, List.nil(),
5603 extending, implementing, List.nil());
5604
5605 ClassSymbol c = (ClassSymbol)owntype.tsym;
5606 Assert.check((c.flags() & COMPOUND) != 0);
5607 cd.sym = c;
5608 c.sourcefile = env.toplevel.sourcefile;
5609
5610 // ... and attribute the bound class
5611 c.flags_field |= UNATTRIBUTED;
5612 Env<AttrContext> cenv = enter.classEnv(cd, env);
5613 typeEnvs.put(c, cenv);
5614 attribClass(c);
5615 return owntype;
5616 }
5617 }
5618
5619 public void visitWildcard(JCWildcard tree) {
5620 //- System.err.println("visitWildcard("+tree+");");//DEBUG
5621 Type type = (tree.kind.kind == BoundKind.UNBOUND)
5622 ? syms.objectType
5623 : attribType(tree.inner, env);
5624 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type),
5625 tree.kind.kind,
5626 syms.boundClass),
5627 KindSelector.TYP, resultInfo);
5628 }
5629
5630 public void visitAnnotation(JCAnnotation tree) {
5631 Assert.error("should be handled in annotate");
5632 }
5633
5634 @Override
5635 public void visitModifiers(JCModifiers tree) {
5636 //error recovery only:
5637 Assert.check(resultInfo.pkind == KindSelector.ERR);
5638
5639 attribAnnotationTypes(tree.annotations, env);
5640 }
5641
5642 public void visitAnnotatedType(JCAnnotatedType tree) {
5643 attribAnnotationTypes(tree.annotations, env);
5644 Type underlyingType = attribType(tree.underlyingType, env);
5645 Type annotatedType = underlyingType.preannotatedType();
5646
5647 annotate.annotateTypeSecondStage(tree, tree.annotations, annotatedType);
5648 result = tree.type = annotatedType;
5649 }
5650
5651 public void visitErroneous(JCErroneous tree) {
5652 if (tree.errs != null) {
5653 WriteableScope newScope = env.info.scope;
5654
5655 if (env.tree instanceof JCClassDecl) {
5656 Symbol fakeOwner =
5657 new MethodSymbol(BLOCK, names.empty, null,
5658 env.info.scope.owner);
5659 newScope = newScope.dupUnshared(fakeOwner);
5660 }
5661
5662 Env<AttrContext> errEnv =
5663 env.dup(env.tree,
5664 env.info.dup(newScope));
5665 errEnv.info.returnResult = unknownExprInfo;
5666 for (JCTree err : tree.errs)
5667 attribTree(err, errEnv, new ResultInfo(KindSelector.ERR, pt()));
5668 }
5669 result = tree.type = syms.errType;
5670 }
5671
5672 /** Default visitor method for all other trees.
5673 */
5674 public void visitTree(JCTree tree) {
5675 throw new AssertionError();
5676 }
5677
5678 /**
5679 * Attribute an env for either a top level tree or class or module declaration.
5680 */
5681 public void attrib(Env<AttrContext> env) {
5682 switch (env.tree.getTag()) {
5683 case MODULEDEF:
5684 attribModule(env.tree.pos(), ((JCModuleDecl)env.tree).sym);
5685 break;
5686 case PACKAGEDEF:
5687 attribPackage(env.tree.pos(), ((JCPackageDecl) env.tree).packge);
5688 break;
5689 default:
5690 attribClass(env.tree.pos(), env.enclClass.sym);
5691 }
5692
5693 annotate.flush();
5694
5695 // Now that this tree is attributed, we can calculate the Lint configuration everywhere within it
5696 lintMapper.calculateLints(env.toplevel.sourcefile, env.tree, env.toplevel.endPositions);
5697 }
5698
5699 public void attribPackage(DiagnosticPosition pos, PackageSymbol p) {
5700 try {
5701 annotate.flush();
5702 attribPackage(p);
5703 } catch (CompletionFailure ex) {
5704 chk.completionError(pos, ex);
5705 }
5706 }
5707
5708 void attribPackage(PackageSymbol p) {
5709 attribWithLint(p,
5710 env -> chk.checkDeprecatedAnnotation(((JCPackageDecl) env.tree).pid.pos(), p));
5711 }
5712
5713 public void attribModule(DiagnosticPosition pos, ModuleSymbol m) {
5714 try {
5715 annotate.flush();
5716 attribModule(m);
5717 } catch (CompletionFailure ex) {
5718 chk.completionError(pos, ex);
5719 }
5720 }
5721
5722 void attribModule(ModuleSymbol m) {
5723 attribWithLint(m, env -> attribStat(env.tree, env));
5724 }
5725
5726 private void attribWithLint(TypeSymbol sym, Consumer<Env<AttrContext>> attrib) {
5727 Env<AttrContext> env = typeEnvs.get(sym);
5728
5729 Env<AttrContext> lintEnv = env;
5730 while (lintEnv.info.lint == null)
5731 lintEnv = lintEnv.next;
5732
5733 Lint lint = lintEnv.info.lint.augment(sym);
5734
5735 Lint prevLint = chk.setLint(lint);
5736 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
5737
5738 try {
5739 attrib.accept(env);
5740 } finally {
5741 log.useSource(prev);
5742 chk.setLint(prevLint);
5743 }
5744 }
5745
5746 /** Main method: attribute class definition associated with given class symbol.
5747 * reporting completion failures at the given position.
5748 * @param pos The source position at which completion errors are to be
5749 * reported.
5750 * @param c The class symbol whose definition will be attributed.
5751 */
5752 public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
5753 try {
5754 annotate.flush();
5755 attribClass(c);
5756 } catch (CompletionFailure ex) {
5757 chk.completionError(pos, ex);
5758 }
5759 }
5760
5761 /** Attribute class definition associated with given class symbol.
5762 * @param c The class symbol whose definition will be attributed.
5763 */
5764 void attribClass(ClassSymbol c) throws CompletionFailure {
5765 if (c.type.hasTag(ERROR)) return;
5766
5767 // Check for cycles in the inheritance graph, which can arise from
5768 // ill-formed class files.
5769 chk.checkNonCyclic(null, c.type);
5770
5771 Type st = types.supertype(c.type);
5772 if ((c.flags_field & Flags.COMPOUND) == 0 &&
5773 (c.flags_field & Flags.SUPER_OWNER_ATTRIBUTED) == 0) {
5774 // First, attribute superclass.
5775 if (st.hasTag(CLASS))
5776 attribClass((ClassSymbol)st.tsym);
5777
5778 // Next attribute owner, if it is a class.
5779 if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS))
5780 attribClass((ClassSymbol)c.owner);
5781
5782 c.flags_field |= Flags.SUPER_OWNER_ATTRIBUTED;
5783 }
5784
5785 // The previous operations might have attributed the current class
5786 // if there was a cycle. So we test first whether the class is still
5787 // UNATTRIBUTED.
5788 if ((c.flags_field & UNATTRIBUTED) != 0) {
5789 c.flags_field &= ~UNATTRIBUTED;
5790
5791 // Get environment current at the point of class definition.
5792 Env<AttrContext> env = typeEnvs.get(c);
5793
5794 // The info.lint field in the envs stored in typeEnvs is deliberately uninitialized,
5795 // because the annotations were not available at the time the env was created. Therefore,
5796 // we look up the environment chain for the first enclosing environment for which the
5797 // lint value is set. Typically, this is the parent env, but might be further if there
5798 // are any envs created as a result of TypeParameter nodes.
5799 Env<AttrContext> lintEnv = env;
5800 while (lintEnv.info.lint == null)
5801 lintEnv = lintEnv.next;
5802
5803 // Having found the enclosing lint value, we can initialize the lint value for this class
5804 env.info.lint = lintEnv.info.lint.augment(c);
5805
5806 Lint prevLint = chk.setLint(env.info.lint);
5807 JavaFileObject prev = log.useSource(c.sourcefile);
5808 ResultInfo prevReturnRes = env.info.returnResult;
5809
5810 try {
5811 if (c.isSealed() &&
5812 !c.isEnum() &&
5813 !c.isPermittedExplicit &&
5814 c.getPermittedSubclasses().isEmpty()) {
5815 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.SealedClassMustHaveSubclasses);
5816 }
5817
5818 if (c.isSealed()) {
5819 Set<Symbol> permittedTypes = new HashSet<>();
5820 boolean sealedInUnnamed = c.packge().modle == syms.unnamedModule || c.packge().modle == syms.noModule;
5821 for (Type subType : c.getPermittedSubclasses()) {
5822 if (subType.isErroneous()) {
5823 // the type already caused errors, don't produce more potentially misleading errors
5824 continue;
5825 }
5826 boolean isTypeVar = false;
5827 if (subType.getTag() == TYPEVAR) {
5828 isTypeVar = true; //error recovery
5829 log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5830 Errors.InvalidPermitsClause(Fragments.IsATypeVariable(subType)));
5831 }
5832 if (subType.tsym.isAnonymous() && !c.isEnum()) {
5833 log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree), Errors.LocalClassesCantExtendSealed(Fragments.Anonymous));
5834 }
5835 if (permittedTypes.contains(subType.tsym)) {
5836 DiagnosticPosition pos =
5837 env.enclClass.permitting.stream()
5838 .filter(permittedExpr -> TreeInfo.diagnosticPositionFor(subType.tsym, permittedExpr, true) != null)
5839 .limit(2).collect(List.collector()).get(1);
5840 log.error(pos, Errors.InvalidPermitsClause(Fragments.IsDuplicated(subType)));
5841 } else {
5842 permittedTypes.add(subType.tsym);
5843 }
5844 if (sealedInUnnamed) {
5845 if (subType.tsym.packge() != c.packge()) {
5846 log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5847 Errors.ClassInUnnamedModuleCantExtendSealedInDiffPackage(c)
5848 );
5849 }
5850 } else if (subType.tsym.packge().modle != c.packge().modle) {
5851 log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5852 Errors.ClassInModuleCantExtendSealedInDiffModule(c, c.packge().modle)
5853 );
5854 }
5855 if (subType.tsym == c.type.tsym || types.isSuperType(subType, c.type)) {
5856 log.error(TreeInfo.diagnosticPositionFor(subType.tsym, ((JCClassDecl)env.tree).permitting),
5857 Errors.InvalidPermitsClause(
5858 subType.tsym == c.type.tsym ?
5859 Fragments.MustNotBeSameClass :
5860 Fragments.MustNotBeSupertype(subType)
5861 )
5862 );
5863 } else if (!isTypeVar) {
5864 boolean thisIsASuper = types.directSupertypes(subType)
5865 .stream()
5866 .anyMatch(d -> d.tsym == c);
5867 if (!thisIsASuper) {
5868 if(c.isInterface()) {
5869 log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5870 Errors.InvalidPermitsClause(Fragments.DoesntImplementSealed(kindName(subType.tsym), subType)));
5871 } else {
5872 log.error(TreeInfo.diagnosticPositionFor(subType.tsym, env.tree),
5873 Errors.InvalidPermitsClause(Fragments.DoesntExtendSealed(subType)));
5874 }
5875 }
5876 }
5877 }
5878 }
5879
5880 List<ClassSymbol> sealedSupers = types.directSupertypes(c.type)
5881 .stream()
5882 .filter(s -> s.tsym.isSealed())
5883 .map(s -> (ClassSymbol) s.tsym)
5884 .collect(List.collector());
5885
5886 if (sealedSupers.isEmpty()) {
5887 if ((c.flags_field & Flags.NON_SEALED) != 0) {
5888 boolean hasErrorSuper = false;
5889
5890 hasErrorSuper |= types.directSupertypes(c.type)
5891 .stream()
5892 .anyMatch(s -> s.tsym.kind == Kind.ERR);
5893
5894 ClassType ct = (ClassType) c.type;
5895
5896 hasErrorSuper |= !ct.isCompound() && ct.interfaces_field != ct.all_interfaces_field;
5897
5898 if (!hasErrorSuper) {
5899 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.NonSealedWithNoSealedSupertype(c));
5900 }
5901 }
5902 } else if ((c.flags_field & Flags.COMPOUND) == 0) {
5903 if (c.isDirectlyOrIndirectlyLocal() && !c.isEnum()) {
5904 log.error(TreeInfo.diagnosticPositionFor(c, env.tree), Errors.LocalClassesCantExtendSealed(c.isAnonymous() ? Fragments.Anonymous : Fragments.Local));
5905 }
5906
5907 if (!c.type.isCompound()) {
5908 for (ClassSymbol supertypeSym : sealedSupers) {
5909 if (!supertypeSym.isPermittedSubclass(c.type.tsym)) {
5910 log.error(TreeInfo.diagnosticPositionFor(c.type.tsym, env.tree), Errors.CantInheritFromSealed(supertypeSym));
5911 }
5912 }
5913 if (!c.isNonSealed() && !c.isFinal() && !c.isSealed()) {
5914 log.error(TreeInfo.diagnosticPositionFor(c, env.tree),
5915 c.isInterface() ?
5916 Errors.NonSealedOrSealedExpected :
5917 Errors.NonSealedSealedOrFinalExpected);
5918 }
5919 }
5920 }
5921
5922 env.info.returnResult = null;
5923 // java.lang.Enum may not be subclassed by a non-enum
5924 if (st.tsym == syms.enumSym &&
5925 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0))
5926 log.error(env.tree.pos(), Errors.EnumNoSubclassing);
5927
5928 // Enums may not be extended by source-level classes
5929 if (st.tsym != null &&
5930 ((st.tsym.flags_field & Flags.ENUM) != 0) &&
5931 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) {
5932 log.error(env.tree.pos(), Errors.EnumTypesNotExtensible);
5933 }
5934
5935 if (rs.isSerializable(c.type)) {
5936 env.info.isSerializable = true;
5937 }
5938
5939 if (c.isValueClass()) {
5940 Assert.check(env.tree.hasTag(CLASSDEF));
5941 chk.checkConstraintsOfValueClass((JCClassDecl) env.tree, c);
5942 }
5943
5944 attribClassBody(env, c);
5945
5946 chk.checkDeprecatedAnnotation(env.tree.pos(), c);
5947 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c);
5948 chk.checkFunctionalInterface((JCClassDecl) env.tree, c);
5949 chk.checkLeaksNotAccessible(env, (JCClassDecl) env.tree);
5950
5951 if (c.isImplicit()) {
5952 chk.checkHasMain(env.tree.pos(), c);
5953 }
5954 } finally {
5955 env.info.returnResult = prevReturnRes;
5956 log.useSource(prev);
5957 chk.setLint(prevLint);
5958 }
5959
5960 }
5961 }
5962
5963 public void visitImport(JCImport tree) {
5964 // nothing to do
5965 }
5966
5967 public void visitModuleDef(JCModuleDecl tree) {
5968 tree.sym.completeUsesProvides();
5969 ModuleSymbol msym = tree.sym;
5970 Lint lint = env.outer.info.lint = env.outer.info.lint.augment(msym);
5971 Lint prevLint = chk.setLint(lint);
5972 try {
5973 chk.checkModuleName(tree);
5974 chk.checkDeprecatedAnnotation(tree, msym);
5975 } finally {
5976 chk.setLint(prevLint);
5977 }
5978 }
5979
5980 /** Finish the attribution of a class. */
5981 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) {
5982 JCClassDecl tree = (JCClassDecl)env.tree;
5983 Assert.check(c == tree.sym);
5984
5985 // Validate type parameters, supertype and interfaces.
5986 attribStats(tree.typarams, env);
5987 if (!c.isAnonymous()) {
5988 //already checked if anonymous
5989 chk.validate(tree.typarams, env);
5990 chk.validate(tree.extending, env);
5991 chk.validate(tree.implementing, env);
5992 }
5993
5994 chk.checkRequiresIdentity(tree, env.info.lint);
5995
5996 c.markAbstractIfNeeded(types);
5997
5998 // If this is a non-abstract class, check that it has no abstract
5999 // methods or unimplemented methods of an implemented interface.
6000 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) {
6001 chk.checkAllDefined(tree.pos(), c);
6002 }
6003
6004 if ((c.flags() & ANNOTATION) != 0) {
6005 if (tree.implementing.nonEmpty())
6006 log.error(tree.implementing.head.pos(),
6007 Errors.CantExtendIntfAnnotation);
6008 if (tree.typarams.nonEmpty()) {
6009 log.error(tree.typarams.head.pos(),
6010 Errors.IntfAnnotationCantHaveTypeParams(c));
6011 }
6012
6013 // If this annotation type has a @Repeatable, validate
6014 Attribute.Compound repeatable = c.getAnnotationTypeMetadata().getRepeatable();
6015 // If this annotation type has a @Repeatable, validate
6016 if (repeatable != null) {
6017 // get diagnostic position for error reporting
6018 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type);
6019 Assert.checkNonNull(cbPos);
6020
6021 chk.validateRepeatable(c, repeatable, cbPos);
6022 }
6023 } else {
6024 // Check that all extended classes and interfaces
6025 // are compatible (i.e. no two define methods with same arguments
6026 // yet different return types). (JLS 8.4.8.3)
6027 chk.checkCompatibleSupertypes(tree.pos(), c.type);
6028 chk.checkDefaultMethodClashes(tree.pos(), c.type);
6029 chk.checkPotentiallyAmbiguousOverloads(tree, c.type);
6030 }
6031
6032 // Check that class does not import the same parameterized interface
6033 // with two different argument lists.
6034 chk.checkClassBounds(tree.pos(), c.type);
6035
6036 tree.type = c.type;
6037
6038 for (List<JCTypeParameter> l = tree.typarams;
6039 l.nonEmpty(); l = l.tail) {
6040 Assert.checkNonNull(env.info.scope.findFirst(l.head.name));
6041 }
6042
6043 // Check that a generic class doesn't extend Throwable
6044 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType))
6045 log.error(tree.extending.pos(), Errors.GenericThrowable);
6046
6047 // Check that all methods which implement some
6048 // method conform to the method they implement.
6049 chk.checkImplementations(tree);
6050
6051 //check that a resource implementing AutoCloseable cannot throw InterruptedException
6052 checkAutoCloseable(env, tree, false);
6053
6054 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
6055 // Attribute declaration
6056 attribStat(l.head, env);
6057 // Check that declarations in inner classes are not static (JLS 8.1.2)
6058 // Make an exception for static constants.
6059 if (!allowRecords &&
6060 c.owner.kind != PCK &&
6061 ((c.flags() & STATIC) == 0 || c.name == names.empty) &&
6062 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) {
6063 VarSymbol sym = null;
6064 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym;
6065 if (sym == null ||
6066 sym.kind != VAR ||
6067 sym.getConstValue() == null)
6068 log.error(l.head.pos(), Errors.IclsCantHaveStaticDecl(c));
6069 }
6070 }
6071
6072 // Check for proper placement of super()/this() calls.
6073 chk.checkSuperInitCalls(tree);
6074
6075 // Check for cycles among non-initial constructors.
6076 chk.checkCyclicConstructors(tree);
6077
6078 // Check for cycles among annotation elements.
6079 chk.checkNonCyclicElements(tree);
6080
6081 // Check for proper use of serialVersionUID and other
6082 // serialization-related fields and methods
6083 if (env.info.lint.isEnabled(LintCategory.SERIAL)
6084 && rs.isSerializable(c.type)
6085 && !c.isAnonymous()) {
6086 chk.checkSerialStructure(env, tree, c);
6087 }
6088 // Correctly organize the positions of the type annotations
6089 typeAnnotations.organizeTypeAnnotationsBodies(tree);
6090
6091 // Check type annotations applicability rules
6092 validateTypeAnnotations(tree, false);
6093 }
6094 // where
6095 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */
6096 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) {
6097 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) {
6098 if (types.isSameType(al.head.annotationType.type, t))
6099 return al.head.pos();
6100 }
6101
6102 return null;
6103 }
6104
6105 private Type capture(Type type) {
6106 return types.capture(type);
6107 }
6108
6109 private void setSyntheticVariableType(JCVariableDecl tree, Type type) {
6110 if (type.isErroneous()) {
6111 tree.vartype = make.at(tree.pos()).Erroneous();
6112 } else if (tree.declaredUsingVar()) {
6113 Assert.check(tree.typePos != Position.NOPOS);
6114 tree.vartype = make.at(tree.typePos).Type(type);
6115 } else {
6116 tree.vartype = make.at(tree.pos()).Type(type);
6117 }
6118 }
6119
6120 public void validateTypeAnnotations(JCTree tree, boolean sigOnly) {
6121 tree.accept(new TypeAnnotationsValidator(sigOnly));
6122 }
6123 //where
6124 private final class TypeAnnotationsValidator extends TreeScanner {
6125
6126 private final boolean sigOnly;
6127 public TypeAnnotationsValidator(boolean sigOnly) {
6128 this.sigOnly = sigOnly;
6129 }
6130
6131 public void visitAnnotation(JCAnnotation tree) {
6132 chk.validateTypeAnnotation(tree, null, false);
6133 super.visitAnnotation(tree);
6134 }
6135 public void visitAnnotatedType(JCAnnotatedType tree) {
6136 if (!tree.underlyingType.type.isErroneous()) {
6137 super.visitAnnotatedType(tree);
6138 }
6139 }
6140 public void visitTypeParameter(JCTypeParameter tree) {
6141 chk.validateTypeAnnotations(tree.annotations, tree.type.tsym, true);
6142 scan(tree.bounds);
6143 // Don't call super.
6144 // This is needed because above we call validateTypeAnnotation with
6145 // false, which would forbid annotations on type parameters.
6146 // super.visitTypeParameter(tree);
6147 }
6148 public void visitMethodDef(JCMethodDecl tree) {
6149 if (tree.recvparam != null &&
6150 !tree.recvparam.vartype.type.isErroneous()) {
6151 checkForDeclarationAnnotations(tree.recvparam.mods.annotations, tree.recvparam.sym);
6152 }
6153 if (tree.restype != null && tree.restype.type != null) {
6154 validateAnnotatedType(tree.restype, tree.restype.type);
6155 }
6156 if (sigOnly) {
6157 scan(tree.mods);
6158 scan(tree.restype);
6159 scan(tree.typarams);
6160 scan(tree.recvparam);
6161 scan(tree.params);
6162 scan(tree.thrown);
6163 } else {
6164 scan(tree.defaultValue);
6165 scan(tree.body);
6166 }
6167 }
6168 public void visitVarDef(final JCVariableDecl tree) {
6169 //System.err.println("validateTypeAnnotations.visitVarDef " + tree);
6170 if (tree.sym != null && tree.sym.type != null && !tree.isImplicitlyTyped())
6171 validateAnnotatedType(tree.vartype, tree.sym.type);
6172 scan(tree.mods);
6173 scan(tree.vartype);
6174 if (!sigOnly) {
6175 scan(tree.init);
6176 }
6177 }
6178 public void visitTypeCast(JCTypeCast tree) {
6179 if (tree.clazz != null && tree.clazz.type != null)
6180 validateAnnotatedType(tree.clazz, tree.clazz.type);
6181 super.visitTypeCast(tree);
6182 }
6183 public void visitTypeTest(JCInstanceOf tree) {
6184 if (tree.pattern != null && !(tree.pattern instanceof JCPattern) && tree.pattern.type != null)
6185 validateAnnotatedType(tree.pattern, tree.pattern.type);
6186 super.visitTypeTest(tree);
6187 }
6188 public void visitNewClass(JCNewClass tree) {
6189 if (tree.clazz != null && tree.clazz.type != null) {
6190 if (tree.clazz.hasTag(ANNOTATED_TYPE)) {
6191 checkForDeclarationAnnotations(((JCAnnotatedType) tree.clazz).annotations,
6192 tree.clazz.type.tsym);
6193 }
6194 if (tree.def != null) {
6195 checkForDeclarationAnnotations(tree.def.mods.annotations, tree.clazz.type.tsym);
6196 }
6197
6198 validateAnnotatedType(tree.clazz, tree.clazz.type);
6199 }
6200 super.visitNewClass(tree);
6201 }
6202 public void visitNewArray(JCNewArray tree) {
6203 if (tree.elemtype != null && tree.elemtype.type != null) {
6204 if (tree.elemtype.hasTag(ANNOTATED_TYPE)) {
6205 checkForDeclarationAnnotations(((JCAnnotatedType) tree.elemtype).annotations,
6206 tree.elemtype.type.tsym);
6207 }
6208 validateAnnotatedType(tree.elemtype, tree.elemtype.type);
6209 }
6210 super.visitNewArray(tree);
6211 }
6212 public void visitClassDef(JCClassDecl tree) {
6213 //System.err.println("validateTypeAnnotations.visitClassDef " + tree);
6214 if (sigOnly) {
6215 scan(tree.mods);
6216 scan(tree.typarams);
6217 scan(tree.extending);
6218 scan(tree.implementing);
6219 }
6220 for (JCTree member : tree.defs) {
6221 if (member.hasTag(Tag.CLASSDEF)) {
6222 continue;
6223 }
6224 scan(member);
6225 }
6226 }
6227 public void visitBlock(JCBlock tree) {
6228 if (!sigOnly) {
6229 scan(tree.stats);
6230 }
6231 }
6232
6233 /* I would want to model this after
6234 * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess)
6235 * and override visitSelect and visitTypeApply.
6236 * However, we only set the annotated type in the top-level type
6237 * of the symbol.
6238 * Therefore, we need to override each individual location where a type
6239 * can occur.
6240 */
6241 private void validateAnnotatedType(final JCTree errtree, final Type type) {
6242 //System.err.println("Attr.validateAnnotatedType: " + errtree + " type: " + type);
6243
6244 if (type.isPrimitiveOrVoid()) {
6245 return;
6246 }
6247
6248 JCTree enclTr = errtree;
6249 Type enclTy = type;
6250
6251 boolean repeat = true;
6252 while (repeat) {
6253 if (enclTr.hasTag(TYPEAPPLY)) {
6254 List<Type> tyargs = enclTy.getTypeArguments();
6255 List<JCExpression> trargs = ((JCTypeApply)enclTr).getTypeArguments();
6256 if (trargs.length() > 0) {
6257 // Nothing to do for diamonds
6258 if (tyargs.length() == trargs.length()) {
6259 for (int i = 0; i < tyargs.length(); ++i) {
6260 validateAnnotatedType(trargs.get(i), tyargs.get(i));
6261 }
6262 }
6263 // If the lengths don't match, it's either a diamond
6264 // or some nested type that redundantly provides
6265 // type arguments in the tree.
6266 }
6267
6268 // Look at the clazz part of a generic type
6269 enclTr = ((JCTree.JCTypeApply)enclTr).clazz;
6270 }
6271
6272 if (enclTr.hasTag(SELECT)) {
6273 enclTr = ((JCTree.JCFieldAccess)enclTr).getExpression();
6274 if (enclTy != null &&
6275 !enclTy.hasTag(NONE)) {
6276 enclTy = enclTy.getEnclosingType();
6277 }
6278 } else if (enclTr.hasTag(ANNOTATED_TYPE)) {
6279 JCAnnotatedType at = (JCTree.JCAnnotatedType) enclTr;
6280 if (enclTy == null || enclTy.hasTag(NONE)) {
6281 ListBuffer<Attribute.TypeCompound> onlyTypeAnnotationsBuf = new ListBuffer<>();
6282 for (JCAnnotation an : at.getAnnotations()) {
6283 if (chk.isTypeAnnotation(an, false)) {
6284 onlyTypeAnnotationsBuf.add((Attribute.TypeCompound) an.attribute);
6285 }
6286 }
6287 List<Attribute.TypeCompound> onlyTypeAnnotations = onlyTypeAnnotationsBuf.toList();
6288 if (!onlyTypeAnnotations.isEmpty()) {
6289 Fragment annotationFragment = onlyTypeAnnotations.size() == 1 ?
6290 Fragments.TypeAnnotation1(onlyTypeAnnotations.head) :
6291 Fragments.TypeAnnotation(onlyTypeAnnotations);
6292 JCDiagnostic.AnnotatedType annotatedType = new JCDiagnostic.AnnotatedType(
6293 type.stripMetadata().annotatedType(onlyTypeAnnotations));
6294 log.error(at.underlyingType.pos(), Errors.TypeAnnotationInadmissible(annotationFragment,
6295 type.tsym.owner, annotatedType));
6296 }
6297 repeat = false;
6298 }
6299 enclTr = at.underlyingType;
6300 // enclTy doesn't need to be changed
6301 } else if (enclTr.hasTag(IDENT)) {
6302 repeat = false;
6303 } else if (enclTr.hasTag(JCTree.Tag.WILDCARD)) {
6304 JCWildcard wc = (JCWildcard) enclTr;
6305 if (wc.getKind() == JCTree.Kind.EXTENDS_WILDCARD ||
6306 wc.getKind() == JCTree.Kind.SUPER_WILDCARD) {
6307 validateAnnotatedType(wc.getBound(), wc.getBound().type);
6308 } else {
6309 // Nothing to do for UNBOUND
6310 }
6311 repeat = false;
6312 } else if (enclTr.hasTag(TYPEARRAY)) {
6313 JCArrayTypeTree art = (JCArrayTypeTree) enclTr;
6314 validateAnnotatedType(art.getType(), art.elemtype.type);
6315 repeat = false;
6316 } else if (enclTr.hasTag(TYPEUNION)) {
6317 JCTypeUnion ut = (JCTypeUnion) enclTr;
6318 for (JCTree t : ut.getTypeAlternatives()) {
6319 validateAnnotatedType(t, t.type);
6320 }
6321 repeat = false;
6322 } else if (enclTr.hasTag(TYPEINTERSECTION)) {
6323 JCTypeIntersection it = (JCTypeIntersection) enclTr;
6324 for (JCTree t : it.getBounds()) {
6325 validateAnnotatedType(t, t.type);
6326 }
6327 repeat = false;
6328 } else if (enclTr.getKind() == JCTree.Kind.PRIMITIVE_TYPE ||
6329 enclTr.getKind() == JCTree.Kind.ERRONEOUS) {
6330 repeat = false;
6331 } else {
6332 Assert.error("Unexpected tree: " + enclTr + " with kind: " + enclTr.getKind() +
6333 " within: "+ errtree + " with kind: " + errtree.getKind());
6334 }
6335 }
6336 }
6337
6338 private void checkForDeclarationAnnotations(List<? extends JCAnnotation> annotations,
6339 Symbol sym) {
6340 // Ensure that no declaration annotations are present.
6341 // Note that a tree type might be an AnnotatedType with
6342 // empty annotations, if only declaration annotations were given.
6343 // This method will raise an error for such a type.
6344 for (JCAnnotation ai : annotations) {
6345 if (!ai.type.isErroneous() &&
6346 typeAnnotations.annotationTargetType(ai, ai.attribute, sym) == TypeAnnotations.AnnotationType.DECLARATION) {
6347 log.error(ai.pos(), Errors.AnnotationTypeNotApplicableToType(ai.type));
6348 }
6349 }
6350 }
6351 }
6352
6353 // <editor-fold desc="post-attribution visitor">
6354
6355 /**
6356 * Handle missing types/symbols in an AST. This routine is useful when
6357 * the compiler has encountered some errors (which might have ended up
6358 * terminating attribution abruptly); if the compiler is used in fail-over
6359 * mode (e.g. by an IDE) and the AST contains semantic errors, this routine
6360 * prevents NPE to be propagated during subsequent compilation steps.
6361 */
6362 public void postAttr(JCTree tree) {
6363 new PostAttrAnalyzer().scan(tree);
6364 }
6365
6366 class PostAttrAnalyzer extends TreeScanner {
6367
6368 private void initTypeIfNeeded(JCTree that) {
6369 if (that.type == null) {
6370 if (that.hasTag(METHODDEF)) {
6371 that.type = dummyMethodType((JCMethodDecl)that);
6372 } else {
6373 that.type = syms.unknownType;
6374 }
6375 }
6376 }
6377
6378 /* Construct a dummy method type. If we have a method declaration,
6379 * and the declared return type is void, then use that return type
6380 * instead of UNKNOWN to avoid spurious error messages in lambda
6381 * bodies (see:JDK-8041704).
6382 */
6383 private Type dummyMethodType(JCMethodDecl md) {
6384 Type restype = syms.unknownType;
6385 if (md != null && md.restype != null && md.restype.hasTag(TYPEIDENT)) {
6386 JCPrimitiveTypeTree prim = (JCPrimitiveTypeTree)md.restype;
6387 if (prim.typetag == VOID)
6388 restype = syms.voidType;
6389 }
6390 return new MethodType(List.nil(), restype,
6391 List.nil(), syms.methodClass);
6392 }
6393 private Type dummyMethodType() {
6394 return dummyMethodType(null);
6395 }
6396
6397 @Override
6398 public void scan(JCTree tree) {
6399 if (tree == null) return;
6400 if (tree instanceof JCExpression) {
6401 initTypeIfNeeded(tree);
6402 }
6403 super.scan(tree);
6404 }
6405
6406 @Override
6407 public void visitIdent(JCIdent that) {
6408 if (that.sym == null) {
6409 that.sym = syms.unknownSymbol;
6410 }
6411 }
6412
6413 @Override
6414 public void visitSelect(JCFieldAccess that) {
6415 if (that.sym == null) {
6416 that.sym = syms.unknownSymbol;
6417 }
6418 super.visitSelect(that);
6419 }
6420
6421 @Override
6422 public void visitClassDef(JCClassDecl that) {
6423 initTypeIfNeeded(that);
6424 if (that.sym == null) {
6425 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol);
6426 }
6427 super.visitClassDef(that);
6428 }
6429
6430 @Override
6431 public void visitMethodDef(JCMethodDecl that) {
6432 initTypeIfNeeded(that);
6433 if (that.sym == null) {
6434 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol);
6435 }
6436 super.visitMethodDef(that);
6437 }
6438
6439 @Override
6440 public void visitVarDef(JCVariableDecl that) {
6441 initTypeIfNeeded(that);
6442 if (that.sym == null) {
6443 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol);
6444 that.sym.adr = 0;
6445 }
6446 if (that.vartype == null) {
6447 that.vartype = make.at(Position.NOPOS).Erroneous();
6448 }
6449 super.visitVarDef(that);
6450 }
6451
6452 @Override
6453 public void visitBindingPattern(JCBindingPattern that) {
6454 initTypeIfNeeded(that);
6455 initTypeIfNeeded(that.var);
6456 if (that.var.sym == null) {
6457 that.var.sym = new BindingSymbol(0, that.var.name, that.var.type, syms.noSymbol);
6458 that.var.sym.adr = 0;
6459 }
6460 super.visitBindingPattern(that);
6461 }
6462
6463 @Override
6464 public void visitRecordPattern(JCRecordPattern that) {
6465 initTypeIfNeeded(that);
6466 if (that.record == null) {
6467 that.record = new ClassSymbol(0, TreeInfo.name(that.deconstructor),
6468 that.type, syms.noSymbol);
6469 }
6470 if (that.fullComponentTypes == null) {
6471 that.fullComponentTypes = List.nil();
6472 }
6473 super.visitRecordPattern(that);
6474 }
6475
6476 @Override
6477 public void visitNewClass(JCNewClass that) {
6478 if (that.constructor == null) {
6479 that.constructor = new MethodSymbol(0, names.init,
6480 dummyMethodType(), syms.noSymbol);
6481 }
6482 if (that.constructorType == null) {
6483 that.constructorType = syms.unknownType;
6484 }
6485 super.visitNewClass(that);
6486 }
6487
6488 @Override
6489 public void visitAssignop(JCAssignOp that) {
6490 if (that.operator == null) {
6491 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
6492 -1, syms.noSymbol);
6493 }
6494 super.visitAssignop(that);
6495 }
6496
6497 @Override
6498 public void visitBinary(JCBinary that) {
6499 if (that.operator == null) {
6500 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
6501 -1, syms.noSymbol);
6502 }
6503 super.visitBinary(that);
6504 }
6505
6506 @Override
6507 public void visitUnary(JCUnary that) {
6508 if (that.operator == null) {
6509 that.operator = new OperatorSymbol(names.empty, dummyMethodType(),
6510 -1, syms.noSymbol);
6511 }
6512 super.visitUnary(that);
6513 }
6514
6515 @Override
6516 public void visitReference(JCMemberReference that) {
6517 super.visitReference(that);
6518 if (that.sym == null) {
6519 that.sym = new MethodSymbol(0, names.empty, dummyMethodType(),
6520 syms.noSymbol);
6521 }
6522 }
6523 }
6524 // </editor-fold>
6525
6526 public void setPackageSymbols(JCExpression pid, Symbol pkg) {
6527 new TreeScanner() {
6528 Symbol packge = pkg;
6529 @Override
6530 public void visitIdent(JCIdent that) {
6531 that.sym = packge;
6532 }
6533
6534 @Override
6535 public void visitSelect(JCFieldAccess that) {
6536 that.sym = packge;
6537 packge = packge.owner;
6538 super.visitSelect(that);
6539 }
6540 }.scan(pid);
6541 }
6542
6543 }
--- EOF ---