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