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