egglog/
prelude.rs

1//! Rust entry point for egglog.
2//!
3//! ```
4//! use egglog::prelude::*;
5//! ```
6//!
7//! Most workflows are best expressed as an egglog program parsed and
8//! run via [`crate::EGraph::parse_and_run_program`]: declare your
9//! sorts, functions, and rules once in egglog text, then call into
10//! the database from Rust around it.
11//!
12//! ```
13//! use egglog::prelude::*;
14//! let mut eg = EGraph::default();
15//! eg.parse_and_run_program(
16//!     None,
17//!     "(datatype Math (Num i64) (Add Math Math))
18//!      (Add (Num 1) (Num 2))",
19//! )?;
20//! # Ok::<(), egglog::Error>(())
21//! ```
22//!
23//! Three cases need a Rust escape from the language:
24//!
25//! 1. **Driving the e-graph database directly** — building rows,
26//!    looking them up, iterating tables, running ad-hoc queries from
27//!    Rust between (or instead of) running egglog rules.
28//! 2. **Custom rules whose right-hand side runs Rust** — a
29//!    [`rust_rule`] / [`rust_rule_full`] callback fires on every
30//!    match and gets a state handle to read/write the database.
31//!    Useful when the rule body needs arithmetic, control flow, or
32//!    data conversion that's awkward in egglog itself.
33//! 3. **Custom primitives callable from egglog expressions** — new
34//!    functions (e.g. arithmetic on a custom Rust type, an FFI call,
35//!    a cost computation) that you want to invoke from egglog code as
36//!    if they were built-ins. See "Extending egglog" below.
37//!
38//! Cases 1 and 2 share the same surface: the [`crate::Read`] and
39//! [`crate::Write`] capability traits, implemented on the
40//! [`crate::PureState`] / [`crate::ReadState`] / [`crate::WriteState`]
41//! / [`crate::FullState`] wrappers. Inside a rule callback you
42//! receive one of those wrappers directly; outside a rule you get a
43//! [`crate::FullState`] from [`crate::EGraph::update`]:
44//!
45//! ```
46//! use egglog::prelude::*;
47//! let mut eg = EGraph::default();
48//! eg.parse_and_run_program(None, "(function f (i64) i64 :no-merge)")?;
49//!
50//! // Stage writes; flush once when the closure returns.
51//! eg.update(|mut fs| fs.set("f", (1_i64,), 42_i64))?;
52//!
53//! // Read in a separate `update` call — writes inside a closure
54//! // aren't visible to reads in the same closure.
55//! let v = eg.update(|fs| fs.lookup("f", 1_i64))?;
56//! assert_eq!(v.map(|v| eg.value_to_base::<i64>(v)), Some(42));
57//! # Ok::<(), egglog::Error>(())
58//! ```
59//!
60//! ## Adding and reading facts
61//!
62//! Methods on [`crate::Read`] and [`crate::Write`], available via the
63//! state wrappers:
64//!
65//! - [`crate::Write::set`] — write a function-table cell `(set (f k) v)`.
66//! - [`crate::Write::add`] — mint or look up a constructor / relation eclass.
67//! - [`crate::Write::remove`] — remove a row from any subtype.
68//! - [`crate::Write::union`] — union two eclass `Value`s in the union-find.
69//! - [`crate::Read::lookup`] — read a function's output value.
70//! - [`crate::Read::eclass_of`] — read a constructor's eclass without minting.
71//! - [`crate::Read::contains`] — row presence on any subtype.
72//!
73//! ## Iterating and querying
74//!
75//! - [`crate::Read::function_entries`] visits each entry of a function
76//!   table via a callback, exposing `inputs` / `output` as raw `Value`s.
77//! - [`crate::Read::constructor_enodes`] visits each enode of a
78//!   constructor / relation table, exposing `children` / `eclass`.
79//! - [`crate::EGraph::query`] runs a one-shot pattern query and
80//!   returns one `HashMap<String, Value>` per match, keyed by
81//!   variable name. Useful for extracting bindings without compiling
82//!   a persistent rule.
83//!
84//! ## Extracting terms
85//!
86//! Pulling a Rust-side term out of an eclass:
87//!
88//! - [`crate::EGraph::extract_value`] — picks the lowest-cost
89//!   representative under the default tree-additive cost model and
90//!   returns it as a [`crate::TermId`] in a [`crate::TermDag`].
91//! - [`crate::EGraph::extract_best`] / [`crate::EGraph::extract_variants`] —
92//!   extract batches of roots under the default cost model.
93//! - [`crate::EGraph::extract_best_with_cost_model`] /
94//!   [`crate::EGraph::extract_variants_with_cost_model`] — do the same under a
95//!   user-supplied cost model.
96//!
97//! See the [`crate::extract`] module for the full API
98//! ([`crate::extract::TreeExtractor`], variant extraction,
99//! sort-restricted extraction, custom cost types).
100//!
101//! To get the `(sort, Value)` pair an `extract_value` call needs in
102//! the first place, the easiest path is to let-bind a global name in
103//! egglog and then resolve it with [`crate::EGraph::eval_expr`]:
104//!
105//! ```
106//! use egglog::prelude::*;
107//! let mut eg = EGraph::default();
108//! eg.parse_and_run_program(
109//!     None,
110//!     "(datatype Math (Num i64) (Add Math Math))
111//!      (let $root (Add (Num 1) (Num 2)))",
112//! )?;
113//! let (sort, value) = eg.eval_expr(&exprs::var("$root"))?;
114//! let (_dag, _term, _cost) = eg.extract_value(&sort, value)?;
115//! # Ok::<(), egglog::Error>(())
116//! ```
117//!
118//! ## Rules
119//!
120//! - [`rule`] — add a rule whose RHS is egglog code.
121//! - [`rust_rule`] — add a rule whose RHS is a Rust closure
122//!   `Fn(WriteState, &[Value]) -> Option<()>`. Seminaive-safe.
123//! - [`rust_rule_full`] — same but the closure receives a
124//!   [`crate::FullState`] (can read the database in the callback).
125//!   Runs `:naive` since the body sees live state.
126//! - [`run_ruleset`] / [`add_ruleset`] step rules forward.
127//!
128//! ## Extending egglog
129//!
130//! - **Custom sort types:** [`BaseSort`] / [`ContainerSort`].
131//! - **Custom primitives:** implement [`crate::Primitive`] plus one
132//!   of [`crate::PurePrim`] / [`crate::ReadPrim`] /
133//!   [`crate::WritePrim`] / [`crate::FullPrim`] (pick by what the
134//!   body needs to do — pure, read-only, write-only, full). Register
135//!   via the matching `EGraph::add_*_primitive`. The state wrapper
136//!   the body sees enforces what the body can do; see issue #772 for
137//!   the seminaive-safety reasoning.
138//! - **Simple pure primitives:** the [`add_primitive!`] /
139//!   [`add_primitive_with_validator!`] / [`add_literal_prim!`] macros
140//!   cover the "pure native function" case without writing out the
141//!   full trait impl.
142//!
143//! ## Caveat: type unsafety at the column level
144//!
145//! Eclass identifiers flow through the API as bare [`Value`]s. A
146//! `Value` returned from a `Math` constructor and a `Value` returned
147//! from a `List` constructor are indistinguishable at compile time
148//! *and* at runtime — callers track sort identity themselves.
149//! [`crate::Write::union`] does not check that its arguments are the
150//! same eq-sort; [`crate::Write::set`] and [`crate::Write::add`] do
151//! not check that their column values match the table's declared
152//! column sorts. Arity (column count) and subtype (function vs.
153//! constructor) *are* checked at runtime via [`crate::ApiError`].
154
155use crate::*;
156use std::any::{Any, TypeId};
157
158// Re-exports in `prelude` for convenience.
159pub use egglog::ast::{Action, Fact, Facts, GenericActions, RustSpan, Span};
160pub use egglog::sort::{BigIntSort, BigRatSort, BoolSort, F64Sort, I64Sort, StringSort, UnitSort};
161pub use egglog::{CommandMacro, CommandMacroRegistry};
162pub use egglog::{Core, FullState, PureState, Read, ReadState, Write, WriteState};
163pub use egglog::{EGraph, span};
164pub use egglog::{action, actions, datatype, expr, fact, facts, sort, vars};
165
166/// Trait for types that can be converted to/from Literal for use in validated primitives.
167/// This enables automatic validator generation for literal primitives.
168pub trait LiteralConvertible: Sized {
169    fn to_literal(self) -> egglog_ast::generic_ast::Literal;
170    fn from_literal(lit: &egglog_ast::generic_ast::Literal) -> Option<Self>;
171}
172
173impl LiteralConvertible for i64 {
174    fn to_literal(self) -> egglog_ast::generic_ast::Literal {
175        egglog_ast::generic_ast::Literal::Int(self)
176    }
177    fn from_literal(lit: &egglog_ast::generic_ast::Literal) -> Option<Self> {
178        match lit {
179            egglog_ast::generic_ast::Literal::Int(i) => Some(*i),
180            _ => None,
181        }
182    }
183}
184
185impl LiteralConvertible for bool {
186    fn to_literal(self) -> egglog_ast::generic_ast::Literal {
187        egglog_ast::generic_ast::Literal::Bool(self)
188    }
189    fn from_literal(lit: &egglog_ast::generic_ast::Literal) -> Option<Self> {
190        match lit {
191            egglog_ast::generic_ast::Literal::Bool(b) => Some(*b),
192            _ => None,
193        }
194    }
195}
196
197impl LiteralConvertible for ordered_float::OrderedFloat<f64> {
198    fn to_literal(self) -> egglog_ast::generic_ast::Literal {
199        egglog_ast::generic_ast::Literal::Float(self)
200    }
201    fn from_literal(lit: &egglog_ast::generic_ast::Literal) -> Option<Self> {
202        match lit {
203            egglog_ast::generic_ast::Literal::Float(f) => Some(*f),
204            _ => None,
205        }
206    }
207}
208
209impl LiteralConvertible for egglog::sort::F {
210    fn to_literal(self) -> egglog_ast::generic_ast::Literal {
211        egglog_ast::generic_ast::Literal::Float(self.0)
212    }
213    fn from_literal(lit: &egglog_ast::generic_ast::Literal) -> Option<Self> {
214        match lit {
215            egglog_ast::generic_ast::Literal::Float(f) => Some(egglog::sort::F::from(*f)),
216            _ => None,
217        }
218    }
219}
220
221impl LiteralConvertible for egglog::sort::S {
222    fn to_literal(self) -> egglog_ast::generic_ast::Literal {
223        egglog_ast::generic_ast::Literal::String(self.0)
224    }
225    fn from_literal(lit: &egglog_ast::generic_ast::Literal) -> Option<Self> {
226        match lit {
227            egglog_ast::generic_ast::Literal::String(s) => Some(egglog::sort::S::new(s.clone())),
228            _ => None,
229        }
230    }
231}
232
233impl LiteralConvertible for () {
234    fn to_literal(self) -> egglog_ast::generic_ast::Literal {
235        egglog_ast::generic_ast::Literal::Unit
236    }
237    fn from_literal(lit: &egglog_ast::generic_ast::Literal) -> Option<Self> {
238        match lit {
239            egglog_ast::generic_ast::Literal::Unit => Some(()),
240            _ => None,
241        }
242    }
243}
244
245pub mod exprs {
246    use super::*;
247
248    /// Creates a variable expression.
249    pub fn var(name: &str) -> Expr {
250        Expr::Var(span!(), name.to_owned())
251    }
252
253    /// Creates an integer literal expression.
254    pub fn int(value: i64) -> Expr {
255        Expr::Lit(span!(), Literal::Int(value))
256    }
257
258    /// Creates a float literal expression.
259    pub fn float(value: f64) -> Expr {
260        Expr::Lit(span!(), Literal::Float(value.into()))
261    }
262
263    /// Creates a string literal expression.
264    pub fn string(value: &str) -> Expr {
265        Expr::Lit(span!(), Literal::String(value.to_owned()))
266    }
267
268    /// Creates a unit literal expression.
269    pub fn unit() -> Expr {
270        Expr::Lit(span!(), Literal::Unit)
271    }
272
273    /// Creates a boolean literal expression.
274    pub fn bool(value: bool) -> Expr {
275        Expr::Lit(span!(), Literal::Bool(value))
276    }
277
278    /// Creates a function call expression.
279    pub fn call(f: &str, xs: Vec<Expr>) -> Expr {
280        Expr::Call(span!(), f.to_owned(), xs)
281    }
282}
283
284/// Create a new ruleset.
285pub fn add_ruleset(egraph: &mut EGraph, ruleset: &str) -> Result<Vec<CommandOutput>, Error> {
286    egraph.run_program(vec![Command::AddRuleset(span!(), ruleset.to_owned())])
287}
288
289/// Run one iteration of a ruleset.
290pub fn run_ruleset(egraph: &mut EGraph, ruleset: &str) -> Result<Vec<CommandOutput>, Error> {
291    egraph.run_program(vec![Command::RunSchedule(Schedule::Run(
292        span!(),
293        RunConfig {
294            ruleset: ruleset.to_owned(),
295            until: None,
296        },
297    ))])
298}
299
300#[macro_export]
301macro_rules! sort {
302    (BigInt) => {
303        BigIntSort.to_arcsort()
304    };
305    (BigRat) => {
306        BigRatSort.to_arcsort()
307    };
308    (bool) => {
309        BoolSort.to_arcsort()
310    };
311    (f64) => {
312        F64Sort.to_arcsort()
313    };
314    (i64) => {
315        I64Sort.to_arcsort()
316    };
317    (String) => {
318        StringSort.to_arcsort()
319    };
320    (Unit) => {
321        UnitSort.to_arcsort()
322    };
323    ($t:expr) => {
324        $t
325    };
326}
327
328#[macro_export]
329macro_rules! vars {
330    [$($x:ident : $t:tt),* $(,)?] => {
331        &[$((stringify!($x), sort!($t))),*]
332    };
333}
334
335#[macro_export]
336macro_rules! expr {
337    ((unquote $unquoted:expr)) => { $unquoted };
338    (($func:tt $($arg:tt)*)) => { exprs::call(stringify!($func), vec![$(expr!($arg)),*]) };
339    ($value:literal) => { exprs::int($value) };
340    ($quoted:tt) => { exprs::var(stringify!($quoted)) };
341}
342
343#[macro_export]
344macro_rules! fact {
345    ((= $($arg:tt)*)) => { Fact::Eq(span!(), $(expr!($arg)),*) };
346    ($a:tt) => { Fact::Fact(expr!($a)) };
347}
348
349#[macro_export]
350macro_rules! facts {
351    ($($tree:tt)*) => { Facts(vec![$(fact!($tree)),*]) };
352}
353
354#[macro_export]
355macro_rules! action {
356    ((let $name:ident $value:tt)) => {
357        Action::Let(span!(), String::from(stringify!($name)), expr!($value))
358    };
359    ((set ($f:ident $($x:tt)*) $value:tt)) => {
360        Action::Set(span!(), String::from(stringify!($f)), vec![$(expr!($x)),*], expr!($value))
361    };
362    ((delete ($f:ident $($x:tt)*))) => {
363        Action::Change(span!(), Change::Delete, String::from(stringify!($f)), vec![$(expr!($x)),*])
364    };
365    ((subsume ($f:ident $($x:tt)*))) => {
366        Action::Change(span!(), Change::Subsume, String::from(stringify!($f)), vec![$(expr!($x)),*])
367    };
368    ((union $x:tt $y:tt)) => {
369        Action::Union(span!(), expr!($x), expr!($y))
370    };
371    ((panic $message:literal)) => {
372        Action::Panic(span!(), $message.to_owned())
373    };
374    ($x:tt) => {
375        Action::Expr(span!(), expr!($x))
376    };
377}
378
379#[macro_export]
380macro_rules! actions {
381    ($($tree:tt)*) => { GenericActions(vec![$(action!($tree)),*]) };
382}
383
384/// Add a rule to the e-graph whose right-hand side is made up of actions.
385/// ```
386/// use egglog::prelude::*;
387///
388/// let mut egraph = EGraph::default();
389/// egraph.parse_and_run_program(
390///     None,
391///     "
392/// (function fib (i64) i64 :no-merge)
393/// (set (fib 0) 0)
394/// (set (fib 1) 1)
395/// (rule (
396///     (= f0 (fib x))
397///     (= f1 (fib (+ x 1)))
398/// ) (
399///     (set (fib (+ x 2)) (+ f0 f1))
400/// ))
401/// (run 10)
402///     ",
403/// )?;
404///
405/// let big_number = 20;
406///
407/// // check that `(fib 20)` is not in the e-graph
408/// let results = egraph.query(
409///     vars![f: i64],
410///     facts![(= (fib (unquote exprs::int(big_number))) f)],
411/// )?;
412///
413/// assert!(results.is_empty());
414///
415/// let ruleset = "custom_ruleset";
416/// add_ruleset(&mut egraph, ruleset)?;
417///
418/// // add the rule from `build_test_database` to the egraph
419/// rule(
420///     &mut egraph,
421///     ruleset,
422///     facts![
423///         (= f0 (fib x))
424///         (= f1 (fib (+ x 1)))
425///     ],
426///     actions![
427///         (set (fib (+ x 2)) (+ f0 f1))
428///     ],
429/// )?;
430///
431/// // run that rule 10 times
432/// for _ in 0..10 {
433///     run_ruleset(&mut egraph, ruleset)?;
434/// }
435///
436/// // check that `(fib 20)` is now in the e-graph
437/// let results = egraph.query(
438///     vars![f: i64],
439///     facts![(= (fib (unquote exprs::int(big_number))) f)],
440/// )?;
441///
442/// let f: Vec<i64> = results.iter().map(|m| egraph.value_to_base::<i64>(m["f"])).collect();
443/// assert_eq!(f, [6765]);
444///
445/// # Ok::<(), egglog::Error>(())
446/// ```
447pub fn rule(
448    egraph: &mut EGraph,
449    ruleset: &str,
450    facts: Facts<String, String>,
451    actions: Actions,
452) -> Result<Vec<CommandOutput>, Error> {
453    let rule = Rule {
454        span: span!(),
455        head: actions,
456        body: facts.0,
457        name: "".into(),
458        ruleset: ruleset.into(),
459        eval_mode: RuleEvalMode::Seminaive,
460        no_decomp: false,
461        include_subsumed: false,
462    };
463
464    egraph.run_program(vec![Command::Rule { rule }])
465}
466
467#[derive(Clone)]
468struct RustRuleRhs<F>
469where
470    F: for<'a, 'db> Fn(crate::WriteState<'a, 'db>, &[Value]) -> Option<()>
471        + Clone
472        + Send
473        + Sync
474        + 'static,
475{
476    name: String,
477    inputs: Vec<ArcSort>,
478    func: F,
479}
480
481impl<F> Primitive for RustRuleRhs<F>
482where
483    F: for<'a, 'db> Fn(crate::WriteState<'a, 'db>, &[Value]) -> Option<()>
484        + Clone
485        + Send
486        + Sync
487        + 'static,
488{
489    fn name(&self) -> &str {
490        &self.name
491    }
492
493    fn get_type_constraints(&self, span: &Span) -> Box<dyn TypeConstraint> {
494        let sorts: Vec<_> = self
495            .inputs
496            .iter()
497            .chain(once(&UnitSort.to_arcsort()))
498            .cloned()
499            .collect();
500        SimpleTypeConstraint::new(self.name(), sorts, span.clone()).into_box()
501    }
502}
503
504impl<F> WritePrim for RustRuleRhs<F>
505where
506    F: for<'a, 'db> Fn(crate::WriteState<'a, 'db>, &[Value]) -> Option<()>
507        + Clone
508        + Send
509        + Sync
510        + 'static,
511{
512    fn apply<'a, 'db>(&self, state: crate::WriteState<'a, 'db>, values: &[Value]) -> Option<Value> {
513        let unit = state.base_values().get(());
514        (self.func)(state, values)?;
515        Some(unit)
516    }
517}
518
519/// Add a rule to the e-graph whose right-hand side is a Rust callback.
520/// ```
521/// use egglog::prelude::*;
522///
523/// let mut egraph = EGraph::default();
524/// egraph.parse_and_run_program(
525///     None,
526///     "
527/// (function fib (i64) i64 :no-merge)
528/// (set (fib 0) 0)
529/// (set (fib 1) 1)
530/// (rule (
531///     (= f0 (fib x))
532///     (= f1 (fib (+ x 1)))
533/// ) (
534///     (set (fib (+ x 2)) (+ f0 f1))
535/// ))
536/// (run 10)
537///     ",
538/// )?;
539///
540/// let big_number = 20;
541///
542/// // check that `(fib 20)` is not in the e-graph
543/// let results = egraph.query(
544///     vars![f: i64],
545///     facts![(= (fib (unquote exprs::int(big_number))) f)],
546/// )?;
547///
548/// assert!(results.is_empty());
549///
550/// let ruleset = "custom_ruleset";
551/// add_ruleset(&mut egraph, ruleset)?;
552///
553/// // add the rule from `build_test_database` to the egraph
554/// rust_rule(
555///     &mut egraph,
556///     "fib_rule",
557///     ruleset,
558///     vars![x: i64, f0: i64, f1: i64],
559///     facts![
560///         (= f0 (fib x))
561///         (= f1 (fib (+ x 1)))
562///     ],
563///     move |mut ctx, values| {
564///         let [x, f0, f1] = values else { unreachable!() };
565///         let x = ctx.value_to_base::<i64>(*x);
566///         let f0 = ctx.value_to_base::<i64>(*f0);
567///         let f1 = ctx.value_to_base::<i64>(*f1);
568///
569///         let y = ctx.base_to_value::<i64>(x + 2);
570///         let f2 = ctx.base_to_value::<i64>(f0 + f1);
571///         ctx.set("fib", (y,), f2);
572///
573///         Some(())
574///     },
575/// )?;
576///
577/// // run that rule 10 times
578/// for _ in 0..10 {
579///     run_ruleset(&mut egraph, ruleset)?;
580/// }
581///
582/// // check that `(fib 20)` is now in the e-graph
583/// let results = egraph.query(
584///     vars![f: i64],
585///     facts![(= (fib (unquote exprs::int(big_number))) f)],
586/// )?;
587///
588/// let f: Vec<i64> = results.iter().map(|m| egraph.value_to_base::<i64>(m["f"])).collect();
589/// assert_eq!(f, [6765]);
590///
591/// # Ok::<(), egglog::Error>(())
592/// ```
593pub fn rust_rule(
594    egraph: &mut EGraph,
595    rule_name: &str,
596    ruleset: &str,
597    vars: &[(&str, ArcSort)],
598    facts: Facts<String, String>,
599    func: impl for<'a, 'db> Fn(crate::WriteState<'a, 'db>, &[Value]) -> Option<()>
600    + Clone
601    + Send
602    + Sync
603    + 'static,
604) -> Result<Vec<CommandOutput>, Error> {
605    if egraph.are_proofs_enabled() {
606        return Err(Error::ProofsIncompatibleApi {
607            api: "rust_rule",
608            reason: "the rule's RHS is a Rust closure with no proof-encoding validator,\n\
609                     so the proof checker cannot verify what it does.",
610        });
611    }
612    let prim_name = egraph.parser.symbol_gen.fresh("rust_rule_prim");
613    egraph.add_write_primitive(
614        RustRuleRhs {
615            name: prim_name.clone(),
616            inputs: vars.iter().map(|(_, s)| s.clone()).collect(),
617            func,
618        },
619        None,
620    );
621
622    let rule = Rule {
623        span: span!(),
624        head: GenericActions(vec![GenericAction::Expr(
625            span!(),
626            exprs::call(
627                &prim_name,
628                vars.iter().map(|(v, _)| exprs::var(v)).collect(),
629            ),
630        )]),
631        body: facts.0,
632        name: egraph.parser.symbol_gen.fresh(rule_name),
633        ruleset: ruleset.into(),
634        eval_mode: RuleEvalMode::Seminaive,
635        no_decomp: false,
636        include_subsumed: false,
637    };
638
639    egraph.run_program(vec![Command::Rule { rule }])
640}
641
642#[derive(Clone)]
643struct RustRuleFullRhs<F>
644where
645    F: for<'a, 'db> Fn(crate::FullState<'a, 'db>, &[Value]) -> Option<()>
646        + Clone
647        + Send
648        + Sync
649        + 'static,
650{
651    name: String,
652    inputs: Vec<ArcSort>,
653    func: F,
654}
655
656impl<F> Primitive for RustRuleFullRhs<F>
657where
658    F: for<'a, 'db> Fn(crate::FullState<'a, 'db>, &[Value]) -> Option<()>
659        + Clone
660        + Send
661        + Sync
662        + 'static,
663{
664    fn name(&self) -> &str {
665        &self.name
666    }
667
668    fn get_type_constraints(&self, span: &Span) -> Box<dyn TypeConstraint> {
669        let sorts: Vec<_> = self
670            .inputs
671            .iter()
672            .chain(once(&UnitSort.to_arcsort()))
673            .cloned()
674            .collect();
675        SimpleTypeConstraint::new(self.name(), sorts, span.clone()).into_box()
676    }
677}
678
679impl<F> crate::FullPrim for RustRuleFullRhs<F>
680where
681    F: for<'a, 'db> Fn(crate::FullState<'a, 'db>, &[Value]) -> Option<()>
682        + Clone
683        + Send
684        + Sync
685        + 'static,
686{
687    fn apply<'a, 'db>(&self, state: crate::FullState<'a, 'db>, values: &[Value]) -> Option<Value> {
688        let unit = state.base_values().get(());
689        (self.func)(state, values)?;
690        Some(unit)
691    }
692}
693
694/// Like [`rust_rule`], but the action callback receives a [`FullState`]
695/// — it can read tables (`ctx.lookup`) in addition to writing them.
696/// Action callbacks of `FullPrim` are only valid in `Context::Full`,
697/// so this helper marks the generated rule `:naive`: the body matches
698/// against the entire database every iteration instead of using the
699/// seminaive delta. Use this when the action genuinely needs to look
700/// up rows; prefer [`rust_rule`] when the data can be bound via the
701/// matcher in the rule body.
702pub fn rust_rule_full(
703    egraph: &mut EGraph,
704    rule_name: &str,
705    ruleset: &str,
706    vars: &[(&str, ArcSort)],
707    facts: Facts<String, String>,
708    func: impl for<'a, 'db> Fn(crate::FullState<'a, 'db>, &[Value]) -> Option<()>
709    + Clone
710    + Send
711    + Sync
712    + 'static,
713) -> Result<Vec<CommandOutput>, Error> {
714    if egraph.are_proofs_enabled() {
715        return Err(Error::ProofsIncompatibleApi {
716            api: "rust_rule_full",
717            reason: "the rule's RHS is a Rust closure with no proof-encoding validator,\n\
718                     so the proof checker cannot verify what it does.",
719        });
720    }
721    let prim_name = egraph.parser.symbol_gen.fresh("rust_rule_full_prim");
722    egraph.add_full_primitive(
723        RustRuleFullRhs {
724            name: prim_name.clone(),
725            inputs: vars.iter().map(|(_, s)| s.clone()).collect(),
726            func,
727        },
728        None,
729    );
730
731    let rule = Rule {
732        span: span!(),
733        head: GenericActions(vec![GenericAction::Expr(
734            span!(),
735            exprs::call(
736                &prim_name,
737                vars.iter().map(|(v, _)| exprs::var(v)).collect(),
738            ),
739        )]),
740        body: facts.0,
741        name: egraph.parser.symbol_gen.fresh(rule_name),
742        ruleset: ruleset.into(),
743        // FullPrim actions require `Context::Full`; use the safe whole-database
744        // `:naive` path (`:unsafe-seminaive` also gets `Full` but is unsafe).
745        eval_mode: RuleEvalMode::Naive,
746        no_decomp: false,
747        include_subsumed: false,
748    };
749
750    egraph.run_program(vec![Command::Rule { rule }])
751}
752
753/// Declare a new sort.
754pub fn add_sort(egraph: &mut EGraph, name: &str) -> Result<Vec<CommandOutput>, Error> {
755    egraph.run_program(vec![Command::Sort {
756        span: span!(),
757        name: name.to_owned(),
758        presort_and_args: None,
759        uf: None,
760        proof_func: None,
761        container_rebuild: None,
762        proof_constructors: None,
763        unionable: true,
764    }])
765}
766
767/// Declare a new function table.
768pub fn add_function(
769    egraph: &mut EGraph,
770    name: &str,
771    schema: Schema,
772    merge: Option<GenericExpr<String, String>>,
773) -> Result<Vec<CommandOutput>, Error> {
774    egraph.run_program(vec![Command::Function {
775        span: span!(),
776        name: name.to_owned(),
777        schema,
778        merge,
779        hidden: false,
780        let_binding: false,
781        term_constructor: None,
782        unextractable: false,
783    }])
784}
785
786/// Declare a new constructor table.
787pub fn add_constructor(
788    egraph: &mut EGraph,
789    name: &str,
790    schema: Schema,
791    cost: Option<DefaultCost>,
792    unextractable: bool,
793) -> Result<Vec<CommandOutput>, Error> {
794    egraph.run_program(vec![Command::Constructor {
795        span: span!(),
796        name: name.to_owned(),
797        schema,
798        cost,
799        unextractable,
800        hidden: false,
801        let_binding: false,
802        term_constructor: None,
803    }])
804}
805
806/// Declare a new relation table.
807pub fn add_relation(
808    egraph: &mut EGraph,
809    name: &str,
810    inputs: Vec<String>,
811) -> Result<Vec<CommandOutput>, Error> {
812    egraph.run_program(vec![Command::Relation {
813        span: span!(),
814        name: name.to_owned(),
815        inputs,
816    }])
817}
818
819/// Adds sorts and constructor tables to the database.
820#[macro_export]
821macro_rules! datatype {
822    ($egraph:expr, (datatype $sort:ident $(($name:ident $($args:ident)* $(:cost $cost:expr)?))*)) => {
823        add_sort($egraph, stringify!($sort))?;
824        $(add_constructor(
825            $egraph,
826            stringify!($name),
827            Schema {
828                input: vec![$(stringify!($args).to_owned()),*],
829                output: stringify!($sort).to_owned(),
830            },
831            [$($cost)*].first().copied(),
832            false,
833        )?;)*
834    };
835}
836
837/// A "default" implementation of [`Sort`] for simple types
838/// which just want to put some data in the e-graph. If you
839/// implement this trait, do not implement `Sort` or
840/// `ContainerSort. Use `add_base_sort` to register base
841/// sorts with the `EGraph`. See `Sort` for documentation
842/// of the methods. Do not override `to_arcsort`.
843pub trait BaseSort: Any + Send + Sync + Debug {
844    type Base: BaseValue;
845    fn name(&self) -> &str;
846    fn register_primitives(&self, _eg: &mut EGraph) {}
847    fn reconstruct_termdag(&self, _: &BaseValues, _: Value, _: &mut TermDag) -> TermId;
848
849    fn to_arcsort(self) -> ArcSort
850    where
851        Self: Sized,
852    {
853        Arc::new(BaseSortImpl(self))
854    }
855}
856
857#[derive(Debug)]
858struct BaseSortImpl<T: BaseSort>(T);
859
860impl<T: BaseSort> Sort for BaseSortImpl<T> {
861    fn name(&self) -> &str {
862        self.0.name()
863    }
864
865    fn column_ty(&self, backend: &egglog_bridge::EGraph) -> ColumnTy {
866        ColumnTy::Base(backend.base_values().get_ty::<T::Base>())
867    }
868
869    fn register_type(&self, backend: &mut egglog_bridge::EGraph) {
870        backend.base_values_mut().register_type::<T::Base>();
871    }
872
873    fn value_type(&self) -> Option<TypeId> {
874        Some(TypeId::of::<T::Base>())
875    }
876
877    fn as_arc_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync + 'static> {
878        self
879    }
880
881    fn register_primitives(self: Arc<Self>, eg: &mut EGraph) {
882        self.0.register_primitives(eg)
883    }
884
885    /// Reconstruct a leaf base value in a TermDag
886    fn reconstruct_termdag_base(
887        &self,
888        base_values: &BaseValues,
889        value: Value,
890        termdag: &mut TermDag,
891    ) -> TermId {
892        self.0.reconstruct_termdag(base_values, value, termdag)
893    }
894}
895
896/// A "default" implementation of [`Sort`] for types which
897/// just want to store a pure data structure in the e-graph.
898/// If you implement this trait, do not implement `Sort` or
899/// `BaseSort`. Use `add_container_sort` to register container
900/// sorts with the `EGraph`. See `Sort` for documentation
901/// of the methods. Do not override `to_arcsort`.
902pub trait ContainerSort: Any + Send + Sync + Debug {
903    type Container: ContainerValue;
904    fn name(&self) -> &str;
905    fn is_eq_container_sort(&self) -> bool;
906    fn inner_sorts(&self) -> Vec<ArcSort>;
907    fn inner_values(&self, _: &ContainerValues, _: Value) -> Vec<(ArcSort, Value)>;
908    fn register_primitives(&self, _eg: &mut EGraph) {}
909    fn reconstruct_termdag(
910        &self,
911        _: &ContainerValues,
912        _: Value,
913        _: &mut TermDag,
914        _: Vec<TermId>,
915    ) -> TermId;
916    fn serialized_name(&self, container_values: &ContainerValues, value: Value) -> String;
917
918    /// Optional: a container that supports proofs returns its canonical
919    /// constructor head and the validator that canonicalizes its term form (e.g.
920    /// `set-of` sorts and dedups). `None` (the default) means proofs are
921    /// unsupported for this container. See [`Sort::rebuild_container_normalizer`].
922    fn rebuild_container_normalizer(&self) -> Option<(String, PrimitiveValidator)> {
923        None
924    }
925
926    fn to_arcsort(self) -> ArcSort
927    where
928        Self: Sized,
929    {
930        Arc::new(ContainerSortImpl(self))
931    }
932}
933
934#[derive(Debug)]
935struct ContainerSortImpl<T: ContainerSort>(T);
936
937impl<T: ContainerSort> Sort for ContainerSortImpl<T> {
938    fn name(&self) -> &str {
939        self.0.name()
940    }
941
942    fn column_ty(&self, _backend: &egglog_bridge::EGraph) -> ColumnTy {
943        ColumnTy::Id
944    }
945
946    fn register_type(&self, backend: &mut egglog_bridge::EGraph) {
947        backend.register_container_ty::<T::Container>();
948    }
949
950    fn value_type(&self) -> Option<TypeId> {
951        Some(TypeId::of::<T::Container>())
952    }
953
954    fn as_arc_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync + 'static> {
955        self
956    }
957
958    fn inner_sorts(&self) -> Vec<ArcSort> {
959        self.0.inner_sorts()
960    }
961
962    fn inner_values(
963        &self,
964        container_values: &ContainerValues,
965        value: Value,
966    ) -> Vec<(ArcSort, Value)> {
967        self.0.inner_values(container_values, value)
968    }
969
970    fn is_container_sort(&self) -> bool {
971        true
972    }
973
974    fn is_eq_container_sort(&self) -> bool {
975        self.0.is_eq_container_sort()
976    }
977
978    fn serialized_name(&self, container_values: &ContainerValues, value: Value) -> String {
979        self.0.serialized_name(container_values, value)
980    }
981
982    fn register_primitives(self: Arc<Self>, eg: &mut EGraph) {
983        self.0.register_primitives(eg);
984    }
985
986    fn reconstruct_termdag_container(
987        &self,
988        container_values: &ContainerValues,
989        value: Value,
990        termdag: &mut TermDag,
991        element_terms: Vec<TermId>,
992    ) -> TermId {
993        self.0
994            .reconstruct_termdag(container_values, value, termdag, element_terms)
995    }
996
997    fn rebuild_container_normalizer(&self) -> Option<(String, PrimitiveValidator)> {
998        self.0.rebuild_container_normalizer()
999    }
1000}
1001
1002/// Add a [`BaseSort`] to the e-graph
1003pub fn add_base_sort(
1004    egraph: &mut EGraph,
1005    base_sort: impl BaseSort,
1006    span: Span,
1007) -> Result<(), TypeError> {
1008    egraph.add_sort(BaseSortImpl(base_sort), span)
1009}
1010
1011pub fn add_container_sort(
1012    egraph: &mut EGraph,
1013    container_sort: impl ContainerSort,
1014    span: Span,
1015) -> Result<(), TypeError> {
1016    egraph.add_sort(ContainerSortImpl(container_sort), span)
1017}
1018
1019#[cfg(test)]
1020mod tests {
1021    use super::*;
1022
1023    fn build_test_database() -> Result<EGraph, Error> {
1024        let mut egraph = EGraph::default();
1025        egraph.parse_and_run_program(
1026            None,
1027            "
1028(function fib (i64) i64 :no-merge)
1029(set (fib 0) 0)
1030(set (fib 1) 1)
1031(rule (
1032    (= f0 (fib x))
1033    (= f1 (fib (+ x 1)))
1034) (
1035    (set (fib (+ x 2)) (+ f0 f1))
1036))
1037(run 10)
1038        ",
1039        )?;
1040        Ok(egraph)
1041    }
1042
1043    #[test]
1044    fn rust_api_query() -> Result<(), Error> {
1045        let mut egraph = build_test_database()?;
1046
1047        let results = egraph.query(
1048            vars![x: i64, y: i64],
1049            facts![
1050                (= (fib x) y)
1051                (= y 13)
1052            ],
1053        )?;
1054
1055        assert_eq!(results.len(), 1);
1056        assert_eq!(egraph.value_to_base::<i64>(results[0]["x"]), 7);
1057        assert_eq!(egraph.value_to_base::<i64>(results[0]["y"]), 13);
1058
1059        Ok(())
1060    }
1061
1062    #[test]
1063    fn rust_api_rule() -> Result<(), Error> {
1064        let mut egraph = build_test_database()?;
1065
1066        let big_number = 20;
1067
1068        // check that `(fib 20)` is not in the e-graph
1069        let results = egraph.query(
1070            vars![f: i64],
1071            facts![(= (fib (unquote exprs::int(big_number))) f)],
1072        )?;
1073
1074        assert!(results.is_empty());
1075
1076        let ruleset = "custom_ruleset";
1077        add_ruleset(&mut egraph, ruleset)?;
1078
1079        // add the rule from `build_test_database` to the egraph
1080        rule(
1081            &mut egraph,
1082            ruleset,
1083            facts![
1084                (= f0 (fib x))
1085                (= f1 (fib (+ x 1)))
1086            ],
1087            actions![
1088                (set (fib (+ x 2)) (+ f0 f1))
1089            ],
1090        )?;
1091
1092        // run that rule 10 times
1093        for _ in 0..10 {
1094            run_ruleset(&mut egraph, ruleset)?;
1095        }
1096
1097        // check that `(fib 20)` is now in the e-graph
1098        let results = egraph.query(
1099            vars![f: i64],
1100            facts![(= (fib (unquote exprs::int(big_number))) f)],
1101        )?;
1102
1103        assert_eq!(results.len(), 1);
1104        assert_eq!(egraph.value_to_base::<i64>(results[0]["f"]), 6765);
1105
1106        Ok(())
1107    }
1108
1109    #[test]
1110    fn rust_api_macros() -> Result<(), Error> {
1111        let mut egraph = build_test_database()?;
1112
1113        datatype!(&mut egraph, (datatype Expr (One) (Two Expr Expr :cost 10)));
1114
1115        let ruleset = "custom_ruleset";
1116        add_ruleset(&mut egraph, ruleset)?;
1117
1118        rule(
1119            &mut egraph,
1120            ruleset,
1121            facts![
1122                (fib 5)
1123                (fib x)
1124                (= f1 (fib (+ x 1)))
1125                (= 3 (unquote exprs::int(1 + 2)))
1126            ],
1127            actions![
1128                (let y (+ x 2))
1129                (set (fib (+ x 2)) (+ f1 f1))
1130                (delete (fib 0))
1131                (subsume (Two (One) (One)))
1132                (union (One) (Two (One) (One)))
1133                (panic "message")
1134                (+ 6 87)
1135            ],
1136        )?;
1137
1138        Ok(())
1139    }
1140
1141    #[test]
1142    fn rust_api_rust_rule() -> Result<(), Error> {
1143        let mut egraph = build_test_database()?;
1144
1145        let big_number = 20;
1146
1147        // check that `(fib 20)` is not in the e-graph
1148        let results = egraph.query(
1149            vars![f: i64],
1150            facts![(= (fib (unquote exprs::int(big_number))) f)],
1151        )?;
1152
1153        assert!(results.is_empty());
1154
1155        let ruleset = "custom_ruleset";
1156        add_ruleset(&mut egraph, ruleset)?;
1157
1158        // add the rule from `build_test_database` to the egraph
1159        rust_rule(
1160            &mut egraph,
1161            "demo_rule",
1162            ruleset,
1163            vars![x: i64, f0: i64, f1: i64],
1164            facts![
1165                (= f0 (fib x))
1166                (= f1 (fib (+ x 1)))
1167            ],
1168            move |mut ctx, values| {
1169                let [x, f0, f1] = values else { unreachable!() };
1170                let x = ctx.value_to_base::<i64>(*x);
1171                let f0 = ctx.value_to_base::<i64>(*f0);
1172                let f1 = ctx.value_to_base::<i64>(*f1);
1173
1174                ctx.set("fib", (x + 2,), f0 + f1).ok()?;
1175
1176                Some(())
1177            },
1178        )?;
1179
1180        // run that rule 10 times
1181        for _ in 0..10 {
1182            run_ruleset(&mut egraph, ruleset)?;
1183        }
1184
1185        // check that `(fib 20)` is now in the e-graph
1186        let results = egraph.query(
1187            vars![f: i64],
1188            facts![(= (fib (unquote exprs::int(big_number))) f)],
1189        )?;
1190
1191        assert_eq!(results.len(), 1);
1192        assert_eq!(egraph.value_to_base::<i64>(results[0]["f"]), 6765);
1193
1194        Ok(())
1195    }
1196}