src/share/classes/com/sun/tools/javac/comp/Flow.java

Tue, 04 Jun 2013 14:17:50 -0700

author
jjg
date
Tue, 04 Jun 2013 14:17:50 -0700
changeset 1802
8fb68f73d4b1
parent 1790
9f11c7676cd5
child 1879
3b4f92a3797f
permissions
-rw-r--r--

8004643: Reduce javac space overhead introduced with compiler support for repeating annotations
Reviewed-by: mcimadamore, jfranck

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

mercurial