Skip to content

fix(grep): translate BRE and preserve rg dialects through rtk grep - #2138

Closed
F0rty-Tw0 wants to merge 1 commit into
rtk-ai:developfrom
F0rty-Tw0:fix/1436/grep-bre-translation
Closed

F0rty-Tw0 wants to merge 1 commit into
rtk-ai:developfrom
F0rty-Tw0:fix/1436/grep-bre-translation

Conversation

@F0rty-Tw0

@F0rty-Tw0 F0rty-Tw0 commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

This PR translates grep's BRE into rg's dialect so rtk could keep running rg underneath and still match what grep matches.

That's not the direction the project took. #2641 (merged) fixes #1436 by running the engine the user actually typed: grep runs grep, rg runs rg, no substitution, no translation. It deletes the exact machinery this PR adds and renames grep_cmd.rs to search.rs, so a rebase would only re-add the code that PR removed.

Closing as superseded.

On #1436 itself:

@KuSh KuSh left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your PR.

I didn't go through all of it but it seems way too complicated and trying to solve non-existent problems (at least from a rtk's point of view).

Can you come back with a second simpler proposal, taking into account what I have already commented on? It seems to be a good addition, just far too complex for now.

Comment thread src/cmds/system/grep_cmd.rs Resolved
Comment thread src/cmds/system/grep_cmd.rs Resolved
Comment thread src/cmds/system/grep_cmd.rs Resolved
Comment thread src/cmds/system/grep_cmd.rs Resolved
Comment thread src/cmds/system/grep_cmd.rs Resolved
Comment thread src/cmds/system/grep_cmd.rs Resolved
Comment thread src/cmds/system/grep_cmd.rs Resolved
@F0rty-Tw0

F0rty-Tw0 commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor Author

@KuSh Thanks for wading through all of it, and fair call.

I had an AI assistant help me review this, and it did the thing they're best at, it found a problem that wasn't really there and then heroically solved it five separate ways. It saw one escaped \| in the issue and concluded the only sane fix was to reimplement POSIX regex semantics from scratch, complete with Windows-without-grep fallbacks for a bug that happened on Linux. I should have pushed back instead of nodding along. That part's on me.

Ill cut it down to:

  • Drop the grep-binary fallback. If someone runs rg and it isn't there, let it fail. rtk shouldn't be in the business of papering over a broken setup.
  • Swap bre_to_rg for your bre_to_pcre. Cleaner, and it passes the same tests, so thank you.
  • Remove reorder_grep_args, the cluster stripping, and the file-type glob mapping.
  • Rename GrepMode to RegexSyntax and have detection return Option<RegexSyntax>.
  • Handle the rg … → rtk grep -P case at the rewrite layer instead, separately from this.

Small course-correction on the rewrite-layer point. I'd planned to do rg → rtk grep -P as a separate PR. But once I tested it, leaving it out means this PR fixes grep and silently breaks rg: the hook rewrites both to rtk grep, so an rg pattern gets BRE-translated and mangled. A known regression behind a "next PR" didn't sit right, so I folded the one-line tag in. grep keeps BRE, rg gets -P. Happy to split it back out if you'd rather review them apart.

@F0rty-Tw0
F0rty-Tw0 force-pushed the fix/1436/grep-bre-translation branch from 4d6bf88 to fa3cc69 Compare June 1, 2026 22:17
@F0rty-Tw0 F0rty-Tw0 changed the title fix(grep): route per regex dialect to preserve POSIX BRE semantics fix(grep): translate BRE to ripgrep regex to preserve POSIX semantics Jun 1, 2026
@F0rty-Tw0
F0rty-Tw0 force-pushed the fix/1436/grep-bre-translation branch 2 times, most recently from b0cc478 to bdf083b Compare June 1, 2026 23:04
@F0rty-Tw0 F0rty-Tw0 changed the title fix(grep): translate BRE to ripgrep regex to preserve POSIX semantics fix(grep): preserve grep BRE and rg dialects through rtk grep Jun 1, 2026
@F0rty-Tw0

Copy link
Copy Markdown
Contributor Author

@KuSh Two deviations from your suggestions

  • Kept the rg→grep fallback. Dropping it made rtk grep return empty in CI without ripgrep, and the hook rewrites plain grep too. Only the 4-line fallback remains; the heavy grep machinery is gone.
  • -E not -P for the rg tag. Bare rg uses its default engine, not PCRE2, so -E is faithful where -P would switch engines. Verified against real rg and grep.

