Package: org.codehaus.groovy.classgen

## [Java] Class VariableScopeVisitor

- org.codehaus.groovy.classgen.VariableScopeVisitor

-     public class VariableScopeVisitor
      extends ClassCodeVisitorSupport

  Initializes the variable scopes for an AST.

  For JEP 394 `instanceof` pattern variables (GROOVY-12242), this class is the single authoritative source of scope decisions. InstanceofFlowBindings answers which pattern variables are definitely bound on each control-flow path; this visitor:

  - declares each pattern variable only where it is live, so out-of-scope references become DynamicVariable (runtime MissingPropertyException in dynamic Groovy — the same rule `@TypeChecked` enforces at compile time); and
  - attaches the same InstanceofFlowBindings instance as AST metadata so later phases (classgen) can read path-live names without re-running the analysis.
  See Also:
    InstanceofFlowBindings

- - ### Nested Class Summary

    Nested classes
    Modifiers | Name | Description
    --- | --- | ---
    `static class` | `VariableScopeVisitor.InstanceofFlowBindings` | Flow-sensitive result for JEP 394 `instanceof` pattern bindings (GROOVY-12242) — the Groovy equivalent of the JLS §6.3.1 “introduced by” sets.

  - ### Constructor Summary

    Constructors
    Constructor and description
    `VariableScopeVisitor(SourceUnit source, boolean recurseInnerClasses)` Creates a new variable scope visitor with optional recursion into inner classes.
    `VariableScopeVisitor(SourceUnit source)` Creates a new variable scope visitor that does not recurse into inner classes.

  - ### Methods Summary

    Methods
    Type Params | Return Type | Name and description
    --- | --- | ---
    `` | `protected SourceUnit` | `getSourceUnit()` * Provides access to the SourceUnit for error reporting during visitation. * Implementations must override this method. * * Returns: the source unit for this visitor
    `` | `public void` | `prepareVisit(ClassNode node)` Sets the current class node context.
    `` | `protected void` | `visitAnnotation(AnnotationNode node)` * Visits an individual AnnotationNode, traversing all member expression values. * Subclasses may override to perform custom annotation processing. * * Parameters: `node` - the annotation node to visit
    `` | `public void` | `visitArrayExpression(ArrayExpression expression)` * Visits an ArrayExpression, traversing element expressions and size expressions. * * Parameters: `expression` - the array expression
    `` | `public void` | `visitAssertStatement(AssertStatement statement)` * Visits an AssertStatement, invoking the statement hook before parent traversal. * * Parameters: `statement` - the assert statement to visit
    `` | `public void` | `visitBinaryExpression(BinaryExpression expression)` Visits binary expressions with flow-aware scoping for `&&` / `||` so pattern variables follow Java short-circuit rules (GROOVY-12242 / JEP 394): `a && b` — true-path bindings of `a` are in scope in `b` `a || b` — true-path bindings of `a` are not in scope in `b`; false-path bindings of `a` are {@code e !
    `` | `public void` | `visitBlockStatement(BlockStatement statement)` * Visits a BlockStatement, invoking the statement hook before parent traversal. * * Parameters: `statement` - the block statement to visit
    `` | `public void` | `visitCastExpression(CastExpression expression)` * Visits a CastExpression, traversing the operand expression. * * Parameters: `expression` - the cast expression
    `` | `public void` | `visitCatchStatement(CatchStatement statement)` * Visits a CatchStatement, processing variable annotations and invoking the statement hook. * * Parameters: `statement` - the catch statement to visit
    `` | `public void` | `visitClass(ClassNode node)` * Visits a ClassNode, processing its annotations, package, imports, contents, and object initializers. * * Parameters: `node` - the class node to visit
    `` | `public void` | `visitClassExpression(ClassExpression expression)` * Visits a ClassExpression. No traversal is performed as class expressions contain no child expressions. * * Parameters: `expression` - the class expression
    `` | `public void` | `visitClosureExpression(ClosureExpression expression)` * Visits a ClosureExpression with annotation processing, traversing parameter annotations * before delegating to parent traversal. * * Parameters: `expression` - the closure expression to visit
    `` | `public void` | `visitConstantExpression(ConstantExpression expression)` * Visits a ConstantExpression. No traversal is performed as constants contain no child expressions. * * Parameters: `expression` - the constant expression
    `` | `public void` | `visitConstructorCallExpression(ConstructorCallExpression expression)` * Visits a ConstructorCallExpression, traversing its argument list. * * Parameters: `call` - the constructor call expression
    `` | `protected void` | `visitConstructorOrMethod(MethodNode node, boolean isConstructor)` * Visits a constructor or method node (implementation detail for both visit methods). * Processes the node's annotations, all parameter annotations, and code block. * * Parameters: `node` - the method or constructor node * `isConstructor` - true if node is a constructor, false if it is a method
    `` | `public void` | `visitDeclarationExpression(DeclarationExpression expression)` * Visits a DeclarationExpression with annotation processing, traversing expression annotations * before delegating to parent traversal. * * Parameters: `expression` - the declaration expression to visit
    `` | `public void` | `visitDoWhileLoop(DoWhileStatement statement)` Visits a `do`/`while` loop (GROOVY-12242).
    `` | `public void` | `visitExpressionStatement(ExpressionStatement statement)` * Visits an ExpressionStatement, invoking the statement hook before parent traversal. * * Parameters: `statement` - the expression statement to visit
    `` | `public void` | `visitField(FieldNode node)` * Visits a FieldNode, processing its annotations and initial value expression if present. * * Parameters: `node` - the field node to visit
    `` | `public void` | `visitFieldExpression(FieldExpression expression)` * Visits a FieldExpression. No traversal is performed as field expressions contain no child expressions. * * Parameters: `expression` - the field expression
    `` | `public void` | `visitForLoop(ForStatement statement)` * Visits a ForStatement, invoking statement hooks and processing loop variable annotations. * * Parameters: `statement` - the for statement to visit
    `` | `public void` | `visitIfElse(IfStatement statement)` Visits an `if`/`else` statement, establishing correct lexical scopes for JEP 394 `instanceof` pattern variables (GROOVY-12242) and attaching InstanceofFlowBindings metadata so later phases need not re-derive the flow analysis.
    `` | `public void` | `visitMethodCallExpression(MethodCallExpression expression)` * Visits a MethodCallExpression, traversing the object expression, * method expression, and argument list. * * Parameters: `call` - the method call expression
    `` | `public void` | `visitProperty(PropertyNode node)` * Visits a PropertyNode, processing its annotations, initial value expression, * and getter/setter blocks if present. * * Parameters: `node` - the property node to visit
    `` | `public void` | `visitPropertyExpression(PropertyExpression expression)` * Visits a PropertyExpression, traversing the object and property name expressions. * * Parameters: `expression` - the property expression
    `` | `public void` | `visitReturnStatement(ReturnStatement statement)` * Visits a ReturnStatement, invoking the statement hook before parent traversal. * * Parameters: `statement` - the return statement to visit
    `` | `public void` | `visitSwitch(SwitchStatement statement)` * Visits a SwitchStatement, invoking the statement hook before parent traversal. * * Parameters: `statement` - the switch statement to visit
    `` | `public void` | `visitTernaryExpression(TernaryExpression expression)` Visits a ternary / Elvis expression with flow scoping for pattern variables: true-path bindings are in scope in the then-branch; false-path bindings in the else-branch (GROOVY-12242 / JEP 394).
    `` | `public void` | `visitVariableExpression(VariableExpression expression)` * Visits a VariableExpression. No traversal is performed as variable expressions contain no child expressions. * * Parameters: `expression` - the variable expression
    `` | `public void` | `visitWhileLoop(WhileStatement statement)` Visits a `while` loop with partial JEP 394 flow scoping for `instanceof` pattern variables (GROOVY-12242).

  - ### Inherited Methods Summary

    Inherited Methods
    Methods inherited from class | Name
    --- | ---
    `class ClassCodeVisitorSupport` | `addError, getSourceUnit, visitAnnotation, visitAnnotations, visitAnnotations, visitAssertStatement, visitBlockStatement, visitBreakStatement, visitCaseStatement, visitCatchStatement, visitClass, visitClassCodeContainer, visitClosureExpression, visitConstructor, visitConstructorOrMethod, visitContinueStatement, visitDeclarationExpression, visitDoWhileLoop, visitExpressionStatement, visitField, visitForLoop, visitIfElse, visitImports, visitMethod, visitObjectInitializerStatements, visitPackage, visitProperty, visitReturnStatement, visitStatement, visitStatementAnnotations, visitSwitch, visitSynchronizedStatement, visitThrowStatement, visitTryCatchFinally, visitWhileLoop`
    `class CodeVisitorSupport` | `afterSwitchCaseStatementsVisited, afterSwitchConditionExpressionVisited, visitArgumentlistExpression, visitArrayExpression, visitAssertStatement, visitAttributeExpression, visitBinaryExpression, visitBitwiseNegationExpression, visitBlockStatement, visitBooleanExpression, visitBreakStatement, visitBytecodeExpression, visitCaseStatement, visitCastExpression, visitCatchStatement, visitClassExpression, visitClosureExpression, visitClosureListExpression, visitConstantExpression, visitConstructorCallExpression, visitContinueStatement, visitDeclarationExpression, visitDoWhileLoop, visitEmptyStatement, visitExpressionStatement, visitFieldExpression, visitForLoop, visitGStringExpression, visitIfElse, visitLambdaExpression, visitListExpression, visitMapEntryExpression, visitMapExpression, visitMethodCallExpression, visitMethodPointerExpression, visitMethodReferenceExpression, visitNotExpression, visitPostfixExpression, visitPrefixExpression, visitPropertyExpression, visitRangeExpression, visitReturnStatement, visitShortTernaryExpression, visitSpreadExpression, visitSpreadMapExpression, visitStaticMethodCallExpression, visitSwitch, visitSynchronizedStatement, visitTernaryExpression, visitThrowStatement, visitTryCatchFinally, visitTupleExpression, visitUnaryMinusExpression, visitUnaryPlusExpression, visitVariableExpression, visitWhileLoop`

- - ### Constructor Detail

    - #### public VariableScopeVisitor(SourceUnit source, boolean recurseInnerClasses)

      Creates a new variable scope visitor with optional recursion into inner classes.

      Parameters:
        `source` - the source unit being processed
        `recurseInnerClasses` - whether to recurse into inner classes

    - #### public VariableScopeVisitor(SourceUnit source)

      Creates a new variable scope visitor that does not recurse into inner classes.

      Parameters:
        `source` - the source unit being processed

  - ### Method Detail

    - #### protected SourceUnit getSourceUnit()

      * Provides access to the SourceUnit for error reporting during visitation. * Implementations must override this method. * *

      Returns:
        the source unit for this visitor

    - #### public void prepareVisit(ClassNode node)

      Sets the current class node context.

    - #### protected void visitAnnotation(AnnotationNode node)

      * Visits an individual AnnotationNode, traversing all member expression values. * Subclasses may override to perform custom annotation processing. * *

      Parameters:
        `node` - the annotation node to visit

    - #### public void visitArrayExpression(ArrayExpression expression)

      * Visits an ArrayExpression, traversing element expressions and size expressions. * *

      Parameters:
        `expression` - the array expression

    - #### public void visitAssertStatement(AssertStatement statement)

      * Visits an AssertStatement, invoking the statement hook before parent traversal. * *

      Parameters:
        `statement` - the assert statement to visit

    - #### public void visitBinaryExpression(BinaryExpression expression)

      Visits binary expressions with flow-aware scoping for `&&` / `||` so pattern variables follow Java short-circuit rules (GROOVY-12242 / JEP 394):

      - `a && b` — true-path bindings of `a` are in scope in `b`
      - `a || b` — true-path bindings of `a` are not in scope in `b`; false-path bindings of `a` are
      - `e !instanceof T t` / `!(e instanceof T t)` — pattern declare is isolated on the left of short-circuit ops; only flow-live sets are re-introduced

    - #### public void visitBlockStatement(BlockStatement statement)

      * Visits a BlockStatement, invoking the statement hook before parent traversal. * *

      Parameters:
        `statement` - the block statement to visit

    - #### public void visitCastExpression(CastExpression expression)

      * Visits a CastExpression, traversing the operand expression. * *

      Parameters:
        `expression` - the cast expression

    - #### public void visitCatchStatement(CatchStatement statement)

      * Visits a CatchStatement, processing variable annotations and invoking the statement hook. * *

      Parameters:
        `statement` - the catch statement to visit

    - #### public void visitClass(ClassNode node)

      * Visits a ClassNode, processing its annotations, package, imports, contents, and object initializers. * *

      Parameters:
        `node` - the class node to visit

    - #### public void visitClassExpression(ClassExpression expression)

      * Visits a ClassExpression. No traversal is performed as class expressions contain no child expressions. * *

      Parameters:
        `expression` - the class expression

    - #### public void visitClosureExpression(ClosureExpression expression)

      * Visits a ClosureExpression with annotation processing, traversing parameter annotations * before delegating to parent traversal. * *

      Parameters:
        `expression` - the closure expression to visit

    - #### public void visitConstantExpression(ConstantExpression expression)

      * Visits a ConstantExpression. No traversal is performed as constants contain no child expressions. * *

      Parameters:
        `expression` - the constant expression

    - #### public void visitConstructorCallExpression(ConstructorCallExpression expression)

      * Visits a ConstructorCallExpression, traversing its argument list. * *

      Parameters:
        `call` - the constructor call expression

    - #### protected void visitConstructorOrMethod(MethodNode node, boolean isConstructor)

      * Visits a constructor or method node (implementation detail for both visit methods). * Processes the node's annotations, all parameter annotations, and code block. * *

      Parameters:
        `node` - the method or constructor node *
        `isConstructor` - true if node is a constructor, false if it is a method

    - #### public void visitDeclarationExpression(DeclarationExpression expression)

      * Visits a DeclarationExpression with annotation processing, traversing expression annotations * before delegating to parent traversal. * *

      Parameters:
        `expression` - the declaration expression to visit

    - #### public void visitDoWhileLoop(DoWhileStatement statement)

      Visits a `do`/`while` loop (GROOVY-12242).

      The body runs before the condition, so pattern variables from the condition are not in scope in the body (same as Java). The condition is visited in a nested scope so short-circuit RHS works and pattern names do not leak after the loop. Like visitWhileLoop, there is no after-loop introduction of `whenFalse` bindings.

    - #### public void visitExpressionStatement(ExpressionStatement statement)

      * Visits an ExpressionStatement, invoking the statement hook before parent traversal. * *

      Parameters:
        `statement` - the expression statement to visit

    - #### public void visitField(FieldNode node)

      * Visits a FieldNode, processing its annotations and initial value expression if present. * *

      Parameters:
        `node` - the field node to visit

    - #### public void visitFieldExpression(FieldExpression expression)

      * Visits a FieldExpression. No traversal is performed as field expressions contain no child expressions. * *

      Parameters:
        `expression` - the field expression

    - #### public void visitForLoop(ForStatement statement)

      * Visits a ForStatement, invoking statement hooks and processing loop variable annotations. * *

      Parameters:
        `statement` - the for statement to visit

    - #### public void visitIfElse(IfStatement statement)

      Visits an `if`/`else` statement, establishing correct lexical scopes for JEP 394 `instanceof` pattern variables (GROOVY-12242) and attaching InstanceofFlowBindings metadata so later phases need not re-derive the flow analysis.

      Rules applied (JLS §6.3.2.2 / JEP 394):

      - §6.3.2.2-200-A: `e.whenTrue()` are in scope in the then-block (S).
      - §6.3.2.2-200-B: `e.whenFalse()` are in scope in the else-block (T).
      - §6.3.2.2-200-C-A: if T cannot complete normally and S can, and the var is in `e.whenTrue()`, the var is introduced after the if-else.
      - §6.3.2.2-200-C-B: if S cannot complete normally and T can (or there is no T), and the var is in `e.whenFalse()`, the var is introduced after the if-else.
      In dynamic Groovy, undeclared references resolve to DynamicVariable (runtime MissingPropertyException). `@TypeChecked` enforces the same rules at compile time; both modes share this visitor.

    - #### public void visitMethodCallExpression(MethodCallExpression expression)

      * Visits a MethodCallExpression, traversing the object expression, * method expression, and argument list. * *

      Parameters:
        `call` - the method call expression

    - #### public void visitProperty(PropertyNode node)

      * Visits a PropertyNode, processing its annotations, initial value expression, * and getter/setter blocks if present. * *

      Parameters:
        `node` - the property node to visit

    - #### public void visitPropertyExpression(PropertyExpression expression)

      * Visits a PropertyExpression, traversing the object and property name expressions. * *

      Parameters:
        `expression` - the property expression

    - #### public void visitReturnStatement(ReturnStatement statement)

      * Visits a ReturnStatement, invoking the statement hook before parent traversal. * *

      Parameters:
        `statement` - the return statement to visit

    - #### public void visitSwitch(SwitchStatement statement)

      * Visits a SwitchStatement, invoking the statement hook before parent traversal. * *

      Parameters:
        `statement` - the switch statement to visit

    - #### public void visitTernaryExpression(TernaryExpression expression)

      Visits a ternary / Elvis expression with flow scoping for pattern variables: true-path bindings are in scope in the then-branch; false-path bindings in the else-branch (GROOVY-12242 / JEP 394). Also attaches InstanceofFlowBindings metadata for later phases.

    - #### public void visitVariableExpression(VariableExpression expression)

      * Visits a VariableExpression. No traversal is performed as variable expressions contain no child expressions. * *

      Parameters:
        `expression` - the variable expression

    - #### public void visitWhileLoop(WhileStatement statement)

      Visits a `while` loop with partial JEP 394 flow scoping for `instanceof` pattern variables (GROOVY-12242).

      What is supported (aligned with the if-then rule for the body):

      - Short-circuit visibility inside the condition (`&&` / `||`).
      - `e.whenTrue()` pattern variables are in scope in the loop body.

      Intentional divergence from JLS §6.3.2.3 (while): Groovy does not introduce `e.whenFalse()` after the loop when the body cannot complete normally. Full after-loop introduction would need definite abrupt-completion analysis of every exit path (including `break`/`continue` of nested loops) and is left out for 6.0 — pattern variables never leak past the loop. Documented as a deliberate partial implementation, not an oversight.