Skip to main content

flow_types/
module.rs

1//! Where a module is: the tree that holds it, the library it belongs to and
2//! its module path there ([`ModulePath`], `modules.md`, *Libraries*), and the
3//! one layout a library's files follow ([`LibraryLayout`]).
4
5use std::fmt;
6
7use crate::path::normal_path;
8
9/// The tree a module is in, as a `code.Tree` writes it: std, a repository
10/// by its host path, or the local tree or bundle a program was formed from.
11#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
12pub enum Tree {
13    /// std.
14    Std,
15    /// A repository, by its host path, such as `github.com/acme/tools`.
16    Repository(String),
17    /// The local tree, or a bundle.
18    Local,
19}
20
21impl Tree {
22    /// The address std is named by.
23    pub const STD: &'static str = "std";
24
25    /// The version std at `major` is written with, as in `std@v1`.
26    pub fn std_version(major: u32) -> String {
27        format!("v{major}")
28    }
29
30    /// The repository the tree is, std's included; `None` for the local
31    /// tree.
32    pub fn repository(&self) -> Option<&str> {
33        match self {
34            Tree::Std => Some(Tree::STD),
35            Tree::Repository(repository) => Some(repository),
36            Tree::Local => None,
37        }
38    }
39}
40
41/// Flow's keywords, which no name may spell (`grammar.md`).
42pub const KEYWORDS: &[&str] = &[
43    "flow", "type", "pub", "opaque", "let", "match", "if", "else", "guard", "return", "use", "as",
44    "true", "false",
45];
46
47/// Whether `text` is a Flow lowercase name that is no keyword, as each name
48/// of a module path is.
49pub fn lowercase_name(text: &str) -> bool {
50    let mut bytes = text.bytes();
51    bytes.next().is_some_and(|byte| byte.is_ascii_lowercase())
52        && bytes.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
53        && !KEYWORDS.contains(&text)
54}
55
56/// Names joined by `/`: a module path inside a library, a library's root
57/// inside its tree, or a file's path inside its tree without its `.flow`.
58/// The empty path is a library's root module, or a tree's own root.
59///
60/// No name is empty or holds a `/`: a path is read from its text
61/// ([`FromStr`](std::str::FromStr)) or made from its names
62/// ([`from_names`](Self::from_names)), and both refuse anything else.
63#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
64pub struct Segments(String);
65
66/// Text that is no path: a name in it is empty, as `a//b`, `/a` and
67/// `a/` make one.
68#[derive(Clone, PartialEq, Eq, Debug)]
69pub struct SegmentsError {
70    /// The text.
71    pub text: String,
72}
73
74impl fmt::Display for SegmentsError {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        write!(f, "`{}` is not a path: a name in it is empty", self.text)
77    }
78}
79
80impl std::error::Error for SegmentsError {}
81
82impl std::str::FromStr for Segments {
83    type Err = SegmentsError;
84
85    /// The path `text` spells, names joined by `/`; the empty text is
86    /// the empty path.
87    fn from_str(text: &str) -> Result<Segments, SegmentsError> {
88        if !text.is_empty() && text.split('/').any(str::is_empty) {
89            return Err(SegmentsError {
90                text: text.to_owned(),
91            });
92        }
93        Ok(Segments(text.to_owned()))
94    }
95}
96
97impl Segments {
98    /// The empty path.
99    pub const fn root() -> Segments {
100        Segments(String::new())
101    }
102
103    /// The path of `names`, in order; `None` when a name is empty or holds
104    /// a `/`, which no path's name does.
105    pub fn from_names<I>(names: I) -> Option<Segments>
106    where
107        I: IntoIterator,
108        I::Item: AsRef<str>,
109    {
110        let mut path = Segments::root();
111        for name in names {
112            let name = name.as_ref();
113            if name.is_empty() || name.contains('/') {
114                return None;
115            }
116            path = path.join(&Segments(name.to_owned()));
117        }
118        Some(path)
119    }
120
121    /// The path as text.
122    pub fn as_str(&self) -> &str {
123        &self.0
124    }
125
126    /// Whether this is the empty path.
127    pub fn is_root(&self) -> bool {
128        self.0.is_empty()
129    }
130
131    /// The path's names, in order.
132    pub fn names(&self) -> impl Iterator<Item = &str> {
133        self.0.split_terminator('/')
134    }
135
136    /// `rest` under this path, either of which may be empty.
137    #[must_use]
138    pub fn join(&self, rest: &Segments) -> Segments {
139        match (self.is_root(), rest.is_root()) {
140            (true, _) => rest.clone(),
141            (false, true) => self.clone(),
142            (false, false) => Segments(format!("{}/{}", self.0, rest.0)),
143        }
144    }
145
146    /// Its first `length` names and the rest; all of it and the empty path
147    /// when it has no more than `length` names.
148    pub fn split_at(&self, length: usize) -> (Segments, Segments) {
149        let Some(before) = length.checked_sub(1) else {
150            return (Segments::root(), self.clone());
151        };
152        match self.0.match_indices('/').nth(before) {
153            Some((at, _)) => (
154                Segments(self.0[..at].to_owned()),
155                Segments(self.0[at + 1..].to_owned()),
156            ),
157            None => (self.clone(), Segments::root()),
158        }
159    }
160
161    /// This path with `prefix` and the `/` after it taken off its front;
162    /// `None` when it does not start with `prefix`'s names.
163    pub fn strip_prefix(&self, prefix: &Segments) -> Option<Segments> {
164        if prefix.is_root() {
165            return Some(self.clone());
166        }
167        let rest = self.0.strip_prefix(prefix.as_str())?;
168        match rest.strip_prefix('/') {
169            Some(rest) => Some(Segments(rest.to_owned())),
170            None => rest.is_empty().then(Segments::root),
171        }
172    }
173}
174
175impl std::borrow::Borrow<str> for Segments {
176    fn borrow(&self) -> &str {
177        &self.0
178    }
179}
180
181impl PartialEq<str> for Segments {
182    fn eq(&self, other: &str) -> bool {
183        self.0 == other
184    }
185}
186
187impl PartialEq<&str> for Segments {
188    fn eq(&self, other: &&str) -> bool {
189        self.0 == *other
190    }
191}
192
193impl fmt::Display for Segments {
194    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195        f.write_str(&self.0)
196    }
197}
198
199/// Which of the two files of one module path in a library holds the
200/// module: the authored `<root>/P.flow` or the contract
201/// `<root>/contract/P.flow`.
202#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
203pub enum Placement {
204    /// The authored file.
205    Authored,
206    /// The contract file.
207    Contract,
208}
209
210/// A module path written inside a library that spells the library's layout
211/// rather than a module, and so names none (`modules.md`, *Libraries*).
212#[derive(Clone, PartialEq, Eq, Debug)]
213pub enum Spelled {
214    /// `lib` or `contract/lib`: the root module's file, whose module path
215    /// is empty.
216    Root,
217    /// `contract/P`, the contract module whose module path is `P`; `P` is
218    /// empty for `contract` alone.
219    Contract {
220        /// `P`.
221        module: Segments,
222    },
223}
224
225/// The layout of a library's files (`modules.md`, *Libraries*): a
226/// directory holding [`MARKER`](Self::MARKER) is a library's root, a module
227/// path `P` names `<root>/P.flow` or `<root>/contract/P.flow`, and the
228/// root module, whose module path is empty, is `lib.flow` or
229/// `contract/lib.flow`.
230#[derive(Debug)]
231pub struct LibraryLayout;
232
233impl LibraryLayout {
234    /// The file whose presence makes a directory a library's root.
235    pub const MARKER: &'static str = "flow.toml";
236    /// The directory, under a library's root, that holds its contract
237    /// modules.
238    pub const CONTRACT: &'static str = "contract";
239    /// The stem of the root module's file.
240    pub const ROOT: &'static str = "lib";
241    /// The extension of a module's file.
242    pub const EXTENSION: &'static str = "flow";
243
244    /// The path of `dir`'s marker, `dir` given from a tree's root and
245    /// empty for the root itself.
246    pub fn marker(dir: &str) -> String {
247        if dir.is_empty() {
248            LibraryLayout::MARKER.to_owned()
249        } else {
250            format!("{dir}/{}", LibraryLayout::MARKER)
251        }
252    }
253
254    /// The name of the file whose path without its extension is `stem`.
255    pub fn file(stem: &str) -> String {
256        format!("{stem}.{}", LibraryLayout::EXTENSION)
257    }
258
259    /// The path of the module file `file` without its extension; `None`
260    /// for a file that is no module's.
261    pub fn stem(file: &str) -> Option<&str> {
262        file.strip_suffix(LibraryLayout::EXTENSION)?
263            .strip_suffix('.')
264    }
265
266    /// The path of `module`'s file without its extension, from the
267    /// directory that holds the files of its placement: the library's root
268    /// for an authored module, its contract directory for a contract one.
269    /// The root module's is `lib`.
270    pub fn placed_stem(module: &Segments) -> Segments {
271        if module.is_root() {
272            Segments(LibraryLayout::ROOT.to_owned())
273        } else {
274            module.clone()
275        }
276    }
277
278    /// The file of `module`, with its extension, from the directory that
279    /// holds the files of its placement: `lib.flow` for the root module.
280    pub fn placed_file(module: &Segments) -> String {
281        LibraryLayout::file(LibraryLayout::placed_stem(module).as_str())
282    }
283
284    /// The module whose file, from the directory that holds the files of
285    /// its placement and without its extension, is `stem`: the inverse of
286    /// [`placed_stem`](Self::placed_stem).
287    pub fn placed_module(stem: &Segments) -> Segments {
288        if *stem == LibraryLayout::ROOT {
289            Segments::root()
290        } else {
291            stem.clone()
292        }
293    }
294
295    /// The file, inside its library and without its extension, that holds
296    /// the module `module` in `placement`.
297    pub fn module_file(module: &Segments, placement: Placement) -> Segments {
298        let stem = LibraryLayout::placed_stem(module);
299        match placement {
300            Placement::Authored => stem,
301            Placement::Contract => Segments(LibraryLayout::CONTRACT.to_owned()).join(&stem),
302        }
303    }
304
305    /// The module a file inside its library, without its extension, holds,
306    /// and where: the inverse of [`module_file`](Self::module_file).
307    pub fn module_of(file: &Segments) -> (Segments, Placement) {
308        match file
309            .as_str()
310            .strip_prefix(LibraryLayout::CONTRACT)
311            .and_then(|rest| rest.strip_prefix('/'))
312        {
313            Some(stem) => (
314                LibraryLayout::placed_module(&Segments(stem.to_owned())),
315                Placement::Contract,
316            ),
317            None => (LibraryLayout::placed_module(file), Placement::Authored),
318        }
319    }
320
321    /// How `module`, a module path as written inside a library, spells
322    /// the layout, if it does.
323    pub fn spelled(module: &Segments) -> Option<Spelled> {
324        let module = match module.as_str().split_once('/') {
325            Some((LibraryLayout::CONTRACT, module)) => module,
326            Some(_) => return None,
327            None => match module.as_str() {
328                LibraryLayout::CONTRACT => "",
329                LibraryLayout::ROOT => return Some(Spelled::Root),
330                _ => return None,
331            },
332        };
333        Some(if module == LibraryLayout::ROOT {
334            Spelled::Root
335        } else {
336            Spelled::Contract {
337                module: Segments(module.to_owned()),
338            }
339        })
340    }
341}
342
343/// Where a module is, as a `code.ModulePath` writes it (`code.md`,
344/// *Programs and modules*): its tree, the root of the library it belongs to
345/// in that tree, and its module path in that library. A module outside
346/// every library has no library, and its path is its file's from the
347/// tree's root, without `.flow`.
348///
349/// A module path names no version: one program reaches one version of each
350/// tree, so where a version is written it is held beside the path.
351#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
352pub struct ModulePath {
353    tree: Tree,
354    library: Option<Segments>,
355    segments: Segments,
356}
357
358impl ModulePath {
359    /// The module at `segments` in the library at `library` of `tree`, or
360    /// outside every library when `library` is `None`.
361    pub fn new(tree: Tree, library: Option<Segments>, segments: Segments) -> ModulePath {
362        ModulePath {
363            tree,
364            library,
365            segments,
366        }
367    }
368
369    /// The module a lone submitted file is: `main` of a one-file bundle
370    /// (`abi.md`, *Identity and signatures*).
371    pub fn submitted() -> ModulePath {
372        ModulePath::new(Tree::Local, None, Segments("main".to_owned()))
373    }
374
375    /// The module the file `file` of `tree`, given from the tree's root
376    /// without its extension, holds in the library at `library`, and
377    /// which of its module path's files it is.
378    pub fn of_file(
379        tree: Tree,
380        library: Option<Segments>,
381        file: &Segments,
382    ) -> (ModulePath, Placement) {
383        let Some(root) = library else {
384            return (
385                ModulePath::new(tree, None, file.clone()),
386                Placement::Authored,
387            );
388        };
389        let inside = file.strip_prefix(&root).unwrap_or_else(|| file.clone());
390        let (segments, placement) = LibraryLayout::module_of(&inside);
391        (ModulePath::new(tree, Some(root), segments), placement)
392    }
393
394    /// Its tree.
395    pub fn tree(&self) -> &Tree {
396        &self.tree
397    }
398
399    /// The root of its library in its tree, the empty path for the tree's
400    /// own root; `None` outside every library.
401    pub fn library(&self) -> Option<&Segments> {
402        self.library.as_ref()
403    }
404
405    /// Its module path in its library, or outside every library its file's
406    /// path from its tree's root.
407    pub fn segments(&self) -> &Segments {
408        &self.segments
409    }
410
411    /// The file of its tree, without its extension, that holds it in
412    /// `placement`.
413    pub fn file(&self, placement: Placement) -> Segments {
414        match &self.library {
415            Some(root) => root.join(&LibraryLayout::module_file(&self.segments, placement)),
416            None => self.segments.clone(),
417        }
418    }
419
420    /// The path inside its tree its imports write it by: its library's
421    /// root followed by its module path.
422    pub fn logical(&self) -> Segments {
423        match &self.library {
424            Some(root) => root.join(&self.segments),
425            None => self.segments.clone(),
426        }
427    }
428
429    /// Its library's address, or for a module outside every library its
430    /// tree's (`abi.md`, *Identity and signatures*): `std` for every
431    /// library std holds, a repository, `github.com/acme/tools/payments`,
432    /// `tools`, `.` for a library at the local tree's root, or empty for a
433    /// module of the local tree outside every library.
434    pub fn address(&self) -> String {
435        match (&self.tree, &self.library) {
436            (Tree::Repository(repository), Some(root)) if !root.is_root() => {
437                format!("{repository}/{root}")
438            }
439            (Tree::Std | Tree::Repository(_), _) => {
440                self.tree.repository().unwrap_or_default().to_owned()
441            }
442            (Tree::Local, Some(root)) => normal_path(root.as_str()),
443            (Tree::Local, None) => String::new(),
444        }
445    }
446
447    /// Its module path inside [`address`](Self::address). std is one
448    /// library named `std`, so a module of a library inside it is that
449    /// library's root followed by its module path there, as `clock` for
450    /// `clock/contract/lib`.
451    pub fn module(&self) -> Segments {
452        match (&self.tree, &self.library) {
453            (Tree::Std, Some(root)) => root.join(&self.segments),
454            (Tree::Std | Tree::Repository(_) | Tree::Local, _) => self.segments.clone(),
455        }
456    }
457
458    /// The module as identities write it: its address, `@version` when
459    /// `version` is given, then its module path, each part that is empty
460    /// left out with its separator. A library at the local tree's root is
461    /// written as the tree's own modules are, by the path from that root.
462    pub fn written(&self, version: Option<&str>) -> String {
463        let mut written = match (&self.tree, &self.library) {
464            (Tree::Local, Some(root)) if root.is_root() => String::new(),
465            _ => self.address(),
466        };
467        if let Some(version) = version {
468            written.push('@');
469            written.push_str(version);
470        }
471        let module = self.module();
472        if !module.is_root() {
473            if !written.is_empty() {
474                written.push('/');
475            }
476            written.push_str(module.as_str());
477        }
478        written
479    }
480
481    /// The path an import from a module of another tree names it by, at
482    /// `version`: `std@v1/clock` or `github.com/acme/tools@v1.2/payments`;
483    /// `None` for a module of the local tree, which is named relative to
484    /// the importing module.
485    pub fn import(&self, version: &str) -> Option<String> {
486        let repository = self.tree.repository()?;
487        let logical = self.logical();
488        Some(if logical.is_root() {
489            format!("{repository}@{version}")
490        } else {
491            format!("{repository}@{version}/{logical}")
492        })
493    }
494}
495
496/// A module's file as history records its source (`history.md`,
497/// *Programs*): `std@v1/<file>`, `<repository>@<version>/<file>`,
498/// `./<file>` for the local tree, each file without its extension, or
499/// `<name>` for a lone submitted file. Its text is its
500/// [`Display`](fmt::Display), which [`FromStr`](std::str::FromStr) reads
501/// back.
502#[derive(Clone, PartialEq, Eq, Debug)]
503pub enum SourcePath {
504    /// A file of std at a major version.
505    Std {
506        /// The major version.
507        major: u32,
508        /// The file, from std's root.
509        file: Segments,
510    },
511    /// A file of a repository at a version, a tag or a commit.
512    Repository {
513        /// The repository's host path.
514        repository: String,
515        /// The version.
516        version: String,
517        /// The file, from the repository's root.
518        file: Segments,
519    },
520    /// A file of the local tree.
521    Local {
522        /// The file, from the tree's root.
523        file: Segments,
524    },
525    /// A lone submitted file.
526    Submitted {
527        /// What the submission is called.
528        name: String,
529    },
530}
531
532/// Why text is no [`SourcePath`].
533#[derive(Clone, PartialEq, Eq, Debug)]
534pub enum SourcePathError {
535    /// The text names std without a major version written `v<major>` or
536    /// without a file.
537    NotStd {
538        /// The text.
539        text: String,
540    },
541    /// The text is none of the forms.
542    NotAPath {
543        /// The text.
544        text: String,
545    },
546}
547
548impl fmt::Display for SourcePathError {
549    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
550        match self {
551            SourcePathError::NotStd { text } => write!(f, "`{text}` is not a std module"),
552            SourcePathError::NotAPath { text } => write!(f, "`{text}` is not a module path"),
553        }
554    }
555}
556
557impl std::error::Error for SourcePathError {}
558
559impl fmt::Display for SourcePath {
560    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
561        match self {
562            SourcePath::Std { major, file } => {
563                write!(f, "{}@{}/{file}", Tree::STD, Tree::std_version(*major))
564            }
565            SourcePath::Repository {
566                repository,
567                version,
568                file,
569            } => write!(f, "{repository}@{version}/{file}"),
570            SourcePath::Local { file } => write!(f, "./{file}"),
571            SourcePath::Submitted { name } => write!(f, "<{name}>"),
572        }
573    }
574}
575
576impl std::str::FromStr for SourcePath {
577    type Err = SourcePathError;
578
579    fn from_str(text: &str) -> Result<SourcePath, SourcePathError> {
580        if let Some(file) = text.strip_prefix("./") {
581            let file = file.parse().map_err(|_| SourcePathError::NotAPath {
582                text: text.to_owned(),
583            })?;
584            return Ok(SourcePath::Local { file });
585        }
586        if let Some(name) = text
587            .strip_prefix('<')
588            .and_then(|rest| rest.strip_suffix('>'))
589        {
590            return Ok(SourcePath::Submitted {
591                name: name.to_owned(),
592            });
593        }
594        let text = text.to_owned();
595        let Some((tree, rest)) = text.split_once('@') else {
596            return Err(SourcePathError::NotAPath { text });
597        };
598        if tree == Tree::STD {
599            let std = rest.split_once('/').and_then(|(version, file)| {
600                let major = version.strip_prefix('v')?.parse().ok()?;
601                let file = file.parse().ok()?;
602                (Tree::std_version(major) == version).then_some(SourcePath::Std { major, file })
603            });
604            return std.ok_or(SourcePathError::NotStd { text });
605        }
606        match rest
607            .split_once('/')
608            .and_then(|(version, file)| Some((version, file.parse().ok()?)))
609        {
610            Some((version, file)) => Ok(SourcePath::Repository {
611                repository: tree.to_owned(),
612                version: version.to_owned(),
613                file,
614            }),
615            None => Err(SourcePathError::NotAPath { text }),
616        }
617    }
618}
619
620#[cfg(test)]
621#[cfg_attr(coverage, coverage(off))]
622mod tests {
623    use super::*;
624
625    fn path(text: &str) -> Segments {
626        text.parse().unwrap()
627    }
628
629    #[test]
630    fn the_keywords_are_the_conformance_fixture_s() {
631        let fixture = include_str!("../../../toolkits/conformance/keywords.txt");
632        assert_eq!(KEYWORDS, fixture.lines().collect::<Vec<_>>());
633    }
634
635    #[test]
636    fn a_lowercase_name_starts_with_a_lowercase_letter_and_is_no_keyword() {
637        for name in ["a", "b_2", "flows", "x9"] {
638            assert!(lowercase_name(name), "{name}");
639        }
640        for name in ["", "Utils", "2b", "_a", "a-b", "flow", "use", "caf\u{e9}"] {
641            assert!(!lowercase_name(name), "{name}");
642        }
643    }
644
645    #[test]
646    fn a_module_file_and_the_module_it_holds_are_one_mapping() {
647        for (module, placement, file) in [
648            ("", Placement::Authored, "lib"),
649            ("", Placement::Contract, "contract/lib"),
650            ("models", Placement::Authored, "models"),
651            ("api/v2", Placement::Contract, "contract/api/v2"),
652            ("lib/x", Placement::Authored, "lib/x"),
653            ("lib/x", Placement::Contract, "contract/lib/x"),
654        ] {
655            let module = path(module);
656            assert_eq!(LibraryLayout::module_file(&module, placement), path(file));
657            assert_eq!(LibraryLayout::module_of(&path(file)), (module, placement));
658        }
659    }
660
661    #[test]
662    fn a_placed_file_and_the_module_it_holds_are_one_mapping() {
663        for (module, file) in [
664            ("", "lib.flow"),
665            ("audit/log", "audit/log.flow"),
666            ("lib/log", "lib/log.flow"),
667        ] {
668            let module = path(module);
669            assert_eq!(LibraryLayout::placed_file(&module), file);
670            let stem = LibraryLayout::stem(file).unwrap();
671            assert_eq!(LibraryLayout::placed_module(&path(stem)), module);
672        }
673    }
674
675    #[test]
676    fn a_written_module_path_that_spells_the_layout_names_no_module() {
677        assert_eq!(LibraryLayout::spelled(&path("lib")), Some(Spelled::Root));
678        assert_eq!(
679            LibraryLayout::spelled(&path("contract/lib")),
680            Some(Spelled::Root)
681        );
682        assert_eq!(
683            LibraryLayout::spelled(&path("contract")),
684            Some(Spelled::Contract { module: path("") })
685        );
686        assert_eq!(
687            LibraryLayout::spelled(&path("contract/a/b")),
688            Some(Spelled::Contract {
689                module: path("a/b")
690            })
691        );
692        for module in ["lib/x", "models", "a/contract", ""] {
693            assert_eq!(LibraryLayout::spelled(&path(module)), None, "{module}");
694        }
695    }
696
697    #[test]
698    fn the_marker_and_the_file_extension_are_the_layout_s() {
699        assert_eq!(LibraryLayout::marker(""), "flow.toml");
700        assert_eq!(LibraryLayout::marker("tools/x"), "tools/x/flow.toml");
701        assert_eq!(LibraryLayout::file("tools/lib"), "tools/lib.flow");
702        assert_eq!(LibraryLayout::stem("tools/lib.flow"), Some("tools/lib"));
703        assert_eq!(LibraryLayout::stem("tools/libflow"), None);
704        assert_eq!(LibraryLayout::stem("flow.toml"), None);
705    }
706
707    #[test]
708    fn a_module_path_is_read_from_its_file_and_gives_it_back() {
709        for (library, file, segments, placement) in [
710            (Some(""), "lib", "", Placement::Authored),
711            (Some("tools"), "tools/contract/lib", "", Placement::Contract),
712            (
713                Some("tools"),
714                "tools/contract/models",
715                "models",
716                Placement::Contract,
717            ),
718            (Some("tools"), "tools/lib/x", "lib/x", Placement::Authored),
719            (None, "app/main", "app/main", Placement::Authored),
720        ] {
721            let (module, read) = ModulePath::of_file(Tree::Local, library.map(path), &path(file));
722            assert_eq!(module.segments(), &path(segments), "{file}");
723            assert_eq!(read, placement, "{file}");
724            assert_eq!(module.file(placement), path(file), "{file}");
725        }
726    }
727
728    #[test]
729    fn identities_write_a_module_by_its_library_s_address() {
730        let std = ModulePath::new(Tree::Std, Some(path("clock")), Segments::root());
731        assert_eq!(std.address(), "std");
732        assert_eq!(std.written(Some("v1")), "std@v1/clock");
733        assert_eq!(std.import("v1").as_deref(), Some("std@v1/clock"));
734        let list = ModulePath::new(Tree::Std, None, path("list"));
735        assert_eq!(list.written(Some("v1")), "std@v1/list");
736        let remote = ModulePath::new(
737            Tree::Repository("github.com/acme/tools".to_owned()),
738            Some(path("payments")),
739            path("x"),
740        );
741        assert_eq!(remote.address(), "github.com/acme/tools/payments");
742        assert_eq!(
743            remote.written(Some("v1.2")),
744            "github.com/acme/tools/payments@v1.2/x"
745        );
746        assert_eq!(remote.written(None), "github.com/acme/tools/payments/x");
747        assert_eq!(
748            remote.import("v1.2").as_deref(),
749            Some("github.com/acme/tools@v1.2/payments/x")
750        );
751        let root = ModulePath::new(Tree::Local, Some(Segments::root()), path("models"));
752        assert_eq!(root.address(), ".");
753        assert_eq!(root.written(None), "models");
754        assert_eq!(root.import("v1"), None);
755        let tools = ModulePath::new(Tree::Local, Some(path("tools")), Segments::root());
756        assert_eq!(tools.written(None), "tools");
757        let loose = ModulePath::new(Tree::Local, None, path("app/main"));
758        assert_eq!(loose.address(), "");
759        assert_eq!(loose.written(None), "app/main");
760    }
761
762    #[test]
763    fn a_source_path_reads_back_as_it_is_written() {
764        for (text, source) in [
765            (
766                "std@v1/clock/contract/lib",
767                SourcePath::Std {
768                    major: 1,
769                    file: path("clock/contract/lib"),
770                },
771            ),
772            (
773                "github.com/acme/tools@v1.2/payments/contract/lib",
774                SourcePath::Repository {
775                    repository: "github.com/acme/tools".to_owned(),
776                    version: "v1.2".to_owned(),
777                    file: path("payments/contract/lib"),
778                },
779            ),
780            (
781                "./app@2/main",
782                SourcePath::Local {
783                    file: path("app@2/main"),
784                },
785            ),
786            (
787                "<inline>",
788                SourcePath::Submitted {
789                    name: "inline".to_owned(),
790                },
791            ),
792        ] {
793            assert_eq!(text.parse::<SourcePath>(), Ok(source.clone()), "{text}");
794            assert_eq!(source.to_string(), text);
795        }
796        for refused in [
797            "main",
798            "app/main",
799            "std@v01/list",
800            "std@1/list",
801            "std@v1",
802            "<open",
803        ] {
804            assert!(refused.parse::<SourcePath>().is_err(), "{refused}");
805        }
806    }
807
808    #[test]
809    fn a_source_path_refuses_a_file_with_an_empty_name() {
810        for text in ["a//b", "/a", "a/", "/"] {
811            for source in [
812                format!("./{text}"),
813                format!("std@v1/{text}"),
814                format!("github.com/acme/tools@v1/{text}"),
815            ] {
816                assert!(source.parse::<SourcePath>().is_err(), "{source}");
817            }
818        }
819    }
820
821    #[test]
822    fn a_path_refuses_an_empty_name() {
823        for text in ["a//b", "/a", "a/", "/"] {
824            assert_eq!(
825                text.parse::<Segments>(),
826                Err(SegmentsError {
827                    text: text.to_owned()
828                }),
829                "{text}"
830            );
831        }
832        assert_eq!("".parse::<Segments>(), Ok(Segments::root()));
833        assert_eq!(path("a/b").names().collect::<Vec<_>>(), ["a", "b"]);
834        assert_eq!(Segments::root().names().count(), 0);
835    }
836
837    #[test]
838    fn a_path_of_names_refuses_an_empty_name_and_a_slash() {
839        assert_eq!(Segments::from_names(["a", "b"]), Some(path("a/b")));
840        assert_eq!(
841            Segments::from_names(Vec::<String>::new()),
842            Some(Segments::root())
843        );
844        assert_eq!(Segments::from_names(["a", ""]), None);
845        assert_eq!(Segments::from_names(["a/b"]), None);
846        assert_eq!(path("a/b/c").strip_prefix(&path("a")), Some(path("b/c")));
847        assert_eq!(path("a").strip_prefix(&path("a")), Some(Segments::root()));
848        let abc = path("a/b/c");
849        assert_eq!(abc.split_at(0), (Segments::root(), abc.clone()));
850        assert_eq!(abc.split_at(1), (path("a"), path("b/c")));
851        assert_eq!(abc.split_at(3), (abc.clone(), Segments::root()));
852        assert_eq!(abc.split_at(4), (abc, Segments::root()));
853        assert_eq!(path("ab/c").strip_prefix(&path("a")), None);
854    }
855}