@F0rty-Tw0
F0rty-Tw0 requested a review from KuSh June 3, 2026 19:25
Comment thread src/discover/registry.rs Resolved
Comment thread src/cmds/system/grep_cmd.rs Resolved
Comment thread src/cmds/system/grep_cmd.rs Resolved
Comment thread src/cmds/system/grep_cmd.rs Resolved
Comment thread src/cmds/system/grep_cmd.rs Resolved
Comment thread src/cmds/system/grep_cmd.rs Resolved
F0rty-Tw0 added a commit to F0rty-Tw0/rtk that referenced this pull request Jun 9, 2026
… clusters

Per review on rtk-ai#2138:

- Split the combined rg|grep rewrite rule in rules.rs: `rg` maps to
  `rtk grep -E`, `grep` to `rtk grep`. Drops the custom tag logic in
  rewrite_segment_inner; a dialect flag later in the command still wins
  (grep applies the LAST dialect flag).
- Add -E/-G/-P/-F as real clap flags on `rtk grep` so the leading -E
  produced by the rule parses into the filtered path instead of
  triggering the raw-command fallback.
- Explicit -G/--basic-regexp now runs native grep directly: the user
  asked for grep's BRE engine, so no rg and no translation.
- Extract rg_forward_args(): the strip list now handles short clusters
  (`-rn` -> `-n`, `-iE` -> `-i`, `-rE` dropped) so rg never sees a
  stray -r (--replace in rg) or dialect char; tokens after `--` pass
  through untouched.
- Restore the removed test cases: BRE alternation reproducer and
  -r/--recursive stripping, now against the real functions.

@KuSh KuSh left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for changes, unfortunately change in src/main.rs will conflict with other grep planned fixes and doesn't seem necessary.

