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/// How serious each kind of finding is *for one program*.
19///
20/// By default a misspelled flag, a misspelled variable and a flag given to a subcommand it does
21/// not belong to are all **errors**: the user's intent is clear and wrong, and carrying on would
22/// run the program without the setting they asked for.
23/// A project that has a reason to be more forgiving says so, once, in its own code:
24///
25/// ```
26/// use argenv_resolve::{LintPolicy, Severity};
27///
28/// // Everything strict (this is the default):
29/// let strict = LintPolicy::default();
30///
31/// // The previous behaviour: surface typos, never stop for them.
32/// let lenient = LintPolicy::lenient();
33///
34/// // Or one class at a time, for example a wrapper that forwards unknown flags to a child:
35/// let wrapper = LintPolicy::default().unknown_flags(Severity::Warning);
36/// # let _ = (strict, lenient, wrapper);
37/// ```
38///
39/// The findings themselves do not change with the policy, only how seriously they are taken. A
40/// problem with a *value* (out of domain, unparseable, missing) is always an error: there is no
41/// usable reading of it.
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43pub struct LintPolicy {
44 unknown_flag: Severity,
45 unknown_variable: Severity,
46 out_of_scope_flag: Severity,
47 deprecated: Severity,
48}
49
50impl Default for LintPolicy {
51 fn default() -> Self {
52 Self::strict()
53 }
54}
55
56impl LintPolicy {
57 /// Typos in flags and variables are errors; use of a deprecated input is a warning.
58 pub const fn strict() -> Self {
59 Self {
60 unknown_flag: Severity::Error,
61 unknown_variable: Severity::Error,
62 out_of_scope_flag: Severity::Error,
63 deprecated: Severity::Warning,
64 }
65 }
66
67 /// Typos are surfaced but never stop the program. This was the behaviour before strictness
68 /// became the default; it is the right choice for a program that forwards flags it does not
69 /// declare, or that runs in environments it does not control.
70 pub const fn lenient() -> Self {
71 Self {
72 unknown_flag: Severity::Warning,
73 unknown_variable: Severity::Warning,
74 out_of_scope_flag: Severity::Warning,
75 deprecated: Severity::Warning,
76 }
77 }
78
79 /// How seriously to take a flag that no input declares.
80 #[must_use]
81 pub const fn unknown_flags(mut self, severity: Severity) -> Self {
82 self.unknown_flag = severity;
83 self
84 }
85
86 /// How seriously to take a variable that closely resembles a declared one.
87 #[must_use]
88 pub const fn unknown_variables(mut self, severity: Severity) -> Self {
89 self.unknown_variable = severity;
90 self
91 }
92
93 /// How seriously to take a flag that is declared, but for other subcommands than the one
94 /// running (for example `--dry-run`, which belongs to `create`, given to `delete`).
95 #[must_use]
96 pub const fn out_of_scope_flags(mut self, severity: Severity) -> Self {
97 self.out_of_scope_flag = severity;
98 self
99 }
100
101 /// How seriously to take the use of a deprecated input.
102 #[must_use]
103 pub const fn deprecated(mut self, severity: Severity) -> Self {
104 self.deprecated = severity;
105 self
106 }
107
108 /// The severity this policy gives a finding.
109 pub fn severity(&self, finding: &Finding) -> Severity {
110 match finding {
111 Finding::UnknownArg { .. } => self.unknown_flag,
112 Finding::UnknownEnv { .. } => self.unknown_variable,
113 Finding::OutOfScope { .. } => self.out_of_scope_flag,
114 Finding::Deprecated { .. } => self.deprecated,
115 Finding::InvalidValue { .. }
116 | Finding::UnknownToken { .. }
117 | Finding::MissingRequired { .. }
118 | Finding::MissingValue { .. }
119 | Finding::UnexpectedValue { .. } => Severity::Error,
120 }
121 }
122}
123
124/// Something wrong with an invocation, relative to the declared contract.
125///
126/// This enum is `#[non_exhaustive]`: a new kind of finding can be added in a minor release, so a
127/// `match` on it needs a wildcard arm. Ask [`Finding::severity`] or a [`LintPolicy`] how serious
128/// one is instead of matching on its kind.
129#[derive(Clone, Debug, PartialEq)]
130#[non_exhaustive]
131pub enum Finding {
132 /// A flag was given that no input declares.
133 UnknownArg {
134 /// The flag as written, dashes included.
135 arg: String,
136 /// The declared flag it most likely meant.
137 did_you_mean: Option<String>,
138 },
139 /// A flag was given that is declared, but only for other subcommands than the one running.
140 ///
141 /// Flags are parsed globally, so without this finding `delete --dry-run` would be accepted
142 /// and the flag silently ignored by `delete`, which is the worst place for a "preview" flag
143 /// to be ignored.
144 OutOfScope {
145 /// The flag by its declared name (`--dry-run`; the short spelling if it has no long one).
146 arg: String,
147 /// The subcommand that is running, if any.
148 command: Option<String>,
149 /// The subcommands the flag belongs to.
150 applies_to: Vec<String>,
151 },
152 /// A variable is set that no input declares, but which closely resembles one
153 /// that exists.
154 ///
155 /// Only near-misses are reported: an environment holds hundreds of unrelated
156 /// variables, and a checker that mentions `PATH` is a checker nobody runs.
157 UnknownEnv {
158 /// The variable that is set.
159 name: String,
160 /// The declared name it most likely meant.
161 did_you_mean: String,
162 },
163 /// A flag that takes a value was given none.
164 MissingValue {
165 /// The flag as written.
166 arg: String,
167 },
168 /// A flag that takes no value was given one.
169 UnexpectedValue {
170 /// The flag as written.
171 arg: String,
172 },
173 /// A declared input received a value outside its domain.
174 InvalidValue {
175 /// The input's key.
176 key: String,
177 /// Where the offending value came from.
178 source: Source,
179 /// The offending raw value.
180 value: String,
181 /// Why it was rejected.
182 reason: String,
183 },
184 /// A token in a list value is not among the declared tokens.
185 UnknownToken {
186 /// The input's key.
187 key: String,
188 /// The offending token.
189 token: String,
190 /// The tokens that are accepted.
191 allowed: Vec<String>,
192 },
193 /// A required input was not supplied and has no default. An input scoped to
194 /// subcommands counts as required only when one of those subcommands is running.
195 MissingRequired {
196 /// The input's key.
197 key: String,
198 /// How it could have been supplied.
199 via: Vec<String>,
200 },
201 /// A deprecated input is in use.
202 Deprecated {
203 /// The input's key.
204 key: String,
205 /// Guidance carried by the declaration.
206 guidance: String,
207 },
208}
209
210impl Finding {
211 /// How seriously to take this finding under the default, strict, [`LintPolicy`]. A program
212 /// with different needs asks its own policy: [`LintPolicy::severity`].
213 pub fn severity(&self) -> Severity {
214 LintPolicy::default().severity(self)
215 }
216}
217
218impl std::fmt::Display for Finding {
219 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220 match self {
221 Finding::UnknownArg { arg, did_you_mean } => match did_you_mean {
222 Some(s) => write!(f, "{arg} is not a declared flag; did you mean {s}?"),
223 None => write!(f, "{arg} is not a declared flag"),
224 },
225 Finding::UnknownEnv { name, did_you_mean } => {
226 write!(f, "{name} is not declared; did you mean {did_you_mean}?")
227 }
228 Finding::OutOfScope {
229 arg,
230 command,
231 applies_to,
232 } => match command {
233 Some(command) => write!(
234 f,
235 "{arg} does not apply to `{command}` (it applies to: {})",
236 applies_to.join(", ")
237 ),
238 None => write!(f, "{arg} only applies to: {}", applies_to.join(", ")),
239 },
240 Finding::MissingValue { arg } => write!(f, "{arg} needs a value"),
241 Finding::UnexpectedValue { arg } => write!(f, "{arg} takes no value"),
242 Finding::InvalidValue {
243 key,
244 source,
245 value,
246 reason,
247 } => write!(
248 f,
249 "{key} (from {source}) is `{value}`, which is invalid: {reason}"
250 ),
251 Finding::UnknownToken {
252 key,
253 token,
254 allowed,
255 } => write!(
256 f,
257 "{key} contains unknown token `{token}`; accepted: {}",
258 allowed.join(", ")
259 ),
260 Finding::MissingRequired { key, via } => {
261 if via.is_empty() {
262 write!(f, "{key} is required but was not supplied")
263 } else {
264 write!(f, "{key} is required; supply it with {}", via.join(" or "))
265 }
266 }
267 Finding::Deprecated { key, guidance } => {
268 if guidance.is_empty() {
269 write!(f, "{key} is deprecated")
270 } else {
271 write!(f, "{key} is deprecated: {guidance}")
272 }
273 }
274 }
275 }
276}
277
278/// Check a resolved invocation against the declared contract.
279///
280/// Works from a [`Resolution`] rather than an [`crate::Invocation`], so
281/// the common flow is:
282///
283/// ```no_run
284/// # use argenv_resolve::*;
285/// # let model: Vec<Record> = vec![];
286/// let resolution = argenv_resolve::parse(&model); // reads process args + env
287/// for finding in argenv_resolve::lint(&model, &resolution) {
288/// eprintln!("{:?}: {finding}", finding.severity());
289/// }
290/// ```
291///
292/// Works from [`Record`]s, so it applies equally to a model declared in this
293/// crate and to a contract document published by a program in another language.
294pub fn lint(model: &[Record], resolution: &Resolution) -> Vec<Finding> {
295 let mut findings = resolution.findings().to_vec();
296 findings.extend(check_resolution(model, resolution));
297 findings.extend(check_environment(model, &resolution.env_names));
298 findings
299}
300
301fn check_resolution(model: &[Record], resolution: &Resolution) -> Vec<Finding> {
302 let mut findings = Vec::new();
303 // The subcommand that is running: the first positional, as resolution itself reads it.
304 let active = resolution.positionals().first().map(String::as_str);
305 for r in model {
306 let Some(value) = resolution.values().get(&r.key) else {
307 // An input scoped to subcommands is only demanded when one of them runs.
308 // Otherwise `required: true` on `delete`'s argument would make every other
309 // subcommand fail its lint.
310 let in_scope = r.subcommands.is_empty()
311 || active.is_some_and(|a| r.subcommands.iter().any(|s| s == a));
312 if r.required && in_scope {
313 let mut via = r.arg_labels();
314 via.extend(r.env_names().iter().map(|n| n.to_string()));
315 findings.push(Finding::MissingRequired {
316 key: r.key.clone(),
317 via,
318 });
319 }
320 continue;
321 };
322
323 // A declared default is the program's own choice; only supplied values
324 // are judged.
325 if value.source == Source::Default {
326 continue;
327 }
328
329 // A flag for other subcommands, given to this one. Flags are parsed globally, so it was
330 // accepted; it must not be silently ignored. Its value is not judged: the problem is
331 // that it is here at all.
332 let is_flag = r.arg.as_ref().is_some_and(|a| a.position.is_none());
333 let in_scope = r.subcommands.is_empty()
334 || active.is_some_and(|a| r.subcommands.iter().any(|s| s == a));
335 if is_flag && value.source == Source::Arg && !in_scope {
336 findings.push(Finding::OutOfScope {
337 arg: r
338 .arg
339 .as_ref()
340 .and_then(|a| {
341 a.long
342 .as_ref()
343 .map(|l| format!("--{l}"))
344 .or_else(|| a.short.as_ref().map(|c| format!("-{c}")))
345 })
346 .unwrap_or_else(|| r.key.clone()),
347 command: active.map(str::to_string),
348 applies_to: r.subcommands.clone(),
349 });
350 continue;
351 }
352
353 if let Err(reason) = r.accepts(&value.raw) {
354 findings.push(Finding::InvalidValue {
355 key: r.key.clone(),
356 source: value.source,
357 value: value.raw.clone(),
358 reason,
359 });
360 }
361 if !r.allowed.is_empty() {
362 for token in r.tokens(&value.raw) {
363 if !r.allowed.iter().any(|a| a == token) {
364 findings.push(Finding::UnknownToken {
365 key: r.key.clone(),
366 token: token.to_string(),
367 allowed: r.allowed.clone(),
368 });
369 }
370 }
371 }
372 if let Some(dep) = &r.deprecation {
373 let guidance = dep
374 .get("replaced_by")
375 .and_then(|v| v.as_str())
376 .map(|s| format!("use {s} instead"))
377 .or_else(|| {
378 dep.get("migration")
379 .and_then(|v| v.as_str())
380 .map(str::to_string)
381 })
382 .unwrap_or_default();
383 findings.push(Finding::Deprecated {
384 key: r.key.clone(),
385 guidance,
386 });
387 }
388 }
389 findings
390}
391
392fn check_environment(model: &[Record], env_names: &[String]) -> Vec<Finding> {
393 let declared: Vec<String> = model
394 .iter()
395 .flat_map(|r| r.env_names().into_iter().map(str::to_string))
396 .collect();
397 let prefixes: std::collections::BTreeSet<&str> = declared
398 .iter()
399 .filter_map(|n| n.split_once('_').map(|(p, _)| p))
400 .collect();
401
402 let mut findings = Vec::new();
403 for name in env_names.iter().cloned() {
404 if declared.contains(&name) {
405 continue;
406 }
407 // Only names plausibly aimed at this program are considered.
408 let shares_prefix = name
409 .split_once('_')
410 .map(|(p, _)| prefixes.contains(p))
411 .unwrap_or(false);
412 if !shares_prefix {
413 continue;
414 }
415 let known: Vec<&str> = declared.iter().map(String::as_str).collect();
416 if let Some(best) = nearest(&name, &known) {
417 findings.push(Finding::UnknownEnv {
418 name,
419 did_you_mean: best,
420 });
421 }
422 }
423 findings
424}
425
426/// The closest known spelling within a small edit distance, if any.
427pub(crate) fn nearest<S: AsRef<str>>(name: &str, known: &[S]) -> Option<String> {
428 // Roughly one typo per eight characters, at least one, at most three.
429 let budget = (name.len() / 8).clamp(1, 3);
430 known
431 .iter()
432 .map(|d| (edit_distance(name, d.as_ref()), d.as_ref()))
433 .filter(|(dist, _)| *dist <= budget)
434 .min_by_key(|(dist, _)| *dist)
435 .map(|(_, d)| d.to_string())
436}
437
438/// Levenshtein distance, two-row variant.
439fn edit_distance(a: &str, b: &str) -> usize {
440 let (a, b): (Vec<char>, Vec<char>) = (a.chars().collect(), b.chars().collect());
441 if a.is_empty() {
442 return b.len();
443 }
444 let mut prev: Vec<usize> = (0..=b.len()).collect();
445 let mut cur = vec![0usize; b.len() + 1];
446 for (i, ca) in a.iter().enumerate() {
447 cur[0] = i + 1;
448 for (j, cb) in b.iter().enumerate() {
449 let cost = usize::from(ca != cb);
450 cur[j + 1] = (prev[j + 1] + 1).min(cur[j] + 1).min(prev[j] + cost);
451 }
452 std::mem::swap(&mut prev, &mut cur);
453 }
454 prev[b.len()]
455}