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 Tool parameter's default, `#[flow(default = v)]`, as the constant its
//! contract gives after `=` (`abi.md`, *Extracting a contract*, Defaults).
//!
//! Rust has no default values, so `#[tool]` reads `v` from the attribute:
//! an integer, boolean or string literal, `None`, or `Some` of a literal. Each
//! kind is built through a trait implemented only for the Rust types whose
//! Flow type that kind of literal is a value of, so a default of the wrong
//! type is a compile error at the attribute, never a contract the checker
//! later refuses. On an `Option<T>` parameter a literal other than `None` is
//! `Some` of it, as a Python default on a `T | None` parameter is.

use flow_abi::contract::{Constant, TypeRef};

use crate::Int;
use crate::function::Owner;

/// A type an integer literal is a default of: `Int`, or an option of one.
pub trait DefaultInt {
    /// The integer whose decimal digits, with any sign, are `digits`.
    fn int(digits: &str) -> Constant<Owner>;
}

/// A type a boolean literal is a default of: `Bool`, or an option of one.
#[expect(
    clippy::fn_params_excessive_bools,
    reason = "the parameter is the boolean literal the default spells"
)]
pub trait DefaultBool {
    /// `flag`.
    fn bool(flag: bool) -> Constant<Owner>;
}

/// A type a string literal is a default of: `Text`, or an option of one.
pub trait DefaultText {
    /// `text`.
    fn text(text: &str) -> Constant<Owner>;
}

/// An option, which `None` and `Some` of a literal are defaults of.
pub trait DefaultOption {
    /// The type `Some` holds.
    type Inner;
    /// `None`.
    fn none() -> Constant<Owner> {
        Constant::None
    }
    /// `Some(inner)`.
    fn some(inner: Constant<Owner>) -> Constant<Owner> {
        Constant::Some(Box::new(inner))
    }
}

/// A newtype's default: its constructor applied to a default of its base,
/// written as the contract names the newtype (`abi.md`, *Extracting a
/// contract*, *Defaults*). Derived for every newtype.
pub trait DefaultNewtype: Sized {
    /// Whether the newtype's constructor is `pub`: its Rust field is.
    const PUBLIC: bool;
    /// The Rust module that defines the newtype, whose contract module
    /// declares it.
    const MODULE: &'static str;
    /// The newtype's base, whose default the constructor is applied to.
    type Base;
    /// The newtype, as a contract names it.
    fn written() -> TypeRef<Owner>;
    /// The default `constructor(inner)`. The constructor is only type
    /// checked: it is the newtype's own exactly when it builds `Self` from
    /// its base.
    fn wrap(
        inner: Constant<Owner>,
        _constructor: impl FnOnce(Self::Base) -> Self,
    ) -> Constant<Owner> {
        Constant::Applied {
            newtype: Self::written(),
            value: Box::new(inner),
        }
    }
}

/// Whether a contract module written from the Rust module `at` can apply
/// the newtype `N`'s constructor: a `pub` one anywhere, a private one only
/// in its own module (`abi.md`, *Extracting a contract*, *Defaults*).
#[must_use]
pub const fn constructor_reachable<N: DefaultNewtype>(at: &str) -> bool {
    if N::PUBLIC {
        return true;
    }
    let (owner, at) = (N::MODULE.as_bytes(), at.as_bytes());
    if owner.len() != at.len() {
        return false;
    }
    let mut index = 0;
    while index < owner.len() {
        if owner[index] != at[index] {
            return false;
        }
        index += 1;
    }
    true
}

impl DefaultInt for Int {
    fn int(digits: &str) -> Constant<Owner> {
        Constant::Int(
            Int::parse(digits).expect("`#[tool]` passes an integer literal's decimal digits"),
        )
    }
}

impl DefaultBool for bool {
    fn bool(flag: bool) -> Constant<Owner> {
        Constant::Bool(flag)
    }
}

