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
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
//! Shared harness: the workspace's `flow` run in a project of its own
//! ([`flow_testing::Project`]), contracts staged as Rust libraries, and the
//! `--contract` file the host hands a library's process.

#![allow(
    dead_code,
    unreachable_pub,
    reason = "shared by several test binaries, each using part of it"
)]

use flow_start::Spawn as _;
use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::process::Output;

use flow_testing::{Outside, Project};

/// The workspace's `flow-toolkit-rust`, built once for this test process.
pub fn rust_toolkit() -> &'static str {
    flow_testing::rust_toolkit()
        .to_str()
        .expect("the build directory is UTF-8")
}

/// The contract `functions` of the crate `crate_name` extract to, each
/// module as the host prints it.
pub fn extract(
    crate_name: &str,
    root: Option<&Path>,
    functions: &[flow_toolkit::__bridge::Function],
) -> Result<BTreeMap<flow_types::Segments, String>, flow_toolkit::ContractError> {
    flow_toolkit::__bridge::extract(crate_name, root, functions).map(|modules| {
        modules
            .into_iter()
            .map(|(path, module)| (path, flow_abi::contract::print(&module)))
            .collect()
    })
}

/// A file of this crate's, by its path inside the crate.
pub fn own(path: &str) -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join(path)
}

/// This test process's [`Outside`]: in the `CARGO_TARGET_TMPDIR` Cargo names
/// for an integration test, and in the system's temporary directory for the
/// unit tests that include this module, which Cargo names none for.
pub fn outside() -> &'static Outside {
    let dir = option_env!("CARGO_TARGET_TMPDIR").map_or_else(
        || std::env::temp_dir().join("flow-toolkit-rust-units"),
        PathBuf::from,
    );
    Outside::of(&dir)
}

/// What `flow ARGS` exited with and wrote, run in a project of its own.
pub fn flow(args: &[&str]) -> Output {
    Project::new(outside(), &[], &[]).flow(args)
}

/// What `output` wrote: its standard output, then its standard error.
pub fn said(output: &Output) -> String {
    format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    )
}

/// `text` formatted by `flow fmt`.
pub fn flow_fmt(text: &str) -> String {
    let project = Project::new(outside(), &[("contract.flow", text)], &[]);
    let formatted = project.flow(&["fmt", "contract.flow"]);
    assert!(formatted.status.success(), "{}", said(&formatted));
    std::fs::read_to_string(project.path().join("contract.flow"))
        .expect("the formatted text is read")
}

/// Writes `contracts`, each library module's contract text by module path,
/// as the committed contract of the library `<dir>/lib`, served by the
/// command line `serve` and naming no generator, beside a `main.flow` that
/// imports each of its modules and goes on with `program`, and returns that
/// program.
pub fn stage_contract(
    dir: &Path,
    contracts: &BTreeMap<flow_types::Segments, String>,
    serve: &str,
    program: &str,
) -> PathBuf {
    let library = dir.join("lib");
    std::fs::create_dir_all(library.join("contract")).expect("the library directory is created");
    std::fs::write(
        library.join("flow.toml"),
        format!("[process]\ncommand = '{serve}'\n"),
    )
    .expect("flow.toml is written");
    let mut imports = String::new();
    let mut bound = std::collections::BTreeSet::new();
    for (module, text) in contracts {
        let module = module.as_str();
        let file = if module.is_empty() {
            library.join("contract/lib.flow")
        } else {
            library.join("contract").join(format!("{module}.flow"))
        };
        std::fs::create_dir_all(file.parent().expect("a contract file has a directory"))
            .expect("the contract directory is created");
        std::fs::write(&file, text).expect("the contract module is written");
        let natural = module.rsplit('/').next().filter(|last| !last.is_empty());
        match natural {
            None if bound.insert("lib".to_owned()) => imports.push_str("use \"./lib\"\n"),
            Some(last) if bound.insert(last.to_owned()) => {
                writeln!(imports, "use \"./lib/{module}\"").expect("a String takes text");
            }
            _ => {
                let alias = format!("lib_{}", module.replace('/', "_"));
                bound.insert(alias.clone());
                writeln!(imports, "use \"./lib/{module}\" as {alias}")
                    .expect("a String takes text");
            }
        }
    }
    let main = dir.join("main.flow");
    std::fs::write(&main, format!("{imports}{program}")).expect("the program is written");
    main
}

