Fri, 18 Oct 2013 15:03:34 -0700
8026749: Missing LV table in lambda bodies
Reviewed-by: vromero, jlahoda
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(log, syms, lint, names).analyzeTree(env);
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 } finally {
228 if (!speculative) {
229 log.popDiagnosticHandler(diagHandler);
230 }
231 }
232 }
234 public List<Type> analyzeLambdaThrownTypes(Env<AttrContext> env, JCLambda that, TreeMaker make) {
235 //we need to disable diagnostics temporarily; the problem is that if
236 //a lambda expression contains e.g. an unreachable statement, an error
237 //message will be reported and will cause compilation to skip the flow analyis
238 //step - if we suppress diagnostics, we won't stop at Attr for flow-analysis
239 //related errors, which will allow for more errors to be detected
240 Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
241 try {
242 new AssignAnalyzer(log, syms, lint, names).analyzeTree(env);
243 LambdaFlowAnalyzer flowAnalyzer = new LambdaFlowAnalyzer();
244 flowAnalyzer.analyzeTree(env, that, make);
245 return flowAnalyzer.inferredThrownTypes;
246 } finally {
247 log.popDiagnosticHandler(diagHandler);
248 }
249 }
251 /**
252 * Definite assignment scan mode
253 */
254 enum FlowKind {
255 /**
256 * This is the normal DA/DU analysis mode
257 */
258 NORMAL("var.might.already.be.assigned", false),
259 /**
260 * This is the speculative DA/DU analysis mode used to speculatively
261 * derive assertions within loop bodies
262 */
263 SPECULATIVE_LOOP("var.might.be.assigned.in.loop", true);
265 final String errKey;
266 final boolean isFinal;
268 FlowKind(String errKey, boolean isFinal) {
269 this.errKey = errKey;
270 this.isFinal = isFinal;
271 }
273 boolean isFinal() {
274 return isFinal;
275 }
276 }
278 protected Flow(Context context) {
279 context.put(flowKey, this);
280 names = Names.instance(context);
281 log = Log.instance(context);
282 syms = Symtab.instance(context);
283 types = Types.instance(context);
284 chk = Check.instance(context);
285 lint = Lint.instance(context);
286 rs = Resolve.instance(context);
287 diags = JCDiagnostic.Factory.instance(context);
288 Source source = Source.instance(context);
289 allowImprovedRethrowAnalysis = source.allowImprovedRethrowAnalysis();
290 allowImprovedCatchAnalysis = source.allowImprovedCatchAnalysis();
291 allowEffectivelyFinalInInnerClasses = source.allowEffectivelyFinalInInnerClasses();
292 }
294 /**
295 * Base visitor class for all visitors implementing dataflow analysis logic.
296 * This class define the shared logic for handling jumps (break/continue statements).
297 */
298 static abstract class BaseAnalyzer<P extends BaseAnalyzer.PendingExit> extends TreeScanner {
300 enum JumpKind {
301 BREAK(JCTree.Tag.BREAK) {
302 @Override
303 JCTree getTarget(JCTree tree) {
304 return ((JCBreak)tree).target;
305 }
306 },
307 CONTINUE(JCTree.Tag.CONTINUE) {
308 @Override
309 JCTree getTarget(JCTree tree) {
310 return ((JCContinue)tree).target;
311 }
312 };
314 final JCTree.Tag treeTag;
316 private JumpKind(Tag treeTag) {
317 this.treeTag = treeTag;
318 }
320 abstract JCTree getTarget(JCTree tree);
321 }
323 /** The currently pending exits that go from current inner blocks
324 * to an enclosing block, in source order.
325 */
326 ListBuffer<P> pendingExits;
328 /** A pending exit. These are the statements return, break, and
329 * continue. In addition, exception-throwing expressions or
330 * statements are put here when not known to be caught. This
331 * will typically result in an error unless it is within a
332 * try-finally whose finally block cannot complete normally.
333 */
334 static class PendingExit {
335 JCTree tree;
337 PendingExit(JCTree tree) {
338 this.tree = tree;
339 }
341 void resolveJump(JCTree tree) {
342 //do nothing
343 }
344 }
346 abstract void markDead(JCTree tree);
348 /** Record an outward transfer of control. */
349 void recordExit(JCTree tree, P pe) {
350 pendingExits.append(pe);
351 markDead(tree);
352 }
354 /** Resolve all jumps of this statement. */
355 private boolean resolveJump(JCTree tree,
356 ListBuffer<P> oldPendingExits,
357 JumpKind jk) {
358 boolean resolved = false;
359 List<P> exits = pendingExits.toList();
360 pendingExits = oldPendingExits;
361 for (; exits.nonEmpty(); exits = exits.tail) {
362 P exit = exits.head;
363 if (exit.tree.hasTag(jk.treeTag) &&
364 jk.getTarget(exit.tree) == tree) {
365 exit.resolveJump(tree);
366 resolved = true;
367 } else {
368 pendingExits.append(exit);
369 }
370 }
371 return resolved;
372 }
374 /** Resolve all continues of this statement. */
375 boolean resolveContinues(JCTree tree) {
376 return resolveJump(tree, new ListBuffer<P>(), JumpKind.CONTINUE);
377 }
379 /** Resolve all breaks of this statement. */
380 boolean resolveBreaks(JCTree tree, ListBuffer<P> oldPendingExits) {
381 return resolveJump(tree, oldPendingExits, JumpKind.BREAK);
382 }
384 @Override
385 public void scan(JCTree tree) {
386 if (tree != null && (
387 tree.type == null ||
388 tree.type != Type.stuckType)) {
389 super.scan(tree);
390 }
391 }
392 }
394 /**
395 * This pass implements the first step of the dataflow analysis, namely
396 * the liveness analysis check. This checks that every statement is reachable.
397 * The output of this analysis pass are used by other analyzers. This analyzer
398 * sets the 'finallyCanCompleteNormally' field in the JCTry class.
399 */
400 class AliveAnalyzer extends BaseAnalyzer<BaseAnalyzer.PendingExit> {
402 /** A flag that indicates whether the last statement could
403 * complete normally.
404 */
405 private boolean alive;
407 @Override
408 void markDead(JCTree tree) {
409 alive = false;
410 }
412 /*************************************************************************
413 * Visitor methods for statements and definitions
414 *************************************************************************/
416 /** Analyze a definition.
417 */
418 void scanDef(JCTree tree) {
419 scanStat(tree);
420 if (tree != null && tree.hasTag(JCTree.Tag.BLOCK) && !alive) {
421 log.error(tree.pos(),
422 "initializer.must.be.able.to.complete.normally");
423 }
424 }
426 /** Analyze a statement. Check that statement is reachable.
427 */
428 void scanStat(JCTree tree) {
429 if (!alive && tree != null) {
430 log.error(tree.pos(), "unreachable.stmt");
431 if (!tree.hasTag(SKIP)) alive = true;
432 }
433 scan(tree);
434 }
436 /** Analyze list of statements.
437 */
438 void scanStats(List<? extends JCStatement> trees) {
439 if (trees != null)
440 for (List<? extends JCStatement> l = trees; l.nonEmpty(); l = l.tail)
441 scanStat(l.head);
442 }
444 /* ------------ Visitor methods for various sorts of trees -------------*/
446 public void visitClassDef(JCClassDecl tree) {
447 if (tree.sym == null) return;
448 boolean alivePrev = alive;
449 ListBuffer<PendingExit> pendingExitsPrev = pendingExits;
450 Lint lintPrev = lint;
452 pendingExits = new ListBuffer<PendingExit>();
453 lint = lint.augment(tree.sym);
455 try {
456 // process all the static initializers
457 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
458 if (!l.head.hasTag(METHODDEF) &&
459 (TreeInfo.flags(l.head) & STATIC) != 0) {
460 scanDef(l.head);
461 }
462 }
464 // process all the instance initializers
465 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
466 if (!l.head.hasTag(METHODDEF) &&
467 (TreeInfo.flags(l.head) & STATIC) == 0) {
468 scanDef(l.head);
469 }
470 }
472 // process all the methods
473 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
474 if (l.head.hasTag(METHODDEF)) {
475 scan(l.head);
476 }
477 }
478 } finally {
479 pendingExits = pendingExitsPrev;
480 alive = alivePrev;
481 lint = lintPrev;
482 }
483 }
485 public void visitMethodDef(JCMethodDecl tree) {
486 if (tree.body == null) return;
487 Lint lintPrev = lint;
489 lint = lint.augment(tree.sym);
491 Assert.check(pendingExits.isEmpty());
493 try {
494 alive = true;
495 scanStat(tree.body);
497 if (alive && !tree.sym.type.getReturnType().hasTag(VOID))
498 log.error(TreeInfo.diagEndPos(tree.body), "missing.ret.stmt");
500 List<PendingExit> exits = pendingExits.toList();
501 pendingExits = new ListBuffer<PendingExit>();
502 while (exits.nonEmpty()) {
503 PendingExit exit = exits.head;
504 exits = exits.tail;
505 Assert.check(exit.tree.hasTag(RETURN));
506 }
507 } finally {
508 lint = lintPrev;
509 }
510 }
512 public void visitVarDef(JCVariableDecl tree) {
513 if (tree.init != null) {
514 Lint lintPrev = lint;
515 lint = lint.augment(tree.sym);
516 try{
517 scan(tree.init);
518 } finally {
519 lint = lintPrev;
520 }
521 }
522 }
524 public void visitBlock(JCBlock tree) {
525 scanStats(tree.stats);
526 }
528 public void visitDoLoop(JCDoWhileLoop tree) {
529 ListBuffer<PendingExit> prevPendingExits = pendingExits;
530 pendingExits = new ListBuffer<PendingExit>();
531 scanStat(tree.body);
532 alive |= resolveContinues(tree);
533 scan(tree.cond);
534 alive = alive && !tree.cond.type.isTrue();
535 alive |= resolveBreaks(tree, prevPendingExits);
536 }
538 public void visitWhileLoop(JCWhileLoop tree) {
539 ListBuffer<PendingExit> prevPendingExits = pendingExits;
540 pendingExits = new ListBuffer<PendingExit>();
541 scan(tree.cond);
542 alive = !tree.cond.type.isFalse();
543 scanStat(tree.body);
544 alive |= resolveContinues(tree);
545 alive = resolveBreaks(tree, prevPendingExits) ||
546 !tree.cond.type.isTrue();
547 }
549 public void visitForLoop(JCForLoop tree) {
550 ListBuffer<PendingExit> prevPendingExits = pendingExits;
551 scanStats(tree.init);
552 pendingExits = new ListBuffer<PendingExit>();
553 if (tree.cond != null) {
554 scan(tree.cond);
555 alive = !tree.cond.type.isFalse();
556 } else {
557 alive = true;
558 }
559 scanStat(tree.body);
560 alive |= resolveContinues(tree);
561 scan(tree.step);
562 alive = resolveBreaks(tree, prevPendingExits) ||
563 tree.cond != null && !tree.cond.type.isTrue();
564 }
566 public void visitForeachLoop(JCEnhancedForLoop tree) {
567 visitVarDef(tree.var);
568 ListBuffer<PendingExit> prevPendingExits = pendingExits;
569 scan(tree.expr);
570 pendingExits = new ListBuffer<PendingExit>();
571 scanStat(tree.body);
572 alive |= resolveContinues(tree);
573 resolveBreaks(tree, prevPendingExits);
574 alive = true;
575 }
577 public void visitLabelled(JCLabeledStatement tree) {
578 ListBuffer<PendingExit> prevPendingExits = pendingExits;
579 pendingExits = new ListBuffer<PendingExit>();
580 scanStat(tree.body);
581 alive |= resolveBreaks(tree, prevPendingExits);
582 }
584 public void visitSwitch(JCSwitch tree) {
585 ListBuffer<PendingExit> prevPendingExits = pendingExits;
586 pendingExits = new ListBuffer<PendingExit>();
587 scan(tree.selector);
588 boolean hasDefault = false;
589 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
590 alive = true;
591 JCCase c = l.head;
592 if (c.pat == null)
593 hasDefault = true;
594 else
595 scan(c.pat);
596 scanStats(c.stats);
597 // Warn about fall-through if lint switch fallthrough enabled.
598 if (alive &&
599 lint.isEnabled(Lint.LintCategory.FALLTHROUGH) &&
600 c.stats.nonEmpty() && l.tail.nonEmpty())
601 log.warning(Lint.LintCategory.FALLTHROUGH,
602 l.tail.head.pos(),
603 "possible.fall-through.into.case");
604 }
605 if (!hasDefault) {
606 alive = true;
607 }
608 alive |= resolveBreaks(tree, prevPendingExits);
609 }
611 public void visitTry(JCTry tree) {
612 ListBuffer<PendingExit> prevPendingExits = pendingExits;
613 pendingExits = new ListBuffer<PendingExit>();
614 for (JCTree resource : tree.resources) {
615 if (resource instanceof JCVariableDecl) {
616 JCVariableDecl vdecl = (JCVariableDecl) resource;
617 visitVarDef(vdecl);
618 } else if (resource instanceof JCExpression) {
619 scan((JCExpression) resource);
620 } else {
621 throw new AssertionError(tree); // parser error
622 }
623 }
625 scanStat(tree.body);
626 boolean aliveEnd = alive;
628 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
629 alive = true;
630 JCVariableDecl param = l.head.param;
631 scan(param);
632 scanStat(l.head.body);
633 aliveEnd |= alive;
634 }
635 if (tree.finalizer != null) {
636 ListBuffer<PendingExit> exits = pendingExits;
637 pendingExits = prevPendingExits;
638 alive = true;
639 scanStat(tree.finalizer);
640 tree.finallyCanCompleteNormally = alive;
641 if (!alive) {
642 if (lint.isEnabled(Lint.LintCategory.FINALLY)) {
643 log.warning(Lint.LintCategory.FINALLY,
644 TreeInfo.diagEndPos(tree.finalizer),
645 "finally.cannot.complete");
646 }
647 } else {
648 while (exits.nonEmpty()) {
649 pendingExits.append(exits.next());
650 }
651 alive = aliveEnd;
652 }
653 } else {
654 alive = aliveEnd;
655 ListBuffer<PendingExit> exits = pendingExits;
656 pendingExits = prevPendingExits;
657 while (exits.nonEmpty()) pendingExits.append(exits.next());
658 }
659 }
661 @Override
662 public void visitIf(JCIf tree) {
663 scan(tree.cond);
664 scanStat(tree.thenpart);
665 if (tree.elsepart != null) {
666 boolean aliveAfterThen = alive;
667 alive = true;
668 scanStat(tree.elsepart);
669 alive = alive | aliveAfterThen;
670 } else {
671 alive = true;
672 }
673 }
675 public void visitBreak(JCBreak tree) {
676 recordExit(tree, new PendingExit(tree));
677 }
679 public void visitContinue(JCContinue tree) {
680 recordExit(tree, new PendingExit(tree));
681 }
683 public void visitReturn(JCReturn tree) {
684 scan(tree.expr);
685 recordExit(tree, new PendingExit(tree));
686 }
688 public void visitThrow(JCThrow tree) {
689 scan(tree.expr);
690 markDead(tree);
691 }
693 public void visitApply(JCMethodInvocation tree) {
694 scan(tree.meth);
695 scan(tree.args);
696 }
698 public void visitNewClass(JCNewClass tree) {
699 scan(tree.encl);
700 scan(tree.args);
701 if (tree.def != null) {
702 scan(tree.def);
703 }
704 }
706 @Override
707 public void visitLambda(JCLambda tree) {
708 if (tree.type != null &&
709 tree.type.isErroneous()) {
710 return;
711 }
713 ListBuffer<PendingExit> prevPending = pendingExits;
714 boolean prevAlive = alive;
715 try {
716 pendingExits = new ListBuffer<>();
717 alive = true;
718 scanStat(tree.body);
719 tree.canCompleteNormally = alive;
720 }
721 finally {
722 pendingExits = prevPending;
723 alive = prevAlive;
724 }
725 }
727 public void visitTopLevel(JCCompilationUnit tree) {
728 // Do nothing for TopLevel since each class is visited individually
729 }
731 /**************************************************************************
732 * main method
733 *************************************************************************/
735 /** Perform definite assignment/unassignment analysis on a tree.
736 */
737 public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
738 analyzeTree(env, env.tree, make);
739 }
740 public void analyzeTree(Env<AttrContext> env, JCTree tree, TreeMaker make) {
741 try {
742 attrEnv = env;
743 Flow.this.make = make;
744 pendingExits = new ListBuffer<PendingExit>();
745 alive = true;
746 scan(tree);
747 } finally {
748 pendingExits = null;
749 Flow.this.make = null;
750 }
751 }
752 }
754 /**
755 * This pass implements the second step of the dataflow analysis, namely
756 * the exception analysis. This is to ensure that every checked exception that is
757 * thrown is declared or caught. The analyzer uses some info that has been set by
758 * the liveliness analyzer.
759 */
760 class FlowAnalyzer extends BaseAnalyzer<FlowAnalyzer.FlowPendingExit> {
762 /** A flag that indicates whether the last statement could
763 * complete normally.
764 */
765 HashMap<Symbol, List<Type>> preciseRethrowTypes;
767 /** The current class being defined.
768 */
769 JCClassDecl classDef;
771 /** The list of possibly thrown declarable exceptions.
772 */
773 List<Type> thrown;
775 /** The list of exceptions that are either caught or declared to be
776 * thrown.
777 */
778 List<Type> caught;
780 class FlowPendingExit extends BaseAnalyzer.PendingExit {
782 Type thrown;
784 FlowPendingExit(JCTree tree, Type thrown) {
785 super(tree);
786 this.thrown = thrown;
787 }
788 }
790 @Override
791 void markDead(JCTree tree) {
792 //do nothing
793 }
795 /*-------------------- Exceptions ----------------------*/
797 /** Complain that pending exceptions are not caught.
798 */
799 void errorUncaught() {
800 for (FlowPendingExit exit = pendingExits.next();
801 exit != null;
802 exit = pendingExits.next()) {
803 if (classDef != null &&
804 classDef.pos == exit.tree.pos) {
805 log.error(exit.tree.pos(),
806 "unreported.exception.default.constructor",
807 exit.thrown);
808 } else if (exit.tree.hasTag(VARDEF) &&
809 ((JCVariableDecl)exit.tree).sym.isResourceVariable()) {
810 log.error(exit.tree.pos(),
811 "unreported.exception.implicit.close",
812 exit.thrown,
813 ((JCVariableDecl)exit.tree).sym.name);
814 } else {
815 log.error(exit.tree.pos(),
816 "unreported.exception.need.to.catch.or.throw",
817 exit.thrown);
818 }
819 }
820 }
822 /** Record that exception is potentially thrown and check that it
823 * is caught.
824 */
825 void markThrown(JCTree tree, Type exc) {
826 if (!chk.isUnchecked(tree.pos(), exc)) {
827 if (!chk.isHandled(exc, caught)) {
828 pendingExits.append(new FlowPendingExit(tree, exc));
829 }
830 thrown = chk.incl(exc, thrown);
831 }
832 }
834 /*************************************************************************
835 * Visitor methods for statements and definitions
836 *************************************************************************/
838 /* ------------ Visitor methods for various sorts of trees -------------*/
840 public void visitClassDef(JCClassDecl tree) {
841 if (tree.sym == null) return;
843 JCClassDecl classDefPrev = classDef;
844 List<Type> thrownPrev = thrown;
845 List<Type> caughtPrev = caught;
846 ListBuffer<FlowPendingExit> pendingExitsPrev = pendingExits;
847 Lint lintPrev = lint;
849 pendingExits = new ListBuffer<FlowPendingExit>();
850 if (tree.name != names.empty) {
851 caught = List.nil();
852 }
853 classDef = tree;
854 thrown = List.nil();
855 lint = lint.augment(tree.sym);
857 try {
858 // process all the static initializers
859 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
860 if (!l.head.hasTag(METHODDEF) &&
861 (TreeInfo.flags(l.head) & STATIC) != 0) {
862 scan(l.head);
863 errorUncaught();
864 }
865 }
867 // add intersection of all thrown clauses of initial constructors
868 // to set of caught exceptions, unless class is anonymous.
869 if (tree.name != names.empty) {
870 boolean firstConstructor = true;
871 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
872 if (TreeInfo.isInitialConstructor(l.head)) {
873 List<Type> mthrown =
874 ((JCMethodDecl) l.head).sym.type.getThrownTypes();
875 if (firstConstructor) {
876 caught = mthrown;
877 firstConstructor = false;
878 } else {
879 caught = chk.intersect(mthrown, caught);
880 }
881 }
882 }
883 }
885 // process all the instance initializers
886 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
887 if (!l.head.hasTag(METHODDEF) &&
888 (TreeInfo.flags(l.head) & STATIC) == 0) {
889 scan(l.head);
890 errorUncaught();
891 }
892 }
894 // in an anonymous class, add the set of thrown exceptions to
895 // the throws clause of the synthetic constructor and propagate
896 // outwards.
897 // Changing the throws clause on the fly is okay here because
898 // the anonymous constructor can't be invoked anywhere else,
899 // and its type hasn't been cached.
900 if (tree.name == names.empty) {
901 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
902 if (TreeInfo.isInitialConstructor(l.head)) {
903 JCMethodDecl mdef = (JCMethodDecl)l.head;
904 mdef.thrown = make.Types(thrown);
905 mdef.sym.type = types.createMethodTypeWithThrown(mdef.sym.type, thrown);
906 }
907 }
908 thrownPrev = chk.union(thrown, thrownPrev);
909 }
911 // process all the methods
912 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
913 if (l.head.hasTag(METHODDEF)) {
914 scan(l.head);
915 errorUncaught();
916 }
917 }
919 thrown = thrownPrev;
920 } finally {
921 pendingExits = pendingExitsPrev;
922 caught = caughtPrev;
923 classDef = classDefPrev;
924 lint = lintPrev;
925 }
926 }
928 public void visitMethodDef(JCMethodDecl tree) {
929 if (tree.body == null) return;
931 List<Type> caughtPrev = caught;
932 List<Type> mthrown = tree.sym.type.getThrownTypes();
933 Lint lintPrev = lint;
935 lint = lint.augment(tree.sym);
937 Assert.check(pendingExits.isEmpty());
939 try {
940 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
941 JCVariableDecl def = l.head;
942 scan(def);
943 }
944 if (TreeInfo.isInitialConstructor(tree))
945 caught = chk.union(caught, mthrown);
946 else if ((tree.sym.flags() & (BLOCK | STATIC)) != BLOCK)
947 caught = mthrown;
948 // else we are in an instance initializer block;
949 // leave caught unchanged.
951 scan(tree.body);
953 List<FlowPendingExit> exits = pendingExits.toList();
954 pendingExits = new ListBuffer<FlowPendingExit>();
955 while (exits.nonEmpty()) {
956 FlowPendingExit exit = exits.head;
957 exits = exits.tail;
958 if (exit.thrown == null) {
959 Assert.check(exit.tree.hasTag(RETURN));
960 } else {
961 // uncaught throws will be reported later
962 pendingExits.append(exit);
963 }
964 }
965 } finally {
966 caught = caughtPrev;
967 lint = lintPrev;
968 }
969 }
971 public void visitVarDef(JCVariableDecl tree) {
972 if (tree.init != null) {
973 Lint lintPrev = lint;
974 lint = lint.augment(tree.sym);
975 try{
976 scan(tree.init);
977 } finally {
978 lint = lintPrev;
979 }
980 }
981 }
983 public void visitBlock(JCBlock tree) {
984 scan(tree.stats);
985 }
987 public void visitDoLoop(JCDoWhileLoop tree) {
988 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
989 pendingExits = new ListBuffer<FlowPendingExit>();
990 scan(tree.body);
991 resolveContinues(tree);
992 scan(tree.cond);
993 resolveBreaks(tree, prevPendingExits);
994 }
996 public void visitWhileLoop(JCWhileLoop tree) {
997 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
998 pendingExits = new ListBuffer<FlowPendingExit>();
999 scan(tree.cond);
1000 scan(tree.body);
1001 resolveContinues(tree);
1002 resolveBreaks(tree, prevPendingExits);
1003 }
1005 public void visitForLoop(JCForLoop tree) {
1006 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
1007 scan(tree.init);
1008 pendingExits = new ListBuffer<FlowPendingExit>();
1009 if (tree.cond != null) {
1010 scan(tree.cond);
1011 }
1012 scan(tree.body);
1013 resolveContinues(tree);
1014 scan(tree.step);
1015 resolveBreaks(tree, prevPendingExits);
1016 }
1018 public void visitForeachLoop(JCEnhancedForLoop tree) {
1019 visitVarDef(tree.var);
1020 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
1021 scan(tree.expr);
1022 pendingExits = new ListBuffer<FlowPendingExit>();
1023 scan(tree.body);
1024 resolveContinues(tree);
1025 resolveBreaks(tree, prevPendingExits);
1026 }
1028 public void visitLabelled(JCLabeledStatement tree) {
1029 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
1030 pendingExits = new ListBuffer<FlowPendingExit>();
1031 scan(tree.body);
1032 resolveBreaks(tree, prevPendingExits);
1033 }
1035 public void visitSwitch(JCSwitch tree) {
1036 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
1037 pendingExits = new ListBuffer<FlowPendingExit>();
1038 scan(tree.selector);
1039 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
1040 JCCase c = l.head;
1041 if (c.pat != null) {
1042 scan(c.pat);
1043 }
1044 scan(c.stats);
1045 }
1046 resolveBreaks(tree, prevPendingExits);
1047 }
1049 public void visitTry(JCTry tree) {
1050 List<Type> caughtPrev = caught;
1051 List<Type> thrownPrev = thrown;
1052 thrown = List.nil();
1053 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1054 List<JCExpression> subClauses = TreeInfo.isMultiCatch(l.head) ?
1055 ((JCTypeUnion)l.head.param.vartype).alternatives :
1056 List.of(l.head.param.vartype);
1057 for (JCExpression ct : subClauses) {
1058 caught = chk.incl(ct.type, caught);
1059 }
1060 }
1062 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
1063 pendingExits = new ListBuffer<FlowPendingExit>();
1064 for (JCTree resource : tree.resources) {
1065 if (resource instanceof JCVariableDecl) {
1066 JCVariableDecl vdecl = (JCVariableDecl) resource;
1067 visitVarDef(vdecl);
1068 } else if (resource instanceof JCExpression) {
1069 scan((JCExpression) resource);
1070 } else {
1071 throw new AssertionError(tree); // parser error
1072 }
1073 }
1074 for (JCTree resource : tree.resources) {
1075 List<Type> closeableSupertypes = resource.type.isCompound() ?
1076 types.interfaces(resource.type).prepend(types.supertype(resource.type)) :
1077 List.of(resource.type);
1078 for (Type sup : closeableSupertypes) {
1079 if (types.asSuper(sup, syms.autoCloseableType.tsym) != null) {
1080 Symbol closeMethod = rs.resolveQualifiedMethod(tree,
1081 attrEnv,
1082 sup,
1083 names.close,
1084 List.<Type>nil(),
1085 List.<Type>nil());
1086 Type mt = types.memberType(resource.type, closeMethod);
1087 if (closeMethod.kind == MTH) {
1088 for (Type t : mt.getThrownTypes()) {
1089 markThrown(resource, t);
1090 }
1091 }
1092 }
1093 }
1094 }
1095 scan(tree.body);
1096 List<Type> thrownInTry = allowImprovedCatchAnalysis ?
1097 chk.union(thrown, List.of(syms.runtimeExceptionType, syms.errorType)) :
1098 thrown;
1099 thrown = thrownPrev;
1100 caught = caughtPrev;
1102 List<Type> caughtInTry = List.nil();
1103 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1104 JCVariableDecl param = l.head.param;
1105 List<JCExpression> subClauses = TreeInfo.isMultiCatch(l.head) ?
1106 ((JCTypeUnion)l.head.param.vartype).alternatives :
1107 List.of(l.head.param.vartype);
1108 List<Type> ctypes = List.nil();
1109 List<Type> rethrownTypes = chk.diff(thrownInTry, caughtInTry);
1110 for (JCExpression ct : subClauses) {
1111 Type exc = ct.type;
1112 if (exc != syms.unknownType) {
1113 ctypes = ctypes.append(exc);
1114 if (types.isSameType(exc, syms.objectType))
1115 continue;
1116 checkCaughtType(l.head.pos(), exc, thrownInTry, caughtInTry);
1117 caughtInTry = chk.incl(exc, caughtInTry);
1118 }
1119 }
1120 scan(param);
1121 preciseRethrowTypes.put(param.sym, chk.intersect(ctypes, rethrownTypes));
1122 scan(l.head.body);
1123 preciseRethrowTypes.remove(param.sym);
1124 }
1125 if (tree.finalizer != null) {
1126 List<Type> savedThrown = thrown;
1127 thrown = List.nil();
1128 ListBuffer<FlowPendingExit> exits = pendingExits;
1129 pendingExits = prevPendingExits;
1130 scan(tree.finalizer);
1131 if (!tree.finallyCanCompleteNormally) {
1132 // discard exits and exceptions from try and finally
1133 thrown = chk.union(thrown, thrownPrev);
1134 } else {
1135 thrown = chk.union(thrown, chk.diff(thrownInTry, caughtInTry));
1136 thrown = chk.union(thrown, savedThrown);
1137 // FIX: this doesn't preserve source order of exits in catch
1138 // versus finally!
1139 while (exits.nonEmpty()) {
1140 pendingExits.append(exits.next());
1141 }
1142 }
1143 } else {
1144 thrown = chk.union(thrown, chk.diff(thrownInTry, caughtInTry));
1145 ListBuffer<FlowPendingExit> exits = pendingExits;
1146 pendingExits = prevPendingExits;
1147 while (exits.nonEmpty()) pendingExits.append(exits.next());
1148 }
1149 }
1151 @Override
1152 public void visitIf(JCIf tree) {
1153 scan(tree.cond);
1154 scan(tree.thenpart);
1155 if (tree.elsepart != null) {
1156 scan(tree.elsepart);
1157 }
1158 }
1160 void checkCaughtType(DiagnosticPosition pos, Type exc, List<Type> thrownInTry, List<Type> caughtInTry) {
1161 if (chk.subset(exc, caughtInTry)) {
1162 log.error(pos, "except.already.caught", exc);
1163 } else if (!chk.isUnchecked(pos, exc) &&
1164 !isExceptionOrThrowable(exc) &&
1165 !chk.intersects(exc, thrownInTry)) {
1166 log.error(pos, "except.never.thrown.in.try", exc);
1167 } else if (allowImprovedCatchAnalysis) {
1168 List<Type> catchableThrownTypes = chk.intersect(List.of(exc), thrownInTry);
1169 // 'catchableThrownTypes' cannnot possibly be empty - if 'exc' was an
1170 // unchecked exception, the result list would not be empty, as the augmented
1171 // thrown set includes { RuntimeException, Error }; if 'exc' was a checked
1172 // exception, that would have been covered in the branch above
1173 if (chk.diff(catchableThrownTypes, caughtInTry).isEmpty() &&
1174 !isExceptionOrThrowable(exc)) {
1175 String key = catchableThrownTypes.length() == 1 ?
1176 "unreachable.catch" :
1177 "unreachable.catch.1";
1178 log.warning(pos, key, catchableThrownTypes);
1179 }
1180 }
1181 }
1182 //where
1183 private boolean isExceptionOrThrowable(Type exc) {
1184 return exc.tsym == syms.throwableType.tsym ||
1185 exc.tsym == syms.exceptionType.tsym;
1186 }
1188 public void visitBreak(JCBreak tree) {
1189 recordExit(tree, new FlowPendingExit(tree, null));
1190 }
1192 public void visitContinue(JCContinue tree) {
1193 recordExit(tree, new FlowPendingExit(tree, null));
1194 }
1196 public void visitReturn(JCReturn tree) {
1197 scan(tree.expr);
1198 recordExit(tree, new FlowPendingExit(tree, null));
1199 }
1201 public void visitThrow(JCThrow tree) {
1202 scan(tree.expr);
1203 Symbol sym = TreeInfo.symbol(tree.expr);
1204 if (sym != null &&
1205 sym.kind == VAR &&
1206 (sym.flags() & (FINAL | EFFECTIVELY_FINAL)) != 0 &&
1207 preciseRethrowTypes.get(sym) != null &&
1208 allowImprovedRethrowAnalysis) {
1209 for (Type t : preciseRethrowTypes.get(sym)) {
1210 markThrown(tree, t);
1211 }
1212 }
1213 else {
1214 markThrown(tree, tree.expr.type);
1215 }
1216 markDead(tree);
1217 }
1219 public void visitApply(JCMethodInvocation tree) {
1220 scan(tree.meth);
1221 scan(tree.args);
1222 for (List<Type> l = tree.meth.type.getThrownTypes(); l.nonEmpty(); l = l.tail)
1223 markThrown(tree, l.head);
1224 }
1226 public void visitNewClass(JCNewClass tree) {
1227 scan(tree.encl);
1228 scan(tree.args);
1229 // scan(tree.def);
1230 for (List<Type> l = tree.constructorType.getThrownTypes();
1231 l.nonEmpty();
1232 l = l.tail) {
1233 markThrown(tree, l.head);
1234 }
1235 List<Type> caughtPrev = caught;
1236 try {
1237 // If the new class expression defines an anonymous class,
1238 // analysis of the anonymous constructor may encounter thrown
1239 // types which are unsubstituted type variables.
1240 // However, since the constructor's actual thrown types have
1241 // already been marked as thrown, it is safe to simply include
1242 // each of the constructor's formal thrown types in the set of
1243 // 'caught/declared to be thrown' types, for the duration of
1244 // the class def analysis.
1245 if (tree.def != null)
1246 for (List<Type> l = tree.constructor.type.getThrownTypes();
1247 l.nonEmpty();
1248 l = l.tail) {
1249 caught = chk.incl(l.head, caught);
1250 }
1251 scan(tree.def);
1252 }
1253 finally {
1254 caught = caughtPrev;
1255 }
1256 }
1258 @Override
1259 public void visitLambda(JCLambda tree) {
1260 if (tree.type != null &&
1261 tree.type.isErroneous()) {
1262 return;
1263 }
1264 List<Type> prevCaught = caught;
1265 List<Type> prevThrown = thrown;
1266 ListBuffer<FlowPendingExit> prevPending = pendingExits;
1267 try {
1268 pendingExits = new ListBuffer<>();
1269 caught = tree.getDescriptorType(types).getThrownTypes();
1270 thrown = List.nil();
1271 scan(tree.body);
1272 List<FlowPendingExit> exits = pendingExits.toList();
1273 pendingExits = new ListBuffer<FlowPendingExit>();
1274 while (exits.nonEmpty()) {
1275 FlowPendingExit exit = exits.head;
1276 exits = exits.tail;
1277 if (exit.thrown == null) {
1278 Assert.check(exit.tree.hasTag(RETURN));
1279 } else {
1280 // uncaught throws will be reported later
1281 pendingExits.append(exit);
1282 }
1283 }
1285 errorUncaught();
1286 } finally {
1287 pendingExits = prevPending;
1288 caught = prevCaught;
1289 thrown = prevThrown;
1290 }
1291 }
1293 public void visitTopLevel(JCCompilationUnit tree) {
1294 // Do nothing for TopLevel since each class is visited individually
1295 }
1297 /**************************************************************************
1298 * main method
1299 *************************************************************************/
1301 /** Perform definite assignment/unassignment analysis on a tree.
1302 */
1303 public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
1304 analyzeTree(env, env.tree, make);
1305 }
1306 public void analyzeTree(Env<AttrContext> env, JCTree tree, TreeMaker make) {
1307 try {
1308 attrEnv = env;
1309 Flow.this.make = make;
1310 pendingExits = new ListBuffer<FlowPendingExit>();
1311 preciseRethrowTypes = new HashMap<Symbol, List<Type>>();
1312 this.thrown = this.caught = null;
1313 this.classDef = null;
1314 scan(tree);
1315 } finally {
1316 pendingExits = null;
1317 Flow.this.make = null;
1318 this.thrown = this.caught = null;
1319 this.classDef = null;
1320 }
1321 }
1322 }
1324 /**
1325 * Specialized pass that performs inference of thrown types for lambdas.
1326 */
1327 class LambdaFlowAnalyzer extends FlowAnalyzer {
1328 List<Type> inferredThrownTypes;
1329 boolean inLambda;
1330 @Override
1331 public void visitLambda(JCLambda tree) {
1332 if ((tree.type != null &&
1333 tree.type.isErroneous()) || inLambda) {
1334 return;
1335 }
1336 List<Type> prevCaught = caught;
1337 List<Type> prevThrown = thrown;
1338 ListBuffer<FlowPendingExit> prevPending = pendingExits;
1339 inLambda = true;
1340 try {
1341 pendingExits = new ListBuffer<>();
1342 caught = List.of(syms.throwableType);
1343 thrown = List.nil();
1344 scan(tree.body);
1345 inferredThrownTypes = thrown;
1346 } finally {
1347 pendingExits = prevPending;
1348 caught = prevCaught;
1349 thrown = prevThrown;
1350 inLambda = false;
1351 }
1352 }
1353 @Override
1354 public void visitClassDef(JCClassDecl tree) {
1355 //skip
1356 }
1357 }
1359 /**
1360 * This pass implements (i) definite assignment analysis, which ensures that
1361 * each variable is assigned when used and (ii) definite unassignment analysis,
1362 * which ensures that no final variable is assigned more than once. This visitor
1363 * depends on the results of the liveliness analyzer. This pass is also used to mark
1364 * effectively-final local variables/parameters.
1365 */
1367 public abstract static class AbstractAssignAnalyzer<P extends AbstractAssignAnalyzer.AbstractAssignPendingExit>
1368 extends BaseAnalyzer<P> {
1370 /** The set of definitely assigned variables.
1371 */
1372 protected final Bits inits;
1374 /** The set of definitely unassigned variables.
1375 */
1376 final Bits uninits;
1378 /** The set of variables that are definitely unassigned everywhere
1379 * in current try block. This variable is maintained lazily; it is
1380 * updated only when something gets removed from uninits,
1381 * typically by being assigned in reachable code. To obtain the
1382 * correct set of variables which are definitely unassigned
1383 * anywhere in current try block, intersect uninitsTry and
1384 * uninits.
1385 */
1386 final Bits uninitsTry;
1388 /** When analyzing a condition, inits and uninits are null.
1389 * Instead we have:
1390 */
1391 final Bits initsWhenTrue;
1392 final Bits initsWhenFalse;
1393 final Bits uninitsWhenTrue;
1394 final Bits uninitsWhenFalse;
1396 /** A mapping from addresses to variable symbols.
1397 */
1398 protected JCVariableDecl[] vardecls;
1400 /** The current class being defined.
1401 */
1402 JCClassDecl classDef;
1404 /** The first variable sequence number in this class definition.
1405 */
1406 int firstadr;
1408 /** The next available variable sequence number.
1409 */
1410 protected int nextadr;
1412 /** The first variable sequence number in a block that can return.
1413 */
1414 protected int returnadr;
1416 /** The list of unreferenced automatic resources.
1417 */
1418 Scope unrefdResources;
1420 /** Set when processing a loop body the second time for DU analysis. */
1421 FlowKind flowKind = FlowKind.NORMAL;
1423 /** The starting position of the analysed tree */
1424 int startPos;
1426 final Symtab syms;
1428 protected Names names;
1430 public static class AbstractAssignPendingExit extends BaseAnalyzer.PendingExit {
1432 final Bits inits;
1433 final Bits uninits;
1434 final Bits exit_inits = new Bits(true);
1435 final Bits exit_uninits = new Bits(true);
1437 public AbstractAssignPendingExit(JCTree tree, final Bits inits, final Bits uninits) {
1438 super(tree);
1439 this.inits = inits;
1440 this.uninits = uninits;
1441 this.exit_inits.assign(inits);
1442 this.exit_uninits.assign(uninits);
1443 }
1445 @Override
1446 public void resolveJump(JCTree tree) {
1447 inits.andSet(exit_inits);
1448 uninits.andSet(exit_uninits);
1449 }
1450 }
1452 public AbstractAssignAnalyzer(Bits inits, Symtab syms, Names names) {
1453 this.inits = inits;
1454 uninits = new Bits();
1455 uninitsTry = new Bits();
1456 initsWhenTrue = new Bits(true);
1457 initsWhenFalse = new Bits(true);
1458 uninitsWhenTrue = new Bits(true);
1459 uninitsWhenFalse = new Bits(true);
1460 this.syms = syms;
1461 this.names = names;
1462 }
1464 @Override
1465 protected void markDead(JCTree tree) {
1466 inits.inclRange(returnadr, nextadr);
1467 uninits.inclRange(returnadr, nextadr);
1468 }
1470 /*-------------- Processing variables ----------------------*/
1472 /** Do we need to track init/uninit state of this symbol?
1473 * I.e. is symbol either a local or a blank final variable?
1474 */
1475 protected boolean trackable(VarSymbol sym) {
1476 return
1477 sym.pos >= startPos &&
1478 ((sym.owner.kind == MTH ||
1479 ((sym.flags() & (FINAL | HASINIT | PARAMETER)) == FINAL &&
1480 classDef.sym.isEnclosedBy((ClassSymbol)sym.owner))));
1481 }
1483 /** Initialize new trackable variable by setting its address field
1484 * to the next available sequence number and entering it under that
1485 * index into the vars array.
1486 */
1487 void newVar(JCVariableDecl varDecl) {
1488 VarSymbol sym = varDecl.sym;
1489 vardecls = ArrayUtils.ensureCapacity(vardecls, nextadr);
1490 if ((sym.flags() & FINAL) == 0) {
1491 sym.flags_field |= EFFECTIVELY_FINAL;
1492 }
1493 sym.adr = nextadr;
1494 vardecls[nextadr] = varDecl;
1495 exclVarFromInits(varDecl, nextadr);
1496 uninits.incl(nextadr);
1497 nextadr++;
1498 }
1500 protected void exclVarFromInits(JCTree tree, int adr) {
1501 inits.excl(adr);
1502 }
1504 protected void assignToInits(JCTree tree, Bits bits) {
1505 inits.assign(bits);
1506 }
1508 protected void andSetInits(JCTree tree, Bits bits) {
1509 inits.andSet(bits);
1510 }
1512 protected void orSetInits(JCTree tree, Bits bits) {
1513 inits.orSet(bits);
1514 }
1516 /** Record an initialization of a trackable variable.
1517 */
1518 void letInit(DiagnosticPosition pos, VarSymbol sym) {
1519 if (sym.adr >= firstadr && trackable(sym)) {
1520 if (uninits.isMember(sym.adr)) {
1521 uninit(sym);
1522 }
1523 inits.incl(sym.adr);
1524 }
1525 }
1526 //where
1527 void uninit(VarSymbol sym) {
1528 if (!inits.isMember(sym.adr)) {
1529 // reachable assignment
1530 uninits.excl(sym.adr);
1531 uninitsTry.excl(sym.adr);
1532 } else {
1533 //log.rawWarning(pos, "unreachable assignment");//DEBUG
1534 uninits.excl(sym.adr);
1535 }
1536 }
1538 /** If tree is either a simple name or of the form this.name or
1539 * C.this.name, and tree represents a trackable variable,
1540 * record an initialization of the variable.
1541 */
1542 void letInit(JCTree tree) {
1543 tree = TreeInfo.skipParens(tree);
1544 if (tree.hasTag(IDENT) || tree.hasTag(SELECT)) {
1545 Symbol sym = TreeInfo.symbol(tree);
1546 if (sym.kind == VAR) {
1547 letInit(tree.pos(), (VarSymbol)sym);
1548 }
1549 }
1550 }
1552 /** Check that trackable variable is initialized.
1553 */
1554 void checkInit(DiagnosticPosition pos, VarSymbol sym) {
1555 checkInit(pos, sym, "var.might.not.have.been.initialized");
1556 }
1558 void checkInit(DiagnosticPosition pos, VarSymbol sym, String errkey) {}
1560 /** Utility method to reset several Bits instances.
1561 */
1562 private void resetBits(Bits... bits) {
1563 for (Bits b : bits) {
1564 b.reset();
1565 }
1566 }
1568 /** Split (duplicate) inits/uninits into WhenTrue/WhenFalse sets
1569 */
1570 void split(boolean setToNull) {
1571 initsWhenFalse.assign(inits);
1572 uninitsWhenFalse.assign(uninits);
1573 initsWhenTrue.assign(inits);
1574 uninitsWhenTrue.assign(uninits);
1575 if (setToNull) {
1576 resetBits(inits, uninits);
1577 }
1578 }
1580 /** Merge (intersect) inits/uninits from WhenTrue/WhenFalse sets.
1581 */
1582 protected void merge(JCTree tree) {
1583 inits.assign(initsWhenFalse.andSet(initsWhenTrue));
1584 uninits.assign(uninitsWhenFalse.andSet(uninitsWhenTrue));
1585 }
1587 /* ************************************************************************
1588 * Visitor methods for statements and definitions
1589 *************************************************************************/
1591 /** Analyze an expression. Make sure to set (un)inits rather than
1592 * (un)initsWhenTrue(WhenFalse) on exit.
1593 */
1594 void scanExpr(JCTree tree) {
1595 if (tree != null) {
1596 scan(tree);
1597 if (inits.isReset()) {
1598 merge(tree);
1599 }
1600 }
1601 }
1603 /** Analyze a list of expressions.
1604 */
1605 void scanExprs(List<? extends JCExpression> trees) {
1606 if (trees != null)
1607 for (List<? extends JCExpression> l = trees; l.nonEmpty(); l = l.tail)
1608 scanExpr(l.head);
1609 }
1611 /** Analyze a condition. Make sure to set (un)initsWhenTrue(WhenFalse)
1612 * rather than (un)inits on exit.
1613 */
1614 void scanCond(JCTree tree) {
1615 if (tree.type.isFalse()) {
1616 if (inits.isReset()) merge(tree);
1617 initsWhenTrue.assign(inits);
1618 initsWhenTrue.inclRange(firstadr, nextadr);
1619 uninitsWhenTrue.assign(uninits);
1620 uninitsWhenTrue.inclRange(firstadr, nextadr);
1621 initsWhenFalse.assign(inits);
1622 uninitsWhenFalse.assign(uninits);
1623 } else if (tree.type.isTrue()) {
1624 if (inits.isReset()) merge(tree);
1625 initsWhenFalse.assign(inits);
1626 initsWhenFalse.inclRange(firstadr, nextadr);
1627 uninitsWhenFalse.assign(uninits);
1628 uninitsWhenFalse.inclRange(firstadr, nextadr);
1629 initsWhenTrue.assign(inits);
1630 uninitsWhenTrue.assign(uninits);
1631 } else {
1632 scan(tree);
1633 if (!inits.isReset())
1634 split(tree.type != syms.unknownType);
1635 }
1636 if (tree.type != syms.unknownType) {
1637 resetBits(inits, uninits);
1638 }
1639 }
1641 /* ------------ Visitor methods for various sorts of trees -------------*/
1643 @Override
1644 public void visitClassDef(JCClassDecl tree) {
1645 if (tree.sym == null) {
1646 return;
1647 }
1649 JCClassDecl classDefPrev = classDef;
1650 int firstadrPrev = firstadr;
1651 int nextadrPrev = nextadr;
1652 ListBuffer<P> pendingExitsPrev = pendingExits;
1654 pendingExits = new ListBuffer<P>();
1655 if (tree.name != names.empty) {
1656 firstadr = nextadr;
1657 }
1658 classDef = tree;
1659 try {
1660 // define all the static fields
1661 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1662 if (l.head.hasTag(VARDEF)) {
1663 JCVariableDecl def = (JCVariableDecl)l.head;
1664 if ((def.mods.flags & STATIC) != 0) {
1665 VarSymbol sym = def.sym;
1666 if (trackable(sym)) {
1667 newVar(def);
1668 }
1669 }
1670 }
1671 }
1673 // process all the static initializers
1674 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1675 if (!l.head.hasTag(METHODDEF) &&
1676 (TreeInfo.flags(l.head) & STATIC) != 0) {
1677 scan(l.head);
1678 }
1679 }
1681 // define all the instance fields
1682 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1683 if (l.head.hasTag(VARDEF)) {
1684 JCVariableDecl def = (JCVariableDecl)l.head;
1685 if ((def.mods.flags & STATIC) == 0) {
1686 VarSymbol sym = def.sym;
1687 if (trackable(sym)) {
1688 newVar(def);
1689 }
1690 }
1691 }
1692 }
1694 // process all the instance initializers
1695 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1696 if (!l.head.hasTag(METHODDEF) &&
1697 (TreeInfo.flags(l.head) & STATIC) == 0) {
1698 scan(l.head);
1699 }
1700 }
1702 // process all the methods
1703 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1704 if (l.head.hasTag(METHODDEF)) {
1705 scan(l.head);
1706 }
1707 }
1708 } finally {
1709 pendingExits = pendingExitsPrev;
1710 nextadr = nextadrPrev;
1711 firstadr = firstadrPrev;
1712 classDef = classDefPrev;
1713 }
1714 }
1716 @Override
1717 public void visitMethodDef(JCMethodDecl tree) {
1718 if (tree.body == null) {
1719 return;
1720 }
1721 /* Ignore synthetic methods, except for translated lambda methods.
1722 */
1723 if ((tree.sym.flags() & (SYNTHETIC | LAMBDA_METHOD)) == SYNTHETIC) {
1724 return;
1725 }
1727 final Bits initsPrev = new Bits(inits);
1728 final Bits uninitsPrev = new Bits(uninits);
1729 int nextadrPrev = nextadr;
1730 int firstadrPrev = firstadr;
1731 int returnadrPrev = returnadr;
1733 Assert.check(pendingExits.isEmpty());
1735 try {
1736 boolean isInitialConstructor =
1737 TreeInfo.isInitialConstructor(tree);
1739 if (!isInitialConstructor) {
1740 firstadr = nextadr;
1741 }
1742 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1743 JCVariableDecl def = l.head;
1744 scan(def);
1745 Assert.check((def.sym.flags() & PARAMETER) != 0, "Method parameter without PARAMETER flag");
1746 /* If we are executing the code from Gen, then there can be
1747 * synthetic or mandated variables, ignore them.
1748 */
1749 initParam(def);
1750 }
1751 // else we are in an instance initializer block;
1752 // leave caught unchanged.
1753 scan(tree.body);
1755 if (isInitialConstructor) {
1756 boolean isSynthesized = (tree.sym.flags() &
1757 GENERATEDCONSTR) != 0;
1758 for (int i = firstadr; i < nextadr; i++) {
1759 JCVariableDecl vardecl = vardecls[i];
1760 VarSymbol var = vardecl.sym;
1761 if (var.owner == classDef.sym) {
1762 // choose the diagnostic position based on whether
1763 // the ctor is default(synthesized) or not
1764 if (isSynthesized) {
1765 checkInit(TreeInfo.diagnosticPositionFor(var, vardecl),
1766 var, "var.not.initialized.in.default.constructor");
1767 } else {
1768 checkInit(TreeInfo.diagEndPos(tree.body), var);
1769 }
1770 }
1771 }
1772 }
1773 List<P> exits = pendingExits.toList();
1774 pendingExits = new ListBuffer<>();
1775 while (exits.nonEmpty()) {
1776 P exit = exits.head;
1777 exits = exits.tail;
1778 Assert.check(exit.tree.hasTag(RETURN), exit.tree);
1779 if (isInitialConstructor) {
1780 assignToInits(exit.tree, exit.exit_inits);
1781 for (int i = firstadr; i < nextadr; i++) {
1782 checkInit(exit.tree.pos(), vardecls[i].sym);
1783 }
1784 }
1785 }
1786 } finally {
1787 assignToInits(tree, initsPrev);
1788 uninits.assign(uninitsPrev);
1789 nextadr = nextadrPrev;
1790 firstadr = firstadrPrev;
1791 returnadr = returnadrPrev;
1792 }
1793 }
1795 protected void initParam(JCVariableDecl def) {
1796 inits.incl(def.sym.adr);
1797 uninits.excl(def.sym.adr);
1798 }
1800 public void visitVarDef(JCVariableDecl tree) {
1801 boolean track = trackable(tree.sym);
1802 if (track && tree.sym.owner.kind == MTH) {
1803 newVar(tree);
1804 }
1805 if (tree.init != null) {
1806 scanExpr(tree.init);
1807 if (track) {
1808 letInit(tree.pos(), tree.sym);
1809 }
1810 }
1811 }
1813 public void visitBlock(JCBlock tree) {
1814 int nextadrPrev = nextadr;
1815 scan(tree.stats);
1816 nextadr = nextadrPrev;
1817 }
1819 int getLogNumberOfErrors() {
1820 return 0;
1821 }
1823 public void visitDoLoop(JCDoWhileLoop tree) {
1824 ListBuffer<P> prevPendingExits = pendingExits;
1825 FlowKind prevFlowKind = flowKind;
1826 flowKind = FlowKind.NORMAL;
1827 final Bits initsSkip = new Bits(true);
1828 final Bits uninitsSkip = new Bits(true);
1829 pendingExits = new ListBuffer<P>();
1830 int prevErrors = getLogNumberOfErrors();
1831 do {
1832 final Bits uninitsEntry = new Bits(uninits);
1833 uninitsEntry.excludeFrom(nextadr);
1834 scan(tree.body);
1835 resolveContinues(tree);
1836 scanCond(tree.cond);
1837 if (!flowKind.isFinal()) {
1838 initsSkip.assign(initsWhenFalse);
1839 uninitsSkip.assign(uninitsWhenFalse);
1840 }
1841 if (getLogNumberOfErrors() != prevErrors ||
1842 flowKind.isFinal() ||
1843 new Bits(uninitsEntry).diffSet(uninitsWhenTrue).nextBit(firstadr)==-1)
1844 break;
1845 assignToInits(tree.cond, initsWhenTrue);
1846 uninits.assign(uninitsEntry.andSet(uninitsWhenTrue));
1847 flowKind = FlowKind.SPECULATIVE_LOOP;
1848 } while (true);
1849 flowKind = prevFlowKind;
1850 assignToInits(tree, initsSkip);
1851 uninits.assign(uninitsSkip);
1852 resolveBreaks(tree, prevPendingExits);
1853 }
1855 public void visitWhileLoop(JCWhileLoop tree) {
1856 ListBuffer<P> prevPendingExits = pendingExits;
1857 FlowKind prevFlowKind = flowKind;
1858 flowKind = FlowKind.NORMAL;
1859 final Bits initsSkip = new Bits(true);
1860 final Bits uninitsSkip = new Bits(true);
1861 pendingExits = new ListBuffer<>();
1862 int prevErrors = getLogNumberOfErrors();
1863 final Bits uninitsEntry = new Bits(uninits);
1864 uninitsEntry.excludeFrom(nextadr);
1865 do {
1866 scanCond(tree.cond);
1867 if (!flowKind.isFinal()) {
1868 initsSkip.assign(initsWhenFalse) ;
1869 uninitsSkip.assign(uninitsWhenFalse);
1870 }
1871 assignToInits(tree, initsWhenTrue);
1872 uninits.assign(uninitsWhenTrue);
1873 scan(tree.body);
1874 resolveContinues(tree);
1875 if (getLogNumberOfErrors() != prevErrors ||
1876 flowKind.isFinal() ||
1877 new Bits(uninitsEntry).diffSet(uninits).nextBit(firstadr) == -1) {
1878 break;
1879 }
1880 uninits.assign(uninitsEntry.andSet(uninits));
1881 flowKind = FlowKind.SPECULATIVE_LOOP;
1882 } while (true);
1883 flowKind = prevFlowKind;
1884 //a variable is DA/DU after the while statement, if it's DA/DU assuming the
1885 //branch is not taken AND if it's DA/DU before any break statement
1886 assignToInits(tree.body, initsSkip);
1887 uninits.assign(uninitsSkip);
1888 resolveBreaks(tree, prevPendingExits);
1889 }
1891 public void visitForLoop(JCForLoop tree) {
1892 ListBuffer<P> prevPendingExits = pendingExits;
1893 FlowKind prevFlowKind = flowKind;
1894 flowKind = FlowKind.NORMAL;
1895 int nextadrPrev = nextadr;
1896 scan(tree.init);
1897 final Bits initsSkip = new Bits(true);
1898 final Bits uninitsSkip = new Bits(true);
1899 pendingExits = new ListBuffer<P>();
1900 int prevErrors = getLogNumberOfErrors();
1901 do {
1902 final Bits uninitsEntry = new Bits(uninits);
1903 uninitsEntry.excludeFrom(nextadr);
1904 if (tree.cond != null) {
1905 scanCond(tree.cond);
1906 if (!flowKind.isFinal()) {
1907 initsSkip.assign(initsWhenFalse);
1908 uninitsSkip.assign(uninitsWhenFalse);
1909 }
1910 assignToInits(tree.body, initsWhenTrue);
1911 uninits.assign(uninitsWhenTrue);
1912 } else if (!flowKind.isFinal()) {
1913 initsSkip.assign(inits);
1914 initsSkip.inclRange(firstadr, nextadr);
1915 uninitsSkip.assign(uninits);
1916 uninitsSkip.inclRange(firstadr, nextadr);
1917 }
1918 scan(tree.body);
1919 resolveContinues(tree);
1920 scan(tree.step);
1921 if (getLogNumberOfErrors() != prevErrors ||
1922 flowKind.isFinal() ||
1923 new Bits(uninitsEntry).diffSet(uninits).nextBit(firstadr) == -1)
1924 break;
1925 uninits.assign(uninitsEntry.andSet(uninits));
1926 flowKind = FlowKind.SPECULATIVE_LOOP;
1927 } while (true);
1928 flowKind = prevFlowKind;
1929 //a variable is DA/DU after a for loop, if it's DA/DU assuming the
1930 //branch is not taken AND if it's DA/DU before any break statement
1931 assignToInits(tree.body, initsSkip);
1932 uninits.assign(uninitsSkip);
1933 resolveBreaks(tree, prevPendingExits);
1934 nextadr = nextadrPrev;
1935 }
1937 public void visitForeachLoop(JCEnhancedForLoop tree) {
1938 visitVarDef(tree.var);
1940 ListBuffer<P> prevPendingExits = pendingExits;
1941 FlowKind prevFlowKind = flowKind;
1942 flowKind = FlowKind.NORMAL;
1943 int nextadrPrev = nextadr;
1944 scan(tree.expr);
1945 final Bits initsStart = new Bits(inits);
1946 final Bits uninitsStart = new Bits(uninits);
1948 letInit(tree.pos(), tree.var.sym);
1949 pendingExits = new ListBuffer<P>();
1950 int prevErrors = getLogNumberOfErrors();
1951 do {
1952 final Bits uninitsEntry = new Bits(uninits);
1953 uninitsEntry.excludeFrom(nextadr);
1954 scan(tree.body);
1955 resolveContinues(tree);
1956 if (getLogNumberOfErrors() != prevErrors ||
1957 flowKind.isFinal() ||
1958 new Bits(uninitsEntry).diffSet(uninits).nextBit(firstadr) == -1)
1959 break;
1960 uninits.assign(uninitsEntry.andSet(uninits));
1961 flowKind = FlowKind.SPECULATIVE_LOOP;
1962 } while (true);
1963 flowKind = prevFlowKind;
1964 assignToInits(tree.body, initsStart);
1965 uninits.assign(uninitsStart.andSet(uninits));
1966 resolveBreaks(tree, prevPendingExits);
1967 nextadr = nextadrPrev;
1968 }
1970 public void visitLabelled(JCLabeledStatement tree) {
1971 ListBuffer<P> prevPendingExits = pendingExits;
1972 pendingExits = new ListBuffer<P>();
1973 scan(tree.body);
1974 resolveBreaks(tree, prevPendingExits);
1975 }
1977 public void visitSwitch(JCSwitch tree) {
1978 ListBuffer<P> prevPendingExits = pendingExits;
1979 pendingExits = new ListBuffer<>();
1980 int nextadrPrev = nextadr;
1981 scanExpr(tree.selector);
1982 final Bits initsSwitch = new Bits(inits);
1983 final Bits uninitsSwitch = new Bits(uninits);
1984 boolean hasDefault = false;
1985 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
1986 assignToInits(l.head, initsSwitch);
1987 uninits.assign(uninits.andSet(uninitsSwitch));
1988 JCCase c = l.head;
1989 if (c.pat == null) {
1990 hasDefault = true;
1991 } else {
1992 scanExpr(c.pat);
1993 }
1994 if (hasDefault) {
1995 assignToInits(null, initsSwitch);
1996 uninits.assign(uninits.andSet(uninitsSwitch));
1997 }
1998 scan(c.stats);
1999 addVars(c.stats, initsSwitch, uninitsSwitch);
2000 if (!hasDefault) {
2001 assignToInits(l.head.stats.last(), initsSwitch);
2002 uninits.assign(uninits.andSet(uninitsSwitch));
2003 }
2004 // Warn about fall-through if lint switch fallthrough enabled.
2005 }
2006 if (!hasDefault) {
2007 andSetInits(null, initsSwitch);
2008 }
2009 resolveBreaks(tree, prevPendingExits);
2010 nextadr = nextadrPrev;
2011 }
2012 // where
2013 /** Add any variables defined in stats to inits and uninits. */
2014 private void addVars(List<JCStatement> stats, final Bits inits,
2015 final Bits uninits) {
2016 for (;stats.nonEmpty(); stats = stats.tail) {
2017 JCTree stat = stats.head;
2018 if (stat.hasTag(VARDEF)) {
2019 int adr = ((JCVariableDecl) stat).sym.adr;
2020 inits.excl(adr);
2021 uninits.incl(adr);
2022 }
2023 }
2024 }
2026 boolean isEnabled(Lint.LintCategory lc) {
2027 return false;
2028 }
2030 void reportWarning(Lint.LintCategory lc, DiagnosticPosition pos, String key, Object ... args) {}
2032 public void visitTry(JCTry tree) {
2033 ListBuffer<JCVariableDecl> resourceVarDecls = new ListBuffer<>();
2034 final Bits uninitsTryPrev = new Bits(uninitsTry);
2035 ListBuffer<P> prevPendingExits = pendingExits;
2036 pendingExits = new ListBuffer<>();
2037 final Bits initsTry = new Bits(inits);
2038 uninitsTry.assign(uninits);
2039 for (JCTree resource : tree.resources) {
2040 if (resource instanceof JCVariableDecl) {
2041 JCVariableDecl vdecl = (JCVariableDecl) resource;
2042 visitVarDef(vdecl);
2043 unrefdResources.enter(vdecl.sym);
2044 resourceVarDecls.append(vdecl);
2045 } else if (resource instanceof JCExpression) {
2046 scanExpr((JCExpression) resource);
2047 } else {
2048 throw new AssertionError(tree); // parser error
2049 }
2050 }
2051 scan(tree.body);
2052 uninitsTry.andSet(uninits);
2053 final Bits initsEnd = new Bits(inits);
2054 final Bits uninitsEnd = new Bits(uninits);
2055 int nextadrCatch = nextadr;
2057 if (!resourceVarDecls.isEmpty() &&
2058 isEnabled(Lint.LintCategory.TRY)) {
2059 for (JCVariableDecl resVar : resourceVarDecls) {
2060 if (unrefdResources.includes(resVar.sym)) {
2061 reportWarning(Lint.LintCategory.TRY, resVar.pos(),
2062 "try.resource.not.referenced", resVar.sym);
2063 unrefdResources.remove(resVar.sym);
2064 }
2065 }
2066 }
2068 /* The analysis of each catch should be independent.
2069 * Each one should have the same initial values of inits and
2070 * uninits.
2071 */
2072 final Bits initsCatchPrev = new Bits(initsTry);
2073 final Bits uninitsCatchPrev = new Bits(uninitsTry);
2075 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
2076 JCVariableDecl param = l.head.param;
2077 assignToInits(tree.body, initsCatchPrev);
2078 uninits.assign(uninitsCatchPrev);
2079 scan(param);
2080 /* If this is a TWR and we are executing the code from Gen,
2081 * then there can be synthetic variables, ignore them.
2082 */
2083 initParam(param);
2084 scan(l.head.body);
2085 initsEnd.andSet(inits);
2086 uninitsEnd.andSet(uninits);
2087 nextadr = nextadrCatch;
2088 }
2089 if (tree.finalizer != null) {
2090 assignToInits(tree.finalizer, initsTry);
2091 uninits.assign(uninitsTry);
2092 ListBuffer<P> exits = pendingExits;
2093 pendingExits = prevPendingExits;
2094 scan(tree.finalizer);
2095 if (!tree.finallyCanCompleteNormally) {
2096 // discard exits and exceptions from try and finally
2097 } else {
2098 uninits.andSet(uninitsEnd);
2099 // FIX: this doesn't preserve source order of exits in catch
2100 // versus finally!
2101 while (exits.nonEmpty()) {
2102 P exit = exits.next();
2103 if (exit.exit_inits != null) {
2104 exit.exit_inits.orSet(inits);
2105 exit.exit_uninits.andSet(uninits);
2106 }
2107 pendingExits.append(exit);
2108 }
2109 orSetInits(tree, initsEnd);
2110 }
2111 } else {
2112 assignToInits(tree, initsEnd);
2113 uninits.assign(uninitsEnd);
2114 ListBuffer<P> exits = pendingExits;
2115 pendingExits = prevPendingExits;
2116 while (exits.nonEmpty()) pendingExits.append(exits.next());
2117 }
2118 uninitsTry.andSet(uninitsTryPrev).andSet(uninits);
2119 }
2121 public void visitConditional(JCConditional tree) {
2122 scanCond(tree.cond);
2123 final Bits initsBeforeElse = new Bits(initsWhenFalse);
2124 final Bits uninitsBeforeElse = new Bits(uninitsWhenFalse);
2125 assignToInits(tree.cond, initsWhenTrue);
2126 uninits.assign(uninitsWhenTrue);
2127 if (tree.truepart.type.hasTag(BOOLEAN) &&
2128 tree.falsepart.type.hasTag(BOOLEAN)) {
2129 // if b and c are boolean valued, then
2130 // v is (un)assigned after a?b:c when true iff
2131 // v is (un)assigned after b when true and
2132 // v is (un)assigned after c when true
2133 scanCond(tree.truepart);
2134 final Bits initsAfterThenWhenTrue = new Bits(initsWhenTrue);
2135 final Bits initsAfterThenWhenFalse = new Bits(initsWhenFalse);
2136 final Bits uninitsAfterThenWhenTrue = new Bits(uninitsWhenTrue);
2137 final Bits uninitsAfterThenWhenFalse = new Bits(uninitsWhenFalse);
2138 assignToInits(tree.truepart, initsBeforeElse);
2139 uninits.assign(uninitsBeforeElse);
2140 scanCond(tree.falsepart);
2141 initsWhenTrue.andSet(initsAfterThenWhenTrue);
2142 initsWhenFalse.andSet(initsAfterThenWhenFalse);
2143 uninitsWhenTrue.andSet(uninitsAfterThenWhenTrue);
2144 uninitsWhenFalse.andSet(uninitsAfterThenWhenFalse);
2145 } else {
2146 scanExpr(tree.truepart);
2147 final Bits initsAfterThen = new Bits(inits);
2148 final Bits uninitsAfterThen = new Bits(uninits);
2149 assignToInits(tree.truepart, initsBeforeElse);
2150 uninits.assign(uninitsBeforeElse);
2151 scanExpr(tree.falsepart);
2152 andSetInits(tree.falsepart, initsAfterThen);
2153 uninits.andSet(uninitsAfterThen);
2154 }
2155 }
2157 public void visitIf(JCIf tree) {
2158 scanCond(tree.cond);
2159 final Bits initsBeforeElse = new Bits(initsWhenFalse);
2160 final Bits uninitsBeforeElse = new Bits(uninitsWhenFalse);
2161 assignToInits(tree.cond, initsWhenTrue);
2162 uninits.assign(uninitsWhenTrue);
2163 scan(tree.thenpart);
2164 if (tree.elsepart != null) {
2165 final Bits initsAfterThen = new Bits(inits);
2166 final Bits uninitsAfterThen = new Bits(uninits);
2167 assignToInits(tree.thenpart, initsBeforeElse);
2168 uninits.assign(uninitsBeforeElse);
2169 scan(tree.elsepart);
2170 andSetInits(tree.elsepart, initsAfterThen);
2171 uninits.andSet(uninitsAfterThen);
2172 } else {
2173 andSetInits(tree.thenpart, initsBeforeElse);
2174 uninits.andSet(uninitsBeforeElse);
2175 }
2176 }
2178 protected P createNewPendingExit(JCTree tree, Bits inits, Bits uninits) {
2179 return null;
2180 }
2182 @Override
2183 public void visitBreak(JCBreak tree) {
2184 recordExit(tree, createNewPendingExit(tree, inits, uninits));
2185 }
2187 @Override
2188 public void visitContinue(JCContinue tree) {
2189 recordExit(tree, createNewPendingExit(tree, inits, uninits));
2190 }
2192 @Override
2193 public void visitReturn(JCReturn tree) {
2194 scanExpr(tree.expr);
2195 recordExit(tree, createNewPendingExit(tree, inits, uninits));
2196 }
2198 public void visitThrow(JCThrow tree) {
2199 scanExpr(tree.expr);
2200 markDead(tree.expr);
2201 }
2203 public void visitApply(JCMethodInvocation tree) {
2204 scanExpr(tree.meth);
2205 scanExprs(tree.args);
2206 }
2208 public void visitNewClass(JCNewClass tree) {
2209 scanExpr(tree.encl);
2210 scanExprs(tree.args);
2211 scan(tree.def);
2212 }
2214 @Override
2215 public void visitLambda(JCLambda tree) {
2216 final Bits prevUninits = new Bits(uninits);
2217 final Bits prevInits = new Bits(inits);
2218 int returnadrPrev = returnadr;
2219 ListBuffer<P> prevPending = pendingExits;
2220 try {
2221 returnadr = nextadr;
2222 pendingExits = new ListBuffer<P>();
2223 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
2224 JCVariableDecl def = l.head;
2225 scan(def);
2226 inits.incl(def.sym.adr);
2227 uninits.excl(def.sym.adr);
2228 }
2229 if (tree.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
2230 scanExpr(tree.body);
2231 } else {
2232 scan(tree.body);
2233 }
2234 }
2235 finally {
2236 returnadr = returnadrPrev;
2237 uninits.assign(prevUninits);
2238 assignToInits(tree, prevInits);
2239 pendingExits = prevPending;
2240 }
2241 }
2243 public void visitNewArray(JCNewArray tree) {
2244 scanExprs(tree.dims);
2245 scanExprs(tree.elems);
2246 }
2248 public void visitAssert(JCAssert tree) {
2249 final Bits initsExit = new Bits(inits);
2250 final Bits uninitsExit = new Bits(uninits);
2251 scanCond(tree.cond);
2252 uninitsExit.andSet(uninitsWhenTrue);
2253 if (tree.detail != null) {
2254 assignToInits(tree, initsWhenFalse);
2255 uninits.assign(uninitsWhenFalse);
2256 scanExpr(tree.detail);
2257 }
2258 assignToInits(tree, initsExit);
2259 uninits.assign(uninitsExit);
2260 }
2262 public void visitAssign(JCAssign tree) {
2263 JCTree lhs = TreeInfo.skipParens(tree.lhs);
2264 if (!(lhs instanceof JCIdent)) {
2265 scanExpr(lhs);
2266 }
2267 scanExpr(tree.rhs);
2268 letInit(lhs);
2269 }
2271 public void visitAssignop(JCAssignOp tree) {
2272 scanExpr(tree.lhs);
2273 scanExpr(tree.rhs);
2274 letInit(tree.lhs);
2275 }
2277 public void visitUnary(JCUnary tree) {
2278 switch (tree.getTag()) {
2279 case NOT:
2280 scanCond(tree.arg);
2281 final Bits t = new Bits(initsWhenFalse);
2282 initsWhenFalse.assign(initsWhenTrue);
2283 initsWhenTrue.assign(t);
2284 t.assign(uninitsWhenFalse);
2285 uninitsWhenFalse.assign(uninitsWhenTrue);
2286 uninitsWhenTrue.assign(t);
2287 break;
2288 case PREINC: case POSTINC:
2289 case PREDEC: case POSTDEC:
2290 scanExpr(tree.arg);
2291 letInit(tree.arg);
2292 break;
2293 default:
2294 scanExpr(tree.arg);
2295 }
2296 }
2298 public void visitBinary(JCBinary tree) {
2299 switch (tree.getTag()) {
2300 case AND:
2301 scanCond(tree.lhs);
2302 final Bits initsWhenFalseLeft = new Bits(initsWhenFalse);
2303 final Bits uninitsWhenFalseLeft = new Bits(uninitsWhenFalse);
2304 assignToInits(tree.lhs, initsWhenTrue);
2305 uninits.assign(uninitsWhenTrue);
2306 scanCond(tree.rhs);
2307 initsWhenFalse.andSet(initsWhenFalseLeft);
2308 uninitsWhenFalse.andSet(uninitsWhenFalseLeft);
2309 break;
2310 case OR:
2311 scanCond(tree.lhs);
2312 final Bits initsWhenTrueLeft = new Bits(initsWhenTrue);
2313 final Bits uninitsWhenTrueLeft = new Bits(uninitsWhenTrue);
2314 assignToInits(tree.lhs, initsWhenFalse);
2315 uninits.assign(uninitsWhenFalse);
2316 scanCond(tree.rhs);
2317 initsWhenTrue.andSet(initsWhenTrueLeft);
2318 uninitsWhenTrue.andSet(uninitsWhenTrueLeft);
2319 break;
2320 default:
2321 scanExpr(tree.lhs);
2322 scanExpr(tree.rhs);
2323 }
2324 }
2326 public void visitIdent(JCIdent tree) {
2327 if (tree.sym.kind == VAR) {
2328 checkInit(tree.pos(), (VarSymbol)tree.sym);
2329 referenced(tree.sym);
2330 }
2331 }
2333 void referenced(Symbol sym) {
2334 unrefdResources.remove(sym);
2335 }
2337 public void visitAnnotatedType(JCAnnotatedType tree) {
2338 // annotations don't get scanned
2339 tree.underlyingType.accept(this);
2340 }
2342 public void visitTopLevel(JCCompilationUnit tree) {
2343 // Do nothing for TopLevel since each class is visited individually
2344 }
2346 /**************************************************************************
2347 * main method
2348 *************************************************************************/
2350 /** Perform definite assignment/unassignment analysis on a tree.
2351 */
2352 public void analyzeTree(Env<?> env) {
2353 analyzeTree(env, env.tree);
2354 }
2356 public void analyzeTree(Env<?> env, JCTree tree) {
2357 try {
2358 startPos = tree.pos().getStartPosition();
2360 if (vardecls == null)
2361 vardecls = new JCVariableDecl[32];
2362 else
2363 for (int i=0; i<vardecls.length; i++)
2364 vardecls[i] = null;
2365 firstadr = 0;
2366 nextadr = 0;
2367 pendingExits = new ListBuffer<>();
2368 this.classDef = null;
2369 unrefdResources = new Scope(env.enclClass.sym);
2370 scan(tree);
2371 } finally {
2372 // note that recursive invocations of this method fail hard
2373 startPos = -1;
2374 resetBits(inits, uninits, uninitsTry, initsWhenTrue,
2375 initsWhenFalse, uninitsWhenTrue, uninitsWhenFalse);
2376 if (vardecls != null) {
2377 for (int i=0; i<vardecls.length; i++)
2378 vardecls[i] = null;
2379 }
2380 firstadr = 0;
2381 nextadr = 0;
2382 pendingExits = null;
2383 this.classDef = null;
2384 unrefdResources = null;
2385 }
2386 }
2387 }
2389 public static class AssignAnalyzer
2390 extends AbstractAssignAnalyzer<AssignAnalyzer.AssignPendingExit> {
2392 Log log;
2393 Lint lint;
2395 public static class AssignPendingExit
2396 extends AbstractAssignAnalyzer.AbstractAssignPendingExit {
2398 public AssignPendingExit(JCTree tree, final Bits inits, final Bits uninits) {
2399 super(tree, inits, uninits);
2400 }
2401 }
2403 public AssignAnalyzer(Log log, Symtab syms, Lint lint, Names names) {
2404 super(new Bits(), syms, names);
2405 this.log = log;
2406 this.lint = lint;
2407 }
2409 @Override
2410 protected AssignPendingExit createNewPendingExit(JCTree tree,
2411 Bits inits, Bits uninits) {
2412 return new AssignPendingExit(tree, inits, uninits);
2413 }
2415 /** Record an initialization of a trackable variable.
2416 */
2417 @Override
2418 void letInit(DiagnosticPosition pos, VarSymbol sym) {
2419 if (sym.adr >= firstadr && trackable(sym)) {
2420 if ((sym.flags() & EFFECTIVELY_FINAL) != 0) {
2421 if (!uninits.isMember(sym.adr)) {
2422 //assignment targeting an effectively final variable
2423 //makes the variable lose its status of effectively final
2424 //if the variable is _not_ definitively unassigned
2425 sym.flags_field &= ~EFFECTIVELY_FINAL;
2426 } else {
2427 uninit(sym);
2428 }
2429 }
2430 else if ((sym.flags() & FINAL) != 0) {
2431 if ((sym.flags() & PARAMETER) != 0) {
2432 if ((sym.flags() & UNION) != 0) { //multi-catch parameter
2433 log.error(pos, "multicatch.parameter.may.not.be.assigned", sym);
2434 }
2435 else {
2436 log.error(pos, "final.parameter.may.not.be.assigned",
2437 sym);
2438 }
2439 } else if (!uninits.isMember(sym.adr)) {
2440 log.error(pos, flowKind.errKey, sym);
2441 } else {
2442 uninit(sym);
2443 }
2444 }
2445 inits.incl(sym.adr);
2446 } else if ((sym.flags() & FINAL) != 0) {
2447 log.error(pos, "var.might.already.be.assigned", sym);
2448 }
2449 }
2451 @Override
2452 void checkInit(DiagnosticPosition pos, VarSymbol sym, String errkey) {
2453 if ((sym.adr >= firstadr || sym.owner.kind != TYP) &&
2454 trackable(sym) &&
2455 !inits.isMember(sym.adr)) {
2456 log.error(pos, errkey, sym);
2457 inits.incl(sym.adr);
2458 }
2459 }
2461 @Override
2462 void reportWarning(Lint.LintCategory lc, DiagnosticPosition pos,
2463 String key, Object ... args) {
2464 log.warning(lc, pos, key, args);
2465 }
2467 @Override
2468 int getLogNumberOfErrors() {
2469 return log.nerrors;
2470 }
2472 @Override
2473 boolean isEnabled(Lint.LintCategory lc) {
2474 return lint.isEnabled(lc);
2475 }
2477 @Override
2478 public void visitClassDef(JCClassDecl tree) {
2479 if (tree.sym == null) {
2480 return;
2481 }
2483 Lint lintPrev = lint;
2484 lint = lint.augment(tree.sym);
2485 try {
2486 super.visitClassDef(tree);
2487 } finally {
2488 lint = lintPrev;
2489 }
2490 }
2492 @Override
2493 public void visitMethodDef(JCMethodDecl tree) {
2494 if (tree.body == null) {
2495 return;
2496 }
2498 /* MemberEnter can generate synthetic methods ignore them
2499 */
2500 if ((tree.sym.flags() & SYNTHETIC) != 0) {
2501 return;
2502 }
2504 Lint lintPrev = lint;
2505 lint = lint.augment(tree.sym);
2506 try {
2507 super.visitMethodDef(tree);
2508 } finally {
2509 lint = lintPrev;
2510 }
2511 }
2513 @Override
2514 public void visitVarDef(JCVariableDecl tree) {
2515 if (tree.init == null) {
2516 super.visitVarDef(tree);
2517 } else {
2518 Lint lintPrev = lint;
2519 lint = lint.augment(tree.sym);
2520 try{
2521 super.visitVarDef(tree);
2522 } finally {
2523 lint = lintPrev;
2524 }
2525 }
2526 }
2528 }
2530 /**
2531 * This pass implements the last step of the dataflow analysis, namely
2532 * the effectively-final analysis check. This checks that every local variable
2533 * reference from a lambda body/local inner class is either final or effectively final.
2534 * As effectively final variables are marked as such during DA/DU, this pass must run after
2535 * AssignAnalyzer.
2536 */
2537 class CaptureAnalyzer extends BaseAnalyzer<BaseAnalyzer.PendingExit> {
2539 JCTree currentTree; //local class or lambda
2541 @Override
2542 void markDead(JCTree tree) {
2543 //do nothing
2544 }
2546 @SuppressWarnings("fallthrough")
2547 void checkEffectivelyFinal(DiagnosticPosition pos, VarSymbol sym) {
2548 if (currentTree != null &&
2549 sym.owner.kind == MTH &&
2550 sym.pos < currentTree.getStartPosition()) {
2551 switch (currentTree.getTag()) {
2552 case CLASSDEF:
2553 if (!allowEffectivelyFinalInInnerClasses) {
2554 if ((sym.flags() & FINAL) == 0) {
2555 reportInnerClsNeedsFinalError(pos, sym);
2556 }
2557 break;
2558 }
2559 case LAMBDA:
2560 if ((sym.flags() & (EFFECTIVELY_FINAL | FINAL)) == 0) {
2561 reportEffectivelyFinalError(pos, sym);
2562 }
2563 }
2564 }
2565 }
2567 @SuppressWarnings("fallthrough")
2568 void letInit(JCTree tree) {
2569 tree = TreeInfo.skipParens(tree);
2570 if (tree.hasTag(IDENT) || tree.hasTag(SELECT)) {
2571 Symbol sym = TreeInfo.symbol(tree);
2572 if (currentTree != null &&
2573 sym.kind == VAR &&
2574 sym.owner.kind == MTH &&
2575 ((VarSymbol)sym).pos < currentTree.getStartPosition()) {
2576 switch (currentTree.getTag()) {
2577 case CLASSDEF:
2578 if (!allowEffectivelyFinalInInnerClasses) {
2579 reportInnerClsNeedsFinalError(tree, sym);
2580 break;
2581 }
2582 case LAMBDA:
2583 reportEffectivelyFinalError(tree, sym);
2584 }
2585 }
2586 }
2587 }
2589 void reportEffectivelyFinalError(DiagnosticPosition pos, Symbol sym) {
2590 String subKey = currentTree.hasTag(LAMBDA) ?
2591 "lambda" : "inner.cls";
2592 log.error(pos, "cant.ref.non.effectively.final.var", sym, diags.fragment(subKey));
2593 }
2595 void reportInnerClsNeedsFinalError(DiagnosticPosition pos, Symbol sym) {
2596 log.error(pos,
2597 "local.var.accessed.from.icls.needs.final",
2598 sym);
2599 }
2601 /*************************************************************************
2602 * Visitor methods for statements and definitions
2603 *************************************************************************/
2605 /* ------------ Visitor methods for various sorts of trees -------------*/
2607 public void visitClassDef(JCClassDecl tree) {
2608 JCTree prevTree = currentTree;
2609 try {
2610 currentTree = tree.sym.isLocal() ? tree : null;
2611 super.visitClassDef(tree);
2612 } finally {
2613 currentTree = prevTree;
2614 }
2615 }
2617 @Override
2618 public void visitLambda(JCLambda tree) {
2619 JCTree prevTree = currentTree;
2620 try {
2621 currentTree = tree;
2622 super.visitLambda(tree);
2623 } finally {
2624 currentTree = prevTree;
2625 }
2626 }
2628 @Override
2629 public void visitIdent(JCIdent tree) {
2630 if (tree.sym.kind == VAR) {
2631 checkEffectivelyFinal(tree, (VarSymbol)tree.sym);
2632 }
2633 }
2635 public void visitAssign(JCAssign tree) {
2636 JCTree lhs = TreeInfo.skipParens(tree.lhs);
2637 if (!(lhs instanceof JCIdent)) {
2638 scan(lhs);
2639 }
2640 scan(tree.rhs);
2641 letInit(lhs);
2642 }
2644 public void visitAssignop(JCAssignOp tree) {
2645 scan(tree.lhs);
2646 scan(tree.rhs);
2647 letInit(tree.lhs);
2648 }
2650 public void visitUnary(JCUnary tree) {
2651 switch (tree.getTag()) {
2652 case PREINC: case POSTINC:
2653 case PREDEC: case POSTDEC:
2654 scan(tree.arg);
2655 letInit(tree.arg);
2656 break;
2657 default:
2658 scan(tree.arg);
2659 }
2660 }
2662 public void visitTopLevel(JCCompilationUnit tree) {
2663 // Do nothing for TopLevel since each class is visited individually
2664 }
2666 /**************************************************************************
2667 * main method
2668 *************************************************************************/
2670 /** Perform definite assignment/unassignment analysis on a tree.
2671 */
2672 public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
2673 analyzeTree(env, env.tree, make);
2674 }
2675 public void analyzeTree(Env<AttrContext> env, JCTree tree, TreeMaker make) {
2676 try {
2677 attrEnv = env;
2678 Flow.this.make = make;
2679 pendingExits = new ListBuffer<PendingExit>();
2680 scan(tree);
2681 } finally {
2682 pendingExits = null;
2683 Flow.this.make = null;
2684 }
2685 }
2686 }
2687 }