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