/// The `--contract` file the host hands the process serving the library
/// [`stage_contract`] stages from `contracts`, when it binds a run of the
/// staged program going on with `program`: every Tool of the
/// library that the functions of `program` reach. Its `main` takes no
/// input, since the host binds before a run starts. The library's command is
/// a recorder, which keeps a copy of the file it is handed and serves
/// nothing, so the binding fails and no run starts.
pub fn listing(contracts: &BTreeMap<flow_types::Segments, String>, program: &str) -> Vec<u8> {
    let project = Project::new(outside(), &[], &[]);
    stage_contract(
        project.path(),
        contracts,
        "sh -c \"cp $2 ../listing\" record",
        program,
    );
    let bound = project.flow(&["run", "main.flow"]);
    std::fs::read(project.path().join("listing")).unwrap_or_else(|error| {
        panic!(
            "the host hands the library a listing ({error}): {}",
            said(&bound)
        )
    })
}

/// A `main` that refers to each of `tools`, by its path, and so reaches it.
pub fn referring(tools: &[&str]) -> String {
    let mut main = String::from("pub flow main() -> Int = {\n");
    for tool in tools {
        writeln!(main, "    let _ = {tool}").expect("a String takes text");
    }
    main.push_str("    1\n}\n");
    main
}

/// Each Tool [`listing`] lists, in its order: its identity and its own
/// description.
pub fn listed(
    contracts: &BTreeMap<flow_types::Segments, String>,
    program: &str,
) -> Vec<(flow_abi::description::Identity, flow_abi::TypeSpec)> {
    flow_abi::read_listing(&listing(contracts, program))
        .expect("the host writes a valid contract file")
        .into_iter()
        .flat_map(|program| program.tools)
        .collect()
}

/// The contract modules an `extract` wrote to the file `out`, by module
/// path, each as the host prints it.
pub fn modules(out: &Path) -> BTreeMap<flow_types::Segments, String> {
    let bytes = std::fs::read(out).expect("the contract file is read");
    let contract =
        flow_abi::contract::Contract::decode(&bytes).expect("extract writes one contract");
    contract
        .modules
        .into_iter()
        .map(|module| {
            let path = flow_types::Segments::from_names(module.path.iter().map(String::as_str))
                .expect("a contract module's path is a module path");
            (path, flow_abi::contract::print(&module.module))
        })
        .collect()
}

/// The paths the depfile at `path` lists: one absolute path to a line, each
/// line ended by a line feed.
pub fn depfile(path: &Path) -> Vec<PathBuf> {
    let text = std::fs::read_to_string(path).expect("the depfile is read");
    assert!(
        text.is_empty() || text.ends_with('\n'),
        "every line ends with a line feed: {text:?}"
    );
    text.lines().map(PathBuf::from).collect()
}

/// The catalog of `decls`, the `n`th being `DeclId(n)`, with std's `Option` and
/// `json.Value`.
pub fn catalog(decls: Vec<flow_types::Decl>) -> flow_abi::Catalog {
    flow_abi::Catalog::std(decls).expect("regular test declarations")
}

/// std's `Result<T, E>`, declared in `std@v1/result`.
pub fn std_result() -> flow_types::Decl {
    use flow_types::{Constructor, EnumShape, Payload};
    flow_types::Decl {
        lexical_ordinal: 1,
        identity: flow_types::Identity {
            origin: flow_types::ModulePath::new(
                flow_types::Tree::Std,
                None,
                "result"
                    .parse::<flow_types::Segments>()
                    .expect("a test path is a path"),
            ),
            version: Some("v1".into()),
            name: "Result".into(),
        },
        doc: None,
        members: Vec::new(),
        params: vec!["T".into(), "E".into()],
        opaque: false,
        body: flow_types::Body::Enum(
            EnumShape::new(
                "Result",
                [
                    Constructor::new("Ok", Payload::Positional(1)),
                    Constructor::new("Err", Payload::Positional(1)),
                ],
            ),
            vec![
                vec![flow_types::Type::Param(0)],
                vec![flow_types::Type::Param(1)],
            ],
        ),
    }
}

/// The context of a call to a Tool generic in `T`, of no parameters, that
/// binds `T` to `bound`, whose declarations `decls` are: what the
/// toolkit hands the author's code for that call.
pub fn bound_call(bound: flow_types::Type, decls: Vec<flow_types::Decl>) -> flow_toolkit::Context {
    let catalog = catalog(decls);
    let signature = flow_abi::Signature {
        params: Vec::new(),
        result: flow_types::Type::Text,
        generic: vec!["T".into()],
    };
    let spec = flow_abi::TypeSpec::from_catalog(&catalog, &signature).expect("a served type");
    let generic = flow_abi::call_views(&catalog, &signature, &[bound]).expect("the call's views");
    flow_toolkit::Context::try_new(
        "7f3a91c04be2d5e6f708192a3b4c5d6e/root#1"
            .parse()
            .expect("a call key"),
        &spec,
        Some(&generic),
        flow_toolkit::Cancellation::default(),
    )
    .expect("the views fit the declaration")
}

