moonproof-runtime-ir 0.2.2

Rust consumer for compactc's contract.mpir — language-agnostic Compact contract IR. Loads, validates, and (eventually) interprets the IR to drive moonproof's contract runtime.
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
//! [`RuntimeValue`] — the dynamically-typed value enum the IR
//! interpreter and witness backends carry on the operand stack.
//!
//! Replaces the previous `serde_json::Value`-as-stack-value design
//! (which forced every byte buffer through hex-string round-trips
//! and coupled the IR interpreter to the `serde_json` crate). The
//! new enum is byte-honest: `Bytes(Vec<u8>)` keeps bytes as bytes,
//! `Int(i128)` covers every Compact `Uint<…>` rung, and `Object` is
//! a `BTreeMap` so iteration order is deterministic across runs.
//!
//! `From<serde_json::Value>` / `Into<serde_json::Value>`
//! conversions exist as a migration aid — call sites that haven't
//! crossed over yet stage at the boundary. Long-term every IR
//! interpreter / witness call should be `RuntimeValue` end-to-end and
//! the conversions become display-only (`runtime::ledger`'s
//! human-surface projector).

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;

/// Dynamically-typed value carried by the IR interpreter and witness
/// backends. See module docs for design notes.
///
/// `Deserialize` is hand-written (see below) rather than derived
/// `#[serde(untagged)]` because serde's untagged dispatch buffers
/// integers through its internal `Content` enum, which has no
/// `i128` variant. CBOR integers (the IR-on-disk format) would
/// silently fail to match the `Int(i128)` variant. The hand-written
/// visitor accepts every CBOR / JSON primitive and chooses the
/// `RuntimeValue` variant directly.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(untagged)]
pub enum RuntimeValue {
    Null,
    Bool(bool),
    /// All Compact `Uint<…>` rungs fit; values above i128 (which
    /// Compact doesn't emit at the value layer) are not
    /// representable.
    Int(i128),
    /// Raw byte buffer — `Bytes<N>`, `Opaque<Uint8Array>`, `Field`
    /// (32-byte LE), `JubjubPoint` coords.
    #[serde(serialize_with = "byte_buf_serde::serialize")]
    Bytes(Vec<u8>),
    /// `Opaque<string>` and enum variant names.
    String(String),
    /// `Vector<…, T>` and `Tuple<…>` payloads.
    Array(Vec<RuntimeValue>),
    /// Struct payloads keyed by IR field name. Ordered for
    /// determinism across runs.
    Object(BTreeMap<String, RuntimeValue>),
}

impl<'de> Deserialize<'de> for RuntimeValue {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        use serde::de::{Error, MapAccess, SeqAccess, Visitor};

        struct RvVisitor;

        impl<'de> Visitor<'de> for RvVisitor {
            type Value = RuntimeValue;

            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str(
                    "any RuntimeValue (null, bool, integer, bytes, string, array, or object)",
                )
            }

            fn visit_unit<E: Error>(self) -> Result<RuntimeValue, E> {
                Ok(RuntimeValue::Null)
            }

            fn visit_none<E: Error>(self) -> Result<RuntimeValue, E> {
                Ok(RuntimeValue::Null)
            }

