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
115 changes: 83 additions & 32 deletions src/matcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,12 +318,9 @@ impl CompiledPattern {
}

if matches!(config.regex_mode, RegexMode::Basic | RegexMode::Extended)
&& has_confusing_bracket(pattern.as_bytes())
&& let Err(msg) = check_brackets(pattern.as_bytes())
{
return Err(USimpleError::new(
2,
"character class syntax is [[:space:]], not [:space:]".to_string(),
));
return Err(USimpleError::new(2, msg.to_string()));
}

if config.regex_mode == RegexMode::Extended && has_empty_interval(pattern.as_bytes()) {
Expand Down Expand Up @@ -600,7 +597,8 @@ fn has_empty_interval(pattern: &[u8]) -> bool {
continue;
}
b'[' => {
i = scan_bracket(pattern, i + 1).1;
// `check_brackets` already accepted every bracket in `pattern`.
i = scan_bracket(pattern, i + 1).unwrap_or(pattern.len());
after_atom = true;
continue;
}
Expand All @@ -616,33 +614,54 @@ fn has_empty_interval(pattern: &[u8]) -> bool {
false
}

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.

check_brackets runs before has_empty_interval, so this branch can't be reached, no?
probably the line codecov is complaining about

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.

scan_bracket returns Result<usize, _> now, so the dummy end index on error is gone; has_empty_interval only falls back to pattern.len() for brackets check_brackets already accepted. Say if you meant another branch.


/// True when `pattern` holds a bracket expression that looks like a misspelled
/// character class, e.g. `[:space:]` instead of `[[:space:]]`. GNU grep rejects
/// those: a bracket whose first and last characters are colons, that holds at
/// least one other character, and that contains no range, class, equivalence
/// class or collating element.
fn has_confusing_bracket(pattern: &[u8]) -> bool {
const CONFUSING_BRACKET: &str = "character class syntax is [[:space:]], not [:space:]";
const UNMATCHED_BRACKET: &str = "Unmatched [, [^, [:, [., or [=";
const INVALID_CLASS_NAME: &str = "Invalid character class name";

fn is_posix_char_class(name: &[u8]) -> bool {
matches!(
name,

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 line is a leftover of the old doc comment, it now sits on is_posix_char_class.
please fix it, and keep the explanation of what a "confusing" bracket is somewhere (on scan_bracket?)

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: the stray line is gone, and the "confusing bracket" explanation now lives on scan_bracket.

b"alnum"
| b"alpha"
| b"blank"
| b"cntrl"
| b"digit"
| b"graph"
| b"lower"
| b"print"
| b"punct"
| b"space"
| b"upper"
| b"xdigit"
)
}

/// Validate bracket expressions in BRE/ERE patterns:
/// - Reject `[:space:]` used without outer `[...]`
/// - Reject non-POSIX `[:name:]` classes
/// - Reject unclosed `[:`, `[.`, `[=` subexpressions inside `[...]`
fn check_brackets(pattern: &[u8]) -> Result<(), &'static str> {
let mut i = 0;
while i < pattern.len() {
match pattern[i] {
b'\\' => i += 2,
b'[' => {
let (confusing, next) = scan_bracket(pattern, i + 1);
if confusing {
return true;
}
i = next;
}
b'[' => i = scan_bracket(pattern, i + 1)?,
_ => i += 1,

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 message is now written twice, could it be a const?

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: the three messages are consts now.

}
}
false
Ok(())
}

/// Scan the body of a bracket expression starting at `start` (just past the
/// `[`). Returns whether it is a misspelled character class and the index just
/// past its closing `]`.
fn scan_bracket(pattern: &[u8], start: usize) -> (bool, usize) {
/// `[`). Returns the index just past its closing `]`, or the diagnostic GNU
/// grep gives for it:
/// - a "confusing" bracket, one that looks like a misspelled character class
/// such as `[:space:]` instead of `[[:space:]]`: its first and last
/// characters are colons, it holds at least one other character, and it
/// contains no range, class, equivalence class or collating element;
/// - an unclosed `[:`, `[.` or `[=` subexpression;
/// - a `[:name:]` whose name is not one of the twelve POSIX classes.
fn scan_bracket(pattern: &[u8], start: usize) -> Result<usize, &'static str> {
const FIRST_IS_COLON: u8 = 1;
const LAST_IS_COLON: u8 = 2;
const HAS_OTHER: u8 = 4;
Expand All @@ -662,18 +681,24 @@ fn scan_bracket(pattern: &[u8], start: usize) -> (bool, usize) {
let c = pattern[i];
// A `]` right at the start of the body is an ordinary character.
if c == b']' && i != body_start {
return (state == FIRST_IS_COLON | LAST_IS_COLON | HAS_OTHER, i + 1);
if state == FIRST_IS_COLON | LAST_IS_COLON | HAS_OTHER {
return Err(CONFUSING_BRACKET);
}
return Ok(i + 1);
}
// Only the character just before the closing `]` counts as the last one.
state &= !LAST_IS_COLON;
// `[:alpha:]`, `[.a.]` and `[=a=]` inside the bracket.
if c == b'[' && matches!(pattern.get(i + 1), Some(b':' | b'.' | b'=')) {
let delimiter = pattern[i + 1];
if let Some(end) = find_bracket_subexpr_end(pattern, i + 2, delimiter) {
state |= HAS_RANGE_OR_CLASS;
i = end;
continue;
let end =
find_bracket_subexpr_end(pattern, i + 2, delimiter).ok_or(UNMATCHED_BRACKET)?;
if delimiter == b':' && !is_posix_char_class(&pattern[i + 2..end - 2]) {
return Err(INVALID_CLASS_NAME);
}
state |= HAS_RANGE_OR_CLASS;
i = end;
continue;
}
// `x-y` is a range, but the `-` of `[x-]` is an ordinary character.
if pattern.get(i + 1) == Some(&b'-')
Expand All @@ -687,7 +712,7 @@ fn scan_bracket(pattern: &[u8], start: usize) -> (bool, usize) {
i += 1;
}
// Unterminated bracket: the regex engine reports that on its own.
(false, pattern.len())
Ok(pattern.len())
}

/// Index just past the `:]`, `.]` or `=]` closing a `[: [. [=` subexpression
Expand All @@ -700,7 +725,10 @@ fn find_bracket_subexpr_end(pattern: &[u8], start: usize, delimiter: u8) -> Opti

#[cfg(test)]
mod tests {
use super::{has_confusing_bracket, plain_literal, utf8_char_step};
use super::{
CONFUSING_BRACKET, INVALID_CLASS_NAME, UNMATCHED_BRACKET, check_brackets, plain_literal,
utf8_char_step,
};
use crate::RegexMode;

#[test]
Expand Down Expand Up @@ -800,7 +828,11 @@ mod tests {
"[:x:]",
"ab[:blank:]",
] {
assert!(has_confusing_bracket(p.as_bytes()), "pattern {p:?}");
assert_eq!(
check_brackets(p.as_bytes()),
Err(CONFUSING_BRACKET),
"pattern {p:?}"
);
}
}

Expand All @@ -820,7 +852,26 @@ mod tests {
"[:digit:", // unterminated
"[a-z]+[0-9]", // no colons at all
] {
assert!(!has_confusing_bracket(p.as_bytes()), "pattern {p:?}");
assert!(check_brackets(p.as_bytes()).is_ok(), "pattern {p:?}");
}
}

#[test]
fn rejects_invalid_and_unclosed_bracket_subexpressions() {
for p in ["[[:word:]]", "[[:^alpha:]]", "[[::]]"] {
assert_eq!(
check_brackets(p.as_bytes()),
Err(INVALID_CLASS_NAME),
"{p:?}"
);
}
for p in ["[[:alpha]]", "[x[:]y]", "[[.a]", "[[=a]"] {
assert_eq!(
check_brackets(p.as_bytes()),
Err(UNMATCHED_BRACKET),
"{p:?}"
);
}
assert!(check_brackets(b"[[:alpha:]][[.a.]][[=a=]]").is_ok());
}
}
38 changes: 38 additions & 0 deletions tests/test_grep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2764,3 +2764,41 @@ fn files_without_match_with_nothing_selectable() {
.stdout_is("trees.txt\n")
.stderr_contains("missing.txt: ");
}

#[test]
fn rejects_invalid_character_class_names() {
let cases = [
("[[:word:]]", "Invalid character class name"),
("[[:ascii:]]", "Invalid character class name"),
("[[:^digit:]]", "Invalid character class name"),
("[[::]]", "Invalid character class name"),
("[[:digit]]", "Unmatched [, [^, [:, [., or [="),
("[x[:]y]", "Unmatched [, [^, [:, [., or [="),

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.

please add cases for unclosed [. and [= too, like [[.a] and [[=a]

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.

[[.a] and [[=a] are in the table in rejects_invalid_character_class_names (for -G and -E); I also added a unit test that calls check_brackets on them.

("[[:]", "Unmatched [, [^, [:, [., or [="),
("[[:a:b]", "Unmatched [, [^, [:, [., or [="),
("[[.a]", "Unmatched [, [^, [:, [., or [="),
("[[=a]", "Unmatched [, [^, [:, [., or [="),
];
for (pattern, message) in cases {
for mode in ["-G", "-E"] {
let (scene, mut c) = ucmd();
scene.fixtures.write("input", "7\n:]\n");
c.args(&[mode, pattern, "input"])
.fails_with_code(2)
.no_stdout()
.stderr_contains(message);
}
}
// The twelve POSIX names and valid bracket subexpressions keep working.
let (scene, mut c) = ucmd();
scene.fixtures.write("valid", "f\nz\n");
c.args(&["[[:xdigit:]]", "valid"])
.succeeds()
.stdout_only("f\n");

let (scene, mut c) = ucmd();
scene.fixtures.write("valid2", "a\nb\n");
c.args(&["[[.a.]][[=b=]]", "valid2"])
.fails_with_code(1)
.no_stdout();
}
Loading