Skip to main content

usage_argv/
lib.rs

1//! A zero-allocation argv parser for [usage](https://usage.jdx.dev) specs.
2//!
3//! This crate implements the binding rules of [the argv grammar]: which token
4//! becomes which flag or argument, when a word selects a subcommand, and what
5//! is an error. It does so without building a command tree, without allocating,
6//! and in one pass.
7//!
8//! It is the runtime half of a compiled parser. The tables it reads are meant to
9//! be emitted by a derive macro as `static` data, so that starting a parse costs
10//! nothing at all: there is no construction step to pay for, only the walk over
11//! `argv`.
12//!
13//! # Shape of the API
14//!
15//! Parsing yields [`Event`]s rather than a map. A map would have to allocate,
16//! and would then have to be read back out again — whereas generated code can
17//! assign an event straight into a struct field. This is the same reason serde
18//! deserializes into your type instead of into a `Value`.
19//!
20//! ```
21//! use usage_argv::{Arg, Command, Event, Flag, Parser};
22//!
23//! static FORCE: Flag = Flag { key: 0, longs: &["force"], shorts: b"f", ..Flag::BOOL };
24//! static FILE: Arg = Arg { key: 1, ..Arg::REQUIRED };
25//! static ROOT: Command = Command {
26//!     name: "ex",
27//!     flags: &[&FORCE],
28//!     args: &[&FILE],
29//!     ..Command::EMPTY
30//! };
31//!
32//! let argv = ["--force", "a.txt"].map(std::ffi::OsStr::new);
33//! let mut parser = Parser::new(&ROOT, &argv);
34//!
35//! let mut force = false;
36//! let mut file = None;
37//! while let Some(event) = parser.next_event() {
38//!     match event.expect("valid command line") {
39//!         Event::Flag { flag, .. } if flag.key == 0 => force = true,
40//!         Event::Arg { value, .. } => file = Some(value),
41//!         _ => {}
42//!     }
43//! }
44//! assert!(force);
45//! assert_eq!(file, Some(&b"a.txt"[..]));
46//! ```
47//!
48//! # Values are bytes
49//!
50//! An [`Event`] carries `&[u8]`, borrowed from `argv`. Converting to `&str` is
51//! the caller's step ([`as_str`]), and it is the right place for the only
52//! failure a value can have: a command line that is not valid UTF-8 still
53//! *parses* — flags match, subcommands route — and only the values that are
54//! actually looked at can fail to convert.
55//!
56//! Slicing an `OsStr` into `&str` pieces safely is not possible without
57//! allocating or `unsafe`. Bytes are what is left, and they turn out to be the
58//! honest interface anyway.
59//!
60//! The reverse conversion is [`os_string_from_bytes`], which lets a `PathBuf`
61//! field hold a filename that is not UTF-8 rather than a mangled copy of one. On
62//! Unix that is lossless and safe; on Windows, where WTF-8 makes it partial, a
63//! value that will not convert is reported. Either way this crate contains no
64//! `unsafe`, which a conversion that guessed would have cost.
65//!
66//! # What this crate does not do
67//!
68//! Only binding. Required-ness, `choices`, `env` fallback, defaults, `var_min`
69//! and `var_max` are all decided *after* the last token is read, and they need to
70//! know a value's type, so they belong to the layer that owns the target struct.
71//! Keeping them out is what makes this loop small.
72//!
73//! # Features
74//!
75//! - `spec` — a parallel tree of cold metadata (help text, choices, defaults,
76//!   effects) and a writer that emits it as a usage spec. Off by default: a
77//!   successful parse never reads any of it, so a CLI that only wants a parser
78//!   should not compile it.
79//! - `complete` — answering a partial command line ([`complete`]), the shell
80//!   scripts that ask ([`script`]), and putting one of those scripts where its
81//!   shell will look for it ([`install`]). Installing ships with the scripts
82//!   rather than behind a gate of its own: a script a CLI still has to tell its
83//!   users to redirect by hand is the unfinished half of shipping one.
84//!
85//! [the argv grammar]: https://usage.jdx.dev/spec/argv
86
87// One module opts out: `tty`, which asks the kernel how wide the terminal is. `forbid` would
88// make that opt-out impossible, and the alternative to the opt-out is a dependency — this
89// crate has none, and a CLI that wraps its help at 80 columns on a wide terminal is worse
90// than two dozen lines of reviewed FFI. Everything else in the crate is still refused.
91#![deny(unsafe_code)]
92
93/// Terminate at the compiled CLI entry-point boundary.
94///
95/// Kept in the runtime rather than expanded into an adopter crate so a project that
96/// forbids direct `std::process::exit` calls does not attribute the derive's process
97/// boundary to application code. `Cli::parse_from*` continues to return errors.
98#[doc(hidden)]
99#[allow(clippy::disallowed_methods)]
100pub fn __usage_process_exit(status: i32) -> ! {
101    std::process::exit(status)
102}
103
104/// Print a generated entry point's output to stdout, ignoring a failed write.
105///
106/// `print!` panics when the write fails, and the usual failure is a reader that has gone
107/// away: `cli --help | head -1`, a pager quit early, or a completion the shell cancelled while
108/// typing. Every caller is about to leave (or has finished a successful parse), so there is
109/// nobody left to tell, and a panic only turns that into a crash — an abort with a core dump
110/// in a `panic = "abort"` build. The exit status stays the one the caller chose.
111#[doc(hidden)]
112pub fn __usage_print(output: std::fmt::Arguments<'_>) {
113    use std::io::Write;
114    let mut stdout = std::io::stdout().lock();
115    let _ = stdout.write_fmt(output).and_then(|()| stdout.flush());
116}
117
118/// The process's arguments, argv[0] included.
119///
120/// Out of line so each derived entry point calls it rather than carrying its own copy of
121/// the collecting loop.
122#[doc(hidden)]
123pub fn __usage_process_args() -> Vec<OsString> {
124    let args = std::env::args_os();
125    let mut all = Vec::with_capacity(args.len());
126    for arg in args {
127        all.push(arg);
128    }
129    all
130}
131
132/// Borrow every word of `words`, for a parse that takes `&[&OsStr]`.
133#[doc(hidden)]
134pub fn __usage_borrow_words(words: &[OsString]) -> Vec<&OsStr> {
135    let mut refs = Vec::with_capacity(words.len());
136    for word in words {
137        refs.push(word.as_os_str());
138    }
139    refs
140}
141
142/// Own every word of `words`, behind a `prefix` of whitespace-separated words, the shape a
143/// view or multicall rewrite hands the parser.
144#[doc(hidden)]
145pub fn __usage_own_words(prefix: &str, words: &[&OsStr]) -> Vec<OsString> {
146    let mut owned = Vec::with_capacity(words.len());
147    for word in prefix.split_ascii_whitespace() {
148        owned.push(OsString::from(word));
149    }
150    for word in words {
151        owned.push((*word).to_os_string());
152    }
153    owned
154}
155
156/// Build a command's future on the heap, for a generated async dispatch to await.
157///
158/// The future is created inside this function, not by the caller, and that is the point:
159/// without optimizations every temporary in an `async fn` gets its own stack slot, held for
160/// as long as the future runs, so a dispatch that wrote `run_async(inner).await` in each arm
161/// kept a slot the size of every command's future on the stack while running any one of them.
162/// Created here, the future only passes through this function's frame, and the dispatch keeps
163/// a `Box` per arm instead. `Send` still follows the command's future, since a box of it is
164/// `Send` exactly when it is.
165#[doc(hidden)]
166pub fn __usage_box_future<F, Fut>(make: F) -> std::pin::Pin<Box<Fut>>
167where
168    F: FnOnce() -> Fut,
169    Fut: std::future::Future,
170{
171    Box::pin(make())
172}
173
174/// [`__usage_print`] for stderr: help and failures that go there, and deprecation warnings.
175#[doc(hidden)]
176pub fn __usage_eprint(output: std::fmt::Arguments<'_>) {
177    use std::io::Write;
178    let _ = std::io::stderr().lock().write_fmt(output);
179}
180
181use std::ffi::{OsStr, OsString};
182
183/// A value's shell-native completion class for `#[usage(value_hint = ...)]`.
184///
185/// This lives in the runtime crate so a declaration never needs clap merely to describe what
186/// kind of path a shell should offer. It is metadata only and adds no work to a successful
187/// parse.
188#[derive(Clone, Copy, Debug, Eq, PartialEq)]
189pub enum ValueHint {
190    /// Let the shell use its normal fallback behavior.
191    Unknown,
192    /// No structured hint applies; suppress the shell's path fallback.
193    Other,
194    /// A path to a file.
195    FilePath,
196    /// A path to either a file or a directory.
197    AnyPath,
198    /// A path to a directory.
199    DirPath,
200    /// A path to an executable file.
201    ExecutablePath,
202    /// A command name, resolved through the shell's command table and `PATH`.
203    CommandName,
204    /// One string containing a command and any arguments.
205    CommandString,
206    /// A trailing argv vector: complete the first value as a command, then its arguments.
207    CommandWithArguments,
208    /// A local operating-system user name.
209    Username,
210    /// A host name known to the shell or operating system.
211    Hostname,
212    /// A web address. This suppresses path fallback but offers no finite candidate set.
213    Url,
214    /// An email address. This suppresses path fallback but offers no finite candidate set.
215    EmailAddress,
216}
217
218#[cfg(feature = "complete")]
219pub mod complete;
220#[cfg(feature = "diagnostics")]
221pub mod diagnostic;
222#[cfg(feature = "spec")]
223pub mod embedded;
224#[cfg(feature = "spec")]
225pub mod env;
226#[cfg(feature = "complete")]
227pub mod install;
228#[cfg(feature = "complete")]
229pub mod script;
230
231/// Checks that the `complete` feature is on, with an explanation when it is not.
232///
233/// `#[usage(completion)]` generates code that reaches into [`complete`], which is behind a
234/// feature the *depending* crate enables — a derive cannot turn on a feature of another crate.
235/// Without this, the failure was `unresolved module complete`, which says nothing about the
236/// attribute that caused it.
237#[cfg(feature = "complete")]
238#[macro_export]
239macro_rules! __usage_needs_complete_feature {
240    () => {};
241}
242
243/// See [`__usage_needs_complete_feature`].
244#[cfg(not(feature = "complete"))]
245#[macro_export]
246macro_rules! __usage_needs_complete_feature {
247    () => {
248        ::core::compile_error!(
249            "`#[usage(completion)]` needs usage-argv's `complete` feature. Add it where \
250             usage-argv is depended on: usage-argv = { version = \"…\", features = \
251             [\"spec\", \"complete\"] }"
252        );
253    };
254}
255#[cfg(feature = "spec")]
256pub mod help;
257#[cfg(feature = "spec")]
258mod order;
259mod slice;
260#[cfg(feature = "spec")]
261mod text;
262// Behind no feature: two traits and no code, so there is nothing here for a binary that
263// does not dispatch to pay for, and a hand-written CLI on the bare runtime can use them.
264pub mod run;
265// Behind no feature either, and public: an application that lays out its own output beside a
266// help page — a table, a progress line — should not have to work the width out a second way
267// and disagree with the page it sits next to.
268#[cfg(feature = "spec")]
269pub mod spec;
270pub mod tty;
271#[cfg(feature = "spec")]
272pub use spec::{parse_args_from, parse_args_from_argv};
273#[cfg(feature = "spec")]
274pub mod warn;
275
276pub use run::{Run, RunAsync, RunAsyncWith, RunWith};
277
278/// How deep a command tree this parser will descend.
279///
280/// The ancestor chain is kept in a fixed-size array so that a parse allocates
281/// nothing; this is that array's size. mise, the largest usage CLI, is four
282/// levels deep.
283pub const MAX_DEPTH: usize = 16;
284
285/// A command: its flags, its positional arguments, and its subcommands.
286///
287/// Every field is a borrowed slice so that a derive can emit the whole tree as
288/// `static` data. Use `..Command::EMPTY` to fill in the parts you do not need.
289#[derive(Debug, Clone, Copy, PartialEq, Eq)]
290pub struct Command<'a> {
291    /// The canonical name, used to select this command.
292    pub name: &'a str,
293    /// Alternative names that also select it.
294    pub aliases: &'a [&'a str],
295    pub flags: &'a [&'a Flag<'a>],
296    /// Positional arguments, in the order they are filled.
297    pub args: &'a [&'a Arg<'a>],
298    /// A repeatable group of scoped flags and positional arguments, if this command has one.
299    ///
300    /// Behind a reference because hardly any command has one: held inline, the clause's five
301    /// slices were two thirds of every command's table whether it declared one or not.
302    pub clause: ::core::option::Option<&'a Clause<'a>>,
303    pub subcommands: &'a [&'a Command<'a>],
304    /// Where a word goes when it names no subcommand of this one.
305    ///
306    /// The spec's `default_subcommand`. `mise build` means `mise run build`: the word names
307    /// no command, so the parser descends into `run` and lets *`run`* have it — even where
308    /// this command declares an argument of its own, which is what makes the property worth
309    /// having rather than a synonym for a positional.
310    ///
311    /// Applied at most once per parse, so a CLI cannot loop through it, and only where a
312    /// subcommand could still be selected.
313    ///
314    /// Resolve it with [`find_subcommand`], which turns a name that no subcommand answers to
315    /// into a compile error.
316    pub default_subcommand: ::core::option::Option<&'a Command<'a>>,
317    /// Look ahead past parent/default flags before implicitly selecting the default.
318    /// A sibling name before any default-only flag stays on the parent; after one,
319    /// later words are the default command's args.
320    pub default_subcommand_flags: bool,
321    /// Select the default subcommand for an otherwise empty successful invocation.
322    pub default_subcommand_on_empty: bool,
323    /// Whether an unmatched word is forwarded as an external command plus the rest of argv.
324    ///
325    /// clap's `allow_external_subcommands`. Known subcommands still win; a
326    /// [`default_subcommand`](Self::default_subcommand) still catches first. Once the
327    /// unmatched word is taken, remaining tokens — including `--help` — are not parsed
328    /// as this command's flags.
329    pub external_subcommand: bool,
330    /// Show this command's help when no argv token follows its name.
331    ///
332    /// This is clap's `arg_required_else_help`. It deliberately observes argv rather than
333    /// bound values: an environment variable or default may fill a field, but neither means
334    /// the user supplied an argument to this invocation.
335    pub arg_required_else_help: bool,
336    /// Selecting a subcommand suppresses this command's required arguments.
337    pub subcommand_negates_reqs: bool,
338    /// Once this command binds a flag or positional, selecting one of its
339    /// subcommands is an error.
340    pub args_conflicts_with_subcommands: bool,
341    /// Let a known subcommand interrupt a variadic argument that would otherwise consume it.
342    pub subcommand_precedence_over_arg: bool,
343    /// Let a later required positional take a word while an earlier optional positional
344    /// remains empty.
345    pub allow_missing_positional: bool,
346    /// Disable delimiter splitting for positional values after `--` or on an
347    /// automatic trailing argument. Inherited by subcommands.
348    pub dont_delimit_trailing_values: bool,
349    /// What an unrecognized flag-like token means here, or `None` to keep whatever the
350    /// enclosing command said. See [`UnknownFlags`].
351    ///
352    /// Inherited rather than resolved per command, which is what usage-lib does — its
353    /// `effective_unknown_flags` walks outward from the command that ran and falls back to
354    /// the spec's. Resolving it in the tables instead was possible only for a builder that
355    /// can see the whole tree: a derive expands one struct at a time and cannot see its
356    /// parent, so `#[usage(unknown_flags = "error")]` on the root reached the root alone and
357    /// a subcommand had no way to say it at all.
358    ///
359    /// The parser carries the effective value down as it descends, so a command that states
360    /// nothing costs nothing.
361    pub unknown_flags: ::core::option::Option<UnknownFlags>,
362    /// Whether this command answers to `--version` and `-V`.
363    ///
364    /// Set on the root, and only when the CLI declares a version: clap adds the flag exactly
365    /// then, and a `--version` that answers with nothing is worse than one that is not there.
366    /// A field rather than a rule about depth, so a CLI that wants it on a subcommand — clap's
367    /// `propagate_version` — has somewhere to say so.
368    pub version: bool,
369    /// Do not synthesize `--help` and `-h` for this command.
370    pub disable_help_flag: bool,
371    /// Do not synthesize the `help` subcommand route for this command.
372    pub disable_help_subcommand: bool,
373    /// Do not synthesize `--version` and `-V` for this command.
374    pub disable_version_flag: bool,
375    /// Caller-assigned identifier, echoed back in [`Event::Command`].
376    ///
377    /// Wide enough for a derive to make these unique without coordination: two
378    /// macro expansions cannot see each other, so the generated keys carry a hash
379    /// of the type they came from in the high half and a per-type index in the low
380    /// half. A parse dispatches on this, so a collision would bind the wrong field
381    /// — [`Spec::to_kdl`](crate::spec::Spec::to_kdl) checks the tree for duplicates
382    /// in debug builds.
383    pub key: u64,
384}
385
386impl Command<'_> {
387    /// A command with nothing declared, for use with struct update syntax.
388    pub const EMPTY: Command<'static> = Command {
389        name: "",
390        aliases: &[],
391        flags: &[],
392        args: &[],
393        clause: ::core::option::Option::None,
394        subcommands: &[],
395        default_subcommand: ::core::option::Option::None,
396        default_subcommand_flags: false,
397        default_subcommand_on_empty: false,
398        external_subcommand: false,
399        arg_required_else_help: false,
400        subcommand_negates_reqs: false,
401        args_conflicts_with_subcommands: false,
402        subcommand_precedence_over_arg: false,
403        allow_missing_positional: false,
404        dont_delimit_trailing_values: false,
405        unknown_flags: ::core::option::Option::None,
406        version: false,
407        disable_help_flag: false,
408        disable_help_subcommand: false,
409        disable_version_flag: false,
410        key: 0,
411    };
412}
413
414/// A repeatable group of scoped flags and positional arguments.
415#[derive(Debug, Clone, Copy, PartialEq, Eq)]
416pub struct Clause<'a> {
417    pub key: u64,
418    pub name: &'a str,
419    /// An explicit token that starts the next instance. When absent, consuming the
420    /// clause's sole required positional completes the current instance.
421    pub separator: ::core::option::Option<&'a [u8]>,
422    pub flags: &'a [&'a Flag<'a>],
423    pub args: &'a [&'a Arg<'a>],
424}
425
426/// Basename of argv[0] for a multicall CLI: last path component, with a trailing
427/// `.exe` stripped so Windows and Unix agree.
428pub fn multicall_basename(argv0: &str) -> &str {
429    let name = argv0.rsplit(['/', '\\']).next().unwrap_or(argv0);
430    match name.get(name.len().saturating_sub(4)..) {
431        Some(ext) if ext.eq_ignore_ascii_case(".exe") => &name[..name.len() - 4],
432        _ => name,
433    }
434}
435
436/// The applet name to parse as the first word, when argv[0] is not the dispatcher.
437///
438/// `None` means a dispatcher invocation (`busybox ls`): skip argv[0] and parse the
439/// rest. `Some` is a symlink invocation (`ls -l`): inject the basename.
440pub fn multicall_applet<'a>(argv0: &'a str, name: &str, bin: Option<&str>) -> Option<&'a str> {
441    let base = multicall_basename(argv0);
442    if !name.is_empty() && base == multicall_basename(name) {
443        return None;
444    }
445    if let Some(bin) = bin
446        && !bin.is_empty()
447        && base == multicall_basename(bin)
448    {
449        return None;
450    }
451    Some(base)
452}
453
454/// Resolved identity of a derive-generated binding type.
455#[derive(Clone, Copy)]
456pub struct BindingType(pub fn() -> &'static str);
457
458impl BindingType {
459    pub fn name(self) -> &'static str {
460        (self.0)()
461    }
462}
463
464impl ::core::fmt::Debug for BindingType {
465    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
466        f.debug_tuple("BindingType").field(&self.name()).finish()
467    }
468}
469
470impl PartialEq for BindingType {
471    fn eq(&self, other: &Self) -> bool {
472        self.name() == other.name()
473    }
474}
475
476impl Eq for BindingType {}
477
478/// A flag, addressed by any of its long or short forms.
479#[derive(Debug, Clone, Copy, PartialEq, Eq)]
480pub struct Flag<'a> {
481    /// Caller-assigned identifier, echoed back in [`Event::Flag`]. This is how
482    /// generated code knows which field to assign without any string comparison.
483    /// See [`Command::key`] on why it is this wide.
484    pub key: u64,
485    /// Compatibility key for mirroring a redeclared child global into an ancestor field.
486    ///
487    /// Zero means no typed binding contract is declared. Derive-generated tables hash the
488    /// binding shape and portable metadata so only equivalent bindings receive the same event.
489    pub binding_key: u64,
490    /// Resolved Rust value type for a derive-generated binding.
491    ///
492    /// This is separate from [`Self::binding_key`] because token spellings are not type
493    /// identities: an imported alias and a fully qualified path can name the same type.
494    pub binding_type: Option<BindingType>,
495    /// Unused by binding, kept so a table entry can carry its own name for
496    /// diagnostics.
497    pub name: &'a str,
498    /// Long forms, written without the leading `--`.
499    pub longs: &'a [&'a str],
500    /// Short forms, as single bytes.
501    ///
502    /// **Should be ASCII.** A cluster like `-xyz` is walked one byte at a time, so a
503    /// non-ASCII short can never be matched, and the remainder after a value-taking one —
504    /// which becomes its value — would begin in the middle of a character.
505    /// `#[derive(Cli)]` rejects a non-ASCII `short`; a table written by hand should keep to
506    /// it. Nothing is unsound if it does not: the value would simply be cut in a place that
507    /// makes no sense, and on Windows would then fail to convert.
508    pub shorts: &'a [u8],
509    /// A long form that sets the flag to false, written without the `--`.
510    pub negate: Option<&'a str>,
511    /// Whether the flag takes a value.
512    pub takes_value: bool,
513    /// Whether one occurrence of this flag keeps taking values, until a flag-like
514    /// token or the end of the command line.
515    ///
516    /// This is the spec's variadic flag *argument* (`--include <pattern>...`). It
517    /// is not the spec's flag-level `var=#true`, which means the flag may be
518    /// repeated and takes one value each time — repetition needs nothing from the
519    /// parser, since it already reports every occurrence separately. Conflating
520    /// the two makes a merely repeatable flag greedy enough to eat a positional.
521    pub variadic: bool,
522    /// How many values one variadic occurrence may take, after which the next word
523    /// belongs to whatever comes next.
524    ///
525    /// Only for [`variadic`](Self::variadic). A merely repeatable flag — the spec's
526    /// `var=#true` — is bounded on how many times it was *given*, which no single token
527    /// can decide, so that bound stays with the metadata and is checked after the parse.
528    pub var_max: ::core::option::Option<u32>,
529    /// The byte that makes one word several values, if the flag declares one.
530    ///
531    /// Here rather than with the metadata for the same reason [`var_max`](Self::var_max)
532    /// is: it decides *where* a word lands. A bound counts values, and a delimiter is what
533    /// makes a word stop being one of them — `--include a,b,c` is three, so a `var_max` of
534    /// two is already past its bound on the single word it was entitled to take. Binding
535    /// cannot count without it.
536    pub delimiter: ::core::option::Option<u8>,
537    /// Whether a detached value may itself look like a flag.
538    ///
539    /// The default is to refuse: `--jobs --force` is far more likely a forgotten
540    /// value than a jobs of `"--force"`. Declared, the next token is taken
541    /// whatever it looks like — including `--` — which is clap's
542    /// `allow_hyphen_values` and the spec's property of the same name. A variadic
543    /// occurrence still stops collecting at a later flag-like token, so a second
544    /// occurrence of the flag is not eaten as a value.
545    pub allow_hyphen_values: bool,
546    /// Whether a detached value may be a negative number while other flag-like
547    /// tokens still stop collection or report as flags.
548    pub allow_negative_numbers: bool,
549    /// A token that ends one variadic occurrence without becoming a value.
550    pub value_terminator: ::core::option::Option<&'a [u8]>,
551    /// Whether the value must be attached with `=`.
552    ///
553    /// `--flag=value` is accepted and `--flag value` is not, which is clap's
554    /// `require_equals` and the spec's property of the same name. A short's
555    /// attached form (`-i9229`, `-i=9229`) still binds: only the following word
556    /// is refused.
557    pub require_equals: bool,
558    /// Whether this value-taking flag may be present without a value.
559    ///
560    /// A missing value emits the flag event with `value: None`; bindings such as
561    /// `Option<Option<T>>` can therefore distinguish an absent flag from a bare
562    /// flag and from a flag with an explicit value.
563    pub value_optional: bool,
564    /// Whether a boolean long flag accepts an attached `true` or `false` value.
565    ///
566    /// This does not make the flag value-taking in the ordinary sense: a detached
567    /// word is never consumed, and help keeps rendering a switch. Only
568    /// `--flag=true` and `--flag=false` opt into an explicit boolean value.
569    pub bool_value: bool,
570    /// Value used when the flag is present but no value is given.
571    ///
572    /// clap's `default_missing_value` and the spec's `default_missing`. `--color`
573    /// binds this, `--color=never` binds `never`, and an absent flag is not bound.
574    /// Combined with [`Self::require_equals`], a following word is still refused.
575    pub default_missing: ::core::option::Option<&'a [u8]>,
576    /// Whether the flag is recognized by every command beneath the one that
577    /// declares it.
578    pub global: bool,
579    /// Whether this declared flag binds a field or requests a built-in response.
580    pub action: ArgAction,
581}
582
583impl Flag<'_> {
584    /// A value-less flag, for use with struct update syntax.
585    pub const BOOL: Flag<'static> = Flag {
586        key: 0,
587        binding_key: 0,
588        binding_type: None,
589        name: "",
590        longs: &[],
591        shorts: &[],
592        negate: None,
593        takes_value: false,
594        variadic: false,
595        var_max: ::core::option::Option::None,
596        delimiter: ::core::option::Option::None,
597        allow_hyphen_values: false,
598        allow_negative_numbers: false,
599        value_terminator: ::core::option::Option::None,
600        require_equals: false,
601        value_optional: false,
602        bool_value: false,
603        default_missing: ::core::option::Option::None,
604        global: false,
605        action: ArgAction::Set,
606    };
607
608    /// A flag that takes a value, for use with struct update syntax.
609    pub const VALUE: Flag<'static> = Flag {
610        takes_value: true,
611        ..Flag::BOOL
612    };
613}
614
615/// What supplying a declared flag does.
616#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
617pub enum ArgAction {
618    /// Bind the flag to its declared field.
619    #[default]
620    Set,
621    /// Show help, choosing the long form for a long spelling and the short form otherwise.
622    Help,
623    /// Always show short help.
624    HelpShort,
625    /// Always show long help.
626    HelpLong,
627    /// Show long help for this command and every visible descendant.
628    HelpAll,
629    /// Show version information.
630    Version,
631}
632
633/// A positional argument.
634#[derive(Debug, Clone, Copy, PartialEq, Eq)]
635pub struct Arg<'a> {
636    /// Caller-assigned identifier, echoed back in [`Event::Arg`]. See
637    /// [`Command::key`] on why it is this wide.
638    pub key: u64,
639    /// Prefix that classifies this positional independently of declaration order.
640    /// The prefix is removed from the value emitted in [`Event::Arg`].
641    pub sigil: ::core::option::Option<&'a [u8]>,
642    /// Whether post-binding requires this positional to have a value. Kept in the hot
643    /// table because `allow_missing_positional` must reserve words for later required args.
644    pub required: bool,
645    /// Whether this argument keeps taking values once it has one.
646    pub var: bool,
647    /// How many words a variadic may take before the next argument gets the rest.
648    ///
649    /// A bound belongs here, in the table binding reads, rather than with the metadata:
650    /// it decides *where* a word lands, not whether what landed is acceptable. clap's
651    /// `num_args` works the same way, and every spec in the wild is generated from a clap
652    /// command. `u32` rather than `usize` because a CLI that bounds a variadic above four
653    /// billion has other problems, and this table is read on the hot path.
654    pub var_max: ::core::option::Option<u32>,
655    /// The byte that makes one word several values, if the argument declares one.
656    ///
657    /// See [`Flag::delimiter`]: a bound counts values, and only this says how many values a
658    /// word carries.
659    pub delimiter: ::core::option::Option<u8>,
660    /// Whether a negative-number token is accepted as this positional even in
661    /// strict flag mode.
662    pub allow_negative_numbers: bool,
663    /// A token that ends this variadic positional without becoming a value.
664    pub value_terminator: ::core::option::Option<&'a [u8]>,
665    /// This argument's relationship to the `--` separator.
666    pub double_dash: DoubleDash,
667    /// Unused by binding, kept so a table entry can carry its own name for
668    /// diagnostics.
669    pub name: &'a str,
670}
671
672impl Arg<'_> {
673    /// A single-value argument, for use with struct update syntax.
674    pub const REQUIRED: Arg<'static> = Arg {
675        key: 0,
676        sigil: ::core::option::Option::None,
677        required: true,
678        var: false,
679        var_max: ::core::option::Option::None,
680        delimiter: ::core::option::Option::None,
681        allow_negative_numbers: false,
682        value_terminator: ::core::option::Option::None,
683        double_dash: DoubleDash::Optional,
684        name: "",
685    };
686
687    /// A variadic argument, for use with struct update syntax.
688    pub const VAR: Arg<'static> = Arg {
689        var: true,
690        ..Arg::REQUIRED
691    };
692}
693
694/// What to do with a flag-like token that names no flag in scope.
695///
696/// The default is [`UnknownFlags::Value`]: the token carries on to the positional
697/// arguments, because a spec is often parsing a command line whose flags belong to
698/// something else — a wrapped tool, a task script. A CLI that owns all of its
699/// flags declares [`UnknownFlags::Error`] and gets typo detection instead.
700///
701/// Stored per command and already resolved: inheritance is a question for whoever
702/// builds the tables, and answering it at compile time keeps it out of the parse.
703#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
704pub enum UnknownFlags {
705    /// Offer the token to the positionals. If none can take it, it is an
706    /// unexpected argument.
707    #[default]
708    Value,
709    /// Reject the token.
710    Error,
711}
712
713/// How an argument relates to the `--` separator.
714#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
715pub enum DoubleDash {
716    /// Values may appear on either side of a `--`.
717    #[default]
718    Optional,
719    /// Values are accepted only after a `--`.
720    Required,
721    /// A `--` is kept as a value rather than consumed as a separator.
722    Preserve,
723    /// Once the argument takes a value, behave as if a `--` had been given, so
724    /// the rest of the command line is values. A wrapper can then forward flags
725    /// without its caller typing the separator.
726    Automatic,
727}
728
729/// Something the parser bound.
730#[derive(Debug, Clone, Copy, PartialEq, Eq)]
731pub enum Event<'t, 'a, 'v> {
732    /// A subcommand was selected; parsing continues inside it.
733    Command(&'t Command<'t>),
734    /// A flag was given. `value` is `Some` for a flag that takes one, and
735    /// `negated` is true when the flag was set through its `negate` form.
736    Flag {
737        flag: &'t Flag<'t>,
738        value: Option<&'v [u8]>,
739        negated: bool,
740    },
741    /// A word was bound to a positional argument. A variadic argument produces
742    /// one event per value.
743    Arg {
744        arg: &'t Arg<'t>,
745        value: &'v [u8],
746        /// Whether this value should be split by the argument's declared delimiter.
747        delimit: bool,
748    },
749    /// Ended one clause instance and began the next.
750    ClauseSeparator { clause: Clause<'t> },
751    /// An unmatched word was forwarded as an external command: the name, then
752    /// every remaining token, including flags.
753    External { values: &'a [&'v OsStr] },
754}
755
756/// A binding failure.
757///
758/// Carries the offending token so a caller can render a good message, but no
759/// message of its own: rendering belongs to a cold path, and building a string
760/// here would allocate on the way to reporting that nothing was allocated.
761///
762/// `non_exhaustive`, because an error enum grows: a caller matching on it needs a
763/// fallback arm so that recognizing a new failure is never a breaking change.
764// No `Copy`: one variant owns its message. `Clone` stays, and the enum is still 40 bytes
765// because that variant is boxed, so nothing on the hot path grew.
766#[derive(Debug, Clone, PartialEq, Eq)]
767#[non_exhaustive]
768pub enum Error<'t, 'v> {
769    /// A flag-like token matched no flag in scope. `token` is the whole token as
770    /// typed, so a bundle containing an unrecognized letter reports `-fz` rather
771    /// than the letter alone — which is also the unit in which it is rejected.
772    UnknownFlag { token: &'v [u8] },
773    /// A flag that needs a value did not get one, either because the command
774    /// line ended or because the next token was flag-like.
775    MissingFlagValue { flag: &'t Flag<'t> },
776    /// A word arrived with no argument left to hold it.
777    UnexpectedArg { token: &'v [u8] },
778    /// A word was offered to a `double_dash = "required"` argument before any
779    /// `--` had been seen.
780    ArgRequiresDoubleDash { arg: &'t Arg<'t> },
781    /// A subcommand was selected after this command had already bound an argument.
782    SubcommandConflict { subcommand: &'t Command<'t> },
783    /// The command tree is deeper than [`MAX_DEPTH`].
784    TooDeep,
785
786    // The rest are raised *after* the parse, by whoever owns the target type: they
787    // need to know a value's declared type, which the parser deliberately does not.
788    // They share this enum so that a caller has one error to handle rather than two.
789    /// Something the command requires was never given.
790    MissingRequired {
791        /// The flag or argument's name, as the spec calls it.
792        name: &'t str,
793    },
794    /// A flag that is not repeatable was given more than once.
795    DuplicateFlag {
796        /// The flag's name, as the spec calls it.
797        name: &'t str,
798    },
799    /// A value was given that is not among the declared choices.
800    ///
801    /// Carries the choices rather than the offending value: rendering the value means
802    /// owning it, and an error that allocates on a path this crate promises not to
803    /// allocate on would be a poor trade for a better message. Diagnostics are a
804    /// separate layer.
805    InvalidChoice {
806        name: &'t str,
807        choices: &'t [&'t str],
808    },
809    /// Fewer values than `var_min`.
810    VarTooFew {
811        name: &'t str,
812        min: usize,
813        got: usize,
814    },
815    /// More values than `var_max`.
816    VarTooMany {
817        name: &'t str,
818        max: usize,
819        got: usize,
820    },
821    /// Two flags declared to conflict were both given.
822    ///
823    /// Carries both names because either one alone reads as a puzzle: which flag is
824    /// unwelcome depends entirely on what else is on the command line.
825    ConflictingFlags {
826        /// The flag whose declaration names the conflict.
827        name: &'t str,
828        /// The flag it cannot be given with, as the declaration spells it.
829        other: &'t str,
830    },
831    /// A value was given that the field's type could not be built from.
832    ///
833    /// Boxed, and the only error here that owns anything. Everything else borrows the
834    /// tables or argv, which is what keeps a *successful* parse allocation-free — and the
835    /// box keeps `Error` the size it was, so the `Result` this rides in on the hot path
836    /// does not grow. A value that will not convert has already failed, and a message
837    /// worth reading is worth one allocation.
838    InvalidValue(::std::boxed::Box<InvalidValue<'t>>),
839    /// A required group had none of its members given.
840    ///
841    /// Carries the members as members rather than as a rendered sentence: the caller
842    /// decides how to say it, and a completion asking what would satisfy this needs the
843    /// list rather than the prose.
844    MissingGroup {
845        /// The group's declared name, which appears in the message so a command with
846        /// several groups does not report the same sentence twice.
847        group: &'t str,
848        /// The flags that would satisfy it, as the declaration spells them.
849        members: &'t [&'t str],
850    },
851    /// A subcommand was required, and none was given.
852    MissingSubcommand,
853    /// `--help` or `-h` was given, and `cmd` is what it was asked about.
854    ///
855    /// Not a failure, and returned as one anyway: a parse that stops to print help has not
856    /// produced a value, and every caller already handles the "no value" shape. clap does the
857    /// same thing for the same reason.
858    ///
859    /// `long` distinguishes the two: `-h` prints the short form and `--help` the long one, as
860    /// clap has them. The caller renders — this crate does not print, because a library that
861    /// writes to stdout on its own is one an adopter cannot embed.
862    Help { cmd: &'t Command<'t>, long: bool },
863    /// `arg_required_else_help` found no command-line arguments for `cmd`.
864    ///
865    /// Unlike an explicit help request, this is a usage failure: clap prints the short help to
866    /// stderr and exits with status 2. Keeping the shape separate lets embedders preserve that
867    /// terminal contract without guessing why [`Error::Help`] was returned.
868    MissingArgsHelp { cmd: &'t Command<'t> },
869    /// Recursive long help was requested for `cmd` and every visible descendant.
870    HelpAll { cmd: &'t Command<'t> },
871    /// `--version` or `-V` was asked for. Not a failure either — the caller prints and leaves.
872    ///
873    /// The version string lives in the spec rather than the parse tables. `long` lets the
874    /// caller choose `long_version` for `--version` while `-V` retains the concise value.
875    Version { long: bool },
876    /// Variables under the CLI's `unknown_env` prefix that nothing in it declares.
877    ///
878    /// Boxed like [`Error::InvalidValue`], and for the same reason: it owns the names, and
879    /// the box keeps `Error` the size it was. See [`env`](crate::env).
880    UnknownEnv(::std::boxed::Box<UnknownEnv<'t>>),
881}
882
883/// Why [`Error::UnknownEnv`] refused a parse.
884#[derive(Debug, Clone, PartialEq, Eq)]
885pub struct UnknownEnv<'t> {
886    /// The prefix the CLI declared as its own.
887    pub prefix: &'t str,
888    /// Every variable under it that nothing declares, sorted.
889    pub names: ::std::vec::Vec<::std::string::String>,
890}
891
892/// The high half of every key one declaration's items get.
893///
894/// A derive cannot see other expansions, so it cannot hand out keys from a shared
895/// counter: it hashes the declaration it was given instead. It cannot see a module path
896/// either, which is why the module is mixed in *here* — `module_path!()` is available to
897/// the generated code as a compile-time string, so two byte-identical declarations in
898/// different modules end up with different keys rather than colliding.
899///
900/// `declaration` is a hash the derive computed over the item's own tokens.
901pub const fn key_base(module: &str, declaration: u32) -> u64 {
902    // FNV-1a, continuing from the declaration's hash rather than starting over, so both
903    // halves contribute. Spelled out rather than taken from a `Hasher`, which is not
904    // guaranteed to be stable between compilations — and these are baked into a binary.
905    let mut hash: u32 = declaration;
906    let bytes = module.as_bytes();
907    let mut i = 0;
908    while i < bytes.len() {
909        hash ^= bytes[i] as u32;
910        hash = hash.wrapping_mul(0x0100_0193);
911        i += 1;
912    }
913    (hash as u64) << 32
914}
915
916/// Why a value would not convert into the type its field holds.
917///
918/// Separate from [`Error`] so that the enum stays small: this is reached through a `Box`.
919#[derive(Debug, Clone, PartialEq, Eq)]
920pub struct InvalidValue<'t> {
921    /// The flag or argument's name, as the spec calls it.
922    pub name: &'t str,
923    /// The text that would not convert.
924    pub value: ::std::string::String,
925    /// What the type's own conversion complained about.
926    pub reason: ::std::string::String,
927}
928
929/// A command-wide validation or finalization failure.
930///
931/// Return this from a `#[usage(validate_with = ...)]` hook or from the
932/// `TryFrom` implementation named by `#[usage(try_into = ...)]`. The derive
933/// turns it into the same [`Error::InvalidValue`] diagnostic used by field
934/// conversion, so callers keep one parse error type.
935#[derive(Debug, Clone, PartialEq, Eq)]
936pub struct ValidationError {
937    name: &'static str,
938    value: String,
939    reason: String,
940}
941
942impl ValidationError {
943    /// Start an error attributed to a flag, positional, or command name.
944    pub fn field(name: &'static str) -> Self {
945        Self {
946            name,
947            value: String::new(),
948            reason: String::new(),
949        }
950    }
951
952    /// Record the value that failed the command-wide invariant.
953    pub fn value(mut self, value: impl Into<String>) -> Self {
954        self.value = value.into();
955        self
956    }
957
958    /// Explain the invariant that the value did not satisfy.
959    pub fn reason(mut self, reason: impl Into<String>) -> Self {
960        self.reason = reason.into();
961        self
962    }
963
964    /// Convert this application-level failure into the parser's diagnostic.
965    pub fn into_parse_error<'v>(self) -> Error<'static, 'v> {
966        Error::InvalidValue(Box::new(InvalidValue {
967            name: self.name,
968            value: self.value,
969            reason: self.reason,
970        }))
971    }
972}
973
974/// Interpret a value as UTF-8.
975///
976/// The parser hands back bytes borrowed from `argv`; this is the conversion most
977/// callers want, and the point at which a non-UTF-8 command line is rejected —
978/// but only for the values actually inspected.
979pub fn as_str(value: &[u8]) -> Result<&str, std::str::Utf8Error> {
980    std::str::from_utf8(value)
981}
982
983/// How many entries a group of tables holds in total.
984///
985/// The length for [`concat_flags`] and [`concat_args`], which need it as a const generic — so
986/// it has to be computable separately from the concatenation itself.
987///
988/// ```
989/// use usage_argv::{table_len, Flag};
990///
991/// static A: Flag = Flag { name: "a", ..Flag::BOOL };
992/// static B: Flag = Flag { name: "b", ..Flag::BOOL };
993/// const GROUPS: &[&[&Flag]] = &[&[&A], &[], &[&B]];
994/// const N: usize = table_len(GROUPS);
995/// assert_eq!(N, 2);
996/// ```
997pub const fn table_len<T>(groups: &[&[T]]) -> usize {
998    let mut total = 0;
999    let mut i = 0;
1000    while i < groups.len() {
1001        total += groups[i].len();
1002        i += 1;
1003    }
1004    total
1005}
1006
1007/// `all[start..start + len]`, at compile time, for a table that points into a joined one.
1008///
1009/// A flattened type's metadata names its own run of the parent's joined tables rather than
1010/// keeping a second copy of every entry.
1011#[doc(hidden)]
1012pub const fn __usage_subslice<T>(all: &'static [T], start: usize, len: usize) -> &'static [T] {
1013    let (_, tail) = all.split_at(start);
1014    let (run, _) = tail.split_at(len);
1015    run
1016}
1017
1018/// Join groups of flag tables into one, at compile time.
1019///
1020/// This is how `#[usage(flatten)]` stays free. A flattened struct's flags have to appear in
1021/// the parent's own table, and the parent's macro expansion cannot see them — it has only a
1022/// type. But it can name that type's [`CommandArgs::COMMAND`](crate::spec::CommandArgs::COMMAND),
1023/// and a `const fn` can read through it, so the two lists become one `static` array before the
1024/// program runs. The parser then walks a single flat slice, exactly as it does for a command
1025/// that declared everything itself: flatten costs nothing at run time.
1026///
1027/// Groups are laid out in the order given, which is what lets a flattened group sit *between*
1028/// two of the parent's own declarations — necessary for positional arguments, where order is
1029/// the meaning.
1030///
1031/// `N` must be [`table_len`] of the same groups. It cannot be inferred, and a wrong one fails
1032/// to compile rather than leaving the difference filled with padding.
1033///
1034/// ```
1035/// use usage_argv::{concat_flags, table_len, Flag};
1036///
1037/// static FORCE: Flag = Flag { name: "force", longs: &["force"], ..Flag::BOOL };
1038/// static QUIET: Flag = Flag { name: "quiet", longs: &["quiet"], ..Flag::BOOL };
1039/// static SHARED: &[&Flag] = &[&QUIET];
1040///
1041/// const GROUPS: &[&[&Flag]] = &[&[&FORCE], SHARED];
1042/// static FLAGS: [&Flag; table_len(GROUPS)] = concat_flags(GROUPS);
1043///
1044/// assert_eq!(FLAGS.iter().map(|f| f.name).collect::<Vec<_>>(), ["force", "quiet"]);
1045/// ```
1046pub const fn concat_flags<const N: usize>(
1047    groups: &[&[&'static Flag<'static>]],
1048) -> [&'static Flag<'static>; N] {
1049    // Every slot is written below, but an array has to start somewhere and `MaybeUninit`
1050    // would mean `unsafe`. A `Flag` nobody can reach is cheaper than that.
1051    static PLACEHOLDER: Flag<'static> = Flag::BOOL;
1052    let mut out = [&PLACEHOLDER; N];
1053    let mut at = 0;
1054    let mut g = 0;
1055    while g < groups.len() {
1056        let group = groups[g];
1057        let mut i = 0;
1058        while i < group.len() {
1059            out[at] = group[i];
1060            at += 1;
1061            i += 1;
1062        }
1063        g += 1;
1064    }
1065    assert!(
1066        at == N,
1067        "`N` must be `table_len` of the same groups, or the table would keep a placeholder \
1068         that answers to nothing"
1069    );
1070    out
1071}
1072
1073/// Join groups of argument tables into one, at compile time.
1074///
1075/// The positional counterpart of [`concat_flags`] — see there for why this exists. Order
1076/// matters more here: an argument's position *is* its identity, so a flattened group has to
1077/// land exactly where the field was written.
1078///
1079/// Two functions rather than one generic: each needs a value to fill an array with before
1080/// overwriting it, and there is no way to ask a type parameter for one in a `const fn`.
1081pub const fn concat_args<const N: usize>(
1082    groups: &[&[&'static Arg<'static>]],
1083) -> [&'static Arg<'static>; N] {
1084    static PLACEHOLDER: Arg<'static> = Arg::REQUIRED;
1085    let mut out = [&PLACEHOLDER; N];
1086    let mut at = 0;
1087    let mut g = 0;
1088    while g < groups.len() {
1089        let group = groups[g];
1090        let mut i = 0;
1091        while i < group.len() {
1092            out[at] = group[i];
1093            at += 1;
1094            i += 1;
1095        }
1096        g += 1;
1097    }
1098    assert!(
1099        at == N,
1100        "`N` must be `table_len` of the same groups, or the table would keep a placeholder \
1101         that answers to nothing"
1102    );
1103    out
1104}
1105
1106/// The key `--help` answers to, and the one `-h` does.
1107///
1108/// Reserved rather than generated: a derive builds keys from a hash of the type they came from
1109/// in the high half and an index in the low half, so the top of the range belongs to nobody.
1110/// Generated code compares against these to tell a help request from a flag of its own.
1111pub const HELP_LONG_KEY: u64 = u64::MAX;
1112/// See [`HELP_LONG_KEY`].
1113pub const HELP_SHORT_KEY: u64 = u64::MAX - 1;
1114
1115/// `--help`, which every command answers to.
1116///
1117/// In the parse table and *not* in the metadata, which is the whole trick: the parser has to
1118/// recognise the flag, and help output must not list it — a spec does not declare `--help`, so
1119/// showing one would make the rendered page disagree with the spec it came from.
1120pub static HELP_LONG: Flag<'static> = Flag {
1121    key: HELP_LONG_KEY,
1122    name: "help",
1123    longs: &["help"],
1124    action: ArgAction::HelpLong,
1125    ..Flag::BOOL
1126};
1127
1128/// See [`HELP_LONG_KEY`].
1129pub const VERSION_LONG_KEY: u64 = u64::MAX - 2;
1130/// See [`HELP_LONG_KEY`].
1131pub const VERSION_SHORT_KEY: u64 = u64::MAX - 3;
1132
1133/// `--version`, where the CLI declared one.
1134///
1135/// In the parse table and not in the metadata, exactly as `--help` is: a spec does not declare
1136/// `--version`, so listing one would make the rendered page disagree with the spec it came from.
1137pub static VERSION_LONG: Flag<'static> = Flag {
1138    key: VERSION_LONG_KEY,
1139    name: "version",
1140    longs: &["version"],
1141    action: ArgAction::Version,
1142    ..Flag::BOOL
1143};
1144
1145/// `-V`, which clap also supplies.
1146pub static VERSION_SHORT: Flag<'static> = Flag {
1147    key: VERSION_SHORT_KEY,
1148    name: "version",
1149    shorts: b"V",
1150    action: ArgAction::Version,
1151    ..Flag::BOOL
1152};
1153
1154/// `-h`, which prints the shorter form.
1155pub static HELP_SHORT: Flag<'static> = Flag {
1156    key: HELP_SHORT_KEY,
1157    name: "help",
1158    shorts: b"h",
1159    action: ArgAction::HelpShort,
1160    ..Flag::BOOL
1161};
1162
1163/// A named subcommand of a given command, by name or alias.
1164///
1165/// Free rather than a method because `help` resolves a path *without* descending: the words
1166/// after it are a question about a command rather than a walk into one.
1167///
1168/// Names across every subcommand before any alias, the precedence the grammar states — and
1169/// the reason this is the only implementation of it on argv's side. `ex run` and `ex help run`
1170/// selecting different commands would be exactly the divergence this rule was written to end.
1171#[inline(never)]
1172pub(crate) fn find_named<'t>(cmd: &'t Command<'t>, name: &[u8]) -> Option<&'t Command<'t>> {
1173    let subcommands = || cmd.subcommands.iter().copied();
1174    subcommands()
1175        .find(|c| c.name.as_bytes() == name)
1176        .or_else(|| subcommands().find(|c| c.aliases.iter().any(|a| a.as_bytes() == name)))
1177}
1178
1179/// What a caller should print for a parse failure, and what to exit with.
1180///
1181/// The one entry point a generated `parse()` reaches for, and the reason it exists here rather
1182/// than in the derive: whether the good rendering is available is a *feature of this crate* in
1183/// the adopter's dependency graph, and a `#[cfg]` written into generated code is evaluated in
1184/// the adopter's crate, where the feature is not theirs to see. That is how a metadata field
1185/// once got silently dropped; the answer is that the cfg lives beside the thing it gates.
1186///
1187/// With `diagnostics` on, this is the clap-shaped message. Without it, the error's `Debug`
1188/// form — which is still better than nothing and is what a parser-only build asked for.
1189///
1190/// [`Error::Help`] and [`Error::Version`] are not failures and must be handled before this.
1191#[cfg(feature = "diagnostics")]
1192pub fn render_failure(spec: &spec::Spec<'_>, argv: &[&OsStr], error: &Error<'_, '_>) -> String {
1193    diagnostic::render(spec, argv, error, diagnostic::Style::auto())
1194}
1195
1196/// A parse failure, never coloured.
1197///
1198/// [`render_failure`] asks the environment whether to colour, which is right for a process and
1199/// wrong for anything that keeps the string: a test that asserts on a message, or a snapshot of
1200/// one, would pass or fail by whether stderr happened to be a terminal. The renderer is the
1201/// same; only the answer to that question is fixed.
1202#[cfg(feature = "diagnostics")]
1203pub fn render_failure_plain(
1204    spec: &spec::Spec<'_>,
1205    argv: &[&OsStr],
1206    error: &Error<'_, '_>,
1207) -> String {
1208    diagnostic::render(spec, argv, error, diagnostic::Style::PLAIN)
1209}
1210
1211/// Render a failure through a spec-declared executable view.
1212///
1213/// `argv` is the original full argv, including the view executable as argv0.
1214#[cfg(feature = "diagnostics")]
1215pub fn render_failure_view<'a>(
1216    spec: &'a spec::Spec<'a>,
1217    argv: &[&OsStr],
1218    error: &Error<'_, '_>,
1219    view: &'a spec::ViewMeta<'a>,
1220) -> String {
1221    diagnostic::render_view(spec, argv, error, diagnostic::Style::auto(), view)
1222}
1223
1224/// What a caller should print for a parse failure, without the renderer that makes it readable.
1225///
1226/// See the other half. A caller that wants the clap-shaped message turns on `diagnostics`;
1227/// this is what a parser-only build asked for, and it still says which error it was.
1228#[cfg(all(feature = "spec", not(feature = "diagnostics")))]
1229pub fn render_failure(spec: &spec::Spec<'_>, argv: &[&OsStr], error: &Error<'_, '_>) -> String {
1230    let _ = (spec, argv);
1231    ::std::format!("error: {error:?}\n")
1232}
1233
1234/// A parse failure without the renderer, which is plain either way.
1235#[cfg(all(feature = "spec", not(feature = "diagnostics")))]
1236pub fn render_failure_plain(
1237    spec: &spec::Spec<'_>,
1238    argv: &[&OsStr],
1239    error: &Error<'_, '_>,
1240) -> String {
1241    render_failure(spec, argv, error)
1242}
1243
1244/// Render a failure through a declared view without the optional diagnostics renderer.
1245#[cfg(all(feature = "spec", not(feature = "diagnostics")))]
1246pub fn render_failure_view(
1247    spec: &spec::Spec<'_>,
1248    argv: &[&OsStr],
1249    error: &Error<'_, '_>,
1250    view: &spec::ViewMeta<'_>,
1251) -> String {
1252    let _ = (spec, argv, view);
1253    ::std::format!("error: {error:?}\n")
1254}
1255
1256/// Answer an error from a generated `parse()` the way a command-line program does, and leave.
1257///
1258/// A help request goes to stdout and exits 0; a request for help because nothing was given goes
1259/// to stderr and exits 2; any other failure is rendered to stderr and exits 2, which is clap's
1260/// status, so a script that checks for it keeps working. [`Error::Version`] is the caller's to
1261/// answer before this, since only the generated code knows the version it prints.
1262///
1263/// Here rather than expanded into every CLI: the body is the same for all of them, and only the
1264/// spec — which carries any computed identity the generated code has already evaluated — and
1265/// the tables differ. `all_argv` includes argv0, which a view's route needs; `argv` does not.
1266#[cfg(feature = "spec")]
1267#[doc(hidden)]
1268pub fn __usage_exit_on_error(
1269    error: Error<'_, '_>,
1270    spec: &spec::Spec<'_>,
1271    root: &Command<'_>,
1272    all_argv: &[&OsStr],
1273    argv: &[&OsStr],
1274    view: Option<&spec::ViewMeta<'_>>,
1275) -> ! {
1276    let (want, to_stderr, cmd) = match error {
1277        Error::Help { cmd, long } => {
1278            let want = if long {
1279                help::Page::Long
1280            } else {
1281                help::Page::Short
1282            };
1283            (want, false, cmd)
1284        }
1285        Error::MissingArgsHelp { cmd } => (help::Page::Short, true, cmd),
1286        Error::HelpAll { cmd } => (help::Page::All, false, cmd),
1287        error => {
1288            let failure = match view {
1289                Some(view) => render_failure_view(spec, all_argv, &error, view),
1290                None => render_failure(spec, argv, &error),
1291            };
1292            __usage_eprint(format_args!("{failure}"));
1293            __usage_process_exit(2);
1294        }
1295    };
1296    let style = if to_stderr {
1297        help::Style::auto_stderr()
1298    } else {
1299        help::Style::auto()
1300    };
1301    let page = match view {
1302        Some(view) => help::page_view(spec, root, all_argv, cmd, view, want, style),
1303        None => help::page(spec, root, argv, cmd, want, style),
1304    };
1305    // `None` is only reachable if the command came from another CLI's tables.
1306    if let Some(page) = page {
1307        if to_stderr {
1308            __usage_eprint(format_args!("{page}"));
1309        } else {
1310            __usage_print(format_args!("{page}"));
1311        }
1312    }
1313    __usage_process_exit(if to_stderr { 2 } else { 0 })
1314}
1315
1316/// Print `bin version` for a generated `parse()`, and leave.
1317///
1318/// The half of [`__usage_exit_on_error`] the generated code answers itself, because the
1319/// version is a declaration of that CLI; the printing and the exit are the same everywhere.
1320#[cfg(feature = "spec")]
1321#[doc(hidden)]
1322pub fn __usage_exit_version(
1323    bin: &str,
1324    view: Option<&spec::ViewMeta<'_>>,
1325    version: &dyn std::fmt::Display,
1326) -> ! {
1327    let bin = view.map_or(bin, |view| view.bin);
1328    __usage_print(format_args!("{bin} {version}\n"));
1329    __usage_process_exit(0)
1330}
1331
1332/// What a caller should print for the deprecations a command line used.
1333///
1334/// The same arrangement as [`render_failure`], and for the same reason: whether the coloured
1335/// rendering is available is a feature of *this* crate in the adopter's dependency graph, so the
1336/// `#[cfg]` lives beside the thing it gates rather than in generated code.
1337///
1338/// Warnings are not failures. A caller prints these to stderr and carries on.
1339#[cfg(feature = "diagnostics")]
1340pub fn render_warnings(warnings: &[warn::Warning<'_>]) -> String {
1341    diagnostic::render_warnings(warnings, diagnostic::Style::auto())
1342}
1343
1344/// The same wording without the renderer that colours it. See the other half.
1345#[cfg(all(feature = "spec", not(feature = "diagnostics")))]
1346pub fn render_warnings(warnings: &[warn::Warning<'_>]) -> String {
1347    warn::render_warnings(warnings)
1348}
1349
1350/// The word a tool sends to ask a binary for its own spec.
1351///
1352/// Not a flag and not a command: a spec request is not something this CLI *does*, so it is
1353/// answered before the parse and stays out of the tables — the same reason
1354/// `__complete_word__` is a word rather than a subcommand. It also keeps the endpoint from
1355/// perturbing the document it prints, which a declared flag would not.
1356pub const SPEC_REQUEST: &str = "__usage_spec__";
1357
1358/// Whether this argv asks for the spec rather than for the CLI to run.
1359///
1360/// Only the first word counts: `mycli build __usage_spec__` passes the word through as an
1361/// ordinary value, because a request is the whole invocation or it is nothing.
1362///
1363/// A root that declares a command of that name keeps it, which is the precedence the `help`
1364/// subcommand already has. The check is here rather than in the derive because a `Cli` derive
1365/// expands one struct and cannot see the variant names of a separate `Subcommands` enum — the
1366/// static tables can.
1367pub fn is_spec_request(root: &Command<'_>, argv: &[&OsStr]) -> bool {
1368    let [first, ..] = argv else { return false };
1369    first.as_encoded_bytes() == SPEC_REQUEST.as_bytes()
1370        && find_named(root, SPEC_REQUEST.as_bytes()).is_none()
1371}
1372
1373/// Whether a flag is one of the two the parser supplies rather than the CLI declaring it.
1374pub fn is_help_flag(flag: &Flag<'_>) -> bool {
1375    matches!(
1376        flag.action,
1377        ArgAction::Help | ArgAction::HelpShort | ArgAction::HelpLong | ArgAction::HelpAll
1378    )
1379}
1380
1381/// Whether a flag is one of the two the parser supplies for `--version`.
1382pub fn is_version_flag(flag: &Flag<'_>) -> bool {
1383    flag.action == ArgAction::Version
1384}
1385
1386/// Whether one exact root argument selects a declared or synthesized version action.
1387///
1388/// Declared flags are checked first because they shadow the built-in `--version` and `-V`
1389/// spellings. Executable views use this before projection so custom version spellings keep
1390/// reporting the package that owns the view.
1391pub fn is_version_arg(cmd: &Command<'_>, word: &OsStr) -> bool {
1392    let token = word.as_encoded_bytes();
1393    if let Some(long) = token.strip_prefix(b"--") {
1394        if let Some(flag) = cmd.flags.iter().find(|flag| {
1395            flag.longs
1396                .iter()
1397                .any(|spelling| spelling.as_bytes() == long)
1398        }) {
1399            return is_version_flag(flag);
1400        }
1401        if cmd.flags.iter().any(|flag| {
1402            flag.negate
1403                .is_some_and(|spelling| spelling.as_bytes() == long)
1404        }) {
1405            return false;
1406        }
1407        return long == b"version" && cmd.version && !cmd.disable_version_flag;
1408    }
1409    if let [b'-', short] = token {
1410        if let Some(flag) = cmd.flags.iter().find(|flag| has_byte(flag.shorts, *short)) {
1411            return is_version_flag(flag);
1412        }
1413        return *short == b'V' && cmd.version && !cmd.disable_version_flag;
1414    }
1415    false
1416}
1417
1418/// Resolve a subcommand by name or alias, at compile time.
1419///
1420/// For [`Command::default_subcommand`], which names a command that a derive cannot see: the
1421/// variants of a subcommand enum are a different macro expansion, so the name is all the
1422/// parent has. Searching the list in a `const fn` closes that gap — the answer is the same
1423/// `&'static` the table already holds, found before the program runs.
1424///
1425/// A name no subcommand answers to is a **compile error**, since this panics during const
1426/// evaluation. That is the whole point of doing it here rather than at startup.
1427///
1428/// ```
1429/// use usage_argv::{find_subcommand, Command};
1430///
1431/// static RUN: Command = Command { name: "run", ..Command::EMPTY };
1432/// static SUBS: &[&Command] = &[&RUN];
1433/// static ROOT: Command = Command {
1434///     name: "ex",
1435///     subcommands: SUBS,
1436///     default_subcommand: Some(find_subcommand(SUBS, "run")),
1437///     ..Command::EMPTY
1438/// };
1439/// assert_eq!(ROOT.default_subcommand.unwrap().name, "run");
1440/// ```
1441pub const fn find_subcommand<'a>(
1442    subcommands: &'a [&'a Command<'a>],
1443    name: &str,
1444) -> &'a Command<'a> {
1445    // Names first, then aliases: a command's own name outranks another command's alias, so
1446    // the answer does not depend on the order the table happens to list them in. Checking
1447    // each candidate's name *and* aliases in one pass instead let whichever command came
1448    // first win, and usage-lib resolved the same spec to the last one.
1449    let mut i = 0;
1450    while i < subcommands.len() {
1451        if str_eq(subcommands[i].name, name) {
1452            return subcommands[i];
1453        }
1454        i += 1;
1455    }
1456    // Aliases answer too, because usage-lib resolves the name against names, aliases and
1457    // hidden aliases alike — so a spec may point `default_subcommand` at any of them.
1458    let mut i = 0;
1459    while i < subcommands.len() {
1460        let candidate = subcommands[i];
1461        let mut a = 0;
1462        while a < candidate.aliases.len() {
1463            if str_eq(candidate.aliases[a], name) {
1464                return candidate;
1465            }
1466            a += 1;
1467        }
1468        i += 1;
1469    }
1470    panic!("`default_subcommand` names a command that this one does not have")
1471}
1472
1473/// Refuse two subcommands that answer to the same name, aliases included.
1474///
1475/// A derive expansion can validate aliases written on one enum, but aliases may also live on
1476/// the independently expanded `Args` structs its variants wrap. This final, joined-table check
1477/// is where both declarations are visible.
1478pub const fn assert_unique_subcommand_names(subcommands: &[&Command<'_>]) {
1479    const fn form<'a>(cmd: &'a Command<'a>, at: usize) -> Option<&'a str> {
1480        if at == 0 {
1481            Some(cmd.name)
1482        } else if at <= cmd.aliases.len() {
1483            Some(cmd.aliases[at - 1])
1484        } else {
1485            None
1486        }
1487    }
1488
1489    let mut command = 0;
1490    while command < subcommands.len() {
1491        let mut at = 0;
1492        while let Some(name) = form(subcommands[command], at) {
1493            let mut other_command = command;
1494            while other_command < subcommands.len() {
1495                let mut other_at = if other_command == command { at + 1 } else { 0 };
1496                while let Some(other) = form(subcommands[other_command], other_at) {
1497                    assert!(
1498                        !str_eq(name, other),
1499                        "two subcommands answer to the same name, counting aliases"
1500                    );
1501                    other_at += 1;
1502                }
1503                other_command += 1;
1504            }
1505            at += 1;
1506        }
1507        command += 1;
1508    }
1509}
1510
1511/// Assert that flags scoped to a clause do not reuse a command-level spelling.
1512///
1513/// Derive-generated command tables include scoped flags so the parser can find them. Entries
1514/// that share a key are therefore the same declaration and are ignored here; every other pair
1515/// must have disjoint long, short, alias, and negated spellings.
1516pub const fn assert_clause_flag_spellings(command: &Command<'_>) {
1517    let Some(clause) = command.clause else {
1518        return;
1519    };
1520    let mut scoped_at = 0;
1521    while scoped_at < clause.flags.len() {
1522        let scoped = clause.flags[scoped_at];
1523        let mut command_at = 0;
1524        while command_at < command.flags.len() {
1525            let flag = command.flags[command_at];
1526            if flag.key != scoped.key && const_flag_forms_overlap(flag, scoped) {
1527                panic!("a clause flag spelling conflicts with a command-level flag");
1528            }
1529            command_at += 1;
1530        }
1531        scoped_at += 1;
1532    }
1533}
1534
1535const fn const_flag_forms_overlap(a: &Flag<'_>, b: &Flag<'_>) -> bool {
1536    let mut i = 0;
1537    while i < a.longs.len() {
1538        let mut j = 0;
1539        while j < b.longs.len() {
1540            if const_bytes_eq(a.longs[i].as_bytes(), b.longs[j].as_bytes()) {
1541                return true;
1542            }
1543            j += 1;
1544        }
1545        if let Some(negate) = b.negate
1546            && const_bytes_eq(a.longs[i].as_bytes(), negate.as_bytes())
1547        {
1548            return true;
1549        }
1550        i += 1;
1551    }
1552    i = 0;
1553    while i < a.shorts.len() {
1554        let mut j = 0;
1555        while j < b.shorts.len() {
1556            if a.shorts[i] == b.shorts[j] {
1557                return true;
1558            }
1559            j += 1;
1560        }
1561        i += 1;
1562    }
1563    if let Some(negate) = a.negate {
1564        let mut j = 0;
1565        while j < b.longs.len() {
1566            if const_bytes_eq(negate.as_bytes(), b.longs[j].as_bytes()) {
1567                return true;
1568            }
1569            j += 1;
1570        }
1571        if let Some(other) = b.negate
1572            && const_bytes_eq(negate.as_bytes(), other.as_bytes())
1573        {
1574            return true;
1575        }
1576    }
1577    false
1578}
1579
1580const fn const_bytes_eq(a: &[u8], b: &[u8]) -> bool {
1581    if a.len() != b.len() {
1582        return false;
1583    }
1584    let mut i = 0;
1585    while i < a.len() {
1586        if a[i] != b[i] {
1587            return false;
1588        }
1589        i += 1;
1590    }
1591    true
1592}
1593
1594/// `==` on strings, in a `const fn`.
1595const fn str_eq(a: &str, b: &str) -> bool {
1596    let (a, b) = (a.as_bytes(), b.as_bytes());
1597    if a.len() != b.len() {
1598        return false;
1599    }
1600    let mut i = 0;
1601    while i < a.len() {
1602        if a[i] != b[i] {
1603            return false;
1604        }
1605        i += 1;
1606    }
1607    true
1608}
1609
1610/// Rebuild an [`OsString`] from bytes the parser handed back.
1611///
1612/// This is the reverse of [`OsStr::as_encoded_bytes`], and it is how a `PathBuf` field
1613/// receives a filename the operating system accepts but UTF-8 does not — `/tmp/\xff` stays
1614/// `/tmp/\xff` rather than becoming a *different* filename with `U+FFFD` in it.
1615///
1616/// Where the platform cannot hold those bytes, they are handed back in the `Err` — as
1617/// `String::from_utf8` does — so the caller can name the value in its error without this
1618/// having to copy it for a case that is nearly never taken.
1619///
1620/// # Why this is not `unsafe`, and why it is not lossless everywhere
1621///
1622/// On **Unix** an `OsString` is an arbitrary byte sequence, so the conversion is total and
1623/// uses the safe [`OsStringExt::from_vec`]. Every byte survives, which is the case that
1624/// matters: non-UTF-8 filenames are ordinary there.
1625///
1626/// [`OsStringExt::from_vec`]: std::os::unix::ffi::OsStringExt::from_vec
1627///
1628/// On **Windows** the encoding is WTF-8, where not every byte sequence is valid, and the only
1629/// constructor that accepts one is `OsString::from_encoded_bytes_unchecked` — whose
1630/// precondition this function cannot enforce. It takes a `Vec<u8>` from a safe caller, so
1631/// there is no way to know the bytes came from `as_encoded_bytes` rather than from anywhere
1632/// else, and a safe function with a precondition that can be violated is unsound however
1633/// carefully its callers behave today.
1634///
1635/// So on Windows the bytes go through UTF-8, and one that is not valid UTF-8 is refused
1636/// rather than assumed. What that gives up is a Windows argument containing an unpaired
1637/// surrogate, which is reported instead of accepted; what it buys is that this crate needs no
1638/// `unsafe` at all.
1639pub fn os_string_from_bytes(value: Vec<u8>) -> Result<OsString, Vec<u8>> {
1640    #[cfg(unix)]
1641    {
1642        Ok(std::os::unix::ffi::OsStringExt::from_vec(value))
1643    }
1644    #[cfg(not(unix))]
1645    {
1646        match String::from_utf8(value) {
1647            Ok(text) => Ok(OsString::from(text)),
1648            Err(bad) => Err(bad.into_bytes()),
1649        }
1650    }
1651}
1652
1653/// A sigil argument given its sigil and nothing after it. Out of line and cold: two places in the
1654/// parser report it, and neither is on the path of a command line that parses.
1655#[cold]
1656#[inline(never)]
1657fn sigil_without_value<'t, 'v>(arg: &'t Arg<'t>, token: &[u8], sigil: &[u8]) -> Error<'t, 'v> {
1658    invalid_value_error(
1659        arg.name,
1660        as_str(token).unwrap_or_default().to_string(),
1661        format!(
1662            "expected a value after sigil {:?}",
1663            as_str(sigil).unwrap_or_default()
1664        ),
1665    )
1666}
1667
1668/// One [`Error::InvalidValue`], built out of line.
1669///
1670/// Cold and never inlined on purpose: this is the failure path of every value
1671/// conversion in every generated `build`, and inlining it there is what made
1672/// those functions large.
1673#[cold]
1674#[inline(never)]
1675pub(crate) fn invalid_value_error<'t, 'v>(
1676    name: &'t str,
1677    value: String,
1678    reason: String,
1679) -> Error<'t, 'v> {
1680    Error::InvalidValue(Box::new(InvalidValue {
1681        name,
1682        value,
1683        reason,
1684    }))
1685}
1686
1687/// One [`Error::InvalidValue`] for a word that was not UTF-8.
1688///
1689/// The error half of what a generated `build` does per text field: the check stays
1690/// inline at the field, and this — the lossy rendering and the allocations — lives
1691/// here once instead of once per field.
1692#[cold]
1693#[inline(never)]
1694pub fn invalid_utf8_value<'t, 'v>(name: &'t str, bad: std::string::FromUtf8Error) -> Error<'t, 'v> {
1695    invalid_value_error(
1696        name,
1697        String::from_utf8_lossy(bad.as_bytes()).into_owned(),
1698        bad.utf8_error().to_string(),
1699    )
1700}
1701
1702/// One [`Error::InvalidValue`] for a value whose type would not build from it.
1703///
1704/// Takes the reason as `&dyn Display` so one copy serves every `FromStr` error type.
1705#[cold]
1706#[inline(never)]
1707pub fn invalid_parsed_value<'t, 'v>(
1708    name: &'t str,
1709    value: String,
1710    reason: &dyn std::fmt::Display,
1711) -> Error<'t, 'v> {
1712    invalid_value_error(name, value, reason.to_string())
1713}
1714
1715/// One [`Error::InvalidValue`] for a word that is not one of a value enum's choices.
1716#[cold]
1717#[inline(never)]
1718pub fn invalid_choice_value<'t, 'v>(name: &'t str, value: String) -> Error<'t, 'v> {
1719    invalid_value_error(name, value, String::from("not one of the declared values"))
1720}
1721
1722/// One [`Error::InvalidValue`] for bytes the platform cannot hold in a path.
1723#[cold]
1724#[inline(never)]
1725pub fn invalid_os_value<'t, 'v>(name: &'t str, bytes: Vec<u8>) -> Error<'t, 'v> {
1726    invalid_value_error(
1727        name,
1728        String::from_utf8_lossy(&bytes).into_owned(),
1729        "this platform cannot hold these bytes in a path".to_string(),
1730    )
1731}
1732
1733/// Convert every repeated value of one text field, reporting `name` for the
1734/// first that is not UTF-8.
1735///
1736/// The shared body of what a generated `build` does per collecting text field:
1737/// one loop in the binary rather than one per field. Converts element by
1738/// element rather than with `collect` so the error can carry the value that
1739/// failed rather than only that one did.
1740///
1741/// The empty case is answered here rather than in the shared loop, and this is
1742/// what keeps sharing the loop free: a command at mise's scale declares dozens
1743/// of collecting fields and a command line names one or two of them, so most of
1744/// these calls have nothing to convert. Testing that at the field costs a branch;
1745/// reaching the loop to learn it costs the call.
1746#[inline]
1747pub fn utf8_values<'t, 'v>(
1748    values: Vec<Vec<u8>>,
1749    name: &'t str,
1750) -> Result<Vec<String>, Error<'t, 'v>> {
1751    if values.is_empty() {
1752        return Ok(Vec::new());
1753    }
1754    utf8_values_given(values, name)
1755}
1756
1757#[inline(never)]
1758fn utf8_values_given<'t, 'v>(
1759    values: Vec<Vec<u8>>,
1760    name: &'t str,
1761) -> Result<Vec<String>, Error<'t, 'v>> {
1762    let mut out = Vec::with_capacity(values.len());
1763    for value in values {
1764        match String::from_utf8(value) {
1765            Ok(text) => out.push(text),
1766            Err(bad) => return Err(invalid_utf8_value(name, bad)),
1767        }
1768    }
1769    Ok(out)
1770}
1771
1772/// Convert every repeated value of one field through
1773/// [`FromStr`](std::str::FromStr), reporting `name` for the first that fails.
1774///
1775/// Monomorphized once per target type rather than expanded once per field, and
1776/// the empty case is answered at the field for the reason [`utf8_values`] gives.
1777#[inline]
1778pub fn parsed_values<'t, 'v, T>(
1779    values: Vec<Vec<u8>>,
1780    name: &'t str,
1781) -> Result<Vec<T>, Error<'t, 'v>>
1782where
1783    T: std::str::FromStr,
1784    T::Err: std::fmt::Display,
1785{
1786    if values.is_empty() {
1787        return Ok(Vec::new());
1788    }
1789    parsed_values_given(values, name)
1790}
1791
1792#[inline(never)]
1793fn parsed_values_given<'t, 'v, T>(
1794    values: Vec<Vec<u8>>,
1795    name: &'t str,
1796) -> Result<Vec<T>, Error<'t, 'v>>
1797where
1798    T: std::str::FromStr,
1799    T::Err: std::fmt::Display,
1800{
1801    let mut out = Vec::with_capacity(values.len());
1802    for value in values {
1803        let text = match String::from_utf8(value) {
1804            Ok(text) => text,
1805            Err(bad) => return Err(invalid_utf8_value(name, bad)),
1806        };
1807        match text.parse() {
1808            Ok(parsed) => out.push(parsed),
1809            Err(reason) => return Err(invalid_parsed_value(name, text, &reason)),
1810        }
1811    }
1812    Ok(out)
1813}
1814
1815/// Convert every repeated value of one path-like field, reporting `name` for
1816/// the first the platform cannot hold.
1817///
1818/// `T` is what the field collects — [`PathBuf`](std::path::PathBuf) or
1819/// [`OsString`] — so one body serves both. The same platform note as
1820/// [`os_string_from_bytes`] applies: lossless on Unix, partial on Windows. The
1821/// empty case is answered at the field for the reason [`utf8_values`] gives.
1822#[inline]
1823pub fn os_values<'t, 'v, T: From<OsString>>(
1824    values: Vec<Vec<u8>>,
1825    name: &'t str,
1826) -> Result<Vec<T>, Error<'t, 'v>> {
1827    if values.is_empty() {
1828        return Ok(Vec::new());
1829    }
1830    os_values_given(values, name)
1831}
1832
1833#[inline(never)]
1834fn os_values_given<'t, 'v, T: From<OsString>>(
1835    values: Vec<Vec<u8>>,
1836    name: &'t str,
1837) -> Result<Vec<T>, Error<'t, 'v>> {
1838    let mut out = Vec::with_capacity(values.len());
1839    for value in values {
1840        match os_string_from_bytes(value) {
1841            Ok(os) => out.push(T::from(os)),
1842            Err(bytes) => return Err(invalid_os_value(name, bytes)),
1843        }
1844    }
1845    Ok(out)
1846}
1847
1848/// What a generated `apply` stores for a flag that takes one value: the word, or nothing
1849/// when the flag arrived without one.
1850///
1851/// Out of line because the copy is an allocation, a `memcpy`, and the drop of whatever the
1852/// field held before — a few dozen instructions that would otherwise be expanded at every
1853/// value-taking field of every command.
1854#[doc(hidden)]
1855#[inline(never)]
1856pub fn bind_text(slot: &mut Vec<u8>, value: Option<&[u8]>) {
1857    *slot = value.map(<[u8]>::to_vec).unwrap_or_default();
1858}
1859
1860/// [`bind_text`] for an `Option<T>` field, which a flag without a value still fills.
1861#[doc(hidden)]
1862#[inline(never)]
1863pub fn bind_some_text(slot: &mut Option<Vec<u8>>, value: Option<&[u8]>) {
1864    *slot = Some(value.map(<[u8]>::to_vec).unwrap_or_default());
1865}
1866
1867/// [`bind_text`] for an `Option<Option<T>>` field, where a flag given without a value is
1868/// the inner `None`.
1869#[doc(hidden)]
1870#[inline(never)]
1871pub fn bind_optional_text(slot: &mut Option<Vec<u8>>, value: Option<&[u8]>) {
1872    *slot = value.map(<[u8]>::to_vec);
1873}
1874
1875/// [`bind_text`] for a collecting field: one more occurrence, appended.
1876#[doc(hidden)]
1877#[inline(never)]
1878pub fn bind_push_text(slot: &mut Vec<Vec<u8>>, value: Option<&[u8]>) {
1879    slot.push(value.map(<[u8]>::to_vec).unwrap_or_default());
1880}
1881
1882/// [`bind_push_text`] for a field with a value delimiter: every part, appended in order.
1883#[doc(hidden)]
1884#[inline(never)]
1885pub fn bind_push_split(slot: &mut Vec<Vec<u8>>, value: Option<&[u8]>, delimiter: u8) {
1886    for part in value.unwrap_or_default().split(|b| *b == delimiter) {
1887        slot.push(part.to_vec());
1888    }
1889}
1890
1891/// A single binding pass over `argv`.
1892///
1893/// [`Command::default_subcommand_flags`] adds a read-only lookahead before binding
1894/// to choose an implicit command boundary.
1895///
1896/// Created with [`Parser::new`] and driven with [`Parser::next_event`].
1897pub struct Parser<'t, 'a, 'v> {
1898    argv: &'a [&'v OsStr],
1899    /// Index of the next token to read.
1900    pos: usize,
1901    /// The command currently in scope.
1902    cmd: &'t Command<'t>,
1903    /// The canonical root, used to hide root globals omitted by an executable view.
1904    #[cfg(feature = "spec")]
1905    root: &'t Command<'t>,
1906    /// The executable projection being parsed, if argv0 selected one.
1907    #[cfg(feature = "spec")]
1908    view: Option<&'t spec::ViewMeta<'t>>,
1909    /// What an unrecognized flag-like token means in the command currently in scope.
1910    ///
1911    /// Carried rather than looked up, because it is inherited: a command that states
1912    /// nothing keeps what the enclosing one said, and walking back up the ancestors on
1913    /// every unrecognized token would pay for the inheritance at the wrong moment.
1914    unknown_flags: UnknownFlags,
1915    /// Effective inherited trailing-delimiter policy.
1916    dont_delimit_trailing_values: bool,
1917    /// The chain above `cmd`, used to find inherited global flags. Fixed size so
1918    /// that nothing is allocated.
1919    ancestors: [Option<&'t Command<'t>>; MAX_DEPTH],
1920    depth: usize,
1921    /// Bytes left in a short-flag bundle, if one is partly read.
1922    bundle: &'v [u8],
1923    /// The whole token the current bundle came from, so an error raised part way
1924    /// through it can still name what the user typed.
1925    bundle_token: &'v [u8],
1926    /// A variadic flag that is still collecting values.
1927    collecting: Option<&'t Flag<'t>>,
1928    /// Where the command in scope began, as an index into `argv`.
1929    cmd_start: usize,
1930    /// Where each ancestor's own words began, in step with `ancestors`.
1931    starts: [usize; MAX_DEPTH],
1932    /// How many values it has taken, so a bound can stop it.
1933    collected: u32,
1934    /// Which of `cmd.args` is next to fill.
1935    arg_pos: usize,
1936    /// How many words the variadic at `arg_pos` has taken, for the same reason.
1937    arg_taken: u32,
1938    /// Whether any word has been bound to a positional of `cmd`. Once one has,
1939    /// no further word can select a subcommand.
1940    arg_filled: bool,
1941    /// Whether this command has bound any flag or positional. Unlike
1942    /// `arg_filled`, flags count because clap's command policy treats both as
1943    /// arguments that exclude a later subcommand.
1944    command_arg_found: bool,
1945    positional_arg_found: bool,
1946    /// Whether flag interpretation has stopped. A `--` does this, and so does an
1947    /// `automatic` argument taking a value.
1948    flags_stopped: bool,
1949    /// Whether a `--` was actually consumed as a separator.
1950    ///
1951    /// Tracked apart from `flags_stopped` because the two can differ: an
1952    /// `automatic` argument stops flag interpretation without any separator being
1953    /// typed, and a `preserve` argument keeps one as a value rather than
1954    /// consuming it. Callers asking this question want to know what the user
1955    /// wrote, not what state the parser reached.
1956    separator_seen: bool,
1957    /// Whether a root clause separator was consumed, so empty-default routing cannot fire.
1958    clause_separator_seen: bool,
1959    /// Whether the default subcommand has already been taken.
1960    ///
1961    /// Once, per parse: a default subcommand that itself declares one would otherwise
1962    /// descend on every word until the tree ran out.
1963    default_taken: bool,
1964    /// Whether this parse reads the words before a cursor. The word under the cursor is still
1965    /// to be typed, so the line is not an empty invocation and `default_subcommand_on_empty`
1966    /// must not route away from the root's own subcommands and flags.
1967    completing: bool,
1968    /// First default-only flag, when lookahead found no explicit sibling.
1969    default_flag_at: Option<usize>,
1970    /// Cursor just after the implicit boundary bundle, whose shorts keep parent ownership.
1971    default_bundle_end: usize,
1972    /// Set once a fatal error has been reported, so iteration stops.
1973    done: bool,
1974    /// Whether declared built-in actions stop parsing with their action error.
1975    ///
1976    /// Invocation parsing does; completion walking only needs the grammar position after the
1977    /// flag, and must not execute an action while inspecting a partial command line.
1978    action_errors: bool,
1979    /// The `argv` range the `help` *word* resolved as a command path, if one was typed.
1980    ///
1981    /// Empty for `--help`, which asks about wherever the parse had got to. For the word, the
1982    /// question is about a command deeper than the parse reached, and only this walk knows
1983    /// which tokens named it: a caller re-scanning `argv` would count a flag's detached value
1984    /// that happens to spell a sibling's name. Two indices rather than the commands
1985    /// themselves, so the parser keeps allocating nothing.
1986    help_span: (usize, usize),
1987    /// An implicit clause boundary follows the positional event that completed it.
1988    pending_clause_boundary: ::core::option::Option<&'t Clause<'t>>,
1989}
1990
1991impl<'t: 'v, 'a, 'v> Parser<'t, 'a, 'v> {
1992    /// Begin parsing `argv` against `root`.
1993    ///
1994    /// `argv` excludes the program name.
1995    pub fn new(root: &'t Command<'t>, argv: &'a [&'v OsStr]) -> Self {
1996        Self::with_action_errors(root, argv, true)
1997    }
1998
1999    /// Begin a non-executing parse for completion walking.
2000    #[cfg(feature = "complete")]
2001    pub(crate) fn for_completion(root: &'t Command<'t>, argv: &'a [&'v OsStr]) -> Self {
2002        let mut parser = Self::with_action_errors(root, argv, false);
2003        parser.completing = true;
2004        parser
2005    }
2006
2007    fn with_action_errors(
2008        root: &'t Command<'t>,
2009        argv: &'a [&'v OsStr],
2010        action_errors: bool,
2011    ) -> Self {
2012        let mut parser = Parser {
2013            argv,
2014            pos: 0,
2015            cmd: root,
2016            #[cfg(feature = "spec")]
2017            root,
2018            #[cfg(feature = "spec")]
2019            view: None,
2020            unknown_flags: match root.unknown_flags {
2021                ::core::option::Option::Some(mode) => mode,
2022                // Nothing above the root to inherit from, so the default stands.
2023                ::core::option::Option::None => UnknownFlags::Value,
2024            },
2025            dont_delimit_trailing_values: root.dont_delimit_trailing_values,
2026            ancestors: [None; MAX_DEPTH],
2027            depth: 0,
2028            bundle: &[],
2029            bundle_token: &[],
2030            collecting: None,
2031            cmd_start: 0,
2032            starts: [0; MAX_DEPTH],
2033            collected: 0,
2034            arg_pos: 0,
2035            arg_taken: 0,
2036            arg_filled: false,
2037            command_arg_found: false,
2038            positional_arg_found: false,
2039            flags_stopped: false,
2040            separator_seen: false,
2041            clause_separator_seen: false,
2042            default_taken: false,
2043            completing: false,
2044            default_flag_at: None,
2045            default_bundle_end: 0,
2046            done: false,
2047            action_errors,
2048            help_span: (0, 0),
2049            pending_clause_boundary: ::core::option::Option::None,
2050        };
2051        if root.default_subcommand_flags {
2052            parser.default_flag_at = parser.default_flag_route();
2053        }
2054        parser
2055    }
2056
2057    /// Find the implicit boundary without binding anything. Parent spellings win while
2058    /// scanning the prefix; after the boundary the ordinary child/global scope applies.
2059    /// Unknown flags stop lookahead because their value arity cannot be guessed.
2060    fn default_flag_route(&self) -> Option<usize> {
2061        let default = self.cmd.default_subcommand?;
2062        let mut at = None;
2063        let mut i = 0;
2064        while let Some(token) = self.argv.get(i).map(bytes) {
2065            let scope = if at.is_some() { default } else { self.cmd };
2066            if token == b"--"
2067                || token == b"-"
2068                || scope.clause.is_some_and(|c| c.separator == Some(token))
2069            {
2070                return at;
2071            }
2072            if !is_flag_like(token) {
2073                // A sibling name before any default-only flag stays on the parent.
2074                // After one, later words are the default command's args (`-u pkg`
2075                // when `pkg` is also a command).
2076                if at.is_none()
2077                    && (self.find_subcommand(token).is_some()
2078                        || (token == b"help" && !self.cmd.disable_help_subcommand))
2079                {
2080                    return None;
2081                }
2082                return at;
2083            }
2084            let mut value_flag = None;
2085            let mut attached = None;
2086            if let Some(body) = token.strip_prefix(b"--") {
2087                let end = body.iter().position(|b| *b == b'=').unwrap_or(body.len());
2088                let name = slice::before(body, end);
2089                let parent = self.find_long(name).or_else(|| self.find_negation(name));
2090                if parent.is_none()
2091                    && ((name == b"help" && !self.cmd.disable_help_flag)
2092                        || (name == b"version"
2093                            && self.cmd.version
2094                            && !self.cmd.disable_version_flag))
2095                {
2096                    i += 1;
2097                    continue;
2098                }
2099                let flag = parent.or_else(|| {
2100                    default.flags.iter().copied().find(|f| {
2101                        f.longs.iter().any(|l| l.as_bytes() == name)
2102                            || f.negate.is_some_and(|n| n.as_bytes() == name)
2103                    })
2104                });
2105                let Some(flag) = flag else {
2106                    return at;
2107                };
2108                if parent.is_none() {
2109                    at.get_or_insert(i);
2110                }
2111                if flag.takes_value && flag.negate.is_none_or(|n| n.as_bytes() != name) {
2112                    value_flag = Some(flag);
2113                    attached = (end < body.len()).then(|| slice::after(body, end + 1));
2114                }
2115            } else {
2116                for (offset, byte) in slice::after(token, 1).iter().enumerate() {
2117                    let parent = self.find_short(*byte);
2118                    let Some(flag) = parent.or_else(|| {
2119                        default
2120                            .flags
2121                            .iter()
2122                            .copied()
2123                            .find(|f| has_byte(f.shorts, *byte))
2124                    }) else {
2125                        return at;
2126                    };
2127                    if parent.is_none() {
2128                        at.get_or_insert(i);
2129                    }
2130                    if flag.takes_value {
2131                        value_flag = Some(flag);
2132                        let rest = slice::after(token, offset + 2);
2133                        attached =
2134                            (!rest.is_empty()).then_some(rest.strip_prefix(b"=").unwrap_or(rest));
2135                        break;
2136                    }
2137                }
2138            }
2139            i += 1;
2140            if let Some(flag) = value_flag {
2141                let scope = if at.is_some() { default } else { self.cmd };
2142                let is_separator =
2143                    |next: &[u8]| scope.clause.is_some_and(|c| c.separator == Some(next));
2144                let first = if let Some(value) = attached {
2145                    Some(value)
2146                } else if !flag.require_equals {
2147                    self.argv
2148                        .get(i)
2149                        .map(bytes)
2150                        .filter(|next| {
2151                            !is_separator(next)
2152                                && (flag.allow_hyphen_values
2153                                    || !is_flag_like(next)
2154                                    || (flag.allow_negative_numbers && is_negative_number(next)))
2155                        })
2156                        .inspect(|_| i += 1)
2157                } else {
2158                    None
2159                };
2160                if first.is_none() && !flag.value_optional && flag.default_missing.is_none() {
2161                    return at;
2162                }
2163                if flag.variadic {
2164                    let mut count = first.map_or(0, |v| values_in(v, flag.delimiter));
2165                    while flag.var_max.is_none_or(|max| count < max) {
2166                        let Some(next) = self.argv.get(i).map(bytes) else {
2167                            break;
2168                        };
2169                        if is_separator(next) {
2170                            break;
2171                        }
2172                        if next == b"--" || flag.value_terminator.is_some_and(|end| end == next) {
2173                            if next != b"--" {
2174                                i += 1;
2175                            }
2176                            break;
2177                        }
2178                        if is_flag_like(next)
2179                            && !(flag.allow_negative_numbers && is_negative_number(next))
2180                        {
2181                            break;
2182                        }
2183                        if self.cmd.subcommand_precedence_over_arg
2184                            && self.find_subcommand(next).is_some()
2185                        {
2186                            break;
2187                        }
2188                        count += values_in(next, flag.delimiter);
2189                        i += 1;
2190                    }
2191                }
2192            }
2193        }
2194        at
2195    }
2196
2197    /// Restrict inherited root globals to those carried by an executable view.
2198    #[cfg(feature = "spec")]
2199    pub fn with_view(mut self, view: &'t spec::ViewMeta<'t>) -> Self {
2200        self.view = Some(view);
2201        self
2202    }
2203
2204    /// The command in scope: the root, or the deepest subcommand selected so far.
2205    pub fn command(&self) -> &'t Command<'t> {
2206        self.cmd
2207    }
2208
2209    /// Whether a `--` was consumed as a separator.
2210    ///
2211    /// False when flag interpretation stopped for another reason, such as an
2212    /// `automatic` argument taking a value, and false for a `--` that a
2213    /// `preserve` argument kept as a value.
2214    pub fn double_dash_seen(&self) -> bool {
2215        self.separator_seen
2216    }
2217
2218    /// Every command entered so far, and where each one's own words begin.
2219    ///
2220    /// The ancestors are already kept for flag scoping; this is the same chain with the offsets,
2221    /// which is what lets a completion hand a callback the words of *its* command rather than of
2222    /// the deepest one — a global flag is declared on an ancestor.
2223    pub fn command_path(&self) -> Vec<(&'t Command<'t>, usize)> {
2224        let mut out = Vec::with_capacity(self.depth + 1);
2225        for (i, ancestor) in slice::before(&self.ancestors, self.depth)
2226            .iter()
2227            .enumerate()
2228        {
2229            if let Some(cmd) = ancestor {
2230                // An ancestor's own words start where the one before it descended, and the
2231                // root's start at the beginning.
2232                out.push((*cmd, self.starts[i]));
2233            }
2234        }
2235        out.push((self.cmd, self.cmd_start));
2236        out
2237    }
2238
2239    /// The `argv` range the `help` word resolved as a command path.
2240    ///
2241    /// Empty unless the word was typed. Every token in it named a subcommand of the one before
2242    /// it — the parser resolved them itself, so nothing here is a flag or a flag's value.
2243    pub fn help_span(&self) -> (usize, usize) {
2244        self.help_span
2245    }
2246
2247    /// Where the command in scope began: the index in `argv` just after its name, or at the
2248    /// unmatched word routed into a default subcommand.
2249    ///
2250    /// `argv[command_start()..]` is what that command was given, which is what a completion
2251    /// callback needs to be handed its own command's half-parsed struct rather than the root's.
2252    pub fn command_start(&self) -> usize {
2253        self.cmd_start
2254    }
2255
2256    /// Whether flag interpretation has stopped, for any reason.
2257    ///
2258    /// Wider than [`double_dash_seen`](Self::double_dash_seen), and the question completion
2259    /// asks: past a separator *or* past the first value of an `automatic` argument, a
2260    /// dash-prefixed word is a value, so there is no flag there to offer.
2261    pub fn flags_stopped(&self) -> bool {
2262        self.flags_stopped
2263    }
2264
2265    /// A variadic flag that is still claiming words.
2266    ///
2267    /// Asked *between* events, because the answer is gone by the end: the call that finds argv
2268    /// exhausted is the one that clears it. A completion needs it — the next word after
2269    /// `--tools a ⌶` is another tool, not the positional that follows.
2270    pub fn collecting(&self) -> Option<&'t Flag<'t>> {
2271        self.collecting
2272    }
2273
2274    /// The positional the next word would fill, if there is one left.
2275    ///
2276    /// A variadic stays here until it reaches its bound, which is what makes it the answer to
2277    /// "what could go where the cursor is" as many times as it can be filled.
2278    pub fn pending_arg(&self) -> Option<&'t Arg<'t>> {
2279        self.next_arg()
2280    }
2281
2282    /// Flags a word here could name: this command's own, then any ancestor's globals.
2283    ///
2284    /// The same set the parser itself would look in, so what is offered and what is accepted
2285    /// cannot disagree — including the shadowing rule, where a subcommand redeclaring an
2286    /// inherited name hides it.
2287    pub fn flags_in_scope(&self) -> impl Iterator<Item = &'t Flag<'t>> + '_ {
2288        let mut all = Vec::new();
2289        self.find_in_scope(Want::All, &mut all);
2290        all.into_iter()
2291    }
2292
2293    /// Read the next event.
2294    ///
2295    /// Returns `None` when `argv` is exhausted. An `Err` is terminal: the parse
2296    /// stops there, since continuing past a token that could not be understood
2297    /// would only produce bindings derived from a guess. Events already yielded
2298    /// before an error are therefore not a partial result to be used — a caller
2299    /// that assigned them into fields should discard the whole attempt.
2300    ///
2301    /// One case is stronger than that, because the grammar demands it: a short
2302    /// bundle containing an unrecognized letter yields the error *instead of*, not
2303    /// after, the letters that did match.
2304    #[allow(clippy::should_implement_trait)] // not an Iterator: items borrow from self's tables
2305    pub fn next_event(&mut self) -> Option<Result<Event<'t, 'a, 'v>, Error<'t, 'v>>> {
2306        if self.done {
2307            return None;
2308        }
2309        let event = self.step();
2310        if matches!(event, Some(Ok(Event::Flag { .. } | Event::Arg { .. }))) {
2311            self.command_arg_found = true;
2312        }
2313        if matches!(event, Some(Ok(Event::Arg { .. }))) {
2314            self.positional_arg_found = true;
2315        }
2316        if event.is_none()
2317            && self.depth == 0
2318            && self.cmd.default_subcommand_on_empty
2319            && !self.default_taken
2320            && !self.completing
2321            && !self.positional_arg_found
2322            && !self.separator_seen
2323            && !self.clause_separator_seen
2324            && let Some(default) = self.cmd.default_subcommand
2325        {
2326            if self.cmd.args_conflicts_with_subcommands && self.command_arg_found {
2327                self.done = true;
2328                return Some(Err(Error::SubcommandConflict {
2329                    subcommand: default,
2330                }));
2331            }
2332            self.default_taken = true;
2333            match self.descend(default) {
2334                Ok(()) => return Some(Ok(Event::Command(default))),
2335                Err(error) => {
2336                    self.done = true;
2337                    return Some(Err(error));
2338                }
2339            }
2340        }
2341        if let Some(Err(_)) = event {
2342            self.done = true;
2343        }
2344        event
2345    }
2346
2347    /// Count parent flags in the shared boundary token before entering the child.
2348    fn default_bundle_has_parent_flag(&self, default: &Command<'_>) -> bool {
2349        let Some(token) = self.argv.get(self.pos).map(bytes) else {
2350            return false;
2351        };
2352        if !token.starts_with(b"-") || token.starts_with(b"--") {
2353            return false;
2354        }
2355        for byte in slice::after(token, 1) {
2356            if self.find_short(*byte).is_some() {
2357                return true;
2358            }
2359            match default.flags.iter().find(|f| has_byte(f.shorts, *byte)) {
2360                Some(flag) if !flag.takes_value => {}
2361                _ => break,
2362            }
2363        }
2364        false
2365    }
2366
2367    fn step(&mut self) -> Option<Result<Event<'t, 'a, 'v>, Error<'t, 'v>>> {
2368        if self.default_flag_at == Some(self.pos) && self.bundle.is_empty() {
2369            self.default_flag_at = None;
2370            if let Some(default) = self.cmd.default_subcommand {
2371                if self.cmd.args_conflicts_with_subcommands
2372                    && (self.command_arg_found || self.default_bundle_has_parent_flag(default))
2373                {
2374                    return Some(Err(Error::SubcommandConflict {
2375                        subcommand: default,
2376                    }));
2377                }
2378                if self.argv.get(self.pos).is_some_and(|word| {
2379                    let token = bytes(word);
2380                    token.starts_with(b"-") && !token.starts_with(b"--")
2381                }) {
2382                    self.default_bundle_end = self.pos + 1;
2383                }
2384                self.default_taken = true;
2385                return Some(self.descend(default).map(|()| Event::Command(default)));
2386            }
2387        }
2388        if let Some(clause) = self.pending_clause_boundary.take() {
2389            self.arg_pos = 0;
2390            self.arg_taken = 0;
2391            self.arg_filled = false;
2392            self.collecting = None;
2393            self.flags_stopped = false;
2394            return Some(Ok(Event::ClauseSeparator { clause: *clause }));
2395        }
2396        // A partly-read short bundle takes priority: its remaining bytes are
2397        // still part of the token being processed.
2398        if !self.bundle.is_empty() {
2399            return Some(self.short_flag());
2400        }
2401
2402        if self.cmd.subcommand_precedence_over_arg
2403            && !self.flags_stopped
2404            && let Some(token) = self.argv.get(self.pos).map(bytes)
2405            && let Some(sub) = self.find_subcommand(token)
2406        {
2407            if self.cmd.args_conflicts_with_subcommands && self.command_arg_found {
2408                return Some(Err(Error::SubcommandConflict { subcommand: sub }));
2409            }
2410            self.pos += 1;
2411            return Some(self.descend(sub).map(|()| Event::Command(sub)));
2412        }
2413
2414        // A variadic flag keeps claiming tokens until one of them could be
2415        // something else.
2416        if let Some(flag) = self.collecting {
2417            match self.argv.get(self.pos) {
2418                Some(next)
2419                    if flag
2420                        .value_terminator
2421                        .is_some_and(|terminator| bytes(next) == terminator) =>
2422                {
2423                    self.pos += 1;
2424                    self.collecting = None;
2425                    return self.step();
2426                }
2427                Some(next)
2428                    if (!is_flag_like(bytes(next))
2429                        || (flag.allow_negative_numbers && is_negative_number(bytes(next))))
2430                        && self.clause_separator(bytes(next)).is_none()
2431                        && bytes(next) != b"--" =>
2432                {
2433                    self.pos += 1;
2434                    self.collected += values_in(bytes(next), flag.delimiter);
2435                    // Same rule as a positional: a bounded occurrence takes that many and
2436                    // leaves the rest to whatever follows.
2437                    if flag.var_max.is_some_and(|max| self.collected >= max) {
2438                        self.collecting = None;
2439                    }
2440                    // Stopping is only the same as staying within the bound while one word
2441                    // is one value. A delimited word can carry the occurrence past it in a
2442                    // single step, and that word cannot be split between two owners, so the
2443                    // overshoot is an error rather than a place to stop.
2444                    if let Some(max) = flag.var_max.filter(|max| self.collected > *max) {
2445                        return Some(Err(Error::VarTooMany {
2446                            name: flag.name,
2447                            max: max as usize,
2448                            got: self.collected as usize,
2449                        }));
2450                    }
2451                    return Some(Ok(Event::Flag {
2452                        flag,
2453                        value: Some(bytes(next)),
2454                        negated: false,
2455                    }));
2456                }
2457                // A token that could be something else ends the run — but the *end of argv*
2458                // decides nothing. Clearing there threw away the answer to "would the next
2459                // word be claimed?", which is the question a completion asks and no parse
2460                // ever does: once argv is exhausted there are no more events either way.
2461                Some(_) => self.collecting = None,
2462                None => {}
2463            }
2464        }
2465
2466        let token = bytes(self.argv.get(self.pos)?);
2467        self.pos += 1;
2468
2469        // A clause separator remains syntax after an automatic positional stopped flags.
2470        // Only an explicit `--` protects a literal separator.
2471        if let Some(clause) = self.clause_separator(token) {
2472            self.arg_pos = 0;
2473            self.arg_taken = 0;
2474            self.arg_filled = false;
2475            self.collecting = None;
2476            self.flags_stopped = false;
2477            if self.depth == 0 {
2478                self.clause_separator_seen = true;
2479            }
2480            return Some(Ok(Event::ClauseSeparator { clause: *clause }));
2481        }
2482
2483        // An automatic trailing argument stops flag interpretation without consuming an
2484        // explicit separator. A later `--` must still unlock a required trailing argument
2485        // (clap's `last`), while a separator already consumed makes every later `--` data.
2486        if self.flags_stopped && (token != b"--" || self.separator_seen) {
2487            return Some(self.word(token));
2488        }
2489
2490        if token == b"--" {
2491            // `preserve` wants the separator itself as a value, so ask the
2492            // argument that would receive it before treating it as syntax.
2493            if self
2494                .next_arg()
2495                .is_some_and(|a| a.double_dash == DoubleDash::Preserve)
2496            {
2497                return Some(self.word(token));
2498            }
2499            self.flags_stopped = true;
2500            self.separator_seen = true;
2501            // An explicit separator unlocks any argument that required one, even
2502            // if earlier arguments are still unfilled.
2503            if let Some(idx) = slice::after(self.current_args(), self.arg_pos)
2504                .iter()
2505                .position(|a| a.double_dash == DoubleDash::Required)
2506            {
2507                // The count belongs to the argument at `arg_pos`, so jumping past it has
2508                // to leave the count behind: a bounded variadic before the separator would
2509                // otherwise lend its total to the argument after it, which then stops
2510                // early or at once.
2511                self.arg_pos += idx;
2512                self.arg_taken = 0;
2513            }
2514            return self.step();
2515        }
2516
2517        if self.arg_taken > 0
2518            && self.next_arg().is_some_and(|arg| {
2519                arg.value_terminator
2520                    .is_some_and(|terminator| token == terminator)
2521            })
2522        {
2523            self.advance_arg();
2524            return self.step();
2525        }
2526
2527        // An exact declared short outranks the numeric shape. This keeps ordinary negative
2528        // numbers available as values while allowing clap-compatible spellings such as fd's
2529        // `-0` / `--print0` switch.
2530        let declared_numeric_short = matches!(token, [b'-', short]
2531            if short.is_ascii_digit() && self.find_short(*short).is_some());
2532
2533        if !declared_numeric_short
2534            && is_negative_number(token)
2535            && self
2536                .next_arg()
2537                .is_some_and(|arg| arg.allow_negative_numbers)
2538        {
2539            return Some(self.word(token));
2540        }
2541
2542        if !declared_numeric_short
2543            && is_negative_number(token)
2544            && self.cmd.external_subcommand
2545            && !self.arg_filled
2546        {
2547            return Some(self.word(token));
2548        }
2549
2550        if is_flag_like(token) {
2551            if token.starts_with(b"--") {
2552                return Some(self.long_flag(token));
2553            }
2554            // Check the whole bundle before emitting anything from it. Events go
2555            // out one at a time, so discovering an unknown letter half way
2556            // through would mean the earlier letters had already been applied —
2557            // and the grammar rejects the entire token, not the tail of it.
2558            match self.check_bundle(token) {
2559                Ok(()) => {}
2560                // Unrecognized, so it is a word unless this command wants it refused.
2561                Err(e) if self.unknown_flags == UnknownFlags::Error => {
2562                    return Some(Err(e));
2563                }
2564                Err(_) => return Some(self.word(token)),
2565            }
2566            self.bundle = slice::after(token, 1);
2567            self.bundle_token = token;
2568            return Some(self.short_flag());
2569        }
2570
2571        Some(self.word(token))
2572    }
2573
2574    fn long_flag(&mut self, token: &'v [u8]) -> Result<Event<'t, 'a, 'v>, Error<'t, 'v>> {
2575        let body = slice::after(token, 2);
2576        let (name, attached) = match body.iter().position(|&b| b == b'=') {
2577            Some(i) => (slice::before(body, i), Some(slice::after(body, i + 1))),
2578            None => (body, None),
2579        };
2580
2581        if let Some(flag) = self.find_long(name) {
2582            let value = if flag.takes_value {
2583                match attached {
2584                    Some(v) => Some(v),
2585                    None => self.take_detached_value(flag)?,
2586                }
2587            } else if flag.bool_value {
2588                validate_bool_value(flag, attached)?
2589            } else {
2590                None
2591            };
2592            if flag.variadic
2593                && let Some(value) = value
2594            {
2595                self.start_collecting(flag, value)?;
2596            }
2597            if let Some(error) = self.flag_action(flag, true) {
2598                return Err(error);
2599            }
2600            return Ok(Event::Flag {
2601                flag,
2602                value,
2603                negated: false,
2604            });
2605        }
2606
2607        if let Some(flag) = self.find_negation(name) {
2608            return Ok(Event::Flag {
2609                flag,
2610                value: if flag.bool_value {
2611                    validate_bool_value(flag, attached)?
2612                } else {
2613                    None
2614                },
2615                negated: true,
2616            });
2617        }
2618
2619        // Where the CLI declared a version, `--version` answers with it — asked after the
2620        // command's own flags, so a CLI declaring its own keeps it.
2621        let version_command = self.version_command();
2622        if name == b"version" && version_command.version && !version_command.disable_version_flag {
2623            return Ok(Event::Flag {
2624                flag: &VERSION_LONG,
2625                value: None,
2626                negated: false,
2627            });
2628        }
2629
2630        // Every CLI answers to `--help`, and none of them declares it. Asked *after* the
2631        // command's own flags, so a CLI that declares its own `--help` keeps it.
2632        if name == b"help" && !self.cmd.disable_help_flag {
2633            return Ok(Event::Flag {
2634                flag: &HELP_LONG,
2635                value: None,
2636                negated: false,
2637            });
2638        }
2639
2640        if self.unknown_flags == UnknownFlags::Error {
2641            return Err(Error::UnknownFlag { token });
2642        }
2643        // Not a flag here, so it is a word like any other.
2644        self.word(token)
2645    }
2646
2647    /// Walk a short-flag token without binding anything, to find out whether all
2648    /// of it is recognized.
2649    ///
2650    /// Scanning stops at the first letter whose flag takes a value, because
2651    /// everything after it is that value rather than more letters.
2652    fn check_bundle(&self, token: &'v [u8]) -> Result<(), Error<'t, 'v>> {
2653        let mut rest = slice::after(token, 1);
2654        while let Some((&byte, tail)) = rest.split_first() {
2655            match self.find_short(byte) {
2656                None => return Err(Error::UnknownFlag { token }),
2657                Some(flag) if flag.takes_value => return Ok(()),
2658                Some(_) => rest = tail,
2659            }
2660        }
2661        Ok(())
2662    }
2663
2664    fn short_flag(&mut self) -> Result<Event<'t, 'a, 'v>, Error<'t, 'v>> {
2665        let (byte, rest) = match self.bundle.split_first() {
2666            Some((&byte, rest)) => (byte, rest),
2667            None => (0, &[][..]),
2668        };
2669
2670        let Some(flag) = self.find_short(byte) else {
2671            // check_bundle already rejected any token containing an unrecognized
2672            // letter, so this is unreachable — but a parser should report rather
2673            // than panic if that ever stops being true.
2674            self.bundle = &[];
2675            return Err(Error::UnknownFlag {
2676                token: self.bundle_token,
2677            });
2678        };
2679
2680        if !flag.takes_value {
2681            self.bundle = rest;
2682            if let Some(error) = self.flag_action(flag, false) {
2683                self.bundle = &[];
2684                return Err(error);
2685            }
2686            return Ok(Event::Flag {
2687                flag,
2688                value: None,
2689                negated: false,
2690            });
2691        }
2692
2693        // A value-taking short ends the token: everything after it is the value,
2694        // less one separating `=`.
2695        self.bundle = &[];
2696        let value = match rest.split_first() {
2697            None => self.take_detached_value(flag)?,
2698            Some((b'=', value)) => Some(value),
2699            Some(_) => Some(rest),
2700        };
2701        if flag.variadic
2702            && let Some(value) = value
2703        {
2704            self.start_collecting(flag, value)?;
2705        }
2706        if let Some(error) = self.flag_action(flag, false) {
2707            return Err(error);
2708        }
2709        Ok(Event::Flag {
2710            flag,
2711            value,
2712            negated: false,
2713        })
2714    }
2715
2716    #[inline(never)]
2717    fn flag_action(&self, flag: &'t Flag<'t>, long_spelling: bool) -> Option<Error<'t, 'v>> {
2718        if matches!(
2719            flag.key,
2720            HELP_LONG_KEY | HELP_SHORT_KEY | VERSION_LONG_KEY | VERSION_SHORT_KEY
2721        ) || !self.action_errors
2722        {
2723            return None;
2724        }
2725        match flag.action {
2726            ArgAction::Set => None,
2727            ArgAction::Help => Some(Error::Help {
2728                cmd: self.cmd,
2729                long: long_spelling,
2730            }),
2731            ArgAction::HelpShort => Some(Error::Help {
2732                cmd: self.cmd,
2733                long: false,
2734            }),
2735            ArgAction::HelpLong => Some(Error::Help {
2736                cmd: self.cmd,
2737                long: true,
2738            }),
2739            ArgAction::HelpAll => Some(Error::HelpAll { cmd: self.cmd }),
2740            ArgAction::Version => Some(Error::Version {
2741                long: long_spelling,
2742            }),
2743        }
2744    }
2745
2746    /// Take the following token as a flag's value.
2747    ///
2748    /// Refuses a flag-like token unless [`Flag::allow_hyphen_values`] is set:
2749    /// `--jobs --force` is far more likely a forgotten value than a deliberate
2750    /// one, and the attached form is available for the deliberate case. Declared,
2751    /// the next token is taken whatever it looks like, including `--`.
2752    fn take_detached_value(
2753        &mut self,
2754        flag: &'t Flag<'t>,
2755    ) -> Result<Option<&'v [u8]>, Error<'t, 'v>> {
2756        if flag.require_equals {
2757            return self.missing_or_default(flag);
2758        }
2759        match self.argv.get(self.pos) {
2760            Some(next)
2761                if self.clause_separator(bytes(next)).is_none()
2762                    && (flag.allow_hyphen_values
2763                        || !is_flag_like(bytes(next))
2764                        || (flag.allow_negative_numbers && is_negative_number(bytes(next)))) =>
2765            {
2766                self.pos += 1;
2767                Ok(Some(bytes(next)))
2768            }
2769            _ => self.missing_or_default(flag),
2770        }
2771    }
2772
2773    fn missing_or_default(&self, flag: &'t Flag<'t>) -> Result<Option<&'v [u8]>, Error<'t, 'v>> {
2774        match flag.default_missing {
2775            Some(value) => Ok(Some(value)),
2776            None if flag.value_optional => Ok(None),
2777            None => Err(Error::MissingFlagValue { flag }),
2778        }
2779    }
2780
2781    #[inline(never)]
2782    fn clause_separator(&self, token: &[u8]) -> Option<&'t Clause<'t>> {
2783        (!self.separator_seen)
2784            .then_some(self.cmd.clause)
2785            .flatten()
2786            .filter(|clause| clause.separator.is_some_and(|separator| token == separator))
2787    }
2788
2789    fn word(&mut self, token: &'v [u8]) -> Result<Event<'t, 'a, 'v>, Error<'t, 'v>> {
2790        // Subcommands are only matched where descent is still possible: once a
2791        // positional of this command has taken a word, a later word that happens
2792        // to equal a subcommand name is just a value.
2793        if !self.arg_filled && !self.flags_stopped {
2794            if let Some(sub) = self.find_subcommand(token) {
2795                if self.cmd.args_conflicts_with_subcommands && self.command_arg_found {
2796                    return Err(Error::SubcommandConflict { subcommand: sub });
2797                }
2798                self.descend(sub)?;
2799                return Ok(Event::Command(sub));
2800            }
2801
2802            // `ex help config ls` — the line every page with a Commands section has printed
2803            // all along ("help  Print this message or the help of the given subcommand(s)"),
2804            // and which until now did nothing. The page is what decides the condition here:
2805            // it prints that line where there are subcommands, so that is where the word is
2806            // answered, and to a leaf `help` is a word like any other.
2807            //
2808            // Asked *after* the subcommand lookup, so a CLI that declares a `help` of its own
2809            // keeps it — the same rule the two help flags follow.
2810            //
2811            // The words after it name a command, resolved here rather than descended into:
2812            // descending would bind them, and they are a question rather than an invocation.
2813            if token == b"help"
2814                && !self.cmd.disable_help_subcommand
2815                && !self.cmd.subcommands.is_empty()
2816            {
2817                let mut cmd = self.cmd;
2818                let from = self.pos;
2819                while let Some(next) = self.argv.get(self.pos) {
2820                    let Some(sub) = find_named(cmd, bytes(next)) else {
2821                        break;
2822                    };
2823                    cmd = sub;
2824                    self.pos += 1;
2825                }
2826                // Kept for `help::route_to`: which mount was asked about is not recoverable
2827                // from `cmd`, since two mounts of one `Subcommands` type are one address.
2828                self.help_span = (from, self.pos);
2829                // The long form, as `ex config --help` gives: someone who typed a whole word to
2830                // ask for help wants the fuller answer.
2831                return Err(Error::Help { cmd, long: true });
2832            }
2833
2834            // A word that names no subcommand goes to the default one, if there is one.
2835            //
2836            // Only a word, though. A dash-prefixed token that named no flag arrives here as a
2837            // value — that is what `unknown_flags = value` means — and it was never a
2838            // candidate to *select* anything, so it binds where it was typed. usage-lib stops
2839            // looking for subcommands at an unrecognised flag for the same reason. `--` is
2840            // excluded on the same grounds: it reaches this function only when a `preserve`
2841            // argument wants it as a value.
2842            //
2843            // The token is *not* consumed: the cursor steps back so the next event reads it
2844            // again, now against the command just descended into. That is what lets it be a
2845            // subcommand of the default (`mise build` where `build` is a task the mount
2846            // added) as easily as an argument of it, without this function having to decide
2847            // which — and without yielding two events for one word.
2848            if let Some(default) = self.cmd.default_subcommand {
2849                // `-` joins `--` in being excluded, and for the reason already written above:
2850                // a value was never a candidate to *select* anything. `is_flag_like` calls a
2851                // lone `-` a value — conventionally stdin — so it passed this guard and
2852                // descended, where mise's `run` has no positional and the parse failed.
2853                // usage-lib and clap both bind it to the root's own `[TASK]` instead.
2854                let default_accepts_negative = is_negative_number(token)
2855                    && default
2856                        .args
2857                        .first()
2858                        .is_some_and(|arg| arg.allow_negative_numbers);
2859                if !self.default_taken
2860                    && (!is_flag_like(token) || default_accepts_negative)
2861                    && token != b"--"
2862                    && token != b"-"
2863                {
2864                    self.default_taken = true;
2865                    self.descend(default)?;
2866                    self.pos -= 1;
2867                    // Unlike an explicitly named command, the default command receives the
2868                    // word that caused descent. Keep its argv boundary at that word so
2869                    // command-level policies and completion callbacks see the same input the
2870                    // command parser is about to re-read.
2871                    self.cmd_start = self.pos;
2872                    return Ok(Event::Command(default));
2873                }
2874            }
2875
2876            // Known subcommands and the default route keep precedence. A sigil positional
2877            // then claims its classified word before an external-subcommand catch-all can.
2878            if let Some((arg, sigil)) = self.match_sigil_arg(token) {
2879                if token.len() == sigil.len() {
2880                    return Err(sigil_without_value(arg, token, sigil));
2881                }
2882                return Ok(Event::Arg {
2883                    arg,
2884                    value: slice::after(token, sigil.len()),
2885                    delimit: true,
2886                });
2887            }
2888
2889            // An unmatched word that names no subcommand is forwarded as an external
2890            // command: this word, then every token after it, including flags. Known
2891            // subcommands already won above, and a default_subcommand already caught.
2892            if self.cmd.external_subcommand
2893                && (!is_flag_like(token) || is_negative_number(token))
2894                && token != b"--"
2895                && token != b"-"
2896            {
2897                let from = self.pos - 1;
2898                self.pos = self.argv.len();
2899                return Ok(Event::External {
2900                    values: slice::after(self.argv, from),
2901                });
2902            }
2903        }
2904
2905        if self.arg_filled
2906            && !self.flags_stopped
2907            && let Some((arg, sigil)) = self.match_sigil_arg(token)
2908        {
2909            if token.len() == sigil.len() {
2910                return Err(sigil_without_value(arg, token, sigil));
2911            }
2912            return Ok(Event::Arg {
2913                arg,
2914                value: slice::after(token, sigil.len()),
2915                delimit: true,
2916            });
2917        }
2918
2919        self.skip_sigil_args();
2920        self.reserve_for_required_positionals();
2921        let Some(arg) = self.next_arg() else {
2922            return Err(Error::UnexpectedArg { token });
2923        };
2924
2925        if arg.double_dash == DoubleDash::Required && !self.separator_seen {
2926            return Err(Error::ArgRequiresDoubleDash { arg });
2927        }
2928
2929        self.arg_filled = true;
2930        // An `automatic` argument stops flag interpretation from here on, as
2931        // though the caller had typed the separator themselves.
2932        let trailing_value = self.separator_seen || arg.double_dash == DoubleDash::Automatic;
2933        let delimit = !(self.dont_delimit_trailing_values && trailing_value);
2934        if arg.double_dash == DoubleDash::Automatic {
2935            self.flags_stopped = true;
2936        }
2937        // A variadic keeps taking values, so the cursor stays put — until it reaches its
2938        // bound, at which point the words after it belong to whatever comes next. That is
2939        // what makes `[a]… [b]` expressible at all.
2940        if arg.var {
2941            self.arg_taken += values_in(token, delimit.then_some(arg.delimiter).flatten());
2942            // Before advancing, which resets the count: as with a variadic flag, reaching
2943            // the bound and passing it are the same event once a word can carry several
2944            // values, and only the second is a mistake.
2945            if let Some(max) = arg.var_max.filter(|max| self.arg_taken > *max) {
2946                return Err(Error::VarTooMany {
2947                    name: arg.name,
2948                    max: max as usize,
2949                    got: self.arg_taken as usize,
2950                });
2951            }
2952            if arg.var_max.is_some_and(|max| self.arg_taken >= max) {
2953                self.advance_arg();
2954            }
2955        } else {
2956            self.advance_arg();
2957        }
2958        if self
2959            .cmd
2960            .clause
2961            .is_some_and(|clause| clause.separator.is_none() && self.next_arg().is_none())
2962        {
2963            self.pending_clause_boundary = self.cmd.clause;
2964        }
2965        Ok(Event::Arg {
2966            arg,
2967            value: token,
2968            delimit,
2969        })
2970    }
2971
2972    #[inline(never)]
2973    fn descend(&mut self, sub: &'t Command<'t>) -> Result<(), Error<'t, 'v>> {
2974        if self.depth >= MAX_DEPTH {
2975            return Err(Error::TooDeep);
2976        }
2977        self.ancestors[self.depth] = Some(self.cmd);
2978        self.starts[self.depth] = self.cmd_start;
2979        self.depth += 1;
2980        self.cmd = sub;
2981        // Only a command that says something changes it, which is what inheriting means.
2982        if let ::core::option::Option::Some(mode) = sub.unknown_flags {
2983            self.unknown_flags = mode;
2984        }
2985        self.dont_delimit_trailing_values |= sub.dont_delimit_trailing_values;
2986        // Where this command's own words start, which is what lets a completion hand a callback
2987        // the half-parsed struct of the command it was declared on rather than of the root.
2988        self.cmd_start = self.pos;
2989        self.arg_pos = 0;
2990        self.arg_taken = 0;
2991        self.arg_filled = false;
2992        self.command_arg_found = false;
2993        Ok(())
2994    }
2995
2996    /// Move to the next positional, forgetting what the last one took.
2997    #[inline(never)]
2998    fn advance_arg(&mut self) {
2999        self.skip_sigil_args();
3000        self.arg_pos += 1;
3001        self.arg_taken = 0;
3002        self.skip_sigil_args();
3003    }
3004
3005    /// A variadic flag occurrence begins, counting from zero.
3006    ///
3007    /// The value it was given on the same token counts, which is why this starts at what
3008    /// that value holds: `--include a b` with `var_max=2` takes `a` and `b`, not three
3009    /// words — and `--include a,b` has already taken both on the one token.
3010    #[inline(never)]
3011    fn start_collecting(&mut self, flag: &'t Flag<'t>, first: &[u8]) -> Result<(), Error<'t, 'v>> {
3012        self.collected = values_in(first, flag.delimiter);
3013        if let Some(max) = flag.var_max.filter(|max| self.collected > *max) {
3014            return Err(Error::VarTooMany {
3015                name: flag.name,
3016                max: max as usize,
3017                got: self.collected as usize,
3018            });
3019        }
3020        self.collecting = if flag.var_max.is_some_and(|max| self.collected >= max) {
3021            None
3022        } else {
3023            Some(flag)
3024        };
3025        Ok(())
3026    }
3027
3028    #[inline(never)]
3029    fn next_arg(&self) -> Option<&'t Arg<'t>> {
3030        slice::after(self.current_args(), self.arg_pos)
3031            .iter()
3032            .find(|arg| arg.sigil.is_none())
3033            .copied()
3034    }
3035
3036    fn skip_sigil_args(&mut self) {
3037        while self
3038            .current_args()
3039            .get(self.arg_pos)
3040            .is_some_and(|arg| arg.sigil.is_some())
3041        {
3042            self.arg_pos += 1;
3043        }
3044    }
3045
3046    fn match_sigil_arg(&self, token: &[u8]) -> Option<(&'t Arg<'t>, &'t [u8])> {
3047        if self.flags_stopped {
3048            return None;
3049        }
3050        // The longest sigil that fits, the later declaration winning a tie, as `max_by_key`
3051        // would say — written as loops, which are smaller than the adapter chain and are
3052        // walked for every positional word.
3053        let mut best: Option<(&'t Arg<'t>, &'t [u8])> = None;
3054        let mut consider = |args: &'t [&'t Arg<'t>]| {
3055            for &arg in args {
3056                if let Some(sigil) = arg.sigil
3057                    && token.starts_with(sigil)
3058                    && best.is_none_or(|(_, longest)| sigil.len() >= longest.len())
3059                {
3060                    best = Some((arg, sigil));
3061                }
3062            }
3063        };
3064        consider(self.current_args());
3065        for cmd in slice::before(&self.ancestors, self.depth)
3066            .iter()
3067            .rev()
3068            .flatten()
3069        {
3070            consider(cmd.args);
3071        }
3072        best
3073    }
3074
3075    fn current_args(&self) -> &'t [&'t Arg<'t>] {
3076        self.cmd
3077            .clause
3078            .map(|clause| clause.args)
3079            .unwrap_or(self.cmd.args)
3080    }
3081
3082    /// Skip empty optional positionals when every remaining value is needed by a later
3083    /// required positional. This is clap's opt-in `allow_missing_positional` policy.
3084    fn reserve_for_required_positionals(&mut self) {
3085        if !self.cmd.allow_missing_positional || self.arg_taken != 0 {
3086            return;
3087        }
3088        loop {
3089            let Some(current) = self.next_arg() else {
3090                return;
3091            };
3092            if current.required {
3093                return;
3094            }
3095            let required_after = slice::after(self.current_args(), self.arg_pos + 1)
3096                .iter()
3097                .filter(|arg| arg.required && arg.sigil.is_none())
3098                .count();
3099            if required_after == 0 {
3100                return;
3101            }
3102            let remaining_values = 1 + slice::after(self.argv, self.pos)
3103                .iter()
3104                .filter(|word| {
3105                    (self.flags_stopped || !is_flag_like(bytes(word)))
3106                        && self.match_sigil_arg(bytes(word)).is_none()
3107                })
3108                .count();
3109            if remaining_values > required_after {
3110                return;
3111            }
3112            self.advance_arg();
3113        }
3114    }
3115
3116    #[cfg(feature = "spec")]
3117    fn view_allows_own_flag(&self, flag: &Flag<'_>) -> bool {
3118        match self.view {
3119            None => true,
3120            // The promoted command keeps its own surface. While the injected path is
3121            // still at the host root, however, only explicitly carried globals belong
3122            // to the view; root-local flags are not part of the projected executable.
3123            Some(view) => {
3124                !core::ptr::eq(self.cmd, self.root) || is_version_flag(flag) || view.carries(flag)
3125            }
3126        }
3127    }
3128
3129    #[cfg(not(feature = "spec"))]
3130    fn view_allows_own_flag(&self, _flag: &Flag<'_>) -> bool {
3131        true
3132    }
3133
3134    #[cfg(feature = "spec")]
3135    fn view_allows_inherited_flag(&self, flag: &Flag<'_>) -> bool {
3136        match self.view {
3137            None => true,
3138            // A portable view carries selected host globals, not globals declared
3139            // by intermediate commands on a multi-segment promoted path.
3140            Some(view) => {
3141                self.root
3142                    .flags
3143                    .iter()
3144                    .any(|root| core::ptr::eq(*root, flag))
3145                    && (is_version_flag(flag) || view.carries(flag))
3146            }
3147        }
3148    }
3149
3150    #[cfg(not(feature = "spec"))]
3151    fn view_allows_inherited_flag(&self, _flag: &Flag<'_>) -> bool {
3152        true
3153    }
3154
3155    #[cfg(feature = "spec")]
3156    fn inherited_flag_is_in_scope(&self, flag: &Flag<'_>) -> bool {
3157        flag.global || (self.view.is_some() && is_version_flag(flag))
3158    }
3159
3160    #[cfg(not(feature = "spec"))]
3161    fn inherited_flag_is_in_scope(&self, flag: &Flag<'_>) -> bool {
3162        flag.global
3163    }
3164
3165    /// Walk the flags in scope: this command's own, then any ancestor's globals.
3166    ///
3167    /// Own flags come first so that a subcommand redeclaring an inherited name
3168    /// shadows it, which is what mise relies on when it redeclares root globals
3169    /// on `run` with different shorts.
3170    ///
3171    /// The first flag that answers to `want`, or none; with [`Want::All`] every flag in scope
3172    /// is appended to `all` instead. One loop for the three ways a flag is looked up and for
3173    /// listing them, rather than an iterator chain compiled once per use: a chain of filters
3174    /// and a flat map inlined at each lookup was the larger part of what a lookup cost in code.
3175    /// What is matched is a branch on a value the loop does not change.
3176    #[inline(never)]
3177    fn find_in_scope(&self, want: Want<'_>, all: &mut Vec<&'t Flag<'t>>) -> Option<&'t Flag<'t>> {
3178        for &flag in self.cmd.flags {
3179            if self.view_allows_own_flag(flag) && visit(want, all, flag) {
3180                return Some(flag);
3181            }
3182        }
3183        for ancestor in slice::before(&self.ancestors, self.depth)
3184            .iter()
3185            .rev()
3186            .flatten()
3187        {
3188            for &flag in ancestor.flags {
3189                if self.inherited_flag_is_in_scope(flag)
3190                    && self.view_allows_inherited_flag(flag)
3191                    && visit(want, all, flag)
3192                {
3193                    return Some(flag);
3194                }
3195            }
3196        }
3197        None
3198    }
3199
3200    fn find_long(&self, name: &[u8]) -> Option<&'t Flag<'t>> {
3201        self.find_in_scope(Want::Long(name), &mut Vec::new())
3202    }
3203
3204    fn find_negation(&self, name: &[u8]) -> Option<&'t Flag<'t>> {
3205        self.find_in_scope(Want::Negation(name), &mut Vec::new())
3206    }
3207
3208    fn find_short(&self, byte: u8) -> Option<&'t Flag<'t>> {
3209        // Only the boundary token is shared. Later tokens use ordinary child/global scope.
3210        if self.default_taken
3211            && self.pos == self.default_bundle_end
3212            && let Some(flag) = self.ancestors[0].and_then(|parent| {
3213                parent
3214                    .flags
3215                    .iter()
3216                    .copied()
3217                    .find(|f| has_byte(f.shorts, byte))
3218            })
3219        {
3220            return Some(flag);
3221        }
3222        self.find_in_scope(Want::Short(byte), &mut Vec::new())
3223            // As for `--help`: supplied by the parser, and only where the command has not
3224            // declared a `-h` of its own.
3225            .or(if byte == b'h' && !self.cmd.disable_help_flag {
3226                Some(&HELP_SHORT)
3227            } else if byte == b'V'
3228                && self.version_command().version
3229                && !self.version_command().disable_version_flag
3230            {
3231                Some(&VERSION_SHORT)
3232            } else {
3233                None
3234            })
3235    }
3236
3237    #[cfg(feature = "spec")]
3238    fn version_command(&self) -> &'t Command<'t> {
3239        if self.view.is_some() {
3240            self.root
3241        } else {
3242            self.cmd
3243        }
3244    }
3245
3246    #[cfg(not(feature = "spec"))]
3247    fn version_command(&self) -> &'t Command<'t> {
3248        self.cmd
3249    }
3250
3251    fn find_subcommand(&self, name: &[u8]) -> Option<&'t Command<'t>> {
3252        // Shared with `help` rather than spelled out again, so descending into a command and
3253        // asking about one cannot drift apart.
3254        find_named(self.cmd, name)
3255    }
3256}
3257
3258/// One flag met on a walk of the flags in scope: whether it answers to `want`, or, for
3259/// [`Want::All`], noted in `all`. Always inlined, so that the walk's loop carries the test itself
3260/// and not a call to it for every flag.
3261#[inline(always)]
3262fn visit<'t>(want: Want<'_>, all: &mut Vec<&'t Flag<'t>>, f: &'t Flag<'t>) -> bool {
3263    match want {
3264        Want::Long(name) => f.longs.iter().any(|l| l.as_bytes() == name),
3265        Want::Negation(name) => f.negate.is_some_and(|n| n.as_bytes() == name),
3266        Want::Short(byte) => has_byte(f.shorts, byte),
3267        Want::All => {
3268            all.push(f);
3269            false
3270        }
3271    }
3272}
3273
3274/// What a walk of the flags in scope is for: a long spelling, a negation, a short letter, or all.
3275#[derive(Clone, Copy)]
3276enum Want<'a> {
3277    Long(&'a [u8]),
3278    Negation(&'a [u8]),
3279    Short(u8),
3280    All,
3281}
3282
3283/// Whether `bytes` holds `wanted`.
3284///
3285/// A loop of its own rather than `<[u8]>::contains`, which expands at each call to a
3286/// word-at-a-time search tuned for long slices. A flag has one or two short letters.
3287#[inline]
3288pub(crate) fn has_byte(bytes: &[u8], wanted: u8) -> bool {
3289    for &byte in bytes {
3290        if byte == wanted {
3291            return true;
3292        }
3293    }
3294    false
3295}
3296
3297/// Whether `list` holds the name `wanted`. One copy for every place a table of names is searched:
3298/// `<[&str]>::contains` expands to its own comparison loop at each of them.
3299#[cfg(any(feature = "complete", feature = "diagnostics"))]
3300#[inline(never)]
3301pub(crate) fn has_str(list: &[&str], wanted: &str) -> bool {
3302    for item in list {
3303        if *item == wanted {
3304            return true;
3305        }
3306    }
3307    false
3308}
3309
3310/// View a token as bytes.
3311///
3312/// `as_encoded_bytes` is a plain accessor with no conversion and no allocation.
3313/// The reverse direction is the one with a cost — see [`os_string_from_bytes`] —
3314/// which is why values come back as bytes.
3315fn bytes<'v>(s: &&'v OsStr) -> &'v [u8] {
3316    s.as_encoded_bytes()
3317}
3318
3319/// How many values one word carries.
3320///
3321/// One, until a delimiter is declared — and then one per separator, counting the same way
3322/// splitting on it does: `a,b` is two, `a,` is two with an empty second, and `` is one.
3323/// Counted rather than split because binding only needs the number, and the split itself
3324/// belongs to the layer that owns the values.
3325#[inline]
3326fn values_in(word: &[u8], delimiter: ::core::option::Option<u8>) -> u32 {
3327    match delimiter {
3328        Some(d) => values_delimited(word, d),
3329        None => 1,
3330    }
3331}
3332
3333/// [`values_in`] for a word that has a delimiter to count. Out of line: counting bytes is a loop
3334/// the optimizer widens into vector code, and inlined at each of the places a word is bound it
3335/// was most of what they weighed.
3336#[inline(never)]
3337fn values_delimited(word: &[u8], delimiter: u8) -> u32 {
3338    1 + word.iter().filter(|b| **b == delimiter).count() as u32
3339}
3340
3341/// Whether a token should be read as a flag.
3342///
3343/// `-` alone is a value, conventionally stdin. Other dash-prefixed tokens are
3344/// flag-like; a field may make the narrower negative-number exception.
3345fn is_flag_like(token: &[u8]) -> bool {
3346    matches!(token, [b'-', rest @ ..] if !rest.is_empty())
3347}
3348
3349fn is_negative_number(token: &[u8]) -> bool {
3350    token.strip_prefix(b"-").is_some_and(is_number)
3351}
3352
3353/// Whether the text after a `-` is a number, so `-1`, `-2.5`, and `-1e5` are values
3354/// while `-1x` is a flag-shaped token that names nothing.
3355///
3356/// Digits, at most one `.`, and an optional exponent. Deliberately narrower than
3357/// `f64::from_str`, which also accepts `inf` and `NaN` — `-inf` is far likelier to be
3358/// a misspelled flag than a number somebody meant to pass.
3359///
3360/// usage-lib applies the same rule, and the corpus pins the edges so the two cannot
3361/// drift apart: they disagreed about `-1e5` when this was a hand-rolled scanner on
3362/// one side and a float parse on the other.
3363///
3364/// Written out rather than deferred to `f64::from_str` because this runs on the hot
3365/// path, and a parse would mean a UTF-8 check on a slice already decided by its
3366/// bytes.
3367#[inline(never)]
3368fn is_number(rest: &[u8]) -> bool {
3369    // One pass: the mantissa's digits and at most one dot, then an optional exponent.
3370    let mut at = 0;
3371    let mut digits = 0;
3372    let mut seen_dot = false;
3373    while let Some(&b) = rest.get(at) {
3374        if b.is_ascii_digit() {
3375            digits += 1;
3376        } else if b == b'.' && !seen_dot {
3377            seen_dot = true;
3378        } else {
3379            break;
3380        }
3381        at += 1;
3382    }
3383    if digits == 0 {
3384        return false;
3385    }
3386    let Some(&marker) = rest.get(at) else {
3387        return true;
3388    };
3389    if marker != b'e' && marker != b'E' {
3390        return false;
3391    }
3392    // An exponent needs digits of its own, and may carry a sign.
3393    let mut exponent = slice::after(rest, at + 1);
3394    if let [b'+' | b'-', tail @ ..] = exponent {
3395        exponent = tail;
3396    }
3397    if exponent.is_empty() {
3398        return false;
3399    }
3400    for b in exponent {
3401        if !b.is_ascii_digit() {
3402            return false;
3403        }
3404    }
3405    true
3406}
3407
3408fn validate_bool_value<'t, 'v>(
3409    flag: &'t Flag<'t>,
3410    value: Option<&'v [u8]>,
3411) -> Result<Option<&'v [u8]>, Error<'t, 'v>> {
3412    match value {
3413        None | Some(b"true" | b"false") => Ok(value),
3414        Some(_) => Err(Error::InvalidChoice {
3415            name: flag.name,
3416            choices: &["true", "false"],
3417        }),
3418    }
3419}
3420
3421#[cfg(test)]
3422mod tests {
3423    use super::*;
3424
3425    #[test]
3426    fn clause_separator_resets_inner_args_and_survives_automatic_mode() {
3427        static TASK: Arg = Arg {
3428            key: 91,
3429            name: "task",
3430            ..Arg::REQUIRED
3431        };
3432        static REST: Arg = Arg {
3433            key: 92,
3434            name: "args",
3435            double_dash: DoubleDash::Automatic,
3436            ..Arg::VAR
3437        };
3438        static ROOT: Command = Command {
3439            name: "ex",
3440            clause: Some(&Clause {
3441                key: 90,
3442                name: "tasks",
3443                separator: Some(b":::"),
3444                flags: &[],
3445                args: &[&TASK, &REST],
3446            }),
3447            ..Command::EMPTY
3448        };
3449        let argv = [
3450            OsStr::new("lint"),
3451            OsStr::new("--fix"),
3452            OsStr::new(":::"),
3453            OsStr::new("test"),
3454        ];
3455        let mut parser = Parser::new(&ROOT, &argv);
3456        let mut seen = Vec::new();
3457        while let Some(event) = parser.next_event() {
3458            match event.expect("valid clause") {
3459                Event::Arg { arg, value, .. } => {
3460                    seen.push((arg.name, String::from_utf8_lossy(value).into_owned()))
3461                }
3462                Event::ClauseSeparator { clause } => seen.push((clause.name, ":::".into())),
3463                _ => {}
3464            }
3465        }
3466        assert_eq!(
3467            seen,
3468            [
3469                ("task", "lint".into()),
3470                ("args", "--fix".into()),
3471                ("tasks", ":::".into()),
3472                ("task", "test".into())
3473            ]
3474        );
3475    }
3476
3477    #[test]
3478    fn clause_separator_is_not_a_scoped_flag_value() {
3479        static POSTINSTALL: Flag = Flag {
3480            key: 93,
3481            name: "postinstall",
3482            longs: &["postinstall"],
3483            takes_value: true,
3484            variadic: true,
3485            ..Flag::BOOL
3486        };
3487        static TOOL: Arg = Arg {
3488            key: 94,
3489            name: "tool",
3490            ..Arg::REQUIRED
3491        };
3492        static ROOT: Command = Command {
3493            name: "ex",
3494            flags: &[&POSTINSTALL],
3495            clause: Some(&Clause {
3496                key: 95,
3497                name: "tools",
3498                separator: Some(b":::"),
3499                flags: &[&POSTINSTALL],
3500                args: &[&TOOL],
3501            }),
3502            ..Command::EMPTY
3503        };
3504        let argv = [OsStr::new("--postinstall"), OsStr::new(":::")];
3505        let mut parser = Parser::new(&ROOT, &argv);
3506        assert!(matches!(
3507            parser.next_event(),
3508            Some(Err(Error::MissingFlagValue { flag })) if flag.key == POSTINSTALL.key
3509        ));
3510
3511        let argv = [
3512            OsStr::new("--postinstall"),
3513            OsStr::new("setup"),
3514            OsStr::new(":::"),
3515            OsStr::new("tool"),
3516        ];
3517        let mut parser = Parser::new(&ROOT, &argv);
3518        assert!(matches!(
3519            parser.next_event(),
3520            Some(Ok(Event::Flag {
3521                value: Some(b"setup"),
3522                ..
3523            }))
3524        ));
3525        assert!(matches!(
3526            parser.next_event(),
3527            Some(Ok(Event::ClauseSeparator { clause })) if clause.key == 95
3528        ));
3529        assert!(matches!(
3530            parser.next_event(),
3531            Some(Ok(Event::Arg { value: b"tool", .. }))
3532        ));
3533    }
3534
3535    static FORCE: Flag = Flag {
3536        key: 1,
3537        longs: &["force"],
3538        shorts: b"f",
3539        ..Flag::BOOL
3540    };
3541    static EXPLICIT_BOOL: Flag = Flag {
3542        key: 20,
3543        name: "color",
3544        longs: &["color"],
3545        negate: Some("no-color"),
3546        bool_value: true,
3547        ..Flag::BOOL
3548    };
3549    static EXPLICIT_BOOL_ROOT: Command = Command {
3550        name: "ex",
3551        flags: &[&EXPLICIT_BOOL],
3552        ..Command::EMPTY
3553    };
3554    static JOBS: Flag = Flag {
3555        key: 2,
3556        longs: &["jobs"],
3557        shorts: b"j",
3558        allow_negative_numbers: true,
3559        ..Flag::VALUE
3560    };
3561    static COLOR: Flag = Flag {
3562        key: 3,
3563        longs: &["color"],
3564        negate: Some("no-color"),
3565        ..Flag::BOOL
3566    };
3567    static VERBOSE: Flag = Flag {
3568        key: 4,
3569        longs: &["verbose"],
3570        shorts: b"v",
3571        global: true,
3572        ..Flag::BOOL
3573    };
3574    static FILE: Arg = Arg {
3575        key: 10,
3576        name: "file",
3577        allow_negative_numbers: true,
3578        ..Arg::REQUIRED
3579    };
3580    static REST: Arg = Arg {
3581        key: 11,
3582        name: "rest",
3583        ..Arg::VAR
3584    };
3585    static INSTALL: Command = Command {
3586        name: "install",
3587        aliases: &["i"],
3588        flags: &[&FORCE],
3589        key: 100,
3590        ..Command::EMPTY
3591    };
3592    /// Same shape as ROOT, but a CLI that owns all of its flags. The subcommand says
3593    /// nothing and inherits it, which is the point: only the root declares the mode.
3594    static STRICT_INSTALL: Command = Command {
3595        name: "install",
3596        aliases: &["i"],
3597        flags: &[&FORCE],
3598        key: 100,
3599        ..Command::EMPTY
3600    };
3601    static STRICT: Command = Command {
3602        name: "ex",
3603        flags: &[&FORCE, &JOBS, &COLOR, &VERBOSE],
3604        args: &[&FILE, &REST],
3605        subcommands: &[&STRICT_INSTALL],
3606        unknown_flags: Some(UnknownFlags::Error),
3607        ..Command::EMPTY
3608    };
3609    static ROOT: Command = Command {
3610        name: "ex",
3611        flags: &[&FORCE, &JOBS, &COLOR, &VERBOSE],
3612        args: &[&FILE, &REST],
3613        subcommands: &[&INSTALL],
3614        ..Command::EMPTY
3615    };
3616    static ARGUMENT_CONFLICT: Command = Command {
3617        name: "ex",
3618        flags: &[&FORCE],
3619        subcommands: &[&INSTALL],
3620        args_conflicts_with_subcommands: true,
3621        ..Command::EMPTY
3622    };
3623
3624    // A CLI shaped exactly like mise's root: a default subcommand, a positional of its own,
3625    // and a subcommand under the default — which is the arrangement that tells routing from
3626    // a plain positional.
3627    static TASK: Arg = Arg {
3628        key: 20,
3629        name: "task",
3630        ..Arg::REQUIRED
3631    };
3632    static RUN_TASK: Arg = Arg {
3633        key: 21,
3634        name: "run_task",
3635        ..Arg::REQUIRED
3636    };
3637    static DEEP: Command = Command {
3638        name: "deep",
3639        args: &[&RUN_TASK],
3640        key: 203,
3641        ..Command::EMPTY
3642    };
3643    static LINT: Command = Command {
3644        name: "lint",
3645        subcommands: &[&DEEP],
3646        // A default of its own, so that a parse which forgot it had already taken one would
3647        // have somewhere to go. Nothing else in these fixtures can show the latch working.
3648        default_subcommand: Some(&DEEP),
3649        key: 202,
3650        ..Command::EMPTY
3651    };
3652    static RUN: Command = Command {
3653        name: "run",
3654        args: &[&RUN_TASK],
3655        subcommands: &[&LINT],
3656        key: 200,
3657        ..Command::EMPTY
3658    };
3659    static DEFAULTING: Command = Command {
3660        name: "mise",
3661        flags: &[&VERBOSE],
3662        args: &[&TASK],
3663        subcommands: &[&RUN, &INSTALL],
3664        default_subcommand: Some(find_subcommand(&[&RUN, &INSTALL], "run")),
3665        ..Command::EMPTY
3666    };
3667
3668    /// Collect every event, or the first error.
3669    fn parse<'t: 'v, 'v>(
3670        root: &'t Command<'t>,
3671        argv: &'v [&'v OsStr],
3672    ) -> Result<Vec<Event<'t, 'v, 'v>>, Error<'t, 'v>> {
3673        let mut parser = Parser::new(root, argv);
3674        let mut events = Vec::new();
3675        while let Some(event) = parser.next_event() {
3676            events.push(event?);
3677        }
3678        Ok(events)
3679    }
3680
3681    fn argv<const N: usize>(tokens: [&str; N]) -> [&OsStr; N] {
3682        tokens.map(OsStr::new)
3683    }
3684
3685    #[test]
3686    fn long_boolean() {
3687        let a = argv(["--force"]);
3688        assert_eq!(
3689            parse(&ROOT, &a).unwrap(),
3690            vec![Event::Flag {
3691                flag: &FORCE,
3692                value: None,
3693                negated: false
3694            }]
3695        );
3696    }
3697
3698    #[test]
3699    fn long_boolean_accepts_only_opted_in_attached_values() {
3700        for (token, negated, value) in [
3701            ("--color=false", false, b"false".as_slice()),
3702            ("--color=true", false, b"true".as_slice()),
3703            ("--no-color=false", true, b"false".as_slice()),
3704        ] {
3705            let a = argv([token]);
3706            assert_eq!(
3707                parse(&EXPLICIT_BOOL_ROOT, &a).unwrap(),
3708                vec![Event::Flag {
3709                    flag: &EXPLICIT_BOOL,
3710                    value: Some(value),
3711                    negated,
3712                }]
3713            );
3714        }
3715
3716        let a = argv(["--color=maybe"]);
3717        assert!(matches!(
3718            parse(&EXPLICIT_BOOL_ROOT, &a),
3719            Err(Error::InvalidChoice { name: "color", .. })
3720        ));
3721
3722        let a = argv(["--force=false"]);
3723        assert_eq!(
3724            parse(&ROOT, &a).unwrap(),
3725            vec![Event::Flag {
3726                flag: &FORCE,
3727                value: None,
3728                negated: false,
3729            }]
3730        );
3731    }
3732
3733    #[test]
3734    fn long_value_forms() {
3735        for tokens in [vec!["--jobs=8"], vec!["--jobs", "8"]] {
3736            let a: Vec<&OsStr> = tokens.iter().map(|t| OsStr::new(*t)).collect();
3737            assert_eq!(
3738                parse(&ROOT, &a).unwrap(),
3739                vec![Event::Flag {
3740                    flag: &JOBS,
3741                    value: Some(b"8"),
3742                    negated: false
3743                }],
3744                "{tokens:?}"
3745            );
3746        }
3747    }
3748
3749    #[test]
3750    fn long_value_keeps_later_equals() {
3751        let a = argv(["--jobs=a=b"]);
3752        let Event::Flag { value, .. } = parse(&ROOT, &a).unwrap()[0] else {
3753            panic!("expected a flag");
3754        };
3755        assert_eq!(value, Some(&b"a=b"[..]));
3756    }
3757
3758    #[test]
3759    fn long_value_attached_empty_is_empty_not_absent() {
3760        let a = argv(["--jobs="]);
3761        let Event::Flag { value, .. } = parse(&ROOT, &a).unwrap()[0] else {
3762            panic!("expected a flag");
3763        };
3764        assert_eq!(value, Some(&b""[..]));
3765    }
3766
3767    #[test]
3768    fn long_value_refuses_flaglike_next_word() {
3769        let a = argv(["--jobs", "--force"]);
3770        assert_eq!(
3771            parse(&ROOT, &a),
3772            Err(Error::MissingFlagValue { flag: &JOBS })
3773        );
3774    }
3775
3776    #[test]
3777    fn long_value_accepts_negative_number() {
3778        let a = argv(["--jobs", "-1"]);
3779        let Event::Flag { value, .. } = parse(&ROOT, &a).unwrap()[0] else {
3780            panic!("expected a flag");
3781        };
3782        assert_eq!(value, Some(&b"-1"[..]));
3783    }
3784
3785    #[test]
3786    fn missing_optional_positional_reserves_the_last_word() {
3787        static OPTIONAL: Arg = Arg {
3788            key: 90,
3789            name: "optional",
3790            required: false,
3791            ..Arg::REQUIRED
3792        };
3793        static REQUIRED: Arg = Arg {
3794            key: 91,
3795            name: "required",
3796            ..Arg::REQUIRED
3797        };
3798        static CMD: Command = Command {
3799            name: "ex",
3800            args: &[&OPTIONAL, &REQUIRED],
3801            allow_missing_positional: true,
3802            ..Command::EMPTY
3803        };
3804
3805        let one = argv(["value"]);
3806        assert_eq!(
3807            parse(&CMD, &one).unwrap(),
3808            vec![Event::Arg {
3809                arg: &REQUIRED,
3810                value: b"value",
3811                delimit: true
3812            }]
3813        );
3814        let two = argv(["optional", "required"]);
3815        assert_eq!(
3816            parse(&CMD, &two).unwrap(),
3817            vec![
3818                Event::Arg {
3819                    arg: &OPTIONAL,
3820                    value: b"optional",
3821                    delimit: true
3822                },
3823                Event::Arg {
3824                    arg: &REQUIRED,
3825                    value: b"required",
3826                    delimit: true
3827                },
3828            ]
3829        );
3830    }
3831
3832    #[test]
3833    fn negative_numbers_are_narrowly_opted_in() {
3834        static PLAIN: Flag = Flag {
3835            key: 90,
3836            name: "plain",
3837            longs: &["plain"],
3838            ..Flag::VALUE
3839        };
3840        static VALUE: Arg = Arg {
3841            key: 91,
3842            name: "value",
3843            ..Arg::REQUIRED
3844        };
3845        static CMD: Command = Command {
3846            name: "ex",
3847            flags: &[&PLAIN],
3848            args: &[&VALUE],
3849            unknown_flags: Some(UnknownFlags::Error),
3850            ..Command::EMPTY
3851        };
3852
3853        let flag = argv(["--plain", "-1"]);
3854        assert_eq!(
3855            parse(&CMD, &flag),
3856            Err(Error::MissingFlagValue { flag: &PLAIN })
3857        );
3858        let positional = argv(["-1"]);
3859        assert_eq!(
3860            parse(&CMD, &positional),
3861            Err(Error::UnknownFlag { token: b"-1" })
3862        );
3863    }
3864
3865    #[test]
3866    fn an_exact_declared_digit_short_outranks_a_negative_number() {
3867        static PRINT0: Flag = Flag {
3868            key: 92,
3869            name: "print0",
3870            shorts: b"0",
3871            ..Flag::BOOL
3872        };
3873        static VALUE: Arg = Arg {
3874            key: 93,
3875            name: "value",
3876            required: false,
3877            allow_negative_numbers: true,
3878            ..Arg::REQUIRED
3879        };
3880        static CMD: Command = Command {
3881            name: "fd",
3882            flags: &[&PRINT0],
3883            args: &[&VALUE],
3884            unknown_flags: Some(UnknownFlags::Error),
3885            ..Command::EMPTY
3886        };
3887
3888        assert_eq!(
3889            parse(&CMD, &argv(["-0"])),
3890            Ok(vec![Event::Flag {
3891                flag: &PRINT0,
3892                value: None,
3893                negated: false,
3894            }])
3895        );
3896        assert!(matches!(
3897            parse(&CMD, &argv(["-1"])),
3898            Ok(events) if matches!(events.as_slice(), [Event::Arg { value: b"-1", .. }])
3899        ));
3900    }
3901
3902    #[test]
3903    fn negation_of_value_flag_does_not_consume_a_value() {
3904        static MODE: Flag = Flag {
3905            key: 9,
3906            name: "mode",
3907            longs: &["mode"],
3908            negate: Some("no-mode"),
3909            ..Flag::VALUE
3910        };
3911        static NEGATED_VALUE: Command = Command {
3912            name: "ex",
3913            flags: &[&MODE],
3914            args: &[&FILE],
3915            ..Command::EMPTY
3916        };
3917
3918        let a = argv(["--no-mode", "input"]);
3919        assert_eq!(
3920            parse(&NEGATED_VALUE, &a).unwrap(),
3921            vec![
3922                Event::Flag {
3923                    flag: &MODE,
3924                    value: None,
3925                    negated: true
3926                },
3927                Event::Arg {
3928                    arg: &FILE,
3929                    value: b"input",
3930                    delimit: true,
3931                }
3932            ]
3933        );
3934    }
3935
3936    #[test]
3937    fn no_abbreviation() {
3938        // A prefix names no flag, so by default it is a value like any other word.
3939        let a = argv(["--forc"]);
3940        assert_eq!(
3941            parse(&ROOT, &a).unwrap(),
3942            vec![Event::Arg {
3943                arg: &FILE,
3944                value: b"--forc",
3945                delimit: true,
3946            }]
3947        );
3948
3949        // And a CLI that owns its flags hears about it, which is the whole reason
3950        // the strict mode exists.
3951        assert!(matches!(
3952            parse(&STRICT, &a),
3953            Err(Error::UnknownFlag { token: b"--forc" })
3954        ));
3955    }
3956
3957    #[test]
3958    fn an_unknown_flag_is_a_value_by_default() {
3959        // The default, and the case it is for: a command line being forwarded to
3960        // something whose flags this spec does not know.
3961        let a = argv(["--wat", "keep"]);
3962        assert_eq!(
3963            parse(&ROOT, &a).unwrap(),
3964            vec![
3965                Event::Arg {
3966                    arg: &FILE,
3967                    value: b"--wat",
3968                    delimit: true,
3969                },
3970                Event::Arg {
3971                    arg: &REST,
3972                    value: b"keep",
3973                    delimit: true,
3974                },
3975            ]
3976        );
3977
3978        // With nowhere to put it, it is an unexpected argument — the same error an
3979        // extra word gets, rather than a special one about flags.
3980        static ONE: Command = Command {
3981            name: "ex",
3982            args: &[&FILE],
3983            ..Command::EMPTY
3984        };
3985        let a = argv(["a", "--wat"]);
3986        assert_eq!(
3987            parse(&ONE, &a),
3988            Err(Error::UnexpectedArg { token: b"--wat" })
3989        );
3990    }
3991
3992    #[test]
3993    fn negation() {
3994        let a = argv(["--no-color"]);
3995        assert_eq!(
3996            parse(&ROOT, &a).unwrap(),
3997            vec![Event::Flag {
3998                flag: &COLOR,
3999                value: None,
4000                negated: true
4001            }]
4002        );
4003    }
4004
4005    #[test]
4006    fn short_bundle_and_attached_value() {
4007        let a = argv(["-fj8"]);
4008        assert_eq!(
4009            parse(&ROOT, &a).unwrap(),
4010            vec![
4011                Event::Flag {
4012                    flag: &FORCE,
4013                    value: None,
4014                    negated: false
4015                },
4016                Event::Flag {
4017                    flag: &JOBS,
4018                    value: Some(b"8"),
4019                    negated: false
4020                },
4021            ]
4022        );
4023    }
4024
4025    #[test]
4026    fn short_value_strips_one_equals() {
4027        for (tokens, want) in [(["-j=8"], &b"8"[..]), (["-j==8"], &b"=8"[..])] {
4028            let a = argv(tokens);
4029            let Event::Flag { value, .. } = parse(&ROOT, &a).unwrap()[0] else {
4030                panic!("expected a flag");
4031            };
4032            assert_eq!(value, Some(want), "{tokens:?}");
4033        }
4034    }
4035
4036    #[test]
4037    fn bare_dash_is_a_value() {
4038        let a = argv(["-"]);
4039        assert_eq!(
4040            parse(&ROOT, &a).unwrap(),
4041            vec![Event::Arg {
4042                arg: &FILE,
4043                value: b"-",
4044                delimit: true,
4045            }]
4046        );
4047    }
4048
4049    #[test]
4050    fn positionals_then_variadic() {
4051        let a = argv(["one", "two", "three"]);
4052        assert_eq!(
4053            parse(&ROOT, &a).unwrap(),
4054            vec![
4055                Event::Arg {
4056                    arg: &FILE,
4057                    value: b"one",
4058                    delimit: true,
4059                },
4060                Event::Arg {
4061                    arg: &REST,
4062                    value: b"two",
4063                    delimit: true,
4064                },
4065                Event::Arg {
4066                    arg: &REST,
4067                    value: b"three",
4068                    delimit: true,
4069                },
4070            ]
4071        );
4072    }
4073
4074    #[test]
4075    fn subcommand_and_alias_route_the_same() {
4076        for token in ["install", "i"] {
4077            let a = argv([token]);
4078            assert_eq!(
4079                parse(&ROOT, &a).unwrap(),
4080                vec![Event::Command(&INSTALL)],
4081                "{token}"
4082            );
4083        }
4084    }
4085
4086    #[test]
4087    fn a_parent_argument_can_exclude_a_later_subcommand() {
4088        let a = argv(["--force", "install"]);
4089        assert!(matches!(
4090            parse(&ARGUMENT_CONFLICT, &a),
4091            Err(Error::SubcommandConflict { subcommand }) if subcommand.name == "install"
4092        ));
4093    }
4094
4095    #[test]
4096    fn subcommand_only_routes_before_a_positional_is_filled() {
4097        let a = argv(["other", "install"]);
4098        assert_eq!(
4099            parse(&ROOT, &a).unwrap(),
4100            vec![
4101                Event::Arg {
4102                    arg: &FILE,
4103                    value: b"other",
4104                    delimit: true,
4105                },
4106                Event::Arg {
4107                    arg: &REST,
4108                    value: b"install",
4109                    delimit: true,
4110                },
4111            ]
4112        );
4113    }
4114
4115    #[test]
4116    fn a_word_naming_no_subcommand_goes_to_the_default_one() {
4117        // usage-lib's answer, which this reproduces: `mise build` comes back as commands
4118        // `["mise", "run"]` with the word bound to *run's* argument — not to `mise`'s own
4119        // `[TASK]`, which is what makes this more than a synonym for a positional.
4120        let a = argv(["build"]);
4121        assert_eq!(
4122            parse(&DEFAULTING, &a).unwrap(),
4123            vec![
4124                Event::Command(&RUN),
4125                Event::Arg {
4126                    arg: &RUN_TASK,
4127                    value: b"build",
4128                    delimit: true,
4129                },
4130            ]
4131        );
4132    }
4133
4134    // A shared table, as a flattened struct's would be. Declared outside the tests so both
4135    // can splice it, which is the arrangement it exists to model.
4136    static SHARED_QUIET: Flag = Flag {
4137        key: 300,
4138        name: "quiet",
4139        longs: &["quiet"],
4140        ..Flag::BOOL
4141    };
4142    static SHARED_FLAGS: &[&Flag] = &[&SHARED_QUIET];
4143    static SHARED_WHAT: Arg = Arg {
4144        key: 301,
4145        name: "what",
4146        ..Arg::REQUIRED
4147    };
4148    static SHARED_ARGS: &[&Arg] = &[&SHARED_WHAT];
4149
4150    #[test]
4151    fn concatenating_tables_keeps_the_order_they_were_given_in() {
4152        // The property positional arguments depend on: a flattened group lands where the
4153        // field was written, not at the end. `[&FILE], SHARED, [&REST]` has to stay in that
4154        // order or `ex a b c` binds the wrong words.
4155        const ARGS: &[&[&Arg]] = &[&[&FILE], SHARED_ARGS, &[&REST]];
4156        static TABLE: [&Arg; table_len(ARGS)] = concat_args(ARGS);
4157        assert_eq!(
4158            TABLE.iter().map(|a| a.name).collect::<Vec<_>>(),
4159            ["file", "what", "rest"]
4160        );
4161
4162        // Empty groups contribute nothing and disturb nothing, which is what lets the derive
4163        // emit a group per field without checking whether it is empty first.
4164        const WITH_GAPS: &[&[&Flag]] = &[&[], &[&FORCE], &[], SHARED_FLAGS, &[]];
4165        static FLAGS: [&Flag; table_len(WITH_GAPS)] = concat_flags(WITH_GAPS);
4166        // By long form: these fixtures do not all set `name`, and the placeholder's is also
4167        // empty — so comparing names could not tell a real entry from a leftover slot.
4168        assert_eq!(
4169            FLAGS.iter().map(|f| f.longs).collect::<Vec<_>>(),
4170            [&["force"], &["quiet"]]
4171        );
4172    }
4173
4174    #[test]
4175    fn a_concatenated_table_parses_like_a_declared_one() {
4176        // The point of doing this at compile time: what the parser walks is one flat slice,
4177        // indistinguishable from a command that declared everything itself.
4178        const FLAG_GROUPS: &[&[&Flag]] = &[&[&FORCE], SHARED_FLAGS];
4179        const ARG_GROUPS: &[&[&Arg]] = &[SHARED_ARGS, &[&REST]];
4180        static FLAGS: [&Flag; table_len(FLAG_GROUPS)] = concat_flags(FLAG_GROUPS);
4181        static ARGS: [&Arg; table_len(ARG_GROUPS)] = concat_args(ARG_GROUPS);
4182        static JOINED: Command = Command {
4183            name: "joined",
4184            flags: &FLAGS,
4185            args: &ARGS,
4186            ..Command::EMPTY
4187        };
4188
4189        let a = argv(["--quiet", "one", "two", "--force"]);
4190        assert_eq!(
4191            parse(&JOINED, &a).unwrap(),
4192            vec![
4193                Event::Flag {
4194                    flag: &SHARED_QUIET,
4195                    value: None,
4196                    negated: false
4197                },
4198                Event::Arg {
4199                    arg: &SHARED_WHAT,
4200                    value: b"one",
4201                    delimit: true,
4202                },
4203                Event::Arg {
4204                    arg: &REST,
4205                    value: b"two",
4206                    delimit: true,
4207                },
4208                Event::Flag {
4209                    flag: &FORCE,
4210                    value: None,
4211                    negated: false
4212                },
4213            ]
4214        );
4215    }
4216
4217    #[test]
4218    fn an_unknown_flag_is_not_routed() {
4219        // A dash-prefixed token that names no flag becomes a value here (the default for
4220        // `unknown_flags`), and it must not thereby become a *subcommand* word: usage-lib
4221        // stops looking for subcommands at an unrecognised flag, and binds it to the command
4222        // still in scope. Verified against usage-lib, where `ex --wat` comes back as commands
4223        // `["ex"]` with `ROOT_TASK = "--wat"`.
4224        for token in ["--wat", "-x"] {
4225            let a = argv([token]);
4226            assert_eq!(
4227                parse(&DEFAULTING, &a).unwrap(),
4228                vec![Event::Arg {
4229                    arg: &TASK,
4230                    value: token.as_bytes(),
4231                    delimit: true,
4232                }],
4233                "{token} should bind where it was typed, not in the default subcommand"
4234            );
4235        }
4236    }
4237
4238    #[test]
4239    fn a_named_subcommand_is_not_routed() {
4240        // The default is for words that name nothing. A word that names a sibling still
4241        // selects it, and the root's own argument is still reachable behind one.
4242        let a = argv(["install"]);
4243        assert_eq!(
4244            parse(&DEFAULTING, &a).unwrap(),
4245            vec![Event::Command(&INSTALL)]
4246        );
4247    }
4248
4249    #[test]
4250    fn an_unmatched_word_is_forwarded_when_external_subcommand_is_set() {
4251        static CATCH: Command = Command {
4252            name: "ex",
4253            flags: &[&VERBOSE],
4254            subcommands: &[&INSTALL],
4255            external_subcommand: true,
4256            unknown_flags: Some(UnknownFlags::Error),
4257            ..Command::EMPTY
4258        };
4259        let a = argv(["foo", "--help", "bar"]);
4260        assert_eq!(
4261            parse(&CATCH, &a).unwrap(),
4262            vec![Event::External { values: &a[..] }]
4263        );
4264
4265        let a = argv(["install"]);
4266        assert_eq!(parse(&CATCH, &a).unwrap(), vec![Event::Command(&INSTALL)]);
4267
4268        let a = argv(["--verbose", "foo", "--verbose"]);
4269        assert_eq!(
4270            parse(&CATCH, &a).unwrap(),
4271            vec![
4272                Event::Flag {
4273                    flag: &VERBOSE,
4274                    value: None,
4275                    negated: false
4276                },
4277                Event::External { values: &a[1..] }
4278            ]
4279        );
4280
4281        let a = argv(["--wat"]);
4282        assert_eq!(
4283            parse(&CATCH, &a),
4284            Err(Error::UnknownFlag { token: b"--wat" })
4285        );
4286
4287        // A negative number is a value, not a flag, so it can be the unmatched word.
4288        let a = argv(["-1", "rest"]);
4289        assert_eq!(
4290            parse(&CATCH, &a).unwrap(),
4291            vec![Event::External { values: &a[..] }]
4292        );
4293    }
4294
4295    #[test]
4296    fn a_default_subcommand_outranks_an_external_one() {
4297        static CATCH_DEFAULT: Command = Command {
4298            name: "ex",
4299            subcommands: &[&RUN],
4300            default_subcommand: Some(&RUN),
4301            external_subcommand: true,
4302            ..Command::EMPTY
4303        };
4304        let a = argv(["build"]);
4305        assert_eq!(
4306            parse(&CATCH_DEFAULT, &a).unwrap(),
4307            vec![
4308                Event::Command(&RUN),
4309                Event::Arg {
4310                    arg: &RUN_TASK,
4311                    value: b"build",
4312                    delimit: true,
4313                }
4314            ]
4315        );
4316    }
4317
4318    #[test]
4319    fn a_default_subcommand_starts_at_the_word_it_receives() {
4320        let a = argv(["build"]);
4321        let mut parser = Parser::new(&DEFAULTING, &a);
4322        assert_eq!(parser.next_event(), Some(Ok(Event::Command(&RUN))));
4323        assert_eq!(parser.command_start(), 0);
4324        assert_eq!(
4325            parser.next_event(),
4326            Some(Ok(Event::Arg {
4327                arg: &RUN_TASK,
4328                value: b"build",
4329                delimit: true,
4330            }))
4331        );
4332    }
4333
4334    #[test]
4335    fn a_root_clause_separator_does_not_select_empty_default() {
4336        static CHILD: Command = Command {
4337            name: "run",
4338            ..Command::EMPTY
4339        };
4340        static ROOT: Command = Command {
4341            name: "ex",
4342            clause: Some(&Clause {
4343                key: 400,
4344                name: "items",
4345                separator: Some(b":::"),
4346                flags: &[],
4347                args: &[],
4348            }),
4349            subcommands: &[&CHILD],
4350            default_subcommand: Some(&CHILD),
4351            default_subcommand_on_empty: true,
4352            ..Command::EMPTY
4353        };
4354        let a = argv([":::"]);
4355        assert_eq!(
4356            parse(&ROOT, &a).unwrap(),
4357            vec![Event::ClauseSeparator {
4358                clause: *ROOT.clause.unwrap(),
4359            }]
4360        );
4361    }
4362
4363    #[test]
4364    fn the_default_can_be_named_by_an_alias() {
4365        // usage-lib resolves the name against subcommand names, aliases and hidden aliases
4366        // alike, so a spec may point `default_subcommand` at any of them.
4367        static BY_ALIAS: Command = Command {
4368            name: "mise",
4369            args: &[&TASK],
4370            subcommands: &[&INSTALL],
4371            // `INSTALL` answers to "i" as well as to its name.
4372            default_subcommand: Some(find_subcommand(&[&INSTALL], "i")),
4373            ..Command::EMPTY
4374        };
4375        assert!(::core::ptr::eq(
4376            BY_ALIAS.default_subcommand.expect("declared"),
4377            &INSTALL
4378        ));
4379    }
4380
4381    #[test]
4382    fn a_name_outranks_another_commands_alias() {
4383        // A spec `assert_unique_subcommand_names` would reject, resolved anyway: a parser
4384        // handed a table nothing validated still has to answer, and the answer is the
4385        // command whose own name it is. Both orders, because taking the first candidate
4386        // that matched on either name or alias made this depend on which was listed first
4387        // — and usage-lib, building a map, took the last.
4388        static ALPHA: Command = Command {
4389            name: "alpha",
4390            aliases: &["run"],
4391            key: 300,
4392            ..Command::EMPTY
4393        };
4394        static PLAIN_RUN: Command = Command {
4395            name: "run",
4396            key: 301,
4397            ..Command::EMPTY
4398        };
4399        for subcommands in [&[&ALPHA, &PLAIN_RUN] as &[&Command], &[&PLAIN_RUN, &ALPHA]] {
4400            assert!(::core::ptr::eq(
4401                find_subcommand(subcommands, "run"),
4402                &PLAIN_RUN
4403            ));
4404            let root: Command = Command {
4405                name: "ex",
4406                subcommands,
4407                ..Command::EMPTY
4408            };
4409            let a = argv(["run"]);
4410            assert_eq!(parse(&root, &a).unwrap(), vec![Event::Command(&PLAIN_RUN)]);
4411            // The alias still reaches its own command by every name it does not share.
4412            let a = argv(["alpha"]);
4413            assert_eq!(parse(&root, &a).unwrap(), vec![Event::Command(&ALPHA)]);
4414            // `ex help run` asks about the command `ex run` selects. These are separate
4415            // lookups — help resolves a path without descending — and answering differently
4416            // for a colliding word is the divergence this rule exists to end.
4417            let a = argv(["help", "run"]);
4418            match parse(&root, &a) {
4419                Err(Error::Help { cmd, .. }) => {
4420                    assert!(
4421                        ::core::ptr::eq(cmd, &PLAIN_RUN),
4422                        "got help for {}",
4423                        cmd.name
4424                    )
4425                }
4426                other => panic!("expected a help request, got {other:?}"),
4427            }
4428        }
4429    }
4430
4431    #[test]
4432    #[should_panic(expected = "two subcommands answer to the same name")]
4433    fn an_alias_cannot_shadow_a_sibling_command() {
4434        static ADD: Command = Command {
4435            name: "add",
4436            aliases: &["install"],
4437            ..Command::EMPTY
4438        };
4439        assert_unique_subcommand_names(&[&INSTALL, &ADD]);
4440    }
4441
4442    #[test]
4443    fn the_word_is_re_examined_against_the_command_it_reached() {
4444        // The reason the cursor steps back rather than the token being consumed: `lint` names
4445        // nothing at the root, and once inside `run` it names a subcommand. mise's mounted
4446        // task names arrive exactly this way.
4447        let a = argv(["lint"]);
4448        assert_eq!(
4449            parse(&DEFAULTING, &a).unwrap(),
4450            vec![Event::Command(&RUN), Event::Command(&LINT)]
4451        );
4452    }
4453
4454    #[test]
4455    fn the_default_is_taken_at_most_once_per_parse() {
4456        // usage-lib latches this for the whole parse rather than per command, and the shape
4457        // that shows the difference needs two of them: `lint` routes through `run`, and `lint`
4458        // declares a default too. A second word there would descend again — walking a CLI
4459        // deeper than anything the user typed — so the answer is that it does not.
4460        let a = argv(["lint", "zzz"]);
4461        assert_eq!(
4462            parse(&DEFAULTING, &a),
4463            Err(Error::UnexpectedArg { token: b"zzz" }),
4464            "the second word must not reach `deep`"
4465        );
4466
4467        // Reached explicitly, the same command still takes it: the latch bounds routing, not
4468        // the tree.
4469        let a = argv(["lint", "deep", "zzz"]);
4470        assert_eq!(
4471            parse(&DEFAULTING, &a).unwrap(),
4472            vec![
4473                Event::Command(&RUN),
4474                Event::Command(&LINT),
4475                Event::Command(&DEEP),
4476                Event::Arg {
4477                    arg: &RUN_TASK,
4478                    value: b"zzz",
4479                    delimit: true,
4480                },
4481            ]
4482        );
4483    }
4484
4485    #[test]
4486    fn a_flag_before_the_word_still_belongs_to_the_root() {
4487        // Routing happens at the word, so anything typed before it was addressed to the
4488        // command the user was actually at.
4489        let a = argv(["--verbose", "build"]);
4490        assert_eq!(
4491            parse(&DEFAULTING, &a).unwrap(),
4492            vec![
4493                Event::Flag {
4494                    flag: &VERBOSE,
4495                    value: None,
4496                    negated: false
4497                },
4498                Event::Command(&RUN),
4499                Event::Arg {
4500                    arg: &RUN_TASK,
4501                    value: b"build",
4502                    delimit: true,
4503                },
4504            ]
4505        );
4506    }
4507
4508    #[test]
4509    fn nothing_routes_after_the_separator() {
4510        // Past `--` there are no subcommands left to select, so there is no default to reach
4511        // either: the words are values of whatever the command declares.
4512        let a = argv(["--", "build"]);
4513        assert_eq!(
4514            parse(&DEFAULTING, &a).unwrap(),
4515            vec![Event::Arg {
4516                arg: &TASK,
4517                value: b"build",
4518                delimit: true,
4519            }]
4520        );
4521    }
4522
4523    #[test]
4524    fn globals_are_inherited_but_plain_flags_are_not() {
4525        let a = argv(["install", "--verbose"]);
4526        assert_eq!(
4527            parse(&ROOT, &a).unwrap(),
4528            vec![
4529                Event::Command(&INSTALL),
4530                Event::Flag {
4531                    flag: &VERBOSE,
4532                    value: None,
4533                    negated: false
4534                }
4535            ]
4536        );
4537
4538        // `--jobs` belongs to the root and is not global, so it is not a flag here.
4539        // Strictly that is an unknown flag; leniently it is a word, and `install`
4540        // declares no argument to hold one — either way it is never read as the
4541        // root's flag, which is what this test is about.
4542        let a = argv(["install", "--jobs", "8"]);
4543        assert!(matches!(parse(&STRICT, &a), Err(Error::UnknownFlag { .. })));
4544        assert!(matches!(
4545            parse(&ROOT, &a),
4546            Err(Error::UnexpectedArg { token: b"--jobs" })
4547        ));
4548    }
4549
4550    #[test]
4551    fn double_dash_protects_flaglike_values() {
4552        let a = argv(["--", "--force", "-x"]);
4553        assert_eq!(
4554            parse(&ROOT, &a).unwrap(),
4555            vec![
4556                Event::Arg {
4557                    arg: &FILE,
4558                    value: b"--force",
4559                    delimit: true,
4560                },
4561                Event::Arg {
4562                    arg: &REST,
4563                    value: b"-x",
4564                    delimit: true,
4565                },
4566            ]
4567        );
4568    }
4569
4570    #[test]
4571    fn second_double_dash_is_a_value() {
4572        let a = argv(["--", "a", "--", "b"]);
4573        let values: Vec<&[u8]> = parse(&ROOT, &a)
4574            .unwrap()
4575            .iter()
4576            .filter_map(|e| match e {
4577                Event::Arg { value, .. } => Some(*value),
4578                _ => None,
4579            })
4580            .collect();
4581        assert_eq!(values, vec![&b"a"[..], &b"--"[..], &b"b"[..]]);
4582    }
4583
4584    #[test]
4585    fn allow_hyphen_values_takes_a_flaglike_detached_value() {
4586        static ARGS: Flag = Flag {
4587            key: 6,
4588            name: "args",
4589            longs: &["args"],
4590            shorts: b"a",
4591            takes_value: true,
4592            allow_hyphen_values: true,
4593            ..Flag::BOOL
4594        };
4595        static DIR: Flag = Flag {
4596            key: 7,
4597            name: "working-dir",
4598            longs: &["working-dir"],
4599            shorts: b"d",
4600            ..Flag::VALUE
4601        };
4602        static HYPHEN: Command = Command {
4603            name: "ex",
4604            flags: &[&ARGS, &DIR],
4605            args: &[&REST],
4606            ..Command::EMPTY
4607        };
4608
4609        let a = argv(["-a", "-destroy"]);
4610        assert_eq!(
4611            parse(&HYPHEN, &a).unwrap(),
4612            vec![Event::Flag {
4613                flag: &ARGS,
4614                value: Some(b"-destroy"),
4615                negated: false
4616            }]
4617        );
4618
4619        let a = argv(["--args", "--", "-x"]);
4620        assert_eq!(
4621            parse(&HYPHEN, &a).unwrap(),
4622            vec![
4623                Event::Flag {
4624                    flag: &ARGS,
4625                    value: Some(b"--"),
4626                    negated: false
4627                },
4628                Event::Arg {
4629                    arg: &REST,
4630                    value: b"-x",
4631                    delimit: true,
4632                },
4633            ]
4634        );
4635    }
4636
4637    #[test]
4638    fn require_equals_refuses_a_detached_value() {
4639        static INSPECT: Flag = Flag {
4640            key: 8,
4641            name: "inspect",
4642            longs: &["inspect"],
4643            shorts: b"i",
4644            takes_value: true,
4645            require_equals: true,
4646            ..Flag::BOOL
4647        };
4648        static EQ: Command = Command {
4649            name: "ex",
4650            flags: &[&INSPECT],
4651            ..Command::EMPTY
4652        };
4653
4654        let a = argv(["--inspect=9229"]);
4655        assert_eq!(
4656            parse(&EQ, &a).unwrap(),
4657            vec![Event::Flag {
4658                flag: &INSPECT,
4659                value: Some(b"9229"),
4660                negated: false
4661            }]
4662        );
4663
4664        let a = argv(["--inspect", "9229"]);
4665        assert!(matches!(
4666            parse(&EQ, &a),
4667            Err(Error::MissingFlagValue { .. })
4668        ));
4669
4670        let a = argv(["-i9229"]);
4671        assert_eq!(
4672            parse(&EQ, &a).unwrap(),
4673            vec![Event::Flag {
4674                flag: &INSPECT,
4675                value: Some(b"9229"),
4676                negated: false
4677            }]
4678        );
4679
4680        static ALL: Flag = Flag {
4681            key: 9,
4682            name: "all",
4683            longs: &["all"],
4684            shorts: b"a",
4685            ..Flag::BOOL
4686        };
4687        static BUNDLE: Command = Command {
4688            name: "ex",
4689            flags: &[&ALL, &INSPECT],
4690            ..Command::EMPTY
4691        };
4692        let a = argv(["-ai", "9229"]);
4693        assert!(
4694            matches!(parse(&BUNDLE, &a), Err(Error::MissingFlagValue { .. })),
4695            "a require_equals short reached through a bundle still refuses the following word"
4696        );
4697    }
4698
4699    #[test]
4700    fn default_missing_binds_when_the_value_is_left_off() {
4701        static COLOR: Flag = Flag {
4702            key: 9,
4703            name: "color",
4704            longs: &["color"],
4705            takes_value: true,
4706            default_missing: Some(b"always"),
4707            ..Flag::BOOL
4708        };
4709        static VERBOSE: Flag = Flag {
4710            key: 10,
4711            name: "verbose",
4712            longs: &["verbose"],
4713            ..Flag::BOOL
4714        };
4715        static MISSING: Command = Command {
4716            name: "ex",
4717            flags: &[&COLOR, &VERBOSE],
4718            ..Command::EMPTY
4719        };
4720
4721        let a = argv(["--color"]);
4722        assert_eq!(
4723            parse(&MISSING, &a).unwrap(),
4724            vec![Event::Flag {
4725                flag: &COLOR,
4726                value: Some(b"always"),
4727                negated: false
4728            }]
4729        );
4730
4731        let a = argv(["--color=never"]);
4732        assert_eq!(
4733            parse(&MISSING, &a).unwrap(),
4734            vec![Event::Flag {
4735                flag: &COLOR,
4736                value: Some(b"never"),
4737                negated: false
4738            }]
4739        );
4740
4741        let a = argv(["--color", "--verbose"]);
4742        assert_eq!(
4743            parse(&MISSING, &a).unwrap(),
4744            vec![
4745                Event::Flag {
4746                    flag: &COLOR,
4747                    value: Some(b"always"),
4748                    negated: false
4749                },
4750                Event::Flag {
4751                    flag: &VERBOSE,
4752                    value: None,
4753                    negated: false
4754                },
4755            ]
4756        );
4757
4758        let a = argv(["--color="]);
4759        assert_eq!(
4760            parse(&MISSING, &a).unwrap(),
4761            vec![Event::Flag {
4762                flag: &COLOR,
4763                value: Some(b""),
4764                negated: false
4765            }]
4766        );
4767    }
4768
4769    #[test]
4770    fn optional_flag_value_distinguishes_bare_and_explicit_forms() {
4771        static BUMP: Flag = Flag {
4772            key: 11,
4773            name: "bump",
4774            longs: &["bump"],
4775            takes_value: true,
4776            value_optional: true,
4777            ..Flag::BOOL
4778        };
4779        static OPTIONAL: Command = Command {
4780            name: "ex",
4781            flags: &[&BUMP],
4782            ..Command::EMPTY
4783        };
4784
4785        assert_eq!(parse(&OPTIONAL, &argv([])).unwrap(), vec![]);
4786        assert_eq!(
4787            parse(&OPTIONAL, &argv(["--bump"])).unwrap(),
4788            vec![Event::Flag {
4789                flag: &BUMP,
4790                value: None,
4791                negated: false,
4792            }]
4793        );
4794        assert_eq!(
4795            parse(&OPTIONAL, &argv(["--bump=5"])).unwrap(),
4796            vec![Event::Flag {
4797                flag: &BUMP,
4798                value: Some(b"5"),
4799                negated: false,
4800            }]
4801        );
4802
4803        static INCLUDE: Flag = Flag {
4804            key: 12,
4805            name: "include",
4806            longs: &["include"],
4807            takes_value: true,
4808            variadic: true,
4809            value_optional: true,
4810            ..Flag::BOOL
4811        };
4812        static VERBOSE: Flag = Flag {
4813            key: 13,
4814            name: "verbose",
4815            longs: &["verbose"],
4816            ..Flag::BOOL
4817        };
4818        static VARIADIC: Command = Command {
4819            name: "ex",
4820            flags: &[&INCLUDE, &VERBOSE],
4821            args: &[&REST],
4822            ..Command::EMPTY
4823        };
4824        assert_eq!(
4825            parse(&VARIADIC, &argv(["--include", "--verbose", "file"])).unwrap(),
4826            vec![
4827                Event::Flag {
4828                    flag: &INCLUDE,
4829                    value: None,
4830                    negated: false,
4831                },
4832                Event::Flag {
4833                    flag: &VERBOSE,
4834                    value: None,
4835                    negated: false,
4836                },
4837                Event::Arg {
4838                    arg: &REST,
4839                    value: b"file",
4840                    delimit: true,
4841                },
4842            ]
4843        );
4844    }
4845
4846    #[test]
4847    fn default_missing_with_require_equals_leaves_the_following_word() {
4848        static INSPECT: Flag = Flag {
4849            key: 11,
4850            name: "inspect",
4851            longs: &["inspect"],
4852            takes_value: true,
4853            require_equals: true,
4854            default_missing: Some(b"9229"),
4855            ..Flag::BOOL
4856        };
4857        static BOTH: Command = Command {
4858            name: "ex",
4859            flags: &[&INSPECT],
4860            args: &[&REST],
4861            ..Command::EMPTY
4862        };
4863
4864        let a = argv(["--inspect"]);
4865        assert_eq!(
4866            parse(&BOTH, &a).unwrap(),
4867            vec![Event::Flag {
4868                flag: &INSPECT,
4869                value: Some(b"9229"),
4870                negated: false
4871            }]
4872        );
4873
4874        let a = argv(["--inspect", "80"]);
4875        assert_eq!(
4876            parse(&BOTH, &a).unwrap(),
4877            vec![
4878                Event::Flag {
4879                    flag: &INSPECT,
4880                    value: Some(b"9229"),
4881                    negated: false
4882                },
4883                Event::Arg {
4884                    arg: &REST,
4885                    value: b"80",
4886                    delimit: true,
4887                },
4888            ]
4889        );
4890
4891        let a = argv(["--inspect="]);
4892        assert_eq!(
4893            parse(&BOTH, &a).unwrap(),
4894            vec![Event::Flag {
4895                flag: &INSPECT,
4896                value: Some(b""),
4897                negated: false
4898            }]
4899        );
4900    }
4901
4902    #[test]
4903    fn variadic_flag_collects_until_a_flaglike_token() {
4904        static INCLUDE: Flag = Flag {
4905            key: 5,
4906            name: "include",
4907            longs: &["include"],
4908            shorts: b"i",
4909            takes_value: true,
4910            variadic: true,
4911            ..Flag::BOOL
4912        };
4913        static GREEDY: Command = Command {
4914            name: "ex",
4915            flags: &[&INCLUDE, &FORCE],
4916            args: &[&FILE],
4917            ..Command::EMPTY
4918        };
4919
4920        let a = argv(["--include", "x", "y", "--force"]);
4921        assert_eq!(
4922            parse(&GREEDY, &a).unwrap(),
4923            vec![
4924                Event::Flag {
4925                    flag: &INCLUDE,
4926                    value: Some(b"x"),
4927                    negated: false
4928                },
4929                Event::Flag {
4930                    flag: &INCLUDE,
4931                    value: Some(b"y"),
4932                    negated: false
4933                },
4934                Event::Flag {
4935                    flag: &FORCE,
4936                    value: None,
4937                    negated: false
4938                },
4939            ]
4940        );
4941    }
4942
4943    #[test]
4944    fn value_terminators_end_variadic_owners_without_binding() {
4945        static INCLUDE: Flag = Flag {
4946            key: 92,
4947            name: "include",
4948            longs: &["include"],
4949            takes_value: true,
4950            variadic: true,
4951            value_terminator: Some(b";"),
4952            ..Flag::BOOL
4953        };
4954        static ITEMS: Arg = Arg {
4955            key: 93,
4956            name: "items",
4957            var: true,
4958            value_terminator: Some(b";"),
4959            ..Arg::REQUIRED
4960        };
4961        static AFTER: Arg = Arg {
4962            key: 94,
4963            name: "after",
4964            ..Arg::REQUIRED
4965        };
4966        static FLAG_CMD: Command = Command {
4967            name: "ex",
4968            flags: &[&INCLUDE],
4969            args: &[&AFTER],
4970            ..Command::EMPTY
4971        };
4972        static ARG_CMD: Command = Command {
4973            name: "ex",
4974            args: &[&ITEMS, &AFTER],
4975            ..Command::EMPTY
4976        };
4977
4978        let flag = argv(["--include", "a", ";", "tail"]);
4979        assert_eq!(
4980            parse(&FLAG_CMD, &flag).unwrap(),
4981            vec![
4982                Event::Flag {
4983                    flag: &INCLUDE,
4984                    value: Some(b"a"),
4985                    negated: false,
4986                },
4987                Event::Arg {
4988                    arg: &AFTER,
4989                    value: b"tail",
4990                    delimit: true,
4991                },
4992            ]
4993        );
4994
4995        let positional = argv(["a", ";", "tail"]);
4996        assert_eq!(
4997            parse(&ARG_CMD, &positional).unwrap(),
4998            vec![
4999                Event::Arg {
5000                    arg: &ITEMS,
5001                    value: b"a",
5002                    delimit: true,
5003                },
5004                Event::Arg {
5005                    arg: &AFTER,
5006                    value: b"tail",
5007                    delimit: true,
5008                },
5009            ]
5010        );
5011    }
5012
5013    #[test]
5014    fn a_non_variadic_flag_leaves_the_next_word_alone() {
5015        // The counterpart to the test above: a flag that takes one value must not
5016        // swallow the word after it, which would silently steal a positional.
5017        let a = argv(["--jobs", "8", "keep-me"]);
5018        assert_eq!(
5019            parse(&ROOT, &a).unwrap(),
5020            vec![
5021                Event::Flag {
5022                    flag: &JOBS,
5023                    value: Some(b"8"),
5024                    negated: false
5025                },
5026                Event::Arg {
5027                    arg: &FILE,
5028                    value: b"keep-me",
5029                    delimit: true,
5030                },
5031            ]
5032        );
5033    }
5034
5035    #[test]
5036    fn double_dash_seen_means_a_separator_was_typed() {
5037        static FILES: Arg = Arg {
5038            key: 23,
5039            name: "files",
5040            double_dash: DoubleDash::Automatic,
5041            ..Arg::VAR
5042        };
5043        static AUTO: Command = Command {
5044            name: "ex",
5045            flags: &[&FORCE],
5046            args: &[&FILES],
5047            ..Command::EMPTY
5048        };
5049
5050        let a = argv(["--", "x"]);
5051        let mut parser = Parser::new(&ROOT, &a);
5052        while parser.next_event().is_some() {}
5053        assert!(parser.double_dash_seen(), "a real separator was consumed");
5054
5055        // `automatic` stops flag interpretation without a separator being typed,
5056        // and reporting one would be a lie to any caller that forwards argv.
5057        let a = argv(["x", "--force"]);
5058        let mut parser = Parser::new(&AUTO, &a);
5059        while parser.next_event().is_some() {}
5060        assert!(
5061            !parser.double_dash_seen(),
5062            "automatic mode must not claim a separator was given"
5063        );
5064    }
5065
5066    #[test]
5067    fn a_wrapper_still_forwards_a_help_flag() {
5068        // Supplying `--help` must not take the two forwarding mechanisms away from a wrapper,
5069        // which is the one place a CLI means to hand the token on rather than answer it.
5070        static ARGS: Arg = Arg {
5071            key: 24,
5072            name: "args",
5073            ..Arg::VAR
5074        };
5075        static WRAP: Command = Command {
5076            name: "wrap",
5077            args: &[&ARGS],
5078            ..Command::EMPTY
5079        };
5080
5081        // A typed separator: everything after it is a value, `--help` included.
5082        let a = argv(["--", "--help", "-h"]);
5083        assert_eq!(
5084            parse(&WRAP, &a).unwrap(),
5085            vec![
5086                Event::Arg {
5087                    arg: &ARGS,
5088                    value: b"--help",
5089                    delimit: true,
5090                },
5091                Event::Arg {
5092                    arg: &ARGS,
5093                    value: b"-h",
5094                    delimit: true,
5095                },
5096            ]
5097        );
5098
5099        // And `automatic`, for the wrapper whose caller should not have to type one: the
5100        // first value stops flag interpretation, so the flags after it forward.
5101        static AUTO_ARGS: Arg = Arg {
5102            key: 25,
5103            name: "args",
5104            double_dash: DoubleDash::Automatic,
5105            ..Arg::VAR
5106        };
5107        static AUTO_WRAP: Command = Command {
5108            name: "wrap",
5109            args: &[&AUTO_ARGS],
5110            ..Command::EMPTY
5111        };
5112
5113        let a = argv(["node", "--help"]);
5114        assert_eq!(
5115            parse(&AUTO_WRAP, &a).unwrap(),
5116            vec![
5117                Event::Arg {
5118                    arg: &AUTO_ARGS,
5119                    value: b"node",
5120                    delimit: true,
5121                },
5122                Event::Arg {
5123                    arg: &AUTO_ARGS,
5124                    value: b"--help",
5125                    delimit: true,
5126                },
5127            ]
5128        );
5129
5130        // Before either takes effect, though, the wrapper's own help is what `--help` asks
5131        // for — `mise run --help` is a question about `run`, not a value for it.
5132        let a = argv(["--help"]);
5133        assert_eq!(
5134            parse(&AUTO_WRAP, &a).unwrap(),
5135            vec![Event::Flag {
5136                flag: &HELP_LONG,
5137                value: None,
5138                negated: false
5139            }]
5140        );
5141    }
5142
5143    #[test]
5144    fn double_dash_required_arg() {
5145        static CMD: Arg = Arg {
5146            key: 20,
5147            name: "cmd",
5148            double_dash: DoubleDash::Required,
5149            ..Arg::REQUIRED
5150        };
5151        static EXEC: Command = Command {
5152            name: "ex",
5153            args: &[&CMD],
5154            ..Command::EMPTY
5155        };
5156
5157        let a = argv(["--", "ls"]);
5158        assert_eq!(
5159            parse(&EXEC, &a).unwrap(),
5160            vec![Event::Arg {
5161                arg: &CMD,
5162                value: b"ls",
5163                delimit: true,
5164            }]
5165        );
5166
5167        let a = argv(["ls"]);
5168        assert_eq!(
5169            parse(&EXEC, &a),
5170            Err(Error::ArgRequiresDoubleDash { arg: &CMD })
5171        );
5172    }
5173
5174    #[test]
5175    fn double_dash_preserve_keeps_the_separator() {
5176        static ARGS: Arg = Arg {
5177            key: 21,
5178            name: "args",
5179            double_dash: DoubleDash::Preserve,
5180            ..Arg::VAR
5181        };
5182        static WRAP: Command = Command {
5183            name: "ex",
5184            args: &[&ARGS],
5185            ..Command::EMPTY
5186        };
5187
5188        let a = argv(["a", "--", "b"]);
5189        let values: Vec<&[u8]> = parse(&WRAP, &a)
5190            .unwrap()
5191            .iter()
5192            .filter_map(|e| match e {
5193                Event::Arg { value, .. } => Some(*value),
5194                _ => None,
5195            })
5196            .collect();
5197        assert_eq!(values, vec![&b"a"[..], &b"--"[..], &b"b"[..]]);
5198    }
5199
5200    #[test]
5201    fn double_dash_automatic_stops_flag_interpretation() {
5202        static FILES: Arg = Arg {
5203            key: 22,
5204            name: "files",
5205            double_dash: DoubleDash::Automatic,
5206            ..Arg::VAR
5207        };
5208        static AUTO: Command = Command {
5209            name: "ex",
5210            flags: &[&FORCE],
5211            args: &[&FILES],
5212            ..Command::EMPTY
5213        };
5214
5215        // The flag before the first value is still a flag; the one after it is a
5216        // value.
5217        let a = argv(["-f", "one", "--force"]);
5218        assert_eq!(
5219            parse(&AUTO, &a).unwrap(),
5220            vec![
5221                Event::Flag {
5222                    flag: &FORCE,
5223                    value: None,
5224                    negated: false
5225                },
5226                Event::Arg {
5227                    arg: &FILES,
5228                    value: b"one",
5229                    delimit: true,
5230                },
5231                Event::Arg {
5232                    arg: &FILES,
5233                    value: b"--force",
5234                    delimit: true,
5235                },
5236            ]
5237        );
5238    }
5239
5240    #[test]
5241    fn too_many_words() {
5242        static ONE: Command = Command {
5243            name: "ex",
5244            args: &[&FILE],
5245            ..Command::EMPTY
5246        };
5247        let a = argv(["a", "b"]);
5248        assert_eq!(parse(&ONE, &a), Err(Error::UnexpectedArg { token: b"b" }));
5249    }
5250
5251    #[test]
5252    fn unknown_letter_rejects_the_whole_bundle() {
5253        // `-f` is real and `-z` is not. The first event must be the error: if the
5254        // flag event came out first, a caller would have applied `-f` from a
5255        // command line that was rejected.
5256        let a = argv(["-fz"]);
5257        let mut parser = Parser::new(&STRICT, &a);
5258        assert_eq!(
5259            parser.next_event(),
5260            Some(Err(Error::UnknownFlag { token: b"-fz" })),
5261            "an unknown letter must reject the token before any of it is applied"
5262        );
5263        assert!(parser.next_event().is_none());
5264
5265        // Leniently, the same token is a value — and `-f` is *not* applied, since
5266        // the token was never a bundle at all.
5267        let a = argv(["-fz"]);
5268        assert_eq!(
5269            parse(&ROOT, &a).unwrap(),
5270            vec![Event::Arg {
5271                arg: &FILE,
5272                value: b"-fz",
5273                delimit: true,
5274            }]
5275        );
5276    }
5277
5278    #[test]
5279    fn unknown_short_error_names_the_whole_token() {
5280        for (tokens, want) in [(["-z"], &b"-z"[..]), (["-fz"], &b"-fz"[..])] {
5281            let a = argv(tokens);
5282            assert_eq!(
5283                parse(&STRICT, &a),
5284                Err(Error::UnknownFlag { token: want }),
5285                "{tokens:?}"
5286            );
5287        }
5288    }
5289
5290    #[test]
5291    fn errors_are_terminal() {
5292        let a = argv(["--wat", "--force"]);
5293        let mut parser = Parser::new(&STRICT, &a);
5294        assert!(parser.next_event().unwrap().is_err());
5295        assert!(parser.next_event().is_none());
5296    }
5297
5298    #[test]
5299    fn non_utf8_values_still_parse() {
5300        // A value that is not valid UTF-8 binds; only converting it fails, and
5301        // only if a caller asks.
5302        let raw = OsStr::new("--force");
5303        let a = [raw];
5304        assert!(parse(&ROOT, &a).is_ok());
5305
5306        assert!(as_str(b"ok").is_ok());
5307        assert!(as_str(&[0xff, 0xfe]).is_err());
5308    }
5309
5310    #[test]
5311    fn a_multicall_applet_is_the_basename_unless_it_is_the_dispatcher() {
5312        assert_eq!(multicall_basename("/usr/bin/ls"), "ls");
5313        assert_eq!(multicall_basename(r"C:\busybox\ls.exe"), "ls");
5314        assert_eq!(
5315            multicall_applet("/usr/bin/ls", "busybox", Some("busybox")),
5316            Some("ls")
5317        );
5318        assert_eq!(
5319            multicall_applet("/usr/bin/busybox", "busybox", Some("busybox")),
5320            None
5321        );
5322        assert_eq!(
5323            multicall_applet("ls.exe", "busybox", Some("busybox")),
5324            Some("ls")
5325        );
5326        assert_eq!(
5327            multicall_applet("/usr/bin/busybox", "BusyBox", Some("/opt/bin/busybox")),
5328            None
5329        );
5330        assert_eq!(
5331            multicall_applet("busybox.exe", "BusyBox", Some("busybox.exe")),
5332            None
5333        );
5334    }
5335
5336    #[test]
5337    fn a_spec_request_is_the_first_word_and_nothing_else() {
5338        let request = [OsStr::new(SPEC_REQUEST)];
5339        assert!(is_spec_request(&ROOT, &request));
5340
5341        // Anywhere but the front it is an ordinary value, which is what makes the endpoint
5342        // safe for a CLI whose arguments are arbitrary text.
5343        let later = ["install", SPEC_REQUEST].map(OsStr::new);
5344        assert!(!is_spec_request(&ROOT, &later));
5345        assert!(!is_spec_request(&ROOT, &[]));
5346        assert!(!is_spec_request(&ROOT, &[OsStr::new("--help")]));
5347    }
5348
5349    #[test]
5350    fn a_declared_command_of_that_name_keeps_it() {
5351        static DECLARED: Command = Command {
5352            name: SPEC_REQUEST,
5353            key: 200,
5354            ..Command::EMPTY
5355        };
5356        static ALIASED: Command = Command {
5357            name: "describe",
5358            aliases: &[SPEC_REQUEST],
5359            key: 201,
5360            ..Command::EMPTY
5361        };
5362        static DECLARES_IT: Command = Command {
5363            name: "ex",
5364            subcommands: &[&DECLARED],
5365            ..Command::EMPTY
5366        };
5367        static ALIASES_IT: Command = Command {
5368            name: "ex",
5369            subcommands: &[&ALIASED],
5370            ..Command::EMPTY
5371        };
5372
5373        let request = [OsStr::new(SPEC_REQUEST)];
5374        assert!(!is_spec_request(&DECLARES_IT, &request));
5375        // An alias selects a command just as its name does, so it wins here too.
5376        assert!(!is_spec_request(&ALIASES_IT, &request));
5377    }
5378}