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
//! A Rust type marked `#[flow(std = "module.Name")]` is std's existing
//! declaration `Name` of `std@v1/module` (`abi.md`, *Generated contracts*):
//! the contract names it, imports its module and declares nothing for it,
//! and the Rust type carries the value whole, as an [`Encoded`], without
//! modelling its fields.
#![expect(
    missing_docs,
    reason = "the test binary's tool fixtures are public by the derive's rule"
)]
mod common;

use std::collections::BTreeMap;
use std::marker::PhantomData;

use flow_toolkit::{Encoded, Flow, Int, tool};

/// A program and its files, as std's `code.Bundle`.
#[derive(Flow, Clone, Debug)]
#[flow(std = "code.Bundle")]
pub struct Bundle(pub Encoded);

/// A run's id, as std's `code.RunId`.
#[derive(Flow, Clone, Debug)]
#[flow(std = "code.RunId")]
pub struct RunId(pub Encoded);

/// A checked program, as std's `code.Checked`.
#[derive(Flow, Clone, Debug)]
#[flow(std = "code.Checked")]
pub struct Checked(pub Encoded);

/// What a checker says, as std's `code.Diagnostic`.
#[derive(Flow, Clone, Debug)]
#[flow(std = "code.Diagnostic")]
pub struct Diagnostic(pub Encoded);

/// A signature, as std's `code.Signature`.
#[derive(Flow, Clone, Debug)]
#[flow(std = "code.Signature")]
pub struct Signature(pub Encoded);

/// A value of any type, as std's `code.Value`.
#[derive(Flow, Clone, Debug)]
#[flow(std = "code.Value")]
pub struct Value(pub Encoded);

/// A generic std declaration: its type parameters are the Rust type's, in
/// order.
#[derive(Flow, Clone, Debug)]
#[flow(std = "code.LocalRef")]
pub struct LocalRef<T>(pub Encoded, pub PhantomData<T>);

/// A run started from a bundle: a record of this library's that holds std
/// values.
#[derive(Flow, Clone, Debug)]
pub struct Started {
    pub bundle: Bundle,
    pub run: Option<RunId>,
}

#[tool]
pub fn start(bundle: Bundle, run: Option<RunId>) -> Started {
    Started { bundle, run }
}

#[tool]
pub fn every(
    checked: Checked,
    diagnostics: Vec<Diagnostic>,
    signature: Signature,
    value: Value,
) -> Vec<Diagnostic> {
    let _ = (checked, signature, value);
    diagnostics
}

/// A Tool whose parameter is named like std's module `code`.
#[tool]
pub fn rename(code: Bundle) -> Bundle {
    code
}

#[tool]
pub fn local(at: LocalRef<Int>) -> Int {
    let _ = at;
    Int::from(0)
}

/// The contract of the Tools `placed`, each placed in the root module.
fn contract(
    placed: Vec<flow_toolkit::__bridge::Function>,
) -> BTreeMap<flow_types::Segments, String> {
    let placed: Vec<_> = placed
        .into_iter()
        .map(|function| flow_toolkit::__bridge::at("", "tests/std_declarations.rs", 1, function))
        .collect();
    common::extract("std_declarations", None, &placed).expect("the contract is written")
}

fn text(contract: &BTreeMap<flow_types::Segments, String>) -> String {
    contract.values().cloned().collect::<Vec<_>>().join("\n")
}

#[test]
fn a_std_declaration_is_named_and_its_module_imported_and_nothing_is_declared_for_it() {
    let source = text(&contract(vec![__flow_tool_start(), __flow_tool_every()]));
    for line in [
        "use \"std@v1/code\"\n",
        "pub flow start(bundle: code.Bundle, run: Option<code.RunId>) -> Started\n",
        "pub flow every(checked: code.Checked, diagnostics: List<code.Diagnostic>, signature: code.Signature, value: code.Value) -> List<code.Diagnostic>\n",
        "    pub bundle: code.Bundle,\n",
        "    pub run: Option<code.RunId>,\n",
    ] {
        assert!(source.contains(line), "{line:?} in {source}");
    }
    for declared in [
        "type Bundle",
        "type RunId",
        "type Checked",
        "type Diagnostic",
        "type Signature",
        "type Value",
    ] {
        assert!(!source.contains(declared), "{declared:?} in {source}");
    }
    assert_eq!(source.matches("use ").count(), 1, "{source}");
}

