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