Skip to main content

argenv_resolve/
lint.rs

1//! Checking a real invocation against the declared contract.
2//!
3//! This is the failure mode the project exists to fix. Without a declaration, a
4//! misspelled flag is an error the program never sees, a misspelled variable is
5//! ignored in silence, and an out-of-domain value is accepted and then
6//! misbehaves somewhere far from its cause.
7use crate::{Record, Resolution, Source};
8
9/// How seriously to take a [`Finding`].
10#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
11pub enum Severity {
12    /// Worth surfacing; safe to continue.
13    Warning,
14    /// The invocation does not satisfy the contract.
15    Error,
16}
17
18/// Something wrong with an invocation, relative to the declared contract.
19#[derive(Clone, Debug, PartialEq)]
20pub enum Finding {
21    /// A flag was given that no input declares.
22    UnknownArg {
23        /// The flag as written, dashes included.
24        arg: String,
25        /// The declared flag it most likely meant.
26        did_you_mean: Option<String>,
27    },
28    /// A variable is set that no input declares, but which closely resembles one
29    /// that exists.
30    ///
31    /// Only near-misses are reported: an environment holds hundreds of unrelated
32    /// variables, and a checker that mentions `PATH` is a checker nobody runs.
33    UnknownEnv {
34        /// The variable that is set.
35        name: String,
36        /// The declared name it most likely meant.
37        did_you_mean: String,
38    },
39    /// A flag that takes a value was given none.
40    MissingValue {
41        /// The flag as written.
42        arg: String,
43    },
44    /// A flag that takes no value was given one.
45    UnexpectedValue {
46        /// The flag as written.
47        arg: String,
48    },
49    /// A declared input received a value outside its domain.
50    InvalidValue {
51        /// The input's key.
52        key: String,
53        /// Where the offending value came from.
54        source: Source,
55        /// The offending raw value.
56        value: String,
57        /// Why it was rejected.
58        reason: String,
59    },
60    /// A token in a list value is not among the declared tokens.
61    UnknownToken {
62        /// The input's key.
63        key: String,
64        /// The offending token.
65        token: String,
66        /// The tokens that are accepted.
67        allowed: Vec<String>,
68    },
69    /// A required input was not supplied and has no default.
70    MissingRequired {
71        /// The input's key.
72        key: String,
73        /// How it could have been supplied.
74        via: Vec<String>,
75    },
76    /// A deprecated input is in use.
77    Deprecated {
78        /// The input's key.
79        key: String,
80        /// Guidance carried by the declaration.
81        guidance: String,
82    },
83}
84
85impl Finding {
86    /// How seriously to take this finding.
87    pub fn severity(&self) -> Severity {
88        match self {
89            Finding::InvalidValue { .. }
90            | Finding::UnknownToken { .. }
91            | Finding::MissingRequired { .. }
92            | Finding::MissingValue { .. }
93            | Finding::UnexpectedValue { .. } => Severity::Error,
94            Finding::UnknownArg { .. }
95            | Finding::UnknownEnv { .. }
96            | Finding::Deprecated { .. } => Severity::Warning,
97        }
98    }
99}
100
101impl std::fmt::Display for Finding {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        match self {
104            Finding::UnknownArg { arg, did_you_mean } => match did_you_mean {
105                Some(s) => write!(f, "{arg} is not a declared flag; did you mean {s}?"),
106                None => write!(f, "{arg} is not a declared flag"),
107            },
108            Finding::UnknownEnv { name, did_you_mean } => {
109                write!(f, "{name} is not declared; did you mean {did_you_mean}?")
110            }
111            Finding::MissingValue { arg } => write!(f, "{arg} needs a value"),
112            Finding::UnexpectedValue { arg } => write!(f, "{arg} takes no value"),
113            Finding::InvalidValue {
114                key,
115                source,
116                value,
117                reason,
118            } => write!(
119                f,
120                "{key} (from {source}) is `{value}`, which is invalid: {reason}"
121            ),
122            Finding::UnknownToken {
123                key,
124                token,
125                allowed,
126            } => write!(
127                f,
128                "{key} contains unknown token `{token}`; accepted: {}",
129                allowed.join(", ")
130            ),
131            Finding::MissingRequired { key, via } => {
132                if via.is_empty() {
133                    write!(f, "{key} is required but was not supplied")
134                } else {
135                    write!(f, "{key} is required; supply it with {}", via.join(" or "))
136                }
137            }
138            Finding::Deprecated { key, guidance } => {
139                if guidance.is_empty() {
140                    write!(f, "{key} is deprecated")
141                } else {
142                    write!(f, "{key} is deprecated: {guidance}")
143                }
144            }
145        }
146    }
147}
148
149/// Check a resolved invocation against the declared contract.
150///
151/// Works from a [`Resolution`] rather than an [`crate::Invocation`], so
152/// the common flow is:
153///
154/// ```no_run
155/// # use argenv_resolve::*;
156/// # let model: Vec<Record> = vec![];
157/// let resolution = argenv_resolve::parse(&model);          // reads process args + env
158/// for finding in argenv_resolve::lint(&model, &resolution) {
159///     eprintln!("{:?}: {finding}", finding.severity());
160/// }
161/// ```
162///
163/// Works from [`Record`]s, so it applies equally to a model declared in this
164/// crate and to a contract document published by a program in another language.
165pub fn lint(model: &[Record], resolution: &Resolution) -> Vec<Finding> {
166    let mut findings = resolution.findings().to_vec();
167    findings.extend(check_resolution(model, resolution));
168    findings.extend(check_environment(model, &resolution.env_names));
169    findings
170}
171
172fn check_resolution(model: &[Record], resolution: &Resolution) -> Vec<Finding> {
173    let mut findings = Vec::new();
174    for r in model {
175        let Some(value) = resolution.values().get(&r.key) else {
176            if r.required {
177                let mut via = r.arg_labels();
178                via.extend(r.env_names().iter().map(|n| n.to_string()));
179                findings.push(Finding::MissingRequired {
180                    key: r.key.clone(),
181                    via,
182                });
183            }
184            continue;
185        };
186
187        // A declared default is the program's own choice; only supplied values
188        // are judged.
189        if value.source == Source::Default {
190            continue;
191        }
192
193        if let Err(reason) = r.accepts(&value.raw) {
194            findings.push(Finding::InvalidValue {
195                key: r.key.clone(),
196                source: value.source,
197                value: value.raw.clone(),
198                reason,
199            });
200        }
201        if !r.allowed.is_empty() {
202            for token in r.tokens(&value.raw) {
203                if !r.allowed.iter().any(|a| a == token) {
204                    findings.push(Finding::UnknownToken {
205                        key: r.key.clone(),
206                        token: token.to_string(),
207                        allowed: r.allowed.clone(),
208                    });
209                }
210            }
211        }
212        if let Some(dep) = &r.deprecation {
213            let guidance = dep
214                .get("replaced_by")
215                .and_then(|v| v.as_str())
216                .map(|s| format!("use {s} instead"))
217                .or_else(|| {
218                    dep.get("migration")
219                        .and_then(|v| v.as_str())
220                        .map(str::to_string)
221                })
222                .unwrap_or_default();
223            findings.push(Finding::Deprecated {
224                key: r.key.clone(),
225                guidance,
226            });
227        }
228    }
229    findings
230}
231
232fn check_environment(model: &[Record], env_names: &[String]) -> Vec<Finding> {
233    let declared: Vec<String> = model
234        .iter()
235        .flat_map(|r| r.env_names().into_iter().map(str::to_string))
236        .collect();
237    let prefixes: std::collections::BTreeSet<&str> = declared
238        .iter()
239        .filter_map(|n| n.split_once('_').map(|(p, _)| p))
240        .collect();
241
242    let mut findings = Vec::new();
243    for name in env_names.iter().cloned() {
244        if declared.contains(&name) {
245            continue;
246        }
247        // Only names plausibly aimed at this program are considered.
248        let shares_prefix = name
249            .split_once('_')
250            .map(|(p, _)| prefixes.contains(p))
251            .unwrap_or(false);
252        if !shares_prefix {
253            continue;
254        }
255        let known: Vec<&str> = declared.iter().map(String::as_str).collect();
256        if let Some(best) = nearest(&name, &known) {
257            findings.push(Finding::UnknownEnv {
258                name,
259                did_you_mean: best,
260            });
261        }
262    }
263    findings
264}
265
266/// The closest known spelling within a small edit distance, if any.
267pub(crate) fn nearest<S: AsRef<str>>(name: &str, known: &[S]) -> Option<String> {
268    // Roughly one typo per eight characters, at least one, at most three.
269    let budget = (name.len() / 8).clamp(1, 3);
270    known
271        .iter()
272        .map(|d| (edit_distance(name, d.as_ref()), d.as_ref()))
273        .filter(|(dist, _)| *dist <= budget)
274        .min_by_key(|(dist, _)| *dist)
275        .map(|(_, d)| d.to_string())
276}
277
278/// Levenshtein distance, two-row variant.
279fn edit_distance(a: &str, b: &str) -> usize {
280    let (a, b): (Vec<char>, Vec<char>) = (a.chars().collect(), b.chars().collect());
281    if a.is_empty() {
282        return b.len();
283    }
284    let mut prev: Vec<usize> = (0..=b.len()).collect();
285    let mut cur = vec![0usize; b.len() + 1];
286    for (i, ca) in a.iter().enumerate() {
287        cur[0] = i + 1;
288        for (j, cb) in b.iter().enumerate() {
289            let cost = usize::from(ca != cb);
290            cur[j + 1] = (prev[j + 1] + 1).min(cur[j] + 1).min(prev[j] + cost);
291        }
292        std::mem::swap(&mut prev, &mut cur);
293    }
294    prev[b.len()]
295}