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