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

Mon, 10 Dec 2012 16:21:26 +0000

author
vromero
date
Mon, 10 Dec 2012 16:21:26 +0000
changeset 1442
fcf89720ae71
parent 1415
01c9d4161882
child 1521
71f35e4b93a5
permissions
-rw-r--r--

8003967: detect and remove all mutable implicit static enum fields in langtools
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2012, 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      * Base visitor class for all visitors implementing dataflow analysis logic.
   280      * This class define the shared logic for handling jumps (break/continue statements).
   281      */
   282     static abstract class BaseAnalyzer<P extends BaseAnalyzer.PendingExit> extends TreeScanner {
   284         enum JumpKind {
   285             BREAK(JCTree.Tag.BREAK) {
   286                 @Override
   287                 JCTree getTarget(JCTree tree) {
   288                     return ((JCBreak)tree).target;
   289                 }
   290             },
   291             CONTINUE(JCTree.Tag.CONTINUE) {
   292                 @Override
   293                 JCTree getTarget(JCTree tree) {
   294                     return ((JCContinue)tree).target;
   295                 }
   296             };
   298             final JCTree.Tag treeTag;
   300             private JumpKind(Tag treeTag) {
   301                 this.treeTag = treeTag;
   302             }
   304             abstract JCTree getTarget(JCTree tree);
   305         }
   307         /** The currently pending exits that go from current inner blocks
   308          *  to an enclosing block, in source order.
   309          */
   310         ListBuffer<P> pendingExits;
   312         /** A pending exit.  These are the statements return, break, and
   313          *  continue.  In addition, exception-throwing expressions or
   314          *  statements are put here when not known to be caught.  This
   315          *  will typically result in an error unless it is within a
   316          *  try-finally whose finally block cannot complete normally.
   317          */
   318         static class PendingExit {
   319             JCTree tree;
   321             PendingExit(JCTree tree) {
   322                 this.tree = tree;
   323             }
   325             void resolveJump() {
   326                 //do nothing
   327             }
   328         }
   330         abstract void markDead();
   332         /** Record an outward transfer of control. */
   333         void recordExit(JCTree tree, P pe) {
   334             pendingExits.append(pe);
   335             markDead();
   336         }
   338         /** Resolve all jumps of this statement. */
   339         private boolean resolveJump(JCTree tree,
   340                         ListBuffer<P> oldPendingExits,
   341                         JumpKind jk) {
   342             boolean resolved = false;
   343             List<P> exits = pendingExits.toList();
   344             pendingExits = oldPendingExits;
   345             for (; exits.nonEmpty(); exits = exits.tail) {
   346                 P exit = exits.head;
   347                 if (exit.tree.hasTag(jk.treeTag) &&
   348                         jk.getTarget(exit.tree) == tree) {
   349                     exit.resolveJump();
   350                     resolved = true;
   351                 } else {
   352                     pendingExits.append(exit);
   353                 }
   354             }
   355             return resolved;
   356         }
   358         /** Resolve all breaks of this statement. */
   359         boolean resolveContinues(JCTree tree) {
   360             return resolveJump(tree, new ListBuffer<P>(), JumpKind.CONTINUE);
   361         }
   363         /** Resolve all continues of this statement. */
   364         boolean resolveBreaks(JCTree tree, ListBuffer<P> oldPendingExits) {
   365             return resolveJump(tree, oldPendingExits, JumpKind.BREAK);
   366         }
   367     }
   369     /**
   370      * This pass implements the first step of the dataflow analysis, namely
   371      * the liveness analysis check. This checks that every statement is reachable.
   372      * The output of this analysis pass are used by other analyzers. This analyzer
   373      * sets the 'finallyCanCompleteNormally' field in the JCTry class.
   374      */
   375     class AliveAnalyzer extends BaseAnalyzer<BaseAnalyzer.PendingExit> {
   377         /** A flag that indicates whether the last statement could
   378          *  complete normally.
   379          */
   380         private boolean alive;
   382         @Override
   383         void markDead() {
   384             alive = false;
   385         }
   387     /*************************************************************************
   388      * Visitor methods for statements and definitions
   389      *************************************************************************/
   391         /** Analyze a definition.
   392          */
   393         void scanDef(JCTree tree) {
   394             scanStat(tree);
   395             if (tree != null && tree.hasTag(JCTree.Tag.BLOCK) && !alive) {
   396                 log.error(tree.pos(),
   397                           "initializer.must.be.able.to.complete.normally");
   398             }
   399         }
   401         /** Analyze a statement. Check that statement is reachable.
   402          */
   403         void scanStat(JCTree tree) {
   404             if (!alive && tree != null) {
   405                 log.error(tree.pos(), "unreachable.stmt");
   406                 if (!tree.hasTag(SKIP)) alive = true;
   407             }
   408             scan(tree);
   409         }
   411         /** Analyze list of statements.
   412          */
   413         void scanStats(List<? extends JCStatement> trees) {
   414             if (trees != null)
   415                 for (List<? extends JCStatement> l = trees; l.nonEmpty(); l = l.tail)
   416                     scanStat(l.head);
   417         }
   419         /* ------------ Visitor methods for various sorts of trees -------------*/
   421         public void visitClassDef(JCClassDecl tree) {
   422             if (tree.sym == null) return;
   423             boolean alivePrev = alive;
   424             ListBuffer<PendingExit> pendingExitsPrev = pendingExits;
   425             Lint lintPrev = lint;
   427             pendingExits = new ListBuffer<PendingExit>();
   428             lint = lint.augment(tree.sym.annotations);
   430             try {
   431                 // process all the static initializers
   432                 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
   433                     if (!l.head.hasTag(METHODDEF) &&
   434                         (TreeInfo.flags(l.head) & STATIC) != 0) {
   435                         scanDef(l.head);
   436                     }
   437                 }
   439                 // process all the instance initializers
   440                 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
   441                     if (!l.head.hasTag(METHODDEF) &&
   442                         (TreeInfo.flags(l.head) & STATIC) == 0) {
   443                         scanDef(l.head);
   444                     }
   445                 }
   447                 // process all the methods
   448                 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
   449                     if (l.head.hasTag(METHODDEF)) {
   450                         scan(l.head);
   451                     }
   452                 }
   453             } finally {
   454                 pendingExits = pendingExitsPrev;
   455                 alive = alivePrev;
   456                 lint = lintPrev;
   457             }
   458         }
   460         public void visitMethodDef(JCMethodDecl tree) {
   461             if (tree.body == null) return;
   462             Lint lintPrev = lint;
   464             lint = lint.augment(tree.sym.annotations);
   466             Assert.check(pendingExits.isEmpty());
   468             try {
   469                 alive = true;
   470                 scanStat(tree.body);
   472                 if (alive && !tree.sym.type.getReturnType().hasTag(VOID))
   473                     log.error(TreeInfo.diagEndPos(tree.body), "missing.ret.stmt");
   475                 List<PendingExit> exits = pendingExits.toList();
   476                 pendingExits = new ListBuffer<PendingExit>();
   477                 while (exits.nonEmpty()) {
   478                     PendingExit exit = exits.head;
   479                     exits = exits.tail;
   480                     Assert.check(exit.tree.hasTag(RETURN));
   481                 }
   482             } finally {
   483                 lint = lintPrev;
   484             }
   485         }
   487         public void visitVarDef(JCVariableDecl tree) {
   488             if (tree.init != null) {
   489                 Lint lintPrev = lint;
   490                 lint = lint.augment(tree.sym.annotations);
   491                 try{
   492                     scan(tree.init);
   493                 } finally {
   494                     lint = lintPrev;
   495                 }
   496             }
   497         }
   499         public void visitBlock(JCBlock tree) {
   500             scanStats(tree.stats);
   501         }
   503         public void visitDoLoop(JCDoWhileLoop tree) {
   504             ListBuffer<PendingExit> prevPendingExits = pendingExits;
   505             pendingExits = new ListBuffer<PendingExit>();
   506             scanStat(tree.body);
   507             alive |= resolveContinues(tree);
   508             scan(tree.cond);
   509             alive = alive && !tree.cond.type.isTrue();
   510             alive |= resolveBreaks(tree, prevPendingExits);
   511         }
   513         public void visitWhileLoop(JCWhileLoop tree) {
   514             ListBuffer<PendingExit> prevPendingExits = pendingExits;
   515             pendingExits = new ListBuffer<PendingExit>();
   516             scan(tree.cond);
   517             alive = !tree.cond.type.isFalse();
   518             scanStat(tree.body);
   519             alive |= resolveContinues(tree);
   520             alive = resolveBreaks(tree, prevPendingExits) ||
   521                 !tree.cond.type.isTrue();
   522         }
   524         public void visitForLoop(JCForLoop tree) {
   525             ListBuffer<PendingExit> prevPendingExits = pendingExits;
   526             scanStats(tree.init);
   527             pendingExits = new ListBuffer<PendingExit>();
   528             if (tree.cond != null) {
   529                 scan(tree.cond);
   530                 alive = !tree.cond.type.isFalse();
   531             } else {
   532                 alive = true;
   533             }
   534             scanStat(tree.body);
   535             alive |= resolveContinues(tree);
   536             scan(tree.step);
   537             alive = resolveBreaks(tree, prevPendingExits) ||
   538                 tree.cond != null && !tree.cond.type.isTrue();
   539         }
   541         public void visitForeachLoop(JCEnhancedForLoop tree) {
   542             visitVarDef(tree.var);
   543             ListBuffer<PendingExit> prevPendingExits = pendingExits;
   544             scan(tree.expr);
   545             pendingExits = new ListBuffer<PendingExit>();
   546             scanStat(tree.body);
   547             alive |= resolveContinues(tree);
   548             resolveBreaks(tree, prevPendingExits);
   549             alive = true;
   550         }
   552         public void visitLabelled(JCLabeledStatement tree) {
   553             ListBuffer<PendingExit> prevPendingExits = pendingExits;
   554             pendingExits = new ListBuffer<PendingExit>();
   555             scanStat(tree.body);
   556             alive |= resolveBreaks(tree, prevPendingExits);
   557         }
   559         public void visitSwitch(JCSwitch tree) {
   560             ListBuffer<PendingExit> prevPendingExits = pendingExits;
   561             pendingExits = new ListBuffer<PendingExit>();
   562             scan(tree.selector);
   563             boolean hasDefault = false;
   564             for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
   565                 alive = true;
   566                 JCCase c = l.head;
   567                 if (c.pat == null)
   568                     hasDefault = true;
   569                 else
   570                     scan(c.pat);
   571                 scanStats(c.stats);
   572                 // Warn about fall-through if lint switch fallthrough enabled.
   573                 if (alive &&
   574                     lint.isEnabled(Lint.LintCategory.FALLTHROUGH) &&
   575                     c.stats.nonEmpty() && l.tail.nonEmpty())
   576                     log.warning(Lint.LintCategory.FALLTHROUGH,
   577                                 l.tail.head.pos(),
   578                                 "possible.fall-through.into.case");
   579             }
   580             if (!hasDefault) {
   581                 alive = true;
   582             }
   583             alive |= resolveBreaks(tree, prevPendingExits);
   584         }
   586         public void visitTry(JCTry tree) {
   587             ListBuffer<PendingExit> prevPendingExits = pendingExits;
   588             pendingExits = new ListBuffer<PendingExit>();
   589             for (JCTree resource : tree.resources) {
   590                 if (resource instanceof JCVariableDecl) {
   591                     JCVariableDecl vdecl = (JCVariableDecl) resource;
   592                     visitVarDef(vdecl);
   593                 } else if (resource instanceof JCExpression) {
   594                     scan((JCExpression) resource);
   595                 } else {
   596                     throw new AssertionError(tree);  // parser error
   597                 }
   598             }
   600             scanStat(tree.body);
   601             boolean aliveEnd = alive;
   603             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
   604                 alive = true;
   605                 JCVariableDecl param = l.head.param;
   606                 scan(param);
   607                 scanStat(l.head.body);
   608                 aliveEnd |= alive;
   609             }
   610             if (tree.finalizer != null) {
   611                 ListBuffer<PendingExit> exits = pendingExits;
   612                 pendingExits = prevPendingExits;
   613                 alive = true;
   614                 scanStat(tree.finalizer);
   615                 tree.finallyCanCompleteNormally = alive;
   616                 if (!alive) {
   617                     if (lint.isEnabled(Lint.LintCategory.FINALLY)) {
   618                         log.warning(Lint.LintCategory.FINALLY,
   619                                 TreeInfo.diagEndPos(tree.finalizer),
   620                                 "finally.cannot.complete");
   621                     }
   622                 } else {
   623                     while (exits.nonEmpty()) {
   624                         pendingExits.append(exits.next());
   625                     }
   626                     alive = aliveEnd;
   627                 }
   628             } else {
   629                 alive = aliveEnd;
   630                 ListBuffer<PendingExit> exits = pendingExits;
   631                 pendingExits = prevPendingExits;
   632                 while (exits.nonEmpty()) pendingExits.append(exits.next());
   633             }
   634         }
   636         @Override
   637         public void visitIf(JCIf tree) {
   638             scan(tree.cond);
   639             scanStat(tree.thenpart);
   640             if (tree.elsepart != null) {
   641                 boolean aliveAfterThen = alive;
   642                 alive = true;
   643                 scanStat(tree.elsepart);
   644                 alive = alive | aliveAfterThen;
   645             } else {
   646                 alive = true;
   647             }
   648         }
   650         public void visitBreak(JCBreak tree) {
   651             recordExit(tree, new PendingExit(tree));
   652         }
   654         public void visitContinue(JCContinue tree) {
   655             recordExit(tree, new PendingExit(tree));
   656         }
   658         public void visitReturn(JCReturn tree) {
   659             scan(tree.expr);
   660             recordExit(tree, new PendingExit(tree));
   661         }
   663         public void visitThrow(JCThrow tree) {
   664             scan(tree.expr);
   665             markDead();
   666         }
   668         public void visitApply(JCMethodInvocation tree) {
   669             scan(tree.meth);
   670             scan(tree.args);
   671         }
   673         public void visitNewClass(JCNewClass tree) {
   674             scan(tree.encl);
   675             scan(tree.args);
   676             if (tree.def != null) {
   677                 scan(tree.def);
   678             }
   679         }
   681         @Override
   682         public void visitLambda(JCLambda tree) {
   683             if (tree.type != null &&
   684                     tree.type.isErroneous()) {
   685                 return;
   686             }
   688             ListBuffer<PendingExit> prevPending = pendingExits;
   689             boolean prevAlive = alive;
   690             try {
   691                 pendingExits = ListBuffer.lb();
   692                 alive = true;
   693                 scanStat(tree.body);
   694                 tree.canCompleteNormally = alive;
   695             }
   696             finally {
   697                 pendingExits = prevPending;
   698                 alive = prevAlive;
   699             }
   700         }
   702         public void visitTopLevel(JCCompilationUnit tree) {
   703             // Do nothing for TopLevel since each class is visited individually
   704         }
   706     /**************************************************************************
   707      * main method
   708      *************************************************************************/
   710         /** Perform definite assignment/unassignment analysis on a tree.
   711          */
   712         public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
   713             analyzeTree(env, env.tree, make);
   714         }
   715         public void analyzeTree(Env<AttrContext> env, JCTree tree, TreeMaker make) {
   716             try {
   717                 attrEnv = env;
   718                 Flow.this.make = make;
   719                 pendingExits = new ListBuffer<PendingExit>();
   720                 alive = true;
   721                 scan(env.tree);
   722             } finally {
   723                 pendingExits = null;
   724                 Flow.this.make = null;
   725             }
   726         }
   727     }
   729     /**
   730      * This pass implements the second step of the dataflow analysis, namely
   731      * the exception analysis. This is to ensure that every checked exception that is
   732      * thrown is declared or caught. The analyzer uses some info that has been set by
   733      * the liveliness analyzer.
   734      */
   735     class FlowAnalyzer extends BaseAnalyzer<FlowAnalyzer.FlowPendingExit> {
   737         /** A flag that indicates whether the last statement could
   738          *  complete normally.
   739          */
   740         HashMap<Symbol, List<Type>> preciseRethrowTypes;
   742         /** The current class being defined.
   743          */
   744         JCClassDecl classDef;
   746         /** The list of possibly thrown declarable exceptions.
   747          */
   748         List<Type> thrown;
   750         /** The list of exceptions that are either caught or declared to be
   751          *  thrown.
   752          */
   753         List<Type> caught;
   755         class FlowPendingExit extends BaseAnalyzer.PendingExit {
   757             Type thrown;
   759             FlowPendingExit(JCTree tree, Type thrown) {
   760                 super(tree);
   761                 this.thrown = thrown;
   762             }
   763         }
   765         @Override
   766         void markDead() {
   767             //do nothing
   768         }
   770         /*-------------------- Exceptions ----------------------*/
   772         /** Complain that pending exceptions are not caught.
   773          */
   774         void errorUncaught() {
   775             for (FlowPendingExit exit = pendingExits.next();
   776                  exit != null;
   777                  exit = pendingExits.next()) {
   778                 if (classDef != null &&
   779                     classDef.pos == exit.tree.pos) {
   780                     log.error(exit.tree.pos(),
   781                             "unreported.exception.default.constructor",
   782                             exit.thrown);
   783                 } else if (exit.tree.hasTag(VARDEF) &&
   784                         ((JCVariableDecl)exit.tree).sym.isResourceVariable()) {
   785                     log.error(exit.tree.pos(),
   786                             "unreported.exception.implicit.close",
   787                             exit.thrown,
   788                             ((JCVariableDecl)exit.tree).sym.name);
   789                 } else {
   790                     log.error(exit.tree.pos(),
   791                             "unreported.exception.need.to.catch.or.throw",
   792                             exit.thrown);
   793                 }
   794             }
   795         }
   797         /** Record that exception is potentially thrown and check that it
   798          *  is caught.
   799          */
   800         void markThrown(JCTree tree, Type exc) {
   801             if (!chk.isUnchecked(tree.pos(), exc)) {
   802                 if (!chk.isHandled(exc, caught))
   803                     pendingExits.append(new FlowPendingExit(tree, exc));
   804                     thrown = chk.incl(exc, thrown);
   805             }
   806         }
   808     /*************************************************************************
   809      * Visitor methods for statements and definitions
   810      *************************************************************************/
   812         /* ------------ Visitor methods for various sorts of trees -------------*/
   814         public void visitClassDef(JCClassDecl tree) {
   815             if (tree.sym == null) return;
   817             JCClassDecl classDefPrev = classDef;
   818             List<Type> thrownPrev = thrown;
   819             List<Type> caughtPrev = caught;
   820             ListBuffer<FlowPendingExit> pendingExitsPrev = pendingExits;
   821             Lint lintPrev = lint;
   823             pendingExits = new ListBuffer<FlowPendingExit>();
   824             if (tree.name != names.empty) {
   825                 caught = List.nil();
   826             }
   827             classDef = tree;
   828             thrown = List.nil();
   829             lint = lint.augment(tree.sym.annotations);
   831             try {
   832                 // process all the static initializers
   833                 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
   834                     if (!l.head.hasTag(METHODDEF) &&
   835                         (TreeInfo.flags(l.head) & STATIC) != 0) {
   836                         scan(l.head);
   837                         errorUncaught();
   838                     }
   839                 }
   841                 // add intersection of all thrown clauses of initial constructors
   842                 // to set of caught exceptions, unless class is anonymous.
   843                 if (tree.name != names.empty) {
   844                     boolean firstConstructor = true;
   845                     for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
   846                         if (TreeInfo.isInitialConstructor(l.head)) {
   847                             List<Type> mthrown =
   848                                 ((JCMethodDecl) l.head).sym.type.getThrownTypes();
   849                             if (firstConstructor) {
   850                                 caught = mthrown;
   851                                 firstConstructor = false;
   852                             } else {
   853                                 caught = chk.intersect(mthrown, caught);
   854                             }
   855                         }
   856                     }
   857                 }
   859                 // process all the instance initializers
   860                 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
   861                     if (!l.head.hasTag(METHODDEF) &&
   862                         (TreeInfo.flags(l.head) & STATIC) == 0) {
   863                         scan(l.head);
   864                         errorUncaught();
   865                     }
   866                 }
   868                 // in an anonymous class, add the set of thrown exceptions to
   869                 // the throws clause of the synthetic constructor and propagate
   870                 // outwards.
   871                 // Changing the throws clause on the fly is okay here because
   872                 // the anonymous constructor can't be invoked anywhere else,
   873                 // and its type hasn't been cached.
   874                 if (tree.name == names.empty) {
   875                     for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
   876                         if (TreeInfo.isInitialConstructor(l.head)) {
   877                             JCMethodDecl mdef = (JCMethodDecl)l.head;
   878                             mdef.thrown = make.Types(thrown);
   879                             mdef.sym.type = types.createMethodTypeWithThrown(mdef.sym.type, thrown);
   880                         }
   881                     }
   882                     thrownPrev = chk.union(thrown, thrownPrev);
   883                 }
   885                 // process all the methods
   886                 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
   887                     if (l.head.hasTag(METHODDEF)) {
   888                         scan(l.head);
   889                         errorUncaught();
   890                     }
   891                 }
   893                 thrown = thrownPrev;
   894             } finally {
   895                 pendingExits = pendingExitsPrev;
   896                 caught = caughtPrev;
   897                 classDef = classDefPrev;
   898                 lint = lintPrev;
   899             }
   900         }
   902         public void visitMethodDef(JCMethodDecl tree) {
   903             if (tree.body == null) return;
   905             List<Type> caughtPrev = caught;
   906             List<Type> mthrown = tree.sym.type.getThrownTypes();
   907             Lint lintPrev = lint;
   909             lint = lint.augment(tree.sym.annotations);
   911             Assert.check(pendingExits.isEmpty());
   913             try {
   914                 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   915                     JCVariableDecl def = l.head;
   916                     scan(def);
   917                 }
   918                 if (TreeInfo.isInitialConstructor(tree))
   919                     caught = chk.union(caught, mthrown);
   920                 else if ((tree.sym.flags() & (BLOCK | STATIC)) != BLOCK)
   921                     caught = mthrown;
   922                 // else we are in an instance initializer block;
   923                 // leave caught unchanged.
   925                 scan(tree.body);
   927                 List<FlowPendingExit> exits = pendingExits.toList();
   928                 pendingExits = new ListBuffer<FlowPendingExit>();
   929                 while (exits.nonEmpty()) {
   930                     FlowPendingExit exit = exits.head;
   931                     exits = exits.tail;
   932                     if (exit.thrown == null) {
   933                         Assert.check(exit.tree.hasTag(RETURN));
   934                     } else {
   935                         // uncaught throws will be reported later
   936                         pendingExits.append(exit);
   937                     }
   938                 }
   939             } finally {
   940                 caught = caughtPrev;
   941                 lint = lintPrev;
   942             }
   943         }
   945         public void visitVarDef(JCVariableDecl tree) {
   946             if (tree.init != null) {
   947                 Lint lintPrev = lint;
   948                 lint = lint.augment(tree.sym.annotations);
   949                 try{
   950                     scan(tree.init);
   951                 } finally {
   952                     lint = lintPrev;
   953                 }
   954             }
   955         }
   957         public void visitBlock(JCBlock tree) {
   958             scan(tree.stats);
   959         }
   961         public void visitDoLoop(JCDoWhileLoop tree) {
   962             ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
   963             pendingExits = new ListBuffer<FlowPendingExit>();
   964             scan(tree.body);
   965             resolveContinues(tree);
   966             scan(tree.cond);
   967             resolveBreaks(tree, prevPendingExits);
   968         }
   970         public void visitWhileLoop(JCWhileLoop tree) {
   971             ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
   972             pendingExits = new ListBuffer<FlowPendingExit>();
   973             scan(tree.cond);
   974             scan(tree.body);
   975             resolveContinues(tree);
   976             resolveBreaks(tree, prevPendingExits);
   977         }
   979         public void visitForLoop(JCForLoop tree) {
   980             ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
   981             scan(tree.init);
   982             pendingExits = new ListBuffer<FlowPendingExit>();
   983             if (tree.cond != null) {
   984                 scan(tree.cond);
   985             }
   986             scan(tree.body);
   987             resolveContinues(tree);
   988             scan(tree.step);
   989             resolveBreaks(tree, prevPendingExits);
   990         }
   992         public void visitForeachLoop(JCEnhancedForLoop tree) {
   993             visitVarDef(tree.var);
   994             ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
   995             scan(tree.expr);
   996             pendingExits = new ListBuffer<FlowPendingExit>();
   997             scan(tree.body);
   998             resolveContinues(tree);
   999             resolveBreaks(tree, prevPendingExits);
  1002         public void visitLabelled(JCLabeledStatement tree) {
  1003             ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
  1004             pendingExits = new ListBuffer<FlowPendingExit>();
  1005             scan(tree.body);
  1006             resolveBreaks(tree, prevPendingExits);
  1009         public void visitSwitch(JCSwitch tree) {
  1010             ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
  1011             pendingExits = new ListBuffer<FlowPendingExit>();
  1012             scan(tree.selector);
  1013             for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
  1014                 JCCase c = l.head;
  1015                 if (c.pat != null) {
  1016                     scan(c.pat);
  1018                 scan(c.stats);
  1020             resolveBreaks(tree, prevPendingExits);
  1023         public void visitTry(JCTry tree) {
  1024             List<Type> caughtPrev = caught;
  1025             List<Type> thrownPrev = thrown;
  1026             thrown = List.nil();
  1027             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1028                 List<JCExpression> subClauses = TreeInfo.isMultiCatch(l.head) ?
  1029                         ((JCTypeUnion)l.head.param.vartype).alternatives :
  1030                         List.of(l.head.param.vartype);
  1031                 for (JCExpression ct : subClauses) {
  1032                     caught = chk.incl(ct.type, caught);
  1036             ListBuffer<FlowPendingExit> prevPendingExits = pendingExits;
  1037             pendingExits = new ListBuffer<FlowPendingExit>();
  1038             for (JCTree resource : tree.resources) {
  1039                 if (resource instanceof JCVariableDecl) {
  1040                     JCVariableDecl vdecl = (JCVariableDecl) resource;
  1041                     visitVarDef(vdecl);
  1042                 } else if (resource instanceof JCExpression) {
  1043                     scan((JCExpression) resource);
  1044                 } else {
  1045                     throw new AssertionError(tree);  // parser error
  1048             for (JCTree resource : tree.resources) {
  1049                 List<Type> closeableSupertypes = resource.type.isCompound() ?
  1050                     types.interfaces(resource.type).prepend(types.supertype(resource.type)) :
  1051                     List.of(resource.type);
  1052                 for (Type sup : closeableSupertypes) {
  1053                     if (types.asSuper(sup, syms.autoCloseableType.tsym) != null) {
  1054                         Symbol closeMethod = rs.resolveQualifiedMethod(tree,
  1055                                 attrEnv,
  1056                                 sup,
  1057                                 names.close,
  1058                                 List.<Type>nil(),
  1059                                 List.<Type>nil());
  1060                         if (closeMethod.kind == MTH) {
  1061                             for (Type t : ((MethodSymbol)closeMethod).getThrownTypes()) {
  1062                                 markThrown(resource, t);
  1068             scan(tree.body);
  1069             List<Type> thrownInTry = allowImprovedCatchAnalysis ?
  1070                 chk.union(thrown, List.of(syms.runtimeExceptionType, syms.errorType)) :
  1071                 thrown;
  1072             thrown = thrownPrev;
  1073             caught = caughtPrev;
  1075             List<Type> caughtInTry = List.nil();
  1076             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1077                 JCVariableDecl param = l.head.param;
  1078                 List<JCExpression> subClauses = TreeInfo.isMultiCatch(l.head) ?
  1079                         ((JCTypeUnion)l.head.param.vartype).alternatives :
  1080                         List.of(l.head.param.vartype);
  1081                 List<Type> ctypes = List.nil();
  1082                 List<Type> rethrownTypes = chk.diff(thrownInTry, caughtInTry);
  1083                 for (JCExpression ct : subClauses) {
  1084                     Type exc = ct.type;
  1085                     if (exc != syms.unknownType) {
  1086                         ctypes = ctypes.append(exc);
  1087                         if (types.isSameType(exc, syms.objectType))
  1088                             continue;
  1089                         checkCaughtType(l.head.pos(), exc, thrownInTry, caughtInTry);
  1090                         caughtInTry = chk.incl(exc, caughtInTry);
  1093                 scan(param);
  1094                 preciseRethrowTypes.put(param.sym, chk.intersect(ctypes, rethrownTypes));
  1095                 scan(l.head.body);
  1096                 preciseRethrowTypes.remove(param.sym);
  1098             if (tree.finalizer != null) {
  1099                 List<Type> savedThrown = thrown;
  1100                 thrown = List.nil();
  1101                 ListBuffer<FlowPendingExit> exits = pendingExits;
  1102                 pendingExits = prevPendingExits;
  1103                 scan(tree.finalizer);
  1104                 if (!tree.finallyCanCompleteNormally) {
  1105                     // discard exits and exceptions from try and finally
  1106                     thrown = chk.union(thrown, thrownPrev);
  1107                 } else {
  1108                     thrown = chk.union(thrown, chk.diff(thrownInTry, caughtInTry));
  1109                     thrown = chk.union(thrown, savedThrown);
  1110                     // FIX: this doesn't preserve source order of exits in catch
  1111                     // versus finally!
  1112                     while (exits.nonEmpty()) {
  1113                         pendingExits.append(exits.next());
  1116             } else {
  1117                 thrown = chk.union(thrown, chk.diff(thrownInTry, caughtInTry));
  1118                 ListBuffer<FlowPendingExit> exits = pendingExits;
  1119                 pendingExits = prevPendingExits;
  1120                 while (exits.nonEmpty()) pendingExits.append(exits.next());
  1124         @Override
  1125         public void visitIf(JCIf tree) {
  1126             scan(tree.cond);
  1127             scan(tree.thenpart);
  1128             if (tree.elsepart != null) {
  1129                 scan(tree.elsepart);
  1133         void checkCaughtType(DiagnosticPosition pos, Type exc, List<Type> thrownInTry, List<Type> caughtInTry) {
  1134             if (chk.subset(exc, caughtInTry)) {
  1135                 log.error(pos, "except.already.caught", exc);
  1136             } else if (!chk.isUnchecked(pos, exc) &&
  1137                     !isExceptionOrThrowable(exc) &&
  1138                     !chk.intersects(exc, thrownInTry)) {
  1139                 log.error(pos, "except.never.thrown.in.try", exc);
  1140             } else if (allowImprovedCatchAnalysis) {
  1141                 List<Type> catchableThrownTypes = chk.intersect(List.of(exc), thrownInTry);
  1142                 // 'catchableThrownTypes' cannnot possibly be empty - if 'exc' was an
  1143                 // unchecked exception, the result list would not be empty, as the augmented
  1144                 // thrown set includes { RuntimeException, Error }; if 'exc' was a checked
  1145                 // exception, that would have been covered in the branch above
  1146                 if (chk.diff(catchableThrownTypes, caughtInTry).isEmpty() &&
  1147                         !isExceptionOrThrowable(exc)) {
  1148                     String key = catchableThrownTypes.length() == 1 ?
  1149                             "unreachable.catch" :
  1150                             "unreachable.catch.1";
  1151                     log.warning(pos, key, catchableThrownTypes);
  1155         //where
  1156             private boolean isExceptionOrThrowable(Type exc) {
  1157                 return exc.tsym == syms.throwableType.tsym ||
  1158                     exc.tsym == syms.exceptionType.tsym;
  1161         public void visitBreak(JCBreak tree) {
  1162             recordExit(tree, new FlowPendingExit(tree, null));
  1165         public void visitContinue(JCContinue tree) {
  1166             recordExit(tree, new FlowPendingExit(tree, null));
  1169         public void visitReturn(JCReturn tree) {
  1170             scan(tree.expr);
  1171             recordExit(tree, new FlowPendingExit(tree, null));
  1174         public void visitThrow(JCThrow tree) {
  1175             scan(tree.expr);
  1176             Symbol sym = TreeInfo.symbol(tree.expr);
  1177             if (sym != null &&
  1178                 sym.kind == VAR &&
  1179                 (sym.flags() & (FINAL | EFFECTIVELY_FINAL)) != 0 &&
  1180                 preciseRethrowTypes.get(sym) != null &&
  1181                 allowImprovedRethrowAnalysis) {
  1182                 for (Type t : preciseRethrowTypes.get(sym)) {
  1183                     markThrown(tree, t);
  1186             else {
  1187                 markThrown(tree, tree.expr.type);
  1189             markDead();
  1192         public void visitApply(JCMethodInvocation tree) {
  1193             scan(tree.meth);
  1194             scan(tree.args);
  1195             for (List<Type> l = tree.meth.type.getThrownTypes(); l.nonEmpty(); l = l.tail)
  1196                 markThrown(tree, l.head);
  1199         public void visitNewClass(JCNewClass tree) {
  1200             scan(tree.encl);
  1201             scan(tree.args);
  1202            // scan(tree.def);
  1203             for (List<Type> l = tree.constructorType.getThrownTypes();
  1204                  l.nonEmpty();
  1205                  l = l.tail) {
  1206                 markThrown(tree, l.head);
  1208             List<Type> caughtPrev = caught;
  1209             try {
  1210                 // If the new class expression defines an anonymous class,
  1211                 // analysis of the anonymous constructor may encounter thrown
  1212                 // types which are unsubstituted type variables.
  1213                 // However, since the constructor's actual thrown types have
  1214                 // already been marked as thrown, it is safe to simply include
  1215                 // each of the constructor's formal thrown types in the set of
  1216                 // 'caught/declared to be thrown' types, for the duration of
  1217                 // the class def analysis.
  1218                 if (tree.def != null)
  1219                     for (List<Type> l = tree.constructor.type.getThrownTypes();
  1220                          l.nonEmpty();
  1221                          l = l.tail) {
  1222                         caught = chk.incl(l.head, caught);
  1224                 scan(tree.def);
  1226             finally {
  1227                 caught = caughtPrev;
  1231         @Override
  1232         public void visitLambda(JCLambda tree) {
  1233             if (tree.type != null &&
  1234                     tree.type.isErroneous()) {
  1235                 return;
  1237             List<Type> prevCaught = caught;
  1238             List<Type> prevThrown = thrown;
  1239             ListBuffer<FlowPendingExit> prevPending = pendingExits;
  1240             try {
  1241                 pendingExits = ListBuffer.lb();
  1242                 caught = List.of(syms.throwableType); //inhibit exception checking
  1243                 thrown = List.nil();
  1244                 scan(tree.body);
  1245                 tree.inferredThrownTypes = thrown;
  1247             finally {
  1248                 pendingExits = prevPending;
  1249                 caught = prevCaught;
  1250                 thrown = prevThrown;
  1254         public void visitTopLevel(JCCompilationUnit tree) {
  1255             // Do nothing for TopLevel since each class is visited individually
  1258     /**************************************************************************
  1259      * main method
  1260      *************************************************************************/
  1262         /** Perform definite assignment/unassignment analysis on a tree.
  1263          */
  1264         public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
  1265             analyzeTree(env, env.tree, make);
  1267         public void analyzeTree(Env<AttrContext> env, JCTree tree, TreeMaker make) {
  1268             try {
  1269                 attrEnv = env;
  1270                 Flow.this.make = make;
  1271                 pendingExits = new ListBuffer<FlowPendingExit>();
  1272                 preciseRethrowTypes = new HashMap<Symbol, List<Type>>();
  1273                 this.thrown = this.caught = null;
  1274                 this.classDef = null;
  1275                 scan(tree);
  1276             } finally {
  1277                 pendingExits = null;
  1278                 Flow.this.make = null;
  1279                 this.thrown = this.caught = null;
  1280                 this.classDef = null;
  1285     /**
  1286      * This pass implements (i) definite assignment analysis, which ensures that
  1287      * each variable is assigned when used and (ii) definite unassignment analysis,
  1288      * which ensures that no final variable is assigned more than once. This visitor
  1289      * depends on the results of the liveliness analyzer. This pass is also used to mark
  1290      * effectively-final local variables/parameters.
  1291      */
  1292     class AssignAnalyzer extends BaseAnalyzer<AssignAnalyzer.AssignPendingExit> {
  1294         /** The set of definitely assigned variables.
  1295          */
  1296         Bits inits;
  1298         /** The set of definitely unassigned variables.
  1299          */
  1300         Bits uninits;
  1302         /** The set of variables that are definitely unassigned everywhere
  1303          *  in current try block. This variable is maintained lazily; it is
  1304          *  updated only when something gets removed from uninits,
  1305          *  typically by being assigned in reachable code.  To obtain the
  1306          *  correct set of variables which are definitely unassigned
  1307          *  anywhere in current try block, intersect uninitsTry and
  1308          *  uninits.
  1309          */
  1310         Bits uninitsTry;
  1312         /** When analyzing a condition, inits and uninits are null.
  1313          *  Instead we have:
  1314          */
  1315         Bits initsWhenTrue;
  1316         Bits initsWhenFalse;
  1317         Bits uninitsWhenTrue;
  1318         Bits uninitsWhenFalse;
  1320         /** A mapping from addresses to variable symbols.
  1321          */
  1322         VarSymbol[] vars;
  1324         /** The current class being defined.
  1325          */
  1326         JCClassDecl classDef;
  1328         /** The first variable sequence number in this class definition.
  1329          */
  1330         int firstadr;
  1332         /** The next available variable sequence number.
  1333          */
  1334         int nextadr;
  1336         /** The first variable sequence number in a block that can return.
  1337          */
  1338         int returnadr;
  1340         /** The list of unreferenced automatic resources.
  1341          */
  1342         Scope unrefdResources;
  1344         /** Set when processing a loop body the second time for DU analysis. */
  1345         FlowKind flowKind = FlowKind.NORMAL;
  1347         /** The starting position of the analysed tree */
  1348         int startPos;
  1350         class AssignPendingExit extends BaseAnalyzer.PendingExit {
  1352             Bits exit_inits;
  1353             Bits exit_uninits;
  1355             AssignPendingExit(JCTree tree, Bits inits, Bits uninits) {
  1356                 super(tree);
  1357                 this.exit_inits = inits.dup();
  1358                 this.exit_uninits = uninits.dup();
  1361             void resolveJump() {
  1362                 inits.andSet(exit_inits);
  1363                 uninits.andSet(exit_uninits);
  1367         @Override
  1368         void markDead() {
  1369             inits.inclRange(returnadr, nextadr);
  1370             uninits.inclRange(returnadr, nextadr);
  1373         /*-------------- Processing variables ----------------------*/
  1375         /** Do we need to track init/uninit state of this symbol?
  1376          *  I.e. is symbol either a local or a blank final variable?
  1377          */
  1378         boolean trackable(VarSymbol sym) {
  1379             return
  1380                 sym.pos >= startPos &&
  1381                 ((sym.owner.kind == MTH ||
  1382                  ((sym.flags() & (FINAL | HASINIT | PARAMETER)) == FINAL &&
  1383                   classDef.sym.isEnclosedBy((ClassSymbol)sym.owner))));
  1386         /** Initialize new trackable variable by setting its address field
  1387          *  to the next available sequence number and entering it under that
  1388          *  index into the vars array.
  1389          */
  1390         void newVar(VarSymbol sym) {
  1391             vars = ArrayUtils.ensureCapacity(vars, nextadr);
  1392             if ((sym.flags() & FINAL) == 0) {
  1393                 sym.flags_field |= EFFECTIVELY_FINAL;
  1395             sym.adr = nextadr;
  1396             vars[nextadr] = sym;
  1397             inits.excl(nextadr);
  1398             uninits.incl(nextadr);
  1399             nextadr++;
  1402         /** Record an initialization of a trackable variable.
  1403          */
  1404         void letInit(DiagnosticPosition pos, VarSymbol sym) {
  1405             if (sym.adr >= firstadr && trackable(sym)) {
  1406                 if ((sym.flags() & EFFECTIVELY_FINAL) != 0) {
  1407                     if (!uninits.isMember(sym.adr)) {
  1408                         //assignment targeting an effectively final variable
  1409                         //makes the variable lose its status of effectively final
  1410                         //if the variable is _not_ definitively unassigned
  1411                         sym.flags_field &= ~EFFECTIVELY_FINAL;
  1412                     } else {
  1413                         uninit(sym);
  1416                 else if ((sym.flags() & FINAL) != 0) {
  1417                     if ((sym.flags() & PARAMETER) != 0) {
  1418                         if ((sym.flags() & UNION) != 0) { //multi-catch parameter
  1419                             log.error(pos, "multicatch.parameter.may.not.be.assigned",
  1420                                       sym);
  1422                         else {
  1423                             log.error(pos, "final.parameter.may.not.be.assigned",
  1424                                   sym);
  1426                     } else if (!uninits.isMember(sym.adr)) {
  1427                         log.error(pos, flowKind.errKey, sym);
  1428                     } else {
  1429                         uninit(sym);
  1432                 inits.incl(sym.adr);
  1433             } else if ((sym.flags() & FINAL) != 0) {
  1434                 log.error(pos, "var.might.already.be.assigned", sym);
  1437         //where
  1438             void uninit(VarSymbol sym) {
  1439                 if (!inits.isMember(sym.adr)) {
  1440                     // reachable assignment
  1441                     uninits.excl(sym.adr);
  1442                     uninitsTry.excl(sym.adr);
  1443                 } else {
  1444                     //log.rawWarning(pos, "unreachable assignment");//DEBUG
  1445                     uninits.excl(sym.adr);
  1449         /** If tree is either a simple name or of the form this.name or
  1450          *  C.this.name, and tree represents a trackable variable,
  1451          *  record an initialization of the variable.
  1452          */
  1453         void letInit(JCTree tree) {
  1454             tree = TreeInfo.skipParens(tree);
  1455             if (tree.hasTag(IDENT) || tree.hasTag(SELECT)) {
  1456                 Symbol sym = TreeInfo.symbol(tree);
  1457                 if (sym.kind == VAR) {
  1458                     letInit(tree.pos(), (VarSymbol)sym);
  1463         /** Check that trackable variable is initialized.
  1464          */
  1465         void checkInit(DiagnosticPosition pos, VarSymbol sym) {
  1466             if ((sym.adr >= firstadr || sym.owner.kind != TYP) &&
  1467                 trackable(sym) &&
  1468                 !inits.isMember(sym.adr)) {
  1469                 log.error(pos, "var.might.not.have.been.initialized",
  1470                           sym);
  1471                 inits.incl(sym.adr);
  1475         /** Split (duplicate) inits/uninits into WhenTrue/WhenFalse sets
  1476          */
  1477         void split(boolean setToNull) {
  1478             initsWhenFalse = inits.dup();
  1479             uninitsWhenFalse = uninits.dup();
  1480             initsWhenTrue = inits;
  1481             uninitsWhenTrue = uninits;
  1482             if (setToNull)
  1483                 inits = uninits = null;
  1486         /** Merge (intersect) inits/uninits from WhenTrue/WhenFalse sets.
  1487          */
  1488         void merge() {
  1489             inits = initsWhenFalse.andSet(initsWhenTrue);
  1490             uninits = uninitsWhenFalse.andSet(uninitsWhenTrue);
  1493     /* ************************************************************************
  1494      * Visitor methods for statements and definitions
  1495      *************************************************************************/
  1497         /** Analyze an expression. Make sure to set (un)inits rather than
  1498          *  (un)initsWhenTrue(WhenFalse) on exit.
  1499          */
  1500         void scanExpr(JCTree tree) {
  1501             if (tree != null) {
  1502                 scan(tree);
  1503                 if (inits == null) merge();
  1507         /** Analyze a list of expressions.
  1508          */
  1509         void scanExprs(List<? extends JCExpression> trees) {
  1510             if (trees != null)
  1511                 for (List<? extends JCExpression> l = trees; l.nonEmpty(); l = l.tail)
  1512                     scanExpr(l.head);
  1515         /** Analyze a condition. Make sure to set (un)initsWhenTrue(WhenFalse)
  1516          *  rather than (un)inits on exit.
  1517          */
  1518         void scanCond(JCTree tree) {
  1519             if (tree.type.isFalse()) {
  1520                 if (inits == null) merge();
  1521                 initsWhenTrue = inits.dup();
  1522                 initsWhenTrue.inclRange(firstadr, nextadr);
  1523                 uninitsWhenTrue = uninits.dup();
  1524                 uninitsWhenTrue.inclRange(firstadr, nextadr);
  1525                 initsWhenFalse = inits;
  1526                 uninitsWhenFalse = uninits;
  1527             } else if (tree.type.isTrue()) {
  1528                 if (inits == null) merge();
  1529                 initsWhenFalse = inits.dup();
  1530                 initsWhenFalse.inclRange(firstadr, nextadr);
  1531                 uninitsWhenFalse = uninits.dup();
  1532                 uninitsWhenFalse.inclRange(firstadr, nextadr);
  1533                 initsWhenTrue = inits;
  1534                 uninitsWhenTrue = uninits;
  1535             } else {
  1536                 scan(tree);
  1537                 if (inits != null)
  1538                     split(tree.type != syms.unknownType);
  1540             if (tree.type != syms.unknownType)
  1541                 inits = uninits = null;
  1544         /* ------------ Visitor methods for various sorts of trees -------------*/
  1546         public void visitClassDef(JCClassDecl tree) {
  1547             if (tree.sym == null) return;
  1549             JCClassDecl classDefPrev = classDef;
  1550             int firstadrPrev = firstadr;
  1551             int nextadrPrev = nextadr;
  1552             ListBuffer<AssignPendingExit> pendingExitsPrev = pendingExits;
  1553             Lint lintPrev = lint;
  1555             pendingExits = new ListBuffer<AssignPendingExit>();
  1556             if (tree.name != names.empty) {
  1557                 firstadr = nextadr;
  1559             classDef = tree;
  1560             lint = lint.augment(tree.sym.annotations);
  1562             try {
  1563                 // define all the static fields
  1564                 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  1565                     if (l.head.hasTag(VARDEF)) {
  1566                         JCVariableDecl def = (JCVariableDecl)l.head;
  1567                         if ((def.mods.flags & STATIC) != 0) {
  1568                             VarSymbol sym = def.sym;
  1569                             if (trackable(sym))
  1570                                 newVar(sym);
  1575                 // process all the static initializers
  1576                 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  1577                     if (!l.head.hasTag(METHODDEF) &&
  1578                         (TreeInfo.flags(l.head) & STATIC) != 0) {
  1579                         scan(l.head);
  1583                 // define all the instance fields
  1584                 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  1585                     if (l.head.hasTag(VARDEF)) {
  1586                         JCVariableDecl def = (JCVariableDecl)l.head;
  1587                         if ((def.mods.flags & STATIC) == 0) {
  1588                             VarSymbol sym = def.sym;
  1589                             if (trackable(sym))
  1590                                 newVar(sym);
  1595                 // process all the instance initializers
  1596                 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  1597                     if (!l.head.hasTag(METHODDEF) &&
  1598                         (TreeInfo.flags(l.head) & STATIC) == 0) {
  1599                         scan(l.head);
  1603                 // process all the methods
  1604                 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  1605                     if (l.head.hasTag(METHODDEF)) {
  1606                         scan(l.head);
  1609             } finally {
  1610                 pendingExits = pendingExitsPrev;
  1611                 nextadr = nextadrPrev;
  1612                 firstadr = firstadrPrev;
  1613                 classDef = classDefPrev;
  1614                 lint = lintPrev;
  1618         public void visitMethodDef(JCMethodDecl tree) {
  1619             if (tree.body == null) return;
  1621             Bits initsPrev = inits.dup();
  1622             Bits uninitsPrev = uninits.dup();
  1623             int nextadrPrev = nextadr;
  1624             int firstadrPrev = firstadr;
  1625             int returnadrPrev = returnadr;
  1626             Lint lintPrev = lint;
  1628             lint = lint.augment(tree.sym.annotations);
  1630             Assert.check(pendingExits.isEmpty());
  1632             try {
  1633                 boolean isInitialConstructor =
  1634                     TreeInfo.isInitialConstructor(tree);
  1636                 if (!isInitialConstructor)
  1637                     firstadr = nextadr;
  1638                 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
  1639                     JCVariableDecl def = l.head;
  1640                     scan(def);
  1641                     inits.incl(def.sym.adr);
  1642                     uninits.excl(def.sym.adr);
  1644                 // else we are in an instance initializer block;
  1645                 // leave caught unchanged.
  1646                 scan(tree.body);
  1648                 if (isInitialConstructor) {
  1649                     for (int i = firstadr; i < nextadr; i++)
  1650                         if (vars[i].owner == classDef.sym)
  1651                             checkInit(TreeInfo.diagEndPos(tree.body), vars[i]);
  1653                 List<AssignPendingExit> exits = pendingExits.toList();
  1654                 pendingExits = new ListBuffer<AssignPendingExit>();
  1655                 while (exits.nonEmpty()) {
  1656                     AssignPendingExit exit = exits.head;
  1657                     exits = exits.tail;
  1658                     Assert.check(exit.tree.hasTag(RETURN), exit.tree);
  1659                     if (isInitialConstructor) {
  1660                         inits = exit.exit_inits;
  1661                         for (int i = firstadr; i < nextadr; i++)
  1662                             checkInit(exit.tree.pos(), vars[i]);
  1665             } finally {
  1666                 inits = initsPrev;
  1667                 uninits = uninitsPrev;
  1668                 nextadr = nextadrPrev;
  1669                 firstadr = firstadrPrev;
  1670                 returnadr = returnadrPrev;
  1671                 lint = lintPrev;
  1675         public void visitVarDef(JCVariableDecl tree) {
  1676             boolean track = trackable(tree.sym);
  1677             if (track && tree.sym.owner.kind == MTH) newVar(tree.sym);
  1678             if (tree.init != null) {
  1679                 Lint lintPrev = lint;
  1680                 lint = lint.augment(tree.sym.annotations);
  1681                 try{
  1682                     scanExpr(tree.init);
  1683                     if (track) letInit(tree.pos(), tree.sym);
  1684                 } finally {
  1685                     lint = lintPrev;
  1690         public void visitBlock(JCBlock tree) {
  1691             int nextadrPrev = nextadr;
  1692             scan(tree.stats);
  1693             nextadr = nextadrPrev;
  1696         public void visitDoLoop(JCDoWhileLoop tree) {
  1697             ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
  1698             FlowKind prevFlowKind = flowKind;
  1699             flowKind = FlowKind.NORMAL;
  1700             Bits initsSkip = null;
  1701             Bits uninitsSkip = null;
  1702             pendingExits = new ListBuffer<AssignPendingExit>();
  1703             int prevErrors = log.nerrors;
  1704             do {
  1705                 Bits uninitsEntry = uninits.dup();
  1706                 uninitsEntry.excludeFrom(nextadr);
  1707                 scan(tree.body);
  1708                 resolveContinues(tree);
  1709                 scanCond(tree.cond);
  1710                 if (!flowKind.isFinal()) {
  1711                     initsSkip = initsWhenFalse;
  1712                     uninitsSkip = uninitsWhenFalse;
  1714                 if (log.nerrors !=  prevErrors ||
  1715                     flowKind.isFinal() ||
  1716                     uninitsEntry.dup().diffSet(uninitsWhenTrue).nextBit(firstadr)==-1)
  1717                     break;
  1718                 inits = initsWhenTrue;
  1719                 uninits = uninitsEntry.andSet(uninitsWhenTrue);
  1720                 flowKind = FlowKind.SPECULATIVE_LOOP;
  1721             } while (true);
  1722             flowKind = prevFlowKind;
  1723             inits = initsSkip;
  1724             uninits = uninitsSkip;
  1725             resolveBreaks(tree, prevPendingExits);
  1728         public void visitWhileLoop(JCWhileLoop tree) {
  1729             ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
  1730             FlowKind prevFlowKind = flowKind;
  1731             flowKind = FlowKind.NORMAL;
  1732             Bits initsSkip = null;
  1733             Bits uninitsSkip = null;
  1734             pendingExits = new ListBuffer<AssignPendingExit>();
  1735             int prevErrors = log.nerrors;
  1736             Bits uninitsEntry = uninits.dup();
  1737             uninitsEntry.excludeFrom(nextadr);
  1738             do {
  1739                 scanCond(tree.cond);
  1740                 if (!flowKind.isFinal()) {
  1741                     initsSkip = initsWhenFalse;
  1742                     uninitsSkip = uninitsWhenFalse;
  1744                 inits = initsWhenTrue;
  1745                 uninits = uninitsWhenTrue;
  1746                 scan(tree.body);
  1747                 resolveContinues(tree);
  1748                 if (log.nerrors != prevErrors ||
  1749                     flowKind.isFinal() ||
  1750                     uninitsEntry.dup().diffSet(uninits).nextBit(firstadr) == -1)
  1751                     break;
  1752                 uninits = uninitsEntry.andSet(uninits);
  1753                 flowKind = FlowKind.SPECULATIVE_LOOP;
  1754             } while (true);
  1755             flowKind = prevFlowKind;
  1756             //a variable is DA/DU after the while statement, if it's DA/DU assuming the
  1757             //branch is not taken AND if it's DA/DU before any break statement
  1758             inits = initsSkip;
  1759             uninits = uninitsSkip;
  1760             resolveBreaks(tree, prevPendingExits);
  1763         public void visitForLoop(JCForLoop tree) {
  1764             ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
  1765             FlowKind prevFlowKind = flowKind;
  1766             flowKind = FlowKind.NORMAL;
  1767             int nextadrPrev = nextadr;
  1768             scan(tree.init);
  1769             Bits initsSkip = null;
  1770             Bits uninitsSkip = null;
  1771             pendingExits = new ListBuffer<AssignPendingExit>();
  1772             int prevErrors = log.nerrors;
  1773             do {
  1774                 Bits uninitsEntry = uninits.dup();
  1775                 uninitsEntry.excludeFrom(nextadr);
  1776                 if (tree.cond != null) {
  1777                     scanCond(tree.cond);
  1778                     if (!flowKind.isFinal()) {
  1779                         initsSkip = initsWhenFalse;
  1780                         uninitsSkip = uninitsWhenFalse;
  1782                     inits = initsWhenTrue;
  1783                     uninits = uninitsWhenTrue;
  1784                 } else if (!flowKind.isFinal()) {
  1785                     initsSkip = inits.dup();
  1786                     initsSkip.inclRange(firstadr, nextadr);
  1787                     uninitsSkip = uninits.dup();
  1788                     uninitsSkip.inclRange(firstadr, nextadr);
  1790                 scan(tree.body);
  1791                 resolveContinues(tree);
  1792                 scan(tree.step);
  1793                 if (log.nerrors != prevErrors ||
  1794                     flowKind.isFinal() ||
  1795                     uninitsEntry.dup().diffSet(uninits).nextBit(firstadr) == -1)
  1796                     break;
  1797                 uninits = uninitsEntry.andSet(uninits);
  1798                 flowKind = FlowKind.SPECULATIVE_LOOP;
  1799             } while (true);
  1800             flowKind = prevFlowKind;
  1801             //a variable is DA/DU after a for loop, if it's DA/DU assuming the
  1802             //branch is not taken AND if it's DA/DU before any break statement
  1803             inits = initsSkip;
  1804             uninits = uninitsSkip;
  1805             resolveBreaks(tree, prevPendingExits);
  1806             nextadr = nextadrPrev;
  1809         public void visitForeachLoop(JCEnhancedForLoop tree) {
  1810             visitVarDef(tree.var);
  1812             ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
  1813             FlowKind prevFlowKind = flowKind;
  1814             flowKind = FlowKind.NORMAL;
  1815             int nextadrPrev = nextadr;
  1816             scan(tree.expr);
  1817             Bits initsStart = inits.dup();
  1818             Bits uninitsStart = uninits.dup();
  1820             letInit(tree.pos(), tree.var.sym);
  1821             pendingExits = new ListBuffer<AssignPendingExit>();
  1822             int prevErrors = log.nerrors;
  1823             do {
  1824                 Bits uninitsEntry = uninits.dup();
  1825                 uninitsEntry.excludeFrom(nextadr);
  1826                 scan(tree.body);
  1827                 resolveContinues(tree);
  1828                 if (log.nerrors != prevErrors ||
  1829                     flowKind.isFinal() ||
  1830                     uninitsEntry.dup().diffSet(uninits).nextBit(firstadr) == -1)
  1831                     break;
  1832                 uninits = uninitsEntry.andSet(uninits);
  1833                 flowKind = FlowKind.SPECULATIVE_LOOP;
  1834             } while (true);
  1835             flowKind = prevFlowKind;
  1836             inits = initsStart;
  1837             uninits = uninitsStart.andSet(uninits);
  1838             resolveBreaks(tree, prevPendingExits);
  1839             nextadr = nextadrPrev;
  1842         public void visitLabelled(JCLabeledStatement tree) {
  1843             ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
  1844             pendingExits = new ListBuffer<AssignPendingExit>();
  1845             scan(tree.body);
  1846             resolveBreaks(tree, prevPendingExits);
  1849         public void visitSwitch(JCSwitch tree) {
  1850             ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
  1851             pendingExits = new ListBuffer<AssignPendingExit>();
  1852             int nextadrPrev = nextadr;
  1853             scanExpr(tree.selector);
  1854             Bits initsSwitch = inits;
  1855             Bits uninitsSwitch = uninits.dup();
  1856             boolean hasDefault = false;
  1857             for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
  1858                 inits = initsSwitch.dup();
  1859                 uninits = uninits.andSet(uninitsSwitch);
  1860                 JCCase c = l.head;
  1861                 if (c.pat == null)
  1862                     hasDefault = true;
  1863                 else
  1864                     scanExpr(c.pat);
  1865                 scan(c.stats);
  1866                 addVars(c.stats, initsSwitch, uninitsSwitch);
  1867                 // Warn about fall-through if lint switch fallthrough enabled.
  1869             if (!hasDefault) {
  1870                 inits.andSet(initsSwitch);
  1872             resolveBreaks(tree, prevPendingExits);
  1873             nextadr = nextadrPrev;
  1875         // where
  1876             /** Add any variables defined in stats to inits and uninits. */
  1877             private void addVars(List<JCStatement> stats, Bits inits,
  1878                                         Bits uninits) {
  1879                 for (;stats.nonEmpty(); stats = stats.tail) {
  1880                     JCTree stat = stats.head;
  1881                     if (stat.hasTag(VARDEF)) {
  1882                         int adr = ((JCVariableDecl) stat).sym.adr;
  1883                         inits.excl(adr);
  1884                         uninits.incl(adr);
  1889         public void visitTry(JCTry tree) {
  1890             ListBuffer<JCVariableDecl> resourceVarDecls = ListBuffer.lb();
  1891             Bits uninitsTryPrev = uninitsTry;
  1892             ListBuffer<AssignPendingExit> prevPendingExits = pendingExits;
  1893             pendingExits = new ListBuffer<AssignPendingExit>();
  1894             Bits initsTry = inits.dup();
  1895             uninitsTry = uninits.dup();
  1896             for (JCTree resource : tree.resources) {
  1897                 if (resource instanceof JCVariableDecl) {
  1898                     JCVariableDecl vdecl = (JCVariableDecl) resource;
  1899                     visitVarDef(vdecl);
  1900                     unrefdResources.enter(vdecl.sym);
  1901                     resourceVarDecls.append(vdecl);
  1902                 } else if (resource instanceof JCExpression) {
  1903                     scanExpr((JCExpression) resource);
  1904                 } else {
  1905                     throw new AssertionError(tree);  // parser error
  1908             scan(tree.body);
  1909             uninitsTry.andSet(uninits);
  1910             Bits initsEnd = inits;
  1911             Bits uninitsEnd = uninits;
  1912             int nextadrCatch = nextadr;
  1914             if (!resourceVarDecls.isEmpty() &&
  1915                     lint.isEnabled(Lint.LintCategory.TRY)) {
  1916                 for (JCVariableDecl resVar : resourceVarDecls) {
  1917                     if (unrefdResources.includes(resVar.sym)) {
  1918                         log.warning(Lint.LintCategory.TRY, resVar.pos(),
  1919                                     "try.resource.not.referenced", resVar.sym);
  1920                         unrefdResources.remove(resVar.sym);
  1925             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
  1926                 JCVariableDecl param = l.head.param;
  1927                 inits = initsTry.dup();
  1928                 uninits = uninitsTry.dup();
  1929                 scan(param);
  1930                 inits.incl(param.sym.adr);
  1931                 uninits.excl(param.sym.adr);
  1932                 scan(l.head.body);
  1933                 initsEnd.andSet(inits);
  1934                 uninitsEnd.andSet(uninits);
  1935                 nextadr = nextadrCatch;
  1937             if (tree.finalizer != null) {
  1938                 inits = initsTry.dup();
  1939                 uninits = uninitsTry.dup();
  1940                 ListBuffer<AssignPendingExit> exits = pendingExits;
  1941                 pendingExits = prevPendingExits;
  1942                 scan(tree.finalizer);
  1943                 if (!tree.finallyCanCompleteNormally) {
  1944                     // discard exits and exceptions from try and finally
  1945                 } else {
  1946                     uninits.andSet(uninitsEnd);
  1947                     // FIX: this doesn't preserve source order of exits in catch
  1948                     // versus finally!
  1949                     while (exits.nonEmpty()) {
  1950                         AssignPendingExit exit = exits.next();
  1951                         if (exit.exit_inits != null) {
  1952                             exit.exit_inits.orSet(inits);
  1953                             exit.exit_uninits.andSet(uninits);
  1955                         pendingExits.append(exit);
  1957                     inits.orSet(initsEnd);
  1959             } else {
  1960                 inits = initsEnd;
  1961                 uninits = uninitsEnd;
  1962                 ListBuffer<AssignPendingExit> exits = pendingExits;
  1963                 pendingExits = prevPendingExits;
  1964                 while (exits.nonEmpty()) pendingExits.append(exits.next());
  1966             uninitsTry.andSet(uninitsTryPrev).andSet(uninits);
  1969         public void visitConditional(JCConditional tree) {
  1970             scanCond(tree.cond);
  1971             Bits initsBeforeElse = initsWhenFalse;
  1972             Bits uninitsBeforeElse = uninitsWhenFalse;
  1973             inits = initsWhenTrue;
  1974             uninits = uninitsWhenTrue;
  1975             if (tree.truepart.type.hasTag(BOOLEAN) &&
  1976                 tree.falsepart.type.hasTag(BOOLEAN)) {
  1977                 // if b and c are boolean valued, then
  1978                 // v is (un)assigned after a?b:c when true iff
  1979                 //    v is (un)assigned after b when true and
  1980                 //    v is (un)assigned after c when true
  1981                 scanCond(tree.truepart);
  1982                 Bits initsAfterThenWhenTrue = initsWhenTrue.dup();
  1983                 Bits initsAfterThenWhenFalse = initsWhenFalse.dup();
  1984                 Bits uninitsAfterThenWhenTrue = uninitsWhenTrue.dup();
  1985                 Bits uninitsAfterThenWhenFalse = uninitsWhenFalse.dup();
  1986                 inits = initsBeforeElse;
  1987                 uninits = uninitsBeforeElse;
  1988                 scanCond(tree.falsepart);
  1989                 initsWhenTrue.andSet(initsAfterThenWhenTrue);
  1990                 initsWhenFalse.andSet(initsAfterThenWhenFalse);
  1991                 uninitsWhenTrue.andSet(uninitsAfterThenWhenTrue);
  1992                 uninitsWhenFalse.andSet(uninitsAfterThenWhenFalse);
  1993             } else {
  1994                 scanExpr(tree.truepart);
  1995                 Bits initsAfterThen = inits.dup();
  1996                 Bits uninitsAfterThen = uninits.dup();
  1997                 inits = initsBeforeElse;
  1998                 uninits = uninitsBeforeElse;
  1999                 scanExpr(tree.falsepart);
  2000                 inits.andSet(initsAfterThen);
  2001                 uninits.andSet(uninitsAfterThen);
  2005         public void visitIf(JCIf tree) {
  2006             scanCond(tree.cond);
  2007             Bits initsBeforeElse = initsWhenFalse;
  2008             Bits uninitsBeforeElse = uninitsWhenFalse;
  2009             inits = initsWhenTrue;
  2010             uninits = uninitsWhenTrue;
  2011             scan(tree.thenpart);
  2012             if (tree.elsepart != null) {
  2013                 Bits initsAfterThen = inits.dup();
  2014                 Bits uninitsAfterThen = uninits.dup();
  2015                 inits = initsBeforeElse;
  2016                 uninits = uninitsBeforeElse;
  2017                 scan(tree.elsepart);
  2018                 inits.andSet(initsAfterThen);
  2019                 uninits.andSet(uninitsAfterThen);
  2020             } else {
  2021                 inits.andSet(initsBeforeElse);
  2022                 uninits.andSet(uninitsBeforeElse);
  2026         public void visitBreak(JCBreak tree) {
  2027             recordExit(tree, new AssignPendingExit(tree, inits, uninits));
  2030         public void visitContinue(JCContinue tree) {
  2031             recordExit(tree, new AssignPendingExit(tree, inits, uninits));
  2034         public void visitReturn(JCReturn tree) {
  2035             scanExpr(tree.expr);
  2036             recordExit(tree, new AssignPendingExit(tree, inits, uninits));
  2039         public void visitThrow(JCThrow tree) {
  2040             scanExpr(tree.expr);
  2041             markDead();
  2044         public void visitApply(JCMethodInvocation tree) {
  2045             scanExpr(tree.meth);
  2046             scanExprs(tree.args);
  2049         public void visitNewClass(JCNewClass tree) {
  2050             scanExpr(tree.encl);
  2051             scanExprs(tree.args);
  2052             scan(tree.def);
  2055         @Override
  2056         public void visitLambda(JCLambda tree) {
  2057             Bits prevUninits = uninits;
  2058             Bits prevInits = inits;
  2059             int returnadrPrev = returnadr;
  2060             ListBuffer<AssignPendingExit> prevPending = pendingExits;
  2061             try {
  2062                 returnadr = nextadr;
  2063                 pendingExits = new ListBuffer<AssignPendingExit>();
  2064                 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
  2065                     JCVariableDecl def = l.head;
  2066                     scan(def);
  2067                     inits.incl(def.sym.adr);
  2068                     uninits.excl(def.sym.adr);
  2070                 if (tree.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
  2071                     scanExpr(tree.body);
  2072                 } else {
  2073                     scan(tree.body);
  2076             finally {
  2077                 returnadr = returnadrPrev;
  2078                 uninits = prevUninits;
  2079                 inits = prevInits;
  2080                 pendingExits = prevPending;
  2084         public void visitNewArray(JCNewArray tree) {
  2085             scanExprs(tree.dims);
  2086             scanExprs(tree.elems);
  2089         public void visitAssert(JCAssert tree) {
  2090             Bits initsExit = inits.dup();
  2091             Bits uninitsExit = uninits.dup();
  2092             scanCond(tree.cond);
  2093             uninitsExit.andSet(uninitsWhenTrue);
  2094             if (tree.detail != null) {
  2095                 inits = initsWhenFalse;
  2096                 uninits = uninitsWhenFalse;
  2097                 scanExpr(tree.detail);
  2099             inits = initsExit;
  2100             uninits = uninitsExit;
  2103         public void visitAssign(JCAssign tree) {
  2104             JCTree lhs = TreeInfo.skipParens(tree.lhs);
  2105             if (!(lhs instanceof JCIdent)) {
  2106                 scanExpr(lhs);
  2108             scanExpr(tree.rhs);
  2109             letInit(lhs);
  2112         public void visitAssignop(JCAssignOp tree) {
  2113             scanExpr(tree.lhs);
  2114             scanExpr(tree.rhs);
  2115             letInit(tree.lhs);
  2118         public void visitUnary(JCUnary tree) {
  2119             switch (tree.getTag()) {
  2120             case NOT:
  2121                 scanCond(tree.arg);
  2122                 Bits t = initsWhenFalse;
  2123                 initsWhenFalse = initsWhenTrue;
  2124                 initsWhenTrue = t;
  2125                 t = uninitsWhenFalse;
  2126                 uninitsWhenFalse = uninitsWhenTrue;
  2127                 uninitsWhenTrue = t;
  2128                 break;
  2129             case PREINC: case POSTINC:
  2130             case PREDEC: case POSTDEC:
  2131                 scanExpr(tree.arg);
  2132                 letInit(tree.arg);
  2133                 break;
  2134             default:
  2135                 scanExpr(tree.arg);
  2139         public void visitBinary(JCBinary tree) {
  2140             switch (tree.getTag()) {
  2141             case AND:
  2142                 scanCond(tree.lhs);
  2143                 Bits initsWhenFalseLeft = initsWhenFalse;
  2144                 Bits uninitsWhenFalseLeft = uninitsWhenFalse;
  2145                 inits = initsWhenTrue;
  2146                 uninits = uninitsWhenTrue;
  2147                 scanCond(tree.rhs);
  2148                 initsWhenFalse.andSet(initsWhenFalseLeft);
  2149                 uninitsWhenFalse.andSet(uninitsWhenFalseLeft);
  2150                 break;
  2151             case OR:
  2152                 scanCond(tree.lhs);
  2153                 Bits initsWhenTrueLeft = initsWhenTrue;
  2154                 Bits uninitsWhenTrueLeft = uninitsWhenTrue;
  2155                 inits = initsWhenFalse;
  2156                 uninits = uninitsWhenFalse;
  2157                 scanCond(tree.rhs);
  2158                 initsWhenTrue.andSet(initsWhenTrueLeft);
  2159                 uninitsWhenTrue.andSet(uninitsWhenTrueLeft);
  2160                 break;
  2161             default:
  2162                 scanExpr(tree.lhs);
  2163                 scanExpr(tree.rhs);
  2167         public void visitIdent(JCIdent tree) {
  2168             if (tree.sym.kind == VAR) {
  2169                 checkInit(tree.pos(), (VarSymbol)tree.sym);
  2170                 referenced(tree.sym);
  2174         void referenced(Symbol sym) {
  2175             unrefdResources.remove(sym);
  2178         public void visitTopLevel(JCCompilationUnit tree) {
  2179             // Do nothing for TopLevel since each class is visited individually
  2182     /**************************************************************************
  2183      * main method
  2184      *************************************************************************/
  2186         /** Perform definite assignment/unassignment analysis on a tree.
  2187          */
  2188         public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
  2189             analyzeTree(env, env.tree, make);
  2192         public void analyzeTree(Env<AttrContext> env, JCTree tree, TreeMaker make) {
  2193             try {
  2194                 attrEnv = env;
  2195                 Flow.this.make = make;
  2196                 startPos = tree.pos().getStartPosition();
  2197                 inits = new Bits();
  2198                 uninits = new Bits();
  2199                 uninitsTry = new Bits();
  2200                 initsWhenTrue = initsWhenFalse =
  2201                     uninitsWhenTrue = uninitsWhenFalse = null;
  2202                 if (vars == null)
  2203                     vars = new VarSymbol[32];
  2204                 else
  2205                     for (int i=0; i<vars.length; i++)
  2206                         vars[i] = null;
  2207                 firstadr = 0;
  2208                 nextadr = 0;
  2209                 pendingExits = new ListBuffer<AssignPendingExit>();
  2210                 this.classDef = null;
  2211                 unrefdResources = new Scope(env.enclClass.sym);
  2212                 scan(tree);
  2213             } finally {
  2214                 // note that recursive invocations of this method fail hard
  2215                 startPos = -1;
  2216                 inits = uninits = uninitsTry = null;
  2217                 initsWhenTrue = initsWhenFalse =
  2218                     uninitsWhenTrue = uninitsWhenFalse = null;
  2219                 if (vars != null) for (int i=0; i<vars.length; i++)
  2220                     vars[i] = null;
  2221                 firstadr = 0;
  2222                 nextadr = 0;
  2223                 pendingExits = null;
  2224                 Flow.this.make = null;
  2225                 this.classDef = null;
  2226                 unrefdResources = null;
  2231     /**
  2232      * This pass implements the last step of the dataflow analysis, namely
  2233      * the effectively-final analysis check. This checks that every local variable
  2234      * reference from a lambda body/local inner class is either final or effectively final.
  2235      * As effectively final variables are marked as such during DA/DU, this pass must run after
  2236      * AssignAnalyzer.
  2237      */
  2238     class CaptureAnalyzer extends BaseAnalyzer<BaseAnalyzer.PendingExit> {
  2240         JCTree currentTree; //local class or lambda
  2242         @Override
  2243         void markDead() {
  2244             //do nothing
  2247         @SuppressWarnings("fallthrough")
  2248         void checkEffectivelyFinal(DiagnosticPosition pos, VarSymbol sym) {
  2249             if (currentTree != null &&
  2250                     sym.owner.kind == MTH &&
  2251                     sym.pos < currentTree.getStartPosition()) {
  2252                 switch (currentTree.getTag()) {
  2253                     case CLASSDEF:
  2254                         if (!allowEffectivelyFinalInInnerClasses) {
  2255                             if ((sym.flags() & FINAL) == 0) {
  2256                                 reportInnerClsNeedsFinalError(pos, sym);
  2258                             break;
  2260                     case LAMBDA:
  2261                         if ((sym.flags() & (EFFECTIVELY_FINAL | FINAL)) == 0) {
  2262                            reportEffectivelyFinalError(pos, sym);
  2268         @SuppressWarnings("fallthrough")
  2269         void letInit(JCTree tree) {
  2270             tree = TreeInfo.skipParens(tree);
  2271             if (tree.hasTag(IDENT) || tree.hasTag(SELECT)) {
  2272                 Symbol sym = TreeInfo.symbol(tree);
  2273                 if (currentTree != null &&
  2274                         sym.kind == VAR &&
  2275                         sym.owner.kind == MTH &&
  2276                         ((VarSymbol)sym).pos < currentTree.getStartPosition()) {
  2277                     switch (currentTree.getTag()) {
  2278                         case CLASSDEF:
  2279                             if (!allowEffectivelyFinalInInnerClasses) {
  2280                                 reportInnerClsNeedsFinalError(tree, sym);
  2281                                 break;
  2283                         case LAMBDA:
  2284                             reportEffectivelyFinalError(tree, sym);
  2290         void reportEffectivelyFinalError(DiagnosticPosition pos, Symbol sym) {
  2291             String subKey = currentTree.hasTag(LAMBDA) ?
  2292                   "lambda"  : "inner.cls";
  2293             log.error(pos, "cant.ref.non.effectively.final.var", sym, diags.fragment(subKey));
  2296         void reportInnerClsNeedsFinalError(DiagnosticPosition pos, Symbol sym) {
  2297             log.error(pos,
  2298                     "local.var.accessed.from.icls.needs.final",
  2299                     sym);
  2302     /*************************************************************************
  2303      * Visitor methods for statements and definitions
  2304      *************************************************************************/
  2306         /* ------------ Visitor methods for various sorts of trees -------------*/
  2308         public void visitClassDef(JCClassDecl tree) {
  2309             JCTree prevTree = currentTree;
  2310             try {
  2311                 currentTree = tree.sym.isLocal() ? tree : null;
  2312                 super.visitClassDef(tree);
  2313             } finally {
  2314                 currentTree = prevTree;
  2318         @Override
  2319         public void visitLambda(JCLambda tree) {
  2320             JCTree prevTree = currentTree;
  2321             try {
  2322                 currentTree = tree;
  2323                 super.visitLambda(tree);
  2324             } finally {
  2325                 currentTree = prevTree;
  2329         @Override
  2330         public void visitIdent(JCIdent tree) {
  2331             if (tree.sym.kind == VAR) {
  2332                 checkEffectivelyFinal(tree, (VarSymbol)tree.sym);
  2336         public void visitAssign(JCAssign tree) {
  2337             JCTree lhs = TreeInfo.skipParens(tree.lhs);
  2338             if (!(lhs instanceof JCIdent)) {
  2339                 scan(lhs);
  2341             scan(tree.rhs);
  2342             letInit(lhs);
  2345         public void visitAssignop(JCAssignOp tree) {
  2346             scan(tree.lhs);
  2347             scan(tree.rhs);
  2348             letInit(tree.lhs);
  2351         public void visitUnary(JCUnary tree) {
  2352             switch (tree.getTag()) {
  2353                 case PREINC: case POSTINC:
  2354                 case PREDEC: case POSTDEC:
  2355                     scan(tree.arg);
  2356                     letInit(tree.arg);
  2357                     break;
  2358                 default:
  2359                     scan(tree.arg);
  2363         public void visitTopLevel(JCCompilationUnit tree) {
  2364             // Do nothing for TopLevel since each class is visited individually
  2367     /**************************************************************************
  2368      * main method
  2369      *************************************************************************/
  2371         /** Perform definite assignment/unassignment analysis on a tree.
  2372          */
  2373         public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
  2374             analyzeTree(env, env.tree, make);
  2376         public void analyzeTree(Env<AttrContext> env, JCTree tree, TreeMaker make) {
  2377             try {
  2378                 attrEnv = env;
  2379                 Flow.this.make = make;
  2380                 pendingExits = new ListBuffer<PendingExit>();
  2381                 scan(tree);
  2382             } finally {
  2383                 pendingExits = null;
  2384                 Flow.this.make = null;

mercurial