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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
//! Where a module is: the tree that holds it, the library it belongs to and
//! its module path there ([`ModulePath`], `modules.md`, *Libraries*), and the
//! one layout a library's files follow ([`LibraryLayout`]).

use std::fmt;

use crate::path::normal_path;

/// The tree a module is in, as a `code.Tree` writes it: std, a repository
/// by its host path, or the local tree or bundle a program was formed from.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum Tree {
    /// std.
    Std,
    /// A repository, by its host path, such as `github.com/acme/tools`.
    Repository(String),
    /// The local tree, or a bundle.
    Local,
}

impl Tree {
    /// The address std is named by.
    pub const STD: &'static str = "std";

    /// The version std at `major` is written with, as in `std@v1`.
    pub fn std_version(major: u32) -> String {
        format!("v{major}")
    }

    /// The repository the tree is, std's included; `None` for the local
    /// tree.
    pub fn repository(&self) -> Option<&str> {
        match self {
            Tree::Std => Some(Tree::STD),
            Tree::Repository(repository) => Some(repository),
            Tree::Local => None,
        }
    }
}

/// Flow's keywords, which no name may spell (`grammar.md`).
pub const KEYWORDS: &[&str] = &[
    "flow", "type", "pub", "opaque", "let", "match", "if", "else", "guard", "return", "use", "as",
    "true", "false",
];

/// Whether `text` is a Flow lowercase name that is no keyword, as each name
/// of a module path is.
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)
}

/// Names joined by `/`: a module path inside a library, a library's root
/// inside its tree, or a file's path inside its tree without its `.flow`.
/// The empty path is a library's root module, or a tree's own root.
///
/// No name is empty or holds a `/`: a path is read from its text
/// ([`FromStr`](std::str::FromStr)) or made from its names
/// ([`from_names`](Self::from_names)), and both refuse anything else.
#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Segments(String);

/// Text that is no path: a name in it is empty, as `a//b`, `/a` and
/// `a/` make one.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct SegmentsError {
    /// The text.
    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;

    /// The path `text` spells, names joined by `/`; the empty text is
    /// the empty path.
    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 {
    /// The empty path.
    pub const fn root() -> Segments {
        Segments(String::new())
    }

    /// The path of `names`, in order; `None` when a name is empty or holds
    /// a `/`, which no path's name does.
    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)
    }

    /// The path as text.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Whether this is the empty path.
    pub fn is_root(&self) -> bool {
        self.0.is_empty()
    }

    /// The path's names, in order.
    pub fn names(&self) -> impl Iterator<Item = &str> {
        self.0.split_terminator('/')
    }

    /// `rest` under this path, either of which may be empty.
    #[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)),
        }
    }

    /// Its first `length` names and the rest; all of it and the empty path
    /// when it has no more than `length` names.
    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()),
        }
    }

    /// This path with `prefix` and the `/` after it taken off its front;
    /// `None` when it does not start with `prefix`'s names.
    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)
    }
}

/// Which of the two files of one module path in a library holds the
/// module: the authored `<root>/P.flow` or the contract
/// `<root>/contract/P.flow`.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum Placement {
    /// The authored file.
    Authored,
    /// The contract file.
    Contract,
}

/// A module path written inside a library that spells the library's layout
/// rather than a module, and so names none (`modules.md`, *Libraries*).
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Spelled {
    /// `lib` or `contract/lib`: the root module's file, whose module path
    /// is empty.
    Root,
    /// `contract/P`, the contract module whose module path is `P`; `P` is
    /// empty for `contract` alone.
    Contract {
        /// `P`.
        module: Segments,
    },
}

/// The layout of a library's files (`modules.md`, *Libraries*): a
/// directory holding [`MARKER`](Self::MARKER) is a library's root, a module
/// path `P` names `<root>/P.flow` or `<root>/contract/P.flow`, and the
/// root module, whose module path is empty, is `lib.flow` or
/// `contract/lib.flow`.
#[derive(Debug)]
pub struct LibraryLayout;

impl LibraryLayout {
    /// The file whose presence makes a directory a library's root.
    pub const MARKER: &'static str = "flow.toml";
    /// The directory, under a library's root, that holds its contract
    /// modules.
    pub const CONTRACT: &'static str = "contract";
    /// The stem of the root module's file.
    pub const ROOT: &'static str = "lib";
    /// The extension of a module's file.
    pub const EXTENSION: &'static str = "flow";

    /// The path of `dir`'s marker, `dir` given from a tree's root and
    /// empty for the root itself.
    pub fn marker(dir: &str) -> String {
        if dir.is_empty() {
            LibraryLayout::MARKER.to_owned()
        } else {
            format!("{dir}/{}", LibraryLayout::MARKER)
        }
    }

    /// The name of the file whose path without its extension is `stem`.
    pub fn file(stem: &str) -> String {
        format!("{stem}.{}", LibraryLayout::EXTENSION)
    }

    /// The path of the module file `file` without its extension; `None`
    /// for a file that is no module's.
    pub fn stem(file: &str) -> Option<&str> {
        file.strip_suffix(LibraryLayout::EXTENSION)?
            .strip_suffix('.')
    }

    /// The path of `module`'s file without its extension, from the
    /// directory that holds the files of its placement: the library's root
    /// for an authored module, its contract directory for a contract one.
    /// The root module's is `lib`.
    pub fn placed_stem(module: &Segments) -> Segments {
        if module.is_root() {
            Segments(LibraryLayout::ROOT.to_owned())
        } else {
            module.clone()
        }
    }

