uor-foundation-sdk 0.3.2

Procedural-macro ergonomics for uor-foundation product, coproduct, and cartesian-product shape construction.
Documentation
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
// @generated by uor-crate from uor-ontology — do not edit manually

//! UOR Foundation SDK — procedural-macro ergonomics for `uor-foundation`.
//!
//! Emitted by `codegen/src/sdk_macros.rs` from the ontology. Consumers of
//! this crate must also depend on `uor-foundation`; the macros emit
//! absolute-path references (`::uor_foundation::…`) that resolve in the
//! *consumer's* dependency graph.
//!
//! # Macros
//!
//! - [`product_shape!`] — emits a `ConstrainedTypeShape` impl and a
//!   `mint_product_witness` helper for the UOR product type `A × B`
//!   (PT_1 / PT_2a / PT_3 / PT_4).
//! - [`coproduct_shape!`] — emits a `ConstrainedTypeShape` impl and a
//!   `mint_coproduct_witness` helper for the UOR sum type `A + B`
//!   (ST_1 / ST_2 / ST_6 / ST_7 / ST_8 / ST_9 / ST_10).
//! - [`cartesian_product_shape!`] — emits a `ConstrainedTypeShape` impl,
//!   a `CartesianProductShape` marker impl, and a `mint_cartesian_witness`
//!   helper for the UOR Cartesian-partition product `A ⊠ B`
//!   (CPT_1 / CPT_2a / CPT_3 / CPT_4 / CPT_5).
//! - [`prism_model!`] — emits the seal impls (`__sdk_seal::Sealed` for
//!   the model and the route witness), the `FoundationClosed` impl on
//!   the route witness, and the `PrismModel<H, B, A>` impl whose
//!   `forward` body delegates to `pipeline::run_route` (wiki ADR-020 +
//!   ADR-022 D1, D3, D4, D5).
//!
//! # Operand support
//!
//! Operand `CONSTRAINTS` arrays may contain every `ConstraintRef`
//! variant: `Residue`, `Hamming`, `Depth`, `Carry`, `Site`, `Affine`,
//! `SatClauses`, `Bound`, and `Conjunction`. Phase 17 stores
//! `Affine.coefficients` as a fixed-size
//! `[i64; AFFINE_MAX_COEFFS]` array (capacity 8) and limits
//! `Conjunction.conjuncts` to a `[LeafConstraintRef; CONJUNCTION_MAX_TERMS]`
//! depth-1 array; both are stable-Rust const-buildable, so the SDK
//! macros support the full operand catalogue. Inputs exceeding the
//! caps fail `validate_const()` with a typed `ShapeViolation`.

#![deny(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    missing_docs,
    clippy::missing_errors_doc
)]

use proc_macro::TokenStream;
use quote::quote;
use syn::parse::{Parse, ParseStream};
use syn::{parse_macro_input, Ident, Result, Token};

/// Callsite input for `product_shape!(Name, A, B)` — three identifier
/// tokens separated by commas.
struct ShapeArgs {
    name: Ident,
    left: Ident,
    right: Ident,
}

impl Parse for ShapeArgs {
    fn parse(input: ParseStream) -> Result<Self> {
        let name: Ident = input.parse()?;
        input.parse::<Token![,]>()?;
        let left: Ident = input.parse()?;
        input.parse::<Token![,]>()?;
        let right: Ident = input.parse()?;
        // Trailing comma permitted for consistency with Rust style.
        let _ = input.parse::<Token![,]>();
        Ok(Self { name, left, right })
    }
}