impl DefaultText for String {
    fn text(text: &str) -> Constant<Owner> {
        Constant::Text(text.to_owned())
    }
}

impl<T> DefaultOption for Option<T> {
    type Inner = T;
}

impl<T: DefaultInt> DefaultInt for Option<T> {
    fn int(digits: &str) -> Constant<Owner> {
        Self::some(T::int(digits))
    }
}

impl<T: DefaultBool> DefaultBool for Option<T> {
    fn bool(flag: bool) -> Constant<Owner> {
        Self::some(T::bool(flag))
    }
}

impl<T: DefaultText> DefaultText for Option<T> {
    fn text(text: &str) -> Constant<Owner> {
        Self::some(T::text(text))
    }
}

#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
    use super::{
        DefaultBool, DefaultInt, DefaultNewtype, DefaultOption, DefaultText, constructor_reachable,
    };
    use crate::Int;
    use crate::function::Owner;
    use flow_abi::contract::{self, Constant, TypeRef};

    /// The text a contract writes for `constant`, a type of another module
    /// through its module's name.
    fn written(constant: &Constant<Owner>) -> String {
        contract::constant(&constant.qualify(&mut |owner| match owner {
            Owner::Rust(module) | Owner::Std(module) => Some((*module).to_owned()),
        }))
    }

    struct Open;
    impl DefaultNewtype for Open {
        const PUBLIC: bool = true;
        const MODULE: &'static str = "ids";
        type Base = String;
        fn written() -> TypeRef<Owner> {
            TypeRef::named("Open")
        }
    }
    struct Sealed;
    impl DefaultNewtype for Sealed {
        const PUBLIC: bool = false;
        const MODULE: &'static str = "lib::ids";
        type Base = String;
        fn written() -> TypeRef<Owner> {
            TypeRef::qualified(Owner::Rust("ids"), "Sealed")
        }
    }
    #[test]
    fn a_private_constructor_is_written_only_in_its_own_module() {
        assert!(constructor_reachable::<Open>("lib::other"));
        assert!(constructor_reachable::<Sealed>("lib::ids"));
        assert!(!constructor_reachable::<Sealed>("lib::idx"));
        assert!(!constructor_reachable::<Sealed>("lib"));
        assert!(!constructor_reachable::<Sealed>("lib::ids::inner"));
        assert_eq!(
            written(&<Sealed as DefaultNewtype>::wrap(
                Constant::Text("t".to_owned()),
                |_| Sealed
            )),
            "ids.Sealed(\"t\")"
        );
        assert_eq!(
            written(&<Open as DefaultNewtype>::wrap(
                Constant::Int(Int::from(1)),
                |_| Open
            )),
            "Open(1)"
        );
    }
    #[test]
    fn a_literal_default_is_written_as_the_flow_literal_of_its_type() {
        assert_eq!(written(&<Int as DefaultInt>::int("20")), "20");
        assert_eq!(written(&<Int as DefaultInt>::int("-3")), "-3");
        assert_eq!(written(&<bool as DefaultBool>::bool(false)), "false");
        assert_eq!(written(&<String as DefaultText>::text("hi")), r#""hi""#);
    }
    #[test]
    fn on_an_option_a_literal_is_some_of_it_and_none_is_none() {
        assert_eq!(written(&<Option<Int> as DefaultInt>::int("5")), "Some(5)");
        assert_eq!(
            written(&<Option<bool> as DefaultBool>::bool(true)),
            "Some(true)"
        );
        assert_eq!(
            written(&<Option<String> as DefaultText>::text("x")),
            r#"Some("x")"#
        );
        assert_eq!(written(&<Option<Int> as DefaultOption>::none()), "None");
        assert_eq!(
            written(&<Option<Option<Int>> as DefaultInt>::int("1")),
            "Some(Some(1))",
            "each option level wraps the literal once"
        );
        assert_eq!(
            written(&<Option<Int> as DefaultOption>::some(
                <Int as DefaultInt>::int("7")
            )),
            "Some(7)"
        );
    }
}