From 074abcf54d1eff58776c2341c8528446dfbc325f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yunus=20Arda=20G=C3=BCney?= <64425746+yunusarda-sudo@users.noreply.github.com> Date: Sat, 5 Dec 2026 07:52:54 +0300 Subject: [PATCH] grep: treat anchors as whole-record delimiters under -z (fixes #195) Under -z a record ends at NUL and newline is ordinary data, so `^` and `$` anchor to the whole record. Rewrite anchor `$` to `\z` since Oniguruma's `$` also matches before a final newline. --- src/matcher.rs | 98 ++++++++++++++++++++++++++++++++++++++++++++-- tests/test_grep.rs | 73 ++++++++++++++++++++++++++++++++++ 2 files changed, 168 insertions(+), 3 deletions(-) diff --git a/src/matcher.rs b/src/matcher.rs index 42405a34..5bbd22fa 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,85 @@ fn find_bracket_subexpr_end(pattern: &[u8], start: usize, delimiter: u8) -> Opti .map(|i| i + 2) } +/// Under `-z`, GNU grep's `$` matches only at the very end of the record, but +/// Oniguruma's `$` also matches before a final newline. Rewrite anchor `$` to `\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 = Vec::with_capacity(pattern.len() + 8); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'\\' if mode == RegexMode::Perl && bytes.get(i + 1) == Some(&b'Q') => { + // `\Q...\E` is literal text: copy it untouched. + let end = pattern[i..].find("\\E").map_or(bytes.len(), |n| i + n + 2); + out.extend_from_slice(&bytes[i..end]); + i = end; + } + b'\\' => { + // Outside -P, `\A`, `\Z` and `\z` are plain letters; the `\z` operator + // is enabled only for the rewrite. + let next = bytes.get(i + 1); + if mode == RegexMode::Perl || !matches!(next, Some(b'A' | b'Z' | b'z')) { + out.push(b'\\'); + } + i += 1; + if i < bytes.len() { + out.push(bytes[i]); + i += 1; + } + } + b'[' => { + let end = bracket_end(bytes, i + 1, mode); + out.extend_from_slice(&bytes[i..end]); + i = end; + } + b'$' => { + let is_anchor = mode != RegexMode::Basic || { + let rest = &bytes[i + 1..]; + rest.is_empty() || rest.starts_with(b"\\)") || rest.starts_with(b"\\|") + }; + out.extend_from_slice(if is_anchor { b"\\z" } else { b"\\$" }); + i += 1; + } + b => { + out.push(b); + i += 1; + } + } + } + + // Only ASCII bytes were inserted or removed, so the result is still UTF-8. + String::from_utf8(out).unwrap_or_else(|_| pattern.to_string()) +} + +/// Index just past the `]` closing the bracket expression whose body starts at `start`. +fn bracket_end(pattern: &[u8], start: usize, mode: RegexMode) -> usize { + if mode != RegexMode::Perl { + return scan_bracket(pattern, start).1; + } + // PCRE: a backslash escapes the next byte, and a leading `]` is literal. + let mut i = start; + if pattern.get(i) == Some(&b'^') { + i += 1; + } + let body_start = i; + while i < pattern.len() { + match pattern[i] { + b']' if i != body_start => return i + 1, + b'\\' => i += 2, + b'[' if pattern.get(i + 1) == Some(&b':') => { + i = find_bracket_subexpr_end(pattern, i + 2, b':').unwrap_or(i + 1); + } + _ => i += 1, + } + } + pattern.len() +} + #[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 51334c5e..d8ae24b2 100644 --- a/tests/test_grep.rs +++ b/tests/test_grep.rs @@ -2764,3 +2764,76 @@ fn files_without_match_with_nothing_selectable() { .stdout_is("trees.txt\n") .stderr_contains("missing.txt: "); } + +#[test] +fn null_data_anchors_are_record_anchors() { + // (options, pattern, record, whether the record matches) + let cases: &[(&[&str], &str, &str, bool)] = &[ + (&[], "^two", "one\ntwo\n", false), + (&[], "one$", "one\ntwo\n", false), + (&["-E"], "one$", "one\ntwo\n", false), + (&["-P"], "one$", "one\ntwo\n", false), + (&[], "^beta", "alpha\nbeta\n", false), + (&["-E"], "alpha$", "alpha\nbeta\n", false), + (&[], "beta$", "alpha\nbeta\n", false), + (&["-E"], "beta$", "alpha\nbeta\n", false), + (&["-P"], "beta$", "alpha\nbeta\n", false), + (&[], "^alpha", "alpha\nbeta", true), + (&["-E"], "^alpha", "alpha\nbeta", true), + (&["-P"], "^alpha", "alpha\nbeta", true), + (&[], "beta$", "alpha\nbeta", true), + (&["-E"], "beta$", "alpha\nbeta", true), + (&["-P"], "beta$", "alpha\nbeta", true), + // A newline in the record is ordinary data. + (&[], "\n$", "alpha\nbeta\n", true), + // Escaped and bracketed dollars stay literal. + (&[], r"foo\$bar", "foo$bar", true), + (&[], "foo[$]bar", "foo$bar", true), + (&[], "[^$]", "x", true), + (&[], "[]$]", "$", true), + (&["-E"], "[[:alpha:]$]", "$", true), + (&["-P"], r"[\]$]", "$", true), + (&["-P"], r"[\]$]", "]", true), + (&["-P"], "[^$]", "x", true), + (&["-P"], "[[:alpha:]$]", "$", true), + (&["-F"], "foo$", "foo$", true), + // In BRE, `$` is an anchor only at the end or before `\)` or `\|`. + (&[], "foo$bar", "foo$bar", true), + (&[], r"\(beta$\)", "alpha\nbeta", true), + (&[], r"foo$\|bar", "foo", true), + // `\Q...\E` is literal text, `$` included. + (&["-P"], r"\Qa$\E", "a$", true), + (&["-P"], r"\Qa$\E", "a", false), + (&["-P"], r"\Qa$b", "a$b", true), + (&["-P"], r"\Qa\E$", "a", true), + (&["-P"], r"\Qa\E$", "a\n", false), + // The pattern is not ASCII-only. + (&[], "café$", "café", true), + (&["-E"], "café$", "café\n", false), + (&["-P"], "café$", "café", true), + // `\A`, `\Z` and `\z` are plain letters outside -P, as in GNU grep. + (&[], r"a\z", "az", true), + (&["-E"], r"a\Z", "aZ", true), + (&[], r"\A", "ab", false), + (&["-P"], r"a\z", "xa", true), + ]; + for (options, pattern, record, matches) in cases { + let (_s, mut c) = ucmd(); + c.args(&["-z", "-c"]) + .args(options) + .arg(pattern) + .pipe_in(format!("{record}\0")); + if *matches { + c.succeeds().stdout_only("1\n"); + } else { + c.fails_with_code(1).stdout_only("0\n"); + } + } + + // Trailing backslash and unclosed PCRE bracket are errors. + let (_s, mut c) = ucmd(); + c.args(&["-z", "-c", "foo\\"]).fails_with_code(2); + + let (_s, mut c) = ucmd(); + c.args(&["-z", "-P", "[abc$"]).fails_with_code(2); +}