Repository navigation
refactor(args): declare flag grammars once, as data - #5099
Conversation
📊 Automated PR Analysis
SummaryRefactors the flag-handling logic in several RTK filters so each tool's flag grammar is declared once as a data table (Grammar/Flag) instead of hand-written predicate functions, with a new abbreviation axis for GNU-style unique-prefix matching. Along the way it fixes several tools' flag parsing to match their actual documented behavior (e.g. git -q meaning, grep -h meaning, ls --numeric-uid-gid handling), covering git, grep, rg, ast-grep, ls, dotnet, maven, golangci-lint, gh, glab, ruff, pytest… Review Checklist
Analyzed automatically by wshm · This is an automated analysis, not a human review. |
576476b to
ad59943
Compare
7ed06f8 to
f52a2fa
Compare
aeppling
left a comment
There was a problem hiding this comment.
Two regressions against develop, both reproduced with release builds of develop and of this branch merged onto develop. Neither comes from #3998.
1. git branch --format=… gets two leading spaces when the listing is one line
$ git branch --format='%(refname:short)' # repo with one branch
main
$ rtk git branch --format='%(refname:short)' # this PR
main
Same with --contains HEAD, --points-at side, -l feat-one: any --format listing that comes back as one line. With two or more lines the output is git's bytes. develop prints main followed by an extra blank line, so the value itself was intact there.
2. grep -r PATTERN file drops the filename prefix under BSD grep
$ grep -rn needle src/main.rs # BSD grep 2.6.0
src/main.rs:2: println!("needle");
$ rtk grep -rn needle src/main.rs # this PR
2: println!("needle");
Same with -r, -R and --recursive. wants_show_file in src/cmds/system/search.rs applies GNU grep 3.12's rule to every grep. BSD grep prints the prefix for a lone file operand under recursion, and develop matches it.
f52a2fa to
9ee625c
Compare
|
Thank you for the review, both findings reproduced here and are fixed in the amended commit. 1. 2.
|
A tool's flag grammar is a `Grammar` in `core/arg_tokenizer.rs`: a
`Dialect` and a list of `Flag` tables, built with `Grammar::new(dialect,
tables)`. The dialect's single-dash axis decides how a flag is spelled.
Under `SingleDash::Cluster` (`Dialect::Posix`) `-x` is a `Short`
token and `--name` a `Long` one, so a flag is a getopt flag with a short
and a long spelling, either optional: `Flag::short`, `Flag::long`,
`Flag::pair`. Under `Atomic` and `AtomicAliasingLong` (`Dialect::Msbuild`,
`CommonsCli`, `GoFlag`) every name is one whole word read as `Long`, so a
flag is `Flag::atomic(&["c", "configuration"])`, one flag under every name
it lists. `Grammar::new` refuses a flag its dialect cannot read, so a
getopt flag in an atomic grammar, or the reverse, cannot sit there
matching nothing. `.takes(spec)` records how each spelling takes its
value; a spelling that is always the whole argument (a long one, any atomic name)
records a solo-only spec as a plain value, and `.takes` panics on a
solo-only spec for a flag with no short spelling. Every flag and grammar in
the crate is a `const`, where either panic is a compile error.
A new axis, `Abbreviation`, says whether a long flag may be typed as a
prefix of its spelling. `Never`, the value of every preset, reads only the
whole spelling. `UniquePrefix` reads GNU `getopt_long`'s rule: a whole
spelling wins over a longer one it prefixes (`--all` is not
`--almost-all`), a prefix of exactly one declared long spelling names that
flag (`ls --sor time` sorts by time), and a prefix of two names neither.
`tokenize_grammar(args, &GRAMMAR)` reads the dialect and every value rule
from the grammar and looks each flag token up once: `Grammar::flag(kind,
name)` finds the declared flag, a `Short` token matching only a short
spelling and a `Long` token only a long one or an atomic name (folding
ASCII case under `NameCase::Folded`, resolving a prefix under
`UniquePrefix`), and the token keeps it in `Token::flag`, beside the grammar's
tables. Code holding tokens asks the token (`token.is(&FLAG)`,
`token.is_one_of(FLAGS)`, `token.value_spec()`), so a token asked several
questions costs one search of the grammar. `is` and `is_one_of` compare
flags by their spellings, which name one declaration per grammar, and every
flag they are asked about must be declared in the grammar that read the
token, exactly as declared: a debug build panics on an undeclared flag or on
a copy that differs from the declaration in one field, and a release build
answers `false`, since no token of that grammar can be that flag. Code that
branches on which of several flags a token is matches `token.flag()` against
their consts (`Some(&FORMAT | &PRETTY)`), each arm pinned by a test. The
lookups by name (`has_flag`, `has_double_dash_flag`,
`double_dash_flag_value(s)`) take the grammar that read the tokens and read
its naming rules, a prefix the grammar resolved included, so the name they look for need not be declared.
A predicate that asks for a flag only some grammars declare keeps its tokens
to those grammars. `git log`/`show` and `git diff` read their arguments into
`LogTokens` and `DiffTokens`, which only `tokenize_log_args` and
`tokenize_diff_args` build: `git show`'s `-q`/`--quiet` check takes
`LogTokens`, and `git diff`'s `--quiet` checks (`suppresses_diff_body`,
`diff_wants_raw_shape`) take `DiffTokens`. Both deref to the token slice for
the checks every git grammar answers alike. The predicates that take a grep
or rg engine, and the git ones that take tokens of either `log` or `diff`,
state which grammar read their tokens.
A grammar declares every flag that takes a value and every flag of the tool
a handler checks tokens for, booleans included, each with the spellings the
tool pairs; a further spelling of the same kind is a flag of its own (git's
`-u` beside `-p`/`--patch`, grep's `--silent` beside `-q`/`--quiet`). Each
spelling and value arity is transcribed from git 2.53's man pages,
`-h` output and `git-completion.bash`, GNU grep 3.12's `--help` and rg's
binary. A check for a set of flags looks the token's flag up in a slice of
consts: git's patch requests, raw log shapes, output indicators, content
transforms, branch actions and list modes, grep's and rg's file lists and
output shapes. A check that only one engine has a flag for asks the engine
(`Engine::no_filename`, `Engine::no_line_number`), so no token is asked
about a flag its grammar lacks. `Grammar` has no notion of a repeatable flag
or of the numeric `-N` shorthand; the handlers that read `-N` test for a
digit run.
Subcommands whose options go through one parser share one grammar:
`git log` and `show` read theirs with `LOG_GRAMMAR`. Distinct grammars
share tables: `git diff`'s `DIFF_GRAMMAR` lists the revision-walk tables
`LOG_GRAMMAR` lists, with `-u` as `-p` and a `--quiet` of its own, and
`git stash show`'s lists them with its own `-u`/`--include-untracked`;
golangci-lint's `run` lists the global table and the output sinks, and
ast-grep's `run` lists the global table beside its own.
The git (global options, status, log/show, diff, checkout, branch, stash
show, worktree, ls-tree), golangci-lint (global, run), ast-grep (global,
run), cargo (the options before its command), grep, rg, dotnet, maven, ls,
ruff (global), glab (view, mr
merge/approve/note/update) and gh (view, pr
checks, run view, pr comment/edit), `rtk task`, pytest (its value flags) and the
usage-request check (git's message flags, `cargo install --version`) grammars are declared this way,
each with a test that checks it against an explicit table of the flags it
declares and the spec each takes (`None` for a boolean flag), under every
token kind and for undeclared names. The same check fails on a spelling
declared twice, compared under the grammar's naming rules. A handler reads
an argument list once and asks every question of those tokens: `git show`
its route, its objects and its content transforms, `git stash show` its
patch request and its word diff, `rtk grep`/`rtk rg` the help request, the
pattern, the paths and the file-list shape, `git log`'s cap probe which flags it
leaves out of the walk it measures (the output shapes, `--graph`,
`--reverse`, and the merge-diff family off a walk that does not select by
diff), ast-grep's `run` its
`--stdin`, its `-i`/`--interactive` and its `--json`, and `ls` whether it
lists dotfiles, whether it prints the long format, and which value flag
ends its arguments unanswered.
The code follows each tool's own pairing, which sets these rules:
- git's `-B`/`--break-rewrites`, `-C`/`--find-copies`,
`-M`/`--find-renames`, `-U`/`--unified` and `-X`/`--dirstat` are one flag
each, with an optional value that is attached only: git 2.53 reads the
`50` of `-M 50` and of `--find-renames 50` as a revision.
`-I`/`--ignore-matching-lines` is one flag, taking a separate value.
- `-l`, the rename limit, takes the rest of its argument or the next one
wherever it sits in a short cluster, under `git log`, `show`, `diff` and
`stash show`: rtk reads the `5` of `-wl 5`, `-pl 5`, `-cl 5` and `-ml 5`
as `-l`'s value. git 2.53's `log` and `show` read it so after `-p`, `-u`,
`-s`, `-w` and `-W`; after `-c`, `-m` and `-t` they read the `5` as a
revision and exit 128 before printing anything, and rtk passes that
failure on. git rejects `git stash show -wl 5`, which takes the `5` as its
stash.
- `-L`, the line log (`-L<start>,<end>:<file>`, `-L:<funcname>:<file>`),
takes a value and has no long spelling (git 2.53's `git log -h` lists
`-L <range:file>` alone). It prints each commit that touches the range
with its patch of that range, so `git log -L` and `git show -L` route
raw: `rtk git log -L 1,2:f` prints git's bytes and exit code.
- `-X` is `--dirstat` under `git log`, `diff` and `show`: git 2.53 reads
`-Xfiles` as the parameter `files`, `-Xp` as the parameter `p` and `-pX`
as `-p` then `-X`. rtk routes both spellings raw, so `git diff -X` prints
git's dirstat.
- The diffstat and dirstat parameters git spells as flags of their own
(`--stat-width`, `--stat-name-width`, `--stat-graph-width`,
`--stat-count`, `--dirstat-by-file`, `--cumulative`) print the stat or the
dirstat as `--stat` and `-X` do, and route raw under `git log`, `show` and
`diff`: `git diff --stat-width=60 HEAD~2` prints git's diffstat. So does
`-z` under `show` and `diff`, which ends git's records with a NUL (the
objects of `show`, the `--raw` and `--numstat` fields); the filtered
`git log` keeps the NUL that ends each commit.
- `--dd` is `--diff-merges=first-parent -p`: `git log --dd` routes raw, as
`git log -p` does, and under `show` and `diff`, whose default output is a
patch, it compacts as `-p` does. `-q` outranks it on either side in
`git show`, as in git 2.53.
- `--output-indicator-new`, `--output-indicator-old` and
`--output-indicator-context` replace the `+`, `-` and ` ` markers
`compact_diff` reads, so `git show` and `git diff` route them raw:
compacting `git diff --output-indicator-old=Y` would count none of the
removed lines. A plain `git log` prints no patch for them to change.
- `-q` is `--quiet` under `git log` and `git show`, and not under
`git diff`: git 2.53's `git log -h` and `git show -h` list
`-q, --[no-]quiet suppress diff output`, `git diff -h` lists no `-q`,
`git diff -q` with no revision prints the patch and exits 0, and
`git diff -q HEAD~1`, `git diff --cached -q` and `git stash show -q` are
usage errors (129). `git show -q` prints the commit summary with no
diffstat, as `git show --quiet` and `-s` do, and a patch request on
either side of it (`-q -p`, `-p -q`) prints the diff, as in git.
- `git stash show` reads its own options, `-u`/`--[no-]include-untracked`
and `--only-untracked`, before the diff options, so `-u` is never `-p`
there: `git stash show -u` prints the stat of the tracked and untracked
files, as git 2.53 does. A value-taking diff option takes the flag after
it, as git's revision machinery takes it: git 2.53 reads the `-p` of
`git stash show --author -p` as the author, and prints a patch only
because any argument makes `stash show` print one, which rtk reads from
git's output; `--author --word-diff` prints a plain patch, which rtk
compacts.
- `git show` of a blob passes through raw when a content transform
(`--textconv`, `--ext-diff`, `--filters`) is one of its options, read from
the tokens. In `git show --grep --textconv HEAD:big.txt` the `--textconv`
is `--grep`'s pattern and git 2.53 prints the plain blob, which rtk
windows as it windows `git show HEAD:big.txt`.
- `git branch -l`/`--list` list the local branches, and the ones matching a
pattern when given one: `git branch -l 'feat*'` prints git's listing of
the matching branches, and a listing without the current branch has no
`* ` line, as in git's.
- A `git branch` listing ends each line with one newline and adds no blank
line. An empty listing (`git branch -r` with no remotes,
`--list 'nomatch*'`, `--no-merged` with every branch merged) prints
nothing, as git 2.53 does. A `--format` listing, which is the caller's own
layout rather than git's default one, or one whose every line is a remote's
`HEAD -> ...` alias, which the compact form leaves out
(`git branch -a --list '*HEAD*'`), prints git's bytes.
- `git branch --delete`/`--move`/`--copy` write, as `-d`/`-m`/`-c` do.
- grep's recursion (`-r`, `-R`, `--recursive`, `--dereference-recursive`)
shows the filename by default, for a lone file operand too. BSD grep
prefixes a lone file under recursion and GNU grep 3.12 does not; rtk
forces `-H` on the engine and cannot tell which grep it runs, so it keeps
the prefix. An explicit `-h` still removes it.
- grep's `-d ACTION`/`--directories=ACTION` takes its value attached or as
the next argument, and `recurse` is recursion, as `-r` is ("like
--directories=recurse", grep 3.12's `--help`); `read` and `skip` are not.
grep reads any prefix that names one action alone (`rec` is `recurse`)
and keeps the last of `-r`, `-R` and `-d`: `-r -d read` does not recurse
and `-d read -r` does. rtk reads the same, so `grep -d recurse PAT` with
no operand prefixes each match with its file, as does a lone file
operand.
- grep's help flag is `--help` alone, since grep's `-h` is
`--no-filename`: `rtk grep -h -r needle dir` runs grep and prints the
matches without their file, as `grep -h -r needle dir` does, and
`rtk grep --help` prints grep's help. rg's `-h` is its help flag, so
`rtk rg -h` prints rg's help, as `rtk rg --help` does.
- rg's `-0` is `--null`, an output-shape flag: `rg -0 PAT` passes through
and prints rg's NUL-joined paths.
- `-V` is `--version` for grep and rg, and passes through to the engine as
`--version` does.
- Each engine's output-shape flags are its own: a shape flag of one engine
that the other lacks (`grep --json`, `rg --silent`) takes the grouping
route, where the engine rejects it with the same message and exit code.
- ast-grep's global and `run` grammars are tables of the options the
module already read: `-c`/`--config` alone ahead of a subcommand, and
every value-taking `run` option of 0.45.3 after `run`. `--debug-query`
takes its value attached only, and `-i`/`--interactive` is declared
beside `--stdin`, the two runs that reach the terminal live.
- dotnet's options are atomic flags carrying each option's names together
(`-c`/`--configuration`, `-l`/`--logger`), and maven's carry each short
and long name commons-cli pairs (`-pl`/`--projects`, `-D`/`--define`).
- ls declares every long option GNU ls's `--help` lists, booleans included, under
`Posix` with `UniquePrefix`: an abbreviation is only unambiguous against
the whole set. `ls --ign beta*` spans `--ignore` and `--ignore-backups`
and stays unread, for ls to reject. GNU's `-I`/`-T`/`-w` take a value and
BSD's do not, so each flavour has its own grammar over the shared long
table. `--numeric-uid-gid`, `-n`'s long spelling, and its abbreviations
print the long format as `-n` does: `rtk ls --numeric-uid-gid` keeps each
entry's mode and size.
The discover registry reads golangci-lint's global flags from the same table
(`golangci_cmd::GLOBAL_FLAGS_CLAIMING_DASH_DASH`), which lets a value take a literal
`--` as cobra does.
The arg_tokenizer section of the core README describes a grammar declared
once, as data, how the single-dash axis decides a flag's form, the
abbreviation axis, and how grammars share tables; the command-filter
checklist and the architecture guide point to it.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
9ee625c to
b1cb395
Compare
There was a problem hiding this comment.
🟢 Approval recommended
No active review issues remain for the declarative argument-grammar migration.
No open issues 🎉
What changed in this PR
Centralizes RTK’s per-tool argument rules in declarative Flag and Grammar tables, reducing duplicated parsing logic across command filters. This extracts the grammar portion of #4401 and builds on #3998’s golangci-lint discovery migration.
Changes:
- Migrates command handlers, discovery, and usage detection to declared grammars.
- Encodes tool-specific aliases and value rules, including search output flags and GNU ls abbreviations.
- Adds grammar-table tests and Git output regression coverage, and updates contributor documentation.
| File | Description |
|---|---|
tests/git_log_cap_notice_test.rs |
Updates coverage for native dirstat and line-log output and capped notes. |
tests/git_branch_format_test.rs |
Adds native-output comparisons for formatted branch listings. |
src/lib.rs |
Extends grep argument-forwarding coverage to clustered -hr. |
src/discover/registry.rs |
Uses golangci-lint’s shared global flag table for discovery. |
src/core/task_cmd.rs |
Declares task option grammar and its table test. |
src/core/runner.rs |
Moves usage-detection value rules into grammars. |
src/core/README.md |
Documents declarations, flag identity, abbreviations, and testing rules. |
src/core/arg_tokenizer/differential.rs |
Adapts frozen-oracle comparisons to the grammar API. |
src/cmds/system/search.rs |
Declares separate grep/rg grammars and refines flag classification. |
src/cmds/system/ls.rs |
Uses declarative abbreviation lookup and recognizes numeric long listings. |
src/cmds/system/ast_grep_cmd.rs |
Declares global/run grammars and tests option-value ownership. |
src/cmds/rust/cargo_cmd.rs |
Declares Cargo prefix options and expands routing tests. |
src/cmds/README.md |
Updates the new-filter checklist for declared grammars. |
src/cmds/python/ruff_cmd.rs |
Uses a global grammar for Ruff routing. |
src/cmds/python/pytest_cmd.rs |
Moves pytest value-taking options into a tested table. |
src/cmds/jvm/mvn_cmd.rs |
Declares Maven options using atomic flag names. |
src/cmds/go/golangci_cmd.rs |
Shares global/run tables and identifies output sinks by declaration. |
src/cmds/git/glab_cmd.rs |
Declares subcommand grammars for identifier extraction. |
src/cmds/git/gh_cmd.rs |
Declares subcommand grammars for identifier and action-target extraction. |
src/cmds/dotnet/dotnet_cmd.rs |
Migrates argument lookups to an atomic MSBuild grammar. |
docs/contributing/ARCHITECTURE.md |
Updates the argument-parsing documentation reference. |
Review effort: Balanced
|
@KuSh lgtm :) |
From PowerShell or cmd, `rtk ls *.txt` reached the child as the literal name `*.txt` (rtk-ai#4103 quotes it), so ls failed with `cannot access`. ls now expands its free positionals, as read with the host flavour's grammar from rtk-ai#5099, so a flag's value such as `-I '*.o'`, `--ignore '*.o'` or `--hide='*~'` still reaches ls as a pattern, and BSD's boolean `-I` leaves the next word an operand. The expansion runs once at the top of `run`, so the filtered listing and `native_listing` name the same files; the tracked command stays what the user typed. operand_glob gains `expand_at`, which expands the arguments at the indices a command's parser picked and keeps the rest; grep/rg now use it too.
From PowerShell or cmd, `rtk ls *.txt` reached the child as the literal name `*.txt` (rtk-ai#4103 quotes it), so ls failed with `cannot access`. ls now expands its free positionals, as read with the host flavour's grammar from rtk-ai#5099, so a flag's value such as `-I '*.o'`, `--ignore '*.o'` or `--hide='*~'` still reaches ls as a pattern, and BSD's boolean `-I` leaves the next word an operand. The expansion runs once at the top of `run`, so the filtered listing and `native_listing` name the same files; the tracked command stays what the user typed. operand_glob gains `expand_at`, which expands the arguments at the indices a command's parser picked and keeps the rest; grep/rg now use it too.
Moves the flags several handlers hand-coded into one declared table per tool. This is the first commit of #4401, which does not need the lexer work it was stacked on, so it can land on develop on its own; #4401 keeps its reserved-words commit.
golangci-lint's discover reading, which #3998 brought to develop, takes its global flags from this table.
Summary
Grammarincore/arg_tokenizer.rsisGrammar::new(dialect, tables): aDialectand the tool'sFlagtables, with how each spelling takes its value.tokenize_grammarreads arguments against it, and each token keeps the flag it matched, so handlers asktoken.is(&FLAG), or matchtoken.flag()against the flag consts when they branch on several (Some(&FORMAT | &PRETTY)).Flag::short/long/pair; an atomic one (MSBuild, commons-cli, Go'sflag) readsFlag::atomic(&["c", "configuration"]), one flag under every name it lists.Grammar::newrefuses any other combination, a compile error in theconst.Abbreviationaxis:UniquePrefixresolves a long flag typed as a prefix of exactly one declared spelling, as GNUgetopt_longdoes. Every preset staysNever.ls-treeincluded), golangci-lint, ast-grep, grep, rg, glab, gh, dotnet, maven, ls, ruff's global options,rtk task, pytest, cargo's options before its command and the usage-request check (git's message flags,cargo install --version) declare their grammars this way, each checked by a table test. Spellings and arities come from the tools' own help and man pages. ls declares every GNU long option underPosixwithUniquePrefix, so--sor timestill sorts by time.Flags rtk now reads as the tool does
-qis--quietunderlogandshowonly.git logprints git's own output, capped, for-L,--dd,-X/--dirstat,--dirstat-by-file,--cumulativeand the--stat-*parameters, as it already did for-p,--statand--dirstat.git showandgit diffprint git's own output for those,-zand--output-indicator-*.git stash show -uis--include-untracked.git branch -l PATTERNlists the matching branches.--formatlisting is printed as git wrote it.-his--no-filename, not help.-d recurserecurses.-rkeeps the filename prefix for a lone file operand, as BSD grep prints it; GNU grep 3.12 omits it (rtk grep -r PATTERN file prefixes the filename GNU grep omits for a lone file #5176).-0passes through.run: no option value is read as a path.--numeric-uid-gidand its abbreviations print the long format, as-ndoes.The commit message lists every rule with the tool behaviour it was checked against.
Test plan
cargo fmt --all --check,cargo clippy --all-targets(no warnings),cargo test --all --no-fail-faston this branch: 5799 passed, 0 failedmatch token.flag(); argument decisions compared on generated argv for every handler it touches, identicalmatch token.flag()arm fails a test when removedCargoCommand::parse) gives the same answer as before on a million generated argument lists, andrtk rewritethe same output on 7,500 cargo commands🤖 Generated with Claude Code