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
//! The Rust toolkit's one command grammar, which `flow-toolkit-rust` and
//! every launcher it builds read alike (`abi.md`, *Toolkits*):
//!
//! ```text
//! serve --contract FILE
//! extract --library ROOT --out CONTRACT [--depfile FILE]
//! export --library ROOT --out DIR
//! new DIR
//! ```
//!
//! `flow-toolkit-rust` runs each command. A library's launcher runs
//! `serve` and `extract` and refuses the others with
//! [`UsageError::NotLauncher`], so a bundle names an exported launcher as
//! `<launcher> serve`, the way a library names `flow-toolkit-rust serve`.
//! Every path is UTF-8, which the toolkit needs to name it in a Cargo
//! manifest or a depfile.

use std::ffi::OsString;
use std::path::PathBuf;

/// The command lines the grammar takes, after the program.
pub const USAGE: &str = "serve --contract FILE | extract --library ROOT --out CONTRACT [--depfile FILE] | export --library ROOT --out DIR | new DIR";

/// A command of the Rust toolkit.
#[derive(Clone, PartialEq, Eq, Debug)]
#[expect(
    clippy::exhaustive_enums,
    reason = "the grammar is closed, and each reader handles every command"
)]
pub enum Command {
    /// `serve --contract FILE`: serve the Tools the host's `--contract`
    /// file lists, as a `[process]` library's command is started
    /// (`abi.md`, *Binding*).
    Serve {
        /// The `--contract` file.
        contract: PathBuf,
    },
    /// `extract --library ROOT --out CONTRACT [--depfile FILE]`: write the
    /// contract of the library at `library` to `out` in the value encoding,
    /// and list in `depfile` every file read (`abi.md`, *Extracting a
    /// contract*).
    Extract {
        /// The library's root.
        library: PathBuf,
        /// The file the contract is written to.
        out: PathBuf,
        /// The depfile, when one is asked for.
        depfile: Option<PathBuf>,
    },
    /// `export --library ROOT --out DIR`: build the library's launcher
    /// for a release and copy it into `out`.
    Export {
        /// The library's root.
        library: PathBuf,
        /// The directory the launcher is copied into.
        out: PathBuf,
    },
    /// `new DIR`: write a library to start from at `directory`.
    New {
        /// Where the library is written.
        directory: PathBuf,
    },
}

/// A word of a command that carries a path: an option, or `new`'s
/// directory.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[expect(
    clippy::exhaustive_enums,
    reason = "the grammar is closed, and each reader handles every argument"
)]
pub enum Argument {
    /// `--contract FILE`.
    Contract,
    /// `--library ROOT`.
    Library,
    /// `--out`: `extract`'s contract file, `export`'s directory.
    Out,
    /// `--depfile FILE`.
    Depfile,
    /// `new`'s `DIR`.
    Directory,
}

impl Argument {
    /// The word naming the argument: the option, or `DIR`.
    #[must_use]
    pub const fn word(self) -> &'static str {
        match self {
            Argument::Contract => "--contract",
            Argument::Library => "--library",
            Argument::Out => "--out",
            Argument::Depfile => "--depfile",
            Argument::Directory => "DIR",
        }
    }
}

impl std::fmt::Display for Argument {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.word())
    }
}

/// Why a command line is no command this reader runs.
#[derive(Clone, PartialEq, Eq, Debug)]
#[expect(
    clippy::exhaustive_enums,
    reason = "the grammar is closed, and a reader handles each refusal"
)]
pub enum UsageError {
    /// The command line is empty.
    Empty,
    /// The first word names no command.
    Unknown(OsString),
    /// A word the command does not take.
    Unexpected(OsString),
    /// The argument is given with no value after it.
    NoValue(Argument),
    /// The argument is given twice.
    Twice(Argument),
    /// The command needs the argument, and it is not given.
    Missing(Argument),
    /// The argument's value is not UTF-8.
    NotUtf8 {
        /// The argument.
        argument: Argument,
        /// Its value.
        value: OsString,
    },
    /// A library's launcher runs `serve` and `extract` only, and this is
    /// another command.
    NotLauncher(Command),
}

