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 crate's generated contract, as its own tests read it: what
//! [`contract!`](crate::contract) returns.

use std::collections::BTreeMap;
use std::fmt;
use std::path::PathBuf;

use flow_types::{LibraryLayout, Placement, Segments};

/// The contract modules generated from a set of Tools: each library module
/// that declares one of them or a type one of them reaches, mapped to its
/// Flow source, byte for byte what `flow build` writes for the same Tools.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Contract {
    root: PathBuf,
    modules: BTreeMap<Segments, String>,
}

impl Contract {
    pub(crate) fn new(root: PathBuf, modules: BTreeMap<Segments, String>) -> Self {
        Self { root, modules }
    }

    /// Every generated module's Flow source, by module path.
    #[must_use]
    pub fn modules(&self) -> &BTreeMap<Segments, String> {
        &self.modules
    }

    /// The generated Flow source of the module `path`, if any of the Tools
    /// generated it.
    #[must_use]
    pub fn module(&self, path: &str) -> Option<&str> {
        self.modules.get(path).map(String::as_str)
    }

    /// The committed contract file of `module`, read from the library root
    /// of the crate that called [`contract!`](crate::contract).
    ///
    /// # Errors
    ///
    /// Returns the error reading the file, such as `NotFound` when the
    /// module has no committed contract yet.
    pub fn committed(&self, module: &Segments) -> std::io::Result<String> {
        let file = LibraryLayout::module_file(module, Placement::Contract);
        std::fs::read_to_string(self.root.join(LibraryLayout::file(file.as_str())))
    }
}

/// Where a refused declaration is: its file, under the library root when
/// one is known, and its line.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Location {
    file: String,
    line: u32,
}

impl Location {
    pub(crate) fn new(file: String, line: u32) -> Self {
        Self { file, line }
    }

    /// The file holding the declaration.
    #[must_use]
    pub fn file(&self) -> &str {
        &self.file
    }

    /// The line that places the declaration in its file.
    #[must_use]
    pub fn line(&self) -> u32 {
        self.line
    }
}

impl fmt::Display for Location {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}:{}:1", self.file, self.line)
    }
}

/// Why a set of Tools has no contract.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ContractError {
    /// A Tool has the name of a std module its contract imports.
    StdImportCollision {
        /// Where the Tool is defined.
        at: Location,
        /// The name shared by the Tool and the imported module.
        name: String,
    },
    /// Two Tools of one name in one module.
    DuplicateTool {
        /// Where the second one is.
        at: Location,
        /// The Tool's name.
        name: String,
    },
    /// A Rust module whose path is no Flow module path.
    NotAModulePath {
        /// The declaration placed in it.
        at: Location,
        /// The module's path, segments joined by `/`.
        module: String,
        /// Its first segment that is no Flow lowercase name.
        segment: String,
    },
    /// A Rust module whose module path spells a library's layout and so
    /// names no module: `lib` directly under the crate root, whose contract
    /// file would be the root module's, or `contract` there.
    Spelled {
        /// The declaration placed in it.
        at: Location,
        /// The module's path, segments joined by `/`.
        module: String,
    },
    /// A Tool reaches a type that a crate the library does not depend on
    /// defines.
    ForeignType {
        /// Where the type is defined.
        at: Location,
        /// The type's name.
        name: String,
        /// The Rust module defining it, as `module_path!()` spells it.
        module: String,
    },
    /// A Tool reaches a type of a crate the library depends on in a way
    /// that gives it no Flow address: by a registry version, or by a git URL
    /// without a version tag.
    UnaddressedType {
        /// Where the type is defined.
        at: Location,
        /// The type's name.
        name: String,
        /// The crate defining it.
        dependency: String,
        /// How the library depends on the crate.
        how: String,
    },
    /// Distinct Rust types that share one Flow name in one module.
    SharedFlowName {
        /// Where the second one is defined.
        at: Location,
        /// The Flow name they share.
        name: String,
        /// The first type's Rust identity.
        first: String,
        /// The second type's Rust identity.
        second: String,
    },
    /// Tools of two crates in one contract: a contract is one library's.
    SeveralCrates {
        /// The first Tool's crate.
        first: String,
        /// A Tool's crate that differs from it.
        second: String,
    },
}

impl fmt::Display for ContractError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::StdImportCollision { at, name } => write!(
                formatter,
                "{at}: Tool `{name}` conflicts with import `std@v1/{name}`; give the Tool a different public name"
            ),
            Self::DuplicateTool { at, name } => {
                write!(formatter, "{at}: duplicate Tool name {name}")
            }
            Self::NotAModulePath {
                at,
                module,
                segment,
            } => write!(
                formatter,
                "{at}: the module `{segment}` of `{module}` is not a Flow lowercase name, so it has no contract module path"
            ),
            Self::Spelled { at, module } => write!(
                formatter,
                "{at}: `{module}` is no module path: `lib` alone is the root module's file, contract/lib.flow, and a first segment `contract` is the contract's directory; rename the Rust module"
            ),
            Self::ForeignType { at, name, module } => write!(
                formatter,
                "{at}: {name} is defined in {module}, of a crate this library does not depend on"
            ),
            Self::UnaddressedType {
                at,
                name,
                dependency,
                how,
            } => write!(
                formatter,
                "{at}: {name} comes from {how}, so it has no Flow address and no contract can import it; depend on {dependency} by a path in this repository or a git URL at a tag"
            ),
            Self::SharedFlowName {
                at,
                name,
                first,
                second,
            } => write!(
                formatter,
                "{at}: distinct Rust types share the Flow name {name} in one module: {first} and {second}"
            ),
            Self::SeveralCrates { first, second } => write!(
                formatter,
                "a contract is one library's, but its Tools are defined in the crates {first} and {second}"
            ),
        }
    }
}

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

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

    #[test]
    fn a_location_names_its_file_and_line_as_an_editor_reads_them() {
        let at = Location::new("src/lib.rs".into(), 12);
        assert_eq!((at.file(), at.line()), ("src/lib.rs", 12));
        assert_eq!(at.to_string(), "src/lib.rs:12:1");
    }

    #[test]
    fn tools_of_two_crates_are_refused_naming_both() {
        let refused = ContractError::SeveralCrates {
            first: "flow_lib_git".into(),
            second: "flow_lib_http".into(),
        };
        assert_eq!(
            refused.to_string(),
            "a contract is one library's, but its Tools are defined in the crates flow_lib_git and flow_lib_http"
        );
    }
}