/// Product-type shape constructor. See crate-level docs.
///
/// # Example
///
/// ```
/// use uor_foundation::pipeline::{ConstrainedTypeShape, ConstraintRef};
/// use uor_foundation_sdk::product_shape;
///
/// pub struct A;
/// impl ConstrainedTypeShape for A {
///     const IRI: &'static str = "https://example.org/A";
///     const SITE_COUNT: usize = 1;
///     const CONSTRAINTS: &'static [ConstraintRef] = &[
///         ConstraintRef::Residue { modulus: 7, residue: 3 },
///     ];
/// }
///
/// pub struct B;
/// impl ConstrainedTypeShape for B {
///     const IRI: &'static str = "https://example.org/B";
///     const SITE_COUNT: usize = 1;
///     const CONSTRAINTS: &'static [ConstraintRef] = &[
///         ConstraintRef::Hamming { bound: 1 },
///     ];
/// }
///
/// product_shape!(MyProduct, A, B);
///
/// assert!(<MyProduct as ConstrainedTypeShape>::IRI.starts_with("urn:uor:product:"));
/// assert_eq!(<MyProduct as ConstrainedTypeShape>::SITE_COUNT, 2);
/// ```
#[proc_macro]
pub fn product_shape(input: TokenStream) -> TokenStream {
    let ShapeArgs { name, left, right } = parse_macro_input!(input as ShapeArgs);
    let iri = format!(
        "urn:uor:product:{}:{}",
        lexically_earlier(&left, &right),
        lexically_later(&left, &right)
    );
    // Canonicalize operand ordering by stable token spelling so
    // `product_shape!(X, A, B)` and `product_shape!(X, B, A)` emit
    // identical source. Documented as the §4e canonicalization rule the
    // SDK enforces — the runtime content-fingerprint match §4e describes
    // is then checked by consumer tests.
    let (l, r) = canonical_operand_pair(&left, &right);
    let raw_const = format_ident_suffix(&name, "__CONSTRAINTS_RAW");
    let len_const = format_ident_suffix(&name, "__CONSTRAINTS_LEN");

    let expansion = quote! {
        /// UOR ProductType shape, emitted by `product_shape!`.
        pub struct #name;

        const #raw_const:
            [::uor_foundation::pipeline::ConstraintRef;
             2 * ::uor_foundation::enforcement::NERVE_CONSTRAINTS_CAP]
        = ::uor_foundation::pipeline::sdk_concat_product_constraints::<#l, #r>();

        const #len_const: usize =
            ::uor_foundation::pipeline::sdk_product_constraints_len::<#l, #r>();

        impl ::uor_foundation::pipeline::ConstrainedTypeShape for #name {
            const IRI: &'static str = #iri;
            const SITE_BUDGET: usize =
                <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_BUDGET
                + <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_BUDGET;
            const SITE_COUNT: usize =
                <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT
                + <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
            const CONSTRAINTS: &'static [::uor_foundation::pipeline::ConstraintRef] = {
                let buf: &'static [::uor_foundation::pipeline::ConstraintRef] = &#raw_const;
                match buf.split_at_checked(#len_const) {
                    Some((head, _tail)) => head,
                    None => &[],
                }
            };
        }

        // Wiki ADR-023: shape-derived inputs receive their `IntoBindingValue`
        // impl alongside `ConstrainedTypeShape`. The shape struct is a
        // zero-sized type-level marker, so the canonical byte sequence is
        // empty (MAX_BYTES = 0) — applications that need to carry runtime
        // input data declare a custom `ConstrainedTypeShape` and write a
        // bespoke `IntoBindingValue` impl.
        impl ::uor_foundation::pipeline::__sdk_seal::Sealed for #name {}
        impl ::uor_foundation::pipeline::IntoBindingValue for #name {
            const MAX_BYTES: usize = 0;
            fn into_binding_bytes(
                &self,
                _out: &mut [u8],
            ) -> ::core::result::Result<usize, ::uor_foundation::enforcement::ShapeViolation> {
                Ok(0)
            }
        }

        impl #name {
            /// Mint a verified [`PartitionProductWitness`] for this shape's
            /// operand pair. The numeric invariants (Euler characteristics,
            /// entropy, fingerprints) are caller-supplied because they depend
            /// on the resolved constraint configuration; shape-derivable
            /// fields (site budgets / site counts) are read from the
            /// operand `ConstrainedTypeShape` impls.
            ///
            /// # Errors
            ///
            /// Returns a `GenericImpossibilityWitness` citing the specific
            /// failed identity when PT_1, PT_3, PT_4, or the foundation
            /// layout-width invariant fails.
            #[allow(clippy::too_many_arguments)]
            pub fn mint_product_witness(
                witt_bits: u16,
                left_fingerprint: ::uor_foundation::ContentFingerprint,
                right_fingerprint: ::uor_foundation::ContentFingerprint,
                left_euler: i32,
                right_euler: i32,
                left_entropy_nats_bits: u64,
                right_entropy_nats_bits: u64,
                combined_euler: i32,
                combined_entropy_nats_bits: u64,
                combined_fingerprint: ::uor_foundation::ContentFingerprint,
            ) -> ::core::result::Result<
                ::uor_foundation::PartitionProductWitness,
                ::uor_foundation::enforcement::GenericImpossibilityWitness,
            > {
                use ::uor_foundation::pipeline::ConstrainedTypeShape;
                let inputs = ::uor_foundation::PartitionProductMintInputs {
                    witt_bits,
                    left_fingerprint,
                    right_fingerprint,
                    left_site_budget: <#l as ConstrainedTypeShape>::SITE_BUDGET as u16,
                    right_site_budget: <#r as ConstrainedTypeShape>::SITE_BUDGET as u16,
                    left_total_site_count: <#l as ConstrainedTypeShape>::SITE_COUNT as u16,
                    right_total_site_count: <#r as ConstrainedTypeShape>::SITE_COUNT as u16,
                    left_euler,
                    right_euler,
                    left_entropy_nats_bits,
                    right_entropy_nats_bits,
                    combined_site_budget: <#name as ConstrainedTypeShape>::SITE_BUDGET as u16,
                    combined_site_count: <#name as ConstrainedTypeShape>::SITE_COUNT as u16,
                    combined_euler,
                    combined_entropy_nats_bits,
                    combined_fingerprint,
                };
                <::uor_foundation::PartitionProductWitness
                    as ::uor_foundation::VerifiedMint>::mint_verified(inputs)
            }
        }
    };

    expansion.into()
}

