Skip to main content

usage/
parse.rs

1use crate::miette::{self, bail};
2use indexmap::IndexMap;
3use itertools::Itertools;
4use log::trace;
5use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
6use std::fmt::{Debug, Display, Formatter};
7use std::sync::Arc;
8
9#[cfg(feature = "cli-help")]
10use crate::docs;
11use crate::error::UsageErr;
12use crate::spec::arg::SpecDoubleDashChoices;
13use crate::spec::unknown_flags::UnknownFlags;
14use crate::warn::Warning;
15use crate::{Spec, SpecArg, SpecChoices, SpecCommand, SpecFlag};
16
17/// Merge a subcommand's flags into the currently available flags when descending
18/// into that subcommand.
19///
20/// On descent we drop the parent's non-global flags (they are scoped to the parent)
21/// but keep its global flags so they remain recognized further down. A subcommand may
22/// re-declare a flag that the parent exposed as global (e.g. `-C/--cd`) but mark its own
23/// copy as non-global. In that case we must NOT let the non-global re-declaration shadow
24/// the inherited global flag, otherwise the next descent's `retain(global)` would drop it
25/// entirely and later parsing would treat the already-consumed global token as an
26/// unexpected positional/flag value.
27///
28/// Descending into a *mounted* subcommand (`crossing_mount`) is different: the mounted
29/// command describes another program, which does not accept the mounting CLI's globals.
30/// Those globals stay recognized (they may appear before the mounted command, and Phase 2
31/// re-parses them), but the mounted command's own flags take precedence over them, so its
32/// choices/completions are not replaced by a global's. Which flags a completion may offer
33/// there is a separate question, answered by [`ParseOutput::completion_flags`].
34///
35/// Returns each flag it built by merging a re-declaration into an inherited global, with the
36/// address of the global it stands for, so a caller tracking where flags came from can carry
37/// that over. See [`ParseOutput::is_mounted_flag`].
38fn merge_subcommand_flags(
39    available: &mut BTreeMap<String, Arc<SpecFlag>>,
40    new_flags: BTreeMap<String, Arc<SpecFlag>>,
41    crossing_mount: bool,
42) -> Vec<(Arc<SpecFlag>, usize)> {
43    let mut merges = Vec::new();
44    // Keep only inherited global flags from the parent.
45    available.retain(|_, f| f.global);
46
47    if crossing_mount {
48        // A mounted command owns its flags outright, including names an inherited global also
49        // uses: a word after the mounted command belongs to the mounted program. Words before
50        // it keep resolving to the global they were read as, via `Token::binding`. Aliases the
51        // mounted command does not declare (e.g. a global's short) stay inherited.
52        for (key, flag) in new_flags {
53            available.insert(key, flag);
54        }
55        return merges;
56    }
57
58    // Cache the merged (global ∪ orphan-alias) flag per re-declared child so every alias key of
59    // that flag ends up sharing one `Arc`. Keyed by the child `Arc`'s identity.
60    let mut merged_cache: HashMap<usize, Arc<SpecFlag>> = HashMap::new();
61    // Maps each merged flag produced below back to the inherited global it was merged from, so
62    // the collision check can compare *origins*: a flag this loop already merged is not a
63    // different global, even though it is a different `Arc`.
64    let mut merged_origin: HashMap<usize, usize> = HashMap::new();
65    // The inherited global a flag stands for: itself, or — for a merged flag — its source global.
66    fn origin_of(merged_origin: &HashMap<usize, usize>, flag: &Arc<SpecFlag>) -> usize {
67        let ptr = Arc::as_ptr(flag) as usize;
68        *merged_origin.get(&ptr).unwrap_or(&ptr)
69    }
70
71    // Iterate the *flattened* child map directly (one entry per alias key). This preserves the
72    // map's existing intra-subcommand collision resolution: when two flags in the same command
73    // share an alias (e.g. `-x --alpha` then `-x --beta`), the BTreeMap already collapsed `-x`
74    // to its last-declared owner, and we must not change which flag owns it.
75    for (key, flag) in new_flags {
76        if flag.global {
77            // A child that re-declares (or adds) a global flag stays recognized everywhere.
78            available.insert(key, flag);
79            continue;
80        }
81
82        // A non-global re-declaration that shares a LONG name with an inherited global flag is
83        // the SAME logical flag (e.g. mise's `-r --raw` re-declaring the long-only `--raw`
84        // global). Keep the global flag (global precedence, so it survives the next descent's
85        // `retain`), but union in any short/long aliases that exist only on the re-declaration,
86        // otherwise those orphan aliases would be silently dropped. Matching on a shared long is
87        // deliberate: a re-declaration sharing only a short letter with an unrelated global
88        // (`-q --quiet` vs `-q --quoting`) is a genuine collision, not an alias addition, and is
89        // handled by the `contains_key` skip below instead.
90        let inherited_global = flag.long.iter().find_map(|l| {
91            available
92                .get(&format!("--{l}"))
93                .filter(|f| f.global)
94                .cloned()
95        });
96        if let Some(global_flag) = inherited_global {
97            // Never clobber a *different* inherited global's alias. If this re-declaration's
98            // orphan alias (e.g. `-r`) is already owned by some other global (e.g. an unrelated
99            // `-r --restrict`), that is a genuine collision: keep the existing global, as global
100            // precedence dictates, instead of stealing the alias for the merged flag.
101            //
102            // Compare origins, not `Arc`s: when the global has several aliases of its own, an
103            // earlier key of this same child already replaced some of them with the merged flag,
104            // which the lookups above may now resolve to. That is the same logical flag, so it
105            // must not read as a collision and leave this key on the pre-merge global.
106            let global_origin = origin_of(&merged_origin, &global_flag);
107            if available.get(&key).is_some_and(|existing| {
108                existing.global && origin_of(&merged_origin, existing) != global_origin
109            }) {
110                continue;
111            }
112            let merged = match merged_cache.get(&(Arc::as_ptr(&flag) as usize)) {
113                Some(merged) => merged.clone(),
114                None => {
115                    let mut merged = (*global_flag).clone();
116                    // `exclusive` is deliberately *not* reconciled here, in either direction.
117                    // One object now answers to two alias sets that may disagree: the child
118                    // owns the spellings it declared, the ancestor keeps the ones only it
119                    // declared. A single bool cannot hold both, so the merged flag carries the
120                    // ancestor's and validation resolves the occurrence by the spelling that
121                    // was typed — the ledger it already consults to decide whether selecting
122                    // the child is company.
123                    for s in &flag.short {
124                        if !merged.short.contains(s) {
125                            merged.short.push(*s);
126                        }
127                    }
128                    for l in &flag.long {
129                        if !merged.long.contains(l) {
130                            merged.long.push(l.clone());
131                        }
132                    }
133                    // A child may deliberately promote one of the ancestor's hidden aliases.
134                    // Hidden lists are subsets of the accepted spellings, so a spelling present
135                    // on the child but absent from its hidden subset is visible at this level.
136                    merged.hidden_short_aliases.retain(|alias| {
137                        !flag.short.contains(alias) || flag.hidden_short_aliases.contains(alias)
138                    });
139                    merged.hidden_aliases.retain(|alias| {
140                        !flag.long.contains(alias) || flag.hidden_aliases.contains(alias)
141                    });
142                    for s in &flag.hidden_short_aliases {
143                        if !merged.hidden_short_aliases.contains(s) {
144                            merged.hidden_short_aliases.push(*s);
145                        }
146                    }
147                    for l in &flag.hidden_aliases {
148                        if !merged.hidden_aliases.contains(l) {
149                            merged.hidden_aliases.push(l.clone());
150                        }
151                    }
152                    let merged = Arc::new(merged);
153                    merged_cache.insert(Arc::as_ptr(&flag) as usize, Arc::clone(&merged));
154                    merged_origin.insert(Arc::as_ptr(&merged) as usize, global_origin);
155                    merges.push((Arc::clone(&merged), global_origin));
156                    // Rebind the global's *other* aliases onto the merged flag. The loop only
157                    // visits keys the child declared, so an alias the child left out (the `-y` of
158                    // a `-y --yes` global re-declared as just `--yes`) would otherwise keep
159                    // pointing at the pre-merge flag and miss the aliases just unioned in. One
160                    // logical flag must be one object under every key it answers to.
161                    for existing in available.values_mut() {
162                        if origin_of(&merged_origin, existing) == global_origin {
163                            *existing = Arc::clone(&merged);
164                        }
165                    }
166                    merged
167                }
168            };
169            available.insert(key, merged);
170            continue;
171        }
172
173        // Purely-local flag (shares nothing with an inherited global), or one that collides only
174        // on a short with an unrelated global. Insert this alias but never shadow an inherited
175        // global flag. Such non-global flags are dropped by the next descent's `retain`.
176        if available.contains_key(&key) {
177            continue;
178        }
179        available.insert(key, flag);
180    }
181    merges
182}
183
184/// Build the lookup keys a flag is registered under in `available_flags`:
185/// `--<long>` for each long name, `-<short>` for each short char, plus the `negate` token.
186fn flag_keys(flag: &SpecFlag) -> Vec<String> {
187    let mut keys: Vec<String> = flag
188        .long
189        .iter()
190        .map(|l| format!("--{l}"))
191        .chain(flag.short.iter().map(|s| format!("-{s}")))
192        .collect();
193    if let Some(negate) = &flag.negate {
194        keys.push(negate.clone());
195    }
196    keys
197}
198
199/// The flags a command declares, keyed by each of their aliases.
200fn gather_flags(cmd: &SpecCommand) -> BTreeMap<String, Arc<SpecFlag>> {
201    cmd.flags
202        .iter()
203        .chain(cmd.clause.iter().flat_map(|clause| &clause.flags))
204        .flat_map(|f| {
205            let f = Arc::new(f.clone()); // One clone per flag, then cheap Arc refs
206            flag_keys(&f)
207                .into_iter()
208                .map(|key| (key, Arc::clone(&f)))
209                .collect::<Vec<_>>()
210        })
211        .collect()
212}
213
214fn unique_flags<'a>(
215    flags: impl IntoIterator<Item = &'a Arc<SpecFlag>>,
216) -> impl Iterator<Item = &'a Arc<SpecFlag>> {
217    let mut seen = HashSet::new();
218    flags
219        .into_iter()
220        .filter(move |flag| seen.insert(Arc::as_ptr(flag) as usize))
221}
222
223/// Every flag a command accepts, resolved the way parsing an invocation of it
224/// resolves them.
225///
226/// `chain` runs from the root command (`spec.cmd`) down to the command in
227/// question; an empty chain yields no flags.
228///
229/// This is not "the command's flags plus its ancestors' globals". A subcommand
230/// that re-declares a global's long name is describing the *same* flag rather
231/// than a new one, so the global's help, argument and effect survive and only
232/// the re-declaration's extra aliases are added — see
233/// [`merge_subcommand_flags`]. Anything that reports a command's flags without
234/// going through this will disagree with what the parser actually accepts.
235pub fn available_flags(chain: &[&SpecCommand]) -> Vec<Arc<SpecFlag>> {
236    let Some((root, rest)) = chain.split_first() else {
237        return vec![];
238    };
239    let mut available = gather_flags(root);
240    for cmd in rest {
241        merge_subcommand_flags(&mut available, gather_flags(cmd), false);
242    }
243
244    // Deduplicating by `Arc` identity is not enough. When a child re-declares a
245    // global that has both a short and a long, the merged flag is written under
246    // the long key while the short key keeps pointing at the pre-merge `Arc` —
247    // two objects for one logical flag. That is harmless for parsing, which
248    // looks flags up by key, but a caller listing flags would see it twice.
249    //
250    // Names break the tie because a long key always sorts before a short one
251    // (`--x` < `-y` at the second byte), so the merged declaration is the one
252    // reached first. Two genuinely distinct flags sharing a name is a spec bug
253    // that `usage lint` reports as a duplicate flag.
254    let mut seen_names = HashSet::new();
255    unique_flags(available.values())
256        .filter(|f| seen_names.insert(f.name.clone()))
257        .cloned()
258        .collect()
259}
260
261/// Extract the flag key from a flag word for lookup in available_flags map
262/// Handles both long flags (--flag, --flag=value) and short flags (-f)
263fn get_flag_key(word: &str) -> &str {
264    if word.starts_with("--") {
265        // Long flag: strip =value if present
266        word.split_once('=').map(|(k, _)| k).unwrap_or(word)
267    } else if let Some((end, _)) = word.char_indices().nth(2) {
268        // Short flag: the dash and one letter, which is one character and not
269        // necessarily one byte.
270        &word[0..end]
271    } else {
272        word
273    }
274}
275
276/// Where a value came from, when it did not come from the command line.
277///
278/// About the *value*, not the flag. `--color` typed bare with `default_missing` has a
279/// token for the flag and none for the value, and that distinction is the whole question
280/// a spec author is asking when they ask why `--color` came out `always`. Values that were
281/// typed are attributed to the token that carried them instead — see [`TokenRole::Value`].
282#[derive(Debug, Clone, PartialEq, Eq)]
283#[non_exhaustive]
284pub enum ValueOrigin {
285    /// A flag that takes a value was given without one, so the declaration supplied it:
286    /// `default_missing`, or the empty tri-state a bare `value_optional` flag records.
287    /// One variant for both, because from argv's side the same thing happened — the flag
288    /// was typed and the value was not.
289    DefaultMissing,
290    /// An environment variable, named.
291    ///
292    /// Named because a flag may list several — `env`, `env_fallback` and `deprecated_env`,
293    /// folded together by [`SpecFlag::env_names`] — and "it came from the environment" does
294    /// not say which declaration fired or which one to delete.
295    Env(String),
296    /// A declared `default`, on the flag or on the flag's argument.
297    ///
298    /// Not two variants: the precedence between them is a spec-authoring oddity rather than
299    /// a fact about the value, and `usage lint` is the place to complain about declaring
300    /// both.
301    Default,
302    /// A `default_if` whose condition matched, with the condition that decided it. The
303    /// selector alone is ambiguous — several conditions may name it with different `when`
304    /// values.
305    DefaultIf {
306        selector: String,
307        when: Option<String>,
308    },
309}
310
311/// What one word of the command line became.
312///
313/// Several because a single token can do more than one thing: `-abc` sets three flags,
314/// `-j8` is a flag and its value.
315#[derive(Debug, Clone)]
316#[non_exhaustive]
317pub enum TokenRole {
318    /// argv[0]. Also a `Command` when a multicall symlink makes the basename a word.
319    Program,
320    /// Selected a subcommand.
321    Command { name: String },
322    /// Named a flag, in this spelling. `negated` for the `negate` form.
323    Flag {
324        flag: Arc<SpecFlag>,
325        spelling: String,
326        negated: bool,
327    },
328    /// Supplied a flag's value. Several values when a `delimiter` split the word.
329    Value {
330        flag: Arc<SpecFlag>,
331        values: Vec<String>,
332        /// Whether the value rode along on the flag's own token (`--env=prod`, `-j8`)
333        /// rather than following it as its own word.
334        attached: bool,
335    },
336    /// Filled a positional argument. Several values when a `delimiter` split the word.
337    Arg {
338        arg: Arc<SpecArg>,
339        values: Vec<String>,
340    },
341    /// An explicit `--`, consumed as a separator.
342    Separator,
343    /// A word the parser answers itself rather than binding: `--help`, `-h`, `--version`,
344    /// `-V`. The parse stops here and the answer travels as an error carrying the text, so
345    /// without a role the word reads as having done nothing while a whole help page arrives
346    /// in the error list.
347    Builtin { spelling: String },
348    /// A declared `value_terminator`, consumed to end a run of values. `ends` names the
349    /// declaration whose run it closed — the word is not one of that run's values, which is
350    /// the whole reason it was declared.
351    ValueTerminator { ends: String },
352    /// A declared `restart_token`: the positional cursor and the values it had filled start
353    /// over here. Recorded because the words before it are still in the report, and without
354    /// this row they look like they filled arguments that then came back empty.
355    Restart,
356    /// A flag-like word no declaration matched. `bound_as` is the positional that took it
357    /// under `unknown_flags="value"`, and `None` when the word was refused.
358    UnknownFlag { bound_as: Option<Arc<SpecArg>> },
359    /// The word reached a declaration that would not take it, and was dropped. Without this
360    /// the token reads as having done nothing, which is the one thing it did not do.
361    Refused { reason: String },
362    /// Forwarded to an external subcommand.
363    External,
364    /// The parser stopped before this word — a help request, a refused value.
365    Unread,
366    /// Filled a sigil-classified positional after removing its declared prefix.
367    Sigil {
368        arg: Arc<SpecArg>,
369        sigil: String,
370        values: Vec<String>,
371    },
372    /// Ended one instance of a repeatable clause and began the next.
373    ClauseSeparator { name: String },
374}
375
376/// One word of the command line, and what it became.
377#[derive(Debug, Clone)]
378#[non_exhaustive]
379pub struct TokenBinding {
380    /// Position in the argv slice the parse was given, argv[0] included.
381    pub index: usize,
382    pub word: String,
383    /// Roles a word the parser made up contributed, folded onto the token it was derived
384    /// from: the tail of a short bundle onto the bundle, a multicall applet name onto
385    /// argv[0]. `word` is what the caller wrote, not what the parser read.
386    pub synthesized: bool,
387    pub roles: Vec<TokenRole>,
388}
389
390#[non_exhaustive]
391pub struct ParseOutput {
392    pub cmd: SpecCommand,
393    pub cmds: Vec<SpecCommand>,
394    pub args: IndexMap<Arc<SpecArg>, ParseValue>,
395    /// Separator-delimited positional instances, keyed by clause name.
396    pub clauses: IndexMap<String, Vec<IndexMap<Arc<SpecArg>, ParseValue>>>,
397    /// Per-instance flags belonging to a repeatable clause, keyed by clause name.
398    pub clause_flags: IndexMap<String, Vec<IndexMap<Arc<SpecFlag>, ParseValue>>>,
399    pub flags: IndexMap<Arc<SpecFlag>, ParseValue>,
400    /// What each word of the command line became, in argv order, one entry per word.
401    ///
402    /// The token half of provenance; [`ParseOutput::flag_origins`] and
403    /// [`ParseOutput::arg_origins`] are the other half. A table keyed by token cannot show
404    /// a value that came from nowhere in argv, and a table keyed by declaration cannot show
405    /// a token that bound to nothing, so both exist.
406    pub tokens: Vec<TokenBinding>,
407    /// Where a flag's value came from when it did not come from argv, in the order the
408    /// fallbacks fired. Keyed as [`ParseOutput::flags`] is.
409    ///
410    /// A list rather than one origin: repeated bare occurrences of a `var` flag each take a
411    /// `default_missing` value, so one flag can have several.
412    pub flag_origins: IndexMap<Arc<SpecFlag>, Vec<ValueOrigin>>,
413    /// Where an argument's value came from when it did not come from argv. Keyed as
414    /// [`ParseOutput::args`] is.
415    pub arg_origins: IndexMap<Arc<SpecArg>, Vec<ValueOrigin>>,
416    /// Flags a later occurrence removed, and the flag that removed them.
417    ///
418    /// The overriding name is the half a caller needs: the fallback phase silently declines
419    /// to fill an overridden flag, so "why is `--quiet` unset when its default says
420    /// otherwise" has no answer without it.
421    pub overridden_flags: BTreeMap<String, String>,
422    /// Every flag the parser recognizes at this point, keyed by each of its aliases
423    /// (`--long`, `-s`, negations).
424    ///
425    /// This includes flags that only remain recognized because they may appear *before* a
426    /// mounted command — see [`ParseOutput::completion_flags`] for the set a completion
427    /// should offer.
428    pub available_flags: BTreeMap<String, Arc<SpecFlag>>,
429    /// Every flag object the parse brought in from a mounted program, by identity. Kept
430    /// rather than derived, because the descent merges, re-declares and shadows flags and no
431    /// later reading of the command chain can tell whose a merged flag is. See
432    /// [`ParseOutput::is_mounted_flag`].
433    mounted_flags: Vec<Arc<SpecFlag>>,
434    pub flag_awaiting_value: Vec<Arc<SpecFlag>>,
435    pub errors: Vec<UsageErr>,
436    /// Deprecated declarations this command line used, for the caller to render when its
437    /// logging is up. Empty from [`parse_partial`]: a half-typed line being completed has
438    /// not used anything yet.
439    pub warnings: Vec<Warning>,
440    /// The positional argument the next word would have filled, i.e. where the parser's
441    /// cursor stopped. `None` once every argument is satisfied.
442    ///
443    /// Completions need exactly this: the parser already accounts for `var_max`, for
444    /// `restart_token` rewinds, and for the jump an explicit `--` performs onto a
445    /// `double_dash="required"` argument, so re-deriving it from `args` would disagree.
446    pub next_arg: Option<Arc<SpecArg>>,
447    /// Whether an explicit `--` was consumed *as a separator*.
448    ///
449    /// A `--` that `double_dash="preserve"` keeps as a value does not count: it is a value
450    /// of the variadic argument collecting it, not a separator, so it does not unlock a
451    /// `double_dash="required"` argument.
452    pub double_dash_seen: bool,
453    /// Remaining argv captured when an unmatched word was forwarded as an external
454    /// subcommand: the command name first, then every token after it.
455    ///
456    /// Absent when no external command was selected. See [`SpecCommand::external_subcommand`].
457    pub external: Option<Vec<String>>,
458}
459
460impl ParseOutput {
461    /// Whether `flag`, a flag this parse recognized, belongs to a mounted program rather than
462    /// to the CLI that mounted it.
463    ///
464    /// Answered from the descent itself: a flag a mounted command declared (or the root flags a
465    /// mount merged into the command it sits on) is the mounted program's, and a flag the
466    /// parser built by merging a re-declaration into an inherited global is whoever's that
467    /// global was. Compared by identity, so pass a flag this parse handed out, such as one in
468    /// [`ParseOutput::flag_awaiting_value`] or [`ParseOutput::available_flags`].
469    pub fn is_mounted_flag(&self, flag: &Arc<SpecFlag>) -> bool {
470        self.mounted_flags
471            .iter()
472            .any(|known| Arc::ptr_eq(known, flag))
473    }
474
475    /// Bring `cmd`'s flags into [`ParseOutput::available_flags`] the way a descent does,
476    /// remembering which of them came from a mounted program.
477    fn merge_command_flags(&mut self, cmd: &SpecCommand, crossing_mount: bool) {
478        let flags = gather_flags(cmd);
479        if cmd.mounted || cmd.flags_from_mount {
480            self.mounted_flags.extend(flags.values().cloned());
481        }
482        for (merged, origin) in
483            merge_subcommand_flags(&mut self.available_flags, flags, crossing_mount)
484        {
485            if self
486                .mounted_flags
487                .iter()
488                .any(|known| Arc::as_ptr(known) as usize == origin)
489            {
490                self.mounted_flags.push(merged);
491            }
492        }
493    }
494
495    /// The flags a completion should offer for the parsed command.
496    ///
497    /// Usually every recognized flag, i.e. [`ParseOutput::available_flags`]. Once a mounted
498    /// command has been reached, though, the commands above it belong to the mounting CLI and
499    /// their flags are not accepted there — mise, for example, forwards everything after a task
500    /// name to the task itself — so only the flags declared from the mount boundary down are
501    /// offered. Those globals stay in `available_flags` because they may legitimately appear
502    /// *before* the mounted command.
503    pub fn completion_flags(&self) -> BTreeMap<String, Arc<SpecFlag>> {
504        let Some(boundary) = self.cmds.iter().position(|cmd| cmd.mounted) else {
505            return self.available_flags.clone();
506        };
507        // A mount can also merge flags from its spec's root into the command it is mounted on
508        // (`SpecCommand::flags_from_mount`). Those describe the mounted program too, so the
509        // replay starts one level up to inherit its globals.
510        let start = match boundary.checked_sub(1) {
511            Some(prev) if self.cmds[prev].flags_from_mount => prev,
512            _ => boundary,
513        };
514        // Re-run the descent from there, which starts with no inherited flags. Below the
515        // boundary the mounted program's commands are ordinary commands, so the descents use
516        // the same merge as the real parse.
517        let mut offered = gather_flags(&self.cmds[start]);
518        for cmd in &self.cmds[start + 1..] {
519            merge_subcommand_flags(&mut offered, gather_flags(cmd), false);
520        }
521        offered
522    }
523}
524
525#[derive(Debug, Clone)]
526pub enum ParseValue {
527    Bool(bool),
528    String(String),
529    MultiBool(Vec<bool>),
530    MultiString(Vec<String>),
531}
532
533impl ParseValue {
534    pub fn try_as_bool(self) -> Option<bool> {
535        match self {
536            Self::Bool(value) => Some(value),
537            _ => None,
538        }
539    }
540
541    pub const fn try_as_bool_ref(&self) -> Option<&bool> {
542        match self {
543            Self::Bool(value) => Some(value),
544            _ => None,
545        }
546    }
547
548    pub fn try_as_bool_mut(&mut self) -> Option<&mut bool> {
549        match self {
550            Self::Bool(value) => Some(value),
551            _ => None,
552        }
553    }
554
555    pub fn try_as_string(self) -> Option<String> {
556        match self {
557            Self::String(value) => Some(value),
558            _ => None,
559        }
560    }
561
562    pub const fn try_as_string_ref(&self) -> Option<&String> {
563        match self {
564            Self::String(value) => Some(value),
565            _ => None,
566        }
567    }
568
569    pub fn try_as_string_mut(&mut self) -> Option<&mut String> {
570        match self {
571            Self::String(value) => Some(value),
572            _ => None,
573        }
574    }
575
576    pub fn try_as_multi_bool(self) -> Option<Vec<bool>> {
577        match self {
578            Self::MultiBool(value) => Some(value),
579            _ => None,
580        }
581    }
582
583    pub const fn try_as_multi_bool_ref(&self) -> Option<&Vec<bool>> {
584        match self {
585            Self::MultiBool(value) => Some(value),
586            _ => None,
587        }
588    }
589
590    pub fn try_as_multi_bool_mut(&mut self) -> Option<&mut Vec<bool>> {
591        match self {
592            Self::MultiBool(value) => Some(value),
593            _ => None,
594        }
595    }
596
597    pub fn try_as_multi_string(self) -> Option<Vec<String>> {
598        match self {
599            Self::MultiString(value) => Some(value),
600            _ => None,
601        }
602    }
603
604    pub const fn try_as_multi_string_ref(&self) -> Option<&Vec<String>> {
605        match self {
606            Self::MultiString(value) => Some(value),
607            _ => None,
608        }
609    }
610
611    pub fn try_as_multi_string_mut(&mut self) -> Option<&mut Vec<String>> {
612        match self {
613            Self::MultiString(value) => Some(value),
614            _ => None,
615        }
616    }
617}
618
619/// The deprecated declarations argv itself named: the commands it descended through, and the
620/// flags it bound.
621///
622/// Called before the environment and defaults have filled anything, because afterwards nothing
623/// distinguishes a flag the user typed from one a variable supplied — and the two are reported
624/// differently, at the point where each is applied.
625///
626/// The root is skipped. A `deprecated` root would otherwise warn on every invocation of the CLI,
627/// including `--help`, and the compiled parser reports selected commands rather than the one the
628/// process already is.
629fn collect_deprecations(out: &mut ParseOutput) {
630    for cmd in out.cmds.iter().skip(1) {
631        if cmd.deprecated.is_none()
632            && cmd.deprecated_warn_at.is_none()
633            && cmd.deprecated_remove_at.is_none()
634        {
635            continue;
636        }
637        out.warnings.push(Warning::command(
638            cmd.name.clone(),
639            cmd.deprecated.clone(),
640            cmd.deprecated_warn_at.clone(),
641            cmd.deprecated_remove_at.clone(),
642        ));
643    }
644    for flag in out.flags.keys() {
645        if let Some(warning) = flag_deprecation(flag) {
646            out.warnings.push(warning);
647        }
648    }
649}
650
651/// A warning for a flag that was used, if its declaration is deprecated at all.
652fn flag_deprecation(flag: &SpecFlag) -> Option<Warning> {
653    if flag.deprecated.is_none()
654        && flag.deprecated_warn_at.is_none()
655        && flag.deprecated_remove_at.is_none()
656    {
657        return None;
658    }
659    Some(Warning::flag(
660        flag_spelling(flag),
661        flag.deprecated.clone(),
662        flag.deprecated_warn_at.clone(),
663        flag.deprecated_remove_at.clone(),
664    ))
665}
666
667/// A flag named the way the user names it. The spec's name for it has no dashes, and a warning
668/// about `old-flag` would be about a word nobody typed.
669fn flag_spelling(flag: &SpecFlag) -> String {
670    flag.long
671        .first()
672        .map(|long| format!("--{long}"))
673        .or_else(|| flag.short.first().map(|short| format!("-{short}")))
674        .unwrap_or_else(|| flag.name.clone())
675}
676
677/// The name this flag reads first, which is what to use instead of a deprecated alias.
678fn flag_current_env(flag: &SpecFlag) -> Option<String> {
679    flag.env
680        .clone()
681        .or_else(|| flag.env_fallback.first().cloned())
682}
683
684fn flag_env_is_deprecated(flag: &SpecFlag, name: &str) -> bool {
685    flag.deprecated_env.iter().any(|declared| declared == name)
686}
687
688/// The same two questions for a positional, which has aliases but no `deprecated` of its own.
689fn arg_current_env(arg: &SpecArg) -> Option<String> {
690    arg.env
691        .clone()
692        .or_else(|| arg.env_fallback.first().cloned())
693}
694
695fn arg_env_is_deprecated(arg: &SpecArg, name: &str) -> bool {
696    arg.deprecated_env.iter().any(|declared| declared == name)
697}
698
699/// The first of `names` that is set, and which one it was.
700///
701/// `env_names()` yields the current name, then the declared fallbacks, then the deprecated
702/// aliases, so the winner's identity is what says whether a value arrived through an alias.
703/// Deciding that a second time, from the outside, would be a copy of this precedence rule free to
704/// disagree with it.
705fn first_set_env<'a>(
706    mut names: impl Iterator<Item = &'a str>,
707    get_env: &impl Fn(&str) -> Option<String>,
708) -> Option<(&'a str, String)> {
709    names.find_map(|name| get_env(name).map(|value| (name, value)))
710}
711
712/// Builder for parsing command-line arguments with custom options.
713///
714/// Use this when you need to customize parsing behavior, such as providing
715/// a custom environment variable map instead of using the process environment.
716///
717/// # Example
718/// ```
719/// use std::collections::HashMap;
720/// use usage::Spec;
721/// use usage::parse::Parser;
722///
723/// let spec: Spec = r#"flag "--name <name>" env="NAME""#.parse().unwrap();
724/// let env: HashMap<String, String> = [("NAME".into(), "john".into())].into();
725///
726/// let result = Parser::new(&spec)
727///     .with_env(env)
728///     .parse(&["cmd".into()])
729///     .unwrap();
730/// ```
731#[non_exhaustive]
732pub struct Parser<'a> {
733    spec: &'a Spec,
734    env: Option<HashMap<String, String>>,
735    mount_outputs: Option<HashMap<String, String>>,
736    run_commands: bool,
737}
738
739impl<'a> Parser<'a> {
740    /// Create a new parser for the given spec.
741    pub fn new(spec: &'a Spec) -> Self {
742        Self {
743            spec,
744            env: None,
745            mount_outputs: None,
746            run_commands: true,
747        }
748    }
749
750    /// Use a custom environment variable map instead of the process environment.
751    ///
752    /// This is useful when parsing for tasks in a monorepo where the env vars
753    /// come from a child config file rather than the current process environment.
754    pub fn with_env(mut self, env: HashMap<String, String>) -> Self {
755        self.env = Some(env);
756        self
757    }
758
759    /// Inject deterministic outputs for mount commands instead of executing them.
760    ///
761    /// Keys are the exact `run` strings declared by mount nodes and values are the
762    /// usage specs those commands would print. When this is set, every encountered
763    /// mount must have an entry. Production parsing remains process-backed unless a
764    /// caller explicitly opts into injection.
765    pub fn with_mount_outputs(mut self, outputs: HashMap<String, String>) -> Self {
766        self.mount_outputs = Some(outputs);
767        self
768    }
769
770    /// Never run a `choices run=` command while parsing.
771    ///
772    /// For a caller that inspects a command line rather than acting on it. A value that the
773    /// declared choices do not accept is let through unchecked instead of being checked
774    /// against the command's output, and a help page describes the command rather than
775    /// listing what it prints. Mounts are unaffected; see [`Parser::with_mount_outputs`].
776    pub fn without_running_commands(mut self) -> Self {
777        self.run_commands = false;
778        self
779    }
780
781    /// Parse the input arguments.
782    ///
783    /// Returns the parsed arguments and flags, with defaults and env vars applied.
784    pub fn parse(self, input: &[String]) -> Result<ParseOutput, miette::Error> {
785        let out = self.parse_collecting(input)?;
786        if let Some(err) = out
787            .errors
788            .iter()
789            .find(|e| matches!(e, UsageErr::Help(_) | UsageErr::Version(_)))
790        {
791            bail!("{err}");
792        }
793        if !out.errors.is_empty() {
794            bail!("{}", out.errors.iter().map(|e| e.to_string()).join("\n"));
795        }
796        Ok(out)
797    }
798
799    /// Everything the parse learned, whether or not it succeeded.
800    ///
801    /// [`Parser::parse`] wants the first error and nothing else, which is right for a
802    /// caller about to act on a command line. A caller that wants to *explain* one wants
803    /// the opposite: the bindings that worked and every complaint about the rest, since a
804    /// report saying only "missing required <src>" is the report you already had.
805    ///
806    /// Failures that stop the parse dead — a mount that will not run, a word no
807    /// declaration can take — still come back as `Err`. There is no output to describe in
808    /// those cases; see [`Parser::explain`] for what to do about it.
809    pub fn explain(self, input: &[String]) -> Result<ParseOutput, miette::Error> {
810        self.parse_collecting(input)
811    }
812
813    /// The binding phase's own answer for a line [`Parser::explain`] refused.
814    ///
815    /// `Ok` when the binding phase finished and the failure came after it — a flag left
816    /// waiting for a value, say. Everything argv supplied is there and only the
817    /// environment-and-defaults phase is missing.
818    ///
819    /// `Err` when the binding phase is where it died, leaving the tokens it had attributed
820    /// by then. Those words are most of what a report is for: "no declaration takes `bogus`"
821    /// is more useful next to the three tokens that did bind than on its own. The word that
822    /// caused the failure carries a role saying so, and everything still queued behind it is
823    /// [`TokenRole::Unread`], for the two failures a command line reaches on its own — a
824    /// word nothing declares, and a flag a strict spec refuses. A failure in the spec rather
825    /// than in the line, such as a mount that will not run, stops the trace where it stopped
826    /// and the words past it carry no role.
827    pub fn explain_refused(self, input: &[String]) -> Result<ParseOutput, Vec<TokenBinding>> {
828        let _no_runs = (!self.run_commands).then(crate::spec::choices::NoRunScope::enter);
829        let mut trace = Trace::new(input);
830        match parse_partial_traced(
831            self.spec,
832            input,
833            self.env.as_ref(),
834            self.mount_outputs.as_ref(),
835            MountTiming::WhenAWordIsUnknown,
836            true,
837            &mut trace,
838        ) {
839            // A parse that got as far as stopping normally already moved its tokens onto the
840            // output, which is where a caller should read them from.
841            Ok((out, _)) => Ok(out),
842            Err(_) => Err(trace.tokens),
843        }
844    }
845
846    fn parse_collecting(self, input: &[String]) -> Result<ParseOutput, miette::Error> {
847        // Held across both phases: defaults are checked against the same `choices run=`
848        // output the words were.
849        let _runs = crate::spec::choices::RunScope::enter();
850        let _no_runs = (!self.run_commands).then(crate::spec::choices::NoRunScope::enter);
851        let custom_env = self.env.as_ref();
852        let (mut out, overridden_flags) = parse_partial_with_env(
853            self.spec,
854            input,
855            custom_env,
856            self.mount_outputs.as_ref(),
857            MountTiming::WhenAWordIsUnknown,
858            false,
859        )?;
860        restore_current_clause(&mut out);
861        trace!("{out:?}");
862
863        // A flag still waiting for a value never got one, so the command line ended
864        // mid-flag. `parse_partial` leaves this for completions to look at — a
865        // half-typed `--jobs ` is exactly what a completion is asked about — but a
866        // full parse has nothing left to wait for, and dropping the flag silently
867        // made a forgotten value look like a working command.
868        while try_bind_default_missing(
869            &mut out.flags,
870            &mut out.flag_awaiting_value,
871            custom_env,
872            &mut out.flag_origins,
873        )? {}
874        if let Some(flag) = out.flag_awaiting_value.first() {
875            let token = flag
876                .long
877                .first()
878                .map(|l| format!("--{l}"))
879                .or_else(|| flag.short.first().map(|s| format!("-{s}")))
880                .unwrap_or_else(|| flag.name.clone());
881            let rendered = input.join(" ");
882            let span = rendered
883                .rfind(&token)
884                .map(|at| (at, token.len()))
885                .unwrap_or((0, 0));
886            return Err(UsageErr::InvalidFlag {
887                token,
888                reason: "requires an argument".to_string(),
889                span: span.into(),
890                input: rendered,
891            }
892            .into());
893        }
894
895        // Before the environment and defaults have their turn, because both mark a field as
896        // filled and only argv can be reported as something the user typed. Env is reported
897        // where it is applied, below; a default is nobody's request and reports nothing.
898        collect_deprecations(&mut out);
899
900        let get_env = |key: &str| -> Option<String> {
901            if let Some(env_map) = custom_env {
902                env_map.get(key).cloned()
903            } else {
904                std::env::var(key).ok()
905            }
906        };
907
908        // Apply env vars and defaults for args
909        //
910        // Not `skip(out.args.len())`: an explicit `--` can jump the parser's cursor past an arg
911        // that stayed empty, leaving a gap that makes the fill count a wrong starting offset.
912        for arg in active_args(&out.cmd) {
913            // Clause instances contain argv only: defaults and environment values do not
914            // manufacture fields inside a repeated group.
915            if out.cmd.clause.is_some() {
916                break;
917            }
918            if out.args.contains_key(arg) {
919                continue;
920            }
921            if let Some((env_name, env_value)) = first_set_env(arg.env_names(), &get_env) {
922                if arg_env_is_deprecated(arg, env_name) {
923                    out.warnings
924                        .push(Warning::env(env_name, arg_current_env(arg)));
925                }
926                let values = split_fallback_values(std::slice::from_ref(&env_value), arg.delimiter);
927                validate_choice_values(
928                    ChoiceTarget::arg(arg),
929                    &values,
930                    arg.choices.as_ref(),
931                    custom_env,
932                )?;
933                let parsed = if arg.var {
934                    validate_arg_fallback_count(arg, values.len(), &mut out.errors);
935                    ParseValue::MultiString(values)
936                } else {
937                    ParseValue::String(values.into_iter().next().unwrap_or_default())
938                };
939                out.args.insert(Arc::new(arg.clone()), parsed);
940                out.arg_origins
941                    .entry(Arc::new(arg.clone()))
942                    .or_default()
943                    .push(ValueOrigin::Env(env_name.to_string()));
944                continue;
945            }
946            if !arg.default.is_empty() {
947                // Consider var when deciding the type of default return value
948                if arg.var {
949                    let values = split_fallback_values(&arg.default, arg.delimiter);
950                    validate_arg_fallback_count(arg, values.len(), &mut out.errors);
951                    validate_choice_values(
952                        ChoiceTarget::arg(arg),
953                        &values,
954                        arg.choices.as_ref(),
955                        custom_env,
956                    )?;
957                    // For var=true, always return a vec (MultiString)
958                    out.args
959                        .insert(Arc::new(arg.clone()), ParseValue::MultiString(values));
960                    out.arg_origins
961                        .entry(Arc::new(arg.clone()))
962                        .or_default()
963                        .push(ValueOrigin::Default);
964                } else {
965                    validate_choice_value(
966                        ChoiceTarget::arg(arg),
967                        &arg.default[0],
968                        arg.choices.as_ref(),
969                        custom_env,
970                    )?;
971                    // For var=false, return the first default value as String
972                    out.args.insert(
973                        Arc::new(arg.clone()),
974                        ParseValue::String(arg.default[0].clone()),
975                    );
976                    out.arg_origins
977                        .entry(Arc::new(arg.clone()))
978                        .or_default()
979                        .push(ValueOrigin::Default);
980                }
981            }
982        }
983
984        // Environment first, for every flag, so a `default_if` can see a sibling
985        // that was filled from env. Applying both in one pass would make the
986        // answer depend on declaration order: `--bin-names` before `--json`
987        // would miss `EX_JSON=1`.
988        let flags: Vec<Arc<SpecFlag>> = out
989            .available_flags
990            .values()
991            .filter(|flag| !is_clause_scoped_flag(&out, flag))
992            .cloned()
993            .collect();
994        for flag in &flags {
995            if out.flags.contains_key(flag) || overridden_flags.contains(&flag.name) {
996                continue;
997            }
998            if let Some((env_name, env_value)) = first_set_env(flag.env_names(), &get_env) {
999                // The flag's own deprecation before the alias's, which is the order the
1000                // compiled parser reports them in: it walks a command's flags and then its
1001                // aliases. Using a deprecated flag through a variable is still using it.
1002                if let Some(warning) = flag_deprecation(flag) {
1003                    out.warnings.push(warning);
1004                }
1005                if flag_env_is_deprecated(flag, env_name) {
1006                    out.warnings
1007                        .push(Warning::env(env_name, flag_current_env(flag)));
1008                }
1009                if let Some(arg) = flag.arg.as_ref() {
1010                    let values =
1011                        split_fallback_values(std::slice::from_ref(&env_value), arg.delimiter);
1012                    validate_choice_values(
1013                        ChoiceTarget::option(flag),
1014                        &values,
1015                        arg.choices.as_ref(),
1016                        custom_env,
1017                    )?;
1018                    let parsed = if flag.var || arg.var {
1019                        if flag.var {
1020                            validate_flag_fallback_count(flag, values.len(), &mut out.errors);
1021                        }
1022                        if arg.var {
1023                            validate_flag_arg_fallback_count(
1024                                flag,
1025                                arg,
1026                                values.len(),
1027                                &mut out.errors,
1028                            );
1029                        }
1030                        ParseValue::MultiString(values)
1031                    } else {
1032                        ParseValue::String(values.into_iter().next().unwrap_or_default())
1033                    };
1034                    out.flags.insert(Arc::clone(flag), parsed);
1035                } else {
1036                    let is_true = matches!(env_value.as_str(), "1" | "true" | "True" | "TRUE");
1037                    out.flags
1038                        .insert(Arc::clone(flag), ParseValue::Bool(is_true));
1039                }
1040                out.flag_origins
1041                    .entry(Arc::clone(flag))
1042                    .or_default()
1043                    .push(ValueOrigin::Env(env_name.to_string()));
1044            }
1045        }
1046        // Decide every `default_if` against argv+env only. Binding as we go would put
1047        // a default into `out.flags` and make the next flag's condition treat it as
1048        // explicit — Go's `Given()` and the derive's `__given_*` both ignore defaults
1049        // here, so an unconditional `default` on `--json` must not fire
1050        // `default_if "--json"`.
1051        let mut from_default_if: Vec<(Arc<SpecFlag>, crate::SpecDefaultIf)> = Vec::new();
1052        for flag in &flags {
1053            if out.flags.contains_key(flag) || overridden_flags.contains(&flag.name) {
1054                continue;
1055            }
1056            if let Some(condition) = flag.default_if.iter().find(|condition| {
1057                default_if_condition_matches(condition, &out, &overridden_flags, custom_env)
1058            }) {
1059                from_default_if.push((Arc::clone(flag), condition.clone()));
1060            }
1061        }
1062        for (flag, condition) in &from_default_if {
1063            // The whole condition, not just the value: several conditions may name the same
1064            // selector with different `when` values, so the selector alone does not say
1065            // which one fired.
1066            bind_flag_fallback(
1067                flag,
1068                std::slice::from_ref(&condition.value),
1069                &mut out,
1070                custom_env,
1071                ValueOrigin::DefaultIf {
1072                    selector: condition.selector.clone(),
1073                    when: condition.when.clone(),
1074                },
1075            )?;
1076        }
1077        for flag in &flags {
1078            if out.flags.contains_key(flag) || overridden_flags.contains(&flag.name) {
1079                continue;
1080            }
1081            if !flag.default.is_empty() {
1082                bind_flag_fallback(
1083                    flag,
1084                    &flag.default,
1085                    &mut out,
1086                    custom_env,
1087                    ValueOrigin::Default,
1088                )?;
1089                continue;
1090            }
1091            if let Some(arg) = flag.arg.as_ref()
1092                && !arg.default.is_empty()
1093            {
1094                bind_flag_fallback(
1095                    flag,
1096                    &arg.default,
1097                    &mut out,
1098                    custom_env,
1099                    ValueOrigin::Default,
1100                )?;
1101            }
1102        }
1103        // The binding phase leaves the last clause instance in `args`/`flags` so
1104        // completion can inspect it. A full parse closes it before applying scoped
1105        // fallbacks: defaults and environment values fill instances that argv made,
1106        // but never manufacture a repeated group on their own.
1107        finalize_current_clause(&mut out);
1108        let clause_explicit = apply_clause_flag_fallbacks(&mut out, &overridden_flags, custom_env)?;
1109        validate_clause_relationships(
1110            &mut out,
1111            &overridden_flags,
1112            custom_env,
1113            clause_explicit.as_deref(),
1114        );
1115        // Declarative value validation is deliberately post-binding. Defaults and
1116        // environment fallbacks have landed by here, and delimiters were already split
1117        // while binding. Like clap's value parsers, a declaration judges each resulting
1118        // raw value independently.
1119        for (arg, parsed) in &out.args {
1120            validate_expression(
1121                &arg.name,
1122                arg.validate.as_deref(),
1123                arg.validate_error.as_deref(),
1124                parsed,
1125                &mut out.errors,
1126            );
1127        }
1128        if let Some(clause) = &out.cmd.clause {
1129            let mut clause_errors = Vec::new();
1130            for (index, instance) in out
1131                .clauses
1132                .get(&clause.name)
1133                .into_iter()
1134                .flatten()
1135                .enumerate()
1136            {
1137                for arg in &clause.args {
1138                    let Some(value) = instance.get(arg) else {
1139                        if arg.required {
1140                            clause_errors.push(UsageErr::MissingClauseArg {
1141                                clause: clause.name.clone(),
1142                                instance: index + 1,
1143                                arg: arg.name.clone(),
1144                            });
1145                        }
1146                        continue;
1147                    };
1148                    if let (true, ParseValue::MultiString(values)) = (arg.var, value) {
1149                        if let Some(min) = arg.var_min
1150                            && values.len() < min
1151                        {
1152                            clause_errors.push(UsageErr::VarArgTooFew {
1153                                name: format!(
1154                                    "{} instance {}: {}",
1155                                    clause.name,
1156                                    index + 1,
1157                                    arg.name
1158                                ),
1159                                min,
1160                                got: values.len(),
1161                            });
1162                        }
1163                        if let Some(max) = arg.var_max
1164                            && values.len() > max
1165                        {
1166                            clause_errors.push(UsageErr::VarArgTooMany {
1167                                name: format!(
1168                                    "{} instance {}: {}",
1169                                    clause.name,
1170                                    index + 1,
1171                                    arg.name
1172                                ),
1173                                max,
1174                                got: values.len(),
1175                            });
1176                        }
1177                    }
1178                }
1179            }
1180            out.errors.extend(clause_errors);
1181        }
1182        let clause_flag_names = out
1183            .cmd
1184            .clause
1185            .iter()
1186            .flat_map(|clause| &clause.flags)
1187            .map(|flag| flag.name.as_str())
1188            .collect::<HashSet<_>>();
1189        for (flag, parsed) in out
1190            .flags
1191            .iter()
1192            .filter(|(flag, _)| !clause_flag_names.contains(flag.name.as_str()))
1193        {
1194            if let Some(arg) = &flag.arg {
1195                validate_expression(
1196                    &flag.name,
1197                    arg.validate.as_deref(),
1198                    arg.validate_error.as_deref(),
1199                    parsed,
1200                    &mut out.errors,
1201                );
1202            }
1203        }
1204        // Against the environment this parse read from, so a caller that supplies its own map
1205        // is judged on that map and not on the process it happens to run in. The commands it
1206        // walked count as well as the spec's: a mount brings its commands in only now. A mount
1207        // this command line never needed is not run for the check — its own flags and timing
1208        // belong to the parse, not here — so what only it declares goes in `allow`.
1209        //
1210        // Not at all for a help or version request: the user asking how to fix the variable
1211        // should get the answer, and nothing should run on the way to it.
1212        let answering = out
1213            .errors
1214            .iter()
1215            .any(|e| matches!(e, UsageErr::Help(_) | UsageErr::Version(_)));
1216        if let Some(unknown_env) = self.spec.unknown_env.as_ref().filter(|_| !answering) {
1217            let process: Vec<std::ffi::OsString>;
1218            // A supplied map is read by exact key, so it is checked by exact key: on Windows a
1219            // map holding `ex_port` does not fill `EX_PORT`, and saying nothing about it would
1220            // hide the very mistake this check exists for. The process environment folds case
1221            // there, and so does its check.
1222            let (names, exact): (Vec<&std::ffi::OsStr>, bool) = match custom_env {
1223                Some(env) => (env.keys().map(std::ffi::OsStr::new).collect(), true),
1224                None => {
1225                    process = std::env::vars_os().map(|(name, _)| name).collect();
1226                    (process.iter().map(|n| n.as_os_str()).collect(), false)
1227                }
1228            };
1229            let unknown =
1230                unknown_env.unknown_with(self.spec, &out.cmds, names.iter().copied(), exact);
1231            if !unknown.is_empty() {
1232                out.errors.push(UsageErr::UnknownEnv {
1233                    prefix: unknown_env.prefix.clone(),
1234                    names: unknown,
1235                });
1236            }
1237        }
1238        // Applied once, here, because this is where the CLI's own version is known: a
1239        // `deprecated_warn_at` the spec has not reached yet is an author saying *not yet*.
1240        crate::warn::retain_reached(&mut out.warnings, self.spec.version.as_deref());
1241        Ok(out)
1242    }
1243}
1244
1245/// Parse command-line arguments according to a spec.
1246///
1247/// Returns the parsed arguments and flags, with defaults and env vars applied.
1248/// Uses `std::env::var` for environment variable lookups.
1249///
1250/// For custom environment variable handling, use [`Parser`] instead.
1251#[must_use = "parsing result should be used"]
1252pub fn parse(spec: &Spec, input: &[String]) -> Result<ParseOutput, miette::Error> {
1253    Parser::new(spec).parse(input)
1254}
1255
1256/// Parse the words before the cursor for completion.
1257///
1258/// Like [`parse_partial`], except that `default_subcommand_on_empty` is not applied. The word
1259/// under the cursor is still to be typed, so the line is not an empty invocation: the root's
1260/// subcommands and flags are all still valid next words, and routing into the default command
1261/// would hide them.
1262#[must_use = "parsing result should be used"]
1263pub fn parse_partial_for_completion(
1264    spec: &Spec,
1265    input: &[String],
1266) -> Result<ParseOutput, miette::Error> {
1267    if spec.default_subcommand_on_empty {
1268        let mut spec = spec.clone();
1269        spec.default_subcommand_on_empty = false;
1270        return parse_partial(&spec, input);
1271    }
1272    parse_partial(spec, input)
1273}
1274
1275/// Parse command-line arguments without applying defaults.
1276///
1277/// Use this for help text generation or when you need the raw parsed values.
1278#[must_use = "parsing result should be used"]
1279pub fn parse_partial(spec: &Spec, input: &[String]) -> Result<ParseOutput, miette::Error> {
1280    parse_partial_with_env(spec, input, None, None, MountTiming::Eager, true).map(|(out, _)| out)
1281}
1282
1283/// Basename of argv[0] for a multicall CLI: last path component, with a trailing
1284/// `.exe` stripped so Windows and Unix agree.
1285pub fn multicall_basename(argv0: &str) -> &str {
1286    let name = argv0.rsplit(['/', '\\']).next().unwrap_or(argv0);
1287    match name.get(name.len().saturating_sub(4)..) {
1288        Some(ext) if ext.eq_ignore_ascii_case(".exe") => &name[..name.len() - 4],
1289        _ => name,
1290    }
1291}
1292
1293/// The applet name to parse as the first word, when argv[0] is not the dispatcher.
1294///
1295/// `None` means a dispatcher invocation (`busybox ls`): skip argv[0] and parse the
1296/// rest. `Some` is a symlink invocation (`ls -l`): inject the basename.
1297pub fn multicall_applet<'a>(argv0: &'a str, name: &str, bin: Option<&str>) -> Option<&'a str> {
1298    let base = multicall_basename(argv0);
1299    if !name.is_empty() && base == multicall_basename(name) {
1300        return None;
1301    }
1302    if let Some(bin) = bin
1303        && !bin.is_empty()
1304        && base == multicall_basename(bin)
1305    {
1306        return None;
1307    }
1308    Some(base)
1309}
1310
1311/// Internal version of parse_partial that accepts an optional custom env map.
1312/// When a command's own `mount` runs, for the root — which nothing descends into.
1313///
1314/// A completion has to know every command before it can offer one, even with
1315/// nothing typed yet, so it resolves up front. An execution knows the word it was
1316/// given, so it only pays for discovery when that word matches nothing declared —
1317/// and a CLI that declares its commands and mounts a few more does not spawn a
1318/// process on every invocation.
1319#[derive(Clone, Copy, PartialEq, Eq)]
1320enum MountTiming {
1321    Eager,
1322    WhenAWordIsUnknown,
1323}
1324
1325/// One word on its way through the parser, with what the parser has learned about it.
1326///
1327/// This holds what a side queue used to: the flag Phase 1 read a word as, previously a
1328/// `VecDeque` popped in step with the words. Two queues staying aligned is an invariant
1329/// nothing checks, and it was delicate enough to need explaining at three call sites; on
1330/// the word itself there is nothing to keep aligned. The argv position is here for the
1331/// same reason: the queue is popped, re-queued, split on `=`, and has subcommand words
1332/// removed from the middle, so position in the queue stops meaning position in argv on the
1333/// first descent.
1334struct Token {
1335    word: String,
1336    /// Where in the caller's argv this word came from.
1337    ///
1338    /// A word the parser made up points at the token it was derived from — the tail of a
1339    /// short bundle at the bundle, a multicall applet name at argv[0] — because that is the
1340    /// token a reader would point at, and there is nothing else to point at.
1341    argv: usize,
1342    /// The flag Phase 1 read this word as, and the command level it read it at.
1343    ///
1344    /// `Some((flag, command_level))` for a flag word, `None` for its value, for anything
1345    /// unresolved, and for every word Phase 1 never reached. The words stay in the queue
1346    /// for Phase 2 to re-parse — that is how they reach `out.flags` and `as_env()` — but by
1347    /// then the recognized flags have changed, because each descent drops the parent's
1348    /// non-global flags and a mounted command may declare the same name as a global seen
1349    /// here. Recording the owner keeps a word bound to the flag it was read as.
1350    ///
1351    /// The level matters to strict parsing: clap permits an inherited global once on each
1352    /// side of a subcommand boundary.
1353    binding: Option<(Arc<SpecFlag>, usize)>,
1354}
1355
1356/// Flag scope for the one token straddling an implicit default-command boundary.
1357struct DefaultBundle {
1358    argv: usize,
1359    flags: BTreeMap<String, Arc<SpecFlag>>,
1360    parent_keys: HashSet<String>,
1361}
1362
1363impl DefaultBundle {
1364    /// Preserve the declaration and command level when a short tail is requeued.
1365    fn binding(&self, key: &str) -> Option<(Arc<SpecFlag>, usize)> {
1366        self.flags.get(key).map(|flag| {
1367            (
1368                Arc::clone(flag),
1369                usize::from(!self.parent_keys.contains(key)),
1370            )
1371        })
1372    }
1373}
1374
1375impl Token {
1376    fn new(word: String, argv: usize) -> Self {
1377        Self {
1378            word,
1379            argv,
1380            binding: None,
1381        }
1382    }
1383}
1384
1385/// The token trace, while it is being built.
1386///
1387/// One row per word of the caller's argv, so a role can be recorded against a position
1388/// without the recorder having to know how many words came before it. Words the parser
1389/// made up have no row of their own and fold onto the row they were derived from.
1390struct Trace {
1391    tokens: Vec<TokenBinding>,
1392}
1393
1394impl Trace {
1395    fn new(input: &[String]) -> Self {
1396        Self {
1397            tokens: input
1398                .iter()
1399                .enumerate()
1400                .map(|(index, word)| TokenBinding {
1401                    index,
1402                    word: word.clone(),
1403                    synthesized: false,
1404                    roles: vec![],
1405                })
1406                .collect(),
1407        }
1408    }
1409
1410    fn record(&mut self, argv: usize, role: TokenRole) {
1411        if let Some(token) = self.tokens.get_mut(argv) {
1412            token.roles.push(role);
1413        }
1414    }
1415
1416    /// Note that what was read at this position is not what the caller wrote there.
1417    fn note_synthesized(&mut self, argv: usize) {
1418        if let Some(token) = self.tokens.get_mut(argv) {
1419            token.synthesized = true;
1420        }
1421    }
1422
1423    /// Every word the parse never reached, once it has stopped.
1424    fn close(&mut self, unread: &VecDeque<Token>) {
1425        for token in unread {
1426            self.record(token.argv, TokenRole::Unread);
1427        }
1428    }
1429}
1430
1431fn parse_partial_with_env(
1432    spec: &Spec,
1433    input: &[String],
1434    custom_env: Option<&HashMap<String, String>>,
1435    mount_outputs: Option<&HashMap<String, String>>,
1436    mount_timing: MountTiming,
1437    validate_clauses: bool,
1438) -> Result<(ParseOutput, HashSet<String>), miette::Error> {
1439    let mut trace = Trace::new(input);
1440    parse_partial_traced(
1441        spec,
1442        input,
1443        custom_env,
1444        mount_outputs,
1445        mount_timing,
1446        validate_clauses,
1447        &mut trace,
1448    )
1449}
1450
1451/// Locate the first default-only flag, while preserving an explicit sibling selector.
1452/// This only reads declarations: it neither binds values nor executes mount commands.
1453fn default_flag_route(spec: &Spec, root: &SpecCommand, input: &VecDeque<Token>) -> Option<usize> {
1454    let default = root.find_subcommand(spec.default_subcommand.as_deref()?)?;
1455    let parent = gather_flags(root);
1456    let child = gather_flags(default);
1457    let path = std::slice::from_ref(root);
1458    let mut at = None;
1459    let mut i = 0;
1460    while let Some(token) = input.get(i).map(|t| t.word.as_str()) {
1461        let scope = if at.is_some() { default } else { root };
1462        if token == "--"
1463            || token == "-"
1464            || scope
1465                .clause
1466                .as_ref()
1467                .is_some_and(|c| c.separator.as_deref() == Some(token))
1468        {
1469            return at;
1470        }
1471        if !is_flag_like(token) {
1472            if at.is_none()
1473                && (root.find_subcommand(token).is_some()
1474                    || (token == "help"
1475                        && spec.disable_help != Some(true)
1476                        && !root.disable_help_subcommand))
1477            {
1478                return None;
1479            }
1480            return at;
1481        }
1482        let mut value_flag = None;
1483        let mut attached = None;
1484        if token.starts_with("--") {
1485            let (name, value) = token
1486                .split_once('=')
1487                .map_or((token, None), |(n, v)| (n, Some(v)));
1488            if !parent.contains_key(name)
1489                && (is_help_arg(spec, root, name) || is_version_arg(spec, path, name))
1490            {
1491                i += 1;
1492                continue;
1493            }
1494            let flag = parent.get(name).or_else(|| child.get(name));
1495            let Some(flag) = flag else {
1496                return at;
1497            };
1498            if !parent.contains_key(name) {
1499                at.get_or_insert(i);
1500            }
1501            if flag.arg.is_some() && flag.negate.as_deref() != Some(name) {
1502                value_flag = Some(flag);
1503                attached = value;
1504            }
1505        } else {
1506            for (offset, letter) in token.char_indices().skip(1) {
1507                let key = format!("-{letter}");
1508                if !parent.contains_key(&key) && supplies_short(spec, path, letter) {
1509                    continue;
1510                }
1511                let flag = parent.get(&key).or_else(|| child.get(&key));
1512                let Some(flag) = flag else {
1513                    return at;
1514                };
1515                if !parent.contains_key(&key) {
1516                    at.get_or_insert(i);
1517                }
1518                if flag.arg.is_some() {
1519                    value_flag = Some(flag);
1520                    let rest = &token[offset + letter.len_utf8()..];
1521                    attached = (!rest.is_empty()).then_some(rest.strip_prefix('=').unwrap_or(rest));
1522                    break;
1523                }
1524            }
1525        }
1526        i += 1;
1527        if let Some(flag) = value_flag {
1528            let scope = if at.is_some() { default } else { root };
1529            let is_separator = |next: &str| {
1530                scope
1531                    .clause
1532                    .as_ref()
1533                    .is_some_and(|c| c.separator.as_deref() == Some(next))
1534            };
1535            let first = if attached.is_some() {
1536                attached
1537            } else {
1538                input
1539                    .get(i)
1540                    .map(|t| t.word.as_str())
1541                    .filter(|next| !is_separator(next) && accepts_detached_flag_value(flag, next))
1542                    .inspect(|_| i += 1)
1543            };
1544            if first.is_none() && !flag.value_optional && flag.default_missing.is_none() {
1545                return at;
1546            }
1547            let arg = flag.arg.as_ref().expect("value flag");
1548            if arg.var {
1549                let count_values = |v: &str| arg.delimiter.map_or(1, |d| v.split(d).count());
1550                let mut count = first.map_or(0, count_values);
1551                while arg.var_max.is_none_or(|max| count < max) {
1552                    let Some(next) = input.get(i).map(|t| t.word.as_str()) else {
1553                        break;
1554                    };
1555                    if is_separator(next) {
1556                        break;
1557                    }
1558                    if next == "--" || arg.value_terminator.as_deref() == Some(next) {
1559                        if next != "--" {
1560                            i += 1;
1561                        }
1562                        break;
1563                    }
1564                    if is_flag_like(next)
1565                        && !(arg.allow_negative_numbers && is_negative_number(next))
1566                    {
1567                        break;
1568                    }
1569                    if root.subcommand_precedence_over_arg && root.find_subcommand(next).is_some() {
1570                        break;
1571                    }
1572                    count += count_values(next);
1573                    i += 1;
1574                }
1575            }
1576        }
1577    }
1578    at
1579}
1580
1581/// The binding phase, with the trace left somewhere the caller can still read it.
1582///
1583/// A failure this phase cannot continue past — a word no declaration can take, a flag a
1584/// strict spec refuses — leaves through `?`, and a trace owned by the loop goes with it. The
1585/// words read before the failure are most of what a report wants, so the caller owns the
1586/// trace instead and keeps them. See [`Parser::explain_refused`].
1587fn parse_partial_traced(
1588    spec: &Spec,
1589    input: &[String],
1590    custom_env: Option<&HashMap<String, String>>,
1591    mount_outputs: Option<&HashMap<String, String>>,
1592    mount_timing: MountTiming,
1593    validate_clauses: bool,
1594    trace: &mut Trace,
1595) -> Result<(ParseOutput, HashSet<String>), miette::Error> {
1596    // Each `choices run=` runs once per parse, however many values are checked against it.
1597    let _runs = crate::spec::choices::RunScope::enter();
1598    if let Some(view) = input.first().and_then(|argv0| spec.view_for_program(argv0)) {
1599        let viewed = spec.for_view(view)?;
1600        return parse_partial_traced(
1601            &viewed,
1602            input,
1603            custom_env,
1604            mount_outputs,
1605            mount_timing,
1606            validate_clauses,
1607            trace,
1608        );
1609    }
1610    trace!("parse_partial: {input:?}");
1611    let mut input = input
1612        .iter()
1613        .enumerate()
1614        .map(|(argv, word)| Token::new(word.clone(), argv))
1615        .collect::<VecDeque<_>>();
1616    let argv0 = input.pop_front();
1617    if let Some(argv0) = argv0.as_ref() {
1618        trace.record(argv0.argv, TokenRole::Program);
1619    }
1620    if spec.multicall
1621        && let Some(raw) = argv0
1622        && let Some(applet) = multicall_applet(&raw.word, &spec.name, Some(spec.bin.as_str()))
1623    {
1624        // A symlink invocation reads a word the caller never typed — the basename of
1625        // the program itself — so argv[0] is both the program and, below, whatever
1626        // that word selects.
1627        trace.note_synthesized(raw.argv);
1628        input.push_front(Token::new(applet.to_string(), raw.argv));
1629    }
1630    // The policy observes the selected command's own argv, not values eventually filled from
1631    // env/default. Start at the root, then reset on every explicit descent. A default
1632    // subcommand receives the unmatched word that selected it, so it is necessarily non-bare.
1633    let mut command_has_argv = !input.is_empty();
1634    // Unlike `out.args`, this survives clause finalization and restart rewinds. It records
1635    // whether the root actually consumed a positional token before empty-default routing.
1636    let mut root_positional_arg_found = false;
1637
1638    let mut out = ParseOutput {
1639        cmd: spec.cmd.clone(),
1640        cmds: vec![spec.cmd.clone()],
1641        args: IndexMap::new(),
1642        clauses: IndexMap::new(),
1643        clause_flags: IndexMap::new(),
1644        flags: IndexMap::new(),
1645        tokens: vec![],
1646        flag_origins: IndexMap::new(),
1647        arg_origins: IndexMap::new(),
1648        overridden_flags: BTreeMap::new(),
1649        available_flags: gather_flags(&spec.cmd),
1650        mounted_flags: vec![],
1651        flag_awaiting_value: vec![],
1652        errors: vec![],
1653        warnings: vec![],
1654        next_arg: None,
1655        double_dash_seen: false,
1656        external: None,
1657    };
1658    // A spec whose mounts were resolved ahead of time can start inside a mounted program.
1659    if spec.cmd.mounted || spec.cmd.flags_from_mount {
1660        out.mounted_flags = out.available_flags.values().cloned().collect();
1661    }
1662    // Keep this internal so adding relationship support remains semver-compatible. The full
1663    // parser uses it to prevent defaults and environment values from restoring overridden flags.
1664    let mut overridden_flags = HashSet::new();
1665    // Which spelling supplied each parsed flag. A child may re-declare one long form of an
1666    // inherited global while the merge keeps the ancestor's other aliases on the same `Arc`.
1667    // The declaration object alone then cannot answer whether `--clean` belonged to the child
1668    // or an inherited `-c` belonged to the ancestor.
1669    let mut parsed_flag_spellings: HashMap<usize, HashSet<String>> = HashMap::new();
1670
1671    // Phase 1: Scan for subcommands and collect global flags
1672    //
1673    // This phase identifies subcommands early because they may have mount points
1674    // that need to be executed with the global flags that appeared before them.
1675    //
1676    // Example: "usage --verbose run task"
1677    //   -> finds "run" subcommand, passes ["--verbose"] to its mount command
1678    //   -> then finds "task" as a subcommand of "run" (if it exists)
1679    //
1680    // We only collect global flags for mounts because:
1681    // - Non-global flags are specific to the current command, not subcommands
1682    // - Global flags affect all commands and should be passed to mount points
1683    let mut prefix_flags: Vec<(Arc<SpecFlag>, Vec<String>)> = vec![];
1684    // Which flag each word skipped here belongs to is recorded on the word — see
1685    // `Token::binding`.
1686    let mut command_arg_found = false;
1687    let mut variadic_flag_active = false;
1688    let mut idx = 0;
1689    // Track whether we've already applied the default_subcommand to prevent
1690    // multiple switches (e.g., if default is "run" and there's a task named "run")
1691    let mut used_default_subcommand = false;
1692    let mut default_bundle: Option<DefaultBundle> = None;
1693    // Whether the command in scope has had its own mounts run. A mount on the root
1694    // is the case that needs this: a subcommand's mounts are run when the parser
1695    // descends into it, but nothing descends into the root.
1696    let mut mounts_resolved = false;
1697    // The active variadic flag takes at most one value, which the flag scan has already read.
1698    let mut variadic_flag_capped = false;
1699    // A `help` word found while selecting commands: the command it asked about, and the words
1700    // after it. The answer waits for Phase 2 to bind the flags typed before the word, so
1701    // `explain` still reports them.
1702    let mut pending_help: Option<(SpecCommand, VecDeque<Token>)> = None;
1703    // A completion needs the whole command list before it can offer anything, and
1704    // `mycli <tab>` has no word to trigger discovery with — so waiting for one would
1705    // mean a root mount never contributed to the very thing it exists for.
1706    //
1707    // The default-subcommand gate applies here too, and has to: offering a discovered
1708    // command that a real parse would hand to the default instead would be worse than
1709    // not offering it. A root mount under a `default_subcommand` that does not say
1710    // `overrides_default` therefore contributes nothing anywhere, which is what
1711    // "the default outranks discovery" means.
1712    let default_outranks_mounts =
1713        spec.default_subcommand.is_some() && !out.cmd.mounts.iter().any(|m| m.overrides_default);
1714    if mount_timing == MountTiming::Eager && !default_outranks_mounts && !out.cmd.mounts.is_empty()
1715    {
1716        mounts_resolved = true;
1717        let mut mounted = out.cmd.clone();
1718        mounted.mount(&[], mount_outputs)?;
1719        out.merge_command_flags(&mounted, false);
1720        if let Some(last) = out.cmds.last_mut() {
1721            *last = mounted.clone();
1722        }
1723        out.cmd = mounted;
1724    }
1725
1726    let default_flag_at = spec
1727        .default_subcommand_flags
1728        .then(|| default_flag_route(spec, &out.cmd, &input))
1729        .flatten();
1730
1731    while idx < input.len() {
1732        // Only for a word that could name a command, and only when it matches
1733        // nothing already declared. A CLI that declares its commands and mounts more
1734        // does not spawn a process for every invocation, and a flag — `--help`, or
1735        // anything unrecognized — never triggers discovery at all, which it would
1736        // otherwise do simply by not being a subcommand.
1737        // A declared `default_subcommand` already says what an unmatched word means,
1738        // and it costs nothing — so discovery waits behind it unless a mount asks to
1739        // outrank it. Without this, a task runner would spawn its discovery process
1740        // once per task invocation.
1741        let default_catches_it = spec.default_subcommand.as_deref().is_some_and(|name| {
1742            default_accepts_word(&out.cmd, name, &input[idx].word)
1743                && !out.cmd.mounts.iter().any(|m| m.overrides_default)
1744        });
1745        if !mounts_resolved
1746            && !out.cmd.mounts.is_empty()
1747            && !default_catches_it
1748            && is_command_word(&input[idx].word)
1749            && !is_negative_number(&input[idx].word)
1750            && out.cmd.find_subcommand(&input[idx].word).is_none()
1751        {
1752            mounts_resolved = true;
1753            let mut mounted = out.cmd.clone();
1754            mounted.mount(&mount_prefix_words(&prefix_flags), mount_outputs)?;
1755            out.merge_command_flags(&mounted, false);
1756            if let Some(last) = out.cmds.last_mut() {
1757                *last = mounted.clone();
1758            }
1759            out.cmd = mounted;
1760        }
1761        if variadic_flag_active
1762            && out.cmd.find_subcommand(&input[idx].word).is_some()
1763            && !out.cmd.subcommand_precedence_over_arg
1764        {
1765            break;
1766        }
1767        let implicit_default = !used_default_subcommand && default_flag_at == Some(idx);
1768        let selected_command = if implicit_default {
1769            out.cmd
1770                .find_subcommand(spec.default_subcommand.as_deref().expect("default route"))
1771        } else {
1772            out.cmd.find_subcommand(&input[idx].word)
1773        };
1774        if let Some(subcommand) = selected_command {
1775            let boundary_has_parent = out.cmd.args_conflicts_with_subcommands
1776                && implicit_default
1777                && input[idx].word.starts_with('-')
1778                && !input[idx].word.starts_with("--")
1779                && {
1780                    let child_flags = gather_flags(subcommand);
1781                    let mut found = false;
1782                    for short in input[idx].word[1..].chars() {
1783                        let key = format!("-{short}");
1784                        if out.available_flags.contains_key(&key)
1785                            || supplies_short(spec, &out.cmds, short)
1786                        {
1787                            found = true;
1788                            break;
1789                        }
1790                        match child_flags.get(&key) {
1791                            Some(flag) if flag.arg.is_none() => {}
1792                            _ => break,
1793                        }
1794                    }
1795                    found
1796                };
1797            if out.cmd.args_conflicts_with_subcommands && (command_arg_found || boundary_has_parent)
1798            {
1799                bail!(
1800                    "subcommand '{}' cannot be used with arguments on its parent command",
1801                    subcommand.name
1802                );
1803            }
1804            let boundary_parent = (implicit_default
1805                && input[idx].word.starts_with('-')
1806                && !input[idx].word.starts_with("--"))
1807            .then(|| out.available_flags.clone());
1808            let mut subcommand = subcommand.clone();
1809            // Pass prefix words (global flags before this subcommand) to mount
1810            subcommand.mount(&mount_prefix_words(&prefix_flags), mount_outputs)?;
1811            // Only the *boundary* is a mount crossing: below it, the mounted program's own
1812            // commands are ordinary commands relative to each other.
1813            let crossing_mount = subcommand.mounted && !out.cmd.mounted;
1814            out.merge_command_flags(&subcommand, crossing_mount);
1815            if let Some(parent) = boundary_parent {
1816                let parent_keys = parent.keys().cloned().collect();
1817                let mut flags = out.available_flags.clone();
1818                flags.extend(parent);
1819                default_bundle = Some(DefaultBundle {
1820                    argv: input[idx].argv,
1821                    flags,
1822                    parent_keys,
1823                });
1824            }
1825            // Remove subcommand from input
1826            let selected = if implicit_default {
1827                used_default_subcommand = true;
1828                None
1829            } else {
1830                input.remove(idx)
1831            };
1832            if let Some(selected) = selected {
1833                trace.record(
1834                    selected.argv,
1835                    TokenRole::Command {
1836                        name: subcommand.name.clone(),
1837                    },
1838                );
1839            }
1840            command_has_argv = idx < input.len();
1841            out.cmds.push(subcommand.clone());
1842            out.cmd = subcommand.clone();
1843            // A descent already ran the new command's mounts, above.
1844            mounts_resolved = true;
1845            prefix_flags.clear();
1846            command_arg_found = false;
1847            variadic_flag_active = false;
1848            // Continue from current position (don't reset to 0)
1849            // After remove(), idx now points to the next element
1850        } else if !is_command_word(&input[idx].word)
1851            || declared_numeric_short(&out.available_flags, &input[idx].word)
1852        {
1853            // Check if this is a known flag
1854            let word = input[idx].word.clone();
1855            let flag_key = get_flag_key(&word);
1856
1857            // A short token keys on its first letter, so `-az` would be recorded as
1858            // `-a` and its tail left over. Check the whole token here, where it is
1859            // first read: a token containing an unrecognized letter is not a bundle,
1860            // and recording it as one is what let `-a` be applied from a token that
1861            // never named it.
1862            let boundary = default_bundle
1863                .as_ref()
1864                .filter(|bundle| bundle.argv == input[idx].argv);
1865            let flags = boundary.map_or(&out.available_flags, |bundle| &bundle.flags);
1866            let is_bundle =
1867                word.starts_with("--") || short_bundle_is_known(spec, &out.cmds, flags, &word);
1868            if let Some(f) = flags.get(flag_key).cloned().filter(|_| is_bundle) {
1869                command_arg_found = true;
1870                variadic_flag_active = f.arg.as_ref().is_some_and(|arg| arg.var);
1871                variadic_flag_capped = f
1872                    .arg
1873                    .as_ref()
1874                    .is_some_and(|arg| arg.var && arg.var_max == Some(1));
1875                // Skip the flag and keep scanning. Both global and non-global flags may precede
1876                // a subcommand (`mycli --verbose run task`, `mycli run --force task`), and
1877                // stopping at one would hide the subcommand — and any mount on it — from the
1878                // parse, leaving the subcommand name to be mis-read as a positional argument.
1879                //
1880                // Only globals are forwarded to mounts: a non-global flag belongs to the
1881                // command that declared it, not to what is mounted below it.
1882                input[idx].binding = boundary
1883                    .and_then(|bundle| bundle.binding(flag_key))
1884                    .or_else(|| Some((Arc::clone(&f), out.cmds.len() - 1)));
1885                let mut forwarded = f.global.then(|| vec![word.clone()]);
1886                idx += 1;
1887
1888                // Only consume next word if flag takes an argument AND value isn't embedded
1889                // Example: "--dir foo" consumes "foo", but "--dir=foo" or "--verbose" do not
1890                if f.arg.is_some()
1891                    && !word.contains('=')
1892                    && idx < input.len()
1893                    && accepts_detached_flag_value(&f, &input[idx].word)
1894                {
1895                    if let Some(words) = forwarded.as_mut() {
1896                        words.push(input[idx].word.clone());
1897                    }
1898                    idx += 1;
1899                }
1900                if let Some(words) = forwarded {
1901                    apply_prefix_flag_overrides(&mut prefix_flags, Arc::clone(&f));
1902                    prefix_flags.push((f, words));
1903                }
1904            } else {
1905                // Unknown flag - stop looking for subcommands
1906                // Let the main parsing phase handle the error
1907                break;
1908            }
1909        } else {
1910            if variadic_flag_active && out.cmd.subcommand_precedence_over_arg {
1911                idx += 1;
1912                continue;
1913            }
1914            // Found a word that's not a flag or subcommand
1915            // Check if we should use the default_subcommand (only once, and only at the
1916            // root, which is the only place a spec can declare one — `out.cmds` holds just
1917            // the root until something descends). Without that second condition the one
1918            // declared name is looked up wherever the parser happens to be standing, so an
1919            // unrelated command acquires a default because a name matched one level down:
1920            // with `default_subcommand "ls"` at the top, `ex config zzz` descended into
1921            // `config ls`.
1922            // `ex help config ls`: the word the page lists under Commands, answered here, among
1923            // the command lookups, so that it outranks a default subcommand and a positional
1924            // the way usage-argv ranks it — after a declared subcommand of that name, which keeps
1925            // its meaning, and before anything that would take the word as a value. The words
1926            // after it name a command, resolved (mounts included) rather than descended into:
1927            // they are a question, not an invocation. The answer is the long form.
1928            if input[idx].word == "help"
1929                && (!variadic_flag_active || variadic_flag_capped)
1930                && spec.disable_help != Some(true)
1931                && !out.cmd.disable_help_subcommand
1932                && !out.cmd.subcommands.is_empty()
1933            {
1934                let help = input.remove(idx).unwrap();
1935                trace.record(
1936                    help.argv,
1937                    TokenRole::Builtin {
1938                        spelling: help.word,
1939                    },
1940                );
1941                let target = resolve_help_target(
1942                    &out.cmd,
1943                    &mut input,
1944                    idx,
1945                    mount_prefix_words(&prefix_flags),
1946                    mount_outputs,
1947                    trace,
1948                )?;
1949                pending_help = Some((target, input.split_off(idx)));
1950                break;
1951            }
1952            if !used_default_subcommand
1953                && out.cmds.len() == 1
1954                && let Some(default_name) = &spec.default_subcommand
1955                && let Some(subcommand) = out
1956                    .cmd
1957                    .find_subcommand(default_name)
1958                    .filter(|_| default_accepts_word(&out.cmd, default_name, &input[idx].word))
1959            {
1960                if out.cmd.args_conflicts_with_subcommands && command_arg_found {
1961                    bail!(
1962                        "subcommand '{}' cannot be used with arguments on its parent command",
1963                        subcommand.name
1964                    );
1965                }
1966                let mut subcommand = subcommand.clone();
1967                // Pass prefix words (global flags before this) to mount
1968                subcommand.mount(&mount_prefix_words(&prefix_flags), mount_outputs)?;
1969                let crossing_mount = subcommand.mounted && !out.cmd.mounted;
1970                out.merge_command_flags(&subcommand, crossing_mount);
1971                out.cmds.push(subcommand.clone());
1972                out.cmd = subcommand.clone();
1973                command_has_argv = true;
1974                prefix_flags.clear();
1975                command_arg_found = false;
1976                variadic_flag_active = false;
1977                // This descent ran the new command's mounts, so lazy
1978                // discovery must not run them a second time.
1979                mounts_resolved = true;
1980                used_default_subcommand = true;
1981                // Continue the loop to check if this word is a subcommand of the
1982                // default subcommand (e.g., a task name added via mount).
1983                // If it's not a subcommand, the next iteration will break and
1984                // Phase 2 will handle it as a positional arg.
1985                continue;
1986            }
1987            // Sigil-classified positionals do not occupy the ordinary positional cursor and
1988            // therefore do not close subcommand routing. Phase 2 binds and strips them. A
1989            // default subcommand gets first refusal so interpreted and compiled routing agree
1990            // when the root sigil and the default command can both accept this word.
1991            if match_sigil_arg_chain(&out.cmds, &input[idx].word).is_some() {
1992                idx += 1;
1993                continue;
1994            }
1995            // An unmatched word that names no subcommand is forwarded as an external
1996            // command: this word, then every token after it, including flags. Known
1997            // subcommands already won above, and a default_subcommand already caught.
1998            // clap's `allow_external_subcommands` is this, not `unknown_flags=value`.
1999            if out.cmd.external_subcommand {
2000                let rest: Vec<Token> = input.drain(idx..).collect();
2001                for token in &rest {
2002                    trace.record(token.argv, TokenRole::External);
2003                }
2004                out.external = Some(rest.into_iter().map(|t| t.word).collect());
2005                break;
2006            }
2007            // This could be a positional argument, so stop subcommand search
2008            break;
2009        }
2010    }
2011
2012    // Phase 2: Main argument and flag parsing
2013    //
2014    // Now that we've identified all subcommands and executed their mounts,
2015    // we can parse the remaining arguments, flags, and their values.
2016
2017    // The cursor into the active positional arguments, kept as an index rather than a reference
2018    // because an explicit `--` may jump it *past* arguments that stay empty (see the `w == "--"`
2019    // arm).
2020    // With such a gap `out.args.len()` no longer equals the cursor, so anything asking "is this
2021    // argument filled?" has to consult `out.args` by key instead of counting.
2022    let mut next_arg_idx = cursor_skip_sigils(&out.cmd, 0);
2023    let mut enable_flags = true;
2024    let mut grouped_flag = false;
2025    // Whether an explicit `--` has been consumed *as a separator* (as opposed to being kept as a
2026    // value by `double_dash="preserve"`). Args declared `double_dash="required"` only accept
2027    // words that come after it — see `report_double_dash_violation`.
2028    let mut seen_double_dash = false;
2029    // Sigils are a leading-segment grammar. A restart begins a later segment but does not
2030    // reopen sigil classification for this invocation.
2031    let mut restart_seen = false;
2032    // Args already reported as having been offered a word before the `--` they require, so a
2033    // variadic one does not report the same violation for every word it is offered.
2034    let mut double_dash_violations: HashSet<String> = HashSet::new();
2035    // A root clause separator is user-supplied syntax, so it must suppress the
2036    // empty-input default just like an explicit `--`. This is separate from
2037    // `seen_double_dash`, which resets for each clause instance.
2038    let mut root_clause_separator_seen = false;
2039    // Scalar occurrences are scoped to the command level where they were written. Inherited
2040    // globals may therefore appear once before and once after a subcommand under clap's strict
2041    // `args_override_self(false)` policy. The bitset also keeps both forms of a negatable flag:
2042    // opposite forms may override one another, while repeating either spelling is an error.
2043    let mut scalar_occurrences: HashMap<(usize, usize), u8> = HashMap::new();
2044
2045    while !input.is_empty() {
2046        let token = input.pop_front().unwrap();
2047        // The flag this word was read as in Phase 1, if it skipped it (see `Token::binding`).
2048        let binding = token.binding;
2049        let argv = token.argv;
2050        let mut w = token.word;
2051        // A short's attached value is re-queued with `grouped_flag` set, and that
2052        // continuation is not a following word. `require_equals` refuses only the
2053        // following word; `-i9229` and `-i=9229` still bind. `default_missing` binds
2054        // only when the value is actually missing, so `-cnever` is still `never`.
2055        let attached_continuation = grouped_flag;
2056        // The opt-in lookahead uses declared value arity, so binding must consume
2057        // the same attached value even after the default changed flag scope.
2058        // Other specs retain the reference parser's legacy short-bundle rules.
2059        if spec.default_subcommand_flags
2060            && attached_continuation
2061            && !out.flag_awaiting_value.is_empty()
2062        {
2063            grouped_flag = false;
2064            w.remove(0);
2065            if w.starts_with('=') {
2066                w.remove(0);
2067            }
2068            if bind_pending_flag_value(
2069                spec,
2070                &out.cmd,
2071                &mut out.errors,
2072                &mut out.flags,
2073                &mut out.flag_awaiting_value,
2074                &mut w,
2075                &mut input,
2076                custom_env,
2077                trace,
2078                argv,
2079                true,
2080            )? {
2081                record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
2082                return Ok((out, overridden_flags));
2083            }
2084            continue;
2085        }
2086
2087        // A clause boundary is syntax even after an automatic trailing argument disabled
2088        // flags. Only an explicit `--` protects a literal separator.
2089        if !seen_double_dash
2090            && let Some(clause) = out.cmd.clause.as_ref()
2091            && clause.separator.as_deref() == Some(w.as_str())
2092        {
2093            while try_bind_default_missing(
2094                &mut out.flags,
2095                &mut out.flag_awaiting_value,
2096                custom_env,
2097                &mut out.flag_origins,
2098            )? {}
2099            if let Some(flag) = out.flag_awaiting_value.first() {
2100                let spelling = flag
2101                    .long
2102                    .first()
2103                    .map(|long| format!("--{long}"))
2104                    .or_else(|| flag.short.first().map(|short| format!("-{short}")))
2105                    .unwrap_or_else(|| flag.name.clone());
2106                return Err(UsageErr::InvalidFlag {
2107                    token: spelling.clone(),
2108                    reason: "requires an argument".to_string(),
2109                    span: (0, spelling.len()).into(),
2110                    input: spelling,
2111                }
2112                .into());
2113            }
2114            let name = clause.name.clone();
2115            if out.cmds.len() == 1 {
2116                root_clause_separator_seen = true;
2117            }
2118            finalize_current_clause(&mut out);
2119            out.arg_origins.clear();
2120            trace.record(argv, TokenRole::ClauseSeparator { name });
2121            next_arg_idx = 0;
2122            out.flag_awaiting_value.clear();
2123            reset_clause_scalar_occurrences(&out, &mut scalar_occurrences);
2124            enable_flags = true;
2125            seen_double_dash = false;
2126            continue;
2127        }
2128
2129        // Check for restart_token - resets argument parsing for multiple command invocations
2130        // e.g., `mise run lint ::: test ::: check` with restart_token=":::"
2131        if let Some(ref restart_token) = out.cmd.restart_token
2132            && w == *restart_token
2133        {
2134            // Reset argument parsing state for a fresh command invocation, keeping the
2135            // flags. `double_dash_violations` is deliberately *not* cleared: `out.errors`
2136            // is not cleared here either, so clearing it would let one arg report the same
2137            // violation once per invocation.
2138            out.args.clear();
2139            // With the values gone, so is where they came from — otherwise the second
2140            // invocation of `run lint ::: test` reports the first one's provenance. The
2141            // token trace is *not* cleared: those words were read, and a report that
2142            // dropped them would show a command line with a hole in it.
2143            out.arg_origins.clear();
2144            trace.record(argv, TokenRole::Restart);
2145            next_arg_idx = cursor_skip_sigils(&out.cmd, 0);
2146            restart_seen = true;
2147            out.flag_awaiting_value.clear(); // Clear any pending flag values
2148            enable_flags = true; // Reset -- separator effect
2149            seen_double_dash = false; // The next invocation needs its own `--`
2150            continue;
2151        }
2152
2153        // A flag declared `allow_hyphen_values` takes the next token whatever it looks
2154        // like, and that has to be asked before the separator arm below rather than
2155        // after it. Asked after, a `--` was consumed as a separator while the flag
2156        // stayed hungry, and the flag then ate the word past it: `ex -a -- -x` bound
2157        // `-x` and the separator was simply gone. Asked here, the flag takes the `--`
2158        // itself, which is what clap does with the same declaration — and no flag can
2159        // still be waiting once the separator has done its job, so the starvation rule
2160        // below has no path around it.
2161        if enable_flags
2162            && !attached_continuation
2163            && w.starts_with('-')
2164            && out
2165                .flag_awaiting_value
2166                .last()
2167                .is_some_and(|flag| accepts_detached_flag_value(flag, &w))
2168        {
2169            // A variadic argument collects here too: which token supplied its first
2170            // value says nothing about how many it takes.
2171            let should_return = bind_pending_flag_value(
2172                spec,
2173                &out.cmd,
2174                &mut out.errors,
2175                &mut out.flags,
2176                &mut out.flag_awaiting_value,
2177                &mut w,
2178                &mut input,
2179                custom_env,
2180                trace,
2181                argv,
2182                // The token a hyphen-valued flag takes is the following word, never attached.
2183                false,
2184            )?;
2185            if should_return {
2186                record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
2187                return Ok((out, overridden_flags));
2188            }
2189            continue;
2190        }
2191
2192        // A flag whose value may be omitted that cannot take this token as a detached
2193        // value finishes bare and leaves the token for whatever comes next:
2194        // `--color --verbose` colours with the missing value and still sets verbose,
2195        // and `--inspect 9229` with `require_equals` binds the missing value rather
2196        // than treating 9229 as the port.
2197        if enable_flags
2198            && !attached_continuation
2199            && !out.flag_awaiting_value.is_empty()
2200            && out.flag_awaiting_value.last().is_some_and(|flag| {
2201                (flag.default_missing.is_some() || flag.value_optional)
2202                    && !accepts_detached_flag_value(flag, &w)
2203            })
2204        {
2205            try_bind_default_missing(
2206                &mut out.flags,
2207                &mut out.flag_awaiting_value,
2208                custom_env,
2209                &mut out.flag_origins,
2210            )?;
2211        }
2212
2213        // The first explicit `--` is still a separator after an `automatic` argument has
2214        // stopped flag parsing. Once an explicit separator has done its job, a second one is
2215        // an ordinary value: every parser worth comparing against keeps it (POSIX getopt,
2216        // argparse, clap, commander, yargs), and jdx/usage#229 was a user reporting the old
2217        // behavior as the bug it is.
2218        if w == "--" && !seen_double_dash {
2219            enable_flags = false;
2220
2221            // Only preserve the double dash token if we're collecting values for a variadic arg
2222            // in double_dash == `preserve` mode
2223            let should_preserve = active_args(&out.cmd)
2224                .get(next_arg_idx)
2225                .map(|arg| arg.var && arg.double_dash == SpecDoubleDashChoices::Preserve)
2226                .unwrap_or(false);
2227
2228            if should_preserve {
2229                // Fall through to arg parsing. This `--` is a *value*, not a separator, so it
2230                // neither counts as one nor unlocks a `double_dash="required"` arg.
2231            } else {
2232                seen_double_dash = true;
2233                trace.record(argv, TokenRole::Separator);
2234
2235                // Everything after an explicit `--` belongs to the arg that requires one, so
2236                // jump the cursor there — past any earlier arg, including a greedy variadic
2237                // that would otherwise swallow the rest. This mirrors clap's `Arg::last(true)`,
2238                // which is what `double_dash="required"` is generated from. Specs without such
2239                // an arg find nothing and keep the cursor where it was.
2240                let target = active_args(&out.cmd).iter().position(|arg| {
2241                    arg.double_dash == SpecDoubleDashChoices::Required
2242                        && !out.args.contains_key(arg)
2243                });
2244                if let Some(target) = target {
2245                    // Forward only. An unfilled required arg declared *before* the cursor is
2246                    // left where it is rather than rewound to — words already assigned to
2247                    // later args would have to be taken back for that to mean anything, and
2248                    // the arg keeps its `MissingArg`. `double_dash="required"` mirrors clap's
2249                    // `Arg::last(true)`, which is the final positional, so a spec that puts
2250                    // one ahead of others is already outside what this models.
2251                    if target > next_arg_idx {
2252                        next_arg_idx = target;
2253                    }
2254                }
2255                continue;
2256            }
2257        }
2258
2259        // long flags
2260        if enable_flags && w.starts_with("--") {
2261            grouped_flag = false;
2262            // `Some` only when an `=` was actually written, so `--jobs=` can supply
2263            // an empty value while `--jobs` supplies none. Collapsing the two lost
2264            // the flag entirely.
2265            let split = w.split_once('=');
2266            let word = split.map(|(word, _)| word).unwrap_or(&w);
2267            let bound_flag = binding.as_ref().map(|(flag, _)| flag);
2268            if let Some(f) = bound_flag.or_else(|| out.available_flags.get(word)) {
2269                let command_level = binding
2270                    .as_ref()
2271                    .map(|(_, level)| *level)
2272                    .unwrap_or(out.cmds.len() - 1);
2273                parsed_flag_spellings
2274                    .entry(Arc::as_ptr(f) as usize)
2275                    .or_default()
2276                    .insert(word.to_string());
2277                // Recorded before the action check below: a token that named a flag named it
2278                // whether or not the parse can carry on afterwards.
2279                trace.record(
2280                    argv,
2281                    TokenRole::Flag {
2282                        flag: Arc::clone(f),
2283                        spelling: word.to_string(),
2284                        negated: f.negate.as_deref() == Some(word),
2285                    },
2286                );
2287                if f.action != crate::SpecFlagAction::Set {
2288                    out.errors
2289                        .push(render_action_err(spec, &out.cmd, f, word, custom_env));
2290                    record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
2291                    return Ok((out, overridden_flags));
2292                }
2293                apply_flag_overrides(
2294                    f,
2295                    &out.available_flags,
2296                    &mut out.flags,
2297                    &mut out.flag_awaiting_value,
2298                    &mut overridden_flags,
2299                    &mut out.overridden_flags,
2300                );
2301                if let Some(pending) = out.flag_awaiting_value.first() {
2302                    out.errors.push(render_missing_flag_value(pending, &w));
2303                    record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
2304                    return Ok((out, overridden_flags));
2305                }
2306                // An attached value only means something to a flag that takes one:
2307                // `--jobs=` is an empty string, while `--force=yes` has nothing to
2308                // give a flag that holds no value. Handing that leftover to the
2309                // positionals would re-split one token into two, so `ex --force=yes`
2310                // would fill an argument the caller never typed a word for.
2311                if f.arg.is_some() {
2312                    record_scalar_flag_occurrence(
2313                        &out.cmds,
2314                        f,
2315                        command_level,
2316                        None,
2317                        &mut scalar_occurrences,
2318                        &mut out.errors,
2319                    );
2320                    let f = Arc::clone(f);
2321                    out.flag_awaiting_value.push(Arc::clone(&f));
2322                    // The `=` has already settled that this text is the value, so it
2323                    // binds here rather than going back on the queue to be read as a
2324                    // token again — where `--jobs=--force` looked like a flag of its
2325                    // own and bound `force`, leaving `jobs` unset.
2326                    if let Some((_, val)) = split {
2327                        // The `=` settles where the *first* value came from and nothing
2328                        // more, so a variadic argument goes on collecting from the words
2329                        // after it exactly as the detached form does.
2330                        let mut val = val.to_string();
2331                        let should_return = bind_pending_flag_value(
2332                            spec,
2333                            &out.cmd,
2334                            &mut out.errors,
2335                            &mut out.flags,
2336                            &mut out.flag_awaiting_value,
2337                            &mut val,
2338                            &mut input,
2339                            custom_env,
2340                            trace,
2341                            argv,
2342                            // The `=` settled that this text is the value, so it rode in on
2343                            // the flag's own token.
2344                            true,
2345                        )?;
2346                        if should_return {
2347                            record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
2348                            return Ok((out, overridden_flags));
2349                        }
2350                    }
2351                } else if f.count {
2352                    let arr = out
2353                        .flags
2354                        .entry(Arc::clone(f))
2355                        .or_insert_with(|| ParseValue::MultiBool(vec![]))
2356                        .try_as_multi_bool_mut()
2357                        .unwrap();
2358                    arr.push(true);
2359                } else {
2360                    let negate = f.negate.clone().unwrap_or_default();
2361                    let negated_form = word == negate;
2362                    let value = if f.bool_value {
2363                        match split.map(|(_, value)| value) {
2364                            Some("true") => !negated_form,
2365                            Some("false") => negated_form,
2366                            Some(value) => {
2367                                out.errors.push(UsageErr::InvalidValue {
2368                                    name: f.name.clone(),
2369                                    value: value.to_string(),
2370                                    reason: "expected `true` or `false`".to_string(),
2371                                });
2372                                continue;
2373                            }
2374                            None => !negated_form,
2375                        }
2376                    } else {
2377                        !negated_form
2378                    };
2379                    // Which form was typed is a question about the name, so it is
2380                    // asked of `word` rather than the whole token: the attached value
2381                    // is dropped just above, and comparing `--no-color=yes` against
2382                    // `--no-color` would take the negation down with it.
2383                    record_scalar_flag_occurrence(
2384                        &out.cmds,
2385                        f,
2386                        command_level,
2387                        Some(!negated_form),
2388                        &mut scalar_occurrences,
2389                        &mut out.errors,
2390                    );
2391                    out.flags.insert(Arc::clone(f), ParseValue::Bool(value));
2392                }
2393                continue;
2394            }
2395            if is_help_arg(spec, &out.cmd, &w) {
2396                out.errors
2397                    .push(render_help_err(spec, &out.cmd, w.len() > 2, custom_env));
2398                trace.record(
2399                    argv,
2400                    TokenRole::Builtin {
2401                        spelling: w.clone(),
2402                    },
2403                );
2404                record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
2405                return Ok((out, overridden_flags));
2406            }
2407            if is_version_arg(spec, &out.cmds, &w) {
2408                out.errors.push(render_version_err(spec, w.len() > 2));
2409                trace.record(
2410                    argv,
2411                    TokenRole::Builtin {
2412                        spelling: w.clone(),
2413                    },
2414                );
2415                record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
2416                return Ok((out, overridden_flags));
2417            }
2418            if let Err(refused) = reject_unknown_flag_if_asked(spec, &out.cmds, &w) {
2419                trace.record(argv, TokenRole::UnknownFlag { bound_as: None });
2420                trace.close(&input);
2421                return Err(refused.into());
2422            }
2423        }
2424
2425        // short flags
2426        //
2427        // A fresh token is checked whole before any of it is applied: `-az` with only
2428        // `-a` declared is not a bundle at all, so it must not set `a` on the way to
2429        // discovering that `z` names nothing. A grouped continuation is exempt — its
2430        // token was already checked when it arrived.
2431        let declared_numeric_short = declared_numeric_short(&out.available_flags, &w);
2432        let positional_negative_number = !declared_numeric_short
2433            && is_negative_number(&w)
2434            && active_args(&out.cmd)
2435                .get(next_arg_idx)
2436                .is_some_and(|arg| arg.allow_negative_numbers);
2437        if enable_flags
2438            && !grouped_flag
2439            // A word phase 1 already resolved to a flag needs no re-checking, and
2440            // the flags in scope have changed since, so re-checking would be wrong.
2441            && binding.is_none()
2442            && w.starts_with('-')
2443            && w.len() > 1
2444            && is_flag_like(&w)
2445            && !positional_negative_number
2446            && !short_bundle_is_known(spec, &out.cmds, &out.available_flags, &w)
2447        {
2448            // Refused if this command asked for that; otherwise it carries on below
2449            // as one word, with none of its letters applied.
2450            if let Err(refused) = reject_unknown_flag_if_asked(spec, &out.cmds, &w) {
2451                trace.record(argv, TokenRole::UnknownFlag { bound_as: None });
2452                trace.close(&input);
2453                return Err(refused.into());
2454            }
2455        } else if enable_flags && !positional_negative_number && w.starts_with('-') && w.len() > 1 {
2456            let short = w.chars().nth(1).unwrap();
2457            if let Some(f) = binding
2458                .as_ref()
2459                .map(|(flag, _)| flag)
2460                .or_else(|| out.available_flags.get(&format!("-{short}")))
2461            {
2462                let command_level = binding
2463                    .as_ref()
2464                    .map(|(_, level)| *level)
2465                    .unwrap_or(out.cmds.len() - 1);
2466                if f.action != crate::SpecFlagAction::Set {
2467                    out.errors.push(render_action_err(
2468                        spec,
2469                        &out.cmd,
2470                        f,
2471                        &format!("-{short}"),
2472                        custom_env,
2473                    ));
2474                    record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
2475                    return Ok((out, overridden_flags));
2476                }
2477                parsed_flag_spellings
2478                    .entry(Arc::as_ptr(f) as usize)
2479                    .or_default()
2480                    .insert(format!("-{short}"));
2481                trace.record(
2482                    argv,
2483                    TokenRole::Flag {
2484                        flag: Arc::clone(f),
2485                        spelling: format!("-{short}"),
2486                        // A short spelling is never the negated form: `negate` is a long.
2487                        negated: false,
2488                    },
2489                );
2490                apply_flag_overrides(
2491                    f,
2492                    &out.available_flags,
2493                    &mut out.flags,
2494                    &mut out.flag_awaiting_value,
2495                    &mut overridden_flags,
2496                    &mut out.overridden_flags,
2497                );
2498                if !attached_continuation && let Some(pending) = out.flag_awaiting_value.first() {
2499                    out.errors.push(render_missing_flag_value(pending, &w));
2500                    record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
2501                    return Ok((out, overridden_flags));
2502                }
2503                let rest = &w[1 + short.len_utf8()..];
2504                if !rest.is_empty() {
2505                    // `-abc` is one token that names three flags, so the tail is read at the
2506                    // bundle's own position rather than at one of its own.
2507                    let mut tail = Token::new(format!("-{rest}"), argv);
2508                    if f.arg.is_none() {
2509                        tail.binding = default_bundle
2510                            .as_ref()
2511                            .filter(|bundle| bundle.argv == argv)
2512                            .and_then(|bundle| bundle.binding(get_flag_key(&tail.word)));
2513                    }
2514                    input.push_front(tail);
2515                }
2516                // A fully consumed short is no longer a grouped continuation.
2517                // Leaving this set after `-ai` made `-i` skip `require_equals`
2518                // and bind the following word.
2519                grouped_flag = !rest.is_empty();
2520                if f.arg.is_some() {
2521                    record_scalar_flag_occurrence(
2522                        &out.cmds,
2523                        f,
2524                        command_level,
2525                        None,
2526                        &mut scalar_occurrences,
2527                        &mut out.errors,
2528                    );
2529                    out.flag_awaiting_value.push(Arc::clone(f));
2530                } else if f.count {
2531                    let arr = out
2532                        .flags
2533                        .entry(Arc::clone(f))
2534                        .or_insert_with(|| ParseValue::MultiBool(vec![]))
2535                        .try_as_multi_bool_mut()
2536                        .unwrap();
2537                    arr.push(true);
2538                } else {
2539                    let negate = f.negate.clone().unwrap_or_default();
2540                    let value = w != negate;
2541                    record_scalar_flag_occurrence(
2542                        &out.cmds,
2543                        f,
2544                        command_level,
2545                        Some(value),
2546                        &mut scalar_occurrences,
2547                        &mut out.errors,
2548                    );
2549                    out.flags.insert(Arc::clone(f), ParseValue::Bool(value));
2550                }
2551                continue;
2552            }
2553            // The letter nothing declared may still be one the parser supplies, and it may
2554            // sit anywhere in the token: `-hv` asks for help as surely as `-vh` does, and
2555            // neither reaches the whole-token spellings below.
2556            if let Some(err) = supplied_short(spec, &out.cmds, short, custom_env) {
2557                out.errors.push(err);
2558                trace.record(
2559                    argv,
2560                    TokenRole::Builtin {
2561                        spelling: format!("-{short}"),
2562                    },
2563                );
2564                record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
2565                return Ok((out, overridden_flags));
2566            }
2567            if is_help_arg(spec, &out.cmd, &w) {
2568                out.errors
2569                    .push(render_help_err(spec, &out.cmd, w.len() > 2, custom_env));
2570                trace.record(
2571                    argv,
2572                    TokenRole::Builtin {
2573                        spelling: w.clone(),
2574                    },
2575                );
2576                record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
2577                return Ok((out, overridden_flags));
2578            }
2579            if is_version_arg(spec, &out.cmds, &w) {
2580                out.errors.push(render_version_err(spec, w.len() > 2));
2581                trace.record(
2582                    argv,
2583                    TokenRole::Builtin {
2584                        spelling: w.clone(),
2585                    },
2586                );
2587                record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
2588                return Ok((out, overridden_flags));
2589            }
2590            if let Err(refused) = reject_unknown_flag_if_asked(spec, &out.cmds, &w) {
2591                trace.record(argv, TokenRole::UnknownFlag { bound_as: None });
2592                trace.close(&input);
2593                return Err(refused.into());
2594            }
2595            if grouped_flag {
2596                grouped_flag = false;
2597                w.remove(0);
2598                // What is left is a short flag's attached value, and one `=` between
2599                // the letter and the value is a separator: `-j=8` means 8. Only one,
2600                // so `-j==8` still means `=8`.
2601                if !out.flag_awaiting_value.is_empty() && w.starts_with('=') {
2602                    w.remove(0);
2603                }
2604            }
2605        }
2606
2607        // Only while flags are still being read. A flag still waiting when the separator
2608        // was consumed is starved: its value would have to come from after the `--`,
2609        // where every token is data. Draining there gave `ex --jobs -- x` the word after
2610        // the separator, so the command line quietly meant `ex --jobs=x` and the `--`
2611        // was gone. Left waiting, it is reported as the missing value it is.
2612        // `require_equals` refuses a detached value: `--flag value` is a missing
2613        // value, not a flag of `"value"`. The attached form is still bound above.
2614        // Reported here rather than left waiting until the end of the line: falling
2615        // through would offer `value` to the positionals and call it an unexpected
2616        // word, which is the wrong error and a different one from usage-argv.
2617        if enable_flags
2618            && !attached_continuation
2619            && !out.flag_awaiting_value.is_empty()
2620            && out
2621                .flag_awaiting_value
2622                .last()
2623                .is_some_and(|flag| flag.require_equals)
2624        {
2625            let flag = out.flag_awaiting_value.last().unwrap();
2626            let token = flag
2627                .long
2628                .first()
2629                .map(|l| format!("--{l}"))
2630                .or_else(|| flag.short.first().map(|s| format!("-{s}")))
2631                .unwrap_or_else(|| flag.name.clone());
2632            out.errors.push(UsageErr::InvalidFlag {
2633                token: token.clone(),
2634                reason: "requires an argument".to_string(),
2635                span: (0, 0).into(),
2636                input: format!("{token} {w}"),
2637            });
2638            record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
2639            return Ok((out, overridden_flags));
2640        }
2641        if enable_flags
2642            && !out.flag_awaiting_value.is_empty()
2643            && (attached_continuation
2644                || out
2645                    .flag_awaiting_value
2646                    .last()
2647                    .is_some_and(|flag| accepts_detached_flag_value(flag, &w)))
2648        {
2649            // Held before the drain pops it: a flag whose argument is variadic keeps
2650            // taking values after this first one.
2651            let should_return = bind_pending_flag_value(
2652                spec,
2653                &out.cmd,
2654                &mut out.errors,
2655                &mut out.flags,
2656                &mut out.flag_awaiting_value,
2657                &mut w,
2658                &mut input,
2659                custom_env,
2660                trace,
2661                argv,
2662                attached_continuation,
2663            )?;
2664            if should_return {
2665                record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
2666                return Ok((out, overridden_flags));
2667            }
2668            continue;
2669        }
2670
2671        if let Some((arg, sigil, value)) = (enable_flags && !restart_seen)
2672            .then(|| match_sigil_arg_chain(&out.cmds, &w))
2673            .flatten()
2674        {
2675            if value.is_empty() {
2676                out.errors.push(UsageErr::InvalidValue {
2677                    name: arg.name.clone(),
2678                    value: w.clone(),
2679                    reason: format!("expected a value after sigil {sigil:?}"),
2680                });
2681                record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
2682                return Ok((out, overridden_flags));
2683            }
2684            let trailing_value = arg.double_dash == SpecDoubleDashChoices::Automatic;
2685            let suppress_trailing_delimiter =
2686                out.cmds.iter().any(|cmd| cmd.dont_delimit_trailing_values);
2687            let delimiter = if suppress_trailing_delimiter && trailing_value {
2688                None
2689            } else {
2690                arg.delimiter
2691            };
2692            let parts = match delimiter {
2693                Some(delimiter) => value
2694                    .split(delimiter)
2695                    .map(str::to_string)
2696                    .collect::<Vec<_>>(),
2697                None => vec![value.to_string()],
2698            };
2699            let mut refused = false;
2700            for part in &parts {
2701                if validate_choices(
2702                    spec,
2703                    &out.cmd,
2704                    &mut out.errors,
2705                    ChoiceTarget::arg(arg),
2706                    part,
2707                    arg.choices.as_ref(),
2708                    custom_env,
2709                )? {
2710                    refused = true;
2711                    break;
2712                }
2713            }
2714            if refused {
2715                record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
2716                return Ok((out, overridden_flags));
2717            }
2718            trace.record(
2719                argv,
2720                TokenRole::Sigil {
2721                    arg: Arc::new(arg.clone()),
2722                    sigil: sigil.to_string(),
2723                    values: parts.clone(),
2724                },
2725            );
2726            let key = Arc::new(arg.clone());
2727            if arg.var {
2728                let arr = out
2729                    .args
2730                    .entry(key)
2731                    .or_insert_with(|| ParseValue::MultiString(vec![]))
2732                    .try_as_multi_string_mut()
2733                    .unwrap();
2734                arr.extend(parts);
2735            } else {
2736                out.args.insert(key, ParseValue::String(value.to_string()));
2737            }
2738            if out.cmds.len() == 1 {
2739                root_positional_arg_found = true;
2740            }
2741            continue;
2742        }
2743
2744        // The `help` word where command selection stopped short of it: after a variadic flag's
2745        // values, which that scan does not count. Still command position — nothing has been
2746        // bound to a positional and no `--` has passed — so it outranks the positional that
2747        // would otherwise take it, as it does in command selection. A restart or a clause
2748        // boundary begins a later invocation, where command selection is long over.
2749        if w == "help"
2750            && !seen_double_dash
2751            && !restart_seen
2752            && out.clauses.is_empty()
2753            && out.args.is_empty()
2754            && spec.disable_help != Some(true)
2755            && !out.cmd.disable_help_subcommand
2756            && !out.cmd.subcommands.is_empty()
2757        {
2758            trace.record(
2759                argv,
2760                TokenRole::Builtin {
2761                    spelling: w.clone(),
2762                },
2763            );
2764            let target = resolve_help_target(
2765                &out.cmd,
2766                &mut input,
2767                0,
2768                mount_prefix_words(&prefix_flags),
2769                mount_outputs,
2770                trace,
2771            )?;
2772            out.errors
2773                .push(render_help_err(spec, &target, true, custom_env));
2774            record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
2775            return Ok((out, overridden_flags));
2776        }
2777
2778        if out.cmd.allow_missing_positional {
2779            next_arg_idx = cursor_skip_sigils(&out.cmd, next_arg_idx);
2780            while let Some(current) = active_args(&out.cmd).get(next_arg_idx) {
2781                if current.required || out.args.contains_key(current) {
2782                    break;
2783                }
2784                let required_after = active_args(&out.cmd)[next_arg_idx + 1..]
2785                    .iter()
2786                    .filter(|arg| arg.required && arg.sigil.is_none())
2787                    .count();
2788                if required_after == 0 {
2789                    break;
2790                }
2791                let remaining_values = 1 + input
2792                    .iter()
2793                    .filter(|token| {
2794                        (!enable_flags || !is_flag_like(&token.word))
2795                            && (!enable_flags
2796                                || restart_seen
2797                                || match_sigil_arg_chain(&out.cmds, &token.word).is_none())
2798                    })
2799                    .count();
2800                if remaining_values > required_after {
2801                    break;
2802                }
2803                next_arg_idx = cursor_skip_sigils(&out.cmd, next_arg_idx + 1);
2804            }
2805        }
2806
2807        if let Some(arg) = active_args(&out.cmd).get(next_arg_idx) {
2808            if arg.var
2809                && out.args.contains_key(arg)
2810                && arg.value_terminator.as_deref() == Some(w.as_str())
2811            {
2812                trace.record(
2813                    argv,
2814                    TokenRole::ValueTerminator {
2815                        ends: arg.name.clone(),
2816                    },
2817                );
2818                next_arg_idx += 1;
2819                continue;
2820            }
2821            // Before anything else: an arg that requires `--` accepts nothing until one has been
2822            // seen. Checking ahead of `validate_choices` keeps a discarded word from also being
2823            // reported as an invalid choice, and from reaching that function's help escape.
2824            if arg.double_dash == SpecDoubleDashChoices::Required && !seen_double_dash {
2825                report_double_dash_violation(arg, &mut out.errors, &mut double_dash_violations);
2826                trace.record(
2827                    argv,
2828                    TokenRole::Refused {
2829                        reason: format!("{} only accepts words after `--`", arg.name),
2830                    },
2831                );
2832                // Drop the word without filling the arg or advancing the cursor: every later
2833                // word hits the same arg and is rejected the same way, so the parse still ends
2834                // in an error rather than in `unexpected word`.
2835                continue;
2836            }
2837            // Split before judging, as the flag path does: after the split the word is
2838            // no longer one value, and `choices` has to be asked about each. Judging
2839            // first rejects `src:docs` against a list that both halves are on, and
2840            // names the whole word rather than the half that was wrong.
2841            let trailing_value =
2842                seen_double_dash || arg.double_dash == SpecDoubleDashChoices::Automatic;
2843            let suppress_trailing_delimiter =
2844                out.cmds.iter().any(|cmd| cmd.dont_delimit_trailing_values);
2845            let delimiter = if suppress_trailing_delimiter && trailing_value {
2846                None
2847            } else {
2848                arg.delimiter
2849            };
2850            let parts: Vec<String> = match delimiter {
2851                Some(delimiter) => w.split(delimiter).map(str::to_string).collect(),
2852                None => vec![w.clone()],
2853            };
2854            let mut refused = false;
2855            for part in &parts {
2856                if validate_choices(
2857                    spec,
2858                    &out.cmd,
2859                    &mut out.errors,
2860                    ChoiceTarget::arg(arg),
2861                    part,
2862                    arg.choices.as_ref(),
2863                    custom_env,
2864                )? {
2865                    refused = true;
2866                    break;
2867                }
2868            }
2869            if refused {
2870                record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
2871                return Ok((out, overridden_flags));
2872            }
2873            // `double_dash="automatic"` means the first value this arg takes is the last
2874            // token read as anything but data: a wrapper declaring it can forward flags
2875            // without its caller typing a `--`. Set before the value is stored, so the
2876            // rest of the command line is already past flag parsing.
2877            if arg.double_dash == SpecDoubleDashChoices::Automatic {
2878                enable_flags = false;
2879            }
2880            // A flag-like word reaching a positional while flags are still being read was
2881            // offered to every declaration and matched none: under the default
2882            // `unknown_flags="value"` it becomes data, and saying so is the difference
2883            // between "you have a typo" and "this argument took your typo".
2884            let unknown_flag = enable_flags
2885                && !positional_negative_number
2886                && is_flag_like(&w)
2887                && binding.is_none();
2888            trace.record(
2889                argv,
2890                if unknown_flag {
2891                    TokenRole::UnknownFlag {
2892                        bound_as: Some(Arc::new(arg.clone())),
2893                    }
2894                } else {
2895                    TokenRole::Arg {
2896                        arg: Arc::new(arg.clone()),
2897                        values: parts.clone(),
2898                    }
2899                },
2900            );
2901            if out.cmds.len() == 1 {
2902                root_positional_arg_found = true;
2903            }
2904            if arg.var {
2905                let arr = out
2906                    .args
2907                    .entry(Arc::new(arg.clone()))
2908                    .or_insert_with(|| ParseValue::MultiString(vec![]))
2909                    .try_as_multi_string_mut()
2910                    .unwrap();
2911                // The values this word carried, split above so that everything
2912                // downstream — `choices`, `var_max` stopping the collection, `var_min` —
2913                // counts the values the user meant rather than the words they typed.
2914                arr.extend(parts.iter().cloned());
2915                if arr.len() >= arg.var_max.unwrap_or(usize::MAX) {
2916                    next_arg_idx += 1;
2917                }
2918            } else {
2919                out.args
2920                    .insert(Arc::new(arg.clone()), ParseValue::String(w));
2921                next_arg_idx += 1;
2922            }
2923            if out
2924                .cmd
2925                .clause
2926                .as_ref()
2927                .is_some_and(|clause| clause.separator.is_none())
2928                && next_arg_idx >= active_args(&out.cmd).len()
2929            {
2930                while try_bind_default_missing(
2931                    &mut out.flags,
2932                    &mut out.flag_awaiting_value,
2933                    custom_env,
2934                    &mut out.flag_origins,
2935                )? {}
2936                if let Some(flag) = out.flag_awaiting_value.first() {
2937                    let spelling = flag
2938                        .long
2939                        .first()
2940                        .map(|long| format!("--{long}"))
2941                        .or_else(|| flag.short.first().map(|short| format!("-{short}")))
2942                        .unwrap_or_else(|| flag.name.clone());
2943                    return Err(UsageErr::InvalidFlag {
2944                        token: spelling.clone(),
2945                        reason: "requires an argument".to_string(),
2946                        span: (0, spelling.len()).into(),
2947                        input: spelling,
2948                    }
2949                    .into());
2950                }
2951                let name = out.cmd.clause.as_ref().unwrap().name.clone();
2952                finalize_current_clause(&mut out);
2953                out.arg_origins.clear();
2954                trace.record(argv, TokenRole::ClauseSeparator { name });
2955                next_arg_idx = 0;
2956                out.flag_awaiting_value.clear();
2957                reset_clause_scalar_occurrences(&out, &mut scalar_occurrences);
2958                enable_flags = true;
2959                seen_double_dash = false;
2960            }
2961            continue;
2962        }
2963        if is_help_arg(spec, &out.cmd, &w) {
2964            out.errors
2965                .push(render_help_err(spec, &out.cmd, w.len() > 2, custom_env));
2966            trace.record(
2967                argv,
2968                TokenRole::Builtin {
2969                    spelling: w.clone(),
2970                },
2971            );
2972            record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
2973            return Ok((out, overridden_flags));
2974        }
2975        if is_version_arg(spec, &out.cmds, &w) {
2976            out.errors.push(render_version_err(spec, w.len() > 2));
2977            trace.record(
2978                argv,
2979                TokenRole::Builtin {
2980                    spelling: w.clone(),
2981                },
2982            );
2983            record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
2984            return Ok((out, overridden_flags));
2985        }
2986        trace.record(
2987            argv,
2988            TokenRole::Refused {
2989                reason: "no declaration takes this word".to_string(),
2990            },
2991        );
2992        trace.close(&input);
2993        bail!("unexpected word: {w}");
2994    }
2995
2996    if let Some((target, unread)) = pending_help {
2997        out.errors
2998            .push(render_help_err(spec, &target, true, custom_env));
2999        record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &unread);
3000        return Ok((out, overridden_flags));
3001    }
3002
3003    // Resolve optional defaults before deciding whether argv is empty. This is deliberately
3004    // inside the opt-in gate: completion's partial parser must retain its pending value when
3005    // the feature is disabled.
3006    if spec.default_subcommand_on_empty
3007        && spec.default_subcommand.is_some()
3008        && out.cmds.len() == 1
3009        && !root_positional_arg_found
3010        && !seen_double_dash
3011        && !root_clause_separator_seen
3012        && out.errors.is_empty()
3013    {
3014        while try_bind_default_missing(
3015            &mut out.flags,
3016            &mut out.flag_awaiting_value,
3017            custom_env,
3018            &mut out.flag_origins,
3019        )? {}
3020        if !out.flag_awaiting_value.is_empty() {
3021            // A required flag value is still pending; leave it for full-parse diagnostics or
3022            // completion rather than routing to a synthetic child.
3023        } else if let Some(subcommand) = out
3024            .cmd
3025            .find_subcommand(spec.default_subcommand.as_deref().unwrap())
3026        {
3027            if out.cmd.args_conflicts_with_subcommands && command_arg_found {
3028                bail!(
3029                    "subcommand '{}' cannot be used with arguments on its parent command",
3030                    subcommand.name
3031                );
3032            }
3033            let mut subcommand = subcommand.clone();
3034            subcommand.mount(&mount_prefix_words(&prefix_flags), mount_outputs)?;
3035            let crossing_mount = subcommand.mounted && !out.cmd.mounted;
3036            out.merge_command_flags(&subcommand, crossing_mount);
3037            out.cmds.push(subcommand.clone());
3038            out.cmd = subcommand;
3039            command_has_argv = false;
3040            prefix_flags.clear();
3041            next_arg_idx = cursor_skip_sigils(&out.cmd, 0);
3042        }
3043    }
3044
3045    record_stop(&mut out, next_arg_idx, seen_double_dash, trace, &input);
3046    if validate_clauses {
3047        validate_clause_relationships(&mut out, &overridden_flags, custom_env, None);
3048    }
3049    let clause_flag_names = out
3050        .cmd
3051        .clause
3052        .iter()
3053        .flat_map(|clause| &clause.flags)
3054        .map(|flag| flag.name.clone())
3055        .collect::<HashSet<_>>();
3056
3057    // `out.flags` is keyed by `SpecFlag`, whose equality is intentionally name-only. Two
3058    // declarations with the same canonical name therefore share one public value entry even
3059    // when both were typed. The spelling ledger is keyed by declaration identity and retains
3060    // both, which is what exclusivity needs.
3061    let flag_was_parsed =
3062        |flag: &Arc<SpecFlag>| parsed_flag_spellings.contains_key(&(Arc::as_ptr(flag) as usize));
3063
3064    // The spellings the selected command's own declaration speaks for, on this object.
3065    //
3066    // Empty unless that declaration really is this object's: a parent and child may each
3067    // declare `--clean` without merging, leaving two flags that share a name, and the
3068    // ancestor's must not be read as the child's. The test is whether every spelling the child
3069    // declared resolves back here — true of a merged flag, and of a plain local one, but not of
3070    // an ancestor whose long form the child took over.
3071    let child_spellings = |flag: &Arc<SpecFlag>| -> HashSet<String> {
3072        let declared: HashSet<String> = out
3073            .cmd
3074            .flags
3075            .iter()
3076            .filter(|declared| declared.name == flag.name)
3077            .flat_map(flag_keys)
3078            .collect();
3079        // *Any* of them, not all. All was too strong: a child may declare a spelling that
3080        // some other inherited global already owns — `-c --clean` beside an inherited
3081        // `-c --config` — and that collision is resolved in the other global's favor, so the
3082        // child's `-c` resolves elsewhere. Requiring every spelling to land here let one
3083        // unrelated collision disown the child from the `--clean` it plainly does own.
3084        //
3085        // Still enough to tell the two-object case apart, which is what this guards: when a
3086        // child re-declares a global as global, the child's own spellings resolve to the
3087        // child's separate flag, so none of them lands on the ancestor's.
3088        let speaks_for_this_flag = declared.iter().any(|spelling| {
3089            out.available_flags
3090                .get(spelling)
3091                .is_some_and(|available| Arc::ptr_eq(available, flag))
3092        });
3093        if speaks_for_this_flag {
3094            declared
3095        } else {
3096            HashSet::new()
3097        }
3098    };
3099
3100    // Whose `exclusive` an occurrence activates, as `(the child's, an ancestor's)`.
3101    //
3102    // A child that re-declares an inherited global merges into one object answering to two
3103    // alias sets whose declarations may disagree, so there is no single owner to name: the
3104    // child owns the spellings it declared and the ancestor keeps the ones only it declared.
3105    // Both sides can be in play at once — `run -c --clean` is the ancestor's alias and the
3106    // child's in one invocation — and each carries its own declaration's answer.
3107    let exclusivity_in_play = |flag: &Arc<SpecFlag>| -> (bool, bool) {
3108        let child = child_spellings(flag);
3109        let child_exclusive = !child.is_empty()
3110            && out
3111                .cmd
3112                .flags
3113                .iter()
3114                .any(|declared| declared.name == flag.name && declared.exclusive);
3115        match parsed_flag_spellings.get(&(Arc::as_ptr(flag) as usize)) {
3116            Some(spellings) => (
3117                child_exclusive && spellings.iter().any(|s| child.contains(s)),
3118                flag.exclusive && spellings.iter().any(|s| !child.contains(s)),
3119            ),
3120            // An environment value has no spelling to attribute it by. The declaration the
3121            // selected command has in scope is the one that answers — which is the child's
3122            // when it re-declared the flag, and the ancestor's when it did not.
3123            None => (child_exclusive, flag.exclusive && child.is_empty()),
3124        }
3125    };
3126
3127    let exclusive_occurrence = |flag: &Arc<SpecFlag>| {
3128        let (child, ancestor) = exclusivity_in_play(flag);
3129        child || ancestor
3130    };
3131
3132    // clap's `exclusive` is also an escape from requiredness: `--version` has to work on a
3133    // command that otherwise needs an input. Companions are still diagnosed below, but an
3134    // exclusive occurrence suppresses the missing-value checks that would make it unusable
3135    // whether it was alone or not.
3136    let exclusive_present = unique_flags(out.available_flags.values().chain(out.flags.keys()))
3137        .filter(|flag| !clause_flag_names.contains(&flag.name))
3138        .any(|flag| {
3139            exclusive_occurrence(flag)
3140                && !overridden_flags.contains(&flag.name)
3141                && (flag_was_parsed(flag) || flag_has_env(flag, custom_env))
3142        });
3143    let ancestor_flags = ancestor_flags(&out);
3144    let requirements_apply = |command_index: usize| {
3145        command_index + 1 == out.cmds.len() || !out.cmds[command_index].subcommand_negates_reqs
3146    };
3147
3148    if out.cmd.arg_required_else_help && !command_has_argv {
3149        out.errors
3150            .push(render_help_err(spec, &out.cmd, false, custom_env));
3151    }
3152
3153    // A command that says it needs a subcommand, given none. Checked on `out.cmd` and nowhere
3154    // else, because `out.cmd` *is* the command the words reached: had a subcommand been taken,
3155    // the child would be here instead. The spec has carried `subcommand_required` since it was
3156    // added for the derive, and this parser never read it — so `mise generate` parsed as a
3157    // complete invocation while usage-argv and clap both refused it.
3158    if out.cmd.subcommand_required && !out.cmd.subcommands.is_empty() && out.external.is_none() {
3159        let mut names: Vec<&str> = out
3160            .cmd
3161            .subcommands
3162            .iter()
3163            // Aliases share a map entry with the name they point at; listing both would offer
3164            // the same command twice under two spellings.
3165            .filter(|(name, sub)| sub.name == **name && !sub.hide)
3166            .map(|(name, _)| name.as_str())
3167            .collect();
3168        names.sort_unstable();
3169        out.errors.push(UsageErr::MissingSubcommand(
3170            out.cmd.name.clone(),
3171            names.join(", "),
3172        ));
3173    }
3174
3175    // Not `skip(out.args.len())`: a `--` may have jumped the cursor past an arg that stayed
3176    // empty, so position and fill count can disagree. Ask `out.args` which args it holds.
3177    if !exclusive_present {
3178        for arg in out
3179            .cmds
3180            .iter()
3181            .enumerate()
3182            .filter(|(index, _)| requirements_apply(*index))
3183            .flat_map(|(_, cmd)| &cmd.args)
3184        {
3185            if out.args.contains_key(arg) {
3186                continue;
3187            }
3188            // Already reported as needing a `--`; one mistake should not yield two messages.
3189            if double_dash_violations.contains(&arg.name) {
3190                continue;
3191            }
3192            let required_if = arg.required_if.iter().any(|selector| {
3193                selector_is_explicit(selector, &out, &overridden_flags, custom_env)
3194            });
3195            let required_if_eq = arg.required_if_eq.iter().any(|condition| {
3196                selector_explicit_has_value(
3197                    &condition.selector,
3198                    &condition.value,
3199                    &out,
3200                    &overridden_flags,
3201                    custom_env,
3202                )
3203            });
3204            let required_if_eq_all = !arg.required_if_eq_all.is_empty()
3205                && arg.required_if_eq_all.iter().all(|condition| {
3206                    selector_explicit_has_value(
3207                        &condition.selector,
3208                        &condition.value,
3209                        &out,
3210                        &overridden_flags,
3211                        custom_env,
3212                    )
3213                });
3214            let unless_any = arg.required_unless.iter().any(|selector| {
3215                selector_is_explicit(selector, &out, &overridden_flags, custom_env)
3216            });
3217            let unless_all = !arg.required_unless_all.is_empty()
3218                && arg.required_unless_all.iter().all(|selector| {
3219                    selector_is_explicit(selector, &out, &overridden_flags, custom_env)
3220                });
3221            let required_unless = !(unless_any
3222                || unless_all
3223                || (arg.required_unless.is_empty() && arg.required_unless_all.is_empty()));
3224            if (arg.required
3225                || required_if
3226                || required_if_eq
3227                || required_if_eq_all
3228                || required_unless)
3229                && arg.default.is_empty()
3230            {
3231                // Check if there's an env var available (custom env map takes precedence)
3232                let has_env = arg
3233                    .env
3234                    .as_ref()
3235                    .is_some_and(|env_var| env_contains(custom_env, env_var));
3236                if !has_env {
3237                    out.errors.push(UsageErr::MissingArg(arg.name.clone()));
3238                }
3239            }
3240        }
3241    }
3242
3243    // Conflicts are a question about the invocation as a whole rather than about any one
3244    // token, so they are checked here beside the requirement checks rather than at the
3245    // point a flag is matched — the flag it conflicts with may still be ahead of it.
3246    // Its own loop: the requirement loop below skips the flags that *were* given, which
3247    // is exactly the set this needs.
3248    //
3249    // A value from the environment counts on both sides, matching what
3250    // `selector_is_explicit` says about the other flag: the question is whether a flag
3251    // has a value, not how it got one. That is what clap does, and an asymmetric rule
3252    // would make the same pair of flags a conflict or not depending on which one
3253    // happened to be typed.
3254    for flag in unique_flags(out.available_flags.values().chain(&ancestor_flags))
3255        .filter(|flag| !clause_flag_names.contains(&flag.name))
3256    {
3257        let given = out.flags.contains_key(flag) || flag_has_env(flag, custom_env);
3258        if !given || overridden_flags.contains(&flag.name) {
3259            continue;
3260        }
3261        for other in &flag.conflicts {
3262            if selector_is_explicit(other, &out, &overridden_flags, custom_env) {
3263                out.errors.push(UsageErr::InvalidFlag {
3264                    token: format!("--{}", flag.name),
3265                    reason: format!("conflicts with {other}"),
3266                    span: (0, 0).into(),
3267                    input: format!("--{} {other}", flag.name),
3268                });
3269            }
3270        }
3271        // The positive form, checked in the same pass and under the same rule: a value
3272        // from the environment satisfies a requirement, because the question is whether
3273        // the other flag has a value rather than how it got one. A flag that was
3274        // overridden away has not been given, so it cannot satisfy anything either —
3275        // which is what `selector_is_explicit` already accounts for.
3276        //
3277        // Reported as the missing flag rather than as something wrong with the flag that
3278        // named it, which is what clap says too: an unmet `requires` is a required
3279        // argument that was not provided. Named by its own name, resolved through the
3280        // same matcher, so a `requires="-f"` reports `--force` rather than the selector.
3281        let owner = out
3282            .cmds
3283            .iter()
3284            .rposition(|cmd| cmd.flags.iter().any(|declared| declared.name == flag.name))
3285            .unwrap_or(out.cmds.len() - 1);
3286        if !exclusive_present && requirements_apply(owner) {
3287            for other in &flag.requires {
3288                if !selector_is_satisfied(other, &out, &overridden_flags, custom_env) {
3289                    let name = selector_flag_name(other, &out).unwrap_or_else(|| other.clone());
3290                    if other.starts_with('-') {
3291                        out.errors.push(UsageErr::MissingFlag(name));
3292                    } else {
3293                        out.errors.push(UsageErr::MissingArg(name));
3294                    }
3295                }
3296            }
3297            for condition in &flag.requires_if {
3298                if explicit_flag_has_value(flag, &condition.value, &out, custom_env)
3299                    && !selector_is_satisfied(
3300                        &condition.requires,
3301                        &out,
3302                        &overridden_flags,
3303                        custom_env,
3304                    )
3305                {
3306                    let name = selector_flag_name(&condition.requires, &out)
3307                        .unwrap_or_else(|| condition.requires.clone());
3308                    out.errors.push(UsageErr::MissingFlag(name));
3309                }
3310            }
3311        }
3312    }
3313
3314    // Positionals can declare the same pairwise conflict as flags. Their selector is
3315    // the bare argument name, while a flag keeps its dashed spelling.
3316    for (command_index, arg) in out
3317        .cmds
3318        .iter()
3319        .enumerate()
3320        .flat_map(|(index, cmd)| cmd.args.iter().map(move |arg| (index, arg)))
3321    {
3322        let given = arg_is_explicit(arg, &out, custom_env);
3323        if !given {
3324            continue;
3325        }
3326        for other in &arg.conflicts {
3327            if selector_is_explicit(other, &out, &overridden_flags, custom_env) {
3328                out.errors.push(UsageErr::InvalidFlag {
3329                    token: arg.name.clone(),
3330                    reason: format!("conflicts with {other}"),
3331                    span: (0, 0).into(),
3332                    input: format!("{} {other}", arg.name),
3333                });
3334            }
3335        }
3336        if !exclusive_present && requirements_apply(command_index) {
3337            for other in &arg.requires {
3338                if !selector_is_satisfied(other, &out, &overridden_flags, custom_env) {
3339                    let name = selector_flag_name(other, &out).unwrap_or_else(|| other.clone());
3340                    if other.starts_with('-') {
3341                        out.errors.push(UsageErr::MissingFlag(name));
3342                    } else {
3343                        out.errors.push(UsageErr::MissingArg(name));
3344                    }
3345                }
3346            }
3347        }
3348    }
3349
3350    // An exclusive flag is the whole-command form of a conflict: `--version` means the
3351    // rest of the line has nothing to act on. Everything the invocation supplied counts,
3352    // positionals included, which is what distinguishes it from being in a group with
3353    // every other flag.
3354    //
3355    // Only what was *given*, as `conflicts` reads it: a defaulted flag standing beside an
3356    // exclusive one is nobody saying anything, and counting it would make the exclusive
3357    // flag unusable on any command that has a default. Environment values do count, also as
3358    // `conflicts` reads them, so the spec parser and the derive agree.
3359    for flag in unique_flags(out.available_flags.values().chain(out.flags.keys()))
3360        .filter(|flag| !clause_flag_names.contains(&flag.name))
3361    {
3362        // `SpecFlag` equality is intentionally name-only for the public parsed-value map,
3363        // but re-declared aliases can leave distinct declarations with that same name in
3364        // scope. Exclusivity is about the declaration the typed spelling resolved to, so
3365        // compare the parser's `Arc`s by identity here.
3366        let given = flag_was_parsed(flag) || flag_has_env(flag, custom_env);
3367        if !exclusive_occurrence(flag) || !given || overridden_flags.contains(&flag.name) {
3368            continue;
3369        }
3370        let other_flag = unique_flags(out.available_flags.values().chain(out.flags.keys()))
3371            .filter(|other| !clause_flag_names.contains(&other.name))
3372            .find(|other| {
3373                !Arc::ptr_eq(other, flag)
3374                    && !overridden_flags.contains(&other.name)
3375                    && (flag_was_parsed(other) || flag_has_env(other, custom_env))
3376            })
3377            .map(|other| format!("--{}", other.name));
3378        let other_arg = active_args(&out.cmd).iter().find(|arg| {
3379            out.args.keys().any(|given| given.name == arg.name)
3380                || out
3381                    .clauses
3382                    .values()
3383                    .flatten()
3384                    .any(|instance| instance.keys().any(|given| given.name == arg.name))
3385                || arg
3386                    .env
3387                    .as_ref()
3388                    .is_some_and(|env| env_contains(custom_env, env))
3389        });
3390        // Selecting a child is company for an exclusive flag declared by an ancestor. An
3391        // exclusive flag belonging to the child itself does not conflict with the command word
3392        // needed to reach that child — so the question is not who owns the flag but whose
3393        // exclusivity is the one being enforced, which is what `exclusivity_in_play` already
3394        // separated.
3395        let (_, ancestor_exclusivity) = exclusivity_in_play(flag);
3396        let selected_subcommand =
3397            (out.cmds.len() > 1 && ancestor_exclusivity).then(|| out.cmd.name.clone());
3398        let other = other_flag
3399            .or_else(|| other_arg.map(|arg| format!("<{}>", arg.name)))
3400            .or(selected_subcommand);
3401        if let Some(other) = other {
3402            out.errors.push(UsageErr::InvalidFlag {
3403                token: format!("--{}", flag.name),
3404                reason: format!("must be given on its own, and {other} was given too"),
3405                span: (0, 0).into(),
3406                input: format!("--{} {other}", flag.name),
3407            });
3408        }
3409    }
3410
3411    // Groups, checked once per group rather than per flag: both questions a group asks —
3412    // how many members were given, and whether that is enough — are about the set, which
3413    // is the whole reason a group exists rather than a pile of pairwise conflicts.
3414    //
3415    // The same "given" rule as everything else here, so a member filled from the
3416    // environment or a default counts.
3417    // Every command in the chain, not only the selected one: a group may name global
3418    // flags, which belong to an ancestor and are declared there.
3419    let mut group_errors: Vec<UsageErr> = Vec::new();
3420    for (command_index, group) in out
3421        .cmds
3422        .iter()
3423        .enumerate()
3424        .flat_map(|(index, cmd)| cmd.groups.iter().map(move |group| (index, group)))
3425    {
3426        // Counted by the *flag* a selector resolves to, not by the selector. `-f` and
3427        // `--file` are two spellings of one flag, and a group naming both — or naming one
3428        // flag twice — would otherwise report that flag as conflicting with itself the
3429        // moment it was given. Deduplicated rather than refused where the group is
3430        // written, because listing both spellings is redundant, not wrong.
3431        let mut given: Vec<&str> = Vec::new();
3432        let mut seen: Vec<String> = Vec::new();
3433        for selector in &group.members {
3434            if !selector_is_explicit(selector, &out, &overridden_flags, custom_env) {
3435                continue;
3436            }
3437            let name = selector_flag_name(selector, &out).unwrap_or_else(|| selector.clone());
3438            if seen.contains(&name) {
3439                continue;
3440            }
3441            seen.push(name);
3442            given.push(selector.as_str());
3443        }
3444        if !group.multiple && given.len() > 1 {
3445            group_errors.push(UsageErr::InvalidFlag {
3446                token: given[1].to_string(),
3447                reason: format!("cannot be used with {} in group {}", given[0], group.name),
3448                span: (0, 0).into(),
3449                input: format!("{} {}", given[0], given[1]),
3450            });
3451        }
3452        // Requiredness is a *positive* rule, so it reads a default as filling a member —
3453        // the rule `requires` follows. That is also why it cannot reuse `given` above:
3454        // exclusivity must count only what was supplied, or a defaulted member would
3455        // collide with the sibling the user actually typed.
3456        let satisfied = group
3457            .members
3458            .iter()
3459            .any(|selector| selector_is_satisfied(selector, &out, &overridden_flags, custom_env));
3460        if group.required && requirements_apply(command_index) && !satisfied && !exclusive_present {
3461            // The members are what a user has to type, so they are in the message; the
3462            // group's name is there too, since a command with several groups would
3463            // otherwise report the same sentence twice with nothing to tell them apart.
3464            group_errors.push(UsageErr::MissingGroup {
3465                group: group.name.clone(),
3466                members: group.members.join(", "),
3467            });
3468        }
3469    }
3470    out.errors.extend(group_errors);
3471
3472    if !exclusive_present {
3473        for flag in unique_flags(out.available_flags.values().chain(&ancestor_flags))
3474            .filter(|flag| !clause_flag_names.contains(&flag.name))
3475        {
3476            let owner = out
3477                .cmds
3478                .iter()
3479                .rposition(|cmd| cmd.flags.iter().any(|declared| declared.name == flag.name))
3480                .unwrap_or(out.cmds.len() - 1);
3481            if !requirements_apply(owner) {
3482                continue;
3483            }
3484            if out.flags.contains_key(flag) || overridden_flags.contains(&flag.name) {
3485                continue;
3486            }
3487            let has_default =
3488                !flag.default.is_empty() || flag.arg.iter().any(|a| !a.default.is_empty());
3489            let has_env = flag_has_env(flag, custom_env);
3490            let required_if = flag.required_if.iter().any(|selector| {
3491                selector_is_explicit(selector, &out, &overridden_flags, custom_env)
3492            });
3493            let required_if_eq = flag.required_if_eq.iter().any(|condition| {
3494                selector_explicit_has_value(
3495                    &condition.selector,
3496                    &condition.value,
3497                    &out,
3498                    &overridden_flags,
3499                    custom_env,
3500                )
3501            });
3502            let required_if_eq_all = !flag.required_if_eq_all.is_empty()
3503                && flag.required_if_eq_all.iter().all(|condition| {
3504                    selector_explicit_has_value(
3505                        &condition.selector,
3506                        &condition.value,
3507                        &out,
3508                        &overridden_flags,
3509                        custom_env,
3510                    )
3511                });
3512            let unless_any = flag.required_unless.iter().any(|selector| {
3513                selector_is_explicit(selector, &out, &overridden_flags, custom_env)
3514            });
3515            let unless_all = !flag.required_unless_all.is_empty()
3516                && flag.required_unless_all.iter().all(|selector| {
3517                    selector_is_explicit(selector, &out, &overridden_flags, custom_env)
3518                });
3519            let required_unless = !(unless_any
3520                || unless_all
3521                || (flag.required_unless.is_empty() && flag.required_unless_all.is_empty()));
3522            if (flag.required
3523                || required_if
3524                || required_if_eq
3525                || required_if_eq_all
3526                || required_unless)
3527                && !has_default
3528                && !has_env
3529            {
3530                out.errors.push(UsageErr::MissingFlag(flag.name.clone()));
3531            }
3532        }
3533    }
3534
3535    // Validate var_min/var_max constraints for variadic args
3536    for (arg, value) in &out.args {
3537        if arg.var
3538            && let ParseValue::MultiString(values) = value
3539        {
3540            if let Some(min) = arg.var_min
3541                && values.len() < min
3542            {
3543                out.errors.push(UsageErr::VarArgTooFew {
3544                    name: arg.name.clone(),
3545                    min,
3546                    got: values.len(),
3547                });
3548            }
3549            if let Some(max) = arg.var_max
3550                && values.len() > max
3551            {
3552                out.errors.push(UsageErr::VarArgTooMany {
3553                    name: arg.name.clone(),
3554                    max,
3555                    got: values.len(),
3556                });
3557            }
3558        }
3559    }
3560
3561    // Validate var_min/var_max constraints for variadic flags. These are bounds on
3562    // repeated occurrences of the flag itself. Bounds on its nested argument are enforced
3563    // by binding once per occurrence, where the per-occurrence count is still available.
3564    for flag in unique_flags(out.available_flags.values())
3565        .filter(|flag| !clause_flag_names.contains(&flag.name))
3566    {
3567        if flag.var {
3568            let bound = match out.flags.get(flag) {
3569                Some(ParseValue::MultiString(values)) => values.len(),
3570                Some(ParseValue::MultiBool(values)) => values.len(),
3571                Some(_) => 1,
3572                None => 0,
3573            };
3574            // A partial parse deliberately leaves the final value-optional flag pending so
3575            // completion can still answer for it. It is nevertheless a real occurrence for
3576            // the repeated flag's bounds; the full parser closes it just after this phase.
3577            let pending = out
3578                .flag_awaiting_value
3579                .iter()
3580                .filter(|pending| {
3581                    Arc::ptr_eq(pending, flag)
3582                        && (pending.value_optional || pending.default_missing.is_some())
3583                })
3584                .count();
3585            let count = bound + pending;
3586            if count == 0 {
3587                continue;
3588            }
3589            if let Some(min) = flag.var_min
3590                && count < min
3591            {
3592                out.errors.push(UsageErr::VarFlagTooFew {
3593                    name: flag.name.clone(),
3594                    min,
3595                    got: count,
3596                });
3597            }
3598            if let Some(max) = flag.var_max
3599                && count > max
3600            {
3601                out.errors.push(UsageErr::VarFlagTooMany {
3602                    name: flag.name.clone(),
3603                    max,
3604                    got: count,
3605                });
3606            }
3607        }
3608    }
3609
3610    Ok((out, overridden_flags))
3611}
3612
3613fn validate_expression(
3614    name: &str,
3615    expression: Option<&str>,
3616    message: Option<&str>,
3617    parsed: &ParseValue,
3618    errors: &mut Vec<UsageErr>,
3619) {
3620    let Some(expression) = expression else {
3621        return;
3622    };
3623    #[cfg(not(feature = "validation"))]
3624    let _ = expression;
3625    let values: &[String] = match parsed {
3626        ParseValue::String(value) => std::slice::from_ref(value),
3627        ParseValue::MultiString(values) => values,
3628        ParseValue::Bool(_) | ParseValue::MultiBool(_) => return,
3629    };
3630    #[cfg(feature = "validation")]
3631    for value in values {
3632        let reason = match usage_validation::validate(expression, value) {
3633            Ok(true) => continue,
3634            Ok(false) => message
3635                .unwrap_or("does not satisfy the validation expression")
3636                .to_string(),
3637            Err(error) => format!("validation expression failed: {error}"),
3638        };
3639        errors.push(UsageErr::InvalidValue {
3640            name: name.to_string(),
3641            value: value.clone(),
3642            reason,
3643        });
3644        break;
3645    }
3646    #[cfg(not(feature = "validation"))]
3647    if let Some(value) = values.first() {
3648        let _ = message;
3649        errors.push(UsageErr::InvalidValue {
3650            name: name.to_string(),
3651            value: value.clone(),
3652            reason: "expression validation requires the `validation` feature".to_string(),
3653        });
3654    }
3655}
3656
3657#[cfg(all(test, not(feature = "validation")))]
3658mod optional_validation_tests {
3659    use crate::{Spec, parse};
3660
3661    #[test]
3662    fn validation_declarations_require_the_opt_in_runtime_feature() {
3663        let spec: Spec = r#"
3664name "ex"
3665bin "ex"
3666arg "<port>" validate="int(value) > 0"
3667        "#
3668        .parse()
3669        .unwrap();
3670        let error = parse(&spec, &["ex".to_string(), "1".to_string()]).unwrap_err();
3671        assert!(
3672            error
3673                .to_string()
3674                .contains("requires the `validation` feature"),
3675            "{error:?}"
3676        );
3677    }
3678}
3679
3680fn flag_matches_selector(flag: &SpecFlag, selector: &str) -> bool {
3681    flag.name == selector || flag_keys(flag).iter().any(|key| key == selector)
3682}
3683
3684fn flags_override(overrider: &SpecFlag, overridden: &SpecFlag) -> bool {
3685    overrider
3686        .overrides
3687        .iter()
3688        .any(|selector| flag_matches_selector(overridden, selector))
3689}
3690
3691fn apply_prefix_flag_overrides(
3692    prefix_flags: &mut Vec<(Arc<SpecFlag>, Vec<String>)>,
3693    flag: Arc<SpecFlag>,
3694) {
3695    prefix_flags
3696        .retain(|(other, _)| !(flags_override(&flag, other) || flags_override(other, &flag)));
3697}
3698
3699/// The command `help <command...>` asks about: the words at `at` that name subcommands, walked
3700/// from `from` and removed from `input`. Each step runs the mounts of the command it enters,
3701/// as a descent does, handing them `prefix` (the global flags typed before the first command)
3702/// once and then nothing. The words are a question rather than an invocation, so they are
3703/// resolved here instead of descended into.
3704fn resolve_help_target(
3705    from: &SpecCommand,
3706    input: &mut VecDeque<Token>,
3707    at: usize,
3708    mut prefix: Vec<String>,
3709    mount_outputs: Option<&HashMap<String, String>>,
3710    trace: &mut Trace,
3711) -> miette::Result<SpecCommand> {
3712    let mut target = from.clone();
3713    while let Some(sub) = input
3714        .get(at)
3715        .and_then(|next| target.find_subcommand(&next.word))
3716    {
3717        let mut sub = sub.clone();
3718        sub.mount(&prefix, mount_outputs)?;
3719        prefix.clear();
3720        let named = input.remove(at).unwrap();
3721        trace.record(
3722            named.argv,
3723            TokenRole::Command {
3724                name: sub.name.clone(),
3725            },
3726        );
3727        target = sub;
3728    }
3729    Ok(target)
3730}
3731
3732fn mount_prefix_words(prefix_flags: &[(Arc<SpecFlag>, Vec<String>)]) -> Vec<String> {
3733    prefix_flags
3734        .iter()
3735        .flat_map(|(_, words)| words.iter().cloned())
3736        .collect()
3737}
3738
3739fn env_contains(custom_env: Option<&HashMap<String, String>>, env_var: &str) -> bool {
3740    match custom_env {
3741        Some(env) => env.contains_key(env_var),
3742        None => std::env::var(env_var).is_ok(),
3743    }
3744}
3745
3746fn flag_has_env(flag: &SpecFlag, custom_env: Option<&HashMap<String, String>>) -> bool {
3747    flag.env_names()
3748        .any(|env_var| env_contains(custom_env, env_var))
3749}
3750
3751fn fallback_is_true(value: &str) -> bool {
3752    matches!(value, "1" | "true" | "True" | "TRUE")
3753}
3754
3755fn split_fallback_values(values: &[String], delimiter: Option<char>) -> Vec<String> {
3756    match delimiter {
3757        Some(delimiter) => values
3758            .iter()
3759            .flat_map(|value| value.split(delimiter).map(str::to_string))
3760            .collect(),
3761        None => values.to_vec(),
3762    }
3763}
3764
3765fn validate_arg_fallback_count(arg: &SpecArg, count: usize, errors: &mut Vec<UsageErr>) {
3766    if let Some(min) = arg.var_min
3767        && count < min
3768    {
3769        errors.push(UsageErr::VarArgTooFew {
3770            name: arg.name.clone(),
3771            min,
3772            got: count,
3773        });
3774    }
3775    if let Some(max) = arg.var_max
3776        && count > max
3777    {
3778        errors.push(UsageErr::VarArgTooMany {
3779            name: arg.name.clone(),
3780            max,
3781            got: count,
3782        });
3783    }
3784}
3785
3786fn validate_flag_fallback_count(flag: &SpecFlag, count: usize, errors: &mut Vec<UsageErr>) {
3787    if let Some(min) = flag.var_min
3788        && count < min
3789    {
3790        errors.push(UsageErr::VarFlagTooFew {
3791            name: flag.name.clone(),
3792            min,
3793            got: count,
3794        });
3795    }
3796    if let Some(max) = flag.var_max
3797        && count > max
3798    {
3799        errors.push(UsageErr::VarFlagTooMany {
3800            name: flag.name.clone(),
3801            max,
3802            got: count,
3803        });
3804    }
3805}
3806
3807fn validate_flag_arg_fallback_count(
3808    flag: &SpecFlag,
3809    arg: &SpecArg,
3810    count: usize,
3811    errors: &mut Vec<UsageErr>,
3812) {
3813    if let Some(min) = arg.var_min
3814        && count < min
3815    {
3816        errors.push(UsageErr::VarFlagTooFew {
3817            name: flag.name.clone(),
3818            min,
3819            got: count,
3820        });
3821    }
3822    if let Some(max) = arg.var_max
3823        && count > max
3824    {
3825        errors.push(UsageErr::VarFlagTooMany {
3826            name: flag.name.clone(),
3827            max,
3828            got: count,
3829        });
3830    }
3831}
3832
3833/// Bind a fallback the way an unconditional `default` does: one value, or several
3834/// for `var`, and choices checked the same way.
3835fn bind_flag_fallback(
3836    flag: &Arc<SpecFlag>,
3837    values: &[String],
3838    out: &mut ParseOutput,
3839    custom_env: Option<&HashMap<String, String>>,
3840    origin: ValueOrigin,
3841) -> Result<(), miette::Error> {
3842    let Some(value) = flag_fallback_value(flag, values, &mut out.errors, custom_env)? else {
3843        return Ok(());
3844    };
3845    out.flags.insert(Arc::clone(flag), value);
3846    out.flag_origins
3847        .entry(Arc::clone(flag))
3848        .or_default()
3849        .push(origin);
3850    Ok(())
3851}
3852
3853fn flag_fallback_value(
3854    flag: &SpecFlag,
3855    values: &[String],
3856    errors: &mut Vec<UsageErr>,
3857    custom_env: Option<&HashMap<String, String>>,
3858) -> Result<Option<ParseValue>, miette::Error> {
3859    if values.is_empty() {
3860        return Ok(None);
3861    }
3862    if let Some(arg) = flag.arg.as_ref() {
3863        let values = split_fallback_values(values, arg.delimiter);
3864        if flag.var || arg.var {
3865            if flag.var {
3866                validate_flag_fallback_count(flag, values.len(), errors);
3867            }
3868            if arg.var {
3869                validate_flag_arg_fallback_count(flag, arg, values.len(), errors);
3870            }
3871            validate_choice_values(
3872                ChoiceTarget::option(flag),
3873                &values,
3874                arg.choices.as_ref(),
3875                custom_env,
3876            )?;
3877            Ok(Some(ParseValue::MultiString(values)))
3878        } else {
3879            let value = values.into_iter().next().unwrap_or_default();
3880            validate_choice_value(
3881                ChoiceTarget::option(flag),
3882                &value,
3883                arg.choices.as_ref(),
3884                custom_env,
3885            )?;
3886            Ok(Some(ParseValue::String(value)))
3887        }
3888    } else if flag.var {
3889        validate_flag_fallback_count(flag, values.len(), errors);
3890        let bools: Vec<bool> = values.iter().map(|s| fallback_is_true(s)).collect();
3891        Ok(Some(ParseValue::MultiBool(bools)))
3892    } else {
3893        Ok(Some(ParseValue::Bool(fallback_is_true(&values[0]))))
3894    }
3895}
3896
3897/// Fill scoped flags inside the clause instances argv created.
3898///
3899/// The returned sets contain argv and environment sources only. Relationship
3900/// validation uses them to keep defaults from becoming explicit conflicts while
3901/// still allowing a fallback value to satisfy a required scoped flag.
3902fn apply_clause_flag_fallbacks(
3903    out: &mut ParseOutput,
3904    overridden_flags: &HashSet<String>,
3905    custom_env: Option<&HashMap<String, String>>,
3906) -> Result<Option<Vec<HashSet<String>>>, miette::Error> {
3907    let Some(clause) = out.cmd.clause.clone() else {
3908        return Ok(None);
3909    };
3910    let Some(positional_instances) = out.clauses.get(&clause.name) else {
3911        return Ok(None);
3912    };
3913    let positional_instances = positional_instances.clone();
3914    let mut flag_instances = out
3915        .clause_flags
3916        .shift_remove(&clause.name)
3917        .unwrap_or_default();
3918    flag_instances.resize_with(positional_instances.len(), IndexMap::new);
3919    let get_env = |key: &str| -> Option<String> {
3920        custom_env
3921            .and_then(|values| values.get(key).cloned())
3922            .or_else(|| {
3923                custom_env
3924                    .is_none()
3925                    .then(|| std::env::var(key).ok())
3926                    .flatten()
3927            })
3928    };
3929    let mut explicit_instances = Vec::with_capacity(flag_instances.len());
3930
3931    for (instance_index, scoped) in flag_instances.iter_mut().enumerate() {
3932        let positional = &positional_instances[instance_index];
3933        let mut explicit = scoped
3934            .keys()
3935            .map(|flag| flag.name.clone())
3936            .collect::<HashSet<_>>();
3937
3938        // Environment first so every default_if sees all explicit sources,
3939        // independent of declaration order.
3940        for declared in &clause.flags {
3941            let flag = Arc::new(declared.clone());
3942            if scoped.contains_key(&flag) {
3943                continue;
3944            }
3945            let Some((env_name, env_value)) = first_set_env(declared.env_names(), &get_env) else {
3946                continue;
3947            };
3948            if let Some(warning) = flag_deprecation(declared) {
3949                out.warnings.push(warning);
3950            }
3951            if flag_env_is_deprecated(declared, env_name) {
3952                out.warnings
3953                    .push(Warning::env(env_name, flag_current_env(declared)));
3954            }
3955            if let Some(value) = flag_fallback_value(
3956                declared,
3957                std::slice::from_ref(&env_value),
3958                &mut out.errors,
3959                custom_env,
3960            )? {
3961                scoped.insert(flag, value);
3962                explicit.insert(declared.name.clone());
3963            }
3964        }
3965
3966        let condition_matches =
3967            |condition: &crate::SpecDefaultIf| {
3968                if let Some(flag) = clause
3969                    .flags
3970                    .iter()
3971                    .find(|flag| flag_matches_selector(flag, &condition.selector))
3972                {
3973                    if !explicit.contains(&flag.name) {
3974                        return false;
3975                    }
3976                    return condition.when.as_ref().is_none_or(|expected| {
3977                        scoped
3978                            .iter()
3979                            .find(|(present, _)| present.name == flag.name)
3980                            .is_some_and(|(_, value)| parse_value_has(value, expected))
3981                    });
3982                }
3983                if let Some(arg) = clause.args.iter().find(|arg| {
3984                    !condition.selector.starts_with('-') && arg.name == condition.selector
3985                }) {
3986                    return positional.get(arg).is_some_and(|value| {
3987                        condition
3988                            .when
3989                            .as_ref()
3990                            .is_none_or(|expected| parse_value_has(value, expected))
3991                    });
3992                }
3993                let command_flag = out
3994                    .available_flags
3995                    .values()
3996                    .chain(out.flags.keys())
3997                    .filter(|flag| !is_clause_scoped_flag(out, flag))
3998                    .find(|flag| flag_matches_selector(flag, &condition.selector));
3999                command_flag.is_some_and(|flag| {
4000                    !overridden_flags.contains(&flag.name)
4001                        && command_flag_has_explicit_source(flag, out)
4002                        && condition.when.as_ref().is_none_or(|expected| {
4003                            out.flags
4004                                .get(flag)
4005                                .is_some_and(|value| parse_value_has(value, expected))
4006                        })
4007                })
4008            };
4009
4010        let conditional = clause
4011            .flags
4012            .iter()
4013            .filter(|flag| !scoped.keys().any(|present| present.name == flag.name))
4014            .filter_map(|flag| {
4015                flag.default_if
4016                    .iter()
4017                    .find(|condition| condition_matches(condition))
4018                    .map(|condition| (flag.clone(), condition.value.clone()))
4019            })
4020            .collect::<Vec<_>>();
4021        for (declared, value) in conditional {
4022            if let Some(value) = flag_fallback_value(
4023                &declared,
4024                std::slice::from_ref(&value),
4025                &mut out.errors,
4026                custom_env,
4027            )? {
4028                scoped.insert(Arc::new(declared), value);
4029            }
4030        }
4031
4032        for declared in &clause.flags {
4033            let flag = Arc::new(declared.clone());
4034            if scoped.contains_key(&flag) {
4035                continue;
4036            }
4037            let values = if !declared.default.is_empty() {
4038                &declared.default
4039            } else if let Some(arg) = declared.arg.as_ref().filter(|arg| !arg.default.is_empty()) {
4040                &arg.default
4041            } else {
4042                continue;
4043            };
4044            if let Some(value) = flag_fallback_value(declared, values, &mut out.errors, custom_env)?
4045            {
4046                scoped.insert(flag, value);
4047            }
4048        }
4049        explicit_instances.push(explicit);
4050    }
4051
4052    out.clause_flags.insert(clause.name, flag_instances);
4053    Ok(Some(explicit_instances))
4054}
4055
4056fn command_flag_has_explicit_source(flag: &SpecFlag, out: &ParseOutput) -> bool {
4057    out.flags.contains_key(flag)
4058        && out.flag_origins.get(flag).is_none_or(|origins| {
4059            origins
4060                .iter()
4061                .any(|origin| matches!(origin, ValueOrigin::DefaultMissing | ValueOrigin::Env(_)))
4062        })
4063}
4064
4065fn default_if_condition_matches(
4066    condition: &crate::SpecDefaultIf,
4067    out: &ParseOutput,
4068    overridden_flags: &HashSet<String>,
4069    custom_env: Option<&HashMap<String, String>>,
4070) -> bool {
4071    match &condition.when {
4072        None => selector_is_explicit(&condition.selector, out, overridden_flags, custom_env),
4073        Some(when) => {
4074            let Some(flag) = selector_flags(out, &condition.selector).into_iter().next() else {
4075                return false;
4076            };
4077            if overridden_flags.contains(&flag.name) {
4078                return false;
4079            }
4080            explicit_flag_has_value(&flag, when, out, custom_env)
4081        }
4082    }
4083}
4084
4085/// Whether an explicitly supplied value of `flag` equals `expected`.
4086///
4087/// clap treats command-line and environment values as explicit for `requires_if`, but
4088/// not defaults. Keep that source distinction here instead of consulting the flag's
4089/// defaults through `selector_is_satisfied`.
4090fn explicit_flag_has_value(
4091    flag: &SpecFlag,
4092    expected: &str,
4093    out: &ParseOutput,
4094    custom_env: Option<&HashMap<String, String>>,
4095) -> bool {
4096    let parsed_matches = out.flags.get(flag).is_some_and(|value| match value {
4097        ParseValue::Bool(value) => value.to_string() == expected,
4098        ParseValue::String(value) => value == expected,
4099        ParseValue::MultiBool(values) => values.iter().any(|value| value.to_string() == expected),
4100        ParseValue::MultiString(values) => values.iter().any(|value| value == expected),
4101    });
4102    if out.flags.contains_key(flag) {
4103        return parsed_matches;
4104    }
4105
4106    let value = flag.env_names().find_map(|env| match custom_env {
4107        Some(values) => values.get(env).cloned(),
4108        None => std::env::var(env).ok(),
4109    });
4110    value.is_some_and(
4111        |value| match flag.arg.as_ref().and_then(|arg| arg.delimiter) {
4112            Some(delimiter) => value.split(delimiter).any(|value| value == expected),
4113            None if flag.arg.is_none() => {
4114                matches!(value.as_str(), "1" | "true" | "True" | "TRUE").to_string() == expected
4115            }
4116            None => value == expected,
4117        },
4118    )
4119}
4120
4121fn parse_value_has(value: &ParseValue, expected: &str) -> bool {
4122    match value {
4123        ParseValue::Bool(value) => value.to_string() == expected,
4124        ParseValue::String(value) => value == expected,
4125        ParseValue::MultiBool(values) => values.iter().any(|value| value.to_string() == expected),
4126        ParseValue::MultiString(values) => values.iter().any(|value| value == expected),
4127    }
4128}
4129
4130/// Clause flags share the command's spelling table so they can be recognized while parsing,
4131/// but their values and validation belong to one clause instance rather than the command.
4132fn is_clause_scoped_flag(out: &ParseOutput, flag: &SpecFlag) -> bool {
4133    out.cmd
4134        .clause
4135        .as_ref()
4136        .is_some_and(|clause| clause.flags.iter().any(|scoped| scoped.name == flag.name))
4137}
4138
4139fn selected_clause_flag<'a>(out: &'a ParseOutput, selector: &str) -> Option<&'a SpecFlag> {
4140    out.cmd
4141        .clause
4142        .as_ref()?
4143        .flags
4144        .iter()
4145        .find(|flag| flag_matches_selector(flag, selector))
4146}
4147
4148fn clause_flag_is_explicit(out: &ParseOutput, flag: &SpecFlag) -> bool {
4149    out.clause_flags
4150        .values()
4151        .flatten()
4152        .any(|instance| instance.keys().any(|present| present.name == flag.name))
4153        || out.flags.keys().any(|present| present.name == flag.name)
4154}
4155
4156fn clause_flag_has_value(out: &ParseOutput, flag: &SpecFlag, expected: &str) -> bool {
4157    out.clause_flags.values().flatten().any(|instance| {
4158        instance
4159            .iter()
4160            .any(|(present, value)| present.name == flag.name && parse_value_has(value, expected))
4161    }) || out
4162        .flags
4163        .iter()
4164        .any(|(present, value)| present.name == flag.name && parse_value_has(value, expected))
4165}
4166
4167fn validate_clause_relationships(
4168    out: &mut ParseOutput,
4169    overridden_flags: &HashSet<String>,
4170    custom_env: Option<&HashMap<String, String>>,
4171    explicit_instances: Option<&[HashSet<String>]>,
4172) {
4173    let Some(clause) = out.cmd.clause.as_ref() else {
4174        return;
4175    };
4176    let Some(instances) = out.clauses.get(&clause.name) else {
4177        return;
4178    };
4179    // A selector the clause itself owns is answered per instance, never by a command-level
4180    // flag that happens to share the alias (a parent `-f --format` against the clause's
4181    // `-f --file`).
4182    let clause_owns = |selector: &str| selected_clause_flag(out, selector).is_some();
4183    let command_flag_is_explicit = |selector: &str| {
4184        !clause_owns(selector)
4185            && selector_flags(out, selector).iter().any(|flag| {
4186                !overridden_flags.contains(&flag.name)
4187                    && (out.flags.contains_key(flag) || flag_has_env(flag, custom_env))
4188            })
4189    };
4190    let command_flag_matches_value = |selector: &str, expected: &str| {
4191        !clause_owns(selector)
4192            && selector_flags(out, selector).first().is_some_and(|flag| {
4193                !overridden_flags.contains(&flag.name)
4194                    && explicit_flag_has_value(flag, expected, out, custom_env)
4195            })
4196    };
4197    let command_flag_is_satisfied = |selector: &str| {
4198        !clause_owns(selector)
4199            && !selector_flags(out, selector).is_empty()
4200            && selector_is_satisfied(selector, out, overridden_flags, custom_env)
4201    };
4202    let mut errors = Vec::new();
4203    for (instance_index, instance) in instances.iter().enumerate() {
4204        let explicit = explicit_instances.and_then(|instances| instances.get(instance_index));
4205        let scoped = out
4206            .clause_flags
4207            .get(&clause.name)
4208            .and_then(|instances| instances.get(instance_index));
4209        let scoped_flag = |selector: &str| {
4210            clause
4211                .flags
4212                .iter()
4213                .find(|flag| flag_matches_selector(flag, selector))
4214        };
4215        let scoped_value = |flag: &SpecFlag| {
4216            scoped.and_then(|values| {
4217                values
4218                    .iter()
4219                    .find(|(present, _)| present.name == flag.name)
4220                    .map(|(_, value)| value)
4221            })
4222        };
4223        let arg_is_explicit = |selector: &str| {
4224            instance
4225                .keys()
4226                .any(|arg| !selector.starts_with('-') && arg.name == selector)
4227        };
4228        let selector_is_explicit = |selector: &str| {
4229            scoped_flag(selector).is_some_and(|flag| {
4230                explicit
4231                    .map(|given| given.contains(&flag.name))
4232                    .unwrap_or_else(|| scoped_value(flag).is_some())
4233            }) || command_flag_is_explicit(selector)
4234                || arg_is_explicit(selector)
4235        };
4236        let selector_has_value = |selector: &str, expected: &str| {
4237            scoped_flag(selector)
4238                .filter(|flag| {
4239                    explicit
4240                        .map(|given| given.contains(&flag.name))
4241                        .unwrap_or_else(|| scoped_value(flag).is_some())
4242                })
4243                .and_then(scoped_value)
4244                .is_some_and(|value| parse_value_has(value, expected))
4245                || command_flag_matches_value(selector, expected)
4246                || instance.iter().any(|(arg, value)| {
4247                    !selector.starts_with('-')
4248                        && arg.name == selector
4249                        && parse_value_has(value, expected)
4250                })
4251        };
4252        let selector_is_satisfied = |selector: &str| {
4253            scoped_flag(selector).is_some_and(|flag| scoped_value(flag).is_some())
4254                || command_flag_is_satisfied(selector)
4255                || arg_is_explicit(selector)
4256        };
4257        let selector_name = |selector: &str| {
4258            scoped_flag(selector)
4259                .map(|flag| flag.name.clone())
4260                .or_else(|| selector_flag_name(selector, out))
4261                .unwrap_or_else(|| selector.to_string())
4262        };
4263
4264        for flag in &clause.flags {
4265            let value = scoped_value(flag);
4266            if value.is_none() {
4267                let required_if = flag
4268                    .required_if
4269                    .iter()
4270                    .any(|selector| selector_is_explicit(selector));
4271                let required_if_eq = flag
4272                    .required_if_eq
4273                    .iter()
4274                    .any(|condition| selector_has_value(&condition.selector, &condition.value));
4275                let required_if_eq_all = !flag.required_if_eq_all.is_empty()
4276                    && flag
4277                        .required_if_eq_all
4278                        .iter()
4279                        .all(|condition| selector_has_value(&condition.selector, &condition.value));
4280                let unless_any = flag
4281                    .required_unless
4282                    .iter()
4283                    .any(|selector| selector_is_explicit(selector));
4284                let unless_all = !flag.required_unless_all.is_empty()
4285                    && flag
4286                        .required_unless_all
4287                        .iter()
4288                        .all(|selector| selector_is_explicit(selector));
4289                let required_unless = !(unless_any
4290                    || unless_all
4291                    || (flag.required_unless.is_empty() && flag.required_unless_all.is_empty()));
4292                if flag.required
4293                    || required_if
4294                    || required_if_eq
4295                    || required_if_eq_all
4296                    || required_unless
4297                {
4298                    errors.push(UsageErr::MissingFlag(flag.name.clone()));
4299                }
4300                continue;
4301            }
4302
4303            let explicitly_provided = explicit
4304                .map(|given| given.contains(&flag.name))
4305                .unwrap_or(true);
4306
4307            if explicitly_provided {
4308                for other in &flag.conflicts {
4309                    if selector_is_explicit(other) {
4310                        errors.push(UsageErr::InvalidFlag {
4311                            token: format!("--{}", flag.name),
4312                            reason: format!("conflicts with {other}"),
4313                            span: (0, 0).into(),
4314                            input: format!("--{} {other}", flag.name),
4315                        });
4316                    }
4317                }
4318                for other in &flag.requires {
4319                    if !selector_is_satisfied(other) {
4320                        errors.push(UsageErr::MissingFlag(selector_name(other)));
4321                    }
4322                }
4323                for condition in &flag.requires_if {
4324                    if value.is_some_and(|value| parse_value_has(value, &condition.value))
4325                        && !selector_is_satisfied(&condition.requires)
4326                    {
4327                        errors.push(UsageErr::MissingFlag(selector_name(&condition.requires)));
4328                    }
4329                }
4330            }
4331            if let (true, Some(value)) = (flag.var, value) {
4332                let count = match value {
4333                    ParseValue::MultiString(values) => values.len(),
4334                    ParseValue::MultiBool(values) => values.len(),
4335                    _ => 1,
4336                };
4337                if let Some(min) = flag.var_min.filter(|min| count < *min) {
4338                    errors.push(UsageErr::VarFlagTooFew {
4339                        name: flag.name.clone(),
4340                        min,
4341                        got: count,
4342                    });
4343                }
4344                if let Some(max) = flag.var_max.filter(|max| count > *max) {
4345                    errors.push(UsageErr::VarFlagTooMany {
4346                        name: flag.name.clone(),
4347                        max,
4348                        got: count,
4349                    });
4350                }
4351            }
4352            if let (Some(arg), Some(value)) = (&flag.arg, value) {
4353                validate_expression(
4354                    &flag.name,
4355                    arg.validate.as_deref(),
4356                    arg.validate_error.as_deref(),
4357                    value,
4358                    &mut errors,
4359                );
4360            }
4361        }
4362        for arg in &clause.args {
4363            let given = instance.keys().any(|present| present.name == arg.name);
4364            if !given {
4365                let required_if = arg
4366                    .required_if
4367                    .iter()
4368                    .any(|selector| selector_is_explicit(selector));
4369                let required_if_eq = arg
4370                    .required_if_eq
4371                    .iter()
4372                    .any(|condition| selector_has_value(&condition.selector, &condition.value));
4373                let required_if_eq_all = !arg.required_if_eq_all.is_empty()
4374                    && arg
4375                        .required_if_eq_all
4376                        .iter()
4377                        .all(|condition| selector_has_value(&condition.selector, &condition.value));
4378                let unless_any = arg
4379                    .required_unless
4380                    .iter()
4381                    .any(|selector| selector_is_explicit(selector));
4382                let unless_all = !arg.required_unless_all.is_empty()
4383                    && arg
4384                        .required_unless_all
4385                        .iter()
4386                        .all(|selector| selector_is_explicit(selector));
4387                let required_unless = !(unless_any
4388                    || unless_all
4389                    || (arg.required_unless.is_empty() && arg.required_unless_all.is_empty()));
4390                if required_if || required_if_eq || required_if_eq_all || required_unless {
4391                    errors.push(UsageErr::MissingClauseArg {
4392                        clause: clause.name.clone(),
4393                        instance: instance_index + 1,
4394                        arg: arg.name.clone(),
4395                    });
4396                }
4397                continue;
4398            }
4399            for other in &arg.conflicts {
4400                if selector_is_explicit(other) {
4401                    errors.push(UsageErr::InvalidFlag {
4402                        token: arg.name.clone(),
4403                        reason: format!("conflicts with {other}"),
4404                        span: (0, 0).into(),
4405                        input: format!("{} {other}", arg.name),
4406                    });
4407                }
4408            }
4409            for other in &arg.requires {
4410                if selector_is_satisfied(other) {
4411                    continue;
4412                }
4413                if other.starts_with('-') {
4414                    errors.push(UsageErr::MissingFlag(selector_name(other)));
4415                } else {
4416                    errors.push(UsageErr::MissingClauseArg {
4417                        clause: clause.name.clone(),
4418                        instance: instance_index + 1,
4419                        arg: other.clone(),
4420                    });
4421                }
4422            }
4423        }
4424    }
4425    out.errors.extend(errors);
4426}
4427
4428fn selector_explicit_has_value(
4429    selector: &str,
4430    expected: &str,
4431    out: &ParseOutput,
4432    overridden_flags: &HashSet<String>,
4433    custom_env: Option<&HashMap<String, String>>,
4434) -> bool {
4435    if let Some(flag) = selected_clause_flag(out, selector) {
4436        return clause_flag_has_value(out, flag, expected);
4437    }
4438    if let Some(flag) = selector_flags(out, selector).first() {
4439        return !overridden_flags.contains(&flag.name)
4440            && explicit_flag_has_value(flag, expected, out, custom_env);
4441    }
4442    let Some(arg) = selector_arg(selector, out) else {
4443        return false;
4444    };
4445    let parsed = out
4446        .args
4447        .iter()
4448        .find(|(given, _)| given.name == arg.name)
4449        .map(|(_, value)| value)
4450        .or_else(|| {
4451            out.clauses.values().flatten().find_map(|instance| {
4452                instance
4453                    .iter()
4454                    .find(|(given, _)| given.name == arg.name)
4455                    .map(|(_, value)| value)
4456            })
4457        });
4458    if let Some(value) = parsed {
4459        return match value {
4460            ParseValue::String(value) => value == expected,
4461            ParseValue::MultiString(values) => values.iter().any(|value| value == expected),
4462            ParseValue::Bool(value) => value.to_string() == expected,
4463            ParseValue::MultiBool(values) => {
4464                values.iter().any(|value| value.to_string() == expected)
4465            }
4466        };
4467    }
4468    let value = arg.env_names().find_map(|env| match custom_env {
4469        Some(values) => values.get(env).cloned(),
4470        None => std::env::var(env).ok(),
4471    });
4472    value.is_some_and(|value| match arg.delimiter {
4473        Some(delimiter) => value.split(delimiter).any(|value| value == expected),
4474        None => value == expected,
4475    })
4476}
4477
4478fn selector_is_explicit(
4479    selector: &str,
4480    out: &ParseOutput,
4481    overridden_flags: &HashSet<String>,
4482    custom_env: Option<&HashMap<String, String>>,
4483) -> bool {
4484    let scoped_flag_is_explicit =
4485        selected_clause_flag(out, selector).is_some_and(|flag| clause_flag_is_explicit(out, flag));
4486    let flag_is_explicit = selector_flags(out, selector).iter().any(|flag| {
4487        !overridden_flags.contains(&flag.name)
4488            && (out.flags.contains_key(flag) || flag_has_env(flag, custom_env))
4489    });
4490    scoped_flag_is_explicit
4491        || flag_is_explicit
4492        || selector_arg(selector, out).is_some_and(|arg| arg_is_explicit(arg, out, custom_env))
4493}
4494
4495/// The name of the flag a selector points at, for an error that has to name it.
4496///
4497/// `selector_is_explicit` only answers yes or no, which is all a check needs; a message
4498/// about a flag that is *missing* has to say which one, and the selector may be a short
4499/// form or an alias rather than the name.
4500fn selector_flag_name(selector: &str, out: &ParseOutput) -> Option<String> {
4501    if let Some(flag) = selected_clause_flag(out, selector) {
4502        return Some(flag.name.clone());
4503    }
4504    selector_flags(out, selector)
4505        .first()
4506        .map(|flag| flag.name.clone())
4507        .or_else(|| selector_arg(selector, out).map(|arg| arg.name.clone()))
4508}
4509
4510/// Whether a selector's flag ended up with a value, however it got one.
4511///
4512/// The rule for a *positive* relationship, and the difference from
4513/// [`selector_is_explicit`] is deliberate. A negative rule — `conflicts`, or a group's
4514/// exclusivity — has to count only what was given, or a flag with a default would
4515/// conflict with everything and no command line would parse. A positive one asks whether
4516/// the flag it names has a value, and a default is a value: that is already how plain
4517/// `required`, `required_if` and `required_unless` read a default, and `requires` saying
4518/// otherwise would have made the same flag missing here and present ten lines below.
4519fn selector_is_satisfied(
4520    selector: &str,
4521    out: &ParseOutput,
4522    overridden_flags: &HashSet<String>,
4523    custom_env: Option<&HashMap<String, String>>,
4524) -> bool {
4525    if selector_is_explicit(selector, out, overridden_flags, custom_env) {
4526        return true;
4527    }
4528    let flag_is_satisfied = selector_flags(out, selector).iter().any(|flag| {
4529        !overridden_flags.contains(&flag.name)
4530            && (!flag.default.is_empty()
4531                || flag.arg.iter().any(|a| !a.default.is_empty())
4532                || flag.default_if.iter().any(|condition| {
4533                    default_if_condition_matches(condition, out, overridden_flags, custom_env)
4534                }))
4535    });
4536    flag_is_satisfied || selector_arg(selector, out).is_some_and(|arg| !arg.default.is_empty())
4537}
4538
4539/// The flags of the commands a descent has left, as a subcommand's relationships still see them.
4540///
4541/// A descent keeps only globals in `available_flags`, yet a parent flag's `required`,
4542/// `requires` and `conflicts`, and its default or environment value as another flag's
4543/// relationship target, stay in force. Only ordinary flags: a clause flag belongs to one
4544/// clause instance and binds nothing until that clause is entered. A name a later command in
4545/// the chain declares again is shadowed by it, and a name already available is not repeated.
4546fn ancestor_flags(out: &ParseOutput) -> Vec<Arc<SpecFlag>> {
4547    let Some((_, ancestors)) = out.cmds.split_last() else {
4548        return vec![];
4549    };
4550    // A mounted program owns its relationships: nothing above the mount point speaks for it.
4551    // Every command inside the program is marked mounted, so the boundary is where the
4552    // trailing run of mounted commands starts, and the program's own parents stay in.
4553    let first = if out.cmds.last().is_some_and(|cmd| cmd.mounted) {
4554        out.cmds
4555            .iter()
4556            .rposition(|cmd| !cmd.mounted)
4557            .map_or(0, |host| host + 1)
4558    } else {
4559        0
4560    };
4561    let mut flags: Vec<Arc<SpecFlag>> = vec![];
4562    for (index, cmd) in ancestors.iter().enumerate().skip(first) {
4563        for flag in &cmd.flags {
4564            let shadowed = out.cmds[index + 1..]
4565                .iter()
4566                .any(|later| later.flags.iter().any(|f| f.name == flag.name));
4567            if !shadowed
4568                && !out.available_flags.values().any(|f| f.name == flag.name)
4569                && !flags.iter().any(|f| f.name == flag.name)
4570            {
4571                flags.push(Arc::new(flag.clone()));
4572            }
4573        }
4574    }
4575    flags
4576}
4577
4578/// The flags a selector names, nearest declaration first: a flag still available, else the
4579/// nearest ancestor command that declares one, else whatever was parsed. A name or alias a
4580/// closer command claims is not answered by a flag further up that merely shares it (a
4581/// child `-f --file` hides a parent `-f --format`). Clause-scoped flags never answer.
4582fn selector_flags(out: &ParseOutput, selector: &str) -> Vec<Arc<SpecFlag>> {
4583    let matches = |flag: &Arc<SpecFlag>| {
4584        !is_clause_scoped_flag(out, flag) && flag_matches_selector(flag, selector)
4585    };
4586    let available: Vec<_> = unique_flags(out.available_flags.values())
4587        .filter(|flag| matches(flag))
4588        .cloned()
4589        .collect();
4590    if !available.is_empty() {
4591        return available;
4592    }
4593    if let Some((_, ancestors)) = out.cmds.split_last() {
4594        let visible = ancestor_flags(out);
4595        for cmd in ancestors.iter().rev() {
4596            let found: Vec<_> = visible
4597                .iter()
4598                .filter(|flag| matches(flag) && cmd.flags.iter().any(|d| d.name == flag.name))
4599                .cloned()
4600                .collect();
4601            if !found.is_empty() {
4602                return found;
4603            }
4604        }
4605    }
4606    // A parsed flag that a later command declares again was shadowed by it.
4607    let shadowed = |flag: &Arc<SpecFlag>| {
4608        let declares = |cmd: &&SpecCommand| cmd.flags.iter().any(|f| f.name == flag.name);
4609        out.cmds
4610            .iter()
4611            .skip_while(|cmd| !declares(cmd))
4612            .skip(1)
4613            .any(|cmd| declares(&cmd))
4614    };
4615    unique_flags(out.flags.keys())
4616        .filter(|flag| matches(flag) && !shadowed(flag))
4617        .cloned()
4618        .collect()
4619}
4620
4621fn selector_arg<'a>(selector: &str, out: &'a ParseOutput) -> Option<&'a SpecArg> {
4622    // Bare words are positional selectors. Keep accepting a flag's internal name above
4623    // for existing specs; when both exist, the dashed flag spelling removes ambiguity.
4624    if selector.starts_with('-') {
4625        return None;
4626    }
4627    out.cmds
4628        .iter()
4629        .flat_map(active_args)
4630        .find(|arg| arg.name == selector)
4631}
4632
4633fn arg_is_explicit(
4634    arg: &SpecArg,
4635    out: &ParseOutput,
4636    custom_env: Option<&HashMap<String, String>>,
4637) -> bool {
4638    out.args.keys().any(|given| given.name == arg.name)
4639        || out
4640            .clauses
4641            .values()
4642            .flatten()
4643            .any(|instance| instance.keys().any(|given| given.name == arg.name))
4644        || arg
4645            .env
4646            .as_ref()
4647            .is_some_and(|env| env_contains(custom_env, env))
4648}
4649
4650fn apply_flag_overrides(
4651    flag: &Arc<SpecFlag>,
4652    available_flags: &BTreeMap<String, Arc<SpecFlag>>,
4653    parsed_flags: &mut IndexMap<Arc<SpecFlag>, ParseValue>,
4654    pending_flags: &mut Vec<Arc<SpecFlag>>,
4655    overridden_flags: &mut HashSet<String>,
4656    // The reportable half of the same fact: which flag did the overriding. The set above
4657    // only stops a default or an environment value restoring what was overridden, and
4658    // "`--quiet` is unset despite its default" has no answer without the name.
4659    attributed: &mut BTreeMap<String, String>,
4660) {
4661    let overridden_names: HashSet<String> = available_flags
4662        .values()
4663        .chain(parsed_flags.keys())
4664        .filter(|other| flags_override(flag, other) || flags_override(other, flag))
4665        .map(|other| other.name.clone())
4666        .collect();
4667
4668    parsed_flags.retain(|parsed, _| !overridden_names.contains(&parsed.name));
4669    pending_flags.retain(|pending| !overridden_names.contains(&pending.name));
4670    for name in &overridden_names {
4671        attributed.insert(name.clone(), flag.name.clone());
4672    }
4673    overridden_flags.extend(overridden_names);
4674    // An explicit occurrence always restores this flag, including self-overrides.
4675    overridden_flags.remove(&flag.name);
4676    attributed.remove(&flag.name);
4677}
4678
4679/// The help a parse answers `--help` with. A parse is a program running, so its page lists
4680/// what `choices run=` prints, run against the environment the parse was given.
4681#[cfg(feature = "cli-help")]
4682fn render_help_err(spec: &Spec, cmd: &SpecCommand, long: bool, env: Env<'_>) -> UsageErr {
4683    UsageErr::Help(docs::cli::render_runtime_help(
4684        spec,
4685        cmd,
4686        long,
4687        docs::cli::Style::PLAIN,
4688        env,
4689    ))
4690}
4691
4692#[cfg(feature = "cli-help")]
4693fn render_help_all_err(spec: &Spec, cmd: &SpecCommand, env: Env<'_>) -> UsageErr {
4694    fn append(out: &mut String, spec: &Spec, cmd: &SpecCommand, env: Env<'_>) {
4695        if !out.is_empty() {
4696            out.push('\n');
4697        }
4698        out.push_str(&docs::cli::render_runtime_help(
4699            spec,
4700            cmd,
4701            true,
4702            docs::cli::Style::PLAIN,
4703            env,
4704        ));
4705        let mut children: Vec<_> = cmd
4706            .subcommands
4707            .values()
4708            .filter(|child| !child.hide)
4709            .collect();
4710        children.sort_by_key(|child| (child.display_order.unwrap_or(999), child.name.as_str()));
4711        for child in children {
4712            append(out, spec, child, env);
4713        }
4714    }
4715
4716    let mut out = String::new();
4717    append(&mut out, spec, cmd, env);
4718    UsageErr::Help(out)
4719}
4720
4721#[cfg(not(feature = "cli-help"))]
4722fn render_help_err(_spec: &Spec, _cmd: &SpecCommand, _long: bool, _env: Env<'_>) -> UsageErr {
4723    UsageErr::Help("help".to_string())
4724}
4725
4726#[cfg(not(feature = "cli-help"))]
4727fn render_help_all_err(_spec: &Spec, _cmd: &SpecCommand, _env: Env<'_>) -> UsageErr {
4728    UsageErr::Help("help".to_string())
4729}
4730
4731/// The version to answer with. `--version` prefers the long text and `-V` the concise
4732/// one, each falling back to the other when only one is declared.
4733fn render_version_err(spec: &Spec, long: bool) -> UsageErr {
4734    let value = if long {
4735        spec.long_version.as_ref().or(spec.version.as_ref())
4736    } else {
4737        spec.version.as_ref().or(spec.long_version.as_ref())
4738    };
4739    UsageErr::Version(value.cloned().unwrap_or_default())
4740}
4741
4742/// The environment a parse was given, which is also what a `choices run=` command runs with.
4743type Env<'a> = Option<&'a HashMap<String, String>>;
4744
4745fn render_action_err(
4746    spec: &Spec,
4747    cmd: &SpecCommand,
4748    flag: &SpecFlag,
4749    spelling: &str,
4750    env: Env<'_>,
4751) -> UsageErr {
4752    use crate::SpecFlagAction;
4753    match flag.action {
4754        SpecFlagAction::Help => render_help_err(spec, cmd, spelling.starts_with("--"), env),
4755        SpecFlagAction::HelpShort => render_help_err(spec, cmd, false, env),
4756        SpecFlagAction::HelpLong => render_help_err(spec, cmd, true, env),
4757        SpecFlagAction::HelpAll => render_help_all_err(spec, cmd, env),
4758        SpecFlagAction::Version => render_version_err(spec, spelling.starts_with("--")),
4759        SpecFlagAction::Set => unreachable!("binding actions are handled before this helper"),
4760    }
4761}
4762
4763/// Report a required flag value that was displaced by a later option.
4764fn render_missing_flag_value(flag: &SpecFlag, following: &str) -> UsageErr {
4765    let token = flag
4766        .long
4767        .first()
4768        .map(|long| format!("--{long}"))
4769        .or_else(|| flag.short.first().map(|short| format!("-{short}")))
4770        .unwrap_or_else(|| flag.name.clone());
4771    UsageErr::InvalidFlag {
4772        token: token.clone(),
4773        reason: "requires an argument".to_string(),
4774        span: (0, 0).into(),
4775        input: format!("{token} {following}"),
4776    }
4777}
4778
4779#[derive(Copy, Clone)]
4780struct ChoiceTarget<'a> {
4781    kind: &'a str,
4782    name: &'a str,
4783}
4784
4785impl<'a> ChoiceTarget<'a> {
4786    fn arg(arg: &'a SpecArg) -> Self {
4787        Self {
4788            kind: "arg",
4789            name: &arg.name,
4790        }
4791    }
4792
4793    fn option(flag: &'a SpecFlag) -> Self {
4794        Self {
4795            kind: "option",
4796            name: &flag.name,
4797        }
4798    }
4799}
4800
4801/// Whether every letter of a short token names a flag in scope.
4802///
4803/// Scanning stops at the first letter whose flag takes a value, because everything
4804/// after it is that value rather than more letters.
4805fn short_bundle_is_known(
4806    spec: &Spec,
4807    cmds: &[SpecCommand],
4808    available: &BTreeMap<String, Arc<SpecFlag>>,
4809    token: &str,
4810) -> bool {
4811    for c in token.chars().skip(1) {
4812        match available.get(&format!("-{c}")) {
4813            // `-h` and `-V` are recognized letters even though no spec declares them, so a
4814            // bundle containing one is a bundle. Without this `-vh` was not read as one at
4815            // all and fell through to `unexpected word`, while usage-argv, usage-go and
4816            // clap all answer it with help.
4817            None if supplies_short(spec, cmds, c) => {}
4818            None => return false,
4819            Some(f) if f.arg.is_some() => return true,
4820            Some(_) => {}
4821        }
4822    }
4823    true
4824}
4825
4826/// The response `-h` or `-V` produces where nothing declares that letter.
4827///
4828/// The letter form of the flags the parser supplies rather than a spec declaring them,
4829/// under exactly the conditions [`is_help_arg`] and [`is_version_arg`] state — asked
4830/// about here one letter at a time, because a bundle is read one letter at a time.
4831///
4832/// Always the short response: `-h` is short help however many letters share its token,
4833/// and `-V` the concise version. The long forms belong to the long spellings. `-?` is not
4834/// here — it is a whole-token spelling of `-h` rather than a letter anyone bundles.
4835fn supplied_short(
4836    spec: &Spec,
4837    cmds: &[SpecCommand],
4838    letter: char,
4839    env: Env<'_>,
4840) -> Option<UsageErr> {
4841    let cmd = cmds.last()?;
4842    match letter {
4843        'h' if is_help_arg(spec, cmd, "-h") => Some(render_help_err(spec, cmd, false, env)),
4844        'V' if is_version_arg(spec, cmds, "-V") => Some(render_version_err(spec, false)),
4845        _ => None,
4846    }
4847}
4848
4849/// Whether [`supplied_short`] would answer for `letter`, without drawing the page it would
4850/// answer with — which can mean running `choices run=` commands.
4851fn supplies_short(spec: &Spec, cmds: &[SpecCommand], letter: char) -> bool {
4852    cmds.last().is_some_and(|cmd| match letter {
4853        'h' => is_help_arg(spec, cmd, "-h"),
4854        'V' => is_version_arg(spec, cmds, "-V"),
4855        _ => false,
4856    })
4857}
4858
4859/// Refuse a flag-like token that named nothing, if this command asked for that.
4860///
4861/// Called from the flag branches, where the lookup has just failed and nothing from
4862/// the token has been applied yet — so a bundle like `-az` is refused whole rather
4863/// than after setting `-a`.
4864fn reject_unknown_flag_if_asked(
4865    spec: &Spec,
4866    path: &[SpecCommand],
4867    token: &str,
4868) -> Result<(), UsageErr> {
4869    // A lone `-` is a value by convention. A negative number reaches this only
4870    // when no pending value opted into the narrower exception.
4871    if !is_flag_like(token) {
4872        return Ok(());
4873    }
4874    if effective_unknown_flags(spec, path) != UnknownFlags::Error {
4875        return Ok(());
4876    }
4877    Err(UsageErr::InvalidFlag {
4878        token: token.to_string(),
4879        reason: "no such flag".to_string(),
4880        span: (0, 0).into(),
4881        input: token.to_string(),
4882    })
4883}
4884
4885/// Whether a flag-like token that matches nothing is a value or an error, here.
4886///
4887/// The nearest enclosing command that stated a preference wins, then the spec,
4888/// then the default. Inherited, unlike `effect`: it describes how a command line
4889/// is read, and a CLI that forwards options tends to forward them at every level.
4890fn effective_unknown_flags(spec: &Spec, path: &[SpecCommand]) -> UnknownFlags {
4891    path.iter()
4892        .rev()
4893        .find_map(|cmd| cmd.unknown_flags)
4894        .or(spec.unknown_flags)
4895        .unwrap_or_default()
4896}
4897
4898/// Whether a token would be read as a flag, for the purpose of rejecting unknown
4899/// ones.
4900///
4901/// A lone `-` is a value by convention. Other dash-prefixed tokens are flag-like;
4902/// a field may make the narrower negative-number exception.
4903fn is_flag_like(token: &str) -> bool {
4904    match token.strip_prefix('-') {
4905        None | Some("") => false,
4906        Some(_) => true,
4907    }
4908}
4909
4910fn is_negative_number(token: &str) -> bool {
4911    token.strip_prefix('-').is_some_and(is_number)
4912}
4913
4914/// Whether a flag may claim its following token as a detached value.
4915///
4916/// A required value keeps the historical negative-number exception. A value
4917/// that may be omitted needs an explicit opt-in to distinguish a negative value
4918/// from the flag's bare form.
4919fn accepts_detached_flag_value(flag: &SpecFlag, token: &str) -> bool {
4920    !flag.require_equals
4921        && (!is_flag_like(token)
4922            || flag.allow_hyphen_values()
4923            || (is_negative_number(token)
4924                && (flag
4925                    .arg
4926                    .as_ref()
4927                    .is_some_and(|arg| arg.allow_negative_numbers)
4928                    || (flag.default_missing.is_none() && !flag.value_optional))))
4929}
4930
4931fn record_scalar_flag_occurrence(
4932    cmds: &[SpecCommand],
4933    flag: &Arc<SpecFlag>,
4934    command_level: usize,
4935    bool_value: Option<bool>,
4936    occurrences: &mut HashMap<(usize, usize), u8>,
4937    errors: &mut Vec<UsageErr>,
4938) {
4939    let strict = cmds.get(command_level).is_some_and(|cmd| {
4940        !cmd.args_override_self
4941            || cmd
4942                .clause
4943                .as_ref()
4944                .is_some_and(|clause| clause.flags.iter().any(|candidate| candidate == &**flag))
4945    });
4946    let collects_values = flag.var || flag.arg.as_ref().is_some_and(|arg| arg.var);
4947    if !strict || flag.count || collects_values {
4948        return;
4949    }
4950
4951    let bit = match bool_value {
4952        Some(false) if flag.negate.is_some() => 0b10,
4953        _ => 0b01,
4954    };
4955    let key = (Arc::as_ptr(flag) as usize, command_level);
4956    let seen = occurrences.entry(key).or_default();
4957    if *seen & bit != 0 {
4958        errors.push(UsageErr::DuplicateFlag(flag.name.clone()));
4959    }
4960    *seen |= bit;
4961}
4962
4963/// A token that can select a subcommand, trigger a mount, or be forwarded as an
4964/// external command.
4965///
4966/// Flag-like tokens are not words. A lone `-` is a value — conventionally stdin —
4967/// so it was never a candidate to *select* anything either. usage-argv uses the
4968/// same rule; without it, `-1` skipped the external-subcommand path because Phase 1
4969/// treated every token that `starts_with('-')` as a flag.
4970fn is_command_word(token: &str) -> bool {
4971    (!is_flag_like(token) || is_negative_number(token)) && token != "-"
4972}
4973
4974/// Whether an otherwise numeric-looking token is an exact declared short flag.
4975///
4976/// This check belongs in both parse phases: phase 1 must skip the flag while it
4977/// searches for a later subcommand, and phase 2 must bind it instead of offering
4978/// it to an `allow_negative_numbers` positional.
4979fn declared_numeric_short(available_flags: &BTreeMap<String, Arc<SpecFlag>>, token: &str) -> bool {
4980    token.len() == 2 && token.as_bytes()[1].is_ascii_digit() && available_flags.contains_key(token)
4981}
4982
4983/// Whether an unmatched word belongs to the root's default command.
4984///
4985/// Ordinary words always do. A negative number only does when the default command's
4986/// first positional explicitly accepts one; otherwise it stays at the root, matching
4987/// usage-argv and generated Go.
4988fn default_accepts_word(cmd: &SpecCommand, default_name: &str, token: &str) -> bool {
4989    !is_negative_number(token)
4990        || cmd
4991            .find_subcommand(default_name)
4992            .and_then(|default| default.args.first())
4993            .is_some_and(|arg| arg.allow_negative_numbers)
4994}
4995
4996/// Digits, at most one `.`, and an optional exponent.
4997///
4998/// Spelled out rather than deferred to `f64::from_str`, which also accepts `inf` and
4999/// `NaN`: `-inf` is far likelier to be a misspelled flag than a number somebody meant
5000/// to pass. usage-argv implements the same rule, and the corpus pins the edges — the
5001/// two disagreed about `-1e5` when one used a float parse and the other did not.
5002fn is_number(rest: &str) -> bool {
5003    let (mantissa, exponent) = match rest.find(['e', 'E']) {
5004        Some(at) => (&rest[..at], Some(&rest[at + 1..])),
5005        None => (rest, None),
5006    };
5007
5008    let mut seen_digit = false;
5009    let mut seen_dot = false;
5010    for c in mantissa.chars() {
5011        match c {
5012            '0'..='9' => seen_digit = true,
5013            '.' if !seen_dot => seen_dot = true,
5014            _ => return false,
5015        }
5016    }
5017    if !seen_digit {
5018        return false;
5019    }
5020
5021    match exponent {
5022        None => true,
5023        Some(exp) => {
5024            let digits = exp
5025                .strip_prefix('+')
5026                .or_else(|| exp.strip_prefix('-'))
5027                .unwrap_or(exp);
5028            !digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit())
5029        }
5030    }
5031}
5032
5033/// Bind one value to the flag waiting for it, and let a variadic argument go on
5034/// collecting from the words that follow.
5035///
5036/// Every route to a flag's value comes through here — the following word, the text
5037/// after an `=`, and the token a `allow_hyphen_values` flag takes whatever it looks
5038/// like — so that all three agree on how many values the flag ends up with.
5039#[allow(clippy::too_many_arguments)]
5040fn bind_pending_flag_value(
5041    spec: &Spec,
5042    cmd: &SpecCommand,
5043    errors: &mut Vec<UsageErr>,
5044    flags: &mut IndexMap<Arc<SpecFlag>, ParseValue>,
5045    flag_awaiting_value: &mut Vec<Arc<SpecFlag>>,
5046    word: &mut String,
5047    input: &mut VecDeque<Token>,
5048    custom_env: Option<&HashMap<String, String>>,
5049    trace: &mut Trace,
5050    // Which token supplied `word`, and whether it rode along on the flag's own token
5051    // (`--jobs=8`, `-j8`) rather than following it. A variadic run's later words carry
5052    // their own positions and are recorded where they are read.
5053    argv: usize,
5054    attached: bool,
5055) -> miette::Result<bool> {
5056    // Held before the drain pops it, along with what the flag is already carrying: a
5057    // `var_max` bounds the values this occurrence takes, not the list they are appended
5058    // to, so a second `--include` starts counting again.
5059    let collecting = flag_awaiting_value
5060        .last()
5061        .filter(|flag| flag.arg.as_ref().is_some_and(|arg| arg.var))
5062        .cloned()
5063        .map(|flag| {
5064            let carried = flags.get(&flag).map(value_count).unwrap_or(0);
5065            (flag, carried)
5066        });
5067    let mut bound = vec![];
5068    let refused = drain_pending_flag_values(
5069        spec,
5070        cmd,
5071        errors,
5072        flags,
5073        flag_awaiting_value,
5074        word,
5075        custom_env,
5076        &mut bound,
5077    )?;
5078    for (flag, values) in bound {
5079        trace.record(
5080            argv,
5081            TokenRole::Value {
5082                flag,
5083                values,
5084                attached,
5085            },
5086        );
5087    }
5088    if refused {
5089        return Ok(true);
5090    }
5091    let Some((flag, carried)) = collecting else {
5092        return Ok(false);
5093    };
5094    collect_variadic_flag_values(
5095        spec,
5096        cmd,
5097        errors,
5098        flags,
5099        flag_awaiting_value,
5100        &flag,
5101        carried,
5102        input,
5103        custom_env,
5104        trace,
5105    )
5106}
5107
5108/// Keep feeding a flag whose argument is variadic from the words that follow it.
5109///
5110/// `--include <pattern>...` collects from a single occurrence, so it takes tokens until
5111/// one is flag-like, a `--` arrives, its `var_max` is reached, or the command line ends.
5112/// This is greedy by design — a command declaring both such a flag and positionals will
5113/// find the flag eating them, and `--` or a `var_max` is how the run is stopped.
5114///
5115/// `carried` is what the flag already held when this occurrence began, so the bound
5116/// counts this run rather than everything the flag has collected across the command
5117/// line. Each value goes through the same drain as the first, so choices are checked
5118/// and the value lands in the same list rather than by a second route that could
5119/// disagree.
5120#[allow(clippy::too_many_arguments)]
5121fn collect_variadic_flag_values(
5122    spec: &Spec,
5123    cmd: &SpecCommand,
5124    errors: &mut Vec<UsageErr>,
5125    flags: &mut IndexMap<Arc<SpecFlag>, ParseValue>,
5126    flag_awaiting_value: &mut Vec<Arc<SpecFlag>>,
5127    flag: &Arc<SpecFlag>,
5128    carried: usize,
5129    input: &mut VecDeque<Token>,
5130    custom_env: Option<&HashMap<String, String>>,
5131    trace: &mut Trace,
5132) -> miette::Result<bool> {
5133    let max = flag
5134        .arg
5135        .as_ref()
5136        .and_then(|arg| arg.var_max)
5137        .unwrap_or(usize::MAX);
5138    while flags
5139        .get(flag)
5140        .map(value_count)
5141        .unwrap_or(0)
5142        .saturating_sub(carried)
5143        < max
5144    {
5145        let Some(next) = input.front().map(|token| token.word.as_str()) else {
5146            break;
5147        };
5148        if flag
5149            .arg
5150            .as_ref()
5151            .and_then(|arg| arg.value_terminator.as_deref())
5152            == Some(next)
5153        {
5154            let terminator = input.pop_front().unwrap();
5155            trace.record(
5156                terminator.argv,
5157                TokenRole::ValueTerminator {
5158                    ends: flag.name.clone(),
5159                },
5160            );
5161            break;
5162        }
5163        // The separator is left where it is: stopping here hands it to the arm that
5164        // knows what it means, rather than reading it as one more value.
5165        if next == "--"
5166            || (is_flag_like(next)
5167                && !(flag
5168                    .arg
5169                    .as_ref()
5170                    .is_some_and(|arg| arg.allow_negative_numbers)
5171                    && is_negative_number(next)))
5172        {
5173            break;
5174        }
5175        let taken = input.pop_front().unwrap();
5176        let argv = taken.argv;
5177        let mut word = taken.word;
5178        flag_awaiting_value.push(Arc::clone(flag));
5179        let mut bound = vec![];
5180        let refused = drain_pending_flag_values(
5181            spec,
5182            cmd,
5183            errors,
5184            flags,
5185            flag_awaiting_value,
5186            &mut word,
5187            custom_env,
5188            &mut bound,
5189        )?;
5190        for (flag, values) in bound {
5191            // A later word of the same occurrence is its own token, and never attached:
5192            // only the first value can ride along on the flag.
5193            trace.record(
5194                argv,
5195                TokenRole::Value {
5196                    flag,
5197                    values,
5198                    attached: false,
5199                },
5200            );
5201        }
5202        if refused {
5203            return Ok(true);
5204        }
5205    }
5206    // The loop stops once the occurrence has reached its bound, which without a delimiter is
5207    // exactly when it has taken `max` words. A delimiter breaks that: one word can carry
5208    // several values, so the run can end up *past* the bound rather than on it, and stopping
5209    // is no longer the same as staying within it. `--include a,b,c` under `var_max=2` is the
5210    // case — three values out of the one word the loop was entitled to take.
5211    //
5212    // Counted against `carried` like the loop itself, so this stays a statement about the
5213    // occurrence rather than about the list the occurrences build up.
5214    let taken = flags
5215        .get(flag)
5216        .map(value_count)
5217        .unwrap_or(0)
5218        .saturating_sub(carried);
5219    if let Some(min) = flag.arg.as_ref().and_then(|arg| arg.var_min)
5220        && taken < min
5221    {
5222        errors.push(UsageErr::VarFlagTooFew {
5223            name: flag.name.clone(),
5224            min,
5225            got: taken,
5226        });
5227    }
5228    if taken > max {
5229        errors.push(UsageErr::VarFlagTooMany {
5230            name: flag.name.clone(),
5231            max,
5232            got: taken,
5233        });
5234    }
5235    Ok(false)
5236}
5237
5238/// How many values a flag is holding, for a bound that counts them.
5239fn value_count(value: &ParseValue) -> usize {
5240    match value {
5241        ParseValue::MultiString(values) => values.len(),
5242        ParseValue::MultiBool(values) => values.len(),
5243        _ => 1,
5244    }
5245}
5246
5247/// Finish a value-optional flag that was given with no value.
5248///
5249/// Returns whether anything was bound. Completions keep the flag waiting — a
5250/// half-typed `--color ` is a question about the value — so this is asked only
5251/// once a full parse has decided the value is not coming, or once the next token
5252/// has made that decision.
5253///
5254/// The missing string is a real value: if the flag names `choices`, it has to
5255/// be one of them, the same way an env var or a `default` is checked. Binding
5256/// first and failing later would leave the flag set to a value the spec forbids.
5257fn try_bind_default_missing(
5258    flags: &mut IndexMap<Arc<SpecFlag>, ParseValue>,
5259    flag_awaiting_value: &mut Vec<Arc<SpecFlag>>,
5260    custom_env: Option<&HashMap<String, String>>,
5261    origins: &mut IndexMap<Arc<SpecFlag>, Vec<ValueOrigin>>,
5262) -> miette::Result<bool> {
5263    let Some(flag) = flag_awaiting_value.last() else {
5264        return Ok(false);
5265    };
5266    let value = match flag.default_missing.clone() {
5267        Some(value) => value,
5268        None if flag.value_optional => {
5269            let flag = flag_awaiting_value.pop().unwrap();
5270            // Presence in the map distinguishes this from an absent flag; an
5271            // empty collection distinguishes it from an explicitly empty
5272            // `--flag=` string without inventing a sentinel value.
5273            let variadic_value = flag.arg.as_ref().is_some_and(|arg| arg.var);
5274            origins
5275                .entry(Arc::clone(&flag))
5276                .or_default()
5277                .push(ValueOrigin::DefaultMissing);
5278            if flag.var {
5279                // A repeated bare occurrence is still an occurrence. The string collection
5280                // uses an empty value for it, just as the concrete `default_missing` path
5281                // pushes one value per occurrence; otherwise bounds and consumers silently
5282                // lose every bare repeat after the first.
5283                flags
5284                    .entry(flag)
5285                    .or_insert_with(|| ParseValue::MultiString(Vec::new()))
5286                    .try_as_multi_string_mut()
5287                    .unwrap()
5288                    .push(String::new());
5289            } else if variadic_value {
5290                // A variadic occurrence stays pending after each value. Reaching the next
5291                // flag (or EOF) closes that same occurrence; it must not erase what it took.
5292                flags
5293                    .entry(flag)
5294                    .or_insert_with(|| ParseValue::MultiString(Vec::new()));
5295            } else {
5296                // A scalar pending here is a new bare occurrence. The normal permissive
5297                // repeat policy makes the later occurrence a correction, including a
5298                // correction from an explicit value back to the bare tri-state.
5299                flags.insert(flag, ParseValue::MultiString(Vec::new()));
5300            }
5301            return Ok(true);
5302        }
5303        None => return Ok(false),
5304    };
5305    if let Some(arg) = flag.arg.as_ref() {
5306        validate_choice_value(
5307            ChoiceTarget::option(flag),
5308            &value,
5309            arg.choices.as_ref(),
5310            custom_env,
5311        )?;
5312    }
5313    let flag = flag_awaiting_value.pop().unwrap();
5314    origins
5315        .entry(Arc::clone(&flag))
5316        .or_default()
5317        .push(ValueOrigin::DefaultMissing);
5318    let collecting = flag.var || flag.arg.as_ref().is_some_and(|arg| arg.var);
5319    if collecting {
5320        let arr = flags
5321            .entry(flag)
5322            .or_insert_with(|| ParseValue::MultiString(vec![]))
5323            .try_as_multi_string_mut()
5324            .unwrap();
5325        arr.push(value);
5326    } else {
5327        flags.insert(flag, ParseValue::String(value));
5328    }
5329    Ok(true)
5330}
5331
5332/// `bound` collects what each drained flag took, in the order it took it. The values are
5333/// the word after any `delimiter` split, which is the only place that split is known: by the
5334/// time they are in `flags` a scalar and a one-element list are indistinguishable, and a
5335/// second occurrence has appended to the same list.
5336#[allow(clippy::too_many_arguments)]
5337fn drain_pending_flag_values(
5338    spec: &Spec,
5339    cmd: &SpecCommand,
5340    errors: &mut Vec<UsageErr>,
5341    flags: &mut IndexMap<Arc<SpecFlag>, ParseValue>,
5342    flag_awaiting_value: &mut Vec<Arc<SpecFlag>>,
5343    word: &mut String,
5344    custom_env: Option<&HashMap<String, String>>,
5345    bound: &mut Vec<(Arc<SpecFlag>, Vec<String>)>,
5346) -> miette::Result<bool> {
5347    while let Some(flag) = flag_awaiting_value.pop() {
5348        let arg = flag.arg.as_ref().unwrap();
5349        // Split before anything judges the word, because after the split it is no longer
5350        // one value: `--env dev,prod` is two, and `choices` has to be asked about each.
5351        // Judging first would reject the whole word against a list neither half is on.
5352        let parts: Vec<String> = match arg.delimiter {
5353            Some(delimiter) => word.split(delimiter).map(str::to_string).collect(),
5354            None => vec![std::mem::take(word)],
5355        };
5356        for part in &parts {
5357            if validate_choices(
5358                spec,
5359                cmd,
5360                errors,
5361                ChoiceTarget::option(&flag),
5362                part,
5363                arg.choices.as_ref(),
5364                custom_env,
5365            )? {
5366                return Ok(true);
5367            }
5368        }
5369        word.clear();
5370        bound.push((Arc::clone(&flag), parts.clone()));
5371        // Two ways to hold several values, and both record a list: a `var` flag
5372        // collects one per occurrence, a variadic argument collects several from one.
5373        if flag.var || arg.var {
5374            let arr = flags
5375                .entry(flag)
5376                .or_insert_with(|| ParseValue::MultiString(vec![]))
5377                .try_as_multi_string_mut()
5378                .unwrap();
5379            arr.extend(parts);
5380        } else {
5381            // Nowhere for a second value to go, so the word stands as it was typed. A
5382            // delimiter on a flag that takes one value is refused where it is written.
5383            flags.insert(
5384                flag,
5385                ParseValue::String(parts.into_iter().next().unwrap_or_default()),
5386            );
5387        }
5388    }
5389    Ok(false)
5390}
5391
5392fn choice_error(
5393    target: ChoiceTarget<'_>,
5394    value: &str,
5395    choices: Option<&SpecChoices>,
5396    custom_env: Option<&HashMap<String, String>>,
5397) -> Option<String> {
5398    let choices = choices?;
5399    if !choices.strict {
5400        return None;
5401    }
5402    // The declared values and `env=` first, so a value they accept never costs a command.
5403    match choices.matches_resolved(value, custom_env) {
5404        Ok(true) => return None,
5405        Ok(false) => {}
5406        // Only a command could say, and this parse may not run one: let the value through
5407        // rather than report an error the real run might not have.
5408        Err(_) if choices.run().is_some() && crate::spec::choices::runs_disabled() => return None,
5409        Err(err) => {
5410            return Some(format!(
5411                "Could not check {} {}: {value} against its choices: {err}",
5412                target.kind, target.name,
5413            ));
5414        }
5415    }
5416    // Already run by the check above, so this reads what it printed rather than running it
5417    // again.
5418    let values = choices
5419        .resolved_values(custom_env)
5420        .unwrap_or_else(|_| choices.values_with_env(custom_env));
5421    if let Some(run) = choices.run()
5422        && values.is_empty()
5423    {
5424        return Some(format!(
5425            "Invalid choice for {} {}: {value}, `{run}` printed no choices",
5426            target.kind, target.name,
5427        ));
5428    }
5429    if let Some(env) = choices.env()
5430        && values.is_empty()
5431    {
5432        return Some(format!(
5433            "Invalid choice for {} {}: {value}, no choices resolved from env {env}",
5434            target.kind, target.name,
5435        ));
5436    }
5437    Some(format!(
5438        "Invalid choice for {} {}: {value}, expected one of {}",
5439        target.kind,
5440        target.name,
5441        values.join(", ")
5442    ))
5443}
5444
5445fn validate_choices(
5446    spec: &Spec,
5447    cmd: &SpecCommand,
5448    errors: &mut Vec<UsageErr>,
5449    target: ChoiceTarget<'_>,
5450    value: &str,
5451    choices: Option<&SpecChoices>,
5452    custom_env: Option<&HashMap<String, String>>,
5453) -> miette::Result<bool> {
5454    // A choice named like a help flag is a value, whether it was declared or printed by
5455    // `run=`. A command that cannot be run leaves the word to mean help, which is what a
5456    // user typing it most likely wanted.
5457    if is_help_arg(spec, cmd, value)
5458        && choices.is_some_and(|choices| {
5459            choices.strict && !choices.matches_resolved(value, custom_env).unwrap_or(false)
5460        })
5461    {
5462        errors.push(render_help_err(spec, cmd, value.len() > 2, custom_env));
5463        return Ok(true);
5464    }
5465
5466    if let Some(err) = choice_error(target, value, choices, custom_env) {
5467        bail!("{err}");
5468    }
5469    Ok(false)
5470}
5471
5472fn validate_choice_value(
5473    target: ChoiceTarget<'_>,
5474    value: &str,
5475    choices: Option<&SpecChoices>,
5476    custom_env: Option<&HashMap<String, String>>,
5477) -> miette::Result<()> {
5478    if let Some(err) = choice_error(target, value, choices, custom_env) {
5479        bail!("{err}");
5480    }
5481    Ok(())
5482}
5483
5484fn validate_choice_values(
5485    target: ChoiceTarget<'_>,
5486    values: &[String],
5487    choices: Option<&SpecChoices>,
5488    custom_env: Option<&HashMap<String, String>>,
5489) -> miette::Result<()> {
5490    for value in values {
5491        validate_choice_value(target, value, choices, custom_env)?;
5492    }
5493    Ok(())
5494}
5495
5496/// Everything a parse records about where it stopped: the positional cursor, so callers that
5497/// do not re-run the parse — completions, above all — agree with it, and the token trace.
5498///
5499/// Every exit from the binding phase comes through here, which is what makes it the right
5500/// place to close the trace: whatever is still queued was never read, and saying so is more
5501/// useful than leaving those words out of the report entirely.
5502fn record_stop(
5503    out: &mut ParseOutput,
5504    next_arg_idx: usize,
5505    seen_double_dash: bool,
5506    trace: &mut Trace,
5507    unread: &VecDeque<Token>,
5508) {
5509    out.next_arg = active_args(&out.cmd)
5510        .get(cursor_skip_sigils(&out.cmd, next_arg_idx))
5511        .cloned()
5512        .map(Arc::new);
5513    out.double_dash_seen = seen_double_dash;
5514    finalize_current_clause(out);
5515    trace.close(unread);
5516    out.tokens = std::mem::take(&mut trace.tokens);
5517}
5518
5519fn finalize_current_clause(out: &mut ParseOutput) {
5520    let Some(clause) = out.cmd.clause.as_ref() else {
5521        return;
5522    };
5523    let has_scoped_flags = clause
5524        .flags
5525        .iter()
5526        .any(|flag| out.flags.contains_key(&Arc::new(flag.clone())));
5527    if clause.separator.is_none() && out.args.is_empty() && !has_scoped_flags {
5528        return;
5529    }
5530    out.clauses
5531        .entry(clause.name.clone())
5532        .or_default()
5533        .push(std::mem::take(&mut out.args));
5534    let mut flags = IndexMap::new();
5535    for clause_flag in &clause.flags {
5536        let key = Arc::new(clause_flag.clone());
5537        if let Some((flag, value)) = out.flags.shift_remove_entry(&key) {
5538            flags.insert(flag, value);
5539        }
5540    }
5541    out.clause_flags
5542        .entry(clause.name.clone())
5543        .or_default()
5544        .push(flags);
5545}
5546
5547fn restore_current_clause(out: &mut ParseOutput) {
5548    let Some(clause) = out.cmd.clause.as_ref() else {
5549        return;
5550    };
5551    if let Some(current) = out.clauses.get_mut(&clause.name).and_then(Vec::pop) {
5552        out.args = current;
5553    }
5554    if let Some(current) = out.clause_flags.get_mut(&clause.name).and_then(Vec::pop) {
5555        out.flags.extend(current);
5556    }
5557}
5558
5559fn reset_clause_scalar_occurrences(
5560    out: &ParseOutput,
5561    occurrences: &mut HashMap<(usize, usize), u8>,
5562) {
5563    let Some(clause) = out.cmd.clause.as_ref() else {
5564        return;
5565    };
5566    let names = clause
5567        .flags
5568        .iter()
5569        .map(|flag| flag.name.as_str())
5570        .collect::<HashSet<_>>();
5571    let pointers = unique_flags(out.available_flags.values())
5572        .filter(|flag| names.contains(flag.name.as_str()))
5573        .map(|flag| Arc::as_ptr(flag) as usize)
5574        .collect::<HashSet<_>>();
5575    occurrences.retain(|(flag, _), _| !pointers.contains(flag));
5576}
5577
5578fn cursor_skip_sigils(cmd: &SpecCommand, mut idx: usize) -> usize {
5579    while active_args(cmd)
5580        .get(idx)
5581        .is_some_and(|arg| arg.sigil.is_some())
5582    {
5583        idx += 1;
5584    }
5585    idx
5586}
5587
5588fn active_args(cmd: &SpecCommand) -> &[SpecArg] {
5589    cmd.clause
5590        .as_ref()
5591        .map(|clause| clause.args.as_slice())
5592        .unwrap_or(cmd.args.as_slice())
5593}
5594
5595fn match_sigil_arg<'a>(
5596    cmd: &'a SpecCommand,
5597    word: &'a str,
5598) -> Option<(&'a SpecArg, &'a str, &'a str)> {
5599    cmd.args
5600        .iter()
5601        .filter_map(|arg| {
5602            let sigil = arg.sigil.as_deref()?;
5603            let value = word.strip_prefix(sigil)?;
5604            Some((arg, sigil, value))
5605        })
5606        .max_by_key(|(_, sigil, _)| sigil.len())
5607}
5608
5609fn match_sigil_arg_chain<'a>(
5610    cmds: &'a [SpecCommand],
5611    word: &'a str,
5612) -> Option<(&'a SpecArg, &'a str, &'a str)> {
5613    cmds.iter()
5614        .filter_map(|cmd| match_sigil_arg(cmd, word))
5615        .max_by_key(|(_, sigil, _)| sigil.len())
5616}
5617
5618/// Record that `arg` was handed a word before the `--` it requires.
5619///
5620/// A variadic arg would otherwise report the same mistake once per word it was offered, so the
5621/// message is emitted only the first time each arg is seen. The set is also what suppresses the
5622/// `MissingArg` that a `required` + `double_dash="required"` arg would otherwise collect at the
5623/// end of the parse.
5624fn report_double_dash_violation(
5625    arg: &SpecArg,
5626    errors: &mut Vec<UsageErr>,
5627    violations: &mut HashSet<String>,
5628) {
5629    if violations.insert(arg.name.clone()) {
5630        errors.push(UsageErr::ArgRequiresDoubleDash(arg.name.clone()));
5631    }
5632}
5633
5634/// `--version` and `-V`, which the parser supplies where the spec declares a version.
5635///
5636/// The twin of [`is_help_arg`], and of the `version` bit in usage-argv's and usage-go's
5637/// command tables — both of which accepted these spellings while this parser called them
5638/// unknown words. The help page has always listed `-V, --version` under the same
5639/// condition, and said in as many words that it did so "only where a version is
5640/// declared, which is where a parser accepts one", so a spec with a `version` rendered a
5641/// page advertising a flag the parse refused.
5642///
5643/// The root only, because that is where the page lists it: `version` is a property of
5644/// the program, and a subcommand answering with the program's version is a claim no spec
5645/// made. A declared flag wins by arriving first — every scan consults this only after
5646/// nothing declared matched — so a CLI that spends `-V` on something else keeps it, and
5647/// keeps `--version` supplied beside it.
5648fn is_version_arg(spec: &Spec, cmds: &[SpecCommand], w: &str) -> bool {
5649    (spec.version.is_some() || spec.long_version.is_some())
5650        && cmds.len() == 1
5651        && !spec.cmd.disable_version_flag
5652        && (w == "--version" || w == "-V")
5653}
5654
5655/// The help flags. The `help` *word* is not here: it is answered while commands are being
5656/// selected, the one place it is a command position, and is an ordinary word anywhere else.
5657fn is_help_arg(spec: &Spec, cmd: &SpecCommand, w: &str) -> bool {
5658    spec.disable_help != Some(true)
5659        && (w == "--help" || w == "-h" || w == "-?")
5660        && !cmd.disable_help_flag
5661}
5662
5663impl ParseOutput {
5664    pub fn as_env(&self) -> BTreeMap<String, String> {
5665        let mut env = BTreeMap::new();
5666        for (flag, val) in &self.flags {
5667            let key = format!("usage_{}", crate::case::snake(&flag.name));
5668            let val = match val {
5669                ParseValue::Bool(b) => if *b { "true" } else { "false" }.to_string(),
5670                ParseValue::String(s) => s.clone(),
5671                ParseValue::MultiBool(b) => b.iter().filter(|b| **b).count().to_string(),
5672                ParseValue::MultiString(s) => crate::shell_words::join(s),
5673            };
5674            env.insert(key, val);
5675        }
5676        for (arg, val) in &self.args {
5677            let key = format!("usage_{}", crate::case::snake(&arg.name));
5678            env.insert(key, val.to_string());
5679        }
5680        // The subcommand path, canonical names joined by spaces (`db migrate`), so a script can
5681        // dispatch on it without re-reading argv. Unset at the root, where there is nothing to
5682        // dispatch on. `cmd` is also an ordinary argument name, so a flag or arg the spec
5683        // declares under it anywhere on the path, clauses included, keeps the variable: a
5684        // script reading `$usage_cmd` for its own `<cmd>` must never get the path instead,
5685        // even when the arg was left out.
5686        let path = self.cmds.iter().skip(1).map(|c| c.name.as_str()).join(" ");
5687        let declared = |c: &SpecCommand| {
5688            let clause = c.clause.as_ref();
5689            c.args
5690                .iter()
5691                .chain(clause.into_iter().flat_map(|cl| &cl.args))
5692                .any(|a| crate::case::snake(&a.name) == "cmd")
5693                || c.flags
5694                    .iter()
5695                    .chain(clause.into_iter().flat_map(|cl| &cl.flags))
5696                    .any(|f| crate::case::snake(&f.name) == "cmd")
5697        };
5698        if !path.is_empty() && !self.cmds.iter().any(declared) {
5699            env.entry("usage_cmd".to_string()).or_insert(path);
5700        }
5701        env
5702    }
5703}
5704
5705impl Display for ParseValue {
5706    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
5707        match self {
5708            ParseValue::Bool(b) => write!(f, "{b}"),
5709            ParseValue::String(s) => write!(f, "{s}"),
5710            ParseValue::MultiBool(b) => write!(f, "{}", b.iter().join(" ")),
5711            ParseValue::MultiString(s) => write!(f, "{}", crate::shell_words::join(s)),
5712        }
5713    }
5714}
5715
5716/// One `tokens` line for [`Debug`]: the position, the word, and what it became.
5717fn render_token(token: &TokenBinding) -> String {
5718    let roles = token.roles.iter().map(render_role).join(", ");
5719    let synthesized = if token.synthesized { " (read as)" } else { "" };
5720    format!("[{}] {}{synthesized}: {roles}", token.index, token.word)
5721}
5722
5723fn render_role(role: &TokenRole) -> String {
5724    match role {
5725        TokenRole::Program => "program".to_string(),
5726        TokenRole::Command { name } => format!("subcommand {name}"),
5727        TokenRole::Flag {
5728            flag,
5729            spelling,
5730            negated,
5731        } => {
5732            let negated = if *negated { ", negated" } else { "" };
5733            format!("flag {} as {spelling}{negated}", flag.name)
5734        }
5735        TokenRole::Value {
5736            flag,
5737            values,
5738            attached,
5739        } => {
5740            let attached = if *attached { ", attached" } else { "" };
5741            format!("value of {} = {values:?}{attached}", flag.name)
5742        }
5743        TokenRole::Arg { arg, values } => format!("arg {} = {values:?}", arg.name),
5744        TokenRole::Sigil { arg, sigil, values } => {
5745            format!("sigil arg {} ({sigil}) = {values:?}", arg.name)
5746        }
5747        TokenRole::Separator => "separator".to_string(),
5748        TokenRole::Builtin { spelling } => format!("built-in {spelling}"),
5749        TokenRole::ValueTerminator { ends } => format!("value terminator, ends {ends}"),
5750        TokenRole::Restart => "restart".to_string(),
5751        TokenRole::ClauseSeparator { name } => format!("clause separator for {name}"),
5752        TokenRole::UnknownFlag { bound_as } => match bound_as {
5753            Some(arg) => format!("unknown flag, bound as {}", arg.name),
5754            None => "unknown flag".to_string(),
5755        },
5756        TokenRole::Refused { reason } => format!("refused: {reason}"),
5757        TokenRole::External => "external".to_string(),
5758        TokenRole::Unread => "unread".to_string(),
5759    }
5760}
5761
5762impl Debug for ParseOutput {
5763    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
5764        f.debug_struct("ParseOutput")
5765            .field("cmds", &self.cmds.iter().map(|c| &c.name).join(" ").trim())
5766            .field(
5767                "args",
5768                &self
5769                    .args
5770                    .iter()
5771                    .map(|(a, w)| format!("{}: {w}", a.name))
5772                    .collect_vec(),
5773            )
5774            .field("clauses", &self.clauses)
5775            .field(
5776                "available_flags",
5777                &self
5778                    .available_flags
5779                    .iter()
5780                    .map(|(f, w)| format!("{f}: {w}"))
5781                    .collect_vec(),
5782            )
5783            .field(
5784                "flags",
5785                &self
5786                    .flags
5787                    .iter()
5788                    .map(|(f, w)| format!("{}: {w}", f.name))
5789                    .collect_vec(),
5790            )
5791            .field("flag_awaiting_value", &self.flag_awaiting_value)
5792            .field("errors", &self.errors)
5793            .field("external", &self.external)
5794            // Provenance, one line per token and one per fallback. This is the parser's
5795            // debug channel under `USAGE_LOG=trace`, so it is where a spec author looks
5796            // first — `usage explain` renders the same facts for a reader.
5797            .field(
5798                "tokens",
5799                &self.tokens.iter().map(render_token).collect_vec(),
5800            )
5801            .field(
5802                "origins",
5803                &self
5804                    .flag_origins
5805                    .iter()
5806                    .map(|(f, o)| format!("{}: {o:?}", f.name))
5807                    .chain(
5808                        self.arg_origins
5809                            .iter()
5810                            .map(|(a, o)| format!("{}: {o:?}", a.name)),
5811                    )
5812                    .collect_vec(),
5813            )
5814            .field("overridden_flags", &self.overridden_flags)
5815            .finish()
5816    }
5817}
5818
5819#[cfg(test)]
5820mod tests {
5821    use super::*;
5822    use crate::SpecFlagAction;
5823
5824    fn input(words: &[&str]) -> Vec<String> {
5825        words.iter().map(|word| (*word).to_string()).collect()
5826    }
5827
5828    #[test]
5829    fn a_declared_version_supplies_the_flag_the_help_page_lists() {
5830        // The page has always listed `-V, --version` wherever a `version` is declared,
5831        // and usage-argv and usage-go have always accepted both. This parser called them
5832        // unknown words, so the one implementation the corpus measures the others against
5833        // was the one that disagreed.
5834        let spec: Spec = "name \"ex\"\nbin \"ex\"\nversion \"1.2.3\"\ncmd \"run\"\n"
5835            .parse()
5836            .unwrap();
5837
5838        for spelling in ["--version", "-V"] {
5839            let err = parse(&spec, &input(&["ex", spelling]))
5840                .expect_err("answering with a version ends the parse");
5841            assert_eq!(err.to_string(), "1.2.3", "{spelling}");
5842        }
5843    }
5844
5845    #[test]
5846    fn the_help_word_is_answered_where_the_page_lists_it() {
5847        // The page prints `help  Print this message…` on a command with subcommands, so that
5848        // is where the word asks for help; to a leaf it is an ordinary word.
5849        let spec: Spec = "name \"ex\"\nbin \"ex\"\ncmd \"a\" {\n  cmd \"b\" help=\"the b\"\n}\n"
5850            .parse()
5851            .unwrap();
5852
5853        for argv in [&["ex", "help"][..], &["ex", "a", "help"]] {
5854            let err = parse(&spec, &input(argv)).unwrap_err().to_string();
5855            assert!(err.contains("Usage:"), "{argv:?}: {err}");
5856        }
5857        let err = parse(&spec, &input(&["ex", "help", "a"]))
5858            .unwrap_err()
5859            .to_string();
5860        assert!(err.contains("Usage: ex a"), "{err}");
5861
5862        let err = parse(&spec, &input(&["ex", "a", "b", "help"]))
5863            .unwrap_err()
5864            .to_string();
5865        assert_eq!(err, "unexpected word: help");
5866    }
5867
5868    #[test]
5869    fn the_help_word_outranks_defaults_and_positionals_but_not_after_a_double_dash() {
5870        let positional: Spec = "name \"ex\"\nbin \"ex\"\narg \"[value]\"\ncmd \"a\"\n"
5871            .parse()
5872            .unwrap();
5873        let err = parse(&positional, &input(&["ex", "help"]))
5874            .unwrap_err()
5875            .to_string();
5876        assert!(err.contains("Usage:"), "{err}");
5877        assert!(parse(&positional, &input(&["ex", "--", "help"])).is_ok());
5878
5879        let default: Spec = "name \"ex\"\nbin \"ex\"\ndefault_subcommand \"a\"\ncmd \"a\"\n"
5880            .parse()
5881            .unwrap();
5882        let err = parse(&default, &input(&["ex", "help"]))
5883            .unwrap_err()
5884            .to_string();
5885        assert!(err.contains("Usage:"), "{err}");
5886    }
5887
5888    #[test]
5889    fn help_keeps_earlier_flags_and_yields_to_a_collecting_flag() {
5890        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--verbose\"\nflag \"--values <value>...\"\ncmd \"run\"\n"
5891            .parse()
5892            .unwrap();
5893        let err = parse(&spec, &input(&["ex", "--verbose", "help"]))
5894            .unwrap_err()
5895            .to_string();
5896        assert!(err.contains("Usage:"), "{err}");
5897        let out = parse(&spec, &input(&["ex", "--values", "a", "help"])).unwrap();
5898        assert!(out.flags.values().any(|v| v.to_string().contains("help")));
5899    }
5900
5901    #[test]
5902    fn the_help_word_is_ordinary_outside_command_position() {
5903        let spec: Spec = "name \"ex\"\nbin \"ex\"\ncmd \"a\"\n".parse().unwrap();
5904        let err = parse(&spec, &input(&["ex", "--", "help"]))
5905            .unwrap_err()
5906            .to_string();
5907        assert_eq!(err, "unexpected word: help");
5908
5909        let capped: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--include\" {\n  arg \"<pattern>...\" var_max=1\n}\narg \"[value]\"\ncmd \"run\"\n"
5910            .parse()
5911            .unwrap();
5912        let err = parse(&capped, &input(&["ex", "--include", "a", "help"]))
5913            .unwrap_err()
5914            .to_string();
5915        assert!(err.contains("Usage:"), "{err}");
5916    }
5917
5918    #[test]
5919    fn the_help_word_outranks_an_external_subcommand_unless_disabled() {
5920        let spec: Spec = "name \"ex\"\nbin \"ex\"\nexternal_subcommand #true\ncmd \"a\"\n"
5921            .parse()
5922            .unwrap();
5923        let err = parse(&spec, &input(&["ex", "help"]))
5924            .unwrap_err()
5925            .to_string();
5926        assert!(err.contains("Usage:"), "{err}");
5927
5928        let spec: Spec = "name \"ex\"\nbin \"ex\"\nexternal_subcommand #true\ndisable_help_subcommand #true\ncmd \"a\"\n"
5929            .parse()
5930            .unwrap();
5931        let out = parse(&spec, &input(&["ex", "help"])).unwrap();
5932        assert_eq!(out.external, Some(vec!["help".to_string()]));
5933    }
5934
5935    #[test]
5936    fn help_follows_a_completed_variadic_value_run() {
5937        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--values\" {\n  arg \"<value>...\" var_max=2\n}\ncmd \"run\"\n"
5938            .parse()
5939            .unwrap();
5940        let err = parse(&spec, &input(&["ex", "--values", "a", "b", "help"]))
5941            .unwrap_err()
5942            .to_string();
5943        assert!(err.contains("Usage:"), "{err}");
5944
5945        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--values\" {\n  arg \"<value>...\" var_max=2\n}\narg \"[value]\"\ncmd \"run\" help=\"the run\"\n"
5946            .parse()
5947            .unwrap();
5948        let err = parse(&spec, &input(&["ex", "--values", "a", "b", "help", "run"]))
5949            .unwrap_err()
5950            .to_string();
5951        assert!(err.contains("Usage: ex run"), "{err}");
5952    }
5953
5954    #[test]
5955    fn help_after_a_variadic_run_resolves_aliases_and_nested_commands() {
5956        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--values\" {\n  arg \"<value>...\" var_max=2\n}\ncmd \"run\" {\n  alias \"r\"\n  cmd \"sub\"\n}\n"
5957            .parse()
5958            .unwrap();
5959        for words in [&["help", "r"][..], &["help", "run"]] {
5960            let mut argv = vec!["ex", "--values", "a", "b"];
5961            argv.extend(words);
5962            let err = parse(&spec, &input(&argv)).unwrap_err().to_string();
5963            assert!(err.contains("Usage: ex run"), "{words:?}: {err}");
5964        }
5965        let err = parse(
5966            &spec,
5967            &input(&["ex", "--values", "a", "b", "help", "run", "sub"]),
5968        )
5969        .unwrap_err()
5970        .to_string();
5971        assert!(err.contains("Usage: ex run sub"), "{err}");
5972    }
5973
5974    #[test]
5975    fn help_after_a_restart_is_a_value() {
5976        let spec: Spec = "name \"ex\"\nbin \"ex\"\ncmd \"run\" restart_token=\":::\" {\n  arg \"<task>\"\n  cmd \"x\"\n}\n"
5977            .parse()
5978            .unwrap();
5979        let out = parse(&spec, &input(&["ex", "run", "build", ":::", "help"])).unwrap();
5980        assert!(out.errors.is_empty(), "{:?}", out.errors);
5981    }
5982
5983    #[test]
5984    fn the_supplied_version_flag_is_the_roots_alone() {
5985        // `version` describes the program, and the page lists the entry on the program's
5986        // own page only. A subcommand answering with it would be a claim no spec made.
5987        let spec: Spec = "name \"ex\"\nbin \"ex\"\nversion \"1.2.3\"\ncmd \"run\"\n"
5988            .parse()
5989            .unwrap();
5990
5991        let err = parse(&spec, &input(&["ex", "run", "--version"])).unwrap_err();
5992        assert_eq!(err.to_string(), "unexpected word: --version");
5993    }
5994
5995    #[test]
5996    fn no_declared_version_supplies_nothing() {
5997        // A `--version` answering with nothing is worse than one that is not there, which
5998        // is why the entry is conditional on the page and the spelling on the parse.
5999        let spec: Spec = "name \"ex\"\nbin \"ex\"\n".parse().unwrap();
6000
6001        for spelling in ["--version", "-V"] {
6002            let err = parse(&spec, &input(&["ex", spelling])).unwrap_err();
6003            assert_eq!(err.to_string(), format!("unexpected word: {spelling}"));
6004        }
6005    }
6006
6007    #[test]
6008    fn disable_version_flag_removes_the_supplied_spellings() {
6009        let spec: Spec = "name \"ex\"\nbin \"ex\"\nversion \"1.2.3\"\ndisable_version_flag #true\n"
6010            .parse()
6011            .unwrap();
6012
6013        for spelling in ["--version", "-V"] {
6014            let err = parse(&spec, &input(&["ex", spelling])).unwrap_err();
6015            assert_eq!(err.to_string(), format!("unexpected word: {spelling}"));
6016        }
6017    }
6018
6019    #[test]
6020    fn a_spelling_the_spec_spends_elsewhere_keeps_its_meaning() {
6021        // The page drops each supplied spelling the CLI claimed and keeps the other; the
6022        // parse agrees without being told, because a declared flag is matched first.
6023        let spec: Spec = "name \"ex\"\nbin \"ex\"\nversion \"1.2.3\"\nflag \"-V --verbose\"\n"
6024            .parse()
6025            .unwrap();
6026
6027        let out = parse(&spec, &input(&["ex", "-V"])).expect("-V is the CLI's own flag");
6028        assert_eq!(out.flags.len(), 1);
6029
6030        let err = parse(&spec, &input(&["ex", "--version"])).unwrap_err();
6031        assert_eq!(err.to_string(), "1.2.3");
6032    }
6033
6034    #[test]
6035    fn the_supplied_spellings_split_the_two_version_texts() {
6036        // The same split `render_action_err` gives a declared version flag: the long
6037        // spelling prefers `long_version`, the short prefers the concise one.
6038        let spec: Spec =
6039            "name \"ex\"\nbin \"ex\"\nversion \"1.2.3\"\nlong_version \"1.2.3 (abcdef)\"\n"
6040                .parse()
6041                .unwrap();
6042
6043        assert_eq!(
6044            parse(&spec, &input(&["ex", "--version"]))
6045                .unwrap_err()
6046                .to_string(),
6047            "1.2.3 (abcdef)"
6048        );
6049        assert_eq!(
6050            parse(&spec, &input(&["ex", "-V"])).unwrap_err().to_string(),
6051            "1.2.3"
6052        );
6053    }
6054
6055    #[test]
6056    fn a_supplied_short_is_a_letter_a_bundle_may_contain() {
6057        // `-h` and `-V` are recognized letters that no spec declares, so a token holding
6058        // one beside a declared letter is a bundle. usage-lib alone read `-vh` as a word
6059        // naming nothing: usage-argv and usage-go both resolve the letter through the
6060        // same lookup that finds a declared short, and clap prints help for it too.
6061        let spec: Spec =
6062            "name \"ex\"\nbin \"ex\"\nversion \"1.2.3\"\nflag \"-v --verbose\"\ncmd \"run\"\n"
6063                .parse()
6064                .unwrap();
6065
6066        for token in ["-vh", "-hv"] {
6067            let err = parse(&spec, &input(&["ex", token])).expect_err("help ends the parse");
6068            assert!(err.to_string().starts_with("ex 1.2.3"), "{token}: {err}");
6069        }
6070        for token in ["-vV", "-Vv"] {
6071            let err = parse(&spec, &input(&["ex", token])).expect_err("a version ends it too");
6072            assert_eq!(err.to_string(), "1.2.3", "{token}");
6073        }
6074    }
6075
6076    #[test]
6077    fn a_bundled_help_letter_asks_for_the_short_page() {
6078        // Whatever else shares the token: `-h` is the short spelling, and the letters
6079        // beside it say nothing about which page was asked for.
6080        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"-v --verbose\" help=\"Be loud\" {\n    long_help \"Be loud, and say so at length.\"\n}\n"
6081            .parse()
6082            .unwrap();
6083
6084        let short = parse(&spec, &input(&["ex", "-vh"]))
6085            .unwrap_err()
6086            .to_string();
6087        let long = parse(&spec, &input(&["ex", "--help"]))
6088            .unwrap_err()
6089            .to_string();
6090        assert!(short.contains("Be loud"), "{short}");
6091        assert!(!short.contains("at length"), "{short}");
6092        assert!(long.contains("at length"), "{long}");
6093    }
6094
6095    #[test]
6096    fn the_bundled_version_letter_is_the_roots_alone() {
6097        // The same rule the whole-token spelling follows, asked one letter at a time.
6098        let spec: Spec =
6099            "name \"ex\"\nbin \"ex\"\nversion \"1.2.3\"\nflag \"-v --verbose\" global=#true\ncmd \"run\"\n"
6100                .parse()
6101                .unwrap();
6102
6103        let err = parse(&spec, &input(&["ex", "run", "-vV"])).unwrap_err();
6104        assert_eq!(err.to_string(), "unexpected word: -vV");
6105    }
6106
6107    #[test]
6108    fn a_declared_letter_keeps_its_meaning_inside_a_bundle() {
6109        // Nothing is supplied where the CLI spent the letter itself, so `-vh local` is
6110        // this spec's own `-h`, taking its value from the rest of the token.
6111        let spec: Spec =
6112            "name \"ex\"\nbin \"ex\"\nversion \"1.2.3\"\nflag \"-v --verbose\"\nflag \"-h --host <host>\"\n"
6113                .parse()
6114                .unwrap();
6115
6116        let out = parse(&spec, &input(&["ex", "-vhlocal"])).expect("a bundle and its value");
6117        assert_eq!(out.flags.len(), 2);
6118        assert!(
6119            out.flags
6120                .iter()
6121                .any(|(flag, value)| flag.name == "host" && value.to_string() == "local")
6122        );
6123    }
6124
6125    #[test]
6126    fn disabling_help_takes_the_letter_back_out_of_the_bundle() {
6127        let spec: Spec =
6128            "name \"ex\"\nbin \"ex\"\ndisable_help_flag #true\nflag \"-v --verbose\"\n"
6129                .parse()
6130                .unwrap();
6131
6132        let err = parse(&spec, &input(&["ex", "-vh"])).unwrap_err();
6133        assert_eq!(err.to_string(), "unexpected word: -vh");
6134    }
6135
6136    #[test]
6137    fn a_letter_nothing_supplies_still_refuses_the_whole_bundle() {
6138        // The rule this must not weaken: `-az` is not a bundle at all, so `-a` is not set
6139        // on the way to discovering that `z` names nothing.
6140        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"-a --all\"\narg \"[file]\"\n"
6141            .parse()
6142            .unwrap();
6143
6144        let out = parse(&spec, &input(&["ex", "-az"])).expect("it falls through to the argument");
6145        assert!(out.flags.is_empty(), "{:?}", out.flags);
6146        assert_eq!(out.args.len(), 1);
6147    }
6148
6149    fn spec_with_arg(arg: SpecArg) -> Spec {
6150        let cmd = SpecCommand::builder().name("test").arg(arg).build();
6151        Spec {
6152            name: "test".to_string(),
6153            bin: "test".to_string(),
6154            cmd,
6155            ..Default::default()
6156        }
6157    }
6158
6159    fn spec_with_flag(flag: SpecFlag) -> Spec {
6160        let cmd = SpecCommand::builder().name("test").flag(flag).build();
6161        Spec {
6162            name: "test".to_string(),
6163            bin: "test".to_string(),
6164            cmd,
6165            ..Default::default()
6166        }
6167    }
6168
6169    fn parse_with_env(
6170        spec: &Spec,
6171        words: &[&str],
6172        env: &[(&str, &str)],
6173    ) -> Result<ParseOutput, miette::Error> {
6174        let env = env
6175            .iter()
6176            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
6177            .collect();
6178        Parser::new(spec).with_env(env).parse(&input(words))
6179    }
6180
6181    fn first_string_value(parsed: &ParseOutput) -> &str {
6182        if let Some(ParseValue::String(value)) = parsed.args.values().next() {
6183            return value;
6184        }
6185        if let Some(ParseValue::String(value)) = parsed.flags.values().next() {
6186            return value;
6187        }
6188        panic!("expected first parsed value to be ParseValue::String");
6189    }
6190
6191    #[test]
6192    fn custom_environment_parser_dispatches_executable_views() {
6193        let spec: Spec = r#"
6194bin "ex"
6195view "runner" root="run"
6196cmd "run" {
6197    flag "--token <token>" env="TOKEN"
6198}
6199        "#
6200        .parse()
6201        .unwrap();
6202        let parsed = Parser::new(&spec)
6203            .with_env([("TOKEN".to_string(), "secret".to_string())].into())
6204            .parse(&input(&["runner"]))
6205            .unwrap();
6206
6207        assert_eq!(parsed.cmd.name, "runner");
6208        assert!(parsed.flags.iter().any(|(flag, value)| flag.name == "token"
6209            && matches!(value, ParseValue::String(value) if value == "secret")));
6210    }
6211
6212    #[test]
6213    fn an_executable_view_keeps_the_hosts_version_action() {
6214        let spec: Spec = r#"
6215bin "ex"
6216version "1.2.3"
6217flag "-V --version" action="version"
6218flag "--verbose" global=#true
6219view "runner" root="run" globals=#true
6220cmd "run"
6221        "#
6222        .parse()
6223        .unwrap();
6224
6225        let error = Parser::new(&spec)
6226            .parse(&input(&["runner", "--version"]))
6227            .expect_err("the host version action should answer before view projection");
6228        assert_eq!(error.to_string(), "1.2.3");
6229
6230        let error = Parser::new(&spec)
6231            .parse(&input(&["runner", "--verbose", "--version"]))
6232            .expect_err("the host version action should remain after a carried global");
6233        assert_eq!(error.to_string(), "1.2.3");
6234    }
6235
6236    fn flag_string_value<'a>(parsed: &'a ParseOutput, name: &str) -> &'a str {
6237        let flag = parsed
6238            .flags
6239            .keys()
6240            .find(|flag| flag.name == name)
6241            .unwrap_or_else(|| panic!("expected flag {name}"));
6242        let value = parsed
6243            .flags
6244            .get(flag)
6245            .unwrap_or_else(|| panic!("expected value for flag {name}"));
6246        match value {
6247            ParseValue::String(value) => value,
6248            _ => panic!("expected flag {name} to be ParseValue::String"),
6249        }
6250    }
6251
6252    fn assert_parse_err(result: Result<ParseOutput, miette::Error>, expected: &str) {
6253        let err = result.expect_err("expected parser error");
6254        assert_eq!(format!("{err}"), expected);
6255    }
6256
6257    #[test]
6258    fn a_short_version_action_falls_back_to_the_long_version() {
6259        let flag = SpecFlag::builder()
6260            .short('R')
6261            .action(SpecFlagAction::Version)
6262            .build();
6263        let spec = Spec {
6264            name: "test".to_string(),
6265            bin: "test".to_string(),
6266            long_version: Some("1.2.3\ncommit abc123".to_string()),
6267            ..Default::default()
6268        };
6269        let UsageErr::Version(version) = render_action_err(&spec, &spec.cmd, &flag, "-R", None)
6270        else {
6271            panic!("expected version action")
6272        };
6273        assert_eq!(version, "1.2.3\ncommit abc123");
6274    }
6275
6276    #[cfg(feature = "unstable_choices_env")]
6277    fn spec_arg_choices_env(key: &str) -> Spec {
6278        spec_with_arg(
6279            SpecArg::builder()
6280                .name("env")
6281                .choices_env(key)
6282                .required(false)
6283                .build(),
6284        )
6285    }
6286
6287    #[cfg(feature = "unstable_choices_env")]
6288    fn spec_flag_choices_env(key: &str) -> Spec {
6289        spec_with_flag(
6290            SpecFlag::builder()
6291                .long("env")
6292                .arg(SpecArg::builder().name("env").choices_env(key).build())
6293                .build(),
6294        )
6295    }
6296
6297    #[test]
6298    fn test_parse() {
6299        let cmd = SpecCommand::builder()
6300            .name("test")
6301            .arg(SpecArg::builder().name("arg").build())
6302            .flag(SpecFlag::builder().long("flag").build())
6303            .build();
6304        let spec = Spec {
6305            name: "test".to_string(),
6306            bin: "test".to_string(),
6307            cmd,
6308            ..Default::default()
6309        };
6310        let input = vec!["test".to_string(), "arg1".to_string(), "--flag".to_string()];
6311        let parsed = parse(&spec, &input).unwrap();
6312        assert_eq!(parsed.cmds.len(), 1);
6313        assert_eq!(parsed.cmds[0].name, "test");
6314        assert_eq!(parsed.args.len(), 1);
6315        assert_eq!(parsed.flags.len(), 1);
6316        assert_eq!(parsed.available_flags.len(), 1);
6317    }
6318
6319    #[test]
6320    fn test_flag_overrides_last_occurrence_wins() {
6321        let spec: Spec = r#"
6322flag "--stdin" default=#true
6323flag "--file <file>" overrides="--stdin"
6324        "#
6325        .parse()
6326        .unwrap();
6327
6328        let file_wins = parse(&spec, &input(&["test", "--stdin", "--file", "input.txt"])).unwrap();
6329        assert_eq!(file_wins.flags.len(), 1);
6330        assert_eq!(flag_string_value(&file_wins, "file"), "input.txt");
6331        assert!(!file_wins.flags.keys().any(|flag| flag.name == "stdin"));
6332
6333        let stdin_wins = parse(&spec, &input(&["test", "--file", "input.txt", "--stdin"])).unwrap();
6334        assert_eq!(stdin_wins.flags.len(), 1);
6335        assert!(stdin_wins.flags.keys().any(|flag| flag.name == "stdin"));
6336        assert!(!stdin_wins.flags.keys().any(|flag| flag.name == "file"));
6337    }
6338
6339    #[test]
6340    fn test_flag_override_clears_pending_value() {
6341        let spec: Spec = r#"
6342flag "--file <file>" overrides="--stdin"
6343flag "--stdin"
6344arg "[input]"
6345        "#
6346        .parse()
6347        .unwrap();
6348
6349        let parsed = parse(&spec, &input(&["test", "--file", "--stdin", "input.txt"])).unwrap();
6350        assert_eq!(parsed.flags.len(), 1);
6351        assert!(parsed.flags.keys().any(|flag| flag.name == "stdin"));
6352        assert_eq!(first_string_value(&parsed), "input.txt");
6353    }
6354
6355    #[cfg(unix)]
6356    #[test]
6357    fn a_mount_on_the_root_discovers_subcommands() {
6358        // The root is a command like any other, so it can find its own subcommands
6359        // by running something. Uses `echo` rather than a fixture because resolving
6360        // a mount is what is being tested.
6361        let spec: Spec = r#"
6362name "ex"
6363bin "ex"
6364cmd "declared"
6365mount run="echo 'cmd \"discovered\"'"
6366"#
6367        .parse()
6368        .unwrap();
6369
6370        let out = parse(&spec, &["ex".to_string(), "discovered".to_string()]).unwrap();
6371        assert_eq!(out.cmd.name, "discovered");
6372    }
6373
6374    #[test]
6375    fn unknown_env_knows_the_variables_a_mounted_command_declares() {
6376        let spec: Spec = r#"
6377name "ex"
6378bin "ex"
6379unknown_env prefix="EX_"
6380mount run="discover"
6381cmd "publish"
6382"#
6383        .parse()
6384        .unwrap();
6385        let mounts: HashMap<String, String> = [(
6386            "discover".to_string(),
6387            "cmd \"serve\" {\n  flag \"--port <port>\" env=\"EX_PORT\"\n}\n".to_string(),
6388        )]
6389        .into();
6390        let env = |name: &str| -> HashMap<String, String> { [(name.into(), "1".into())].into() };
6391
6392        let out = Parser::new(&spec)
6393            .with_mount_outputs(mounts.clone())
6394            .with_env(env("EX_PORT"))
6395            .parse(&input(&["ex", "serve"]))
6396            .expect("the mounted command declares EX_PORT");
6397        assert_eq!(out.cmd.name, "serve");
6398
6399        // `publish` is declared, so the parse never runs the mount, and the check does not run
6400        // it either: what only a mount declares is for `allow`.
6401        let err = Parser::new(&spec)
6402            .with_mount_outputs(mounts.clone())
6403            .with_env(env("EX_PORT"))
6404            .parse(&input(&["ex", "publish"]))
6405            .unwrap_err();
6406        assert!(err.to_string().contains("EX_PORT"), "{err}");
6407
6408        let err = Parser::new(&spec)
6409            .with_mount_outputs(mounts)
6410            .with_env(env("EX_PROT"))
6411            .parse(&input(&["ex", "serve"]))
6412            .unwrap_err();
6413        assert!(err.to_string().contains("EX_PROT"), "{err}");
6414    }
6415
6416    #[test]
6417    fn injected_mount_outputs_are_complete_and_never_fall_back_to_processes() {
6418        let spec: Spec = r#"
6419name "ex"
6420bin "ex"
6421mount run="this command must never run"
6422cmd "declared"
6423"#
6424        .parse()
6425        .unwrap();
6426
6427        Parser::new(&spec)
6428            .with_mount_outputs(HashMap::new())
6429            .parse(&input(&["ex", "declared"]))
6430            .expect("a declared command does not resolve the mount");
6431
6432        let error = Parser::new(&spec)
6433            .with_mount_outputs(HashMap::new())
6434            .parse(&input(&["ex", "discovered"]))
6435            .unwrap_err();
6436        assert!(
6437            error
6438                .to_string()
6439                .contains("No injected output was provided for mount command"),
6440            "{error}"
6441        );
6442    }
6443
6444    #[cfg(unix)]
6445    #[test]
6446    fn completion_sees_root_mounted_commands_with_nothing_typed() {
6447        // The case a root mount exists for. `mycli <tab>` has no word to trigger
6448        // discovery with, so a completion has to resolve up front or the mounted
6449        // commands are never offered.
6450        let spec: Spec = r#"
6451name "ex"
6452bin "ex"
6453cmd "declared"
6454mount run="echo 'cmd \"discovered\"'"
6455"#
6456        .parse()
6457        .unwrap();
6458
6459        let out = parse_partial(&spec, &["ex".to_string()]).unwrap();
6460        assert!(
6461            out.cmd.subcommands.contains_key("discovered"),
6462            "a completion should see mounted commands; got {:?}",
6463            out.cmd.subcommands.keys().collect::<Vec<_>>()
6464        );
6465    }
6466
6467    #[cfg(unix)]
6468    #[test]
6469    fn completion_and_execution_agree_about_discovery() {
6470        // Offering a command that a real parse would hand to the default instead is
6471        // worse than not offering it, so the gate applies to both paths. The mount
6472        // fails if it runs, which is how both halves are checked at once.
6473        let spec: Spec = r#"
6474name "ex"
6475bin "ex"
6476default_subcommand "run"
6477cmd "run" {
6478  arg "<task>"
6479}
6480mount run="exit 1"
6481"#
6482        .parse()
6483        .unwrap();
6484
6485        let out = parse_partial(&spec, &["ex".to_string()]).unwrap();
6486        assert!(
6487            !out.cmd.subcommands.contains_key("discovered"),
6488            "a completion must not offer what execution will not route"
6489        );
6490
6491        let out = parse(&spec, &["ex".to_string(), "mytask".to_string()]).unwrap();
6492        assert_eq!(out.cmd.name, "run");
6493    }
6494
6495    #[cfg(unix)]
6496    #[test]
6497    fn a_default_subcommand_outranks_discovery() {
6498        // The default already says what an unmatched word means, and says it for
6499        // free. The mount fails if it runs, so parsing proves discovery was skipped.
6500        let spec: Spec = r#"
6501name "ex"
6502bin "ex"
6503default_subcommand "run"
6504cmd "run" {
6505  arg "<task>"
6506}
6507mount run="exit 1"
6508"#
6509        .parse()
6510        .unwrap();
6511
6512        let out = parse(&spec, &["ex".to_string(), "mytask".to_string()]).unwrap();
6513        assert_eq!(out.cmd.name, "run");
6514    }
6515
6516    #[cfg(unix)]
6517    #[test]
6518    fn a_mount_may_ask_to_outrank_the_default() {
6519        // Opting in, and paying for it: discovery runs first, so a discovered
6520        // command wins over the fallback.
6521        let spec: Spec = r#"
6522name "ex"
6523bin "ex"
6524default_subcommand "run"
6525cmd "run" {
6526  arg "<task>"
6527}
6528mount run="echo 'cmd \"discovered\"'" overrides_default=#true
6529"#
6530        .parse()
6531        .unwrap();
6532
6533        let out = parse(&spec, &["ex".to_string(), "discovered".to_string()]).unwrap();
6534        assert_eq!(out.cmd.name, "discovered");
6535
6536        // A word it does not know still reaches the default.
6537        let out = parse(&spec, &["ex".to_string(), "mytask".to_string()]).unwrap();
6538        assert_eq!(out.cmd.name, "run");
6539    }
6540
6541    #[cfg(unix)]
6542    #[test]
6543    fn a_flag_does_not_run_the_mount() {
6544        // A flag matches no subcommand, which would have been enough to trigger
6545        // discovery — so `ex --help` spawned a process. The mount fails if it runs,
6546        // so parsing at all is the proof that it did not.
6547        let spec: Spec = r#"
6548name "ex"
6549bin "ex"
6550flag "--verbose"
6551cmd "declared"
6552mount run="exit 1"
6553"#
6554        .parse()
6555        .unwrap();
6556
6557        let out = parse(&spec, &["ex".to_string(), "--verbose".to_string()]).unwrap();
6558        assert_eq!(out.cmd.name, "ex");
6559    }
6560
6561    #[cfg(unix)]
6562    #[test]
6563    fn a_declared_subcommand_does_not_run_the_mount() {
6564        // The mount would fail if it ran, so this parsing at all is the proof that
6565        // discovery is skipped when the word is already known. Worth pinning: a root
6566        // mount that resolved eagerly would spawn a process on every invocation.
6567        let spec: Spec = r#"
6568name "ex"
6569bin "ex"
6570cmd "declared"
6571mount run="exit 1"
6572"#
6573        .parse()
6574        .unwrap();
6575
6576        let out = parse(&spec, &["ex".to_string(), "declared".to_string()]).unwrap();
6577        assert_eq!(out.cmd.name, "declared");
6578    }
6579
6580    #[test]
6581    fn a_root_mount_survives_being_written_out() {
6582        let spec: Spec = "name \"ex\"\nbin \"ex\"\nmount run=\"ex plugins --usage\"\n"
6583            .parse()
6584            .unwrap();
6585        assert_eq!(spec.cmd.mounts.len(), 1);
6586
6587        let reparsed: Spec = spec.to_string().parse().unwrap();
6588        assert_eq!(reparsed.cmd.mounts.len(), 1, "written:\n{spec}");
6589        assert_eq!(reparsed.cmd.mounts[0].run, "ex plugins --usage");
6590    }
6591
6592    #[test]
6593    fn test_mount_prefix_applies_flag_overrides() {
6594        let stdin = Arc::new(
6595            SpecFlag::builder()
6596                .name("stdin")
6597                .long("stdin")
6598                .global(true)
6599                .build(),
6600        );
6601        let file = Arc::new(
6602            SpecFlag::builder()
6603                .name("file")
6604                .long("file")
6605                .arg(SpecArg::builder().name("file").build())
6606                .global(true)
6607                .overrides_with(vec!["--stdin".to_string()])
6608                .build(),
6609        );
6610        let mut prefix_flags = vec![(stdin, vec!["--stdin".to_string()])];
6611
6612        apply_prefix_flag_overrides(&mut prefix_flags, Arc::clone(&file));
6613        prefix_flags.push((file, vec!["--file".to_string(), "input.txt".to_string()]));
6614
6615        assert_eq!(mount_prefix_words(&prefix_flags), ["--file", "input.txt"]);
6616    }
6617
6618    #[test]
6619    fn test_flag_override_suppresses_env_value() {
6620        let spec: Spec = r#"
6621flag "--stdin" env="USE_STDIN"
6622flag "--file <file>" overrides="--stdin"
6623        "#
6624        .parse()
6625        .unwrap();
6626
6627        let parsed = parse_with_env(
6628            &spec,
6629            &["test", "--file", "input.txt"],
6630            &[("USE_STDIN", "true")],
6631        )
6632        .unwrap();
6633        assert_eq!(parsed.flags.len(), 1);
6634        assert_eq!(flag_string_value(&parsed, "file"), "input.txt");
6635    }
6636
6637    #[test]
6638    fn test_flag_override_suppresses_required_check() {
6639        let spec: Spec = r#"
6640flag "--stdin" required=#true
6641flag "--file <file>" overrides="--stdin"
6642        "#
6643        .parse()
6644        .unwrap();
6645
6646        let parsed = parse(&spec, &input(&["test", "--file", "input.txt"])).unwrap();
6647        assert_eq!(parsed.flags.len(), 1);
6648        assert_eq!(flag_string_value(&parsed, "file"), "input.txt");
6649    }
6650
6651    #[test]
6652    fn test_flag_required_if() {
6653        let spec: Spec = r#"
6654flag "--dir <dir>"
6655flag "--file <file>" required_if="--dir"
6656        "#
6657        .parse()
6658        .unwrap();
6659
6660        parse(&spec, &input(&["test"])).unwrap();
6661        assert_parse_err(
6662            parse(&spec, &input(&["test", "--dir", "src"])),
6663            "Missing required flag: --file <file>",
6664        );
6665        parse(
6666            &spec,
6667            &input(&["test", "--dir", "src", "--file", "input.txt"]),
6668        )
6669        .unwrap();
6670    }
6671
6672    #[test]
6673    fn test_flag_required_unless() {
6674        let spec: Spec = r#"
6675flag "--stdin"
6676flag "--file <file>" required_unless="--stdin"
6677        "#
6678        .parse()
6679        .unwrap();
6680
6681        assert_parse_err(
6682            parse(&spec, &input(&["test"])),
6683            "Missing required flag: --file <file>",
6684        );
6685        parse(&spec, &input(&["test", "--stdin"])).unwrap();
6686        parse(&spec, &input(&["test", "--file", "input.txt"])).unwrap();
6687    }
6688
6689    #[test]
6690    fn complete_required_relationship_truth_tables() {
6691        let spec: Spec = r#"
6692name "ex"
6693bin "ex"
6694flag "--mode <mode>"
6695flag "--scope <scope>"
6696flag "--token <token>" {
6697    required_if_eq "--mode" "remote"
6698}
6699flag "--approval <approval>" {
6700    required_if_eq_all "--mode" "remote" "--scope" "global"
6701}
6702flag "--input <input>" {
6703    required_unless "--stdin" "--file"
6704}
6705flag "--checksum <checksum>" {
6706    required_unless_all "--stdin" "--file"
6707}
6708flag "--stdin"
6709flag "--file <file>"
6710arg "[request]" {
6711    requires "--mode" "--scope"
6712}
6713"#
6714        .parse()
6715        .unwrap();
6716        let parse_args = |args: &[&str]| {
6717            parse(
6718                &spec,
6719                &args
6720                    .iter()
6721                    .map(|arg| (*arg).to_string())
6722                    .collect::<Vec<_>>(),
6723            )
6724        };
6725
6726        assert!(parse_args(&["ex", "--mode", "remote", "--stdin"]).is_err());
6727        assert!(
6728            parse_args(&[
6729                "ex", "--mode", "remote", "--token", "secret", "--scope", "global", "--stdin",
6730            ])
6731            .is_err()
6732        );
6733        parse_args(&[
6734            "ex",
6735            "--mode",
6736            "remote",
6737            "--token",
6738            "secret",
6739            "--scope",
6740            "global",
6741            "--approval",
6742            "yes",
6743            "--stdin",
6744            "--file",
6745            "in",
6746        ])
6747        .unwrap();
6748        parse_args(&[
6749            "ex",
6750            "--mode",
6751            "local",
6752            "--scope",
6753            "project",
6754            "--stdin",
6755            "--checksum",
6756            "sum",
6757            "request.json",
6758        ])
6759        .unwrap();
6760
6761        let reparsed: Spec = spec.to_string().parse().unwrap();
6762        assert_eq!(reparsed.cmd.flags[2].required_if_eq.len(), 1);
6763        assert_eq!(reparsed.cmd.flags[3].required_if_eq_all.len(), 2);
6764        assert_eq!(reparsed.cmd.flags[5].required_unless_all.len(), 2);
6765        assert_eq!(reparsed.cmd.args[0].requires.len(), 2);
6766    }
6767
6768    #[test]
6769    fn test_conditional_requirements_treat_env_as_explicit() {
6770        let spec: Spec = r#"
6771flag "--dir <dir>" env="INPUT_DIR"
6772flag "--stdin" env="USE_STDIN"
6773flag "--file <file>" required_if="--dir" required_unless="--stdin"
6774        "#
6775        .parse()
6776        .unwrap();
6777
6778        assert_parse_err(
6779            parse_with_env(&spec, &["test"], &[("INPUT_DIR", "src")]),
6780            "Missing required flag: --file <file>",
6781        );
6782        parse_with_env(&spec, &["test"], &[("USE_STDIN", "true")]).unwrap();
6783    }
6784
6785    #[test]
6786    fn test_custom_env_does_not_fall_back_to_process_env() {
6787        assert!(std::env::var("PATH").is_ok());
6788        let spec: Spec = r#"flag "--file <file>" env="PATH" required=#true"#.parse().unwrap();
6789
6790        assert_parse_err(
6791            parse_with_env(&spec, &["test"], &[]),
6792            "Missing required flag: --file <file>",
6793        );
6794    }
6795
6796    #[test]
6797    fn test_conditional_requirements_ignore_defaults_on_condition_flags() {
6798        let spec: Spec = r#"
6799flag "--dir <dir>" default="src"
6800flag "--file <file>" required_if="--dir"
6801        "#
6802        .parse()
6803        .unwrap();
6804
6805        parse(&spec, &input(&["test"])).unwrap();
6806    }
6807
6808    #[test]
6809    fn test_conditional_requirements_see_overridden_flags_as_absent() {
6810        let spec: Spec = r#"
6811flag "--stdin"
6812flag "--dir <dir>" overrides="--stdin"
6813flag "--file <file>" required_unless="--stdin"
6814        "#
6815        .parse()
6816        .unwrap();
6817
6818        assert_parse_err(
6819            parse(&spec, &input(&["test", "--stdin", "--dir", "src"])),
6820            "Missing required flag: --file <file>",
6821        );
6822    }
6823
6824    #[test]
6825    fn short_flag_is_one_character_not_one_byte() {
6826        // A short is declared and read by character. Counting bytes instead either
6827        // refuses the declaration or slices the token inside the character, and clap
6828        // — which many specs are generated from — accepts shorts like this one.
6829        let spec = spec_with_flag(
6830            SpecFlag::builder()
6831                .short('磨')
6832                .long("polish")
6833                .arg(SpecArg::builder().name("opt").build())
6834                .build(),
6835        );
6836        let attached = Parser::new(&spec)
6837            .parse(&input(&["test", "-磨VALUE"]))
6838            .unwrap();
6839        assert_eq!(flag_string_value(&attached, "polish"), "VALUE");
6840        let detached = Parser::new(&spec)
6841            .parse(&input(&["test", "-磨", "V"]))
6842            .unwrap();
6843        assert_eq!(flag_string_value(&detached, "polish"), "V");
6844    }
6845
6846    #[test]
6847    fn test_as_env() {
6848        let cmd = SpecCommand::builder()
6849            .name("test")
6850            .arg(SpecArg::builder().name("arg").build())
6851            .flag(SpecFlag::builder().long("flag").build())
6852            .flag(
6853                SpecFlag::builder()
6854                    .long("force")
6855                    .negate("--no-force")
6856                    .build(),
6857            )
6858            .build();
6859        let spec = Spec {
6860            name: "test".to_string(),
6861            bin: "test".to_string(),
6862            cmd,
6863            ..Default::default()
6864        };
6865        let input = vec![
6866            "test".to_string(),
6867            "--flag".to_string(),
6868            "--no-force".to_string(),
6869        ];
6870        let parsed = parse(&spec, &input).unwrap();
6871        let env = parsed.as_env();
6872        assert_eq!(env.len(), 2);
6873        assert_eq!(env.get("usage_flag"), Some(&"true".to_string()));
6874        assert_eq!(env.get("usage_force"), Some(&"false".to_string()));
6875    }
6876
6877    #[test]
6878    fn as_env_names_the_subcommand_path() {
6879        let spec: Spec = r#"
6880            flag "-v --verbose"
6881            cmd "db" {
6882                cmd "migrate" {
6883                    alias "m"
6884                    arg "[target]"
6885                }
6886            }
6887            "#
6888        .parse()
6889        .unwrap();
6890        let env = |args: &[&str]| {
6891            let input: Vec<String> = std::iter::once("test")
6892                .chain(args.iter().copied())
6893                .map(String::from)
6894                .collect();
6895            parse(&spec, &input).unwrap().as_env()
6896        };
6897
6898        // The canonical name, not the alias that was typed.
6899        let nested = env(&["db", "m", "v2"]);
6900        assert_eq!(
6901            nested.get("usage_cmd").map(String::as_str),
6902            Some("db migrate")
6903        );
6904        assert_eq!(nested.get("usage_target").map(String::as_str), Some("v2"));
6905        assert_eq!(
6906            env(&["db"]).get("usage_cmd").map(String::as_str),
6907            Some("db")
6908        );
6909        assert!(!env(&["-v"]).contains_key("usage_cmd"));
6910    }
6911
6912    #[test]
6913    fn as_env_leaves_usage_cmd_to_a_declared_cmd() {
6914        // Declared on the chosen command, and supplied: the value is the arg's.
6915        let spec: Spec = r#"
6916            cmd "run" {
6917                arg "[cmd]"
6918            }
6919            "#
6920        .parse()
6921        .unwrap();
6922        let input = ["test", "run", "build"].map(String::from);
6923        let env = parse(&spec, &input).unwrap().as_env();
6924        assert_eq!(env.get("usage_cmd").map(String::as_str), Some("build"));
6925        // Declared but left out: still the arg's, so unset rather than the path.
6926        let input = ["test", "run"].map(String::from);
6927        assert!(
6928            !parse(&spec, &input)
6929                .unwrap()
6930                .as_env()
6931                .contains_key("usage_cmd")
6932        );
6933
6934        // Declared as a global flag on an ancestor.
6935        let spec: Spec = r#"
6936            flag "--cmd <cmd>" global=#true
6937            cmd "run"
6938            "#
6939        .parse()
6940        .unwrap();
6941        let input = ["test", "run"].map(String::from);
6942        assert!(
6943            !parse(&spec, &input)
6944                .unwrap()
6945                .as_env()
6946                .contains_key("usage_cmd")
6947        );
6948
6949        // Declared inside a clause, and the clause left out.
6950        let spec: Spec = r#"
6951            cmd "run" {
6952                clause "steps" separator=":::" {
6953                    arg "[cmd]"
6954                }
6955            }
6956            "#
6957        .parse()
6958        .unwrap();
6959        let input = ["test", "run"].map(String::from);
6960        assert!(
6961            !parse(&spec, &input)
6962                .unwrap()
6963                .as_env()
6964                .contains_key("usage_cmd")
6965        );
6966    }
6967
6968    #[test]
6969    fn test_arg_env_var() {
6970        let cmd = SpecCommand::builder()
6971            .name("test")
6972            .arg(
6973                SpecArg::builder()
6974                    .name("input")
6975                    .env("TEST_ARG_INPUT")
6976                    .required(true)
6977                    .build(),
6978            )
6979            .build();
6980        let spec = Spec {
6981            name: "test".to_string(),
6982            bin: "test".to_string(),
6983            cmd,
6984            ..Default::default()
6985        };
6986
6987        // Set env var
6988        // FIXME: Audit that the environment access only happens in single-threaded code.
6989        unsafe { std::env::set_var("TEST_ARG_INPUT", "test_file.txt") };
6990
6991        let input = vec!["test".to_string()];
6992        let parsed = parse(&spec, &input).unwrap();
6993
6994        assert_eq!(parsed.args.len(), 1);
6995        let arg = parsed.args.keys().next().unwrap();
6996        assert_eq!(arg.name, "input");
6997        let value = parsed.args.values().next().unwrap();
6998        assert_eq!(value.to_string(), "test_file.txt");
6999
7000        // Clean up
7001        // FIXME: Audit that the environment access only happens in single-threaded code.
7002        unsafe { std::env::remove_var("TEST_ARG_INPUT") };
7003    }
7004
7005    #[test]
7006    fn test_flag_env_var_with_arg() {
7007        let cmd = SpecCommand::builder()
7008            .name("test")
7009            .flag(
7010                SpecFlag::builder()
7011                    .long("output")
7012                    .env("TEST_FLAG_OUTPUT")
7013                    .arg(SpecArg::builder().name("file").build())
7014                    .build(),
7015            )
7016            .build();
7017        let spec = Spec {
7018            name: "test".to_string(),
7019            bin: "test".to_string(),
7020            cmd,
7021            ..Default::default()
7022        };
7023
7024        // Set env var
7025        // FIXME: Audit that the environment access only happens in single-threaded code.
7026        unsafe { std::env::set_var("TEST_FLAG_OUTPUT", "output.txt") };
7027
7028        let input = vec!["test".to_string()];
7029        let parsed = parse(&spec, &input).unwrap();
7030
7031        assert_eq!(parsed.flags.len(), 1);
7032        let flag = parsed.flags.keys().next().unwrap();
7033        assert_eq!(flag.name, "output");
7034        let value = parsed.flags.values().next().unwrap();
7035        assert_eq!(value.to_string(), "output.txt");
7036
7037        // Clean up
7038        // FIXME: Audit that the environment access only happens in single-threaded code.
7039        unsafe { std::env::remove_var("TEST_FLAG_OUTPUT") };
7040    }
7041
7042    #[test]
7043    fn test_flag_env_var_boolean() {
7044        let cmd = SpecCommand::builder()
7045            .name("test")
7046            .flag(
7047                SpecFlag::builder()
7048                    .long("verbose")
7049                    .env("TEST_FLAG_VERBOSE")
7050                    .build(),
7051            )
7052            .build();
7053        let spec = Spec {
7054            name: "test".to_string(),
7055            bin: "test".to_string(),
7056            cmd,
7057            ..Default::default()
7058        };
7059
7060        // Set env var to true
7061        // FIXME: Audit that the environment access only happens in single-threaded code.
7062        unsafe { std::env::set_var("TEST_FLAG_VERBOSE", "true") };
7063
7064        let input = vec!["test".to_string()];
7065        let parsed = parse(&spec, &input).unwrap();
7066
7067        assert_eq!(parsed.flags.len(), 1);
7068        let flag = parsed.flags.keys().next().unwrap();
7069        assert_eq!(flag.name, "verbose");
7070        let value = parsed.flags.values().next().unwrap();
7071        assert_eq!(value.to_string(), "true");
7072
7073        // Clean up
7074        // FIXME: Audit that the environment access only happens in single-threaded code.
7075        unsafe { std::env::remove_var("TEST_FLAG_VERBOSE") };
7076    }
7077
7078    #[test]
7079    fn test_env_var_precedence() {
7080        // CLI args should take precedence over env vars
7081        let cmd = SpecCommand::builder()
7082            .name("test")
7083            .arg(
7084                SpecArg::builder()
7085                    .name("input")
7086                    .env("TEST_PRECEDENCE_INPUT")
7087                    .required(true)
7088                    .build(),
7089            )
7090            .build();
7091        let spec = Spec {
7092            name: "test".to_string(),
7093            bin: "test".to_string(),
7094            cmd,
7095            ..Default::default()
7096        };
7097
7098        // Set env var
7099        // FIXME: Audit that the environment access only happens in single-threaded code.
7100        unsafe { std::env::set_var("TEST_PRECEDENCE_INPUT", "env_file.txt") };
7101
7102        let input = vec!["test".to_string(), "cli_file.txt".to_string()];
7103        let parsed = parse(&spec, &input).unwrap();
7104
7105        assert_eq!(parsed.args.len(), 1);
7106        let value = parsed.args.values().next().unwrap();
7107        // CLI arg should take precedence
7108        assert_eq!(value.to_string(), "cli_file.txt");
7109
7110        // Clean up
7111        // FIXME: Audit that the environment access only happens in single-threaded code.
7112        unsafe { std::env::remove_var("TEST_PRECEDENCE_INPUT") };
7113    }
7114
7115    #[test]
7116    fn test_flag_var_true_with_single_default() {
7117        // When var=true and default="bar", the default should be MultiString(["bar"])
7118        let cmd = SpecCommand::builder()
7119            .name("test")
7120            .flag(
7121                SpecFlag::builder()
7122                    .long("foo")
7123                    .var(true)
7124                    .arg(SpecArg::builder().name("foo").build())
7125                    .default_value("bar")
7126                    .build(),
7127            )
7128            .build();
7129        let spec = Spec {
7130            name: "test".to_string(),
7131            bin: "test".to_string(),
7132            cmd,
7133            ..Default::default()
7134        };
7135
7136        // User doesn't provide the flag
7137        let input = vec!["test".to_string()];
7138        let parsed = parse(&spec, &input).unwrap();
7139
7140        assert_eq!(parsed.flags.len(), 1);
7141        let flag = parsed.flags.keys().next().unwrap();
7142        assert_eq!(flag.name, "foo");
7143        let value = parsed.flags.values().next().unwrap();
7144        // Should be MultiString, not String
7145        match value {
7146            ParseValue::MultiString(v) => {
7147                assert_eq!(v.len(), 1);
7148                assert_eq!(v[0], "bar");
7149            }
7150            _ => panic!("Expected MultiString, got {:?}", value),
7151        }
7152    }
7153
7154    #[test]
7155    fn test_flag_var_true_with_multiple_defaults() {
7156        // When var=true and multiple defaults, should return MultiString(["xyz", "bar"])
7157        let cmd = SpecCommand::builder()
7158            .name("test")
7159            .flag(
7160                SpecFlag::builder()
7161                    .long("foo")
7162                    .var(true)
7163                    .arg(SpecArg::builder().name("foo").build())
7164                    .default_values(["xyz", "bar"])
7165                    .build(),
7166            )
7167            .build();
7168        let spec = Spec {
7169            name: "test".to_string(),
7170            bin: "test".to_string(),
7171            cmd,
7172            ..Default::default()
7173        };
7174
7175        // User doesn't provide the flag
7176        let input = vec!["test".to_string()];
7177        let parsed = parse(&spec, &input).unwrap();
7178
7179        assert_eq!(parsed.flags.len(), 1);
7180        let value = parsed.flags.values().next().unwrap();
7181        // Should be MultiString with both values
7182        match value {
7183            ParseValue::MultiString(v) => {
7184                assert_eq!(v.len(), 2);
7185                assert_eq!(v[0], "xyz");
7186                assert_eq!(v[1], "bar");
7187            }
7188            _ => panic!("Expected MultiString, got {:?}", value),
7189        }
7190    }
7191
7192    #[test]
7193    fn test_flag_var_false_with_default_remains_string() {
7194        // When var=false (default), the default should still be String("bar")
7195        let cmd = SpecCommand::builder()
7196            .name("test")
7197            .flag(
7198                SpecFlag::builder()
7199                    .long("foo")
7200                    .var(false) // Default behavior
7201                    .arg(SpecArg::builder().name("foo").build())
7202                    .default_value("bar")
7203                    .build(),
7204            )
7205            .build();
7206        let spec = Spec {
7207            name: "test".to_string(),
7208            bin: "test".to_string(),
7209            cmd,
7210            ..Default::default()
7211        };
7212
7213        // User doesn't provide the flag
7214        let input = vec!["test".to_string()];
7215        let parsed = parse(&spec, &input).unwrap();
7216
7217        assert_eq!(parsed.flags.len(), 1);
7218        let value = parsed.flags.values().next().unwrap();
7219        // Should be String, not MultiString
7220        match value {
7221            ParseValue::String(s) => {
7222                assert_eq!(s, "bar");
7223            }
7224            _ => panic!("Expected String, got {:?}", value),
7225        }
7226    }
7227
7228    #[test]
7229    fn test_arg_var_true_with_single_default() {
7230        // When arg has var=true and default="bar", the default should be MultiString(["bar"])
7231        let cmd = SpecCommand::builder()
7232            .name("test")
7233            .arg(
7234                SpecArg::builder()
7235                    .name("files")
7236                    .var(true)
7237                    .default_value("default.txt")
7238                    .required(false)
7239                    .build(),
7240            )
7241            .build();
7242        let spec = Spec {
7243            name: "test".to_string(),
7244            bin: "test".to_string(),
7245            cmd,
7246            ..Default::default()
7247        };
7248
7249        // User doesn't provide the arg
7250        let input = vec!["test".to_string()];
7251        let parsed = parse(&spec, &input).unwrap();
7252
7253        assert_eq!(parsed.args.len(), 1);
7254        let value = parsed.args.values().next().unwrap();
7255        // Should be MultiString, not String
7256        match value {
7257            ParseValue::MultiString(v) => {
7258                assert_eq!(v.len(), 1);
7259                assert_eq!(v[0], "default.txt");
7260            }
7261            _ => panic!("Expected MultiString, got {:?}", value),
7262        }
7263    }
7264
7265    #[test]
7266    fn test_arg_var_true_with_multiple_defaults() {
7267        // When arg has var=true and multiple defaults
7268        let cmd = SpecCommand::builder()
7269            .name("test")
7270            .arg(
7271                SpecArg::builder()
7272                    .name("files")
7273                    .var(true)
7274                    .default_values(["file1.txt", "file2.txt"])
7275                    .required(false)
7276                    .build(),
7277            )
7278            .build();
7279        let spec = Spec {
7280            name: "test".to_string(),
7281            bin: "test".to_string(),
7282            cmd,
7283            ..Default::default()
7284        };
7285
7286        // User doesn't provide the arg
7287        let input = vec!["test".to_string()];
7288        let parsed = parse(&spec, &input).unwrap();
7289
7290        assert_eq!(parsed.args.len(), 1);
7291        let value = parsed.args.values().next().unwrap();
7292        // Should be MultiString with both values
7293        match value {
7294            ParseValue::MultiString(v) => {
7295                assert_eq!(v.len(), 2);
7296                assert_eq!(v[0], "file1.txt");
7297                assert_eq!(v[1], "file2.txt");
7298            }
7299            _ => panic!("Expected MultiString, got {:?}", value),
7300        }
7301    }
7302
7303    #[test]
7304    fn test_arg_var_false_with_default_remains_string() {
7305        // When arg has var=false (default), the default should still be String
7306        let cmd = SpecCommand::builder()
7307            .name("test")
7308            .arg(
7309                SpecArg::builder()
7310                    .name("file")
7311                    .var(false)
7312                    .default_value("default.txt")
7313                    .required(false)
7314                    .build(),
7315            )
7316            .build();
7317        let spec = Spec {
7318            name: "test".to_string(),
7319            bin: "test".to_string(),
7320            cmd,
7321            ..Default::default()
7322        };
7323
7324        // User doesn't provide the arg
7325        let input = vec!["test".to_string()];
7326        let parsed = parse(&spec, &input).unwrap();
7327
7328        assert_eq!(parsed.args.len(), 1);
7329        let value = parsed.args.values().next().unwrap();
7330        // Should be String, not MultiString
7331        match value {
7332            ParseValue::String(s) => {
7333                assert_eq!(s, "default.txt");
7334            }
7335            _ => panic!("Expected String, got {:?}", value),
7336        }
7337    }
7338
7339    #[test]
7340    fn test_scalar_defaults_validate_only_first_default_choice() {
7341        let specs = [
7342            spec_with_arg(
7343                SpecArg::builder()
7344                    .name("env")
7345                    .var(false)
7346                    .default_values(["dev", "prod"])
7347                    .choices(["dev"])
7348                    .required(false)
7349                    .build(),
7350            ),
7351            spec_with_flag(
7352                SpecFlag::builder()
7353                    .long("env")
7354                    .arg(
7355                        SpecArg::builder()
7356                            .name("env")
7357                            .default_values(["dev", "prod"])
7358                            .choices(["dev"])
7359                            .build(),
7360                    )
7361                    .build(),
7362            ),
7363        ];
7364
7365        for spec in specs {
7366            let parsed = parse(&spec, &input(&["test"])).unwrap();
7367            assert_eq!(first_string_value(&parsed), "dev");
7368        }
7369    }
7370
7371    #[test]
7372    fn a_delimiter_turns_one_word_into_several_values() {
7373        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--tags <tag>\" var=#true delimiter=\",\"\narg \"[files]...\" var=#true delimiter=\":\"\n"
7374            .parse()
7375            .unwrap();
7376
7377        let parsed = parse(&spec, &input(&["ex", "--tags", "a,b,c", "x:y"])).unwrap();
7378        let multi = |value: &ParseValue| match value {
7379            ParseValue::MultiString(values) => values.clone(),
7380            other => panic!("expected several values, got {other:?}"),
7381        };
7382        let tags = parsed
7383            .flags
7384            .iter()
7385            .find(|(f, _)| f.name == "tags")
7386            .map(|(_, v)| v)
7387            .unwrap();
7388        assert_eq!(multi(tags), vec!["a", "b", "c"]);
7389        assert_eq!(multi(parsed.args.values().next().unwrap()), vec!["x", "y"]);
7390    }
7391
7392    #[test]
7393    fn a_positional_splits_before_its_choices_are_asked() {
7394        // The flag path did this and the positional path did not, so a word whose parts
7395        // were all choices was rejected as one value, and a bad half was reported as the
7396        // whole word.
7397        let spec: Spec = "name \"ex\"\nbin \"ex\"\narg \"[paths]...\" var=#true delimiter=\":\" {\n  choices \"src\" \"docs\"\n}\n"
7398            .parse()
7399            .unwrap();
7400
7401        parse(&spec, &input(&["ex", "src:docs"])).expect("both halves are choices");
7402
7403        let err = parse(&spec, &input(&["ex", "src:nowhere"])).unwrap_err();
7404        let message = err.to_string();
7405        assert!(message.contains("nowhere"), "{message}");
7406        assert!(
7407            !message.contains("src:nowhere"),
7408            "the bad half should be named, not the whole word: {message}"
7409        );
7410    }
7411
7412    #[test]
7413    fn a_split_value_is_counted_and_judged_as_values() {
7414        // Split during the parse rather than after it, so everything downstream sees the
7415        // values the user meant rather than the words they typed: `choices` judges each
7416        // one, and the bounds count them.
7417        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--env <e>\" var=#true delimiter=\",\" var_max=2 {\n  choices \"dev\" \"prod\"\n}\n"
7418            .parse()
7419            .unwrap();
7420
7421        parse(&spec, &input(&["ex", "--env", "dev,prod"])).expect("two values, both allowed");
7422        let err = parse(&spec, &input(&["ex", "--env", "dev,staging"])).unwrap_err();
7423        assert!(err.to_string().contains("staging"), "{err}");
7424        assert!(
7425            parse(&spec, &input(&["ex", "--env", "dev,prod,dev"])).is_err(),
7426            "three values should breach var_max=2"
7427        );
7428    }
7429
7430    #[test]
7431    fn a_split_bound_counts_one_occurrence_at_a_time() {
7432        // The bound on a variadic flag *argument* is what one occurrence may take. Without a
7433        // delimiter the collection simply stops at it, so it could never be exceeded; a word
7434        // carrying several values can carry an occurrence past it in one step, and that is
7435        // the only way this bound is ever breached.
7436        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--include <pattern>...\" delimiter=\",\" {\n  arg \"<pattern>...\" var=#true var_max=2\n}\n"
7437            .parse()
7438            .unwrap();
7439
7440        parse(&spec, &input(&["ex", "--include", "a,b"])).expect("exactly the bound is fine");
7441        assert!(
7442            parse(&spec, &input(&["ex", "--include", "a,b,c"])).is_err(),
7443            "three values out of one word is still three values"
7444        );
7445        // The rule the corpus documents for plain words, on split ones: a second occurrence
7446        // starts counting again rather than adding to the first.
7447        parse(
7448            &spec,
7449            &input(&["ex", "--include", "a,b", "--include", "c,d"]),
7450        )
7451        .expect("two per occurrence, twice, is within the bound");
7452    }
7453
7454    #[test]
7455    fn a_nested_minimum_is_checked_once_per_flag_occurrence() {
7456        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--pair <value>...\" {\n  arg \"<value>...\" var=#true var_min=2 var_max=2\n}\n"
7457            .parse()
7458            .unwrap();
7459
7460        parse(
7461            &spec,
7462            &input(&["ex", "--pair", "a", "b", "--pair", "c", "d"]),
7463        )
7464        .expect("each occurrence satisfies the bound independently");
7465
7466        let error = parse(&spec, &input(&["ex", "--pair", "a", "--pair", "b", "c"])).unwrap_err();
7467        assert!(
7468            error
7469                .to_string()
7470                .contains("requires at least 2 value(s), got 1"),
7471            "{error:?}"
7472        );
7473    }
7474
7475    #[test]
7476    fn an_exclusive_flag_has_to_be_alone() {
7477        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--dump\" exclusive=#true\nflag \"--verbose\"\narg \"[target]\"\n"
7478            .parse()
7479            .unwrap();
7480
7481        parse(&spec, &input(&["ex", "--dump"])).expect("alone is the point");
7482
7483        // Any other flag.
7484        let err = parse(&spec, &input(&["ex", "--dump", "--verbose"])).unwrap_err();
7485        assert!(err.to_string().contains("on its own"), "{err}");
7486
7487        // And a positional, which is what makes this more than a conflict with every
7488        // other flag.
7489        let err = parse(&spec, &input(&["ex", "--dump", "t"])).unwrap_err();
7490        assert!(err.to_string().contains("on its own"), "{err}");
7491
7492        // Not given, so it imposes nothing.
7493        parse(&spec, &input(&["ex", "--verbose", "t"])).expect("without it, nothing changes");
7494    }
7495
7496    #[test]
7497    fn an_exclusive_flag_conflicts_with_clause_arguments() {
7498        let spec: Spec = r#"name "ex"
7499bin "ex"
7500flag "--dump" exclusive=#true
7501clause "tasks" separator=":::" {
7502  arg "<task>"
7503}
7504"#
7505        .parse()
7506        .unwrap();
7507
7508        let err = parse(&spec, &input(&["ex", "--dump", "lint"])).unwrap_err();
7509        assert!(err.to_string().contains("on its own"), "{err}");
7510    }
7511
7512    #[test]
7513    fn a_partial_parse_reports_the_next_implicit_clause_argument() {
7514        let spec: Spec = r#"name "ex"
7515bin "ex"
7516clause "tools" {
7517  arg "<tool@version>"
7518}
7519"#
7520        .parse()
7521        .unwrap();
7522
7523        let parsed = parse_partial(&spec, &input(&["ex"])).unwrap();
7524
7525        assert_eq!(
7526            parsed.next_arg.as_ref().map(|arg| arg.name.as_str()),
7527            Some("tool@version")
7528        );
7529    }
7530
7531    #[test]
7532    fn an_exclusive_flag_is_not_disturbed_by_a_default() {
7533        // Only what was supplied counts, as `conflicts` reads it. A default counting as
7534        // company would make an exclusive flag unusable on any command that has one.
7535        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--dump\" exclusive=#true\nflag \"--jobs <n>\" default=\"4\"\n"
7536            .parse()
7537            .unwrap();
7538
7539        parse(&spec, &input(&["ex", "--dump"])).expect("a default is nobody saying anything");
7540        assert!(parse(&spec, &input(&["ex", "--dump", "--jobs", "8"])).is_err());
7541    }
7542
7543    #[test]
7544    fn an_exclusive_flag_bypasses_required_siblings() {
7545        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--dump\" exclusive=#true\nflag \"--out <path>\" required=#true\narg \"<target>\"\n"
7546            .parse()
7547            .unwrap();
7548
7549        parse(&spec, &input(&["ex", "--dump"]))
7550            .expect("exclusive is the command's requiredness escape");
7551        assert!(
7552            parse(
7553                &spec,
7554                &input(&["ex", "--dump", "--out", "somewhere", "target"])
7555            )
7556            .is_err()
7557        );
7558    }
7559
7560    #[test]
7561    fn an_environment_value_counts_for_an_exclusive_flag() {
7562        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--dump\" exclusive=#true\nflag \"--out <path>\" env=\"EX_OUT\"\n"
7563            .parse()
7564            .unwrap();
7565
7566        assert!(parse_with_env(&spec, &["ex", "--dump"], &[("EX_OUT", "somewhere")]).is_err());
7567        parse_with_env(&spec, &["ex", "--dump"], &[]).expect("without the value it is alone");
7568    }
7569
7570    #[test]
7571    fn a_selected_subcommand_counts_for_an_ancestor_exclusive_flag() {
7572        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--version\" global=#true exclusive=#true\ncmd \"run\"\n"
7573            .parse()
7574            .unwrap();
7575
7576        parse(&spec, &input(&["ex", "--version"])).expect("alone is allowed");
7577        assert!(parse(&spec, &input(&["ex", "--version", "run"])).is_err());
7578    }
7579
7580    #[test]
7581    fn a_child_exclusive_flag_is_not_mistaken_for_a_same_named_parent_flag() {
7582        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--clean\" exclusive=#true\ncmd \"run\" {\n  flag \"--clean\" exclusive=#true\n}\n"
7583            .parse()
7584            .unwrap();
7585
7586        parse(&spec, &input(&["ex", "run", "--clean"]))
7587            .expect("the child flag is alone within the child command");
7588        assert!(
7589            parse(&spec, &input(&["ex", "--clean", "run"])).is_err(),
7590            "the parent flag still conflicts with selecting the child"
7591        );
7592    }
7593
7594    #[test]
7595    fn a_child_local_exclusive_redeclaration_belongs_to_the_child() {
7596        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--clean\" global=#true exclusive=#true\ncmd \"run\" {\n  flag \"--clean\" exclusive=#true\n}\n"
7597            .parse()
7598            .unwrap();
7599
7600        parse(&spec, &input(&["ex", "run", "--clean"]))
7601            .expect("the child-local exclusive flag is alone inside the child command");
7602        assert!(
7603            parse(&spec, &input(&["ex", "--clean", "run"])).is_err(),
7604            "the ancestor spelling still conflicts with selecting the child"
7605        );
7606    }
7607
7608    #[test]
7609    fn a_same_named_parent_flag_is_company_for_a_child_exclusive_flag() {
7610        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--clean\" global=#true\ncmd \"run\" {\n  flag \"--clean\" global=#true exclusive=#true\n}\n"
7611            .parse()
7612            .unwrap();
7613
7614        parse(&spec, &input(&["ex", "run", "--clean"])).expect("the child exclusive flag is alone");
7615        assert!(
7616            parse(&spec, &input(&["ex", "--clean", "run", "--clean"])).is_err(),
7617            "the distinct parent declaration is still company despite sharing a name"
7618        );
7619    }
7620
7621    #[test]
7622    fn a_local_child_redeclaration_keeps_its_exclusivity_when_merged() {
7623        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--clean\" global=#true\ncmd \"run\" {\n  flag \"--clean\" exclusive=#true\n  flag \"--verbose\"\n}\n"
7624            .parse()
7625            .unwrap();
7626
7627        parse(&spec, &input(&["ex", "run", "--clean"]))
7628            .expect("the child exclusive flag is valid alone");
7629        assert!(
7630            parse(&spec, &input(&["ex", "run", "--clean", "--verbose"])).is_err(),
7631            "merging with the inherited global must not discard child exclusivity"
7632        );
7633    }
7634
7635    #[test]
7636    fn an_orphan_parent_alias_does_not_disown_a_child_local_exclusive_flag() {
7637        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"-c --clean\" global=#true exclusive=#true\ncmd \"run\" {\n  flag \"--clean\" exclusive=#true\n}\n"
7638            .parse()
7639            .unwrap();
7640
7641        parse(&spec, &input(&["ex", "run", "--clean"]))
7642            .expect("the typed long form belongs to the child declaration");
7643        assert!(
7644            parse(&spec, &input(&["ex", "run", "-c"])).is_err(),
7645            "the inherited short form still belongs to the ancestor"
7646        );
7647        assert!(
7648            parse(&spec, &input(&["ex", "run", "-c", "--clean"])).is_err(),
7649            "a child spelling cannot mask the ancestor-exclusive occurrence on the same merged flag"
7650        );
7651    }
7652
7653    #[test]
7654    fn an_inherited_alias_keeps_its_ancestor_exclusivity() {
7655        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"-c --clean\" global=#true exclusive=#true\ncmd \"run\" {\n  flag \"--clean\" global=#true\n}\n"
7656            .parse()
7657            .unwrap();
7658
7659        parse(&spec, &input(&["ex", "run", "--clean"]))
7660            .expect("the child's spelling does not activate the orphan ancestor alias");
7661        assert!(
7662            parse(&spec, &input(&["ex", "run", "-c"])).is_err(),
7663            "the inherited short alias still belongs to the ancestor exclusive flag"
7664        );
7665    }
7666
7667    #[test]
7668    fn an_inherited_negated_alias_keeps_its_ancestor_exclusivity() {
7669        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"-c --clean\" negate=\"--no-clean\" global=#true exclusive=#true\ncmd \"run\" {\n  flag \"-c --clean\" global=#true\n}\n"
7670            .parse()
7671            .unwrap();
7672
7673        assert!(
7674            parse(&spec, &input(&["ex", "run", "--no-clean"])).is_err(),
7675            "the inherited negated alias still belongs to the ancestor exclusive flag"
7676        );
7677    }
7678
7679    #[test]
7680    fn a_colliding_alias_does_not_disown_the_child_from_the_rest() {
7681        // The child re-declares the inherited `--clean` as exclusive and gives it a `-c` that
7682        // an unrelated inherited global already owns. That collision is resolved in the other
7683        // global's favor, so the child's `-c` resolves elsewhere — but the child plainly owns
7684        // the `--clean` it declared, and its exclusivity holds.
7685        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--clean\" global=#true\nflag \"-c --config <f>\" global=#true\ncmd \"run\" {\n  flag \"-c --clean\" exclusive=#true\n  flag \"--verbose\"\n}\n"
7686            .parse()
7687            .unwrap();
7688
7689        parse(&spec, &input(&["ex", "run", "--clean"])).expect("alone is allowed");
7690        assert!(
7691            parse(&spec, &input(&["ex", "run", "--clean", "--verbose"])).is_err(),
7692            "one unrelated alias collision cannot disown the child from its own flag"
7693        );
7694    }
7695
7696    #[test]
7697    fn a_local_child_declaration_is_not_in_scope_before_the_subcommand() {
7698        // A child's *local* re-declaration describes the flag at the child. Typed ahead of the
7699        // subcommand word the flag can only be the ancestor's, because that is the only one in
7700        // scope there — so the ancestor's exclusivity is the one that answers, whichever way it
7701        // is set. The pair below differ in nothing else, which is what makes this one rule
7702        // rather than two behaviors.
7703        let quiet: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--clean\" global=#true\ncmd \"run\" {\n  flag \"--clean\" exclusive=#true\n  flag \"--verbose\"\n}\n"
7704            .parse()
7705            .unwrap();
7706        parse(&quiet, &input(&["ex", "--clean", "run", "--verbose"]))
7707            .expect("the ancestor owns this occurrence, and it is not exclusive");
7708        assert!(
7709            parse(&quiet, &input(&["ex", "run", "--clean", "--verbose"])).is_err(),
7710            "after the subcommand word the child's declaration is in scope, and it is exclusive"
7711        );
7712
7713        let loud: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--clean\" global=#true exclusive=#true\ncmd \"run\" {\n  flag \"--clean\" exclusive=#true\n}\n"
7714            .parse()
7715            .unwrap();
7716        assert!(
7717            parse(&loud, &input(&["ex", "--clean", "run"])).is_err(),
7718            "the same rule, with an exclusive ancestor: selecting the child is company for it"
7719        );
7720    }
7721
7722    #[test]
7723    fn an_orphan_ancestor_alias_keeps_its_exclusivity_past_a_plain_child_redeclaration() {
7724        // The mirror of `a_local_child_redeclaration_keeps_its_exclusivity_when_merged`: the
7725        // child owns `--clean` and says nothing about exclusivity, but `-c` is a spelling only
7726        // the ancestor ever declared, so the ancestor's answer still governs it.
7727        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"-c --clean\" global=#true exclusive=#true\ncmd \"run\" {\n  flag \"--clean\"\n  flag \"--verbose\"\n}\n"
7728            .parse()
7729            .unwrap();
7730
7731        assert!(
7732            parse(&spec, &input(&["ex", "run", "-c"])).is_err(),
7733            "the orphan ancestor alias is still the ancestor's exclusive flag"
7734        );
7735        parse(&spec, &input(&["ex", "run", "--clean", "--verbose"]))
7736            .expect("the child's own spelling drops the exclusivity the child did not restate");
7737    }
7738
7739    #[test]
7740    fn a_child_spelling_carries_its_exclusivity_even_beside_an_ancestor_spelling() {
7741        // Both spellings of one merged flag, typed together. The child's `--clean` is exclusive
7742        // whatever else was typed alongside it, so `--verbose` is company; attributing the whole
7743        // occurrence to the ancestor because `-c` appeared in it lost that.
7744        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"-c --clean\" global=#true\ncmd \"run\" {\n  flag \"--clean\" exclusive=#true\n  flag \"--verbose\"\n}\n"
7745            .parse()
7746            .unwrap();
7747
7748        assert!(
7749            parse(&spec, &input(&["ex", "run", "-c", "--clean", "--verbose"])).is_err(),
7750            "the child spelling is exclusive whatever it was typed beside"
7751        );
7752        parse(&spec, &input(&["ex", "run", "-c", "--verbose"]))
7753            .expect("the ancestor's own spelling was never exclusive");
7754    }
7755
7756    #[test]
7757    fn an_environment_value_takes_the_exclusivity_of_the_declaration_in_scope() {
7758        // An environment value has no spelling to attribute, so the declaration the selected
7759        // command has in scope answers — in both directions. Comparing whole alias sets asked
7760        // the ancestor instead, because the merged flag also carries its orphan `-c`.
7761        let added: Spec = "name \"ex\"\nbin \"ex\"\nflag \"-c --clean\" global=#true env=\"EX_CLEAN\"\ncmd \"run\" {\n  flag \"--clean\" exclusive=#true\n  flag \"--verbose\"\n}\n"
7762            .parse()
7763            .unwrap();
7764
7765        assert!(
7766            parse_with_env(&added, &["ex", "run", "--verbose"], &[("EX_CLEAN", "1")]).is_err(),
7767            "the child added exclusivity the environment value has to honor"
7768        );
7769
7770        let dropped: Spec = "name \"ex\"\nbin \"ex\"\nflag \"-c --clean\" global=#true exclusive=#true env=\"EX_CLEAN\"\ncmd \"run\" {\n  flag \"--clean\"\n  flag \"--verbose\"\n}\n"
7771            .parse()
7772            .unwrap();
7773
7774        parse_with_env(&dropped, &["ex", "run", "--verbose"], &[("EX_CLEAN", "1")])
7775            .expect("the child dropped the exclusivity, and the environment value follows it");
7776    }
7777
7778    #[test]
7779    fn a_merged_child_exclusive_flag_still_escapes_requiredness() {
7780        // Exclusivity suppresses missing-value checks, and that has to survive the merge for
7781        // the same reason the companion check does.
7782        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--clean\" global=#true\ncmd \"run\" {\n  flag \"--clean\" exclusive=#true\n  flag \"--out <path>\" required=#true\n}\n"
7783            .parse()
7784            .unwrap();
7785
7786        parse(&spec, &input(&["ex", "run", "--clean"]))
7787            .expect("a merged child exclusive flag is still the command's requiredness escape");
7788    }
7789
7790    #[test]
7791    fn a_group_allows_one_member_and_refuses_two() {
7792        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--file <f>\"\nflag \"--url <u>\"\nflag \"--stdin\"\ngroup \"input\" \"--file\" \"--url\" \"--stdin\"\n"
7793            .parse()
7794            .unwrap();
7795
7796        // One is fine, and so is none: a plain group says "at most one".
7797        parse(&spec, &input(&["ex", "--file", "a.txt"])).expect("one member is fine");
7798        parse(&spec, &input(&["ex"])).expect("a group that is not required asks for nothing");
7799
7800        let err = parse(&spec, &input(&["ex", "--file", "a.txt", "--stdin"])).unwrap_err();
7801        assert!(err.to_string().contains("group input"), "{err}");
7802    }
7803
7804    #[test]
7805    fn positional_selectors_work_in_conflicts_and_groups() {
7806        let conflicts: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--from-file <path>\" conflicts=\"value\"\narg \"[value]\"\n"
7807            .parse()
7808            .unwrap();
7809        parse(&conflicts, &input(&["ex", "--from-file", "vars.env"]))
7810            .expect("the flag alone is valid");
7811        parse(&conflicts, &input(&["ex", "literal"])).expect("the positional alone is valid");
7812        assert!(
7813            parse(
7814                &conflicts,
7815                &input(&["ex", "--from-file", "vars.env", "literal"])
7816            )
7817            .is_err()
7818        );
7819
7820        let positional_source: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--from-file <path>\"\narg \"[value]\" conflicts=\"--from-file\"\n"
7821            .parse()
7822            .unwrap();
7823        assert!(
7824            parse(
7825                &positional_source,
7826                &input(&["ex", "--from-file", "vars.env", "literal"])
7827            )
7828            .is_err()
7829        );
7830
7831        let group: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--file <path>\"\narg \"[target]\"\ngroup \"input\" \"--file\" \"target\" required=#true\n"
7832            .parse()
7833            .unwrap();
7834        assert!(parse(&group, &input(&["ex"])).is_err());
7835        parse(&group, &input(&["ex", "target-name"]))
7836            .expect("a positional satisfies a required group");
7837        assert!(
7838            parse(
7839                &group,
7840                &input(&["ex", "--file", "input.txt", "target-name"])
7841            )
7842            .is_err()
7843        );
7844    }
7845
7846    #[test]
7847    fn a_required_group_needs_one_of_its_members() {
7848        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--file <f>\"\nflag \"--url <u>\"\ngroup \"input\" \"--file\" \"--url\" required=#true\n"
7849            .parse()
7850            .unwrap();
7851
7852        let err = parse(&spec, &input(&["ex"])).unwrap_err();
7853        // The members, because that is what a user has to type; the name, because a
7854        // command with several groups would otherwise report the same sentence twice.
7855        assert!(err.to_string().contains("--file, --url"), "{err}");
7856        assert!(err.to_string().contains("input"), "{err}");
7857
7858        parse(&spec, &input(&["ex", "--url", "u"])).expect("one member satisfies it");
7859    }
7860
7861    #[test]
7862    fn a_multiple_group_only_polices_requiredness() {
7863        // `multiple` with `required` is "at least one of these", so two is fine and
7864        // none is not.
7865        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--a\"\nflag \"--b\"\ngroup \"any\" \"--a\" \"--b\" required=#true multiple=#true\n"
7866            .parse()
7867            .unwrap();
7868
7869        parse(&spec, &input(&["ex", "--a", "--b"])).expect("multiple allows both");
7870        assert!(parse(&spec, &input(&["ex"])).is_err());
7871    }
7872
7873    #[test]
7874    fn a_group_reads_a_default_for_requiredness_and_not_for_exclusivity() {
7875        // The two halves of a group are two kinds of rule, and they read a default
7876        // differently on purpose. Requiredness asks whether a member has a value, and a
7877        // default is a value — the rule `requires` follows. Exclusivity asks what the
7878        // user supplied, because a defaulted member counted as supplied would collide
7879        // with the sibling they actually typed and refuse a correct command line.
7880        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--file <f>\" default=\"a.txt\"\nflag \"--url <u>\"\ngroup \"input\" \"--file\" \"--url\" required=#true\n"
7881            .parse()
7882            .unwrap();
7883
7884        parse(&spec, &input(&["ex"])).expect("the default fills the group");
7885        parse(&spec, &input(&["ex", "--url", "u"]))
7886            .expect("the default must not conflict with the flag the user typed");
7887    }
7888
7889    #[test]
7890    fn a_group_naming_two_spellings_of_one_flag_is_not_a_conflict() {
7891        // `-f` and `--file` are one flag. Counted by selector, giving it once would
7892        // report it as conflicting with itself.
7893        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"-f --file <f>\"\nflag \"--url <u>\"\ngroup \"input\" \"-f\" \"--file\" \"--url\"\n"
7894            .parse()
7895            .unwrap();
7896
7897        parse(&spec, &input(&["ex", "--file", "a.txt"])).expect("one flag is one member");
7898        parse(&spec, &input(&["ex", "-f", "a.txt"])).expect("either spelling, still one member");
7899
7900        // A genuine collision is still one.
7901        let err = parse(&spec, &input(&["ex", "--file", "a.txt", "--url", "u"])).unwrap_err();
7902        assert!(err.to_string().contains("group input"), "{err}");
7903    }
7904
7905    #[test]
7906    fn a_group_reads_the_environment_as_given() {
7907        // The environment does count, which is the same asymmetry `conflicts` has: an
7908        // env var is somebody saying something, a default is nobody saying anything.
7909        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--file <f>\" env=\"EX_FILE\"\nflag \"--url <u>\"\ngroup \"input\" \"--file\" \"--url\" required=#true\n"
7910            .parse()
7911            .unwrap();
7912
7913        parse_with_env(&spec, &["ex"], &[("EX_FILE", "a.txt")]).expect("the environment fills it");
7914    }
7915
7916    #[test]
7917    fn a_requirement_names_the_flag_that_is_missing() {
7918        // Reported as the missing flag rather than as something wrong with `--out`,
7919        // which is what clap says for an unmet `requires` and what a user can act on.
7920        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--out <p>\" requires=\"--format\"\nflag \"--format <f>\"\n"
7921            .parse()
7922            .unwrap();
7923
7924        let err = parse(&spec, &input(&["ex", "--out", "a.txt"])).unwrap_err();
7925        assert!(
7926            err.to_string().contains("format"),
7927            "the missing flag should be named: {err}"
7928        );
7929
7930        // Satisfied, in either order.
7931        for words in [
7932            &["ex", "--out", "a.txt", "--format", "json"][..],
7933            &["ex", "--format", "json", "--out", "a.txt"][..],
7934        ] {
7935            parse(&spec, &input(words)).unwrap_or_else(|e| panic!("{words:?}: {e}"));
7936        }
7937
7938        // Nothing happens when the flag that imposes the rule is absent: a requirement
7939        // is a consequence of using the flag, not a rule about the command line.
7940        parse(&spec, &input(&["ex"])).expect("a bare invocation requires nothing");
7941    }
7942
7943    #[test]
7944    fn a_value_activates_only_its_conditional_requirement() {
7945        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--config <file>\" {\n  requires_if \"special.toml\" \"--key\"\n  requires_if \"remote.toml\" \"--token\"\n}\nflag \"--key <key>\"\nflag \"--token <token>\"\n"
7946            .parse()
7947            .unwrap();
7948
7949        parse(&spec, &input(&["ex", "--config", "ordinary.toml"]))
7950            .expect("an unrelated value requires nothing");
7951
7952        let key = parse(&spec, &input(&["ex", "--config", "special.toml"])).unwrap_err();
7953        assert!(key.to_string().contains("key"), "{key}");
7954        parse(
7955            &spec,
7956            &input(&["ex", "--config", "special.toml", "--key", "secret"]),
7957        )
7958        .expect("the matching requirement is satisfied");
7959
7960        let token = parse(&spec, &input(&["ex", "--config", "remote.toml"])).unwrap_err();
7961        assert!(token.to_string().contains("token"), "{token}");
7962    }
7963
7964    #[test]
7965    fn conditional_requirements_read_explicit_env_but_not_defaults() {
7966        let from_env: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--config <file>\" env=\"EX_CONFIG\" {\n  requires_if \"special.toml\" \"--key\"\n}\nflag \"--key <key>\"\n"
7967            .parse()
7968            .unwrap();
7969        let err = parse_with_env(&from_env, &["ex"], &[("EX_CONFIG", "special.toml")]).unwrap_err();
7970        assert!(err.to_string().contains("key"), "{err}");
7971
7972        let from_default: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--config <file>\" default=\"special.toml\" {\n  requires_if \"special.toml\" \"--key\"\n}\nflag \"--key <key>\"\n"
7973            .parse()
7974            .unwrap();
7975        parse(&from_default, &input(&["ex"]))
7976            .expect("a default is not an explicit conditional value");
7977    }
7978
7979    #[test]
7980    fn command_line_values_override_env_for_conditional_requirements() {
7981        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--config <file>\" env=\"EX_CONFIG\" {\n  requires_if \"special.toml\" \"--key\"\n}\nflag \"--key <key>\"\n"
7982            .parse()
7983            .unwrap();
7984
7985        parse_with_env(
7986            &spec,
7987            &["ex", "--config", "ordinary.toml"],
7988            &[("EX_CONFIG", "special.toml")],
7989        )
7990        .expect("the command-line value takes precedence over the environment");
7991    }
7992
7993    #[test]
7994    fn conditional_requirements_normalize_boolean_env_values() {
7995        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--feature\" env=\"EX_FEATURE\" {\n  requires_if \"true\" \"--key\"\n}\nflag \"--key <key>\"\n"
7996            .parse()
7997            .unwrap();
7998
7999        for value in ["1", "true", "True", "TRUE"] {
8000            let err = parse_with_env(&spec, &["ex"], &[("EX_FEATURE", value)]).unwrap_err();
8001            assert!(err.to_string().contains("key"), "{value}: {err}");
8002        }
8003        parse_with_env(&spec, &["ex"], &[("EX_FEATURE", "false")])
8004            .expect("a false environment value does not activate a true condition");
8005    }
8006
8007    #[test]
8008    fn a_default_satisfies_a_requirement() {
8009        // The flag it names has a value, which is the question a requirement asks. Read
8010        // any other way, `--format` would be missing here and present ten lines further
8011        // down, where plain required-ness reads the same default as filling it.
8012        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--out <p>\" requires=\"--format\"\nflag \"--format <f>\" default=\"json\"\n"
8013            .parse()
8014            .unwrap();
8015
8016        parse(&spec, &input(&["ex", "--out", "a.txt"]))
8017            .expect("a defaulted flag is not a missing one");
8018    }
8019
8020    #[test]
8021    fn a_present_flag_binds_a_conditional_default() {
8022        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--bin-names\" {\n  default_if \"--json\" \"true\"\n}\nflag \"--json\"\n"
8023            .parse()
8024            .unwrap();
8025
8026        let with = parse(&spec, &input(&["ex", "--json"])).unwrap();
8027        assert_eq!(
8028            with.as_env().get("usage_bin_names").map(String::as_str),
8029            Some("true")
8030        );
8031
8032        let without = parse(&spec, &input(&["ex"])).unwrap();
8033        assert!(
8034            !without.as_env().contains_key("usage_bin_names"),
8035            "IsPresent does nothing when the selector is absent"
8036        );
8037    }
8038
8039    #[test]
8040    fn an_equals_condition_binds_a_conditional_default() {
8041        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--style <s>\" {\n  default_if \"--output\" \"json\" \"pretty\"\n}\nflag \"--output <fmt>\"\n"
8042            .parse()
8043            .unwrap();
8044
8045        let json = parse(&spec, &input(&["ex", "--output", "json"])).unwrap();
8046        assert_eq!(
8047            json.as_env().get("usage_style").map(String::as_str),
8048            Some("pretty")
8049        );
8050        let yaml = parse(&spec, &input(&["ex", "--output", "yaml"])).unwrap();
8051        assert!(!yaml.as_env().contains_key("usage_style"));
8052    }
8053
8054    #[test]
8055    fn an_equals_condition_reads_a_negated_flag() {
8056        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--pretty\" {\n  default_if \"--json\" \"false\" \"true\"\n}\nflag \"--json\" negate=\"--no-json\"\n"
8057            .parse()
8058            .unwrap();
8059
8060        let off = parse(&spec, &input(&["ex", "--no-json"])).unwrap();
8061        assert_eq!(
8062            off.as_env().get("usage_pretty").map(String::as_str),
8063            Some("true")
8064        );
8065        let on = parse(&spec, &input(&["ex", "--json"])).unwrap();
8066        assert!(
8067            !on.as_env().contains_key("usage_pretty"),
8068            "--json is true, so when=false should miss"
8069        );
8070    }
8071
8072    #[test]
8073    fn the_first_matching_conditional_default_wins() {
8074        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--style <s>\" {\n  default_if \"--json\" \"compact\"\n  default_if \"--pretty\" \"pretty\"\n}\nflag \"--json\"\nflag \"--pretty\"\n"
8075            .parse()
8076            .unwrap();
8077
8078        let out = parse(&spec, &input(&["ex", "--json", "--pretty"])).unwrap();
8079        assert_eq!(
8080            out.as_env().get("usage_style").map(String::as_str),
8081            Some("compact")
8082        );
8083    }
8084
8085    #[test]
8086    fn argv_and_env_suppress_a_conditional_default() {
8087        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--bin-names\" env=\"EX_BIN\" {\n  default_if \"--json\" \"true\"\n}\nflag \"--json\"\n"
8088            .parse()
8089            .unwrap();
8090
8091        let from_env = parse_with_env(&spec, &["ex", "--json"], &[("EX_BIN", "false")]).unwrap();
8092        assert_eq!(
8093            from_env.as_env().get("usage_bin_names").map(String::as_str),
8094            Some("false"),
8095            "the target's environment wins over default_if"
8096        );
8097    }
8098
8099    #[test]
8100    fn a_sibling_env_activates_a_conditional_default() {
8101        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--bin-names\" {\n  default_if \"--json\" \"true\"\n}\nflag \"--json\" env=\"EX_JSON\"\n"
8102            .parse()
8103            .unwrap();
8104
8105        let out = parse_with_env(&spec, &["ex"], &[("EX_JSON", "1")]).unwrap();
8106        assert_eq!(
8107            out.as_env().get("usage_bin_names").map(String::as_str),
8108            Some("true")
8109        );
8110    }
8111
8112    #[test]
8113    fn a_default_does_not_activate_a_conditional_default() {
8114        // `--json` sorts before `--pretty` in the available-flag map, so a one-pass
8115        // bind would put json's default into `out.flags` and then treat it as
8116        // explicit for pretty's `default_if`. Go and the derive ignore defaults.
8117        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--pretty\" {\n  default_if \"--json\" \"true\"\n}\nflag \"--json\" default=#true\n"
8118            .parse()
8119            .unwrap();
8120
8121        let out = parse(&spec, &input(&["ex"])).unwrap();
8122        assert_eq!(
8123            out.as_env().get("usage_json").map(String::as_str),
8124            Some("true")
8125        );
8126        assert!(
8127            !out.as_env().contains_key("usage_pretty"),
8128            "a default is not an explicit value for default_if"
8129        );
8130    }
8131
8132    #[test]
8133    fn a_conditional_default_does_not_activate_requires_if() {
8134        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--format <f>\" {\n  default_if \"--json\" \"json\"\n  requires_if \"json\" \"--schema\"\n}\nflag \"--schema <s>\"\nflag \"--json\"\n"
8135            .parse()
8136            .unwrap();
8137
8138        parse(&spec, &input(&["ex", "--json"]))
8139            .expect("a default_if value is not explicit for requires_if");
8140        assert!(parse(&spec, &input(&["ex", "--format", "json"])).is_err());
8141    }
8142
8143    #[test]
8144    fn a_conditional_default_satisfies_a_requirement() {
8145        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--out <p>\" requires=\"--format\"\nflag \"--format <f>\" {\n  default_if \"--json\" \"json\"\n}\nflag \"--json\"\n"
8146            .parse()
8147            .unwrap();
8148
8149        parse(&spec, &input(&["ex", "--out", "a.txt", "--json"]))
8150            .expect("default_if fills the required flag");
8151        assert!(parse(&spec, &input(&["ex", "--out", "a.txt"])).is_err());
8152    }
8153
8154    #[test]
8155    fn an_environment_value_satisfies_a_requirement() {
8156        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--out <p>\" requires=\"--format\"\nflag \"--format <f>\" env=\"EX_FORMAT\"\n"
8157            .parse()
8158            .unwrap();
8159
8160        assert!(parse(&spec, &input(&["ex", "--out", "a.txt"])).is_err());
8161        parse_with_env(&spec, &["ex", "--out", "a.txt"], &[("EX_FORMAT", "json")])
8162            .expect("the environment supplies it");
8163    }
8164
8165    #[test]
8166    fn a_requirement_is_satisfied_by_a_short_form() {
8167        // The selector may spell the other flag any way it answers to, so the check
8168        // resolves it the way every other selector is resolved rather than matching
8169        // text. The error names the flag, not the selector.
8170        let spec: Spec =
8171            "name \"ex\"\nbin \"ex\"\nflag \"--sign\" requires=\"-k\"\nflag \"-k --key <k>\"\n"
8172                .parse()
8173                .unwrap();
8174
8175        parse(&spec, &input(&["ex", "--sign", "--key", "x"])).expect("--key satisfies -k");
8176
8177        let err = parse(&spec, &input(&["ex", "--sign"])).unwrap_err();
8178        assert!(err.to_string().contains("key"), "{err}");
8179    }
8180
8181    #[test]
8182    fn conflicting_flags_are_rejected_in_either_order() {
8183        // Declared once, on `--file`, which is all clap exposes — so the check has to
8184        // be order-independent by looking at every flag that was given rather than at
8185        // the one that declared the conflict.
8186        let spec: Spec =
8187            "name \"ex\"\nbin \"ex\"\nflag \"--file <f>\" conflicts=\"--stdin\"\nflag \"--stdin\"\n"
8188                .parse()
8189                .unwrap();
8190
8191        for words in [
8192            &["ex", "--file", "a.txt", "--stdin"][..],
8193            &["ex", "--stdin", "--file", "a.txt"][..],
8194        ] {
8195            let err = parse(&spec, &input(words)).unwrap_err();
8196            assert!(
8197                err.to_string().contains("conflicts with --stdin"),
8198                "{words:?} should be refused: {err}"
8199            );
8200        }
8201
8202        // Either one alone is fine.
8203        parse(&spec, &input(&["ex", "--stdin"])).unwrap();
8204        parse(&spec, &input(&["ex", "--file", "a.txt"])).unwrap();
8205    }
8206
8207    #[test]
8208    fn unknown_flags_are_values_by_default() {
8209        // The default, and the reason it is the default: a spec often parses a
8210        // command line whose flags belong to something else.
8211        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--force\"\narg \"[rest]...\"\n"
8212            .parse()
8213            .unwrap();
8214        let out = parse(
8215            &spec,
8216            &["ex".to_string(), "--wat".to_string(), "x".to_string()],
8217        )
8218        .unwrap();
8219        let rest = out.args.keys().find(|a| a.name == "rest").unwrap();
8220        assert_eq!(out.args[rest].to_string(), "--wat x");
8221    }
8222
8223    #[test]
8224    fn repeated_scalar_flags_override_by_default_and_can_be_strict() {
8225        let permissive: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--jobs <n>\"\nflag \"--verbose\"\n"
8226            .parse()
8227            .unwrap();
8228        let out = parse(&permissive, &input(&["ex", "--jobs", "1", "--jobs", "2"]))
8229            .expect("a repeat is a correction by default");
8230        let jobs = out.flags.keys().find(|f| f.name == "jobs").unwrap();
8231        assert_eq!(out.flags[jobs].to_string(), "2");
8232        parse(&permissive, &input(&["ex", "--verbose", "--verbose"]))
8233            .expect("switches use the same default");
8234
8235        let strict: Spec = "name \"ex\"\nbin \"ex\"\nargs_override_self #false\nflag \"--jobs <n>\"\nflag \"--verbose\"\n"
8236            .parse()
8237            .unwrap();
8238        for words in [
8239            &["ex", "--jobs", "1", "--jobs", "2"][..],
8240            &["ex", "--verbose", "--verbose"][..],
8241        ] {
8242            let err = parse(&strict, &input(words)).unwrap_err();
8243            assert!(
8244                err.to_string().contains("cannot be used multiple times"),
8245                "{err}"
8246            );
8247        }
8248
8249        let reparsed: Spec = strict.to_string().parse().unwrap();
8250        assert!(!reparsed.cmd.args_override_self);
8251    }
8252
8253    #[test]
8254    fn strict_negated_flags_allow_opposite_forms_but_reject_the_same_form() {
8255        let spec: Spec = "name \"ex\"\nbin \"ex\"\nargs_override_self #false\nflag \"--color\" negate=\"--no-color\"\n"
8256            .parse()
8257            .unwrap();
8258
8259        let out = parse(&spec, &input(&["ex", "--color", "--no-color"]))
8260            .expect("opposite forms override each other");
8261        let color = out.flags.keys().find(|f| f.name == "color").unwrap();
8262        assert!(matches!(out.flags[color], ParseValue::Bool(false)));
8263
8264        for words in [
8265            &["ex", "--color", "--color"][..],
8266            &["ex", "--no-color", "--no-color"][..],
8267        ] {
8268            let err = parse(&spec, &input(words)).unwrap_err();
8269            assert!(err.to_string().contains("cannot be used multiple times"));
8270        }
8271    }
8272
8273    #[test]
8274    fn strict_global_flags_may_repeat_across_command_levels() {
8275        let spec: Spec = "name \"ex\"\nbin \"ex\"\nargs_override_self #false\nflag \"--color\" negate=\"--no-color\" global=#true\nflag \"--jobs <n>\" global=#true\ncmd \"run\" {\n  args_override_self #false\n}\n"
8276            .parse()
8277            .unwrap();
8278
8279        let out = parse(
8280            &spec,
8281            &input(&[
8282                "ex", "--color", "--jobs", "1", "run", "--color", "--jobs", "2",
8283            ]),
8284        )
8285        .expect("an inherited global is allowed once at each command level");
8286        let jobs = out.flags.keys().find(|f| f.name == "jobs").unwrap();
8287        assert_eq!(out.flags[jobs].to_string(), "2");
8288
8289        for words in [
8290            &["ex", "--color", "--color", "run", "--no-color"][..],
8291            &["ex", "--jobs", "1", "run", "--jobs", "2", "--jobs", "3"][..],
8292        ] {
8293            let err = parse(&spec, &input(words)).unwrap_err();
8294            assert!(err.to_string().contains("cannot be used multiple times"));
8295        }
8296    }
8297
8298    #[test]
8299    fn a_subcommand_can_negate_only_its_parents_requirements() {
8300        let base = r#"name "ex"
8301bin "ex"
8302flag "--config" required=#true
8303flag "--mode" requires="--config"
8304flag "--other"
8305arg "<input>"
8306group "source" "--config" "--other" required=#true
8307cmd "run" { flag "--child" required=#true }
8308"#;
8309        let strict: Spec = base.parse().unwrap();
8310        let err = parse(&strict, &input(&["ex", "run"])).unwrap_err();
8311        let message = err.to_string();
8312        assert!(
8313            message.contains("input") || message.contains("config"),
8314            "{message}"
8315        );
8316
8317        let negated: Spec = base
8318            .replacen("bin \"ex\"", "bin \"ex\"\nsubcommand_negates_reqs #true", 1)
8319            .parse()
8320            .unwrap();
8321        let err = parse(&negated, &input(&["ex", "run"])).unwrap_err();
8322        assert!(
8323            err.to_string().contains("child"),
8324            "the selected command keeps its own requirements: {err}"
8325        );
8326
8327        let mut child_optional = negated.clone();
8328        child_optional.cmd.subcommands["run"].flags[0].required = false;
8329        parse(&child_optional, &input(&["ex", "run"]))
8330            .expect("the child selection satisfies all parent requirements");
8331        parse(&child_optional, &input(&["ex", "--mode", "run"]))
8332            .expect("parent requires relationships are negated too");
8333    }
8334
8335    #[test]
8336    fn a_parent_argument_can_conflict_with_a_later_subcommand() {
8337        let spec: Spec = r#"name "ex"
8338bin "ex"
8339args_conflicts_with_subcommands #true
8340flag "--verbose"
8341cmd "run"
8342"#
8343        .parse()
8344        .unwrap();
8345
8346        parse(&spec, &input(&["ex", "run"]))
8347            .expect("the subcommand is valid without a parent argument");
8348        let err = parse(&spec, &input(&["ex", "--verbose", "run"])).unwrap_err();
8349        assert!(
8350            err.to_string().contains("cannot be used with arguments"),
8351            "{err}"
8352        );
8353    }
8354
8355    #[test]
8356    fn a_subcommand_can_take_precedence_over_a_variadic_flag() {
8357        let base = r#"name "ex"
8358bin "ex"
8359flag "--values <value>..."
8360cmd "run"
8361"#;
8362        let plain: Spec = base.parse().unwrap();
8363        let out = parse(&plain, &input(&["ex", "--values", "a", "run"])).unwrap();
8364        assert_eq!(out.cmd.name, "ex");
8365
8366        let precedence: Spec = base
8367            .replacen(
8368                "bin \"ex\"",
8369                "bin \"ex\"\nsubcommand_precedence_over_arg #true",
8370                1,
8371            )
8372            .parse()
8373            .unwrap();
8374        let out = parse(&precedence, &input(&["ex", "--values", "a", "run"])).unwrap();
8375        assert_eq!(out.cmd.name, "run");
8376    }
8377
8378    #[test]
8379    fn a_required_positional_can_follow_an_unfilled_optional_one() {
8380        let base = r#"name "ex"
8381bin "ex"
8382arg "[optional]"
8383arg "<required>"
8384"#;
8385        let plain: Spec = base.parse().unwrap();
8386        let err = parse(&plain, &input(&["ex", "value"])).unwrap_err();
8387        assert!(err.to_string().contains("required"), "{err}");
8388
8389        let enabled: Spec = base
8390            .replacen(
8391                "bin \"ex\"",
8392                "bin \"ex\"\nallow_missing_positional #true",
8393                1,
8394            )
8395            .parse()
8396            .unwrap();
8397        let out = parse(&enabled, &input(&["ex", "value"])).unwrap();
8398        assert!(!out.args.keys().any(|arg| arg.name == "optional"));
8399        let value = &out
8400            .args
8401            .iter()
8402            .find(|(arg, _)| arg.name == "required")
8403            .unwrap()
8404            .1;
8405        assert!(matches!(value, ParseValue::String(value) if value == "value"));
8406    }
8407
8408    #[test]
8409    fn sigil_args_do_not_block_optional_positional_skipping() {
8410        let spec: Spec = r#"name "ex"
8411bin "ex"
8412allow_missing_positional #true
8413arg "[optional]"
8414arg "[tool]" sigil="@"
8415arg "<required>"
8416"#
8417        .parse()
8418        .unwrap();
8419
8420        let out = parse(&spec, &input(&["ex", "@node", "value"])).unwrap();
8421        assert!(!out.args.keys().any(|arg| arg.name == "optional"));
8422        let tool = out.args.keys().find(|arg| arg.name == "tool").unwrap();
8423        let required = out.args.keys().find(|arg| arg.name == "required").unwrap();
8424        assert_eq!(out.args[tool].to_string(), "node");
8425        assert_eq!(out.args[required].to_string(), "value");
8426    }
8427
8428    #[test]
8429    fn unknown_env_refuses_every_undeclared_variable_under_the_prefix() {
8430        let spec: Spec = r#"name "ex"
8431bin "ex"
8432unknown_env prefix="EX_" {
8433    allow "EX_LIBRARY"
8434}
8435flag "--port <port>" env="EX_PORT"
8436cmd "serve" {
8437    flag "--tls" deprecated_env="EX_SSL"
8438}
8439cmd "publish"
8440"#
8441        .parse()
8442        .unwrap();
8443        let env = |names: &[&str]| -> HashMap<String, String> {
8444            names.iter().map(|n| (n.to_string(), "1".into())).collect()
8445        };
8446        let argv = input(&["ex", "publish"]);
8447
8448        // A variable for `serve` is known while running `publish`, and a deprecated name
8449        // keeps its deprecation warning instead of becoming an error.
8450        let out = Parser::new(&spec)
8451            .with_env(env(&["EX_PORT", "EX_SSL", "EX_LIBRARY", "OTHER"]))
8452            .parse(&argv)
8453            .unwrap();
8454        assert!(out.errors.is_empty());
8455
8456        let err = Parser::new(&spec)
8457            .with_env(env(&["EX_PROT", "EX_PORT", "EX_TSL"]))
8458            .parse(&argv)
8459            .unwrap_err()
8460            .to_string();
8461        assert_eq!(
8462            err,
8463            "Unknown environment variables under EX_: EX_PROT, EX_TSL"
8464        );
8465
8466        // Help is still help: the user asking how to fix the typo should get the answer.
8467        let err = Parser::new(&spec)
8468            .with_env(env(&["EX_PROT"]))
8469            .parse(&input(&["ex", "--help"]))
8470            .unwrap_err()
8471            .to_string();
8472        assert!(!err.contains("EX_PROT"), "{err}");
8473        assert!(err.contains("Usage:"), "{err}");
8474    }
8475
8476    #[test]
8477    fn unknown_flags_can_be_rejected_for_the_whole_cli() {
8478        let spec: Spec =
8479            "name \"ex\"\nbin \"ex\"\nunknown_flags \"error\"\nflag \"--force\"\nflag \"-0 --print0\"\narg \"[rest]...\" allow_negative_numbers=#true\n"
8480                .parse()
8481                .unwrap();
8482        let err = parse(&spec, &["ex".to_string(), "--wat".to_string()]).unwrap_err();
8483        assert!(
8484            err.to_string().contains("--wat"),
8485            "the message should name the token: {err}"
8486        );
8487
8488        // The positional opts into the narrower negative-number carve-out without
8489        // accepting arbitrary unknown flags.
8490        let out = parse(&spec, &["ex".to_string(), "-1".to_string()]).unwrap();
8491        let rest = out.args.keys().find(|a| a.name == "rest").unwrap();
8492        assert_eq!(out.args[rest].to_string(), "-1");
8493
8494        let out = parse(&spec, &["ex".to_string(), "-0".to_string()]).unwrap();
8495        let print0 = out.flags.keys().find(|flag| flag.name == "print0").unwrap();
8496        assert!(matches!(out.flags[print0], ParseValue::Bool(true)));
8497    }
8498
8499    #[test]
8500    fn a_declared_digit_short_does_not_stop_the_subcommand_scan() {
8501        let spec: Spec = r#"
8502name "ex"
8503bin "ex"
8504unknown_flags "error"
8505flag "-0 --print0" global=#true
8506cmd "run" {
8507  flag "--force"
8508}
8509"#
8510        .parse()
8511        .unwrap();
8512        let out = parse(&spec, &input(&["ex", "-0", "run", "--force"])).unwrap();
8513        assert_eq!(out.cmd.name, "run");
8514        let print0 = out.flags.keys().find(|flag| flag.name == "print0").unwrap();
8515        let force = out.flags.keys().find(|flag| flag.name == "force").unwrap();
8516        assert!(matches!(out.flags[print0], ParseValue::Bool(true)));
8517        assert!(matches!(out.flags[force], ParseValue::Bool(true)));
8518    }
8519
8520    #[test]
8521    fn a_command_may_override_the_cli_wide_setting() {
8522        // Strict overall, lenient for the one command that forwards options.
8523        let spec: Spec = r#"
8524name "ex"
8525bin "ex"
8526unknown_flags "error"
8527cmd "exec" unknown_flags="value" {
8528  arg "[rest]..."
8529}
8530cmd "build" {
8531  arg "[rest]..."
8532}
8533"#
8534        .parse()
8535        .unwrap();
8536
8537        let out = parse(
8538            &spec,
8539            &["ex".to_string(), "exec".to_string(), "--wat".to_string()],
8540        )
8541        .unwrap();
8542        let rest = out.args.keys().find(|a| a.name == "rest").unwrap();
8543        assert_eq!(out.args[rest].to_string(), "--wat");
8544
8545        assert!(
8546            parse(
8547                &spec,
8548                &["ex".to_string(), "build".to_string(), "--wat".to_string()]
8549            )
8550            .is_err(),
8551            "a command that says nothing inherits the CLI's choice"
8552        );
8553    }
8554
8555    #[test]
8556    fn the_setting_survives_a_round_trip() {
8557        let spec: Spec =
8558            "name \"ex\"\nbin \"ex\"\nunknown_flags \"error\"\ncmd \"x\" unknown_flags=\"value\"\n"
8559                .parse()
8560                .unwrap();
8561        let reparsed: Spec = spec.to_string().parse().unwrap();
8562        assert_eq!(reparsed.unknown_flags, Some(UnknownFlags::Error));
8563        assert_eq!(
8564            reparsed.cmd.subcommands["x"].unknown_flags,
8565            Some(UnknownFlags::Value)
8566        );
8567    }
8568
8569    #[test]
8570    fn test_default_subcommand() {
8571        // Test that default_subcommand routes to the specified subcommand
8572        let run_cmd = SpecCommand::builder()
8573            .name("run")
8574            .arg(SpecArg::builder().name("task").build())
8575            .build();
8576        let mut cmd = SpecCommand::builder().name("test").build();
8577        cmd.subcommands.insert("run".to_string(), run_cmd);
8578
8579        let spec = Spec {
8580            name: "test".to_string(),
8581            bin: "test".to_string(),
8582            cmd,
8583            default_subcommand: Some("run".to_string()),
8584            ..Default::default()
8585        };
8586
8587        // "test mytask" should be parsed as if it were "test run mytask"
8588        let input = vec!["test".to_string(), "mytask".to_string()];
8589        let parsed = parse(&spec, &input).unwrap();
8590
8591        // Should have two commands: root and "run"
8592        assert_eq!(parsed.cmds.len(), 2);
8593        assert_eq!(parsed.cmds[1].name, "run");
8594
8595        // Should have parsed the task argument
8596        assert_eq!(parsed.args.len(), 1);
8597        let arg = parsed.args.keys().next().unwrap();
8598        assert_eq!(arg.name, "task");
8599        let value = parsed.args.values().next().unwrap();
8600        assert_eq!(value.to_string(), "mytask");
8601    }
8602
8603    #[test]
8604    fn default_subcommand_outranks_root_sigil_arg() {
8605        let spec: Spec = r#"
8606name "test"
8607bin "test"
8608default_subcommand "run"
8609arg "[tools]..." sigil="+"
8610cmd "run" { arg "<task>" }
8611"#
8612        .parse()
8613        .unwrap();
8614
8615        let parsed = parse(&spec, &input(&["test", "+node", "node"])).unwrap();
8616        assert_eq!(parsed.cmd.name, "run");
8617        let value = |name| {
8618            parsed
8619                .args
8620                .iter()
8621                .find(|(arg, _)| arg.name == name)
8622                .map(|(_, value)| value.to_string())
8623                .unwrap()
8624        };
8625        assert_eq!(value("tools"), "node");
8626        assert_eq!(value("task"), "node");
8627    }
8628
8629    #[test]
8630    fn test_default_subcommand_explicit_still_works() {
8631        // Test that explicit subcommand takes precedence
8632        let run_cmd = SpecCommand::builder()
8633            .name("run")
8634            .arg(SpecArg::builder().name("task").build())
8635            .build();
8636        let other_cmd = SpecCommand::builder()
8637            .name("other")
8638            .arg(SpecArg::builder().name("other_arg").build())
8639            .build();
8640        let mut cmd = SpecCommand::builder().name("test").build();
8641        cmd.subcommands.insert("run".to_string(), run_cmd);
8642        cmd.subcommands.insert("other".to_string(), other_cmd);
8643
8644        let spec = Spec {
8645            name: "test".to_string(),
8646            bin: "test".to_string(),
8647            cmd,
8648            default_subcommand: Some("run".to_string()),
8649            ..Default::default()
8650        };
8651
8652        // "test other foo" should use "other" subcommand, not default
8653        let input = vec!["test".to_string(), "other".to_string(), "foo".to_string()];
8654        let parsed = parse(&spec, &input).unwrap();
8655
8656        // Should have used "other" subcommand
8657        assert_eq!(parsed.cmds.len(), 2);
8658        assert_eq!(parsed.cmds[1].name, "other");
8659    }
8660
8661    #[test]
8662    fn test_default_subcommand_applies_only_at_the_root() {
8663        // `default_subcommand` is declared once, for the whole spec, and only at the top. It
8664        // was being looked up wherever the parser happened to be standing, so a command with
8665        // an unrelated subcommand of the same name acquired a default of its own: with
8666        // `default_subcommand "ls"`, `ex config zzz` descended into `config ls` and bound
8667        // `zzz` there. Nothing declared that, and nothing could have.
8668        let mut config_ls = SpecCommand::builder().name("ls").build();
8669        config_ls.args.push(SpecArg::builder().name("what").build());
8670        let mut config_cmd = SpecCommand::builder().name("config").build();
8671        config_cmd.subcommands.insert("ls".to_string(), config_ls);
8672
8673        // The root's own `ls`, which is what its default points at. It takes an argument so
8674        // that a routed word has somewhere to land.
8675        let mut root_ls = SpecCommand::builder().name("ls").build();
8676        root_ls.args.push(SpecArg::builder().name("what").build());
8677        let mut cmd = SpecCommand::builder().name("ex").build();
8678        cmd.subcommands.insert("ls".to_string(), root_ls);
8679        cmd.subcommands.insert("config".to_string(), config_cmd);
8680
8681        let spec = Spec {
8682            name: "ex".to_string(),
8683            bin: "ex".to_string(),
8684            cmd,
8685            default_subcommand: Some("ls".to_string()),
8686            ..Default::default()
8687        };
8688
8689        // `config` has an `ls`, but `config` did not declare a default, so `zzz` is `config`'s
8690        // own business — and `config` takes no argument, so this is an error rather than a
8691        // silent descent.
8692        let input = vec!["ex".to_string(), "config".to_string(), "zzz".to_string()];
8693        assert!(
8694            parse(&spec, &input).is_err(),
8695            "`config` has no default subcommand and no argument, so `zzz` cannot bind"
8696        );
8697
8698        // At the root, where it is declared, it still applies.
8699        let input = vec!["ex".to_string(), "zzz".to_string()];
8700        let parsed = parse(&spec, &input).expect("the root's default applies");
8701        assert_eq!(
8702            parsed
8703                .cmds
8704                .iter()
8705                .map(|c| c.name.as_str())
8706                .collect::<Vec<_>>(),
8707            ["ex", "ls"]
8708        );
8709        assert_eq!(
8710            parsed.args.values().next().map(|v| v.to_string()),
8711            Some("zzz".to_string()),
8712            "and the word binds inside the command it reached"
8713        );
8714    }
8715
8716    #[test]
8717    fn test_default_subcommand_with_nested_subcommands() {
8718        // Test that default_subcommand works when the default subcommand has nested subcommands.
8719        // This is the mise use case: "mise say" should be parsed as "mise run say"
8720        // where "say" is a subcommand of "run" (a task).
8721        let say_cmd = SpecCommand::builder()
8722            .name("say")
8723            .arg(SpecArg::builder().name("name").build())
8724            .build();
8725        let mut run_cmd = SpecCommand::builder().name("run").build();
8726        run_cmd.subcommands.insert("say".to_string(), say_cmd);
8727
8728        let mut cmd = SpecCommand::builder().name("test").build();
8729        cmd.subcommands.insert("run".to_string(), run_cmd);
8730
8731        let spec = Spec {
8732            name: "test".to_string(),
8733            bin: "test".to_string(),
8734            cmd,
8735            default_subcommand: Some("run".to_string()),
8736            ..Default::default()
8737        };
8738
8739        // "test say hello" should be parsed as "test run say hello"
8740        let input = vec!["test".to_string(), "say".to_string(), "hello".to_string()];
8741        let parsed = parse(&spec, &input).unwrap();
8742
8743        // Should have three commands: root, "run", and "say"
8744        assert_eq!(parsed.cmds.len(), 3);
8745        assert_eq!(parsed.cmds[0].name, "test");
8746        assert_eq!(parsed.cmds[1].name, "run");
8747        assert_eq!(parsed.cmds[2].name, "say");
8748
8749        // Should have parsed the "name" argument
8750        assert_eq!(parsed.args.len(), 1);
8751        let arg = parsed.args.keys().next().unwrap();
8752        assert_eq!(arg.name, "name");
8753        let value = parsed.args.values().next().unwrap();
8754        assert_eq!(value.to_string(), "hello");
8755    }
8756
8757    /// Build a spec equivalent to the post-mount structure produced by mise's
8758    /// `mise usage` output: a root with a value-taking global flag (`-C/--cd`), a `run`
8759    /// subcommand that re-declares the same flag as NON-global, and a mounted task
8760    /// (`sample:run`) carrying a positional arg with `choices`.
8761    ///
8762    /// We construct the merged structure directly instead of executing a real mount so the
8763    /// test stays hermetic and cross-platform while still exercising the parser defect.
8764    fn mounted_global_flag_spec() -> Spec {
8765        let task_cmd = SpecCommand::builder()
8766            .name("sample:run")
8767            .arg(
8768                SpecArg::builder()
8769                    .name("profile")
8770                    .choices(["alpha", "beta", "gamma"])
8771                    .build(),
8772            )
8773            .build();
8774        // `run` re-declares `-C/--cd` but as a NON-global flag, mirroring the mise spec.
8775        let mut run_cmd = SpecCommand::builder()
8776            .name("run")
8777            .flag(
8778                SpecFlag::builder()
8779                    .name("cd")
8780                    .short('C')
8781                    .long("cd")
8782                    .arg(SpecArg::builder().name("dir").build())
8783                    .global(false)
8784                    .build(),
8785            )
8786            .build();
8787        run_cmd
8788            .subcommands
8789            .insert("sample:run".to_string(), task_cmd);
8790
8791        let mut cmd = SpecCommand::builder()
8792            .name("test")
8793            .flag(
8794                SpecFlag::builder()
8795                    .name("cd")
8796                    .short('C')
8797                    .long("cd")
8798                    .arg(SpecArg::builder().name("dir").build())
8799                    .global(true)
8800                    .build(),
8801            )
8802            .build();
8803        cmd.subcommands.insert("run".to_string(), run_cmd);
8804
8805        Spec {
8806            name: "test".to_string(),
8807            bin: "test".to_string(),
8808            cmd,
8809            ..Default::default()
8810        }
8811    }
8812
8813    #[test]
8814    fn test_prefix_global_flag_does_not_pollute_choices() {
8815        // Regression for the parser-side root cause referenced by jdx/mise#10069.
8816        //
8817        // When `run` re-declares the global `-C/--cd` as non-global, descending into it (and
8818        // then into the mounted `sample:run`) used to drop the inherited global flag from
8819        // `available_flags`. Phase 2 then no longer recognized the prefix `-C`, so it was
8820        // mis-validated against the task's `choices` positional arg.
8821        let spec = mounted_global_flag_spec();
8822
8823        // The prefix global flag must stay recognized so it is consumed as a flag (not as the
8824        // positional). Before the fix this bailed with "Invalid choice for arg profile: -C".
8825        for words in [
8826            &["test", "-C", "/tmp", "run", "sample:run"][..],
8827            // Embedded-value form must behave identically.
8828            &["test", "--cd=/tmp", "run", "sample:run"][..],
8829        ] {
8830            let parsed = parse_partial(&spec, &input(words)).unwrap();
8831            assert_eq!(
8832                parsed
8833                    .cmds
8834                    .iter()
8835                    .map(|c| c.name.as_str())
8836                    .collect::<Vec<_>>(),
8837                vec!["test", "run", "sample:run"],
8838            );
8839            // No positional arg should have been consumed by the leftover global-flag tokens.
8840            assert!(
8841                parsed.args.is_empty(),
8842                "args should be empty, got {:?}",
8843                parsed.args
8844            );
8845
8846            // Fix (B): the inherited global flag survives the descent even though `run`
8847            // re-declares `-C/--cd` as non-global.
8848            let cd = parsed
8849                .available_flags
8850                .get("--cd")
8851                .expect("--cd should remain available after descending into the subcommand");
8852            assert!(cd.global, "--cd must stay global after descent");
8853            assert!(
8854                parsed.available_flags.get("-C").is_some_and(|f| f.global),
8855                "-C must stay global after descent",
8856            );
8857
8858            // The global flag must still be recorded in `out.flags` so it reaches `as_env()`
8859            // for normal execution and for the env passed to mount scripts. (Removing the
8860            // token in Phase 1 instead of re-parsing it would silently drop `usage_cd`.)
8861            assert_eq!(
8862                parsed.as_env().get("usage_cd").map(String::as_str),
8863                Some("/tmp"),
8864                "global flag value must survive in as_env(), got {:?}",
8865                parsed.as_env(),
8866            );
8867        }
8868
8869        // A real, valid choice still parses through the global flag prefix.
8870        let parsed = parse_partial(
8871            &spec,
8872            &input(&["test", "-C", "/tmp", "run", "sample:run", "alpha"]),
8873        )
8874        .unwrap();
8875        assert_eq!(parsed.args.len(), 1);
8876        assert_eq!(parsed.args.values().next().unwrap().to_string(), "alpha");
8877
8878        // And genuinely invalid choices are still rejected (we didn't disable validation).
8879        assert_parse_err(
8880            parse_partial(&spec, &input(&["test", "run", "sample:run", "wrong"])),
8881            "Invalid choice for arg profile: wrong, expected one of alpha, beta, gamma",
8882        );
8883    }
8884
8885    /// Build a spec mirroring mise's orphan-short re-declarations: a root with a LONG-ONLY
8886    /// global boolean flag (`--raw`, no short), a `run` subcommand that re-declares it as a
8887    /// NON-global flag while ADDING a short (`-r --raw`) plus a purely-local `-f/--force`
8888    /// flag, and a mounted task (`sample:run`) with a `choices` positional arg.
8889    fn mounted_orphan_short_spec() -> Spec {
8890        let task_cmd = SpecCommand::builder()
8891            .name("sample:run")
8892            .arg(
8893                SpecArg::builder()
8894                    .name("profile")
8895                    .choices(["alpha", "beta", "gamma"])
8896                    .build(),
8897            )
8898            .build();
8899        // `run` re-declares `--raw` as NON-global but adds a `-r` short that exists only here,
8900        // and also carries a purely-local `-f/--force` flag (shares nothing with a global).
8901        let mut run_cmd = SpecCommand::builder()
8902            .name("run")
8903            .flag(
8904                SpecFlag::builder()
8905                    .name("raw")
8906                    .short('r')
8907                    .long("raw")
8908                    .global(false)
8909                    .build(),
8910            )
8911            .flag(
8912                SpecFlag::builder()
8913                    .name("force")
8914                    .short('f')
8915                    .long("force")
8916                    .global(false)
8917                    .build(),
8918            )
8919            .build();
8920        run_cmd
8921            .subcommands
8922            .insert("sample:run".to_string(), task_cmd);
8923
8924        // Root global is LONG-ONLY: `--raw` with no short.
8925        let mut cmd = SpecCommand::builder()
8926            .name("test")
8927            .flag(
8928                SpecFlag::builder()
8929                    .name("raw")
8930                    .long("raw")
8931                    .global(true)
8932                    .build(),
8933            )
8934            .build();
8935        cmd.subcommands.insert("run".to_string(), run_cmd);
8936
8937        Spec {
8938            name: "test".to_string(),
8939            bin: "test".to_string(),
8940            cmd,
8941            ..Default::default()
8942        }
8943    }
8944
8945    #[test]
8946    fn test_orphan_short_alias_survives_merge() {
8947        // Follow-up to test_prefix_global_flag_does_not_pollute_choices (jdx/mise#10069):
8948        // when `run` re-declares the long-only global `--raw` as a non-global `-r --raw`, the
8949        // added short `-r` must be unioned onto the surviving inherited global flag instead of
8950        // being discarded with the wholesale re-declaration. Otherwise `mycli run -r <task>`
8951        // would not recognize `-r` and would mis-validate it against the task's `choices` arg.
8952        let spec = mounted_orphan_short_spec();
8953
8954        let parsed = parse_partial(&spec, &input(&["test", "run", "-r", "sample:run"])).unwrap();
8955        assert_eq!(
8956            parsed
8957                .cmds
8958                .iter()
8959                .map(|c| c.name.as_str())
8960                .collect::<Vec<_>>(),
8961            vec!["test", "run", "sample:run"],
8962        );
8963
8964        // (a) The orphan short `-r` survives the descent, merged onto the inherited global flag,
8965        // and the original long `--raw` is still global too.
8966        assert!(
8967            parsed.available_flags.get("-r").is_some_and(|f| f.global),
8968            "-r must be merged onto the inherited global flag and stay global after descent",
8969        );
8970        assert!(
8971            parsed
8972                .available_flags
8973                .get("--raw")
8974                .is_some_and(|f| f.global),
8975            "--raw must stay global after descent",
8976        );
8977
8978        // (b) The token is consumed as a flag, not mistaken for the `choices` positional.
8979        assert!(
8980            parsed.args.is_empty(),
8981            "args should be empty, got {:?}",
8982            parsed.args
8983        );
8984
8985        // (c) The value still reaches as_env() so `usage_raw` is produced for execution/mounts.
8986        assert_eq!(
8987            parsed.as_env().get("usage_raw").map(String::as_str),
8988            Some("true"),
8989            "merged short's value must survive in as_env(), got {:?}",
8990            parsed.as_env(),
8991        );
8992
8993        // (d) Negative case: a purely-local flag that shares nothing with a global is NOT
8994        // promoted/merged — it is correctly dropped when descending into the mount.
8995        assert!(
8996            !parsed.available_flags.contains_key("-f"),
8997            "purely-local -f must not be promoted onto a global",
8998        );
8999        assert!(
9000            !parsed.available_flags.contains_key("--force"),
9001            "purely-local --force must not be promoted onto a global",
9002        );
9003
9004        // A real, valid choice still parses through the merged short prefix.
9005        let parsed =
9006            parse_partial(&spec, &input(&["test", "run", "-r", "sample:run", "alpha"])).unwrap();
9007        assert_eq!(parsed.args.len(), 1);
9008        assert_eq!(parsed.args.values().next().unwrap().to_string(), "alpha");
9009
9010        // And genuinely invalid choices are still rejected.
9011        assert_parse_err(
9012            parse_partial(&spec, &input(&["test", "run", "-r", "sample:run", "wrong"])),
9013            "Invalid choice for arg profile: wrong, expected one of alpha, beta, gamma",
9014        );
9015    }
9016
9017    #[test]
9018    fn test_orphan_short_does_not_clobber_unrelated_global() {
9019        // When a re-declaration's orphan short collides with a DIFFERENT inherited global's
9020        // short, the merge must not steal it. Here the root has both a long-only `--raw` global
9021        // and a `-r --restrict` global; `run` re-declares `-r --raw` as non-global. `-r` is a
9022        // genuine collision with `--restrict`, so global precedence must keep `-r -> restrict`.
9023        let run_cmd = SpecCommand::builder()
9024            .name("run")
9025            .flag(
9026                SpecFlag::builder()
9027                    .name("raw")
9028                    .short('r')
9029                    .long("raw")
9030                    .global(false)
9031                    .build(),
9032            )
9033            .build();
9034        let mut cmd = SpecCommand::builder()
9035            .name("test")
9036            .flag(
9037                SpecFlag::builder()
9038                    .name("raw")
9039                    .long("raw")
9040                    .global(true)
9041                    .build(),
9042            )
9043            .flag(
9044                SpecFlag::builder()
9045                    .name("restrict")
9046                    .short('r')
9047                    .long("restrict")
9048                    .global(true)
9049                    .build(),
9050            )
9051            .build();
9052        cmd.subcommands.insert("run".to_string(), run_cmd);
9053        let spec = Spec {
9054            name: "test".to_string(),
9055            bin: "test".to_string(),
9056            cmd,
9057            ..Default::default()
9058        };
9059
9060        let parsed = parse_partial(&spec, &input(&["test", "run"])).unwrap();
9061        // `-r` stays owned by the unrelated `--restrict` global, not stolen by the merged raw.
9062        assert_eq!(
9063            parsed.available_flags.get("-r").map(|f| f.name.as_str()),
9064            Some("restrict"),
9065            "-r must remain owned by the unrelated global it already belonged to",
9066        );
9067        // Both globals are still recognized and global after the descent.
9068        assert!(
9069            parsed
9070                .available_flags
9071                .get("--raw")
9072                .is_some_and(|f| f.global)
9073        );
9074        assert!(
9075            parsed
9076                .available_flags
9077                .get("--restrict")
9078                .is_some_and(|f| f.global)
9079        );
9080    }
9081
9082    #[test]
9083    fn test_redeclared_global_aliases_share_one_flag() {
9084        // A global declared with BOTH a short and a long, re-declared non-globally by a
9085        // subcommand that adds a third alias. Every alias key must resolve to the SAME merged
9086        // flag: the child's keys iterate in BTreeMap order (`--assume-yes`, `--yes`, `-y`), so by
9087        // the time `-y` is reached the long already points at the merged flag. That merged flag is
9088        // not a *different* inherited global, so the collision guard must not skip `-y` and leave
9089        // it pointing at the pre-merge global (which lacks the added `assume-yes` alias).
9090        let spec = r#"
9091flag "-y --yes" global=#true effect="write"
9092cmd "run" {
9093    flag "-y --yes --assume-yes"
9094}
9095"#
9096        .parse::<Spec>()
9097        .unwrap();
9098
9099        let parsed = parse_partial(&spec, &input(&["test", "run"])).unwrap();
9100
9101        for key in ["-y", "--yes", "--assume-yes"] {
9102            let flag = parsed
9103                .available_flags
9104                .get(key)
9105                .unwrap_or_else(|| panic!("{key} must be recognized after the descent"));
9106            assert!(flag.global, "{key} must stay global after the descent");
9107            assert_eq!(
9108                flag.long,
9109                vec!["yes".to_string(), "assume-yes".to_string()],
9110                "{key} must resolve to the flag carrying every alias",
9111            );
9112            assert_eq!(flag.short, vec!['y'], "{key} must keep the global's short");
9113        }
9114
9115        // One logical flag means one object: all three keys share a single `Arc`.
9116        assert_eq!(
9117            unique_flags(parsed.available_flags.values()).count(),
9118            1,
9119            "all aliases must point at one flag object, got {:?}",
9120            parsed.available_flags,
9121        );
9122
9123        // The global's effect survives the merge, so `-y` still marks the command as writing.
9124        assert_eq!(
9125            parsed.available_flags["-y"].effect,
9126            Some(crate::SpecCommandEffect::Write),
9127        );
9128    }
9129
9130    #[test]
9131    fn test_redeclared_global_keeps_hidden_alias_metadata() {
9132        let spec = r#"
9133flag "--yes" global=#true {
9134    alias "-q" "--quietly" hide=#true
9135}
9136cmd "run" {
9137    flag "--yes --assume-yes" {
9138        alias "-s" "--secret" hide=#true
9139    }
9140}
9141"#
9142        .parse::<Spec>()
9143        .unwrap();
9144
9145        let parsed = parse_partial(&spec, &input(&["test", "run"])).unwrap();
9146        let merged = &parsed.available_flags["--yes"];
9147        assert_eq!(merged.hidden_short_aliases, ['q', 's']);
9148        assert_eq!(merged.hidden_aliases, ["quietly", "secret"]);
9149        for key in ["-q", "-s", "--quietly", "--secret"] {
9150            assert!(Arc::ptr_eq(&parsed.available_flags[key], merged), "{key}");
9151        }
9152    }
9153
9154    #[test]
9155    fn test_redeclared_global_can_promote_hidden_aliases() {
9156        let spec = r#"
9157flag "--yes" global=#true {
9158    alias "-q" "--quietly" hide=#true
9159}
9160cmd "run" {
9161    flag "-q --yes --quietly"
9162}
9163"#
9164        .parse::<Spec>()
9165        .unwrap();
9166
9167        let parsed = parse_partial(&spec, &input(&["test", "run"])).unwrap();
9168        let merged = &parsed.available_flags["--yes"];
9169        assert!(merged.hidden_short_aliases.is_empty());
9170        assert!(merged.hidden_aliases.is_empty());
9171        for key in ["-q", "--quietly"] {
9172            assert!(Arc::ptr_eq(&parsed.available_flags[key], merged), "{key}");
9173        }
9174    }
9175
9176    #[test]
9177    fn test_partially_redeclared_global_keeps_all_aliases_on_one_flag() {
9178        // Same one-flag-one-object requirement as above, but the child re-declares only ONE of
9179        // the global's three aliases (`--yes`, not `-y`/`--confirm`) while adding a new one. The
9180        // aliases the child omits are never visited by the merge loop, so they must be rebound to
9181        // the merged flag explicitly — otherwise `-y` and `--confirm` keep pointing at the
9182        // pre-merge global and miss the added `assume-yes`.
9183        let spec = r#"
9184flag "-y --yes --confirm" global=#true
9185cmd "run" {
9186    flag "--yes --assume-yes"
9187}
9188"#
9189        .parse::<Spec>()
9190        .unwrap();
9191
9192        let parsed = parse_partial(&spec, &input(&["test", "run"])).unwrap();
9193
9194        for key in ["-y", "--yes", "--confirm", "--assume-yes"] {
9195            let flag = parsed
9196                .available_flags
9197                .get(key)
9198                .unwrap_or_else(|| panic!("{key} must be recognized after the descent"));
9199            assert!(flag.global, "{key} must stay global after the descent");
9200            assert_eq!(
9201                flag.long,
9202                vec![
9203                    "yes".to_string(),
9204                    "confirm".to_string(),
9205                    "assume-yes".to_string()
9206                ],
9207                "{key} must resolve to the flag carrying every alias",
9208            );
9209        }
9210
9211        assert_eq!(
9212            unique_flags(parsed.available_flags.values()).count(),
9213            1,
9214            "all aliases must point at one flag object, got {:?}",
9215            parsed.available_flags,
9216        );
9217    }
9218
9219    /// Build a spec shaped like mise's post-mount structure for jdx/mise#11282: a root with
9220    /// globals (`-E/--env <ENV>`, `--silent`), a `run` subcommand with a non-global flag, and a
9221    /// MOUNTED task command that declares its own `--env` (with choices) plus `--bump`.
9222    ///
9223    /// The task command is marked `mounted` the same way `SpecCommand::mount()` marks the
9224    /// commands it merges in, so the test stays hermetic (no mount subprocess).
9225    fn mounted_task_flag_spec() -> Spec {
9226        let mut task_cmd = SpecCommand::builder()
9227            .name("mytask")
9228            .flag(
9229                SpecFlag::builder()
9230                    .name("env")
9231                    .long("env")
9232                    .arg(
9233                        SpecArg::builder()
9234                            .name("name")
9235                            .choices(["dev", "stage", "prod"])
9236                            .build(),
9237                    )
9238                    .global(false)
9239                    .build(),
9240            )
9241            .flag(
9242                SpecFlag::builder()
9243                    .name("bump")
9244                    .long("bump")
9245                    .arg(
9246                        SpecArg::builder()
9247                            .name("type")
9248                            .choices(["auto", "major"])
9249                            .build(),
9250                    )
9251                    .global(false)
9252                    .build(),
9253            )
9254            .build();
9255        task_cmd.mounted = true;
9256
9257        let mut run_cmd = SpecCommand::builder()
9258            .name("run")
9259            .flag(
9260                SpecFlag::builder()
9261                    .name("force")
9262                    .short('f')
9263                    .long("force")
9264                    .global(false)
9265                    .build(),
9266            )
9267            .build();
9268        run_cmd.subcommands.insert("mytask".to_string(), task_cmd);
9269
9270        let mut cmd = SpecCommand::builder()
9271            .name("test")
9272            .flag(
9273                SpecFlag::builder()
9274                    .name("env")
9275                    .short('E')
9276                    .long("env")
9277                    .arg(SpecArg::builder().name("ENV").build())
9278                    .global(true)
9279                    .build(),
9280            )
9281            .flag(
9282                SpecFlag::builder()
9283                    .name("silent")
9284                    .long("silent")
9285                    .global(true)
9286                    .build(),
9287            )
9288            .build();
9289        cmd.subcommands.insert("run".to_string(), run_cmd);
9290
9291        Spec {
9292            name: "test".to_string(),
9293            bin: "test".to_string(),
9294            cmd,
9295            ..Default::default()
9296        }
9297    }
9298
9299    #[test]
9300    fn test_mount_boundary_does_not_apply_inside_the_mounted_tree() {
9301        // The mounted program's own commands are ordinary commands relative to each other, so
9302        // descending *within* the mounted tree must follow the normal rules — including keeping
9303        // an inherited global that a nested command re-declares as non-global (jdx/usage#649).
9304        // Treating every level of the tree as a mount boundary let the re-declaration shadow the
9305        // global, which the next descent's `retain(global)` then dropped entirely.
9306        let deep = SpecCommand::builder().name("deep").build();
9307        let mut sub = SpecCommand::builder()
9308            .name("sub")
9309            // Re-declares the mounted program's own global as non-global.
9310            .flag(
9311                SpecFlag::builder()
9312                    .name("cd")
9313                    .short('C')
9314                    .long("cd")
9315                    .arg(SpecArg::builder().name("dir").build())
9316                    .global(false)
9317                    .build(),
9318            )
9319            .build();
9320        sub.subcommands.insert("deep".to_string(), deep);
9321        let mut task = SpecCommand::builder()
9322            .name("task")
9323            .flag(
9324                SpecFlag::builder()
9325                    .name("cd")
9326                    .short('C')
9327                    .long("cd")
9328                    .arg(SpecArg::builder().name("dir").build())
9329                    .global(true)
9330                    .build(),
9331            )
9332            .build();
9333        task.subcommands.insert("sub".to_string(), sub);
9334        task.mark_mounted();
9335
9336        let mut run_cmd = SpecCommand::builder().name("run").build();
9337        run_cmd.subcommands.insert("task".to_string(), task);
9338        let mut cmd = SpecCommand::builder().name("test").build();
9339        cmd.subcommands.insert("run".to_string(), run_cmd);
9340        let spec = Spec {
9341            name: "test".to_string(),
9342            bin: "test".to_string(),
9343            cmd,
9344            ..Default::default()
9345        };
9346
9347        let parsed = parse_partial(&spec, &input(&["test", "run", "task", "sub", "deep"])).unwrap();
9348        assert!(
9349            parsed.available_flags.get("--cd").is_some_and(|f| f.global),
9350            "the mounted program's own global must survive descents inside the mounted tree",
9351        );
9352        assert!(
9353            parsed.completion_flags().contains_key("--cd"),
9354            "and must still be offered there: it belongs to the mounted program",
9355        );
9356        assert!(
9357            parsed.completion_flags().contains_key("-C"),
9358            "including the short the nested command re-declared",
9359        );
9360    }
9361
9362    #[test]
9363    fn test_mount_flags_merged_into_the_mounting_cmd_are_offered() {
9364        // A mounted spec may declare flags on its own root, which `SpecCommand::merge` folds
9365        // into the command the mount sits on. They belong to the mounted program, so they must
9366        // be offered inside the mounted commands rather than filtered out with the mounting
9367        // CLI's own flags.
9368        let mut task = SpecCommand::builder()
9369            .name("task")
9370            .flag(
9371                SpecFlag::builder()
9372                    .name("bump")
9373                    .long("bump")
9374                    .global(false)
9375                    .build(),
9376            )
9377            .build();
9378        task.mark_mounted();
9379
9380        let mut run_cmd = SpecCommand::builder().name("run").build();
9381        run_cmd.subcommands.insert("task".to_string(), task);
9382        // What `mount()` leaves behind when the mounted spec's root declares flags.
9383        run_cmd.flags = vec![
9384            SpecFlag::builder()
9385                .name("tglobal")
9386                .long("tglobal")
9387                .global(true)
9388                .build(),
9389            SpecFlag::builder()
9390                .name("tlocal")
9391                .long("tlocal")
9392                .global(false)
9393                .build(),
9394        ];
9395        run_cmd.flags_from_mount = true;
9396
9397        let mut cmd = SpecCommand::builder()
9398            .name("test")
9399            .flag(
9400                SpecFlag::builder()
9401                    .name("silent")
9402                    .long("silent")
9403                    .global(true)
9404                    .build(),
9405            )
9406            .build();
9407        cmd.subcommands.insert("run".to_string(), run_cmd);
9408        let spec = Spec {
9409            name: "test".to_string(),
9410            bin: "test".to_string(),
9411            cmd,
9412            ..Default::default()
9413        };
9414
9415        let parsed = parse_partial(&spec, &input(&["test", "run", "task"])).unwrap();
9416        assert_eq!(
9417            parsed.completion_flags().keys().collect::<Vec<_>>(),
9418            vec!["--bump", "--tglobal"],
9419            "the mounted spec's root global belongs to the mounted program; the mounting CLI's \
9420             `--silent` does not, and the mount's non-global root flag is not inherited",
9421        );
9422    }
9423
9424    #[test]
9425    fn test_mounted_cmd_does_not_offer_mounting_cli_globals() {
9426        // Regression for jdx/mise#11282. A mounted command describes another program, which
9427        // does not accept the mounting CLI's globals (mise forwards everything after a task
9428        // name to the task). They must stay recognized — they may appear before the mounted
9429        // command — but must not be offered in completions there.
9430        let spec = mounted_task_flag_spec();
9431        let parsed = parse_partial(&spec, &input(&["test", "run", "mytask"])).unwrap();
9432
9433        // Still recognized for parsing...
9434        assert!(parsed.available_flags.contains_key("--silent"));
9435        assert!(parsed.available_flags.contains_key("-E"));
9436        // ...but belonging to a command above the mount, so not offered.
9437        assert_eq!(
9438            parsed.completion_flags().keys().collect::<Vec<_>>(),
9439            vec!["--bump", "--env"],
9440            "only the mounted command's own flags may be offered",
9441        );
9442
9443        // `run`'s own non-global flag is dropped on descent, as it always was.
9444        assert!(!parsed.available_flags.contains_key("--force"));
9445    }
9446
9447    #[test]
9448    fn test_mounted_cmd_flag_wins_over_inherited_global() {
9449        // Second half of jdx/mise#11282: the mounted `--env` (with choices) used to be shadowed
9450        // by the root's `--env` global, so completing its value fell back to file completion.
9451        let spec = mounted_task_flag_spec();
9452        let parsed = parse_partial(&spec, &input(&["test", "run", "mytask", "--env"])).unwrap();
9453
9454        let awaiting = parsed
9455            .flag_awaiting_value
9456            .first()
9457            .expect("--env should await a value");
9458        assert_eq!(
9459            awaiting
9460                .arg
9461                .as_ref()
9462                .and_then(|a| a.choices.as_ref())
9463                .map(|c| c.choices.clone()),
9464            Some(vec![
9465                "dev".to_string(),
9466                "stage".to_string(),
9467                "prod".to_string()
9468            ]),
9469            "the mounted command's own --env must win over the inherited global",
9470        );
9471
9472        // The global's short is not declared by the mounted command, so it keeps pointing at
9473        // the global and a value passed before the mounted command still parses.
9474        let parsed =
9475            parse_partial(&spec, &input(&["test", "-E", "anything", "run", "mytask"])).unwrap();
9476        assert!(
9477            parsed.args.is_empty(),
9478            "prefix global tokens must not be consumed as positionals, got {:?}",
9479            parsed.args
9480        );
9481        assert_eq!(
9482            parsed.as_env().get("usage_env").map(String::as_str),
9483            Some("anything"),
9484        );
9485    }
9486
9487    #[test]
9488    fn test_prefix_flag_keeps_the_flag_it_was_read_as() {
9489        // A word before the mounted command is re-parsed by Phase 2, when the mounted command
9490        // already owns the name. It has to stay bound to the flag Phase 1 read it as, or the
9491        // global's value would be validated against the mounted flag's choices and a legitimate
9492        // value would be rejected.
9493        let spec = mounted_task_flag_spec();
9494        let parsed = parse_partial(
9495            &spec,
9496            &input(&["test", "--env", "not-a-task-choice", "run", "mytask"]),
9497        )
9498        .unwrap();
9499        assert!(
9500            parsed.errors.is_empty(),
9501            "prefix global value must not be validated against the mounted flag: {:?}",
9502            parsed
9503                .errors
9504                .iter()
9505                .map(|e| e.to_string())
9506                .collect::<Vec<_>>(),
9507        );
9508        assert_eq!(
9509            parsed.as_env().get("usage_env").map(String::as_str),
9510            Some("not-a-task-choice"),
9511        );
9512
9513        // The embedded-value form binds the same way.
9514        let parsed = parse_partial(
9515            &spec,
9516            &input(&["test", "--env=not-a-task-choice", "run", "mytask"]),
9517        )
9518        .unwrap();
9519        assert!(parsed.errors.is_empty());
9520        assert_eq!(
9521            parsed.as_env().get("usage_env").map(String::as_str),
9522            Some("not-a-task-choice"),
9523        );
9524
9525        // Meanwhile a word *after* the mounted command belongs to the mounted flag, even when
9526        // the same name was already used before it.
9527        let parsed = parse_partial(
9528            &spec,
9529            &input(&["test", "--env", "prod", "run", "mytask", "--env"]),
9530        )
9531        .unwrap();
9532        let awaiting = parsed
9533            .flag_awaiting_value
9534            .first()
9535            .expect("--env should await a value");
9536        assert_eq!(
9537            awaiting
9538                .arg
9539                .as_ref()
9540                .and_then(|a| a.choices.as_ref())
9541                .map(|c| c.choices.clone()),
9542            Some(vec![
9543                "dev".to_string(),
9544                "stage".to_string(),
9545                "prod".to_string()
9546            ]),
9547            "the mounted command's --env must own the name after the mounted command",
9548        );
9549    }
9550
9551    #[test]
9552    fn test_non_global_flag_does_not_hide_subcommand() {
9553        // A non-global flag may precede a subcommand (`mycli run --force task`). Phase 1 used to
9554        // stop scanning at one, so the subcommand — and any mount on it — was never reached and
9555        // its name was left to Phase 2 to mis-read as a positional: `unexpected word: mytask`.
9556        let spec = mounted_task_flag_spec();
9557
9558        for words in [
9559            // `run` declares `-f/--force` as non-global.
9560            &["test", "run", "--force", "mytask"][..],
9561            &["test", "run", "-f", "mytask"][..],
9562            // Mixed with a global before the subcommand.
9563            &["test", "-E", "prod", "run", "--force", "mytask"][..],
9564        ] {
9565            let parsed = parse_partial(&spec, &input(words)).unwrap();
9566            assert_eq!(
9567                parsed
9568                    .cmds
9569                    .iter()
9570                    .map(|c| c.name.as_str())
9571                    .collect::<Vec<_>>(),
9572                vec!["test", "run", "mytask"],
9573                "{words:?} should descend into the mounted command",
9574            );
9575            assert!(
9576                parsed.args.is_empty(),
9577                "{words:?} should not consume a positional, got {:?}",
9578                parsed.args,
9579            );
9580            assert_eq!(
9581                parsed.as_env().get("usage_force").map(String::as_str),
9582                Some("true"),
9583                "the non-global flag must still be recorded for {words:?}",
9584            );
9585        }
9586
9587        // A non-global flag that takes a value consumes it, rather than reading the value as the
9588        // subcommand.
9589        let mut run_cmd = SpecCommand::builder()
9590            .name("run")
9591            .flag(
9592                SpecFlag::builder()
9593                    .name("output")
9594                    .short('o')
9595                    .long("output")
9596                    .arg(SpecArg::builder().name("mode").build())
9597                    .global(false)
9598                    .build(),
9599            )
9600            .build();
9601        run_cmd.subcommands.insert(
9602            "task".to_string(),
9603            SpecCommand::builder().name("task").build(),
9604        );
9605        let mut cmd = SpecCommand::builder().name("test").build();
9606        cmd.subcommands.insert("run".to_string(), run_cmd);
9607        let spec = Spec {
9608            name: "test".to_string(),
9609            bin: "test".to_string(),
9610            cmd,
9611            ..Default::default()
9612        };
9613
9614        let parsed =
9615            parse_partial(&spec, &input(&["test", "run", "--output", "quiet", "task"])).unwrap();
9616        assert_eq!(
9617            parsed
9618                .cmds
9619                .iter()
9620                .map(|c| c.name.as_str())
9621                .collect::<Vec<_>>(),
9622            vec!["test", "run", "task"],
9623        );
9624        assert_eq!(
9625            parsed.as_env().get("usage_output").map(String::as_str),
9626            Some("quiet"),
9627        );
9628
9629        // An unknown flag still stops the scan: it may take a value, so the next word cannot be
9630        // assumed to be a subcommand. `run` takes no positional, so this stays an error.
9631        assert_parse_err(
9632            parse_partial(&spec, &input(&["test", "run", "--nope", "task"])),
9633            "unexpected word: --nope",
9634        );
9635    }
9636
9637    #[test]
9638    fn test_non_mounted_subcommand_offers_inherited_globals() {
9639        // Nothing changes for ordinary (non-mounted) subcommands: a global declared above is
9640        // still both recognized and offered.
9641        let mut run_cmd = SpecCommand::builder().name("run").build();
9642        run_cmd.subcommands.insert(
9643            "nested".to_string(),
9644            SpecCommand::builder().name("nested").build(),
9645        );
9646        let mut cmd = SpecCommand::builder()
9647            .name("test")
9648            .flag(
9649                SpecFlag::builder()
9650                    .name("silent")
9651                    .long("silent")
9652                    .global(true)
9653                    .build(),
9654            )
9655            .build();
9656        cmd.subcommands.insert("run".to_string(), run_cmd);
9657        let spec = Spec {
9658            name: "test".to_string(),
9659            bin: "test".to_string(),
9660            cmd,
9661            ..Default::default()
9662        };
9663
9664        let parsed = parse_partial(&spec, &input(&["test", "run", "nested"])).unwrap();
9665        assert_eq!(
9666            parsed.completion_flags().keys().collect::<Vec<_>>(),
9667            parsed.available_flags.keys().collect::<Vec<_>>(),
9668        );
9669        assert!(parsed.completion_flags().contains_key("--silent"));
9670    }
9671
9672    #[test]
9673    fn test_subcommand_alias_collision_keeps_last_owner() {
9674        // The orphan-alias merge must not disturb how two flags in the SAME subcommand that
9675        // share an alias are resolved. Historically the flattened flag map gave the shared
9676        // alias to the LAST-declared flag (last-writer-wins); that must be preserved.
9677        let run_cmd = SpecCommand::builder()
9678            .name("run")
9679            .flag(
9680                SpecFlag::builder()
9681                    .name("alpha")
9682                    .short('x')
9683                    .long("alpha")
9684                    .global(false)
9685                    .build(),
9686            )
9687            .flag(
9688                SpecFlag::builder()
9689                    .name("beta")
9690                    .short('x')
9691                    .long("beta")
9692                    .global(false)
9693                    .build(),
9694            )
9695            .build();
9696        let mut cmd = SpecCommand::builder().name("test").build();
9697        cmd.subcommands.insert("run".to_string(), run_cmd);
9698        let spec = Spec {
9699            name: "test".to_string(),
9700            bin: "test".to_string(),
9701            cmd,
9702            ..Default::default()
9703        };
9704
9705        let parsed = parse_partial(&spec, &input(&["test", "run"])).unwrap();
9706        // `-x` is declared by both flags; the last one (`beta`) keeps it, as before the fix.
9707        assert_eq!(
9708            parsed.available_flags.get("-x").map(|f| f.name.as_str()),
9709            Some("beta"),
9710            "the last-declared flag must keep a shared short alias",
9711        );
9712        // Both distinct long aliases remain recognized and point to their own flag.
9713        assert_eq!(
9714            parsed
9715                .available_flags
9716                .get("--alpha")
9717                .map(|f| f.name.as_str()),
9718            Some("alpha"),
9719        );
9720        assert_eq!(
9721            parsed
9722                .available_flags
9723                .get("--beta")
9724                .map(|f| f.name.as_str()),
9725            Some("beta"),
9726        );
9727    }
9728
9729    #[test]
9730    fn test_default_subcommand_same_name_child() {
9731        // Test that default_subcommand doesn't cause issues when the default subcommand
9732        // has a child with the same name (e.g., "run" has a task named "run").
9733        // This verifies we don't switch multiple times or get stuck in a loop.
9734        let run_task = SpecCommand::builder()
9735            .name("run")
9736            .arg(SpecArg::builder().name("args").build())
9737            .build();
9738        let mut run_cmd = SpecCommand::builder().name("run").build();
9739        run_cmd.subcommands.insert("run".to_string(), run_task);
9740
9741        let mut cmd = SpecCommand::builder().name("test").build();
9742        cmd.subcommands.insert("run".to_string(), run_cmd);
9743
9744        let spec = Spec {
9745            name: "test".to_string(),
9746            bin: "test".to_string(),
9747            cmd,
9748            default_subcommand: Some("run".to_string()),
9749            ..Default::default()
9750        };
9751
9752        // "test run" explicitly matches the "run" subcommand (not via default_subcommand)
9753        let input = vec!["test".to_string(), "run".to_string()];
9754        let parsed = parse(&spec, &input).unwrap();
9755
9756        // Should have two commands: root and "run"
9757        assert_eq!(parsed.cmds.len(), 2);
9758        assert_eq!(parsed.cmds[0].name, "test");
9759        assert_eq!(parsed.cmds[1].name, "run");
9760
9761        // "test run run" should descend into the "run" task (child of "run" subcommand)
9762        let input = vec![
9763            "test".to_string(),
9764            "run".to_string(),
9765            "run".to_string(),
9766            "hello".to_string(),
9767        ];
9768        let parsed = parse(&spec, &input).unwrap();
9769
9770        assert_eq!(parsed.cmds.len(), 3);
9771        assert_eq!(parsed.cmds[0].name, "test");
9772        assert_eq!(parsed.cmds[1].name, "run");
9773        assert_eq!(parsed.cmds[2].name, "run");
9774        assert_eq!(parsed.args.len(), 1);
9775        let value = parsed.args.values().next().unwrap();
9776        assert_eq!(value.to_string(), "hello");
9777
9778        // Key test case: "test other" should switch to default subcommand "run"
9779        // and treat "other" as a positional arg (not try to switch again because
9780        // "run" also has a "run" child).
9781        let mut run_cmd = SpecCommand::builder()
9782            .name("run")
9783            .arg(SpecArg::builder().name("task").build())
9784            .build();
9785        let run_task = SpecCommand::builder().name("run").build();
9786        run_cmd.subcommands.insert("run".to_string(), run_task);
9787
9788        let mut cmd = SpecCommand::builder().name("test").build();
9789        cmd.subcommands.insert("run".to_string(), run_cmd);
9790
9791        let spec = Spec {
9792            name: "test".to_string(),
9793            bin: "test".to_string(),
9794            cmd,
9795            default_subcommand: Some("run".to_string()),
9796            ..Default::default()
9797        };
9798
9799        let input = vec!["test".to_string(), "other".to_string()];
9800        let parsed = parse(&spec, &input).unwrap();
9801
9802        // Should have two commands: root and "run" (the default)
9803        // We should NOT have switched again to the "run" task child
9804        assert_eq!(parsed.cmds.len(), 2);
9805        assert_eq!(parsed.cmds[0].name, "test");
9806        assert_eq!(parsed.cmds[1].name, "run");
9807
9808        // "other" should be parsed as a positional arg
9809        assert_eq!(parsed.args.len(), 1);
9810        let value = parsed.args.values().next().unwrap();
9811        assert_eq!(value.to_string(), "other");
9812    }
9813
9814    #[test]
9815    fn test_restart_token() {
9816        // Test that restart_token resets argument parsing
9817        let run_cmd = SpecCommand::builder()
9818            .name("run")
9819            .arg(SpecArg::builder().name("task").build())
9820            .restart_token(":::".to_string())
9821            .build();
9822        let mut cmd = SpecCommand::builder().name("test").build();
9823        cmd.subcommands.insert("run".to_string(), run_cmd);
9824
9825        let spec = Spec {
9826            name: "test".to_string(),
9827            bin: "test".to_string(),
9828            cmd,
9829            ..Default::default()
9830        };
9831
9832        // "test run task1 ::: task2" - should end up with task2 as the arg
9833        let input = vec![
9834            "test".to_string(),
9835            "run".to_string(),
9836            "task1".to_string(),
9837            ":::".to_string(),
9838            "task2".to_string(),
9839        ];
9840        let parsed = parse(&spec, &input).unwrap();
9841
9842        // After restart, args were cleared and task2 was parsed
9843        assert_eq!(parsed.args.len(), 1);
9844        let value = parsed.args.values().next().unwrap();
9845        assert_eq!(value.to_string(), "task2");
9846    }
9847
9848    #[test]
9849    fn test_restart_token_multiple() {
9850        // Test multiple restart tokens
9851        let run_cmd = SpecCommand::builder()
9852            .name("run")
9853            .arg(SpecArg::builder().name("task").build())
9854            .restart_token(":::".to_string())
9855            .build();
9856        let mut cmd = SpecCommand::builder().name("test").build();
9857        cmd.subcommands.insert("run".to_string(), run_cmd);
9858
9859        let spec = Spec {
9860            name: "test".to_string(),
9861            bin: "test".to_string(),
9862            cmd,
9863            ..Default::default()
9864        };
9865
9866        // "test run task1 ::: task2 ::: task3" - should end up with task3 as the arg
9867        let input = vec![
9868            "test".to_string(),
9869            "run".to_string(),
9870            "task1".to_string(),
9871            ":::".to_string(),
9872            "task2".to_string(),
9873            ":::".to_string(),
9874            "task3".to_string(),
9875        ];
9876        let parsed = parse(&spec, &input).unwrap();
9877
9878        // After multiple restarts, args were cleared and task3 was parsed
9879        assert_eq!(parsed.args.len(), 1);
9880        let value = parsed.args.values().next().unwrap();
9881        assert_eq!(value.to_string(), "task3");
9882    }
9883
9884    #[test]
9885    fn test_restart_token_clears_flag_awaiting_value() {
9886        // Test that restart_token clears pending flag values
9887        let run_cmd = SpecCommand::builder()
9888            .name("run")
9889            .arg(SpecArg::builder().name("task").build())
9890            .flag(
9891                SpecFlag::builder()
9892                    .name("jobs")
9893                    .long("jobs")
9894                    .arg(SpecArg::builder().name("count").build())
9895                    .build(),
9896            )
9897            .restart_token(":::".to_string())
9898            .build();
9899        let mut cmd = SpecCommand::builder().name("test").build();
9900        cmd.subcommands.insert("run".to_string(), run_cmd);
9901
9902        let spec = Spec {
9903            name: "test".to_string(),
9904            bin: "test".to_string(),
9905            cmd,
9906            ..Default::default()
9907        };
9908
9909        // "test run task1 --jobs ::: task2" - task2 should be an arg, not a flag value
9910        let input = vec![
9911            "test".to_string(),
9912            "run".to_string(),
9913            "task1".to_string(),
9914            "--jobs".to_string(),
9915            ":::".to_string(),
9916            "task2".to_string(),
9917        ];
9918        let parsed = parse(&spec, &input).unwrap();
9919
9920        // task2 should be parsed as the task arg, not as --jobs value
9921        assert_eq!(parsed.args.len(), 1);
9922        let value = parsed.args.values().next().unwrap();
9923        assert_eq!(value.to_string(), "task2");
9924        // --jobs should not have a value
9925        assert!(parsed.flag_awaiting_value.is_empty());
9926    }
9927
9928    #[test]
9929    fn test_restart_token_resets_double_dash() {
9930        // Test that restart_token resets the -- separator effect
9931        let run_cmd = SpecCommand::builder()
9932            .name("run")
9933            .arg(SpecArg::builder().name("task").build())
9934            .arg(SpecArg::builder().name("extra_args").var(true).build())
9935            .flag(SpecFlag::builder().name("verbose").long("verbose").build())
9936            .restart_token(":::".to_string())
9937            .build();
9938        let mut cmd = SpecCommand::builder().name("test").build();
9939        cmd.subcommands.insert("run".to_string(), run_cmd);
9940
9941        let spec = Spec {
9942            name: "test".to_string(),
9943            bin: "test".to_string(),
9944            cmd,
9945            ..Default::default()
9946        };
9947
9948        // "test run task1 -- extra ::: --verbose task2" - --verbose should be a flag after :::
9949        let input = vec![
9950            "test".to_string(),
9951            "run".to_string(),
9952            "task1".to_string(),
9953            "--".to_string(),
9954            "extra".to_string(),
9955            ":::".to_string(),
9956            "--verbose".to_string(),
9957            "task2".to_string(),
9958        ];
9959        let parsed = parse(&spec, &input).unwrap();
9960
9961        // --verbose should be parsed as a flag (not an arg) after the restart
9962        assert!(parsed.flags.keys().any(|f| f.name == "verbose"));
9963        // task2 should be the arg after restart
9964        let task_arg = parsed.args.keys().find(|a| a.name == "task").unwrap();
9965        let value = parsed.args.get(task_arg).unwrap();
9966        assert_eq!(value.to_string(), "task2");
9967    }
9968
9969    #[test]
9970    fn test_double_dashes_without_preserve() {
9971        // Only the first `--` is a separator; a later one is a value, because flag
9972        // parsing has already stopped and there is nothing left for it to do.
9973        // `preserve` is about the *first* one — see the test below, where none is
9974        // consumed at all.
9975        let run_cmd = SpecCommand::builder()
9976            .name("run")
9977            .arg(SpecArg::builder().name("args").var(true).build())
9978            .build();
9979        let mut cmd = SpecCommand::builder().name("test").build();
9980        cmd.subcommands.insert("run".to_string(), run_cmd);
9981
9982        let spec = Spec {
9983            name: "test".to_string(),
9984            bin: "test".to_string(),
9985            cmd,
9986            ..Default::default()
9987        };
9988
9989        // "test run arg1 -- arg2 -- arg3": the first separates, the second is a value
9990        let input = vec![
9991            "test".to_string(),
9992            "run".to_string(),
9993            "arg1".to_string(),
9994            "--".to_string(),
9995            "arg2".to_string(),
9996            "--".to_string(),
9997            "arg3".to_string(),
9998        ];
9999        let parsed = parse(&spec, &input).unwrap();
10000
10001        let args_arg = parsed.args.keys().find(|a| a.name == "args").unwrap();
10002        let value = parsed.args.get(args_arg).unwrap();
10003        assert_eq!(value.to_string(), "arg1 arg2 -- arg3");
10004    }
10005
10006    #[test]
10007    fn test_double_dashes_with_preserve() {
10008        // Test that variadic args WITH `preserve` keep all double dashes
10009        let run_cmd = SpecCommand::builder()
10010            .name("run")
10011            .arg(
10012                SpecArg::builder()
10013                    .name("args")
10014                    .var(true)
10015                    .double_dash(SpecDoubleDashChoices::Preserve)
10016                    .build(),
10017            )
10018            .build();
10019        let mut cmd = SpecCommand::builder().name("test").build();
10020        cmd.subcommands.insert("run".to_string(), run_cmd);
10021
10022        let spec = Spec {
10023            name: "test".to_string(),
10024            bin: "test".to_string(),
10025            cmd,
10026            ..Default::default()
10027        };
10028
10029        // "test run arg1 -- arg2 -- arg3" - all double dashes should be preserved
10030        let input = vec![
10031            "test".to_string(),
10032            "run".to_string(),
10033            "arg1".to_string(),
10034            "--".to_string(),
10035            "arg2".to_string(),
10036            "--".to_string(),
10037            "arg3".to_string(),
10038        ];
10039        let parsed = parse(&spec, &input).unwrap();
10040
10041        let args_arg = parsed.args.keys().find(|a| a.name == "args").unwrap();
10042        let value = parsed.args.get(args_arg).unwrap();
10043        assert_eq!(value.to_string(), "arg1 -- arg2 -- arg3");
10044    }
10045
10046    #[test]
10047    fn test_double_dashes_with_preserve_only_dashes() {
10048        // Test that variadic args WITH `preserve` keep all double dashes even
10049        // if the values are just double dashes
10050        let run_cmd = SpecCommand::builder()
10051            .name("run")
10052            .arg(
10053                SpecArg::builder()
10054                    .name("args")
10055                    .var(true)
10056                    .double_dash(SpecDoubleDashChoices::Preserve)
10057                    .build(),
10058            )
10059            .build();
10060        let mut cmd = SpecCommand::builder().name("test").build();
10061        cmd.subcommands.insert("run".to_string(), run_cmd);
10062
10063        let spec = Spec {
10064            name: "test".to_string(),
10065            bin: "test".to_string(),
10066            cmd,
10067            ..Default::default()
10068        };
10069
10070        // "test run -- --" - all double dashes should be preserved
10071        let input = vec![
10072            "test".to_string(),
10073            "run".to_string(),
10074            "--".to_string(),
10075            "--".to_string(),
10076        ];
10077        let parsed = parse(&spec, &input).unwrap();
10078
10079        let args_arg = parsed.args.keys().find(|a| a.name == "args").unwrap();
10080        let value = parsed.args.get(args_arg).unwrap();
10081        assert_eq!(value.to_string(), "-- --");
10082    }
10083
10084    #[test]
10085    fn test_double_dashes_with_preserve_multiple_args() {
10086        // Test with multiple args where only the second has has `preserve`
10087        let run_cmd = SpecCommand::builder()
10088            .name("run")
10089            .arg(SpecArg::builder().name("task").build())
10090            .arg(
10091                SpecArg::builder()
10092                    .name("extra_args")
10093                    .var(true)
10094                    .double_dash(SpecDoubleDashChoices::Preserve)
10095                    .build(),
10096            )
10097            .build();
10098        let mut cmd = SpecCommand::builder().name("test").build();
10099        cmd.subcommands.insert("run".to_string(), run_cmd);
10100
10101        let spec = Spec {
10102            name: "test".to_string(),
10103            bin: "test".to_string(),
10104            cmd,
10105            ..Default::default()
10106        };
10107
10108        // The first arg "task1" is captured normally
10109        // Then extra_args with `preserve` captures everything, including the "--" tokens
10110        let input = vec![
10111            "test".to_string(),
10112            "run".to_string(),
10113            "task1".to_string(),
10114            "--".to_string(),
10115            "arg1".to_string(),
10116            "--".to_string(),
10117            "--foo".to_string(),
10118        ];
10119        let parsed = parse(&spec, &input).unwrap();
10120
10121        let task_arg = parsed.args.keys().find(|a| a.name == "task").unwrap();
10122        let task_value = parsed.args.get(task_arg).unwrap();
10123        assert_eq!(task_value.to_string(), "task1");
10124
10125        let extra_arg = parsed.args.keys().find(|a| a.name == "extra_args").unwrap();
10126        let extra_value = parsed.args.get(extra_arg).unwrap();
10127        assert_eq!(extra_value.to_string(), "-- arg1 -- --foo");
10128    }
10129
10130    fn spec_with_args(args: impl IntoIterator<Item = SpecArg>) -> Spec {
10131        let cmd = SpecCommand::builder().name("test").args(args).build();
10132        Spec {
10133            name: "test".to_string(),
10134            bin: "test".to_string(),
10135            cmd,
10136            ..Default::default()
10137        }
10138    }
10139
10140    fn arg_value(parsed: &ParseOutput, name: &str) -> String {
10141        let arg = parsed
10142            .args
10143            .keys()
10144            .find(|a| a.name == name)
10145            .unwrap_or_else(|| panic!("expected arg {name} to be parsed"));
10146        parsed.args.get(arg).unwrap().to_string()
10147    }
10148
10149    fn required_arg(name: &str) -> SpecArg {
10150        SpecArg::builder()
10151            .name(name)
10152            .var(true)
10153            .required(false)
10154            .double_dash(SpecDoubleDashChoices::Required)
10155            .build()
10156    }
10157
10158    #[test]
10159    fn test_double_dash_required_reports_error_once_for_variadic() {
10160        // A variadic arg is offered every remaining word, but the mistake is one mistake.
10161        let spec = spec_with_args([required_arg("files")]);
10162
10163        let parsed = parse_partial(&spec, &input(&["test", "a", "b", "c"])).unwrap();
10164
10165        assert!(parsed.args.is_empty());
10166        assert_eq!(parsed.errors.len(), 1);
10167        assert!(
10168            matches!(&parsed.errors[0], UsageErr::ArgRequiresDoubleDash(name) if name == "files")
10169        );
10170    }
10171
10172    #[test]
10173    fn test_double_dash_required_suppresses_missing_arg() {
10174        // The arg is never filled, so the end-of-parse check would also call it missing.
10175        let spec = spec_with_args([SpecArg::builder()
10176            .name("file")
10177            .required(true)
10178            .double_dash(SpecDoubleDashChoices::Required)
10179            .build()]);
10180
10181        let parsed = parse_partial(&spec, &input(&["test", "x"])).unwrap();
10182
10183        assert_eq!(parsed.errors.len(), 1);
10184        assert!(matches!(
10185            &parsed.errors[0],
10186            UsageErr::ArgRequiresDoubleDash(_)
10187        ));
10188        // The cursor stays put, so a completion keeps offering the same arg.
10189        assert_eq!(
10190            parsed.next_arg.as_ref().map(|a| a.name.as_str()),
10191            Some("file")
10192        );
10193        assert!(!parsed.double_dash_seen);
10194    }
10195
10196    #[test]
10197    fn test_double_dash_routes_to_required_arg() {
10198        // Everything after `--` belongs to the arg that requires it, even though the greedy
10199        // variadic before it would otherwise swallow the rest (clap's `Arg::last(true)`).
10200        let spec = spec_with_args([
10201            SpecArg::builder()
10202                .name("tool")
10203                .var(true)
10204                .required(false)
10205                .build(),
10206            required_arg("command"),
10207        ]);
10208
10209        let parsed = parse(&spec, &input(&["test", "node@20", "--", "node", "app.js"])).unwrap();
10210
10211        assert_eq!(arg_value(&parsed, "tool"), "node@20");
10212        assert_eq!(arg_value(&parsed, "command"), "node app.js");
10213        assert!(parsed.double_dash_seen);
10214    }
10215
10216    #[test]
10217    fn test_double_dash_routes_with_gap_reports_missing_arg() {
10218        // Jumping the cursor leaves `tool` empty even though `command` is filled, so the
10219        // "is it filled?" check cannot be a count of how many args were filled.
10220        let spec = spec_with_args([
10221            SpecArg::builder()
10222                .name("tool")
10223                .var(true)
10224                .required(true)
10225                .build(),
10226            required_arg("command"),
10227        ]);
10228
10229        let parsed = parse_partial(&spec, &input(&["test", "--", "ls"])).unwrap();
10230
10231        assert_eq!(arg_value(&parsed, "command"), "ls");
10232        assert!(parsed.args.keys().all(|a| a.name != "tool"));
10233        assert!(
10234            parsed
10235                .errors
10236                .iter()
10237                .any(|e| matches!(e, UsageErr::MissingArg(name) if name == "tool"))
10238        );
10239    }
10240
10241    #[test]
10242    fn test_double_dash_gap_applies_defaults() {
10243        // Same gap, seen from `Parser::parse`: the skipped arg still gets its default.
10244        let spec = spec_with_args([
10245            SpecArg::builder()
10246                .name("tool")
10247                .var(true)
10248                .required(false)
10249                .default_value("node@20")
10250                .build(),
10251            required_arg("command"),
10252        ]);
10253
10254        let parsed = parse(&spec, &input(&["test", "--", "ls"])).unwrap();
10255
10256        assert_eq!(arg_value(&parsed, "command"), "ls");
10257        assert_eq!(arg_value(&parsed, "tool"), "node@20");
10258    }
10259
10260    fn spec_with_restart_token_and_required_arg() -> Spec {
10261        let run_cmd = SpecCommand::builder()
10262            .name("run")
10263            .arg(SpecArg::builder().name("task").build())
10264            .arg(required_arg("run_args"))
10265            .restart_token(":::".to_string())
10266            .build();
10267        let mut cmd = SpecCommand::builder().name("test").build();
10268        cmd.subcommands.insert("run".to_string(), run_cmd);
10269        Spec {
10270            name: "test".to_string(),
10271            bin: "test".to_string(),
10272            cmd,
10273            ..Default::default()
10274        }
10275    }
10276
10277    #[test]
10278    fn test_double_dash_required_restart_token_resets_separator() {
10279        // The `--` before `:::` belongs to the previous invocation only.
10280        let spec = spec_with_restart_token_and_required_arg();
10281
10282        let parsed = parse_partial(
10283            &spec,
10284            &input(&["test", "run", "task1", "--", "a", ":::", "task2", "b"]),
10285        )
10286        .unwrap();
10287
10288        assert_eq!(arg_value(&parsed, "task"), "task2");
10289        assert!(parsed.args.keys().all(|a| a.name != "run_args"));
10290        // Reported once even though the arg was violated after already succeeding once.
10291        assert_eq!(
10292            parsed
10293                .errors
10294                .iter()
10295                .filter(|e| matches!(e, UsageErr::ArgRequiresDoubleDash(_)))
10296                .count(),
10297            1
10298        );
10299    }
10300
10301    #[test]
10302    fn test_double_dash_required_restart_token_accepts_new_separator() {
10303        let spec = spec_with_restart_token_and_required_arg();
10304
10305        let parsed = parse(
10306            &spec,
10307            &input(&["test", "run", "task1", "--", "a", ":::", "task2", "--", "c"]),
10308        )
10309        .unwrap();
10310
10311        assert_eq!(arg_value(&parsed, "task"), "task2");
10312        assert_eq!(arg_value(&parsed, "run_args"), "c");
10313    }
10314
10315    #[test]
10316    fn test_double_dash_preserve_is_not_a_separator() {
10317        // A `--` that `preserve` keeps is a *value* of that arg, so it must not unlock the
10318        // arg that requires a separator. Deliberate: one token cannot be both.
10319        let spec = spec_with_args([
10320            SpecArg::builder()
10321                .name("kept")
10322                .var(true)
10323                .var_max(1)
10324                .required(false)
10325                .double_dash(SpecDoubleDashChoices::Preserve)
10326                .build(),
10327            required_arg("rest"),
10328        ]);
10329
10330        let parsed = parse_partial(&spec, &input(&["test", "--", "x"])).unwrap();
10331
10332        assert_eq!(arg_value(&parsed, "kept"), "--");
10333        assert!(parsed.args.keys().all(|a| a.name != "rest"));
10334        assert!(!parsed.double_dash_seen);
10335        assert_eq!(parsed.errors.len(), 1);
10336    }
10337
10338    #[test]
10339    fn test_double_dash_required_does_not_bail_in_parse_partial() {
10340        // Completions parse half-typed command lines; they must still get a result.
10341        let spec = spec_with_args([required_arg("file")]);
10342
10343        assert!(parse_partial(&spec, &input(&["test", "x"])).is_ok());
10344        assert!(parse(&spec, &input(&["test", "x"])).is_err());
10345    }
10346
10347    #[test]
10348    fn test_double_dash_without_required_arg_does_not_move_cursor() {
10349        // Specs with no `double_dash="required"` arg are untouched by the jump.
10350        let spec = spec_with_args([
10351            SpecArg::builder().name("first").required(false).build(),
10352            SpecArg::builder().name("second").required(false).build(),
10353        ]);
10354
10355        let parsed = parse(&spec, &input(&["test", "--", "a", "b"])).unwrap();
10356
10357        assert_eq!(arg_value(&parsed, "first"), "a");
10358        assert_eq!(arg_value(&parsed, "second"), "b");
10359        assert!(parsed.next_arg.is_none());
10360    }
10361
10362    #[test]
10363    fn test_parser_with_custom_env_for_required_arg() {
10364        let spec = spec_with_arg(
10365            SpecArg::builder()
10366                .name("name")
10367                .env("NAME")
10368                .required(true)
10369                .build(),
10370        );
10371        // FIXME: Audit that the environment access only happens in single-threaded code.
10372        unsafe { std::env::remove_var("NAME") };
10373
10374        let parsed = parse_with_env(&spec, &["test"], &[("NAME", "john")])
10375            .expect("parse should succeed with custom env");
10376        assert_eq!(parsed.args.len(), 1);
10377        assert_eq!(first_string_value(&parsed), "john");
10378    }
10379
10380    #[test]
10381    fn test_parser_with_custom_env_for_required_flag() {
10382        let spec = spec_with_flag(
10383            SpecFlag::builder()
10384                .long("name")
10385                .env("NAME")
10386                .required(true)
10387                .arg(SpecArg::builder().name("name").build())
10388                .build(),
10389        );
10390        // FIXME: Audit that the environment access only happens in single-threaded code.
10391        unsafe { std::env::remove_var("NAME") };
10392
10393        let parsed = parse_with_env(&spec, &["test"], &[("NAME", "jane")])
10394            .expect("parse should succeed with custom env");
10395        assert_eq!(parsed.flags.len(), 1);
10396        assert_eq!(first_string_value(&parsed), "jane");
10397    }
10398
10399    #[test]
10400    fn test_flag_environment_fallbacks_preserve_declaration_order() {
10401        let spec = spec_with_flag(
10402            SpecFlag::builder()
10403                .long("name")
10404                .env("NAME")
10405                .env_fallback("OLD_NAME")
10406                .env_fallback("OLDER_NAME")
10407                .deprecated_env("DEPRECATED_NAME")
10408                .arg(SpecArg::builder().name("name").build())
10409                .build(),
10410        );
10411
10412        let parsed = parse_with_env(
10413            &spec,
10414            &["test"],
10415            &[
10416                ("NAME", "canonical"),
10417                ("OLD_NAME", "fallback"),
10418                ("DEPRECATED_NAME", "deprecated"),
10419            ],
10420        )
10421        .unwrap();
10422        assert_eq!(first_string_value(&parsed), "canonical");
10423
10424        let parsed = parse_with_env(
10425            &spec,
10426            &["test"],
10427            &[("OLDER_NAME", "older"), ("OLD_NAME", "old")],
10428        )
10429        .unwrap();
10430        assert_eq!(first_string_value(&parsed), "old");
10431
10432        let parsed =
10433            parse_with_env(&spec, &["test"], &[("DEPRECATED_NAME", "deprecated")]).unwrap();
10434        assert_eq!(first_string_value(&parsed), "deprecated");
10435    }
10436
10437    #[test]
10438    fn a_value_from_a_deprecated_alias_says_which_name_to_use() {
10439        let spec = spec_with_flag(
10440            SpecFlag::builder()
10441                .long("name")
10442                .env("NAME")
10443                .deprecated_env("DEPRECATED_NAME")
10444                .arg(SpecArg::builder().name("name").build())
10445                .build(),
10446        );
10447
10448        // The current name is not a deprecated one, and says nothing.
10449        let parsed = parse_with_env(&spec, &["test"], &[("NAME", "canonical")]).unwrap();
10450        assert!(parsed.warnings.is_empty(), "{:?}", parsed.warnings);
10451
10452        let parsed =
10453            parse_with_env(&spec, &["test"], &[("DEPRECATED_NAME", "deprecated")]).unwrap();
10454        assert_eq!(parsed.warnings.len(), 1, "{:?}", parsed.warnings);
10455        assert_eq!(
10456            parsed.warnings[0].kind,
10457            crate::warn::WarningKind::DeprecatedEnv
10458        );
10459        assert_eq!(parsed.warnings[0].name, "DEPRECATED_NAME");
10460        assert_eq!(parsed.warnings[0].replacement.as_deref(), Some("NAME"));
10461        // Reported, not printed, and the value still arrives.
10462        assert_eq!(first_string_value(&parsed), "deprecated");
10463    }
10464
10465    #[test]
10466    fn a_deprecated_flag_reports_only_when_it_was_used() {
10467        let spec = spec_with_flag(
10468            SpecFlag::builder()
10469                .long("output")
10470                .deprecated("use --out")
10471                .deprecated_remove_at("3.0.0")
10472                .arg(SpecArg::builder().name("output").build())
10473                .build(),
10474        );
10475
10476        let parsed = parse_with_env(&spec, &["test"], &[]).unwrap();
10477        assert!(parsed.warnings.is_empty(), "{:?}", parsed.warnings);
10478
10479        let parsed = parse_with_env(&spec, &["test", "--output", "a.txt"], &[]).unwrap();
10480        assert_eq!(parsed.warnings.len(), 1, "{:?}", parsed.warnings);
10481        assert_eq!(
10482            parsed.warnings[0].kind,
10483            crate::warn::WarningKind::DeprecatedFlag
10484        );
10485        // Named the way it was typed, dashes and all.
10486        assert_eq!(parsed.warnings[0].name, "--output");
10487        assert_eq!(parsed.warnings[0].remove_at.as_deref(), Some("3.0.0"));
10488        assert_eq!(
10489            parsed.warnings[0].render(),
10490            "warning: --output is deprecated, removed at 3.0.0: use --out\n",
10491        );
10492    }
10493
10494    #[test]
10495    fn a_milestone_the_spec_has_not_reached_stays_quiet() {
10496        let flag = SpecFlag::builder()
10497            .long("output")
10498            .deprecated("use --out")
10499            .deprecated_warn_at("9.0.0")
10500            .arg(SpecArg::builder().name("output").build())
10501            .build();
10502        let mut spec = spec_with_flag(flag);
10503        spec.version = Some("2.0.0".to_string());
10504
10505        let parsed = parse_with_env(&spec, &["test", "--output", "a.txt"], &[]).unwrap();
10506        assert!(parsed.warnings.is_empty(), "{:?}", parsed.warnings);
10507
10508        // And once the CLI is the release that was named, it speaks up.
10509        spec.version = Some("9.0.0".to_string());
10510        let parsed = parse_with_env(&spec, &["test", "--output", "a.txt"], &[]).unwrap();
10511        assert_eq!(parsed.warnings.len(), 1, "{:?}", parsed.warnings);
10512    }
10513
10514    #[test]
10515    fn test_parser_with_custom_env_still_fails_when_missing() {
10516        let spec = spec_with_arg(
10517            SpecArg::builder()
10518                .name("name")
10519                .env("NAME")
10520                .required(true)
10521                .build(),
10522        );
10523        // FIXME: Audit that the environment access only happens in single-threaded code.
10524        unsafe { std::env::remove_var("NAME") };
10525        assert!(parse_with_env(&spec, &["test"], &[]).is_err());
10526    }
10527
10528    #[test]
10529    fn test_parser_does_not_treat_env_choice_value_as_help() {
10530        let spec = spec_with_arg(
10531            SpecArg::builder()
10532                .name("env")
10533                .env("CURRENT_ENV")
10534                .choices(["dev", "staging"])
10535                .required(false)
10536                .build(),
10537        );
10538
10539        assert_parse_err(
10540            parse_with_env(&spec, &["test"], &[("CURRENT_ENV", "--help")]),
10541            "Invalid choice for arg env: --help, expected one of dev, staging",
10542        );
10543    }
10544
10545    #[test]
10546    fn test_parser_does_not_treat_default_choice_value_as_help() {
10547        let spec = spec_with_flag(
10548            SpecFlag::builder()
10549                .long("env")
10550                .arg(
10551                    SpecArg::builder()
10552                        .name("env")
10553                        .choices(["dev", "staging"])
10554                        .build(),
10555                )
10556                .default_value("--help")
10557                .build(),
10558        );
10559
10560        assert_parse_err(
10561            parse_with_env(&spec, &["test"], &[]),
10562            "Invalid choice for option env: --help, expected one of dev, staging",
10563        );
10564    }
10565
10566    /// argv as `parse` wants it, program name included.
10567    fn words(of: &[&str]) -> Vec<String> {
10568        of.iter().map(|s| s.to_string()).collect()
10569    }
10570
10571    #[test]
10572    fn a_command_that_needs_a_subcommand_says_so() {
10573        // The spec has carried `subcommand_required` since the derive needed it, and this parser
10574        // never read it — so `mise generate`, which declares it, parsed as a complete
10575        // invocation while usage-argv and clap both refused. Found by the differential fuzzer.
10576        let spec: Spec = r#"
10577name "ex"
10578bin "ex"
10579cmd "gen" subcommand_required=#true {
10580    cmd "two" {}
10581    cmd "one" {}
10582    cmd "secret" hide=#true {}
10583    alias "g"
10584}
10585cmd "open" {
10586    cmd "sub" {}
10587}
10588"#
10589        .parse()
10590        .unwrap();
10591
10592        let err = parse(&spec, &words(&["ex", "gen"])).unwrap_err();
10593        // Sorted, so the message does not depend on map order; hidden commands left out,
10594        // because a message telling someone to type a hidden name is worse than a vague one;
10595        // and the alias not listed beside the name it points at.
10596        assert_eq!(err.to_string(), "`gen` needs a subcommand: one of one, two");
10597
10598        // Reached through its alias, and still about the command rather than the spelling.
10599        let err = parse(&spec, &words(&["ex", "g"])).unwrap_err();
10600        assert!(err.to_string().starts_with("`gen` needs a subcommand"));
10601
10602        // Given one: fine.
10603        parse(&spec, &words(&["ex", "gen", "one"])).unwrap();
10604
10605        // And a command that has subcommands without declaring them required is untouched —
10606        // this is the half that keeps the check from being "any command with children".
10607        parse(&spec, &words(&["ex", "open"])).unwrap();
10608        parse(&spec, &words(&["ex", "open", "sub"])).unwrap();
10609    }
10610
10611    #[test]
10612    fn arg_required_else_help_observes_the_selected_commands_argv() {
10613        let spec: Spec = r#"
10614name "ex"
10615bin "ex"
10616flag "--verbose" global=#true
10617cmd "run" arg_required_else_help=#true {
10618    flag "--all"
10619}
10620"#
10621        .parse()
10622        .unwrap();
10623        let words = |items: &[&str]| items.iter().map(|s| (*s).to_string()).collect::<Vec<_>>();
10624
10625        let err = parse(&spec, &words(&["ex", "run"])).unwrap_err();
10626        assert!(err.to_string().contains("Usage: ex run"), "{err}");
10627
10628        // A global before the command belongs to the ancestor. It selected `run`, but did not
10629        // give `run` an argument of its own.
10630        let err = parse(&spec, &words(&["ex", "--verbose", "run"])).unwrap_err();
10631        assert!(err.to_string().contains("Usage: ex run"), "{err}");
10632
10633        parse(&spec, &words(&["ex", "run", "--all"])).expect("run received an argv token");
10634    }
10635
10636    #[test]
10637    fn empty_default_with_parent_flags_observes_child_argv() {
10638        let spec: Spec = r#"
10639name "ex"
10640bin "ex"
10641default_subcommand "run"
10642default_subcommand_on_empty #true
10643flag "--verbose" global=#true
10644cmd "run" arg_required_else_help=#true {}
10645"#
10646        .parse()
10647        .unwrap();
10648        let words = |items: &[&str]| items.iter().map(|s| (*s).to_string()).collect::<Vec<_>>();
10649        let err = parse(&spec, &words(&["ex", "--verbose"])).unwrap_err();
10650        assert!(err.to_string().contains("Usage: ex run"), "{err}");
10651    }
10652
10653    #[test]
10654    fn an_unmatched_word_is_forwarded_when_external_subcommand_is_set() {
10655        let spec: Spec = r#"
10656name "ex"
10657bin "ex"
10658unknown_flags "error"
10659external_subcommand #true
10660cmd "install"
10661flag "-v --verbose" global=#true
10662"#
10663        .parse()
10664        .unwrap();
10665
10666        let parsed = parse(&spec, &input(&["ex", "foo", "--help", "bar"])).unwrap();
10667        assert_eq!(
10668            parsed.external,
10669            Some(vec!["foo".into(), "--help".into(), "bar".into()])
10670        );
10671        assert!(parsed.flags.is_empty());
10672
10673        // Known subcommands still win.
10674        let parsed = parse(&spec, &input(&["ex", "install"])).unwrap();
10675        assert_eq!(parsed.cmd.name, "install");
10676        assert!(parsed.external.is_none());
10677
10678        // A global flag before the unmatched word still binds on the parent.
10679        let parsed = parse(&spec, &input(&["ex", "-v", "foo", "--verbose"])).unwrap();
10680        assert_eq!(
10681            parsed.external,
10682            Some(vec!["foo".into(), "--verbose".into()])
10683        );
10684        assert!(parsed.flags.keys().any(|flag| flag.name == "verbose"));
10685
10686        // An unknown flag on the parent is still an error, which is what clap does.
10687        assert!(parse(&spec, &input(&["ex", "--wat"])).is_err());
10688
10689        // A negative number is a value, not a flag, so it can be the unmatched word.
10690        // usage-argv already forwarded `-1`; Phase 1 used to treat every `starts_with('-')`
10691        // token as a flag and never reach the catch-all.
10692        let parsed = parse(&spec, &input(&["ex", "-1", "rest"])).unwrap();
10693        assert_eq!(parsed.external, Some(vec!["-1".into(), "rest".into()]));
10694    }
10695
10696    #[test]
10697    fn an_external_subcommand_satisfies_subcommand_required() {
10698        let mut spec: Spec = r#"
10699name "ex"
10700bin "ex"
10701external_subcommand #true
10702cmd "install"
10703"#
10704        .parse()
10705        .unwrap();
10706        spec.cmd.subcommand_required = true;
10707
10708        parse(&spec, &input(&["ex", "foo", "--help"])).unwrap();
10709        assert!(parse(&spec, &input(&["ex"])).is_err());
10710    }
10711
10712    #[test]
10713    fn a_default_subcommand_outranks_an_external_one() {
10714        let spec: Spec = r#"
10715name "ex"
10716bin "ex"
10717default_subcommand "run"
10718external_subcommand #true
10719cmd "run" {
10720    arg "[task]"
10721}
10722"#
10723        .parse()
10724        .unwrap();
10725
10726        let parsed = parse(&spec, &input(&["ex", "build"])).unwrap();
10727        assert_eq!(parsed.cmd.name, "run");
10728        assert!(parsed.external.is_none());
10729        assert_eq!(first_string_value(&parsed), "build");
10730    }
10731
10732    #[test]
10733    fn multicall_basename_strips_a_path_and_exe() {
10734        assert_eq!(multicall_basename("/usr/bin/ls"), "ls");
10735        assert_eq!(multicall_basename(r"C:\busybox\ls.exe"), "ls");
10736        assert_eq!(multicall_basename("LS.EXE"), "LS");
10737        assert_eq!(multicall_basename("busybox"), "busybox");
10738    }
10739
10740    #[test]
10741    fn a_multicall_applet_is_the_first_word() {
10742        let spec: Spec = r#"
10743name "busybox"
10744bin "busybox"
10745multicall #true
10746cmd "ls" {
10747    arg "[ARGS]" var=#true
10748}
10749cmd "cat"
10750"#
10751        .parse()
10752        .unwrap();
10753
10754        // A symlink: argv[0] is the applet.
10755        let parsed = parse(&spec, &input(&["/usr/bin/ls", "-l"])).unwrap();
10756        assert_eq!(parsed.cmd.name, "ls");
10757        match parsed.args.values().next() {
10758            Some(ParseValue::MultiString(values)) => assert_eq!(values, &["-l".to_string()]),
10759            other => panic!("expected ARGS to collect -l, got {other:?}"),
10760        }
10761
10762        // A dispatcher invocation still skips argv[0].
10763        let parsed = parse(&spec, &input(&["/usr/bin/busybox", "ls", "-l"])).unwrap();
10764        assert_eq!(parsed.cmd.name, "ls");
10765
10766        // Configured dispatcher values receive the same path and extension normalization.
10767        let mut configured = spec.clone();
10768        configured.name = "BusyBox".to_string();
10769        configured.bin = "/opt/bin/busybox.exe".to_string();
10770        let parsed = parse(&configured, &input(&["/usr/bin/busybox.exe", "ls", "-l"])).unwrap();
10771        assert_eq!(parsed.cmd.name, "ls");
10772
10773        // `.exe` is stripped so Windows and Unix agree.
10774        let parsed = parse(&spec, &input(&["ls.exe"])).unwrap();
10775        assert_eq!(parsed.cmd.name, "ls");
10776
10777        // Without the property, argv[0] is discarded as usual.
10778        let mut plain = spec.clone();
10779        plain.multicall = false;
10780        let parsed = parse(&plain, &input(&["/usr/bin/ls", "ls"])).unwrap();
10781        assert_eq!(parsed.cmd.name, "ls");
10782    }
10783
10784    #[test]
10785    fn a_multicall_unknown_applet_can_be_external() {
10786        let spec: Spec = r#"
10787name "busybox"
10788bin "busybox"
10789multicall #true
10790unknown_flags "error"
10791external_subcommand #true
10792cmd "ls"
10793"#
10794        .parse()
10795        .unwrap();
10796
10797        let parsed = parse(&spec, &input(&["/usr/bin/git", "--help"])).unwrap();
10798        assert_eq!(parsed.external, Some(vec!["git".into(), "--help".into()]));
10799
10800        let mut closed = spec.clone();
10801        closed.cmd.external_subcommand = false;
10802        assert!(parse(&closed, &input(&["wat"])).is_err());
10803    }
10804
10805    #[cfg(feature = "unstable_choices_env")]
10806    #[test]
10807    fn test_parser_arg_choices_from_custom_env() {
10808        let spec = spec_arg_choices_env("DEPLOY_ENVS");
10809
10810        let parsed =
10811            parse_with_env(&spec, &["test", "bar"], &[("DEPLOY_ENVS", "foo,bar baz")]).unwrap();
10812        assert_eq!(first_string_value(&parsed), "bar");
10813
10814        assert_parse_err(
10815            parse_with_env(&spec, &["test", "prod"], &[("DEPLOY_ENVS", "foo,bar baz")]),
10816            "Invalid choice for arg env: prod, expected one of foo, bar, baz",
10817        );
10818        assert_parse_err(
10819            parse_with_env(&spec, &["test", "prod"], &[]),
10820            "Invalid choice for arg env: prod, no choices resolved from env DEPLOY_ENVS",
10821        );
10822    }
10823
10824    #[cfg(feature = "unstable_choices_env")]
10825    #[test]
10826    fn test_parser_validates_flag_choices_from_custom_env() {
10827        let spec = spec_flag_choices_env("DEPLOY_ENVS");
10828        let parsed = parse_with_env(
10829            &spec,
10830            &["test", "--env", "baz"],
10831            &[("DEPLOY_ENVS", "foo,bar baz")],
10832        )
10833        .unwrap();
10834        assert_eq!(first_string_value(&parsed), "baz");
10835    }
10836
10837    #[cfg(feature = "unstable_choices_env")]
10838    #[test]
10839    fn test_parser_revalidates_env_and_default_values_against_choices_env() {
10840        let arg_env_spec = spec_with_arg(
10841            SpecArg::builder()
10842                .name("env")
10843                .env("CURRENT_ENV")
10844                .choices_env("DEPLOY_ENVS")
10845                .build(),
10846        );
10847        assert_parse_err(
10848            parse_with_env(
10849                &arg_env_spec,
10850                &["test"],
10851                &[("CURRENT_ENV", "prod"), ("DEPLOY_ENVS", "dev,staging")],
10852            ),
10853            "Invalid choice for arg env: prod, expected one of dev, staging",
10854        );
10855
10856        let flag_default_spec = spec_with_flag(
10857            SpecFlag::builder()
10858                .long("env")
10859                .arg(
10860                    SpecArg::builder()
10861                        .name("env")
10862                        .choices_env("DEPLOY_ENVS")
10863                        .build(),
10864                )
10865                .default_value("prod")
10866                .build(),
10867        );
10868        assert_parse_err(
10869            parse_with_env(
10870                &flag_default_spec,
10871                &["test"],
10872                &[("DEPLOY_ENVS", "dev,staging")],
10873            ),
10874            "Invalid choice for option env: prod, expected one of dev, staging",
10875        );
10876    }
10877
10878    #[test]
10879    fn test_variadic_arg_captures_unknown_flags_from_spec_string() {
10880        let spec: Spec = r#"
10881            flag "-v --verbose" var=#true
10882            arg "[database]" default="myapp_dev"
10883            arg "[args...]"
10884        "#
10885        .parse()
10886        .unwrap();
10887        let input: Vec<String> = vec!["test", "mydb", "--host", "localhost"]
10888            .into_iter()
10889            .map(String::from)
10890            .collect();
10891        let parsed = parse(&spec, &input).unwrap();
10892        let env = parsed.as_env();
10893        assert_eq!(env.get("usage_database").unwrap(), "mydb");
10894        assert_eq!(env.get("usage_args").unwrap(), "--host localhost");
10895    }
10896
10897    #[test]
10898    fn test_variadic_arg_captures_unknown_flags() {
10899        let cmd = SpecCommand::builder()
10900            .name("test")
10901            .flag(SpecFlag::builder().short('v').long("verbose").build())
10902            .arg(SpecArg::builder().name("database").required(false).build())
10903            .arg(
10904                SpecArg::builder()
10905                    .name("args")
10906                    .required(false)
10907                    .var(true)
10908                    .build(),
10909            )
10910            .build();
10911        let spec = Spec {
10912            name: "test".to_string(),
10913            bin: "test".to_string(),
10914            cmd,
10915            ..Default::default()
10916        };
10917
10918        // Unknown --host flag and its value should be captured by [args...]
10919        let input: Vec<String> = vec!["test", "mydb", "--host", "localhost"]
10920            .into_iter()
10921            .map(String::from)
10922            .collect();
10923        let parsed = parse(&spec, &input).unwrap();
10924        assert_eq!(parsed.args.len(), 2);
10925        let args_val = parsed
10926            .args
10927            .iter()
10928            .find(|(a, _)| a.name == "args")
10929            .unwrap()
10930            .1;
10931        match args_val {
10932            ParseValue::MultiString(v) => {
10933                assert_eq!(v, &vec!["--host".to_string(), "localhost".to_string()]);
10934            }
10935            _ => panic!("Expected MultiString, got {:?}", args_val),
10936        }
10937    }
10938
10939    #[test]
10940    fn test_variadic_arg_captures_unknown_flags_with_double_dash() {
10941        let cmd = SpecCommand::builder()
10942            .name("test")
10943            .flag(SpecFlag::builder().short('v').long("verbose").build())
10944            .arg(SpecArg::builder().name("database").required(false).build())
10945            .arg(
10946                SpecArg::builder()
10947                    .name("args")
10948                    .required(false)
10949                    .var(true)
10950                    .build(),
10951            )
10952            .build();
10953        let spec = Spec {
10954            name: "test".to_string(),
10955            bin: "test".to_string(),
10956            cmd,
10957            ..Default::default()
10958        };
10959
10960        // With explicit -- separator
10961        let input: Vec<String> = vec!["test", "--", "mydb", "--host", "localhost"]
10962            .into_iter()
10963            .map(String::from)
10964            .collect();
10965        let parsed = parse(&spec, &input).unwrap();
10966        assert_eq!(parsed.args.len(), 2);
10967        let args_val = parsed
10968            .args
10969            .iter()
10970            .find(|(a, _)| a.name == "args")
10971            .unwrap()
10972            .1;
10973        match args_val {
10974            ParseValue::MultiString(v) => {
10975                assert_eq!(v, &vec!["--host".to_string(), "localhost".to_string()]);
10976            }
10977            _ => panic!("Expected MultiString, got {:?}", args_val),
10978        }
10979    }
10980
10981    #[test]
10982    fn test_variadic_arg_unknown_flag_equals_value_not_split() {
10983        // Regression: --flag=value should be treated as a single positional token when
10984        // --flag is not a known spec flag, not split into "--flag=value" AND "value".
10985        let spec: Spec = r#"arg "[other_args]" var=#true"#.parse().unwrap();
10986
10987        // Single unknown --flag=value: must not produce a stray "3" positional.
10988        // as_env() shell-joins values, so "=" gets quoted.
10989        let input: Vec<String> = vec!["test", "--option=3"]
10990            .into_iter()
10991            .map(String::from)
10992            .collect();
10993        let parsed = parse(&spec, &input).unwrap();
10994        let env = parsed.as_env();
10995        assert_eq!(
10996            env.get("usage_other_args").map(String::as_str),
10997            Some("'--option=3'"),
10998            "expected a single --option=3 token, got {:?}",
10999            env.get("usage_other_args"),
11000        );
11001
11002        // Multiple unknown --flag=value args should each be kept intact
11003        let input2: Vec<String> = vec!["test", "--foo=bar", "--baz=qux"]
11004            .into_iter()
11005            .map(String::from)
11006            .collect();
11007        let parsed2 = parse(&spec, &input2).unwrap();
11008        let env2 = parsed2.as_env();
11009        assert_eq!(
11010            env2.get("usage_other_args").map(String::as_str),
11011            Some("'--foo=bar' '--baz=qux'"),
11012            "expected two intact tokens, got {:?}",
11013            env2.get("usage_other_args"),
11014        );
11015
11016        // Mix of plain positional args and unknown --flag=value tokens
11017        let input3: Vec<String> = vec!["test", "positional1", "--option=3", "positional2"]
11018            .into_iter()
11019            .map(String::from)
11020            .collect();
11021        let parsed3 = parse(&spec, &input3).unwrap();
11022        let env3 = parsed3.as_env();
11023        assert_eq!(
11024            env3.get("usage_other_args").map(String::as_str),
11025            Some("positional1 '--option=3' positional2"),
11026            "expected positional args and intact flag token, got {:?}",
11027            env3.get("usage_other_args"),
11028        );
11029    }
11030
11031    #[test]
11032    fn test_allow_hyphen_values_consumes_short_flag_collision() {
11033        let spec = r#"
11034flag "-d --working-dir <DIR>"
11035flag "-a --args <ARGS>" allow_hyphen_values=#true
11036"#
11037        .parse::<Spec>()
11038        .unwrap();
11039
11040        let parsed = parse(&spec, &input(&["test", "-a", "-destroy"])).unwrap();
11041
11042        assert_eq!(parsed.flags.len(), 1);
11043        assert_eq!(flag_string_value(&parsed, "args"), "-destroy");
11044    }
11045
11046    #[test]
11047    fn test_allow_hyphen_values_consumes_embedded_long_value() {
11048        let spec = r#"
11049flag "-d --working-dir <DIR>"
11050flag "-a --args <ARGS>" allow_hyphen_values=#true
11051"#
11052        .parse::<Spec>()
11053        .unwrap();
11054
11055        let parsed = parse(&spec, &input(&["test", "--args=-destroy"])).unwrap();
11056
11057        assert_eq!(parsed.flags.len(), 1);
11058        assert_eq!(flag_string_value(&parsed, "args"), "-destroy");
11059    }
11060
11061    #[test]
11062    fn test_allow_hyphen_values_takes_the_separator_as_its_value() {
11063        // The flag is declared to accept a token that looks like a flag, and `--` looks
11064        // like one, so it binds — which is what clap does with the same declaration.
11065        // Letting the separator arm run first consumed it and left the flag hungry, and
11066        // the flag then ate the word past it: `-a -- -x` bound `-x` with the `--` gone.
11067        let spec = r#"
11068flag "-a --args <ARGS>" allow_hyphen_values=#true
11069arg "[rest]..."
11070"#
11071        .parse::<Spec>()
11072        .unwrap();
11073
11074        let parsed = parse(&spec, &input(&["test", "-a", "--", "-x"])).unwrap();
11075
11076        assert_eq!(flag_string_value(&parsed, "args"), "--");
11077        let rest = parsed
11078            .args
11079            .values()
11080            .next()
11081            .expect("expected the word after the separator to reach the argument");
11082        assert_eq!(rest.to_string(), "-x");
11083    }
11084
11085    #[test]
11086    fn test_variadic_allow_hyphen_values_collects_after_a_hyphenated_first_value() {
11087        // Which token supplied the first value says nothing about how many the argument
11088        // takes, so collection carries on from a hyphenated one exactly as from a plain
11089        // one. It still stops at the next flag-like token, which is what keeps a second
11090        // occurrence of the flag from being eaten as a value.
11091        let spec = r#"
11092flag "-a --args <ARGS>..." allow_hyphen_values=#true
11093"#
11094        .parse::<Spec>()
11095        .unwrap();
11096
11097        let parsed = parse(&spec, &input(&["test", "-a", "-x", "b", "c"])).unwrap();
11098
11099        let flag = parsed
11100            .flags
11101            .keys()
11102            .find(|flag| flag.name == "args")
11103            .expect("expected args flag");
11104        match parsed.flags.get(flag).expect("expected args value") {
11105            ParseValue::MultiString(values) => assert_eq!(values, &["-x", "b", "c"]),
11106            other => panic!("expected a list of values, got {other:?}"),
11107        }
11108    }
11109
11110    #[test]
11111    fn test_variadic_allow_hyphen_values_consumes_repeated_flag_values() {
11112        let spec = r#"
11113flag "-a --args <ARGS>" var=#true allow_hyphen_values=#true
11114"#
11115        .parse::<Spec>()
11116        .unwrap();
11117
11118        let parsed = parse(&spec, &input(&["test", "-a", "-val1", "-a", "-val2"])).unwrap();
11119
11120        let flag = parsed
11121            .flags
11122            .keys()
11123            .find(|flag| flag.name == "args")
11124            .expect("expected args flag");
11125        let value = parsed.flags.get(flag).expect("expected args value");
11126        match value {
11127            ParseValue::MultiString(values) => {
11128                assert_eq!(values, &vec!["-val1".to_string(), "-val2".to_string()]);
11129            }
11130            _ => panic!("expected MultiString, got {value:?}"),
11131        }
11132    }
11133
11134    #[test]
11135    fn test_require_equals_accepts_attached_and_refuses_detached() {
11136        let spec = r#"
11137flag "--inspect <PORT>" require_equals=#true
11138"#
11139        .parse::<Spec>()
11140        .unwrap();
11141
11142        let parsed = parse(&spec, &input(&["test", "--inspect=9229"])).unwrap();
11143        assert_eq!(flag_string_value(&parsed, "inspect"), "9229");
11144
11145        let err = parse(&spec, &input(&["test", "--inspect", "9229"])).unwrap_err();
11146        let msg = format!("{err}");
11147        assert!(
11148            msg.contains("requires an argument") || msg.contains("inspect"),
11149            "detached value must be refused: {msg}"
11150        );
11151    }
11152
11153    #[test]
11154    fn boolean_flags_can_accept_attached_values_when_enabled() {
11155        let spec: Spec = r#"
11156name "ex"
11157bin "ex"
11158flag "--color" negate="--no-color" bool_value=#true
11159arg "[rest]"
11160"#
11161        .parse()
11162        .unwrap();
11163
11164        for (token, expected) in [
11165            ("--color", true),
11166            ("--color=true", true),
11167            ("--color=false", false),
11168            ("--no-color", false),
11169            ("--no-color=false", true),
11170        ] {
11171            let parsed = parse(&spec, &input(&["ex", token])).unwrap();
11172            assert!(
11173                matches!(
11174                    parsed.flags.get(&spec.cmd.flags[0]),
11175                    Some(ParseValue::Bool(value)) if *value == expected
11176                ),
11177                "{token}"
11178            );
11179        }
11180
11181        let parsed = parse(&spec, &input(&["ex", "--color=false", "word"])).unwrap();
11182        assert!(matches!(
11183            parsed.args.get(&spec.cmd.args[0]),
11184            Some(ParseValue::String(value)) if value == "word"
11185        ));
11186        let err = parse(&spec, &input(&["ex", "--color=maybe"])).unwrap_err();
11187        assert!(err.to_string().contains("expected `true` or `false`"));
11188
11189        let strict: Spec = r#"
11190name "ex"
11191bin "ex"
11192args_override_self #false
11193flag "--color" negate="--no-color" bool_value=#true
11194"#
11195        .parse()
11196        .unwrap();
11197        assert!(parse(&strict, &input(&["ex", "--color=false", "--color=true"])).is_err());
11198        let parsed = parse(
11199            &strict,
11200            &input(&["ex", "--color=false", "--no-color=false"]),
11201        )
11202        .unwrap();
11203        assert!(matches!(
11204            parsed.flags.get(&strict.cmd.flags[0]),
11205            Some(ParseValue::Bool(true))
11206        ));
11207    }
11208
11209    #[test]
11210    fn test_require_equals_refuses_a_detached_value_after_a_short_bundle() {
11211        let spec = r#"
11212flag "-a --all"
11213flag "-i --inspect <PORT>" require_equals=#true
11214"#
11215        .parse::<Spec>()
11216        .unwrap();
11217
11218        let err = parse(&spec, &input(&["test", "-ai", "9229"])).unwrap_err();
11219        let msg = format!("{err}");
11220        assert!(
11221            msg.contains("requires an argument") || msg.contains("inspect"),
11222            "bundled short must refuse the following word: {msg}"
11223        );
11224    }
11225
11226    #[test]
11227    fn test_default_missing_binds_when_the_value_is_left_off() {
11228        let spec = r#"
11229flag "-c --color <WHEN>" default_missing="always"
11230flag "-v --verbose"
11231"#
11232        .parse::<Spec>()
11233        .unwrap();
11234
11235        let parsed = parse(&spec, &input(&["test", "--color"])).unwrap();
11236        assert_eq!(flag_string_value(&parsed, "color"), "always");
11237
11238        let parsed = parse(&spec, &input(&["test", "--color=never"])).unwrap();
11239        assert_eq!(flag_string_value(&parsed, "color"), "never");
11240
11241        let parsed = parse(&spec, &input(&["test", "--color", "never"])).unwrap();
11242        assert_eq!(flag_string_value(&parsed, "color"), "never");
11243
11244        let parsed = parse(&spec, &input(&["test", "--color", "--verbose"])).unwrap();
11245        assert_eq!(flag_string_value(&parsed, "color"), "always");
11246        assert!(parsed.flags.keys().any(|f| f.name == "verbose"));
11247
11248        let parsed = parse(&spec, &input(&["test", "--color="])).unwrap();
11249        assert_eq!(flag_string_value(&parsed, "color"), "");
11250
11251        let parsed = parse(&spec, &input(&["test", "-cnever"])).unwrap();
11252        assert_eq!(flag_string_value(&parsed, "color"), "never");
11253
11254        let parsed = parse(&spec, &input(&["test", "-c", "-v"])).unwrap();
11255        assert_eq!(flag_string_value(&parsed, "color"), "always");
11256        assert!(parsed.flags.keys().any(|f| f.name == "verbose"));
11257    }
11258
11259    #[test]
11260    fn test_default_missing_requires_opt_in_for_detached_negative_flag_values() {
11261        let spec = r#"
11262flag "--apps <N>"
11263flag "--jobs <N>" default_missing="default missing"
11264flag "--kids <N>" default_missing="default missing" allow_negative_numbers=#true
11265"#
11266        .parse::<Spec>()
11267        .unwrap();
11268
11269        let parsed = parse(&spec, &input(&["test", "--apps", "-1"])).unwrap();
11270        assert_eq!(flag_string_value(&parsed, "apps"), "-1");
11271
11272        let err = parse(&spec, &input(&["test", "--jobs", "-1"])).unwrap_err();
11273        assert!(
11274            err.to_string().contains("unexpected word: -1"),
11275            "default_missing must keep an unopted negative value separate: {err}"
11276        );
11277
11278        let parsed = parse(&spec, &input(&["test", "--kids", "-1"])).unwrap();
11279        assert_eq!(flag_string_value(&parsed, "kids"), "-1");
11280
11281        let external_spec = r#"
11282external_subcommand #true
11283flag "--apps <N>"
11284"#
11285        .parse::<Spec>()
11286        .unwrap();
11287        let parsed = parse(&external_spec, &input(&["test", "--apps", "-1"])).unwrap();
11288        assert_eq!(flag_string_value(&parsed, "apps"), "-1");
11289        assert!(parsed.external.is_none());
11290
11291        for words in [
11292            &["test", "--apps", "--jobs", "1"][..],
11293            &["test", "--apps", "--kids", "-1"][..],
11294        ] {
11295            let err = parse(&spec, &input(words)).unwrap_err();
11296            let message = err.to_string();
11297            assert!(
11298                message.contains("--apps") && message.contains("requires an argument"),
11299                "the earlier flag must report its missing value for {words:?}: {message}"
11300            );
11301        }
11302    }
11303
11304    #[test]
11305    fn test_optional_flag_value_preserves_bare_and_explicit_empty_forms() {
11306        let spec = r#"
11307flag "--bump [LEVEL]" value_optional=#true
11308flag "--verbose"
11309arg "[FILE]"
11310"#
11311        .parse::<Spec>()
11312        .unwrap();
11313
11314        let absent = parse(&spec, &input(&["test"])).unwrap();
11315        assert!(!absent.flags.keys().any(|flag| flag.name == "bump"));
11316
11317        let bare = parse(&spec, &input(&["test", "--bump", "--verbose", "file.txt"])).unwrap();
11318        let bump = bare
11319            .flags
11320            .iter()
11321            .find(|(flag, _)| flag.name == "bump")
11322            .map(|(_, value)| value)
11323            .unwrap();
11324        assert!(matches!(bump, ParseValue::MultiString(values) if values.is_empty()));
11325        assert!(bare.flags.keys().any(|flag| flag.name == "verbose"));
11326        assert_eq!(arg_value(&bare, "FILE"), "file.txt");
11327
11328        let explicit = parse(&spec, &input(&["test", "--bump=", "file.txt"])).unwrap();
11329        assert_eq!(flag_string_value(&explicit, "bump"), "");
11330
11331        let corrected = parse(
11332            &spec,
11333            &input(&["test", "--bump=2", "--bump", "--verbose", "file.txt"]),
11334        )
11335        .unwrap();
11336        let bump = corrected
11337            .flags
11338            .iter()
11339            .find(|(flag, _)| flag.name == "bump")
11340            .map(|(_, value)| value)
11341            .unwrap();
11342        assert!(matches!(bump, ParseValue::MultiString(values) if values.is_empty()));
11343
11344        let collecting = r#"
11345flag "--tag [TAG]..." value_optional=#true
11346flag "--verbose"
11347"#
11348        .parse::<Spec>()
11349        .unwrap();
11350        let valued = parse(
11351            &collecting,
11352            &input(&["test", "--tag", "one", "two", "--verbose"]),
11353        )
11354        .unwrap();
11355        let tag = valued
11356            .flags
11357            .iter()
11358            .find(|(flag, _)| flag.name == "tag")
11359            .map(|(_, value)| value)
11360            .unwrap();
11361        assert!(matches!(tag, ParseValue::MultiString(values) if values == &["one", "two"]));
11362    }
11363
11364    #[test]
11365    fn test_repeatable_bare_optional_values_count_each_occurrence() {
11366        let spec = r#"
11367flag "--tag [TAG]" var=#true var_min=2 var_max=2 value_optional=#true
11368"#
11369        .parse::<Spec>()
11370        .unwrap();
11371
11372        let parsed = parse(&spec, &input(&["test", "--tag", "--tag"])).unwrap();
11373        let tag = parsed
11374            .flags
11375            .iter()
11376            .find(|(flag, _)| flag.name == "tag")
11377            .map(|(_, value)| value)
11378            .unwrap();
11379        assert!(matches!(tag, ParseValue::MultiString(values) if values == &["", ""]));
11380
11381        assert!(parse(&spec, &input(&["test", "--tag"])).is_err());
11382        assert!(parse(&spec, &input(&["test", "--tag", "--tag", "--tag"])).is_err());
11383    }
11384
11385    #[test]
11386    fn test_repeatable_variadic_optional_values_do_not_gain_bare_occurrences() {
11387        let spec = r#"
11388flag "--tag [TAG]..." var=#true value_optional=#true
11389flag "--verbose"
11390"#
11391        .parse::<Spec>()
11392        .unwrap();
11393
11394        for argv in [
11395            &["test", "--tag", "one", "two"][..],
11396            &["test", "--tag", "one", "two", "--verbose"][..],
11397            &["test", "--tag", "one", "--tag", "two"][..],
11398        ] {
11399            let parsed = parse(&spec, &input(argv)).unwrap();
11400            let tag = parsed
11401                .flags
11402                .iter()
11403                .find(|(flag, _)| flag.name == "tag")
11404                .map(|(_, value)| value)
11405                .unwrap();
11406            assert!(
11407                matches!(tag, ParseValue::MultiString(values) if values == &["one", "two"]),
11408                "argv={argv:?}: {tag:?}"
11409            );
11410        }
11411
11412        let bare = parse(&spec, &input(&["test", "--tag", "--verbose"])).unwrap();
11413        let tag = bare
11414            .flags
11415            .iter()
11416            .find(|(flag, _)| flag.name == "tag")
11417            .map(|(_, value)| value)
11418            .unwrap();
11419        assert!(matches!(tag, ParseValue::MultiString(values) if values == &[""]));
11420    }
11421
11422    #[test]
11423    fn test_default_missing_with_require_equals_refuses_the_following_word() {
11424        let spec = r#"
11425flag "--inspect <PORT>" require_equals=#true default_missing="9229"
11426arg "[rest]"
11427"#
11428        .parse::<Spec>()
11429        .unwrap();
11430
11431        let parsed = parse(&spec, &input(&["test", "--inspect"])).unwrap();
11432        assert_eq!(flag_string_value(&parsed, "inspect"), "9229");
11433
11434        let parsed = parse(&spec, &input(&["test", "--inspect=1234"])).unwrap();
11435        assert_eq!(flag_string_value(&parsed, "inspect"), "1234");
11436
11437        // The following word is not the value; the missing value is, and 80 is a positional.
11438        let parsed = parse(&spec, &input(&["test", "--inspect", "80"])).unwrap();
11439        assert_eq!(flag_string_value(&parsed, "inspect"), "9229");
11440        assert_eq!(
11441            parsed
11442                .args
11443                .values()
11444                .next()
11445                .map(|v| v.to_string())
11446                .as_deref(),
11447            Some("80")
11448        );
11449
11450        let parsed = parse(&spec, &input(&["test", "--inspect="])).unwrap();
11451        assert_eq!(flag_string_value(&parsed, "inspect"), "");
11452    }
11453
11454    #[test]
11455    fn test_default_missing_must_be_a_choice() {
11456        let spec = r#"
11457flag "--color <WHEN>" default_missing="always" {
11458    choices "auto" "always" "never"
11459}
11460"#
11461        .parse::<Spec>()
11462        .unwrap();
11463
11464        let parsed = parse(&spec, &input(&["test", "--color"])).unwrap();
11465        assert_eq!(flag_string_value(&parsed, "color"), "always");
11466
11467        let parsed = parse(&spec, &input(&["test", "--color=never"])).unwrap();
11468        assert_eq!(flag_string_value(&parsed, "color"), "never");
11469
11470        let spec = r#"
11471flag "--color <WHEN>" default_missing="wat" {
11472    choices "auto" "always" "never"
11473}
11474"#
11475        .parse::<Spec>()
11476        .unwrap();
11477
11478        let err = parse(&spec, &input(&["test", "--color"])).unwrap_err();
11479        let msg = format!("{err}");
11480        assert!(
11481            msg.contains("Invalid choice for option color: wat"),
11482            "missing default has to pass choices the same way a typed value does: {msg}"
11483        );
11484
11485        let err = parse(&spec, &input(&["test", "--color=wat"])).unwrap_err();
11486        let msg = format!("{err}");
11487        assert!(
11488            msg.contains("Invalid choice for option color: wat"),
11489            "an attached value that is not a choice is still refused: {msg}"
11490        );
11491
11492        let spec = r#"
11493flag "--inspect <PORT>" require_equals=#true default_missing="wat" {
11494    choices "9229" "80"
11495}
11496arg "[rest]"
11497"#
11498        .parse::<Spec>()
11499        .unwrap();
11500
11501        let err = parse(&spec, &input(&["test", "--inspect", "80"])).unwrap_err();
11502        let msg = format!("{err}");
11503        assert!(
11504            msg.contains("Invalid choice for option inspect: wat"),
11505            "require_equals still binds the missing string, so the error is the choice: {msg}"
11506        );
11507    }
11508
11509    #[test]
11510    fn test_hyphen_values_still_start_short_flag_parsing() {
11511        let spec = r#"
11512flag "-d --working-dir <DIR>"
11513flag "-a --args <ARGS>"
11514"#
11515        .parse::<Spec>()
11516        .unwrap();
11517
11518        let err = parse(&spec, &input(&["test", "-a", "-destroy"])).unwrap_err();
11519        let message = err.to_string();
11520        assert!(
11521            message.contains("--args") && message.contains("requires an argument"),
11522            "the recognized -d must leave the earlier -a missing: {message}"
11523        );
11524    }
11525
11526    /// `available_flags` has to agree with what an actual parse accepts, since
11527    /// its whole reason to exist is answering that question without one.
11528    mod available_flags {
11529        use super::*;
11530
11531        fn spec() -> Spec {
11532            r#"
11533bin "test"
11534flag "-v --verbose" global=#true
11535flag "--raw" global=#true effect="write"
11536flag "--local-only"
11537cmd "run" {
11538    flag "-r --raw"
11539    flag "-w --watch"
11540    cmd "once"
11541}
11542"#
11543            .parse::<Spec>()
11544            .unwrap()
11545        }
11546
11547        fn chain<'a>(spec: &'a Spec, path: &[&str]) -> Vec<&'a SpecCommand> {
11548            let mut chain = vec![&spec.cmd];
11549            for segment in path {
11550                chain.push(chain.last().unwrap().find_subcommand(segment).unwrap());
11551            }
11552            chain
11553        }
11554
11555        fn names(spec: &Spec, path: &[&str]) -> Vec<String> {
11556            let mut names: Vec<_> = available_flags(&chain(spec, path))
11557                .iter()
11558                .map(|f| f.name.clone())
11559                .collect();
11560            names.sort();
11561            names
11562        }
11563
11564        #[test]
11565        fn an_empty_chain_yields_nothing() {
11566            assert!(available_flags(&[]).is_empty());
11567        }
11568
11569        #[test]
11570        fn the_root_gets_its_own_flags() {
11571            let spec = spec();
11572            assert_eq!(names(&spec, &[]), ["local-only", "raw", "verbose"]);
11573        }
11574
11575        #[test]
11576        fn a_subcommand_keeps_globals_and_drops_local_only_ancestors() {
11577            let spec = spec();
11578            assert_eq!(names(&spec, &["run"]), ["raw", "verbose", "watch"]);
11579        }
11580
11581        #[test]
11582        fn a_re_declared_global_is_listed_once() {
11583            // The merge can leave the long key on the merged flag and the short
11584            // key on the pre-merge one. Same flag; it must not be listed twice.
11585            let spec = r#"
11586bin "test"
11587flag "-y --yes" global=#true effect="write"
11588cmd "rm" {
11589    flag "-y --yes"
11590}
11591"#
11592            .parse::<Spec>()
11593            .unwrap();
11594            let flags = available_flags(&chain(&spec, &["rm"]));
11595            assert_eq!(flags.len(), 1, "{flags:?}");
11596            assert_eq!(flags[0].effect.map(|e| e.as_str()), Some("write"));
11597        }
11598
11599        #[test]
11600        fn a_re_declared_global_keeps_the_globals_declaration() {
11601            // `run` re-declares the long-only global `--raw` as `-r --raw`
11602            // without `global`. That is the same flag: the global's `effect`
11603            // survives, the orphan short is unioned in, and it stays global.
11604            let spec = spec();
11605            let flags = available_flags(&chain(&spec, &["run"]));
11606            let raw = flags.iter().find(|f| f.name == "raw").unwrap();
11607            assert!(raw.global);
11608            assert_eq!(raw.effect.map(|e| e.as_str()), Some("write"));
11609            assert_eq!(raw.short, ['r']);
11610        }
11611
11612        #[test]
11613        fn it_matches_what_a_parse_accepts() {
11614            // The invariant. If these ever disagree, one of them is lying to a
11615            // caller about which flags a command takes.
11616            let spec = spec();
11617            for path in [vec![], vec!["run"], vec!["run", "once"]] {
11618                let argv = std::iter::once("test".to_string())
11619                    .chain(path.iter().map(|s| s.to_string()))
11620                    .collect::<Vec<_>>();
11621                let parsed = parse_partial(&spec, &argv).unwrap();
11622
11623                let mut from_parse: Vec<_> = unique_flags(parsed.available_flags.values())
11624                    .map(|f| f.name.clone())
11625                    .collect();
11626                from_parse.sort();
11627                assert_eq!(names(&spec, &path), from_parse, "path {path:?}");
11628            }
11629        }
11630    }
11631
11632    // Provenance: which token bound what, and where a value came from when no token did.
11633
11634    /// Every role a token was given, rendered the way `Debug` renders it, so a test can
11635    /// assert on the whole picture rather than on one field at a time.
11636    fn roles(parsed: &ParseOutput, index: usize) -> Vec<String> {
11637        parsed
11638            .tokens
11639            .iter()
11640            .find(|token| token.index == index)
11641            .unwrap_or_else(|| panic!("no token at {index}"))
11642            .roles
11643            .iter()
11644            .map(render_role)
11645            .collect()
11646    }
11647
11648    fn origins(parsed: &ParseOutput, flag: &str) -> Vec<ValueOrigin> {
11649        parsed
11650            .flag_origins
11651            .iter()
11652            .find(|(f, _)| f.name == flag)
11653            .map(|(_, origins)| origins.clone())
11654            .unwrap_or_default()
11655    }
11656
11657    fn explain_with_env(spec: &Spec, words: &[&str], env: &[(&str, &str)]) -> ParseOutput {
11658        let env = env
11659            .iter()
11660            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
11661            .collect();
11662        Parser::new(spec)
11663            .with_env(env)
11664            .explain(&input(words))
11665            .unwrap()
11666    }
11667
11668    fn explain(spec: &Spec, words: &[&str]) -> ParseOutput {
11669        explain_with_env(spec, words, &[])
11670    }
11671
11672    #[test]
11673    fn an_attached_long_value_is_recorded_on_the_flag_token() {
11674        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--env <env>\"\n"
11675            .parse()
11676            .unwrap();
11677
11678        let parsed = explain(&spec, &["ex", "--env=prod"]);
11679
11680        assert_eq!(roles(&parsed, 0), ["program"]);
11681        assert_eq!(
11682            roles(&parsed, 1),
11683            ["flag env as --env", "value of env = [\"prod\"], attached"]
11684        );
11685        // This is jdx/mise discussion #8883: a hand-written scanner dropped the attached
11686        // form while the detached one worked, and nothing could show the difference.
11687        assert!(origins(&parsed, "env").is_empty(), "typed, so no fallback");
11688    }
11689
11690    #[test]
11691    fn a_detached_long_value_is_recorded_on_its_own_token() {
11692        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--env <env>\"\n"
11693            .parse()
11694            .unwrap();
11695
11696        let parsed = explain(&spec, &["ex", "--env", "prod"]);
11697
11698        assert_eq!(roles(&parsed, 1), ["flag env as --env"]);
11699        assert_eq!(roles(&parsed, 2), ["value of env = [\"prod\"]"]);
11700    }
11701
11702    #[test]
11703    fn a_short_bundle_is_attributed_to_the_bundle_token() {
11704        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"-a\"\nflag \"-b\"\nflag \"-j <n>\"\n"
11705            .parse()
11706            .unwrap();
11707
11708        let parsed = explain(&spec, &["ex", "-abj8"]);
11709
11710        // One word the caller wrote, four things it did — and the re-queued tails are
11711        // folded back onto it rather than appearing as tokens nobody typed.
11712        assert_eq!(
11713            roles(&parsed, 1),
11714            [
11715                "flag a as -a",
11716                "flag b as -b",
11717                "flag j as -j",
11718                "value of j = [\"8\"], attached",
11719            ]
11720        );
11721        assert_eq!(parsed.tokens.len(), 2);
11722    }
11723
11724    #[test]
11725    fn a_delimiter_splits_one_token_into_several_values() {
11726        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--tags <tags>...\" delimiter=\",\"\n"
11727            .parse()
11728            .unwrap();
11729
11730        let parsed = explain(&spec, &["ex", "--tags", "a,b,c"]);
11731
11732        assert_eq!(
11733            roles(&parsed, 2),
11734            ["value of tags = [\"a\", \"b\", \"c\"]"],
11735            "the values meant, not the word typed"
11736        );
11737    }
11738
11739    #[test]
11740    fn a_separator_and_the_words_after_it_are_distinguished() {
11741        let spec: Spec = "name \"ex\"\nbin \"ex\"\narg \"<src>\"\narg \"[raw]...\"\n"
11742            .parse()
11743            .unwrap();
11744
11745        let parsed = explain(&spec, &["ex", "a", "--", "-x"]);
11746
11747        assert_eq!(roles(&parsed, 1), ["arg src = [\"a\"]"]);
11748        assert_eq!(roles(&parsed, 2), ["separator"]);
11749        // Past the separator `-x` is data, not an unknown flag.
11750        assert_eq!(roles(&parsed, 3), ["arg raw = [\"-x\"]"]);
11751    }
11752
11753    #[test]
11754    fn a_second_separator_is_data() {
11755        let spec: Spec = "name \"ex\"\nbin \"ex\"\narg \"[raw]...\"\n"
11756            .parse()
11757            .unwrap();
11758
11759        let parsed = explain(&spec, &["ex", "--", "a", "--", "b"]);
11760
11761        assert_eq!(roles(&parsed, 1), ["separator"]);
11762        assert_eq!(roles(&parsed, 3), ["arg raw = [\"--\"]"]);
11763    }
11764
11765    #[test]
11766    fn an_unknown_flag_says_what_took_it() {
11767        let spec: Spec = "name \"ex\"\nbin \"ex\"\narg \"[rest]...\"\n"
11768            .parse()
11769            .unwrap();
11770
11771        let parsed = explain(&spec, &["ex", "--wat"]);
11772
11773        // The default is lax, so the word became data. Which is the useful thing to be
11774        // told: the alternative reading is "you have a typo".
11775        assert_eq!(roles(&parsed, 1), ["unknown flag, bound as rest"]);
11776    }
11777
11778    #[test]
11779    fn a_subcommand_word_is_not_a_positional() {
11780        let spec: Spec = "name \"ex\"\nbin \"ex\"\ncmd \"build\" {\n    arg \"<target>\"\n}\n"
11781            .parse()
11782            .unwrap();
11783
11784        let parsed = explain(&spec, &["ex", "build", "a"]);
11785
11786        assert_eq!(roles(&parsed, 1), ["subcommand build"]);
11787        assert_eq!(roles(&parsed, 2), ["arg target = [\"a\"]"]);
11788    }
11789
11790    #[test]
11791    fn a_multicall_applet_is_read_at_argv0() {
11792        let spec: Spec =
11793            "name \"box\"\nbin \"box\"\nmulticall #true\ncmd \"ls\" {\n    flag \"-l\"\n}\n"
11794                .parse()
11795                .unwrap();
11796
11797        let parsed = explain(&spec, &["/usr/bin/ls", "-l"]);
11798
11799        // argv[0] is both the program and the word that selected the applet, and the word
11800        // read there is not the word the caller wrote.
11801        assert_eq!(roles(&parsed, 0), ["program", "subcommand ls"]);
11802        assert!(parsed.tokens[0].synthesized);
11803        assert_eq!(parsed.tokens[0].word, "/usr/bin/ls");
11804    }
11805
11806    #[test]
11807    fn words_the_parse_never_reached_say_so() {
11808        let spec: Spec = "name \"ex\"\nbin \"ex\"\narg \"[rest]...\"\n"
11809            .parse()
11810            .unwrap();
11811
11812        let parsed = Parser::new(&spec)
11813            .explain(&input(&["ex", "--help", "a"]))
11814            .unwrap();
11815
11816        assert_eq!(roles(&parsed, 2), ["unread"]);
11817    }
11818
11819    #[test]
11820    fn an_env_origin_names_the_variable_that_fired() {
11821        let spec: Spec =
11822            "name \"ex\"\nbin \"ex\"\nflag \"--token <t>\" env=\"EX_TOKEN\" env_fallback=\"EX_TOKEN_OLD\"\n"
11823                .parse()
11824                .unwrap();
11825
11826        let primary = explain_with_env(&spec, &["ex"], &[("EX_TOKEN", "a")]);
11827        assert_eq!(
11828            origins(&primary, "token"),
11829            [ValueOrigin::Env("EX_TOKEN".to_string())]
11830        );
11831
11832        // The fallback firing is a different fact from the primary firing, and which one it
11833        // was is what says which declaration to delete.
11834        let fallback = explain_with_env(&spec, &["ex"], &[("EX_TOKEN_OLD", "b")]);
11835        assert_eq!(
11836            origins(&fallback, "token"),
11837            [ValueOrigin::Env("EX_TOKEN_OLD".to_string())]
11838        );
11839    }
11840
11841    #[test]
11842    fn a_default_origin_is_recorded_for_flags_and_args() {
11843        let spec: Spec =
11844            "name \"ex\"\nbin \"ex\"\nflag \"--color <when>\" default=\"auto\"\narg \"[src]\" default=\".\"\n"
11845                .parse()
11846                .unwrap();
11847
11848        let parsed = explain(&spec, &["ex"]);
11849
11850        assert_eq!(origins(&parsed, "color"), [ValueOrigin::Default]);
11851        let (arg, origins) = parsed.arg_origins.iter().next().unwrap();
11852        assert_eq!(arg.name, "src");
11853        assert_eq!(origins, &[ValueOrigin::Default]);
11854    }
11855
11856    #[test]
11857    fn a_default_if_origin_carries_the_condition_that_fired() {
11858        let spec: Spec = r#"
11859name "ex"
11860bin "ex"
11861flag "--profile <p>"
11862flag "--strict" {
11863    default_if "--profile" "prod" "true"
11864}
11865        "#
11866        .parse()
11867        .unwrap();
11868
11869        let parsed = explain(&spec, &["ex", "--profile", "prod"]);
11870
11871        // The selector alone is ambiguous: several conditions may name it with different
11872        // `when` values, so the report has to say which one matched.
11873        assert_eq!(
11874            origins(&parsed, "strict"),
11875            [ValueOrigin::DefaultIf {
11876                selector: "--profile".to_string(),
11877                when: Some("prod".to_string()),
11878            }]
11879        );
11880    }
11881
11882    #[test]
11883    fn a_bare_optional_value_flag_records_default_missing() {
11884        let spec: Spec =
11885            "name \"ex\"\nbin \"ex\"\nflag \"--color <when>\" default_missing=\"always\"\nflag \"-v\"\n"
11886                .parse()
11887                .unwrap();
11888
11889        let parsed = explain(&spec, &["ex", "--color", "-v"]);
11890
11891        // The flag was typed and the value was not, which is the distinction a spec author
11892        // is asking about when they ask why `--color` came out `always`.
11893        assert_eq!(roles(&parsed, 1), ["flag color as --color"]);
11894        assert_eq!(origins(&parsed, "color"), [ValueOrigin::DefaultMissing]);
11895        assert_eq!(roles(&parsed, 2), ["flag v as -v"]);
11896    }
11897
11898    #[test]
11899    fn a_var_flag_can_take_one_value_from_argv_and_one_from_default_missing() {
11900        let spec: Spec =
11901            "name \"ex\"\nbin \"ex\"\nflag \"--color <when>\" var=#true default_missing=\"always\"\n"
11902                .parse()
11903                .unwrap();
11904
11905        let parsed = explain(&spec, &["ex", "--color=red", "--color"]);
11906
11907        // Why origins are a list: one declaration, two occurrences, two different answers.
11908        assert_eq!(
11909            roles(&parsed, 1),
11910            [
11911                "flag color as --color",
11912                "value of color = [\"red\"], attached"
11913            ]
11914        );
11915        assert_eq!(origins(&parsed, "color"), [ValueOrigin::DefaultMissing]);
11916    }
11917
11918    #[test]
11919    fn an_override_names_the_flag_that_did_it() {
11920        let spec: Spec =
11921            "name \"ex\"\nbin \"ex\"\nflag \"--quiet\" default=\"true\"\nflag \"--loud\" overrides=\"--quiet\"\n"
11922                .parse()
11923                .unwrap();
11924
11925        let parsed = explain(&spec, &["ex", "--loud"]);
11926
11927        // Without the overriding name, "`--quiet` is unset despite its default" has no
11928        // answer: the fallback phase silently declines to fill an overridden flag.
11929        assert_eq!(parsed.overridden_flags.get("quiet").unwrap(), "loud");
11930        assert!(origins(&parsed, "quiet").is_empty());
11931    }
11932
11933    #[test]
11934    fn a_restart_token_leaves_the_tokens_and_clears_the_arg_origins() {
11935        let spec: Spec = r#"
11936name "ex"
11937bin "ex"
11938cmd "run" restart_token=":::" {
11939    arg "<task>" default="build"
11940}
11941        "#
11942        .parse()
11943        .unwrap();
11944
11945        let parsed = explain(&spec, &["ex", "run", "lint", ":::", "test"]);
11946
11947        // The values belong to the last invocation, so provenance must too — but the words
11948        // of the first were still read, and a report that dropped them would show a command
11949        // line with a hole in it.
11950        assert_eq!(roles(&parsed, 2), ["arg task = [\"lint\"]"]);
11951        // And the token that did the resetting says so: without a role of its own it reads
11952        // as a word that did nothing, next to a `lint` that filled an arg now empty.
11953        assert_eq!(roles(&parsed, 3), ["restart"]);
11954        assert_eq!(roles(&parsed, 4), ["arg task = [\"test\"]"]);
11955        assert!(parsed.arg_origins.is_empty());
11956    }
11957
11958    #[test]
11959    fn a_value_terminator_says_which_run_it_ended() {
11960        let spec: Spec = r#"
11961name "ex"
11962bin "ex"
11963flag "--exec <cmd>..." value_terminator=";"
11964arg "<src>"
11965        "#
11966        .parse()
11967        .unwrap();
11968
11969        let parsed = explain(&spec, &["ex", "--exec", "rm", "tmp", ";", "a"]);
11970
11971        assert_eq!(roles(&parsed, 3), ["value of exec = [\"tmp\"]"]);
11972        // The terminator is consumed and is not one of the values, which is the whole reason
11973        // it was declared — so it needs a row saying that rather than an empty one.
11974        assert_eq!(roles(&parsed, 4), ["value terminator, ends exec"]);
11975        assert_eq!(roles(&parsed, 5), ["arg src = [\"a\"]"]);
11976    }
11977
11978    #[test]
11979    fn an_args_value_terminator_says_which_run_it_ended() {
11980        let spec: Spec = r#"
11981name "ex"
11982bin "ex"
11983arg "<files>..." value_terminator=";"
11984arg "[dest]"
11985        "#
11986        .parse()
11987        .unwrap();
11988
11989        let parsed = explain(&spec, &["ex", "a", "b", ";", "out"]);
11990
11991        assert_eq!(roles(&parsed, 2), ["arg files = [\"b\"]"]);
11992        assert_eq!(roles(&parsed, 3), ["value terminator, ends files"]);
11993        assert_eq!(roles(&parsed, 4), ["arg dest = [\"out\"]"]);
11994    }
11995
11996    #[test]
11997    fn explain_keeps_the_bindings_of_a_command_line_that_fails() {
11998        let spec: Spec = "name \"ex\"\nbin \"ex\"\nflag \"--env <env>\"\narg \"<src>\"\n"
11999            .parse()
12000            .unwrap();
12001
12002        let parsed = Parser::new(&spec)
12003            .explain(&input(&["ex", "--env=prod"]))
12004            .unwrap();
12005
12006        // `parse` reports "missing required <src>" and nothing else, which is the report the
12007        // caller already had. This is the case the whole thing exists for.
12008        assert!(
12009            Parser::new(&spec)
12010                .parse(&input(&["ex", "--env=prod"]))
12011                .is_err()
12012        );
12013        assert_eq!(
12014            roles(&parsed, 1),
12015            ["flag env as --env", "value of env = [\"prod\"], attached"]
12016        );
12017        assert!(
12018            parsed.errors.iter().any(|e| e.to_string().contains("src")),
12019            "{:?}",
12020            parsed.errors
12021        );
12022    }
12023
12024    #[test]
12025    fn an_external_subcommand_forwards_whole_tokens() {
12026        let spec: Spec = "name \"ex\"\nbin \"ex\"\nexternal_subcommand #true\ncmd \"build\"\n"
12027            .parse()
12028            .unwrap();
12029
12030        let parsed = explain(&spec, &["ex", "deploy", "--now"]);
12031
12032        assert_eq!(roles(&parsed, 1), ["external"]);
12033        assert_eq!(roles(&parsed, 2), ["external"]);
12034    }
12035
12036    #[test]
12037    fn a_view_keeps_the_callers_argv_positions() {
12038        let spec: Spec = r#"
12039bin "ex"
12040view "runner" root="run"
12041cmd "run" {
12042    flag "--token <token>"
12043}
12044        "#
12045        .parse()
12046        .unwrap();
12047
12048        let parsed = explain(&spec, &["runner", "--token", "secret"]);
12049
12050        // A view re-enters the parse with the same argv, so the positions still mean what
12051        // the caller wrote.
12052        assert_eq!(roles(&parsed, 0), ["program"]);
12053        assert_eq!(roles(&parsed, 2), ["value of token = [\"secret\"]"]);
12054    }
12055
12056    #[test]
12057    fn empty_default_does_not_hide_a_missing_parent_flag_value() {
12058        let spec: Spec = r#"
12059name "ex"
12060bin "ex"
12061default_subcommand "run"
12062default_subcommand_on_empty #true
12063flag "--value <value>"
12064cmd "run" arg_required_else_help=#true
12065"#
12066        .parse()
12067        .unwrap();
12068        let err = Parser::new(&spec)
12069            .parse(&input(&["ex", "--value"]))
12070            .unwrap_err();
12071        assert!(err.to_string().contains("requires an argument"), "{err}");
12072        assert!(!err.to_string().contains("Usage: ex run"), "{err}");
12073    }
12074
12075    #[test]
12076    fn empty_default_honors_parent_args_conflict_policy() {
12077        let spec: Spec = r#"
12078name "ex"
12079bin "ex"
12080default_subcommand "run"
12081default_subcommand_on_empty #true
12082args_conflicts_with_subcommands #true
12083flag "--verbose"
12084cmd "run"
12085"#
12086        .parse()
12087        .unwrap();
12088        let err = Parser::new(&spec)
12089            .parse(&input(&["ex", "--verbose"]))
12090            .unwrap_err();
12091        assert!(
12092            err.to_string().contains("cannot be used with arguments"),
12093            "{err}"
12094        );
12095    }
12096
12097    #[test]
12098    fn the_parse_records_which_flags_a_mounted_program_declared() {
12099        let mut spec: Spec = r#"
12100bin ex
12101flag "-p --pick <tool>" global=#true
12102cmd run {
12103    mount run=tasks
12104}
12105"#
12106        .parse()
12107        .unwrap();
12108        let mounted = r#"
12109cmd outer {
12110    cmd inner {
12111        flag "-p --other <name>"
12112    }
12113}
12114cmd deep {
12115    flag "--pick <tool>" global=#true
12116    cmd leaf {
12117        flag "-p --pick <tool>"
12118    }
12119}
12120"#;
12121        spec.resolve_mount_outputs(&HashMap::from([("tasks".to_string(), mounted.to_string())]))
12122            .unwrap();
12123        let pending_is_mounted = |words: &[&str]| {
12124            let words: Vec<String> = words.iter().map(|word| word.to_string()).collect();
12125            let out = parse_partial(&spec, &words).unwrap();
12126            let flag = out
12127                .flag_awaiting_value
12128                .first()
12129                .expect("a flag awaiting its value");
12130            out.is_mounted_flag(flag)
12131        };
12132
12133        assert!(!pending_is_mounted(&["ex", "--pick"]));
12134        // `inner`'s own `-p` collides with the host's global `-p`, which the parser keeps.
12135        assert!(!pending_is_mounted(&["ex", "run", "outer", "inner", "-p"]));
12136        assert!(!pending_is_mounted(&[
12137            "ex", "run", "outer", "inner", "--pick"
12138        ]));
12139        assert!(pending_is_mounted(&[
12140            "ex", "run", "outer", "inner", "--other"
12141        ]));
12142        // `leaf` re-declares `deep`'s global `--pick`, and the parser merges the two into one
12143        // flag that matches neither declaration. It is still the mounted program's.
12144        assert!(pending_is_mounted(&["ex", "run", "deep", "--pick"]));
12145        assert!(pending_is_mounted(&["ex", "run", "deep", "leaf", "--pick"]));
12146        assert!(!pending_is_mounted(&["ex", "run", "deep", "leaf", "-p"]));
12147    }
12148
12149    #[test]
12150    fn empty_default_mount_matches_explicit_selection() {
12151        let spec: Spec = r#"
12152name "ex"
12153bin "ex"
12154default_subcommand "run"
12155default_subcommand_on_empty #true
12156cmd "run" { mount run="discover" }
12157"#
12158        .parse()
12159        .unwrap();
12160        let mut mounts = HashMap::new();
12161        mounts.insert(
12162            "discover".to_string(),
12163            "name \"run\"\nbin \"run\"\nflag \"--mounted <mounted>\" default=\"yes\"\n".to_string(),
12164        );
12165        for argv in [
12166            vec!["ex".to_string()],
12167            vec!["ex".to_string(), "run".to_string()],
12168        ] {
12169            let out = Parser::new(&spec)
12170                .with_mount_outputs(mounts.clone())
12171                .parse(&argv)
12172                .unwrap();
12173            assert_eq!(out.cmds.last().unwrap().name, "run");
12174            assert_eq!(out.flags.values().next().unwrap().to_string(), "yes");
12175        }
12176    }
12177
12178    #[test]
12179    fn pending_parent_value_stays_pending_in_partial_parse() {
12180        let spec: Spec = r#"
12181name "ex"
12182bin "ex"
12183default_subcommand "run"
12184default_subcommand_on_empty #true
12185flag "--value <value>"
12186cmd "run" {}
12187"#
12188        .parse()
12189        .unwrap();
12190        let out = parse_partial(&spec, &input(&["ex", "--value"])).unwrap();
12191        assert_eq!(out.cmd.name, "ex");
12192        assert_eq!(out.flag_awaiting_value[0].name, "value");
12193    }
12194
12195    #[test]
12196    fn optional_default_missing_still_selects_empty_child() {
12197        let spec: Spec = r#"
12198name "ex"
12199bin "ex"
12200default_subcommand "run"
12201default_subcommand_on_empty #true
12202flag "--value <value>" default_missing="fallback"
12203cmd "run" {}
12204"#
12205        .parse()
12206        .unwrap();
12207        let out = Parser::new(&spec)
12208            .parse(&input(&["ex", "--value"]))
12209            .unwrap();
12210        assert_eq!(out.cmd.name, "run");
12211        assert_eq!(out.flags.values().next().unwrap().to_string(), "fallback");
12212    }
12213
12214    #[test]
12215    fn empty_default_resets_cursor_after_root_sigil() {
12216        let spec: Spec = r#"
12217name "ex"
12218bin "ex"
12219default_subcommand "run"
12220default_subcommand_on_empty #true
12221arg "[tool]..." sigil="@"
12222cmd "run" { arg "[path]" }
12223"#
12224        .parse()
12225        .unwrap();
12226        let out = parse_partial(&spec, &input(&["ex"])).unwrap();
12227        assert_eq!(out.cmd.name, "run");
12228        assert_eq!(out.next_arg.as_ref().unwrap().name, "path");
12229    }
12230
12231    #[test]
12232    fn root_clause_positional_prevents_empty_default() {
12233        let spec: Spec = r#"
12234name "ex"
12235bin "ex"
12236default_subcommand "run"
12237default_subcommand_on_empty #true
12238clause "tasks" {
12239  arg "<number>" allow_negative_numbers=#true
12240}
12241cmd "run" { arg "[task]" }
12242"#
12243        .parse()
12244        .unwrap();
12245        let out = Parser::new(&spec).parse(&input(&["ex", "-7"])).unwrap();
12246        assert!(
12247            out.cmds.iter().all(|cmd| cmd.name != "run"),
12248            "cmds={:?} args={:?}",
12249            out.cmds.iter().map(|c| &c.name).collect::<Vec<_>>(),
12250            out.args
12251        );
12252        let number = spec.cmd.clause.as_ref().unwrap().args.first().unwrap();
12253        assert_eq!(
12254            out.clauses["tasks"][0].get(number).unwrap().to_string(),
12255            "-7"
12256        );
12257    }
12258}