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