flow-toolkit 0.1.0

Ordinary typed Rust functions and exact native data for Flow Tools, automatically prepared from direct native imports.
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
//! Values converted under the value encoding (`abi.md`, *The value
//! encoding* and *Decoding*): [`Data`] for every Rust type a Flow data type
//! maps to, and the pieces generated records and enums are written with.
//!
//! Encoding writes what the table says, numbers exactly; decoding is
//! directed by the type and strict, as the runtime's is: nothing is coerced,
//! guessed, defaulted or repaired. A record ignores a field it does not
//! declare, and an `Option` field is left out for `None` and read as `None`
//! when missing or `null`; anywhere else an `Option` is an ordinary enum.
//! The scalars whose text has rules of its own — `Int`, `Bytes`,
//! `Duration` and `Instant` — are read by the runtime's own decoder.

use std::collections::{BTreeMap, BTreeSet};
use std::convert::Infallible;
use std::sync::LazyLock;

use flow_abi::{Catalog, Json, Limits, Mode, Type};
use flow_value::{Constructor, Decimal, Duration, EnumShape, Instant, Int, Payload, Value};

pub use flow_abi::DecodeError;

/// Parses exact JSON syntax with the toolkit's bounded input limits.
/// A generic Tool value still requires validation through its invocation codec.
pub fn parse_json(text: &str) -> Result<Json, DecodeError> {
    flow_abi::parse(text, &LIMITS)
}

/// A Rust type that a Flow data type maps to, converted under the encoding.
pub trait Data: Sized {
    /// Whether this is `Text`, whose dictionaries encode as JSON objects.
    const TEXT: bool = false;

    /// The value's JSON.
    fn encode(&self) -> Json;

    /// The value `json` encodes, or why it encodes none.
    fn decode(json: &Json) -> Result<Self, DecodeError>;
}

/// `Bytes`: raw bytes, encoded as standard base64 with padding.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)]
pub struct Bytes(pub Vec<u8>);

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

impl From<&[u8]> for Bytes {
    fn from(bytes: &[u8]) -> Self {
        Bytes(bytes.to_vec())
    }
}

/// A decoding failure at the whole value.
pub fn refused(problem: impl Into<String>) -> DecodeError {
    DecodeError {
        path: String::new(),
        problem: problem.into(),
        kind: flow_abi::DecodeErrorKind::Invalid,
    }
}

/// `error`, found inside the part `step` names: a field or constructor's
/// name, or `[index]`, or `["key"]`.
pub fn inside(mut error: DecodeError, step: &str) -> DecodeError {
    error.path = if error.path.is_empty() {
        step.to_owned()
    } else if error.path.starts_with('[') {
        format!("{step}{}", error.path)
    } else {
        format!("{step}.{}", error.path)
    };
    error
}

/// What `read` makes of `json`, any failure located inside `step`.
pub fn within<T>(
    json: &Json,
    step: &str,
    read: impl FnOnce(&Json) -> Result<T, DecodeError>,
) -> Result<T, DecodeError> {
    read(json).map_err(|error| inside(error, step))
}

fn expected(what: &str, json: &Json) -> DecodeError {
    refused(format!("should be {what}, not {}", json.kind()))
}

/// How large a value the toolkit reads: well past what any host sends.
pub(crate) const LIMITS: Limits = Limits {
    depth: 1_024,
    int_bits: 16_777_216,
    text_bytes: 1_073_741_824,
};

/// The value of the built-in type `ty` that `json` encodes, read by the
/// runtime's own decoder.
fn scalar<T>(ty: &Type, json: &Json, take: fn(Value) -> Option<T>) -> Result<T, DecodeError> {
    static CATALOG: LazyLock<Catalog> = LazyLock::new(|| {
        let option = EnumShape::new(
            "Option",
            [
                Constructor::new("None", Payload::None),
                Constructor::new("Some", Payload::Positional(1)),
            ],
        );
        Catalog::new(Vec::new(), option, None).expect("std's Option has None and Some")
    });
    let value = flow_abi::decode(&CATALOG, ty, json, Mode::Reply, &LIMITS)?;
    Ok(take(value).expect("the decoder builds the type it is asked for"))
}

