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