#[test]
fn a_parameter_named_like_a_std_module_leaves_its_import_alone() {
    let source = text(&contract(vec![__flow_tool_rename()]));
    assert!(source.contains("use \"std@v1/code\"\n"), "{source}");
    assert!(
        source.contains("pub flow rename(code: code.Bundle) -> code.Bundle\n"),
        "{source}"
    );
}

#[test]
fn a_generic_std_declaration_takes_the_rust_types_arguments_in_order() {
    let source = text(&contract(vec![__flow_tool_local()]));
    assert!(
        source.contains("pub flow local(at: code.LocalRef<Int>) -> Int\n"),
        "{source}"
    );
}

/// A run's child: its entry is private, and its result type only a
/// phantom parameter.
#[derive(Flow, Clone, Debug)]
pub struct Child<O> {
    pub run: RunId,
    entry: Option<Signature>,
    result: PhantomData<O>,
}

#[tool]
pub fn child(child: Child<Int>) -> Child<Int> {
    let _ = (&child.entry, child.result);
    child
}

#[test]
fn a_records_phantom_field_is_skipped_and_its_parameter_stays_on_the_declaration() {
    let source = text(&contract(vec![__flow_tool_child()]));
    assert!(
        source.contains(
            "pub type Child<O> {\n    pub run: code.RunId,\n    entry: Option<code.Signature>,\n}\n"
        ),
        "{source}"
    );
    assert!(
        source.contains("pub flow child(child: Child<Int>) -> Child<Int>\n"),
        "{source}"
    );
    // It crosses as its other fields alone, at the type the compiler
    // describes for it.
    let (catalog, ty) = parameter(vec![__flow_tool_child()], "child");
    let bytes = common::runtime_bytes(
        &catalog,
        &ty,
        r#"{"run":"0123456789abcdef0123456789abcdef"}"#,
    );
    let (child, written) = common::reread::<Child<Int>>(&catalog, &ty, &bytes);
    assert!(child.entry.is_none());
    assert_eq!(written, bytes);
}

/// The catalog and the type of the first parameter of the one Tool
/// `placed`, named `tool`, as the host lists it.
fn parameter(
    placed: Vec<flow_toolkit::__bridge::Function>,
    tool: &str,
) -> (flow_abi::Catalog, flow_types::Type) {
    let listed = common::listed(
        &contract(placed),
        &common::referring(&[&format!("lib.{tool}")]),
    );
    let mut own = listed.iter().filter(|(identity, _)| {
        identity
            .library
            .as_ref()
            .is_none_or(|library| library.address != "std")
    });
    let (Some((_, spec)), None) = (own.next(), own.next()) else {
        panic!("one Tool of the library's own: {listed:?}")
    };
    (spec.catalog().clone(), spec.signature().params[0].1.clone())
}

#[tool]
pub fn mixed(bundle: Bundle, at: std::path::PathBuf, raw: flow_toolkit::JsonValue) -> Bundle {
    let _ = (at, raw);
    bundle
}

#[test]
fn every_std_module_a_contract_names_is_imported_once_in_module_order() {
    // `json`, `path` and `code` together: the fixed list the generator had
    // is now whatever the contract names.
    let source = text(&contract(vec![__flow_tool_mixed()]));
    let imports: Vec<&str> = source
        .lines()
        .filter(|line| line.starts_with("use "))
        .collect();
    assert_eq!(
        imports,
        [
            "use \"std@v1/code\"",
            "use \"std@v1/json\"",
            "use \"std@v1/path\""
        ],
        "{source}"
    );
}

#[test]
fn the_generated_contract_is_one_the_checker_accepts() {
    let contract = contract(vec![
        __flow_tool_start(),
        __flow_tool_every(),
        __flow_tool_rename(),
    ]);
    let listed = common::listed(
        &contract,
        &common::referring(&["lib.start", "lib.every", "lib.rename"]),
    );
    assert!(common::tool_names(&listed).contains(&"start"));
    for name in ["Bundle", "RunId", "Checked", "Diagnostic"] {
        assert!(common::names_std(&listed, "code", name), "code.{name}");
    }
}

#[test]
fn a_std_value_is_carried_whole_and_read_and_written_at_its_declaration() {
    let (catalog, ty) = parameter(vec![__flow_tool_rename()], "rename");
    let bytes = common::runtime_bytes(
        &catalog,
        &ty,
        r#"{"entry":{"module":{"tree":"Local","segments":[]},"name":"main"},"files":[]}"#,
    );
    let (bundle, written) = common::reread::<Bundle>(&catalog, &ty, &bytes);
    assert_eq!(
        format!("{bundle:?}"),
        format!("Bundle(Encoded({} bytes))", bytes.len())
    );
    assert_eq!(written, bytes);
}