impl Data for Int {
    fn encode(&self) -> Json {
        Json::Number(Decimal::from(self))
    }

    fn decode(json: &Json) -> Result<Self, DecodeError> {
        scalar(&Type::Int, json, |value| match value {
            Value::Int(int) => Some(int),
            _ => None,
        })
    }
}

impl Data for Decimal {
    fn encode(&self) -> Json {
        Json::Number(self.clone())
    }

    fn decode(json: &Json) -> Result<Self, DecodeError> {
        match json {
            Json::Number(number) => Ok(number.clone()),
            other => Err(expected("a number", other)),
        }
    }
}

impl Data for bool {
    fn encode(&self) -> Json {
        Json::Bool(*self)
    }

    fn decode(json: &Json) -> Result<Self, DecodeError> {
        match json {
            Json::Bool(value) => Ok(*value),
            other => Err(expected("a boolean", other)),
        }
    }
}

impl Data for String {
    const TEXT: bool = true;

    fn encode(&self) -> Json {
        Json::String(self.clone())
    }

    fn decode(json: &Json) -> Result<Self, DecodeError> {
        match json {
            Json::String(text) => Ok(text.clone()),
            other => Err(expected("a string", other)),
        }
    }
}

impl Data for Bytes {
    fn encode(&self) -> Json {
        Json::String(flow_value::Bytes::new(&self.0).to_base64())
    }

    fn decode(json: &Json) -> Result<Self, DecodeError> {
        scalar(&Type::Bytes, json, |value| match value {
            Value::Bytes(bytes) => Some(Bytes(bytes.as_slice().to_vec())),
            _ => None,
        })
    }
}

impl Data for Duration {
    fn encode(&self) -> Json {
        Json::String(self.to_string())
    }

    fn decode(json: &Json) -> Result<Self, DecodeError> {
        scalar(&Type::Duration, json, |value| match value {
            Value::Duration(duration) => Some(duration),
            _ => None,
        })
    }
}

impl Data for Instant {
    fn encode(&self) -> Json {
        Json::String(self.to_string())
    }

    fn decode(json: &Json) -> Result<Self, DecodeError> {
        scalar(&Type::Instant, json, |value| match value {
            Value::Instant(instant) => Some(instant),
            _ => None,
        })
    }
}

/// `Unit`, the empty array.
impl Data for () {
    fn encode(&self) -> Json {
        Json::Array(Vec::new())
    }

    fn decode(json: &Json) -> Result<Self, DecodeError> {
        match json {
            Json::Array(items) if items.is_empty() => Ok(()),
            other => Err(expected("the empty array", other)),
        }
    }
}

/// `Never`, which has no values.
impl Data for Infallible {
    fn encode(&self) -> Json {
        match *self {}
    }

    fn decode(_: &Json) -> Result<Self, DecodeError> {
        Err(refused("is of `Never`, which has no values"))
    }
}

/// `json.Value`, std's enum for raw JSON, with its equality and order
/// (`data.md`; `types.md`, *Equality, ordering and text*): constructors in
/// declaration order, `Null` lowest; numbers by value, so `1.0` is `1`;
/// text by code point; lists element by element; and an object as a
/// `Dict<Text, json.Value>`, whatever order its members were written in.
/// It encodes as the JSON value it stands for.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum JsonValue {
    /// `null`.
    Null,
    /// `true` or `false`.
    Bool(bool),
    /// A number, exactly.
    Number(Decimal),
    /// A string.
    Text(String),
    /// An array.
    List(Vec<JsonValue>),
    /// An object, its members by name.
    Object(BTreeMap<String, JsonValue>),
}

impl Data for JsonValue {
    fn encode(&self) -> Json {
        match self {
            JsonValue::Null => Json::Null,
            JsonValue::Bool(value) => Json::Bool(*value),
            JsonValue::Number(number) => Json::Number(number.clone()),
            JsonValue::Text(text) => Json::String(text.clone()),
            JsonValue::List(items) => Json::Array(items.iter().map(Data::encode).collect()),
            JsonValue::Object(members) => Json::Object(
                members
                    .iter()
                    .map(|(key, value)| (key.clone(), value.encode()))
                    .collect(),
            ),
        }
    }

