Skip to main content

Module parser

Module parser 

Source
Expand description

Tokenization and argument parsing for raw argv slices.

The parser operates in three stages:

  1. Tokenize — the raw &[&str] argv is converted to a typed token stream by the internal tokenizer module. Each token is one of: a plain word, a long flag (--name / --name=val), a short flag (-f / -fval), or the -- separator.

  2. Subcommand tree walk — the first word token is resolved to a top-level Command using the Resolver. While the resolved command has subcommands and the next token is a word that resolves to one of them, the parser descends into the subcommand tree. A word that fails to resolve is treated as the start of positional arguments rather than an error.

  3. Flag and argument binding — remaining tokens are bound using a queue-based loop: long and short flag tokens are matched against the resolved command’s flag definitions; plain word tokens are accumulated as positional arguments. Adjacent short flags (-abc) are expanded inline: each boolean flag in the run registers "true" and the remaining characters are re-queued as a new ShortFlag token. Boolean flags also support --no-{name} negation syntax, which sets the value to "false". After all tokens are consumed, positional arguments are bound by declaration order (variadic last arguments collect all remaining positionals into a JSON array); required flags and arguments are validated; and defaults and environment-variable fallbacks are applied.

§Example

let cmd = Command::builder("list")
    .argument(Argument::builder("filter").build().unwrap())
    .flag(Flag::builder("verbose").short('v').build().unwrap())
    .build()
    .unwrap();

let cmds = vec![cmd];
let parser = Parser::new(&cmds);

let parsed = parser.parse(&["list", "foo", "-v"]).unwrap();
assert_eq!(parsed.command.canonical, "list");
assert_eq!(parsed.args["filter"], "foo");
assert_eq!(parsed.flags["verbose"], "true");

Structs§

Parser
Parses raw argument slices against a slice of registered Commands.

Enums§

ParseError
Errors produced by Parser::parse.