flow-types 0.1.0-rc.5

The Flow declaration model with no values: types, declarations and their identities, record and enum shapes, and which types decoding may build.
Documentation
//! A `code.Bundle`'s files (`code.md`, *Checked bundles*): the file each
//! of its modules is at in the tree the bundle holds, which forming the
//! bundle reads and every diagnostic about it names.

use crate::{LibraryLayout, ModulePath, Placement, Segments, Tree};

/// Why a `code.Bundle` is no bundle of files.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum BundleError {
    /// The JSON is not a `code.Bundle`'s form: what was wrong.
    Shape(String),
    /// A module is not in the local tree, which is all a bundle holds.
    NotLocal(String),
    /// A segment of a module path would leave its directory.
    Segment(String),
    /// Two modules of the bundle are one file.
    Twice(String),
    /// The entry's module is not one of the bundle's files.
    NoEntryModule(String),
}

impl std::fmt::Display for BundleError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BundleError::Shape(what) => write!(f, "the bundle is malformed: {what}"),
            BundleError::NotLocal(path) => {
                write!(f, "the module {path} is not in the bundle's own tree")
            }
            BundleError::Segment(segment) => {
                write!(f, "`{segment}` is not a segment of a module path")
            }
            BundleError::Twice(file) => write!(f, "two modules of the bundle are the file {file}"),
            BundleError::NoEntryModule(path) => {
                write!(f, "the entry's module {path} is not in the bundle")
            }
        }
    }
}

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

/// The file, from a bundle's root, of the module of its local tree whose
/// library is `library`, `"."` for the root, and whose path inside it is
/// `segments`, and the directory of its library, `""` for the root, when it
/// is in one. A module outside every library is `<segments>.flow` from the
/// root; a library's module is its contract module
/// `<library>/contract/<segments>.flow`, `contract/lib.flow` for its root
/// module.
///
/// # Errors
///
/// [`BundleError`] when a segment would leave its directory, or a module
/// outside every library has no segments.
pub fn bundled_file(
    library: Option<&str>,
    segments: &[String],
) -> Result<(String, Option<String>), BundleError> {
    let inside =
        Segments::from_names(segments).ok_or_else(|| BundleError::Segment(segments.join("/")))?;
    if let Some(segment) = inside.names().find(|segment| unsafe_name(segment)) {
        return Err(BundleError::Segment(segment.to_owned()));
    }
    let library = match library {
        None if inside.is_root() => {
            return Err(BundleError::Shape(
                "a module outside every library has no segments".to_owned(),
            ));
        }
        None => None,
        Some(".") => Some(Segments::root()),
        Some(other) => {
            let root: Segments = other
                .parse()
                .map_err(|_| BundleError::Segment(other.to_owned()))?;
            if root.names().any(unsafe_name) {
                return Err(BundleError::Segment(other.to_owned()));
            }
            Some(root)
        }
    };
    let module = ModulePath::new(Tree::Local, library, inside);
    let file = LibraryLayout::file(module.file(Placement::Contract).as_str());
    Ok((file, module.library().map(ToString::to_string)))
}

/// Whether `name`, a name of a path, steps out of its directory or holds a
/// separator some host reads.
fn unsafe_name(name: &str) -> bool {
    matches!(name, "." | "..") || name.contains('\\')
}