egglog_ast/
generic_ast_helpers.rs

1use std::fmt::{Display, Formatter};
2use std::hash::Hash;
3
4use ordered_float::OrderedFloat;
5
6use super::util::ListDisplay;
7use crate::generic_ast::*;
8use crate::span::Span;
9
10// Macro to implement From conversions for Literal types
11macro_rules! impl_from {
12    ($ctor:ident($t:ty)) => {
13        impl From<Literal> for $t {
14            fn from(literal: Literal) -> Self {
15                match literal {
16                    Literal::$ctor(t) => t,
17                    #[allow(unreachable_patterns)]
18                    _ => panic!("Expected {}, got {literal}", stringify!($ctor)),
19                }
20            }
21        }
22
23        impl From<$t> for Literal {
24            fn from(t: $t) -> Self {
25                Literal::$ctor(t)
26            }
27        }
28    };
29}
30
31pub const INTERNAL_SYMBOL_PREFIX: &str = "@";
32
33impl<Head: Display, Leaf: Display> Display for GenericRule<Head, Leaf>
34where
35    Head: Clone + Display,
36    Leaf: Clone + PartialEq + Eq + Display + Hash,
37{
38    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
39        let indent = " ".repeat(7);
40        write!(f, "(rule (")?;
41        for (i, fact) in self.body.iter().enumerate() {
42            if i > 0 {
43                write!(f, "{indent}")?;
44            }
45
46            if i != self.body.len() - 1 {
47                writeln!(f, "{fact}")?;
48            } else {
49                write!(f, "{fact}")?;
50            }
51        }
52        write!(f, ")\n      (")?;
53        for (i, action) in self.head.0.iter().enumerate() {
54            if i > 0 {
55                write!(f, "{indent}")?;
56            }
57            if i != self.head.0.len() - 1 {
58                writeln!(f, "{action}")?;
59            } else {
60                write!(f, "{action}")?;
61            }
62        }
63        let ruleset = if !self.ruleset.is_empty() {
64            format!(":ruleset {}", &self.ruleset)
65        } else {
66            "".into()
67        };
68        let name = if !self.name.is_empty() {
69            format!(":name {}", Literal::String(self.name.clone()))
70        } else {
71            "".into()
72        };
73        let eval_mode = match self.eval_mode {
74            RuleEvalMode::Seminaive => "",
75            RuleEvalMode::Naive => " :naive",
76            RuleEvalMode::UnsafeSeminaive => " :unsafe-seminaive",
77        };
78        let no_decomp = if self.no_decomp { " :no-decomp" } else { "" };
79        let include_subsumed = if self.include_subsumed {
80            " :internal-include-subsumed"
81        } else {
82            ""
83        };
84        write!(
85            f,
86            ")\n{indent} {ruleset} {name}{eval_mode}{no_decomp}{include_subsumed})"
87        )
88    }
89}
90
91// Use the macro for Int, Float, and String conversions
92impl_from!(Int(i64));
93impl_from!(Float(OrderedFloat<f64>));
94impl_from!(String(String));
95
96impl<Head: Display, Leaf: Display> Display for GenericFact<Head, Leaf> {
97    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
98        match self {
99            GenericFact::Eq(_, e1, e2) => write!(f, "(= {e1} {e2})"),
100            GenericFact::Fact(expr) => write!(f, "{expr}"),
101        }
102    }
103}
104
105// Implement Display for GenericAction
106impl<Head: Display, Leaf: Display> Display for GenericAction<Head, Leaf>
107where
108    Head: Clone + Display,
109    Leaf: Clone + PartialEq + Eq + Display + Hash,
110{
111    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
112        match self {
113            GenericAction::Let(_, lhs, rhs) => write!(f, "(let {lhs} {rhs})"),
114            GenericAction::Set(_, lhs, args, rhs) => {
115                if args.is_empty() {
116                    write!(f, "(set ({lhs}) {rhs})")
117                } else {
118                    write!(
119                        f,
120                        "(set ({} {}) {})",
121                        lhs,
122                        args.iter()
123                            .map(|a| format!("{a}"))
124                            .collect::<Vec<_>>()
125                            .join(" "),
126                        rhs
127                    )
128                }
129            }
130            GenericAction::Union(_, lhs, rhs) => write!(f, "(union {lhs} {rhs})"),
131            GenericAction::Change(_, change, lhs, args) => {
132                let change_str = match change {
133                    Change::Delete => "delete",
134                    Change::Subsume => "subsume",
135                };
136                if args.is_empty() {
137                    write!(f, "({change_str} ({lhs}))")
138                } else {
139                    write!(
140                        f,
141                        "({} ({} {}))",
142                        change_str,
143                        lhs,
144                        args.iter()
145                            .map(|a| format!("{a}"))
146                            .collect::<Vec<_>>()
147                            .join(" ")
148                    )
149                }
150            }
151            GenericAction::Panic(_, msg) => {
152                write!(f, "(panic {})", Literal::String(msg.clone()))
153            }
154            GenericAction::Expr(_, e) => write!(f, "{e}"),
155        }
156    }
157}
158
159impl<Head, Leaf> Display for GenericExpr<Head, Leaf>
160where
161    Head: Display,
162    Leaf: Display,
163{
164    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
165        match self {
166            GenericExpr::Lit(_ann, lit) => write!(f, "{lit}"),
167            GenericExpr::Var(_ann, var) => write!(f, "{var}"),
168            GenericExpr::Call(_ann, op, children) => match children.is_empty() {
169                true => write!(f, "({op})"),
170                false => write!(f, "({} {})", op, ListDisplay(children, " ")),
171            },
172        }
173    }
174}
175
176impl<Head, Leaf> Default for GenericActions<Head, Leaf>
177where
178    Head: Clone + Display,
179    Leaf: Clone + PartialEq + Eq + Display + Hash,
180{
181    fn default() -> Self {
182        Self(vec![])
183    }
184}
185
186impl<Head, Leaf> GenericRule<Head, Leaf>
187where
188    Head: Clone + Display,
189    Leaf: Clone + PartialEq + Eq + Display + Hash,
190{
191    /// Applies `f` to every expression that appears in the rule body or head.
192    pub fn visit_exprs(
193        self,
194        f: &mut impl FnMut(GenericExpr<Head, Leaf>) -> GenericExpr<Head, Leaf>,
195    ) -> Self {
196        Self {
197            span: self.span,
198            head: self.head.visit_exprs(f),
199            body: self
200                .body
201                .into_iter()
202                .map(|bexpr| bexpr.visit_exprs(f))
203                .collect(),
204            name: self.name,
205            ruleset: self.ruleset,
206            eval_mode: self.eval_mode,
207            no_decomp: self.no_decomp,
208            include_subsumed: self.include_subsumed,
209        }
210    }
211
212    /// Applies `f` to each action in the rule head, leaving the body unchanged.
213    pub fn visit_actions(
214        self,
215        f: &mut impl FnMut(GenericAction<Head, Leaf>) -> GenericAction<Head, Leaf>,
216    ) -> Self {
217        Self {
218            span: self.span,
219            head: self.head.visit_actions(f),
220            body: self.body,
221            name: self.name,
222            ruleset: self.ruleset,
223            eval_mode: self.eval_mode,
224            no_decomp: self.no_decomp,
225            include_subsumed: self.include_subsumed,
226        }
227    }
228
229    /// Applies the provided `head` and `leaf` mappings to every symbol that appears in the rule.
230    pub fn map_symbols<Head2, Leaf2>(
231        self,
232        head: &mut impl FnMut(Head) -> Head2,
233        leaf: &mut impl FnMut(Leaf) -> Leaf2,
234    ) -> GenericRule<Head2, Leaf2>
235    where
236        Head2: Clone + Display,
237        Leaf2: Clone + PartialEq + Eq + Display + Hash,
238    {
239        GenericRule {
240            span: self.span,
241            head: self.head.map_symbols(head, leaf),
242            body: self
243                .body
244                .into_iter()
245                .map(|fact| fact.map_symbols(head, leaf))
246                .collect(),
247            name: self.name,
248            ruleset: self.ruleset,
249            eval_mode: self.eval_mode,
250            no_decomp: self.no_decomp,
251            include_subsumed: self.include_subsumed,
252        }
253    }
254
255    /// Converts the rule into its unresolved representation by formatting heads and leaves.
256    pub fn make_unresolved(self) -> GenericRule<String, String> {
257        let mut map_head = |h: Head| h.to_string();
258        let mut map_leaf = |l: Leaf| l.to_string();
259        self.map_symbols(&mut map_head, &mut map_leaf)
260    }
261}
262
263impl<Head, Leaf> GenericActions<Head, Leaf>
264where
265    Head: Clone + Display,
266    Leaf: Clone + PartialEq + Eq + Display + Hash,
267{
268    pub fn len(&self) -> usize {
269        self.0.len()
270    }
271
272    pub fn is_empty(&self) -> bool {
273        self.0.is_empty()
274    }
275
276    pub fn iter(&self) -> impl Iterator<Item = &GenericAction<Head, Leaf>> {
277        self.0.iter()
278    }
279
280    pub fn visit_vars(&self, f: &mut impl FnMut(&Span, &Leaf)) {
281        for action in &self.0 {
282            action.visit_vars(f);
283        }
284    }
285
286    /// Transforms every expression appearing in the action list using `f`.
287    pub fn visit_exprs(
288        self,
289        f: &mut impl FnMut(GenericExpr<Head, Leaf>) -> GenericExpr<Head, Leaf>,
290    ) -> Self {
291        Self(self.0.into_iter().map(|a| a.visit_exprs(f)).collect())
292    }
293
294    /// Rewrites each action in the collection with the provided closure.
295    pub fn visit_actions(
296        self,
297        f: &mut impl FnMut(GenericAction<Head, Leaf>) -> GenericAction<Head, Leaf>,
298    ) -> Self {
299        Self(self.0.into_iter().map(f).collect())
300    }
301
302    pub fn new(actions: Vec<GenericAction<Head, Leaf>>) -> Self {
303        Self(actions)
304    }
305
306    pub fn singleton(action: GenericAction<Head, Leaf>) -> Self {
307        Self(vec![action])
308    }
309
310    /// Applies the provided `head` and `leaf` mappings to each action.
311    pub fn map_symbols<Head2, Leaf2>(
312        self,
313        head: &mut impl FnMut(Head) -> Head2,
314        leaf: &mut impl FnMut(Leaf) -> Leaf2,
315    ) -> GenericActions<Head2, Leaf2>
316    where
317        Head2: Clone + Display,
318        Leaf2: Clone + PartialEq + Eq + Display + Hash,
319    {
320        GenericActions(
321            self.0
322                .into_iter()
323                .map(|action| action.map_symbols(head, leaf))
324                .collect(),
325        )
326    }
327
328    /// Converts the actions into their unresolved representation by formatting heads and leaves.
329    pub fn make_unresolved(self) -> GenericActions<String, String> {
330        let mut map_head = |h: Head| h.to_string();
331        let mut map_leaf = |l: Leaf| l.to_string();
332        self.map_symbols(&mut map_head, &mut map_leaf)
333    }
334}
335
336impl<Head, Leaf> GenericAction<Head, Leaf>
337where
338    Head: Clone + Display,
339    Leaf: Clone + Eq + Display + Hash,
340{
341    /// Visits every variable occurrence, including `let` binders before their values.
342    pub fn visit_vars(&self, f: &mut impl FnMut(&Span, &Leaf)) {
343        match self {
344            GenericAction::Let(span, lhs, rhs) => {
345                f(span, lhs);
346                rhs.visit_vars(f);
347            }
348            GenericAction::Set(_, _, args, rhs) => {
349                for arg in args {
350                    arg.visit_vars(f);
351                }
352                rhs.visit_vars(f);
353            }
354            GenericAction::Change(_, _, _, args) => {
355                for arg in args {
356                    arg.visit_vars(f);
357                }
358            }
359            GenericAction::Union(_, lhs, rhs) => {
360                lhs.visit_vars(f);
361                rhs.visit_vars(f);
362            }
363            GenericAction::Panic(..) => {}
364            GenericAction::Expr(_, expr) => expr.visit_vars(f),
365        }
366    }
367
368    // Applys `f` to all expressions in the action.
369    pub fn map_exprs(
370        &self,
371        f: &mut impl FnMut(&GenericExpr<Head, Leaf>) -> GenericExpr<Head, Leaf>,
372    ) -> Self {
373        match self {
374            GenericAction::Let(span, lhs, rhs) => {
375                GenericAction::Let(span.clone(), lhs.clone(), f(rhs))
376            }
377            GenericAction::Set(span, lhs, args, rhs) => {
378                let right = f(rhs);
379                GenericAction::Set(
380                    span.clone(),
381                    lhs.clone(),
382                    args.iter().map(f).collect(),
383                    right,
384                )
385            }
386            GenericAction::Change(span, change, lhs, args) => GenericAction::Change(
387                span.clone(),
388                *change,
389                lhs.clone(),
390                args.iter().map(f).collect(),
391            ),
392            GenericAction::Union(span, lhs, rhs) => {
393                GenericAction::Union(span.clone(), f(lhs), f(rhs))
394            }
395            GenericAction::Panic(span, msg) => GenericAction::Panic(span.clone(), msg.clone()),
396            GenericAction::Expr(span, e) => GenericAction::Expr(span.clone(), f(e)),
397        }
398    }
399
400    /// Applys `f` to all sub-expressions (including `self`)
401    /// bottom-up, collecting the results.
402    pub fn visit_exprs(
403        self,
404        f: &mut impl FnMut(GenericExpr<Head, Leaf>) -> GenericExpr<Head, Leaf>,
405    ) -> Self {
406        match self {
407            GenericAction::Let(span, lhs, rhs) => GenericAction::Let(span, lhs, rhs.visit_exprs(f)),
408            // TODO should we refactor `Set` so that we can map over Expr::Call(lhs, args)?
409            // This seems more natural to oflatt
410            // Currently, visit_exprs does not apply f to the first argument of Set.
411            GenericAction::Set(span, lhs, args, rhs) => {
412                let args = args.into_iter().map(|e| e.visit_exprs(f)).collect();
413                GenericAction::Set(span, lhs, args, rhs.visit_exprs(f))
414            }
415            GenericAction::Change(span, change, lhs, args) => {
416                let args = args.into_iter().map(|e| e.visit_exprs(f)).collect();
417                GenericAction::Change(span, change, lhs, args)
418            }
419            GenericAction::Union(span, lhs, rhs) => {
420                GenericAction::Union(span, lhs.visit_exprs(f), rhs.visit_exprs(f))
421            }
422            GenericAction::Panic(span, msg) => GenericAction::Panic(span, msg),
423            GenericAction::Expr(span, e) => GenericAction::Expr(span, e.visit_exprs(f)),
424        }
425    }
426
427    pub fn subst(&self, subst: &mut impl FnMut(&Span, &Leaf) -> GenericExpr<Head, Leaf>) -> Self {
428        self.map_exprs(&mut |e| e.subst_leaf(subst))
429    }
430
431    pub fn map_def_use(self, fvar: &mut impl FnMut(Leaf, bool) -> Leaf) -> Self {
432        macro_rules! fvar_expr {
433            () => {
434                |span, s: _| GenericExpr::Var(span.clone(), fvar(s.clone(), false))
435            };
436        }
437        match self {
438            GenericAction::Let(span, lhs, rhs) => {
439                let lhs = fvar(lhs, true);
440                let rhs = rhs.subst_leaf(&mut fvar_expr!());
441                GenericAction::Let(span, lhs, rhs)
442            }
443            GenericAction::Set(span, lhs, args, rhs) => {
444                let args = args
445                    .into_iter()
446                    .map(|e| e.subst_leaf(&mut fvar_expr!()))
447                    .collect();
448                let rhs = rhs.subst_leaf(&mut fvar_expr!());
449                GenericAction::Set(span, lhs.clone(), args, rhs)
450            }
451            GenericAction::Change(span, change, lhs, args) => {
452                let args = args
453                    .into_iter()
454                    .map(|e| e.subst_leaf(&mut fvar_expr!()))
455                    .collect();
456                GenericAction::Change(span, change, lhs.clone(), args)
457            }
458            GenericAction::Union(span, lhs, rhs) => {
459                let lhs = lhs.subst_leaf(&mut fvar_expr!());
460                let rhs = rhs.subst_leaf(&mut fvar_expr!());
461                GenericAction::Union(span, lhs, rhs)
462            }
463            GenericAction::Panic(span, msg) => GenericAction::Panic(span, msg.clone()),
464            GenericAction::Expr(span, e) => {
465                GenericAction::Expr(span, e.subst_leaf(&mut fvar_expr!()))
466            }
467        }
468    }
469
470    /// Applies the provided `head` and `leaf` mappings to the action and all nested expressions.
471    pub fn map_symbols<Head2, Leaf2>(
472        self,
473        head: &mut impl FnMut(Head) -> Head2,
474        leaf: &mut impl FnMut(Leaf) -> Leaf2,
475    ) -> GenericAction<Head2, Leaf2>
476    where
477        Head2: Clone + Display,
478        Leaf2: Clone + Eq + Display + Hash,
479    {
480        match self {
481            GenericAction::Let(span, lhs, rhs) => {
482                GenericAction::Let(span, leaf(lhs), rhs.map_symbols(head, leaf))
483            }
484            GenericAction::Set(span, head_sym, args, rhs) => {
485                let mut mapped_args = Vec::with_capacity(args.len());
486                for arg in args {
487                    mapped_args.push(arg.map_symbols(head, leaf));
488                }
489                GenericAction::Set(
490                    span,
491                    head(head_sym),
492                    mapped_args,
493                    rhs.map_symbols(head, leaf),
494                )
495            }
496            GenericAction::Change(span, change, head_sym, args) => {
497                let mut mapped_args = Vec::with_capacity(args.len());
498                for arg in args {
499                    mapped_args.push(arg.map_symbols(head, leaf));
500                }
501                GenericAction::Change(span, change, head(head_sym), mapped_args)
502            }
503            GenericAction::Union(span, lhs, rhs) => GenericAction::Union(
504                span,
505                lhs.map_symbols(head, leaf),
506                rhs.map_symbols(head, leaf),
507            ),
508            GenericAction::Panic(span, msg) => GenericAction::Panic(span, msg),
509            GenericAction::Expr(span, expr) => {
510                GenericAction::Expr(span, expr.map_symbols(head, leaf))
511            }
512        }
513    }
514
515    /// Converts the action into its unresolved representation using String by
516    /// formatting heads and leaves.
517    pub fn make_unresolved(self) -> GenericAction<String, String> {
518        let mut map_head = |h: Head| h.to_string();
519        let mut map_leaf = |l: Leaf| l.to_string();
520        self.map_symbols(&mut map_head, &mut map_leaf)
521    }
522}
523
524impl<Head, Leaf> GenericFact<Head, Leaf>
525where
526    Head: Clone + Display,
527    Leaf: Clone + PartialEq + Eq + Display + Hash,
528{
529    pub fn visit_vars(&self, f: &mut impl FnMut(&Span, &Leaf)) {
530        match self {
531            GenericFact::Eq(_, lhs, rhs) => {
532                lhs.visit_vars(f);
533                rhs.visit_vars(f);
534            }
535            GenericFact::Fact(expr) => expr.visit_vars(f),
536        }
537    }
538
539    pub fn visit_exprs(
540        self,
541        f: &mut impl FnMut(GenericExpr<Head, Leaf>) -> GenericExpr<Head, Leaf>,
542    ) -> GenericFact<Head, Leaf> {
543        match self {
544            GenericFact::Eq(span, e1, e2) => {
545                GenericFact::Eq(span, e1.visit_exprs(f), e2.visit_exprs(f))
546            }
547            GenericFact::Fact(expr) => GenericFact::Fact(expr.visit_exprs(f)),
548        }
549    }
550
551    pub fn map_exprs<Head2, Leaf2>(
552        &self,
553        f: &mut impl FnMut(&GenericExpr<Head, Leaf>) -> GenericExpr<Head2, Leaf2>,
554    ) -> GenericFact<Head2, Leaf2> {
555        match self {
556            GenericFact::Eq(span, e1, e2) => GenericFact::Eq(span.clone(), f(e1), f(e2)),
557            GenericFact::Fact(expr) => GenericFact::Fact(f(expr)),
558        }
559    }
560
561    pub fn subst<Leaf2, Head2>(
562        &self,
563        subst_leaf: &mut impl FnMut(&Span, &Leaf) -> GenericExpr<Head2, Leaf2>,
564        subst_head: &mut impl FnMut(&Head) -> Head2,
565    ) -> GenericFact<Head2, Leaf2> {
566        self.map_exprs(&mut |e| e.subst(subst_leaf, subst_head))
567    }
568}
569
570impl<Head, Leaf> GenericFact<Head, Leaf>
571where
572    Leaf: Clone + PartialEq + Eq + Display + Hash,
573    Head: Clone + Display,
574{
575    /// Applies the provided `head` and `leaf` mappings to the fact.
576    pub fn map_symbols<Head2, Leaf2>(
577        self,
578        head: &mut impl FnMut(Head) -> Head2,
579        leaf: &mut impl FnMut(Leaf) -> Leaf2,
580    ) -> GenericFact<Head2, Leaf2>
581    where
582        Head2: Clone + Display,
583        Leaf2: Clone + PartialEq + Eq + Display + Hash,
584    {
585        match self {
586            GenericFact::Eq(span, e1, e2) => {
587                GenericFact::Eq(span, e1.map_symbols(head, leaf), e2.map_symbols(head, leaf))
588            }
589            GenericFact::Fact(expr) => GenericFact::Fact(expr.map_symbols(head, leaf)),
590        }
591    }
592
593    /// Converts all heads and leaves to strings.
594    pub fn make_unresolved(self) -> GenericFact<String, String> {
595        let mut map_head = |h: Head| h.to_string();
596        let mut map_leaf = |l: Leaf| l.to_string();
597        self.map_symbols(&mut map_head, &mut map_leaf)
598    }
599}
600
601impl<Head: Clone + Display, Leaf: Hash + Clone + Display + Eq> GenericExpr<Head, Leaf> {
602    pub fn visit_vars(&self, f: &mut impl FnMut(&Span, &Leaf)) {
603        self.walk(&mut |_| {}, &mut |expr| {
604            if let GenericExpr::Var(span, var) = expr {
605                f(span, var);
606            }
607        });
608    }
609
610    pub fn span(&self) -> Span {
611        match self {
612            GenericExpr::Lit(span, _) => span.clone(),
613            GenericExpr::Var(span, _) => span.clone(),
614            GenericExpr::Call(span, _, _) => span.clone(),
615        }
616    }
617
618    pub fn is_var(&self) -> bool {
619        matches!(self, GenericExpr::Var(_, _))
620    }
621
622    pub fn get_var(&self) -> Option<Leaf> {
623        match self {
624            GenericExpr::Var(_ann, v) => Some(v.clone()),
625            _ => None,
626        }
627    }
628
629    fn children(&self) -> &[Self] {
630        match self {
631            GenericExpr::Var(_, _) | GenericExpr::Lit(_, _) => &[],
632            GenericExpr::Call(_, _, children) => children,
633        }
634    }
635
636    pub fn ast_size(&self) -> usize {
637        let mut size = 0;
638        self.walk(&mut |_e| size += 1, &mut |_| {});
639        size
640    }
641
642    /// Traverse the expression tree, calling `pre` before visiting children
643    /// and `post` after visiting children. Visits all nodes in the tree.
644    pub fn walk(&self, pre: &mut impl FnMut(&Self), post: &mut impl FnMut(&Self)) {
645        pre(self);
646        self.children()
647            .iter()
648            .for_each(|child| child.walk(pre, post));
649        post(self);
650    }
651
652    /// Fold over the expression tree bottom-up, collecting results from children.
653    /// The function `f` is called on each node with the node itself and the results
654    /// from folding over its children. Results are computed from leaves to root.
655    pub fn fold<Out>(&self, f: &mut impl FnMut(&Self, Vec<Out>) -> Out) -> Out {
656        let ts = self.children().iter().map(|child| child.fold(f)).collect();
657        f(self, ts)
658    }
659
660    /// Search for the first node matching a predicate, returning early once found.
661    /// Traverses the tree in pre-order (top-down).
662    pub fn find<Out>(&self, f: &mut impl FnMut(&Self) -> Option<Out>) -> Option<Out> {
663        // Check current node first
664        if let Some(result) = f(self) {
665            return Some(result);
666        }
667
668        // Then check children
669        for child in self.children().iter() {
670            if let Some(result) = child.find(f) {
671                return Some(result);
672            }
673        }
674
675        None
676    }
677
678    /// Applys `f` to all sub-expressions (including `self`)
679    /// bottom-up, collecting the results.
680    pub fn visit_exprs(self, f: &mut impl FnMut(Self) -> Self) -> Self {
681        match self {
682            GenericExpr::Lit(..) => f(self),
683            GenericExpr::Var(..) => f(self),
684            GenericExpr::Call(span, op, children) => {
685                let children = children.into_iter().map(|c| c.visit_exprs(f)).collect();
686                f(GenericExpr::Call(span, op, children))
687            }
688        }
689    }
690
691    /// `subst` replaces occurrences of variables and head symbols in the expression.
692    pub fn subst<Head2, Leaf2>(
693        &self,
694        subst_leaf: &mut impl FnMut(&Span, &Leaf) -> GenericExpr<Head2, Leaf2>,
695        subst_head: &mut impl FnMut(&Head) -> Head2,
696    ) -> GenericExpr<Head2, Leaf2> {
697        match self {
698            GenericExpr::Lit(span, lit) => GenericExpr::Lit(span.clone(), lit.clone()),
699            GenericExpr::Var(span, v) => subst_leaf(span, v),
700            GenericExpr::Call(span, op, children) => {
701                let children = children
702                    .iter()
703                    .map(|c| c.subst(subst_leaf, subst_head))
704                    .collect();
705                GenericExpr::Call(span.clone(), subst_head(op), children)
706            }
707        }
708    }
709
710    pub fn subst_leaf<Leaf2>(
711        &self,
712        subst_leaf: &mut impl FnMut(&Span, &Leaf) -> GenericExpr<Head, Leaf2>,
713    ) -> GenericExpr<Head, Leaf2> {
714        self.subst(subst_leaf, &mut |x| x.clone())
715    }
716
717    /// Applies the provided `head` and `leaf` mappings to every symbol within the expression.
718    pub fn map_symbols<Head2, Leaf2>(
719        self,
720        head: &mut impl FnMut(Head) -> Head2,
721        leaf: &mut impl FnMut(Leaf) -> Leaf2,
722    ) -> GenericExpr<Head2, Leaf2> {
723        match self {
724            GenericExpr::Lit(span, lit) => GenericExpr::Lit(span, lit),
725            GenericExpr::Var(span, var) => GenericExpr::Var(span, leaf(var)),
726            GenericExpr::Call(span, op, children) => {
727                let mut mapped_children = Vec::with_capacity(children.len());
728                for child in children {
729                    mapped_children.push(child.map_symbols(head, leaf));
730                }
731                GenericExpr::Call(span, head(op), mapped_children)
732            }
733        }
734    }
735
736    /// Converts all heads and leaves to strings.
737    pub fn make_unresolved(self) -> GenericExpr<String, String> {
738        let mut map_head = |h: Head| h.to_string();
739        let mut map_leaf = |l: Leaf| l.to_string();
740        self.map_symbols(&mut map_head, &mut map_leaf)
741    }
742
743    pub fn vars(&self) -> impl Iterator<Item = Leaf> + '_ {
744        let iterator: Box<dyn Iterator<Item = Leaf>> = match self {
745            GenericExpr::Lit(_ann, _l) => Box::new(std::iter::empty()),
746            GenericExpr::Var(_ann, v) => Box::new(std::iter::once(v.clone())),
747            GenericExpr::Call(_ann, _head, exprs) => Box::new(exprs.iter().flat_map(|e| e.vars())),
748        };
749        iterator
750    }
751}
752
753impl Display for Literal {
754    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
755        match &self {
756            Literal::Int(i) => Display::fmt(i, f),
757            Literal::Float(n) => {
758                // need to display with decimal if there is none
759                let str = n.to_string();
760                if let Ok(_num) = str.parse::<i64>() {
761                    write!(f, "{str}.0")
762                } else {
763                    write!(f, "{str}")
764                }
765            }
766            Literal::Bool(b) => Display::fmt(b, f),
767            // Escape backslashes and quotes so the output round-trips through the
768            // lexer; otherwise a string holding either character produces text
769            // that fails to re-parse. Other characters (newlines, tabs, ...) are
770            // accepted verbatim by the lexer, so we leave them as-is.
771            Literal::String(s) => {
772                write!(f, "\"")?;
773                for c in s.chars() {
774                    match c {
775                        '\\' => write!(f, "\\\\")?,
776                        '"' => write!(f, "\\\"")?,
777                        c => write!(f, "{c}")?,
778                    }
779                }
780                write!(f, "\"")
781            }
782            Literal::Unit => write!(f, "()"),
783        }
784    }
785}
786
787#[cfg(test)]
788mod tests {
789    use super::*;
790    use crate::span::RustSpan;
791    use std::sync::Arc;
792
793    #[test]
794    fn visit_vars_expr_preserves_occurrences_and_spans() {
795        let spans: Vec<_> = (1..=3)
796            .map(|line| {
797                Span::Rust(Arc::new(RustSpan {
798                    file: file!(),
799                    line,
800                    column: 1,
801                }))
802            })
803            .collect();
804        let expr = GenericExpr::Call(
805            Span::Panic,
806            "outer",
807            vec![
808                GenericExpr::Lit(Span::Panic, Literal::Int(1)),
809                GenericExpr::Var(spans[0].clone(), "x"),
810                GenericExpr::Call(
811                    Span::Panic,
812                    "inner",
813                    vec![
814                        GenericExpr::Var(spans[1].clone(), "y"),
815                        GenericExpr::Var(spans[2].clone(), "x"),
816                    ],
817                ),
818                GenericExpr::Call(Span::Panic, "empty", vec![]),
819            ],
820        );
821        let mut visited = Vec::new();
822        expr.visit_vars(&mut |span, var| visited.push((span.clone(), *var)));
823
824        assert_eq!(
825            visited,
826            vec![
827                (spans[0].clone(), "x"),
828                (spans[1].clone(), "y"),
829                (spans[2].clone(), "x"),
830            ]
831        );
832    }
833
834    #[test]
835    fn visit_vars_facts_visit_both_sides_in_order() {
836        let facts = [
837            GenericFact::Eq(
838                Span::Panic,
839                GenericExpr::Call(
840                    Span::Panic,
841                    "f",
842                    vec![
843                        GenericExpr::Var(Span::Panic, "x"),
844                        GenericExpr::Var(Span::Panic, "x"),
845                    ],
846                ),
847                GenericExpr::Var(Span::Panic, "y"),
848            ),
849            GenericFact::Fact(GenericExpr::Var(Span::Panic, "z")),
850        ];
851        let mut visited = Vec::new();
852        for fact in &facts {
853            fact.visit_vars(&mut |_, var| visited.push(*var));
854        }
855
856        assert_eq!(visited, vec!["x", "x", "y", "z"]);
857    }
858
859    #[test]
860    fn visit_vars_actions_include_binders_before_uses() {
861        let action_span = Span::Rust(Arc::new(RustSpan {
862            file: file!(),
863            line: 1,
864            column: 1,
865        }));
866        let var_span = Span::Rust(Arc::new(RustSpan {
867            file: file!(),
868            line: 2,
869            column: 1,
870        }));
871        let actions = GenericActions(vec![
872            GenericAction::Let(
873                action_span.clone(),
874                "bound",
875                GenericExpr::Var(var_span.clone(), "bound"),
876            ),
877            GenericAction::Set(
878                action_span.clone(),
879                "function",
880                vec![
881                    GenericExpr::Var(var_span.clone(), "arg1"),
882                    GenericExpr::Var(var_span.clone(), "arg2"),
883                ],
884                GenericExpr::Var(var_span.clone(), "value"),
885            ),
886            GenericAction::Change(
887                action_span.clone(),
888                Change::Delete,
889                "function",
890                vec![GenericExpr::Var(var_span.clone(), "deleted")],
891            ),
892            GenericAction::Change(
893                action_span.clone(),
894                Change::Subsume,
895                "function",
896                vec![GenericExpr::Var(var_span.clone(), "subsumed")],
897            ),
898            GenericAction::Union(
899                action_span.clone(),
900                GenericExpr::Var(var_span.clone(), "left"),
901                GenericExpr::Var(var_span.clone(), "right"),
902            ),
903            GenericAction::Panic(action_span.clone(), "message".into()),
904            GenericAction::Expr(
905                action_span.clone(),
906                GenericExpr::Var(var_span.clone(), "expr"),
907            ),
908        ]);
909        let mut visited = Vec::new();
910        actions.visit_vars(&mut |span, var| visited.push((span.clone(), *var)));
911
912        assert_eq!(
913            visited,
914            vec![
915                (action_span, "bound"),
916                (var_span.clone(), "bound"),
917                (var_span.clone(), "arg1"),
918                (var_span.clone(), "arg2"),
919                (var_span.clone(), "value"),
920                (var_span.clone(), "deleted"),
921                (var_span.clone(), "subsumed"),
922                (var_span.clone(), "left"),
923                (var_span.clone(), "right"),
924                (var_span, "expr"),
925            ]
926        );
927    }
928
929    #[test]
930    fn display_nullary_call_without_trailing_space() {
931        let expr = GenericExpr::<String, String>::Call(Span::Panic, "foo".into(), vec![]);
932
933        assert_eq!(expr.to_string(), "(foo)");
934    }
935
936    #[test]
937    fn display_nullary_change_without_trailing_space() {
938        let delete = GenericAction::<String, String>::Change(
939            Span::Panic,
940            Change::Delete,
941            "foo".into(),
942            vec![],
943        );
944        let subsume = GenericAction::<String, String>::Change(
945            Span::Panic,
946            Change::Subsume,
947            "foo".into(),
948            vec![],
949        );
950
951        assert_eq!(delete.to_string(), "(delete (foo))");
952        assert_eq!(subsume.to_string(), "(subsume (foo))");
953    }
954
955    #[test]
956    fn display_string_literal_escapes_special_characters() {
957        assert_eq!(Literal::String("plain".into()).to_string(), "\"plain\"");
958        assert_eq!(Literal::String("a\"b".into()).to_string(), "\"a\\\"b\"");
959        assert_eq!(Literal::String("a\\b".into()).to_string(), "\"a\\\\b\"");
960        // Newlines and tabs are accepted verbatim by the lexer, so they are not escaped.
961        assert_eq!(Literal::String("a\nb".into()).to_string(), "\"a\nb\"");
962    }
963
964    #[test]
965    fn display_rule_name_escapes_special_characters() {
966        let rule = GenericRule::<String, String> {
967            span: Span::Panic,
968            head: GenericActions(vec![]),
969            body: vec![],
970            name: "a\"b\\c".into(),
971            ruleset: String::new(),
972            eval_mode: RuleEvalMode::Seminaive,
973            no_decomp: false,
974            include_subsumed: false,
975        };
976
977        assert!(rule.to_string().contains(r#":name "a\"b\\c""#));
978    }
979
980    #[test]
981    fn display_panic_message_escapes_special_characters() {
982        let action = GenericAction::<String, String>::Panic(Span::Panic, "a\"b\\c".into());
983
984        assert_eq!(action.to_string(), r#"(panic "a\"b\\c")"#);
985    }
986}