impl std::fmt::Display for UsageError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            UsageError::Empty => formatter.write_str("no command")?,
            UsageError::Unknown(word) => {
                write!(formatter, "{} is no command", word.to_string_lossy())?;
            }
            UsageError::Unexpected(word) => {
                write!(
                    formatter,
                    "the command does not take {}",
                    word.to_string_lossy()
                )?;
            }
            UsageError::NoValue(argument) => write!(formatter, "{argument} needs a path")?,
            UsageError::Twice(argument) => write!(formatter, "{argument} is given twice")?,
            UsageError::Missing(argument) => write!(formatter, "the command needs {argument}")?,
            UsageError::NotUtf8 { argument, value } => write!(
                formatter,
                "{argument} {}: the path is not UTF-8",
                value.to_string_lossy()
            )?,
            UsageError::NotLauncher(command) => {
                return write!(
                    formatter,
                    "a library's launcher runs serve and extract; {} is flow-toolkit-rust's",
                    command.name()
                );
            }
        }
        write!(formatter, "; usage: {USAGE}")
    }
}

impl std::error::Error for UsageError {}

impl Command {
    /// The command's name, its first word.
    #[must_use]
    pub const fn name(&self) -> &'static str {
        match self {
            Command::Serve { .. } => "serve",
            Command::Extract { .. } => "extract",
            Command::Export { .. } => "export",
            Command::New { .. } => "new",
        }
    }

    /// The command `arguments` spell, the program's own name not among
    /// them.
    ///
    /// # Errors
    ///
    /// Why `arguments` spell no command.
    pub fn parse(arguments: &[OsString]) -> Result<Self, UsageError> {
        type Build = fn(&mut Given) -> Result<Command, UsageError>;
        let (name, rest) = arguments.split_first().ok_or(UsageError::Empty)?;
        let (takes, build): (&[Argument], Build) = match name.to_str() {
            Some("serve") => (&[Argument::Contract], |given| {
                Ok(Command::Serve {
                    contract: given.need(Argument::Contract)?,
                })
            }),
            Some("extract") => (
                &[Argument::Library, Argument::Out, Argument::Depfile],
                |given| {
                    Ok(Command::Extract {
                        library: given.need(Argument::Library)?,
                        out: given.need(Argument::Out)?,
                        depfile: given.take(Argument::Depfile),
                    })
                },
            ),
            Some("export") => (&[Argument::Library, Argument::Out], |given| {
                Ok(Command::Export {
                    library: given.need(Argument::Library)?,
                    out: given.need(Argument::Out)?,
                })
            }),
            Some("new") => {
                return match rest {
                    [] => Err(UsageError::Missing(Argument::Directory)),
                    [directory] => Ok(Command::New {
                        directory: path(Argument::Directory, directory)?,
                    }),
                    [_, extra, ..] => Err(UsageError::Unexpected(extra.clone())),
                };
            }
            _ => return Err(UsageError::Unknown(name.clone())),
        };
        let mut given = Given(Vec::new());
        let mut words = rest.iter();
        while let Some(word) = words.next() {
            let argument = takes
                .iter()
                .copied()
                .find(|argument| word.to_str() == Some(argument.word()))
                .ok_or_else(|| UsageError::Unexpected(word.clone()))?;
            let value = words.next().ok_or(UsageError::NoValue(argument))?;
            if given.0.iter().any(|(seen, _)| *seen == argument) {
                return Err(UsageError::Twice(argument));
            }
            given.0.push((argument, path(argument, value)?));
        }
        build(&mut given)
    }
}

/// The options a command line gives, each once.
struct Given(Vec<(Argument, PathBuf)>);

impl Given {
    /// The value of `argument`, if it is given.
    fn take(&mut self, argument: Argument) -> Option<PathBuf> {
        let index = self.0.iter().position(|(seen, _)| *seen == argument)?;
        Some(self.0.swap_remove(index).1)
    }

    /// The value of `argument`, which the command needs.
    fn need(&mut self, argument: Argument) -> Result<PathBuf, UsageError> {
        self.take(argument).ok_or(UsageError::Missing(argument))
    }
}