    fn decode(json: &Json) -> Result<Self, DecodeError> {
        Ok(match json {
            Json::Null => JsonValue::Null,
            Json::Bool(value) => JsonValue::Bool(*value),
            Json::Number(number) => JsonValue::Number(number.clone()),
            Json::String(text) => JsonValue::Text(text.clone()),
            Json::Array(_) => JsonValue::List(elements(json)?),
            Json::Object(members) => {
                let mut object = BTreeMap::new();
                for (key, value) in members {
                    let step = format!("[{}]", Json::String(key.clone()).canonical());
                    if object
                        .insert(key.clone(), within(value, &step, JsonValue::decode)?)
                        .is_some()
                    {
                        return Err(inside(refused("repeats a key already given"), &step));
                    }
                }
                JsonValue::Object(object)
            }
        })
    }
}

/// A Tool's type parameter: the JSON itself, untouched.
impl Data for Json {
    fn encode(&self) -> Json {
        self.clone()
    }

    fn decode(json: &Json) -> Result<Self, DecodeError> {
        Ok(json.clone())
    }
}

/// A part a recursive type holds directly.
impl<T: Data> Data for Box<T> {
    fn encode(&self) -> Json {
        (**self).encode()
    }

    fn decode(json: &Json) -> Result<Self, DecodeError> {
        T::decode(json).map(Box::new)
    }
}

/// The elements of the array `json`, each decoded inside its position.
fn elements<T: Data, C: FromIterator<T>>(json: &Json) -> Result<C, DecodeError> {
    match json {
        Json::Array(items) => items
            .iter()
            .enumerate()
            .map(|(index, item)| within(item, &format!("[{index}]"), T::decode))
            .collect(),
        other => Err(expected("an array", other)),
    }
}

/// `List<T>`.
impl<T: Data> Data for Vec<T> {
    fn encode(&self) -> Json {
        Json::Array(self.iter().map(Data::encode).collect())
    }

    fn decode(json: &Json) -> Result<Self, DecodeError> {
        elements(json)
    }
}

/// `Set<T>`, in ascending order; repeated elements collapse.
impl<T: Data + Ord> Data for BTreeSet<T> {
    fn encode(&self) -> Json {
        Json::Array(self.iter().map(Data::encode).collect())
    }

    fn decode(json: &Json) -> Result<Self, DecodeError> {
        elements(json)
    }
}

/// `Dict<K, V>`: an object when the keys are `Text`, and otherwise an array
/// of `[key, value]` pairs in ascending key order. Two equal keys are
/// refused.
impl<K: Data + Ord, V: Data> Data for BTreeMap<K, V> {
    fn encode(&self) -> Json {
        if K::TEXT {
            Json::Object(
                self.iter()
                    .map(|(key, value)| match key.encode() {
                        Json::String(key) => (key, value.encode()),
                        _ => unreachable!("a key of Text encodes as a string"),
                    })
                    .collect(),
            )
        } else {
            Json::Array(
                self.iter()
                    .map(|(key, value)| Json::Array(vec![key.encode(), value.encode()]))
                    .collect(),
            )
        }
    }

    fn decode(json: &Json) -> Result<Self, DecodeError> {
        let mut dict = BTreeMap::new();
        match json {
            Json::Object(members) if K::TEXT => {
                for (key, value) in members {
                    let step = format!("[{}]", Json::String(key.clone()).canonical());
                    let key = K::decode(&Json::String(key.clone()))?;
                    dict.insert(key, within(value, &step, V::decode)?);
                }
            }
            Json::Array(pairs) if !K::TEXT => {
                for (index, pair) in pairs.iter().enumerate() {
                    let (key, value) = within(pair, &format!("[{index}]"), |pair| {
                        let parts = positional(pair, 2)?;
                        Ok((part(parts, 0)?, part(parts, 1)?))
                    })?;
                    if dict.insert(key, value).is_some() {
                        return Err(inside(
                            refused("repeats a key already given"),
                            &format!("[{index}]"),
                        ));
                    }
                }
            }
            other => {
                return Err(expected(
                    if K::TEXT { "an object" } else { "an array" },
                    other,
                ));
            }
        }
        Ok(dict)
    }
}

