RewriteTools.jl

Author willow-ahrens
Popularity
4 Stars
Updated Last
6 Months Ago
Started In
January 2022

RewriteTools

Documentation Build Status

RewriteTools.jl is a utility for term rewriting. RewriteTools.jl is a fork of SymbolicUtils.jl version 1.17, preserving and simplifying only the functionality related to term rewriting. The semantics of matcher and rewriter objects is simplified and more uniform. RewriteTools.jl is intended for use with custom ASTs that have syntax which implements SyntaxInterface.jl.

Installation

julia> using Pkg; Pkg.add("RewriteTools")

Rule-based rewriting

Rewrite rules match and transform an expression. A rule is written using the @rule macro and creates a callable Rule object.

A Simple Example

Here is a simple rewrite rule, that uses the formula for the double angle of the sine function:

using RewriteTools
r1 = @rule :call(sin, :call(*, 2, ~x)) => :(2 * sin($x) * cos($x))
r1(:(sin(2 * z)))

The @rule macro pairs a matcher pattern with its consequent (@rule matcher => consequent). When an expression matches the matcher, it's rewritten to the consequent pattern. This rule signifies: if an expression fits the sin(2x) pattern, it's transformed to 2sin(x)cos(x).

Rewriting

Rewriters are powerful tools in Julia for transforming expressions. They can be composed and chained together to create sophisticated transformations.

Overview of Composing Rewriters

A rewriter is any callable object that takes an expression and returns either a new expression or nothing. Nothing indicates no applicable changes. The RewriteTools.Rewriters module provides several types of rewriters:

  • Empty(): Always returns nothing.
  • Chain(itr): Chains an iterator of rewriters into a single rewriter. Each rewriter is applied in sequence. If a rewriter returns nothing, it's treated as a no-change.
  • RestartedChain(itr): Similar to Chain(itr) but restarts from the first rewriter after a successful application.
  • IfElse(cond, rw1, rw2): Applies rw1 if cond returns true, otherwise rw2.
  • If(cond, rw): Equivalent to IfElse(cond, rw, Empty()).
  • Prewalk(rw): Performs a pre-order traversal of an expression, applying rw at each step. threaded enables multithreading.
  • Postwalk(rw): Post-order traversal, applying rw.
  • Fixpoint(rw): Repeatedly applies rw until no further changes occur.
  • Prestep(rw): Recursively rewrites each node using rw. Only recurses if rw is not nothing.
  • Rewrite(rw): If rw(x) returns nothing, Rewrite returns x instead.
  • Cache(rw): Cache the result of rw.

Required Packages

Used By Packages