Skip to main content

semi_persistent_egraph/
sortcheck.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Sort-checking: validate that all terms and patterns are well-sorted,
4//! resolve operator and sort names to dense ids, produce `CCommand`.
5
6use crate::DenseId;
7use crate::ast::*;
8use crate::lit_model::LitModel;
9use crate::literal::LitVal;
10use crate::registry::{OpKind, OpRegistry, SortRegistry};
11use crate::resolve::{GlobalCtx, ResolvedQuery, RhsResolveCtx};
12use std::hash::Hash;
13
14// ── Error type ──
15
16#[derive(Clone, Debug)]
17pub struct SortError {
18    pub msg: String,
19    pub span: Span,
20}
21
22impl std::fmt::Display for SortError {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        match self.span {
25            Span::Dummy => write!(f, "sort error: {}", self.msg),
26            Span::Range { start, end } => {
27                write!(f, "sort error at {}..{}: {}", start, end, self.msg)
28            }
29        }
30    }
31}
32
33fn serr(msg: impl Into<String>, span: Span) -> SortError {
34    SortError {
35        msg: msg.into(),
36        span,
37    }
38}
39
40// ── Checked types ──
41
42/// Fully sort-checked term. Every node has an `OpId` and a `SortId`.
43#[derive(Clone, Debug)]
44pub enum CTerm<O, S, L> {
45    Lit(L, S),
46    App {
47        op: O,
48        sort: S,
49        children: Vec<CTerm<O, S, L>>,
50    },
51    /// Reference to a let-bound global. Resolved at interpret time.
52    Global(String, S),
53}
54
55/// Fully resolved command — ready for interpretation.
56#[derive(Clone, Debug)]
57pub enum CCommand<O, S, L> {
58    /// Declaration — replay through interpreter's existing exec path.
59    Decl(Command),
60    Let(String, CTerm<O, S, L>),
61    Union(CTerm<O, S, L>, CTerm<O, S, L>),
62    Insert(CTerm<O, S, L>),
63    Check(CTerm<O, S, L>),
64    CheckEq(CTerm<O, S, L>, CTerm<O, S, L>),
65    CheckNeq(CTerm<O, S, L>, CTerm<O, S, L>),
66    Extract(CTerm<O, S, L>),
67    Rewrite {
68        query: ResolvedQuery<O, S, L>,
69        rhs_locals: crate::resolve::RhsLocalShape,
70        rhs: crate::resolve::RRhsTerm<O, S, L>,
71        root_vid: crate::ast::VarId,
72        subsume: bool,
73        ruleset: Option<crate::apply::RulesetId>,
74    },
75    Rule {
76        query: ResolvedQuery<O, S, L>,
77        rhs_locals: crate::resolve::RhsLocalShape,
78        actions: Vec<crate::resolve::ResolvedAction<O, S, L>>,
79        ruleset: Option<crate::apply::RulesetId>,
80    },
81    Run {
82        ruleset: Option<crate::apply::RulesetId>,
83        limit: u64,
84        until: Option<CGoal<O, S, L>>,
85    },
86    /// `(print-size [Op])` — `None` is every op plus the total.
87    PrintSize(Option<O>),
88    /// `(print-stats [:file path])`.
89    PrintStats(Option<String>),
90    AntiUnify {
91        left: CTerm<O, S, L>,
92        right: CTerm<O, S, L>,
93        playouts: u64,
94        algorithm: String,
95        cycle_mode: String,
96    },
97    CheckAu {
98        left: CTerm<O, S, L>,
99        right: CTerm<O, S, L>,
100        max_size: u32,
101        playouts: u64,
102        algorithm: String,
103        cycle_mode: String,
104    },
105    Push(bool), // true = shrink on mark
106    Pop,
107}
108
109/// A sort-checked `:until` goal: the two ground terms, and whether the run stops when their
110/// classes are equal or when they are distinct.
111#[derive(Clone, Debug)]
112pub struct CGoal<O, S, L> {
113    pub left: CTerm<O, S, L>,
114    pub right: CTerm<O, S, L>,
115    pub equal: bool,
116}
117
118/// Ruleset names in declaration order; a name's index is its
119/// [`RulesetId`](crate::apply::RulesetId). Local to one `sortcheck_program` call, which is
120/// how a whole program is checked — rulesets are static, so they are neither scoped by
121/// `(push)`/`(pop)` nor carried between calls.
122#[derive(Debug, Default)]
123struct RulesetTable {
124    names: Vec<String>,
125}
126
127impl RulesetTable {
128    /// Declare a ruleset, or return the existing id if the name was already declared.
129    fn declare(&mut self, name: &str) -> crate::apply::RulesetId {
130        match self.id_of(name) {
131            Some(id) => id,
132            None => {
133                self.names.push(name.to_owned());
134                (self.names.len() - 1) as crate::apply::RulesetId
135            }
136        }
137    }
138
139    fn id_of(&self, name: &str) -> Option<crate::apply::RulesetId> {
140        self.names
141            .iter()
142            .position(|n| n == name)
143            .map(|i| i as crate::apply::RulesetId)
144    }
145
146    /// Resolve a declared ruleset name, naming the undeclared ones rather than silently
147    /// running an empty rule set.
148    fn resolve(&self, name: &Option<String>) -> Result<Option<crate::apply::RulesetId>, SortError> {
149        match name {
150            None => Ok(None),
151            Some(n) => self.id_of(n).map(Some).ok_or_else(|| {
152                serr(
153                    format!("unknown ruleset '{n}' (declare it with `(ruleset {n})`)"),
154                    Span::Dummy,
155                )
156            }),
157        }
158    }
159}
160
161// ── Sort-check a Term ──
162
163pub fn check_term<O, S, L, M, const TRACK: bool>(
164    term: &Term,
165    hint: Option<S>,
166    ops: &OpRegistry<O, S, TRACK>,
167    sorts: &SortRegistry<S, TRACK>,
168    model: &M,
169    globals: &GlobalCtx<S, impl Copy>,
170) -> Result<CTerm<O, S, L>, SortError>
171where
172    O: DenseId + Hash + Copy,
173    S: DenseId + Copy,
174    L: LitVal,
175    M: LitModel<Value = L>,
176{
177    match term {
178        Term::Lit(tok, span) => {
179            // Global name?
180            if let Some((_gid, sort, _)) = globals.get(tok.as_str()) {
181                if let Some(h) = hint
182                    && h != sort
183                {
184                    return Err(serr(
185                        format!(
186                            "global '{}' has sort '{}' but expected '{}'",
187                            tok,
188                            sorts.name(sort),
189                            sorts.name(h)
190                        ),
191                        *span,
192                    ));
193                }
194                return Ok(CTerm::Global(tok.clone(), sort));
195            }
196            // Try hint sort first
197            if let Some(sort) = hint {
198                let sort_name = sorts.name(sort);
199                if let Some(val) = model.parse_as(sort_name, tok) {
200                    return Ok(CTerm::Lit(val, sort));
201                }
202            }
203            // Try all sorts
204            if let Some((sort_name, val)) = model.parse_any(tok) {
205                let sort = sorts
206                    .id_by_name(sort_name)
207                    .ok_or_else(|| serr(format!("unknown sort '{sort_name}'"), *span))?;
208                return Ok(CTerm::Lit(val, sort));
209            }
210            // Might be a nullary op name
211            if let Some(op_id) = ops.id_by_name(tok) {
212                let info = ops.info(op_id);
213                match &info.kind {
214                    OpKind::Normal { arg_sorts } if arg_sorts.is_empty() => {
215                        return Ok(CTerm::App {
216                            op: op_id,
217                            sort: info.return_sort,
218                            children: vec![],
219                        });
220                    }
221                    _ => {}
222                }
223            }
224            Err(serr(
225                format!("cannot resolve '{tok}' as literal or nullary op"),
226                *span,
227            ))
228        }
229        Term::App { op, children, span } => {
230            let op_id = ops
231                .id_by_name(op)
232                .ok_or_else(|| serr(format!("unknown operator '{op}'"), *span))?;
233            let info = ops.info(op_id);
234            let ret_sort = info.return_sort;
235
236            // Check arity
237            let expected = match &info.kind {
238                OpKind::Normal { arg_sorts } => Some(arg_sorts.len()),
239                OpKind::Commutative { .. } => Some(2),
240                OpKind::Lit => Some(0), // lit nodes have no children in terms
241                _ => None,              // variadic: any count
242            };
243            if let Some(exp) = expected
244                && children.len() != exp
245            {
246                return Err(serr(
247                    format!(
248                        "operator '{op}' expects {exp} arguments, got {}",
249                        children.len()
250                    ),
251                    *span,
252                ));
253            }
254
255            // Zero-child variadic applications: the empty monomial denotes the op's
256            // identity, so `(add)` is meaningful only when the op declares `:identity e`
257            // (it then builds the unit). Without one, the empty monomial names nothing in
258            // the algebra — reject here, mirroring the pattern-side "at least 1 child"
259            // rule, instead of minting a meaningless empty node.
260            if children.is_empty() {
261                match &info.kind {
262                    OpKind::MSet { identity: None, .. } | OpKind::Set { identity: None, .. } => {
263                        return Err(serr(
264                            format!(
265                                "operator '{op}' has no :identity — a zero-argument \
266                                 application (the empty monomial) is meaningless; declare \
267                                 an identity or supply at least one argument"
268                            ),
269                            *span,
270                        ));
271                    }
272                    OpKind::A { .. } => {
273                        return Err(serr(
274                            format!("operator '{op}' requires at least 1 argument"),
275                            *span,
276                        ));
277                    }
278                    _ => {}
279                }
280            }
281
282            // Sort-check children
283            let mut checked = Vec::with_capacity(children.len());
284            for (i, child) in children.iter().enumerate() {
285                let child_sort = child_sort_hint(&info.kind, i);
286                let ct = check_term(child, child_sort, ops, sorts, model, globals)?;
287                // Verify child sort matches expected
288                if let Some(expected_sort) = child_sort {
289                    let actual = cterm_sort(&ct);
290                    if actual != expected_sort {
291                        return Err(serr(
292                            format!(
293                                "argument {} of '{}': expected sort '{}', got '{}'",
294                                i + 1,
295                                op,
296                                sorts.name(expected_sort),
297                                sorts.name(actual),
298                            ),
299                            child.span(),
300                        ));
301                    }
302                }
303                checked.push(ct);
304            }
305
306            Ok(CTerm::App {
307                op: op_id,
308                sort: ret_sort,
309                children: checked,
310            })
311        }
312    }
313}
314
315fn child_sort_hint<S: DenseId + Copy>(kind: &OpKind<S>, pos: usize) -> Option<S> {
316    match kind {
317        OpKind::Normal { arg_sorts } => arg_sorts.get(pos).copied(),
318        OpKind::Commutative { arg_sorts } => arg_sorts.get(pos).copied(),
319        OpKind::A { arg_sort, .. }
320        | OpKind::MSet { arg_sort, .. }
321        | OpKind::Set { arg_sort, .. } => Some(*arg_sort),
322        OpKind::Lit => None,
323    }
324}
325
326fn cterm_sort<O, S: Copy, L>(ct: &CTerm<O, S, L>) -> S {
327    match ct {
328        CTerm::Lit(_, s) | CTerm::Global(_, s) => *s,
329        CTerm::App { sort, .. } => *sort,
330    }
331}
332
333// ── Flatten SurfacePattern directly to Atom (skip Pattern) ──
334
335use crate::compile::{Atom, FlatMult, FlatQuery, PredExpr};
336use crate::surface_ast::{SurfaceCommand, SurfacePatChild, SurfacePattern};
337
338/// The operator name reserved for the root-binding pattern form `(= p q)`.
339///
340/// Reserved rather than looked up: a declaration named `=` would otherwise shadow the
341/// form and silently change what every existing `(= …)` in a rule body means.
342pub const EQ_FORM: &str = "=";
343
344/// Flatten surface patterns directly to `FlatQuery`, skipping `Pattern`.
345pub fn flatten_surface<O, S, const TRACK: bool>(
346    patterns: &[SurfacePattern],
347    ops: &crate::registry::OpRegistry<O, S, TRACK>,
348) -> Result<FlatQuery, String>
349where
350    O: crate::DenseId + std::hash::Hash + Copy,
351    S: crate::DenseId + Copy,
352{
353    let mut ctx = SurfaceFlatCtx {
354        atoms: Vec::new(),
355        next_fresh: 0,
356        ops,
357    };
358    let mut root_vars = Vec::with_capacity(patterns.len());
359    for p in patterns {
360        root_vars.push(ctx.flatten_root(p)?);
361    }
362    Ok(FlatQuery {
363        atoms: ctx.atoms,
364        root_vars,
365    })
366}
367
368struct SurfaceFlatCtx<'a, O: crate::DenseId, S: crate::DenseId, const TRACK: bool> {
369    atoms: Vec<Atom>,
370    next_fresh: usize,
371    ops: &'a crate::registry::OpRegistry<O, S, TRACK>,
372}
373
374impl<'a, O, S, const TRACK: bool> SurfaceFlatCtx<'a, O, S, TRACK>
375where
376    O: crate::DenseId + std::hash::Hash + Copy,
377    S: crate::DenseId + Copy,
378{
379    fn fresh(&mut self, hint: &str) -> String {
380        let id = self.next_fresh;
381        self.next_fresh += 1;
382        format!("?{hint}{id}")
383    }
384
385    /// Flatten a top-level conjunct of a rule body or `:when` list.
386    ///
387    /// Two forms are only legal here, at the top of a conjunct: the root-binding
388    /// `(= v pat)` (legal nested too, but idiomatic here) and a primitive predicate
389    /// guard, which is a constraint rather than a subterm and so has no meaningful
390    /// nested reading.
391    fn flatten_root(&mut self, pat: &SurfacePattern) -> Result<String, String> {
392        if let SurfacePattern::App { op, .. } = pat
393            && op != EQ_FORM
394            && let Some(op_id) = self.ops.id_by_name(op)
395            && self.ops.is_prim_op(op_id)
396        {
397            let expr = self.pred_expr(pat)?;
398            self.atoms.push(Atom::Pred {
399                expr,
400                span: pat.span(),
401            });
402            // A guard binds nothing, so it has no root e-class to name. The fresh
403            // name is never interned; a caller that needs the root (a rewrite's
404            // left-hand side) fails to find it and reports that.
405            return Ok(self.fresh("guard"));
406        }
407        self.flatten_child(pat)
408    }
409
410    /// Flatten a pattern to the name of the variable holding its root e-class.
411    fn flatten_child(&mut self, pat: &SurfacePattern) -> Result<String, String> {
412        match pat {
413            SurfacePattern::Var(v, _) => Ok(v.clone()),
414            SurfacePattern::Lit(text, span) => {
415                let v = self.fresh("lit");
416                self.atoms.push(Atom::Lit {
417                    node: v.clone(),
418                    text: text.clone(),
419                    span: *span,
420                });
421                Ok(v)
422            }
423            SurfacePattern::App { op, .. } if op == EQ_FORM => self.flatten_eq(pat),
424            SurfacePattern::App { .. } => {
425                let v = self.fresh("n");
426                self.flatten_app(pat, &v)?;
427                Ok(v)
428            }
429        }
430    }
431
432    /// Flatten the root-binding form `(= p q)`: both subpatterns match, and their root
433    /// e-classes are constrained equal.
434    ///
435    /// Each side flattens exactly as it would on its own, so the form adds no atom kind
436    /// of its own: one `Atom::Eq` between the two roots is the whole of it, and resolve,
437    /// scheduling and matching already handle that. The common case `(= v pat)` costs
438    /// nothing beyond `pat`, because the left side is a bare variable and the `Eq` lowers
439    /// to a `CopyBinding` the moment `pat`'s root is bound.
440    fn flatten_eq(&mut self, pat: &SurfacePattern) -> Result<String, String> {
441        let SurfacePattern::App {
442            op,
443            prefix,
444            children,
445            suffix,
446            ..
447        } = pat
448        else {
449            unreachable!()
450        };
451        if prefix.is_some() || suffix.is_some() {
452            return Err(format!("'{op}' takes no rest variables"));
453        }
454        if children.len() != 2 {
455            return Err(format!(
456                "'{op}' takes exactly 2 subpatterns, got {}",
457                children.len()
458            ));
459        }
460        let mut sides = Vec::with_capacity(2);
461        for c in children {
462            match c {
463                SurfacePatChild::Elem(p) => sides.push(self.flatten_child(p)?),
464                SurfacePatChild::ElemMult(..) => {
465                    return Err(format!("'{op}' takes no multiplicities"));
466                }
467            }
468        }
469        let b = sides.pop().unwrap();
470        let a = sides.pop().unwrap();
471        if a != b {
472            self.atoms.push(Atom::Eq(a.clone(), b));
473        }
474        Ok(a)
475    }
476
477    /// Build a guard expression: primitive applications over literal constants and the
478    /// variables other atoms bind to literal payloads.
479    fn pred_expr(&self, pat: &SurfacePattern) -> Result<PredExpr, String> {
480        match pat {
481            SurfacePattern::Var(v, span) => Ok(PredExpr::Var(v.clone(), *span)),
482            SurfacePattern::Lit(text, span) => Ok(PredExpr::Lit(text.clone(), *span)),
483            SurfacePattern::App {
484                op,
485                prefix,
486                children,
487                suffix,
488                span,
489            } => {
490                if prefix.is_some() || suffix.is_some() {
491                    return Err(format!("guard operator '{op}' takes no rest variables"));
492                }
493                let op_id = self
494                    .ops
495                    .id_by_name(op)
496                    .ok_or_else(|| format!("unknown operator '{op}'"))?;
497                if !self.ops.is_prim_op(op_id) {
498                    return Err(format!(
499                        "'{op}' is not a primitive operator; every operator inside a guard \
500                         must be one, because a guard is evaluated over bound literal values \
501                         rather than matched against the e-graph"
502                    ));
503                }
504                let mut args = Vec::with_capacity(children.len());
505                for c in children {
506                    match c {
507                        SurfacePatChild::Elem(p) => args.push(self.pred_expr(p)?),
508                        SurfacePatChild::ElemMult(..) => {
509                            return Err(format!("guard operator '{op}' takes no multiplicities"));
510                        }
511                    }
512                }
513                Ok(PredExpr::App {
514                    op: op.clone(),
515                    args,
516                    span: *span,
517                })
518            }
519        }
520    }
521
522    /// Flatten children, returning var names. Only Elem children (no mults).
523    fn flatten_elems(&mut self, children: &[SurfacePatChild]) -> Result<Vec<String>, String> {
524        children
525            .iter()
526            .map(|c| match c {
527                SurfacePatChild::Elem(p) => self.flatten_child(p),
528                SurfacePatChild::ElemMult(_, _) => unreachable!("mults already rejected"),
529            })
530            .collect()
531    }
532
533    /// Flatten children with multiplicities, returning (var, mult) pairs.
534    fn flatten_elems_with_mult(
535        &mut self,
536        children: &[SurfacePatChild],
537    ) -> Result<Vec<(String, FlatMult)>, String> {
538        children
539            .iter()
540            .map(|c| match c {
541                SurfacePatChild::Elem(p) => Ok((self.flatten_child(p)?, FlatMult::Exact(1))),
542                SurfacePatChild::ElemMult(p, m) => {
543                    Ok((self.flatten_child(p)?, flatten_mult_spec(m)))
544                }
545            })
546            .collect()
547    }
548
549    fn has_mult(children: &[SurfacePatChild]) -> bool {
550        children
551            .iter()
552            .any(|c| matches!(c, SurfacePatChild::ElemMult(..)))
553    }
554
555    fn flatten_app(&mut self, pat: &SurfacePattern, node_var: &str) -> Result<(), String> {
556        let SurfacePattern::App {
557            op,
558            prefix,
559            children,
560            suffix,
561            span,
562        } = pat
563        else {
564            unreachable!()
565        };
566        let has_mult = Self::has_mult(children);
567
568        let op_id = self
569            .ops
570            .id_by_name(op)
571            .ok_or_else(|| format!("unknown operator '{op}'"))?;
572        let info = self.ops.info(op_id);
573
574        match &info.kind {
575            OpKind::Normal { arg_sorts } => {
576                if prefix.is_some() || suffix.is_some() {
577                    return Err(format!(
578                        "operator '{op}' is plain; rest variables not allowed"
579                    ));
580                }
581                if has_mult {
582                    return Err(format!(
583                        "operator '{op}' is plain; multiplicities not allowed"
584                    ));
585                }
586                if children.len() != arg_sorts.len() {
587                    return Err(format!(
588                        "operator '{op}' expects {} args, got {}",
589                        arg_sorts.len(),
590                        children.len()
591                    ));
592                }
593                let cvars = self.flatten_elems(children)?;
594                self.atoms.push(Atom::Plain {
595                    node: node_var.to_owned(),
596                    op: op.clone(),
597                    children: cvars,
598                    span: *span,
599                });
600            }
601            OpKind::Commutative { .. } => {
602                if prefix.is_some() || suffix.is_some() {
603                    return Err(format!(
604                        "operator '{op}' is commutative; rest variables not allowed"
605                    ));
606                }
607                if has_mult {
608                    return Err(format!(
609                        "operator '{op}' is commutative; multiplicities not allowed"
610                    ));
611                }
612                if children.len() != 2 {
613                    return Err(format!(
614                        "operator '{op}' expects 2 args, got {}",
615                        children.len()
616                    ));
617                }
618                let cvars = self.flatten_elems(children)?;
619                self.atoms.push(Atom::Plain {
620                    node: node_var.to_owned(),
621                    op: op.clone(),
622                    children: cvars,
623                    span: *span,
624                });
625            }
626            OpKind::Lit => {
627                if prefix.is_some() || suffix.is_some() {
628                    return Err(format!(
629                        "operator '{op}' is a literal op; rest variables not allowed"
630                    ));
631                }
632                if has_mult {
633                    return Err(format!(
634                        "operator '{op}' is a literal op; multiplicities not allowed"
635                    ));
636                }
637                if children.len() != 1 {
638                    return Err(format!(
639                        "operator '{op}' expects 1 arg, got {}",
640                        children.len()
641                    ));
642                }
643                let cvars = self.flatten_elems(children)?;
644                self.atoms.push(Atom::Plain {
645                    node: node_var.to_owned(),
646                    op: op.clone(),
647                    children: cvars,
648                    span: *span,
649                });
650            }
651            OpKind::A { .. } => {
652                if has_mult {
653                    return Err(format!(
654                        "operator '{op}' is associative; multiplicities not allowed (use AC)"
655                    ));
656                }
657                let fixed = self.flatten_elems(children)?;
658                match (prefix, suffix) {
659                    (None, None) => {
660                        self.atoms.push(Atom::AExact {
661                            node: node_var.to_owned(),
662                            op: op.clone(),
663                            children: fixed,
664                            span: *span,
665                        });
666                    }
667                    (Some((pre, _)), None) => {
668                        self.atoms.push(Atom::APrefix {
669                            node: node_var.to_owned(),
670                            op: op.clone(),
671                            rest: pre.clone(),
672                            fixed,
673                            span: *span,
674                        });
675                    }
676                    (None, Some((suf, _))) => {
677                        self.atoms.push(Atom::ASuffix {
678                            node: node_var.to_owned(),
679                            op: op.clone(),
680                            fixed,
681                            rest: suf.clone(),
682                            span: *span,
683                        });
684                    }
685                    (Some((pre, _)), Some((suf, _))) => {
686                        self.atoms.push(Atom::ABoth {
687                            node: node_var.to_owned(),
688                            op: op.clone(),
689                            pre: pre.clone(),
690                            fixed,
691                            suf: suf.clone(),
692                            span: *span,
693                        });
694                    }
695                }
696            }
697            OpKind::MSet { .. } => {
698                if prefix.is_some() {
699                    return Err(format!(
700                        "operator '{op}' is AC; prefix rest variable not allowed"
701                    ));
702                }
703                let elems = self.flatten_elems_with_mult(children)?;
704                match suffix {
705                    None => {
706                        self.atoms.push(Atom::ACExact {
707                            node: node_var.to_owned(),
708                            op: op.clone(),
709                            elems,
710                            span: *span,
711                        });
712                    }
713                    Some((rest, _)) => {
714                        self.atoms.push(Atom::ACSub {
715                            node: node_var.to_owned(),
716                            op: op.clone(),
717                            elems,
718                            rest: rest.clone(),
719                            span: *span,
720                        });
721                    }
722                }
723            }
724            OpKind::Set { .. } => {
725                if prefix.is_some() {
726                    return Err(format!(
727                        "operator '{op}' is ACI; prefix rest variable not allowed"
728                    ));
729                }
730                if has_mult {
731                    return Err(format!(
732                        "operator '{op}' is ACI (set); multiplicities not allowed (use AC)"
733                    ));
734                }
735                let elems = self.flatten_elems(children)?;
736                match suffix {
737                    None => {
738                        self.atoms.push(Atom::ACIExact {
739                            node: node_var.to_owned(),
740                            op: op.clone(),
741                            elems,
742                            span: *span,
743                        });
744                    }
745                    Some((rest, _)) => {
746                        self.atoms.push(Atom::ACISub {
747                            node: node_var.to_owned(),
748                            op: op.clone(),
749                            elems,
750                            rest: rest.clone(),
751                            span: *span,
752                        });
753                    }
754                }
755            }
756        }
757        Ok(())
758    }
759}
760
761fn flatten_mult_spec(m: &MultSpec) -> FlatMult {
762    match m {
763        MultSpec::Exact(n) => FlatMult::Exact(*n),
764        MultSpec::Var { name, constraint } => FlatMult::Var {
765            name: name.clone(),
766            constraint: *constraint,
767        },
768    }
769}
770
771// ── Top-level sort-check ──
772
773use crate::resolve::{resolve, resolve_action, resolve_rhs};
774
775/// Sort-check a full program against a live egraph.
776/// Declarations register directly into the egraph (setting up caches).
777pub fn sortcheck_program<Cfg, L, M, const TRACK: bool, const PROOFS: bool>(
778    cmds: Vec<SurfaceCommand>,
779    eg: &mut crate::egraph::EGraph<Cfg, L, TRACK, PROOFS>,
780    model: &M,
781    globals: &mut GlobalCtx<Cfg::S>,
782) -> Result<Vec<CCommand<Cfg::O, Cfg::S, L>>, SortError>
783where
784    Cfg: crate::config::EGraphConfig,
785    Cfg::O: Hash,
786    L: LitVal,
787    M: LitModel<Value = L>,
788    crate::canon::MSetCanon: crate::canon::VarCanon<Cfg::G, Cfg::C>,
789{
790    let mut out = Vec::with_capacity(cmds.len());
791    let mut rulesets = RulesetTable::default();
792    // Runtime push/pop truncates global bindings. Mirror only that part here
793    // so GlobalVarId assignment remains identical in the checked and runtime
794    // contexts. Declarations and ruleset names intentionally remain static.
795    let mut global_marks: Vec<usize> = Vec::new();
796    for cmd in cmds {
797        let is_push = matches!(&cmd, SurfaceCommand::Pass(Command::Push(_)));
798        let is_pop = matches!(&cmd, SurfaceCommand::Pass(Command::Pop));
799        out.push(sortcheck_one(cmd, eg, model, globals, &mut rulesets)?);
800        if is_push {
801            global_marks.push(globals.len());
802        } else if is_pop && let Some(n) = global_marks.pop() {
803            globals.truncate(n);
804        }
805    }
806    Ok(out)
807}
808
809fn sortcheck_one<Cfg, L, M, const TRACK: bool, const PROOFS: bool>(
810    cmd: SurfaceCommand,
811    eg: &mut crate::egraph::EGraph<Cfg, L, TRACK, PROOFS>,
812    model: &M,
813    globals: &mut GlobalCtx<Cfg::S>,
814    rulesets: &mut RulesetTable,
815) -> Result<CCommand<Cfg::O, Cfg::S, L>, SortError>
816where
817    Cfg: crate::config::EGraphConfig,
818    Cfg::O: Hash,
819    L: LitVal,
820    M: LitModel<Value = L>,
821    crate::canon::MSetCanon: crate::canon::VarCanon<Cfg::G, Cfg::C>,
822{
823    match cmd {
824        SurfaceCommand::Pass(c) => sortcheck_pass(c, eg, model, globals, rulesets),
825        SurfaceCommand::Rewrite {
826            lhs,
827            rhs,
828            when,
829            subsume,
830            ruleset,
831        } => {
832            let ruleset = rulesets.resolve(&ruleset)?;
833            let lhs_span = lhs.span();
834            let mut pats = vec![lhs];
835            pats.extend(when);
836            let fq = flatten_surface(&pats, eg.ops()).map_err(|e| serr(e, Span::Dummy))?;
837            let root_name = fq.root_vars[0].clone();
838            let rq = resolve(&fq, eg.ops(), eg.sorts(), model, globals)
839                .map_err(|e| serr(e.to_string(), Span::Dummy))?;
840            let root_vid = rq.shape.find_var(&root_name).ok_or_else(|| {
841                serr(
842                    "a rewrite's left-hand side must name an e-class to rewrite; a \
843                     primitive predicate guard names none (it belongs in `:when`)",
844                    lhs_span,
845                )
846            })?;
847            let root_sort = rq.var_sorts[root_vid.idx()];
848            let mut rhs_ctx = RhsResolveCtx::new(&rq);
849            let resolved_rhs = resolve_rhs(
850                &rhs,
851                root_sort,
852                eg.ops(),
853                eg.sorts(),
854                model,
855                &mut rhs_ctx,
856                globals,
857            )
858            .map_err(|e| serr(e.to_string(), Span::Dummy))?;
859            let rhs_locals = rhs_ctx.local_shape();
860            Ok(CCommand::Rewrite {
861                query: rq,
862                rhs_locals,
863                rhs: resolved_rhs,
864                root_vid,
865                subsume,
866                ruleset,
867            })
868        }
869        SurfaceCommand::Rule {
870            body,
871            head,
872            ruleset,
873        } => {
874            let ruleset = rulesets.resolve(&ruleset)?;
875            let fq = flatten_surface(&body, eg.ops()).map_err(|e| serr(e, Span::Dummy))?;
876            let rq = resolve(&fq, eg.ops(), eg.sorts(), model, globals)
877                .map_err(|e| serr(e.to_string(), Span::Dummy))?;
878            let mut rhs_ctx = RhsResolveCtx::new(&rq);
879            let mut actions = Vec::with_capacity(head.len());
880            for a in &head {
881                let ra = resolve_action(a, eg.ops(), eg.sorts(), model, &mut rhs_ctx, globals)
882                    .map_err(|e| serr(e.to_string(), Span::Dummy))?;
883                actions.push(ra);
884            }
885            let rhs_locals = rhs_ctx.local_shape();
886            Ok(CCommand::Rule {
887                query: rq,
888                rhs_locals,
889                actions,
890                ruleset,
891            })
892        }
893    }
894}
895
896fn sortcheck_pass<Cfg, L, M, const TRACK: bool, const PROOFS: bool>(
897    cmd: Command,
898    eg: &mut crate::egraph::EGraph<Cfg, L, TRACK, PROOFS>,
899    model: &M,
900    globals: &mut GlobalCtx<Cfg::S>,
901    rulesets: &mut RulesetTable,
902) -> Result<CCommand<Cfg::O, Cfg::S, L>, SortError>
903where
904    Cfg: crate::config::EGraphConfig,
905    Cfg::O: Hash,
906    L: LitVal,
907    M: LitModel<Value = L>,
908    crate::canon::MSetCanon: crate::canon::VarCanon<Cfg::G, Cfg::C>,
909{
910    // Declarations: register into egraph, then wrap as Decl
911    match &cmd {
912        Command::Sort(_) | Command::Function { .. } | Command::Datatype { .. } => {
913            // Use the interpreter's existing exec_function / intern_sort logic
914            // by delegating to the egraph directly.
915            exec_decl(&cmd, eg, model, globals)?;
916            return Ok(CCommand::Decl(cmd));
917        }
918        _ => {}
919    }
920    // Non-declaration commands: sort-check terms
921    match cmd {
922        Command::Let(name, term) => {
923            let ct = check_term(&term, None, eg.ops(), eg.sorts(), model, globals)?;
924            globals.insert(name.clone(), cterm_sort(&ct), ());
925            Ok(CCommand::Let(name, ct))
926        }
927        Command::Union(a, b) => {
928            let ca = check_term(&a, None, eg.ops(), eg.sorts(), model, globals)?;
929            let cb = check_term(&b, None, eg.ops(), eg.sorts(), model, globals)?;
930            Ok(CCommand::Union(ca, cb))
931        }
932        Command::Insert(term) => {
933            let ct = check_term(&term, None, eg.ops(), eg.sorts(), model, globals)?;
934            Ok(CCommand::Insert(ct))
935        }
936        Command::Check(t) => {
937            let ct = check_term(&t, None, eg.ops(), eg.sorts(), model, globals)?;
938            Ok(CCommand::Check(ct))
939        }
940        Command::CheckEq(a, b) => {
941            let ca = check_term(&a, None, eg.ops(), eg.sorts(), model, globals)?;
942            let cb = check_term(&b, None, eg.ops(), eg.sorts(), model, globals)?;
943            Ok(CCommand::CheckEq(ca, cb))
944        }
945        Command::CheckNeq(a, b) => {
946            let ca = check_term(&a, None, eg.ops(), eg.sorts(), model, globals)?;
947            let cb = check_term(&b, None, eg.ops(), eg.sorts(), model, globals)?;
948            Ok(CCommand::CheckNeq(ca, cb))
949        }
950        Command::Extract(t) => {
951            let ct = check_term(&t, None, eg.ops(), eg.sorts(), model, globals)?;
952            Ok(CCommand::Extract(ct))
953        }
954        Command::Ruleset(name) => {
955            rulesets.declare(&name);
956            Ok(CCommand::Decl(Command::Ruleset(name)))
957        }
958        Command::Run {
959            ruleset,
960            limit,
961            until,
962        } => {
963            let rid = rulesets.resolve(&ruleset)?;
964            // The goal's terms are sort-checked here and built once at run time; they are
965            // ground, so nothing about them changes between iterations.
966            let cgoal = match until {
967                None => None,
968                Some(g) => Some(CGoal {
969                    left: check_term(&g.left, None, eg.ops(), eg.sorts(), model, globals)?,
970                    right: check_term(&g.right, None, eg.ops(), eg.sorts(), model, globals)?,
971                    equal: g.equal,
972                }),
973            };
974            Ok(CCommand::Run {
975                ruleset: rid,
976                limit,
977                until: cgoal,
978            })
979        }
980        Command::PrintSize(op) => match op {
981            None => Ok(CCommand::PrintSize(None)),
982            Some(name) => {
983                let id = eg
984                    .ops()
985                    .id_by_name(&name)
986                    .ok_or_else(|| serr(format!("unknown operator '{name}'"), Span::Dummy))?;
987                Ok(CCommand::PrintSize(Some(id)))
988            }
989        },
990        Command::PrintStats(file) => Ok(CCommand::PrintStats(file)),
991        Command::AntiUnify {
992            left,
993            right,
994            playouts,
995            algorithm,
996            cycle_mode,
997        } => {
998            let cl = check_term(&left, None, eg.ops(), eg.sorts(), model, globals)?;
999            let cr = check_term(&right, None, eg.ops(), eg.sorts(), model, globals)?;
1000            Ok(CCommand::AntiUnify {
1001                left: cl,
1002                right: cr,
1003                playouts,
1004                algorithm,
1005                cycle_mode,
1006            })
1007        }
1008        Command::CheckAu {
1009            left,
1010            right,
1011            max_size,
1012            playouts,
1013            algorithm,
1014            cycle_mode,
1015        } => {
1016            let cl = check_term(&left, None, eg.ops(), eg.sorts(), model, globals)?;
1017            let cr = check_term(&right, None, eg.ops(), eg.sorts(), model, globals)?;
1018            Ok(CCommand::CheckAu {
1019                left: cl,
1020                right: cr,
1021                max_size,
1022                playouts,
1023                algorithm,
1024                cycle_mode,
1025            })
1026        }
1027        Command::Push(shrink) => Ok(CCommand::Push(shrink)),
1028        Command::Pop => Ok(CCommand::Pop),
1029        _ => unreachable!(),
1030    }
1031}
1032
1033/// Register a declaration command into the egraph. `model`/`globals` are needed to resolve a
1034/// completion op's `:identity` unit term to a node at registration.
1035fn exec_decl<Cfg, L, M, const TRACK: bool, const PROOFS: bool>(
1036    cmd: &Command,
1037    eg: &mut crate::egraph::EGraph<Cfg, L, TRACK, PROOFS>,
1038    model: &M,
1039    globals: &GlobalCtx<Cfg::S>,
1040) -> Result<(), SortError>
1041where
1042    Cfg: crate::config::EGraphConfig,
1043    Cfg::O: Hash,
1044    L: LitVal,
1045    M: LitModel<Value = L>,
1046    crate::canon::MSetCanon: crate::canon::VarCanon<Cfg::G, Cfg::C>,
1047{
1048    match cmd {
1049        Command::Sort(name) => {
1050            eg.intern_sort(name);
1051        }
1052        Command::Function {
1053            name,
1054            arg_sorts,
1055            ret_sort,
1056            tags,
1057            meta,
1058        } => {
1059            let ret = eg
1060                .sorts()
1061                .id_by_name(ret_sort)
1062                .ok_or_else(|| serr(format!("unknown sort '{ret_sort}'"), Span::Dummy))?;
1063            let args: Vec<Cfg::S> = arg_sorts
1064                .iter()
1065                .map(|s| {
1066                    eg.sorts()
1067                        .id_by_name(s)
1068                        .ok_or_else(|| serr(format!("unknown sort '{s}'"), Span::Dummy))
1069                })
1070                .collect::<Result<_, _>>()?;
1071            register_op(eg, name, &args, ret, tags, *meta, model, globals)?;
1072        }
1073        Command::Datatype { name, variants } => {
1074            eg.intern_sort(name);
1075            let sid = eg.sorts().id_by_name(name).unwrap();
1076            for v in variants {
1077                let arg_ids: Vec<Cfg::S> = v
1078                    .arg_sorts
1079                    .iter()
1080                    .map(|s| {
1081                        eg.sorts()
1082                            .id_by_name(s)
1083                            .ok_or_else(|| serr(format!("unknown sort '{s}'"), Span::Dummy))
1084                    })
1085                    .collect::<Result<_, _>>()?;
1086                register_op(eg, &v.name, &arg_ids, sid, &v.tags, v.meta, model, globals)?;
1087            }
1088        }
1089        _ => {}
1090    }
1091    Ok(())
1092}
1093
1094/// Resolve a composable algebra-tag set into a concrete op registration.
1095/// Validates the combination and builds the `OpKind` descriptor. A declared
1096/// `:identity e` is resolved to a real node here (sortcheck has the model) and stored in the
1097/// egraph's per-op unit map; `:inverse` is resolved to an op id and stored in its per-op map.
1098/// Plain `:assoc :comm` reproduces AC and `+ :idempotent` reproduces ACI. Canonization consumes
1099/// the unit and clamp even when completion is disabled.
1100fn register_op<Cfg, L, M, const TRACK: bool, const PROOFS: bool>(
1101    eg: &mut crate::egraph::EGraph<Cfg, L, TRACK, PROOFS>,
1102    name: &str,
1103    args: &[Cfg::S],
1104    ret: Cfg::S,
1105    tags: &[AlgTag],
1106    meta: crate::registry::OpMeta,
1107    model: &M,
1108    globals: &GlobalCtx<Cfg::S>,
1109) -> Result<Cfg::O, SortError>
1110where
1111    Cfg: crate::config::EGraphConfig,
1112    Cfg::O: Hash,
1113    L: LitVal,
1114    M: LitModel<Value = L>,
1115    crate::canon::MSetCanon: crate::canon::VarCanon<Cfg::G, Cfg::C>,
1116{
1117    use crate::registry::{AssocDir, Clamp, OpKind, UnitRef};
1118
1119    // No algebra tags → plain op. (`meta` still applies: `:cost` / `:unextractable` /
1120    // constructor-ness are orthogonal to the algebraic kind.)
1121    if tags.is_empty() {
1122        return Ok(eg.register_kind_meta(
1123            name,
1124            ret,
1125            OpKind::Normal {
1126                arg_sorts: args.to_vec(),
1127            },
1128            meta,
1129        ));
1130    }
1131
1132    // Collect the tag set into flags. Duplicate basic tags are folded; incompatible
1133    // associativity directions are rejected. The result is independent of tag order.
1134    let mut comm = false;
1135    let mut assoc = false;
1136    let mut dir: Option<AssocDir> = None;
1137    let mut idempotent = false;
1138    let mut nilpotent: Option<u8> = None;
1139    let mut identity: Option<Term> = None;
1140    let mut cancellative = false;
1141    let mut inverse: Option<String> = None;
1142    let mut set_assoc_dir = |next: AssocDir| -> Result<(), SortError> {
1143        if dir.is_some_and(|current| current != next) {
1144            return Err(serr(
1145                ":assoc, :assoc-left, and :assoc-right are mutually exclusive",
1146                Span::Dummy,
1147            ));
1148        }
1149        assoc = true;
1150        dir = Some(next);
1151        Ok(())
1152    };
1153    for tag in tags {
1154        match tag {
1155            AlgTag::Comm => comm = true,
1156            AlgTag::Assoc => set_assoc_dir(AssocDir::Both)?,
1157            AlgTag::AssocLeft => set_assoc_dir(AssocDir::Left)?,
1158            AlgTag::AssocRight => set_assoc_dir(AssocDir::Right)?,
1159            AlgTag::Idempotent => idempotent = true,
1160            AlgTag::Nilpotent(order) => nilpotent = Some(order.unwrap_or(2)),
1161            AlgTag::Identity(term) => identity = Some(term.clone()),
1162            AlgTag::Cancellative => cancellative = true,
1163            AlgTag::Inverse(n) => inverse = Some(n.clone()),
1164        }
1165    }
1166
1167    // --- Validation (reject at registration; design §"Validation at registration") ---
1168    if comm && matches!(dir, Some(AssocDir::Left) | Some(AssocDir::Right)) {
1169        return Err(serr(
1170            ":assoc-left/:assoc-right cannot be combined with :comm; use :assoc :comm for AC",
1171            Span::Dummy,
1172        ));
1173    }
1174    if idempotent && nilpotent.is_some() {
1175        return Err(serr(
1176            ":idempotent and :nilpotent are mutually exclusive",
1177            Span::Dummy,
1178        ));
1179    }
1180    // Idempotent + inverse is algebraically incoherent, not merely unimplemented: an idempotent
1181    // group is trivial (x∘x = x ⟹ x = e), so an idempotent op has no non-trivial inverses. (The
1182    // intended `not`/complement cancels to the annihilator, not the identity — it is a `xor`, not
1183    // an `and`-inverse. See the design doc "Inverse is a group inverse, not a complement".)
1184    if idempotent && inverse.is_some() {
1185        return Err(serr(
1186            ":idempotent and :inverse are mutually exclusive (an idempotent op has no group inverse; \
1187             logical negation is xor-with-true, not an and-inverse)",
1188            Span::Dummy,
1189        ));
1190    }
1191    // A cancellative idempotent monoid is trivial: x∘x = x and cancellation
1192    // give x = e for every x, so the tag set describes a one-element algebra.
1193    if idempotent && cancellative {
1194        return Err(serr(
1195            ":idempotent and :cancellative are mutually exclusive (a cancellative idempotent \
1196             monoid collapses to the identity)",
1197            Span::Dummy,
1198        ));
1199    }
1200    if (idempotent || nilpotent.is_some()) && !(assoc && comm) {
1201        return Err(serr(
1202            ":idempotent/:nilpotent require :assoc :comm",
1203            Span::Dummy,
1204        ));
1205    }
1206    if nilpotent.is_some() && identity.is_none() {
1207        return Err(serr(
1208            ":nilpotent requires :identity (the emptied monomial must reduce to the unit)",
1209            Span::Dummy,
1210        ));
1211    }
1212    if inverse.is_some() && identity.is_none() {
1213        return Err(serr(":inverse requires :identity", Span::Dummy));
1214    }
1215    // Cancellativity is an inference rule on AC monomial equations (Kapur §5); on an
1216    // A-only, C-only, or plain operator the tag would be stored nowhere and silently
1217    // ignored, so reject it up front like the other AC-only property tags.
1218    if cancellative && !(assoc && comm) {
1219        return Err(serr(
1220            ":cancellative requires :assoc :comm (an AC operator)",
1221            Span::Dummy,
1222        ));
1223    }
1224    // `:cancellative` drives the Kapur §5 cancel-closure
1225    // inferences (C1 rule cancel-close + C2 cancelative disjoint superposition, minus the
1226    // §5.2(iii)(b) no-identity per-constant case), and `:inverse` drives inverse-PAIR
1227    // cancellation (x ∘ inv(x) = e) — gate-level group support, not §5.4's full
1228    // Abelian-group completion. An op with an inverse is cancelative (a group is), so the
1229    // flag is implied below.
1230    let cancellative = cancellative || inverse.is_some();
1231
1232    // Build the deferred unit reference from the identity term, if any.
1233    let unit_ref = match &identity {
1234        None => None,
1235        Some(Term::Lit(tok, _)) => Some(UnitRef::Lit { token: tok.clone() }),
1236        Some(term @ Term::App { .. }) => Some(UnitRef::Ctor { term: term.clone() }),
1237    };
1238
1239    // --- Dispatch on the (assoc, comm) shape ---
1240    match (assoc, comm) {
1241        // AC family: assoc + comm, variadic (1 declared arg sort).
1242        (true, true) => {
1243            if args.len() != 1 {
1244                return Err(serr(
1245                    ":assoc :comm operator takes one argument sort",
1246                    Span::Dummy,
1247                ));
1248            }
1249            if args[0] != ret {
1250                return Err(serr(
1251                    format!(
1252                        "associative operator '{name}' must use the same argument and return \
1253                         sort (argument '{}', return '{}')",
1254                        eg.sorts().name(args[0]),
1255                        eg.sorts().name(ret),
1256                    ),
1257                    Span::Dummy,
1258                ));
1259            }
1260            // Partition is derived from the clamp (design "storage partition and clamp are
1261            // independent"): idempotent → Set (dedup is the sound build canonize); plain AC and
1262            // nilpotent → MSet (nilpotent needs true multiplicities for the build/recanonize
1263            // mod-n reduction — the Set dedup canonize would destroy them).
1264            let kind = if idempotent {
1265                OpKind::Set {
1266                    arg_sort: args[0],
1267                    clamp: Clamp::Idempotent,
1268                    identity: unit_ref,
1269                    cancellative,
1270                }
1271            } else {
1272                OpKind::MSet {
1273                    arg_sort: args[0],
1274                    clamp: match nilpotent {
1275                        Some(order) => Clamp::Nilpotent { order },
1276                        None => Clamp::None,
1277                    },
1278                    identity: unit_ref,
1279                    cancellative,
1280                }
1281            };
1282            let op = eg.register_kind_meta(name, ret, kind, meta);
1283            // Resolve `:identity e` to a real node NOW (sortcheck has the model to parse the
1284            // term; the node id is stored in the egraph's per-op unit map — `OpKind<S>` cannot
1285            // carry a `Cfg::G`). The unit must sort-check to the op's return sort and be a
1286            // ground term (a literal or a constructor over ground args), so its constructors
1287            // must already be declared. Stored on the egraph, rolls back with the op decl.
1288            if let Some(term) = &identity {
1289                let ct = check_term(term, Some(ret), eg.ops(), eg.sorts(), model, globals)
1290                    .map_err(|e| {
1291                        serr(
1292                            format!(":identity term does not sort-check: {e}"),
1293                            Span::Dummy,
1294                        )
1295                    })?;
1296                let unit = eg.build_ground_cterm(&ct);
1297                eg.set_unit_node(op, unit);
1298            }
1299            // Resolve `:inverse neg` to a real op id now (it must be declared before this
1300            // op, like the identity's constructors) and validate the group-inverse
1301            // signature `neg : ret -> ret`. Stored in the egraph's per-op inverse map
1302            // (same persistence as the unit map).
1303            if let Some(inv_name) = &inverse {
1304                let inv_op = eg.ops().id_by_name(inv_name).ok_or_else(|| {
1305                    serr(
1306                        format!(":inverse operator '{inv_name}' is not declared"),
1307                        Span::Dummy,
1308                    )
1309                })?;
1310                let info = eg.ops().info(inv_op);
1311                let sig_ok = matches!(
1312                    &info.kind,
1313                    OpKind::Normal { arg_sorts } if arg_sorts.as_slice() == [ret]
1314                ) && info.return_sort == ret;
1315                if !sig_ok {
1316                    return Err(serr(
1317                        format!(
1318                            ":inverse operator '{inv_name}' must be unary over the op's \
1319                             sort (inv : S -> S)"
1320                        ),
1321                        Span::Dummy,
1322                    ));
1323                }
1324                eg.set_inverse_op(op, inv_op);
1325            }
1326            Ok(op)
1327        }
1328        // Associative-only (A): a sequence op; no comm/idempotent/nilpotent/identity semantics.
1329        (true, false) => {
1330            if idempotent || nilpotent.is_some() || identity.is_some() || inverse.is_some() {
1331                return Err(serr(
1332                    ":idempotent/:nilpotent/:identity/:inverse require :comm (an AC operator)",
1333                    Span::Dummy,
1334                ));
1335            }
1336            if args.len() != 1 {
1337                return Err(serr(":assoc requires 1 argument sort", Span::Dummy));
1338            }
1339            if args[0] != ret {
1340                return Err(serr(
1341                    format!(
1342                        "associative operator '{name}' must use the same argument and return \
1343                         sort (argument '{}', return '{}')",
1344                        eg.sorts().name(args[0]),
1345                        eg.sorts().name(ret),
1346                    ),
1347                    Span::Dummy,
1348                ));
1349            }
1350            Ok(eg.register_kind_meta(
1351                name,
1352                ret,
1353                OpKind::A {
1354                    arg_sort: args[0],
1355                    dir: dir.unwrap_or(AssocDir::Both),
1356                },
1357                meta,
1358            ))
1359        }
1360        // Commutative-only (C): binary.
1361        (false, true) => {
1362            if idempotent || nilpotent.is_some() || identity.is_some() || inverse.is_some() {
1363                return Err(serr(
1364                    ":idempotent/:nilpotent/:identity/:inverse require :assoc (an AC operator)",
1365                    Span::Dummy,
1366                ));
1367            }
1368            if args.len() != 2 {
1369                return Err(serr(":comm requires 2 argument sorts", Span::Dummy));
1370            }
1371            if args[0] != args[1] {
1372                return Err(serr(
1373                    format!(
1374                        "commutative operator '{name}' must use the same sort for both arguments \
1375                         (got '{}' and '{}')",
1376                        eg.sorts().name(args[0]),
1377                        eg.sorts().name(args[1]),
1378                    ),
1379                    Span::Dummy,
1380                ));
1381            }
1382            Ok(eg.register_kind_meta(
1383                name,
1384                ret,
1385                OpKind::Commutative {
1386                    arg_sorts: [args[0], args[1]],
1387                },
1388                meta,
1389            ))
1390        }
1391        // No structural tag but property tags present → error (idempotent-only etc. is meaningless).
1392        (false, false) => Err(serr(
1393            "algebra tags require :assoc and/or :comm",
1394            Span::Dummy,
1395        )),
1396    }
1397}