            fn visit_some<D: serde::Deserializer<'de>>(
                self,
                d: D,
            ) -> Result<RuntimeValue, D::Error> {
                d.deserialize_any(self)
            }

            fn visit_bool<E: Error>(self, v: bool) -> Result<RuntimeValue, E> {
                Ok(RuntimeValue::Bool(v))
            }

            fn visit_i64<E: Error>(self, v: i64) -> Result<RuntimeValue, E> {
                Ok(RuntimeValue::Int(i128::from(v)))
            }

            fn visit_u64<E: Error>(self, v: u64) -> Result<RuntimeValue, E> {
                Ok(RuntimeValue::Int(i128::from(v)))
            }

            fn visit_i128<E: Error>(self, v: i128) -> Result<RuntimeValue, E> {
                Ok(RuntimeValue::Int(v))
            }

            fn visit_u128<E: Error>(self, v: u128) -> Result<RuntimeValue, E> {
                i128::try_from(v)
                    .map(RuntimeValue::Int)
                    .map_err(|_| Error::custom(format!("u128 value {v} exceeds i128 range")))
            }

            fn visit_f64<E: Error>(self, v: f64) -> Result<RuntimeValue, E> {
                // Compact has no float type; encode as String so the
                // host can surface unexpected upstream payloads
                // without losing information. This matches the
                // `From<JsonValue> for RuntimeValue` shim.
                Ok(RuntimeValue::String(format!("{v}")))
            }

            fn visit_str<E: Error>(self, v: &str) -> Result<RuntimeValue, E> {
                Ok(RuntimeValue::String(v.to_owned()))
            }

            fn visit_string<E: Error>(self, v: String) -> Result<RuntimeValue, E> {
                Ok(RuntimeValue::String(v))
            }

            fn visit_bytes<E: Error>(self, v: &[u8]) -> Result<RuntimeValue, E> {
                Ok(RuntimeValue::Bytes(v.to_vec()))
            }

            fn visit_byte_buf<E: Error>(self, v: Vec<u8>) -> Result<RuntimeValue, E> {
                Ok(RuntimeValue::Bytes(v))
            }

            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<RuntimeValue, A::Error> {
                let mut out = Vec::with_capacity(seq.size_hint().unwrap_or(0));
                while let Some(elem) = seq.next_element::<RuntimeValue>()? {
                    out.push(elem);
                }
                Ok(RuntimeValue::Array(out))
            }

            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<RuntimeValue, A::Error> {
                let mut out = BTreeMap::new();
                while let Some((k, v)) = map.next_entry::<String, RuntimeValue>()? {
                    out.insert(k, v);
                }
                Ok(RuntimeValue::Object(out))
            }
        }

        d.deserialize_any(RvVisitor)
    }
}

impl RuntimeValue {
    /// Convenience constructor for unit / `Tuple<>` results.
    #[must_use]
    pub fn unit() -> Self {
        RuntimeValue::Array(Vec::new())
    }

    /// Borrow a struct field by name. Returns `None` if `self` is
    /// not an object or the field is absent.
    #[must_use]
    pub fn field(&self, name: &str) -> Option<&RuntimeValue> {
        match self {
            RuntimeValue::Object(o) => o.get(name),
            _ => None,
        }
    }

