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