/// `Option<T>` anywhere but a record field: `"None"` or `{"Some": v}`.
impl<T: Data> Data for Option<T> {
    fn encode(&self) -> Json {
        match self {
            None => Json::String("None".to_owned()),
            Some(value) => variant("Some", value.encode()),
        }
    }

    fn decode(json: &Json) -> Result<Self, DecodeError> {
        match constructor(json)? {
            ("None", None) => Ok(None),
            ("Some", Some(payload)) => within(payload, "Some", T::decode).map(Some),
            (name, payload) => Err(mismatch("Option", name, payload)),
        }
    }
}

/// Ordinary nested `Result<T, E>` data; Tool completion is a separate boundary.
impl<T: Data, E: Data> Data for std::result::Result<T, E> {
    fn encode(&self) -> Json {
        match self {
            Ok(value) => variant("Ok", value.encode()),
            Err(value) => variant("Err", value.encode()),
        }
    }
    fn decode(json: &Json) -> Result<Self, DecodeError> {
        match constructor(json)? {
            ("Ok", Some(payload)) => within(payload, "Ok", T::decode).map(Ok),
            ("Err", Some(payload)) => within(payload, "Err", E::decode).map(Err),
            (name, payload) => Err(mismatch("Result", name, payload)),
        }
    }
}

macro_rules! tuple {
    ($count:literal: $($part:ident $index:tt),+) => {
        /// A tuple: an array of its elements.
        impl<$($part: Data),+> Data for ($($part,)+) {
            fn encode(&self) -> Json {
                Json::Array(vec![$(self.$index.encode()),+])
            }

            fn decode(json: &Json) -> Result<Self, DecodeError> {
                let parts = positional(json, $count)?;
                Ok(($(part::<$part>(parts, $index)?,)+))
            }
        }
    };
}

tuple!(2: A 0, B 1);
tuple!(3: A 0, B 1, C 2);
tuple!(4: A 0, B 1, C 2, D 3);
tuple!(5: A 0, B 1, C 2, D 3, E 4);
tuple!(6: A 0, B 1, C 2, D 3, E 4, F 5);
tuple!(7: A 0, B 1, C 2, D 3, E 4, F 5, G 6);
tuple!(8: A 0, B 1, C 2, D 3, E 4, F 5, G 6, H 7);

/// The named fields of a record or a constructor's named payload, being
/// written.
#[derive(Default, Debug)]
pub struct Fields(Vec<(String, Json)>);

impl Fields {
    /// No fields yet.
    pub fn new() -> Self {
        Fields::default()
    }

    /// With the field `name` holding `value`.
    #[must_use]
    pub fn field<T: Data>(mut self, name: &str, value: &T) -> Self {
        self.0.push((name.to_owned(), value.encode()));
        self
    }

    /// With the `Option` field `name`: left out for `None`, and holding
    /// the value itself for `Some`.
    #[must_use]
    pub fn optional<T: Data>(mut self, name: &str, value: Option<&T>) -> Self {
        if let Some(value) = value {
            self.0.push((name.to_owned(), value.encode()));
        }
        self
    }

    /// The object.
    pub fn build(self) -> Json {
        Json::Object(self.0)
    }
}

/// The named fields of a record or a named payload, being read.
#[derive(Debug)]
pub struct Object<'j>(&'j [(String, Json)]);

/// The fields of the object `json`.
pub fn object(json: &Json) -> Result<Object<'_>, DecodeError> {
    match json {
        Json::Object(members) => Ok(Object(members)),
        other => Err(expected("an object", other)),
    }
}

impl Object<'_> {
    fn get(&self, name: &str) -> Option<&Json> {
        self.0
            .iter()
            .find(|(key, _)| key == name)
            .map(|(_, value)| value)
    }

    /// The field `name`, which must be there.
    pub fn field<T: Data>(&self, name: &str) -> Result<T, DecodeError> {
        match self.get(name) {
            Some(value) => within(value, name, T::decode),
            None => Err(inside(refused("is missing"), name)),
        }
    }

    /// The `Option` field `name`: `None` when it is missing or `null`.
    pub fn optional<T: Data>(&self, name: &str) -> Result<Option<T>, DecodeError> {
        match self.get(name) {
            None | Some(Json::Null) => Ok(None),
            Some(value) => within(value, name, T::decode).map(Some),
        }
    }
}

