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