    /// Type tag string for diagnostics.
    #[must_use]
    pub fn type_label(&self) -> &'static str {
        match self {
            RuntimeValue::Null => "null",
            RuntimeValue::Bool(_) => "bool",
            RuntimeValue::Int(_) => "int",
            RuntimeValue::Bytes(_) => "bytes",
            RuntimeValue::String(_) => "string",
            RuntimeValue::Array(_) => "array",
            RuntimeValue::Object(_) => "object",
        }
    }

    // ----- serde_json::Value-style accessors (migration aid) -----

    #[must_use]
    pub fn is_null(&self) -> bool {
        matches!(self, RuntimeValue::Null)
    }

    #[must_use]
    pub fn is_number(&self) -> bool {
        matches!(self, RuntimeValue::Int(_))
    }

    #[must_use]
    pub fn is_string(&self) -> bool {
        matches!(self, RuntimeValue::String(_))
    }

    #[must_use]
    pub fn is_array(&self) -> bool {
        matches!(self, RuntimeValue::Array(_))
    }

    #[must_use]
    pub fn is_object(&self) -> bool {
        matches!(self, RuntimeValue::Object(_))
    }

    #[must_use]
    pub fn is_bool(&self) -> bool {
        matches!(self, RuntimeValue::Bool(_))
    }

    #[must_use]
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            RuntimeValue::Bool(b) => Some(*b),
            _ => None,
        }
    }

    #[must_use]
    pub fn as_i128(&self) -> Option<i128> {
        match self {
            RuntimeValue::Int(i) => Some(*i),
            _ => None,
        }
    }

    #[must_use]
    pub fn as_u64(&self) -> Option<u64> {
        match self {
            RuntimeValue::Int(i) if *i >= 0 => u64::try_from(*i).ok(),
            _ => None,
        }
    }

    #[must_use]
    pub fn as_u128(&self) -> Option<u128> {
        match self {
            RuntimeValue::Int(i) if *i >= 0 => u128::try_from(*i).ok(),
            _ => None,
        }
    }

    #[must_use]
    pub fn as_str(&self) -> Option<&str> {
        match self {
            RuntimeValue::String(s) => Some(s.as_str()),
            _ => None,
        }
    }

    #[must_use]
    pub fn as_bytes(&self) -> Option<&[u8]> {
        match self {
            RuntimeValue::Bytes(b) => Some(b.as_slice()),
            _ => None,
        }
    }

    #[must_use]
    pub fn as_array(&self) -> Option<&Vec<RuntimeValue>> {
        match self {
            RuntimeValue::Array(a) => Some(a),
            _ => None,
        }
    }

    #[must_use]
    pub fn as_array_mut(&mut self) -> Option<&mut Vec<RuntimeValue>> {
        match self {
            RuntimeValue::Array(a) => Some(a),
            _ => None,
        }
    }

    #[must_use]
    pub fn as_object(&self) -> Option<&BTreeMap<String, RuntimeValue>> {
        match self {
            RuntimeValue::Object(o) => Some(o),
            _ => None,
        }
    }

    #[must_use]
    pub fn as_object_mut(&mut self) -> Option<&mut BTreeMap<String, RuntimeValue>> {
        match self {
            RuntimeValue::Object(o) => Some(o),
            _ => None,
        }
    }

    /// Object field / array index lookup. Mirrors
    /// `serde_json::Value::get`. Accepts a `&str` (object key) or
    /// `usize` (array index).
    #[must_use]
    #[expect(
        clippy::needless_pass_by_value,
        reason = "mirrors `serde_json::Value::get`: callers pass `\"key\"` or `0` by value through `ValueIndex`"
    )]
    pub fn get<I: ValueIndex>(&self, idx: I) -> Option<&RuntimeValue> {
        idx.get_in(self)
    }
}

/// Index trait for [`RuntimeValue::get`]. Mirrors
/// `serde_json::value::Index` — `&str` indexes objects, `usize`
/// indexes arrays.
pub trait ValueIndex {
    fn get_in<'a>(&self, v: &'a RuntimeValue) -> Option<&'a RuntimeValue>;
}

impl ValueIndex for &str {
    fn get_in<'a>(&self, v: &'a RuntimeValue) -> Option<&'a RuntimeValue> {
        match v {
            RuntimeValue::Object(o) => o.get(*self),
            _ => None,
        }
    }
}

impl ValueIndex for usize {
    fn get_in<'a>(&self, v: &'a RuntimeValue) -> Option<&'a RuntimeValue> {
        match v {
            RuntimeValue::Array(a) => a.get(*self),
            _ => None,
        }
    }
}

impl ValueIndex for &String {
    fn get_in<'a>(&self, v: &'a RuntimeValue) -> Option<&'a RuntimeValue> {
        self.as_str().get_in(v)
    }
}

impl std::fmt::Display for RuntimeValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RuntimeValue::Null => f.write_str("null"),
            RuntimeValue::Bool(b) => write!(f, "{b}"),
            RuntimeValue::Int(i) => write!(f, "{i}"),
            RuntimeValue::Bytes(b) => write!(f, "0x{}", hex::encode(b)),
            RuntimeValue::String(s) => write!(f, "{s:?}"),
            RuntimeValue::Array(a) => {
                f.write_str("[")?;
                for (i, v) in a.iter().enumerate() {
                    if i > 0 {
                        f.write_str(", ")?;
                    }
                    write!(f, "{v}")?;
                }
                f.write_str("]")
            }
            RuntimeValue::Object(o) => {
                f.write_str("{")?;
                for (i, (k, v)) in o.iter().enumerate() {
                    if i > 0 {
                        f.write_str(", ")?;
                    }
                    write!(f, "{k:?}: {v}")?;
                }
                f.write_str("}")
            }
        }
    }
}