/// Coproduct shape constructor. See crate-level docs.
///
/// # Example
///
/// Demonstrates the post-Phase-17 fixed-array `Affine` operand variant.
///
/// ```
/// use uor_foundation::pipeline::{
///     AFFINE_MAX_COEFFS, ConstrainedTypeShape, ConstraintRef,
/// };
/// use uor_foundation_sdk::coproduct_shape;
///
/// const A_COEFFS: [i64; AFFINE_MAX_COEFFS] = {
///     let mut a = [0i64; AFFINE_MAX_COEFFS];
///     a[0] = 1;
///     a
/// };
///
/// pub struct A;
/// impl ConstrainedTypeShape for A {
///     const IRI: &'static str = "https://example.org/A";
///     const SITE_COUNT: usize = 1;
///     const CONSTRAINTS: &'static [ConstraintRef] = &[
///         ConstraintRef::Affine {
///             coefficients: A_COEFFS,
///             coefficient_count: 1,
///             bias: 0,
///         },
///     ];
/// }
///
/// pub struct B;
/// impl ConstrainedTypeShape for B {
///     const IRI: &'static str = "https://example.org/B";
///     const SITE_COUNT: usize = 1;
///     const CONSTRAINTS: &'static [ConstraintRef] = &[];
/// }
///
/// coproduct_shape!(MySum, A, B);
/// assert!(<MySum as ConstrainedTypeShape>::IRI.starts_with("urn:uor:coproduct:"));
/// ```
#[proc_macro]
pub fn coproduct_shape(input: TokenStream) -> TokenStream {
    let ShapeArgs { name, left, right } = parse_macro_input!(input as ShapeArgs);
    let iri = format!(
        "urn:uor:coproduct:{}:{}",
        lexically_earlier(&left, &right),
        lexically_later(&left, &right)
    );
    let (l, r) = canonical_operand_pair(&left, &right);

    // Per amendment §4b' + §4d: coproduct layout is
    //   constraints(A) ∪ {tag-pinner bias=0} ∪ constraints(B) ∪ {tag-pinner bias=-1}
    // with tag_site = max(SITE_COUNT(A), SITE_COUNT(B)). The foundation
    // `sdk_concat_product_constraints` helper handles the A / B splice
    // but the two Affine tag-pinners require construction at macro time,
    // because the tag_site index is a call-site-specific const expression.
    //
    // For a coproduct, the Affine coefficient slices are `&[i64]` with
    // all-zero entries except position tag_site = 1. Since the macro
    // cannot allocate `&'static [i64]` slices of arbitrary length, the
    // emission uses a fixed-size coefficient array that matches
    // `NERVE_CONSTRAINTS_CAP` (the bound on site indices in SDK shapes).
    let raw_const = format_ident_suffix(&name, "__CONSTRAINTS_RAW");
    let len_const = format_ident_suffix(&name, "__CONSTRAINTS_LEN");
    let tag_coeffs_l = format_ident_suffix(&name, "__TAG_COEFFS_L");
    let tag_coeffs_r = format_ident_suffix(&name, "__TAG_COEFFS_R");
    let tag_coeff_count = format_ident_suffix(&name, "__TAG_COEFF_COUNT");

    let expansion = quote! {
        /// UOR SumType shape, emitted by `coproduct_shape!`.
        pub struct #name;

        // Two tag-pinning Affine coefficient arrays, one per variant,
        // each of length 2 * NERVE_CONSTRAINTS_CAP so the single `1` at
        // the tag_site position fits regardless of how wide the
        // operands' SITE_COUNTs are (bounded by NERVE_CONSTRAINTS_CAP
        // each, so tag_site = max(L::SITE_COUNT, R::SITE_COUNT) <
        // Phase 17: tag-pinner coefficient buffer is now a fixed-size
        // `[i64; AFFINE_MAX_COEFFS]` array stored inline in the
        // ConstraintRef::Affine variant. The active prefix runs to
        // `tag_site + 1`. For coproduct shapes whose
        // `max(L::SITE_COUNT, R::SITE_COUNT) + 1` exceeds
        // AFFINE_MAX_COEFFS = 8, the const-eval clamps the tag-pinner
        // to a no-op (count = 0), and `validate_const` rejects the
        // shape at admission time as Affine-unsatisfiable.
        const #tag_coeffs_l: [i64; ::uor_foundation::pipeline::AFFINE_MAX_COEFFS] = {
            let mut out = [0i64; ::uor_foundation::pipeline::AFFINE_MAX_COEFFS];
            let tag_site = {
                let a = <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
                let b = <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
                if a > b { a } else { b }
            };
            if tag_site < ::uor_foundation::pipeline::AFFINE_MAX_COEFFS {
                out[tag_site] = 1;
            }
            out
        };
        const #tag_coeffs_r: [i64; ::uor_foundation::pipeline::AFFINE_MAX_COEFFS] = #tag_coeffs_l;
        const #tag_coeff_count: u32 = {
            let a = <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
            let b = <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
            let tag_site = if a > b { a } else { b };
            (tag_site as u32).saturating_add(1)
        };

        // Full constraint buffer: L constraints + L tag-pinner (bias=0)
        // + R constraints (shifted by L::SITE_COUNT? — per amendment §4d
        // sum types share the data-site space so R's site references are
        // NOT shifted). The foundation helper
        // `sdk_concat_product_constraints` shifts R by A::SITE_COUNT, which
        // is correct for products but wrong for coproducts. Coproducts
        // instead splice R's constraints verbatim since the tag site is
        // the distinguishing bit, not a layout offset.
        //
        // This makes coproduct construction diverge from the helper's
        // assumption, so we emit a per-callsite const fn that does the
        // correct coproduct splice.
        const #raw_const:
            [::uor_foundation::pipeline::ConstraintRef;
             2 * ::uor_foundation::enforcement::NERVE_CONSTRAINTS_CAP + 2]
        = {
            let mut out =
                [::uor_foundation::pipeline::ConstraintRef::Site { position: u32::MAX };
                 2 * ::uor_foundation::enforcement::NERVE_CONSTRAINTS_CAP + 2];
            let left_arr = <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::CONSTRAINTS;
            let right_arr = <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::CONSTRAINTS;
            let mut i = 0;
            while i < left_arr.len() {
                out[i] = left_arr[i];
                i += 1;
            }
            // L's tag-pinner: bias 0.
            out[i] = ::uor_foundation::pipeline::ConstraintRef::Affine {
                coefficients: #tag_coeffs_l,
                coefficient_count: #tag_coeff_count,
                bias: 0,
            };
            let left_boundary = i + 1;
            let mut j = 0;
            while j < right_arr.len() {
                out[left_boundary + j] = right_arr[j];
                j += 1;
            }
            // R's tag-pinner: bias -1.
            out[left_boundary + right_arr.len()] = ::uor_foundation::pipeline::ConstraintRef::Affine {
                coefficients: #tag_coeffs_r,
                coefficient_count: #tag_coeff_count,
                bias: -1,
            };
            out
        };
        const #len_const: usize =
            <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::CONSTRAINTS.len()
            + <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::CONSTRAINTS.len()
            + 2;

        impl ::uor_foundation::pipeline::ConstrainedTypeShape for #name {
            const IRI: &'static str = #iri;
            const SITE_BUDGET: usize = {
                let a = <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_BUDGET;
                let b = <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_BUDGET;
                if a > b { a } else { b }
            };
            const SITE_COUNT: usize = {
                let a = <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
                let b = <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
                (if a > b { a } else { b }) + 1
            };
            const CONSTRAINTS: &'static [::uor_foundation::pipeline::ConstraintRef] = {
                let buf: &'static [::uor_foundation::pipeline::ConstraintRef] = &#raw_const;
                match buf.split_at_checked(#len_const) {
                    Some((head, _tail)) => head,
                    None => &[],
                }
            };
        }

        // Wiki ADR-023: shape-derived inputs receive their `IntoBindingValue`
        // impl alongside `ConstrainedTypeShape` (zero-sized marker; canonical
        // byte sequence is empty).
        impl ::uor_foundation::pipeline::__sdk_seal::Sealed for #name {}
        impl ::uor_foundation::pipeline::IntoBindingValue for #name {
            const MAX_BYTES: usize = 0;
            fn into_binding_bytes(
                &self,
                _out: &mut [u8],
            ) -> ::core::result::Result<usize, ::uor_foundation::enforcement::ShapeViolation> {
                Ok(0)
            }
        }

        impl #name {
            /// Mint a verified [`PartitionCoproductWitness`] for this shape's
            /// operand pair. See `product_shape!`'s `mint_product_witness`
            /// doc comment for the caller-vs-derived field split.
            ///
            /// # Errors
            ///
            /// Returns a `GenericImpossibilityWitness` citing the specific
            /// failed identity when ST_1, ST_2, ST_6, ST_7, ST_8, ST_9,
            /// ST_10, the `CoproductLayoutWidth` layout invariant, or the
            /// `CoproductTagEncoding` byte-pattern invariant fails.
            #[allow(clippy::too_many_arguments)]
            pub fn mint_coproduct_witness(
                witt_bits: u16,
                left_fingerprint: ::uor_foundation::ContentFingerprint,
                right_fingerprint: ::uor_foundation::ContentFingerprint,
                left_euler: i32,
                right_euler: i32,
                left_entropy_nats_bits: u64,
                right_entropy_nats_bits: u64,
                left_betti: [u32; ::uor_foundation::enforcement::MAX_BETTI_DIMENSION],
                right_betti: [u32; ::uor_foundation::enforcement::MAX_BETTI_DIMENSION],
                combined_euler: i32,
                combined_entropy_nats_bits: u64,
                combined_betti: [u32; ::uor_foundation::enforcement::MAX_BETTI_DIMENSION],
                combined_fingerprint: ::uor_foundation::ContentFingerprint,
            ) -> ::core::result::Result<
                ::uor_foundation::PartitionCoproductWitness,
                ::uor_foundation::enforcement::GenericImpossibilityWitness,
            > {
                use ::uor_foundation::pipeline::ConstrainedTypeShape;
                let left_total_site_count = <#l as ConstrainedTypeShape>::SITE_COUNT as u16;
                let right_total_site_count = <#r as ConstrainedTypeShape>::SITE_COUNT as u16;
                let tag_site = if left_total_site_count > right_total_site_count {
                    left_total_site_count
                } else {
                    right_total_site_count
                };
                let left_constraint_count =
                    <#l as ConstrainedTypeShape>::CONSTRAINTS.len() + 1;
                let inputs = ::uor_foundation::PartitionCoproductMintInputs {
                    witt_bits,
                    left_fingerprint,
                    right_fingerprint,
                    left_site_budget: <#l as ConstrainedTypeShape>::SITE_BUDGET as u16,
                    right_site_budget: <#r as ConstrainedTypeShape>::SITE_BUDGET as u16,
                    left_total_site_count,
                    right_total_site_count,
                    left_euler,
                    right_euler,
                    left_entropy_nats_bits,
                    right_entropy_nats_bits,
                    left_betti,
                    right_betti,
                    combined_site_budget: <#name as ConstrainedTypeShape>::SITE_BUDGET as u16,
                    combined_site_count: <#name as ConstrainedTypeShape>::SITE_COUNT as u16,
                    combined_euler,
                    combined_entropy_nats_bits,
                    combined_betti,
                    combined_fingerprint,
                    combined_constraints: <#name as ConstrainedTypeShape>::CONSTRAINTS,
                    left_constraint_count,
                    tag_site,
                };
                <::uor_foundation::PartitionCoproductWitness
                    as ::uor_foundation::VerifiedMint>::mint_verified(inputs)
            }
        }
    };

    expansion.into()
}

