Wed, 15 May 2013 14:00:31 +0100
8012003: Method diagnostics resolution need to be simplified in some cases
Summary: Unfold method resolution diagnostics when they mention errors in poly expressions
Reviewed-by: jjg, vromero
1 /*
2 * Copyright (c) 1999, 2013, 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 */
26 //todo: one might eliminate uninits.andSets when monotonic
28 package com.sun.tools.javac.comp;
30 import java.util.HashMap;
32 import com.sun.tools.javac.code.*;
33 import com.sun.tools.javac.tree.*;
34 import com.sun.tools.javac.util.*;
35 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
37 import com.sun.tools.javac.code.Symbol.*;
38 import com.sun.tools.javac.tree.JCTree.*;
40 import static com.sun.tools.javac.code.Flags.*;
41 import static com.sun.tools.javac.code.Flags.BLOCK;
42 import static com.sun.tools.javac.code.Kinds.*;
43 import static com.sun.tools.javac.code.TypeTag.BOOLEAN;
44 import static com.sun.tools.javac.code.TypeTag.VOID;
45 import static com.sun.tools.javac.tree.JCTree.Tag.*;
47 /** This pass implements dataflow analysis for Java programs though
48 * different AST visitor steps. Liveness analysis (see AliveAlanyzer) checks that
49 * every statement is reachable. Exception analysis (see FlowAnalyzer) ensures that
50 * every checked exception that is thrown is declared or caught. Definite assignment analysis
51 * (see AssignAnalyzer) ensures that each variable is assigned when used. Definite
52 * unassignment analysis (see AssignAnalyzer) in ensures that no final variable
53 * is assigned more than once. Finally, local variable capture analysis (see CaptureAnalyzer)
54 * determines that local variables accessed within the scope of an inner class/lambda
55 * are either final or effectively-final.
56 *
57 * <p>The JLS has a number of problems in the
58 * specification of these flow analysis problems. This implementation
59 * attempts to address those issues.
60 *
61 * <p>First, there is no accommodation for a finally clause that cannot
62 * complete normally. For liveness analysis, an intervening finally
63 * clause can cause a break, continue, or return not to reach its
64 * target. For exception analysis, an intervening finally clause can
65 * cause any exception to be "caught". For DA/DU analysis, the finally
66 * clause can prevent a transfer of control from propagating DA/DU
67 * state to the target. In addition, code in the finally clause can
68 * affect the DA/DU status of variables.
69 *
70 * <p>For try statements, we introduce the idea of a variable being
71 * definitely unassigned "everywhere" in a block. A variable V is
72 * "unassigned everywhere" in a block iff it is unassigned at the
73 * beginning of the block and there is no reachable assignment to V
74 * in the block. An assignment V=e is reachable iff V is not DA
75 * after e. Then we can say that V is DU at the beginning of the
76 * catch block iff V is DU everywhere in the try block. Similarly, V
77 * is DU at the beginning of the finally block iff V is DU everywhere
78 * in the try block and in every catch block. Specifically, the
79 * following bullet is added to 16.2.2
80 * <pre>
81 * V is <em>unassigned everywhere</em> in a block if it is
82 * unassigned before the block and there is no reachable
83 * assignment to V within the block.
84 * </pre>
85 * <p>In 16.2.15, the third bullet (and all of its sub-bullets) for all
86 * try blocks is changed to
87 * <pre>
88 * V is definitely unassigned before a catch block iff V is
89 * definitely unassigned everywhere in the try block.
90 * </pre>
91 * <p>The last bullet (and all of its sub-bullets) for try blocks that
92 * have a finally block is changed to
93 * <pre>
94 * V is definitely unassigned before the finally block iff
95 * V is definitely unassigned everywhere in the try block
96 * and everywhere in each catch block of the try statement.
97 * </pre>
98 * <p>In addition,
99 * <pre>
100 * V is definitely assigned at the end of a constructor iff
101 * V is definitely assigned after the block that is the body
102 * of the constructor and V is definitely assigned at every
103 * return that can return from the constructor.
104 * </pre>
105 * <p>In addition, each continue statement with the loop as its target
106 * is treated as a jump to the end of the loop body, and "intervening"
107 * finally clauses are treated as follows: V is DA "due to the
108 * continue" iff V is DA before the continue statement or V is DA at
109 * the end of any intervening finally block. V is DU "due to the
110 * continue" iff any intervening finally cannot complete normally or V
111 * is DU at the end of every intervening finally block. This "due to
112 * the continue" concept is then used in the spec for the loops.
113 *
114 * <p>Similarly, break statements must consider intervening finally
115 * blocks. For liveness analysis, a break statement for which any
116 * intervening finally cannot complete normally is not considered to
117 * cause the target statement to be able to complete normally. Then
118 * we say V is DA "due to the break" iff V is DA before the break or
119 * V is DA at the end of any intervening finally block. V is DU "due
120 * to the break" iff any intervening finally cannot complete normally
121 * or V is DU at the break and at the end of every intervening
122 * finally block. (I suspect this latter condition can be
123 * simplified.) This "due to the break" is then used in the spec for
124 * all statements that can be "broken".
125 *
126 * <p>The return statement is treated similarly. V is DA "due to a
127 * return statement" iff V is DA before the return statement or V is
128 * DA at the end of any intervening finally block. Note that we
129 * don't have to worry about the return expression because this
130 * concept is only used for construcrors.
131 *
132 * <p>There is no spec in the JLS for when a variable is definitely
133 * assigned at the end of a constructor, which is needed for final
134 * fields (8.3.1.2). We implement the rule that V is DA at the end
135 * of the constructor iff it is DA and the end of the body of the
136 * constructor and V is DA "due to" every return of the constructor.
137 *
138 * <p>Intervening finally blocks similarly affect exception analysis. An
139 * intervening finally that cannot complete normally allows us to ignore
140 * an otherwise uncaught exception.
141 *
142 * <p>To implement the semantics of intervening finally clauses, all
143 * nonlocal transfers (break, continue, return, throw, method call that
144 * can throw a checked exception, and a constructor invocation that can
145 * thrown a checked exception) are recorded in a queue, and removed
146 * from the queue when we complete processing the target of the
147 * nonlocal transfer. This allows us to modify the queue in accordance
148 * with the above rules when we encounter a finally clause. The only
149 * exception to this [no pun intended] is that checked exceptions that
150 * are known to be caught or declared to be caught in the enclosing
151 * method are not recorded in the queue, but instead are recorded in a
152 * global variable "{@code Set<Type> thrown}" that records the type of all
153 * exceptions that can be thrown.
154 *
155 * <p>Other minor issues the treatment of members of other classes
156 * (always considered DA except that within an anonymous class
157 * constructor, where DA status from the enclosing scope is
158 * preserved), treatment of the case expression (V is DA before the
159 * case expression iff V is DA after the switch expression),
160 * treatment of variables declared in a switch block (the implied
161 * DA/DU status after the switch expression is DU and not DA for
162 * variables defined in a switch block), the treatment of boolean ?:
163 * expressions (The JLS rules only handle b and c non-boolean; the
164 * new rule is that if b and c are boolean valued, then V is
165 * (un)assigned after a?b:c when true/false iff V is (un)assigned
166 * after b when true/false and V is (un)assigned after c when
167 * true/false).
168 *
169 * <p>There is the remaining question of what syntactic forms constitute a
170 * reference to a variable. It is conventional to allow this.x on the
171 * left-hand-side to initialize a final instance field named x, yet
172 * this.x isn't considered a "use" when appearing on a right-hand-side
173 * in most implementations. Should parentheses affect what is
174 * considered a variable reference? The simplest rule would be to
175 * allow unqualified forms only, parentheses optional, and phase out
176 * support for assigning to a final field via this.x.
177 *
178 * <p><b>This is NOT part of any supported API.
179 * If you write code that depends on this, you do so at your own risk.
180 * This code and its internal interfaces are subject to change or
181 * deletion without notice.</b>
182 */
183 public class Flow {
184 protected static final Context.Key<Flow> flowKey =
185 new Context.Key<Flow>();
187 private final Names names;
188 private final Log log;
189 private final Symtab syms;
190 private final Types types;
191 private final Check chk;
192 private TreeMaker make;
193 private final Resolve rs;
194 private final JCDiagnostic.Factory diags;
195 private Env<AttrContext> attrEnv;
196 private Lint lint;
197 private final boolean allowImprovedRethrowAnalysis;
198 private final boolean allowImprovedCatchAnalysis;
199 private final boolean allowEffectivelyFinalInInnerClasses;
201 public static Flow instance(Context context) {
202 Flow instance = context.get(flowKey);
203 if (instance == null)
204 instance = new Flow(context);
205 return instance;
206 }
208 public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
209 new AliveAnalyzer().analyzeTree(env, make);
210 new AssignAnalyzer().analyzeTree(env, make);
211 new FlowAnalyzer().analyzeTree(env, make);
212 new CaptureAnalyzer().analyzeTree(env, make);
213 }
215 public void analyzeLambda(Env<AttrContext> env, JCLambda that, TreeMaker make, boolean speculative) {
216 Log.DiagnosticHandler diagHandler = null;
217 //we need to disable diagnostics temporarily; the problem is that if
218 //a lambda expression contains e.g. an unreachable statement, an error
219 //message will be reported and will cause compilation to skip the flow analyis
220 //step - if we suppress diagnostics, we won't stop at Attr for flow-analysis
221 //related errors, which will allow for more errors to be detected
222 if (!speculative) {
223 diagHandler = new Log.DiscardDiagnosticHandler(log);
224 }
225 try {
226 new AliveAnalyzer().analyzeTree(env, that, make);
227 new FlowAnalyzer().analyzeTree(env, that, make);
228 } finally {
229 if (!speculative) {
230 log.popDiagnosticHandler(diagHandler);
231 }
232 }
233 }
235 /**
236 * Definite assignment scan mode
237 */
238 enum FlowKind {
239 /**
240 * This is the normal DA/DU analysis mode
241 */
242 NORMAL("var.might.already.be.assigned", false),
243 /**
244 * This is the speculative DA/DU analysis mode used to speculatively
245 * derive assertions within loop bodies
246 */
247 SPECULATIVE_LOOP("var.might.be.assigned.in.loop", true);
249 final String errKey;
250 final boolean isFinal;
252 FlowKind(String errKey, boolean isFinal) {
253 this.errKey = errKey;
254 this.isFinal = isFinal;
255 }
257 boolean isFinal() {
258 return isFinal;
259 }
260 }
262 protected Flow(Context context) {
263 context.put(flowKey, this);
264 names = Names.instance(context);
265 log = Log.instance(context);
266 syms = Symtab.instance(context);
267 types = Types.instance(context);
268 chk = Check.instance(context);
269 lint = Lint.instance(context);
270 rs = Resolve.instance(context);
271 diags = JCDiagnostic.Factory.instance(context);
272 Source source = Source.instance(context);
273 allowImprovedRethrowAnalysis = source.allowImprovedRethrowAnalysis();
274 allowImprovedCatchAnalysis = source.allowImprovedCatchAnalysis();
275 allowEffectivelyFinalInInnerClasses = source.allowEffectivelyFinalInInnerClasses();
276 }
278 /**
279 * Utility method to reset several Bits instances.
280 */
281 private void resetBits(Bits... bits) {
282 for (Bits b : bits) {
283 b.reset();
284 }
285 }
287 /**
288 * Base visitor class for all visitors implementing dataflow analysis logic.
289 * This class define the shared logic for handling jumps (break/continue statements).
290 */
291 static abstract class BaseAnalyzer<P extends BaseAnalyzer.PendingExit> extends TreeScanner {
293 enum JumpKind {
294 BREAK(JCTree.Tag.BREAK) {
295 @Override
296 JCTree getTarget(JCTree tree) {
297 return ((JCBreak)tree).target;
298 }
299 },
300 CONTINUE(JCTree.Tag.CONTINUE) {
301 @Override
302 JCTree getTarget(JCTree tree) {
303 return ((JCContinue)tree).target;
304 }
305 };
307 final JCTree.Tag treeTag;
309 private JumpKind(Tag treeTag) {
310 this.treeTag = treeTag;
311 }
313 abstract JCTree getTarget(JCTree tree);
314 }
316 /** The currently pending exits that go from current inner blocks
317 * to an enclosing block, in source order.
318 */
319 ListBuffer<P> pendingExits;
321 /** A pending exit. These are the statements return, break, and
322 * continue. In addition, exception-throwing expressions or
323 * statements are put here when not known to be caught. This
324 * will typically result in an error unless it is within a
325 * try-finally whose finally block cannot complete normally.
326 */
327 static class PendingExit {
328 JCTree tree;
330 PendingExit(JCTree tree) {
331 this.tree = tree;
332 }
334 void resolveJump() {
335 //do nothing
336 }
337 }
339 abstract void markDead();
341 /** Record an outward transfer of control. */
342 void recordExit(JCTree tree, P pe) {
343 pendingExits.append(pe);
344 markDead();
345 }
347 /** Resolve all jumps of this statement. */
348 private boolean resolveJump(JCTree tree,
349 ListBuffer<P> oldPendingExits,
350 JumpKind jk) {
351 boolean resolved = false;
352 List<P> exits = pendingExits.toList();
353 pendingExits = oldPendingExits;
354 for (; exits.nonEmpty(); exits = exits.tail) {
355 P exit = exits.head;
356 if (exit.tree.hasTag(jk.treeTag) &&
357 jk.getTarget(exit.tree) == tree) {
358 exit.resolveJump();
359 resolved = true;
360 } else {
361 pendingExits.append(exit);
362 }
363 }
364 return resolved;
365 }
367 /** Resolve all breaks of this statement. */
368 boolean resolveContinues(JCTree tree) {
369 return resolveJump(tree, new ListBuffer<P>(), JumpKind.CONTINUE);
370 }
372 /** Resolve all continues of this statement. */
373 boolean resolveBreaks(JCTree tree, ListBuffer<P> oldPendingExits) {
374 return resolveJump(tree, oldPendingExits, JumpKind.BREAK);
375 }
376 }
378 /**
379 * This pass implements the first step of the dataflow analysis, namely
380 * the liveness analysis check. This checks that every statement is reachable.
381 * The output of this analysis pass are used by other analyzers. This analyzer
382 * sets the 'finallyCanCompleteNormally' field in the JCTry class.
383 */
384 class AliveAnalyzer extends BaseAnalyzer<BaseAnalyzer.PendingExit> {
386 /** A flag that indicates whether the last statement could
387 * complete normally.
388 */
389 private boolean alive;
391 @Override
392 void markDead() {
393 alive = false;
394 }
396 /*************************************************************************
397 * Visitor methods for statements and definitions
398 *************************************************************************/
400 /** Analyze a definition.
401 */
402 void scanDef(JCTree tree) {
403 scanStat(tree);
404 if (tree != null && tree.hasTag(JCTree.Tag.BLOCK) && !alive) {
405 log.error(tree.pos(),
406 "initializer.must.be.able.to.complete.normally");
407 }
408 }
410 /** Analyze a statement. Check that statement is reachable.
411 */
412 void scanStat(JCTree tree) {
413 if (!alive && tree != null) {
414 log.error(tree.pos(), "unreachable.stmt");
415 if (!tree.hasTag(SKIP)) alive = true;
416 }
417 scan(tree);
418 }
420 /** Analyze list of statements.
421 */
422 void scanStats(List<? extends JCStatement> trees) {
423 if (trees != null)
424 for (List<? extends JCStatement> l = trees; l.nonEmpty(); l = l.tail)
425 scanStat(l.head);
426 }
428 /* ------------ Visitor methods for various sorts of trees -------------*/
430 public void visitClassDef(JCClassDecl tree) {
431 if (tree.sym == null) return;
432 boolean alivePrev = alive;
433 ListBuffer<PendingExit> pendingExitsPrev = pendingExits;
434 Lint lintPrev = lint;
436 pendingExits = new ListBuffer<PendingExit>();
437 lint = lint.augment(tree.sym.annotations);
439 try {
440 // process all the static initializers
441 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
442 if (!l.head.hasTag(METHODDEF) &&
443 (TreeInfo.flags(l.head) & STATIC) != 0) {
444 scanDef(l.head);
445 }
446 }
448 // process all the instance initializers
449 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
450 if (!l.head.hasTag(METHODDEF) &&
451 (TreeInfo.flags(l.head) & STATIC) == 0) {
452 scanDef(l.head);
453 }
454 }
456 // process all the methods
457 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
458 if (l.head.hasTag(METHODDEF)) {
459 scan(l.head);
460 }
461 }
462 } finally {
463 pendingExits = pendingExitsPrev;
464 alive = alivePrev;
465 lint = lintPrev;
466 }
467 }
469 public void visitMethodDef(JCMethodDecl tree) {
470 if (tree.body == null) return;
471 Lint lintPrev = lint;
473 lint = lint.augment(tree.sym.annotations);
475 Assert.check(pendingExits.isEmpty());
477 try {
478 alive = true;
479 scanStat(tree.body);
481 if (alive && !tree.sym.type.getReturnType().hasTag(VOID))
482 log.error(TreeInfo.diagEndPos(tree.body), "missing.ret.stmt");
484 List<PendingExit> exits = pendingExits.toList();
485 pendingExits = new ListBuffer<PendingExit>();
486 while (exits.nonEmpty()) {
487 PendingExit exit = exits.head;
488 exits = exits.tail;
489 Assert.check(exit.tree.hasTag(RETURN));
490 }
491 } finally {
492 lint = lintPrev;
493 }
494 }
496 public void visitVarDef(JCVariableDecl tree) {
497 if (tree.init != null) {
498 Lint lintPrev = lint;
499 lint = lint.augment(tree.sym.annotations);
500 try{
501 scan(tree.init);
502 } finally {
503 lint = lintPrev;
504 }
505 }
506 }
508 public void visitBlock(JCBlock tree) {
509 scanStats(tree.stats);
510 }
512 public void visitDoLoop(JCDoWhileLoop tree) {
513 ListBuffer<PendingExit> prevPendingExits = pendingExits;
514 pendingExits = new ListBuffer<PendingExit>();
515 scanStat(tree.body);
516 alive |= resolveContinues(tree);
517 scan(tree.cond);
518 alive = alive && !tree.cond.type.isTrue();
519 alive |= resolveBreaks(tree, prevPendingExits);
520 }
522 public void visitWhileLoop(JCWhileLoop tree) {
523 ListBuffer<PendingExit> prevPendingExits = pendingExits;
524 pendingExits = new ListBuffer<PendingExit>();
525 scan(tree.cond);
526 alive = !tree.cond.type.isFalse();
527 scanStat(tree.body);
528 alive |= resolveContinues(tree);
529 alive = resolveBreaks(tree, prevPendingExits) ||
530 !tree.cond.type.isTrue();
531 }
533 public void visitForLoop(JCForLoop tree) {
534 ListBuffer<PendingExit> prevPendingExits = pendingExits;
535 scanStats(tree.init);
536 pendingExits = new ListBuffer<PendingExit>();
537 if (tree.cond != null) {
538 scan(tree.cond);
539 alive = !tree.cond.type.isFalse();
540 } else {
541 alive = true;
542 }
543 scanStat(tree.body);
544 alive |= resolveContinues(tree);
545 scan(tree.step);
546 alive = resolveBreaks(tree, prevPendingExits) ||
547 tree.cond != null && !tree.cond.type.isTrue();
548 }
550 public void visitForeachLoop(JCEnhancedForLoop tree) {
551 visitVarDef(tree.var);
552 ListBuffer<PendingExit> prevPendingExits = pendingExits;
553 scan(tree.expr);
554 pendingExits = new ListBuffer<PendingExit>();
555 scanStat(tree.body);
556 alive |= resolveContinues(tree);
557 resolveBreaks(tree, prevPendingExits);
558 alive = true;
559 }
561 public void visitLabelled(JCLabeledStatement tree) {
562 ListBuffer<PendingExit> prevPendingExits = pendingExits;
563 pendingExits = new ListBuffer<PendingExit>();
564 scanStat(tree.body);
565 alive |= resolveBreaks(tree, prevPendingExits);
566 }
568 public void visitSwitch(JCSwitch tree) {
569 ListBuffer<PendingExit> prevPendingExits = pendingExits;
570 pendingExits = new ListBuffer<PendingExit>();
571 scan(tree.selector);
572 boolean hasDefault = false;
573 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
574 alive = true;
575 JCCase c = l.head;
576 if (c.pat == null)
577 hasDefault = true;
578 else
579 scan(c.pat);
580 scanStats(c.stats);
581 // Warn about fall-through if lint switch fallthrough enabled.
582 if (alive &&
583 lint.isEnabled(Lint.LintCategory.FALLTHROUGH) &&
584 c.stats.nonEmpty() && l.tail.nonEmpty())
585 log.warning(Lint.LintCategory.FALLTHROUGH,
586 l.tail.head.pos(),
587 "possible.fall-through.into.case");
588 }
589 if (!hasDefault) {
590 alive = true;
591 }
592 alive |= resolveBreaks(tree, prevPendingExits);
593 }
595 public void visitTry(JCTry tree) {
596 ListBuffer<PendingExit> prevPendingExits = pendingExits;
597 pendingExits = new ListBuffer<PendingExit>();
598 for (JCTree resource : tree.resources) {
599 if (resource instanceof JCVariableDecl) {
600 JCVariableDecl vdecl = (JCVariableDecl) resource;
601 visitVarDef(vdecl);
602 } else if (resource instanceof JCExpression) {
603 scan((JCExpression) resource);
604 } else {
605 throw new AssertionError(tree); // parser error
606 }
607 }
609 scanStat(tree.body);
610 boolean aliveEnd = alive;
612 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
613 alive = true;
614 JCVariableDecl param = l.head.param;
615 scan(param);
616 scanStat(l.head.body);
617 aliveEnd |= alive;
618 }
619 if (tree.finalizer != null) {
620 ListBuffer<PendingExit> exits = pendingExits;
621 pendingExits = prevPendingExits;
622 alive = true;
623 scanStat(tree.finalizer);
624 tree.finallyCanCompleteNormally = alive;
625 if (!alive) {
626 if (lint.isEnabled(Lint.LintCategory.FINALLY)) {
627 log.warning(Lint.LintCategory.FINALLY,
628 TreeInfo.diagEndPos(tree.finalizer),
629 "finally.cannot.complete");
630 }
631 } else {
632 while (exits.nonEmpty()) {
633 pendingExits.append(exits.next());
634 }
635 alive = aliveEnd;
636 }
637 } else {
638 alive = aliveEnd;
639 ListBuffer<PendingExit> exits = pendingExits;
640 pendingExits = prevPendingExits;
641 while (exits.nonEmpty()) pendingExits.append(exits.next());
642 }
643 }
645 @Override
646 public void visitIf(JCIf tree) {
647 scan(tree.cond);
648 scanStat(tree.thenpart);
649 if (tree.elsepart != null) {
650 boolean aliveAfterThen = alive;
651 alive = true;
652 scanStat(tree.elsepart);
653 alive = alive | aliveAfterThen;
654 } else {
655 alive = true;
656 }
657 }
659 public void visitBreak(JCBreak tree) {
660 recordExit(tree, new PendingExit(tree));
661 }
663 public void visitContinue(JCContinue tree) {
664 recordExit(tree, new PendingExit(tree));
665 }
667 public void visitReturn(JCReturn tree) {
668 scan(tree.expr);
669 recordExit(tree, new PendingExit(tree));
670 }
672 public void visitThrow(JCThrow tree) {
673 scan(tree.expr);
674 markDead();
675 }
677 public void visitApply(JCMethodInvocation tree) {
678 scan(tree.meth);
679 scan(tree.args);
680 }
682 public void visitNewClass(JCNewClass tree) {
683 scan(tree.encl);
684 scan(tree.args);
685 if (tree.def != null) {
686 scan(tree.def);
687 }
688 }
690 @Override
691 public void visitLambda(JCLambda tree) {
692 if (tree.type != null &&
693 tree.type.isErroneous()) {
694 return;
695 }
697 ListBuffer<PendingExit> prevPending = pendingExits;
698 boolean prevAlive = alive;
699 try {
700 pendingExits = ListBuffer.lb();
701 alive = true;
702 scanStat(tree.body);
703 tree.canCompleteNormally = alive;
704 }
705 finally {
706 pendingExits = prevPending;
707 alive = prevAlive;
708 }
709 }
711 public void visitTopLevel(JCCompilationUnit tree) {
712 // Do nothing for TopLevel since each class is visited individually
713 }
715 /**************************************************************************
716 * main method
717 *************************************************************************/
719 /** Perform definite assignment/unassignment analysis on a tree.
720 */
721 public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
722 analyzeTree(env, env.tree, make);
723 }
724 public void analyzeTree(Env<AttrContext> env, JCTree tree, TreeMaker make) {
725 try {
726 attrEnv = env;
727 Flow.this.make = make;
728 pendingExits = new ListBuffer<PendingExit>();
729 alive = true;
730 scan(tree);
731 } finally {
732 pendingExits = null;
733 Flow.this.make = null;
734 }
735 }
736 }
738 /**
739 * This pass implements the second step of the dataflow analysis, namely
740 * the exception analysis. This is to ensure that every checked exception that is
741 * thrown is declared or caught. The analyzer uses some info that has been set by
742 * the liveliness analyzer.
743 */
744 class FlowAnalyzer extends BaseAnalyzer<FlowAnalyzer.FlowPendingExit> {
746 /** A flag that indicates whether the last statement could
747 * complete normally.
748 */
749 HashMap<Symbol, List<Type>> preciseRethrowTypes;
751 /** The current class being defined.
752 */
753 JCClassDecl classDef;
755 /** The list of possibly thrown declarable exceptions.
756 */
757 List<Type> thrown;
759 /** The list of exceptions that are either caught or declared to be
760 * thrown.
761 */
762 List<Type> caught;
764 class FlowPendingExit extends BaseAnalyzer.PendingExit {
766 Type thrown;
768 FlowPendingExit(JCTree tree, Type thrown) {
769 super(tree);
770 this.thrown = thrown;
771 }
772 }
774 @Override
775 void markDead() {
776 //do nothing
777 }
779 /*-------------------- Exceptions ----------------------*/
781 /** Complain that pending exceptions are not caught.
782 */
783 void errorUncaught() {
784 for (FlowPendingExit exit = pendingExits.next();
785 exit != null;
786 exit = pendingExits.next()) {
787 if (classDef != null &&
788 classDef.pos == exit.tree.pos) {
789 log.error(exit.tree.pos(),
790 "unreported.exception.default.constructor",
791 exit.thrown);
792 } else if (exit.tree.hasTag(VARDEF) &&
793 ((JCVariableDecl)exit.tree).sym.isResourceVariable()) {
794 log.error(exit.tree.pos(),
795 "unreported.exception.implicit.close",
796 exit.thrown,
797 ((JCVariableDecl)exit.tree).sym.name);
798 } else {
799 log.error(exit.tree.pos(),
800 "unreported.exception.need.to.catch.or.throw",
801 exit.thrown);
802 }
803 }
804 }
806 /** Record that exception is potentially thrown and check that it
807 * is caught.
808 */
809 void markThrown(JCTree tree, Type exc) {
810 if (!chk.isUnchecked(tree.pos(), exc)) {
811 if (!chk.isHandled(exc, caught))
812 pendingExits.append(new FlowPendingExit(tree, exc));
813 thrown = chk.incl(exc, thrown);
814 }
815 }
817 /*************************************************************************
818 * Visitor methods for statements and definitions
819 *************************************************************************/
821 /* ------------ Visitor methods for various sorts of trees -------------*/
823 public void visitClassDef(JCClassDecl tree) {
824 if (tree.sym == null) return;
826 JCClassDecl classDefPrev = classDef;
827 List<Type> thrownPrev = thrown;
828 List<Type> caughtPrev = caught;
829 ListBuffer<FlowPendingExit> pendingExitsPrev = pendingExits;
830 Lint lintPrev = lint;
832 pendingExits = new ListBuffer<FlowPendingExit>();
833 if (tree.name != names.empty) {
834 caught = List.nil();
835 }
836 classDef = tree;
837 thrown = List.nil();
838 lint = lint.augment(tree.sym.annotations);
840 try {
841 // process all the static initializers
842 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
843 if (!l.head.hasTag(METHODDEF) &&
844 (TreeInfo.flags(l.head) & STATIC) != 0) {
845 scan(l.head);
846 errorUncaught();
847 }
848 }
850 // add intersection of all thrown clauses of initial constructors
851 // to set of caught exceptions, unless class is anonymous.
852 if (tree.name != names.empty) {
853 boolean firstConstructor = true;
854 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
855 if (TreeInfo.isInitialConstructor(l.head)) {
856 List<Type> mthrown =
857 ((JCMethodDecl) l.head).sym.type.getThrownTypes();
858 if (firstConstructor) {
859 caught = mthrown;
860 firstConstructor = false;
861 } else {
862 caught = chk.intersect(mthrown, caught);
863 }
864 }
865 }
866 }
868 // process all the instance initializers
869 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
870 if (!l.head.hasTag(METHODDEF) &&
871 (TreeInfo.flags(l.head) & STATIC) == 0) {
872 scan(l.head);
873 errorUncaught();
874 }
875 }
877 // in an anonymous class, add the set of thrown exceptions to
878 // the throws clause of the synthetic constructor and propagate
879 // outwards.
880 // Changing the throws clause on the fly is okay here because
881 // the anonymous constructor can't be invoked anywhere else,
882 // and its type hasn't been cached.
883 if (tree.name == names.empty) {
884 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
885 if (TreeInfo.isInitialConstructor(l.head)) {
886 JCMethodDecl mdef = (JCMethodDecl)l.head;
887 mdef.thrown = make.Types(thrown);
888 mdef.sym.type = types.createMethodTypeWithThrown(mdef.sym.type, thrown);
889 }
890 }
891 thrownPrev = chk.union(thrown, thrownPrev);
892 }
894 // process all the methods
895 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
896 if (l.head.hasTag(METHODDEF)) {
897 scan(l.head);
898 errorUncaught();
899 }
900 }
902 thrown = thrownPrev;
903 } finally {
904 pendingExits = pendingExitsPrev;
905 caught = caughtPrev;
906 classDef = classDefPrev;
907 lint = lintPrev;
908 }
909 }
911 public void visitMethodDef(JCMethodDecl tree) {
912 if (tree.body == null) return;
914 List<Type> caughtPrev = caught;
915 List<Type> mthrown = tree.sym.type.getThrownTypes();
916 Lint lintPrev = lint;
918 lint = lint.augment(tree.sym.annotations);
920 Assert.check(pendingExits.isEmpty());
922 try {
923 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
924 JCVariableDecl def = l.head;
925 scan(def);
926 }
927 if (TreeInfo.isInitialConstructor(tree))
928 caught = chk.union(caught, mthrown);
929 else if ((tree.sym.flags() & (BLOCK | STATIC)) != BLOCK)
930 caught = mthrown;
931 // else we are in an instance initializer block;
932 // leave caught unchanged.
934 scan(tree.body);
936 List<FlowPendingExit> exits = pendingExits.toList();
937 pendingExits = new ListBuffer<FlowPendingExit>();
938 while (exits.nonEmpty()) {
939 FlowPendingExit exit = exits.head;
940 exits = exits.tail;
941 if (exit.thrown == null) {
942 Assert.check(exit.tree.hasTag(RETURN));
943 } else {
944 // uncaught throws will be reported later
945 pendingExits.append(exit);
946 }
947 }
948 } finally {
949 caught = caughtPrev;
950 lint = lintPrev;
951 }
952 }
954 public void visitVarDef(JCVariableDecl tree) {
955 if (tree.init != null) {
956 Lint lintPrev = lint;
957 lint = lint.augment(tree.sym.annotations);
958 try{
959 scan(tree.init);
960 } finally {
961 lint = lintPrev;
962 }
963 }
964 }
966 public void visitBlock(JCBlock tree) {
967 scan(tree.stats);
968 }
970 public void visitDoLoop(JCDoWhileLoop tree) {
971 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
972 pendingExits = new ListBuffer<FlowPendingExit>();
973 scan(tree.body);
974 resolveContinues(tree);
975 scan(tree.cond);
976 resolveBreaks(tree, prevPendingExits);
977 }
979 public void visitWhileLoop(JCWhileLoop tree) {
980 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
981 pendingExits = new ListBuffer<FlowPendingExit>();
982 scan(tree.cond);
983 scan(tree.body);
984 resolveContinues(tree);
985 resolveBreaks(tree, prevPendingExits);
986 }
988 public void visitForLoop(JCForLoop tree) {
989 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
990 scan(tree.init);
991 pendingExits = new ListBuffer<FlowPendingExit>();
992 if (tree.cond != null) {
993 scan(tree.cond);
994 }
995 scan(tree.body);
996 resolveContinues(tree);
997 scan(tree.step);
998 resolveBreaks(tree, prevPendingExits);
999 }
1001 public void visitForeachLoop(JCEnhancedForLoop tree) {
1002 visitVarDef(tree.var);
1003 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
1004 scan(tree.expr);
1005 pendingExits = new ListBuffer<FlowPendingExit>();
1006 scan(tree.body);
1007 resolveContinues(tree);
1008 resolveBreaks(tree, prevPendingExits);
1009 }
1011 public void visitLabelled(JCLabeledStatement tree) {
1012 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
1013 pendingExits = new ListBuffer<FlowPendingExit>();
1014 scan(tree.body);
1015 resolveBreaks(tree, prevPendingExits);
1016 }
1018 public void visitSwitch(JCSwitch tree) {
1019 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
1020 pendingExits = new ListBuffer<FlowPendingExit>();
1021 scan(tree.selector);
1022 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
1023 JCCase c = l.head;
1024 if (c.pat != null) {
1025 scan(c.pat);
1026 }
1027 scan(c.stats);
1028 }
1029 resolveBreaks(tree, prevPendingExits);
1030 }
1032 public void visitTry(JCTry tree) {
1033 List<Type> caughtPrev = caught;
1034 List<Type> thrownPrev = thrown;
1035 thrown = List.nil();
1036 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1037 List<JCExpression> subClauses = TreeInfo.isMultiCatch(l.head) ?
1038 ((JCTypeUnion)l.head.param.vartype).alternatives :
1039 List.of(l.head.param.vartype);
1040 for (JCExpression ct : subClauses) {
1041 caught = chk.incl(ct.type, caught);
1042 }
1043 }
1045 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
1046 pendingExits = new ListBuffer<FlowPendingExit>();
1047 for (JCTree resource : tree.resources) {
1048 if (resource instanceof JCVariableDecl) {
1049 JCVariableDecl vdecl = (JCVariableDecl) resource;
1050 visitVarDef(vdecl);
1051 } else if (resource instanceof JCExpression) {
1052 scan((JCExpression) resource);
1053 } else {
1054 throw new AssertionError(tree); // parser error
1055 }
1056 }
1057 for (JCTree resource : tree.resources) {
1058 List<Type> closeableSupertypes = resource.type.isCompound() ?
1059 types.interfaces(resource.type).prepend(types.supertype(resource.type)) :
1060 List.of(resource.type);
1061 for (Type sup : closeableSupertypes) {
1062 if (types.asSuper(sup, syms.autoCloseableType.tsym) != null) {
1063 Symbol closeMethod = rs.resolveQualifiedMethod(tree,
1064 attrEnv,
1065 sup,
1066 names.close,
1067 List.<Type>nil(),
1068 List.<Type>nil());
1069 if (closeMethod.kind == MTH) {
1070 for (Type t : ((MethodSymbol)closeMethod).getThrownTypes()) {
1071 markThrown(resource, t);
1072 }
1073 }
1074 }
1075 }
1076 }
1077 scan(tree.body);
1078 List<Type> thrownInTry = allowImprovedCatchAnalysis ?
1079 chk.union(thrown, List.of(syms.runtimeExceptionType, syms.errorType)) :
1080 thrown;
1081 thrown = thrownPrev;
1082 caught = caughtPrev;
1084 List<Type> caughtInTry = List.nil();
1085 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1086 JCVariableDecl param = l.head.param;
1087 List<JCExpression> subClauses = TreeInfo.isMultiCatch(l.head) ?
1088 ((JCTypeUnion)l.head.param.vartype).alternatives :
1089 List.of(l.head.param.vartype);
1090 List<Type> ctypes = List.nil();
1091 List<Type> rethrownTypes = chk.diff(thrownInTry, caughtInTry);
1092 for (JCExpression ct : subClauses) {
1093 Type exc = ct.type;
1094 if (exc != syms.unknownType) {
1095 ctypes = ctypes.append(exc);
1096 if (types.isSameType(exc, syms.objectType))
1097 continue;
1098 checkCaughtType(l.head.pos(), exc, thrownInTry, caughtInTry);
1099 caughtInTry = chk.incl(exc, caughtInTry);
1100 }
1101 }
1102 scan(param);
1103 preciseRethrowTypes.put(param.sym, chk.intersect(ctypes, rethrownTypes));
1104 scan(l.head.body);
1105 preciseRethrowTypes.remove(param.sym);
1106 }
1107 if (tree.finalizer != null) {
1108 List<Type> savedThrown = thrown;
1109 thrown = List.nil();
1110 ListBuffer<FlowPendingExit> exits = pendingExits;
1111 pendingExits = prevPendingExits;
1112 scan(tree.finalizer);
1113 if (!tree.finallyCanCompleteNormally) {
1114 // discard exits and exceptions from try and finally
1115 thrown = chk.union(thrown, thrownPrev);
1116 } else {
1117 thrown = chk.union(thrown, chk.diff(thrownInTry, caughtInTry));
1118 thrown = chk.union(thrown, savedThrown);
1119 // FIX: this doesn't preserve source order of exits in catch
1120 // versus finally!
1121 while (exits.nonEmpty()) {
1122 pendingExits.append(exits.next());
1123 }
1124 }
1125 } else {
1126 thrown = chk.union(thrown, chk.diff(thrownInTry, caughtInTry));
1127 ListBuffer<FlowPendingExit> exits = pendingExits;
1128 pendingExits = prevPendingExits;
1129 while (exits.nonEmpty()) pendingExits.append(exits.next());
1130 }
1131 }
1133 @Override
1134 public void visitIf(JCIf tree) {
1135 scan(tree.cond);
1136 scan(tree.thenpart);
1137 if (tree.elsepart != null) {
1138 scan(tree.elsepart);
1139 }
1140 }
1142 void checkCaughtType(DiagnosticPosition pos, Type exc, List<Type> thrownInTry, List<Type> caughtInTry) {
1143 if (chk.subset(exc, caughtInTry)) {
1144 log.error(pos, "except.already.caught", exc);
1145 } else if (!chk.isUnchecked(pos, exc) &&
1146 !isExceptionOrThrowable(exc) &&
1147 !chk.intersects(exc, thrownInTry)) {
1148 log.error(pos, "except.never.thrown.in.try", exc);
1149 } else if (allowImprovedCatchAnalysis) {
1150 List<Type> catchableThrownTypes = chk.intersect(List.of(exc), thrownInTry);
1151 // 'catchableThrownTypes' cannnot possibly be empty - if 'exc' was an
1152 // unchecked exception, the result list would not be empty, as the augmented
1153 // thrown set includes { RuntimeException, Error }; if 'exc' was a checked
1154 // exception, that would have been covered in the branch above
1155 if (chk.diff(catchableThrownTypes, caughtInTry).isEmpty() &&
1156 !isExceptionOrThrowable(exc)) {
1157 String key = catchableThrownTypes.length() == 1 ?
1158 "unreachable.catch" :
1159 "unreachable.catch.1";
1160 log.warning(pos, key, catchableThrownTypes);
1161 }
1162 }
1163 }
1164 //where
1165 private boolean isExceptionOrThrowable(Type exc) {
1166 return exc.tsym == syms.throwableType.tsym ||
1167 exc.tsym == syms.exceptionType.tsym;
1168 }
1170 public void visitBreak(JCBreak tree) {
1171 recordExit(tree, new FlowPendingExit(tree, null));
1172 }
1174 public void visitContinue(JCContinue tree) {
1175 recordExit(tree, new FlowPendingExit(tree, null));
1176 }
1178 public void visitReturn(JCReturn tree) {
1179 scan(tree.expr);
1180 recordExit(tree, new FlowPendingExit(tree, null));
1181 }
1183 public void visitThrow(JCThrow tree) {
1184 scan(tree.expr);
1185 Symbol sym = TreeInfo.symbol(tree.expr);
1186 if (sym != null &&
1187 sym.kind == VAR &&
1188 (sym.flags() & (FINAL | EFFECTIVELY_FINAL)) != 0 &&
1189 preciseRethrowTypes.get(sym) != null &&
1190 allowImprovedRethrowAnalysis) {
1191 for (Type t : preciseRethrowTypes.get(sym)) {
1192 markThrown(tree, t);
1193 }
1194 }
1195 else {
1196 markThrown(tree, tree.expr.type);
1197 }
1198 markDead();
1199 }
1201 public void visitApply(JCMethodInvocation tree) {
1202 scan(tree.meth);
1203 scan(tree.args);
1204 for (List<Type> l = tree.meth.type.getThrownTypes(); l.nonEmpty(); l = l.tail)
1205 markThrown(tree, l.head);
1206 }
1208 public void visitNewClass(JCNewClass tree) {
1209 scan(tree.encl);
1210 scan(tree.args);
1211 // scan(tree.def);
1212 for (List<Type> l = tree.constructorType.getThrownTypes();
1213 l.nonEmpty();
1214 l = l.tail) {
1215 markThrown(tree, l.head);
1216 }
1217 List<Type> caughtPrev = caught;
1218 try {
1219 // If the new class expression defines an anonymous class,
1220 // analysis of the anonymous constructor may encounter thrown
1221 // types which are unsubstituted type variables.
1222 // However, since the constructor's actual thrown types have
1223 // already been marked as thrown, it is safe to simply include
1224 // each of the constructor's formal thrown types in the set of
1225 // 'caught/declared to be thrown' types, for the duration of
1226 // the class def analysis.
1227 if (tree.def != null)
1228 for (List<Type> l = tree.constructor.type.getThrownTypes();
1229 l.nonEmpty();
1230 l = l.tail) {
1231 caught = chk.incl(l.head, caught);
1232 }
1233 scan(tree.def);
1234 }
1235 finally {
1236 caught = caughtPrev;
1237 }
1238 }
1240 @Override
1241 public void visitLambda(JCLambda tree) {
1242 if (tree.type != null &&
1243 tree.type.isErroneous()) {
1244 return;
1245 }
1246 List<Type> prevCaught = caught;
1247 List<Type> prevThrown = thrown;
1248 ListBuffer<FlowPendingExit> prevPending = pendingExits;
1249 try {
1250 pendingExits = ListBuffer.lb();
1251 caught = List.of(syms.throwableType); //inhibit exception checking
1252 thrown = List.nil();
1253 scan(tree.body);
1254 tree.inferredThrownTypes = thrown;
1255 }
1256 finally {
1257 pendingExits = prevPending;
1258 caught = prevCaught;
1259 thrown = prevThrown;
1260 }
1261 }
1263 public void visitTopLevel(JCCompilationUnit tree) {
1264 // Do nothing for TopLevel since each class is visited individually
1265 }
1267 /**************************************************************************
1268 * main method
1269 *************************************************************************/
1271 /** Perform definite assignment/unassignment analysis on a tree.
1272 */
1273 public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
1274 analyzeTree(env, env.tree, make);
1275 }
1276 public void analyzeTree(Env<AttrContext> env, JCTree tree, TreeMaker make) {
1277 try {
1278 attrEnv = env;
1279 Flow.this.make = make;
1280 pendingExits = new ListBuffer<FlowPendingExit>();
1281 preciseRethrowTypes = new HashMap<Symbol, List<Type>>();
1282 this.thrown = this.caught = null;
1283 this.classDef = null;
1284 scan(tree);
1285 } finally {
1286 pendingExits = null;
1287 Flow.this.make = null;
1288 this.thrown = this.caught = null;
1289 this.classDef = null;
1290 }
1291 }
1292 }
1294 /**
1295 * This pass implements (i) definite assignment analysis, which ensures that
1296 * each variable is assigned when used and (ii) definite unassignment analysis,
1297 * which ensures that no final variable is assigned more than once. This visitor
1298 * depends on the results of the liveliness analyzer. This pass is also used to mark
1299 * effectively-final local variables/parameters.
1300 */
1301 class AssignAnalyzer extends BaseAnalyzer<AssignAnalyzer.AssignPendingExit> {
1303 /** The set of definitely assigned variables.
1304 */
1305 final Bits inits;
1307 /** The set of definitely unassigned variables.
1308 */
1309 final Bits uninits;
1311 /** The set of variables that are definitely unassigned everywhere
1312 * in current try block. This variable is maintained lazily; it is
1313 * updated only when something gets removed from uninits,
1314 * typically by being assigned in reachable code. To obtain the
1315 * correct set of variables which are definitely unassigned
1316 * anywhere in current try block, intersect uninitsTry and
1317 * uninits.
1318 */
1319 final Bits uninitsTry;
1321 /** When analyzing a condition, inits and uninits are null.
1322 * Instead we have:
1323 */
1324 final Bits initsWhenTrue;
1325 final Bits initsWhenFalse;
1326 final Bits uninitsWhenTrue;
1327 final Bits uninitsWhenFalse;
1329 /** A mapping from addresses to variable symbols.
1330 */
1331 VarSymbol[] vars;
1333 /** The current class being defined.
1334 */
1335 JCClassDecl classDef;
1337 /** The first variable sequence number in this class definition.
1338 */
1339 int firstadr;
1341 /** The next available variable sequence number.
1342 */
1343 int nextadr;
1345 /** The first variable sequence number in a block that can return.
1346 */
1347 int returnadr;
1349 /** The list of unreferenced automatic resources.
1350 */
1351 Scope unrefdResources;
1353 /** Set when processing a loop body the second time for DU analysis. */
1354 FlowKind flowKind = FlowKind.NORMAL;
1356 /** The starting position of the analysed tree */
1357 int startPos;
1359 AssignAnalyzer() {
1360 inits = new Bits();
1361 uninits = new Bits();
1362 uninitsTry = new Bits();
1363 initsWhenTrue = new Bits(true);
1364 initsWhenFalse = new Bits(true);
1365 uninitsWhenTrue = new Bits(true);
1366 uninitsWhenFalse = new Bits(true);
1367 }
1369 class AssignPendingExit extends BaseAnalyzer.PendingExit {
1371 final Bits exit_inits = new Bits(true);
1372 final Bits exit_uninits = new Bits(true);
1374 AssignPendingExit(JCTree tree, final Bits inits, final Bits uninits) {
1375 super(tree);
1376 this.exit_inits.assign(inits);
1377 this.exit_uninits.assign(uninits);
1378 }
1380 void resolveJump() {
1381 inits.andSet(exit_inits);
1382 uninits.andSet(exit_uninits);
1383 }
1384 }
1386 @Override
1387 void markDead() {
1388 inits.inclRange(returnadr, nextadr);
1389 uninits.inclRange(returnadr, nextadr);
1390 }
1392 /*-------------- Processing variables ----------------------*/
1394 /** Do we need to track init/uninit state of this symbol?
1395 * I.e. is symbol either a local or a blank final variable?
1396 */
1397 boolean trackable(VarSymbol sym) {
1398 return
1399 sym.pos >= startPos &&
1400 ((sym.owner.kind == MTH ||
1401 ((sym.flags() & (FINAL | HASINIT | PARAMETER)) == FINAL &&
1402 classDef.sym.isEnclosedBy((ClassSymbol)sym.owner))));
1403 }
1405 /** Initialize new trackable variable by setting its address field
1406 * to the next available sequence number and entering it under that
1407 * index into the vars array.
1408 */
1409 void newVar(VarSymbol sym) {
1410 vars = ArrayUtils.ensureCapacity(vars, nextadr);
1411 if ((sym.flags() & FINAL) == 0) {
1412 sym.flags_field |= EFFECTIVELY_FINAL;
1413 }
1414 sym.adr = nextadr;
1415 vars[nextadr] = sym;
1416 inits.excl(nextadr);
1417 uninits.incl(nextadr);
1418 nextadr++;
1419 }
1421 /** Record an initialization of a trackable variable.
1422 */
1423 void letInit(DiagnosticPosition pos, VarSymbol sym) {
1424 if (sym.adr >= firstadr && trackable(sym)) {
1425 if ((sym.flags() & EFFECTIVELY_FINAL) != 0) {
1426 if (!uninits.isMember(sym.adr)) {
1427 //assignment targeting an effectively final variable
1428 //makes the variable lose its status of effectively final
1429 //if the variable is _not_ definitively unassigned
1430 sym.flags_field &= ~EFFECTIVELY_FINAL;
1431 } else {
1432 uninit(sym);
1433 }
1434 }
1435 else if ((sym.flags() & FINAL) != 0) {
1436 if ((sym.flags() & PARAMETER) != 0) {
1437 if ((sym.flags() & UNION) != 0) { //multi-catch parameter
1438 log.error(pos, "multicatch.parameter.may.not.be.assigned",
1439 sym);
1440 }
1441 else {
1442 log.error(pos, "final.parameter.may.not.be.assigned",
1443 sym);
1444 }
1445 } else if (!uninits.isMember(sym.adr)) {
1446 log.error(pos, flowKind.errKey, sym);
1447 } else {
1448 uninit(sym);
1449 }
1450 }
1451 inits.incl(sym.adr);
1452 } else if ((sym.flags() & FINAL) != 0) {
1453 log.error(pos, "var.might.already.be.assigned", sym);
1454 }
1455 }
1456 //where
1457 void uninit(VarSymbol sym) {
1458 if (!inits.isMember(sym.adr)) {
1459 // reachable assignment
1460 uninits.excl(sym.adr);
1461 uninitsTry.excl(sym.adr);
1462 } else {
1463 //log.rawWarning(pos, "unreachable assignment");//DEBUG
1464 uninits.excl(sym.adr);
1465 }
1466 }
1468 /** If tree is either a simple name or of the form this.name or
1469 * C.this.name, and tree represents a trackable variable,
1470 * record an initialization of the variable.
1471 */
1472 void letInit(JCTree tree) {
1473 tree = TreeInfo.skipParens(tree);
1474 if (tree.hasTag(IDENT) || tree.hasTag(SELECT)) {
1475 Symbol sym = TreeInfo.symbol(tree);
1476 if (sym.kind == VAR) {
1477 letInit(tree.pos(), (VarSymbol)sym);
1478 }
1479 }
1480 }
1482 /** Check that trackable variable is initialized.
1483 */
1484 void checkInit(DiagnosticPosition pos, VarSymbol sym) {
1485 if ((sym.adr >= firstadr || sym.owner.kind != TYP) &&
1486 trackable(sym) &&
1487 !inits.isMember(sym.adr)) {
1488 log.error(pos, "var.might.not.have.been.initialized",
1489 sym);
1490 inits.incl(sym.adr);
1491 }
1492 }
1494 /** Split (duplicate) inits/uninits into WhenTrue/WhenFalse sets
1495 */
1496 void split(boolean setToNull) {
1497 initsWhenFalse.assign(inits);
1498 uninitsWhenFalse.assign(uninits);
1499 initsWhenTrue.assign(inits);
1500 uninitsWhenTrue.assign(uninits);
1501 if (setToNull) {
1502 resetBits(inits, uninits);
1503 }
1504 }
1506 /** Merge (intersect) inits/uninits from WhenTrue/WhenFalse sets.
1507 */
1508 void merge() {
1509 inits.assign(initsWhenFalse.andSet(initsWhenTrue));
1510 uninits.assign(uninitsWhenFalse.andSet(uninitsWhenTrue));
1511 }
1513 /* ************************************************************************
1514 * Visitor methods for statements and definitions
1515 *************************************************************************/
1517 /** Analyze an expression. Make sure to set (un)inits rather than
1518 * (un)initsWhenTrue(WhenFalse) on exit.
1519 */
1520 void scanExpr(JCTree tree) {
1521 if (tree != null) {
1522 scan(tree);
1523 if (inits.isReset()) merge();
1524 }
1525 }
1527 /** Analyze a list of expressions.
1528 */
1529 void scanExprs(List<? extends JCExpression> trees) {
1530 if (trees != null)
1531 for (List<? extends JCExpression> l = trees; l.nonEmpty(); l = l.tail)
1532 scanExpr(l.head);
1533 }
1535 /** Analyze a condition. Make sure to set (un)initsWhenTrue(WhenFalse)
1536 * rather than (un)inits on exit.
1537 */
1538 void scanCond(JCTree tree) {
1539 if (tree.type.isFalse()) {
1540 if (inits.isReset()) merge();
1541 initsWhenTrue.assign(inits);
1542 initsWhenTrue.inclRange(firstadr, nextadr);
1543 uninitsWhenTrue.assign(uninits);
1544 uninitsWhenTrue.inclRange(firstadr, nextadr);
1545 initsWhenFalse.assign(inits);
1546 uninitsWhenFalse.assign(uninits);
1547 } else if (tree.type.isTrue()) {
1548 if (inits.isReset()) merge();
1549 initsWhenFalse.assign(inits);
1550 initsWhenFalse.inclRange(firstadr, nextadr);
1551 uninitsWhenFalse.assign(uninits);
1552 uninitsWhenFalse.inclRange(firstadr, nextadr);
1553 initsWhenTrue.assign(inits);
1554 uninitsWhenTrue.assign(uninits);
1555 } else {
1556 scan(tree);
1557 if (!inits.isReset())
1558 split(tree.type != syms.unknownType);
1559 }
1560 if (tree.type != syms.unknownType) {
1561 resetBits(inits, uninits);
1562 }
1563 }
1565 /* ------------ Visitor methods for various sorts of trees -------------*/
1567 public void visitClassDef(JCClassDecl tree) {
1568 if (tree.sym == null) return;
1570 JCClassDecl classDefPrev = classDef;
1571 int firstadrPrev = firstadr;
1572 int nextadrPrev = nextadr;
1573 ListBuffer<AssignPendingExit> pendingExitsPrev = pendingExits;
1574 Lint lintPrev = lint;
1576 pendingExits = new ListBuffer<AssignPendingExit>();
1577 if (tree.name != names.empty) {
1578 firstadr = nextadr;
1579 }
1580 classDef = tree;
1581 lint = lint.augment(tree.sym.annotations);
1583 try {
1584 // define all the static fields
1585 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1586 if (l.head.hasTag(VARDEF)) {
1587 JCVariableDecl def = (JCVariableDecl)l.head;
1588 if ((def.mods.flags & STATIC) != 0) {
1589 VarSymbol sym = def.sym;
1590 if (trackable(sym))
1591 newVar(sym);
1592 }
1593 }
1594 }
1596 // process all the static initializers
1597 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1598 if (!l.head.hasTag(METHODDEF) &&
1599 (TreeInfo.flags(l.head) & STATIC) != 0) {
1600 scan(l.head);
1601 }
1602 }
1604 // define all the instance fields
1605 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1606 if (l.head.hasTag(VARDEF)) {
1607 JCVariableDecl def = (JCVariableDecl)l.head;
1608 if ((def.mods.flags & STATIC) == 0) {
1609 VarSymbol sym = def.sym;
1610 if (trackable(sym))
1611 newVar(sym);
1612 }
1613 }
1614 }
1616 // process all the instance initializers
1617 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1618 if (!l.head.hasTag(METHODDEF) &&
1619 (TreeInfo.flags(l.head) & STATIC) == 0) {
1620 scan(l.head);
1621 }
1622 }
1624 // process all the methods
1625 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1626 if (l.head.hasTag(METHODDEF)) {
1627 scan(l.head);
1628 }
1629 }
1630 } finally {
1631 pendingExits = pendingExitsPrev;
1632 nextadr = nextadrPrev;
1633 firstadr = firstadrPrev;
1634 classDef = classDefPrev;
1635 lint = lintPrev;
1636 }
1637 }
1639 public void visitMethodDef(JCMethodDecl tree) {
1640 if (tree.body == null) return;
1642 final Bits initsPrev = new Bits(inits);
1643 final Bits uninitsPrev = new Bits(uninits);
1644 int nextadrPrev = nextadr;
1645 int firstadrPrev = firstadr;
1646 int returnadrPrev = returnadr;
1647 Lint lintPrev = lint;
1649 lint = lint.augment(tree.sym.annotations);
1651 Assert.check(pendingExits.isEmpty());
1653 try {
1654 boolean isInitialConstructor =
1655 TreeInfo.isInitialConstructor(tree);
1657 if (!isInitialConstructor)
1658 firstadr = nextadr;
1659 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1660 JCVariableDecl def = l.head;
1661 scan(def);
1662 inits.incl(def.sym.adr);
1663 uninits.excl(def.sym.adr);
1664 }
1665 // else we are in an instance initializer block;
1666 // leave caught unchanged.
1667 scan(tree.body);
1669 if (isInitialConstructor) {
1670 for (int i = firstadr; i < nextadr; i++)
1671 if (vars[i].owner == classDef.sym)
1672 checkInit(TreeInfo.diagEndPos(tree.body), vars[i]);
1673 }
1674 List<AssignPendingExit> exits = pendingExits.toList();
1675 pendingExits = new ListBuffer<AssignPendingExit>();
1676 while (exits.nonEmpty()) {
1677 AssignPendingExit exit = exits.head;
1678 exits = exits.tail;
1679 Assert.check(exit.tree.hasTag(RETURN), exit.tree);
1680 if (isInitialConstructor) {
1681 inits.assign(exit.exit_inits);
1682 for (int i = firstadr; i < nextadr; i++)
1683 checkInit(exit.tree.pos(), vars[i]);
1684 }
1685 }
1686 } finally {
1687 inits.assign(initsPrev);
1688 uninits.assign(uninitsPrev);
1689 nextadr = nextadrPrev;
1690 firstadr = firstadrPrev;
1691 returnadr = returnadrPrev;
1692 lint = lintPrev;
1693 }
1694 }
1696 public void visitVarDef(JCVariableDecl tree) {
1697 boolean track = trackable(tree.sym);
1698 if (track && tree.sym.owner.kind == MTH) newVar(tree.sym);
1699 if (tree.init != null) {
1700 Lint lintPrev = lint;
1701 lint = lint.augment(tree.sym.annotations);
1702 try{
1703 scanExpr(tree.init);
1704 if (track) letInit(tree.pos(), tree.sym);
1705 } finally {
1706 lint = lintPrev;
1707 }
1708 }
1709 }
1711 public void visitBlock(JCBlock tree) {
1712 int nextadrPrev = nextadr;
1713 scan(tree.stats);
1714 nextadr = nextadrPrev;
1715 }
1717 public void visitDoLoop(JCDoWhileLoop tree) {
1718 ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
1719 FlowKind prevFlowKind = flowKind;
1720 flowKind = FlowKind.NORMAL;
1721 final Bits initsSkip = new Bits(true);
1722 final Bits uninitsSkip = new Bits(true);
1723 pendingExits = new ListBuffer<AssignPendingExit>();
1724 int prevErrors = log.nerrors;
1725 do {
1726 final Bits uninitsEntry = new Bits(uninits);
1727 uninitsEntry.excludeFrom(nextadr);
1728 scan(tree.body);
1729 resolveContinues(tree);
1730 scanCond(tree.cond);
1731 if (!flowKind.isFinal()) {
1732 initsSkip.assign(initsWhenFalse);
1733 uninitsSkip.assign(uninitsWhenFalse);
1734 }
1735 if (log.nerrors != prevErrors ||
1736 flowKind.isFinal() ||
1737 new Bits(uninitsEntry).diffSet(uninitsWhenTrue).nextBit(firstadr)==-1)
1738 break;
1739 inits.assign(initsWhenTrue);
1740 uninits.assign(uninitsEntry.andSet(uninitsWhenTrue));
1741 flowKind = FlowKind.SPECULATIVE_LOOP;
1742 } while (true);
1743 flowKind = prevFlowKind;
1744 inits.assign(initsSkip);
1745 uninits.assign(uninitsSkip);
1746 resolveBreaks(tree, prevPendingExits);
1747 }
1749 public void visitWhileLoop(JCWhileLoop tree) {
1750 ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
1751 FlowKind prevFlowKind = flowKind;
1752 flowKind = FlowKind.NORMAL;
1753 final Bits initsSkip = new Bits(true);
1754 final Bits uninitsSkip = new Bits(true);
1755 pendingExits = new ListBuffer<AssignPendingExit>();
1756 int prevErrors = log.nerrors;
1757 final Bits uninitsEntry = new Bits(uninits);
1758 uninitsEntry.excludeFrom(nextadr);
1759 do {
1760 scanCond(tree.cond);
1761 if (!flowKind.isFinal()) {
1762 initsSkip.assign(initsWhenFalse) ;
1763 uninitsSkip.assign(uninitsWhenFalse);
1764 }
1765 inits.assign(initsWhenTrue);
1766 uninits.assign(uninitsWhenTrue);
1767 scan(tree.body);
1768 resolveContinues(tree);
1769 if (log.nerrors != prevErrors ||
1770 flowKind.isFinal() ||
1771 new Bits(uninitsEntry).diffSet(uninits).nextBit(firstadr) == -1)
1772 break;
1773 uninits.assign(uninitsEntry.andSet(uninits));
1774 flowKind = FlowKind.SPECULATIVE_LOOP;
1775 } while (true);
1776 flowKind = prevFlowKind;
1777 //a variable is DA/DU after the while statement, if it's DA/DU assuming the
1778 //branch is not taken AND if it's DA/DU before any break statement
1779 inits.assign(initsSkip);
1780 uninits.assign(uninitsSkip);
1781 resolveBreaks(tree, prevPendingExits);
1782 }
1784 public void visitForLoop(JCForLoop tree) {
1785 ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
1786 FlowKind prevFlowKind = flowKind;
1787 flowKind = FlowKind.NORMAL;
1788 int nextadrPrev = nextadr;
1789 scan(tree.init);
1790 final Bits initsSkip = new Bits(true);
1791 final Bits uninitsSkip = new Bits(true);
1792 pendingExits = new ListBuffer<AssignPendingExit>();
1793 int prevErrors = log.nerrors;
1794 do {
1795 final Bits uninitsEntry = new Bits(uninits);
1796 uninitsEntry.excludeFrom(nextadr);
1797 if (tree.cond != null) {
1798 scanCond(tree.cond);
1799 if (!flowKind.isFinal()) {
1800 initsSkip.assign(initsWhenFalse);
1801 uninitsSkip.assign(uninitsWhenFalse);
1802 }
1803 inits.assign(initsWhenTrue);
1804 uninits.assign(uninitsWhenTrue);
1805 } else if (!flowKind.isFinal()) {
1806 initsSkip.assign(inits);
1807 initsSkip.inclRange(firstadr, nextadr);
1808 uninitsSkip.assign(uninits);
1809 uninitsSkip.inclRange(firstadr, nextadr);
1810 }
1811 scan(tree.body);
1812 resolveContinues(tree);
1813 scan(tree.step);
1814 if (log.nerrors != prevErrors ||
1815 flowKind.isFinal() ||
1816 new Bits(uninitsEntry).diffSet(uninits).nextBit(firstadr) == -1)
1817 break;
1818 uninits.assign(uninitsEntry.andSet(uninits));
1819 flowKind = FlowKind.SPECULATIVE_LOOP;
1820 } while (true);
1821 flowKind = prevFlowKind;
1822 //a variable is DA/DU after a for loop, if it's DA/DU assuming the
1823 //branch is not taken AND if it's DA/DU before any break statement
1824 inits.assign(initsSkip);
1825 uninits.assign(uninitsSkip);
1826 resolveBreaks(tree, prevPendingExits);
1827 nextadr = nextadrPrev;
1828 }
1830 public void visitForeachLoop(JCEnhancedForLoop tree) {
1831 visitVarDef(tree.var);
1833 ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
1834 FlowKind prevFlowKind = flowKind;
1835 flowKind = FlowKind.NORMAL;
1836 int nextadrPrev = nextadr;
1837 scan(tree.expr);
1838 final Bits initsStart = new Bits(inits);
1839 final Bits uninitsStart = new Bits(uninits);
1841 letInit(tree.pos(), tree.var.sym);
1842 pendingExits = new ListBuffer<AssignPendingExit>();
1843 int prevErrors = log.nerrors;
1844 do {
1845 final Bits uninitsEntry = new Bits(uninits);
1846 uninitsEntry.excludeFrom(nextadr);
1847 scan(tree.body);
1848 resolveContinues(tree);
1849 if (log.nerrors != prevErrors ||
1850 flowKind.isFinal() ||
1851 new Bits(uninitsEntry).diffSet(uninits).nextBit(firstadr) == -1)
1852 break;
1853 uninits.assign(uninitsEntry.andSet(uninits));
1854 flowKind = FlowKind.SPECULATIVE_LOOP;
1855 } while (true);
1856 flowKind = prevFlowKind;
1857 inits.assign(initsStart);
1858 uninits.assign(uninitsStart.andSet(uninits));
1859 resolveBreaks(tree, prevPendingExits);
1860 nextadr = nextadrPrev;
1861 }
1863 public void visitLabelled(JCLabeledStatement tree) {
1864 ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
1865 pendingExits = new ListBuffer<AssignPendingExit>();
1866 scan(tree.body);
1867 resolveBreaks(tree, prevPendingExits);
1868 }
1870 public void visitSwitch(JCSwitch tree) {
1871 ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
1872 pendingExits = new ListBuffer<AssignPendingExit>();
1873 int nextadrPrev = nextadr;
1874 scanExpr(tree.selector);
1875 final Bits initsSwitch = new Bits(inits);
1876 final Bits uninitsSwitch = new Bits(uninits);
1877 boolean hasDefault = false;
1878 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
1879 inits.assign(initsSwitch);
1880 uninits.assign(uninits.andSet(uninitsSwitch));
1881 JCCase c = l.head;
1882 if (c.pat == null)
1883 hasDefault = true;
1884 else
1885 scanExpr(c.pat);
1886 scan(c.stats);
1887 addVars(c.stats, initsSwitch, uninitsSwitch);
1888 // Warn about fall-through if lint switch fallthrough enabled.
1889 }
1890 if (!hasDefault) {
1891 inits.andSet(initsSwitch);
1892 }
1893 resolveBreaks(tree, prevPendingExits);
1894 nextadr = nextadrPrev;
1895 }
1896 // where
1897 /** Add any variables defined in stats to inits and uninits. */
1898 private void addVars(List<JCStatement> stats, final Bits inits,
1899 final Bits uninits) {
1900 for (;stats.nonEmpty(); stats = stats.tail) {
1901 JCTree stat = stats.head;
1902 if (stat.hasTag(VARDEF)) {
1903 int adr = ((JCVariableDecl) stat).sym.adr;
1904 inits.excl(adr);
1905 uninits.incl(adr);
1906 }
1907 }
1908 }
1910 public void visitTry(JCTry tree) {
1911 ListBuffer<JCVariableDecl> resourceVarDecls = ListBuffer.lb();
1912 final Bits uninitsTryPrev = new Bits(uninitsTry);
1913 ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
1914 pendingExits = new ListBuffer<AssignPendingExit>();
1915 final Bits initsTry = new Bits(inits);
1916 uninitsTry.assign(uninits);
1917 for (JCTree resource : tree.resources) {
1918 if (resource instanceof JCVariableDecl) {
1919 JCVariableDecl vdecl = (JCVariableDecl) resource;
1920 visitVarDef(vdecl);
1921 unrefdResources.enter(vdecl.sym);
1922 resourceVarDecls.append(vdecl);
1923 } else if (resource instanceof JCExpression) {
1924 scanExpr((JCExpression) resource);
1925 } else {
1926 throw new AssertionError(tree); // parser error
1927 }
1928 }
1929 scan(tree.body);
1930 uninitsTry.andSet(uninits);
1931 final Bits initsEnd = new Bits(inits);
1932 final Bits uninitsEnd = new Bits(uninits);
1933 int nextadrCatch = nextadr;
1935 if (!resourceVarDecls.isEmpty() &&
1936 lint.isEnabled(Lint.LintCategory.TRY)) {
1937 for (JCVariableDecl resVar : resourceVarDecls) {
1938 if (unrefdResources.includes(resVar.sym)) {
1939 log.warning(Lint.LintCategory.TRY, resVar.pos(),
1940 "try.resource.not.referenced", resVar.sym);
1941 unrefdResources.remove(resVar.sym);
1942 }
1943 }
1944 }
1946 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1947 JCVariableDecl param = l.head.param;
1948 inits.assign(initsTry);
1949 uninits.assign(uninitsTry);
1950 scan(param);
1951 inits.incl(param.sym.adr);
1952 uninits.excl(param.sym.adr);
1953 scan(l.head.body);
1954 initsEnd.andSet(inits);
1955 uninitsEnd.andSet(uninits);
1956 nextadr = nextadrCatch;
1957 }
1958 if (tree.finalizer != null) {
1959 inits.assign(initsTry);
1960 uninits.assign(uninitsTry);
1961 ListBuffer<AssignPendingExit> exits = pendingExits;
1962 pendingExits = prevPendingExits;
1963 scan(tree.finalizer);
1964 if (!tree.finallyCanCompleteNormally) {
1965 // discard exits and exceptions from try and finally
1966 } else {
1967 uninits.andSet(uninitsEnd);
1968 // FIX: this doesn't preserve source order of exits in catch
1969 // versus finally!
1970 while (exits.nonEmpty()) {
1971 AssignPendingExit exit = exits.next();
1972 if (exit.exit_inits != null) {
1973 exit.exit_inits.orSet(inits);
1974 exit.exit_uninits.andSet(uninits);
1975 }
1976 pendingExits.append(exit);
1977 }
1978 inits.orSet(initsEnd);
1979 }
1980 } else {
1981 inits.assign(initsEnd);
1982 uninits.assign(uninitsEnd);
1983 ListBuffer<AssignPendingExit> exits = pendingExits;
1984 pendingExits = prevPendingExits;
1985 while (exits.nonEmpty()) pendingExits.append(exits.next());
1986 }
1987 uninitsTry.andSet(uninitsTryPrev).andSet(uninits);
1988 }
1990 public void visitConditional(JCConditional tree) {
1991 scanCond(tree.cond);
1992 final Bits initsBeforeElse = new Bits(initsWhenFalse);
1993 final Bits uninitsBeforeElse = new Bits(uninitsWhenFalse);
1994 inits.assign(initsWhenTrue);
1995 uninits.assign(uninitsWhenTrue);
1996 if (tree.truepart.type.hasTag(BOOLEAN) &&
1997 tree.falsepart.type.hasTag(BOOLEAN)) {
1998 // if b and c are boolean valued, then
1999 // v is (un)assigned after a?b:c when true iff
2000 // v is (un)assigned after b when true and
2001 // v is (un)assigned after c when true
2002 scanCond(tree.truepart);
2003 final Bits initsAfterThenWhenTrue = new Bits(initsWhenTrue);
2004 final Bits initsAfterThenWhenFalse = new Bits(initsWhenFalse);
2005 final Bits uninitsAfterThenWhenTrue = new Bits(uninitsWhenTrue);
2006 final Bits uninitsAfterThenWhenFalse = new Bits(uninitsWhenFalse);
2007 inits.assign(initsBeforeElse);
2008 uninits.assign(uninitsBeforeElse);
2009 scanCond(tree.falsepart);
2010 initsWhenTrue.andSet(initsAfterThenWhenTrue);
2011 initsWhenFalse.andSet(initsAfterThenWhenFalse);
2012 uninitsWhenTrue.andSet(uninitsAfterThenWhenTrue);
2013 uninitsWhenFalse.andSet(uninitsAfterThenWhenFalse);
2014 } else {
2015 scanExpr(tree.truepart);
2016 final Bits initsAfterThen = new Bits(inits);
2017 final Bits uninitsAfterThen = new Bits(uninits);
2018 inits.assign(initsBeforeElse);
2019 uninits.assign(uninitsBeforeElse);
2020 scanExpr(tree.falsepart);
2021 inits.andSet(initsAfterThen);
2022 uninits.andSet(uninitsAfterThen);
2023 }
2024 }
2026 public void visitIf(JCIf tree) {
2027 scanCond(tree.cond);
2028 final Bits initsBeforeElse = new Bits(initsWhenFalse);
2029 final Bits uninitsBeforeElse = new Bits(uninitsWhenFalse);
2030 inits.assign(initsWhenTrue);
2031 uninits.assign(uninitsWhenTrue);
2032 scan(tree.thenpart);
2033 if (tree.elsepart != null) {
2034 final Bits initsAfterThen = new Bits(inits);
2035 final Bits uninitsAfterThen = new Bits(uninits);
2036 inits.assign(initsBeforeElse);
2037 uninits.assign(uninitsBeforeElse);
2038 scan(tree.elsepart);
2039 inits.andSet(initsAfterThen);
2040 uninits.andSet(uninitsAfterThen);
2041 } else {
2042 inits.andSet(initsBeforeElse);
2043 uninits.andSet(uninitsBeforeElse);
2044 }
2045 }
2047 public void visitBreak(JCBreak tree) {
2048 recordExit(tree, new AssignPendingExit(tree, inits, uninits));
2049 }
2051 public void visitContinue(JCContinue tree) {
2052 recordExit(tree, new AssignPendingExit(tree, inits, uninits));
2053 }
2055 public void visitReturn(JCReturn tree) {
2056 scanExpr(tree.expr);
2057 recordExit(tree, new AssignPendingExit(tree, inits, uninits));
2058 }
2060 public void visitThrow(JCThrow tree) {
2061 scanExpr(tree.expr);
2062 markDead();
2063 }
2065 public void visitApply(JCMethodInvocation tree) {
2066 scanExpr(tree.meth);
2067 scanExprs(tree.args);
2068 }
2070 public void visitNewClass(JCNewClass tree) {
2071 scanExpr(tree.encl);
2072 scanExprs(tree.args);
2073 scan(tree.def);
2074 }
2076 @Override
2077 public void visitLambda(JCLambda tree) {
2078 final Bits prevUninits = new Bits(uninits);
2079 final Bits prevInits = new Bits(inits);
2080 int returnadrPrev = returnadr;
2081 ListBuffer<AssignPendingExit> prevPending = pendingExits;
2082 try {
2083 returnadr = nextadr;
2084 pendingExits = new ListBuffer<AssignPendingExit>();
2085 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
2086 JCVariableDecl def = l.head;
2087 scan(def);
2088 inits.incl(def.sym.adr);
2089 uninits.excl(def.sym.adr);
2090 }
2091 if (tree.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
2092 scanExpr(tree.body);
2093 } else {
2094 scan(tree.body);
2095 }
2096 }
2097 finally {
2098 returnadr = returnadrPrev;
2099 uninits.assign(prevUninits);
2100 inits.assign(prevInits);
2101 pendingExits = prevPending;
2102 }
2103 }
2105 public void visitNewArray(JCNewArray tree) {
2106 scanExprs(tree.dims);
2107 scanExprs(tree.elems);
2108 }
2110 public void visitAssert(JCAssert tree) {
2111 final Bits initsExit = new Bits(inits);
2112 final Bits uninitsExit = new Bits(uninits);
2113 scanCond(tree.cond);
2114 uninitsExit.andSet(uninitsWhenTrue);
2115 if (tree.detail != null) {
2116 inits.assign(initsWhenFalse);
2117 uninits.assign(uninitsWhenFalse);
2118 scanExpr(tree.detail);
2119 }
2120 inits.assign(initsExit);
2121 uninits.assign(uninitsExit);
2122 }
2124 public void visitAssign(JCAssign tree) {
2125 JCTree lhs = TreeInfo.skipParens(tree.lhs);
2126 if (!(lhs instanceof JCIdent)) {
2127 scanExpr(lhs);
2128 }
2129 scanExpr(tree.rhs);
2130 letInit(lhs);
2131 }
2133 public void visitAssignop(JCAssignOp tree) {
2134 scanExpr(tree.lhs);
2135 scanExpr(tree.rhs);
2136 letInit(tree.lhs);
2137 }
2139 public void visitUnary(JCUnary tree) {
2140 switch (tree.getTag()) {
2141 case NOT:
2142 scanCond(tree.arg);
2143 final Bits t = new Bits(initsWhenFalse);
2144 initsWhenFalse.assign(initsWhenTrue);
2145 initsWhenTrue.assign(t);
2146 t.assign(uninitsWhenFalse);
2147 uninitsWhenFalse.assign(uninitsWhenTrue);
2148 uninitsWhenTrue.assign(t);
2149 break;
2150 case PREINC: case POSTINC:
2151 case PREDEC: case POSTDEC:
2152 scanExpr(tree.arg);
2153 letInit(tree.arg);
2154 break;
2155 default:
2156 scanExpr(tree.arg);
2157 }
2158 }
2160 public void visitBinary(JCBinary tree) {
2161 switch (tree.getTag()) {
2162 case AND:
2163 scanCond(tree.lhs);
2164 final Bits initsWhenFalseLeft = new Bits(initsWhenFalse);
2165 final Bits uninitsWhenFalseLeft = new Bits(uninitsWhenFalse);
2166 inits.assign(initsWhenTrue);
2167 uninits.assign(uninitsWhenTrue);
2168 scanCond(tree.rhs);
2169 initsWhenFalse.andSet(initsWhenFalseLeft);
2170 uninitsWhenFalse.andSet(uninitsWhenFalseLeft);
2171 break;
2172 case OR:
2173 scanCond(tree.lhs);
2174 final Bits initsWhenTrueLeft = new Bits(initsWhenTrue);
2175 final Bits uninitsWhenTrueLeft = new Bits(uninitsWhenTrue);
2176 inits.assign(initsWhenFalse);
2177 uninits.assign(uninitsWhenFalse);
2178 scanCond(tree.rhs);
2179 initsWhenTrue.andSet(initsWhenTrueLeft);
2180 uninitsWhenTrue.andSet(uninitsWhenTrueLeft);
2181 break;
2182 default:
2183 scanExpr(tree.lhs);
2184 scanExpr(tree.rhs);
2185 }
2186 }
2188 public void visitIdent(JCIdent tree) {
2189 if (tree.sym.kind == VAR) {
2190 checkInit(tree.pos(), (VarSymbol)tree.sym);
2191 referenced(tree.sym);
2192 }
2193 }
2195 void referenced(Symbol sym) {
2196 unrefdResources.remove(sym);
2197 }
2199 public void visitAnnotatedType(JCAnnotatedType tree) {
2200 // annotations don't get scanned
2201 tree.underlyingType.accept(this);
2202 }
2204 public void visitTopLevel(JCCompilationUnit tree) {
2205 // Do nothing for TopLevel since each class is visited individually
2206 }
2208 /**************************************************************************
2209 * main method
2210 *************************************************************************/
2212 /** Perform definite assignment/unassignment analysis on a tree.
2213 */
2214 public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
2215 analyzeTree(env, env.tree, make);
2216 }
2218 public void analyzeTree(Env<AttrContext> env, JCTree tree, TreeMaker make) {
2219 try {
2220 attrEnv = env;
2221 Flow.this.make = make;
2222 startPos = tree.pos().getStartPosition();
2224 if (vars == null)
2225 vars = new VarSymbol[32];
2226 else
2227 for (int i=0; i<vars.length; i++)
2228 vars[i] = null;
2229 firstadr = 0;
2230 nextadr = 0;
2231 pendingExits = new ListBuffer<AssignPendingExit>();
2232 this.classDef = null;
2233 unrefdResources = new Scope(env.enclClass.sym);
2234 scan(tree);
2235 } finally {
2236 // note that recursive invocations of this method fail hard
2237 startPos = -1;
2238 resetBits(inits, uninits, uninitsTry, initsWhenTrue,
2239 initsWhenFalse, uninitsWhenTrue, uninitsWhenFalse);
2240 if (vars != null) for (int i=0; i<vars.length; i++)
2241 vars[i] = null;
2242 firstadr = 0;
2243 nextadr = 0;
2244 pendingExits = null;
2245 Flow.this.make = null;
2246 this.classDef = null;
2247 unrefdResources = null;
2248 }
2249 }
2250 }
2252 /**
2253 * This pass implements the last step of the dataflow analysis, namely
2254 * the effectively-final analysis check. This checks that every local variable
2255 * reference from a lambda body/local inner class is either final or effectively final.
2256 * As effectively final variables are marked as such during DA/DU, this pass must run after
2257 * AssignAnalyzer.
2258 */
2259 class CaptureAnalyzer extends BaseAnalyzer<BaseAnalyzer.PendingExit> {
2261 JCTree currentTree; //local class or lambda
2263 @Override
2264 void markDead() {
2265 //do nothing
2266 }
2268 @SuppressWarnings("fallthrough")
2269 void checkEffectivelyFinal(DiagnosticPosition pos, VarSymbol sym) {
2270 if (currentTree != null &&
2271 sym.owner.kind == MTH &&
2272 sym.pos < currentTree.getStartPosition()) {
2273 switch (currentTree.getTag()) {
2274 case CLASSDEF:
2275 if (!allowEffectivelyFinalInInnerClasses) {
2276 if ((sym.flags() & FINAL) == 0) {
2277 reportInnerClsNeedsFinalError(pos, sym);
2278 }
2279 break;
2280 }
2281 case LAMBDA:
2282 if ((sym.flags() & (EFFECTIVELY_FINAL | FINAL)) == 0) {
2283 reportEffectivelyFinalError(pos, sym);
2284 }
2285 }
2286 }
2287 }
2289 @SuppressWarnings("fallthrough")
2290 void letInit(JCTree tree) {
2291 tree = TreeInfo.skipParens(tree);
2292 if (tree.hasTag(IDENT) || tree.hasTag(SELECT)) {
2293 Symbol sym = TreeInfo.symbol(tree);
2294 if (currentTree != null &&
2295 sym.kind == VAR &&
2296 sym.owner.kind == MTH &&
2297 ((VarSymbol)sym).pos < currentTree.getStartPosition()) {
2298 switch (currentTree.getTag()) {
2299 case CLASSDEF:
2300 if (!allowEffectivelyFinalInInnerClasses) {
2301 reportInnerClsNeedsFinalError(tree, sym);
2302 break;
2303 }
2304 case LAMBDA:
2305 reportEffectivelyFinalError(tree, sym);
2306 }
2307 }
2308 }
2309 }
2311 void reportEffectivelyFinalError(DiagnosticPosition pos, Symbol sym) {
2312 String subKey = currentTree.hasTag(LAMBDA) ?
2313 "lambda" : "inner.cls";
2314 log.error(pos, "cant.ref.non.effectively.final.var", sym, diags.fragment(subKey));
2315 }
2317 void reportInnerClsNeedsFinalError(DiagnosticPosition pos, Symbol sym) {
2318 log.error(pos,
2319 "local.var.accessed.from.icls.needs.final",
2320 sym);
2321 }
2323 /*************************************************************************
2324 * Visitor methods for statements and definitions
2325 *************************************************************************/
2327 /* ------------ Visitor methods for various sorts of trees -------------*/
2329 public void visitClassDef(JCClassDecl tree) {
2330 JCTree prevTree = currentTree;
2331 try {
2332 currentTree = tree.sym.isLocal() ? tree : null;
2333 super.visitClassDef(tree);
2334 } finally {
2335 currentTree = prevTree;
2336 }
2337 }
2339 @Override
2340 public void visitLambda(JCLambda tree) {
2341 JCTree prevTree = currentTree;
2342 try {
2343 currentTree = tree;
2344 super.visitLambda(tree);
2345 } finally {
2346 currentTree = prevTree;
2347 }
2348 }
2350 @Override
2351 public void visitIdent(JCIdent tree) {
2352 if (tree.sym.kind == VAR) {
2353 checkEffectivelyFinal(tree, (VarSymbol)tree.sym);
2354 }
2355 }
2357 public void visitAssign(JCAssign tree) {
2358 JCTree lhs = TreeInfo.skipParens(tree.lhs);
2359 if (!(lhs instanceof JCIdent)) {
2360 scan(lhs);
2361 }
2362 scan(tree.rhs);
2363 letInit(lhs);
2364 }
2366 public void visitAssignop(JCAssignOp tree) {
2367 scan(tree.lhs);
2368 scan(tree.rhs);
2369 letInit(tree.lhs);
2370 }
2372 public void visitUnary(JCUnary tree) {
2373 switch (tree.getTag()) {
2374 case PREINC: case POSTINC:
2375 case PREDEC: case POSTDEC:
2376 scan(tree.arg);
2377 letInit(tree.arg);
2378 break;
2379 default:
2380 scan(tree.arg);
2381 }
2382 }
2384 public void visitTopLevel(JCCompilationUnit tree) {
2385 // Do nothing for TopLevel since each class is visited individually
2386 }
2388 /**************************************************************************
2389 * main method
2390 *************************************************************************/
2392 /** Perform definite assignment/unassignment analysis on a tree.
2393 */
2394 public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
2395 analyzeTree(env, env.tree, make);
2396 }
2397 public void analyzeTree(Env<AttrContext> env, JCTree tree, TreeMaker make) {
2398 try {
2399 attrEnv = env;
2400 Flow.this.make = make;
2401 pendingExits = new ListBuffer<PendingExit>();
2402 scan(tree);
2403 } finally {
2404 pendingExits = null;
2405 Flow.this.make = null;
2406 }
2407 }
2408 }
2409 }