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
98 changes: 95 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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

this also makes a user's \A, \Z and \z anchors in BRE/ERE, but only with -z. is it wanted?
maybe only \z should be produced by the rewrite, without exposing the operator

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Only the rewrite produces \z now: a user's \A, \Z and \z stay plain letters outside -P, as in GNU. Tests added.

}
}

fn compile_with(
Expand Down Expand Up @@ -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'\\' => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

with -P, \Qa$\E becomes \Qa\z\E and then matches a literal a\z instead of a$.
could you please leave the content of \Q...\E untouched? with a test

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done: \Q...\E is copied untouched under -P, with tests (\Qa$\E, \Qa$b, \Qa\E$).

// 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};
Expand Down
73 changes: 73 additions & 0 deletions tests/test_grep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2764,3 +2764,76 @@ fn files_without_match_with_nothing_selectable() {
.stdout_is("trees.txt\n")
.stderr_contains("missing.txt: ");
}

#[test]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

missing empty line before #[test]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed.

fn null_data_anchors_are_record_anchors() {
// (options, pattern, record, whether the record matches)
let cases: &[(&[&str], &str, &str, bool)] = &[

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

two and one aren't in alpha\nbeta\n, so these 4 cases pass even without the fix.
please use one\ntwo as in the issue

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done: those cases use one\ntwo now and fail on main.

(&[], "^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);
}
Loading