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