/// Cartesian-product shape constructor. See crate-level docs.
///
/// # Example
///
/// ```
/// use uor_foundation::pipeline::{
///     CartesianProductShape, ConstrainedTypeShape, ConstraintRef,
/// };
/// use uor_foundation_sdk::cartesian_product_shape;
///
/// pub struct A;
/// impl ConstrainedTypeShape for A {
///     const IRI: &'static str = "https://example.org/A";
///     const SITE_COUNT: usize = 1;
///     const CONSTRAINTS: &'static [ConstraintRef] = &[];
/// }
/// pub struct B;
/// impl ConstrainedTypeShape for B {
///     const IRI: &'static str = "https://example.org/B";
///     const SITE_COUNT: usize = 1;
///     const CONSTRAINTS: &'static [ConstraintRef] = &[];
/// }
///
/// cartesian_product_shape!(MyCartesian, A, B);
///
/// fn assert_marker<T: CartesianProductShape>() {}
/// assert_marker::<MyCartesian>();
/// ```
#[proc_macro]
pub fn cartesian_product_shape(input: TokenStream) -> TokenStream {
    let ShapeArgs { name, left, right } = parse_macro_input!(input as ShapeArgs);
    let iri = format!(
        "urn:uor:cartesian:{}:{}",
        lexically_earlier(&left, &right),
        lexically_later(&left, &right)
    );
    let (l, r) = canonical_operand_pair(&left, &right);
    let raw_const = format_ident_suffix(&name, "__CONSTRAINTS_RAW");
    let len_const = format_ident_suffix(&name, "__CONSTRAINTS_LEN");

    // CartesianProduct emission mirrors product_shape!'s layout but
    // additionally implements `CartesianProductShape` so the nerve-Betti
    // pipeline uses `primitive_cartesian_nerve_betti` (Künneth) instead of
    // the flat simplicial primitive.
    let expansion = quote! {
        /// UOR CartesianPartitionProduct shape, emitted by
        /// `cartesian_product_shape!`.
        pub struct #name;

        const #raw_const:
            [::uor_foundation::pipeline::ConstraintRef;
             2 * ::uor_foundation::enforcement::NERVE_CONSTRAINTS_CAP]
        = ::uor_foundation::pipeline::sdk_concat_product_constraints::<#l, #r>();

        const #len_const: usize =
            ::uor_foundation::pipeline::sdk_product_constraints_len::<#l, #r>();

        impl ::uor_foundation::pipeline::ConstrainedTypeShape for #name {
            const IRI: &'static str = #iri;
            const SITE_BUDGET: usize =
                <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_BUDGET
                + <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_BUDGET;
            const SITE_COUNT: usize =
                <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT
                + <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
            const CONSTRAINTS: &'static [::uor_foundation::pipeline::ConstraintRef] = {
                let buf: &'static [::uor_foundation::pipeline::ConstraintRef] = &#raw_const;
                match buf.split_at_checked(#len_const) {
                    Some((head, _tail)) => head,
                    None => &[],
                }
            };
        }

        impl ::uor_foundation::pipeline::CartesianProductShape for #name {
            type Left = #l;
            type Right = #r;
        }

        // Wiki ADR-023: shape-derived inputs receive their `IntoBindingValue`
        // impl alongside `ConstrainedTypeShape` (zero-sized marker; canonical
        // byte sequence is empty).
        impl ::uor_foundation::pipeline::__sdk_seal::Sealed for #name {}
        impl ::uor_foundation::pipeline::IntoBindingValue for #name {
            const MAX_BYTES: usize = 0;
            fn into_binding_bytes(
                &self,
                _out: &mut [u8],
            ) -> ::core::result::Result<usize, ::uor_foundation::enforcement::ShapeViolation> {
                Ok(0)
            }
        }

        impl #name {
            /// Mint a verified [`CartesianProductWitness`] for this shape's
            /// operand pair.
            ///
            /// # Errors
            ///
            /// Returns a `GenericImpossibilityWitness` citing the specific
            /// failed identity when CPT_1, CPT_3, CPT_4, CPT_5, or the
            /// `CartesianLayoutWidth` layout invariant fails.
            #[allow(clippy::too_many_arguments)]
            pub fn mint_cartesian_witness(
                witt_bits: u16,
                left_fingerprint: ::uor_foundation::ContentFingerprint,
                right_fingerprint: ::uor_foundation::ContentFingerprint,
                left_euler: i32,
                right_euler: i32,
                left_betti: [u32; ::uor_foundation::enforcement::MAX_BETTI_DIMENSION],
                right_betti: [u32; ::uor_foundation::enforcement::MAX_BETTI_DIMENSION],
                left_entropy_nats_bits: u64,
                right_entropy_nats_bits: u64,
                combined_euler: i32,
                combined_betti: [u32; ::uor_foundation::enforcement::MAX_BETTI_DIMENSION],
                combined_entropy_nats_bits: u64,
                combined_fingerprint: ::uor_foundation::ContentFingerprint,
            ) -> ::core::result::Result<
                ::uor_foundation::CartesianProductWitness,
                ::uor_foundation::enforcement::GenericImpossibilityWitness,
            > {
                use ::uor_foundation::pipeline::ConstrainedTypeShape;
                let inputs = ::uor_foundation::CartesianProductMintInputs {
                    witt_bits,
                    left_fingerprint,
                    right_fingerprint,
                    left_site_budget: <#l as ConstrainedTypeShape>::SITE_BUDGET as u16,
                    right_site_budget: <#r as ConstrainedTypeShape>::SITE_BUDGET as u16,
                    left_total_site_count: <#l as ConstrainedTypeShape>::SITE_COUNT as u16,
                    right_total_site_count: <#r as ConstrainedTypeShape>::SITE_COUNT as u16,
                    left_euler,
                    right_euler,
                    left_betti,
                    right_betti,
                    left_entropy_nats_bits,
                    right_entropy_nats_bits,
                    combined_site_budget: <#name as ConstrainedTypeShape>::SITE_BUDGET as u16,
                    combined_site_count: <#name as ConstrainedTypeShape>::SITE_COUNT as u16,
                    combined_euler,
                    combined_betti,
                    combined_entropy_nats_bits,
                    combined_fingerprint,
                };
                <::uor_foundation::CartesianProductWitness
                    as ::uor_foundation::VerifiedMint>::mint_verified(inputs)
            }
        }
    };

    expansion.into()
}

