Wed, 17 Jul 2013 14:19:25 +0100
8019340: varargs-related warnings are meaningless on signature-polymorphic methods such as MethodHandle.invokeExact
Summary: Disable certain varargs warnings when compiling polymorphic signature calls
Reviewed-by: jjg
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 }
377 @Override
378 public void scan(JCTree tree) {
379 if (tree != null && (
380 tree.type == null ||
381 tree.type != Type.stuckType)) {
382 super.scan(tree);
383 }
384 }
385 }
387 /**
388 * This pass implements the first step of the dataflow analysis, namely
389 * the liveness analysis check. This checks that every statement is reachable.
390 * The output of this analysis pass are used by other analyzers. This analyzer
391 * sets the 'finallyCanCompleteNormally' field in the JCTry class.
392 */
393 class AliveAnalyzer extends BaseAnalyzer<BaseAnalyzer.PendingExit> {
395 /** A flag that indicates whether the last statement could
396 * complete normally.
397 */
398 private boolean alive;
400 @Override
401 void markDead() {
402 alive = false;
403 }
405 /*************************************************************************
406 * Visitor methods for statements and definitions
407 *************************************************************************/
409 /** Analyze a definition.
410 */
411 void scanDef(JCTree tree) {
412 scanStat(tree);
413 if (tree != null && tree.hasTag(JCTree.Tag.BLOCK) && !alive) {
414 log.error(tree.pos(),
415 "initializer.must.be.able.to.complete.normally");
416 }
417 }
419 /** Analyze a statement. Check that statement is reachable.
420 */
421 void scanStat(JCTree tree) {
422 if (!alive && tree != null) {
423 log.error(tree.pos(), "unreachable.stmt");
424 if (!tree.hasTag(SKIP)) alive = true;
425 }
426 scan(tree);
427 }
429 /** Analyze list of statements.
430 */
431 void scanStats(List<? extends JCStatement> trees) {
432 if (trees != null)
433 for (List<? extends JCStatement> l = trees; l.nonEmpty(); l = l.tail)
434 scanStat(l.head);
435 }
437 /* ------------ Visitor methods for various sorts of trees -------------*/
439 public void visitClassDef(JCClassDecl tree) {
440 if (tree.sym == null) return;
441 boolean alivePrev = alive;
442 ListBuffer<PendingExit> pendingExitsPrev = pendingExits;
443 Lint lintPrev = lint;
445 pendingExits = new ListBuffer<PendingExit>();
446 lint = lint.augment(tree.sym);
448 try {
449 // process all the static initializers
450 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
451 if (!l.head.hasTag(METHODDEF) &&
452 (TreeInfo.flags(l.head) & STATIC) != 0) {
453 scanDef(l.head);
454 }
455 }
457 // process all the instance initializers
458 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
459 if (!l.head.hasTag(METHODDEF) &&
460 (TreeInfo.flags(l.head) & STATIC) == 0) {
461 scanDef(l.head);
462 }
463 }
465 // process all the methods
466 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
467 if (l.head.hasTag(METHODDEF)) {
468 scan(l.head);
469 }
470 }
471 } finally {
472 pendingExits = pendingExitsPrev;
473 alive = alivePrev;
474 lint = lintPrev;
475 }
476 }
478 public void visitMethodDef(JCMethodDecl tree) {
479 if (tree.body == null) return;
480 Lint lintPrev = lint;
482 lint = lint.augment(tree.sym);
484 Assert.check(pendingExits.isEmpty());
486 try {
487 alive = true;
488 scanStat(tree.body);
490 if (alive && !tree.sym.type.getReturnType().hasTag(VOID))
491 log.error(TreeInfo.diagEndPos(tree.body), "missing.ret.stmt");
493 List<PendingExit> exits = pendingExits.toList();
494 pendingExits = new ListBuffer<PendingExit>();
495 while (exits.nonEmpty()) {
496 PendingExit exit = exits.head;
497 exits = exits.tail;
498 Assert.check(exit.tree.hasTag(RETURN));
499 }
500 } finally {
501 lint = lintPrev;
502 }
503 }
505 public void visitVarDef(JCVariableDecl tree) {
506 if (tree.init != null) {
507 Lint lintPrev = lint;
508 lint = lint.augment(tree.sym);
509 try{
510 scan(tree.init);
511 } finally {
512 lint = lintPrev;
513 }
514 }
515 }
517 public void visitBlock(JCBlock tree) {
518 scanStats(tree.stats);
519 }
521 public void visitDoLoop(JCDoWhileLoop tree) {
522 ListBuffer<PendingExit> prevPendingExits = pendingExits;
523 pendingExits = new ListBuffer<PendingExit>();
524 scanStat(tree.body);
525 alive |= resolveContinues(tree);
526 scan(tree.cond);
527 alive = alive && !tree.cond.type.isTrue();
528 alive |= resolveBreaks(tree, prevPendingExits);
529 }
531 public void visitWhileLoop(JCWhileLoop tree) {
532 ListBuffer<PendingExit> prevPendingExits = pendingExits;
533 pendingExits = new ListBuffer<PendingExit>();
534 scan(tree.cond);
535 alive = !tree.cond.type.isFalse();
536 scanStat(tree.body);
537 alive |= resolveContinues(tree);
538 alive = resolveBreaks(tree, prevPendingExits) ||
539 !tree.cond.type.isTrue();
540 }
542 public void visitForLoop(JCForLoop tree) {
543 ListBuffer<PendingExit> prevPendingExits = pendingExits;
544 scanStats(tree.init);
545 pendingExits = new ListBuffer<PendingExit>();
546 if (tree.cond != null) {
547 scan(tree.cond);
548 alive = !tree.cond.type.isFalse();
549 } else {
550 alive = true;
551 }
552 scanStat(tree.body);
553 alive |= resolveContinues(tree);
554 scan(tree.step);
555 alive = resolveBreaks(tree, prevPendingExits) ||
556 tree.cond != null && !tree.cond.type.isTrue();
557 }
559 public void visitForeachLoop(JCEnhancedForLoop tree) {
560 visitVarDef(tree.var);
561 ListBuffer<PendingExit> prevPendingExits = pendingExits;
562 scan(tree.expr);
563 pendingExits = new ListBuffer<PendingExit>();
564 scanStat(tree.body);
565 alive |= resolveContinues(tree);
566 resolveBreaks(tree, prevPendingExits);
567 alive = true;
568 }
570 public void visitLabelled(JCLabeledStatement tree) {
571 ListBuffer<PendingExit> prevPendingExits = pendingExits;
572 pendingExits = new ListBuffer<PendingExit>();
573 scanStat(tree.body);
574 alive |= resolveBreaks(tree, prevPendingExits);
575 }
577 public void visitSwitch(JCSwitch tree) {
578 ListBuffer<PendingExit> prevPendingExits = pendingExits;
579 pendingExits = new ListBuffer<PendingExit>();
580 scan(tree.selector);
581 boolean hasDefault = false;
582 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
583 alive = true;
584 JCCase c = l.head;
585 if (c.pat == null)
586 hasDefault = true;
587 else
588 scan(c.pat);
589 scanStats(c.stats);
590 // Warn about fall-through if lint switch fallthrough enabled.
591 if (alive &&
592 lint.isEnabled(Lint.LintCategory.FALLTHROUGH) &&
593 c.stats.nonEmpty() && l.tail.nonEmpty())
594 log.warning(Lint.LintCategory.FALLTHROUGH,
595 l.tail.head.pos(),
596 "possible.fall-through.into.case");
597 }
598 if (!hasDefault) {
599 alive = true;
600 }
601 alive |= resolveBreaks(tree, prevPendingExits);
602 }
604 public void visitTry(JCTry tree) {
605 ListBuffer<PendingExit> prevPendingExits = pendingExits;
606 pendingExits = new ListBuffer<PendingExit>();
607 for (JCTree resource : tree.resources) {
608 if (resource instanceof JCVariableDecl) {
609 JCVariableDecl vdecl = (JCVariableDecl) resource;
610 visitVarDef(vdecl);
611 } else if (resource instanceof JCExpression) {
612 scan((JCExpression) resource);
613 } else {
614 throw new AssertionError(tree); // parser error
615 }
616 }
618 scanStat(tree.body);
619 boolean aliveEnd = alive;
621 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
622 alive = true;
623 JCVariableDecl param = l.head.param;
624 scan(param);
625 scanStat(l.head.body);
626 aliveEnd |= alive;
627 }
628 if (tree.finalizer != null) {
629 ListBuffer<PendingExit> exits = pendingExits;
630 pendingExits = prevPendingExits;
631 alive = true;
632 scanStat(tree.finalizer);
633 tree.finallyCanCompleteNormally = alive;
634 if (!alive) {
635 if (lint.isEnabled(Lint.LintCategory.FINALLY)) {
636 log.warning(Lint.LintCategory.FINALLY,
637 TreeInfo.diagEndPos(tree.finalizer),
638 "finally.cannot.complete");
639 }
640 } else {
641 while (exits.nonEmpty()) {
642 pendingExits.append(exits.next());
643 }
644 alive = aliveEnd;
645 }
646 } else {
647 alive = aliveEnd;
648 ListBuffer<PendingExit> exits = pendingExits;
649 pendingExits = prevPendingExits;
650 while (exits.nonEmpty()) pendingExits.append(exits.next());
651 }
652 }
654 @Override
655 public void visitIf(JCIf tree) {
656 scan(tree.cond);
657 scanStat(tree.thenpart);
658 if (tree.elsepart != null) {
659 boolean aliveAfterThen = alive;
660 alive = true;
661 scanStat(tree.elsepart);
662 alive = alive | aliveAfterThen;
663 } else {
664 alive = true;
665 }
666 }
668 public void visitBreak(JCBreak tree) {
669 recordExit(tree, new PendingExit(tree));
670 }
672 public void visitContinue(JCContinue tree) {
673 recordExit(tree, new PendingExit(tree));
674 }
676 public void visitReturn(JCReturn tree) {
677 scan(tree.expr);
678 recordExit(tree, new PendingExit(tree));
679 }
681 public void visitThrow(JCThrow tree) {
682 scan(tree.expr);
683 markDead();
684 }
686 public void visitApply(JCMethodInvocation tree) {
687 scan(tree.meth);
688 scan(tree.args);
689 }
691 public void visitNewClass(JCNewClass tree) {
692 scan(tree.encl);
693 scan(tree.args);
694 if (tree.def != null) {
695 scan(tree.def);
696 }
697 }
699 @Override
700 public void visitLambda(JCLambda tree) {
701 if (tree.type != null &&
702 tree.type.isErroneous()) {
703 return;
704 }
706 ListBuffer<PendingExit> prevPending = pendingExits;
707 boolean prevAlive = alive;
708 try {
709 pendingExits = ListBuffer.lb();
710 alive = true;
711 scanStat(tree.body);
712 tree.canCompleteNormally = alive;
713 }
714 finally {
715 pendingExits = prevPending;
716 alive = prevAlive;
717 }
718 }
720 public void visitTopLevel(JCCompilationUnit tree) {
721 // Do nothing for TopLevel since each class is visited individually
722 }
724 /**************************************************************************
725 * main method
726 *************************************************************************/
728 /** Perform definite assignment/unassignment analysis on a tree.
729 */
730 public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
731 analyzeTree(env, env.tree, make);
732 }
733 public void analyzeTree(Env<AttrContext> env, JCTree tree, TreeMaker make) {
734 try {
735 attrEnv = env;
736 Flow.this.make = make;
737 pendingExits = new ListBuffer<PendingExit>();
738 alive = true;
739 scan(tree);
740 } finally {
741 pendingExits = null;
742 Flow.this.make = null;
743 }
744 }
745 }
747 /**
748 * This pass implements the second step of the dataflow analysis, namely
749 * the exception analysis. This is to ensure that every checked exception that is
750 * thrown is declared or caught. The analyzer uses some info that has been set by
751 * the liveliness analyzer.
752 */
753 class FlowAnalyzer extends BaseAnalyzer<FlowAnalyzer.FlowPendingExit> {
755 /** A flag that indicates whether the last statement could
756 * complete normally.
757 */
758 HashMap<Symbol, List<Type>> preciseRethrowTypes;
760 /** The current class being defined.
761 */
762 JCClassDecl classDef;
764 /** The list of possibly thrown declarable exceptions.
765 */
766 List<Type> thrown;
768 /** The list of exceptions that are either caught or declared to be
769 * thrown.
770 */
771 List<Type> caught;
773 class FlowPendingExit extends BaseAnalyzer.PendingExit {
775 Type thrown;
777 FlowPendingExit(JCTree tree, Type thrown) {
778 super(tree);
779 this.thrown = thrown;
780 }
781 }
783 @Override
784 void markDead() {
785 //do nothing
786 }
788 /*-------------------- Exceptions ----------------------*/
790 /** Complain that pending exceptions are not caught.
791 */
792 void errorUncaught() {
793 for (FlowPendingExit exit = pendingExits.next();
794 exit != null;
795 exit = pendingExits.next()) {
796 if (classDef != null &&
797 classDef.pos == exit.tree.pos) {
798 log.error(exit.tree.pos(),
799 "unreported.exception.default.constructor",
800 exit.thrown);
801 } else if (exit.tree.hasTag(VARDEF) &&
802 ((JCVariableDecl)exit.tree).sym.isResourceVariable()) {
803 log.error(exit.tree.pos(),
804 "unreported.exception.implicit.close",
805 exit.thrown,
806 ((JCVariableDecl)exit.tree).sym.name);
807 } else {
808 log.error(exit.tree.pos(),
809 "unreported.exception.need.to.catch.or.throw",
810 exit.thrown);
811 }
812 }
813 }
815 /** Record that exception is potentially thrown and check that it
816 * is caught.
817 */
818 void markThrown(JCTree tree, Type exc) {
819 if (!chk.isUnchecked(tree.pos(), exc)) {
820 if (!chk.isHandled(exc, caught)) {
821 pendingExits.append(new FlowPendingExit(tree, exc));
822 }
823 thrown = chk.incl(exc, thrown);
824 }
825 }
827 /*************************************************************************
828 * Visitor methods for statements and definitions
829 *************************************************************************/
831 /* ------------ Visitor methods for various sorts of trees -------------*/
833 public void visitClassDef(JCClassDecl tree) {
834 if (tree.sym == null) return;
836 JCClassDecl classDefPrev = classDef;
837 List<Type> thrownPrev = thrown;
838 List<Type> caughtPrev = caught;
839 ListBuffer<FlowPendingExit> pendingExitsPrev = pendingExits;
840 Lint lintPrev = lint;
842 pendingExits = new ListBuffer<FlowPendingExit>();
843 if (tree.name != names.empty) {
844 caught = List.nil();
845 }
846 classDef = tree;
847 thrown = List.nil();
848 lint = lint.augment(tree.sym);
850 try {
851 // process all the static initializers
852 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
853 if (!l.head.hasTag(METHODDEF) &&
854 (TreeInfo.flags(l.head) & STATIC) != 0) {
855 scan(l.head);
856 errorUncaught();
857 }
858 }
860 // add intersection of all thrown clauses of initial constructors
861 // to set of caught exceptions, unless class is anonymous.
862 if (tree.name != names.empty) {
863 boolean firstConstructor = true;
864 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
865 if (TreeInfo.isInitialConstructor(l.head)) {
866 List<Type> mthrown =
867 ((JCMethodDecl) l.head).sym.type.getThrownTypes();
868 if (firstConstructor) {
869 caught = mthrown;
870 firstConstructor = false;
871 } else {
872 caught = chk.intersect(mthrown, caught);
873 }
874 }
875 }
876 }
878 // process all the instance initializers
879 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
880 if (!l.head.hasTag(METHODDEF) &&
881 (TreeInfo.flags(l.head) & STATIC) == 0) {
882 scan(l.head);
883 errorUncaught();
884 }
885 }
887 // in an anonymous class, add the set of thrown exceptions to
888 // the throws clause of the synthetic constructor and propagate
889 // outwards.
890 // Changing the throws clause on the fly is okay here because
891 // the anonymous constructor can't be invoked anywhere else,
892 // and its type hasn't been cached.
893 if (tree.name == names.empty) {
894 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
895 if (TreeInfo.isInitialConstructor(l.head)) {
896 JCMethodDecl mdef = (JCMethodDecl)l.head;
897 mdef.thrown = make.Types(thrown);
898 mdef.sym.type = types.createMethodTypeWithThrown(mdef.sym.type, thrown);
899 }
900 }
901 thrownPrev = chk.union(thrown, thrownPrev);
902 }
904 // process all the methods
905 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
906 if (l.head.hasTag(METHODDEF)) {
907 scan(l.head);
908 errorUncaught();
909 }
910 }
912 thrown = thrownPrev;
913 } finally {
914 pendingExits = pendingExitsPrev;
915 caught = caughtPrev;
916 classDef = classDefPrev;
917 lint = lintPrev;
918 }
919 }
921 public void visitMethodDef(JCMethodDecl tree) {
922 if (tree.body == null) return;
924 List<Type> caughtPrev = caught;
925 List<Type> mthrown = tree.sym.type.getThrownTypes();
926 Lint lintPrev = lint;
928 lint = lint.augment(tree.sym);
930 Assert.check(pendingExits.isEmpty());
932 try {
933 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
934 JCVariableDecl def = l.head;
935 scan(def);
936 }
937 if (TreeInfo.isInitialConstructor(tree))
938 caught = chk.union(caught, mthrown);
939 else if ((tree.sym.flags() & (BLOCK | STATIC)) != BLOCK)
940 caught = mthrown;
941 // else we are in an instance initializer block;
942 // leave caught unchanged.
944 scan(tree.body);
946 List<FlowPendingExit> exits = pendingExits.toList();
947 pendingExits = new ListBuffer<FlowPendingExit>();
948 while (exits.nonEmpty()) {
949 FlowPendingExit exit = exits.head;
950 exits = exits.tail;
951 if (exit.thrown == null) {
952 Assert.check(exit.tree.hasTag(RETURN));
953 } else {
954 // uncaught throws will be reported later
955 pendingExits.append(exit);
956 }
957 }
958 } finally {
959 caught = caughtPrev;
960 lint = lintPrev;
961 }
962 }
964 public void visitVarDef(JCVariableDecl tree) {
965 if (tree.init != null) {
966 Lint lintPrev = lint;
967 lint = lint.augment(tree.sym);
968 try{
969 scan(tree.init);
970 } finally {
971 lint = lintPrev;
972 }
973 }
974 }
976 public void visitBlock(JCBlock tree) {
977 scan(tree.stats);
978 }
980 public void visitDoLoop(JCDoWhileLoop tree) {
981 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
982 pendingExits = new ListBuffer<FlowPendingExit>();
983 scan(tree.body);
984 resolveContinues(tree);
985 scan(tree.cond);
986 resolveBreaks(tree, prevPendingExits);
987 }
989 public void visitWhileLoop(JCWhileLoop tree) {
990 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
991 pendingExits = new ListBuffer<FlowPendingExit>();
992 scan(tree.cond);
993 scan(tree.body);
994 resolveContinues(tree);
995 resolveBreaks(tree, prevPendingExits);
996 }
998 public void visitForLoop(JCForLoop tree) {
999 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
1000 scan(tree.init);
1001 pendingExits = new ListBuffer<FlowPendingExit>();
1002 if (tree.cond != null) {
1003 scan(tree.cond);
1004 }
1005 scan(tree.body);
1006 resolveContinues(tree);
1007 scan(tree.step);
1008 resolveBreaks(tree, prevPendingExits);
1009 }
1011 public void visitForeachLoop(JCEnhancedForLoop tree) {
1012 visitVarDef(tree.var);
1013 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
1014 scan(tree.expr);
1015 pendingExits = new ListBuffer<FlowPendingExit>();
1016 scan(tree.body);
1017 resolveContinues(tree);
1018 resolveBreaks(tree, prevPendingExits);
1019 }
1021 public void visitLabelled(JCLabeledStatement tree) {
1022 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
1023 pendingExits = new ListBuffer<FlowPendingExit>();
1024 scan(tree.body);
1025 resolveBreaks(tree, prevPendingExits);
1026 }
1028 public void visitSwitch(JCSwitch tree) {
1029 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
1030 pendingExits = new ListBuffer<FlowPendingExit>();
1031 scan(tree.selector);
1032 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
1033 JCCase c = l.head;
1034 if (c.pat != null) {
1035 scan(c.pat);
1036 }
1037 scan(c.stats);
1038 }
1039 resolveBreaks(tree, prevPendingExits);
1040 }
1042 public void visitTry(JCTry tree) {
1043 List<Type> caughtPrev = caught;
1044 List<Type> thrownPrev = thrown;
1045 thrown = List.nil();
1046 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1047 List<JCExpression> subClauses = TreeInfo.isMultiCatch(l.head) ?
1048 ((JCTypeUnion)l.head.param.vartype).alternatives :
1049 List.of(l.head.param.vartype);
1050 for (JCExpression ct : subClauses) {
1051 caught = chk.incl(ct.type, caught);
1052 }
1053 }
1055 ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
1056 pendingExits = new ListBuffer<FlowPendingExit>();
1057 for (JCTree resource : tree.resources) {
1058 if (resource instanceof JCVariableDecl) {
1059 JCVariableDecl vdecl = (JCVariableDecl) resource;
1060 visitVarDef(vdecl);
1061 } else if (resource instanceof JCExpression) {
1062 scan((JCExpression) resource);
1063 } else {
1064 throw new AssertionError(tree); // parser error
1065 }
1066 }
1067 for (JCTree resource : tree.resources) {
1068 List<Type> closeableSupertypes = resource.type.isCompound() ?
1069 types.interfaces(resource.type).prepend(types.supertype(resource.type)) :
1070 List.of(resource.type);
1071 for (Type sup : closeableSupertypes) {
1072 if (types.asSuper(sup, syms.autoCloseableType.tsym) != null) {
1073 Symbol closeMethod = rs.resolveQualifiedMethod(tree,
1074 attrEnv,
1075 sup,
1076 names.close,
1077 List.<Type>nil(),
1078 List.<Type>nil());
1079 Type mt = types.memberType(resource.type, closeMethod);
1080 if (closeMethod.kind == MTH) {
1081 for (Type t : mt.getThrownTypes()) {
1082 markThrown(resource, t);
1083 }
1084 }
1085 }
1086 }
1087 }
1088 scan(tree.body);
1089 List<Type> thrownInTry = allowImprovedCatchAnalysis ?
1090 chk.union(thrown, List.of(syms.runtimeExceptionType, syms.errorType)) :
1091 thrown;
1092 thrown = thrownPrev;
1093 caught = caughtPrev;
1095 List<Type> caughtInTry = List.nil();
1096 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1097 JCVariableDecl param = l.head.param;
1098 List<JCExpression> subClauses = TreeInfo.isMultiCatch(l.head) ?
1099 ((JCTypeUnion)l.head.param.vartype).alternatives :
1100 List.of(l.head.param.vartype);
1101 List<Type> ctypes = List.nil();
1102 List<Type> rethrownTypes = chk.diff(thrownInTry, caughtInTry);
1103 for (JCExpression ct : subClauses) {
1104 Type exc = ct.type;
1105 if (exc != syms.unknownType) {
1106 ctypes = ctypes.append(exc);
1107 if (types.isSameType(exc, syms.objectType))
1108 continue;
1109 checkCaughtType(l.head.pos(), exc, thrownInTry, caughtInTry);
1110 caughtInTry = chk.incl(exc, caughtInTry);
1111 }
1112 }
1113 scan(param);
1114 preciseRethrowTypes.put(param.sym, chk.intersect(ctypes, rethrownTypes));
1115 scan(l.head.body);
1116 preciseRethrowTypes.remove(param.sym);
1117 }
1118 if (tree.finalizer != null) {
1119 List<Type> savedThrown = thrown;
1120 thrown = List.nil();
1121 ListBuffer<FlowPendingExit> exits = pendingExits;
1122 pendingExits = prevPendingExits;
1123 scan(tree.finalizer);
1124 if (!tree.finallyCanCompleteNormally) {
1125 // discard exits and exceptions from try and finally
1126 thrown = chk.union(thrown, thrownPrev);
1127 } else {
1128 thrown = chk.union(thrown, chk.diff(thrownInTry, caughtInTry));
1129 thrown = chk.union(thrown, savedThrown);
1130 // FIX: this doesn't preserve source order of exits in catch
1131 // versus finally!
1132 while (exits.nonEmpty()) {
1133 pendingExits.append(exits.next());
1134 }
1135 }
1136 } else {
1137 thrown = chk.union(thrown, chk.diff(thrownInTry, caughtInTry));
1138 ListBuffer<FlowPendingExit> exits = pendingExits;
1139 pendingExits = prevPendingExits;
1140 while (exits.nonEmpty()) pendingExits.append(exits.next());
1141 }
1142 }
1144 @Override
1145 public void visitIf(JCIf tree) {
1146 scan(tree.cond);
1147 scan(tree.thenpart);
1148 if (tree.elsepart != null) {
1149 scan(tree.elsepart);
1150 }
1151 }
1153 void checkCaughtType(DiagnosticPosition pos, Type exc, List<Type> thrownInTry, List<Type> caughtInTry) {
1154 if (chk.subset(exc, caughtInTry)) {
1155 log.error(pos, "except.already.caught", exc);
1156 } else if (!chk.isUnchecked(pos, exc) &&
1157 !isExceptionOrThrowable(exc) &&
1158 !chk.intersects(exc, thrownInTry)) {
1159 log.error(pos, "except.never.thrown.in.try", exc);
1160 } else if (allowImprovedCatchAnalysis) {
1161 List<Type> catchableThrownTypes = chk.intersect(List.of(exc), thrownInTry);
1162 // 'catchableThrownTypes' cannnot possibly be empty - if 'exc' was an
1163 // unchecked exception, the result list would not be empty, as the augmented
1164 // thrown set includes { RuntimeException, Error }; if 'exc' was a checked
1165 // exception, that would have been covered in the branch above
1166 if (chk.diff(catchableThrownTypes, caughtInTry).isEmpty() &&
1167 !isExceptionOrThrowable(exc)) {
1168 String key = catchableThrownTypes.length() == 1 ?
1169 "unreachable.catch" :
1170 "unreachable.catch.1";
1171 log.warning(pos, key, catchableThrownTypes);
1172 }
1173 }
1174 }
1175 //where
1176 private boolean isExceptionOrThrowable(Type exc) {
1177 return exc.tsym == syms.throwableType.tsym ||
1178 exc.tsym == syms.exceptionType.tsym;
1179 }
1181 public void visitBreak(JCBreak tree) {
1182 recordExit(tree, new FlowPendingExit(tree, null));
1183 }
1185 public void visitContinue(JCContinue tree) {
1186 recordExit(tree, new FlowPendingExit(tree, null));
1187 }
1189 public void visitReturn(JCReturn tree) {
1190 scan(tree.expr);
1191 recordExit(tree, new FlowPendingExit(tree, null));
1192 }
1194 public void visitThrow(JCThrow tree) {
1195 scan(tree.expr);
1196 Symbol sym = TreeInfo.symbol(tree.expr);
1197 if (sym != null &&
1198 sym.kind == VAR &&
1199 (sym.flags() & (FINAL | EFFECTIVELY_FINAL)) != 0 &&
1200 preciseRethrowTypes.get(sym) != null &&
1201 allowImprovedRethrowAnalysis) {
1202 for (Type t : preciseRethrowTypes.get(sym)) {
1203 markThrown(tree, t);
1204 }
1205 }
1206 else {
1207 markThrown(tree, tree.expr.type);
1208 }
1209 markDead();
1210 }
1212 public void visitApply(JCMethodInvocation tree) {
1213 scan(tree.meth);
1214 scan(tree.args);
1215 for (List<Type> l = tree.meth.type.getThrownTypes(); l.nonEmpty(); l = l.tail)
1216 markThrown(tree, l.head);
1217 }
1219 public void visitNewClass(JCNewClass tree) {
1220 scan(tree.encl);
1221 scan(tree.args);
1222 // scan(tree.def);
1223 for (List<Type> l = tree.constructorType.getThrownTypes();
1224 l.nonEmpty();
1225 l = l.tail) {
1226 markThrown(tree, l.head);
1227 }
1228 List<Type> caughtPrev = caught;
1229 try {
1230 // If the new class expression defines an anonymous class,
1231 // analysis of the anonymous constructor may encounter thrown
1232 // types which are unsubstituted type variables.
1233 // However, since the constructor's actual thrown types have
1234 // already been marked as thrown, it is safe to simply include
1235 // each of the constructor's formal thrown types in the set of
1236 // 'caught/declared to be thrown' types, for the duration of
1237 // the class def analysis.
1238 if (tree.def != null)
1239 for (List<Type> l = tree.constructor.type.getThrownTypes();
1240 l.nonEmpty();
1241 l = l.tail) {
1242 caught = chk.incl(l.head, caught);
1243 }
1244 scan(tree.def);
1245 }
1246 finally {
1247 caught = caughtPrev;
1248 }
1249 }
1251 @Override
1252 public void visitLambda(JCLambda tree) {
1253 if (tree.type != null &&
1254 tree.type.isErroneous()) {
1255 return;
1256 }
1257 List<Type> prevCaught = caught;
1258 List<Type> prevThrown = thrown;
1259 ListBuffer<FlowPendingExit> prevPending = pendingExits;
1260 try {
1261 pendingExits = ListBuffer.lb();
1262 caught = List.of(syms.throwableType); //inhibit exception checking
1263 thrown = List.nil();
1264 scan(tree.body);
1265 tree.inferredThrownTypes = thrown;
1266 }
1267 finally {
1268 pendingExits = prevPending;
1269 caught = prevCaught;
1270 thrown = prevThrown;
1271 }
1272 }
1274 public void visitTopLevel(JCCompilationUnit tree) {
1275 // Do nothing for TopLevel since each class is visited individually
1276 }
1278 /**************************************************************************
1279 * main method
1280 *************************************************************************/
1282 /** Perform definite assignment/unassignment analysis on a tree.
1283 */
1284 public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
1285 analyzeTree(env, env.tree, make);
1286 }
1287 public void analyzeTree(Env<AttrContext> env, JCTree tree, TreeMaker make) {
1288 try {
1289 attrEnv = env;
1290 Flow.this.make = make;
1291 pendingExits = new ListBuffer<FlowPendingExit>();
1292 preciseRethrowTypes = new HashMap<Symbol, List<Type>>();
1293 this.thrown = this.caught = null;
1294 this.classDef = null;
1295 scan(tree);
1296 } finally {
1297 pendingExits = null;
1298 Flow.this.make = null;
1299 this.thrown = this.caught = null;
1300 this.classDef = null;
1301 }
1302 }
1303 }
1305 /**
1306 * This pass implements (i) definite assignment analysis, which ensures that
1307 * each variable is assigned when used and (ii) definite unassignment analysis,
1308 * which ensures that no final variable is assigned more than once. This visitor
1309 * depends on the results of the liveliness analyzer. This pass is also used to mark
1310 * effectively-final local variables/parameters.
1311 */
1312 class AssignAnalyzer extends BaseAnalyzer<AssignAnalyzer.AssignPendingExit> {
1314 /** The set of definitely assigned variables.
1315 */
1316 final Bits inits;
1318 /** The set of definitely unassigned variables.
1319 */
1320 final Bits uninits;
1322 /** The set of variables that are definitely unassigned everywhere
1323 * in current try block. This variable is maintained lazily; it is
1324 * updated only when something gets removed from uninits,
1325 * typically by being assigned in reachable code. To obtain the
1326 * correct set of variables which are definitely unassigned
1327 * anywhere in current try block, intersect uninitsTry and
1328 * uninits.
1329 */
1330 final Bits uninitsTry;
1332 /** When analyzing a condition, inits and uninits are null.
1333 * Instead we have:
1334 */
1335 final Bits initsWhenTrue;
1336 final Bits initsWhenFalse;
1337 final Bits uninitsWhenTrue;
1338 final Bits uninitsWhenFalse;
1340 /** A mapping from addresses to variable symbols.
1341 */
1342 VarSymbol[] vars;
1344 /** The current class being defined.
1345 */
1346 JCClassDecl classDef;
1348 /** The first variable sequence number in this class definition.
1349 */
1350 int firstadr;
1352 /** The next available variable sequence number.
1353 */
1354 int nextadr;
1356 /** The first variable sequence number in a block that can return.
1357 */
1358 int returnadr;
1360 /** The list of unreferenced automatic resources.
1361 */
1362 Scope unrefdResources;
1364 /** Set when processing a loop body the second time for DU analysis. */
1365 FlowKind flowKind = FlowKind.NORMAL;
1367 /** The starting position of the analysed tree */
1368 int startPos;
1370 AssignAnalyzer() {
1371 inits = new Bits();
1372 uninits = new Bits();
1373 uninitsTry = new Bits();
1374 initsWhenTrue = new Bits(true);
1375 initsWhenFalse = new Bits(true);
1376 uninitsWhenTrue = new Bits(true);
1377 uninitsWhenFalse = new Bits(true);
1378 }
1380 class AssignPendingExit extends BaseAnalyzer.PendingExit {
1382 final Bits exit_inits = new Bits(true);
1383 final Bits exit_uninits = new Bits(true);
1385 AssignPendingExit(JCTree tree, final Bits inits, final Bits uninits) {
1386 super(tree);
1387 this.exit_inits.assign(inits);
1388 this.exit_uninits.assign(uninits);
1389 }
1391 void resolveJump() {
1392 inits.andSet(exit_inits);
1393 uninits.andSet(exit_uninits);
1394 }
1395 }
1397 @Override
1398 void markDead() {
1399 inits.inclRange(returnadr, nextadr);
1400 uninits.inclRange(returnadr, nextadr);
1401 }
1403 /*-------------- Processing variables ----------------------*/
1405 /** Do we need to track init/uninit state of this symbol?
1406 * I.e. is symbol either a local or a blank final variable?
1407 */
1408 boolean trackable(VarSymbol sym) {
1409 return
1410 sym.pos >= startPos &&
1411 ((sym.owner.kind == MTH ||
1412 ((sym.flags() & (FINAL | HASINIT | PARAMETER)) == FINAL &&
1413 classDef.sym.isEnclosedBy((ClassSymbol)sym.owner))));
1414 }
1416 /** Initialize new trackable variable by setting its address field
1417 * to the next available sequence number and entering it under that
1418 * index into the vars array.
1419 */
1420 void newVar(VarSymbol sym) {
1421 vars = ArrayUtils.ensureCapacity(vars, nextadr);
1422 if ((sym.flags() & FINAL) == 0) {
1423 sym.flags_field |= EFFECTIVELY_FINAL;
1424 }
1425 sym.adr = nextadr;
1426 vars[nextadr] = sym;
1427 inits.excl(nextadr);
1428 uninits.incl(nextadr);
1429 nextadr++;
1430 }
1432 /** Record an initialization of a trackable variable.
1433 */
1434 void letInit(DiagnosticPosition pos, VarSymbol sym) {
1435 if (sym.adr >= firstadr && trackable(sym)) {
1436 if ((sym.flags() & EFFECTIVELY_FINAL) != 0) {
1437 if (!uninits.isMember(sym.adr)) {
1438 //assignment targeting an effectively final variable
1439 //makes the variable lose its status of effectively final
1440 //if the variable is _not_ definitively unassigned
1441 sym.flags_field &= ~EFFECTIVELY_FINAL;
1442 } else {
1443 uninit(sym);
1444 }
1445 }
1446 else if ((sym.flags() & FINAL) != 0) {
1447 if ((sym.flags() & PARAMETER) != 0) {
1448 if ((sym.flags() & UNION) != 0) { //multi-catch parameter
1449 log.error(pos, "multicatch.parameter.may.not.be.assigned",
1450 sym);
1451 }
1452 else {
1453 log.error(pos, "final.parameter.may.not.be.assigned",
1454 sym);
1455 }
1456 } else if (!uninits.isMember(sym.adr)) {
1457 log.error(pos, flowKind.errKey, sym);
1458 } else {
1459 uninit(sym);
1460 }
1461 }
1462 inits.incl(sym.adr);
1463 } else if ((sym.flags() & FINAL) != 0) {
1464 log.error(pos, "var.might.already.be.assigned", sym);
1465 }
1466 }
1467 //where
1468 void uninit(VarSymbol sym) {
1469 if (!inits.isMember(sym.adr)) {
1470 // reachable assignment
1471 uninits.excl(sym.adr);
1472 uninitsTry.excl(sym.adr);
1473 } else {
1474 //log.rawWarning(pos, "unreachable assignment");//DEBUG
1475 uninits.excl(sym.adr);
1476 }
1477 }
1479 /** If tree is either a simple name or of the form this.name or
1480 * C.this.name, and tree represents a trackable variable,
1481 * record an initialization of the variable.
1482 */
1483 void letInit(JCTree tree) {
1484 tree = TreeInfo.skipParens(tree);
1485 if (tree.hasTag(IDENT) || tree.hasTag(SELECT)) {
1486 Symbol sym = TreeInfo.symbol(tree);
1487 if (sym.kind == VAR) {
1488 letInit(tree.pos(), (VarSymbol)sym);
1489 }
1490 }
1491 }
1493 /** Check that trackable variable is initialized.
1494 */
1495 void checkInit(DiagnosticPosition pos, VarSymbol sym) {
1496 if ((sym.adr >= firstadr || sym.owner.kind != TYP) &&
1497 trackable(sym) &&
1498 !inits.isMember(sym.adr)) {
1499 log.error(pos, "var.might.not.have.been.initialized",
1500 sym);
1501 inits.incl(sym.adr);
1502 }
1503 }
1505 /** Split (duplicate) inits/uninits into WhenTrue/WhenFalse sets
1506 */
1507 void split(boolean setToNull) {
1508 initsWhenFalse.assign(inits);
1509 uninitsWhenFalse.assign(uninits);
1510 initsWhenTrue.assign(inits);
1511 uninitsWhenTrue.assign(uninits);
1512 if (setToNull) {
1513 resetBits(inits, uninits);
1514 }
1515 }
1517 /** Merge (intersect) inits/uninits from WhenTrue/WhenFalse sets.
1518 */
1519 void merge() {
1520 inits.assign(initsWhenFalse.andSet(initsWhenTrue));
1521 uninits.assign(uninitsWhenFalse.andSet(uninitsWhenTrue));
1522 }
1524 /* ************************************************************************
1525 * Visitor methods for statements and definitions
1526 *************************************************************************/
1528 /** Analyze an expression. Make sure to set (un)inits rather than
1529 * (un)initsWhenTrue(WhenFalse) on exit.
1530 */
1531 void scanExpr(JCTree tree) {
1532 if (tree != null) {
1533 scan(tree);
1534 if (inits.isReset()) merge();
1535 }
1536 }
1538 /** Analyze a list of expressions.
1539 */
1540 void scanExprs(List<? extends JCExpression> trees) {
1541 if (trees != null)
1542 for (List<? extends JCExpression> l = trees; l.nonEmpty(); l = l.tail)
1543 scanExpr(l.head);
1544 }
1546 /** Analyze a condition. Make sure to set (un)initsWhenTrue(WhenFalse)
1547 * rather than (un)inits on exit.
1548 */
1549 void scanCond(JCTree tree) {
1550 if (tree.type.isFalse()) {
1551 if (inits.isReset()) merge();
1552 initsWhenTrue.assign(inits);
1553 initsWhenTrue.inclRange(firstadr, nextadr);
1554 uninitsWhenTrue.assign(uninits);
1555 uninitsWhenTrue.inclRange(firstadr, nextadr);
1556 initsWhenFalse.assign(inits);
1557 uninitsWhenFalse.assign(uninits);
1558 } else if (tree.type.isTrue()) {
1559 if (inits.isReset()) merge();
1560 initsWhenFalse.assign(inits);
1561 initsWhenFalse.inclRange(firstadr, nextadr);
1562 uninitsWhenFalse.assign(uninits);
1563 uninitsWhenFalse.inclRange(firstadr, nextadr);
1564 initsWhenTrue.assign(inits);
1565 uninitsWhenTrue.assign(uninits);
1566 } else {
1567 scan(tree);
1568 if (!inits.isReset())
1569 split(tree.type != syms.unknownType);
1570 }
1571 if (tree.type != syms.unknownType) {
1572 resetBits(inits, uninits);
1573 }
1574 }
1576 /* ------------ Visitor methods for various sorts of trees -------------*/
1578 public void visitClassDef(JCClassDecl tree) {
1579 if (tree.sym == null) return;
1581 JCClassDecl classDefPrev = classDef;
1582 int firstadrPrev = firstadr;
1583 int nextadrPrev = nextadr;
1584 ListBuffer<AssignPendingExit> pendingExitsPrev = pendingExits;
1585 Lint lintPrev = lint;
1587 pendingExits = new ListBuffer<AssignPendingExit>();
1588 if (tree.name != names.empty) {
1589 firstadr = nextadr;
1590 }
1591 classDef = tree;
1592 lint = lint.augment(tree.sym);
1594 try {
1595 // define all the static fields
1596 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1597 if (l.head.hasTag(VARDEF)) {
1598 JCVariableDecl def = (JCVariableDecl)l.head;
1599 if ((def.mods.flags & STATIC) != 0) {
1600 VarSymbol sym = def.sym;
1601 if (trackable(sym))
1602 newVar(sym);
1603 }
1604 }
1605 }
1607 // process all the static initializers
1608 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1609 if (!l.head.hasTag(METHODDEF) &&
1610 (TreeInfo.flags(l.head) & STATIC) != 0) {
1611 scan(l.head);
1612 }
1613 }
1615 // define all the instance fields
1616 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1617 if (l.head.hasTag(VARDEF)) {
1618 JCVariableDecl def = (JCVariableDecl)l.head;
1619 if ((def.mods.flags & STATIC) == 0) {
1620 VarSymbol sym = def.sym;
1621 if (trackable(sym))
1622 newVar(sym);
1623 }
1624 }
1625 }
1627 // process all the instance initializers
1628 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1629 if (!l.head.hasTag(METHODDEF) &&
1630 (TreeInfo.flags(l.head) & STATIC) == 0) {
1631 scan(l.head);
1632 }
1633 }
1635 // process all the methods
1636 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1637 if (l.head.hasTag(METHODDEF)) {
1638 scan(l.head);
1639 }
1640 }
1641 } finally {
1642 pendingExits = pendingExitsPrev;
1643 nextadr = nextadrPrev;
1644 firstadr = firstadrPrev;
1645 classDef = classDefPrev;
1646 lint = lintPrev;
1647 }
1648 }
1650 public void visitMethodDef(JCMethodDecl tree) {
1651 if (tree.body == null) return;
1653 final Bits initsPrev = new Bits(inits);
1654 final Bits uninitsPrev = new Bits(uninits);
1655 int nextadrPrev = nextadr;
1656 int firstadrPrev = firstadr;
1657 int returnadrPrev = returnadr;
1658 Lint lintPrev = lint;
1660 lint = lint.augment(tree.sym);
1662 Assert.check(pendingExits.isEmpty());
1664 try {
1665 boolean isInitialConstructor =
1666 TreeInfo.isInitialConstructor(tree);
1668 if (!isInitialConstructor)
1669 firstadr = nextadr;
1670 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1671 JCVariableDecl def = l.head;
1672 scan(def);
1673 inits.incl(def.sym.adr);
1674 uninits.excl(def.sym.adr);
1675 }
1676 // else we are in an instance initializer block;
1677 // leave caught unchanged.
1678 scan(tree.body);
1680 if (isInitialConstructor) {
1681 for (int i = firstadr; i < nextadr; i++)
1682 if (vars[i].owner == classDef.sym)
1683 checkInit(TreeInfo.diagEndPos(tree.body), vars[i]);
1684 }
1685 List<AssignPendingExit> exits = pendingExits.toList();
1686 pendingExits = new ListBuffer<AssignPendingExit>();
1687 while (exits.nonEmpty()) {
1688 AssignPendingExit exit = exits.head;
1689 exits = exits.tail;
1690 Assert.check(exit.tree.hasTag(RETURN), exit.tree);
1691 if (isInitialConstructor) {
1692 inits.assign(exit.exit_inits);
1693 for (int i = firstadr; i < nextadr; i++)
1694 checkInit(exit.tree.pos(), vars[i]);
1695 }
1696 }
1697 } finally {
1698 inits.assign(initsPrev);
1699 uninits.assign(uninitsPrev);
1700 nextadr = nextadrPrev;
1701 firstadr = firstadrPrev;
1702 returnadr = returnadrPrev;
1703 lint = lintPrev;
1704 }
1705 }
1707 public void visitVarDef(JCVariableDecl tree) {
1708 boolean track = trackable(tree.sym);
1709 if (track && tree.sym.owner.kind == MTH) newVar(tree.sym);
1710 if (tree.init != null) {
1711 Lint lintPrev = lint;
1712 lint = lint.augment(tree.sym);
1713 try{
1714 scanExpr(tree.init);
1715 if (track) letInit(tree.pos(), tree.sym);
1716 } finally {
1717 lint = lintPrev;
1718 }
1719 }
1720 }
1722 public void visitBlock(JCBlock tree) {
1723 int nextadrPrev = nextadr;
1724 scan(tree.stats);
1725 nextadr = nextadrPrev;
1726 }
1728 public void visitDoLoop(JCDoWhileLoop tree) {
1729 ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
1730 FlowKind prevFlowKind = flowKind;
1731 flowKind = FlowKind.NORMAL;
1732 final Bits initsSkip = new Bits(true);
1733 final Bits uninitsSkip = new Bits(true);
1734 pendingExits = new ListBuffer<AssignPendingExit>();
1735 int prevErrors = log.nerrors;
1736 do {
1737 final Bits uninitsEntry = new Bits(uninits);
1738 uninitsEntry.excludeFrom(nextadr);
1739 scan(tree.body);
1740 resolveContinues(tree);
1741 scanCond(tree.cond);
1742 if (!flowKind.isFinal()) {
1743 initsSkip.assign(initsWhenFalse);
1744 uninitsSkip.assign(uninitsWhenFalse);
1745 }
1746 if (log.nerrors != prevErrors ||
1747 flowKind.isFinal() ||
1748 new Bits(uninitsEntry).diffSet(uninitsWhenTrue).nextBit(firstadr)==-1)
1749 break;
1750 inits.assign(initsWhenTrue);
1751 uninits.assign(uninitsEntry.andSet(uninitsWhenTrue));
1752 flowKind = FlowKind.SPECULATIVE_LOOP;
1753 } while (true);
1754 flowKind = prevFlowKind;
1755 inits.assign(initsSkip);
1756 uninits.assign(uninitsSkip);
1757 resolveBreaks(tree, prevPendingExits);
1758 }
1760 public void visitWhileLoop(JCWhileLoop tree) {
1761 ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
1762 FlowKind prevFlowKind = flowKind;
1763 flowKind = FlowKind.NORMAL;
1764 final Bits initsSkip = new Bits(true);
1765 final Bits uninitsSkip = new Bits(true);
1766 pendingExits = new ListBuffer<AssignPendingExit>();
1767 int prevErrors = log.nerrors;
1768 final Bits uninitsEntry = new Bits(uninits);
1769 uninitsEntry.excludeFrom(nextadr);
1770 do {
1771 scanCond(tree.cond);
1772 if (!flowKind.isFinal()) {
1773 initsSkip.assign(initsWhenFalse) ;
1774 uninitsSkip.assign(uninitsWhenFalse);
1775 }
1776 inits.assign(initsWhenTrue);
1777 uninits.assign(uninitsWhenTrue);
1778 scan(tree.body);
1779 resolveContinues(tree);
1780 if (log.nerrors != prevErrors ||
1781 flowKind.isFinal() ||
1782 new Bits(uninitsEntry).diffSet(uninits).nextBit(firstadr) == -1)
1783 break;
1784 uninits.assign(uninitsEntry.andSet(uninits));
1785 flowKind = FlowKind.SPECULATIVE_LOOP;
1786 } while (true);
1787 flowKind = prevFlowKind;
1788 //a variable is DA/DU after the while statement, if it's DA/DU assuming the
1789 //branch is not taken AND if it's DA/DU before any break statement
1790 inits.assign(initsSkip);
1791 uninits.assign(uninitsSkip);
1792 resolveBreaks(tree, prevPendingExits);
1793 }
1795 public void visitForLoop(JCForLoop tree) {
1796 ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
1797 FlowKind prevFlowKind = flowKind;
1798 flowKind = FlowKind.NORMAL;
1799 int nextadrPrev = nextadr;
1800 scan(tree.init);
1801 final Bits initsSkip = new Bits(true);
1802 final Bits uninitsSkip = new Bits(true);
1803 pendingExits = new ListBuffer<AssignPendingExit>();
1804 int prevErrors = log.nerrors;
1805 do {
1806 final Bits uninitsEntry = new Bits(uninits);
1807 uninitsEntry.excludeFrom(nextadr);
1808 if (tree.cond != null) {
1809 scanCond(tree.cond);
1810 if (!flowKind.isFinal()) {
1811 initsSkip.assign(initsWhenFalse);
1812 uninitsSkip.assign(uninitsWhenFalse);
1813 }
1814 inits.assign(initsWhenTrue);
1815 uninits.assign(uninitsWhenTrue);
1816 } else if (!flowKind.isFinal()) {
1817 initsSkip.assign(inits);
1818 initsSkip.inclRange(firstadr, nextadr);
1819 uninitsSkip.assign(uninits);
1820 uninitsSkip.inclRange(firstadr, nextadr);
1821 }
1822 scan(tree.body);
1823 resolveContinues(tree);
1824 scan(tree.step);
1825 if (log.nerrors != prevErrors ||
1826 flowKind.isFinal() ||
1827 new Bits(uninitsEntry).diffSet(uninits).nextBit(firstadr) == -1)
1828 break;
1829 uninits.assign(uninitsEntry.andSet(uninits));
1830 flowKind = FlowKind.SPECULATIVE_LOOP;
1831 } while (true);
1832 flowKind = prevFlowKind;
1833 //a variable is DA/DU after a for loop, if it's DA/DU assuming the
1834 //branch is not taken AND if it's DA/DU before any break statement
1835 inits.assign(initsSkip);
1836 uninits.assign(uninitsSkip);
1837 resolveBreaks(tree, prevPendingExits);
1838 nextadr = nextadrPrev;
1839 }
1841 public void visitForeachLoop(JCEnhancedForLoop tree) {
1842 visitVarDef(tree.var);
1844 ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
1845 FlowKind prevFlowKind = flowKind;
1846 flowKind = FlowKind.NORMAL;
1847 int nextadrPrev = nextadr;
1848 scan(tree.expr);
1849 final Bits initsStart = new Bits(inits);
1850 final Bits uninitsStart = new Bits(uninits);
1852 letInit(tree.pos(), tree.var.sym);
1853 pendingExits = new ListBuffer<AssignPendingExit>();
1854 int prevErrors = log.nerrors;
1855 do {
1856 final Bits uninitsEntry = new Bits(uninits);
1857 uninitsEntry.excludeFrom(nextadr);
1858 scan(tree.body);
1859 resolveContinues(tree);
1860 if (log.nerrors != prevErrors ||
1861 flowKind.isFinal() ||
1862 new Bits(uninitsEntry).diffSet(uninits).nextBit(firstadr) == -1)
1863 break;
1864 uninits.assign(uninitsEntry.andSet(uninits));
1865 flowKind = FlowKind.SPECULATIVE_LOOP;
1866 } while (true);
1867 flowKind = prevFlowKind;
1868 inits.assign(initsStart);
1869 uninits.assign(uninitsStart.andSet(uninits));
1870 resolveBreaks(tree, prevPendingExits);
1871 nextadr = nextadrPrev;
1872 }
1874 public void visitLabelled(JCLabeledStatement tree) {
1875 ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
1876 pendingExits = new ListBuffer<AssignPendingExit>();
1877 scan(tree.body);
1878 resolveBreaks(tree, prevPendingExits);
1879 }
1881 public void visitSwitch(JCSwitch tree) {
1882 ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
1883 pendingExits = new ListBuffer<AssignPendingExit>();
1884 int nextadrPrev = nextadr;
1885 scanExpr(tree.selector);
1886 final Bits initsSwitch = new Bits(inits);
1887 final Bits uninitsSwitch = new Bits(uninits);
1888 boolean hasDefault = false;
1889 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
1890 inits.assign(initsSwitch);
1891 uninits.assign(uninits.andSet(uninitsSwitch));
1892 JCCase c = l.head;
1893 if (c.pat == null)
1894 hasDefault = true;
1895 else
1896 scanExpr(c.pat);
1897 scan(c.stats);
1898 addVars(c.stats, initsSwitch, uninitsSwitch);
1899 // Warn about fall-through if lint switch fallthrough enabled.
1900 }
1901 if (!hasDefault) {
1902 inits.andSet(initsSwitch);
1903 }
1904 resolveBreaks(tree, prevPendingExits);
1905 nextadr = nextadrPrev;
1906 }
1907 // where
1908 /** Add any variables defined in stats to inits and uninits. */
1909 private void addVars(List<JCStatement> stats, final Bits inits,
1910 final Bits uninits) {
1911 for (;stats.nonEmpty(); stats = stats.tail) {
1912 JCTree stat = stats.head;
1913 if (stat.hasTag(VARDEF)) {
1914 int adr = ((JCVariableDecl) stat).sym.adr;
1915 inits.excl(adr);
1916 uninits.incl(adr);
1917 }
1918 }
1919 }
1921 public void visitTry(JCTry tree) {
1922 ListBuffer<JCVariableDecl> resourceVarDecls = ListBuffer.lb();
1923 final Bits uninitsTryPrev = new Bits(uninitsTry);
1924 ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
1925 pendingExits = new ListBuffer<AssignPendingExit>();
1926 final Bits initsTry = new Bits(inits);
1927 uninitsTry.assign(uninits);
1928 for (JCTree resource : tree.resources) {
1929 if (resource instanceof JCVariableDecl) {
1930 JCVariableDecl vdecl = (JCVariableDecl) resource;
1931 visitVarDef(vdecl);
1932 unrefdResources.enter(vdecl.sym);
1933 resourceVarDecls.append(vdecl);
1934 } else if (resource instanceof JCExpression) {
1935 scanExpr((JCExpression) resource);
1936 } else {
1937 throw new AssertionError(tree); // parser error
1938 }
1939 }
1940 scan(tree.body);
1941 uninitsTry.andSet(uninits);
1942 final Bits initsEnd = new Bits(inits);
1943 final Bits uninitsEnd = new Bits(uninits);
1944 int nextadrCatch = nextadr;
1946 if (!resourceVarDecls.isEmpty() &&
1947 lint.isEnabled(Lint.LintCategory.TRY)) {
1948 for (JCVariableDecl resVar : resourceVarDecls) {
1949 if (unrefdResources.includes(resVar.sym)) {
1950 log.warning(Lint.LintCategory.TRY, resVar.pos(),
1951 "try.resource.not.referenced", resVar.sym);
1952 unrefdResources.remove(resVar.sym);
1953 }
1954 }
1955 }
1957 /* The analysis of each catch should be independent.
1958 * Each one should have the same initial values of inits and
1959 * uninits.
1960 */
1961 final Bits initsCatchPrev = new Bits(initsTry);
1962 final Bits uninitsCatchPrev = new Bits(uninitsTry);
1964 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1965 JCVariableDecl param = l.head.param;
1966 inits.assign(initsCatchPrev);
1967 uninits.assign(uninitsCatchPrev);
1968 scan(param);
1969 inits.incl(param.sym.adr);
1970 uninits.excl(param.sym.adr);
1971 scan(l.head.body);
1972 initsEnd.andSet(inits);
1973 uninitsEnd.andSet(uninits);
1974 nextadr = nextadrCatch;
1975 }
1976 if (tree.finalizer != null) {
1977 inits.assign(initsTry);
1978 uninits.assign(uninitsTry);
1979 ListBuffer<AssignPendingExit> exits = pendingExits;
1980 pendingExits = prevPendingExits;
1981 scan(tree.finalizer);
1982 if (!tree.finallyCanCompleteNormally) {
1983 // discard exits and exceptions from try and finally
1984 } else {
1985 uninits.andSet(uninitsEnd);
1986 // FIX: this doesn't preserve source order of exits in catch
1987 // versus finally!
1988 while (exits.nonEmpty()) {
1989 AssignPendingExit exit = exits.next();
1990 if (exit.exit_inits != null) {
1991 exit.exit_inits.orSet(inits);
1992 exit.exit_uninits.andSet(uninits);
1993 }
1994 pendingExits.append(exit);
1995 }
1996 inits.orSet(initsEnd);
1997 }
1998 } else {
1999 inits.assign(initsEnd);
2000 uninits.assign(uninitsEnd);
2001 ListBuffer<AssignPendingExit> exits = pendingExits;
2002 pendingExits = prevPendingExits;
2003 while (exits.nonEmpty()) pendingExits.append(exits.next());
2004 }
2005 uninitsTry.andSet(uninitsTryPrev).andSet(uninits);
2006 }
2008 public void visitConditional(JCConditional tree) {
2009 scanCond(tree.cond);
2010 final Bits initsBeforeElse = new Bits(initsWhenFalse);
2011 final Bits uninitsBeforeElse = new Bits(uninitsWhenFalse);
2012 inits.assign(initsWhenTrue);
2013 uninits.assign(uninitsWhenTrue);
2014 if (tree.truepart.type.hasTag(BOOLEAN) &&
2015 tree.falsepart.type.hasTag(BOOLEAN)) {
2016 // if b and c are boolean valued, then
2017 // v is (un)assigned after a?b:c when true iff
2018 // v is (un)assigned after b when true and
2019 // v is (un)assigned after c when true
2020 scanCond(tree.truepart);
2021 final Bits initsAfterThenWhenTrue = new Bits(initsWhenTrue);
2022 final Bits initsAfterThenWhenFalse = new Bits(initsWhenFalse);
2023 final Bits uninitsAfterThenWhenTrue = new Bits(uninitsWhenTrue);
2024 final Bits uninitsAfterThenWhenFalse = new Bits(uninitsWhenFalse);
2025 inits.assign(initsBeforeElse);
2026 uninits.assign(uninitsBeforeElse);
2027 scanCond(tree.falsepart);
2028 initsWhenTrue.andSet(initsAfterThenWhenTrue);
2029 initsWhenFalse.andSet(initsAfterThenWhenFalse);
2030 uninitsWhenTrue.andSet(uninitsAfterThenWhenTrue);
2031 uninitsWhenFalse.andSet(uninitsAfterThenWhenFalse);
2032 } else {
2033 scanExpr(tree.truepart);
2034 final Bits initsAfterThen = new Bits(inits);
2035 final Bits uninitsAfterThen = new Bits(uninits);
2036 inits.assign(initsBeforeElse);
2037 uninits.assign(uninitsBeforeElse);
2038 scanExpr(tree.falsepart);
2039 inits.andSet(initsAfterThen);
2040 uninits.andSet(uninitsAfterThen);
2041 }
2042 }
2044 public void visitIf(JCIf tree) {
2045 scanCond(tree.cond);
2046 final Bits initsBeforeElse = new Bits(initsWhenFalse);
2047 final Bits uninitsBeforeElse = new Bits(uninitsWhenFalse);
2048 inits.assign(initsWhenTrue);
2049 uninits.assign(uninitsWhenTrue);
2050 scan(tree.thenpart);
2051 if (tree.elsepart != null) {
2052 final Bits initsAfterThen = new Bits(inits);
2053 final Bits uninitsAfterThen = new Bits(uninits);
2054 inits.assign(initsBeforeElse);
2055 uninits.assign(uninitsBeforeElse);
2056 scan(tree.elsepart);
2057 inits.andSet(initsAfterThen);
2058 uninits.andSet(uninitsAfterThen);
2059 } else {
2060 inits.andSet(initsBeforeElse);
2061 uninits.andSet(uninitsBeforeElse);
2062 }
2063 }
2065 public void visitBreak(JCBreak tree) {
2066 recordExit(tree, new AssignPendingExit(tree, inits, uninits));
2067 }
2069 public void visitContinue(JCContinue tree) {
2070 recordExit(tree, new AssignPendingExit(tree, inits, uninits));
2071 }
2073 public void visitReturn(JCReturn tree) {
2074 scanExpr(tree.expr);
2075 recordExit(tree, new AssignPendingExit(tree, inits, uninits));
2076 }
2078 public void visitThrow(JCThrow tree) {
2079 scanExpr(tree.expr);
2080 markDead();
2081 }
2083 public void visitApply(JCMethodInvocation tree) {
2084 scanExpr(tree.meth);
2085 scanExprs(tree.args);
2086 }
2088 public void visitNewClass(JCNewClass tree) {
2089 scanExpr(tree.encl);
2090 scanExprs(tree.args);
2091 scan(tree.def);
2092 }
2094 @Override
2095 public void visitLambda(JCLambda tree) {
2096 final Bits prevUninits = new Bits(uninits);
2097 final Bits prevInits = new Bits(inits);
2098 int returnadrPrev = returnadr;
2099 ListBuffer<AssignPendingExit> prevPending = pendingExits;
2100 try {
2101 returnadr = nextadr;
2102 pendingExits = new ListBuffer<AssignPendingExit>();
2103 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
2104 JCVariableDecl def = l.head;
2105 scan(def);
2106 inits.incl(def.sym.adr);
2107 uninits.excl(def.sym.adr);
2108 }
2109 if (tree.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
2110 scanExpr(tree.body);
2111 } else {
2112 scan(tree.body);
2113 }
2114 }
2115 finally {
2116 returnadr = returnadrPrev;
2117 uninits.assign(prevUninits);
2118 inits.assign(prevInits);
2119 pendingExits = prevPending;
2120 }
2121 }
2123 public void visitNewArray(JCNewArray tree) {
2124 scanExprs(tree.dims);
2125 scanExprs(tree.elems);
2126 }
2128 public void visitAssert(JCAssert tree) {
2129 final Bits initsExit = new Bits(inits);
2130 final Bits uninitsExit = new Bits(uninits);
2131 scanCond(tree.cond);
2132 uninitsExit.andSet(uninitsWhenTrue);
2133 if (tree.detail != null) {
2134 inits.assign(initsWhenFalse);
2135 uninits.assign(uninitsWhenFalse);
2136 scanExpr(tree.detail);
2137 }
2138 inits.assign(initsExit);
2139 uninits.assign(uninitsExit);
2140 }
2142 public void visitAssign(JCAssign tree) {
2143 JCTree lhs = TreeInfo.skipParens(tree.lhs);
2144 if (!(lhs instanceof JCIdent)) {
2145 scanExpr(lhs);
2146 }
2147 scanExpr(tree.rhs);
2148 letInit(lhs);
2149 }
2151 public void visitAssignop(JCAssignOp tree) {
2152 scanExpr(tree.lhs);
2153 scanExpr(tree.rhs);
2154 letInit(tree.lhs);
2155 }
2157 public void visitUnary(JCUnary tree) {
2158 switch (tree.getTag()) {
2159 case NOT:
2160 scanCond(tree.arg);
2161 final Bits t = new Bits(initsWhenFalse);
2162 initsWhenFalse.assign(initsWhenTrue);
2163 initsWhenTrue.assign(t);
2164 t.assign(uninitsWhenFalse);
2165 uninitsWhenFalse.assign(uninitsWhenTrue);
2166 uninitsWhenTrue.assign(t);
2167 break;
2168 case PREINC: case POSTINC:
2169 case PREDEC: case POSTDEC:
2170 scanExpr(tree.arg);
2171 letInit(tree.arg);
2172 break;
2173 default:
2174 scanExpr(tree.arg);
2175 }
2176 }
2178 public void visitBinary(JCBinary tree) {
2179 switch (tree.getTag()) {
2180 case AND:
2181 scanCond(tree.lhs);
2182 final Bits initsWhenFalseLeft = new Bits(initsWhenFalse);
2183 final Bits uninitsWhenFalseLeft = new Bits(uninitsWhenFalse);
2184 inits.assign(initsWhenTrue);
2185 uninits.assign(uninitsWhenTrue);
2186 scanCond(tree.rhs);
2187 initsWhenFalse.andSet(initsWhenFalseLeft);
2188 uninitsWhenFalse.andSet(uninitsWhenFalseLeft);
2189 break;
2190 case OR:
2191 scanCond(tree.lhs);
2192 final Bits initsWhenTrueLeft = new Bits(initsWhenTrue);
2193 final Bits uninitsWhenTrueLeft = new Bits(uninitsWhenTrue);
2194 inits.assign(initsWhenFalse);
2195 uninits.assign(uninitsWhenFalse);
2196 scanCond(tree.rhs);
2197 initsWhenTrue.andSet(initsWhenTrueLeft);
2198 uninitsWhenTrue.andSet(uninitsWhenTrueLeft);
2199 break;
2200 default:
2201 scanExpr(tree.lhs);
2202 scanExpr(tree.rhs);
2203 }
2204 }
2206 public void visitIdent(JCIdent tree) {
2207 if (tree.sym.kind == VAR) {
2208 checkInit(tree.pos(), (VarSymbol)tree.sym);
2209 referenced(tree.sym);
2210 }
2211 }
2213 void referenced(Symbol sym) {
2214 unrefdResources.remove(sym);
2215 }
2217 public void visitAnnotatedType(JCAnnotatedType tree) {
2218 // annotations don't get scanned
2219 tree.underlyingType.accept(this);
2220 }
2222 public void visitTopLevel(JCCompilationUnit tree) {
2223 // Do nothing for TopLevel since each class is visited individually
2224 }
2226 /**************************************************************************
2227 * main method
2228 *************************************************************************/
2230 /** Perform definite assignment/unassignment analysis on a tree.
2231 */
2232 public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
2233 analyzeTree(env, env.tree, make);
2234 }
2236 public void analyzeTree(Env<AttrContext> env, JCTree tree, TreeMaker make) {
2237 try {
2238 attrEnv = env;
2239 Flow.this.make = make;
2240 startPos = tree.pos().getStartPosition();
2242 if (vars == null)
2243 vars = new VarSymbol[32];
2244 else
2245 for (int i=0; i<vars.length; i++)
2246 vars[i] = null;
2247 firstadr = 0;
2248 nextadr = 0;
2249 pendingExits = new ListBuffer<AssignPendingExit>();
2250 this.classDef = null;
2251 unrefdResources = new Scope(env.enclClass.sym);
2252 scan(tree);
2253 } finally {
2254 // note that recursive invocations of this method fail hard
2255 startPos = -1;
2256 resetBits(inits, uninits, uninitsTry, initsWhenTrue,
2257 initsWhenFalse, uninitsWhenTrue, uninitsWhenFalse);
2258 if (vars != null) for (int i=0; i<vars.length; i++)
2259 vars[i] = null;
2260 firstadr = 0;
2261 nextadr = 0;
2262 pendingExits = null;
2263 Flow.this.make = null;
2264 this.classDef = null;
2265 unrefdResources = null;
2266 }
2267 }
2268 }
2270 /**
2271 * This pass implements the last step of the dataflow analysis, namely
2272 * the effectively-final analysis check. This checks that every local variable
2273 * reference from a lambda body/local inner class is either final or effectively final.
2274 * As effectively final variables are marked as such during DA/DU, this pass must run after
2275 * AssignAnalyzer.
2276 */
2277 class CaptureAnalyzer extends BaseAnalyzer<BaseAnalyzer.PendingExit> {
2279 JCTree currentTree; //local class or lambda
2281 @Override
2282 void markDead() {
2283 //do nothing
2284 }
2286 @SuppressWarnings("fallthrough")
2287 void checkEffectivelyFinal(DiagnosticPosition pos, VarSymbol sym) {
2288 if (currentTree != null &&
2289 sym.owner.kind == MTH &&
2290 sym.pos < currentTree.getStartPosition()) {
2291 switch (currentTree.getTag()) {
2292 case CLASSDEF:
2293 if (!allowEffectivelyFinalInInnerClasses) {
2294 if ((sym.flags() & FINAL) == 0) {
2295 reportInnerClsNeedsFinalError(pos, sym);
2296 }
2297 break;
2298 }
2299 case LAMBDA:
2300 if ((sym.flags() & (EFFECTIVELY_FINAL | FINAL)) == 0) {
2301 reportEffectivelyFinalError(pos, sym);
2302 }
2303 }
2304 }
2305 }
2307 @SuppressWarnings("fallthrough")
2308 void letInit(JCTree tree) {
2309 tree = TreeInfo.skipParens(tree);
2310 if (tree.hasTag(IDENT) || tree.hasTag(SELECT)) {
2311 Symbol sym = TreeInfo.symbol(tree);
2312 if (currentTree != null &&
2313 sym.kind == VAR &&
2314 sym.owner.kind == MTH &&
2315 ((VarSymbol)sym).pos < currentTree.getStartPosition()) {
2316 switch (currentTree.getTag()) {
2317 case CLASSDEF:
2318 if (!allowEffectivelyFinalInInnerClasses) {
2319 reportInnerClsNeedsFinalError(tree, sym);
2320 break;
2321 }
2322 case LAMBDA:
2323 reportEffectivelyFinalError(tree, sym);
2324 }
2325 }
2326 }
2327 }
2329 void reportEffectivelyFinalError(DiagnosticPosition pos, Symbol sym) {
2330 String subKey = currentTree.hasTag(LAMBDA) ?
2331 "lambda" : "inner.cls";
2332 log.error(pos, "cant.ref.non.effectively.final.var", sym, diags.fragment(subKey));
2333 }
2335 void reportInnerClsNeedsFinalError(DiagnosticPosition pos, Symbol sym) {
2336 log.error(pos,
2337 "local.var.accessed.from.icls.needs.final",
2338 sym);
2339 }
2341 /*************************************************************************
2342 * Visitor methods for statements and definitions
2343 *************************************************************************/
2345 /* ------------ Visitor methods for various sorts of trees -------------*/
2347 public void visitClassDef(JCClassDecl tree) {
2348 JCTree prevTree = currentTree;
2349 try {
2350 currentTree = tree.sym.isLocal() ? tree : null;
2351 super.visitClassDef(tree);
2352 } finally {
2353 currentTree = prevTree;
2354 }
2355 }
2357 @Override
2358 public void visitLambda(JCLambda tree) {
2359 JCTree prevTree = currentTree;
2360 try {
2361 currentTree = tree;
2362 super.visitLambda(tree);
2363 } finally {
2364 currentTree = prevTree;
2365 }
2366 }
2368 @Override
2369 public void visitIdent(JCIdent tree) {
2370 if (tree.sym.kind == VAR) {
2371 checkEffectivelyFinal(tree, (VarSymbol)tree.sym);
2372 }
2373 }
2375 public void visitAssign(JCAssign tree) {
2376 JCTree lhs = TreeInfo.skipParens(tree.lhs);
2377 if (!(lhs instanceof JCIdent)) {
2378 scan(lhs);
2379 }
2380 scan(tree.rhs);
2381 letInit(lhs);
2382 }
2384 public void visitAssignop(JCAssignOp tree) {
2385 scan(tree.lhs);
2386 scan(tree.rhs);
2387 letInit(tree.lhs);
2388 }
2390 public void visitUnary(JCUnary tree) {
2391 switch (tree.getTag()) {
2392 case PREINC: case POSTINC:
2393 case PREDEC: case POSTDEC:
2394 scan(tree.arg);
2395 letInit(tree.arg);
2396 break;
2397 default:
2398 scan(tree.arg);
2399 }
2400 }
2402 public void visitTopLevel(JCCompilationUnit tree) {
2403 // Do nothing for TopLevel since each class is visited individually
2404 }
2406 /**************************************************************************
2407 * main method
2408 *************************************************************************/
2410 /** Perform definite assignment/unassignment analysis on a tree.
2411 */
2412 public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
2413 analyzeTree(env, env.tree, make);
2414 }
2415 public void analyzeTree(Env<AttrContext> env, JCTree tree, TreeMaker make) {
2416 try {
2417 attrEnv = env;
2418 Flow.this.make = make;
2419 pendingExits = new ListBuffer<PendingExit>();
2420 scan(tree);
2421 } finally {
2422 pendingExits = null;
2423 Flow.this.make = null;
2424 }
2425 }
2426 }
2427 }