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