Skip to main content

semi_persistent_egraph/
compile.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Pattern compiler: flatten recursive patterns into atomic constraints.
4
5use crate::ast::{CmpOp, MultSpec, Pattern, Span};
6
7/// A flat atomic pattern — one e-node shape to match.
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub enum Atom {
10    /// `node_var = (op child_vars...)`
11    Plain {
12        node: String,
13        op: String,
14        children: Vec<String>,
15        span: Span,
16    },
17    /// `node_var = lit_text`
18    Lit {
19        node: String,
20        text: String,
21        span: Span,
22    },
23    /// `node_var = (op [children...])` — A exact match
24    AExact {
25        node: String,
26        op: String,
27        children: Vec<String>,
28        span: Span,
29    },
30    /// A with prefix rest
31    APrefix {
32        node: String,
33        op: String,
34        rest: String,
35        fixed: Vec<String>,
36        span: Span,
37    },
38    /// A with suffix rest
39    ASuffix {
40        node: String,
41        op: String,
42        fixed: Vec<String>,
43        rest: String,
44        span: Span,
45    },
46    /// A with both rests
47    ABoth {
48        node: String,
49        op: String,
50        pre: String,
51        fixed: Vec<String>,
52        suf: String,
53        span: Span,
54    },
55    /// `node_var = (op {e:m ...})` — AC exact
56    ACExact {
57        node: String,
58        op: String,
59        elems: Vec<(String, FlatMult)>,
60        span: Span,
61    },
62    /// AC subset with rest
63    ACSub {
64        node: String,
65        op: String,
66        elems: Vec<(String, FlatMult)>,
67        rest: String,
68        span: Span,
69    },
70    /// ACI exact
71    ACIExact {
72        node: String,
73        op: String,
74        elems: Vec<String>,
75        span: Span,
76    },
77    /// ACI subset with rest
78    ACISub {
79        node: String,
80        op: String,
81        elems: Vec<String>,
82        rest: String,
83        span: Span,
84    },
85    /// Equality constraint: two vars must be in the same e-class.
86    Eq(String, String),
87    /// Primitive predicate guard: `expr` must evaluate to a true boolean over the
88    /// literal values bound elsewhere in the query. Binds nothing and scans no
89    /// relation.
90    Pred { expr: PredExpr, span: Span },
91}
92
93/// A primitive-predicate guard expression: a computation over literal values, built
94/// from primitive operators, literal constants, and the pattern variables that other
95/// atoms bind to literal payloads.
96///
97/// This is the one pattern position where a primitive operator may appear. Everywhere
98/// else in a left-hand side a primitive is rejected, because a primitive names a
99/// function on values and not a relation the e-graph stores — there is nothing to
100/// match it against. A guard is not matched; it is evaluated, once its variables are
101/// bound.
102#[derive(Clone, Debug, PartialEq, Eq)]
103pub enum PredExpr {
104    /// A pattern variable bound to a literal payload by some other atom.
105    Var(String, Span),
106    /// A literal constant written in the guard.
107    Lit(String, Span),
108    /// `(prim arg...)`.
109    App {
110        op: String,
111        args: Vec<PredExpr>,
112        span: Span,
113    },
114}
115
116/// Flattened multiplicity spec.
117#[derive(Clone, Debug, PartialEq, Eq)]
118pub enum FlatMult {
119    Exact(u64),
120    Var {
121        name: String,
122        constraint: Option<(CmpOp, u64)>,
123    },
124}
125
126/// Result of flattening a set of patterns.
127#[derive(Clone, Debug)]
128pub struct FlatQuery {
129    pub atoms: Vec<Atom>,
130    /// Root variable name for each top-level pattern (index matches input pattern order).
131    pub root_vars: Vec<String>,
132}
133
134/// Flatten one or more patterns into a `FlatQuery`.
135pub fn flatten(patterns: &[Pattern]) -> FlatQuery {
136    let mut ctx = FlatCtx {
137        atoms: Vec::new(),
138        next_fresh: 0,
139    };
140    let root_vars: Vec<String> = patterns.iter().map(|pat| ctx.flatten_root(pat)).collect();
141    FlatQuery {
142        atoms: ctx.atoms,
143        root_vars,
144    }
145}
146
147struct FlatCtx {
148    atoms: Vec<Atom>,
149    next_fresh: usize,
150}
151
152impl FlatCtx {
153    fn fresh(&mut self, hint: &str) -> String {
154        let id = self.next_fresh;
155        self.next_fresh += 1;
156        format!("?{hint}{id}")
157    }
158
159    /// Flatten a pattern that appears at the top level (not nested inside another).
160    fn flatten_root(&mut self, pat: &Pattern) -> String {
161        match pat {
162            Pattern::Var(v, _) => v.clone(),
163            Pattern::Lit(text, span) => {
164                let v = self.fresh("lit");
165                self.atoms.push(Atom::Lit {
166                    node: v.clone(),
167                    text: text.clone(),
168                    span: *span,
169                });
170                v
171            }
172            _ => {
173                let node = self.fresh("n");
174                self.flatten_into(pat, &node);
175                node
176            }
177        }
178    }
179
180    /// Flatten `pat`, binding its result to `target`.
181    fn flatten_child(&mut self, pat: &Pattern) -> String {
182        match pat {
183            Pattern::Var(v, _) => v.clone(),
184            Pattern::Lit(text, span) => {
185                let v = self.fresh("lit");
186                self.atoms.push(Atom::Lit {
187                    node: v.clone(),
188                    text: text.clone(),
189                    span: *span,
190                });
191                v
192            }
193            _ => {
194                let v = self.fresh("n");
195                self.flatten_into(pat, &v);
196                v
197            }
198        }
199    }
200
201    /// Emit atoms for `pat`, assigning the node to `node_var`.
202    fn flatten_into(&mut self, pat: &Pattern, node_var: &str) {
203        let span = pat.span();
204        match pat {
205            Pattern::Var(v, _) => {
206                if v != node_var {
207                    self.atoms.push(Atom::Eq(node_var.to_owned(), v.clone()));
208                }
209            }
210            Pattern::Lit(text, _) => {
211                self.atoms.push(Atom::Lit {
212                    node: node_var.to_owned(),
213                    text: text.clone(),
214                    span,
215                });
216            }
217            Pattern::Plain { op, children, .. } => {
218                let cvars: Vec<String> = children.iter().map(|c| self.flatten_child(c)).collect();
219                self.atoms.push(Atom::Plain {
220                    node: node_var.to_owned(),
221                    op: op.clone(),
222                    children: cvars,
223                    span,
224                });
225            }
226            Pattern::AExact { op, children, .. } => {
227                let cvars: Vec<String> = children.iter().map(|c| self.flatten_child(c)).collect();
228                self.atoms.push(Atom::AExact {
229                    node: node_var.to_owned(),
230                    op: op.clone(),
231                    children: cvars,
232                    span,
233                });
234            }
235            Pattern::APrefix {
236                op, rest, fixed, ..
237            } => {
238                let fvars: Vec<String> = fixed.iter().map(|c| self.flatten_child(c)).collect();
239                self.atoms.push(Atom::APrefix {
240                    node: node_var.to_owned(),
241                    op: op.clone(),
242                    rest: rest.clone(),
243                    fixed: fvars,
244                    span,
245                });
246            }
247            Pattern::ASuffix {
248                op, fixed, rest, ..
249            } => {
250                let fvars: Vec<String> = fixed.iter().map(|c| self.flatten_child(c)).collect();
251                self.atoms.push(Atom::ASuffix {
252                    node: node_var.to_owned(),
253                    op: op.clone(),
254                    fixed: fvars,
255                    rest: rest.clone(),
256                    span,
257                });
258            }
259            Pattern::ABoth {
260                op,
261                pre,
262                fixed,
263                suf,
264                ..
265            } => {
266                let fvars: Vec<String> = fixed.iter().map(|c| self.flatten_child(c)).collect();
267                self.atoms.push(Atom::ABoth {
268                    node: node_var.to_owned(),
269                    op: op.clone(),
270                    pre: pre.clone(),
271                    fixed: fvars,
272                    suf: suf.clone(),
273                    span,
274                });
275            }
276            Pattern::ACExact { op, elems, .. } => {
277                let felems: Vec<(String, FlatMult)> = elems
278                    .iter()
279                    .map(|(p, m)| (self.flatten_child(p), flatten_mult(m)))
280                    .collect();
281                self.atoms.push(Atom::ACExact {
282                    node: node_var.to_owned(),
283                    op: op.clone(),
284                    elems: felems,
285                    span,
286                });
287            }
288            Pattern::ACSub {
289                op, elems, rest, ..
290            } => {
291                let felems: Vec<(String, FlatMult)> = elems
292                    .iter()
293                    .map(|(p, m)| (self.flatten_child(p), flatten_mult(m)))
294                    .collect();
295                self.atoms.push(Atom::ACSub {
296                    node: node_var.to_owned(),
297                    op: op.clone(),
298                    elems: felems,
299                    rest: rest.clone(),
300                    span,
301                });
302            }
303            Pattern::ACIExact { op, elems, .. } => {
304                let evars: Vec<String> = elems.iter().map(|c| self.flatten_child(c)).collect();
305                self.atoms.push(Atom::ACIExact {
306                    node: node_var.to_owned(),
307                    op: op.clone(),
308                    elems: evars,
309                    span,
310                });
311            }
312            Pattern::ACISub {
313                op, elems, rest, ..
314            } => {
315                let evars: Vec<String> = elems.iter().map(|c| self.flatten_child(c)).collect();
316                self.atoms.push(Atom::ACISub {
317                    node: node_var.to_owned(),
318                    op: op.clone(),
319                    elems: evars,
320                    rest: rest.clone(),
321                    span,
322                });
323            }
324        }
325    }
326}
327
328fn flatten_mult(m: &MultSpec) -> FlatMult {
329    match m {
330        MultSpec::Exact(n) => FlatMult::Exact(*n),
331        MultSpec::Var { name, constraint } => FlatMult::Var {
332            name: name.clone(),
333            constraint: *constraint,
334        },
335    }
336}
337
338#[cfg(test)]
339mod tests {
340    use super::*;
341    use crate::id::{OpId, SortId};
342    use crate::registry::{OpRegistry, SortRegistry};
343    use crate::sortcheck::flatten_surface;
344    use crate::test_helpers::parse_pattern;
345
346    fn setup() -> (OpRegistry<OpId, SortId, false>, SortRegistry<SortId, false>) {
347        let mut sorts = SortRegistry::new();
348        let e = sorts.intern("Expr");
349        let mut ops = OpRegistry::new();
350        ops.register("f", &[e, e], e);
351        ops.register("g", &[e], e);
352        ops.register("h", &[e], e);
353        ops.register("f1", &[e], e);
354        ops.register("f3", &[e, e, e], e);
355        ops.register("a", &[], e);
356        ops.register("b", &[], e);
357        ops.register_a("concat", e, e, crate::registry::AssocDir::Right);
358        ops.register_mset("add", e, e);
359        ops.register_set("union", e, e);
360        let ibig = sorts.intern("IBig");
361        ops.register("ILit", &[ibig], e);
362        (ops, sorts)
363    }
364
365    fn flat(src: &str) -> FlatQuery {
366        let (ops, _sorts) = setup();
367        let pat = parse_pattern(src);
368        flatten_surface(&[pat], &ops).unwrap()
369    }
370
371    #[test]
372    fn plain_no_nesting() {
373        let fq = flat("(f x y)");
374        assert_eq!(fq.atoms.len(), 1);
375        match &fq.atoms[0] {
376            Atom::Plain { op, children, .. } => {
377                assert_eq!(op, "f");
378                assert_eq!(children.len(), 2);
379                // children should be the user vars x, y
380                assert_eq!(children[0], "x");
381                assert_eq!(children[1], "y");
382            }
383            _ => panic!("expected Plain"),
384        }
385    }
386
387    #[test]
388    fn nested_introduces_intermediate() {
389        // (f x (g y)) → two atoms: ?n1 = (g y), ?n0 = (f x ?n1)
390        let fq = flat("(f x (g y))");
391        assert_eq!(fq.atoms.len(), 2);
392        // First atom emitted is the inner (g y)
393        match &fq.atoms[0] {
394            Atom::Plain { op, children, .. } => {
395                assert_eq!(op, "g");
396                assert_eq!(children[0], "y");
397            }
398            _ => panic!("expected inner Plain"),
399        }
400        // Second atom is the outer (f x ?intermediate)
401        match &fq.atoms[1] {
402            Atom::Plain { op, children, .. } => {
403                assert_eq!(op, "f");
404                assert_eq!(children[0], "x");
405                // children[1] is the intermediate var
406                assert!(children[1].starts_with("?"));
407            }
408            _ => panic!("expected outer Plain"),
409        }
410    }
411
412    #[test]
413    fn deeply_nested() {
414        // (f1 (g (h x))) → 3 atoms
415        let fq = flat("(f1 (g (h x)))");
416        assert_eq!(fq.atoms.len(), 3);
417        assert!(matches!(&fq.atoms[0], Atom::Plain { op, .. } if op == "h"));
418        assert!(matches!(&fq.atoms[1], Atom::Plain { op, .. } if op == "g"));
419        assert!(matches!(&fq.atoms[2], Atom::Plain { op, .. } if op == "f1"));
420    }
421
422    #[test]
423    fn nonlinear_no_extra_atoms() {
424        // (f x x) — same var twice, no nesting
425        let fq = flat("(f x x)");
426        assert_eq!(fq.atoms.len(), 1);
427        match &fq.atoms[0] {
428            Atom::Plain { children, .. } => assert_eq!(children[0], children[1]),
429            _ => panic!("expected Plain"),
430        }
431    }
432
433    #[test]
434    fn literal_child() {
435        let fq = flat("(f1 42)");
436        assert_eq!(fq.atoms.len(), 2); // Lit atom + Plain atom
437        assert!(matches!(&fq.atoms[0], Atom::Lit { text, .. } if text == "42"));
438        assert!(matches!(&fq.atoms[1], Atom::Plain { op, .. } if op == "f1"));
439    }
440
441    #[test]
442    fn nullary() {
443        let fq = flat("(a)");
444        assert_eq!(fq.atoms.len(), 1);
445        match &fq.atoms[0] {
446            Atom::Plain { op, children, .. } => {
447                assert_eq!(op, "a");
448                assert!(children.is_empty());
449            }
450            _ => panic!("expected Plain"),
451        }
452    }
453
454    #[test]
455    fn ac_subset_nested() {
456        // (add (f1 x):2 ..rest)
457        let fq = flat("(add (f1 x):2 ..rest)");
458        // Should produce: inner Plain for (f1 x), then ACSub
459        assert_eq!(fq.atoms.len(), 2);
460        assert!(matches!(&fq.atoms[0], Atom::Plain { op, .. } if op == "f1"));
461        match &fq.atoms[1] {
462            Atom::ACSub {
463                op, elems, rest, ..
464            } => {
465                assert_eq!(op, "add");
466                assert_eq!(elems.len(), 1);
467                assert_eq!(elems[0].1, FlatMult::Exact(2));
468                assert_eq!(rest, "rest");
469            }
470            _ => panic!("expected ACSub"),
471        }
472    }
473
474    #[test]
475    fn a_prefix() {
476        let fq = flat("(concat ..pre x y)");
477        assert_eq!(fq.atoms.len(), 1);
478        match &fq.atoms[0] {
479            Atom::APrefix {
480                op, rest, fixed, ..
481            } => {
482                assert_eq!(op, "concat");
483                assert_eq!(rest, "pre");
484                assert_eq!(fixed.len(), 2);
485            }
486            _ => panic!("expected APrefix"),
487        }
488    }
489
490    #[test]
491    fn multi_pattern_rule() {
492        // Two patterns in a rule body: (f x y), (f y z)
493        let (ops, _) = setup();
494        let p1 = parse_pattern("(f x y)");
495        let p2 = parse_pattern("(f y z)");
496        let fq = flatten_surface(&[p1, p2], &ops).unwrap();
497        assert_eq!(fq.atoms.len(), 2);
498        // y should be shared between the two atoms
499        match (&fq.atoms[0], &fq.atoms[1]) {
500            (Atom::Plain { children: c1, .. }, Atom::Plain { children: c2, .. }) => {
501                assert_eq!(c1[1], c2[0]); // y is child[1] of first f and child[0] of second f
502            }
503            _ => panic!("expected two Plain atoms"),
504        }
505    }
506
507    #[test]
508    fn fresh_vars_generated() {
509        let fq = flat("(f (g x) (h y))");
510        // 3 atoms: (g x), (h y), (f ?n0 ?n1)
511        assert_eq!(fq.atoms.len(), 3);
512        // Root should be a fresh name
513        assert!(fq.root_vars[0].starts_with("?"));
514    }
515}