| 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.
julia> using Pkg; Pkg.add("RewriteTools")Rewrite rules match and transform an expression. A rule is written using the @rule macro and creates a callable Rule object.
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).
Rewriters are powerful tools in Julia for transforming expressions. They can be composed and chained together to create sophisticated transformations.
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 returnsnothing.Chain(itr): Chains an iterator of rewriters into a single rewriter. Each rewriter is applied in sequence. If a rewriter returnsnothing, it's treated as a no-change.RestartedChain(itr): Similar toChain(itr)but restarts from the first rewriter after a successful application.IfElse(cond, rw1, rw2): Appliesrw1ifcondreturns true, otherwiserw2.If(cond, rw): Equivalent toIfElse(cond, rw, Empty()).Prewalk(rw): Performs a pre-order traversal of an expression, applyingrwat each step.threadedenables multithreading.Postwalk(rw): Post-order traversal, applyingrw.Fixpoint(rw): Repeatedly appliesrwuntil no further changes occur.Prestep(rw): Recursively rewrites each node usingrw. Only recurses ifrwis not nothing.Rewrite(rw): Ifrw(x)returnsnothing,Rewritereturnsxinstead.Cache(rw): Cache the result of rw.