catlog/
egglog_util.rs

1//! Utilities for working with e-graphs as implemented in egglog.
2
3use egglog::ast::{Actions, Command, Expr};
4use egglog::{Error, prelude::*};
5
6/// Extension trait for [`EGraph`] with convenience methods.
7pub trait EGraphUtils {
8    /// Runs a single action on the e-graph.
9    fn run_action(&mut self, action: Action) -> Result<(), Error>;
10
11    /// Runs multiple actions on the e-graph.
12    fn run_actions(&mut self, actions: Actions) -> Result<(), Error>;
13
14    /// Checks equality of two expressions in e-graph.
15    fn check_equal(&mut self, lhs: Expr, rhs: Expr) -> Result<bool, Error>;
16}
17
18impl EGraphUtils for EGraph {
19    fn run_action(&mut self, action: Action) -> Result<(), Error> {
20        self.run_program(vec![Command::Action(action)])?;
21        Ok(())
22    }
23
24    fn run_actions(&mut self, actions: Actions) -> Result<(), Error> {
25        let commands = actions.0.into_iter().map(Command::Action).collect();
26        self.run_program(commands)?;
27        Ok(())
28    }
29
30    fn check_equal(&mut self, lhs: Expr, rhs: Expr) -> Result<bool, Error> {
31        let result = self.run_program(vec![Command::Check(
32            span!(),
33            vec![fact!((= (unquote lhs) (unquote rhs)))],
34        )]);
35        match result {
36            Ok(_) => Ok(true),
37            Err(Error::CheckError(_, _)) => Ok(false),
38            Err(error) => Err(error),
39        }
40    }
41}