/// An enum value's constructor name, and its payload when it has one.
pub fn constructor(json: &Json) -> Result<(&str, Option<&Json>), DecodeError> {
    match json {
        Json::String(name) => Ok((name, None)),
        Json::Object(members) if members.len() == 1 => {
            Ok((members[0].0.as_str(), Some(&members[0].1)))
        }
        other => Err(expected(
            "a constructor's name or an object of one member",
            other,
        )),
    }
}

/// The enum value of the constructor `name` with `payload`.
pub fn variant(name: &str, payload: Json) -> Json {
    Json::Object(vec![(name.to_owned(), payload)])
}

/// Why `name`, with or without a payload, is no constructor of the enum
/// `enum_name`.
pub fn mismatch(enum_name: &str, name: &str, payload: Option<&Json>) -> DecodeError {
    let with = if payload.is_some() {
        "with a payload"
    } else {
        "without a payload"
    };
    refused(format!(
        "names no constructor of `{enum_name}`: `{name}` {with}"
    ))
}

/// The `count` elements of the array `json`: a tuple, or a constructor's
/// positional payload of several values.
pub fn positional(json: &Json, count: usize) -> Result<&[Json], DecodeError> {
    match json {
        Json::Array(parts) if parts.len() == count => Ok(parts),
        Json::Array(parts) => Err(refused(format!(
            "has {} elements, not {count}",
            parts.len()
        ))),
        other => Err(expected("an array", other)),
    }
}

/// The element at `index` of `parts`, decoded inside its position.
pub fn part<T: Data>(parts: &[Json], index: usize) -> Result<T, DecodeError> {
    within(&parts[index], &format!("[{index}]"), T::decode)
}

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

    #[test]
    fn a_path_is_written_as_the_runtime_writes_one() {
        let error = inside(inside(refused("is wrong"), "[2]"), "steps");
        assert_eq!(error.path, "steps[2]");
        let error = inside(inside(refused("is wrong"), "owner"), "[0]");
        assert_eq!(error.path, "[0].owner");
        assert_eq!(error.problem, "is wrong");
    }
}

/// An owned type-directed codec for one validated concrete call root.
#[derive(Clone, Debug)]
pub struct ContextCodec {
    graph: std::sync::Arc<flow_abi::ValidatedTypes>,
    ty: Type,
    mode: Mode,
}

impl ContextCodec {
    pub(crate) fn is_text(&self) -> bool {
        matches!(self.ty, Type::Text)
    }
    pub(crate) fn new(
        graph: std::sync::Arc<flow_abi::ValidatedTypes>,
        ty: Type,
        mode: Mode,
    ) -> Result<Self, DecodeError> {
        flow_abi::crossable(graph.catalog(), &ty)?;
        flow_abi::decodable(graph.catalog(), &ty, mode)?;
        Ok(Self { graph, ty, mode })
    }

    /// Decodes and normalizes a value using the caller's concrete type.
    pub fn decode(&self, json: &Json) -> Result<Json, DecodeError> {
        let value = flow_abi::decode(self.graph.catalog(), &self.ty, json, self.mode, &LIMITS)?;
        self.encode_value(&value)
    }

    fn encode_value(&self, value: &flow_value::Value) -> Result<Json, DecodeError> {
        flow_abi::encode(self.graph.catalog(), &self.ty, value)
            .map_err(|error| refused(error.to_string()))
    }

    /// Validates an author's JSON at this root and writes its canonical value.
    pub fn encode(&self, json: &Json) -> Result<Json, DecodeError> {
        self.decode(json)
    }

    /// Flow's comparison, directed by this root rather than JSON key order.
    pub fn compare(&self, left: &Json, right: &Json) -> Result<std::cmp::Ordering, DecodeError> {
        let decode =
            |json| flow_abi::decode(self.graph.catalog(), &self.ty, json, self.mode, &LIMITS);
        flow_value::compare(&decode(left)?, &decode(right)?)
            .map_err(|error| refused(error.to_string()))
    }

