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
//! Visibility follows the native code (`abi.md`, *Generated contracts*):
//! every declaration is `pub`, a Rust field that is not `pub` is a private
//! Flow field, and a tuple struct whose field is not `pub` has a private
//! constructor. A program reads only the `pub` fields, builds only a value
//! whose parts are all `pub`, and passes back the others a Tool gave it.
#![expect(
    missing_docs,
    reason = "the test binary's tool fixtures are public by the derive's rule"
)]
mod common;

use std::collections::BTreeMap;

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

/// An account: its owner is public, its balance and note are not.
#[derive(Flow, Clone, Debug, PartialEq)]
pub struct Account {
    pub owner: String,
    balance: Int,
    pub(crate) note: String,
}

/// A token only a Tool makes: its constructor is private.
#[derive(Flow, Clone, Debug, PartialEq)]
pub struct Token(String);

/// A user's id, which anyone makes: its constructor is public.
#[derive(Flow, Clone, Debug, PartialEq)]
pub struct UserId(pub String);

/// An enum's payload fields have no visibility of their own.
#[derive(Flow, Clone, Debug, PartialEq)]
pub enum Event {
    Opened { owner: String },
    Closed,
}

#[tool]
pub fn open(owner: UserId) -> Account {
    Account {
        owner: owner.0,
        balance: Int::from(0),
        note: String::new(),
    }
}

#[tool]
pub fn token() -> Token {
    Token("t".to_owned())
}

/// A default may apply a private constructor in the newtype's own module.
#[tool]
pub fn mint(#[flow(default = Token("t"))] token: Token) -> Token {
    token
}

#[tool]
pub fn spend(account: Account, token: Token) -> Event {
    let _ = (account.balance, account.note, token.0);
    Event::Closed
}

fn contract() -> BTreeMap<flow_types::Segments, String> {
    let placed = [
        __flow_tool_open(),
        __flow_tool_token(),
        __flow_tool_mint(),
        __flow_tool_spend(),
    ]
    .map(|function| flow_toolkit::__bridge::at("", "tests/visibility.rs", 1, function));
    common::extract("visibility", None, &placed).expect("the contract is written")
}

#[test]
fn a_field_that_is_not_pub_in_rust_is_a_private_flow_field() {
    let source = contract().into_values().collect::<String>();
    assert!(
        source.contains(
            "pub type Account {\n    pub owner: Text,\n    balance: Int,\n    note: Text,\n}\n"
        ),
        "{source}"
    );
}

#[test]
fn a_tuple_struct_whose_field_is_not_pub_has_a_private_constructor() {
    let source = contract().into_values().collect::<String>();
    // `struct UserId(pub String)` and `struct Token(String)`, as abi.md's
    // *Extracting a contract* writes them.
    assert!(source.contains("pub type UserId(pub Text)\n"), "{source}");
    assert!(source.contains("pub type Token(Text)\n"), "{source}");
}

#[test]
fn every_declaration_stays_pub_and_payload_fields_are_unmarked() {
    let source = contract().into_values().collect::<String>();
    assert!(
        source.contains(
            "pub type Event {\n    Opened {\n        owner: Text,\n    },\n    Closed,\n}\n"
        ),
        "{source}"
    );
    for declaration in ["Account", "Token", "UserId", "Event"] {
        assert!(
            source.contains(&format!("pub type {declaration}")),
            "{declaration} in {source}"
        );
    }
}

/// What `flow check` says of `program`, which imports the generated
/// contract as `lib`.
fn checked(program: &str) -> (Option<i32>, String) {
    let files = tempfile::TempDir::with_prefix("flow-toolkit-visibility").expect("a directory");
    let main = common::stage_contract(
        files.path(),
        &contract(),
        "flow-toolkit-rust serve",
        program,
    );
    let output = common::flow(&["check", main.to_str().expect("a UTF-8 path")]);
    (output.status.code(), common::said(&output))
}

#[test]
fn a_program_reads_pub_fields_and_passes_back_what_a_tool_gave_it() {
    let (code, said) = checked(
        "pub flow main() -> Result<Text, ToolProblem> = {\n    let account = lib.open(lib.UserId(\"ada\"))?\n    let _ = lib.spend(account, lib.token()?)?\n    Ok(account.owner)\n}\n",
    );
    assert_eq!(code, Some(0), "{said}");
}

#[test]
fn a_default_applies_a_private_constructor_in_the_newtypes_own_module() {
    let source = contract().into_values().collect::<String>();
    assert!(
        source.contains("pub flow mint(token: Token = Token(\"t\")) -> Token\n"),
        "{source}"
    );
    let (code, said) = checked("pub flow main() -> Result<lib.Token, ToolProblem> = lib.mint()\n");
    assert_eq!(code, Some(0), "{said}");
}

#[test]
fn a_program_that_builds_or_reads_a_private_part_is_refused() {
    for (program, private) in [
        (
            "pub flow main() -> lib.Account = lib.Account { owner: \"ada\", balance: 1, note: \"\" }\n",
            "balance",
        ),
        (
            "pub flow main() -> lib.Token = lib.Token(\"forged\")\n",
            "Token",
        ),
        (
            "pub flow main() -> Result<Int, ToolProblem> = {\n    let account = lib.open(lib.UserId(\"ada\"))?\n    Ok(account.balance)\n}\n",
            "balance",
        ),
    ] {
        let (code, said) = checked(program);
        assert_ne!(code, Some(0), "{program} is refused: {said}");
        assert!(said.contains(private), "{private:?} in {said}");
    }
}