rust_args_parser/
lib.rs

1#![forbid(unsafe_code)]
2#![warn(missing_docs)]
3
4//! SPDX-License-Identifier: MIT or Apache-2.0
5//! rust-args-parser — Tiny, fast, callback-based CLI argument parser for Rust inspired by
6//! <https://github.com/milchinskiy/c-args-parser>
7
8use std::env;
9use std::fmt::{self, Write as _};
10use std::io::{self, Write};
11
12/* ================================ Public API ================================= */
13type BoxError = Box<dyn std::error::Error>;
14/// Library level error type.
15pub type Result<T> = std::result::Result<T, Error>;
16
17/// Each option/flag invokes a callback.
18pub type OptCallback<Ctx> =
19    for<'a> fn(Option<&'a str>, &mut Ctx) -> std::result::Result<(), BoxError>;
20
21/// Command runner for the resolved command (receives final positionals).
22pub type RunCallback<Ctx> = fn(&[&str], &mut Ctx) -> std::result::Result<(), BoxError>;
23
24/// Whether the option takes a value or not.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum ArgKind {
27    /// No value required
28    None,
29    /// Value required
30    Required,
31    /// Value optional
32    Optional,
33}
34
35/// Group mode.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum GroupMode {
38    /// No group
39    None,
40    /// Exclusive group
41    Xor,
42    /// Required one group
43    ReqOne,
44}
45/// Value hint.
46#[derive(Clone, Copy)]
47pub enum ValueHint {
48    /// Any value
49    Any,
50    /// Number
51    Number,
52}
53/// An option/flag specification.
54#[derive(Clone, Copy)]
55pub struct OptSpec<'a, Ctx: ?Sized> {
56    name: &'a str,            // long name without "--"
57    short: Option<char>,      // short form without '-'
58    arg: ArgKind,             // whether it takes a value
59    metavar: Option<&'a str>, // shown in help for value
60    help: &'a str,            // help text
61    env: Option<&'a str>,     // environment variable default (name)
62    default: Option<&'a str>, // string default
63    group_id: u16,            // 0 = none, >0 = group identifier
64    group_mode: GroupMode,    // XOR / REQ_ONE semantics
65    value_hint: ValueHint,    // value hint
66    cb: OptCallback<Ctx>,     // callback on set/apply
67}
68
69impl<'a, Ctx: ?Sized> OptSpec<'a, Ctx> {
70    /// Create a new option.
71    pub const fn new(name: &'a str, cb: OptCallback<Ctx>) -> Self {
72        Self {
73            name,
74            short: None,
75            arg: ArgKind::None,
76            metavar: None,
77            help: "",
78            env: None,
79            default: None,
80            group_id: 0,
81            group_mode: GroupMode::None,
82            value_hint: ValueHint::Any,
83            cb,
84        }
85    }
86    /// Set value hint
87    #[must_use]
88    pub const fn numeric(mut self) -> Self {
89        self.value_hint = ValueHint::Number;
90        self
91    }
92    /// Set short form.
93    #[must_use]
94    pub const fn short(mut self, short: char) -> Self {
95        self.short = Some(short);
96        self
97    }
98    /// Set metavar.
99    #[must_use]
100    pub const fn metavar(mut self, metavar: &'a str) -> Self {
101        self.metavar = Some(metavar);
102        self
103    }
104    /// Set help text.
105    #[must_use]
106    pub const fn help(mut self, help: &'a str) -> Self {
107        self.help = help;
108        self
109    }
110    /// Set argument kind.
111    #[must_use]
112    pub const fn arg(mut self, arg: ArgKind) -> Self {
113        self.arg = arg;
114        self
115    }
116    /// Set optional
117    #[must_use]
118    pub const fn optional(mut self) -> Self {
119        self.arg = ArgKind::Optional;
120        self
121    }
122    /// Set required
123    #[must_use]
124    pub const fn required(mut self) -> Self {
125        self.arg = ArgKind::Required;
126        self
127    }
128    /// Set flag
129    #[must_use]
130    pub const fn flag(mut self) -> Self {
131        self.arg = ArgKind::None;
132        self
133    }
134    /// Set environment variable name.
135    #[must_use]
136    pub const fn env(mut self, env: &'a str) -> Self {
137        self.env = Some(env);
138        self
139    }
140    /// Set default value.
141    #[must_use]
142    pub const fn default(mut self, val: &'a str) -> Self {
143        self.default = Some(val);
144        self
145    }
146    /// Set at most one state and group identifier.
147    #[must_use]
148    pub const fn at_most_one(mut self, group_id: u16) -> Self {
149        self.group_id = group_id;
150        self.group_mode = GroupMode::Xor;
151        self
152    }
153    /// Set at least one state and group identifier.
154    #[must_use]
155    pub const fn at_least_one(mut self, group_id: u16) -> Self {
156        self.group_id = group_id;
157        self.group_mode = GroupMode::ReqOne;
158        self
159    }
160}
161
162/// Positional argument specification.
163#[derive(Clone, Copy)]
164pub struct PosSpec<'a> {
165    name: &'a str,
166    desc: Option<&'a str>,
167    min: usize,
168    max: usize,
169}
170
171impl<'a> PosSpec<'a> {
172    /// Create a new positional argument.
173    #[must_use]
174    pub const fn new(name: &'a str) -> Self {
175        Self { name, desc: None, min: 0, max: 0 }
176    }
177    /// Set description.
178    #[must_use]
179    pub const fn desc(mut self, desc: &'a str) -> Self {
180        self.desc = Some(desc);
181        self
182    }
183    /// Set one required.
184    #[must_use]
185    pub const fn one(mut self) -> Self {
186        self.min = 1;
187        self.max = 1;
188        self
189    }
190    /// Set any number.
191    #[must_use]
192    pub const fn range(mut self, min: usize, max: usize) -> Self {
193        self.min = min;
194        self.max = max;
195        self
196    }
197}
198
199/// Command specification.
200pub struct CmdSpec<'a, Ctx: ?Sized> {
201    name: Option<&'a str>, // None for root
202    desc: Option<&'a str>,
203    opts: Box<[OptSpec<'a, Ctx>]>,
204    subs: Box<[CmdSpec<'a, Ctx>]>,
205    pos: Box<[PosSpec<'a>]>,
206    aliases: Box<[&'a str]>,
207    run: Option<RunCallback<Ctx>>, // called with positionals
208}
209
210impl<'a, Ctx: ?Sized> CmdSpec<'a, Ctx> {
211    /// Create a new command.
212    /// `name` is `None` for root command.
213    #[must_use]
214    pub fn new(name: Option<&'a str>, run: Option<RunCallback<Ctx>>) -> Self {
215        Self {
216            name,
217            desc: None,
218            opts: Vec::new().into_boxed_slice(),
219            subs: Vec::new().into_boxed_slice(),
220            pos: Vec::new().into_boxed_slice(),
221            aliases: Vec::new().into_boxed_slice(),
222            run,
223        }
224    }
225    /// Set description.
226    #[must_use]
227    pub const fn desc(mut self, desc: &'a str) -> Self {
228        self.desc = Some(desc);
229        self
230    }
231    /// Set options.
232    #[must_use]
233    pub fn opts<S>(mut self, s: S) -> Self
234    where
235        S: Into<Vec<OptSpec<'a, Ctx>>>,
236    {
237        self.opts = s.into().into_boxed_slice();
238        self
239    }
240    /// Set positionals.
241    #[must_use]
242    pub fn pos<S>(mut self, s: S) -> Self
243    where
244        S: Into<Vec<PosSpec<'a>>>,
245    {
246        self.pos = s.into().into_boxed_slice();
247        self
248    }
249    /// Set subcommands.
250    #[must_use]
251    pub fn subs<S>(mut self, s: S) -> Self
252    where
253        S: Into<Vec<Self>>,
254    {
255        self.subs = s.into().into_boxed_slice();
256        self
257    }
258    /// Set aliases.
259    #[must_use]
260    pub fn aliases<S>(mut self, s: S) -> Self
261    where
262        S: Into<Vec<&'a str>>,
263    {
264        self.aliases = s.into().into_boxed_slice();
265        self
266    }
267}
268
269/// Environment configuration
270pub struct Env<'a> {
271    name: &'a str,
272    version: Option<&'a str>,
273    author: Option<&'a str>,
274    auto_help: bool,
275    wrap_cols: usize,
276    color: bool,
277}
278
279impl<'a> Env<'a> {
280    /// Create a new environment.
281    #[must_use]
282    pub const fn new(name: &'a str) -> Self {
283        Self { name, version: None, author: None, auto_help: false, wrap_cols: 0, color: false }
284    }
285    /// Set version.
286    #[must_use]
287    pub const fn version(mut self, version: &'a str) -> Self {
288        self.version = Some(version);
289        self
290    }
291    /// Set author.
292    #[must_use]
293    pub const fn author(mut self, author: &'a str) -> Self {
294        self.author = Some(author);
295        self
296    }
297    /// Set auto help.
298    #[must_use]
299    pub const fn auto_help(mut self, auto_help: bool) -> Self {
300        self.auto_help = auto_help;
301        self
302    }
303    /// Set wrap columns.
304    #[must_use]
305    pub const fn wrap_cols(mut self, wrap_cols: usize) -> Self {
306        self.wrap_cols = wrap_cols;
307        self
308    }
309    /// Set color.
310    #[must_use]
311    pub const fn color(mut self, color: bool) -> Self {
312        self.color = color;
313        self
314    }
315    /// Set auto color.
316    /// Check for `NO_COLOR` env var.
317    #[must_use]
318    pub fn auto_color(mut self) -> Self {
319        self.color = env::var("NO_COLOR").is_err();
320        self
321    }
322}
323
324/// Parse and dispatch starting from `root` using `argv` (not including program name), writing
325/// auto help/version/author output to `out` when triggered.
326/// # Errors
327/// See [`Error`]
328pub fn dispatch_to<Ctx: ?Sized, W: Write>(
329    env: &Env<'_>,
330    root: &CmdSpec<'_, Ctx>,
331    argv: &[&str],
332    context: &mut Ctx,
333    out: &mut W,
334) -> Result<()> {
335    let mut idx = 0usize;
336    let mut cmd = root;
337    let mut chain: Vec<&str> = Vec::new();
338    while idx < argv.len() {
339        if let Some(next) = find_sub(cmd, argv[idx]) {
340            chain.push(argv[idx]);
341            cmd = next;
342            idx += 1;
343        } else {
344            break;
345        }
346    }
347    // If this command defines subcommands but no positional schema,
348    // the next bare token must be a known subcommand; otherwise it's an error.
349    if !cmd.subs.is_empty() && cmd.pos.is_empty() && idx < argv.len() {
350        let tok = argv[idx];
351        if !tok.starts_with('-') && tok != "--" && find_sub(cmd, tok).is_none() {
352            return Err(unknown_command_error(cmd, tok));
353        }
354    }
355    // small counter array parallel to opts
356    let mut gcounts: Vec<u8> = vec![0; cmd.opts.len()];
357    // parse options and collect positionals
358    let mut pos: Vec<&str> = Vec::with_capacity(argv.len().saturating_sub(idx));
359    let mut stop_opts = false;
360    while idx < argv.len() {
361        let tok = argv[idx];
362        if !stop_opts {
363            if tok == "--" {
364                stop_opts = true;
365                idx += 1;
366                continue;
367            }
368            if tok.starts_with("--") {
369                idx += 1;
370                parse_long(env, cmd, tok, &mut idx, argv, context, &mut gcounts, out, &chain)?;
371                continue;
372            }
373            if is_short_like(tok) {
374                idx += 1;
375                parse_short_cluster(env, cmd, tok, &mut idx, argv, context, &mut gcounts, out, &chain)?;
376                continue;
377            }
378        }
379        pos.push(tok);
380        idx += 1;
381    }
382    // When no positional schema is declared, any leftover bare token is unexpected.
383    if cmd.pos.is_empty() && !pos.is_empty() {
384        return Err(Error::UnexpectedArgument(pos[0].to_string()));
385    }
386    apply_env_and_defaults(cmd, context, &mut gcounts)?;
387    // strict groups: XOR → ≤1, REQ_ONE → ≥1 (env/defaults count)
388    check_groups(cmd, &gcounts)?;
389    // validate positionals against schema
390    validate_positionals(cmd, &pos)?;
391    // run command
392    if let Some(run) = cmd.run {
393        return run(&pos, context).map_err(Error::Callback);
394    }
395    if env.auto_help {
396        print_help_to(env, cmd, &chain, out);
397    }
398    Err(Error::Exit(1))
399}
400
401/// Default dispatch that prints auto help/version/author to **stdout**.
402/// # Errors
403/// See [`Error`]
404pub fn dispatch<Ctx>(
405    env: &Env<'_>,
406    root: &CmdSpec<'_, Ctx>,
407    argv: &[&str],
408    context: &mut Ctx,
409) -> Result<()> {
410    let mut out = io::stdout();
411    dispatch_to(env, root, argv, context, &mut out)
412}
413
414/* ================================ Suggestions ===================================== */
415#[inline]
416fn format_alternates(items: &[String]) -> String {
417    match items.len() {
418        0 => String::new(),
419        1 => format!("'{}'", items[0]),
420        2 => format!("'{}' or '{}'", items[0], items[1]),
421        _ => {
422            // 'a', 'b', or 'c'
423            let mut s = String::new();
424            for (i, it) in items.iter().enumerate() {
425                if i > 0 {
426                    s.push_str(if i + 1 == items.len() { ", or " } else { ", " });
427                }
428                s.push('\'');
429                s.push_str(it);
430                s.push('\'');
431            }
432            s
433        }
434    }
435}
436
437#[inline]
438const fn max_distance_for(len: usize) -> usize {
439    match len {
440        0..=3 => 1,
441        4..=6 => 2,
442        _ => 3,
443    }
444}
445
446// Simple Levenshtein (O(n*m)); inputs are tiny (flags/commands), so it's fine.
447fn lev(a: &str, b: &str) -> usize {
448    let (na, nb) = (a.len(), b.len());
449    if na == 0 {
450        return nb;
451    }
452    if nb == 0 {
453        return na;
454    }
455    let mut prev: Vec<usize> = (0..=nb).collect();
456    let mut curr = vec![0; nb + 1];
457    for (i, ca) in a.chars().enumerate() {
458        curr[0] = i + 1;
459        for (j, cb) in b.chars().enumerate() {
460            let cost = usize::from(ca != cb);
461            curr[j + 1] = (prev[j + 1] + 1).min(curr[j] + 1).min(prev[j] + cost);
462        }
463        std::mem::swap(&mut prev, &mut curr);
464    }
465    prev[nb]
466}
467
468fn collect_long_candidates<Ctx: ?Sized>(env: &Env<'_>, cmd: &CmdSpec<'_, Ctx>) -> Vec<String> {
469    let mut v = Vec::with_capacity(cmd.opts.len() + 3);
470    if env.auto_help {
471        v.push("help".to_string());
472    }
473    if env.version.is_some() {
474        v.push("version".to_string());
475    }
476    if env.author.is_some() {
477        v.push("author".to_string());
478    }
479    for o in &cmd.opts {
480        v.push(o.name.to_string());
481    }
482    v
483}
484
485fn collect_short_candidates<Ctx: ?Sized>(env: &Env<'_>, cmd: &CmdSpec<'_, Ctx>) -> Vec<char> {
486    let mut v = Vec::with_capacity(cmd.opts.len() + 3);
487    if env.auto_help {
488        v.push('h');
489    }
490    if env.version.is_some() {
491        v.push('V');
492    }
493    if env.author.is_some() {
494        v.push('A');
495    }
496    for o in &cmd.opts {
497        if let Some(ch) = o.short {
498            v.push(ch);
499        }
500    }
501    v
502}
503
504fn collect_cmd_candidates<'a, Ctx: ?Sized>(cmd: &'a CmdSpec<'a, Ctx>) -> Vec<&'a str> {
505    let mut v = Vec::with_capacity(cmd.subs.len());
506    for s in &cmd.subs {
507        if let Some(n) = s.name {
508            v.push(n);
509        }
510        for &al in &s.aliases {
511            v.push(al);
512        }
513    }
514    v
515}
516
517fn suggest_longs<Ctx: ?Sized>(env: &Env<'_>, cmd: &CmdSpec<'_, Ctx>, name: &str) -> Vec<String> {
518    let thr = max_distance_for(name.len());
519    let mut scored: Vec<(usize, String)> = collect_long_candidates(env, cmd)
520        .into_iter()
521        .map(|cand| (lev(name, &cand), format!("--{cand}")))
522        .collect();
523    scored.sort_by_key(|(d, _)| *d);
524    scored.into_iter().take_while(|(d, _)| *d <= thr).take(3).map(|(_, s)| s).collect()
525}
526
527fn suggest_shorts<Ctx: ?Sized>(env: &Env<'_>, cmd: &CmdSpec<'_, Ctx>, ch: char) -> Vec<String> {
528    let mut v: Vec<(usize, String)> = collect_short_candidates(env, cmd)
529        .into_iter()
530        .map(|c| (usize::from(c != ch), format!("-{c}")))
531        .collect();
532    v.sort_by_key(|(d, _)| *d);
533    v.into_iter().take_while(|(d, _)| *d <= 1).take(3).map(|(_, s)| s).collect()
534}
535
536fn suggest_cmds<Ctx: ?Sized>(cmd: &CmdSpec<'_, Ctx>, tok: &str) -> Vec<String> {
537    let thr = max_distance_for(tok.len());
538    let mut v: Vec<(usize, String)> = collect_cmd_candidates(cmd)
539        .into_iter()
540        .map(|cand| (lev(tok, cand), cand.to_string()))
541        .collect();
542    v.sort_by_key(|(d, _)| *d);
543    v.into_iter().take_while(|(d, _)| *d <= thr).take(3).map(|(_, s)| s).collect()
544}
545
546/* ================================ Errors ===================================== */
547#[non_exhaustive]
548#[derive(Debug)]
549/// Error type
550pub enum Error {
551    /// Missing value
552    MissingValue(String),
553    /// Unexpected argument
554    UnexpectedArgument(String),
555    /// Unknown option
556    UnknownOption {
557        /// Token
558        token: String,
559        /// Suggestions
560        suggestions: Vec<String>,
561    },
562    /// Unknown command
563    UnknownCommand {
564        /// Token
565        token: String,
566        /// Suggestions
567        suggestions: Vec<String>,
568    },
569    /// Group violation
570    GroupViolation(String),
571    /// Missing positional
572    MissingPositional(String),
573    /// Too many positionals
574    TooManyPositional(String),
575    /// Callback error
576    Callback(BoxError),
577    /// Exit with code
578    Exit(i32),
579    /// User error
580    User(&'static str),
581}
582impl fmt::Display for Error {
583    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
584        match self {
585            Self::UnknownOption { token, suggestions } => {
586                write!(f, "unknown option: '{token}'")?;
587                if !suggestions.is_empty() {
588                    write!(f, ". Did you mean {}?", format_alternates(suggestions))?;
589                }
590                Ok(())
591            }
592            Self::MissingValue(n) => write!(f, "missing value for --{n}"),
593            Self::UnexpectedArgument(s) => write!(f, "unexpected argument: {s}"),
594            Self::UnknownCommand { token, suggestions } => {
595                write!(f, "unknown command: {token}")?;
596                if !suggestions.is_empty() {
597                    write!(f, ". Did you mean {}?", format_alternates(suggestions))?;
598                }
599                Ok(())
600            }
601            Self::GroupViolation(s) => write!(f, "{s}"),
602            Self::MissingPositional(n) => write!(f, "missing positional: {n}"),
603            Self::TooManyPositional(n) => write!(f, "too many values for: {n}"),
604            Self::Callback(e) => write!(f, "{e}"),
605            Self::Exit(code) => write!(f, "exit {code}"),
606            Self::User(s) => write!(f, "{s}"),
607        }
608    }
609}
610impl std::error::Error for Error {}
611
612/* ================================ Parsing ==================================== */
613fn find_sub<'a, Ctx: ?Sized>(
614    cmd: &'a CmdSpec<'a, Ctx>,
615    name: &str,
616) -> Option<&'a CmdSpec<'a, Ctx>> {
617    for c in &cmd.subs {
618        if let Some(n) = c.name {
619            if n == name {
620                return Some(c);
621            }
622        }
623        if c.aliases.contains(&name) {
624            return Some(c);
625        }
626    }
627    None
628}
629fn apply_env_and_defaults<Ctx: ?Sized>(
630    cmd: &CmdSpec<'_, Ctx>,
631    context: &mut Ctx,
632    counts: &mut [u8],
633) -> Result<()> {
634    if cmd.opts.is_empty() {
635        return Ok(());
636    }
637    if !any_env_or_default(cmd) {
638        return Ok(());
639    }
640
641    // env first
642    for (i, o) in cmd.opts.iter().enumerate() {
643        if let Some(key) = o.env {
644            if let Ok(val) = std::env::var(key) {
645                counts[i] = counts[i].saturating_add(1);
646                (o.cb)(Some(val.as_str()), context).map_err(Error::Callback)?;
647            }
648        }
649    }
650    // defaults next; skip if anything in the same group is already present
651    for (i, o) in cmd.opts.iter().enumerate() {
652        if counts[i] != 0 {
653            continue;
654        }
655        let Some(def) = o.default else { continue };
656        if o.group_id != 0 {
657            let gid = o.group_id;
658            let mut taken = false;
659            for (j, p) in cmd.opts.iter().enumerate() {
660                if p.group_id == gid && counts[j] != 0 {
661                    taken = true;
662                    break;
663                }
664            }
665            if taken {
666                continue;
667            }
668        }
669        counts[i] = counts[i].saturating_add(1);
670        (o.cb)(Some(def), context).map_err(Error::Callback)?;
671    }
672    Ok(())
673}
674
675#[allow(clippy::too_many_arguments)]
676fn parse_long<Ctx: ?Sized, W: std::io::Write>(
677    env: &Env<'_>,
678    cmd: &CmdSpec<'_, Ctx>,
679    tok: &str,
680    idx: &mut usize,
681    argv: &[&str],
682    context: &mut Ctx,
683    counts: &mut [u8],
684    out: &mut W,
685    chain: &[&str],
686) -> Result<()> {
687    // formats: --name, --name=value, --name value
688    let s = &tok[2..];
689    let (name, attached) = s
690        .as_bytes()
691        .iter()
692        .position(|&b| b == b'=')
693        .map_or((s, None), |eq| (&s[..eq], Some(&s[eq + 1..])));
694    // built‑ins
695    if env.auto_help && name == "help" {
696        print_help_to(env, cmd, chain, out);
697        return Err(Error::Exit(0));
698    }
699    if env.version.is_some() && name == "version" {
700        print_version_to(env, out);
701        return Err(Error::Exit(0));
702    }
703    if env.author.is_some() && name == "author" {
704        print_author_to(env, out);
705        return Err(Error::Exit(0));
706    }
707    let (i, spec) = match cmd.opts.iter().enumerate().find(|(_, o)| o.name == name) {
708        Some(x) => x,
709        None => return Err(unknown_long_error(env, cmd, name)),
710    };
711    counts[i] = counts[i].saturating_add(1);
712    match spec.arg {
713        ArgKind::None => {
714            (spec.cb)(None, context).map_err(Error::Callback)?;
715        }
716        ArgKind::Required => {
717            let v = if let Some(a) = attached {
718                if a.is_empty() {
719                    return Err(Error::MissingValue(spec.name.to_string()));
720                }
721                a
722            } else {
723                take_next(idx, argv).ok_or_else(|| Error::MissingValue(spec.name.to_string()))?
724            };
725            (spec.cb)(Some(v), context).map_err(Error::Callback)?;
726        }
727        ArgKind::Optional => {
728            let v = match (attached, argv.get(*idx).copied()) {
729                (Some(a), _) => Some(a),
730                (None, Some("-")) => {
731                    *idx += 1; // consume standalone "-" but treat as none
732                    None
733                }
734                (None, Some(n))
735                    if matches!(spec.value_hint, ValueHint::Number) && is_dash_number(n) =>
736                {
737                    *idx += 1;
738                    Some(n)
739                }
740                (None, Some(n)) if looks_value_like(n) => {
741                    *idx += 1;
742                    Some(n)
743                }
744                _ => None,
745            };
746            (spec.cb)(v, context).map_err(Error::Callback)?;
747        }
748    }
749    Ok(())
750}
751
752#[allow(clippy::too_many_arguments)]
753fn parse_short_cluster<Ctx: ?Sized, W: std::io::Write>(
754    env: &Env<'_>,
755    cmd: &CmdSpec<'_, Ctx>,
756    tok: &str,
757    idx: &mut usize,
758    argv: &[&str],
759    context: &mut Ctx,
760    counts: &mut [u8],
761    out: &mut W,
762    chain: &[&str],
763) -> Result<()> {
764    // formats: -abc, -j10, -j 10, -j -12  (no -j=10 by design)
765    let short_idx = build_short_idx(cmd);
766    let s = &tok[1..];
767    let bytes = s.as_bytes();
768    let mut i = 0usize;
769    while i < bytes.len() {
770        // Fast ASCII path for common cases; fall back to UTF‑8 char boundary when needed.
771        let (ch, adv) = if bytes[i] < 128 {
772            (bytes[i] as char, 1)
773        } else {
774            let c = s[i..].chars().next().unwrap();
775            (c, c.len_utf8())
776        };
777        i += adv;
778
779        // built‑ins
780        if env.auto_help && ch == 'h' {
781            print_help_to(env, cmd, chain, out);
782            return Err(Error::Exit(0));
783        }
784        if env.version.is_some() && ch == 'V' {
785            print_version_to(env, out);
786            return Err(Error::Exit(0));
787        }
788        if env.author.is_some() && ch == 'A' {
789            print_author_to(env, out);
790            return Err(Error::Exit(0));
791        }
792        let (oi, spec) = match lookup_short(cmd, &short_idx, ch) {
793            Some(x) => x,
794            None => return Err(unknown_short_error(env, cmd, ch)),
795        };
796        counts[oi] = counts[oi].saturating_add(1);
797        match spec.arg {
798            ArgKind::None => {
799                (spec.cb)(None, context).map_err(Error::Callback)?;
800            }
801            ArgKind::Required => {
802                if i < s.len() {
803                    let rem = &s[i..];
804                    (spec.cb)(Some(rem), context).map_err(Error::Callback)?;
805                    return Ok(());
806                }
807                let v = take_next(idx, argv)
808                    .ok_or_else(|| Error::MissingValue(spec.name.to_string()))?;
809                (spec.cb)(Some(v), context).map_err(Error::Callback)?;
810                return Ok(());
811            }
812            ArgKind::Optional => {
813                if i < s.len() {
814                    let rem = &s[i..];
815                    (spec.cb)(Some(rem), context).map_err(Error::Callback)?;
816                    return Ok(());
817                }
818                // SPECIAL: if next token is exactly "-", CONSUME it but treat as "no value".
819                let v = match argv.get(*idx) {
820                    Some(&"-") => {
821                        *idx += 1;
822                        None
823                    }
824                    // If hint is Number, allow a directly following numeric like `-j -1.25`.
825                    Some(n)
826                        if matches!(spec.value_hint, ValueHint::Number) && is_dash_number(n) =>
827                    {
828                        *idx += 1;
829                        Some(n)
830                    }
831                    // Otherwise consume if it looks like a plausible value (incl. -1, -0.5, 1e3…)
832                    Some(n) if looks_value_like(n) => {
833                        *idx += 1;
834                        Some(n)
835                    }
836                    _ => None,
837                };
838                (spec.cb)(v.map(|v| &**v), context).map_err(Error::Callback)?;
839                return Ok(());
840            }
841        }
842    }
843    Ok(())
844}
845
846#[inline]
847fn any_env_or_default<Ctx: ?Sized>(cmd: &CmdSpec<'_, Ctx>) -> bool {
848    cmd.opts.iter().any(|o| o.env.is_some() || o.default.is_some())
849}
850#[inline]
851fn take_next<'a>(idx: &mut usize, argv: &'a [&'a str]) -> Option<&'a str> {
852    let i = *idx;
853    if i < argv.len() {
854        *idx = i + 1;
855        Some(argv[i])
856    } else {
857        None
858    }
859}
860#[inline]
861fn is_short_like(s: &str) -> bool {
862    let b = s.as_bytes();
863    b.len() >= 2 && b[0] == b'-' && b[1] != b'-'
864}
865#[inline]
866fn is_dash_number(s: &str) -> bool {
867    let b = s.as_bytes();
868    if b.is_empty() || b[0] != b'-' {
869        return false;
870    }
871    // "-" alone is not a number
872    if b.len() == 1 {
873        return false;
874    }
875    is_numeric_like(&b[1..])
876}
877#[inline]
878fn looks_value_like(s: &str) -> bool {
879    if !s.starts_with('-') {
880        return true;
881    }
882    if s == "-" {
883        return false;
884    }
885    is_numeric_like(&s.as_bytes()[1..])
886}
887#[inline]
888fn is_numeric_like(b: &[u8]) -> bool {
889    // digits, optional dot, optional exponent part
890    let mut i = 0;
891    let n = b.len();
892    // optional leading dot: .5
893    if i < n && b[i] == b'.' {
894        i += 1;
895    }
896    // at least one digit
897    let mut nd = 0;
898    while i < n && (b[i] as char).is_ascii_digit() {
899        i += 1;
900        nd += 1;
901    }
902    if nd == 0 {
903        return false;
904    }
905    // optional fractional part .ddd
906    if i < n && b[i] == b'.' {
907        i += 1;
908        while i < n && (b[i] as char).is_ascii_digit() {
909            i += 1;
910        }
911    }
912    // optional exponent e[+/-]ddd
913    if i < n && (b[i] == b'e' || b[i] == b'E') {
914        i += 1;
915        if i < n && (b[i] == b'+' || b[i] == b'-') {
916            i += 1;
917        }
918        let mut ed = 0;
919        while i < n && (b[i] as char).is_ascii_digit() {
920            i += 1;
921            ed += 1;
922        }
923        if ed == 0 {
924            return false;
925        }
926    }
927    i == n
928}
929
930fn check_groups<Ctx: ?Sized>(cmd: &CmdSpec<'_, Ctx>, counts: &[u8]) -> Result<()> {
931    let opts = &cmd.opts;
932    let opts_len = opts.len();
933    let mut index = 0usize;
934    while index < opts_len {
935        let id = opts[index].group_id;
936        if id != 0 {
937            // ensure we only process each id once
938            let mut seen = false;
939            let mut k = 0usize;
940            while k < index {
941                if opts[k].group_id == id {
942                    seen = true;
943                    break;
944                }
945                k += 1;
946            }
947            if !seen {
948                let mut total = 0u32;
949                let mut xor = false;
950                let mut req = false;
951                let mut j = 0usize;
952                while j < opts_len {
953                    let o = &opts[j];
954                    if o.group_id == id {
955                        total += u32::from(counts[j]);
956                        match o.group_mode {
957                            GroupMode::Xor => xor = true,
958                            GroupMode::ReqOne => req = true,
959                            GroupMode::None => {}
960                        }
961                        if xor && total > 1 {
962                            return Err(Error::GroupViolation(group_msg(opts, id, true)));
963                        }
964                    }
965                    j += 1;
966                }
967                if req && total == 0 {
968                    return Err(Error::GroupViolation(group_msg(opts, id, false)));
969                }
970            }
971        }
972        index += 1;
973    }
974    Ok(())
975}
976
977#[cold]
978#[inline(never)]
979fn group_msg<Ctx: ?Sized>(opts: &[OptSpec<'_, Ctx>], id: u16, xor: bool) -> String {
980    let mut names = String::new();
981    for o in opts.iter().filter(|o| o.group_id == id) {
982        if !names.is_empty() {
983            names.push_str(" | ");
984        }
985        names.push_str(o.name);
986    }
987    if xor {
988        format!("at most one of the following options may be used: {names}")
989    } else {
990        format!("one of the following options is required: {names}")
991    }
992}
993
994fn validate_positionals<Ctx: ?Sized>(cmd: &CmdSpec<'_, Ctx>, pos: &[&str]) -> Result<()> {
995    if cmd.pos.is_empty() {
996        return Ok(());
997    }
998    let total = pos.len();
999    let mut min_sum: usize = 0;
1000    let mut max_sum: Option<usize> = Some(0);
1001    for p in &cmd.pos {
1002        min_sum = min_sum.saturating_add(p.min);
1003        if let Some(ms) = max_sum {
1004            if p.max == usize::MAX {
1005                max_sum = None;
1006            } else {
1007                max_sum = Some(ms.saturating_add(p.max));
1008            }
1009        }
1010    }
1011    // Not enough arguments: find the first positional whose minimum cannot be met
1012    if total < min_sum {
1013        let mut need = 0usize;
1014        for p in &cmd.pos {
1015            need = need.saturating_add(p.min);
1016            if total < need {
1017                return Err(Error::MissingPositional(p.name.to_string()));
1018            }
1019        }
1020        // Fallback (should be unreachable)
1021        return Err(Error::MissingPositional(
1022            cmd.pos.first().map_or("<args>", |p| p.name).to_string(),
1023        ));
1024    }
1025    // Too many arguments (only when all maxima are finite)
1026    if let Some(ms) = max_sum {
1027        if total > ms {
1028            let last = cmd.pos.last().map_or("<args>", |p| p.name);
1029            return Err(Error::TooManyPositional(last.to_string()));
1030        }
1031    }
1032    Ok(())
1033}
1034#[inline]
1035const fn plain_opt_label_len<Ctx: ?Sized>(o: &OptSpec<'_, Ctx>) -> usize {
1036    let mut len = if o.short.is_some() { 4 } else { 0 }; // "-x, "
1037    len += 2 + o.name.len(); // "--" + name
1038    if let Some(m) = o.metavar {
1039        len += 1 + m.len();
1040    }
1041    len
1042}
1043#[inline]
1044fn make_opt_label<Ctx: ?Sized>(o: &OptSpec<'_, Ctx>) -> String {
1045    let mut s = String::new();
1046    if let Some(ch) = o.short {
1047        s.push('-');
1048        s.push(ch);
1049        s.push(',');
1050        s.push(' ');
1051    }
1052    s.push_str("--");
1053    s.push_str(o.name);
1054    if let Some(m) = o.metavar {
1055        s.push(' ');
1056        s.push_str(m);
1057    }
1058    s
1059}
1060
1061/* ================================ Help ======================================= */
1062const C_BOLD: &str = "\u{001b}[1m";
1063const C_UNDERLINE: &str = "\u{001b}[4m";
1064const C_BRIGHT_WHITE: &str = "\u{001b}[97m";
1065const C_CYAN: &str = "\u{001b}[36m";
1066const C_MAGENTA: &str = "\u{001b}[35m";
1067const C_YELLOW: &str = "\u{001b}[33m";
1068const C_RESET: &str = "\u{001b}[0m";
1069#[inline]
1070fn colorize(s: &str, color: &str, env: &Env) -> String {
1071    if !env.color || color.is_empty() {
1072        s.to_string()
1073    } else {
1074        format!("{color}{s}{C_RESET}")
1075    }
1076}
1077#[inline]
1078fn help_text_for_opt<Ctx: ?Sized>(o: &OptSpec<'_, Ctx>) -> String {
1079    match (o.env, o.default) {
1080        (Some(k), Some(d)) => format!("{} (env {k}, default={d})", o.help),
1081        (Some(k), None) => format!("{} (env {k})", o.help),
1082        (None, Some(d)) => format!("{} (default={d})", o.help),
1083        (None, None) => o.help.to_string(),
1084    }
1085}
1086#[inline]
1087fn print_header(buf: &mut String, text: &str, env: &Env) {
1088    let _ = writeln!(buf, "\n{}:", colorize(text, &[C_BOLD, C_UNDERLINE].concat(), env).as_str());
1089}
1090#[inline]
1091fn lookup_short<'a, Ctx: ?Sized>(
1092    cmd: &'a CmdSpec<'a, Ctx>,
1093    table: &[u16; 128],
1094    ch: char,
1095) -> Option<(usize, &'a OptSpec<'a, Ctx>)> {
1096    let c = ch as u32;
1097    if c < 128 {
1098        let i = table[c as usize];
1099        if i != u16::MAX {
1100            let idx = i as usize;
1101            return Some((idx, &cmd.opts[idx]));
1102        }
1103        return None;
1104    }
1105    cmd.opts.iter().enumerate().find(|(_, o)| o.short == Some(ch))
1106}
1107fn build_short_idx<Ctx: ?Sized>(cmd: &CmdSpec<'_, Ctx>) -> [u16; 128] {
1108    let mut map = [u16::MAX; 128];
1109    let mut i = 0usize;
1110    let len = cmd.opts.len();
1111    while i < len {
1112        let o = &cmd.opts[i];
1113        if let Some(ch) = o.short {
1114            let cu = ch as usize;
1115            if cu < 128 {
1116                debug_assert!(u16::try_from(i).is_ok());
1117                map[cu] = u16::try_from(i).unwrap_or(0); // safe due to debug assert
1118            }
1119        }
1120        i += 1;
1121    }
1122    map
1123}
1124#[inline]
1125fn write_wrapped(buf: &mut String, text: &str, indent_cols: usize, wrap_cols: usize) {
1126    if wrap_cols == 0 {
1127        let _ = writeln!(buf, "{text}");
1128        return;
1129    }
1130    let mut col = indent_cols;
1131    let mut first = true;
1132    for word in text.split_whitespace() {
1133        let wlen = word.len();
1134        if first {
1135            for _ in 0..indent_cols {
1136                buf.push(' ');
1137            }
1138            buf.push_str(word);
1139            col = indent_cols + wlen;
1140            first = false;
1141            continue;
1142        }
1143        if col + 1 + wlen > wrap_cols {
1144            buf.push('\n');
1145            for _ in 0..indent_cols {
1146                buf.push(' ');
1147            }
1148            buf.push_str(word);
1149            col = indent_cols + wlen;
1150        } else {
1151            buf.push(' ');
1152            buf.push_str(word);
1153            col += 1 + wlen;
1154        }
1155    }
1156    buf.push('\n');
1157}
1158
1159fn write_row(
1160    buf: &mut String,
1161    env: &Env,
1162    color: &str,
1163    plain_label: &str,
1164    help: &str,
1165    label_col: usize,
1166) {
1167    let _ = write!(buf, "  {}", colorize(plain_label, color, env));
1168    let pad = label_col.saturating_sub(plain_label.len());
1169    for _ in 0..pad {
1170        buf.push(' ');
1171    }
1172    buf.push(' ');
1173    buf.push(' ');
1174    let indent = 4 + label_col;
1175    write_wrapped(buf, help, indent, env.wrap_cols);
1176}
1177
1178/// Print help to the provided writer.
1179#[cold]
1180#[inline(never)]
1181pub fn print_help_to<Ctx: ?Sized, W: Write>(
1182    env: &Env<'_>,
1183    cmd: &CmdSpec<'_, Ctx>,
1184    path: &[&str],
1185    mut out: W,
1186) {
1187    let mut buf = String::new();
1188    let _ = write!(
1189        buf,
1190        "Usage: {}",
1191        colorize(env.name, [C_BOLD, C_BRIGHT_WHITE].concat().as_str(), env)
1192    );
1193    for tok in path {
1194        let _ = write!(buf, " {}", colorize(tok, C_MAGENTA, env));
1195    }
1196    if !cmd.subs.is_empty() {
1197        let _ = write!(buf, " {}", colorize("<command>", C_MAGENTA, env));
1198    }
1199    if !cmd.opts.is_empty() {
1200        let _ = write!(buf, " {}", colorize("[options]", C_CYAN, env));
1201    }
1202    for p in &cmd.pos {
1203        if p.min == 0 {
1204            let _ = write!(buf, " [{}]", colorize(p.name, C_YELLOW, env));
1205        } else if p.min == 1 && p.max == 1 {
1206            let _ = write!(buf, " {}", colorize(p.name, C_YELLOW, env));
1207        } else if p.max > 1 {
1208            let _ = write!(buf, " {}...", colorize(p.name, C_YELLOW, env));
1209        }
1210    }
1211    let _ = writeln!(buf);
1212    if let Some(desc) = cmd.desc {
1213        let _ = writeln!(buf, "\n{desc}");
1214    }
1215    if env.auto_help || env.version.is_some() || env.author.is_some() || !cmd.opts.is_empty() {
1216        print_header(&mut buf, "Options", env);
1217        let mut width = 0usize;
1218        if env.auto_help {
1219            width = width.max("-h, --help".len());
1220        }
1221        if env.version.is_some() {
1222            width = width.max("-V, --version".len());
1223        }
1224        if env.author.is_some() {
1225            width = width.max("-A, --author".len());
1226        }
1227        for o in &cmd.opts {
1228            width = width.max(plain_opt_label_len(o));
1229        }
1230
1231        if env.auto_help {
1232            write_row(&mut buf, env, C_CYAN, "-h, --help", "Show this help and exit", width);
1233        }
1234        if env.version.is_some() {
1235            write_row(&mut buf, env, C_CYAN, "-V, --version", "Show version and exit", width);
1236        }
1237        if env.author.is_some() {
1238            write_row(&mut buf, env, C_CYAN, "--author", "Show author and exit", width);
1239        }
1240        for o in &cmd.opts {
1241            let label = make_opt_label(o);
1242            let help = help_text_for_opt(o);
1243            write_row(&mut buf, env, C_CYAN, &label, &help, width);
1244        }
1245    }
1246    // Commands
1247    if !cmd.subs.is_empty() {
1248        print_header(&mut buf, "Commands", env);
1249        let width = cmd.subs.iter().map(|s| s.name.unwrap_or("<root>").len()).max().unwrap_or(0);
1250        for s in &cmd.subs {
1251            let name = s.name.unwrap_or("<root>");
1252            write_row(&mut buf, env, C_MAGENTA, name, s.desc.unwrap_or(""), width);
1253        }
1254    }
1255    // Positionals
1256    if !cmd.pos.is_empty() {
1257        print_header(&mut buf, "Positionals", env);
1258        let width = cmd.pos.iter().map(|p| p.name.len()).max().unwrap_or(0);
1259        for p in &cmd.pos {
1260            let help = help_for_pos(p);
1261            write_row(&mut buf, env, C_YELLOW, p.name, &help, width);
1262        }
1263    }
1264    let _ = out.write_all(buf.as_bytes());
1265}
1266fn help_for_pos(p: &PosSpec) -> String {
1267    if let Some(d) = p.desc {
1268        return d.to_string();
1269    }
1270    if p.min == 0 {
1271        return "(optional)".to_string();
1272    }
1273    if p.min == 1 && p.max == 1 {
1274        return "(required)".to_string();
1275    }
1276    if p.min == 1 {
1277        return "(at least one required)".to_string();
1278    }
1279    format!("min={} max={}", p.min, p.max)
1280}
1281/// Prints the version number
1282#[cold]
1283#[inline(never)]
1284pub fn print_version_to<W: Write>(env: &Env<'_>, mut out: W) {
1285    if let Some(v) = env.version {
1286        let _ = writeln!(out, "{v}");
1287    }
1288}
1289/// Prints the author
1290#[cold]
1291#[inline(never)]
1292pub fn print_author_to<W: Write>(env: &Env<'_>, mut out: W) {
1293    if let Some(a) = env.author {
1294        let _ = writeln!(out, "{a}");
1295    }
1296}
1297#[cold]
1298#[inline(never)]
1299fn unknown_long_error<Ctx: ?Sized>(env: &Env<'_>, cmd: &CmdSpec<'_, Ctx>, name: &str) -> Error {
1300    let token = {
1301        let mut s = String::with_capacity(2 + name.len());
1302        s.push_str("--");
1303        s.push_str(name);
1304        s
1305    };
1306    let suggestions = suggest_longs(env, cmd, name);
1307    Error::UnknownOption { token, suggestions }
1308}
1309
1310#[cold]
1311#[inline(never)]
1312fn unknown_short_error<Ctx: ?Sized>(env: &Env<'_>, cmd: &CmdSpec<'_, Ctx>, ch: char) -> Error {
1313    let mut token = String::with_capacity(2);
1314    token.push('-');
1315    token.push(ch);
1316    let suggestions = suggest_shorts(env, cmd, ch);
1317    Error::UnknownOption { token, suggestions }
1318}
1319
1320#[cold]
1321#[inline(never)]
1322fn unknown_command_error<Ctx: ?Sized>(cmd: &CmdSpec<'_, Ctx>, tok: &str) -> Error {
1323    Error::UnknownCommand { token: tok.to_string(), suggestions: suggest_cmds(cmd, tok) }
1324}