    fn child(&self, ty: Type) -> Result<Self, DecodeError> {
        Self::new(self.graph.clone(), ty, self.mode)
    }

    /// The element of a list, set or option.
    pub fn element(&self) -> Result<Self, DecodeError> {
        match &self.ty {
            Type::List(ty) | Type::Set(ty) | Type::Option(ty) => self.child((**ty).clone()),
            _ => Err(refused("type has no element codec")),
        }
    }
    /// The key of a dictionary.
    pub fn key(&self) -> Result<Self, DecodeError> {
        match &self.ty {
            Type::Dict(key, _) => self.child((**key).clone()),
            _ => Err(refused("type is not a dictionary")),
        }
    }
    /// The value of a dictionary.
    pub fn value(&self) -> Result<Self, DecodeError> {
        match &self.ty {
            Type::Dict(_, value) => self.child((**value).clone()),
            _ => Err(refused("type is not a dictionary")),
        }
    }
    /// A tuple's part at its declaration position.
    pub fn positional(&self, index: usize) -> Result<Self, DecodeError> {
        match &self.ty {
            Type::Tuple(parts) => parts
                .get(index)
                .cloned()
                .ok_or_else(|| refused("tuple index is out of range"))
                .and_then(|ty| self.child(ty)),
            _ => Err(refused("type is not a tuple")),
        }
    }
    /// A record field after substituting the caller's type arguments.
    pub fn field(&self, name: &str) -> Result<Self, DecodeError> {
        if let Type::Named(id, args) = &self.ty
            && let flow_abi::Body::Record(shape, fields) = &self.graph.catalog().decl(*id).body
            && let Some(index) = shape.fields().position(|field| field == name)
        {
            return self.child(fields[index].subst(args));
        }
        Err(refused(format!("type has no field {name}")))
    }
    /// Reads a record field, resolving Option presence after substitution.
    pub fn decode_field(&self, parent: &Json, name: &str) -> Result<Json, DecodeError> {
        self.field(name)?.read_field(parent, name)
    }
    /// Encodes a record field, omitting None after substitution.
    pub fn encode_field(&self, value: &Json, name: &str) -> Result<Option<Json>, DecodeError> {
        self.field(name)?.write_field(value)
    }
    fn read_field(&self, parent: &Json, name: &str) -> Result<Json, DecodeError> {
        let value = parent.get(name);
        if let Type::Option(_) = self.ty {
            return match value {
                None | Some(Json::Null) => Ok(Json::String("None".into())),
                Some(value) => self.decode(&variant("Some", value.clone())),
            };
        }
        self.decode(value.ok_or_else(|| inside(refused("is missing"), name))?)
    }
    fn write_field(&self, value: &Json) -> Result<Option<Json>, DecodeError> {
        let normalized = self.encode(value)?;
        if let Type::Option(_) = self.ty {
            return match constructor(&normalized)? {
                ("None", None) => Ok(None),
                ("Some", Some(value)) => Ok(Some(value.clone())),
                _ => Err(refused("invalid normalized Option")),
            };
        }
        Ok(Some(normalized))
    }
    /// Selects one enum constructor before looking up its payload members.
    pub fn variant(&self, name: &str) -> Result<PayloadView, DecodeError> {
        if let Type::Named(id, args) = &self.ty
            && let flow_abi::Body::Enum(shape, parts) = &self.graph.catalog().decl(*id).body
        {
            for (index, fields) in parts.iter().enumerate() {
                let ctor = shape.constructor(index).expect("validated enum shape");
                if ctor.name() == name {
                    return Ok(PayloadView {
                        parent: self.clone(),
                        kind: ctor.payload().clone(),
                        parts: fields.iter().map(|ty| ty.subst(args)).collect(),
                    });
                }
            }
        }
        Err(refused(format!("type has no constructor {name}")))
    }
}

