egg

    Equality saturation with e-graphs

    Download zip
    Author
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    2 hours ago
    Downloads
    2

    No dependencies

    #egg for MoonBit

    A small equality saturation library based on egg: Fast and Extensible Equality Saturation. An e-graph stores equivalent expressions in e-classes. Rewrites add alternatives, and extraction picks an inexpensive expression from the resulting graph.

    #Simplify an expression

    In the paper's Figure 2, rewriting (* a 2) as a shift can hide the opportunity to cancel the division. Both forms remain available in the e-graph, so the cancellation can still produce a. The rule (/ ?x ?x) → 1 uses moonbitlang/core/string to recognize nonzero integer literals.

    ///|
    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"))
    }

    These rules use the algebra in Figure 2. Choose rules that preserve equality in your expression language. String operators support prefix S-expressions and double-quoted symbols. An unquoted leaf beginning with ? and followed by a name is a pattern variable. Use Expr(...), Pattern::node, and Pattern::variable for operators of any type implementing Eq and Hash. Keep their equality and hash stable after insertion.

    #Fold constants with an e-class analysis

    The analysis interface follows Section 4 of the paper. This example tracks whether an e-class denotes Boolean true. Its make computes that fact from a node and its child facts. The join takes the logical OR of facts from equivalent nodes. When a class is known to be true, modify adds the literal true to it.

    ///|
    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)
    }

    After the merge and rebuild, fold_boolean_constants() returns true.

    Use an associative, commutative, idempotent join and a monotone make. The term returned by modify must be equivalent to its class. Use immutable facts and ensure the analysis reaches a fixed point. To read facts during matching, pass a condition to Rewrite(...). It receives the match and a function that reads an e-class's fact.

    #Rebuilding and extraction

    • add interns nodes by operator and child class IDs. merge unions two classes and queues parent nodes whose child IDs may have changed. rebuild repairs those nodes in batches and propagates analysis facts until both worklists empty.
    • Pass IDs back to the graph that issued them. After manual merges, call rebuild before reading transitive congruence or final analysis facts. Pattern::search, EGraph::run, and EGraph::extract rebuild automatically.
    • Each round of run searches all rules on a stable graph, applies their matches, then rebuilds. It reports saturation, the iteration limit, or the node limit. The node limit is a threshold checked between complete rewrites and rebuilds, so one rewrite or analysis pass can overshoot it.
    • extract minimizes the sum of operator weights in the expression tree. The default weight is one. Pass a stable weight function for a custom cost. The result is None if the minimum cost exceeds UInt64.

    #Extract a balanced sum

    Associativity makes a balanced sum available in the graph. Use extract_with_cost to minimize tree depth by adding one to the largest child cost.

    ///|
    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))"))
    }

    Use moon check to check the examples and moon test to run the library tests.

    #Package layout

    • Yoorkin/egg is the application entry point. It owns expressions, patterns, rewrite rules, and the saturation runner.
    • Yoorkin/egg/graph holds e-classes, congruence rebuilding, analysis propagation, e-matching, and the cost search used by extraction.
    • internal/sexp implements the shared S-expression syntax. Integration tests live in tests/ and import the root package.

    ENode

    using @Yoorkin/egg/graph { type ENode }

    An operator applied to e-classes.
    using @Yoorkin/egg/graph { type Id }

    An e-class identifier issued by one graph. Use it only with that graph.

    ParseError

    pub(all) suberror ParseError {
    InvalidSyntax(position~ : Int, String)
    } derive(Eq,
    Debug
    )

    The position is a zero-based offset in Unicode code points.

    RewriteError

    pub(all) suberror RewriteError {
    UnboundVariable(String)
    } derive(Eq,
    Debug
    )

    Analysis

    type Analysis[Op, Data]

    An e-class analysis computes a fact for each node and joins facts in each equivalence class. The optional modify function supplies an equivalent term.

    Analysis::Analysis

    #alias(new)
    fn[Op, Data] Analysis::Analysis(make~ : (Op, ReadOnlyArray[Data]) -> Data, join~ : (Data, Data) -> Data, modify? : (Data) -> Expr[Op]?) -> Analysis[Op, Data]

    Use a monotone make and an associative, commutative, idempotent join. Modify must be idempotent at a fixed fact and the analysis must converge.

    EGraph

    type EGraph[Op, Data]

    An e-graph with an optional e-class analysis.

    EGraph::EGraph

    #alias(new)
    fn[Op : Hash + Eq] EGraph::EGraph() -> EGraph[Op, Unit]

    EGraph::add

    fn[Op : Hash + Eq, Data] EGraph::add(self : EGraph[Op, Data], expr : Expr[Op]) ->
    Id

    Add a finite expression and return its root class.

    EGraph::add_node

    fn[Op : Hash + Eq, Data] EGraph::add_node(self : EGraph[Op, Data], op : Op, children? : ArrayView[
    Id
    ]) ->
    Id

    Add an operator applied to existing classes and return its class.

    EGraph::class_count

    fn[Op, Data] EGraph::class_count(self : EGraph[Op, Data]) -> Int

    EGraph::data

    fn[Op, Data] EGraph::data(self : EGraph[Op, Data], id :
    Id
    ) -> Data

    Read the class's analysis fact. Call rebuild to finish propagating updates.

    EGraph::equivalent

    fn[Op, Data] EGraph::equivalent(self : EGraph[Op, Data], left :
    Id
    , right :
    Id
    ) -> Bool

    Test whether two identifiers belong to the same class. Call rebuild first to account for indirect equalities implied by recent merges.

    EGraph::extract

    fn[Op : Hash + Eq, Data : Eq] EGraph::extract(self : EGraph[Op, Data], root :
    Id
    , weight? : (Op) -> UInt64) -> Extraction[Op]?

    Extract a cheapest finite expression under additive operator weights. The default weight of one minimizes the number of nodes in the expression tree. Weights must be stable. Returns None if the minimum overflows UInt64.

    EGraph::extract_with_cost

    fn[Op : Hash + Eq, Data : Eq] EGraph::extract_with_cost(self : EGraph[Op, Data], root :
    Id
    , cost~ : (Op, ArrayView[UInt64]) -> UInt64?) -> Extraction[Op]?

    Extract a cheapest finite expression using the operator and child costs. The callback receives child costs in operand order for the duration of the call. The cost must be stable, nondecreasing in each child cost, and at least as large as each child cost. Return None for an unrepresentable cost.

    EGraph::find

    fn[Op, Data] EGraph::find(self : EGraph[Op, Data], id :
    Id
    ) ->
    Id

    Find the canonical identifier using path halving.

    EGraph::merge

    fn[Op, Data : Eq] EGraph::merge(self : EGraph[Op, Data], left :
    Id
    , right :
    Id
    ) -> Bool

    Assert that two classes are equivalent. Return whether the classes merged. Rebuild after a batch of merges to propagate congruence and analysis facts.

    EGraph::node_count

    fn[Op, Data] EGraph::node_count(self : EGraph[Op, Data]) -> Int

    Return the number of e-nodes. Rebuild removes any pending duplicates.

    EGraph::nodes

    fn[Op, Data] EGraph::nodes(self : EGraph[Op, Data], id :
    Id
    ) -> ReadOnlyArray[
    ENode
    [Op]]

    View the nodes of a class. Call rebuild to canonicalize every child.

    EGraph::rebuild

    fn[Op : Hash + Eq, Data : Eq] EGraph::rebuild(self : EGraph[Op, Data]) -> Unit

    Restore congruence and propagate analysis facts to a fixed point.

    EGraph::run

    fn[Op : Hash + Eq, Data : Eq] EGraph::run(self : EGraph[Op, Data], rules : ArrayView[Rewrite[Op, Data]], iteration_limit? : Int, node_limit? : Int) -> RunResult

    Search every rule on a stable graph, apply the matches, then rebuild once per round. Check the node threshold after each rewrite and rebuild.

    EGraph::with_analysis

    fn[Op : Hash + Eq, Data] EGraph::with_analysis(analysis : Analysis[Op, Data]) -> EGraph[Op, Data]

    Expr

    type Expr[Op] derive(Eq,
    Debug
    )

    A finite expression over a caller-defined set of operators.

    Expr::Expr

    #alias(new)
    fn[Op] Expr::Expr(op : Op, children? : ArrayView[Expr[Op]]) -> Expr[Op]

    Expr::children

    fn[Op] Expr::children(self : Expr[Op]) -> ReadOnlyArray[Expr[Op]]

    Expr::op

    fn[Op] Expr::op(self : Expr[Op]) -> Op

    Expr::parse

    fn Expr::parse(input : String) -> Expr[String] raise ParseError

    Parse a single expression in prefix S-expression notation.

    Expr::to_sexp

    fn Expr::to_sexp(self : Expr[String]) -> String

    Render a string expression in S-expression notation.

    Extraction

    pub struct Extraction[Op] {
    cost : UInt64
    expr : Expr[Op]
    } derive(Eq,
    Debug
    )

    Match

    pub struct Match {
    eclass :
    Id

    // private fields
    }

    Match::get

    fn Match::get(self : Match, name : String) ->
    Id
    ?

    Read the class bound to a variable by name.

    Pattern

    type Pattern[Op]

    A pattern matches operators and binds variables to e-classes.

    Pattern::node

    fn[Op] Pattern::node(op : Op, children? : ArrayView[Pattern[Op]]) -> Pattern[Op]

    Pattern::parse

    fn Pattern::parse(input : String) -> Pattern[String] raise ParseError

    Parse a pattern. An unquoted leaf such as ?x binds that exact variable name.

    Pattern::search

    fn[Op : Hash + Eq, Data : Eq] Pattern::search(self : Pattern[Op], graph : EGraph[Op, Data]) -> Array[Match]

    Search all classes after rebuilding the graph.

    Pattern::variable

    fn[Op] Pattern::variable(name : String) -> Pattern[Op]

    Rewrite

    type Rewrite[Op, Data]

    A directed rule that adds an equivalent expression for each match.

    Rewrite::Rewrite

    #alias(new)
    fn[Op, Data] Rewrite::Rewrite(name : String, lhs : Pattern[Op], rhs : Pattern[Op], condition? : (Match, (
    Id
    ) -> Data) -> Bool) -> Rewrite[Op, Data] raise RewriteError

    Every right-hand variable must occur on the left. The optional condition reads analysis facts from the graph at the start of the saturation round.

    Rewrite::name

    fn[Op, Data] Rewrite::name(self : Rewrite[Op, Data]) -> String

    RunResult

    pub struct RunResult {
    iterations : Int
    reason : StopReason
    } derive(Eq,
    Debug
    )

    StopReason

    pub(all) enum StopReason {
    Saturated
    IterationLimit
    NodeLimit
    } derive(Eq,
    Debug
    )