    /// The file of `module`, with its extension, from the directory that
    /// holds the files of its placement: `lib.flow` for the root module.
    pub fn placed_file(module: &Segments) -> String {
        LibraryLayout::file(LibraryLayout::placed_stem(module).as_str())
    }

    /// The module whose file, from the directory that holds the files of
    /// its placement and without its extension, is `stem`: the inverse of
    /// [`placed_stem`](Self::placed_stem).
    pub fn placed_module(stem: &Segments) -> Segments {
        if *stem == LibraryLayout::ROOT {
            Segments::root()
        } else {
            stem.clone()
        }
    }

    /// The file, inside its library and without its extension, that holds
    /// the module `module` in `placement`.
    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),
        }
    }

    /// The module a file inside its library, without its extension, holds,
    /// and where: the inverse of [`module_file`](Self::module_file).
    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),
        }
    }

    /// How `module`, a module path as written inside a library, spells
    /// the layout, if it does.
    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()),
            }
        })
    }
}

/// Where a module is, as a `code.ModulePath` writes it (`code.md`,
/// *Programs and modules*): its tree, the root of the library it belongs to
/// in that tree, and its module path in that library. A module outside
/// every library has no library, and its path is its file's from the
/// tree's root, without `.flow`.
///
/// A module path names no version: one program reaches one version of each
/// tree, so where a version is written it is held beside the path.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct ModulePath {
    tree: Tree,
    library: Option<Segments>,
    segments: Segments,
}

impl ModulePath {
    /// The module at `segments` in the library at `library` of `tree`, or
    /// outside every library when `library` is `None`.
    pub fn new(tree: Tree, library: Option<Segments>, segments: Segments) -> ModulePath {
        ModulePath {
            tree,
            library,
            segments,
        }
    }

    /// The module a lone submitted file is: `main` of a one-file bundle
    /// (`abi.md`, *Identity and signatures*).
    pub fn submitted() -> ModulePath {
        ModulePath::new(Tree::Local, None, Segments("main".to_owned()))
    }

    /// The module the file `file` of `tree`, given from the tree's root
    /// without its extension, holds in the library at `library`, and
    /// which of its module path's files it is.
    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)
    }

    /// Its tree.
    pub fn tree(&self) -> &Tree {
        &self.tree
    }

    /// The root of its library in its tree, the empty path for the tree's
    /// own root; `None` outside every library.
    pub fn library(&self) -> Option<&Segments> {
        self.library.as_ref()
    }

    /// Its module path in its library, or outside every library its file's
    /// path from its tree's root.
    pub fn segments(&self) -> &Segments {
        &self.segments
    }

    /// The file of its tree, without its extension, that holds it in
    /// `placement`.
    pub fn file(&self, placement: Placement) -> Segments {
        match &self.library {
            Some(root) => root.join(&LibraryLayout::module_file(&self.segments, placement)),
            None => self.segments.clone(),
        }
    }

    /// The path inside its tree its imports write it by: its library's
    /// root followed by its module path.
    pub fn logical(&self) -> Segments {
        match &self.library {
            Some(root) => root.join(&self.segments),
            None => self.segments.clone(),
        }
    }

    /// Its library's address, or for a module outside every library its
    /// tree's (`abi.md`, *Identity and signatures*): `std` for every
    /// library std holds, a repository, `github.com/acme/tools/payments`,
    /// `tools`, `.` for a library at the local tree's root, or empty for a
    /// module of the local tree outside every library.
    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(),
        }
    }

    /// Its module path inside [`address`](Self::address). std is one
    /// library named `std`, so a module of a library inside it is that
    /// library's root followed by its module path there, as `clock` for
    /// `clock/contract/lib`.
    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(),
        }
    }

    /// The module as identities write it: its address, `@version` when
    /// `version` is given, then its module path, each part that is empty
    /// left out with its separator. A library at the local tree's root is
    /// written as the tree's own modules are, by the path from that root.
    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
    }

    /// The path an import from a module of another tree names it by, at
    /// `version`: `std@v1/clock` or `github.com/acme/tools@v1.2/payments`;
    /// `None` for a module of the local tree, which is named relative to
    /// the importing module.
    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}")
        })
    }
}

/// A module's file as history records its source (`history.md`,
/// *Programs*): `std@v1/<file>`, `<repository>@<version>/<file>`,
/// `./<file>` for the local tree, each file without its extension, or
/// `<name>` for a lone submitted file. Its text is its
/// [`Display`](fmt::Display), which [`FromStr`](std::str::FromStr) reads
/// back.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum SourcePath {
    /// A file of std at a major version.
    Std {
        /// The major version.
        major: u32,
        /// The file, from std's root.
        file: Segments,
    },
    /// A file of a repository at a version, a tag or a commit.
    Repository {
        /// The repository's host path.
        repository: String,
        /// The version.
        version: String,
        /// The file, from the repository's root.
        file: Segments,
    },
    /// A file of the local tree.
    Local {
        /// The file, from the tree's root.
        file: Segments,
    },
    /// A lone submitted file.
    Submitted {
        /// What the submission is called.
        name: String,
    },
}

/// Why text is no [`SourcePath`].
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum SourcePathError {
    /// The text names std without a major version written `v<major>` or
    /// without a file.
    NotStd {
        /// The text.
        text: String,
    },
    /// The text is none of the forms.
    NotAPath {
        /// The text.
        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);
    }
}