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
250 changes: 249 additions & 1 deletion src/matcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use onig::{RegexOptions, Region, SearchOptions, Syntax, SyntaxBehavior, SyntaxOp
use onig_sys::{
ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS, OnigEncCtype_ONIGENC_CTYPE_WORD, OnigEncodingUTF8,
};
use std::borrow::Cow;
use std::ptr::{null, null_mut};
use std::sync::Mutex;
use uucore::error::{UResult, USimpleError};
Expand Down Expand Up @@ -326,6 +327,17 @@ impl CompiledPattern {
));
}

let collating_rewritten =
if matches!(config.regex_mode, RegexMode::Basic | RegexMode::Extended) {
match rewrite_collating_symbols(pattern)? {
Cow::Owned(s) => Some(s),
Cow::Borrowed(_) => None,
}
} else {
None
};
let pattern = collating_rewritten.as_deref().unwrap_or(pattern);

if config.regex_mode == RegexMode::Extended && has_empty_interval(pattern.as_bytes()) {
return Err(USimpleError::new(
2,
Expand Down Expand Up @@ -698,10 +710,246 @@ fn find_bracket_subexpr_end(pattern: &[u8], start: usize, delimiter: u8) -> Opti
.map(|i| i + 2)
}

/// Rewrite POSIX collating symbols `[.c.]` in bracket expressions for Basic
/// and Extended regular expressions. In the C locale, a single-character symbol
/// stands for that character. Multi-character symbols are rejected with
/// "Invalid collation character", and unclosed `[.` within brackets is rejected
/// with "Unmatched [, [^, [:, [., or [=".
fn rewrite_collating_symbols(pattern: &str) -> UResult<Cow<'_, str>> {
if !pattern.contains("[.") {
return Ok(Cow::Borrowed(pattern));
}

let bytes = pattern.as_bytes();
let mut out = String::with_capacity(pattern.len());
let mut i = 0;
let mut copied = 0;

while i < bytes.len() {
match bytes[i] {
b'\\' => {
i += 2;
}
b'[' => {
let bracket_start = i;
let mut j = i + 1;
if j < bytes.len() && bytes[j] == b'^' {
j += 1;
}
let body_start = j;

// Find the closing `]` of this bracket expression.
let mut close_idx = None;
let mut k = body_start;
while k < bytes.len() {
let b = bytes[k];
if b == b']' && k != body_start {
close_idx = Some(k);
break;
}
if b == b'[' && matches!(bytes.get(k + 1), Some(b':' | b'.' | b'=')) {
let delim = bytes[k + 1];
if let Some(sub_end) = find_bracket_subexpr_end(bytes, k + 2, delim) {
k = sub_end;
continue;
}
}
k += 1;
}

let Some(close) = close_idx else {
// Unterminated bracket: Oniguruma reports this error.
break;
};

// Check if this bracket expression contains `[.` in its body.
let has_collating = (body_start..close)
.any(|idx| bytes[idx] == b'[' && bytes.get(idx + 1) == Some(&b'.'));

if !has_collating {
i = close + 1;
continue;
}

out.push_str(&pattern[copied..bracket_start]);
out.push('[');
if body_start > bracket_start + 1 {
out.push('^');
}
let body_out_start = out.len();

let mut idx = body_start;
let mut last_copied = body_start;
let mut has_unranged_hyphen = false;
let mut leading_bracket = false;

if body_start < close && bytes[body_start] == b']' {
idx += 1;
}

while idx < close {
let b = bytes[idx];
if b == b'[' && bytes.get(idx + 1) == Some(&b'.') {
let Some(end) =
find_bracket_subexpr_end(bytes, idx + 2, b'.').filter(|&e| e <= close)
else {
return Err(USimpleError::new(
2,
"Unmatched [, [^, [:, [., or [=".to_string(),
));
};

let sym_bytes = &bytes[idx + 2..end - 2];
let sym = std::str::from_utf8(sym_bytes)
.expect("ASCII delimiters preserve UTF-8");
if sym.chars().count() != 1 {
return Err(USimpleError::new(
2,
"Invalid collation character".to_string(),
));
}

out.push_str(&pattern[last_copied..idx]);

let ch = sym.chars().next().unwrap();
if ch == '-' {
let is_range_end =
idx > body_start && bytes[idx - 1] == b'-' && idx - 1 > body_start;
let is_range_start = end < close
&& bytes[end] == b'-'
&& end + 1 < close
&& bytes[end + 1] != b']';

if is_range_end || is_range_start {
out.push('-');
} else {
has_unranged_hyphen = true;
}
} else if ch == '^' {
if out.ends_with('[') || out.ends_with("[^") {
out.push_str(r"\^");
} else {
out.push('^');
}
} else if ch == ']' {
leading_bracket = true;
} else {
out.push(ch);
}
last_copied = end;
idx = end;
continue;
}

if b == b'[' && matches!(bytes.get(idx + 1), Some(b':' | b'=')) {
let delim = bytes[idx + 1];
if let Some(sub_end) =
find_bracket_subexpr_end(bytes, idx + 2, delim).filter(|&e| e <= close)
{
idx = sub_end;
continue;
}
}

idx += 1;
}

out.push_str(&pattern[last_copied..close]);

if leading_bracket {
out.insert(body_out_start, ']');
}

if has_unranged_hyphen {
out.push('-');
}

out.push(']');
copied = close + 1;
i = close + 1;
}
_ => {
i += 1;
}
}
}

if copied == 0 {
Ok(Cow::Borrowed(pattern))
} else {
out.push_str(&pattern[copied..]);
Ok(Cow::Owned(out))
}
}

#[cfg(test)]
mod tests {
use super::{has_confusing_bracket, plain_literal, utf8_char_step};
use super::{has_confusing_bracket, plain_literal, rewrite_collating_symbols, utf8_char_step};
use crate::RegexMode;
use std::borrow::Cow;

#[test]
fn collating_symbols_rewriting() {
assert_eq!(rewrite_collating_symbols("[[.a.]]").unwrap(), "[a]");
assert_eq!(rewrite_collating_symbols("[[.q.]x]").unwrap(), "[qx]");
assert_eq!(rewrite_collating_symbols("[[.a.]-[.c.]]").unwrap(), "[a-c]");
assert_eq!(rewrite_collating_symbols("[[.a.]-c]").unwrap(), "[a-c]");
assert_eq!(rewrite_collating_symbols("[a-[.c.]]").unwrap(), "[a-c]");
assert_eq!(rewrite_collating_symbols("[[.-.]]").unwrap(), "[-]");
assert_eq!(
rewrite_collating_symbols("[^[:alnum:][.-.]_]").unwrap(),
"[^[:alnum:]_-]"
);
assert_eq!(rewrite_collating_symbols("[[.-.]-z]").unwrap(), "[--z]");
assert_eq!(rewrite_collating_symbols("[0-[.-.]]").unwrap(), "[0--]");
assert_eq!(rewrite_collating_symbols("[[.^.]]").unwrap(), r"[\^]");
assert_eq!(rewrite_collating_symbols("[a[.^.]]").unwrap(), "[a^]");
assert_eq!(rewrite_collating_symbols("[[.].]]").unwrap(), "[]]");
assert_eq!(rewrite_collating_symbols("[]a[.b.]]").unwrap(), "[]ab]");
assert_eq!(rewrite_collating_symbols("[[:[.a.]]").unwrap(), "[[:a]");

// Non-collating, unterminated, or escaped patterns borrow as-is
assert!(matches!(
rewrite_collating_symbols("abc").unwrap(),
Cow::Borrowed(_)
));
assert!(matches!(
rewrite_collating_symbols("[.a.]").unwrap(),
Cow::Borrowed(_)
));
assert!(matches!(
rewrite_collating_symbols("[[.a.").unwrap(),
Cow::Borrowed(_)
));
assert!(matches!(
rewrite_collating_symbols("\\[[.a.]]").unwrap(),
Cow::Borrowed(_)
));

// Multi-character or empty collating symbols are rejected
assert_eq!(
rewrite_collating_symbols("[[.tab.]]")
.unwrap_err()
.to_string(),
"Invalid collation character"
);
assert_eq!(
rewrite_collating_symbols("[[.space.]]")
.unwrap_err()
.to_string(),
"Invalid collation character"
);
assert_eq!(
rewrite_collating_symbols("[[..]]").unwrap_err().to_string(),
"Invalid collation character"
);

// Unclosed collating symbol
assert_eq!(
rewrite_collating_symbols("[[.a]").unwrap_err().to_string(),
"Unmatched [, [^, [:, [., or [="
);
}

#[test]
fn utf8_char_step_follows_maximal_subpart_recovery() {
Expand Down
59 changes: 58 additions & 1 deletion tests/test_grep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1489,7 +1489,7 @@ fn color_never_emits_no_escapes() {
}

// Guard against treating empty TERM or "DUMB" as "dumb".
#[cfg(unix)]
#[cfg(all(unix, not(target_os = "cygwin")))]
#[rstest]
#[case::unset(None, false)]
#[case::dumb(Some("dumb"), false)]
Expand Down Expand Up @@ -2744,3 +2744,60 @@ 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 collating_symbols_in_brackets() {
for mode in ["-G", "-E"] {
let (_s, mut c) = ucmd();
c.args(&[mode, "[[.q.]x]"])
.pipe_in("q\nx\nz\n")
.succeeds()
.stdout_only("q\nx\n");

let (_s, mut c) = ucmd();
c.args(&[mode, "[[.a.]-[.c.]]"])
.pipe_in("a\nb\nc\nd\n")
.succeeds()
.stdout_only("a\nb\nc\n");

let (_s, mut c) = ucmd();
c.args(&[mode, "[[.-.]]"])
.pipe_in("a-b\nab\n")
.succeeds()
.stdout_only("a-b\n");

let (_s, mut c) = ucmd();
c.args(&[mode, "[^[:alnum:][.-.]_]"])
.pipe_in("a\n-\n_\n+\n")
.succeeds()
.stdout_only("+\n");

let (_s, mut c) = ucmd();
c.args(&[mode, "[[.tab.]]"])
.pipe_in("t\n")
.fails_with_code(2)
.no_stdout()
.stderr_contains("Invalid collation character");

let (_s, mut c) = ucmd();
c.args(&[mode, "[[.space.]]"])
.pipe_in("s\n")
.fails_with_code(2)
.no_stdout()
.stderr_contains("Invalid collation character");

let (_s, mut c) = ucmd();
c.args(&[mode, "[[.a]"])
.pipe_in("a\n")
.fails_with_code(2)
.no_stdout()
.stderr_contains("Unmatched [, [^, [:, [., or [=");
}

// -F treats collating symbol syntax literally
let (_s, mut c) = ucmd();
c.args(&["-F", "[[.space.]]"])
.pipe_in("[[.space.]]\nspace\n")
.succeeds()
.stdout_only("[[.space.]]\n");
}
Loading