1use crate::*;
156use std::any::{Any, TypeId};
157
158pub 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
166pub 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 pub fn var(name: &str) -> Expr {
250 Expr::Var(span!(), name.to_owned())
251 }
252
253 pub fn int(value: i64) -> Expr {
255 Expr::Lit(span!(), Literal::Int(value))
256 }
257
258 pub fn float(value: f64) -> Expr {
260 Expr::Lit(span!(), Literal::Float(value.into()))
261 }
262
263 pub fn string(value: &str) -> Expr {
265 Expr::Lit(span!(), Literal::String(value.to_owned()))
266 }
267
268 pub fn unit() -> Expr {
270 Expr::Lit(span!(), Literal::Unit)
271 }
272
273 pub fn bool(value: bool) -> Expr {
275 Expr::Lit(span!(), Literal::Bool(value))
276 }
277
278 pub fn call(f: &str, xs: Vec<Expr>) -> Expr {
280 Expr::Call(span!(), f.to_owned(), xs)
281 }
282}
283
284pub 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
289pub 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
384pub 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
519pub 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
694pub 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 eval_mode: RuleEvalMode::Naive,
746 no_decomp: false,
747 include_subsumed: false,
748 };
749
750 egraph.run_program(vec![Command::Rule { rule }])
751}
752
753pub 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
767pub 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
786pub 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
806pub 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#[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
837pub 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 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
896pub 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 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
1002pub 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 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 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 for _ in 0..10 {
1094 run_ruleset(&mut egraph, ruleset)?;
1095 }
1096
1097 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 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 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 for _ in 0..10 {
1182 run_ruleset(&mut egraph, ruleset)?;
1183 }
1184
1185 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}