From d8903dd2806cd7a828528c088784bba318a58f8e Mon Sep 17 00:00:00 2001 From: Yunus Ardaguney Date: Thu, 26 Nov 2026 02:47:35 +0300 Subject: [PATCH] grep: treat anchors as whole-record delimiters under -z (fixes #195) --- src/matcher.rs | 106 +++++++++++++++++++++++++++++++++++++++++++-- tests/test_grep.rs | 55 +++++++++++++++++++++++ 2 files changed, 158 insertions(+), 3 deletions(-) diff --git a/src/matcher.rs b/src/matcher.rs index 42405a3..989ec40 100644 --- a/src/matcher.rs +++ b/src/matcher.rs @@ -344,6 +344,13 @@ impl CompiledPattern { pattern }; + let null_data_normalized = if config.null_data { + Some(normalize_null_data_dollar(pattern, config.regex_mode)) + } else { + None + }; + let pattern = null_data_normalized.as_deref().unwrap_or(pattern); + if config.regex_mode == RegexMode::Perl { // GNU grep supports `(?P...)`. // Unfortunately, the onig crate defines the OP2 flag without the @@ -364,9 +371,15 @@ impl CompiledPattern { // for `.` and negated bracket expressions `[^...]`, but PCRE keeps its // existing non-DOTALL behavior. The GNU `pcre-context` test documents // this as current behavior until PCRE2. - if config.null_data && matches!(config.regex_mode, RegexMode::Basic | RegexMode::Extended) { - options |= RegexOptions::REGEX_OPTION_MULTILINE; - syntax.disable_behavior(SyntaxBehavior::SYNTAX_BEHAVIOR_NOT_NEWLINE_IN_NEGATIVE_CC); + if config.null_data { + options |= RegexOptions::REGEX_OPTION_SINGLELINE; + if matches!(config.regex_mode, RegexMode::Basic | RegexMode::Extended) { + options |= RegexOptions::REGEX_OPTION_MULTILINE; + syntax.disable_behavior(SyntaxBehavior::SYNTAX_BEHAVIOR_NOT_NEWLINE_IN_NEGATIVE_CC); + } + if config.regex_mode != RegexMode::Fixed { + syntax.enable_operators(SyntaxOperator::SYNTAX_OPERATOR_ESC_AZ_BUF_ANCHOR); + } } fn compile_with( @@ -698,6 +711,93 @@ fn find_bracket_subexpr_end(pattern: &[u8], start: usize, delimiter: u8) -> Opti .map(|i| i + 2) } +/// In `-z / --null-data` mode, a record ends at NUL (`\0`) and newline is ordinary data. +/// Oniguruma's `SINGLELINE` option maps `$` to `ANCR_SEMI_END_BUF`, which matches before +/// a trailing newline at the end of the buffer. In GNU grep, `$` under `-z` anchors strictly +/// to the end of the buffer (`\z` / `ANCR_END_BUF`). +/// +/// This helper replaces anchor `$` outside bracket expressions with `\z`. +fn normalize_null_data_dollar(pattern: &str, mode: RegexMode) -> String { + if mode == RegexMode::Fixed || !pattern.contains('$') { + return pattern.to_string(); + } + + let bytes = pattern.as_bytes(); + let mut out = String::with_capacity(pattern.len() + 8); + let mut i = 0; + let mut in_bracket = false; + let mut bracket_first = false; + + while i < bytes.len() { + let b = bytes[i]; + if in_bracket { + out.push(b as char); + if bracket_first { + bracket_first = false; + } else if b == b']' { + in_bracket = false; + } + i += 1; + continue; + } + + if b == b'\\' { + out.push('\\'); + if i + 1 < bytes.len() { + out.push(bytes[i + 1] as char); + i += 2; + } else { + i += 1; + } + continue; + } + + if b == b'[' { + in_bracket = true; + bracket_first = true; + out.push('['); + if i + 1 < bytes.len() && bytes[i + 1] == b'^' { + out.push('^'); + i += 2; + } else { + i += 1; + } + // In POSIX brackets, if the first character after `[` or `[^` is `]`, + // it is literal `]`, not the closing bracket. + if i < bytes.len() && bytes[i] == b']' { + out.push(']'); + i += 1; + bracket_first = false; + } + continue; + } + + if b == b'$' { + let is_anchor = match mode { + RegexMode::Perl | RegexMode::Extended => true, + RegexMode::Basic => { + let rest = &bytes[i + 1..]; + rest.is_empty() || rest.starts_with(b"\\)") || rest.starts_with(b"\\|") + } + RegexMode::Fixed => false, + }; + + if is_anchor { + out.push_str(r"\z"); + } else { + out.push('$'); + } + i += 1; + continue; + } + + out.push(b as char); + i += 1; + } + + out +} + #[cfg(test)] mod tests { use super::{has_confusing_bracket, plain_literal, utf8_char_step}; diff --git a/tests/test_grep.rs b/tests/test_grep.rs index e2cbbeb..33081ce 100644 --- a/tests/test_grep.rs +++ b/tests/test_grep.rs @@ -2697,3 +2697,58 @@ 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 null_data_anchors_are_record_anchors() { + for args in [ + &["-z", "-c", "^two"][..], + &["-z", "-c", "one$"][..], + &["-z", "-c", "-E", "one$"][..], + &["-z", "-c", "-P", "one$"][..], + &["-z", "-c", "^beta"][..], + &["-z", "-c", "-E", "alpha$"][..], + &["-z", "-c", "beta$"][..], + &["-z", "-c", "-E", "beta$"][..], + &["-z", "-c", "-P", "beta$"][..], + ] { + let (_s, mut c) = ucmd(); + c.args(args) + .pipe_in("alpha\nbeta\n\0") + .fails_with_code(1) + .stdout_only("0\n"); + } + + for args in [ + &["-z", "-c", "^alpha"][..], + &["-z", "-c", "-E", "^alpha"][..], + &["-z", "-c", "-P", "^alpha"][..], + &["-z", "-c", "beta$"][..], + &["-z", "-c", "-E", "beta$"][..], + &["-z", "-c", "-P", "beta$"][..], + ] { + let (_s, mut c) = ucmd(); + c.args(args) + .pipe_in("alpha\nbeta\0") + .succeeds() + .stdout_only("1\n"); + } + + // Record with trailing newline matches newline before anchor + let (_s, mut c) = ucmd(); + c.args(&["-z", "-c", "\n$"]) + .pipe_in("alpha\nbeta\n\0") + .succeeds() + .stdout_only("1\n"); + + // Escaped and bracketed dollar remains literal + let (_s, mut c) = ucmd(); + c.args(&["-z", "-c", "foo\\$bar"]) + .pipe_in("foo$bar\0") + .succeeds() + .stdout_only("1\n"); + + let (_s, mut c) = ucmd(); + c.args(&["-z", "-c", "foo[$]bar"]) + .pipe_in("foo$bar\0") + .succeeds() + .stdout_only("1\n"); +}