flow-toolkit 0.1.0-rc.5

Ordinary typed Rust functions and exact native data for Flow Tools, served from a Rust library's one launcher.
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
//! A generic Tool's values and a std value carried whole, read and written
//! at the types a call's description gives them (`abi.md`, *Toolkits*): an
//! [`Encoded`] value and the derived types generic over one, written and read
//! directly at their Flow types.
#![allow(
    unreachable_pub,
    reason = "public native boundary fixtures inside a private test module"
)]

use std::collections::{BTreeMap, BTreeSet};

use flow_abi::primitives::Reader;
use flow_abi::{Catalog, Limits, Mode};
use flow_toolkit::{Encoded, Flow, Int, Shaped};
use flow_types::{Body, DeclId, Type};
use flow_types::{Constructor, EnumShape, Payload};

use crate::test_types::{catalog, newtype, record};

#[derive(Flow, Clone, PartialEq, Eq, Debug)]
pub struct Container<T: Ord> {
    pub items: BTreeSet<T>,
    pub fixed: Int,
}

#[derive(Flow, Clone, PartialEq, Eq, Debug)]
pub enum Choice<T> {
    Empty,
    One(T),
    Pair(T, Int),
    Named { value: T, fixed: Int },
}

#[derive(Flow, Clone, PartialEq, Eq, Debug)]
pub struct Chain<T> {
    pub head: T,
    pub next: Option<Box<Chain<T>>>,
}

#[derive(Flow, Clone, Debug)]
#[flow(std = "code.Bundle")]
pub struct Bundle(pub Encoded);

const CONTAINER: DeclId = DeclId(0);
const CHOICE: DeclId = DeclId(1);
const CHAIN: DeclId = DeclId(2);
const ORDER: DeclId = DeclId(3);

/// The declarations the fixtures above write, as a caller's catalog holds
/// them, with the newtype `OrderId(Text)`.
fn fixtures() -> Catalog {
    let param = Type::Param(0);
    let choice = flow_types::Decl {
        body: Body::Enum(
            EnumShape::new(
                "Choice",
                [
                    Constructor::new("Empty", Payload::None),
                    Constructor::new("One", Payload::Positional(1)),
                    Constructor::new("Pair", Payload::Positional(2)),
                    Constructor::new("Named", Payload::named(["value", "fixed"])),
                ],
            ),
            vec![
                vec![],
                vec![param.clone()],
                vec![param.clone(), Type::Int],
                vec![param.clone(), Type::Int],
            ],
        ),
        ..record("Choice", &[], &["T"])
    };
    catalog(vec![
        record(
            "Container",
            &[("items", Type::set(param.clone())), ("fixed", Type::Int)],
            &["T"],
        ),
        choice,
        record(
            "Chain",
            &[
                ("head", param.clone()),
                ("next", Type::option(Type::Named(CHAIN, vec![param]))),
            ],
            &["T"],
        ),
        newtype("OrderId", Type::Text, &[]),
    ])
}

/// The bytes of the value `json`, a JSON form, at `ty` in `catalog`.
fn bytes(catalog: &Catalog, ty: &Type, json: &str) -> Vec<u8> {
    let json = flow_abi::parse(json, &Limits::default()).expect("JSON");
    let value = flow_abi::decode(catalog, ty, &json, Mode::Rebuild, &Limits::default())
        .expect("the JSON form decodes at its type");
    let mut out = Vec::new();
    flow_abi::write_value(&mut out, catalog, ty, &value).expect("it encodes");
    out
}

/// The JSON form of the value `bytes` hold at `ty`.
fn form(catalog: &Catalog, ty: &Type, bytes: &[u8]) -> String {
    let value =
        flow_abi::decode_bytes(catalog, ty, bytes, Mode::Rebuild, &Limits::default()).unwrap();
    flow_abi::encode(catalog, ty, &value)
        .expect("a JSON form")
        .canonical()
}

/// `T` read at `ty` from `held`, as the seam reads a call's argument, or
/// none when `held` is not exactly one of `T`'s values.
fn read_bytes<T: Shaped>(catalog: &Catalog, ty: &Type, held: &[u8]) -> Option<T> {
    let mut reader = Reader::new(held);
    let value = flow_abi::read_shaped(&mut reader, catalog, ty, Mode::Rebuild, &Limits::default());
    value.ok().filter(|_| reader.is_empty())
}

/// `T` read from the bytes of `json` at `ty`.
fn read<T: Shaped>(catalog: &Catalog, ty: &Type, json: &str) -> T {
    read_bytes(catalog, ty, &bytes(catalog, ty, json)).expect("it is one of the Rust type's")
}