/// `value`'s bytes at `ty`, whose declarations `decls` are; none when it
/// is no value of `ty`.
pub fn written_at<T: flow_toolkit::Shaped>(
    value: &T,
    ty: &flow_types::Type,
    decls: Vec<flow_types::Decl>,
) -> Option<Vec<u8>> {
    let catalog = catalog(decls);
    let mut bytes = Vec::new();
    flow_abi::write_shaped(&mut bytes, &catalog, ty, value).ok()?;
    Some(bytes)
}

/// The `json.Value` the JSON text `text` is.
pub fn raw(text: &str) -> flow_toolkit::JsonValue {
    use flow_toolkit::{Json, JsonValue};
    fn of(json: &Json) -> JsonValue {
        match json {
            Json::Null => JsonValue::Null,
            Json::Bool(flag) => JsonValue::Bool(*flag),
            Json::Number(number) => JsonValue::Number(number.clone()),
            Json::String(text) => JsonValue::Text(text.clone()),
            Json::Array(items) => JsonValue::List(items.iter().map(of).collect()),
            Json::Object(members) => JsonValue::Object(
                members
                    .iter()
                    .map(|(name, member)| (name.clone(), of(member)))
                    .collect(),
            ),
        }
    }
    of(&flow_toolkit::parse_json(text).expect("JSON"))
}

/// Whether a description among `listed` names std's declaration
/// `module.name`.
pub fn names_std(
    listed: &[(flow_abi::description::Identity, flow_abi::TypeSpec)],
    module: &str,
    name: &str,
) -> bool {
    listed.iter().any(|(_, spec)| {
        spec.catalog().decls().any(|(_, decl)| {
            decl.identity.name == name
                && *decl.identity.origin.tree() == flow_types::Tree::Std
                && *decl.identity.origin.segments() == module
        })
    })
}

/// The names of the Tools `listed` that are not std's, in name order.
pub fn tool_names(listed: &[(flow_abi::description::Identity, flow_abi::TypeSpec)]) -> Vec<&str> {
    let mut names: Vec<&str> = listed
        .iter()
        .filter(|(identity, _)| {
            identity
                .library
                .as_ref()
                .is_none_or(|library| library.address != "std")
        })
        .map(|(identity, _)| identity.name.as_str())
        .collect();
    names.sort_unstable();
    names
}

/// A declaration named `name` of the local file `./main`, generic in
/// `params`.
pub fn local(name: &str, params: &[&str], body: flow_types::Body) -> flow_types::Decl {
    flow_types::Decl {
        lexical_ordinal: 1,
        identity: flow_types::Identity {
            origin: flow_types::ModulePath::new(
                flow_types::Tree::Local,
                None,
                "main"
                    .parse::<flow_types::Segments>()
                    .expect("a test path is a path"),
            ),
            version: None,
            name: name.into(),
        },
        doc: None,
        members: Vec::new(),
        params: params.iter().map(|param| (*param).to_owned()).collect(),
        opaque: false,
        body,
    }
}

/// The bytes of the value whose JSON form is `json`, at `ty` in `catalog`,
/// as the runtime writes them.
pub fn runtime_bytes(catalog: &flow_abi::Catalog, ty: &flow_types::Type, json: &str) -> Vec<u8> {
    let limits = flow_abi::Limits::default();
    let json = flow_abi::parse(json, &limits).expect("JSON");
    let value = flow_abi::decode(catalog, ty, &json, flow_abi::Mode::Rebuild, &limits)
        .expect("the runtime reads the JSON form");
    flow_abi::encode_bytes(catalog, ty, &value).expect("the runtime writes the value")
}

/// The `T` that `bytes` hold at `ty`, read as the seam reads it, and
/// its bytes written back as the seam writes it.
pub fn reread<T: flow_toolkit::Shaped>(
    catalog: &flow_abi::Catalog,
    ty: &flow_types::Type,
    bytes: &[u8],
) -> (T, Vec<u8>) {
    let mut reader = flow_abi::primitives::Reader::new(bytes);
    let value: T = flow_abi::read_shaped(
        &mut reader,
        catalog,
        ty,
        flow_abi::Mode::Rebuild,
        &flow_abi::Limits::default(),
    )
    .expect("one of the Rust type's");
    assert!(reader.is_empty(), "the bytes are one whole value");
    let mut out = Vec::new();
    flow_abi::write_shaped(&mut out, catalog, ty, &value).expect("it is written");
    (value, out)
}