mod byte_buf_serde {
    //! Serialise `Bytes` so cbor stores raw bytes (efficient) and json
    //! stores hex (matches upstream IR-on-disk shape from compactc).
    //! Deserialising is the hand-written `RuntimeValue` visitor's job.
    use serde::Serializer;

    pub fn serialize<S: Serializer>(v: &Vec<u8>, s: S) -> Result<S::Ok, S::Error> {
        // Use serde_bytes for binary cbor; falls back to a string
        // representation when the serializer is human-readable
        // (json) — hex matches compactc's IR convention.
        if s.is_human_readable() {
            s.serialize_str(&hex::encode(v))
        } else {
            s.serialize_bytes(v)
        }
    }
}

// ---------------------------------------------------------------------------
// JSON bridge — migration aid + human-surface projection
// ---------------------------------------------------------------------------

impl From<RuntimeValue> for JsonValue {
    fn from(v: RuntimeValue) -> Self {
        match v {
            RuntimeValue::Null => JsonValue::Null,
            RuntimeValue::Bool(b) => JsonValue::Bool(b),
            RuntimeValue::Int(i) => {
                if let Ok(u) = u64::try_from(i) {
                    JsonValue::Number(u.into())
                } else if let Ok(s) = i64::try_from(i) {
                    JsonValue::Number(s.into())
                } else {
                    JsonValue::String(i.to_string())
                }
            }
            RuntimeValue::Bytes(b) => JsonValue::String(hex::encode(b)),
            RuntimeValue::String(s) => JsonValue::String(s),
            RuntimeValue::Array(a) => JsonValue::Array(a.into_iter().map(Into::into).collect()),
            RuntimeValue::Object(o) => {
                let mut m = serde_json::Map::with_capacity(o.len());
                for (k, v) in o {
                    m.insert(k, v.into());
                }
                JsonValue::Object(m)
            }
        }
    }
}

