use std::fmt;
use crate::path::normal_path;
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum Tree {
Std,
Repository(String),
Local,
}
impl Tree {
pub const STD: &'static str = "std";
pub fn std_version(major: u32) -> String {
format!("v{major}")
}
pub fn repository(&self) -> Option<&str> {
match self {
Tree::Std => Some(Tree::STD),
Tree::Repository(repository) => Some(repository),
Tree::Local => None,
}
}
}
pub const KEYWORDS: &[&str] = &[
"flow", "type", "pub", "opaque", "let", "match", "if", "else", "guard", "return", "use", "as",
"true", "false",
];
pub fn lowercase_name(text: &str) -> bool {
let mut bytes = text.bytes();
bytes.next().is_some_and(|byte| byte.is_ascii_lowercase())
&& bytes.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
&& !KEYWORDS.contains(&text)
}
#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Segments(String);
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct SegmentsError {
pub text: String,
}
impl fmt::Display for SegmentsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "`{}` is not a path: a name in it is empty", self.text)
}
}
impl std::error::Error for SegmentsError {}
impl std::str::FromStr for Segments {
type Err = SegmentsError;
fn from_str(text: &str) -> Result<Segments, SegmentsError> {
if !text.is_empty() && text.split('/').any(str::is_empty) {
return Err(SegmentsError {
text: text.to_owned(),
});
}
Ok(Segments(text.to_owned()))
}
}
impl Segments {
pub const fn root() -> Segments {
Segments(String::new())
}
pub fn from_names<I>(names: I) -> Option<Segments>
where
I: IntoIterator,
I::Item: AsRef<str>,
{
let mut path = Segments::root();
for name in names {
let name = name.as_ref();
if name.is_empty() || name.contains('/') {
return None;
}
path = path.join(&Segments(name.to_owned()));
}
Some(path)
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn is_root(&self) -> bool {
self.0.is_empty()
}
pub fn names(&self) -> impl Iterator<Item = &str> {
self.0.split_terminator('/')
}
#[must_use]
pub fn join(&self, rest: &Segments) -> Segments {
match (self.is_root(), rest.is_root()) {
(true, _) => rest.clone(),
(false, true) => self.clone(),
(false, false) => Segments(format!("{}/{}", self.0, rest.0)),
}
}
pub fn split_at(&self, length: usize) -> (Segments, Segments) {
let Some(before) = length.checked_sub(1) else {
return (Segments::root(), self.clone());
};
match self.0.match_indices('/').nth(before) {
Some((at, _)) => (
Segments(self.0[..at].to_owned()),
Segments(self.0[at + 1..].to_owned()),
),
None => (self.clone(), Segments::root()),
}
}
pub fn strip_prefix(&self, prefix: &Segments) -> Option<Segments> {
if prefix.is_root() {
return Some(self.clone());
}
let rest = self.0.strip_prefix(prefix.as_str())?;
match rest.strip_prefix('/') {
Some(rest) => Some(Segments(rest.to_owned())),
None => rest.is_empty().then(Segments::root),
}
}
}
impl std::borrow::Borrow<str> for Segments {
fn borrow(&self) -> &str {
&self.0
}
}
impl PartialEq<str> for Segments {
fn eq(&self, other: &str) -> bool {
self.0 == other
}
}
impl PartialEq<&str> for Segments {
fn eq(&self, other: &&str) -> bool {
self.0 == *other
}
}
impl fmt::Display for Segments {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum Placement {
Authored,
Contract,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Spelled {
Root,
Contract {
module: Segments,
},
}
#[derive(Debug)]
pub struct LibraryLayout;
impl LibraryLayout {
pub const MARKER: &'static str = "flow.toml";
pub const CONTRACT: &'static str = "contract";
pub const ROOT: &'static str = "lib";
pub const EXTENSION: &'static str = "flow";
pub fn marker(dir: &str) -> String {
if dir.is_empty() {
LibraryLayout::MARKER.to_owned()
} else {
format!("{dir}/{}", LibraryLayout::MARKER)
}
}
pub fn file(stem: &str) -> String {
format!("{stem}.{}", LibraryLayout::EXTENSION)
}
pub fn stem(file: &str) -> Option<&str> {
file.strip_suffix(LibraryLayout::EXTENSION)?
.strip_suffix('.')
}
pub fn placed_stem(module: &Segments) -> Segments {
if module.is_root() {
Segments(LibraryLayout::ROOT.to_owned())
} else {
module.clone()
}
}
pub fn placed_file(module: &Segments) -> String {
LibraryLayout::file(LibraryLayout::placed_stem(module).as_str())
}
pub fn placed_module(stem: &Segments) -> Segments {
if *stem == LibraryLayout::ROOT {
Segments::root()
} else {
stem.clone()
}
}
pub fn module_file(module: &Segments, placement: Placement) -> Segments {
let stem = LibraryLayout::placed_stem(module);
match placement {
Placement::Authored => stem,
Placement::Contract => Segments(LibraryLayout::CONTRACT.to_owned()).join(&stem),
}
}
pub fn module_of(file: &Segments) -> (Segments, Placement) {
match file
.as_str()
.strip_prefix(LibraryLayout::CONTRACT)
.and_then(|rest| rest.strip_prefix('/'))
{
Some(stem) => (
LibraryLayout::placed_module(&Segments(stem.to_owned())),
Placement::Contract,
),
None => (LibraryLayout::placed_module(file), Placement::Authored),
}
}
pub fn spelled(module: &Segments) -> Option<Spelled> {
let module = match module.as_str().split_once('/') {
Some((LibraryLayout::CONTRACT, module)) => module,
Some(_) => return None,
None => match module.as_str() {
LibraryLayout::CONTRACT => "",
LibraryLayout::ROOT => return Some(Spelled::Root),
_ => return None,
},
};
Some(if module == LibraryLayout::ROOT {
Spelled::Root
} else {
Spelled::Contract {
module: Segments(module.to_owned()),
}
})
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct ModulePath {
tree: Tree,
library: Option<Segments>,
segments: Segments,
}
impl ModulePath {
pub fn new(tree: Tree, library: Option<Segments>, segments: Segments) -> ModulePath {
ModulePath {
tree,
library,
segments,
}
}
pub fn submitted() -> ModulePath {
ModulePath::new(Tree::Local, None, Segments("main".to_owned()))
}
pub fn of_file(
tree: Tree,
library: Option<Segments>,
file: &Segments,
) -> (ModulePath, Placement) {
let Some(root) = library else {
return (
ModulePath::new(tree, None, file.clone()),
Placement::Authored,
);
};
let inside = file.strip_prefix(&root).unwrap_or_else(|| file.clone());
let (segments, placement) = LibraryLayout::module_of(&inside);
(ModulePath::new(tree, Some(root), segments), placement)
}
pub fn tree(&self) -> &Tree {
&self.tree
}
pub fn library(&self) -> Option<&Segments> {
self.library.as_ref()
}
pub fn segments(&self) -> &Segments {
&self.segments
}
pub fn file(&self, placement: Placement) -> Segments {
match &self.library {
Some(root) => root.join(&LibraryLayout::module_file(&self.segments, placement)),
None => self.segments.clone(),
}
}
pub fn logical(&self) -> Segments {
match &self.library {
Some(root) => root.join(&self.segments),
None => self.segments.clone(),
}
}
pub fn address(&self) -> String {
match (&self.tree, &self.library) {
(Tree::Repository(repository), Some(root)) if !root.is_root() => {
format!("{repository}/{root}")
}
(Tree::Std | Tree::Repository(_), _) => {
self.tree.repository().unwrap_or_default().to_owned()
}
(Tree::Local, Some(root)) => normal_path(root.as_str()),
(Tree::Local, None) => String::new(),
}
}
pub fn module(&self) -> Segments {
match (&self.tree, &self.library) {
(Tree::Std, Some(root)) => root.join(&self.segments),
(Tree::Std | Tree::Repository(_) | Tree::Local, _) => self.segments.clone(),
}
}
pub fn written(&self, version: Option<&str>) -> String {
let mut written = match (&self.tree, &self.library) {
(Tree::Local, Some(root)) if root.is_root() => String::new(),
_ => self.address(),
};
if let Some(version) = version {
written.push('@');
written.push_str(version);
}
let module = self.module();
if !module.is_root() {
if !written.is_empty() {
written.push('/');
}
written.push_str(module.as_str());
}
written
}
pub fn import(&self, version: &str) -> Option<String> {
let repository = self.tree.repository()?;
let logical = self.logical();
Some(if logical.is_root() {
format!("{repository}@{version}")
} else {
format!("{repository}@{version}/{logical}")
})
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum SourcePath {
Std {
major: u32,
file: Segments,
},
Repository {
repository: String,
version: String,
file: Segments,
},
Local {
file: Segments,
},
Submitted {
name: String,
},
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum SourcePathError {
NotStd {
text: String,
},
NotAPath {
text: String,
},
}
impl fmt::Display for SourcePathError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SourcePathError::NotStd { text } => write!(f, "`{text}` is not a std module"),
SourcePathError::NotAPath { text } => write!(f, "`{text}` is not a module path"),
}
}
}
impl std::error::Error for SourcePathError {}
impl fmt::Display for SourcePath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SourcePath::Std { major, file } => {
write!(f, "{}@{}/{file}", Tree::STD, Tree::std_version(*major))
}
SourcePath::Repository {
repository,
version,
file,
} => write!(f, "{repository}@{version}/{file}"),
SourcePath::Local { file } => write!(f, "./{file}"),
SourcePath::Submitted { name } => write!(f, "<{name}>"),
}
}
}
impl std::str::FromStr for SourcePath {
type Err = SourcePathError;
fn from_str(text: &str) -> Result<SourcePath, SourcePathError> {
if let Some(file) = text.strip_prefix("./") {
let file = file.parse().map_err(|_| SourcePathError::NotAPath {
text: text.to_owned(),
})?;
return Ok(SourcePath::Local { file });
}
if let Some(name) = text
.strip_prefix('<')
.and_then(|rest| rest.strip_suffix('>'))
{
return Ok(SourcePath::Submitted {
name: name.to_owned(),
});
}
let text = text.to_owned();
let Some((tree, rest)) = text.split_once('@') else {
return Err(SourcePathError::NotAPath { text });
};
if tree == Tree::STD {
let std = rest.split_once('/').and_then(|(version, file)| {
let major = version.strip_prefix('v')?.parse().ok()?;
let file = file.parse().ok()?;
(Tree::std_version(major) == version).then_some(SourcePath::Std { major, file })
});
return std.ok_or(SourcePathError::NotStd { text });
}
match rest
.split_once('/')
.and_then(|(version, file)| Some((version, file.parse().ok()?)))
{
Some((version, file)) => Ok(SourcePath::Repository {
repository: tree.to_owned(),
version: version.to_owned(),
file,
}),
None => Err(SourcePathError::NotAPath { text }),
}
}
}
#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
use super::*;
fn path(text: &str) -> Segments {
text.parse().unwrap()
}
#[test]
fn the_keywords_are_the_conformance_fixture_s() {
let fixture = include_str!("../../../toolkits/conformance/keywords.txt");
assert_eq!(KEYWORDS, fixture.lines().collect::<Vec<_>>());
}
#[test]
fn a_lowercase_name_starts_with_a_lowercase_letter_and_is_no_keyword() {
for name in ["a", "b_2", "flows", "x9"] {
assert!(lowercase_name(name), "{name}");
}
for name in ["", "Utils", "2b", "_a", "a-b", "flow", "use", "caf\u{e9}"] {
assert!(!lowercase_name(name), "{name}");
}
}
#[test]
fn a_module_file_and_the_module_it_holds_are_one_mapping() {
for (module, placement, file) in [
("", Placement::Authored, "lib"),
("", Placement::Contract, "contract/lib"),
("models", Placement::Authored, "models"),
("api/v2", Placement::Contract, "contract/api/v2"),
("lib/x", Placement::Authored, "lib/x"),
("lib/x", Placement::Contract, "contract/lib/x"),
] {
let module = path(module);
assert_eq!(LibraryLayout::module_file(&module, placement), path(file));
assert_eq!(LibraryLayout::module_of(&path(file)), (module, placement));
}
}
#[test]
fn a_placed_file_and_the_module_it_holds_are_one_mapping() {
for (module, file) in [
("", "lib.flow"),
("audit/log", "audit/log.flow"),
("lib/log", "lib/log.flow"),
] {
let module = path(module);
assert_eq!(LibraryLayout::placed_file(&module), file);
let stem = LibraryLayout::stem(file).unwrap();
assert_eq!(LibraryLayout::placed_module(&path(stem)), module);
}
}
#[test]
fn a_written_module_path_that_spells_the_layout_names_no_module() {
assert_eq!(LibraryLayout::spelled(&path("lib")), Some(Spelled::Root));
assert_eq!(
LibraryLayout::spelled(&path("contract/lib")),
Some(Spelled::Root)
);
assert_eq!(
LibraryLayout::spelled(&path("contract")),
Some(Spelled::Contract { module: path("") })
);
assert_eq!(
LibraryLayout::spelled(&path("contract/a/b")),
Some(Spelled::Contract {
module: path("a/b")
})
);
for module in ["lib/x", "models", "a/contract", ""] {
assert_eq!(LibraryLayout::spelled(&path(module)), None, "{module}");
}
}
#[test]
fn the_marker_and_the_file_extension_are_the_layout_s() {
assert_eq!(LibraryLayout::marker(""), "flow.toml");
assert_eq!(LibraryLayout::marker("tools/x"), "tools/x/flow.toml");
assert_eq!(LibraryLayout::file("tools/lib"), "tools/lib.flow");
assert_eq!(LibraryLayout::stem("tools/lib.flow"), Some("tools/lib"));
assert_eq!(LibraryLayout::stem("tools/libflow"), None);
assert_eq!(LibraryLayout::stem("flow.toml"), None);
}
#[test]
fn a_module_path_is_read_from_its_file_and_gives_it_back() {
for (library, file, segments, placement) in [
(Some(""), "lib", "", Placement::Authored),
(Some("tools"), "tools/contract/lib", "", Placement::Contract),
(
Some("tools"),
"tools/contract/models",
"models",
Placement::Contract,
),
(Some("tools"), "tools/lib/x", "lib/x", Placement::Authored),
(None, "app/main", "app/main", Placement::Authored),
] {
let (module, read) = ModulePath::of_file(Tree::Local, library.map(path), &path(file));
assert_eq!(module.segments(), &path(segments), "{file}");
assert_eq!(read, placement, "{file}");
assert_eq!(module.file(placement), path(file), "{file}");
}
}
#[test]
fn identities_write_a_module_by_its_library_s_address() {
let std = ModulePath::new(Tree::Std, Some(path("clock")), Segments::root());
assert_eq!(std.address(), "std");
assert_eq!(std.written(Some("v1")), "std@v1/clock");
assert_eq!(std.import("v1").as_deref(), Some("std@v1/clock"));
let list = ModulePath::new(Tree::Std, None, path("list"));
assert_eq!(list.written(Some("v1")), "std@v1/list");
let remote = ModulePath::new(
Tree::Repository("github.com/acme/tools".to_owned()),
Some(path("payments")),
path("x"),
);
assert_eq!(remote.address(), "github.com/acme/tools/payments");
assert_eq!(
remote.written(Some("v1.2")),
"github.com/acme/tools/payments@v1.2/x"
);
assert_eq!(remote.written(None), "github.com/acme/tools/payments/x");
assert_eq!(
remote.import("v1.2").as_deref(),
Some("github.com/acme/tools@v1.2/payments/x")
);
let root = ModulePath::new(Tree::Local, Some(Segments::root()), path("models"));
assert_eq!(root.address(), ".");
assert_eq!(root.written(None), "models");
assert_eq!(root.import("v1"), None);
let tools = ModulePath::new(Tree::Local, Some(path("tools")), Segments::root());
assert_eq!(tools.written(None), "tools");
let loose = ModulePath::new(Tree::Local, None, path("app/main"));
assert_eq!(loose.address(), "");
assert_eq!(loose.written(None), "app/main");
}
#[test]
fn a_source_path_reads_back_as_it_is_written() {
for (text, source) in [
(
"std@v1/clock/contract/lib",
SourcePath::Std {
major: 1,
file: path("clock/contract/lib"),
},
),
(
"github.com/acme/tools@v1.2/payments/contract/lib",
SourcePath::Repository {
repository: "github.com/acme/tools".to_owned(),
version: "v1.2".to_owned(),
file: path("payments/contract/lib"),
},
),
(
"./app@2/main",
SourcePath::Local {
file: path("app@2/main"),
},
),
(
"<inline>",
SourcePath::Submitted {
name: "inline".to_owned(),
},
),
] {
assert_eq!(text.parse::<SourcePath>(), Ok(source.clone()), "{text}");
assert_eq!(source.to_string(), text);
}
for refused in [
"main",
"app/main",
"std@v01/list",
"std@1/list",
"std@v1",
"<open",
] {
assert!(refused.parse::<SourcePath>().is_err(), "{refused}");
}
}
#[test]
fn a_source_path_refuses_a_file_with_an_empty_name() {
for text in ["a//b", "/a", "a/", "/"] {
for source in [
format!("./{text}"),
format!("std@v1/{text}"),
format!("github.com/acme/tools@v1/{text}"),
] {
assert!(source.parse::<SourcePath>().is_err(), "{source}");
}
}
}
#[test]
fn a_path_refuses_an_empty_name() {
for text in ["a//b", "/a", "a/", "/"] {
assert_eq!(
text.parse::<Segments>(),
Err(SegmentsError {
text: text.to_owned()
}),
"{text}"
);
}
assert_eq!("".parse::<Segments>(), Ok(Segments::root()));
assert_eq!(path("a/b").names().collect::<Vec<_>>(), ["a", "b"]);
assert_eq!(Segments::root().names().count(), 0);
}
#[test]
fn a_path_of_names_refuses_an_empty_name_and_a_slash() {
assert_eq!(Segments::from_names(["a", "b"]), Some(path("a/b")));
assert_eq!(
Segments::from_names(Vec::<String>::new()),
Some(Segments::root())
);
assert_eq!(Segments::from_names(["a", ""]), None);
assert_eq!(Segments::from_names(["a/b"]), None);
assert_eq!(path("a/b/c").strip_prefix(&path("a")), Some(path("b/c")));
assert_eq!(path("a").strip_prefix(&path("a")), Some(Segments::root()));
let abc = path("a/b/c");
assert_eq!(abc.split_at(0), (Segments::root(), abc.clone()));
assert_eq!(abc.split_at(1), (path("a"), path("b/c")));
assert_eq!(abc.split_at(3), (abc.clone(), Segments::root()));
assert_eq!(abc.split_at(4), (abc, Segments::root()));
assert_eq!(path("ab/c").strip_prefix(&path("a")), None);
}
}