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
106 changes: 103 additions & 3 deletions src/matcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<name>...)`.
// Unfortunately, the onig crate defines the OP2 flag without the
Expand All @@ -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(
Expand Down Expand Up @@ -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};
Expand Down
55 changes: 55 additions & 0 deletions tests/test_grep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
Loading