impl From<JsonValue> for RuntimeValue {
    fn from(v: JsonValue) -> Self {
        match v {
            JsonValue::Null => RuntimeValue::Null,
            JsonValue::Bool(b) => RuntimeValue::Bool(b),
            JsonValue::Number(n) => {
                if let Some(u) = n.as_u64() {
                    RuntimeValue::Int(i128::from(u))
                } else if let Some(s) = n.as_i64() {
                    RuntimeValue::Int(i128::from(s))
                } else if let Some(f) = n.as_f64() {
                    // Compact has no float type; this only fires for
                    // unexpected upstream payloads. Truncate to i128
                    // rather than silently losing precision.
                    #[expect(
                        clippy::cast_possible_truncation,
                        reason = "truncating a non-integral JSON float to i128 is the intended projection; `as` saturates and maps NaN to 0"
                    )]
                    let truncated = f as i128;
                    RuntimeValue::Int(truncated)
                } else {
                    RuntimeValue::Null
                }
            }
            // Strings could be byte buffers (hex) or actual strings —
            // ambiguous without context. The interpreter / typed
            // decoders disambiguate at use; default to String here so
            // round-tripping `Opaque<string>` doesn't corrupt UTF-8.
            JsonValue::String(s) => RuntimeValue::String(s),
            JsonValue::Array(a) => RuntimeValue::Array(a.into_iter().map(Into::into).collect()),
            JsonValue::Object(o) => {
                let mut m = BTreeMap::new();
                for (k, v) in o {
                    m.insert(k, v.into());
                }
                RuntimeValue::Object(m)
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Primitive From / TryFrom — typed Rust ↔ RuntimeValue
//
// Generated code (Rust ledger readers, circuit method args) reaches
// for these so `(arg).into()` and `rv.try_into()` round-trip a
// primitive without any descriptor walk on the consumer side.
// Conventions match `runtime::ir::descriptor`'s `decode_aligned_value`
// so values from on-chain reads project the same way values pushed
// at deploy/call time do.
//
// `[u8; N]` and `Vec<u8>` are deliberately NOT given blanket impls:
// the Compact wire convention treats `Bytes<N>` / `Field` /
// `Opaque<Uint8Array>` as hex-encoded strings, while a `Vector<N,
// Uint<8>>` would round-trip through `Array(Int)`. Codegen emits the
// right shape per descriptor.
// ---------------------------------------------------------------------------

/// Failure projecting a [`RuntimeValue`] back into a typed Rust
/// scalar. Carried by every `TryFrom<RuntimeValue>` impl so generated
/// code can wrap with field/argument context.
#[derive(Debug, Clone, thiserror::Error)]
#[error("RuntimeValue projection: {0}")]
pub struct ValueProjectionError(pub String);

impl ValueProjectionError {
    pub fn new(msg: impl Into<String>) -> Self {
        Self(msg.into())
    }
}

impl From<bool> for RuntimeValue {
    fn from(b: bool) -> Self {
        RuntimeValue::Bool(b)
    }
}

macro_rules! from_uint {
    ($($t:ty),*) => {
        $(
            impl From<$t> for RuntimeValue {
                fn from(n: $t) -> Self {
                    RuntimeValue::Int(i128::from(n))
                }
            }
        )*
    };
}
from_uint!(u8, u16, u32, u64);

macro_rules! from_int {
    ($($t:ty),*) => {
        $(
            impl From<$t> for RuntimeValue {
                fn from(n: $t) -> Self {
                    RuntimeValue::Int(i128::from(n))
                }
            }
        )*
    };
}
from_int!(i8, i16, i32, i64);

impl From<i128> for RuntimeValue {
    fn from(n: i128) -> Self {
        RuntimeValue::Int(n)
    }
}

impl From<u128> for RuntimeValue {
    fn from(n: u128) -> Self {
        match i128::try_from(n) {
            Ok(i) => RuntimeValue::Int(i),
            Err(_) => RuntimeValue::String(n.to_string()),
        }
    }
}

impl From<String> for RuntimeValue {
    fn from(s: String) -> Self {
        RuntimeValue::String(s)
    }
}

impl From<&str> for RuntimeValue {
    fn from(s: &str) -> Self {
        RuntimeValue::String(s.to_owned())
    }
}

// Byte buffers — `Bytes<N>`, `Field`, `Opaque<Uint8Array>` all bridge
// through these. RuntimeValue::Bytes is the byte-honest canonical
// representation (no hex round-trip). Generated code uses these
// blanket impls in both directions.
impl<const N: usize> From<[u8; N]> for RuntimeValue {
    fn from(b: [u8; N]) -> Self {
        RuntimeValue::Bytes(b.to_vec())
    }
}

impl From<Vec<u8>> for RuntimeValue {
    fn from(b: Vec<u8>) -> Self {
        RuntimeValue::Bytes(b)
    }
}

impl<const N: usize> TryFrom<RuntimeValue> for [u8; N] {
    type Error = ValueProjectionError;
    fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
        // Pad to declared N (compactc strips trailing zeros on the wire).
        let bytes: Vec<u8> = match v {
            RuntimeValue::Bytes(b) => b,
            other => {
                return Err(ValueProjectionError::new(format!(
                    "expected Bytes for [u8; {N}], got {}",
                    other.type_label()
                )));
            }
        };
        if bytes.len() > N {
            return Err(ValueProjectionError::new(format!(
                "[u8; {N}] expected ≤ {N} bytes, got {}",
                bytes.len()
            )));
        }
        let mut out = [0u8; N];
        out[..bytes.len()].copy_from_slice(&bytes);
        Ok(out)
    }
}

impl TryFrom<RuntimeValue> for Vec<u8> {
    type Error = ValueProjectionError;
    fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
        match v {
            RuntimeValue::Bytes(b) => Ok(b),
            other => Err(ValueProjectionError::new(format!(
                "expected Bytes for Vec<u8>, got {}",
                other.type_label()
            ))),
        }
    }
}

