diff --git a/src/sed/delimited_parser.rs b/src/sed/delimited_parser.rs index d4fff8ff..c5ce054f 100644 --- a/src/sed/delimited_parser.rs +++ b/src/sed/delimited_parser.rs @@ -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 { @@ -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 != '[' => { diff --git a/tests/by-util/test_sed.rs b/tests/by-util/test_sed.rs index 99cc9897..10f66268 100644 --- a/tests/by-util/test_sed.rs +++ b/tests/by-util/test_sed.rs @@ -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); +}