Skip to main content

smix_contract/
lib.rs

1//! What an app owes, with an id, so coverage can be reconciled.
2//!
3//! The requirement is usually already written down — in the comment
4//! above a flow, in a ticket, in a design note. What it does not have
5//! is an identity, and without one nothing can answer "is this covered
6//! on both platforms" except a person reading two test suites side by
7//! side and remembering.
8//!
9//! This crate is the identity and the arithmetic. It reads contracts
10//! and per-platform claims and answers three sets: nobody claims,
11//! one platform claims, both claim.
12//!
13//! **It reports who claimed, never who verified.** Those are different
14//! words. A claim says a test suite means to cover a requirement; it
15//! does not say the test is good, or that it passed, or that the two
16//! platforms' tests check the same thing — which is not mechanically
17//! decidable, and pretending otherwise would make this one more cheap
18//! signal standing in for the thing to be proven. The output uses the
19//! word it can support.
20
21#![forbid(unsafe_code)]
22
23pub mod ratchet;
24pub mod reconcile;
25pub mod render;
26pub mod scan;
27pub mod tree;
28
29pub use ratchet::{Baseline, Regression, baseline_of, regressions};
30pub use reconcile::{Claim, PartialClaim, Reconciliation, reconcile};
31pub use render::render;
32pub use scan::scan_claims;
33pub use tree::{platform_of, reconcile_tree};
34
35use serde::Deserialize;
36use std::fmt;
37
38/// One requirement the app owes, and the id that lets it be claimed.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct Contract {
41    pub id: String,
42    pub statement: String,
43    /// Where this was read from, carried so a refusal can say where.
44    pub origin: String,
45}
46
47/// Why a contract file was refused.
48///
49/// Each variant names the thing that is wrong and where it was read,
50/// because a parse error that says only "invalid" sends the reader
51/// back to the file to do the search again.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum ContractError {
54    /// The file is not the shape a contract file has.
55    Malformed { origin: String, detail: String },
56    /// An entry is missing a field it cannot do without.
57    MissingField {
58        origin: String,
59        field: &'static str,
60        entry: usize,
61    },
62    /// An entry has the field and it is empty, which is the same
63    /// absence wearing a present field.
64    BlankField {
65        origin: String,
66        field: &'static str,
67        entry: usize,
68    },
69    /// One id, two requirements. Every later answer about that id is
70    /// meaningless, so this is refused rather than warned about.
71    DuplicateId {
72        origin: String,
73        id: String,
74        first: usize,
75        second: usize,
76    },
77    /// A claim names an id no contract carries. Silently dropping it
78    /// would leave a requirement looking unclaimed while somebody
79    /// believes they are covering it.
80    UnknownContract { origin: String, id: String },
81    /// A claim names a platform nobody expects — the same shape as a
82    /// mistyped id, one level up.
83    UnexpectedPlatform {
84        origin: String,
85        platform: String,
86        expected: Vec<String>,
87    },
88    /// There is nothing for a reconciliation to say. Three empty sets
89    /// over an empty corpus is the shape of perfect coverage, and it is
90    /// an agreement nobody earned.
91    NothingToReconcile { detail: String },
92    /// One id defined in two contract files. Every claim on it is
93    /// ambiguous, and the reader needs to know which two files.
94    DuplicateAcrossFiles {
95        id: String,
96        first: String,
97        second: String,
98    },
99    /// A source file claims something and nothing in its path says
100    /// which platform it is. Guessing would let a requirement covered
101    /// on one platform read as covered on both.
102    PlatformNotInPath {
103        origin: String,
104        expected: Vec<String>,
105    },
106}
107
108impl fmt::Display for ContractError {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        match self {
111            Self::Malformed { origin, detail } => write!(
112                f,
113                "{origin}: not a contract file — a contract file is a list of \
114                 entries, each with an id and a statement ({detail})"
115            ),
116            Self::MissingField {
117                origin,
118                field,
119                entry,
120            } => write!(
121                f,
122                "{origin}: entry {entry} has no `{field}`. A contract without an \
123                 id cannot be claimed by anything, and one without a statement \
124                 stands for nothing"
125            ),
126            Self::BlankField {
127                origin,
128                field,
129                entry,
130            } => write!(
131                f,
132                "{origin}: entry {entry} has an empty `{field}`. A present-but-empty \
133                 field passes a check for the field and says nothing"
134            ),
135            Self::DuplicateId {
136                origin,
137                id,
138                first,
139                second,
140            } => write!(
141                f,
142                "{origin}: id `{id}` is on entry {first} and entry {second}. One id \
143                 pointing at two requirements makes every claim on it ambiguous — \
144                 there is no answer to which of the two a claim covers"
145            ),
146            Self::UnexpectedPlatform {
147                origin,
148                platform,
149                expected,
150            } => write!(
151                f,
152                "{origin}: claims platform `{platform}`, which is not one of the \
153                 expected platforms ({}). A misspelt platform claims nothing, and \
154                 the one it meant goes on looking unclaimed",
155                expected.join(", ")
156            ),
157            Self::DuplicateAcrossFiles { id, first, second } => write!(
158                f,
159                "id `{id}` is defined in {first} and in {second}. One id in two \
160                 files makes every claim on it ambiguous — there is no answer to \
161                 which of the two a claim covers"
162            ),
163            Self::PlatformNotInPath { origin, expected } => write!(
164                f,
165                "{origin} claims a contract and nothing in its path says which \
166                 platform it is (looked for {}). Guessing would let a requirement \
167                 covered on one platform read as covered on both",
168                expected.join(", ")
169            ),
170            Self::NothingToReconcile { detail } => write!(
171                f,
172                "nothing to reconcile: {detail}. A comparison that holds on empty \
173                 input is not a comparison"
174            ),
175            Self::UnknownContract { origin, id } => write!(
176                f,
177                "{origin}: claims `{id}`, which no contract carries. A mistyped id \
178                 leaves the requirement it meant looking unclaimed while somebody \
179                 believes they are covering it"
180            ),
181        }
182    }
183}
184
185impl std::error::Error for ContractError {}
186
187#[derive(Deserialize)]
188struct RawClaim {
189    contract: Option<String>,
190    platform: Option<String>,
191}
192
193/// Read a claim file: which platform means to cover which contract.
194pub fn parse_claims(text: &str, origin: &str) -> Result<Vec<Claim>, ContractError> {
195    if text.trim().is_empty() {
196        return Ok(Vec::new());
197    }
198    let raw: Vec<RawClaim> =
199        serde_norway::from_str(text).map_err(|e| ContractError::Malformed {
200            origin: origin.to_string(),
201            detail: e.to_string(),
202        })?;
203    let mut out = Vec::with_capacity(raw.len());
204    for (i, entry) in raw.into_iter().enumerate() {
205        let n = i + 1;
206        out.push(Claim {
207            contract_id: required(entry.contract, "contract", origin, n)?,
208            platform: required(entry.platform, "platform", origin, n)?,
209            origin: origin.to_string(),
210        });
211    }
212    Ok(out)
213}
214
215#[derive(Deserialize)]
216struct RawContract {
217    id: Option<String>,
218    statement: Option<String>,
219}
220
221/// Read a contract file.
222///
223/// `origin` is what the file should be called in any refusal — a path,
224/// usually. It is a parameter rather than read from the text because
225/// the caller knows where the bytes came from and this does not.
226pub fn parse_contracts(text: &str, origin: &str) -> Result<Vec<Contract>, ContractError> {
227    if text.trim().is_empty() {
228        return Ok(Vec::new());
229    }
230    let raw: Vec<RawContract> =
231        serde_norway::from_str(text).map_err(|e| ContractError::Malformed {
232            origin: origin.to_string(),
233            detail: e.to_string(),
234        })?;
235
236    let mut out: Vec<Contract> = Vec::with_capacity(raw.len());
237    let mut seen: Vec<(String, usize)> = Vec::with_capacity(raw.len());
238
239    for (i, entry) in raw.into_iter().enumerate() {
240        let n = i + 1;
241        let id = required(entry.id, "id", origin, n)?;
242        let statement = required(entry.statement, "statement", origin, n)?;
243        if let Some((_, first)) = seen.iter().find(|(seen_id, _)| *seen_id == id) {
244            return Err(ContractError::DuplicateId {
245                origin: origin.to_string(),
246                id,
247                first: *first,
248                second: n,
249            });
250        }
251        seen.push((id.clone(), n));
252        out.push(Contract {
253            id,
254            statement,
255            origin: origin.to_string(),
256        });
257    }
258    Ok(out)
259}
260
261fn required(
262    value: Option<String>,
263    field: &'static str,
264    origin: &str,
265    entry: usize,
266) -> Result<String, ContractError> {
267    match value {
268        None => Err(ContractError::MissingField {
269            origin: origin.to_string(),
270            field,
271            entry,
272        }),
273        Some(v) if v.trim().is_empty() => Err(ContractError::BlankField {
274            origin: origin.to_string(),
275            field,
276            entry,
277        }),
278        Some(v) => Ok(v),
279    }
280}