Package org.apache.groovy.contracts.ast

# Class LoopInvariantASTTransformation

java.lang.Object
org.apache.groovy.contracts.ast.LoopInvariantASTTransformation

All Implemented Interfaces:
  `CompilationUnitAware`, `ASTTransformation`

public class LoopInvariantASTTransformation extends Object implements ASTTransformation, CompilationUnitAware
Handles `Invariant` annotations placed on loop statements (`for`, `while`, `do-while`). For `for` and `while` loops the invariant closure is evaluated as an assertion at the start of each loop iteration. For `do-while` loops it is evaluated after each body execution instead (GROOVY-12128): the body runs before the first condition check, so the invariant only needs to be established by that first execution — checking it at loop entry would reject valid loops. (A `continue` inside a `do-while` jumps straight to the condition and therefore skips the check for that pass.)

When `@Invariant` is placed on a class (its original usage), this transform returns immediately, letting the existing global contract pipeline handle it.

Example:

     int sum = 0
     @Invariant({ 0 <= i && i <= 4 })
     for (int i in 0..4) {
         sum += i
     }

Since:
  6.0.0
See Also:
  - `Invariant`
  - `LoopInvariantViolation`

- ## Constructor Summary

  Constructors
  Constructor
  Description
  `LoopInvariantASTTransformation()`

- ## Method Summary

  Modifier and Type
  Method
  Description
  `void`
  `setCompilationUnit(CompilationUnit unit)`
  Sets the compilation unit currently applying this transformation.
  `void`
  `visit(ASTNode[] nodes, SourceUnit source)`
  Rewrites a loop-level `Invariant` annotation into assertion checks injected at the start of the loop body.

  ### Methods inherited from class java.lang.Object

  `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- ## Constructor Details

  - ### LoopInvariantASTTransformation

    public LoopInvariantASTTransformation()

- ## Method Details

  - ### setCompilationUnit

    public void setCompilationUnit(CompilationUnit unit)
    Description copied from interface: `CompilationUnitAware`
    Sets the compilation unit currently applying this transformation.
    Specified by:
      `setCompilationUnit` in interface `CompilationUnitAware`
    Parameters:
      `unit` - the active compilation unit

  - ### visit

    public void visit(ASTNode[] nodes, SourceUnit source)
    Rewrites a loop-level `Invariant` annotation into assertion checks injected at the start of the loop body.
    Specified by:
      `visit` in interface `ASTTransformation`
    Parameters:
      `nodes` - the annotated AST nodes supplied by the compiler
      `source` - the current source unit