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