/// Stages the independently authored Rust conformance crate as the Rust
/// library `<project>/tools` served by the toolkit `executable`, and returns
/// the path a program imports it by.
pub fn stage_native_conformance(project: &Path, executable: &str) -> String {
    let native = project.join("tools");
    std::fs::create_dir(&native).expect("the fixture directory is created");
    for file in ["tools.rs", "sample.rs"] {
        std::fs::copy(own(&format!("tests/conformance/{file}")), native.join(file))
            .expect("the fixture file is copied");
    }
    std::fs::write(native.join("flow.toml"), flow_toml(executable)).expect("flow.toml is written");
    toolkit_consumer(
        &native,
        "staged-native-conformance",
        "[lib]\npath=\"tools.rs\"\n",
    );
    "./tools".into()
}

/// A Rust library's `flow.toml`: the toolkit `executable` as its `[process]`
/// command and generator, named by its path because the host finds a bare
/// name on a `PATH` the test process cannot change.
pub fn flow_toml(executable: &str) -> String {
    format!("[process]\ncommand = '\"{executable}\" serve'\nextract = '\"{executable}\" extract'\n")
}

/// Writes a Rust library at `root` with the toolkit `executable`'s `new`.
pub fn new_library(executable: &str, root: &Path) {
    let made = toolkit(executable)
        .arg("new")
        .arg(root)
        .locked_output()
        .expect("the toolkit runs");
    assert!(
        made.status.success(),
        "{}",
        String::from_utf8_lossy(&made.stderr)
    );
    std::fs::write(root.join("flow.toml"), flow_toml(executable)).expect("flow.toml is written");
}

/// The cache directory the toolkit runs with in these tests, as
/// `XDG_CACHE_HOME`: one for every test, so that their launchers share one
/// Cargo target directory as a toolkit's do.
pub fn cache_home() -> PathBuf {
    std::env::temp_dir().join("flow-toolkit-rust-tests")
}

/// The command running the toolkit `executable` with the tests'
/// [`cache_home`].
pub fn toolkit(executable: &str) -> std::process::Command {
    let mut command = std::process::Command::new(executable);
    command.env("XDG_CACHE_HOME", cache_home());
    command
}

/// Where the toolkit prepares the launcher of the Rust library at `root`:
/// its directory in the cache, keyed by the digest of the canonical root.
pub fn launcher_cache(root: &Path) -> PathBuf {
    use sha2::Digest as _;
    let root = root.canonicalize().expect("the path exists");
    let digest = sha2::Sha256::digest(root.as_os_str().as_encoded_bytes());
    let key = digest.iter().fold(String::new(), |mut key, byte| {
        use std::fmt::Write as _;
        let _ = write!(key, "{byte:02x}");
        key
    });
    cache_home()
        .join("flow-toolkit-rust/libraries")
        .join(&key[..32])
        .join("build")
}

/// Writes the manifest of a scratch Cargo package at `root` named `name`, a
/// workspace of its own depending on this toolkit by path, with `extra`
/// appended (more dependencies, or a `[lib]` table), and locks it from the
/// repository's lock in the same step, so no scratch consumer resolves from
/// the registry index. Its sources must already be written.
pub fn toolkit_consumer(root: &Path, name: &str, extra: &str) {
    let sdk = own("")
        .canonicalize()
        .expect("the toolkit's directory exists");
    let manifest = format!(
        "[package]\nname={name:?}\nversion=\"0.0.0\"\nedition=\"2024\"\n[workspace]\n[dependencies]\nflow-toolkit={{path={}}}\n{extra}",
        flow_abi::Json::String(sdk.to_str().expect("a UTF-8 path").into()).canonical()
    );
    std::fs::write(root.join("Cargo.toml"), manifest).expect("Cargo.toml is written");
    flow_testing::lock_from_repository(root);
}

/// The contract a stand-in launcher writes: one root module from `rust
/// module fixture` declaring `pub flow echo(value: Text) -> Result<Text,
/// Text>`.
pub fn echo_contract() -> Vec<u8> {
    use flow_abi::contract;
    let text = || contract::TypeRef::named("Text");
    let echo = contract::FlowDeclaration {
        name: "echo".to_owned(),
        generics: Vec::new(),
        params: vec![contract::Param {
            name: "value".to_owned(),
            ty: text(),
            default: None,
        }],
        result: contract::TypeRef::applied("Result", vec![text(), text()]),
    };
    contract::Contract {
        modules: vec![contract::Module {
            path: Vec::new(),
            module: contract::ContractModule {
                generated_from: "rust module fixture".to_owned(),
                imports: Vec::new(),
                items: vec![contract::Item {
                    docs: String::new(),
                    origin: None,
                    declaration: contract::Declaration::Flow(echo),
                }],
            },
        }],
    }
    .bytes()
}

/// A `printf` format that writes exactly `bytes`, each as an octal escape.
pub fn printf_format(bytes: &[u8]) -> String {
    bytes.iter().fold(String::new(), |mut out, byte| {
        let _ = write!(out, "\\{byte:03o}");
        out
    })
}