Thu, 03 Mar 2011 17:32:35 +0000
7023703: Valid code doesn't compile
Summary: leftovers cause problems when analyzing loops in Flow.java
Reviewed-by: jjg
1 /*
2 * Copyright (c) 1999, 2011, 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;
31 import java.util.Map;
32 import java.util.LinkedHashMap;
34 import com.sun.tools.javac.code.*;
35 import com.sun.tools.javac.tree.*;
36 import com.sun.tools.javac.util.*;
37 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
39 import com.sun.tools.javac.code.Symbol.*;
40 import com.sun.tools.javac.tree.JCTree.*;
42 import static com.sun.tools.javac.code.Flags.*;
43 import static com.sun.tools.javac.code.Kinds.*;
44 import static com.sun.tools.javac.code.TypeTags.*;
46 /** This pass implements dataflow analysis for Java programs.
47 * Liveness analysis checks that every statement is reachable.
48 * Exception analysis ensures that every checked exception that is
49 * thrown is declared or caught. Definite assignment analysis
50 * ensures that each variable is assigned when used. Definite
51 * unassignment analysis ensures that no final variable is assigned
52 * more than once.
53 *
54 * <p>The second edition of the JLS has a number of problems in the
55 * specification of these flow analysis problems. This implementation
56 * attempts to address those issues.
57 *
58 * <p>First, there is no accommodation for a finally clause that cannot
59 * complete normally. For liveness analysis, an intervening finally
60 * clause can cause a break, continue, or return not to reach its
61 * target. For exception analysis, an intervening finally clause can
62 * cause any exception to be "caught". For DA/DU analysis, the finally
63 * clause can prevent a transfer of control from propagating DA/DU
64 * state to the target. In addition, code in the finally clause can
65 * affect the DA/DU status of variables.
66 *
67 * <p>For try statements, we introduce the idea of a variable being
68 * definitely unassigned "everywhere" in a block. A variable V is
69 * "unassigned everywhere" in a block iff it is unassigned at the
70 * beginning of the block and there is no reachable assignment to V
71 * in the block. An assignment V=e is reachable iff V is not DA
72 * after e. Then we can say that V is DU at the beginning of the
73 * catch block iff V is DU everywhere in the try block. Similarly, V
74 * is DU at the beginning of the finally block iff V is DU everywhere
75 * in the try block and in every catch block. Specifically, the
76 * following bullet is added to 16.2.2
77 * <pre>
78 * V is <em>unassigned everywhere</em> in a block if it is
79 * unassigned before the block and there is no reachable
80 * assignment to V within the block.
81 * </pre>
82 * <p>In 16.2.15, the third bullet (and all of its sub-bullets) for all
83 * try blocks is changed to
84 * <pre>
85 * V is definitely unassigned before a catch block iff V is
86 * definitely unassigned everywhere in the try block.
87 * </pre>
88 * <p>The last bullet (and all of its sub-bullets) for try blocks that
89 * have a finally block is changed to
90 * <pre>
91 * V is definitely unassigned before the finally block iff
92 * V is definitely unassigned everywhere in the try block
93 * and everywhere in each catch block of the try statement.
94 * </pre>
95 * <p>In addition,
96 * <pre>
97 * V is definitely assigned at the end of a constructor iff
98 * V is definitely assigned after the block that is the body
99 * of the constructor and V is definitely assigned at every
100 * return that can return from the constructor.
101 * </pre>
102 * <p>In addition, each continue statement with the loop as its target
103 * is treated as a jump to the end of the loop body, and "intervening"
104 * finally clauses are treated as follows: V is DA "due to the
105 * continue" iff V is DA before the continue statement or V is DA at
106 * the end of any intervening finally block. V is DU "due to the
107 * continue" iff any intervening finally cannot complete normally or V
108 * is DU at the end of every intervening finally block. This "due to
109 * the continue" concept is then used in the spec for the loops.
110 *
111 * <p>Similarly, break statements must consider intervening finally
112 * blocks. For liveness analysis, a break statement for which any
113 * intervening finally cannot complete normally is not considered to
114 * cause the target statement to be able to complete normally. Then
115 * we say V is DA "due to the break" iff V is DA before the break or
116 * V is DA at the end of any intervening finally block. V is DU "due
117 * to the break" iff any intervening finally cannot complete normally
118 * or V is DU at the break and at the end of every intervening
119 * finally block. (I suspect this latter condition can be
120 * simplified.) This "due to the break" is then used in the spec for
121 * all statements that can be "broken".
122 *
123 * <p>The return statement is treated similarly. V is DA "due to a
124 * return statement" iff V is DA before the return statement or V is
125 * DA at the end of any intervening finally block. Note that we
126 * don't have to worry about the return expression because this
127 * concept is only used for construcrors.
128 *
129 * <p>There is no spec in JLS2 for when a variable is definitely
130 * assigned at the end of a constructor, which is needed for final
131 * fields (8.3.1.2). We implement the rule that V is DA at the end
132 * of the constructor iff it is DA and the end of the body of the
133 * constructor and V is DA "due to" every return of the constructor.
134 *
135 * <p>Intervening finally blocks similarly affect exception analysis. An
136 * intervening finally that cannot complete normally allows us to ignore
137 * an otherwise uncaught exception.
138 *
139 * <p>To implement the semantics of intervening finally clauses, all
140 * nonlocal transfers (break, continue, return, throw, method call that
141 * can throw a checked exception, and a constructor invocation that can
142 * thrown a checked exception) are recorded in a queue, and removed
143 * from the queue when we complete processing the target of the
144 * nonlocal transfer. This allows us to modify the queue in accordance
145 * with the above rules when we encounter a finally clause. The only
146 * exception to this [no pun intended] is that checked exceptions that
147 * are known to be caught or declared to be caught in the enclosing
148 * method are not recorded in the queue, but instead are recorded in a
149 * global variable "Set<Type> thrown" that records the type of all
150 * exceptions that can be thrown.
151 *
152 * <p>Other minor issues the treatment of members of other classes
153 * (always considered DA except that within an anonymous class
154 * constructor, where DA status from the enclosing scope is
155 * preserved), treatment of the case expression (V is DA before the
156 * case expression iff V is DA after the switch expression),
157 * treatment of variables declared in a switch block (the implied
158 * DA/DU status after the switch expression is DU and not DA for
159 * variables defined in a switch block), the treatment of boolean ?:
160 * expressions (The JLS rules only handle b and c non-boolean; the
161 * new rule is that if b and c are boolean valued, then V is
162 * (un)assigned after a?b:c when true/false iff V is (un)assigned
163 * after b when true/false and V is (un)assigned after c when
164 * true/false).
165 *
166 * <p>There is the remaining question of what syntactic forms constitute a
167 * reference to a variable. It is conventional to allow this.x on the
168 * left-hand-side to initialize a final instance field named x, yet
169 * this.x isn't considered a "use" when appearing on a right-hand-side
170 * in most implementations. Should parentheses affect what is
171 * considered a variable reference? The simplest rule would be to
172 * allow unqualified forms only, parentheses optional, and phase out
173 * support for assigning to a final field via this.x.
174 *
175 * <p><b>This is NOT part of any supported API.
176 * If you write code that depends on this, you do so at your own risk.
177 * This code and its internal interfaces are subject to change or
178 * deletion without notice.</b>
179 */
180 public class Flow extends TreeScanner {
181 protected static final Context.Key<Flow> flowKey =
182 new Context.Key<Flow>();
184 private final Names names;
185 private final Log log;
186 private final Symtab syms;
187 private final Types types;
188 private final Check chk;
189 private TreeMaker make;
190 private final Resolve rs;
191 private Env<AttrContext> attrEnv;
192 private Lint lint;
193 private final boolean allowRethrowAnalysis;
195 public static Flow instance(Context context) {
196 Flow instance = context.get(flowKey);
197 if (instance == null)
198 instance = new Flow(context);
199 return instance;
200 }
202 protected Flow(Context context) {
203 context.put(flowKey, this);
204 names = Names.instance(context);
205 log = Log.instance(context);
206 syms = Symtab.instance(context);
207 types = Types.instance(context);
208 chk = Check.instance(context);
209 lint = Lint.instance(context);
210 rs = Resolve.instance(context);
211 Source source = Source.instance(context);
212 allowRethrowAnalysis = source.allowMulticatch();
213 }
215 /** A flag that indicates whether the last statement could
216 * complete normally.
217 */
218 private boolean alive;
220 /** The set of definitely assigned variables.
221 */
222 Bits inits;
224 /** The set of definitely unassigned variables.
225 */
226 Bits uninits;
228 HashMap<Symbol, List<Type>> preciseRethrowTypes;
230 /** The set of variables that are definitely unassigned everywhere
231 * in current try block. This variable is maintained lazily; it is
232 * updated only when something gets removed from uninits,
233 * typically by being assigned in reachable code. To obtain the
234 * correct set of variables which are definitely unassigned
235 * anywhere in current try block, intersect uninitsTry and
236 * uninits.
237 */
238 Bits uninitsTry;
240 /** When analyzing a condition, inits and uninits are null.
241 * Instead we have:
242 */
243 Bits initsWhenTrue;
244 Bits initsWhenFalse;
245 Bits uninitsWhenTrue;
246 Bits uninitsWhenFalse;
248 /** A mapping from addresses to variable symbols.
249 */
250 VarSymbol[] vars;
252 /** The current class being defined.
253 */
254 JCClassDecl classDef;
256 /** The first variable sequence number in this class definition.
257 */
258 int firstadr;
260 /** The next available variable sequence number.
261 */
262 int nextadr;
264 /** The list of possibly thrown declarable exceptions.
265 */
266 List<Type> thrown;
268 /** The list of exceptions that are either caught or declared to be
269 * thrown.
270 */
271 List<Type> caught;
273 /** The list of unreferenced automatic resources.
274 */
275 Scope unrefdResources;
277 /** Set when processing a loop body the second time for DU analysis. */
278 boolean loopPassTwo = false;
280 /*-------------------- Environments ----------------------*/
282 /** A pending exit. These are the statements return, break, and
283 * continue. In addition, exception-throwing expressions or
284 * statements are put here when not known to be caught. This
285 * will typically result in an error unless it is within a
286 * try-finally whose finally block cannot complete normally.
287 */
288 static class PendingExit {
289 JCTree tree;
290 Bits inits;
291 Bits uninits;
292 Type thrown;
293 PendingExit(JCTree tree, Bits inits, Bits uninits) {
294 this.tree = tree;
295 this.inits = inits.dup();
296 this.uninits = uninits.dup();
297 }
298 PendingExit(JCTree tree, Type thrown) {
299 this.tree = tree;
300 this.thrown = thrown;
301 }
302 }
304 /** The currently pending exits that go from current inner blocks
305 * to an enclosing block, in source order.
306 */
307 ListBuffer<PendingExit> pendingExits;
309 /*-------------------- Exceptions ----------------------*/
311 /** Complain that pending exceptions are not caught.
312 */
313 void errorUncaught() {
314 for (PendingExit exit = pendingExits.next();
315 exit != null;
316 exit = pendingExits.next()) {
317 if (classDef != null &&
318 classDef.pos == exit.tree.pos) {
319 log.error(exit.tree.pos(),
320 "unreported.exception.default.constructor",
321 exit.thrown);
322 } else if (exit.tree.getTag() == JCTree.VARDEF &&
323 ((JCVariableDecl)exit.tree).sym.isResourceVariable()) {
324 log.error(exit.tree.pos(),
325 "unreported.exception.implicit.close",
326 exit.thrown,
327 ((JCVariableDecl)exit.tree).sym.name);
328 } else {
329 log.error(exit.tree.pos(),
330 "unreported.exception.need.to.catch.or.throw",
331 exit.thrown);
332 }
333 }
334 }
336 /** Record that exception is potentially thrown and check that it
337 * is caught.
338 */
339 void markThrown(JCTree tree, Type exc) {
340 if (!chk.isUnchecked(tree.pos(), exc)) {
341 if (!chk.isHandled(exc, caught))
342 pendingExits.append(new PendingExit(tree, exc));
343 thrown = chk.incl(exc, thrown);
344 }
345 }
347 /*-------------- Processing variables ----------------------*/
349 /** Do we need to track init/uninit state of this symbol?
350 * I.e. is symbol either a local or a blank final variable?
351 */
352 boolean trackable(VarSymbol sym) {
353 return
354 (sym.owner.kind == MTH ||
355 ((sym.flags() & (FINAL | HASINIT | PARAMETER)) == FINAL &&
356 classDef.sym.isEnclosedBy((ClassSymbol)sym.owner)));
357 }
359 /** Initialize new trackable variable by setting its address field
360 * to the next available sequence number and entering it under that
361 * index into the vars array.
362 */
363 void newVar(VarSymbol sym) {
364 if (nextadr == vars.length) {
365 VarSymbol[] newvars = new VarSymbol[nextadr * 2];
366 System.arraycopy(vars, 0, newvars, 0, nextadr);
367 vars = newvars;
368 }
369 sym.adr = nextadr;
370 vars[nextadr] = sym;
371 inits.excl(nextadr);
372 uninits.incl(nextadr);
373 nextadr++;
374 }
376 /** Record an initialization of a trackable variable.
377 */
378 void letInit(DiagnosticPosition pos, VarSymbol sym) {
379 if (sym.adr >= firstadr && trackable(sym)) {
380 if ((sym.flags() & FINAL) != 0) {
381 if ((sym.flags() & PARAMETER) != 0) {
382 if ((sym.flags() & DISJUNCTION) != 0) { //multi-catch parameter
383 log.error(pos, "multicatch.parameter.may.not.be.assigned",
384 sym);
385 }
386 else {
387 log.error(pos, "final.parameter.may.not.be.assigned",
388 sym);
389 }
390 } else if (!uninits.isMember(sym.adr)) {
391 log.error(pos,
392 loopPassTwo
393 ? "var.might.be.assigned.in.loop"
394 : "var.might.already.be.assigned",
395 sym);
396 } else if (!inits.isMember(sym.adr)) {
397 // reachable assignment
398 uninits.excl(sym.adr);
399 uninitsTry.excl(sym.adr);
400 } else {
401 //log.rawWarning(pos, "unreachable assignment");//DEBUG
402 uninits.excl(sym.adr);
403 }
404 }
405 inits.incl(sym.adr);
406 } else if ((sym.flags() & FINAL) != 0) {
407 log.error(pos, "var.might.already.be.assigned", sym);
408 }
409 }
411 /** If tree is either a simple name or of the form this.name or
412 * C.this.name, and tree represents a trackable variable,
413 * record an initialization of the variable.
414 */
415 void letInit(JCTree tree) {
416 tree = TreeInfo.skipParens(tree);
417 if (tree.getTag() == JCTree.IDENT || tree.getTag() == JCTree.SELECT) {
418 Symbol sym = TreeInfo.symbol(tree);
419 if (sym.kind == VAR) {
420 letInit(tree.pos(), (VarSymbol)sym);
421 }
422 }
423 }
425 /** Check that trackable variable is initialized.
426 */
427 void checkInit(DiagnosticPosition pos, VarSymbol sym) {
428 if ((sym.adr >= firstadr || sym.owner.kind != TYP) &&
429 trackable(sym) &&
430 !inits.isMember(sym.adr)) {
431 log.error(pos, "var.might.not.have.been.initialized",
432 sym);
433 inits.incl(sym.adr);
434 }
435 }
437 /*-------------------- Handling jumps ----------------------*/
439 /** Record an outward transfer of control. */
440 void recordExit(JCTree tree) {
441 pendingExits.append(new PendingExit(tree, inits, uninits));
442 markDead();
443 }
445 /** Resolve all breaks of this statement. */
446 boolean resolveBreaks(JCTree tree,
447 ListBuffer<PendingExit> oldPendingExits) {
448 boolean result = false;
449 List<PendingExit> exits = pendingExits.toList();
450 pendingExits = oldPendingExits;
451 for (; exits.nonEmpty(); exits = exits.tail) {
452 PendingExit exit = exits.head;
453 if (exit.tree.getTag() == JCTree.BREAK &&
454 ((JCBreak) exit.tree).target == tree) {
455 inits.andSet(exit.inits);
456 uninits.andSet(exit.uninits);
457 result = true;
458 } else {
459 pendingExits.append(exit);
460 }
461 }
462 return result;
463 }
465 /** Resolve all continues of this statement. */
466 boolean resolveContinues(JCTree tree) {
467 boolean result = false;
468 List<PendingExit> exits = pendingExits.toList();
469 pendingExits = new ListBuffer<PendingExit>();
470 for (; exits.nonEmpty(); exits = exits.tail) {
471 PendingExit exit = exits.head;
472 if (exit.tree.getTag() == JCTree.CONTINUE &&
473 ((JCContinue) exit.tree).target == tree) {
474 inits.andSet(exit.inits);
475 uninits.andSet(exit.uninits);
476 result = true;
477 } else {
478 pendingExits.append(exit);
479 }
480 }
481 return result;
482 }
484 /** Record that statement is unreachable.
485 */
486 void markDead() {
487 inits.inclRange(firstadr, nextadr);
488 uninits.inclRange(firstadr, nextadr);
489 alive = false;
490 }
492 /** Split (duplicate) inits/uninits into WhenTrue/WhenFalse sets
493 */
494 void split(boolean setToNull) {
495 initsWhenFalse = inits.dup();
496 uninitsWhenFalse = uninits.dup();
497 initsWhenTrue = inits;
498 uninitsWhenTrue = uninits;
499 if (setToNull)
500 inits = uninits = null;
501 }
503 /** Merge (intersect) inits/uninits from WhenTrue/WhenFalse sets.
504 */
505 void merge() {
506 inits = initsWhenFalse.andSet(initsWhenTrue);
507 uninits = uninitsWhenFalse.andSet(uninitsWhenTrue);
508 }
510 /* ************************************************************************
511 * Visitor methods for statements and definitions
512 *************************************************************************/
514 /** Analyze a definition.
515 */
516 void scanDef(JCTree tree) {
517 scanStat(tree);
518 if (tree != null && tree.getTag() == JCTree.BLOCK && !alive) {
519 log.error(tree.pos(),
520 "initializer.must.be.able.to.complete.normally");
521 }
522 }
524 /** Analyze a statement. Check that statement is reachable.
525 */
526 void scanStat(JCTree tree) {
527 if (!alive && tree != null) {
528 log.error(tree.pos(), "unreachable.stmt");
529 if (tree.getTag() != JCTree.SKIP) alive = true;
530 }
531 scan(tree);
532 }
534 /** Analyze list of statements.
535 */
536 void scanStats(List<? extends JCStatement> trees) {
537 if (trees != null)
538 for (List<? extends JCStatement> l = trees; l.nonEmpty(); l = l.tail)
539 scanStat(l.head);
540 }
542 /** Analyze an expression. Make sure to set (un)inits rather than
543 * (un)initsWhenTrue(WhenFalse) on exit.
544 */
545 void scanExpr(JCTree tree) {
546 if (tree != null) {
547 scan(tree);
548 if (inits == null) merge();
549 }
550 }
552 /** Analyze a list of expressions.
553 */
554 void scanExprs(List<? extends JCExpression> trees) {
555 if (trees != null)
556 for (List<? extends JCExpression> l = trees; l.nonEmpty(); l = l.tail)
557 scanExpr(l.head);
558 }
560 /** Analyze a condition. Make sure to set (un)initsWhenTrue(WhenFalse)
561 * rather than (un)inits on exit.
562 */
563 void scanCond(JCTree tree) {
564 if (tree.type.isFalse()) {
565 if (inits == null) merge();
566 initsWhenTrue = inits.dup();
567 initsWhenTrue.inclRange(firstadr, nextadr);
568 uninitsWhenTrue = uninits.dup();
569 uninitsWhenTrue.inclRange(firstadr, nextadr);
570 initsWhenFalse = inits;
571 uninitsWhenFalse = uninits;
572 } else if (tree.type.isTrue()) {
573 if (inits == null) merge();
574 initsWhenFalse = inits.dup();
575 initsWhenFalse.inclRange(firstadr, nextadr);
576 uninitsWhenFalse = uninits.dup();
577 uninitsWhenFalse.inclRange(firstadr, nextadr);
578 initsWhenTrue = inits;
579 uninitsWhenTrue = uninits;
580 } else {
581 scan(tree);
582 if (inits != null)
583 split(tree.type != syms.unknownType);
584 }
585 if (tree.type != syms.unknownType)
586 inits = uninits = null;
587 }
589 /* ------------ Visitor methods for various sorts of trees -------------*/
591 public void visitClassDef(JCClassDecl tree) {
592 if (tree.sym == null) return;
594 JCClassDecl classDefPrev = classDef;
595 List<Type> thrownPrev = thrown;
596 List<Type> caughtPrev = caught;
597 boolean alivePrev = alive;
598 int firstadrPrev = firstadr;
599 int nextadrPrev = nextadr;
600 ListBuffer<PendingExit> pendingExitsPrev = pendingExits;
601 Lint lintPrev = lint;
603 pendingExits = new ListBuffer<PendingExit>();
604 if (tree.name != names.empty) {
605 caught = List.nil();
606 firstadr = nextadr;
607 }
608 classDef = tree;
609 thrown = List.nil();
610 lint = lint.augment(tree.sym.attributes_field);
612 try {
613 // define all the static fields
614 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
615 if (l.head.getTag() == JCTree.VARDEF) {
616 JCVariableDecl def = (JCVariableDecl)l.head;
617 if ((def.mods.flags & STATIC) != 0) {
618 VarSymbol sym = def.sym;
619 if (trackable(sym))
620 newVar(sym);
621 }
622 }
623 }
625 // process all the static initializers
626 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
627 if (l.head.getTag() != JCTree.METHODDEF &&
628 (TreeInfo.flags(l.head) & STATIC) != 0) {
629 scanDef(l.head);
630 errorUncaught();
631 }
632 }
634 // add intersection of all thrown clauses of initial constructors
635 // to set of caught exceptions, unless class is anonymous.
636 if (tree.name != names.empty) {
637 boolean firstConstructor = true;
638 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
639 if (TreeInfo.isInitialConstructor(l.head)) {
640 List<Type> mthrown =
641 ((JCMethodDecl) l.head).sym.type.getThrownTypes();
642 if (firstConstructor) {
643 caught = mthrown;
644 firstConstructor = false;
645 } else {
646 caught = chk.intersect(mthrown, caught);
647 }
648 }
649 }
650 }
652 // define all the instance fields
653 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
654 if (l.head.getTag() == JCTree.VARDEF) {
655 JCVariableDecl def = (JCVariableDecl)l.head;
656 if ((def.mods.flags & STATIC) == 0) {
657 VarSymbol sym = def.sym;
658 if (trackable(sym))
659 newVar(sym);
660 }
661 }
662 }
664 // process all the instance initializers
665 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
666 if (l.head.getTag() != JCTree.METHODDEF &&
667 (TreeInfo.flags(l.head) & STATIC) == 0) {
668 scanDef(l.head);
669 errorUncaught();
670 }
671 }
673 // in an anonymous class, add the set of thrown exceptions to
674 // the throws clause of the synthetic constructor and propagate
675 // outwards.
676 // Changing the throws clause on the fly is okay here because
677 // the anonymous constructor can't be invoked anywhere else,
678 // and its type hasn't been cached.
679 if (tree.name == names.empty) {
680 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
681 if (TreeInfo.isInitialConstructor(l.head)) {
682 JCMethodDecl mdef = (JCMethodDecl)l.head;
683 mdef.thrown = make.Types(thrown);
684 mdef.sym.type = types.createMethodTypeWithThrown(mdef.sym.type, thrown);
685 }
686 }
687 thrownPrev = chk.union(thrown, thrownPrev);
688 }
690 // process all the methods
691 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
692 if (l.head.getTag() == JCTree.METHODDEF) {
693 scan(l.head);
694 errorUncaught();
695 }
696 }
698 thrown = thrownPrev;
699 } finally {
700 pendingExits = pendingExitsPrev;
701 alive = alivePrev;
702 nextadr = nextadrPrev;
703 firstadr = firstadrPrev;
704 caught = caughtPrev;
705 classDef = classDefPrev;
706 lint = lintPrev;
707 }
708 }
710 public void visitMethodDef(JCMethodDecl tree) {
711 if (tree.body == null) return;
713 List<Type> caughtPrev = caught;
714 List<Type> mthrown = tree.sym.type.getThrownTypes();
715 Bits initsPrev = inits.dup();
716 Bits uninitsPrev = uninits.dup();
717 int nextadrPrev = nextadr;
718 int firstadrPrev = firstadr;
719 Lint lintPrev = lint;
721 lint = lint.augment(tree.sym.attributes_field);
723 Assert.check(pendingExits.isEmpty());
725 try {
726 boolean isInitialConstructor =
727 TreeInfo.isInitialConstructor(tree);
729 if (!isInitialConstructor)
730 firstadr = nextadr;
731 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
732 JCVariableDecl def = l.head;
733 scan(def);
734 inits.incl(def.sym.adr);
735 uninits.excl(def.sym.adr);
736 }
737 if (isInitialConstructor)
738 caught = chk.union(caught, mthrown);
739 else if ((tree.sym.flags() & (BLOCK | STATIC)) != BLOCK)
740 caught = mthrown;
741 // else we are in an instance initializer block;
742 // leave caught unchanged.
744 alive = true;
745 scanStat(tree.body);
747 if (alive && tree.sym.type.getReturnType().tag != VOID)
748 log.error(TreeInfo.diagEndPos(tree.body), "missing.ret.stmt");
750 if (isInitialConstructor) {
751 for (int i = firstadr; i < nextadr; i++)
752 if (vars[i].owner == classDef.sym)
753 checkInit(TreeInfo.diagEndPos(tree.body), vars[i]);
754 }
755 List<PendingExit> exits = pendingExits.toList();
756 pendingExits = new ListBuffer<PendingExit>();
757 while (exits.nonEmpty()) {
758 PendingExit exit = exits.head;
759 exits = exits.tail;
760 if (exit.thrown == null) {
761 Assert.check(exit.tree.getTag() == JCTree.RETURN);
762 if (isInitialConstructor) {
763 inits = exit.inits;
764 for (int i = firstadr; i < nextadr; i++)
765 checkInit(exit.tree.pos(), vars[i]);
766 }
767 } else {
768 // uncaught throws will be reported later
769 pendingExits.append(exit);
770 }
771 }
772 } finally {
773 inits = initsPrev;
774 uninits = uninitsPrev;
775 nextadr = nextadrPrev;
776 firstadr = firstadrPrev;
777 caught = caughtPrev;
778 lint = lintPrev;
779 }
780 }
782 public void visitVarDef(JCVariableDecl tree) {
783 boolean track = trackable(tree.sym);
784 if (track && tree.sym.owner.kind == MTH) newVar(tree.sym);
785 if (tree.init != null) {
786 Lint lintPrev = lint;
787 lint = lint.augment(tree.sym.attributes_field);
788 try{
789 scanExpr(tree.init);
790 if (track) letInit(tree.pos(), tree.sym);
791 } finally {
792 lint = lintPrev;
793 }
794 }
795 }
797 public void visitBlock(JCBlock tree) {
798 int nextadrPrev = nextadr;
799 scanStats(tree.stats);
800 nextadr = nextadrPrev;
801 }
803 public void visitDoLoop(JCDoWhileLoop tree) {
804 ListBuffer<PendingExit> prevPendingExits = pendingExits;
805 boolean prevLoopPassTwo = loopPassTwo;
806 pendingExits = new ListBuffer<PendingExit>();
807 int prevErrors = log.nerrors;
808 do {
809 Bits uninitsEntry = uninits.dup();
810 uninitsEntry.excludeFrom(nextadr);
811 scanStat(tree.body);
812 alive |= resolveContinues(tree);
813 scanCond(tree.cond);
814 if (log.nerrors != prevErrors ||
815 loopPassTwo ||
816 uninitsEntry.dup().diffSet(uninitsWhenTrue).nextBit(firstadr)==-1)
817 break;
818 inits = initsWhenTrue;
819 uninits = uninitsEntry.andSet(uninitsWhenTrue);
820 loopPassTwo = true;
821 alive = true;
822 } while (true);
823 loopPassTwo = prevLoopPassTwo;
824 inits = initsWhenFalse;
825 uninits = uninitsWhenFalse;
826 alive = alive && !tree.cond.type.isTrue();
827 alive |= resolveBreaks(tree, prevPendingExits);
828 }
830 public void visitWhileLoop(JCWhileLoop tree) {
831 ListBuffer<PendingExit> prevPendingExits = pendingExits;
832 boolean prevLoopPassTwo = loopPassTwo;
833 Bits initsCond;
834 Bits uninitsCond;
835 pendingExits = new ListBuffer<PendingExit>();
836 int prevErrors = log.nerrors;
837 do {
838 Bits uninitsEntry = uninits.dup();
839 uninitsEntry.excludeFrom(nextadr);
840 scanCond(tree.cond);
841 initsCond = initsWhenFalse;
842 uninitsCond = uninitsWhenFalse;
843 inits = initsWhenTrue;
844 uninits = uninitsWhenTrue;
845 alive = !tree.cond.type.isFalse();
846 scanStat(tree.body);
847 alive |= resolveContinues(tree);
848 if (log.nerrors != prevErrors ||
849 loopPassTwo ||
850 uninitsEntry.dup().diffSet(uninits).nextBit(firstadr) == -1)
851 break;
852 uninits = uninitsEntry.andSet(uninits);
853 loopPassTwo = true;
854 alive = true;
855 } while (true);
856 loopPassTwo = prevLoopPassTwo;
857 inits = initsCond;
858 uninits = uninitsCond;
859 alive = resolveBreaks(tree, prevPendingExits) ||
860 !tree.cond.type.isTrue();
861 }
863 public void visitForLoop(JCForLoop tree) {
864 ListBuffer<PendingExit> prevPendingExits = pendingExits;
865 boolean prevLoopPassTwo = loopPassTwo;
866 int nextadrPrev = nextadr;
867 scanStats(tree.init);
868 Bits initsCond;
869 Bits uninitsCond;
870 pendingExits = new ListBuffer<PendingExit>();
871 int prevErrors = log.nerrors;
872 do {
873 Bits uninitsEntry = uninits.dup();
874 uninitsEntry.excludeFrom(nextadr);
875 if (tree.cond != null) {
876 scanCond(tree.cond);
877 initsCond = initsWhenFalse;
878 uninitsCond = uninitsWhenFalse;
879 inits = initsWhenTrue;
880 uninits = uninitsWhenTrue;
881 alive = !tree.cond.type.isFalse();
882 } else {
883 initsCond = inits.dup();
884 initsCond.inclRange(firstadr, nextadr);
885 uninitsCond = uninits.dup();
886 uninitsCond.inclRange(firstadr, nextadr);
887 alive = true;
888 }
889 scanStat(tree.body);
890 alive |= resolveContinues(tree);
891 scan(tree.step);
892 if (log.nerrors != prevErrors ||
893 loopPassTwo ||
894 uninitsEntry.dup().diffSet(uninits).nextBit(firstadr) == -1)
895 break;
896 uninits = uninitsEntry.andSet(uninits);
897 loopPassTwo = true;
898 alive = true;
899 } while (true);
900 loopPassTwo = prevLoopPassTwo;
901 inits = initsCond;
902 uninits = uninitsCond;
903 alive = resolveBreaks(tree, prevPendingExits) ||
904 tree.cond != null && !tree.cond.type.isTrue();
905 nextadr = nextadrPrev;
906 }
908 public void visitForeachLoop(JCEnhancedForLoop tree) {
909 visitVarDef(tree.var);
911 ListBuffer<PendingExit> prevPendingExits = pendingExits;
912 boolean prevLoopPassTwo = loopPassTwo;
913 int nextadrPrev = nextadr;
914 scan(tree.expr);
915 Bits initsStart = inits.dup();
916 Bits uninitsStart = uninits.dup();
918 letInit(tree.pos(), tree.var.sym);
919 pendingExits = new ListBuffer<PendingExit>();
920 int prevErrors = log.nerrors;
921 do {
922 Bits uninitsEntry = uninits.dup();
923 uninitsEntry.excludeFrom(nextadr);
924 scanStat(tree.body);
925 alive |= resolveContinues(tree);
926 if (log.nerrors != prevErrors ||
927 loopPassTwo ||
928 uninitsEntry.dup().diffSet(uninits).nextBit(firstadr) == -1)
929 break;
930 uninits = uninitsEntry.andSet(uninits);
931 loopPassTwo = true;
932 alive = true;
933 } while (true);
934 loopPassTwo = prevLoopPassTwo;
935 inits = initsStart;
936 uninits = uninitsStart.andSet(uninits);
937 resolveBreaks(tree, prevPendingExits);
938 alive = true;
939 nextadr = nextadrPrev;
940 }
942 public void visitLabelled(JCLabeledStatement tree) {
943 ListBuffer<PendingExit> prevPendingExits = pendingExits;
944 pendingExits = new ListBuffer<PendingExit>();
945 scanStat(tree.body);
946 alive |= resolveBreaks(tree, prevPendingExits);
947 }
949 public void visitSwitch(JCSwitch tree) {
950 ListBuffer<PendingExit> prevPendingExits = pendingExits;
951 pendingExits = new ListBuffer<PendingExit>();
952 int nextadrPrev = nextadr;
953 scanExpr(tree.selector);
954 Bits initsSwitch = inits;
955 Bits uninitsSwitch = uninits.dup();
956 boolean hasDefault = false;
957 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
958 alive = true;
959 inits = initsSwitch.dup();
960 uninits = uninits.andSet(uninitsSwitch);
961 JCCase c = l.head;
962 if (c.pat == null)
963 hasDefault = true;
964 else
965 scanExpr(c.pat);
966 scanStats(c.stats);
967 addVars(c.stats, initsSwitch, uninitsSwitch);
968 // Warn about fall-through if lint switch fallthrough enabled.
969 if (!loopPassTwo &&
970 alive &&
971 lint.isEnabled(Lint.LintCategory.FALLTHROUGH) &&
972 c.stats.nonEmpty() && l.tail.nonEmpty())
973 log.warning(Lint.LintCategory.FALLTHROUGH,
974 l.tail.head.pos(),
975 "possible.fall-through.into.case");
976 }
977 if (!hasDefault) {
978 inits.andSet(initsSwitch);
979 alive = true;
980 }
981 alive |= resolveBreaks(tree, prevPendingExits);
982 nextadr = nextadrPrev;
983 }
984 // where
985 /** Add any variables defined in stats to inits and uninits. */
986 private static void addVars(List<JCStatement> stats, Bits inits,
987 Bits uninits) {
988 for (;stats.nonEmpty(); stats = stats.tail) {
989 JCTree stat = stats.head;
990 if (stat.getTag() == JCTree.VARDEF) {
991 int adr = ((JCVariableDecl) stat).sym.adr;
992 inits.excl(adr);
993 uninits.incl(adr);
994 }
995 }
996 }
998 public void visitTry(JCTry tree) {
999 List<Type> caughtPrev = caught;
1000 List<Type> thrownPrev = thrown;
1001 thrown = List.nil();
1002 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1003 List<JCExpression> subClauses = TreeInfo.isMultiCatch(l.head) ?
1004 ((JCTypeDisjunction)l.head.param.vartype).alternatives :
1005 List.of(l.head.param.vartype);
1006 for (JCExpression ct : subClauses) {
1007 caught = chk.incl(ct.type, caught);
1008 }
1009 }
1010 ListBuffer<JCVariableDecl> resourceVarDecls = ListBuffer.lb();
1011 Bits uninitsTryPrev = uninitsTry;
1012 ListBuffer<PendingExit> prevPendingExits = pendingExits;
1013 pendingExits = new ListBuffer<PendingExit>();
1014 Bits initsTry = inits.dup();
1015 uninitsTry = uninits.dup();
1016 for (JCTree resource : tree.resources) {
1017 if (resource instanceof JCVariableDecl) {
1018 JCVariableDecl vdecl = (JCVariableDecl) resource;
1019 visitVarDef(vdecl);
1020 unrefdResources.enter(vdecl.sym);
1021 resourceVarDecls.append(vdecl);
1022 } else if (resource instanceof JCExpression) {
1023 scanExpr((JCExpression) resource);
1024 } else {
1025 throw new AssertionError(tree); // parser error
1026 }
1027 }
1028 for (JCTree resource : tree.resources) {
1029 List<Type> closeableSupertypes = resource.type.isCompound() ?
1030 types.interfaces(resource.type).prepend(types.supertype(resource.type)) :
1031 List.of(resource.type);
1032 for (Type sup : closeableSupertypes) {
1033 if (types.asSuper(sup, syms.autoCloseableType.tsym) != null) {
1034 Symbol closeMethod = rs.resolveQualifiedMethod(tree,
1035 attrEnv,
1036 sup,
1037 names.close,
1038 List.<Type>nil(),
1039 List.<Type>nil());
1040 if (closeMethod.kind == MTH) {
1041 for (Type t : ((MethodSymbol)closeMethod).getThrownTypes()) {
1042 markThrown(resource, t);
1043 }
1044 }
1045 }
1046 }
1047 }
1048 scanStat(tree.body);
1049 List<Type> thrownInTry = thrown;
1050 thrown = thrownPrev;
1051 caught = caughtPrev;
1052 boolean aliveEnd = alive;
1053 uninitsTry.andSet(uninits);
1054 Bits initsEnd = inits;
1055 Bits uninitsEnd = uninits;
1056 int nextadrCatch = nextadr;
1058 if (!resourceVarDecls.isEmpty() &&
1059 lint.isEnabled(Lint.LintCategory.TRY)) {
1060 for (JCVariableDecl resVar : resourceVarDecls) {
1061 if (unrefdResources.includes(resVar.sym)) {
1062 log.warning(Lint.LintCategory.TRY, resVar.pos(),
1063 "try.resource.not.referenced", resVar.sym);
1064 unrefdResources.remove(resVar.sym);
1065 }
1066 }
1067 }
1069 List<Type> caughtInTry = List.nil();
1070 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1071 alive = true;
1072 JCVariableDecl param = l.head.param;
1073 List<JCExpression> subClauses = TreeInfo.isMultiCatch(l.head) ?
1074 ((JCTypeDisjunction)l.head.param.vartype).alternatives :
1075 List.of(l.head.param.vartype);
1076 List<Type> ctypes = List.nil();
1077 List<Type> rethrownTypes = chk.diff(thrownInTry, caughtInTry);
1078 for (JCExpression ct : subClauses) {
1079 Type exc = ct.type;
1080 if (exc != syms.unknownType) {
1081 ctypes = ctypes.append(exc);
1082 if (types.isSameType(exc, syms.objectType))
1083 continue;
1084 if (chk.subset(exc, caughtInTry)) {
1085 log.error(l.head.pos(),
1086 "except.already.caught", exc);
1087 } else if (!chk.isUnchecked(l.head.pos(), exc) &&
1088 exc.tsym != syms.throwableType.tsym &&
1089 exc.tsym != syms.exceptionType.tsym &&
1090 !chk.intersects(exc, thrownInTry)) {
1091 log.error(l.head.pos(),
1092 "except.never.thrown.in.try", exc);
1093 }
1094 caughtInTry = chk.incl(exc, caughtInTry);
1095 }
1096 }
1097 inits = initsTry.dup();
1098 uninits = uninitsTry.dup();
1099 scan(param);
1100 inits.incl(param.sym.adr);
1101 uninits.excl(param.sym.adr);
1102 preciseRethrowTypes.put(param.sym, chk.intersect(ctypes, rethrownTypes));
1103 scanStat(l.head.body);
1104 initsEnd.andSet(inits);
1105 uninitsEnd.andSet(uninits);
1106 nextadr = nextadrCatch;
1107 preciseRethrowTypes.remove(param.sym);
1108 aliveEnd |= alive;
1109 }
1110 if (tree.finalizer != null) {
1111 List<Type> savedThrown = thrown;
1112 thrown = List.nil();
1113 inits = initsTry.dup();
1114 uninits = uninitsTry.dup();
1115 ListBuffer<PendingExit> exits = pendingExits;
1116 pendingExits = prevPendingExits;
1117 alive = true;
1118 scanStat(tree.finalizer);
1119 if (!alive) {
1120 // discard exits and exceptions from try and finally
1121 thrown = chk.union(thrown, thrownPrev);
1122 if (!loopPassTwo &&
1123 lint.isEnabled(Lint.LintCategory.FINALLY)) {
1124 log.warning(Lint.LintCategory.FINALLY,
1125 TreeInfo.diagEndPos(tree.finalizer),
1126 "finally.cannot.complete");
1127 }
1128 } else {
1129 thrown = chk.union(thrown, chk.diff(thrownInTry, caughtInTry));
1130 thrown = chk.union(thrown, savedThrown);
1131 uninits.andSet(uninitsEnd);
1132 // FIX: this doesn't preserve source order of exits in catch
1133 // versus finally!
1134 while (exits.nonEmpty()) {
1135 PendingExit exit = exits.next();
1136 if (exit.inits != null) {
1137 exit.inits.orSet(inits);
1138 exit.uninits.andSet(uninits);
1139 }
1140 pendingExits.append(exit);
1141 }
1142 inits.orSet(initsEnd);
1143 alive = aliveEnd;
1144 }
1145 } else {
1146 thrown = chk.union(thrown, chk.diff(thrownInTry, caughtInTry));
1147 inits = initsEnd;
1148 uninits = uninitsEnd;
1149 alive = aliveEnd;
1150 ListBuffer<PendingExit> exits = pendingExits;
1151 pendingExits = prevPendingExits;
1152 while (exits.nonEmpty()) pendingExits.append(exits.next());
1153 }
1154 uninitsTry.andSet(uninitsTryPrev).andSet(uninits);
1155 }
1157 public void visitConditional(JCConditional tree) {
1158 scanCond(tree.cond);
1159 Bits initsBeforeElse = initsWhenFalse;
1160 Bits uninitsBeforeElse = uninitsWhenFalse;
1161 inits = initsWhenTrue;
1162 uninits = uninitsWhenTrue;
1163 if (tree.truepart.type.tag == BOOLEAN &&
1164 tree.falsepart.type.tag == BOOLEAN) {
1165 // if b and c are boolean valued, then
1166 // v is (un)assigned after a?b:c when true iff
1167 // v is (un)assigned after b when true and
1168 // v is (un)assigned after c when true
1169 scanCond(tree.truepart);
1170 Bits initsAfterThenWhenTrue = initsWhenTrue.dup();
1171 Bits initsAfterThenWhenFalse = initsWhenFalse.dup();
1172 Bits uninitsAfterThenWhenTrue = uninitsWhenTrue.dup();
1173 Bits uninitsAfterThenWhenFalse = uninitsWhenFalse.dup();
1174 inits = initsBeforeElse;
1175 uninits = uninitsBeforeElse;
1176 scanCond(tree.falsepart);
1177 initsWhenTrue.andSet(initsAfterThenWhenTrue);
1178 initsWhenFalse.andSet(initsAfterThenWhenFalse);
1179 uninitsWhenTrue.andSet(uninitsAfterThenWhenTrue);
1180 uninitsWhenFalse.andSet(uninitsAfterThenWhenFalse);
1181 } else {
1182 scanExpr(tree.truepart);
1183 Bits initsAfterThen = inits.dup();
1184 Bits uninitsAfterThen = uninits.dup();
1185 inits = initsBeforeElse;
1186 uninits = uninitsBeforeElse;
1187 scanExpr(tree.falsepart);
1188 inits.andSet(initsAfterThen);
1189 uninits.andSet(uninitsAfterThen);
1190 }
1191 }
1193 public void visitIf(JCIf tree) {
1194 scanCond(tree.cond);
1195 Bits initsBeforeElse = initsWhenFalse;
1196 Bits uninitsBeforeElse = uninitsWhenFalse;
1197 inits = initsWhenTrue;
1198 uninits = uninitsWhenTrue;
1199 scanStat(tree.thenpart);
1200 if (tree.elsepart != null) {
1201 boolean aliveAfterThen = alive;
1202 alive = true;
1203 Bits initsAfterThen = inits.dup();
1204 Bits uninitsAfterThen = uninits.dup();
1205 inits = initsBeforeElse;
1206 uninits = uninitsBeforeElse;
1207 scanStat(tree.elsepart);
1208 inits.andSet(initsAfterThen);
1209 uninits.andSet(uninitsAfterThen);
1210 alive = alive | aliveAfterThen;
1211 } else {
1212 inits.andSet(initsBeforeElse);
1213 uninits.andSet(uninitsBeforeElse);
1214 alive = true;
1215 }
1216 }
1220 public void visitBreak(JCBreak tree) {
1221 recordExit(tree);
1222 }
1224 public void visitContinue(JCContinue tree) {
1225 recordExit(tree);
1226 }
1228 public void visitReturn(JCReturn tree) {
1229 scanExpr(tree.expr);
1230 // if not initial constructor, should markDead instead of recordExit
1231 recordExit(tree);
1232 }
1234 public void visitThrow(JCThrow tree) {
1235 scanExpr(tree.expr);
1236 Symbol sym = TreeInfo.symbol(tree.expr);
1237 if (sym != null &&
1238 sym.kind == VAR &&
1239 (sym.flags() & (FINAL | EFFECTIVELY_FINAL)) != 0 &&
1240 preciseRethrowTypes.get(sym) != null &&
1241 allowRethrowAnalysis) {
1242 for (Type t : preciseRethrowTypes.get(sym)) {
1243 markThrown(tree, t);
1244 }
1245 }
1246 else {
1247 markThrown(tree, tree.expr.type);
1248 }
1249 markDead();
1250 }
1252 public void visitApply(JCMethodInvocation tree) {
1253 scanExpr(tree.meth);
1254 scanExprs(tree.args);
1255 for (List<Type> l = tree.meth.type.getThrownTypes(); l.nonEmpty(); l = l.tail)
1256 markThrown(tree, l.head);
1257 }
1259 public void visitNewClass(JCNewClass tree) {
1260 scanExpr(tree.encl);
1261 scanExprs(tree.args);
1262 // scan(tree.def);
1263 for (List<Type> l = tree.constructorType.getThrownTypes();
1264 l.nonEmpty();
1265 l = l.tail) {
1266 markThrown(tree, l.head);
1267 }
1268 List<Type> caughtPrev = caught;
1269 try {
1270 // If the new class expression defines an anonymous class,
1271 // analysis of the anonymous constructor may encounter thrown
1272 // types which are unsubstituted type variables.
1273 // However, since the constructor's actual thrown types have
1274 // already been marked as thrown, it is safe to simply include
1275 // each of the constructor's formal thrown types in the set of
1276 // 'caught/declared to be thrown' types, for the duration of
1277 // the class def analysis.
1278 if (tree.def != null)
1279 for (List<Type> l = tree.constructor.type.getThrownTypes();
1280 l.nonEmpty();
1281 l = l.tail) {
1282 caught = chk.incl(l.head, caught);
1283 }
1284 scan(tree.def);
1285 }
1286 finally {
1287 caught = caughtPrev;
1288 }
1289 }
1291 public void visitNewArray(JCNewArray tree) {
1292 scanExprs(tree.dims);
1293 scanExprs(tree.elems);
1294 }
1296 public void visitAssert(JCAssert tree) {
1297 Bits initsExit = inits.dup();
1298 Bits uninitsExit = uninits.dup();
1299 scanCond(tree.cond);
1300 uninitsExit.andSet(uninitsWhenTrue);
1301 if (tree.detail != null) {
1302 inits = initsWhenFalse;
1303 uninits = uninitsWhenFalse;
1304 scanExpr(tree.detail);
1305 }
1306 inits = initsExit;
1307 uninits = uninitsExit;
1308 }
1310 public void visitAssign(JCAssign tree) {
1311 JCTree lhs = TreeInfo.skipParens(tree.lhs);
1312 if (!(lhs instanceof JCIdent)) scanExpr(lhs);
1313 scanExpr(tree.rhs);
1314 letInit(lhs);
1315 }
1317 public void visitAssignop(JCAssignOp tree) {
1318 scanExpr(tree.lhs);
1319 scanExpr(tree.rhs);
1320 letInit(tree.lhs);
1321 }
1323 public void visitUnary(JCUnary tree) {
1324 switch (tree.getTag()) {
1325 case JCTree.NOT:
1326 scanCond(tree.arg);
1327 Bits t = initsWhenFalse;
1328 initsWhenFalse = initsWhenTrue;
1329 initsWhenTrue = t;
1330 t = uninitsWhenFalse;
1331 uninitsWhenFalse = uninitsWhenTrue;
1332 uninitsWhenTrue = t;
1333 break;
1334 case JCTree.PREINC: case JCTree.POSTINC:
1335 case JCTree.PREDEC: case JCTree.POSTDEC:
1336 scanExpr(tree.arg);
1337 letInit(tree.arg);
1338 break;
1339 default:
1340 scanExpr(tree.arg);
1341 }
1342 }
1344 public void visitBinary(JCBinary tree) {
1345 switch (tree.getTag()) {
1346 case JCTree.AND:
1347 scanCond(tree.lhs);
1348 Bits initsWhenFalseLeft = initsWhenFalse;
1349 Bits uninitsWhenFalseLeft = uninitsWhenFalse;
1350 inits = initsWhenTrue;
1351 uninits = uninitsWhenTrue;
1352 scanCond(tree.rhs);
1353 initsWhenFalse.andSet(initsWhenFalseLeft);
1354 uninitsWhenFalse.andSet(uninitsWhenFalseLeft);
1355 break;
1356 case JCTree.OR:
1357 scanCond(tree.lhs);
1358 Bits initsWhenTrueLeft = initsWhenTrue;
1359 Bits uninitsWhenTrueLeft = uninitsWhenTrue;
1360 inits = initsWhenFalse;
1361 uninits = uninitsWhenFalse;
1362 scanCond(tree.rhs);
1363 initsWhenTrue.andSet(initsWhenTrueLeft);
1364 uninitsWhenTrue.andSet(uninitsWhenTrueLeft);
1365 break;
1366 default:
1367 scanExpr(tree.lhs);
1368 scanExpr(tree.rhs);
1369 }
1370 }
1372 public void visitIdent(JCIdent tree) {
1373 if (tree.sym.kind == VAR) {
1374 checkInit(tree.pos(), (VarSymbol)tree.sym);
1375 referenced(tree.sym);
1376 }
1377 }
1379 void referenced(Symbol sym) {
1380 unrefdResources.remove(sym);
1381 }
1383 public void visitTypeCast(JCTypeCast tree) {
1384 super.visitTypeCast(tree);
1385 if (!tree.type.isErroneous()
1386 && lint.isEnabled(Lint.LintCategory.CAST)
1387 && types.isSameType(tree.expr.type, tree.clazz.type)
1388 && !is292targetTypeCast(tree)) {
1389 log.warning(Lint.LintCategory.CAST,
1390 tree.pos(), "redundant.cast", tree.expr.type);
1391 }
1392 }
1393 //where
1394 private boolean is292targetTypeCast(JCTypeCast tree) {
1395 boolean is292targetTypeCast = false;
1396 JCExpression expr = TreeInfo.skipParens(tree.expr);
1397 if (expr.getTag() == JCTree.APPLY) {
1398 JCMethodInvocation apply = (JCMethodInvocation)expr;
1399 Symbol sym = TreeInfo.symbol(apply.meth);
1400 is292targetTypeCast = sym != null &&
1401 sym.kind == MTH &&
1402 (sym.flags() & POLYMORPHIC_SIGNATURE) != 0;
1403 }
1404 return is292targetTypeCast;
1405 }
1407 public void visitTopLevel(JCCompilationUnit tree) {
1408 // Do nothing for TopLevel since each class is visited individually
1409 }
1411 /**************************************************************************
1412 * main method
1413 *************************************************************************/
1415 /** Perform definite assignment/unassignment analysis on a tree.
1416 */
1417 public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
1418 try {
1419 attrEnv = env;
1420 JCTree tree = env.tree;
1421 this.make = make;
1422 inits = new Bits();
1423 uninits = new Bits();
1424 uninitsTry = new Bits();
1425 initsWhenTrue = initsWhenFalse =
1426 uninitsWhenTrue = uninitsWhenFalse = null;
1427 if (vars == null)
1428 vars = new VarSymbol[32];
1429 else
1430 for (int i=0; i<vars.length; i++)
1431 vars[i] = null;
1432 firstadr = 0;
1433 nextadr = 0;
1434 pendingExits = new ListBuffer<PendingExit>();
1435 preciseRethrowTypes = new HashMap<Symbol, List<Type>>();
1436 alive = true;
1437 this.thrown = this.caught = null;
1438 this.classDef = null;
1439 unrefdResources = new Scope(env.enclClass.sym);
1440 scan(tree);
1441 } finally {
1442 // note that recursive invocations of this method fail hard
1443 inits = uninits = uninitsTry = null;
1444 initsWhenTrue = initsWhenFalse =
1445 uninitsWhenTrue = uninitsWhenFalse = null;
1446 if (vars != null) for (int i=0; i<vars.length; i++)
1447 vars[i] = null;
1448 firstadr = 0;
1449 nextadr = 0;
1450 pendingExits = null;
1451 this.make = null;
1452 this.thrown = this.caught = null;
1453 this.classDef = null;
1454 unrefdResources = null;
1455 }
1456 }
1457 }