Equality saturation with e-graphs
///|
test {
let nonzero : @egg.Analysis[String, Bool] = Analysis(
make=fn(op, children) {
guard children.is_empty() else { return false }
let integer = @string.parse_bigint(op, radix=10) catch {
_ => return false
}
!integer.is_zero()
},
join=(left, right) => left || right,
)
let graph = @egg.EGraph::with_analysis(nonzero)
let root = graph.add(@egg.Expr::parse("(/ (* a 2) 2)"))
let rules = [
@egg.Rewrite(
"shift",
@egg.Pattern::parse("(* ?x 2)"),
@egg.Pattern::parse("(<< ?x 1)"),
),
Rewrite(
"reassociate division",
@egg.Pattern::parse("(/ (* ?x ?y) ?z)"),
@egg.Pattern::parse("(* ?x (/ ?y ?z))"),
),
Rewrite(
"divide nonzero by itself",
@egg.Pattern::parse("(/ ?x ?x)"),
@egg.Pattern::parse("1"),
condition=fn(found, read) {
guard found.get("?x") is Some(id) else { return false }
read(id)
},
),
Rewrite(
"multiply by one",
@egg.Pattern::parse("(* ?x 1)"),
@egg.Pattern::parse("?x"),
),
]
ignore(graph.run(rules))
assert_eq(graph.extract(root).map(best => best.expr.to_sexp()), Some("a"))
}///|
pub fn fold_boolean_constants() -> Bool raise @egg.ParseError {
let analysis : @egg.Analysis[String, Bool] = Analysis(
make=fn(op, children) {
match (op, children) {
("true", []) => true
("and", [left, right]) => left && right
_ => false
}
},
join=(left, right) => left || right,
modify=known => if known { Some(Expr("true")) } else { None },
)
let graph = @egg.EGraph::with_analysis(analysis)
let root = graph.add(@egg.Expr::parse("(and a (and true true))"))
let a = graph.add_node("a")
let literal = graph.add_node("true")
let _ = graph.merge(a, literal)
graph.rebuild()
graph.data(root)
}///|
test {
let graph : @egg.EGraph[String, Unit] = EGraph()
let root = graph.add(@egg.Expr::parse("(+ (+ (+ a b) c) d)"))
let associate = @egg.Rewrite(
"associate addition to the right",
@egg.Pattern::parse("(+ (+ ?x ?y) ?z)"),
@egg.Pattern::parse("(+ ?x (+ ?y ?z))"),
)
ignore(graph.run([associate]))
let best = graph.extract_with_cost(root, cost=(_, children) => {
Some(1UL + children.fold(init=0UL, UInt64::max))
})
assert_eq(best.map(term => term.expr.to_sexp()), Some("(+ (+ a b) (+ c d))"))
}type Analysis[Op, Data]type EGraph[Op, Data]type Pattern[Op]type Rewrite[Op, Data]