1use std::fmt;
6
7use crate::path::normal_path;
8
9#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
12pub enum Tree {
13 Std,
15 Repository(String),
17 Local,
19}
20
21impl Tree {
22 pub const STD: &'static str = "std";
24
25 pub fn std_version(major: u32) -> String {
27 format!("v{major}")
28 }
29
30 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
41pub const KEYWORDS: &[&str] = &[
43 "flow", "type", "pub", "opaque", "let", "match", "if", "else", "guard", "return", "use", "as",
44 "true", "false",
45];
46
47pub 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#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
64pub struct Segments(String);
65
66#[derive(Clone, PartialEq, Eq, Debug)]
69pub struct SegmentsError {
70 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 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 pub const fn root() -> Segments {
100 Segments(String::new())
101 }
102
103 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 pub fn as_str(&self) -> &str {
123 &self.0
124 }
125
126 pub fn is_root(&self) -> bool {
128 self.0.is_empty()
129 }
130
131 pub fn names(&self) -> impl Iterator<Item = &str> {
133 self.0.split_terminator('/')
134 }
135
136 #[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 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 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#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
203pub enum Placement {
204 Authored,
206 Contract,
208}
209
210#[derive(Clone, PartialEq, Eq, Debug)]
213pub enum Spelled {
214 Root,
217 Contract {
220 module: Segments,
222 },
223}
224
225#[derive(Debug)]
231pub struct LibraryLayout;
232
233impl LibraryLayout {
234 pub const MARKER: &'static str = "flow.toml";
236 pub const CONTRACT: &'static str = "contract";
239 pub const ROOT: &'static str = "lib";
241 pub const EXTENSION: &'static str = "flow";
243
244 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 pub fn file(stem: &str) -> String {
256 format!("{stem}.{}", LibraryLayout::EXTENSION)
257 }
258
259 pub fn stem(file: &str) -> Option<&str> {
262 file.strip_suffix(LibraryLayout::EXTENSION)?
263 .strip_suffix('.')
264 }
265
266 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 pub fn placed_file(module: &Segments) -> String {
281 LibraryLayout::file(LibraryLayout::placed_stem(module).as_str())
282 }
283
284 pub fn placed_module(stem: &Segments) -> Segments {
288 if *stem == LibraryLayout::ROOT {
289 Segments::root()
290 } else {
291 stem.clone()
292 }
293 }
294
295 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 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 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#[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 pub fn new(tree: Tree, library: Option<Segments>, segments: Segments) -> ModulePath {
362 ModulePath {
363 tree,
364 library,
365 segments,
366 }
367 }
368
369 pub fn submitted() -> ModulePath {
372 ModulePath::new(Tree::Local, None, Segments("main".to_owned()))
373 }
374
375 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 pub fn tree(&self) -> &Tree {
396 &self.tree
397 }
398
399 pub fn library(&self) -> Option<&Segments> {
402 self.library.as_ref()
403 }
404
405 pub fn segments(&self) -> &Segments {
408 &self.segments
409 }
410
411 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 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 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 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 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 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#[derive(Clone, PartialEq, Eq, Debug)]
503pub enum SourcePath {
504 Std {
506 major: u32,
508 file: Segments,
510 },
511 Repository {
513 repository: String,
515 version: String,
517 file: Segments,
519 },
520 Local {
522 file: Segments,
524 },
525 Submitted {
527 name: String,
529 },
530}
531
532#[derive(Clone, PartialEq, Eq, Debug)]
534pub enum SourcePathError {
535 NotStd {
538 text: String,
540 },
541 NotAPath {
543 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}