Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions src/matcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,16 @@ struct CompiledPattern {
longest_anchored: OnigRegex,
}

fn enable_syntax_behavior(syntax: &mut Syntax, behavior: SyntaxBehavior) {
let raw_ptr = syntax as *mut Syntax as *mut onig_sys::OnigSyntaxType;
let mut current_bits = unsafe { onig_sys::onig_get_syntax_behavior(raw_ptr) };
// GNU grep rejects empty ranges like [b-a] with "Invalid range end", while
// OnigSyntaxGrep enables ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC by default.
current_bits &= !onig_sys::ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC;
let new_bits = current_bits | (behavior.bits() as std::os::raw::c_uint);
syntax.set_behavior(SyntaxBehavior::from_bits_retain(new_bits as u32));
}

impl CompiledPattern {
fn compile(pattern: &str, config: &Config) -> UResult<Self> {
let mut syntax = *match config.regex_mode {
Expand All @@ -306,15 +316,21 @@ impl CompiledPattern {
};
if config.regex_mode != RegexMode::Fixed {
// GNU grep supports `{,n}` as an alias for `{0,n}`.
syntax.enable_behavior(SyntaxBehavior::SYNTAX_BEHAVIOR_ALLOW_INTERVAL_LOW_ABBREV);
enable_syntax_behavior(
&mut syntax,
SyntaxBehavior::SYNTAX_BEHAVIOR_ALLOW_INTERVAL_LOW_ABBREV,
);
}
if matches!(config.regex_mode, RegexMode::Basic | RegexMode::Extended) {
// GNU grep supports \` and \' as buffer anchors in BRE and ERE.
syntax.enable_operators(SyntaxOperator::SYNTAX_OPERATOR_ESC_GNU_BUF_ANCHOR);
}
if config.regex_mode == RegexMode::Extended {
// GNU grep -E reads an unmatched `)` as a literal.
syntax.enable_behavior(SyntaxBehavior::SYNTAX_BEHAVIOR_ALLOW_UNMATCHED_CLOSE_SUBEXP);
enable_syntax_behavior(
&mut syntax,
SyntaxBehavior::SYNTAX_BEHAVIOR_ALLOW_UNMATCHED_CLOSE_SUBEXP,
);
}

if matches!(config.regex_mode, RegexMode::Basic | RegexMode::Extended)
Expand Down
22 changes: 22 additions & 0 deletions tests/test_grep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2697,3 +2697,25 @@ fn diagnostics_follow_earlier_output() {
"a.txt:foo a\ngrep: bin.dat: binary file matches\ngrep: missing.txt: No such file or directory\nb.txt:foo b\n"
);
}

#[test]
fn bre_anchors_are_literal_away_from_the_edges() {
let (_s, mut c) = ucmd();
c.args(&["a$b"])
.pipe_in("a$b\nab\n")
.succeeds()
.stdout_only("a$b\n");

let (_s, mut c) = ucmd();
c.args(&["x^2"])
.pipe_in("x^2\nx2\n")
.succeeds()
.stdout_only("x^2\n");

// Still anchors at the edges of the pattern and of a group.
let (_s, mut c) = ucmd();
c.args(&["^a\\(b$\\)"])
.pipe_in("ab\nxab\nabc\n")
.succeeds()
.stdout_only("ab\n");
}
Loading