/// `value`'s bytes at `ty`, or none when it is no value of `ty`.
fn write<T: Shaped>(catalog: &Catalog, ty: &Type, value: &T) -> Option<Vec<u8>> {
    let mut out = Vec::new();
    flow_abi::write_shaped(&mut out, catalog, ty, value).ok()?;
    Some(out)
}

/// The JSON form of `value`, written at `ty`.
fn written<T: Shaped>(catalog: &Catalog, ty: &Type, value: &T) -> String {
    let out = write(catalog, ty, value).expect("it writes at its type");
    form(catalog, ty, &out)
}

/// `json` read as `T` at `ty` and written back, as a JSON form.
fn round_trip<T: Shaped>(catalog: &Catalog, ty: &Type, json: &str) -> String {
    written(catalog, ty, &read::<T>(catalog, ty, json))
}

/// Every scalar and collection an encoded value holds, as its JSON form.
fn crossings() -> Vec<(Type, &'static str)> {
    vec![
        (Type::Unit, "[]"),
        (Type::Bool, "true"),
        (Type::Int, "-7"),
        (Type::Text, r#""é""#),
        (Type::Decimal, "1.5"),
        (Type::Bytes, r#""AAE=""#),
        (Type::Duration, r#""PT1S""#),
        (Type::Instant, r#""2026-01-01T00:00:00Z""#),
        (Type::Json, r#"{"a":[1,2.5,null,true,"x"]}"#),
        (Type::list(Type::Int), "[3,1]"),
        (Type::set(Type::Int), "[1,2]"),
        (Type::dict(Type::Text, Type::Int), r#"{"a":1}"#),
        (Type::Tuple(vec![Type::Int, Type::Text]), r#"[1,"a"]"#),
        (Type::option(Type::Int), r#"{"Some":4}"#),
        (Type::Named(ORDER, vec![]), r#""o-1""#),
        (
            Type::Named(CONTAINER, vec![Type::Text]),
            r#"{"fixed":3,"items":["a","b"]}"#,
        ),
        (Type::Named(CHOICE, vec![Type::Int]), r#"{"Pair":[1,2]}"#),
        (
            Type::Named(CHAIN, vec![Type::Named(ORDER, vec![])]),
            r#"{"head":"a","next":{"head":"b"}}"#,
        ),
    ]
}

#[test]
fn an_encoded_value_crosses_unchanged_at_every_type() {
    let types = fixtures();
    for (ty, json) in crossings() {
        let held = bytes(&types, &ty, json);
        let encoded = read::<Encoded>(&types, &ty, json);
        assert_eq!(write(&types, &ty, &encoded), Some(held.clone()), "{json}");
        assert_eq!(
            Encoded::new(&types, &ty, held.clone())
                .ok()
                .and_then(|made| write(&types, &ty, &made)),
            Some(held),
            "{json}"
        );
    }
}

#[test]
fn an_encoded_value_is_written_only_at_a_type_its_bytes_are_a_value_of() {
    let types = fixtures();
    let text = read::<Encoded>(&types, &Type::Text, r#""1""#);
    assert!(write(&types, &Type::Int, &text).is_none());
    let three = read::<Encoded>(&types, &Type::list(Type::Int), "[1,2,3]");
    assert!(write(&types, &Type::Tuple(vec![Type::Int; 3]), &three).is_none());
    assert!(Encoded::new(&types, &Type::Int, bytes(&types, &Type::Text, r#""1""#)).is_err());
    let mut cut = bytes(&types, &Type::list(Type::Int), "[1,2]");
    cut.pop();
    assert!(Encoded::new(&types, &Type::list(Type::Int), cut).is_err());
}

#[test]
fn encoded_values_are_equal_when_they_are_one_value() {
    let types = fixtures();
    let one = read::<Encoded>(&types, &Type::Int, "7");
    assert_eq!(one, read::<Encoded>(&types, &Type::Int, "7"));
    assert_ne!(one, read::<Encoded>(&types, &Type::Int, "8"));
    let ints = Type::set(Type::Int);
    let read = read::<BTreeSet<Encoded>>(&types, &ints, "[1,2,3]");
    assert_eq!(read.len(), 3);
    let mut doubled = read;
    doubled.insert(one.clone());
    doubled.insert(one);
    assert_eq!(written(&types, &ints, &doubled), "[1,2,3,7]");
}

#[test]
fn an_encoded_value_shows_only_its_length() {
    let types = fixtures();
    let held = read::<Encoded>(&types, &Type::Text, r#""secret""#);
    assert_eq!(format!("{held:?}"), "Encoded(7 bytes)");
}

#[test]
fn a_derived_generic_type_reads_its_type_parameter_at_the_calls_concrete_type() {
    let types = fixtures();
    let container = Type::Named(CONTAINER, vec![Type::Int]);
    let read = read::<Container<Int>>(&types, &container, r#"{"items":[9,2],"fixed":1}"#);
    assert_eq!(
        read,
        Container {
            items: BTreeSet::from([Int::from(2), Int::from(9)]),
            fixed: Int::from(1)
        }
    );
    assert_eq!(
        written(&types, &container, &read),
        r#"{"fixed":1,"items":[2,9]}"#
    );
    let numbers = Type::Named(CONTAINER, vec![Type::Int]);
    assert_eq!(
        round_trip::<Container<Encoded>>(&types, &numbers, r#"{"items":[10,2,300],"fixed":1}"#),
        r#"{"fixed":1,"items":[2,10,300]}"#,
        "a set of encoded values is written in Flow's order, not their bytes'"
    );
    let choice = Type::Named(CHOICE, vec![Type::Named(ORDER, vec![])]);
    for json in [
        r#""Empty""#,
        r#"{"One":"a"}"#,
        r#"{"Pair":["a",2]}"#,
        r#"{"Named":{"fixed":3,"value":"b"}}"#,
    ] {
        assert_eq!(round_trip::<Choice<Encoded>>(&types, &choice, json), json);
    }
    let chain = Type::Named(CHAIN, vec![Type::list(Type::Int)]);
    let json = r#"{"head":[1],"next":{"head":[2,3]}}"#;
    assert_eq!(round_trip::<Chain<Encoded>>(&types, &chain, json), json);
    let nested = Type::list(Type::set(Type::Int));
    assert_eq!(
        round_trip::<Vec<BTreeSet<Int>>>(&types, &nested, "[[9,2],[1]]"),
        "[[2,9],[1]]"
    );
    let maybe = Type::option(Type::dict(Type::Int, Type::Text));
    assert_eq!(
        round_trip::<Option<BTreeMap<Int, Encoded>>>(
            &types,
            &maybe,
            r#"{"Some":[[9,"a"],[2,"b"]]}"#
        ),
        r#"{"Some":[[2,"b"],[9,"a"]]}"#
    );
}

#[derive(Flow, Clone, Debug)]
pub struct Stamp<T> {
    pub at: T,
}

#[derive(Flow, Clone, Debug)]
pub enum Mark<T> {
    Placed { at: T },
}

#[test]
fn a_derived_type_reads_a_field_by_any_name_its_declaration_gives() {
    let types = catalog(vec![
        record("Stamp", &[("at", Type::Param(0))], &["T"]),
        flow_types::Decl {
            body: Body::Enum(
                EnumShape::new("Mark", [Constructor::new("Placed", Payload::named(["at"]))]),
                vec![vec![Type::Param(0)]],
            ),
            ..record("Mark", &[], &["T"])
        },
    ]);
    let stamp = Type::Named(DeclId(0), vec![Type::Int]);
    assert_eq!(
        round_trip::<Stamp<Encoded>>(&types, &stamp, r#"{"at":4}"#),
        r#"{"at":4}"#
    );
    let mark = Type::Named(DeclId(1), vec![Type::Text]);
    let json = r#"{"Placed":{"at":"here"}}"#;
    assert_eq!(round_trip::<Mark<Encoded>>(&types, &mark, json), json);
}

#[test]
fn a_derived_type_read_at_another_shape_is_refused() {
    let types = fixtures();
    let wrong = Type::Named(CHAIN, vec![Type::Int]);
    let chain = bytes(&types, &wrong, r#"{"head":1}"#);
    assert!(read_bytes::<Container<Int>>(&types, &wrong, &chain).is_none());
    let container = Container {
        items: BTreeSet::from(["x".to_owned()]),
        fixed: Int::from(0),
    };
    assert!(
        write(&types, &Type::Named(CONTAINER, vec![Type::Int]), &container).is_none(),
        "a set of text is no set of integers"
    );
}

#[test]
fn a_set_or_dictionary_written_from_rust_follows_flows_order() {
    let types = fixtures();
    let texts = BTreeSet::from(["é".to_owned(), "z".to_owned(), "a".to_owned()]);
    assert_eq!(
        written(&types, &Type::set(Type::Text), &texts),
        r#"["a","z","é"]"#,
        "text by code point"
    );
    let dict = Type::dict(Type::Int, Type::Text);
    assert_eq!(
        round_trip::<BTreeMap<Int, String>>(&types, &dict, r#"[[10,"ten"],[2,"two"]]"#),
        r#"[[2,"two"],[10,"ten"]]"#,
        "a dictionary in ascending key order"
    );
}

#[test]
fn a_std_value_carried_whole_is_read_and_written_at_its_declaration() {
    let types = fixtures();
    let order = Type::Named(ORDER, vec![]);
    let bundle = read::<Bundle>(&types, &order, r#""b-1""#);
    assert_eq!(written(&types, &order, &bundle), r#""b-1""#);
}

#[test]
fn a_tuple_reads_and_writes_each_part_at_its_type() {
    let types = fixtures();
    let pair = Type::Tuple(vec![Type::Int, Type::Text]);
    assert_eq!(
        round_trip::<(Int, String)>(&types, &pair, r#"[1,"a"]"#),
        r#"[1,"a"]"#
    );
    let triple = Type::Tuple(vec![Type::Int, Type::Text, Type::Int]);
    let three = bytes(&types, &triple, r#"[1,"a",2]"#);
    assert!(
        read_bytes::<(Int, String)>(&types, &triple, &three).is_none(),
        "a pair is not read at a triple"
    );
}

#[test]
fn an_option_refuses_a_constructor_it_does_not_have() {
    let types = fixtures();
    let maybe = Type::option(Type::Int);
    let refused = flow_abi::decode_bytes(&types, &maybe, &[2], Mode::Rebuild, &Limits::default())
        .expect_err("an Option has two constructors");
    assert!(refused.to_string().contains("Option"), "{refused}");
}

#[test]
fn a_result_is_no_value_of_another_type() {
    let types = fixtures();
    let one = bytes(&types, &Type::Int, "1");
    assert!(read_bytes::<Result<Int, String>>(&types, &Type::Int, &one).is_none());
}

#[test]
fn each_native_type_is_named_as_flow_source_names_it() {
    use crate::function::Owner;
    use flow_abi::contract::TypeRef;
    use flow_toolkit::{Decimal, Duration};
    let mut types = flow_toolkit::__bridge::Types::default();
    assert_eq!(types.form(Decimal::FORM), TypeRef::named("Decimal"));
    assert_eq!(
        types.form(Duration::FORM),
        TypeRef::qualified(Owner::Std("duration"), "Duration")
    );
    assert_eq!(
        types.form(std::path::PathBuf::FORM),
        TypeRef::qualified(Owner::Std("path"), "Path")
    );
}

#[test]
fn a_native_form_is_held_by_its_std_declaration() {
    use flow_toolkit::Url;
    use flow_types::{Identity, ModulePath, Segments, Tree};
    let path = flow_types::Decl {
        identity: Identity {
            origin: ModulePath::new(
                Tree::Std,
                None,
                "path".parse::<Segments>().expect("a test path is a path"),
            ),
            version: Some("v1".into()),
            name: "Path".into(),
        },
        ..newtype("Path", Type::Text, &[])
    };
    let types = catalog(vec![path]);
    let path = Type::Named(DeclId(0), vec![]);
    assert!(write(&types, &path, &std::path::PathBuf::from("a/b")).is_some());
    let url = Url::parse("http://example.com/").expect("a URL");
    assert!(write(&types, &path, &url).is_none());
}

#[test]
fn a_set_or_dictionary_cut_short_refuses_to_read() {
    let types = fixtures();
    let set = Type::set(Type::Int);
    let mut held = bytes(&types, &set, "[1,2]");
    held.pop();
    let cut = |ty: &Type, held: &[u8]| {
        flow_abi::read_value(
            &mut Reader::new(held),
            &types,
            ty,
            Mode::Rebuild,
            &Limits::default(),
        )
        .is_err()
    };
    assert!(cut(&set, &held));
    let dict = Type::dict(Type::Text, Type::Int);
    let mut held = bytes(&types, &dict, r#"{"a":1,"b":2}"#);
    held.pop();
    assert!(cut(&dict, &held));
}

#[test]
fn a_host_value_crosses_as_its_token() {
    let types = catalog(vec![flow_types::Decl {
        body: Body::Host,
        ..record("Handle", &[], &[])
    }]);
    let handle = Type::Named(DeclId(0), vec![]);
    let value = read::<Encoded>(&types, &handle, r#""h-1""#);
    assert_eq!(written(&types, &handle, &value), r#""h-1""#);
}

#[test]
fn a_type_parameters_place_holder_has_no_values() {
    use flow_toolkit::__bridge::wire::Param;
    let types = fixtures();
    let unit = bytes(&types, &Type::Unit, "[]");
    assert!(read_bytes::<Param<0>>(&types, &Type::Unit, &unit).is_none());
}

#[test]
fn a_tool_problem_is_named_as_std_declares_it() {
    let mut named = flow_toolkit::__bridge::Types::default();
    assert_eq!(
        named.form(flow_toolkit::ToolProblem::FORM),
        flow_abi::contract::TypeRef::named("ToolProblem")
    );
}