CommonSubexpressionElimination

scalus.uplc.transform.CommonSubexpressionElimination
See theCommonSubexpressionElimination companion object
class CommonSubexpressionElimination(logger: Logger = ...) extends Optimizer

Common Subexpression Elimination (CSE) for UPLC terms.

Identifies duplicated subexpressions and hoists them into shared let-bindings (encoded as Apply(LamAbs(name, body), expr)). This reduces on-chain execution budget by avoiding redundant computation.

==Algorithm==

Adapted from the Plutus CSE (3-pass path-based algorithm):

  1. '''Count pass''': Traverse the term, assigning unique path IDs at evaluation boundaries (LamAbs, Delay, Case branches). Count (TermKey, Path) -> occurrences pairs. Track which variables are introduced at each path segment.
  2. '''Merge & filter''': Merge counts to common ancestor paths and filter to candidates with total count >= 2 that are not work-free. Verify that all free variables of the candidate are in scope at the bind path.
  3. '''Substitute pass''': For each candidate (largest first), replace occurrences with a fresh variable and insert Apply(LamAbs(freshName, body), candidate) at the bind point.

==Safety==

  • Work-free terms (Var, Const, LamAbs, Delay, Builtin, unsaturated builtins) are never extracted
  • Error terms are never extracted
  • Bare Force(Builtin(...)) patterns are skipped (handled by ForcedBuiltinsExtractor)
  • CSE does not hoist expressions past lambdas that bind their free variables
  • CSE does not hoist across evaluation boundaries, preserving evaluation order

Value parameters

logger

Logger for tracking CSE operations

Attributes

See also
Companion
object
Graph
Supertypes
trait Optimizer
class Object
trait Matchable
class Any

Members list

Value members

Concrete methods

def apply(term: Term): Term

Applies the optimization to a UPLC term.

Applies the optimization to a UPLC term.

Value parameters

term

The UPLC term to optimize

Attributes

Returns

The optimized UPLC term, semantically equivalent to the input

def logs: Seq[String]

Returns the log messages from optimization operations.

Returns the log messages from optimization operations.

Each log entry describes an optimization that was applied, useful for debugging and understanding the optimization process.

Attributes

Returns

Sequence of log messages describing applied optimizations