// Tuple From / TryFrom — per-arity (1..=12). Compact's tuple
// descriptor walks positionally; the runtime convention is
// `RuntimeValue::Array` with one element per slot.
//
// Note: macro positional re-use of generics + an `idx` token (each
// tuple arity gets a hand-written impl block in the macro expansion)
// keeps inference straightforward without nightly variadic generics.
macro_rules! tuple_impls {
    ( $( ( $arity:literal, $( ($t:ident, $idx:tt) ),+ ) ),+ $(,)? ) => {
        $(
            impl< $( $t ),+ > From<( $( $t , )+ )> for RuntimeValue
            where $( $t: Into<RuntimeValue> ),+
            {
                fn from(t: ( $( $t , )+ )) -> Self {
                    RuntimeValue::Array(::std::vec![ $( t.$idx.into() ),+ ])
                }
            }

            impl< $( $t ),+ > TryFrom<RuntimeValue> for ( $( $t , )+ )
            where $( $t: TryFrom<RuntimeValue, Error = ValueProjectionError> ),+
            {
                type Error = ValueProjectionError;
                fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
                    let mut arr = match v {
                        RuntimeValue::Array(a) => a,
                        other => return Err(ValueProjectionError::new(format!(
                            "expected Array for tuple of arity {}, got {}",
                            $arity, other.type_label()
                        ))),
                    };
                    if arr.len() != $arity {
                        return Err(ValueProjectionError::new(format!(
                            "tuple expected {} elements, got {}", $arity, arr.len()
                        )));
                    }
                    let mut iter = arr.drain(..);
                    Ok(( $( {
                        let _ = $idx;  // referenced for macro symmetry
                        let elem = iter.next().expect("checked length");
                        <$t>::try_from(elem)?
                    } , )+ ))
                }
            }
        )+
    };
}

tuple_impls!(
    (1, (T0, 0)),
    (2, (T0, 0), (T1, 1)),
    (3, (T0, 0), (T1, 1), (T2, 2)),
    (4, (T0, 0), (T1, 1), (T2, 2), (T3, 3)),
    (5, (T0, 0), (T1, 1), (T2, 2), (T3, 3), (T4, 4)),
    (6, (T0, 0), (T1, 1), (T2, 2), (T3, 3), (T4, 4), (T5, 5)),
    (
        7,
        (T0, 0),
        (T1, 1),
        (T2, 2),
        (T3, 3),
        (T4, 4),
        (T5, 5),
        (T6, 6)
    ),
    (
        8,
        (T0, 0),
        (T1, 1),
        (T2, 2),
        (T3, 3),
        (T4, 4),
        (T5, 5),
        (T6, 6),
        (T7, 7)
    ),
    (
        9,
        (T0, 0),
        (T1, 1),
        (T2, 2),
        (T3, 3),
        (T4, 4),
        (T5, 5),
        (T6, 6),
        (T7, 7),
        (T8, 8)
    ),
    (
        10,
        (T0, 0),
        (T1, 1),
        (T2, 2),
        (T3, 3),
        (T4, 4),
        (T5, 5),
        (T6, 6),
        (T7, 7),
        (T8, 8),
        (T9, 9)
    ),
    (
        11,
        (T0, 0),
        (T1, 1),
        (T2, 2),
        (T3, 3),
        (T4, 4),
        (T5, 5),
        (T6, 6),
        (T7, 7),
        (T8, 8),
        (T9, 9),
        (T10, 10)
    ),
    (
        12,
        (T0, 0),
        (T1, 1),
        (T2, 2),
        (T3, 3),
        (T4, 4),
        (T5, 5),
        (T6, 6),
        (T7, 7),
        (T8, 8),
        (T9, 9),
        (T10, 10),
        (T11, 11)
    ),
);

// Empty tuple — `()`.
impl From<()> for RuntimeValue {
    fn from((): ()) -> Self {
        RuntimeValue::Array(::std::vec::Vec::new())
    }
}

impl TryFrom<RuntimeValue> for () {
    type Error = ValueProjectionError;
    fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
        match v {
            RuntimeValue::Array(a) if a.is_empty() => Ok(()),
            RuntimeValue::Null => Ok(()),
            other => Err(ValueProjectionError::new(format!(
                "expected empty Array / Null for `()`, got {}",
                other.type_label()
            ))),
        }
    }
}

// Reverse: TryFrom<RuntimeValue> for primitives.