Comment thread src/cmds/system/grep_cmd.rs Outdated
Comment on lines +606 to +608
fn args(list: &[&str]) -> Vec<String> {
list.iter().map(|s| s.to_string()).collect()
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick, you can make rg_forward_args accepts &[impl AsRef<str>] and avoid such boilerplate

then your tests simplifies to

    #[test]
    fn test_rg_forward_args_strips_recursive() {
        // rg is recursive by default and re-purposes -r as --replace.
        assert_eq!(rg_forward_args(&["-r", "-i"]), vec!["-i"]);
        assert_eq!(rg_forward_args(&["--recursive"]), Vec::<String>::new());
    }

Comment thread src/main.rs Outdated
Comment on lines +325 to +336
/// Pattern is an extended regexp (grep -E / rg's native dialect)
#[arg(short = 'E', long)]
extended_regexp: bool,
/// Pattern is a basic regexp (grep -G); runs native grep
#[arg(short = 'G', long)]
basic_regexp: bool,
/// Pattern is a Perl-compatible regexp (grep -P)
#[arg(short = 'P', long)]
perl_regexp: bool,
/// Pattern is a fixed string, not a regexp (grep -F)
#[arg(short = 'F', long)]
fixed_strings: bool,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That should be avoided as clap with eat the args and mess with them. I've pushed a PR that go the opposite and removes most grep args handlings from clap.

I don't see why this is needed, if extra_args contains everything this should work without specific handling. Or am I missing something?

@KuSh

KuSh commented Jun 14, 2026

Copy link
Copy Markdown
Collaborator

Okay, I've iterated a lot on grep handling through #2333. You'll have to rebase once merged, here's a full detailed test suite you'll have to take into account to be sure nothing is left unhandled:

bre_to_pcre() — unit tests on the translation function

The core obligation: BRE literals that are PCRE metacharacters must be escaped, and BRE escapes that mean "special" must be unescaped.

// Literals in BRE that are special in PCRE → must be escaped
"delete()"      → "delete\(\)"     // parens: literal in BRE, group in PCRE
"a+b"           → "a\+b"           // + is literal in BRE
"a?b"           → "a\?b"           // ? is literal in BRE
"foo|bar"       → "foo\|bar"       // | is literal in BRE
"a{2}"          → "a\{2\}"         // braces are literal in BRE
"a{2,3}"        → "a\{2,3\}"

// BRE escapes that mean PCRE special → must be unescaped
"\(group\)"     → "(group)"        // BRE grouping → PCRE group
"a\{2\}"        → "a{2}"           // BRE repetition → PCRE repetition
"foo\|bar"      → "foo|bar"        // GNU BRE alternation → PCRE alternation
"a\+"           → "a+"             // GNU BRE one-or-more → PCRE
"a\?"           → "a?"             // GNU BRE optional → PCRE

// Passthrough: same meaning in BRE and PCRE
".*"            → ".*"
"^foo$"         → "^foo$"
"[a-z]"         → "[a-z]"
"\."            → "\."             // escaped dot = literal in both
"foo\nbar"      → "foo\nbar"       // \n is not a BRE metachar

// Composed
"fn delete(.*)"  → "fn delete\(.*\)"

detect_syntax() — unit tests on flag scanning

Input: the flags vec from extract_pattern_path. The function returns the detected dialect.

// Defaults
[]                          → BRE
["-i", "-n"]                → BRE     // no dialect flag

// Long forms
["--extended-regexp"]       → ERE
["--basic-regexp"]          → BRE
["--perl-regexp"]           → PCRE
["--fixed-strings"]         → Fixed

// Short forms (these land in flags as boolean, since -E not in VALUE_FLAGS_SHORT)
["-E"]                      → ERE
["-G"]                      → BRE
["-P"]                      → PCRE
["-F"]                      → Fixed

// Last wins
["-E", "-G"]                → BRE
["-G", "-E"]                → ERE
["-E", "-P"]                → PCRE
["-P", "-F"]                → Fixed

// Stop at "--" (flags never contain "--" after extract_pattern_path, but defensive)
["-E", "--", "-G"]          → ERE   // stops at "--"

// Short cluster: "-nE" → extract_pattern_path emits "-nE" since E is not in
// VALUE_FLAGS_SHORT and n is boolean → both end up in bool_acc → flag "-nE"
// detect_syntax must scan individual chars within a short cluster
["-nE"]                     → ERE
["-inP"]                    → PCRE

// Interleaved with other flags
["-i", "--glob", "*.rs", "-E", "-A", "2"]  → ERE

Important interaction with the current branch: extract_pattern_path does NOT consume -E as value-taking (intentionally left out of VALUE_FLAGS_SHORT). So -E appears in flags as-is. detect_syntax receives it correctly for standalone use. For the cluster case (-nE), the left-to-right scan hits E — since E is NOT in VALUE_FLAGS_SHORT, it gets accumulated into bool_acc alongside n, producing the flag -nE. detect_syntax must handle this by checking each char of short flag clusters, not just exact string matches.


Dialect flag stripping — flags forwarded to rg

After detect_syntax, the dialect flags must be removed from extra_args before rg invocation. None of them are safe to forward raw:

Flag Why it must be stripped
-E rg treats it as --encoding (value-taking) — next arg consumed as encoding name
-G rg has no -G, would error
--basic-regexp rg has no --basic-regexp
--extended-regexp rg has no --extended-regexp
-P rg has no -P; use --pcre2 instead
--perl-regexp rg has no --perl-regexp
-F rg DOES have -F, safe to forward — but strip-and-re-add is cleaner for consistency
--fixed-strings rg has --fixed-strings, safe to forward
// rg invocation — per dialect
BRE  "delete()" src  →  rg ... -e 'delete\(\)' -- src    // translated, no dialect flag
ERE  -E 'foo(bar)+' src → rg ... -e 'foo(bar)+' -- src   // NOT translated, -E stripped
PCRE -P 'foo\d+' src    → rg ... --pcre2 -e 'foo\d+' -- src  // -P stripped, --pcre2 added
Fixed -F 'foo.bar' src  → rg ... -F -e 'foo.bar' -- src  // -F stripped then re-added as -F

grep fallback dialect

The grep fallback gets original (untranslated) patterns plus grep-compatible flags:

// grep receives the dialect flag because grep understands it
// grep does NOT receive --pcre2 (it doesn't know that)
BRE  "delete()" src  →  grep -e 'delete()' -rnHZ -- src   // no translation for grep
ERE  -E 'foo' src    →  grep -E -e 'foo' -rnHZ -- src     // -E is valid grep flag
PCRE -P 'foo' src    →  grep -P -e 'foo' -rnHZ -- src     // grep may support -P (PCRE)
Fixed -F 'foo' src   →  grep -F -e 'foo' -rnHZ -- src

-E parsing conflict

This is the hardest interaction. Currently rtk grep -E utf8 PATTERN src produces:

  • extract_pattern_path sees: -E (bool flag → flags), utf8 (positional → pattern!), PATTERN (positional → path), src (positional → path)
  • Result: patterns=["utf8"], paths=["PATTERN", "src"] ← wrong

#2138 must fix this. The canonical approach: a pre-pass that strips dialect flags from the raw arg list before extract_pattern_path runs.

// After pre-pass strips -E:
// raw: ["-E", "utf8", "PATTERN", "src"]
// → #2138 detects -E, removes it
// → extract_pattern_path sees: ["utf8", "PATTERN", "src"]  ← still wrong if utf8 is encoding value

// This only works cleanly if #2138 knows -E takes NO positional value in grep context
// (grep's -E is boolean; rg's --encoding takes a value — they're different flags)

Concrete tests #2138 must pass:
// -E is boolean in grep, so no value consumed
"-E" "'foo(bar)+'" "src"  → patterns=["foo(bar)+"], paths=["src"], dialect=ERE

// -P is boolean in grep
"-P" "'\d+'" "src"        → patterns=["\d+"], paths=["src"], dialect=PCRE

// -F is boolean in grep
"-F" "'foo.bar'" "src"    → patterns=["foo.bar"], paths=["src"], dialect=Fixed

// mixed cluster with E at the end
"-inE" "'foo'" "src"      → patterns=["foo"], paths=["src"], flags=["-in"], dialect=ERE

rg-origin rewrite (discover/registry.rs)

When the hook converts rg 'pat' → rtk grep 'pat', patterns that were already PCRE must not go through BRE translation. The fix is appending -E to the rewritten command.

rg 'foo(bar)+'         → rtk grep 'foo(bar)+' -E      // -E preserves PCRE semantics
rg -e 'foo(bar)+'      → rtk grep -e 'foo(bar)+' -E
rg -e 'foo' -e 'bar'   → rtk grep -e 'foo' -e 'bar' -E
rg 'foo\|bar'          → rtk grep 'foo\|bar' -E        // even BRE-looking patterns get -E since source is rg

// End-to-end: the -E survives to detect_syntax and suppresses BRE translation
extract_pattern_path(["-E", "foo(bar)+", "src"])  // after pre-pass removes -E
→ detect_syntax returns ERE
→ rg receives -e 'foo(bar)+' (no translation)  ✓

Multiple patterns

// Each pattern translated independently
"-e" "delete()" "-e" "foo\|bar" "src"
→ BRE → rg: -e 'delete\(\)' -e 'foo|bar' -- src

// ERE: no translation
"-E" "-e" "foo(bar)+" "-e" "baz" "src"
→ ERE → rg: -e 'foo(bar)+' -e 'baz' -- src

// --regexp (long form of -e) treated identically
"--regexp" "delete()" "src"
→ BRE → rg: -e 'delete\(\)' -- src

@F0rty-Tw0

Copy link
Copy Markdown
Contributor Author

Hey @KuSh, sorry for the long silence. Changed jobs and got buried, this one also turned out trickier than the few-line fix I thought it was, so it kept sliding.

Caught up now. I see #2333 landed and pulls grep handling out of Clap, which is the right call and the opposite of where I'd gone with the dialect flags. I'll rebase onto it, drop the Clap-flag approach, and re-seat detection on top of extract_pattern_path (incl. the pre-pass for the -E-eats-the-positional case and the -nE cluster scan). The test suite you wrote out is exactly what I needed, thanks for taking the time, I'll make all of it pass.

Back on track, will push the rebased version shortly.

@F0rty-Tw0

Copy link
Copy Markdown
Contributor Author

pushed!

quick thing before i wrap this up: the -G routing. first round you asked for Basic to skip straight to native grep, so hat's what i've got. explicit -G/--basic-regexp runs grep directly, no rg, no translation.

the new strip-table puts -G under "strip before rg" though, which reads like you'd rather it go through rg now (stripped, pattern BRE-translated) than hit native grep. which did you mean? either works, one-liner to switch.

@F0rty-Tw0
F0rty-Tw0 force-pushed the fix/1436/grep-bre-translation branch from 115e4ed to fecfde6 Compare June 14, 2026 20:24
@F0rty-Tw0
F0rty-Tw0 requested a review from KuSh June 14, 2026 20:24
@F0rty-Tw0 F0rty-Tw0 changed the title fix(grep): preserve grep BRE and rg dialects through rtk grep fix(grep): translate BRE and preserve rg dialects through rtk grep Jun 14, 2026
@KuSh

KuSh commented Jun 14, 2026

Copy link
Copy Markdown
Collaborator

the new strip-table puts -G under "strip before rg" though, which reads like you'd rather it go through rg now (stripped, pattern BRE-translated) than hit native grep. which did you mean? either works, one-liner to switch.

Yeah, Claude has gone way over its head here, dialect flags should select the correct binary as we have discussed before, this way it will never hit rg and use grep as first intended by the caller. So keep tests as it was before: if a dialect IS requested direct to the correct binary, if none is requested we can use rg (and translate if necessary)

Comment thread src/cmds/system/grep_cmd.rs Resolved
Comment thread src/cmds/system/grep_cmd.rs Resolved
Comment thread src/cmds/system/grep_cmd.rs Resolved
@KuSh KuSh self-assigned this Jun 14, 2026
F0rty-Tw0 added a commit to F0rty-Tw0/rtk that referenced this pull request Jun 19, 2026
…-ai#2138)

Explicit -E/-G/-P/-F now run native grep directly (grep applies the
dialect itself); only the no-dialect default goes through rg with BRE
translation. Removes rg_forward_args and the rg engine-selection block.

- Add has_rg_engine_flag: --engine/--auto-hybrid-regex force the rg path
  and skip translation, fixing --engine=pcre2 patterns being BRE-escaped.
- rg-origin rewrite marker changes from -E to --engine=auto so rg patterns
  keep \d/\w/\b instead of being routed to grep -E.
- Rename strip_r -> strip_short_args, strip_recursive -> strip_long_args.
@F0rty-Tw0

Copy link
Copy Markdown
Contributor Author

All four dialects now route to native grep; only the no-dialect default hits rg + translation. Deleted rg_forward_args and the engine-select block (~-65 lines).

One deviation: rg-origin marker is --engine=auto, not -E. -E would send rg patterns to grep -E and drop \d/\w/\b. One-line revert if you disagree.

…rtk-ai#2138)

Plain grep (BRE default) translates to rg's dialect (issue rtk-ai#1436); an
explicit grep dialect flag (-E/-G/-P/-F) routes to native grep, which
applies it directly. Only the no-dialect default goes through rg.

- detect_syntax + bre_to_pcre: BRE literals like `delete()` match
  literally instead of as an empty regex group.
- has_rg_engine_flag: --engine/--auto-hybrid-regex force the rg path and
  skip translation; rg-origin hook rewrites use --engine=auto.
- strip_short_args/strip_long_args drop -r/--recursive during the split.
@KuSh

KuSh commented Jun 27, 2026

Copy link
Copy Markdown
Collaborator

Hi @F0rty-Tw0 sorry for the delay, could you please rebase and resolve conflicts?

@KuSh

KuSh commented Jun 27, 2026

Copy link
Copy Markdown
Collaborator

Thanks for working on this! I just wanted to let you know that @aeppling merged a refactor (#2641) in this area that actually addresses the grep-to-rg translation piece. So it looks like we might not need this PR anymore.

@F0rty-Tw0

Copy link
Copy Markdown
Contributor Author

Hi @KuSh, thanks for the confirmation. I also was extremely busy with other stuff and couldn't focus on this one and push it till the end.

Thanks @aeppling for making it happen. You can close this pr if you find it necessary, and nothing else can benefit to the original issue.

Happy to help you on other windows/.net related issues.

@F0rty-Tw0

Copy link
Copy Markdown
Contributor Author

Closing this one. #2641 took #1436 the other way, running the invoked engine instead of substituting rg for grep, and that's the better call. The translation approach here doesn't have a place anymore, and rebasing would just bring back the code that PR removed.

Where I think #1436 stands:

I haven't reproduced the original case against current develop, so I'm not closing the issue myself. If someone runs that repro and it comes back clean, #1436 can close. Nothing on this branch is worth salvaging.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

The rtk grep is not grep-compatible

2 participants