// =====================================================================
// `prism_model!` — wiki ADR-020 + ADR-022 D3.
//
// The macro accepts the closure-bodied form the wiki specifies as the
// maximally-Rust-native syntax for declaring a Prism model:
//
// ```text
// prism_model! {
//     pub struct MyModel;
//     pub struct MyRoute;
//     impl PrismModel<HType, BType, AType> for MyModel {
//         type Input  = InputShape;
//         type Output = OutputShape;
//         type Route  = MyRoute;
//         fn route(input: Self::Input) -> Self::Output {
//             // closure body — Rust expression syntax parsed by the macro
//             // into a Term tree at expansion time. The body never executes
//             // as Rust at runtime; it is consumed at macro time, mapped to
//             // the term-tree representation, and the macro emits both the
//             // term tree (as a `&'static [Term]` slice) and the
//             // closure-checked `FoundationClosed` impl.
//             //
//             // Recognised foundation-vocabulary forms:
//             //   - integer literals          → Term::Literal
//             //   - identifier `input`        → Term::Variable
//             //   - lowercase PrimitiveOp     → Term::Application
//             //     names: add, sub, mul, xor, and, or
//             //           neg, bnot, succ, pred
//             // Anything else fails to compile, pointing at the offending
//             // call site (a closure violation per ADR-020).
//         }
//     }
// }
// ```
//
// Emissions (per ADR-022):
//   D1: `impl __sdk_seal::Sealed for MyModel`,
//       `impl __sdk_seal::Sealed for MyRoute`
//   D2: `const ROUTE_TERMS_<MODEL>: &'static [Term] = &[…]` (fully const
//       — `TermArena::from_slice(ROUTE_TERMS_<MODEL>)` is a `const fn`)
//   D5: `impl FoundationClosed for MyRoute { arena_slice() → ROUTE_TERMS_<MODEL> }`
//   D4: `impl PrismModel<H,B,A> for MyModel { …; fn forward(input) { run_route::<H,B,A,Self>(input) } }`

/// Parsed shape of the macro input — a struct declaration for the model,
/// optionally one for the route witness, and an `impl PrismModel<…> for
/// <Model>` block carrying the three associated types and the closure-bodied
/// `route` function.
struct PrismModelInput {
    model_vis: syn::Visibility,
    model_name: Ident,
    route_vis: syn::Visibility,
    route_name: Ident,
    h_ty: syn::Type,
    b_ty: syn::Type,
    a_ty: syn::Type,
    input_ty: syn::Type,
    output_ty: syn::Type,
    route_input_ident: Ident,
    route_body: syn::Block,
}

