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
24 changes: 24 additions & 0 deletions src/sed/delimited_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -420,9 +420,13 @@ pub fn parse_regex_for_mode(
// In an ERE, a quantifier must follow something it can repeat. GNU sed
// rejects one at the start of the regex or right after `(`, `|`, `^` or
// `$`, and reports it once the whole regex has been read.
// In a BRE, a `*` with nothing to repeat stands for itself, so it is
// emitted as `\*`. That is at the start of the regex, right after `\(`
// or `\|`, or right after a `^` anchor in one of those places.
let is_ere = matches!(regex_mode, RegexMode::Extended);
let mut can_quantify = false;
let mut quantifier_without_atom = false;
let mut bre_at_start = true;
while !line.eol() {
let c = line.current();
if is_ere && c != delimiter {
Expand All @@ -431,6 +435,26 @@ pub fn parse_regex_for_mode(
quantifier_without_atom = true;
}
can_quantify = !matches!(c, '(' | '|' | '^' | '$');
} else if c != delimiter {
if c == '*' && !can_quantify {
result.extend_from_slice(b"\\*");
can_quantify = true;
bre_at_start = false;
line.advance();
continue;
}
let at_start = bre_at_start;
bre_at_start = false;
can_quantify = !(c == '^' && at_start);
if c == '\\' {
let next = line
.get_line()
.get(line.get_pos() + 1)
.map(|&b| char::from(b));
let opens = matches!(next, Some('(')) || (matches!(next, Some('|')) && !posix);
bre_at_start = opens && next != Some(delimiter);
can_quantify = !bre_at_start;
}
}
match c {
'[' if delimiter != '[' => {
Expand Down
25 changes: 25 additions & 0 deletions tests/by-util/test_sed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4393,3 +4393,28 @@ fn test_lone_lead_byte_delimiter() {
.succeeds()
.stdout_only("y\n");
}

#[rstest]
#[case::star_first(&[], "s/*/x/", "*a*b\n", "xa*b\n")]
#[case::star_after_caret(&[], "s/^*/x/", "*a*b\n", "xa*b\n")]
#[case::double_star_after_caret(&[], "s/^**/x/g", "*a*b\n", "xa*b\n")]
#[case::star_after_group_open(&[], "s/\\(*\\)/x/g", "*a*b\n", "xaxb\n")]
#[case::star_after_alternation(&[], "s/b\\|*/x/g", "*a*b\n", "xaxx\n")]
#[case::address_star_after_caret(&[], "/^*a/s/b/x/", "*a*b\n", "*a*x\n")]
#[case::star_after_alternation_pipe_delim(&[], "s|\\|*|x|g", "*a*b\n", "x*xax*xbx\n")]
// Under --posix `\|` is a literal `|`, so the `*` repeats it.
#[case::posix_pipe_before_star(&["--posix"], "s/b\\|*/x/g", "*a*b\nab||*\n", "*a*x\nax*\n")]
fn test_bre_star_without_preceding_atom(
#[case] extra_args: &[&str],
#[case] script: &str,
#[case] input: &str,
#[case] expected: &str,
) {
let file = script_file(script);
new_ucmd!()
.args(extra_args)
.args(&["-f", script_path(&file)])
.pipe_in(input)
.succeeds()
.stdout_is(expected);
}
Loading