/// `value`, the value of `argument`, as a path.
fn path(argument: Argument, value: &OsString) -> Result<PathBuf, UsageError> {
    value
        .to_str()
        .map(PathBuf::from)
        .ok_or_else(|| UsageError::NotUtf8 {
            argument,
            value: value.clone(),
        })
}

#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
    use super::*;

    fn parse(words: &[&str]) -> Result<Command, UsageError> {
        Command::parse(&words.iter().map(OsString::from).collect::<Vec<_>>())
    }

    #[test]
    fn each_command_reads_its_own_arguments_in_any_order() {
        assert_eq!(
            parse(&["serve", "--contract", "c"]),
            Ok(Command::Serve {
                contract: "c".into()
            })
        );
        assert_eq!(
            parse(&["extract", "--out", "o", "--library", "l"]),
            Ok(Command::Extract {
                library: "l".into(),
                out: "o".into(),
                depfile: None
            })
        );
        assert_eq!(
            parse(&["extract", "--depfile", "d", "--library", "l", "--out", "o"]),
            Ok(Command::Extract {
                library: "l".into(),
                out: "o".into(),
                depfile: Some("d".into())
            })
        );
        assert_eq!(
            parse(&["export", "--library", "l", "--out", "o"]),
            Ok(Command::Export {
                library: "l".into(),
                out: "o".into()
            })
        );
        assert_eq!(
            parse(&["new", "ledger"]),
            Ok(Command::New {
                directory: "ledger".into()
            })
        );
    }

    #[test]
    fn a_command_line_that_spells_no_command_is_refused_with_why() {
        for (words, refused) in [
            (&[][..], UsageError::Empty),
            (
                &["--contract", "c"],
                UsageError::Unknown("--contract".into()),
            ),
            (
                &["Serve", "--contract", "c"],
                UsageError::Unknown("Serve".into()),
            ),
            (&["serve"], UsageError::Missing(Argument::Contract)),
            (&["serve", "c"], UsageError::Unexpected("c".into())),
            (
                &["serve", "--contract"],
                UsageError::NoValue(Argument::Contract),
            ),
            (
                &["serve", "--contract", "c", "--contract", "d"],
                UsageError::Twice(Argument::Contract),
            ),
            (
                &["serve", "--contract", "c", "--out", "o"],
                UsageError::Unexpected("--out".into()),
            ),
            (
                &["extract", "--library", "l"],
                UsageError::Missing(Argument::Out),
            ),
            (
                &["extract", "/lib", "/out"],
                UsageError::Unexpected("/lib".into()),
            ),
            (
                &["export", "--library", "l", "--out", "o", "--depfile", "d"],
                UsageError::Unexpected("--depfile".into()),
            ),
            (&["new"], UsageError::Missing(Argument::Directory)),
            (&["new", "a", "b"], UsageError::Unexpected("b".into())),
        ] {
            assert_eq!(parse(words), Err(refused), "{words:?}");
        }
    }

    #[cfg(unix)]
    #[test]
    fn a_path_that_is_not_utf8_is_refused_naming_its_argument() {
        use std::os::unix::ffi::OsStrExt as _;
        let not_utf8 = std::ffi::OsStr::from_bytes(b"caf\xe9").to_owned();
        for (words, argument) in [
            (
                vec!["serve".into(), "--contract".into(), not_utf8.clone()],
                Argument::Contract,
            ),
            (vec!["new".into(), not_utf8.clone()], Argument::Directory),
        ] {
            let refused = Command::parse(&words).unwrap_err();
            assert_eq!(
                refused,
                UsageError::NotUtf8 {
                    argument,
                    value: not_utf8.clone()
                }
            );
            assert!(refused.to_string().contains("not UTF-8"), "{refused}");
        }
    }

    #[test]
    fn a_refusal_says_why_and_the_usage() {
        let refused = parse(&["serve"]).unwrap_err().to_string();
        assert_eq!(
            refused,
            format!("the command needs --contract; usage: {USAGE}")
        );
        let refused = UsageError::NotLauncher(Command::New {
            directory: "x".into(),
        })
        .to_string();
        assert!(refused.contains("new is flow-toolkit-rust's"), "{refused}");
    }
}