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