/// A payload view belonging to one explicitly selected constructor.
#[derive(Clone, Debug)]
pub struct PayloadView {
    parent: ContextCodec,
    kind: Payload,
    parts: Vec<Type>,
}
impl PayloadView {
    /// A positional payload member.
    pub fn positional(&self, index: usize) -> Result<ContextCodec, DecodeError> {
        if !matches!(self.kind, Payload::Positional(_)) {
            return Err(refused("payload is not positional"));
        }
        self.parts
            .get(index)
            .cloned()
            .ok_or_else(|| refused("payload index is out of range"))
            .and_then(|ty| self.parent.child(ty))
    }
    /// A named payload field.
    pub fn field(&self, name: &str) -> Result<ContextCodec, DecodeError> {
        if let Payload::Named(names) = &self.kind
            && let Some(index) = names.iter().position(|field| field.as_ref() == name)
        {
            return self.parent.child(self.parts[index].clone());
        }
        Err(refused(format!("payload has no field {name}")))
    }
    /// Reads a named member with substituted Option presence.
    pub fn decode_field(&self, parent: &Json, name: &str) -> Result<Json, DecodeError> {
        self.field(name)?.read_field(parent, name)
    }
    /// Writes a named member with substituted Option presence.
    pub fn encode_field(&self, value: &Json, name: &str) -> Result<Option<Json>, DecodeError> {
        self.field(name)?.write_field(value)
    }
}

/// A set whose elements use one owned concrete Flow codec.
#[derive(Clone, Debug)]
pub struct ContextSet {
    codec: ContextCodec,
    values: Vec<Json>,
}
impl ContextSet {
    /// Normalizes, orders and collapses equal elements without a JSON comparator.
    pub fn new(codec: ContextCodec, values: Vec<Json>) -> Result<Self, DecodeError> {
        // Decode once; the runtime collection sorts typed values in O(n log n)
        // comparisons instead of decoding the sorted prefix at every insertion.
        let decoded = values
            .into_iter()
            .map(|json| {
                flow_abi::decode(codec.graph.catalog(), &codec.ty, &json, codec.mode, &LIMITS)
            })
            .collect::<Result<Vec<_>, _>>()?;
        let ordered =
            flow_value::Set::from_items(decoded).map_err(|error| refused(error.to_string()))?;
        let values = ordered
            .iter()
            .map(|value| codec.encode_value(value))
            .collect::<Result<_, _>>()?;
        Ok(Self { codec, values })
    }
    /// The owned element codec.
    pub fn codec(&self) -> &ContextCodec {
        &self.codec
    }
    /// Elements in Flow order.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = &Json> {
        self.values.iter()
    }
    /// Canonical array, revalidated at the output root by generated code.
    pub fn canonical_json(&self) -> Json {
        Json::Array(self.values.clone())
    }
}

/// A dictionary whose keys and values use owned concrete Flow codecs.
#[derive(Clone, Debug)]
pub struct ContextDict {
    key: ContextCodec,
    value: ContextCodec,
    values: Vec<(Json, Json)>,
    text: bool,
}
impl ContextDict {
    /// Normalizes and orders entries, refusing duplicate typed keys.
    pub fn new(
        key: ContextCodec,
        value: ContextCodec,
        entries: Vec<(Json, Json)>,
    ) -> Result<Self, DecodeError> {
        let text = key.ty == Type::Text;
        let count = entries.len();
        let decoded = entries
            .into_iter()
            .map(|(k, v)| {
                Ok((
                    flow_abi::decode(key.graph.catalog(), &key.ty, &k, key.mode, &LIMITS)?,
                    flow_abi::decode(value.graph.catalog(), &value.ty, &v, value.mode, &LIMITS)?,
                ))
            })
            .collect::<Result<Vec<_>, DecodeError>>()?;
        // Runtime dictionaries sort in O(n log n) comparisons and collapse equal
        // keys. This constructor refuses duplicates rather than keeping a value.
        let ordered =
            flow_value::Dict::from_entries(decoded).map_err(|error| refused(error.to_string()))?;
        if ordered.len() != count {
            return Err(refused("dictionary has a duplicate key"));
        }
        let values = ordered
            .iter()
            .map(|(k, v)| Ok((key.encode_value(k)?, value.encode_value(v)?)))
            .collect::<Result<_, DecodeError>>()?;
        Ok(Self {
            key,
            value,
            values,
            text,
        })
    }
    /// The owned key codec.
    pub fn key_codec(&self) -> &ContextCodec {
        &self.key
    }
    /// The owned value codec.
    pub fn value_codec(&self) -> &ContextCodec {
        &self.value
    }
    /// Entries in Flow key order.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = &(Json, Json)> {
        self.values.iter()
    }
    /// Text keys form an object; other keys form pairs.
    pub fn canonical_json(&self) -> Json {
        if self.text {
            Json::Object(
                self.values
                    .iter()
                    .map(|(key, value)| match key {
                        Json::String(key) => (key.clone(), value.clone()),
                        _ => unreachable!("validated Text key"),
                    })
                    .collect(),
            )
        } else {
            Json::Array(
                self.values
                    .iter()
                    .map(|(key, value)| Json::Array(vec![key.clone(), value.clone()]))
                    .collect(),
            )
        }
    }
}

