1 /*
   2  * Copyright (c) 1999, 2021, 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  */
  25 
  26 //todo: one might eliminate uninits.andSets when monotonic
  27 
  28 package com.sun.tools.javac.comp;
  29 
  30 import java.util.HashMap;
  31 import java.util.HashSet;
  32 import java.util.Set;
  33 import java.util.stream.StreamSupport;
  34 
  35 import com.sun.source.tree.LambdaExpressionTree.BodyKind;
  36 import com.sun.tools.javac.code.*;
  37 import com.sun.tools.javac.code.Scope.WriteableScope;
  38 import com.sun.tools.javac.code.Source.Feature;
  39 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  40 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
  41 import com.sun.tools.javac.tree.*;
  42 import com.sun.tools.javac.tree.TreeInfo.PatternPrimaryType;
  43 import com.sun.tools.javac.util.*;
  44 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  45 import com.sun.tools.javac.util.JCDiagnostic.Error;
  46 import com.sun.tools.javac.util.JCDiagnostic.Warning;
  47 
  48 import com.sun.tools.javac.code.Symbol.*;
  49 import com.sun.tools.javac.tree.JCTree.*;
  50 
  51 import static com.sun.tools.javac.code.Flags.*;
  52 import static com.sun.tools.javac.code.Flags.BLOCK;
  53 import static com.sun.tools.javac.code.Kinds.Kind.*;
  54 import com.sun.tools.javac.code.Type.TypeVar;
  55 import static com.sun.tools.javac.code.TypeTag.BOOLEAN;
  56 import static com.sun.tools.javac.code.TypeTag.VOID;
  57 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  58 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  59 import com.sun.tools.javac.util.JCDiagnostic.Fragment;
  60 
  61 /** This pass implements dataflow analysis for Java programs though
  62  *  different AST visitor steps. Liveness analysis (see AliveAnalyzer) checks that
  63  *  every statement is reachable. Exception analysis (see FlowAnalyzer) ensures that
  64  *  every checked exception that is thrown is declared or caught.  Definite assignment analysis
  65  *  (see AssignAnalyzer) ensures that each variable is assigned when used.  Definite
  66  *  unassignment analysis (see AssignAnalyzer) in ensures that no final variable
  67  *  is assigned more than once. Finally, local variable capture analysis (see CaptureAnalyzer)
  68  *  determines that local variables accessed within the scope of an inner class/lambda
  69  *  are either final or effectively-final.
  70  *
  71  *  <p>The JLS has a number of problems in the
  72  *  specification of these flow analysis problems. This implementation
  73  *  attempts to address those issues.
  74  *
  75  *  <p>First, there is no accommodation for a finally clause that cannot
  76  *  complete normally. For liveness analysis, an intervening finally
  77  *  clause can cause a break, continue, or return not to reach its
  78  *  target.  For exception analysis, an intervening finally clause can
  79  *  cause any exception to be "caught".  For DA/DU analysis, the finally
  80  *  clause can prevent a transfer of control from propagating DA/DU
  81  *  state to the target.  In addition, code in the finally clause can
  82  *  affect the DA/DU status of variables.
  83  *
  84  *  <p>For try statements, we introduce the idea of a variable being
  85  *  definitely unassigned "everywhere" in a block.  A variable V is
  86  *  "unassigned everywhere" in a block iff it is unassigned at the
  87  *  beginning of the block and there is no reachable assignment to V
  88  *  in the block.  An assignment V=e is reachable iff V is not DA
  89  *  after e.  Then we can say that V is DU at the beginning of the
  90  *  catch block iff V is DU everywhere in the try block.  Similarly, V
  91  *  is DU at the beginning of the finally block iff V is DU everywhere
  92  *  in the try block and in every catch block.  Specifically, the
  93  *  following bullet is added to 16.2.2
  94  *  <pre>
  95  *      V is <em>unassigned everywhere</em> in a block if it is
  96  *      unassigned before the block and there is no reachable
  97  *      assignment to V within the block.
  98  *  </pre>
  99  *  <p>In 16.2.15, the third bullet (and all of its sub-bullets) for all
 100  *  try blocks is changed to
 101  *  <pre>
 102  *      V is definitely unassigned before a catch block iff V is
 103  *      definitely unassigned everywhere in the try block.
 104  *  </pre>
 105  *  <p>The last bullet (and all of its sub-bullets) for try blocks that
 106  *  have a finally block is changed to
 107  *  <pre>
 108  *      V is definitely unassigned before the finally block iff
 109  *      V is definitely unassigned everywhere in the try block
 110  *      and everywhere in each catch block of the try statement.
 111  *  </pre>
 112  *  <p>In addition,
 113  *  <pre>
 114  *      V is definitely assigned at the end of a constructor iff
 115  *      V is definitely assigned after the block that is the body
 116  *      of the constructor and V is definitely assigned at every
 117  *      return that can return from the constructor.
 118  *  </pre>
 119  *  <p>In addition, each continue statement with the loop as its target
 120  *  is treated as a jump to the end of the loop body, and "intervening"
 121  *  finally clauses are treated as follows: V is DA "due to the
 122  *  continue" iff V is DA before the continue statement or V is DA at
 123  *  the end of any intervening finally block.  V is DU "due to the
 124  *  continue" iff any intervening finally cannot complete normally or V
 125  *  is DU at the end of every intervening finally block.  This "due to
 126  *  the continue" concept is then used in the spec for the loops.
 127  *
 128  *  <p>Similarly, break statements must consider intervening finally
 129  *  blocks.  For liveness analysis, a break statement for which any
 130  *  intervening finally cannot complete normally is not considered to
 131  *  cause the target statement to be able to complete normally. Then
 132  *  we say V is DA "due to the break" iff V is DA before the break or
 133  *  V is DA at the end of any intervening finally block.  V is DU "due
 134  *  to the break" iff any intervening finally cannot complete normally
 135  *  or V is DU at the break and at the end of every intervening
 136  *  finally block.  (I suspect this latter condition can be
 137  *  simplified.)  This "due to the break" is then used in the spec for
 138  *  all statements that can be "broken".
 139  *
 140  *  <p>The return statement is treated similarly.  V is DA "due to a
 141  *  return statement" iff V is DA before the return statement or V is
 142  *  DA at the end of any intervening finally block.  Note that we
 143  *  don't have to worry about the return expression because this
 144  *  concept is only used for constructors.
 145  *
 146  *  <p>There is no spec in the JLS for when a variable is definitely
 147  *  assigned at the end of a constructor, which is needed for final
 148  *  fields (8.3.1.2).  We implement the rule that V is DA at the end
 149  *  of the constructor iff it is DA and the end of the body of the
 150  *  constructor and V is DA "due to" every return of the constructor.
 151  *
 152  *  <p>Intervening finally blocks similarly affect exception analysis.  An
 153  *  intervening finally that cannot complete normally allows us to ignore
 154  *  an otherwise uncaught exception.
 155  *
 156  *  <p>To implement the semantics of intervening finally clauses, all
 157  *  nonlocal transfers (break, continue, return, throw, method call that
 158  *  can throw a checked exception, and a constructor invocation that can
 159  *  thrown a checked exception) are recorded in a queue, and removed
 160  *  from the queue when we complete processing the target of the
 161  *  nonlocal transfer.  This allows us to modify the queue in accordance
 162  *  with the above rules when we encounter a finally clause.  The only
 163  *  exception to this [no pun intended] is that checked exceptions that
 164  *  are known to be caught or declared to be caught in the enclosing
 165  *  method are not recorded in the queue, but instead are recorded in a
 166  *  global variable "{@code Set<Type> thrown}" that records the type of all
 167  *  exceptions that can be thrown.
 168  *
 169  *  <p>Other minor issues the treatment of members of other classes
 170  *  (always considered DA except that within an anonymous class
 171  *  constructor, where DA status from the enclosing scope is
 172  *  preserved), treatment of the case expression (V is DA before the
 173  *  case expression iff V is DA after the switch expression),
 174  *  treatment of variables declared in a switch block (the implied
 175  *  DA/DU status after the switch expression is DU and not DA for
 176  *  variables defined in a switch block), the treatment of boolean ?:
 177  *  expressions (The JLS rules only handle b and c non-boolean; the
 178  *  new rule is that if b and c are boolean valued, then V is
 179  *  (un)assigned after a?b:c when true/false iff V is (un)assigned
 180  *  after b when true/false and V is (un)assigned after c when
 181  *  true/false).
 182  *
 183  *  <p>There is the remaining question of what syntactic forms constitute a
 184  *  reference to a variable.  It is conventional to allow this.x on the
 185  *  left-hand-side to initialize a final instance field named x, yet
 186  *  this.x isn't considered a "use" when appearing on a right-hand-side
 187  *  in most implementations.  Should parentheses affect what is
 188  *  considered a variable reference?  The simplest rule would be to
 189  *  allow unqualified forms only, parentheses optional, and phase out
 190  *  support for assigning to a final field via this.x.
 191  *
 192  *  <p><b>This is NOT part of any supported API.
 193  *  If you write code that depends on this, you do so at your own risk.
 194  *  This code and its internal interfaces are subject to change or
 195  *  deletion without notice.</b>
 196  */
 197 public class Flow {
 198     protected static final Context.Key<Flow> flowKey = new Context.Key<>();
 199 
 200     private final Names names;
 201     private final Log log;
 202     private final Symtab syms;
 203     private final Types types;
 204     private final Check chk;
 205     private       TreeMaker make;
 206     private final Resolve rs;
 207     private final JCDiagnostic.Factory diags;
 208     private Env<AttrContext> attrEnv;
 209     private       Lint lint;
 210     private final DeferredCompletionFailureHandler dcfh;
 211     private final boolean allowEffectivelyFinalInInnerClasses;
 212 
 213     public static Flow instance(Context context) {
 214         Flow instance = context.get(flowKey);
 215         if (instance == null)
 216             instance = new Flow(context);
 217         return instance;
 218     }
 219 
 220     public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
 221         new AliveAnalyzer().analyzeTree(env, make);
 222         new AssignAnalyzer().analyzeTree(env, make);
 223         new FlowAnalyzer().analyzeTree(env, make);
 224         new CaptureAnalyzer().analyzeTree(env, make);
 225     }
 226 
 227     public void analyzeLambda(Env<AttrContext> env, JCLambda that, TreeMaker make, boolean speculative) {
 228         Log.DiagnosticHandler diagHandler = null;
 229         //we need to disable diagnostics temporarily; the problem is that if
 230         //a lambda expression contains e.g. an unreachable statement, an error
 231         //message will be reported and will cause compilation to skip the flow analysis
 232         //step - if we suppress diagnostics, we won't stop at Attr for flow-analysis
 233         //related errors, which will allow for more errors to be detected
 234         if (!speculative) {
 235             diagHandler = new Log.DiscardDiagnosticHandler(log);
 236         }
 237         try {
 238             new LambdaAliveAnalyzer().analyzeTree(env, that, make);
 239         } finally {
 240             if (!speculative) {
 241                 log.popDiagnosticHandler(diagHandler);
 242             }
 243         }
 244     }
 245 
 246     public List<Type> analyzeLambdaThrownTypes(final Env<AttrContext> env,
 247             JCLambda that, TreeMaker make) {
 248         //we need to disable diagnostics temporarily; the problem is that if
 249         //a lambda expression contains e.g. an unreachable statement, an error
 250         //message will be reported and will cause compilation to skip the flow analysis
 251         //step - if we suppress diagnostics, we won't stop at Attr for flow-analysis
 252         //related errors, which will allow for more errors to be detected
 253         Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
 254         try {
 255             new LambdaAssignAnalyzer(env).analyzeTree(env, that, make);
 256             LambdaFlowAnalyzer flowAnalyzer = new LambdaFlowAnalyzer();
 257             flowAnalyzer.analyzeTree(env, that, make);
 258             return flowAnalyzer.inferredThrownTypes;
 259         } finally {
 260             log.popDiagnosticHandler(diagHandler);
 261         }
 262     }
 263 
 264     public boolean aliveAfter(Env<AttrContext> env, JCTree that, TreeMaker make) {
 265         //we need to disable diagnostics temporarily; the problem is that if
 266         //"that" contains e.g. an unreachable statement, an error
 267         //message will be reported and will cause compilation to skip the flow analysis
 268         //step - if we suppress diagnostics, we won't stop at Attr for flow-analysis
 269         //related errors, which will allow for more errors to be detected
 270         Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
 271         try {
 272             SnippetAliveAnalyzer analyzer = new SnippetAliveAnalyzer();
 273 
 274             analyzer.analyzeTree(env, that, make);
 275             return analyzer.isAlive();
 276         } finally {
 277             log.popDiagnosticHandler(diagHandler);
 278         }
 279     }
 280 
 281     public boolean breaksOutOf(Env<AttrContext> env, JCTree loop, JCTree body, TreeMaker make) {
 282         //we need to disable diagnostics temporarily; the problem is that if
 283         //"that" contains e.g. an unreachable statement, an error
 284         //message will be reported and will cause compilation to skip the flow analysis
 285         //step - if we suppress diagnostics, we won't stop at Attr for flow-analysis
 286         //related errors, which will allow for more errors to be detected
 287         Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
 288         try {
 289             SnippetBreakAnalyzer analyzer = new SnippetBreakAnalyzer();
 290 
 291             analyzer.analyzeTree(env, body, make);
 292             return analyzer.breaksOut();
 293         } finally {
 294             log.popDiagnosticHandler(diagHandler);
 295         }
 296     }
 297 
 298     /**
 299      * Definite assignment scan mode
 300      */
 301     enum FlowKind {
 302         /**
 303          * This is the normal DA/DU analysis mode
 304          */
 305         NORMAL("var.might.already.be.assigned", false),
 306         /**
 307          * This is the speculative DA/DU analysis mode used to speculatively
 308          * derive assertions within loop bodies
 309          */
 310         SPECULATIVE_LOOP("var.might.be.assigned.in.loop", true);
 311 
 312         final String errKey;
 313         final boolean isFinal;
 314 
 315         FlowKind(String errKey, boolean isFinal) {
 316             this.errKey = errKey;
 317             this.isFinal = isFinal;
 318         }
 319 
 320         boolean isFinal() {
 321             return isFinal;
 322         }
 323     }
 324 
 325     protected Flow(Context context) {
 326         context.put(flowKey, this);
 327         names = Names.instance(context);
 328         log = Log.instance(context);
 329         syms = Symtab.instance(context);
 330         types = Types.instance(context);
 331         chk = Check.instance(context);
 332         lint = Lint.instance(context);
 333         rs = Resolve.instance(context);
 334         diags = JCDiagnostic.Factory.instance(context);
 335         dcfh = DeferredCompletionFailureHandler.instance(context);
 336         Source source = Source.instance(context);
 337         allowEffectivelyFinalInInnerClasses = Feature.EFFECTIVELY_FINAL_IN_INNER_CLASSES.allowedInSource(source);
 338     }
 339 
 340     /**
 341      * Base visitor class for all visitors implementing dataflow analysis logic.
 342      * This class define the shared logic for handling jumps (break/continue statements).
 343      */
 344     static abstract class BaseAnalyzer extends TreeScanner {
 345 
 346         enum JumpKind {
 347             BREAK(JCTree.Tag.BREAK) {
 348                 @Override
 349                 JCTree getTarget(JCTree tree) {
 350                     return ((JCBreak)tree).target;
 351                 }
 352             },
 353             CONTINUE(JCTree.Tag.CONTINUE) {
 354                 @Override
 355                 JCTree getTarget(JCTree tree) {
 356                     return ((JCContinue)tree).target;
 357                 }
 358             },
 359             YIELD(JCTree.Tag.YIELD) {
 360                 @Override
 361                 JCTree getTarget(JCTree tree) {
 362                     return ((JCYield)tree).target;
 363                 }
 364             };
 365 
 366             final JCTree.Tag treeTag;
 367 
 368             private JumpKind(Tag treeTag) {
 369                 this.treeTag = treeTag;
 370             }
 371 
 372             abstract JCTree getTarget(JCTree tree);
 373         }
 374 
 375         /** The currently pending exits that go from current inner blocks
 376          *  to an enclosing block, in source order.
 377          */
 378         ListBuffer<PendingExit> pendingExits;
 379 
 380         /** A pending exit.  These are the statements return, break, and
 381          *  continue.  In addition, exception-throwing expressions or
 382          *  statements are put here when not known to be caught.  This
 383          *  will typically result in an error unless it is within a
 384          *  try-finally whose finally block cannot complete normally.
 385          */
 386         static class PendingExit {
 387             JCTree tree;
 388 
 389             PendingExit(JCTree tree) {
 390                 this.tree = tree;
 391             }
 392 
 393             void resolveJump() {
 394                 //do nothing
 395             }
 396         }
 397 
 398         abstract void markDead();
 399 
 400         /** Record an outward transfer of control. */
 401         void recordExit(PendingExit pe) {
 402             pendingExits.append(pe);
 403             markDead();
 404         }
 405 
 406         /** Resolve all jumps of this statement. */
 407         private Liveness resolveJump(JCTree tree,
 408                          ListBuffer<PendingExit> oldPendingExits,
 409                          JumpKind jk) {
 410             boolean resolved = false;
 411             List<PendingExit> exits = pendingExits.toList();
 412             pendingExits = oldPendingExits;
 413             for (; exits.nonEmpty(); exits = exits.tail) {
 414                 PendingExit exit = exits.head;
 415                 if (exit.tree.hasTag(jk.treeTag) &&
 416                         jk.getTarget(exit.tree) == tree) {
 417                     exit.resolveJump();
 418                     resolved = true;
 419                 } else {
 420                     pendingExits.append(exit);
 421                 }
 422             }
 423             return Liveness.from(resolved);
 424         }
 425 
 426         /** Resolve all continues of this statement. */
 427         Liveness resolveContinues(JCTree tree) {
 428             return resolveJump(tree, new ListBuffer<PendingExit>(), JumpKind.CONTINUE);
 429         }
 430 
 431         /** Resolve all breaks of this statement. */
 432         Liveness resolveBreaks(JCTree tree, ListBuffer<PendingExit> oldPendingExits) {
 433             return resolveJump(tree, oldPendingExits, JumpKind.BREAK);
 434         }
 435 
 436         /** Resolve all yields of this statement. */
 437         Liveness resolveYields(JCTree tree, ListBuffer<PendingExit> oldPendingExits) {
 438             return resolveJump(tree, oldPendingExits, JumpKind.YIELD);
 439         }
 440 
 441         @Override
 442         public void scan(JCTree tree) {
 443             if (tree != null && (
 444                     tree.type == null ||
 445                     tree.type != Type.stuckType)) {
 446                 super.scan(tree);
 447             }
 448         }
 449 
 450         public void visitPackageDef(JCPackageDecl tree) {
 451             // Do nothing for PackageDecl
 452         }
 453 
 454         protected void scanSyntheticBreak(TreeMaker make, JCTree swtch) {
 455             if (swtch.hasTag(SWITCH_EXPRESSION)) {
 456                 JCYield brk = make.at(Position.NOPOS).Yield(null);
 457                 brk.target = swtch;
 458                 scan(brk);
 459             } else {
 460                 JCBreak brk = make.at(Position.NOPOS).Break(null);
 461                 brk.target = swtch;
 462                 scan(brk);
 463             }
 464         }
 465     }
 466 
 467     /**
 468      * This pass implements the first step of the dataflow analysis, namely
 469      * the liveness analysis check. This checks that every statement is reachable.
 470      * The output of this analysis pass are used by other analyzers. This analyzer
 471      * sets the 'finallyCanCompleteNormally' field in the JCTry class.
 472      */
 473     class AliveAnalyzer extends BaseAnalyzer {
 474 
 475         /** A flag that indicates whether the last statement could
 476          *  complete normally.
 477          */
 478         private Liveness alive;
 479 
 480         @Override
 481         void markDead() {
 482             alive = Liveness.DEAD;
 483         }
 484 
 485     /*************************************************************************
 486      * Visitor methods for statements and definitions
 487      *************************************************************************/
 488 
 489         /** Analyze a definition.
 490          */
 491         void scanDef(JCTree tree) {
 492             scanStat(tree);
 493             if (tree != null && tree.hasTag(JCTree.Tag.BLOCK) && alive == Liveness.DEAD) {
 494                 log.error(tree.pos(),
 495                           Errors.InitializerMustBeAbleToCompleteNormally);
 496             }
 497         }
 498 
 499         /** Analyze a statement. Check that statement is reachable.
 500          */
 501         void scanStat(JCTree tree) {
 502             if (alive == Liveness.DEAD && tree != null) {
 503                 log.error(tree.pos(), Errors.UnreachableStmt);
 504                 if (!tree.hasTag(SKIP)) alive = Liveness.RECOVERY;
 505             }
 506             scan(tree);
 507         }
 508 
 509         /** Analyze list of statements.
 510          */
 511         void scanStats(List<? extends JCStatement> trees) {
 512             if (trees != null)
 513                 for (List<? extends JCStatement> l = trees; l.nonEmpty(); l = l.tail)
 514                     scanStat(l.head);
 515         }
 516 
 517         /* ------------ Visitor methods for various sorts of trees -------------*/
 518 
 519         public void visitClassDef(JCClassDecl tree) {
 520             if (tree.sym == null) return;
 521             Liveness alivePrev = alive;
 522             ListBuffer<PendingExit> pendingExitsPrev = pendingExits;
 523             Lint lintPrev = lint;
 524 
 525             pendingExits = new ListBuffer<>();
 526             lint = lint.augment(tree.sym);
 527 
 528             try {
 529                 // process all the static initializers
 530                 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
 531                     if (!l.head.hasTag(METHODDEF) &&
 532                         (TreeInfo.flags(l.head) & STATIC) != 0) {
 533                         scanDef(l.head);
 534                         clearPendingExits(false);
 535                     }
 536                 }
 537 
 538                 // process all the instance initializers
 539                 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
 540                     if (!l.head.hasTag(METHODDEF) &&
 541                         (TreeInfo.flags(l.head) & STATIC) == 0) {
 542                         scanDef(l.head);
 543                         clearPendingExits(false);
 544                     }
 545                 }
 546 
 547                 // process all the methods
 548                 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
 549                     if (l.head.hasTag(METHODDEF)) {
 550                         scan(l.head);
 551                     }
 552                 }
 553             } finally {
 554                 pendingExits = pendingExitsPrev;
 555                 alive = alivePrev;
 556                 lint = lintPrev;
 557             }
 558         }
 559 
 560         public void visitMethodDef(JCMethodDecl tree) {
 561             if (tree.body == null) return;
 562             Lint lintPrev = lint;
 563 
 564             lint = lint.augment(tree.sym);
 565 
 566             Assert.check(pendingExits.isEmpty());
 567 
 568             try {
 569                 alive = Liveness.ALIVE;
 570                 scanStat(tree.body);
 571                 tree.completesNormally = alive != Liveness.DEAD;
 572 
 573                 if (alive == Liveness.ALIVE && !tree.sym.type.getReturnType().hasTag(VOID))
 574                     log.error(TreeInfo.diagEndPos(tree.body), Errors.MissingRetStmt);
 575 
 576                 clearPendingExits(true);
 577             } finally {
 578                 lint = lintPrev;
 579             }
 580         }
 581 
 582         private void clearPendingExits(boolean inMethod) {
 583             List<PendingExit> exits = pendingExits.toList();
 584             pendingExits = new ListBuffer<>();
 585             while (exits.nonEmpty()) {
 586                 PendingExit exit = exits.head;
 587                 exits = exits.tail;
 588                 Assert.check((inMethod && exit.tree.hasTag(RETURN)) ||
 589                                 log.hasErrorOn(exit.tree.pos()));
 590             }
 591         }
 592 
 593         public void visitVarDef(JCVariableDecl tree) {
 594             if (tree.init != null) {
 595                 Lint lintPrev = lint;
 596                 lint = lint.augment(tree.sym);
 597                 try{
 598                     scan(tree.init);
 599                 } finally {
 600                     lint = lintPrev;
 601                 }
 602             }
 603         }
 604 
 605         public void visitBlock(JCBlock tree) {
 606             scanStats(tree.stats);
 607         }
 608 
 609         public void visitDoLoop(JCDoWhileLoop tree) {
 610             ListBuffer<PendingExit> prevPendingExits = pendingExits;
 611             pendingExits = new ListBuffer<>();
 612             scanStat(tree.body);
 613             alive = alive.or(resolveContinues(tree));
 614             scan(tree.cond);
 615             alive = alive.and(!tree.cond.type.isTrue());
 616             alive = alive.or(resolveBreaks(tree, prevPendingExits));
 617         }
 618 
 619         public void visitWhileLoop(JCWhileLoop tree) {
 620             ListBuffer<PendingExit> prevPendingExits = pendingExits;
 621             pendingExits = new ListBuffer<>();
 622             scan(tree.cond);
 623             alive = Liveness.from(!tree.cond.type.isFalse());
 624             scanStat(tree.body);
 625             alive = alive.or(resolveContinues(tree));
 626             alive = resolveBreaks(tree, prevPendingExits).or(
 627                 !tree.cond.type.isTrue());
 628         }
 629 
 630         public void visitForLoop(JCForLoop tree) {
 631             ListBuffer<PendingExit> prevPendingExits = pendingExits;
 632             scanStats(tree.init);
 633             pendingExits = new ListBuffer<>();
 634             if (tree.cond != null) {
 635                 scan(tree.cond);
 636                 alive = Liveness.from(!tree.cond.type.isFalse());
 637             } else {
 638                 alive = Liveness.ALIVE;
 639             }
 640             scanStat(tree.body);
 641             alive = alive.or(resolveContinues(tree));
 642             scan(tree.step);
 643             alive = resolveBreaks(tree, prevPendingExits).or(
 644                 tree.cond != null && !tree.cond.type.isTrue());
 645         }
 646 
 647         public void visitForeachLoop(JCEnhancedForLoop tree) {
 648             visitVarDef(tree.var);
 649             ListBuffer<PendingExit> prevPendingExits = pendingExits;
 650             scan(tree.expr);
 651             pendingExits = new ListBuffer<>();
 652             scanStat(tree.body);
 653             alive = alive.or(resolveContinues(tree));
 654             resolveBreaks(tree, prevPendingExits);
 655             alive = Liveness.ALIVE;
 656         }
 657 
 658         public void visitLabelled(JCLabeledStatement tree) {
 659             ListBuffer<PendingExit> prevPendingExits = pendingExits;
 660             pendingExits = new ListBuffer<>();
 661             scanStat(tree.body);
 662             alive = alive.or(resolveBreaks(tree, prevPendingExits));
 663         }
 664 
 665         public void visitSwitch(JCSwitch tree) {
 666             ListBuffer<PendingExit> prevPendingExits = pendingExits;
 667             pendingExits = new ListBuffer<>();
 668             scan(tree.selector);
 669             boolean exhaustiveSwitch = tree.patternSwitch ||
 670                                        tree.cases.stream()
 671                                                  .flatMap(c -> c.labels.stream())
 672                                                  .anyMatch(l -> TreeInfo.isNull(l));
 673             Set<Symbol> constants = exhaustiveSwitch ? new HashSet<>() : null;
 674             for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
 675                 alive = Liveness.ALIVE;
 676                 JCCase c = l.head;
 677                 for (JCCaseLabel pat : c.labels) {
 678                     scan(pat);
 679                     handleConstantCaseLabel(constants, pat);
 680                 }
 681                 scanStats(c.stats);
 682                 if (alive != Liveness.DEAD && c.caseKind == JCCase.RULE) {
 683                     scanSyntheticBreak(make, tree);
 684                     alive = Liveness.DEAD;
 685                 }
 686                 // Warn about fall-through if lint switch fallthrough enabled.
 687                 if (alive == Liveness.ALIVE &&
 688                     lint.isEnabled(Lint.LintCategory.FALLTHROUGH) &&
 689                     c.stats.nonEmpty() && l.tail.nonEmpty())
 690                     log.warning(Lint.LintCategory.FALLTHROUGH,
 691                                 l.tail.head.pos(),
 692                                 Warnings.PossibleFallThroughIntoCase);
 693             }
 694             if (!tree.hasTotalPattern && exhaustiveSwitch &&
 695                 !TreeInfo.isErrorEnumSwitch(tree.selector, tree.cases) &&
 696                 (constants == null || !isExhaustive(tree.selector.type, constants))) {
 697                 log.error(tree, Errors.NotExhaustiveStatement);
 698             }
 699             if (!tree.hasTotalPattern) {
 700                 alive = Liveness.ALIVE;
 701             }
 702             alive = alive.or(resolveBreaks(tree, prevPendingExits));
 703         }
 704 
 705         @Override
 706         public void visitSwitchExpression(JCSwitchExpression tree) {
 707             ListBuffer<PendingExit> prevPendingExits = pendingExits;
 708             pendingExits = new ListBuffer<>();
 709             scan(tree.selector);
 710             Set<Symbol> constants = new HashSet<>();
 711             Liveness prevAlive = alive;
 712             for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
 713                 alive = Liveness.ALIVE;
 714                 JCCase c = l.head;
 715                 for (JCCaseLabel pat : c.labels) {
 716                     scan(pat);
 717                     handleConstantCaseLabel(constants, pat);
 718                 }
 719                 scanStats(c.stats);
 720                 if (alive == Liveness.ALIVE) {
 721                     if (c.caseKind == JCCase.RULE) {
 722                         log.error(TreeInfo.diagEndPos(c.body),
 723                                   Errors.RuleCompletesNormally);
 724                     } else if (l.tail.isEmpty()) {
 725                         log.error(TreeInfo.diagEndPos(tree),
 726                                   Errors.SwitchExpressionCompletesNormally);
 727                     }
 728                 }
 729             }
 730             if (!tree.hasTotalPattern && !TreeInfo.isErrorEnumSwitch(tree.selector, tree.cases) &&
 731                 !isExhaustive(tree.selector.type, constants)) {
 732                 log.error(tree, Errors.NotExhaustive);
 733             }
 734             alive = prevAlive;
 735             alive = alive.or(resolveYields(tree, prevPendingExits));
 736         }
 737 
 738         private void handleConstantCaseLabel(Set<Symbol> constants, JCCaseLabel pat) {
 739             if (constants != null) {
 740                 if (pat.isExpression()) {
 741                     JCExpression expr = (JCExpression) pat;
 742                     if (expr.hasTag(IDENT) && ((JCIdent) expr).sym.isEnum())
 743                         constants.add(((JCIdent) expr).sym);
 744                 } else if (pat.isPattern()) {
 745                     PatternPrimaryType patternType = TreeInfo.primaryPatternType((JCPattern) pat);
 746 
 747                     if (patternType.unconditional()) {
 748                         constants.add(patternType.type().tsym);
 749                     }
 750                 }
 751             }
 752         }
 753 
 754         private void transitiveCovers(Set<Symbol> covered) {
 755             List<Symbol> todo = List.from(covered);
 756             while (todo.nonEmpty()) {
 757                 Symbol sym = todo.head;
 758                 todo = todo.tail;
 759                 switch (sym.kind) {
 760                     case VAR -> {
 761                         Iterable<Symbol> constants = sym.owner
 762                                                         .members()
 763                                                         .getSymbols(s -> s.isEnum() &&
 764                                                                          s.kind == VAR);
 765                         boolean hasAll = StreamSupport.stream(constants.spliterator(), false)
 766                                                       .allMatch(covered::contains);
 767 
 768                         if (hasAll && covered.add(sym.owner)) {
 769                             todo = todo.prepend(sym.owner);
 770                         }
 771                     }
 772 
 773                     case TYP -> {
 774                         for (Type sup : types.directSupertypes(sym.type)) {
 775                             if (sup.tsym.kind == TYP) {
 776                                 if (isTransitivelyCovered(sup.tsym, covered) &&
 777                                     covered.add(sup.tsym)) {
 778                                     todo = todo.prepend(sup.tsym);
 779                                 }
 780                             }
 781                         }
 782                     }
 783                 }
 784             }
 785         }
 786 
 787         private boolean isTransitivelyCovered(Symbol sealed, Set<Symbol> covered) {
 788             DeferredCompletionFailureHandler.Handler prevHandler =
 789                     dcfh.setHandler(dcfh.speculativeCodeHandler);
 790             try {
 791                 if (covered.stream().anyMatch(c -> sealed.isSubClass(c, types)))
 792                     return true;
 793                 if (sealed.kind == TYP && sealed.isAbstract() && sealed.isSealed()) {
 794                     return ((ClassSymbol) sealed).permitted
 795                                                  .stream()
 796                                                  .allMatch(s -> isTransitivelyCovered(s, covered));
 797                 }
 798                 return false;
 799             } catch (CompletionFailure cf) {
 800                 //safe to ignore, the symbol will be un-completed when the speculative handler is removed.
 801                 return false;
 802             } finally {
 803                 dcfh.setHandler(prevHandler);
 804             }
 805         }
 806 
 807         private boolean isExhaustive(Type seltype, Set<Symbol> covered) {
 808             transitiveCovers(covered);
 809             return switch (seltype.getTag()) {
 810                 case CLASS -> {
 811                     if (seltype.isCompound()) {
 812                         if (seltype.isIntersection()) {
 813                             yield ((Type.IntersectionClassType) seltype).getComponents().stream().anyMatch(t -> isExhaustive(t, covered));
 814                         }
 815                         yield false;
 816                     }
 817                     yield covered.contains(seltype.tsym);
 818                 }
 819                 case TYPEVAR -> isExhaustive(((TypeVar) seltype).getUpperBound(), covered);
 820                 default -> false;
 821             };
 822         }
 823 
 824         public void visitTry(JCTry tree) {
 825             ListBuffer<PendingExit> prevPendingExits = pendingExits;
 826             pendingExits = new ListBuffer<>();
 827             for (JCTree resource : tree.resources) {
 828                 if (resource instanceof JCVariableDecl variableDecl) {
 829                     visitVarDef(variableDecl);
 830                 } else if (resource instanceof JCExpression expression) {
 831                     scan(expression);
 832                 } else {
 833                     throw new AssertionError(tree);  // parser error
 834                 }
 835             }
 836 
 837             scanStat(tree.body);
 838             Liveness aliveEnd = alive;
 839 
 840             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
 841                 alive = Liveness.ALIVE;
 842                 JCVariableDecl param = l.head.param;
 843                 scan(param);
 844                 scanStat(l.head.body);
 845                 aliveEnd = aliveEnd.or(alive);
 846             }
 847             if (tree.finalizer != null) {
 848                 ListBuffer<PendingExit> exits = pendingExits;
 849                 pendingExits = prevPendingExits;
 850                 alive = Liveness.ALIVE;
 851                 scanStat(tree.finalizer);
 852                 tree.finallyCanCompleteNormally = alive != Liveness.DEAD;
 853                 if (alive == Liveness.DEAD) {
 854                     if (lint.isEnabled(Lint.LintCategory.FINALLY)) {
 855                         log.warning(Lint.LintCategory.FINALLY,
 856                                 TreeInfo.diagEndPos(tree.finalizer),
 857                                 Warnings.FinallyCannotComplete);
 858                     }
 859                 } else {
 860                     while (exits.nonEmpty()) {
 861                         pendingExits.append(exits.next());
 862                     }
 863                     alive = aliveEnd;
 864                 }
 865             } else {
 866                 alive = aliveEnd;
 867                 ListBuffer<PendingExit> exits = pendingExits;
 868                 pendingExits = prevPendingExits;
 869                 while (exits.nonEmpty()) pendingExits.append(exits.next());
 870             }
 871         }
 872 
 873         @Override
 874         public void visitIf(JCIf tree) {
 875             scan(tree.cond);
 876             scanStat(tree.thenpart);
 877             if (tree.elsepart != null) {
 878                 Liveness aliveAfterThen = alive;
 879                 alive = Liveness.ALIVE;
 880                 scanStat(tree.elsepart);
 881                 alive = alive.or(aliveAfterThen);
 882             } else {
 883                 alive = Liveness.ALIVE;
 884             }
 885         }
 886 
 887         public void visitBreak(JCBreak tree) {
 888             recordExit(new PendingExit(tree));
 889         }
 890 
 891         @Override
 892         public void visitYield(JCYield tree) {
 893             scan(tree.value);
 894             recordExit(new PendingExit(tree));
 895         }
 896 
 897         public void visitContinue(JCContinue tree) {
 898             recordExit(new PendingExit(tree));
 899         }
 900 
 901         public void visitReturn(JCReturn tree) {
 902             scan(tree.expr);
 903             recordExit(new PendingExit(tree));
 904         }
 905 
 906         public void visitThrow(JCThrow tree) {
 907             scan(tree.expr);
 908             markDead();
 909         }
 910 
 911         public void visitApply(JCMethodInvocation tree) {
 912             scan(tree.meth);
 913             scan(tree.args);
 914         }
 915 
 916         public void visitNewClass(JCNewClass tree) {
 917             scan(tree.encl);
 918             scan(tree.args);
 919             if (tree.def != null) {
 920                 scan(tree.def);
 921             }
 922         }
 923 
 924         @Override
 925         public void visitLambda(JCLambda tree) {
 926             if (tree.type != null &&
 927                     tree.type.isErroneous()) {
 928                 return;
 929             }
 930 
 931             ListBuffer<PendingExit> prevPending = pendingExits;
 932             Liveness prevAlive = alive;
 933             try {
 934                 pendingExits = new ListBuffer<>();
 935                 alive = Liveness.ALIVE;
 936                 scanStat(tree.body);
 937                 tree.canCompleteNormally = alive != Liveness.DEAD;
 938             }
 939             finally {
 940                 pendingExits = prevPending;
 941                 alive = prevAlive;
 942             }
 943         }
 944 
 945         public void visitModuleDef(JCModuleDecl tree) {
 946             // Do nothing for modules
 947         }
 948 
 949     /**************************************************************************
 950      * main method
 951      *************************************************************************/
 952 
 953         /** Perform definite assignment/unassignment analysis on a tree.
 954          */
 955         public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
 956             analyzeTree(env, env.tree, make);
 957         }
 958         public void analyzeTree(Env<AttrContext> env, JCTree tree, TreeMaker make) {
 959             try {
 960                 attrEnv = env;
 961                 Flow.this.make = make;
 962                 pendingExits = new ListBuffer<>();
 963                 alive = Liveness.ALIVE;
 964                 scan(tree);
 965             } finally {
 966                 pendingExits = null;
 967                 Flow.this.make = null;
 968             }
 969         }
 970     }
 971 
 972     /**
 973      * This pass implements the second step of the dataflow analysis, namely
 974      * the exception analysis. This is to ensure that every checked exception that is
 975      * thrown is declared or caught. The analyzer uses some info that has been set by
 976      * the liveliness analyzer.
 977      */
 978     class FlowAnalyzer extends BaseAnalyzer {
 979 
 980         /** A flag that indicates whether the last statement could
 981          *  complete normally.
 982          */
 983         HashMap<Symbol, List<Type>> preciseRethrowTypes;
 984 
 985         /** The current class being defined.
 986          */
 987         JCClassDecl classDef;
 988 
 989         /** The list of possibly thrown declarable exceptions.
 990          */
 991         List<Type> thrown;
 992 
 993         /** The list of exceptions that are either caught or declared to be
 994          *  thrown.
 995          */
 996         List<Type> caught;
 997 
 998         class ThrownPendingExit extends BaseAnalyzer.PendingExit {
 999 
1000             Type thrown;
1001 
1002             ThrownPendingExit(JCTree tree, Type thrown) {
1003                 super(tree);
1004                 this.thrown = thrown;
1005             }
1006         }
1007 
1008         @Override
1009         void markDead() {
1010             //do nothing
1011         }
1012 
1013         /*-------------------- Exceptions ----------------------*/
1014 
1015         /** Complain that pending exceptions are not caught.
1016          */
1017         void errorUncaught() {
1018             for (PendingExit exit = pendingExits.next();
1019                  exit != null;
1020                  exit = pendingExits.next()) {
1021                 if (exit instanceof ThrownPendingExit thrownExit) {
1022                     if (classDef != null &&
1023                         classDef.pos == exit.tree.pos) {
1024                         log.error(exit.tree.pos(),
1025                                   Errors.UnreportedExceptionDefaultConstructor(thrownExit.thrown));
1026                     } else if (exit.tree.hasTag(VARDEF) &&
1027                             ((JCVariableDecl)exit.tree).sym.isResourceVariable()) {
1028                         log.error(exit.tree.pos(),
1029                                   Errors.UnreportedExceptionImplicitClose(thrownExit.thrown,
1030                                                                           ((JCVariableDecl)exit.tree).sym.name));
1031                     } else {
1032                         log.error(exit.tree.pos(),
1033                                   Errors.UnreportedExceptionNeedToCatchOrThrow(thrownExit.thrown));
1034                     }
1035                 } else {
1036                     Assert.check(log.hasErrorOn(exit.tree.pos()));
1037                 }
1038             }
1039         }
1040 
1041         /** Record that exception is potentially thrown and check that it
1042          *  is caught.
1043          */
1044         void markThrown(JCTree tree, Type exc) {
1045             if (!chk.isUnchecked(tree.pos(), exc)) {
1046                 if (!chk.isHandled(exc, caught)) {
1047                     pendingExits.append(new ThrownPendingExit(tree, exc));
1048                 }
1049                 thrown = chk.incl(exc, thrown);
1050             }
1051         }
1052 
1053     /*************************************************************************
1054      * Visitor methods for statements and definitions
1055      *************************************************************************/
1056 
1057         /* ------------ Visitor methods for various sorts of trees -------------*/
1058 
1059         public void visitClassDef(JCClassDecl tree) {
1060             if (tree.sym == null) return;
1061 
1062             JCClassDecl classDefPrev = classDef;
1063             List<Type> thrownPrev = thrown;
1064             List<Type> caughtPrev = caught;
1065             ListBuffer<PendingExit> pendingExitsPrev = pendingExits;
1066             Lint lintPrev = lint;
1067             boolean anonymousClass = tree.name == names.empty;
1068             pendingExits = new ListBuffer<>();
1069             if (!anonymousClass) {
1070                 caught = List.nil();
1071             }
1072             classDef = tree;
1073             thrown = List.nil();
1074             lint = lint.augment(tree.sym);
1075 
1076             try {
1077                 // process all the static initializers
1078                 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1079                     if (!l.head.hasTag(METHODDEF) &&
1080                         (TreeInfo.flags(l.head) & STATIC) != 0) {
1081                         scan(l.head);
1082                         errorUncaught();
1083                     }
1084                 }
1085 
1086                 // add intersection of all thrown clauses of initial constructors
1087                 // to set of caught exceptions, unless class is anonymous.
1088                 if (!anonymousClass) {
1089                     boolean firstConstructor = true;
1090                     for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1091                         if (TreeInfo.isInitialConstructor(l.head)) {
1092                             List<Type> mthrown =
1093                                 ((JCMethodDecl) l.head).sym.type.getThrownTypes();
1094                             if (firstConstructor) {
1095                                 caught = mthrown;
1096                                 firstConstructor = false;
1097                             } else {
1098                                 caught = chk.intersect(mthrown, caught);
1099                             }
1100                         }
1101                     }
1102                 }
1103 
1104                 // process all the instance initializers
1105                 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1106                     if (!l.head.hasTag(METHODDEF) &&
1107                         (TreeInfo.flags(l.head) & STATIC) == 0) {
1108                         scan(l.head);
1109                         errorUncaught();
1110                     }
1111                 }
1112 
1113                 // in an anonymous class, add the set of thrown exceptions to
1114                 // the throws clause of the synthetic constructor and propagate
1115                 // outwards.
1116                 // Changing the throws clause on the fly is okay here because
1117                 // the anonymous constructor can't be invoked anywhere else,
1118                 // and its type hasn't been cached.
1119                 if (anonymousClass) {
1120                     for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1121                         if (TreeInfo.isConstructor(l.head)) {
1122                             JCMethodDecl mdef = (JCMethodDecl)l.head;
1123                             scan(mdef);
1124                             mdef.thrown = make.Types(thrown);
1125                             mdef.sym.type = types.createMethodTypeWithThrown(mdef.sym.type, thrown);
1126                         }
1127                     }
1128                     thrownPrev = chk.union(thrown, thrownPrev);
1129                 }
1130 
1131                 // process all the methods
1132                 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
1133                     if (anonymousClass && TreeInfo.isConstructor(l.head))
1134                         continue; // there can never be an uncaught exception.
1135                     if (l.head.hasTag(METHODDEF)) {
1136                         scan(l.head);
1137                         errorUncaught();
1138                     }
1139                 }
1140 
1141                 thrown = thrownPrev;
1142             } finally {
1143                 pendingExits = pendingExitsPrev;
1144                 caught = caughtPrev;
1145                 classDef = classDefPrev;
1146                 lint = lintPrev;
1147             }
1148         }
1149 
1150         public void visitMethodDef(JCMethodDecl tree) {
1151             if (tree.body == null) return;
1152 
1153             List<Type> caughtPrev = caught;
1154             List<Type> mthrown = tree.sym.type.getThrownTypes();
1155             Lint lintPrev = lint;
1156 
1157             lint = lint.augment(tree.sym);
1158 
1159             Assert.check(pendingExits.isEmpty());
1160 
1161             try {
1162                 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1163                     JCVariableDecl def = l.head;
1164                     scan(def);
1165                 }
1166                 if (TreeInfo.isInitialConstructor(tree))
1167                     caught = chk.union(caught, mthrown);
1168                 else if ((tree.sym.flags() & (BLOCK | STATIC)) != BLOCK)
1169                     caught = mthrown;
1170                 // else we are in an instance initializer block;
1171                 // leave caught unchanged.
1172 
1173                 scan(tree.body);
1174 
1175                 List<PendingExit> exits = pendingExits.toList();
1176                 pendingExits = new ListBuffer<>();
1177                 while (exits.nonEmpty()) {
1178                     PendingExit exit = exits.head;
1179                     exits = exits.tail;
1180                     if (!(exit instanceof ThrownPendingExit)) {
1181                         Assert.check(exit.tree.hasTag(RETURN) ||
1182                                          log.hasErrorOn(exit.tree.pos()));
1183                     } else {
1184                         // uncaught throws will be reported later
1185                         pendingExits.append(exit);
1186                     }
1187                 }
1188             } finally {
1189                 caught = caughtPrev;
1190                 lint = lintPrev;
1191             }
1192         }
1193 
1194         public void visitVarDef(JCVariableDecl tree) {
1195             if (tree.init != null) {
1196                 Lint lintPrev = lint;
1197                 lint = lint.augment(tree.sym);
1198                 try{
1199                     scan(tree.init);
1200                 } finally {
1201                     lint = lintPrev;
1202                 }
1203             }
1204         }
1205 
1206         public void visitBlock(JCBlock tree) {
1207             scan(tree.stats);
1208         }
1209 
1210         public void visitDoLoop(JCDoWhileLoop tree) {
1211             ListBuffer<PendingExit> prevPendingExits = pendingExits;
1212             pendingExits = new ListBuffer<>();
1213             scan(tree.body);
1214             resolveContinues(tree);
1215             scan(tree.cond);
1216             resolveBreaks(tree, prevPendingExits);
1217         }
1218 
1219         public void visitWhileLoop(JCWhileLoop tree) {
1220             ListBuffer<PendingExit> prevPendingExits = pendingExits;
1221             pendingExits = new ListBuffer<>();
1222             scan(tree.cond);
1223             scan(tree.body);
1224             resolveContinues(tree);
1225             resolveBreaks(tree, prevPendingExits);
1226         }
1227 
1228         public void visitForLoop(JCForLoop tree) {
1229             ListBuffer<PendingExit> prevPendingExits = pendingExits;
1230             scan(tree.init);
1231             pendingExits = new ListBuffer<>();
1232             if (tree.cond != null) {
1233                 scan(tree.cond);
1234             }
1235             scan(tree.body);
1236             resolveContinues(tree);
1237             scan(tree.step);
1238             resolveBreaks(tree, prevPendingExits);
1239         }
1240 
1241         public void visitForeachLoop(JCEnhancedForLoop tree) {
1242             visitVarDef(tree.var);
1243             ListBuffer<PendingExit> prevPendingExits = pendingExits;
1244             scan(tree.expr);
1245             pendingExits = new ListBuffer<>();
1246             scan(tree.body);
1247             resolveContinues(tree);
1248             resolveBreaks(tree, prevPendingExits);
1249         }
1250 
1251         public void visitLabelled(JCLabeledStatement tree) {
1252             ListBuffer<PendingExit> prevPendingExits = pendingExits;
1253             pendingExits = new ListBuffer<>();
1254             scan(tree.body);
1255             resolveBreaks(tree, prevPendingExits);
1256         }
1257 
1258         public void visitSwitch(JCSwitch tree) {
1259             handleSwitch(tree, tree.selector, tree.cases);
1260         }
1261 
1262         @Override
1263         public void visitSwitchExpression(JCSwitchExpression tree) {
1264             handleSwitch(tree, tree.selector, tree.cases);
1265         }
1266 
1267         private void handleSwitch(JCTree tree, JCExpression selector, List<JCCase> cases) {
1268             ListBuffer<PendingExit> prevPendingExits = pendingExits;
1269             pendingExits = new ListBuffer<>();
1270             scan(selector);
1271             for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
1272                 JCCase c = l.head;
1273                 scan(c.labels);
1274                 scan(c.stats);
1275             }
1276             if (tree.hasTag(SWITCH_EXPRESSION)) {
1277                 resolveYields(tree, prevPendingExits);
1278             } else {
1279                 resolveBreaks(tree, prevPendingExits);
1280             }
1281         }
1282 
1283         public void visitTry(JCTry tree) {
1284             List<Type> caughtPrev = caught;
1285             List<Type> thrownPrev = thrown;
1286             thrown = List.nil();
1287             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1288                 List<JCExpression> subClauses = TreeInfo.isMultiCatch(l.head) ?
1289                         ((JCTypeUnion)l.head.param.vartype).alternatives :
1290                         List.of(l.head.param.vartype);
1291                 for (JCExpression ct : subClauses) {
1292                     caught = chk.incl(ct.type, caught);
1293                 }
1294             }
1295 
1296             ListBuffer<PendingExit> prevPendingExits = pendingExits;
1297             pendingExits = new ListBuffer<>();
1298             for (JCTree resource : tree.resources) {
1299                 if (resource instanceof JCVariableDecl variableDecl) {
1300                     visitVarDef(variableDecl);
1301                 } else if (resource instanceof JCExpression expression) {
1302                     scan(expression);
1303                 } else {
1304                     throw new AssertionError(tree);  // parser error
1305                 }
1306             }
1307             for (JCTree resource : tree.resources) {
1308                 List<Type> closeableSupertypes = resource.type.isCompound() ?
1309                     types.interfaces(resource.type).prepend(types.supertype(resource.type)) :
1310                     List.of(resource.type);
1311                 for (Type sup : closeableSupertypes) {
1312                     if (types.asSuper(sup, syms.autoCloseableType.tsym) != null) {
1313                         Symbol closeMethod = rs.resolveQualifiedMethod(tree,
1314                                 attrEnv,
1315                                 types.skipTypeVars(sup, false),
1316                                 names.close,
1317                                 List.nil(),
1318                                 List.nil());
1319                         Type mt = types.memberType(resource.type, closeMethod);
1320                         if (closeMethod.kind == MTH) {
1321                             for (Type t : mt.getThrownTypes()) {
1322                                 markThrown(resource, t);
1323                             }
1324                         }
1325                     }
1326                 }
1327             }
1328             scan(tree.body);
1329             List<Type> thrownInTry = chk.union(thrown, List.of(syms.runtimeExceptionType, syms.errorType));
1330             thrown = thrownPrev;
1331             caught = caughtPrev;
1332 
1333             List<Type> caughtInTry = List.nil();
1334             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
1335                 JCVariableDecl param = l.head.param;
1336                 List<JCExpression> subClauses = TreeInfo.isMultiCatch(l.head) ?
1337                         ((JCTypeUnion)l.head.param.vartype).alternatives :
1338                         List.of(l.head.param.vartype);
1339                 List<Type> ctypes = List.nil();
1340                 List<Type> rethrownTypes = chk.diff(thrownInTry, caughtInTry);
1341                 for (JCExpression ct : subClauses) {
1342                     Type exc = ct.type;
1343                     if (exc != syms.unknownType) {
1344                         ctypes = ctypes.append(exc);
1345                         if (types.isSameType(exc, syms.objectType))
1346                             continue;
1347                         var pos = subClauses.size() > 1 ? ct.pos() : l.head.pos();
1348                         checkCaughtType(pos, exc, thrownInTry, caughtInTry);
1349                         caughtInTry = chk.incl(exc, caughtInTry);
1350                     }
1351                 }
1352                 scan(param);
1353                 preciseRethrowTypes.put(param.sym, chk.intersect(ctypes, rethrownTypes));
1354                 scan(l.head.body);
1355                 preciseRethrowTypes.remove(param.sym);
1356             }
1357             if (tree.finalizer != null) {
1358                 List<Type> savedThrown = thrown;
1359                 thrown = List.nil();
1360                 ListBuffer<PendingExit> exits = pendingExits;
1361                 pendingExits = prevPendingExits;
1362                 scan(tree.finalizer);
1363                 if (!tree.finallyCanCompleteNormally) {
1364                     // discard exits and exceptions from try and finally
1365                     thrown = chk.union(thrown, thrownPrev);
1366                 } else {
1367                     thrown = chk.union(thrown, chk.diff(thrownInTry, caughtInTry));
1368                     thrown = chk.union(thrown, savedThrown);
1369                     // FIX: this doesn't preserve source order of exits in catch
1370                     // versus finally!
1371                     while (exits.nonEmpty()) {
1372                         pendingExits.append(exits.next());
1373                     }
1374                 }
1375             } else {
1376                 thrown = chk.union(thrown, chk.diff(thrownInTry, caughtInTry));
1377                 ListBuffer<PendingExit> exits = pendingExits;
1378                 pendingExits = prevPendingExits;
1379                 while (exits.nonEmpty()) pendingExits.append(exits.next());
1380             }
1381         }
1382 
1383         @Override
1384         public void visitIf(JCIf tree) {
1385             scan(tree.cond);
1386             scan(tree.thenpart);
1387             if (tree.elsepart != null) {
1388                 scan(tree.elsepart);
1389             }
1390         }
1391 
1392         void checkCaughtType(DiagnosticPosition pos, Type exc, List<Type> thrownInTry, List<Type> caughtInTry) {
1393             if (chk.subset(exc, caughtInTry)) {
1394                 log.error(pos, Errors.ExceptAlreadyCaught(exc));
1395             } else if (!chk.isUnchecked(pos, exc) &&
1396                     !isExceptionOrThrowable(exc) &&
1397                     !chk.intersects(exc, thrownInTry)) {
1398                 log.error(pos, Errors.ExceptNeverThrownInTry(exc));
1399             } else {
1400                 List<Type> catchableThrownTypes = chk.intersect(List.of(exc), thrownInTry);
1401                 // 'catchableThrownTypes' cannot possibly be empty - if 'exc' was an
1402                 // unchecked exception, the result list would not be empty, as the augmented
1403                 // thrown set includes { RuntimeException, Error }; if 'exc' was a checked
1404                 // exception, that would have been covered in the branch above
1405                 if (chk.diff(catchableThrownTypes, caughtInTry).isEmpty() &&
1406                         !isExceptionOrThrowable(exc)) {
1407                     Warning key = catchableThrownTypes.length() == 1 ?
1408                             Warnings.UnreachableCatch(catchableThrownTypes) :
1409                             Warnings.UnreachableCatch1(catchableThrownTypes);
1410                     log.warning(pos, key);
1411                 }
1412             }
1413         }
1414         //where
1415             private boolean isExceptionOrThrowable(Type exc) {
1416                 return exc.tsym == syms.throwableType.tsym ||
1417                     exc.tsym == syms.exceptionType.tsym;
1418             }
1419 
1420         public void visitBreak(JCBreak tree) {
1421             recordExit(new PendingExit(tree));
1422         }
1423 
1424         public void visitYield(JCYield tree) {
1425             scan(tree.value);
1426             recordExit(new PendingExit(tree));
1427         }
1428 
1429         public void visitContinue(JCContinue tree) {
1430             recordExit(new PendingExit(tree));
1431         }
1432 
1433         public void visitReturn(JCReturn tree) {
1434             scan(tree.expr);
1435             recordExit(new PendingExit(tree));
1436         }
1437 
1438         public void visitThrow(JCThrow tree) {
1439             scan(tree.expr);
1440             Symbol sym = TreeInfo.symbol(tree.expr);
1441             if (sym != null &&
1442                 sym.kind == VAR &&
1443                 (sym.flags() & (FINAL | EFFECTIVELY_FINAL)) != 0 &&
1444                 preciseRethrowTypes.get(sym) != null) {
1445                 for (Type t : preciseRethrowTypes.get(sym)) {
1446                     markThrown(tree, t);
1447                 }
1448             }
1449             else {
1450                 markThrown(tree, tree.expr.type);
1451             }
1452             markDead();
1453         }
1454 
1455         public void visitApply(JCMethodInvocation tree) {
1456             scan(tree.meth);
1457             scan(tree.args);
1458             for (List<Type> l = tree.meth.type.getThrownTypes(); l.nonEmpty(); l = l.tail)
1459                 markThrown(tree, l.head);
1460         }
1461 
1462         public void visitNewClass(JCNewClass tree) {
1463             scan(tree.encl);
1464             scan(tree.args);
1465            // scan(tree.def);
1466             for (List<Type> l = tree.constructorType.getThrownTypes();
1467                  l.nonEmpty();
1468                  l = l.tail) {
1469                 markThrown(tree, l.head);
1470             }
1471             List<Type> caughtPrev = caught;
1472             try {
1473                 // If the new class expression defines an anonymous class,
1474                 // analysis of the anonymous constructor may encounter thrown
1475                 // types which are unsubstituted type variables.
1476                 // However, since the constructor's actual thrown types have
1477                 // already been marked as thrown, it is safe to simply include
1478                 // each of the constructor's formal thrown types in the set of
1479                 // 'caught/declared to be thrown' types, for the duration of
1480                 // the class def analysis.
1481                 if (tree.def != null)
1482                     for (List<Type> l = tree.constructor.type.getThrownTypes();
1483                          l.nonEmpty();
1484                          l = l.tail) {
1485                         caught = chk.incl(l.head, caught);
1486                     }
1487                 scan(tree.def);
1488             }
1489             finally {
1490                 caught = caughtPrev;
1491             }
1492         }
1493 
1494         @Override
1495         public void visitLambda(JCLambda tree) {
1496             if (tree.type != null &&
1497                     tree.type.isErroneous()) {
1498                 return;
1499             }
1500             List<Type> prevCaught = caught;
1501             List<Type> prevThrown = thrown;
1502             ListBuffer<PendingExit> prevPending = pendingExits;
1503             try {
1504                 pendingExits = new ListBuffer<>();
1505                 caught = tree.getDescriptorType(types).getThrownTypes();
1506                 thrown = List.nil();
1507                 scan(tree.body);
1508                 List<PendingExit> exits = pendingExits.toList();
1509                 pendingExits = new ListBuffer<>();
1510                 while (exits.nonEmpty()) {
1511                     PendingExit exit = exits.head;
1512                     exits = exits.tail;
1513                     if (!(exit instanceof ThrownPendingExit)) {
1514                         Assert.check(exit.tree.hasTag(RETURN) ||
1515                                         log.hasErrorOn(exit.tree.pos()));
1516                     } else {
1517                         // uncaught throws will be reported later
1518                         pendingExits.append(exit);
1519                     }
1520                 }
1521 
1522                 errorUncaught();
1523             } finally {
1524                 pendingExits = prevPending;
1525                 caught = prevCaught;
1526                 thrown = prevThrown;
1527             }
1528         }
1529 
1530         public void visitModuleDef(JCModuleDecl tree) {
1531             // Do nothing for modules
1532         }
1533 
1534     /**************************************************************************
1535      * main method
1536      *************************************************************************/
1537 
1538         /** Perform definite assignment/unassignment analysis on a tree.
1539          */
1540         public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
1541             analyzeTree(env, env.tree, make);
1542         }
1543         public void analyzeTree(Env<AttrContext> env, JCTree tree, TreeMaker make) {
1544             try {
1545                 attrEnv = env;
1546                 Flow.this.make = make;
1547                 pendingExits = new ListBuffer<>();
1548                 preciseRethrowTypes = new HashMap<>();
1549                 this.thrown = this.caught = null;
1550                 this.classDef = null;
1551                 scan(tree);
1552             } finally {
1553                 pendingExits = null;
1554                 Flow.this.make = null;
1555                 this.thrown = this.caught = null;
1556                 this.classDef = null;
1557             }
1558         }
1559     }
1560 
1561     /**
1562      * Specialized pass that performs reachability analysis on a lambda
1563      */
1564     class LambdaAliveAnalyzer extends AliveAnalyzer {
1565 
1566         boolean inLambda;
1567 
1568         @Override
1569         public void visitReturn(JCReturn tree) {
1570             //ignore lambda return expression (which might not even be attributed)
1571             recordExit(new PendingExit(tree));
1572         }
1573 
1574         @Override
1575         public void visitLambda(JCLambda tree) {
1576             if (inLambda || tree.getBodyKind() == BodyKind.EXPRESSION) {
1577                 return;
1578             }
1579             inLambda = true;
1580             try {
1581                 super.visitLambda(tree);
1582             } finally {
1583                 inLambda = false;
1584             }
1585         }
1586 
1587         @Override
1588         public void visitClassDef(JCClassDecl tree) {
1589             //skip
1590         }
1591     }
1592 
1593     /**
1594      * Determine if alive after the given tree.
1595      */
1596     class SnippetAliveAnalyzer extends AliveAnalyzer {
1597         @Override
1598         public void visitClassDef(JCClassDecl tree) {
1599             //skip
1600         }
1601         @Override
1602         public void visitLambda(JCLambda tree) {
1603             //skip
1604         }
1605         public boolean isAlive() {
1606             return super.alive != Liveness.DEAD;
1607         }
1608     }
1609 
1610     class SnippetBreakAnalyzer extends AliveAnalyzer {
1611         private final Set<JCTree> seenTrees = new HashSet<>();
1612         private boolean breaksOut;
1613 
1614         public SnippetBreakAnalyzer() {
1615         }
1616 
1617         @Override
1618         public void visitLabelled(JCTree.JCLabeledStatement tree) {
1619             seenTrees.add(tree);
1620             super.visitLabelled(tree);
1621         }
1622 
1623         @Override
1624         public void visitWhileLoop(JCTree.JCWhileLoop tree) {
1625             seenTrees.add(tree);
1626             super.visitWhileLoop(tree);
1627         }
1628 
1629         @Override
1630         public void visitForLoop(JCTree.JCForLoop tree) {
1631             seenTrees.add(tree);
1632             super.visitForLoop(tree);
1633         }
1634 
1635         @Override
1636         public void visitForeachLoop(JCTree.JCEnhancedForLoop tree) {
1637             seenTrees.add(tree);
1638             super.visitForeachLoop(tree);
1639         }
1640 
1641         @Override
1642         public void visitDoLoop(JCTree.JCDoWhileLoop tree) {
1643             seenTrees.add(tree);
1644             super.visitDoLoop(tree);
1645         }
1646 
1647         @Override
1648         public void visitBreak(JCBreak tree) {
1649             breaksOut |= (super.alive == Liveness.ALIVE &&
1650                           !seenTrees.contains(tree.target));
1651             super.visitBreak(tree);
1652         }
1653 
1654         public boolean breaksOut() {
1655             return breaksOut;
1656         }
1657     }
1658 
1659     /**
1660      * Specialized pass that performs DA/DU on a lambda
1661      */
1662     class LambdaAssignAnalyzer extends AssignAnalyzer {
1663         WriteableScope enclosedSymbols;
1664         boolean inLambda;
1665 
1666         LambdaAssignAnalyzer(Env<AttrContext> env) {
1667             enclosedSymbols = WriteableScope.create(env.enclClass.sym);
1668         }
1669 
1670         @Override
1671         public void visitLambda(JCLambda tree) {
1672             if (inLambda) {
1673                 return;
1674             }
1675             inLambda = true;
1676             try {
1677                 super.visitLambda(tree);
1678             } finally {
1679                 inLambda = false;
1680             }
1681         }
1682 
1683         @Override
1684         public void visitVarDef(JCVariableDecl tree) {
1685             enclosedSymbols.enter(tree.sym);
1686             super.visitVarDef(tree);
1687         }
1688         @Override
1689         protected boolean trackable(VarSymbol sym) {
1690             return enclosedSymbols.includes(sym) &&
1691                    sym.owner.kind == MTH;
1692         }
1693 
1694         @Override
1695         public void visitClassDef(JCClassDecl tree) {
1696             //skip
1697         }
1698     }
1699 
1700     /**
1701      * Specialized pass that performs inference of thrown types for lambdas.
1702      */
1703     class LambdaFlowAnalyzer extends FlowAnalyzer {
1704         List<Type> inferredThrownTypes;
1705         boolean inLambda;
1706         @Override
1707         public void visitLambda(JCLambda tree) {
1708             if ((tree.type != null &&
1709                     tree.type.isErroneous()) || inLambda) {
1710                 return;
1711             }
1712             List<Type> prevCaught = caught;
1713             List<Type> prevThrown = thrown;
1714             ListBuffer<PendingExit> prevPending = pendingExits;
1715             inLambda = true;
1716             try {
1717                 pendingExits = new ListBuffer<>();
1718                 caught = List.of(syms.throwableType);
1719                 thrown = List.nil();
1720                 scan(tree.body);
1721                 inferredThrownTypes = thrown;
1722             } finally {
1723                 pendingExits = prevPending;
1724                 caught = prevCaught;
1725                 thrown = prevThrown;
1726                 inLambda = false;
1727             }
1728         }
1729         @Override
1730         public void visitClassDef(JCClassDecl tree) {
1731             //skip
1732         }
1733     }
1734 
1735     /**
1736      * This pass implements (i) definite assignment analysis, which ensures that
1737      * each variable is assigned when used and (ii) definite unassignment analysis,
1738      * which ensures that no final variable is assigned more than once. This visitor
1739      * depends on the results of the liveliness analyzer. This pass is also used to mark
1740      * effectively-final local variables/parameters.
1741      */
1742 
1743     public class AssignAnalyzer extends BaseAnalyzer {
1744 
1745         /** The set of definitely assigned variables.
1746          */
1747         final Bits inits;
1748 
1749         /** The set of definitely unassigned variables.
1750          */
1751         final Bits uninits;
1752 
1753         /** The set of variables that are definitely unassigned everywhere
1754          *  in current try block. This variable is maintained lazily; it is
1755          *  updated only when something gets removed from uninits,
1756          *  typically by being assigned in reachable code.  To obtain the
1757          *  correct set of variables which are definitely unassigned
1758          *  anywhere in current try block, intersect uninitsTry and
1759          *  uninits.
1760          */
1761         final Bits uninitsTry;
1762 
1763         /** When analyzing a condition, inits and uninits are null.
1764          *  Instead we have:
1765          */
1766         final Bits initsWhenTrue;
1767         final Bits initsWhenFalse;
1768         final Bits uninitsWhenTrue;
1769         final Bits uninitsWhenFalse;
1770 
1771         /** A mapping from addresses to variable symbols.
1772          */
1773         protected JCVariableDecl[] vardecls;
1774 
1775         /** The current class being defined.
1776          */
1777         JCClassDecl classDef;
1778 
1779         /** The first variable sequence number in this class definition.
1780          */
1781         int firstadr;
1782 
1783         /** The next available variable sequence number.
1784          */
1785         protected int nextadr;
1786 
1787         /** The first variable sequence number in a block that can return.
1788          */
1789         protected int returnadr;
1790 
1791         /** The list of unreferenced automatic resources.
1792          */
1793         WriteableScope unrefdResources;
1794 
1795         /** Modified when processing a loop body the second time for DU analysis. */
1796         FlowKind flowKind = FlowKind.NORMAL;
1797 
1798         /** The starting position of the analyzed tree */
1799         int startPos;
1800 
1801         public class AssignPendingExit extends BaseAnalyzer.PendingExit {
1802 
1803             final Bits inits;
1804             final Bits uninits;
1805             final Bits exit_inits = new Bits(true);
1806             final Bits exit_uninits = new Bits(true);
1807 
1808             public AssignPendingExit(JCTree tree, final Bits inits, final Bits uninits) {
1809                 super(tree);
1810                 this.inits = inits;
1811                 this.uninits = uninits;
1812                 this.exit_inits.assign(inits);
1813                 this.exit_uninits.assign(uninits);
1814             }
1815 
1816             @Override
1817             public void resolveJump() {
1818                 inits.andSet(exit_inits);
1819                 uninits.andSet(exit_uninits);
1820             }
1821         }
1822 
1823         public AssignAnalyzer() {
1824             this.inits = new Bits();
1825             uninits = new Bits();
1826             uninitsTry = new Bits();
1827             initsWhenTrue = new Bits(true);
1828             initsWhenFalse = new Bits(true);
1829             uninitsWhenTrue = new Bits(true);
1830             uninitsWhenFalse = new Bits(true);
1831         }
1832 
1833         private boolean isInitialConstructor = false;
1834 
1835         @Override
1836         protected void markDead() {
1837             if (!isInitialConstructor) {
1838                 inits.inclRange(returnadr, nextadr);
1839             } else {
1840                 for (int address = returnadr; address < nextadr; address++) {
1841                     if (!(isFinalUninitializedStaticField(vardecls[address].sym))) {
1842                         inits.incl(address);
1843                     }
1844                 }
1845             }
1846             uninits.inclRange(returnadr, nextadr);
1847         }
1848 
1849         /*-------------- Processing variables ----------------------*/
1850 
1851         /** Do we need to track init/uninit state of this symbol?
1852          *  I.e. is symbol either a local or a blank final variable?
1853          */
1854         protected boolean trackable(VarSymbol sym) {
1855             return
1856                 sym.pos >= startPos &&
1857                 ((sym.owner.kind == MTH || sym.owner.kind == VAR ||
1858                 isFinalUninitializedField(sym)));
1859         }
1860 
1861         boolean isFinalUninitializedField(VarSymbol sym) {
1862             return sym.owner.kind == TYP &&
1863                    ((sym.flags() & (FINAL | HASINIT | PARAMETER)) == FINAL &&
1864                    classDef.sym.isEnclosedBy((ClassSymbol)sym.owner));
1865         }
1866 
1867         boolean isFinalUninitializedStaticField(VarSymbol sym) {
1868             return isFinalUninitializedField(sym) && sym.isStatic();
1869         }
1870 
1871         /** Initialize new trackable variable by setting its address field
1872          *  to the next available sequence number and entering it under that
1873          *  index into the vars array.
1874          */
1875         void newVar(JCVariableDecl varDecl) {
1876             VarSymbol sym = varDecl.sym;
1877             vardecls = ArrayUtils.ensureCapacity(vardecls, nextadr);
1878             if ((sym.flags() & FINAL) == 0) {
1879                 sym.flags_field |= EFFECTIVELY_FINAL;
1880             }
1881             sym.adr = nextadr;
1882             vardecls[nextadr] = varDecl;
1883             inits.excl(nextadr);
1884             uninits.incl(nextadr);
1885             nextadr++;
1886         }
1887 
1888         /** Record an initialization of a trackable variable.
1889          */
1890         void letInit(DiagnosticPosition pos, VarSymbol sym) {
1891             if (sym.adr >= firstadr && trackable(sym)) {
1892                 if ((sym.flags() & EFFECTIVELY_FINAL) != 0) {
1893                     if (!uninits.isMember(sym.adr)) {
1894                         //assignment targeting an effectively final variable
1895                         //makes the variable lose its status of effectively final
1896                         //if the variable is _not_ definitively unassigned
1897                         sym.flags_field &= ~EFFECTIVELY_FINAL;
1898                     } else {
1899                         uninit(sym);
1900                     }
1901                 }
1902                 else if ((sym.flags() & FINAL) != 0) {
1903                     if ((sym.flags() & PARAMETER) != 0) {
1904                         if ((sym.flags() & UNION) != 0) { //multi-catch parameter
1905                             log.error(pos, Errors.MulticatchParameterMayNotBeAssigned(sym));
1906                         }
1907                         else {
1908                             log.error(pos,
1909                                       Errors.FinalParameterMayNotBeAssigned(sym));
1910                         }
1911                     } else if (!uninits.isMember(sym.adr)) {
1912                         log.error(pos, diags.errorKey(flowKind.errKey, sym));
1913                     } else {
1914                         uninit(sym);
1915                     }
1916                 }
1917                 inits.incl(sym.adr);
1918             } else if ((sym.flags() & FINAL) != 0) {
1919                 log.error(pos, Errors.VarMightAlreadyBeAssigned(sym));
1920             }
1921         }
1922         //where
1923             void uninit(VarSymbol sym) {
1924                 if (!inits.isMember(sym.adr)) {
1925                     // reachable assignment
1926                     uninits.excl(sym.adr);
1927                     uninitsTry.excl(sym.adr);
1928                 } else {
1929                     //log.rawWarning(pos, "unreachable assignment");//DEBUG
1930                     uninits.excl(sym.adr);
1931                 }
1932             }
1933 
1934         /** If tree is either a simple name or of the form this.name or
1935          *  C.this.name, and tree represents a trackable variable,
1936          *  record an initialization of the variable.
1937          */
1938         void letInit(JCTree tree) {
1939             tree = TreeInfo.skipParens(tree);
1940             if (tree.hasTag(IDENT) || tree.hasTag(SELECT)) {
1941                 Symbol sym = TreeInfo.symbol(tree);
1942                 if (sym.kind == VAR) {
1943                     letInit(tree.pos(), (VarSymbol)sym);
1944                 }
1945             }
1946         }
1947 
1948         /** Check that trackable variable is initialized.
1949          */
1950         void checkInit(DiagnosticPosition pos, VarSymbol sym) {
1951             checkInit(pos, sym, Errors.VarMightNotHaveBeenInitialized(sym));
1952         }
1953 
1954         void checkInit(DiagnosticPosition pos, VarSymbol sym, Error errkey) {
1955             if ((sym.adr >= firstadr || sym.owner.kind != TYP) &&
1956                 trackable(sym) &&
1957                 !inits.isMember(sym.adr) &&
1958                 (sym.flags_field & CLASH) == 0) {
1959                     log.error(pos, errkey);
1960                 inits.incl(sym.adr);
1961             }
1962         }
1963 
1964         /** Utility method to reset several Bits instances.
1965          */
1966         private void resetBits(Bits... bits) {
1967             for (Bits b : bits) {
1968                 b.reset();
1969             }
1970         }
1971 
1972         /** Split (duplicate) inits/uninits into WhenTrue/WhenFalse sets
1973          */
1974         void split(boolean setToNull) {
1975             initsWhenFalse.assign(inits);
1976             uninitsWhenFalse.assign(uninits);
1977             initsWhenTrue.assign(inits);
1978             uninitsWhenTrue.assign(uninits);
1979             if (setToNull) {
1980                 resetBits(inits, uninits);
1981             }
1982         }
1983 
1984         /** Merge (intersect) inits/uninits from WhenTrue/WhenFalse sets.
1985          */
1986         protected void merge() {
1987             inits.assign(initsWhenFalse.andSet(initsWhenTrue));
1988             uninits.assign(uninitsWhenFalse.andSet(uninitsWhenTrue));
1989         }
1990 
1991     /* ************************************************************************
1992      * Visitor methods for statements and definitions
1993      *************************************************************************/
1994 
1995         /** Analyze an expression. Make sure to set (un)inits rather than
1996          *  (un)initsWhenTrue(WhenFalse) on exit.
1997          */
1998         void scanExpr(JCTree tree) {
1999             if (tree != null) {
2000                 scan(tree);
2001                 if (inits.isReset()) {
2002                     merge();
2003                 }
2004             }
2005         }
2006 
2007         /** Analyze a list of expressions.
2008          */
2009         void scanExprs(List<? extends JCExpression> trees) {
2010             if (trees != null)
2011                 for (List<? extends JCExpression> l = trees; l.nonEmpty(); l = l.tail)
2012                     scanExpr(l.head);
2013         }
2014 
2015         /** Analyze a condition. Make sure to set (un)initsWhenTrue(WhenFalse)
2016          *  rather than (un)inits on exit.
2017          */
2018         void scanCond(JCTree tree) {
2019             if (tree.type.isFalse()) {
2020                 if (inits.isReset()) merge();
2021                 initsWhenTrue.assign(inits);
2022                 initsWhenTrue.inclRange(firstadr, nextadr);
2023                 uninitsWhenTrue.assign(uninits);
2024                 uninitsWhenTrue.inclRange(firstadr, nextadr);
2025                 initsWhenFalse.assign(inits);
2026                 uninitsWhenFalse.assign(uninits);
2027             } else if (tree.type.isTrue()) {
2028                 if (inits.isReset()) merge();
2029                 initsWhenFalse.assign(inits);
2030                 initsWhenFalse.inclRange(firstadr, nextadr);
2031                 uninitsWhenFalse.assign(uninits);
2032                 uninitsWhenFalse.inclRange(firstadr, nextadr);
2033                 initsWhenTrue.assign(inits);
2034                 uninitsWhenTrue.assign(uninits);
2035             } else {
2036                 scan(tree);
2037                 if (!inits.isReset())
2038                     split(tree.type != syms.unknownType);
2039             }
2040             if (tree.type != syms.unknownType) {
2041                 resetBits(inits, uninits);
2042             }
2043         }
2044 
2045         /* ------------ Visitor methods for various sorts of trees -------------*/
2046 
2047         public void visitClassDef(JCClassDecl tree) {
2048             if (tree.sym == null) {
2049                 return;
2050             }
2051 
2052             Lint lintPrev = lint;
2053             lint = lint.augment(tree.sym);
2054             try {
2055                 if (tree.sym == null) {
2056                     return;
2057                 }
2058 
2059                 JCClassDecl classDefPrev = classDef;
2060                 int firstadrPrev = firstadr;
2061                 int nextadrPrev = nextadr;
2062                 ListBuffer<PendingExit> pendingExitsPrev = pendingExits;
2063 
2064                 pendingExits = new ListBuffer<>();
2065                 if (tree.name != names.empty) {
2066                     firstadr = nextadr;
2067                 }
2068                 classDef = tree;
2069                 try {
2070                     // define all the static fields
2071                     for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
2072                         if (l.head.hasTag(VARDEF)) {
2073                             JCVariableDecl def = (JCVariableDecl)l.head;
2074                             if ((def.mods.flags & STATIC) != 0) {
2075                                 VarSymbol sym = def.sym;
2076                                 if (trackable(sym)) {
2077                                     newVar(def);
2078                                 }
2079                             }
2080                         }
2081                     }
2082 
2083                     // process all the static initializers
2084                     for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
2085                         if (!l.head.hasTag(METHODDEF) &&
2086                             (TreeInfo.flags(l.head) & STATIC) != 0) {
2087                             scan(l.head);
2088                             clearPendingExits(false);
2089                         }
2090                     }
2091 
2092                     // define all the instance fields
2093                     for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
2094                         if (l.head.hasTag(VARDEF)) {
2095                             JCVariableDecl def = (JCVariableDecl)l.head;
2096                             if ((def.mods.flags & STATIC) == 0) {
2097                                 VarSymbol sym = def.sym;
2098                                 if (trackable(sym)) {
2099                                     newVar(def);
2100                                 }
2101                             }
2102                         }
2103                     }
2104 
2105                     // process all the instance initializers
2106                     for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
2107                         if (!l.head.hasTag(METHODDEF) &&
2108                             (TreeInfo.flags(l.head) & STATIC) == 0) {
2109                             scan(l.head);
2110                             clearPendingExits(false);
2111                         }
2112                     }
2113 
2114                     // process all the methods
2115                     for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
2116                         if (l.head.hasTag(METHODDEF)) {
2117                             scan(l.head);
2118                         }
2119                     }
2120                 } finally {
2121                     pendingExits = pendingExitsPrev;
2122                     nextadr = nextadrPrev;
2123                     firstadr = firstadrPrev;
2124                     classDef = classDefPrev;
2125                 }
2126             } finally {
2127                 lint = lintPrev;
2128             }
2129         }
2130 
2131         public void visitMethodDef(JCMethodDecl tree) {
2132             if (tree.body == null) {
2133                 return;
2134             }
2135 
2136             /*  MemberEnter can generate synthetic methods ignore them
2137              */
2138             if ((tree.sym.flags() & SYNTHETIC) != 0) {
2139                 return;
2140             }
2141 
2142             Lint lintPrev = lint;
2143             lint = lint.augment(tree.sym);
2144             try {
2145                 if (tree.body == null) {
2146                     return;
2147                 }
2148                 /*  Ignore synthetic methods, except for translated lambda methods.
2149                  */
2150                 if ((tree.sym.flags() & (SYNTHETIC | LAMBDA_METHOD)) == SYNTHETIC) {
2151                     return;
2152                 }
2153 
2154                 final Bits initsPrev = new Bits(inits);
2155                 final Bits uninitsPrev = new Bits(uninits);
2156                 int nextadrPrev = nextadr;
2157                 int firstadrPrev = firstadr;
2158                 int returnadrPrev = returnadr;
2159 
2160                 Assert.check(pendingExits.isEmpty());
2161                 boolean lastInitialConstructor = isInitialConstructor;
2162                 try {
2163                     isInitialConstructor = TreeInfo.isInitialConstructor(tree);
2164 
2165                     if (!isInitialConstructor) {
2166                         firstadr = nextadr;
2167                     }
2168                     for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
2169                         JCVariableDecl def = l.head;
2170                         scan(def);
2171                         Assert.check((def.sym.flags() & PARAMETER) != 0, "Method parameter without PARAMETER flag");
2172                         /*  If we are executing the code from Gen, then there can be
2173                          *  synthetic or mandated variables, ignore them.
2174                          */
2175                         initParam(def);
2176                     }
2177                     // else we are in an instance initializer block;
2178                     // leave caught unchanged.
2179                     scan(tree.body);
2180 
2181                     boolean isCompactConstructor = (tree.sym.flags() & Flags.COMPACT_RECORD_CONSTRUCTOR) != 0;
2182                     if (isInitialConstructor) {
2183                         boolean isSynthesized = (tree.sym.flags() &
2184                                                  GENERATEDCONSTR) != 0;
2185                         for (int i = firstadr; i < nextadr; i++) {
2186                             JCVariableDecl vardecl = vardecls[i];
2187                             VarSymbol var = vardecl.sym;
2188                             if (var.owner == classDef.sym) {
2189                                 // choose the diagnostic position based on whether
2190                                 // the ctor is default(synthesized) or not
2191                                 if (isSynthesized && !isCompactConstructor) {
2192                                     checkInit(TreeInfo.diagnosticPositionFor(var, vardecl),
2193                                             var, Errors.VarNotInitializedInDefaultConstructor(var));
2194                                 } else if (isCompactConstructor) {
2195                                     boolean isInstanceRecordField = var.enclClass().isRecord() &&
2196                                             (var.flags_field & (Flags.PRIVATE | Flags.FINAL | Flags.GENERATED_MEMBER | Flags.RECORD)) != 0 &&
2197                                             !var.isStatic() &&
2198                                             var.owner.kind == TYP;
2199                                     if (isInstanceRecordField) {
2200                                         boolean notInitialized = !inits.isMember(var.adr);
2201                                         if (notInitialized && uninits.isMember(var.adr) && tree.completesNormally) {
2202                                         /*  this way we indicate Lower that it should generate an initialization for this field
2203                                          *  in the compact constructor
2204                                          */
2205                                             var.flags_field |= UNINITIALIZED_FIELD;
2206                                         } else {
2207                                             checkInit(TreeInfo.diagEndPos(tree.body), var);
2208                                         }
2209                                     } else {
2210                                         checkInit(TreeInfo.diagnosticPositionFor(var, vardecl), var);
2211                                     }
2212                                 } else {
2213                                     checkInit(TreeInfo.diagEndPos(tree.body), var);
2214                                 }
2215                             }
2216                         }
2217                     }
2218                     clearPendingExits(true);
2219                 } finally {
2220                     inits.assign(initsPrev);
2221                     uninits.assign(uninitsPrev);
2222                     nextadr = nextadrPrev;
2223                     firstadr = firstadrPrev;
2224                     returnadr = returnadrPrev;
2225                     isInitialConstructor = lastInitialConstructor;
2226                 }
2227             } finally {
2228                 lint = lintPrev;
2229             }
2230         }
2231 
2232         private void clearPendingExits(boolean inMethod) {
2233             List<PendingExit> exits = pendingExits.toList();
2234             pendingExits = new ListBuffer<>();
2235             while (exits.nonEmpty()) {
2236                 PendingExit exit = exits.head;
2237                 exits = exits.tail;
2238                 Assert.check((inMethod && exit.tree.hasTag(RETURN)) ||
2239                                  log.hasErrorOn(exit.tree.pos()),
2240                              exit.tree);
2241                 if (inMethod && isInitialConstructor) {
2242                     Assert.check(exit instanceof AssignPendingExit);
2243                     inits.assign(((AssignPendingExit) exit).exit_inits);
2244                     for (int i = firstadr; i < nextadr; i++) {
2245                         checkInit(exit.tree.pos(), vardecls[i].sym);
2246                     }
2247                 }
2248             }
2249         }
2250         protected void initParam(JCVariableDecl def) {
2251             inits.incl(def.sym.adr);
2252             uninits.excl(def.sym.adr);
2253         }
2254 
2255         public void visitVarDef(JCVariableDecl tree) {
2256             Lint lintPrev = lint;
2257             lint = lint.augment(tree.sym);
2258             try{
2259                 boolean track = trackable(tree.sym);
2260                 if (track && (tree.sym.owner.kind == MTH || tree.sym.owner.kind == VAR)) {
2261                     newVar(tree);
2262                 }
2263                 if (tree.init != null) {
2264                     scanExpr(tree.init);
2265                     if (track) {
2266                         letInit(tree.pos(), tree.sym);
2267                     }
2268                 }
2269             } finally {
2270                 lint = lintPrev;
2271             }
2272         }
2273 
2274         public void visitBlock(JCBlock tree) {
2275             int nextadrPrev = nextadr;
2276             scan(tree.stats);
2277             nextadr = nextadrPrev;
2278         }
2279 
2280         public void visitDoLoop(JCDoWhileLoop tree) {
2281             ListBuffer<PendingExit> prevPendingExits = pendingExits;
2282             FlowKind prevFlowKind = flowKind;
2283             flowKind = FlowKind.NORMAL;
2284             final Bits initsSkip = new Bits(true);
2285             final Bits uninitsSkip = new Bits(true);
2286             pendingExits = new ListBuffer<>();
2287             int prevErrors = log.nerrors;
2288             do {
2289                 final Bits uninitsEntry = new Bits(uninits);
2290                 uninitsEntry.excludeFrom(nextadr);
2291                 scan(tree.body);
2292                 resolveContinues(tree);
2293                 scanCond(tree.cond);
2294                 if (!flowKind.isFinal()) {
2295                     initsSkip.assign(initsWhenFalse);
2296                     uninitsSkip.assign(uninitsWhenFalse);
2297                 }
2298                 if (log.nerrors !=  prevErrors ||
2299                     flowKind.isFinal() ||
2300                     new Bits(uninitsEntry).diffSet(uninitsWhenTrue).nextBit(firstadr)==-1)
2301                     break;
2302                 inits.assign(initsWhenTrue);
2303                 uninits.assign(uninitsEntry.andSet(uninitsWhenTrue));
2304                 flowKind = FlowKind.SPECULATIVE_LOOP;
2305             } while (true);
2306             flowKind = prevFlowKind;
2307             inits.assign(initsSkip);
2308             uninits.assign(uninitsSkip);
2309             resolveBreaks(tree, prevPendingExits);
2310         }
2311 
2312         public void visitWhileLoop(JCWhileLoop tree) {
2313             ListBuffer<PendingExit> prevPendingExits = pendingExits;
2314             FlowKind prevFlowKind = flowKind;
2315             flowKind = FlowKind.NORMAL;
2316             final Bits initsSkip = new Bits(true);
2317             final Bits uninitsSkip = new Bits(true);
2318             pendingExits = new ListBuffer<>();
2319             int prevErrors = log.nerrors;
2320             final Bits uninitsEntry = new Bits(uninits);
2321             uninitsEntry.excludeFrom(nextadr);
2322             do {
2323                 scanCond(tree.cond);
2324                 if (!flowKind.isFinal()) {
2325                     initsSkip.assign(initsWhenFalse) ;
2326                     uninitsSkip.assign(uninitsWhenFalse);
2327                 }
2328                 inits.assign(initsWhenTrue);
2329                 uninits.assign(uninitsWhenTrue);
2330                 scan(tree.body);
2331                 resolveContinues(tree);
2332                 if (log.nerrors != prevErrors ||
2333                     flowKind.isFinal() ||
2334                     new Bits(uninitsEntry).diffSet(uninits).nextBit(firstadr) == -1) {
2335                     break;
2336                 }
2337                 uninits.assign(uninitsEntry.andSet(uninits));
2338                 flowKind = FlowKind.SPECULATIVE_LOOP;
2339             } while (true);
2340             flowKind = prevFlowKind;
2341             //a variable is DA/DU after the while statement, if it's DA/DU assuming the
2342             //branch is not taken AND if it's DA/DU before any break statement
2343             inits.assign(initsSkip);
2344             uninits.assign(uninitsSkip);
2345             resolveBreaks(tree, prevPendingExits);
2346         }
2347 
2348         public void visitForLoop(JCForLoop tree) {
2349             ListBuffer<PendingExit> prevPendingExits = pendingExits;
2350             FlowKind prevFlowKind = flowKind;
2351             flowKind = FlowKind.NORMAL;
2352             int nextadrPrev = nextadr;
2353             scan(tree.init);
2354             final Bits initsSkip = new Bits(true);
2355             final Bits uninitsSkip = new Bits(true);
2356             pendingExits = new ListBuffer<>();
2357             int prevErrors = log.nerrors;
2358             do {
2359                 final Bits uninitsEntry = new Bits(uninits);
2360                 uninitsEntry.excludeFrom(nextadr);
2361                 if (tree.cond != null) {
2362                     scanCond(tree.cond);
2363                     if (!flowKind.isFinal()) {
2364                         initsSkip.assign(initsWhenFalse);
2365                         uninitsSkip.assign(uninitsWhenFalse);
2366                     }
2367                     inits.assign(initsWhenTrue);
2368                     uninits.assign(uninitsWhenTrue);
2369                 } else if (!flowKind.isFinal()) {
2370                     initsSkip.assign(inits);
2371                     initsSkip.inclRange(firstadr, nextadr);
2372                     uninitsSkip.assign(uninits);
2373                     uninitsSkip.inclRange(firstadr, nextadr);
2374                 }
2375                 scan(tree.body);
2376                 resolveContinues(tree);
2377                 scan(tree.step);
2378                 if (log.nerrors != prevErrors ||
2379                     flowKind.isFinal() ||
2380                     new Bits(uninitsEntry).diffSet(uninits).nextBit(firstadr) == -1)
2381                     break;
2382                 uninits.assign(uninitsEntry.andSet(uninits));
2383                 flowKind = FlowKind.SPECULATIVE_LOOP;
2384             } while (true);
2385             flowKind = prevFlowKind;
2386             //a variable is DA/DU after a for loop, if it's DA/DU assuming the
2387             //branch is not taken AND if it's DA/DU before any break statement
2388             inits.assign(initsSkip);
2389             uninits.assign(uninitsSkip);
2390             resolveBreaks(tree, prevPendingExits);
2391             nextadr = nextadrPrev;
2392         }
2393 
2394         public void visitForeachLoop(JCEnhancedForLoop tree) {
2395             visitVarDef(tree.var);
2396 
2397             ListBuffer<PendingExit> prevPendingExits = pendingExits;
2398             FlowKind prevFlowKind = flowKind;
2399             flowKind = FlowKind.NORMAL;
2400             int nextadrPrev = nextadr;
2401             scan(tree.expr);
2402             final Bits initsStart = new Bits(inits);
2403             final Bits uninitsStart = new Bits(uninits);
2404 
2405             letInit(tree.pos(), tree.var.sym);
2406             pendingExits = new ListBuffer<>();
2407             int prevErrors = log.nerrors;
2408             do {
2409                 final Bits uninitsEntry = new Bits(uninits);
2410                 uninitsEntry.excludeFrom(nextadr);
2411                 scan(tree.body);
2412                 resolveContinues(tree);
2413                 if (log.nerrors != prevErrors ||
2414                     flowKind.isFinal() ||
2415                     new Bits(uninitsEntry).diffSet(uninits).nextBit(firstadr) == -1)
2416                     break;
2417                 uninits.assign(uninitsEntry.andSet(uninits));
2418                 flowKind = FlowKind.SPECULATIVE_LOOP;
2419             } while (true);
2420             flowKind = prevFlowKind;
2421             inits.assign(initsStart);
2422             uninits.assign(uninitsStart.andSet(uninits));
2423             resolveBreaks(tree, prevPendingExits);
2424             nextadr = nextadrPrev;
2425         }
2426 
2427         public void visitLabelled(JCLabeledStatement tree) {
2428             ListBuffer<PendingExit> prevPendingExits = pendingExits;
2429             pendingExits = new ListBuffer<>();
2430             scan(tree.body);
2431             resolveBreaks(tree, prevPendingExits);
2432         }
2433 
2434         public void visitSwitch(JCSwitch tree) {
2435             handleSwitch(tree, tree.selector, tree.cases, tree.hasTotalPattern);
2436         }
2437 
2438         public void visitSwitchExpression(JCSwitchExpression tree) {
2439             handleSwitch(tree, tree.selector, tree.cases, tree.hasTotalPattern);
2440         }
2441 
2442         private void handleSwitch(JCTree tree, JCExpression selector,
2443                                   List<JCCase> cases, boolean hasTotalPattern) {
2444             ListBuffer<PendingExit> prevPendingExits = pendingExits;
2445             pendingExits = new ListBuffer<>();
2446             int nextadrPrev = nextadr;
2447             scanExpr(selector);
2448             final Bits initsSwitch = new Bits(inits);
2449             final Bits uninitsSwitch = new Bits(uninits);
2450             for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
2451                 inits.assign(initsSwitch);
2452                 uninits.assign(uninits.andSet(uninitsSwitch));
2453                 JCCase c = l.head;
2454                 for (JCCaseLabel pat : c.labels) {
2455                     scan(pat);
2456                     if (inits.isReset()) {
2457                         inits.assign(initsWhenTrue);
2458                         uninits.assign(uninitsWhenTrue);
2459                     }
2460                 }
2461                 if (l.head.stats.isEmpty() &&
2462                     l.tail.nonEmpty() &&
2463                     l.tail.head.labels.size() == 1 &&
2464                     l.tail.head.labels.head.isExpression() &&
2465                     TreeInfo.isNull(l.tail.head.labels.head)) {
2466                     //handling:
2467                     //case Integer i:
2468                     //case null:
2469                     //joining these two cases together - processing Integer i pattern,
2470                     //but statements from case null:
2471                     l = l.tail;
2472                     c = l.head;
2473                 }
2474                 scan(c.stats);
2475                 if (c.completesNormally && c.caseKind == JCCase.RULE) {
2476                     scanSyntheticBreak(make, tree);
2477                 }
2478                 addVars(c.stats, initsSwitch, uninitsSwitch);
2479                 // Warn about fall-through if lint switch fallthrough enabled.
2480             }
2481             if (!hasTotalPattern) {
2482                 if (tree.hasTag(SWITCH_EXPRESSION)) {
2483                     markDead();
2484                 } else {
2485                     inits.assign(initsSwitch);
2486                     uninits.assign(uninits.andSet(uninitsSwitch));
2487                 }
2488             }
2489             if (tree.hasTag(SWITCH_EXPRESSION)) {
2490                 resolveYields(tree, prevPendingExits);
2491             } else {
2492                 resolveBreaks(tree, prevPendingExits);
2493             }
2494             nextadr = nextadrPrev;
2495         }
2496         // where
2497             /** Add any variables defined in stats to inits and uninits. */
2498             private void addVars(List<JCStatement> stats, final Bits inits,
2499                                         final Bits uninits) {
2500                 for (;stats.nonEmpty(); stats = stats.tail) {
2501                     JCTree stat = stats.head;
2502                     if (stat.hasTag(VARDEF)) {
2503                         int adr = ((JCVariableDecl) stat).sym.adr;
2504                         inits.excl(adr);
2505                         uninits.incl(adr);
2506                     }
2507                 }
2508             }
2509 
2510         public void visitTry(JCTry tree) {
2511             ListBuffer<JCVariableDecl> resourceVarDecls = new ListBuffer<>();
2512             final Bits uninitsTryPrev = new Bits(uninitsTry);
2513             ListBuffer<PendingExit> prevPendingExits = pendingExits;
2514             pendingExits = new ListBuffer<>();
2515             final Bits initsTry = new Bits(inits);
2516             uninitsTry.assign(uninits);
2517             for (JCTree resource : tree.resources) {
2518                 if (resource instanceof JCVariableDecl variableDecl) {
2519                     visitVarDef(variableDecl);
2520                     unrefdResources.enter(variableDecl.sym);
2521                     resourceVarDecls.append(variableDecl);
2522                 } else if (resource instanceof JCExpression expression) {
2523                     scanExpr(expression);
2524                 } else {
2525                     throw new AssertionError(tree);  // parser error
2526                 }
2527             }
2528             scan(tree.body);
2529             uninitsTry.andSet(uninits);
2530             final Bits initsEnd = new Bits(inits);
2531             final Bits uninitsEnd = new Bits(uninits);
2532             int nextadrCatch = nextadr;
2533 
2534             if (!resourceVarDecls.isEmpty() &&
2535                     lint.isEnabled(Lint.LintCategory.TRY)) {
2536                 for (JCVariableDecl resVar : resourceVarDecls) {
2537                     if (unrefdResources.includes(resVar.sym)) {
2538                         log.warning(Lint.LintCategory.TRY, resVar.pos(),
2539                                     Warnings.TryResourceNotReferenced(resVar.sym));
2540                         unrefdResources.remove(resVar.sym);
2541                     }
2542                 }
2543             }
2544 
2545             /*  The analysis of each catch should be independent.
2546              *  Each one should have the same initial values of inits and
2547              *  uninits.
2548              */
2549             final Bits initsCatchPrev = new Bits(initsTry);
2550             final Bits uninitsCatchPrev = new Bits(uninitsTry);
2551 
2552             for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) {
2553                 JCVariableDecl param = l.head.param;
2554                 inits.assign(initsCatchPrev);
2555                 uninits.assign(uninitsCatchPrev);
2556                 scan(param);
2557                 /* If this is a TWR and we are executing the code from Gen,
2558                  * then there can be synthetic variables, ignore them.
2559                  */
2560                 initParam(param);
2561                 scan(l.head.body);
2562                 initsEnd.andSet(inits);
2563                 uninitsEnd.andSet(uninits);
2564                 nextadr = nextadrCatch;
2565             }
2566             if (tree.finalizer != null) {
2567                 inits.assign(initsTry);
2568                 uninits.assign(uninitsTry);
2569                 ListBuffer<PendingExit> exits = pendingExits;
2570                 pendingExits = prevPendingExits;
2571                 scan(tree.finalizer);
2572                 if (!tree.finallyCanCompleteNormally) {
2573                     // discard exits and exceptions from try and finally
2574                 } else {
2575                     uninits.andSet(uninitsEnd);
2576                     // FIX: this doesn't preserve source order of exits in catch
2577                     // versus finally!
2578                     while (exits.nonEmpty()) {
2579                         PendingExit exit = exits.next();
2580                         if (exit instanceof AssignPendingExit assignPendingExit) {
2581                             assignPendingExit.exit_inits.orSet(inits);
2582                             assignPendingExit.exit_uninits.andSet(uninits);
2583                         }
2584                         pendingExits.append(exit);
2585                     }
2586                     inits.orSet(initsEnd);
2587                 }
2588             } else {
2589                 inits.assign(initsEnd);
2590                 uninits.assign(uninitsEnd);
2591                 ListBuffer<PendingExit> exits = pendingExits;
2592                 pendingExits = prevPendingExits;
2593                 while (exits.nonEmpty()) pendingExits.append(exits.next());
2594             }
2595             uninitsTry.andSet(uninitsTryPrev).andSet(uninits);
2596         }
2597 
2598         public void visitConditional(JCConditional tree) {
2599             scanCond(tree.cond);
2600             final Bits initsBeforeElse = new Bits(initsWhenFalse);
2601             final Bits uninitsBeforeElse = new Bits(uninitsWhenFalse);
2602             inits.assign(initsWhenTrue);
2603             uninits.assign(uninitsWhenTrue);
2604             if (tree.truepart.type.hasTag(BOOLEAN) &&
2605                 tree.falsepart.type.hasTag(BOOLEAN)) {
2606                 // if b and c are boolean valued, then
2607                 // v is (un)assigned after a?b:c when true iff
2608                 //    v is (un)assigned after b when true and
2609                 //    v is (un)assigned after c when true
2610                 scanCond(tree.truepart);
2611                 final Bits initsAfterThenWhenTrue = new Bits(initsWhenTrue);
2612                 final Bits initsAfterThenWhenFalse = new Bits(initsWhenFalse);
2613                 final Bits uninitsAfterThenWhenTrue = new Bits(uninitsWhenTrue);
2614                 final Bits uninitsAfterThenWhenFalse = new Bits(uninitsWhenFalse);
2615                 inits.assign(initsBeforeElse);
2616                 uninits.assign(uninitsBeforeElse);
2617                 scanCond(tree.falsepart);
2618                 initsWhenTrue.andSet(initsAfterThenWhenTrue);
2619                 initsWhenFalse.andSet(initsAfterThenWhenFalse);
2620                 uninitsWhenTrue.andSet(uninitsAfterThenWhenTrue);
2621                 uninitsWhenFalse.andSet(uninitsAfterThenWhenFalse);
2622             } else {
2623                 scanExpr(tree.truepart);
2624                 final Bits initsAfterThen = new Bits(inits);
2625                 final Bits uninitsAfterThen = new Bits(uninits);
2626                 inits.assign(initsBeforeElse);
2627                 uninits.assign(uninitsBeforeElse);
2628                 scanExpr(tree.falsepart);
2629                 inits.andSet(initsAfterThen);
2630                 uninits.andSet(uninitsAfterThen);
2631             }
2632         }
2633 
2634         public void visitIf(JCIf tree) {
2635             scanCond(tree.cond);
2636             final Bits initsBeforeElse = new Bits(initsWhenFalse);
2637             final Bits uninitsBeforeElse = new Bits(uninitsWhenFalse);
2638             inits.assign(initsWhenTrue);
2639             uninits.assign(uninitsWhenTrue);
2640             scan(tree.thenpart);
2641             if (tree.elsepart != null) {
2642                 final Bits initsAfterThen = new Bits(inits);
2643                 final Bits uninitsAfterThen = new Bits(uninits);
2644                 inits.assign(initsBeforeElse);
2645                 uninits.assign(uninitsBeforeElse);
2646                 scan(tree.elsepart);
2647                 inits.andSet(initsAfterThen);
2648                 uninits.andSet(uninitsAfterThen);
2649             } else {
2650                 inits.andSet(initsBeforeElse);
2651                 uninits.andSet(uninitsBeforeElse);
2652             }
2653         }
2654 
2655         @Override
2656         public void visitBreak(JCBreak tree) {
2657             recordExit(new AssignPendingExit(tree, inits, uninits));
2658         }
2659 
2660         @Override
2661         public void visitYield(JCYield tree) {
2662             JCSwitchExpression expr = (JCSwitchExpression) tree.target;
2663             if (expr != null && expr.type.hasTag(BOOLEAN)) {
2664                 scanCond(tree.value);
2665                 Bits initsAfterBreakWhenTrue = new Bits(initsWhenTrue);
2666                 Bits initsAfterBreakWhenFalse = new Bits(initsWhenFalse);
2667                 Bits uninitsAfterBreakWhenTrue = new Bits(uninitsWhenTrue);
2668                 Bits uninitsAfterBreakWhenFalse = new Bits(uninitsWhenFalse);
2669                 PendingExit exit = new PendingExit(tree) {
2670                     @Override
2671                     void resolveJump() {
2672                         if (!inits.isReset()) {
2673                             split(true);
2674                         }
2675                         initsWhenTrue.andSet(initsAfterBreakWhenTrue);
2676                         initsWhenFalse.andSet(initsAfterBreakWhenFalse);
2677                         uninitsWhenTrue.andSet(uninitsAfterBreakWhenTrue);
2678                         uninitsWhenFalse.andSet(uninitsAfterBreakWhenFalse);
2679                     }
2680                 };
2681                 merge();
2682                 recordExit(exit);
2683                 return ;
2684             } else {
2685                 scanExpr(tree.value);
2686                 recordExit(new AssignPendingExit(tree, inits, uninits));
2687             }
2688         }
2689 
2690         @Override
2691         public void visitContinue(JCContinue tree) {
2692             recordExit(new AssignPendingExit(tree, inits, uninits));
2693         }
2694 
2695         @Override
2696         public void visitReturn(JCReturn tree) {
2697             scanExpr(tree.expr);
2698             recordExit(new AssignPendingExit(tree, inits, uninits));
2699         }
2700 
2701         public void visitThrow(JCThrow tree) {
2702             scanExpr(tree.expr);
2703             markDead();
2704         }
2705 
2706         public void visitApply(JCMethodInvocation tree) {
2707             scanExpr(tree.meth);
2708             scanExprs(tree.args);
2709         }
2710 
2711         public void visitNewClass(JCNewClass tree) {
2712             scanExpr(tree.encl);
2713             scanExprs(tree.args);
2714             scan(tree.def);
2715         }
2716 
2717         @Override
2718         public void visitLambda(JCLambda tree) {
2719             final Bits prevUninits = new Bits(uninits);
2720             final Bits prevInits = new Bits(inits);
2721             int returnadrPrev = returnadr;
2722             int nextadrPrev = nextadr;
2723             ListBuffer<PendingExit> prevPending = pendingExits;
2724             try {
2725                 returnadr = nextadr;
2726                 pendingExits = new ListBuffer<>();
2727                 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
2728                     JCVariableDecl def = l.head;
2729                     scan(def);
2730                     inits.incl(def.sym.adr);
2731                     uninits.excl(def.sym.adr);
2732                 }
2733                 if (tree.getBodyKind() == JCLambda.BodyKind.EXPRESSION) {
2734                     scanExpr(tree.body);
2735                 } else {
2736                     scan(tree.body);
2737                 }
2738             }
2739             finally {
2740                 returnadr = returnadrPrev;
2741                 uninits.assign(prevUninits);
2742                 inits.assign(prevInits);
2743                 pendingExits = prevPending;
2744                 nextadr = nextadrPrev;
2745             }
2746         }
2747 
2748         public void visitNewArray(JCNewArray tree) {
2749             scanExprs(tree.dims);
2750             scanExprs(tree.elems);
2751         }
2752 
2753         public void visitAssert(JCAssert tree) {
2754             final Bits initsExit = new Bits(inits);
2755             final Bits uninitsExit = new Bits(uninits);
2756             scanCond(tree.cond);
2757             uninitsExit.andSet(uninitsWhenTrue);
2758             if (tree.detail != null) {
2759                 inits.assign(initsWhenFalse);
2760                 uninits.assign(uninitsWhenFalse);
2761                 scanExpr(tree.detail);
2762             }
2763             inits.assign(initsExit);
2764             uninits.assign(uninitsExit);
2765         }
2766 
2767         public void visitAssign(JCAssign tree) {
2768             if (!TreeInfo.isIdentOrThisDotIdent(tree.lhs))
2769                 scanExpr(tree.lhs);
2770             scanExpr(tree.rhs);
2771             letInit(tree.lhs);
2772         }
2773 
2774         // check fields accessed through this.<field> are definitely
2775         // assigned before reading their value
2776         public void visitSelect(JCFieldAccess tree) {
2777             super.visitSelect(tree);
2778             if (TreeInfo.isThisQualifier(tree.selected) &&
2779                 tree.sym.kind == VAR) {
2780                 checkInit(tree.pos(), (VarSymbol)tree.sym);
2781             }
2782         }
2783 
2784         public void visitAssignop(JCAssignOp tree) {
2785             scanExpr(tree.lhs);
2786             scanExpr(tree.rhs);
2787             letInit(tree.lhs);
2788         }
2789 
2790         public void visitUnary(JCUnary tree) {
2791             switch (tree.getTag()) {
2792             case NOT:
2793                 scanCond(tree.arg);
2794                 final Bits t = new Bits(initsWhenFalse);
2795                 initsWhenFalse.assign(initsWhenTrue);
2796                 initsWhenTrue.assign(t);
2797                 t.assign(uninitsWhenFalse);
2798                 uninitsWhenFalse.assign(uninitsWhenTrue);
2799                 uninitsWhenTrue.assign(t);
2800                 break;
2801             case PREINC: case POSTINC:
2802             case PREDEC: case POSTDEC:
2803                 scanExpr(tree.arg);
2804                 letInit(tree.arg);
2805                 break;
2806             default:
2807                 scanExpr(tree.arg);
2808             }
2809         }
2810 
2811         public void visitBinary(JCBinary tree) {
2812             switch (tree.getTag()) {
2813             case AND:
2814                 scanCond(tree.lhs);
2815                 final Bits initsWhenFalseLeft = new Bits(initsWhenFalse);
2816                 final Bits uninitsWhenFalseLeft = new Bits(uninitsWhenFalse);
2817                 inits.assign(initsWhenTrue);
2818                 uninits.assign(uninitsWhenTrue);
2819                 scanCond(tree.rhs);
2820                 initsWhenFalse.andSet(initsWhenFalseLeft);
2821                 uninitsWhenFalse.andSet(uninitsWhenFalseLeft);
2822                 break;
2823             case OR:
2824                 scanCond(tree.lhs);
2825                 final Bits initsWhenTrueLeft = new Bits(initsWhenTrue);
2826                 final Bits uninitsWhenTrueLeft = new Bits(uninitsWhenTrue);
2827                 inits.assign(initsWhenFalse);
2828                 uninits.assign(uninitsWhenFalse);
2829                 scanCond(tree.rhs);
2830                 initsWhenTrue.andSet(initsWhenTrueLeft);
2831                 uninitsWhenTrue.andSet(uninitsWhenTrueLeft);
2832                 break;
2833             default:
2834                 scanExpr(tree.lhs);
2835                 scanExpr(tree.rhs);
2836             }
2837         }
2838 
2839         public void visitIdent(JCIdent tree) {
2840             if (tree.sym.kind == VAR) {
2841                 checkInit(tree.pos(), (VarSymbol)tree.sym);
2842                 referenced(tree.sym);
2843             }
2844         }
2845 
2846         @Override
2847         public void visitBindingPattern(JCBindingPattern tree) {
2848             super.visitBindingPattern(tree);
2849             initParam(tree.var);
2850         }
2851 
2852         void referenced(Symbol sym) {
2853             unrefdResources.remove(sym);
2854         }
2855 
2856         public void visitAnnotatedType(JCAnnotatedType tree) {
2857             // annotations don't get scanned
2858             tree.underlyingType.accept(this);
2859         }
2860 
2861         public void visitModuleDef(JCModuleDecl tree) {
2862             // Do nothing for modules
2863         }
2864 
2865     /**************************************************************************
2866      * main method
2867      *************************************************************************/
2868 
2869         /** Perform definite assignment/unassignment analysis on a tree.
2870          */
2871         public void analyzeTree(Env<?> env, TreeMaker make) {
2872             analyzeTree(env, env.tree, make);
2873          }
2874 
2875         public void analyzeTree(Env<?> env, JCTree tree, TreeMaker make) {
2876             try {
2877                 startPos = tree.pos().getStartPosition();
2878 
2879                 if (vardecls == null)
2880                     vardecls = new JCVariableDecl[32];
2881                 else
2882                     for (int i=0; i<vardecls.length; i++)
2883                         vardecls[i] = null;
2884                 firstadr = 0;
2885                 nextadr = 0;
2886                 Flow.this.make = make;
2887                 pendingExits = new ListBuffer<>();
2888                 this.classDef = null;
2889                 unrefdResources = WriteableScope.create(env.enclClass.sym);
2890                 scan(tree);
2891             } finally {
2892                 // note that recursive invocations of this method fail hard
2893                 startPos = -1;
2894                 resetBits(inits, uninits, uninitsTry, initsWhenTrue,
2895                         initsWhenFalse, uninitsWhenTrue, uninitsWhenFalse);
2896                 if (vardecls != null) {
2897                     for (int i=0; i<vardecls.length; i++)
2898                         vardecls[i] = null;
2899                 }
2900                 firstadr = 0;
2901                 nextadr = 0;
2902                 Flow.this.make = null;
2903                 pendingExits = null;
2904                 this.classDef = null;
2905                 unrefdResources = null;
2906             }
2907         }
2908     }
2909 
2910     /**
2911      * This pass implements the last step of the dataflow analysis, namely
2912      * the effectively-final analysis check. This checks that every local variable
2913      * reference from a lambda body/local inner class is either final or effectively final.
2914      * Additional this also checks that every variable that is used as an operand to
2915      * try-with-resources is final or effectively final.
2916      * As effectively final variables are marked as such during DA/DU, this pass must run after
2917      * AssignAnalyzer.
2918      */
2919     class CaptureAnalyzer extends BaseAnalyzer {
2920 
2921         JCTree currentTree; //local class or lambda
2922 
2923         @Override
2924         void markDead() {
2925             //do nothing
2926         }
2927 
2928         @SuppressWarnings("fallthrough")
2929         void checkEffectivelyFinal(DiagnosticPosition pos, VarSymbol sym) {
2930             if (currentTree != null &&
2931                     sym.owner.kind == MTH &&
2932                     sym.pos < currentTree.getStartPosition()) {
2933                 switch (currentTree.getTag()) {
2934                     case CLASSDEF:
2935                         if (!allowEffectivelyFinalInInnerClasses) {
2936                             if ((sym.flags() & FINAL) == 0) {
2937                                 reportInnerClsNeedsFinalError(pos, sym);
2938                             }
2939                             break;
2940                         }
2941                     case GUARDPATTERN:
2942                     case LAMBDA:
2943                         if ((sym.flags() & (EFFECTIVELY_FINAL | FINAL)) == 0) {
2944                            reportEffectivelyFinalError(pos, sym);
2945                         }
2946                 }
2947             }
2948         }
2949 
2950         @SuppressWarnings("fallthrough")
2951         void letInit(JCTree tree) {
2952             tree = TreeInfo.skipParens(tree);
2953             if (tree.hasTag(IDENT) || tree.hasTag(SELECT)) {
2954                 Symbol sym = TreeInfo.symbol(tree);
2955                 if (currentTree != null &&
2956                         sym.kind == VAR &&
2957                         sym.owner.kind == MTH &&
2958                         ((VarSymbol)sym).pos < currentTree.getStartPosition()) {
2959                     switch (currentTree.getTag()) {
2960                         case CLASSDEF:
2961                             if (!allowEffectivelyFinalInInnerClasses) {
2962                                 reportInnerClsNeedsFinalError(tree, sym);
2963                                 break;
2964                             }
2965                         case GUARDPATTERN:
2966                         case LAMBDA:
2967                             reportEffectivelyFinalError(tree, sym);
2968                     }
2969                 }
2970             }
2971         }
2972 
2973         void reportEffectivelyFinalError(DiagnosticPosition pos, Symbol sym) {
2974             Fragment subKey = switch (currentTree.getTag()) {
2975                 case LAMBDA -> Fragments.Lambda;
2976                 case GUARDPATTERN -> Fragments.Guard;
2977                 case CLASSDEF -> Fragments.InnerCls;
2978                 default -> throw new AssertionError("Unexpected tree kind: " + currentTree.getTag());
2979             };
2980             log.error(pos, Errors.CantRefNonEffectivelyFinalVar(sym, diags.fragment(subKey)));
2981         }
2982 
2983         void reportInnerClsNeedsFinalError(DiagnosticPosition pos, Symbol sym) {
2984             log.error(pos,
2985                       Errors.LocalVarAccessedFromIclsNeedsFinal(sym));
2986         }
2987 
2988     /*************************************************************************
2989      * Visitor methods for statements and definitions
2990      *************************************************************************/
2991 
2992         /* ------------ Visitor methods for various sorts of trees -------------*/
2993 
2994         public void visitClassDef(JCClassDecl tree) {
2995             JCTree prevTree = currentTree;
2996             try {
2997                 currentTree = tree.sym.isDirectlyOrIndirectlyLocal() ? tree : null;
2998                 super.visitClassDef(tree);
2999             } finally {
3000                 currentTree = prevTree;
3001             }
3002         }
3003 
3004         @Override
3005         public void visitLambda(JCLambda tree) {
3006             JCTree prevTree = currentTree;
3007             try {
3008                 currentTree = tree;
3009                 super.visitLambda(tree);
3010             } finally {
3011                 currentTree = prevTree;
3012             }
3013         }
3014 
3015         @Override
3016         public void visitGuardPattern(JCGuardPattern tree) {
3017             scan(tree.patt);
3018             JCTree prevTree = currentTree;
3019             try {
3020                 currentTree = tree;
3021                 scan(tree.expr);
3022             } finally {
3023                 currentTree = prevTree;
3024             }
3025         }
3026 
3027         @Override
3028         public void visitIdent(JCIdent tree) {
3029             if (tree.sym.kind == VAR) {
3030                 checkEffectivelyFinal(tree, (VarSymbol)tree.sym);
3031             }
3032         }
3033 
3034         public void visitAssign(JCAssign tree) {
3035             JCTree lhs = TreeInfo.skipParens(tree.lhs);
3036             if (!(lhs instanceof JCIdent)) {
3037                 scan(lhs);
3038             }
3039             scan(tree.rhs);
3040             letInit(lhs);
3041         }
3042 
3043         public void visitAssignop(JCAssignOp tree) {
3044             scan(tree.lhs);
3045             scan(tree.rhs);
3046             letInit(tree.lhs);
3047         }
3048 
3049         public void visitUnary(JCUnary tree) {
3050             switch (tree.getTag()) {
3051                 case PREINC: case POSTINC:
3052                 case PREDEC: case POSTDEC:
3053                     scan(tree.arg);
3054                     letInit(tree.arg);
3055                     break;
3056                 default:
3057                     scan(tree.arg);
3058             }
3059         }
3060 
3061         public void visitTry(JCTry tree) {
3062             for (JCTree resource : tree.resources) {
3063                 if (!resource.hasTag(VARDEF)) {
3064                     Symbol var = TreeInfo.symbol(resource);
3065                     if (var != null && (var.flags() & (FINAL | EFFECTIVELY_FINAL)) == 0) {
3066                         log.error(resource.pos(), Errors.TryWithResourcesExprEffectivelyFinalVar(var));
3067                     }
3068                 }
3069             }
3070             super.visitTry(tree);
3071         }
3072 
3073         @Override
3074         public void visitYield(JCYield tree) {
3075             scan(tree.value);
3076         }
3077 
3078         public void visitModuleDef(JCModuleDecl tree) {
3079             // Do nothing for modules
3080         }
3081 
3082     /**************************************************************************
3083      * main method
3084      *************************************************************************/
3085 
3086         /** Perform definite assignment/unassignment analysis on a tree.
3087          */
3088         public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
3089             analyzeTree(env, env.tree, make);
3090         }
3091         public void analyzeTree(Env<AttrContext> env, JCTree tree, TreeMaker make) {
3092             try {
3093                 attrEnv = env;
3094                 Flow.this.make = make;
3095                 pendingExits = new ListBuffer<>();
3096                 scan(tree);
3097             } finally {
3098                 pendingExits = null;
3099                 Flow.this.make = null;
3100             }
3101         }
3102     }
3103 
3104     enum Liveness {
3105         ALIVE {
3106             @Override
3107             public Liveness or(Liveness other) {
3108                 return this;
3109             }
3110             @Override
3111             public Liveness and(Liveness other) {
3112                 return other;
3113             }
3114         },
3115         DEAD {
3116             @Override
3117             public Liveness or(Liveness other) {
3118                 return other;
3119             }
3120             @Override
3121             public Liveness and(Liveness other) {
3122                 return this;
3123             }
3124         },
3125         RECOVERY {
3126             @Override
3127             public Liveness or(Liveness other) {
3128                 if (other == ALIVE) {
3129                     return ALIVE;
3130                 } else {
3131                     return this;
3132                 }
3133             }
3134             @Override
3135             public Liveness and(Liveness other) {
3136                 if (other == DEAD) {
3137                     return DEAD;
3138                 } else {
3139                     return this;
3140                 }
3141             }
3142         };
3143 
3144         public abstract Liveness or(Liveness other);
3145         public abstract Liveness and(Liveness other);
3146         public Liveness or(boolean value) {
3147             return or(from(value));
3148         }
3149         public Liveness and(boolean value) {
3150             return and(from(value));
3151         }
3152         public static Liveness from(boolean value) {
3153             return value ? ALIVE : DEAD;
3154         }
3155     }
3156 
3157 }