impl Parse for PrismModelInput {
    fn parse(input: ParseStream) -> Result<Self> {
        // Model struct: `pub struct ModelName;`
        let model_vis: syn::Visibility = input.parse()?;
        input.parse::<Token![struct]>()?;
        let model_name: Ident = input.parse()?;
        input.parse::<Token![;]>()?;

        // Route witness struct: `pub struct RouteName;`
        let route_vis: syn::Visibility = input.parse()?;
        input.parse::<Token![struct]>()?;
        let route_name: Ident = input.parse()?;
        input.parse::<Token![;]>()?;

        // `impl PrismModel<H, B, A> for ModelName`
        input.parse::<Token![impl]>()?;
        let trait_ident: Ident = input.parse()?;
        if trait_ident != "PrismModel" {
            return Err(syn::Error::new(
                trait_ident.span(),
                "prism_model! expects an `impl PrismModel<H, B, A> for <Model>` block",
            ));
        }
        input.parse::<Token![<]>()?;
        let h_ty: syn::Type = input.parse()?;
        input.parse::<Token![,]>()?;
        let b_ty: syn::Type = input.parse()?;
        input.parse::<Token![,]>()?;
        let a_ty: syn::Type = input.parse()?;
        input.parse::<Token![>]>()?;
        input.parse::<Token![for]>()?;
        let impl_target: Ident = input.parse()?;
        if impl_target != model_name {
            return Err(syn::Error::new(
                impl_target.span(),
                "prism_model!'s `impl PrismModel<…> for <Model>` target must match the declared model struct",
            ));
        }

        // Body of the impl block: `{ type Input = …; type Output = …; type Route = …; fn route(…) { … } }`
        let body;
        syn::braced!(body in input);

        // type Input = …;
        body.parse::<Token![type]>()?;
        let input_kw: Ident = body.parse()?;
        if input_kw != "Input" {
            return Err(syn::Error::new(
                input_kw.span(),
                "expected `type Input = …;`",
            ));
        }
        body.parse::<Token![=]>()?;
        let input_ty: syn::Type = body.parse()?;
        body.parse::<Token![;]>()?;

        // type Output = …;
        body.parse::<Token![type]>()?;
        let output_kw: Ident = body.parse()?;
        if output_kw != "Output" {
            return Err(syn::Error::new(
                output_kw.span(),
                "expected `type Output = …;`",
            ));
        }
        body.parse::<Token![=]>()?;
        let output_ty: syn::Type = body.parse()?;
        body.parse::<Token![;]>()?;

        // type Route = …;
        body.parse::<Token![type]>()?;
        let route_kw: Ident = body.parse()?;
        if route_kw != "Route" {
            return Err(syn::Error::new(
                route_kw.span(),
                "expected `type Route = …;`",
            ));
        }
        body.parse::<Token![=]>()?;
        let route_ty_ident: Ident = body.parse()?;
        if route_ty_ident != route_name {
            return Err(syn::Error::new(
                route_ty_ident.span(),
                "prism_model!'s `type Route = <RouteName>;` must match the declared route struct",
            ));
        }
        body.parse::<Token![;]>()?;

        // fn route(input: Self::Input) -> Self::Output { … }
        body.parse::<Token![fn]>()?;
        let fn_kw: Ident = body.parse()?;
        if fn_kw != "route" {
            return Err(syn::Error::new(
                fn_kw.span(),
                "expected `fn route(input: Self::Input) -> Self::Output { … }`",
            ));
        }
        let params;
        syn::parenthesized!(params in body);
        let route_input_ident: Ident = params.parse()?;
        params.parse::<Token![:]>()?;
        let _input_param_ty: syn::Type = params.parse()?;
        // Discard return-type position — we already know it from `type Output`.
        body.parse::<Token![->]>()?;
        let _output_param_ty: syn::Type = body.parse()?;
        let route_body: syn::Block = body.parse()?;

        Ok(Self {
            model_vis,
            model_name,
            route_vis,
            route_name,
            h_ty,
            b_ty,
            a_ty,
            input_ty,
            output_ty,
            route_input_ident,
            route_body,
        })
    }
}

/// One spec entry in the term arena being built. Maps to a `Term::*`
/// variant token stream at emission time.
enum TermSpec {
    /// `Term::Literal { value, level: WittLevel::W8 }`
    Literal(u64),
    /// `Term::Variable { name_index: 0 }` (the macro recognises `input`
    /// as the sole bound name; future iterations support `let` bindings).
    Variable,
    /// `Term::Application { operator, args: TermList { start, len } }`
    Application {
        operator: proc_macro2::TokenStream,
        args_start: u32,
        args_len: u32,
    },
}

/// Recursively walk a Rust expression and append the terms that compute
/// it to `arena`, returning the index where this expression's *root*
/// term lands. `route_input` is the name of the route's bound input
/// parameter (mapped to `Term::Variable { name_index: 0 }`).
fn emit_term_for_expr(
    expr: &syn::Expr,
    route_input: &Ident,
    arena: &mut Vec<TermSpec>,
) -> Result<usize> {
    match expr {
        syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(int_lit), .. }) => {
            let value: u64 = int_lit.base10_parse().map_err(|e| {
                syn::Error::new(int_lit.span(), format!("integer literal out of u64 range: {e}"))
            })?;
            let idx = arena.len();
            arena.push(TermSpec::Literal(value));
            Ok(idx)
        }
        syn::Expr::Path(path_expr) if path_expr.path.get_ident() == Some(route_input) => {
            let idx = arena.len();
            arena.push(TermSpec::Variable);
            Ok(idx)
        }
        syn::Expr::Path(path_expr) => Err(syn::Error::new_spanned(
            path_expr,
            "closure violation: identifier is not a foundation-vocabulary name (only the route's `input` parameter is recognised as a variable reference)",
        )),
        syn::Expr::Call(call_expr) => emit_term_for_call(call_expr, route_input, arena),
        syn::Expr::Block(block_expr) => {
            // A `{ expr }` block — accept iff it has exactly one expression
            // statement (the canonical closure-body shape after parsing).
            let stmts = &block_expr.block.stmts;
            if stmts.len() == 1 {
                if let syn::Stmt::Expr(inner, _) = &stmts[0] {
                    return emit_term_for_expr(inner, route_input, arena);
                }
            }
            Err(syn::Error::new_spanned(
                block_expr,
                "closure violation: block expressions must contain exactly one expression statement",
            ))
        }
        syn::Expr::Paren(paren_expr) => emit_term_for_expr(&paren_expr.expr, route_input, arena),
        other => Err(syn::Error::new_spanned(
            other,
            "closure violation: expression form is not in foundation vocabulary (recognised forms: integer literals, the route's `input` parameter, and lowercase PrimitiveOp function calls — add, sub, mul, xor, and, or, neg, bnot, succ, pred)",
        )),
    }
}

