Skip to main content

flow_toolkit/
contract.rs

1//! A crate's generated contract, as its own tests read it: what
2//! [`contract!`](crate::contract) returns.
3
4use std::collections::BTreeMap;
5use std::fmt;
6use std::path::PathBuf;
7
8use flow_types::{LibraryLayout, Placement, Segments};
9
10/// The contract modules generated from a set of Tools: each library module
11/// that declares one of them or a type one of them reaches, mapped to its
12/// Flow source, byte for byte what `flow build` writes for the same Tools.
13#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct Contract {
15    root: PathBuf,
16    modules: BTreeMap<Segments, String>,
17}
18
19impl Contract {
20    pub(crate) fn new(root: PathBuf, modules: BTreeMap<Segments, String>) -> Self {
21        Self { root, modules }
22    }
23
24    /// Every generated module's Flow source, by module path.
25    #[must_use]
26    pub fn modules(&self) -> &BTreeMap<Segments, String> {
27        &self.modules
28    }
29
30    /// The generated Flow source of the module `path`, if any of the Tools
31    /// generated it.
32    #[must_use]
33    pub fn module(&self, path: &str) -> Option<&str> {
34        self.modules.get(path).map(String::as_str)
35    }
36
37    /// The committed contract file of `module`, read from the library root
38    /// of the crate that called [`contract!`](crate::contract).
39    ///
40    /// # Errors
41    ///
42    /// Returns the error reading the file, such as `NotFound` when the
43    /// module has no committed contract yet.
44    pub fn committed(&self, module: &Segments) -> std::io::Result<String> {
45        let file = LibraryLayout::module_file(module, Placement::Contract);
46        std::fs::read_to_string(self.root.join(LibraryLayout::file(file.as_str())))
47    }
48}
49
50/// Where a refused declaration is: its file, under the library root when
51/// one is known, and its line.
52#[derive(Clone, Debug, PartialEq, Eq)]
53pub struct Location {
54    file: String,
55    line: u32,
56}
57
58impl Location {
59    pub(crate) fn new(file: String, line: u32) -> Self {
60        Self { file, line }
61    }
62
63    /// The file holding the declaration.
64    #[must_use]
65    pub fn file(&self) -> &str {
66        &self.file
67    }
68
69    /// The line that places the declaration in its file.
70    #[must_use]
71    pub fn line(&self) -> u32 {
72        self.line
73    }
74}
75
76impl fmt::Display for Location {
77    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
78        write!(formatter, "{}:{}:1", self.file, self.line)
79    }
80}
81
82/// Why a set of Tools has no contract.
83#[derive(Clone, Debug, PartialEq, Eq)]
84#[non_exhaustive]
85pub enum ContractError {
86    /// A Tool has the name of a std module its contract imports.
87    StdImportCollision {
88        /// Where the Tool is defined.
89        at: Location,
90        /// The name shared by the Tool and the imported module.
91        name: String,
92    },
93    /// Two Tools of one name in one module.
94    DuplicateTool {
95        /// Where the second one is.
96        at: Location,
97        /// The Tool's name.
98        name: String,
99    },
100    /// A Rust module whose path is no Flow module path.
101    NotAModulePath {
102        /// The declaration placed in it.
103        at: Location,
104        /// The module's path, segments joined by `/`.
105        module: String,
106        /// Its first segment that is no Flow lowercase name.
107        segment: String,
108    },
109    /// A Rust module whose module path spells a library's layout and so
110    /// names no module: `lib` directly under the crate root, whose contract
111    /// file would be the root module's, or `contract` there.
112    Spelled {
113        /// The declaration placed in it.
114        at: Location,
115        /// The module's path, segments joined by `/`.
116        module: String,
117    },
118    /// A Tool reaches a type that a crate the library does not depend on
119    /// defines.
120    ForeignType {
121        /// Where the type is defined.
122        at: Location,
123        /// The type's name.
124        name: String,
125        /// The Rust module defining it, as `module_path!()` spells it.
126        module: String,
127    },
128    /// A Tool reaches a type of a crate the library depends on in a way
129    /// that gives it no Flow address: by a registry version, or by a git URL
130    /// without a version tag.
131    UnaddressedType {
132        /// Where the type is defined.
133        at: Location,
134        /// The type's name.
135        name: String,
136        /// The crate defining it.
137        dependency: String,
138        /// How the library depends on the crate.
139        how: String,
140    },
141    /// Distinct Rust types that share one Flow name in one module.
142    SharedFlowName {
143        /// Where the second one is defined.
144        at: Location,
145        /// The Flow name they share.
146        name: String,
147        /// The first type's Rust identity.
148        first: String,
149        /// The second type's Rust identity.
150        second: String,
151    },
152    /// Tools of two crates in one contract: a contract is one library's.
153    SeveralCrates {
154        /// The first Tool's crate.
155        first: String,
156        /// A Tool's crate that differs from it.
157        second: String,
158    },
159}
160
161impl fmt::Display for ContractError {
162    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
163        match self {
164            Self::StdImportCollision { at, name } => write!(
165                formatter,
166                "{at}: Tool `{name}` conflicts with import `std@v1/{name}`; give the Tool a different public name"
167            ),
168            Self::DuplicateTool { at, name } => {
169                write!(formatter, "{at}: duplicate Tool name {name}")
170            }
171            Self::NotAModulePath {
172                at,
173                module,
174                segment,
175            } => write!(
176                formatter,
177                "{at}: the module `{segment}` of `{module}` is not a Flow lowercase name, so it has no contract module path"
178            ),
179            Self::Spelled { at, module } => write!(
180                formatter,
181                "{at}: `{module}` is no module path: `lib` alone is the root module's file, contract/lib.flow, and a first segment `contract` is the contract's directory; rename the Rust module"
182            ),
183            Self::ForeignType { at, name, module } => write!(
184                formatter,
185                "{at}: {name} is defined in {module}, of a crate this library does not depend on"
186            ),
187            Self::UnaddressedType {
188                at,
189                name,
190                dependency,
191                how,
192            } => write!(
193                formatter,
194                "{at}: {name} comes from {how}, so it has no Flow address and no contract can import it; depend on {dependency} by a path in this repository or a git URL at a tag"
195            ),
196            Self::SharedFlowName {
197                at,
198                name,
199                first,
200                second,
201            } => write!(
202                formatter,
203                "{at}: distinct Rust types share the Flow name {name} in one module: {first} and {second}"
204            ),
205            Self::SeveralCrates { first, second } => write!(
206                formatter,
207                "a contract is one library's, but its Tools are defined in the crates {first} and {second}"
208            ),
209        }
210    }
211}
212
213impl std::error::Error for ContractError {}
214
215#[cfg(test)]
216#[cfg_attr(coverage, coverage(off))]
217mod tests {
218    use super::{ContractError, Location};
219
220    #[test]
221    fn a_location_names_its_file_and_line_as_an_editor_reads_them() {
222        let at = Location::new("src/lib.rs".into(), 12);
223        assert_eq!((at.file(), at.line()), ("src/lib.rs", 12));
224        assert_eq!(at.to_string(), "src/lib.rs:12:1");
225    }
226
227    #[test]
228    fn tools_of_two_crates_are_refused_naming_both() {
229        let refused = ContractError::SeveralCrates {
230            first: "flow_lib_git".into(),
231            second: "flow_lib_http".into(),
232        };
233        assert_eq!(
234            refused.to_string(),
235            "a contract is one library's, but its Tools are defined in the crates flow_lib_git and flow_lib_http"
236        );
237    }
238}