Skip to main content

semi_persistent_egraph/
ast.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! AST types for the Semper surface language.
4//!
5//! All names are strings at this stage; resolution to OpId/SortId/VarId
6//! happens in a later pass.
7
8use crate::registry::OpMeta;
9
10macro_rules! typed_var_id {
11    ($(#[doc = $doc:expr] pub struct $name:ident;)*) => {$(
12        #[doc = $doc]
13        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
14        pub struct $name(pub u16);
15        impl $name {
16            pub const fn new(x: u16) -> Self { Self(x) }
17            pub const fn idx(self) -> usize { self.0 as usize }
18        }
19    )*};
20}
21
22typed_var_id! {
23    #[doc = "E-node variable (single G binding) — raw flatten namespace."]
24    pub struct VarId;
25    #[doc = "Sequence rest variable (A nodes, `&[G]` slice into pool)."]
26    pub struct SeqVarId;
27    #[doc = "Set rest variable (ACI nodes, `&[G]` slice into pool)."]
28    pub struct SetVarId;
29    #[doc = "Multiset rest variable (AC nodes, &[(G,u32)] slice into pool)."]
30    pub struct MsetVarId;
31    #[doc = "Multiplicity variable (single u32 binding)."]
32    pub struct MultVarId;
33    #[doc = "RHS-local e-node variable introduced by a comprehension."]
34    pub struct RhsLocalVarId;
35    #[doc = "RHS-local multiplicity variable introduced by a comprehension."]
36    pub struct RhsLocalMultVarId;
37    #[doc = "Literal value variable (single LitValId binding from OpKind::Lit nodes)."]
38    pub struct LitValVarId;
39    #[doc = "Global variable (let-bound, resolved at match time from global bindings)."]
40    pub struct GlobalVarId;
41}
42
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub enum CmpOp {
45    Lt,
46    Le,
47    Gt,
48    Ge,
49    Eq,
50    Ne,
51}
52
53/// Byte-offset range `[start, end)` into the original source string.
54#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
55pub enum Span {
56    /// No source location available.
57    #[default]
58    Dummy,
59    /// Byte offsets `[start, end)` into the original source string.
60    Range { start: u32, end: u32 },
61}
62
63impl Span {
64    pub const fn new(start: u32, end: u32) -> Self {
65        Self::Range { start, end }
66    }
67}
68
69/// Multiplicity constraint on an AC element.
70#[derive(Clone, Debug, PartialEq, Eq)]
71pub enum MultSpec {
72    Exact(u64),
73    Var {
74        name: String,
75        constraint: Option<(CmpOp, u64)>,
76    },
77}
78
79// ---------------------------------------------------------------------------
80// Patterns (LHS of rules) — bare ident = variable, (op ...) = application
81// ---------------------------------------------------------------------------
82
83#[derive(Clone, Debug, PartialEq, Eq)]
84pub enum Pattern {
85    /// Bare identifier = pattern variable.
86    Var(String, Span),
87    /// Literal constant (integer, rational, bool).
88    Lit(String, Span),
89    /// `(op p1 p2 ...)` — plain/C application (including nullary `(op)`).
90    Plain {
91        op: String,
92        children: Vec<Pattern>,
93        span: Span,
94    },
95    /// `(op [p1 p2 ...])` — A exact.
96    AExact {
97        op: String,
98        children: Vec<Pattern>,
99        span: Span,
100    },
101    /// `(op [..pre p1 ...])` — A with prefix rest.
102    APrefix {
103        op: String,
104        rest: String,
105        fixed: Vec<Pattern>,
106        span: Span,
107    },
108    /// `(op [p1 ... ..suf])` — A with suffix rest.
109    ASuffix {
110        op: String,
111        fixed: Vec<Pattern>,
112        rest: String,
113        span: Span,
114    },
115    /// `(op [..pre p1 ... ..suf])` — A with both rests.
116    ABoth {
117        op: String,
118        pre: String,
119        fixed: Vec<Pattern>,
120        suf: String,
121        span: Span,
122    },
123    /// `(op {e1:m1 e2:m2 ...})` — AC exact.
124    ACExact {
125        op: String,
126        elems: Vec<(Pattern, MultSpec)>,
127        span: Span,
128    },
129    /// `(op {e1:m1 ... ..rest})` — AC subset.
130    ACSub {
131        op: String,
132        elems: Vec<(Pattern, MultSpec)>,
133        rest: String,
134        span: Span,
135    },
136    /// `(op {e1 e2 ...})` — ACI exact.
137    ACIExact {
138        op: String,
139        elems: Vec<Pattern>,
140        span: Span,
141    },
142    /// `(op {e1 ... ..rest})` — ACI subset.
143    ACISub {
144        op: String,
145        elems: Vec<Pattern>,
146        rest: String,
147        span: Span,
148    },
149}
150
151impl Pattern {
152    pub fn span(&self) -> Span {
153        match self {
154            Pattern::Var(_, s) | Pattern::Lit(_, s) => *s,
155            Pattern::Plain { span, .. }
156            | Pattern::AExact { span, .. }
157            | Pattern::APrefix { span, .. }
158            | Pattern::ASuffix { span, .. }
159            | Pattern::ABoth { span, .. }
160            | Pattern::ACExact { span, .. }
161            | Pattern::ACSub { span, .. }
162            | Pattern::ACIExact { span, .. }
163            | Pattern::ACISub { span, .. } => *span,
164        }
165    }
166}
167
168// ---------------------------------------------------------------------------
169// Terms (ground — no variables, plain S-expr, canonized post-parse)
170// ---------------------------------------------------------------------------
171
172#[derive(Clone, Debug, PartialEq, Eq)]
173pub enum Term {
174    Lit(String, Span),
175    App {
176        op: String,
177        children: Vec<Term>,
178        span: Span,
179    },
180}
181
182impl Term {
183    pub fn span(&self) -> Span {
184        match self {
185            Term::Lit(_, s) => *s,
186            Term::App { span, .. } => *span,
187        }
188    }
189}
190
191impl std::fmt::Display for Term {
192    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193        match self {
194            Term::Lit(s, _) => write!(f, "{s}"),
195            Term::App { op, children, .. } => {
196                write!(f, "({op}")?;
197                for c in children {
198                    write!(f, " {c}")?;
199                }
200                write!(f, ")")
201            }
202        }
203    }
204}
205
206// ---------------------------------------------------------------------------
207// RHS terms (rewrite right-hand side — variables + rest splicing)
208// ---------------------------------------------------------------------------
209
210#[derive(Clone, Debug, PartialEq, Eq)]
211pub enum RhsTerm {
212    Var(String, Span),
213    Lit(String, Span),
214    App {
215        op: String,
216        children: Vec<RhsChild>,
217        span: Span,
218    },
219}
220
221impl RhsTerm {
222    pub fn span(&self) -> Span {
223        match self {
224            RhsTerm::Var(_, s) | RhsTerm::Lit(_, s) => *s,
225            RhsTerm::App { span, .. } => *span,
226        }
227    }
228}
229
230#[derive(Clone, Debug, PartialEq, Eq)]
231pub enum RhsChild {
232    Term(RhsTerm),
233    /// `term:mult` under a variadic op — the term contributed `mult` times.
234    /// Multiplicity 0 omits the term (the k−1 = 0 case of a multiplicity variant).
235    TermMult {
236        term: RhsTerm,
237        mult: MultExpr,
238        span: Span,
239    },
240    /// `..name` — splice rest variable contents.
241    Splice(String, Span),
242    /// `..{body for v in source [if guard]}` — set comprehension.
243    SetComp {
244        body: Box<RhsTerm>,
245        var: String,
246        source: String,
247        filter: Option<Box<RhsTerm>>,
248        span: Span,
249    },
250    /// `..{body:mult for v:k in source [if guard]}` — multiset comprehension.
251    MsetComp {
252        body: Box<RhsTerm>,
253        mult: MultExpr,
254        var: String,
255        mult_var: String,
256        source: String,
257        filter: Option<Box<RhsTerm>>,
258        span: Span,
259    },
260    /// `..[body for v in source [if guard]]` — sequence comprehension.
261    SeqComp {
262        body: Box<RhsTerm>,
263        var: String,
264        source: String,
265        filter: Option<Box<RhsTerm>>,
266        span: Span,
267    },
268}
269
270/// Multiplicity expression in RHS multiset comprehension.
271#[derive(Clone, Debug, PartialEq, Eq)]
272pub enum MultExpr {
273    Lit(u64),
274    Var(String),
275    /// `(u64::- k 1)` — checked u64 arithmetic over multiplicity variables
276    /// and literals. The op vocabulary mirrors the u64 primitive ops; the
277    /// resolver interval-checks the expression against the LHS multiplicity
278    /// constraints so an underflow or division by zero is a compile error,
279    /// not a runtime one.
280    Prim {
281        op: String,
282        args: Vec<MultExpr>,
283    },
284}
285
286// ---------------------------------------------------------------------------
287// Commands
288// ---------------------------------------------------------------------------
289
290/// A single composable algebraic-property tag on a function declaration. Tags combine freely
291/// at the surface (`:assoc :comm :idempotent`); the sortcheck resolver maps a tag *set* to a
292/// concrete `OpKind` and validates the combination (see `doc/design/ac-algebraic-properties.md`
293/// Facet A). The old pre-combined `:assoc-comm` / `:assoc-comm-idem` are accepted as aliases
294/// that the parser expands into these basic tags.
295#[derive(Clone, Debug, PartialEq, Eq)]
296pub enum AlgTag {
297    Comm,
298    Assoc,
299    AssocLeft,
300    AssocRight,
301    /// `x∘x = x` (idempotent, set representation, dedup).
302    Idempotent,
303    /// `x∘x = e` (nilpotent); optional order `n` (default 2). Requires `Identity`.
304    Nilpotent(Option<u8>),
305    /// Identity/unit element `e` (`x∘e = x`), given as a ground surface term (`:identity 0`,
306    /// `:identity (zero)`). Parsed here, sort-checked and stored deferred at registration.
307    Identity(Term),
308    /// Cancellativity (`x∘z = y∘z ⟹ x = y`); an equation-level inference, no element.
309    Cancellative,
310    /// Group inverse: names the unary inverse op (`:inverse neg`). Requires `Identity`.
311    Inverse(String),
312}
313
314/// The `:until` goal of a `(run …)`: two ground terms and the relation that has to hold
315/// between their classes for the run to stop. `equal` distinguishes `(= a b)` from `(!= a b)`.
316#[derive(Clone, Debug, PartialEq, Eq)]
317pub struct RunGoal {
318    pub left: Term,
319    pub right: Term,
320    pub equal: bool,
321}
322
323/// One `(datatype …)` variant: a constructor declaration whose return sort is the datatype.
324#[derive(Clone, Debug, PartialEq, Eq)]
325pub struct Variant {
326    pub name: String,
327    pub arg_sorts: Vec<String>,
328    pub tags: Vec<AlgTag>,
329    /// Always has `is_constructor: true` — a datatype variant is a constructor by
330    /// construction — plus whatever `:cost` / `:unextractable` the variant declared.
331    pub meta: OpMeta,
332}
333
334#[derive(Clone, Debug, PartialEq, Eq)]
335pub enum Command {
336    Sort(String),
337    /// `(function …)` and `(constructor …)`: the same declaration, distinguished only by
338    /// `meta.is_constructor`. Both register an operator with identical congruence and
339    /// matching behavior; a constructor additionally carries the extraction semantics
340    /// (`FLAG_CONSTRUCTOR` on its nodes, `:cost`, `:unextractable`).
341    Function {
342        name: String,
343        arg_sorts: Vec<String>,
344        ret_sort: String,
345        tags: Vec<AlgTag>,
346        meta: OpMeta,
347    },
348    Datatype {
349        name: String,
350        variants: Vec<Variant>,
351    },
352    /// `(ruleset name)` — declares a ruleset. Rules tagged `:ruleset name` join it, and
353    /// `(run name N)` runs exactly those rules.
354    Ruleset(String),
355    Let(String, Term),
356    Union(Term, Term),
357    Insert(Term),
358    /// `(run [ruleset] N [:until (= a b) | :until (!= a b)])`.
359    Run {
360        /// The ruleset to run, or `None` for the default one (rules with no `:ruleset` tag).
361        ruleset: Option<String>,
362        /// Iteration budget.
363        limit: u64,
364        /// Goal that stops the run early once it holds.
365        until: Option<RunGoal>,
366    },
367    /// `(print-size)` — per-operator node counts and the total — or `(print-size Op)`, the
368    /// count for one operator.
369    PrintSize(Option<String>),
370    /// `(print-stats)` — the last run's counters on stdout — or `(print-stats :file "p.json")`,
371    /// the same numbers as JSON in a file.
372    PrintStats(Option<String>),
373    Check(Term),
374    CheckEq(Term, Term),
375    CheckNeq(Term, Term),
376    Extract(Term),
377    AntiUnify {
378        left: Term,
379        right: Term,
380        playouts: u64,
381        algorithm: String,
382        cycle_mode: String,
383    },
384    CheckAu {
385        left: Term,
386        right: Term,
387        max_size: u32,
388        playouts: u64,
389        algorithm: String,
390        cycle_mode: String,
391    },
392    Push(bool), // true = shrink on mark
393    Pop,
394}
395
396#[derive(Clone, Debug, PartialEq, Eq)]
397pub enum Action {
398    Union(RhsTerm, RhsTerm),
399    Insert(RhsTerm),
400    Set {
401        func: String,
402        args: Vec<RhsTerm>,
403        value: RhsTerm,
404    },
405}