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