impl TryFrom<RuntimeValue> for bool {
    type Error = ValueProjectionError;
    fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
        match v {
            RuntimeValue::Bool(b) => Ok(b),
            other => Err(ValueProjectionError::new(format!(
                "expected bool, got {}",
                other.type_label()
            ))),
        }
    }
}

macro_rules! try_from_uint {
    ($($t:ty),*) => {
        $(
            impl TryFrom<RuntimeValue> for $t {
                type Error = ValueProjectionError;
                fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
                    let n = match &v {
                        RuntimeValue::Int(i) if *i >= 0 => u128::try_from(*i).ok(),
                        RuntimeValue::String(s) => s.parse::<u128>().ok(),
                        _ => None,
                    };
                    let n = n.ok_or_else(|| ValueProjectionError::new(format!(
                        "expected non-negative integer for {}, got {}",
                        stringify!($t),
                        v.type_label()
                    )))?;
                    <$t>::try_from(n).map_err(|e| ValueProjectionError::new(format!(
                        "uint {} doesn't fit {}: {}", n, stringify!($t), e
                    )))
                }
            }
        )*
    };
}
try_from_uint!(u8, u16, u32, u64, u128);

impl TryFrom<RuntimeValue> for i128 {
    type Error = ValueProjectionError;
    fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
        match &v {
            RuntimeValue::Int(i) => Ok(*i),
            RuntimeValue::String(s) => s
                .parse::<i128>()
                .map_err(|e| ValueProjectionError::new(format!("not an i128 string: `{s}` ({e})"))),
            _ => Err(ValueProjectionError::new(format!(
                "expected i128, got {}",
                v.type_label()
            ))),
        }
    }
}

impl TryFrom<RuntimeValue> for String {
    type Error = ValueProjectionError;
    fn try_from(v: RuntimeValue) -> Result<Self, Self::Error> {
        match v {
            RuntimeValue::String(s) => Ok(s),
            other => Err(ValueProjectionError::new(format!(
                "expected string, got {}",
                other.type_label()
            ))),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn round_trip_through_json_preserves_shape() {
        let rv = RuntimeValue::Object(BTreeMap::from([
            ("a".into(), RuntimeValue::Bool(true)),
            ("b".into(), RuntimeValue::Int(42)),
            (
                "c".into(),
                RuntimeValue::Array(vec![RuntimeValue::Null, RuntimeValue::String("hi".into())]),
            ),
        ]));
        let j: JsonValue = rv.clone().into();
        let back: RuntimeValue = j.into();
        assert_eq!(rv, back);
    }

    #[test]
    fn bytes_serializes_as_hex_in_json() {
        let rv = RuntimeValue::Bytes(vec![0xaa, 0xbb]);
        let j: JsonValue = rv.into();
        assert_eq!(j, json!("aabb"));
    }

    #[test]
    fn unit_is_empty_array() {
        assert_eq!(RuntimeValue::unit(), RuntimeValue::Array(vec![]));
    }

    #[test]
    fn type_labels_disambiguate() {
        assert_eq!(RuntimeValue::Null.type_label(), "null");
        assert_eq!(RuntimeValue::Bool(true).type_label(), "bool");
        assert_eq!(RuntimeValue::Int(0).type_label(), "int");
        assert_eq!(RuntimeValue::Bytes(vec![]).type_label(), "bytes");
        assert_eq!(RuntimeValue::String(String::new()).type_label(), "string");
        assert_eq!(RuntimeValue::Array(vec![]).type_label(), "array");
        assert_eq!(RuntimeValue::Object(BTreeMap::new()).type_label(), "object");
    }

    #[test]
    fn cbor_round_trips_bytes_as_raw() {
        let rv = RuntimeValue::Bytes(vec![1, 2, 3, 4]);
        let buf = crate::cbor_fast::encode_runtime_value_vec(&rv);
        // CBOR major type 2 (byte string) header for length 4 = 0x44.
        assert!(buf.contains(&0x44));
        let back = crate::cbor_fast::decode_runtime_value_slice(&buf).unwrap();
        assert_eq!(back, rv);
    }
}