/// Map a function-call expression to a `Term::Application`. Recognises
/// the ten lowercase PrimitiveOp names and rejects anything else as a
/// closure violation.
fn emit_term_for_call(
    call: &syn::ExprCall,
    route_input: &Ident,
    arena: &mut Vec<TermSpec>,
) -> Result<usize> {
    // The function being called must be a bare identifier matching one
    // of the recognised PrimitiveOp names.
    let func_ident = match call.func.as_ref() {
        syn::Expr::Path(p) => p.path.get_ident().cloned().ok_or_else(|| {
            syn::Error::new_spanned(
                &call.func,
                "closure violation: call target must be a bare identifier matching a PrimitiveOp name",
            )
        })?,
        other => {
            return Err(syn::Error::new_spanned(
                other,
                "closure violation: call target must be a bare identifier matching a PrimitiveOp name",
            ));
        }
    };

    let (operator, expected_arity) = match func_ident.to_string().as_str() {
        "add" => (quote! { ::uor_foundation::PrimitiveOp::Add }, 2usize),
        "sub" => (quote! { ::uor_foundation::PrimitiveOp::Sub }, 2),
        "mul" => (quote! { ::uor_foundation::PrimitiveOp::Mul }, 2),
        "xor" => (quote! { ::uor_foundation::PrimitiveOp::Xor }, 2),
        "and" => (quote! { ::uor_foundation::PrimitiveOp::And }, 2),
        "or" => (quote! { ::uor_foundation::PrimitiveOp::Or }, 2),
        "neg" => (quote! { ::uor_foundation::PrimitiveOp::Neg }, 1),
        "bnot" => (quote! { ::uor_foundation::PrimitiveOp::Bnot }, 1),
        "succ" => (quote! { ::uor_foundation::PrimitiveOp::Succ }, 1),
        "pred" => (quote! { ::uor_foundation::PrimitiveOp::Pred }, 1),
        other => {
            return Err(syn::Error::new(
                func_ident.span(),
                format!(
                    "closure violation: `{other}` is not a foundation PrimitiveOp (recognised: add, sub, mul, xor, and, or, neg, bnot, succ, pred)"
                ),
            ));
        }
    };

    if call.args.len() != expected_arity {
        return Err(syn::Error::new(
            func_ident.span(),
            format!(
                "PrimitiveOp `{}` expects {} argument(s), got {}",
                func_ident,
                expected_arity,
                call.args.len()
            ),
        ));
    }

    // Emit each arg's subtree and record its root index.
    let mut arg_root_indices: Vec<usize> = Vec::with_capacity(call.args.len());
    for arg in call.args.iter() {
        arg_root_indices.push(emit_term_for_expr(arg, route_input, arena)?);
    }

    // ADR-022 D2: the args block must be CONTIGUOUS in the arena. If
    // the arg roots already are (the common case for leaf args or for
    // the canonical post-order layout), use them directly. Otherwise
    // duplicate each arg's root term into a fresh contiguous block —
    // a duplicate carries the same `Term` value (same operator + same
    // args.start), so it is semantically identical.
    let already_contiguous = arg_root_indices.windows(2).all(|w| w[1] == w[0] + 1);

    let (args_start, args_len) = if already_contiguous && !arg_root_indices.is_empty() {
        let len = arg_root_indices.len();
        let start = arg_root_indices[0];
        (start as u32, len as u32)
    } else {
        // Build a contiguous duplicate block at the end of the arena.
        let start = arena.len();
        for &idx in &arg_root_indices {
            // Clone the spec at idx into a new slot. Since TermSpec is
            // not Clone, hand-build a fresh entry referring to the same
            // contents. (Operators are token streams; clone via .clone()
            // on the field.)
            let dup = match &arena[idx] {
                TermSpec::Literal(v) => TermSpec::Literal(*v),
                TermSpec::Variable => TermSpec::Variable,
                TermSpec::Application {
                    operator,
                    args_start,
                    args_len,
                } => TermSpec::Application {
                    operator: operator.clone(),
                    args_start: *args_start,
                    args_len: *args_len,
                },
            };
            arena.push(dup);
        }
        (start as u32, arg_root_indices.len() as u32)
    };

    let app_idx = arena.len();
    arena.push(TermSpec::Application {
        operator,
        args_start,
        args_len,
    });
    Ok(app_idx)
}

/// Emit the macro-time-built term arena as a sequence of `Term::*`
/// constructor expressions, ready to splice into a `&'static [Term]`
/// const-array literal.
fn render_arena(arena: &[TermSpec]) -> Vec<proc_macro2::TokenStream> {
    arena
        .iter()
        .map(|spec| match spec {
            TermSpec::Literal(value) => quote! {
                ::uor_foundation::enforcement::Term::Literal {
                    value: #value,
                    level: ::uor_foundation::WittLevel::W8,
                }
            },
            TermSpec::Variable => quote! {
                ::uor_foundation::enforcement::Term::Variable { name_index: 0u32 }
            },
            TermSpec::Application {
                operator,
                args_start,
                args_len,
            } => {
                let s = *args_start;
                let l = *args_len;
                quote! {
                    ::uor_foundation::enforcement::Term::Application {
                        operator: #operator,
                        args: ::uor_foundation::enforcement::TermList {
                            start: #s,
                            len: #l,
                        },
                    }
                }
            }
        })
        .collect()
}