/// Reads a dynamic set using the caller's normalized element order.
pub fn read_context_set(codec: &ContextCodec, json: &Json) -> Result<ContextSet, DecodeError> {
    if !matches!(codec.ty, Type::Set(_)) {
        return Err(refused("type is not a set"));
    }
    let Json::Array(values) = codec.decode(json)? else {
        return Err(refused("set must be an array"));
    };
    Ok(ContextSet {
        codec: codec.element()?,
        values,
    })
}
/// Reads a dynamic dictionary from its concrete object or pair form.
pub fn read_context_dict(codec: &ContextCodec, json: &Json) -> Result<ContextDict, DecodeError> {
    let values = match codec.decode(json)? {
        Json::Object(fields) => fields
            .into_iter()
            .map(|(key, value)| (Json::String(key), value))
            .collect(),
        Json::Array(pairs) => pairs
            .into_iter()
            .map(|pair| match pair {
                Json::Array(mut pair) if pair.len() == 2 => {
                    let value = pair.pop().expect("pair value");
                    let key = pair.pop().expect("pair key");
                    Ok((key, value))
                }
                _ => Err(refused("dictionary entry must be a pair")),
            })
            .collect::<Result<_, _>>()?,
        _ => return Err(refused("dictionary must be an object or pairs")),
    };
    let key = codec.key()?;
    let text = key.ty == Type::Text;
    Ok(ContextDict {
        key,
        value: codec.value()?,
        values,
        text,
    })
}
/// Composes an owned contextual list codec with native element factories.
pub fn read_context_list<T>(
    codec: &ContextCodec,
    json: &Json,
    read: impl Fn(&ContextCodec, &Json) -> Result<T, DecodeError>,
) -> Result<Vec<T>, DecodeError> {
    let Json::Array(values) = codec.decode(json)? else {
        return Err(refused("list must be an array"));
    };
    let child = codec.element()?;
    values
        .iter()
        .enumerate()
        .map(|(at, value)| read(&child, value).map_err(|error| inside(error, &format!("[{at}]"))))
        .collect()
}
/// Composes a contextual list encoder with native element factories.
pub fn write_context_list<T>(
    codec: &ContextCodec,
    values: &[T],
    write: impl Fn(&ContextCodec, &T) -> Result<Json, DecodeError>,
) -> Result<Json, DecodeError> {
    let child = codec.element()?;
    codec.encode(&Json::Array(
        values
            .iter()
            .map(|value| write(&child, value))
            .collect::<Result<_, _>>()?,
    ))
}
/// Reads standalone Option's canonical enum representation.
pub fn read_context_option<T>(
    codec: &ContextCodec,
    json: &Json,
    read: impl Fn(&ContextCodec, &Json) -> Result<T, DecodeError>,
) -> Result<Option<T>, DecodeError> {
    let normalized = codec.decode(json)?;
    match constructor(&normalized)? {
        ("None", None) => Ok(None),
        ("Some", Some(value)) => read(&codec.element()?, value).map(Some),
        _ => Err(refused("invalid Option")),
    }
}
/// Writes standalone Option's canonical enum representation.
pub fn write_context_option<T>(
    codec: &ContextCodec,
    value: &Option<T>,
    write: impl Fn(&ContextCodec, &T) -> Result<Json, DecodeError>,
) -> Result<Json, DecodeError> {
    let json = match value {
        None => Json::String("None".into()),
        Some(value) => variant("Some", write(&codec.element()?, value)?),
    };
    codec.encode(&json)
}