/// `prism_model!` — wiki ADR-020 + ADR-022 D3 closure-bodied form.
///
/// Parses the model declaration (struct, route witness struct, impl block
/// with `Input` / `Output` / `Route` associated types and a closure-bodied
/// `route` function), maps the closure body to a foundation-vocabulary
/// term tree at expansion time, and emits:
///
/// - `pub struct <Model>;` and `pub struct <Route>;` (re-emitted from input)
/// - `const ROUTE_TERMS_<MODEL>: &'static [Term] = &[…];` (the term tree)
/// - `impl __sdk_seal::Sealed for <Model>` and `for <Route>` (D1)
/// - `impl FoundationClosed for <Route> { arena_slice() → ROUTE_TERMS_<MODEL> }` (D5)
/// - `impl PrismModel<H, B, A> for <Model>` with `forward` body delegating
///   to `pipeline::run_route::<H, B, A, Self>(input)` (D4 + D5)
///
/// A function call to a name not in the foundation PrimitiveOp catalogue
/// (add, sub, mul, xor, and, or, neg, bnot, succ, pred) fails to compile,
/// pointing at the offending span — the wiki's closure-violation
/// enforcement (ADR-020).
#[proc_macro]
pub fn prism_model(input: TokenStream) -> TokenStream {
    let parsed = parse_macro_input!(input as PrismModelInput);
    let PrismModelInput {
        model_vis,
        model_name,
        route_vis,
        route_name,
        h_ty,
        b_ty,
        a_ty,
        input_ty,
        output_ty,
        route_input_ident,
        route_body,
    } = parsed;

    // Walk the closure body — the macro-time mapping that ADR-020 / D3
    // names. The body must be a single expression block; we accept the
    // canonical Rust shape of `{ expr }` and treat the lone expression
    // as the route's term tree.
    let final_expr = match route_body.stmts.last() {
        Some(syn::Stmt::Expr(e, _)) => e.clone(),
        _ => {
            return syn::Error::new_spanned(
                &route_body,
                "closure violation: route body must end with an expression statement (no `;`)",
            )
            .to_compile_error()
            .into();
        }
    };

    let mut arena: Vec<TermSpec> = Vec::new();
    if let Err(e) = emit_term_for_expr(&final_expr, &route_input_ident, &mut arena) {
        return e.to_compile_error().into();
    }
    let term_specs = render_arena(&arena);

    // Synthesize a unique const name from the model's identifier so two
    // models in the same module don't clash on `ROUTE_TERMS`.
    let route_terms_const = Ident::new(
        &format!(
            "ROUTE_TERMS_FOR_{}",
            to_screaming_snake(&model_name.to_string())
        ),
        model_name.span(),
    );

    let expansion = quote! {
        // Re-emit the model + route witness structs from the input.
        #model_vis struct #model_name;
        #route_vis struct #route_name;

        // ADR-022 D2: const term-tree slice. Macro-time-built, fully
        // const, ready for `TermArena::from_slice` if a caller wants
        // to wrap it. `pipeline::run_route` reads it directly via
        // `FoundationClosed::arena_slice`.
        #[allow(non_upper_case_globals, dead_code)]
        const #route_terms_const: &[::uor_foundation::enforcement::Term] = &[
            #( #term_specs ),*
        ];

        // ADR-022 D1: seal impls. Foundation-internal macro is the
        // only sanctioned producer outside foundation itself.
        impl ::uor_foundation::pipeline::__sdk_seal::Sealed for #model_name {}
        impl ::uor_foundation::pipeline::__sdk_seal::Sealed for #route_name {}

        // ADR-022 D5: FoundationClosed impl returning the parsed term-tree.
        impl ::uor_foundation::pipeline::FoundationClosed for #route_name {
            fn arena_slice() -> &'static [::uor_foundation::enforcement::Term] {
                #route_terms_const
            }
        }

        // ADR-020 + ADR-022 D4: PrismModel impl.
        impl ::uor_foundation::pipeline::PrismModel<#h_ty, #b_ty, #a_ty> for #model_name {
            type Input = #input_ty;
            type Output = #output_ty;
            type Route = #route_name;

            fn forward(
                input: <Self as ::uor_foundation::pipeline::PrismModel<#h_ty, #b_ty, #a_ty>>::Input,
            ) -> ::core::result::Result<
                ::uor_foundation::enforcement::Grounded<
                    <Self as ::uor_foundation::pipeline::PrismModel<#h_ty, #b_ty, #a_ty>>::Output,
                >,
                ::uor_foundation::PipelineFailure,
            > {
                ::uor_foundation::pipeline::run_route::<#h_ty, #b_ty, #a_ty, Self>(input)
            }
        }
    };

    expansion.into()
}

// Helpers — canonical operand ordering and suffix-identifier construction.

/// Returns the lexically-earlier identifier of two — stable string compare.
/// Used to canonicalize operand ordering in emitted IRIs so
/// `product_shape!(X, A, B)` and `product_shape!(X, B, A)` produce the
/// same `IRI` constant.
fn lexically_earlier(a: &Ident, b: &Ident) -> String {
    let a_s = a.to_string();
    let b_s = b.to_string();
    if a_s.as_str() <= b_s.as_str() {
        a_s
    } else {
        b_s
    }
}

fn lexically_later(a: &Ident, b: &Ident) -> String {
    let a_s = a.to_string();
    let b_s = b.to_string();
    if a_s.as_str() > b_s.as_str() {
        a_s
    } else {
        b_s
    }
}

/// Returns the operand pair in canonical order. The caller's original
/// (left, right) is reordered so the lexically-earlier identifier is
/// returned first. Amendment §4e canonicalization — token-string-based
/// proxy for the runtime content fingerprint, documented in the plan.
fn canonical_operand_pair(a: &Ident, b: &Ident) -> (Ident, Ident) {
    let a_s = a.to_string();
    let b_s = b.to_string();
    if a_s.as_str() <= b_s.as_str() {
        (a.clone(), b.clone())
    } else {
        (b.clone(), a.clone())
    }
}

/// Build a new identifier for a `const` declaration. Converts the base
/// name to SCREAMING_SNAKE_CASE (so a PascalCase shape name like
/// `LeafA_Times_LeafB` becomes `LEAF_A_TIMES_LEAF_B`) and appends the
/// suffix, preserving the original's call-site span for error reporting.
/// This satisfies Rust's `non_upper_case_globals` lint uniformly
/// regardless of the casing style the caller uses for shape names.
fn format_ident_suffix(base: &Ident, suffix: &str) -> Ident {
    let upper_base = to_screaming_snake(&base.to_string());
    let joined = format!("{upper_base}{suffix}");
    Ident::new(&joined, base.span())
}

/// Converts a PascalCase / camelCase / snake_case string to
/// SCREAMING_SNAKE_CASE. Handles runs of uppercase letters, interior
/// underscores, and digit boundaries so the result is idiomatic
/// SCREAMING_SNAKE.
fn to_screaming_snake(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 4);
    let chars: Vec<char> = s.chars().collect();
    for (i, ch) in chars.iter().enumerate() {
        if *ch == '_' {
            if !out.ends_with('_') && !out.is_empty() {
                out.push('_');
            }
            continue;
        }
        if ch.is_ascii_uppercase() {
            // Insert a separator before an uppercase letter when:
            //  (a) previous char was lowercase or digit
            //  (b) previous was uppercase but next is lowercase (end of a
            //      run like `HTTPServer` → `HTTP_Server`).
            let prev_lower_or_digit = i > 0
                && chars[i - 1] != '_'
                && (chars[i - 1].is_ascii_lowercase() || chars[i - 1].is_ascii_digit());
            let run_ending = i > 0
                && chars[i - 1].is_ascii_uppercase()
                && i + 1 < chars.len()
                && chars[i + 1].is_ascii_lowercase();
            if (prev_lower_or_digit || run_ending) && !out.ends_with('_') && !out.is_empty() {
                out.push('_');
            }
            out.push(*ch);
        } else {
            out.push(ch.to_ascii_uppercase());
        }
    }
    out
}