diff --git a/src/lib.rs b/src/lib.rs index 7fd4174..f5bd008 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -87,6 +87,16 @@ pub struct GlobSet { } #[doc(hidden)] +/// A pattern to match, together with where it came from. +#[derive(Clone, Copy, Debug)] +pub struct Pattern<'a> { + pub text: &'a str, + /// The `-f` file (`-` for standard input) and 1-based line the pattern was + /// read from, or `None` for `-e` and positional patterns. GNU grep names + /// this location when such a pattern fails to compile. + pub origin: Option<(&'a str, usize)>, +} + pub struct Config<'a> { // Searcher pub directory_mode: DirectoryMode, @@ -104,7 +114,7 @@ pub struct Config<'a> { pub has_context: bool, // Matcher - pub patterns: &'a [&'a str], + pub patterns: &'a [Pattern<'a>], pub regex_mode: RegexMode, pub ignore_case: bool, pub invert_match: bool, @@ -236,7 +246,10 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { { for expr in regexp { for line in expr.split('\n') { - patterns.push(line); + patterns.push(Pattern { + text: line, + origin: None, + }); } } @@ -250,13 +263,16 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { } else { std::fs::read_to_string(path).map_err(|err| read_error(path, &err))? }; - pattern_strings.push(contents); + pattern_strings.push((path.as_str(), contents)); } - for contents in &pattern_strings { + for (path, contents) in &pattern_strings { if !contents.is_empty() { let body = contents.strip_suffix('\n').unwrap_or(contents); - for line in body.split('\n') { - patterns.push(line); + for (index, line) in body.split('\n').enumerate() { + patterns.push(Pattern { + text: line, + origin: Some((*path, index + 1)), + }); } } } @@ -266,7 +282,10 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { .to_str() .ok_or_else(|| USimpleError::new(2, "pattern must be valid UTF-8".to_string()))?; for line in pat.split('\n') { - patterns.push(line); + patterns.push(Pattern { + text: line, + origin: None, + }); } } } @@ -460,7 +479,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { // An empty pattern matches every line; with `-v`, GNU grep selects no lines // and exits as "no match" without reading any input files. - if invert_match && patterns.iter().any(|pattern| pattern.is_empty()) { + if invert_match && patterns.iter().any(|pattern| pattern.text.is_empty()) { return Err(ExitCode::new(1)); } diff --git a/src/matcher.rs b/src/matcher.rs index 5efacc3..17c1eee 100644 --- a/src/matcher.rs +++ b/src/matcher.rs @@ -30,8 +30,12 @@ pub struct Matcher<'a> { impl<'a> Matcher<'a> { pub fn compile(config: &'a Config<'a>) -> UResult { let mut patterns = Vec::with_capacity(config.patterns.len()); - for raw in config.patterns { - patterns.push(CompiledPattern::compile(raw, config)?); + for pattern in config.patterns { + patterns.push(CompiledPattern::compile( + pattern.text, + pattern.origin, + config, + )?); } // If we can reduce the whole pattern set to literal needles, keep a @@ -39,7 +43,7 @@ impl<'a> Matcher<'a> { let needles: Option>> = config .patterns .iter() - .map(|p| plain_literal(p, config.ignore_case, config.regex_mode)) + .map(|p| plain_literal(p.text, config.ignore_case, config.regex_mode)) .collect(); let literal_searchers = needles.filter(|n| !n.is_empty()).map(|n| { n.iter() @@ -262,7 +266,8 @@ struct CompiledPattern { } impl CompiledPattern { - fn compile(pattern: &str, config: &Config) -> UResult { + /// `origin` is the `-f` file and line the pattern came from, if any. + fn compile(pattern: &str, origin: Option<(&str, usize)>, config: &Config) -> UResult { let mut syntax = *match config.regex_mode { RegexMode::Fixed => Syntax::asis(), RegexMode::Basic => Syntax::grep(), @@ -325,10 +330,16 @@ impl CompiledPattern { options |= RegexOptions::REGEX_OPTION_MULTILINE; } + // Like GNU grep, a regex syntax error in a pattern read with `-f FILE` + // names the file and line (`FILE:LINE: message`). GNU's PCRE backend + // reports its errors without this location. + let origin = origin.filter(|_| config.regex_mode != RegexMode::Perl); + fn compile_with( pattern: &str, syntax: &Syntax, options: RegexOptions, + origin: Option<(&str, usize)>, ) -> UResult { OnigRegex::compile(pattern, syntax, options).map_err(|err| { // A reversed range like `[b-a]` is ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS. @@ -338,15 +349,20 @@ impl CompiledPattern { ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS => "Invalid range end".to_string(), _ => format!("invalid pattern \"{pattern}\": {}", err.message), }; + let message = match origin { + Some((file, line)) => format!("{file}:{line}: {message}"), + None => message, + }; USimpleError::new(2, message) }) } - let leftmost = compile_with(pattern, &syntax, options)?; + let leftmost = compile_with(pattern, &syntax, options, origin)?; let longest_anchored = compile_with( pattern, &syntax, options | RegexOptions::REGEX_OPTION_FIND_LONGEST, + origin, )?; Ok(Self { leftmost, diff --git a/tests/test_grep.rs b/tests/test_grep.rs index 75961f7..002e686 100644 --- a/tests/test_grep.rs +++ b/tests/test_grep.rs @@ -164,6 +164,62 @@ fn reversed_range_endpoints_match_gnu_message() { } } +/// Prefix of an error reported through uucore, which names the binary as +/// invoked: `grep.exe` on Windows. +fn uucore_error(message: &str) -> String { + let name = if cfg!(windows) { "grep.exe" } else { "grep" }; + format!("{name}: {message}\n") +} + +#[test] +fn pattern_file_compile_error_names_file_and_line() { + // GNU grep prefixes a syntax error in a pattern read with `-f FILE` with + // `FILE:LINE: `, so the user knows which line of the file to fix. + let (scene, mut c) = ucmd(); + // Empty lines and duplicate patterns still count as lines. + scene.fixtures.write("pats", "foo\n\nfoo\n[z-a]\n"); + c.args(&["-f", "pats"]) + .pipe_in("foo\n") + // grep fails before reading standard input. + .ignore_stdin_write_error() + .fails_with_code(2) + .no_stdout() + .stderr_is(uucore_error("pats:4: Invalid range end")); + + // `-f -` reads standard input, which GNU names `-`. + let (_s, mut c) = ucmd(); + c.args(&["-f", "-"]) + .pipe_in("x\n[z-a]\n") + .fails_with_code(2) + .stderr_is(uucore_error("-:2: Invalid range end")); + + // The line is counted per file, also in extended mode. + let (scene, mut c) = ucmd(); + scene.fixtures.write("ok", "foo\nbar\n"); + scene.fixtures.write("bad", "[z-a]\n"); + c.args(&["-E", "-f", "ok", "-f", "bad"]) + .pipe_in("foo\n") + .ignore_stdin_write_error() + .fails_with_code(2) + .stderr_is(uucore_error("bad:1: Invalid range end")); + + // Patterns from `-e` or the command line get no prefix, and neither do + // errors from the PCRE backend. + let (_s, mut c) = ucmd(); + c.args(&["-e", "[z-a]"]) + .pipe_in("foo\n") + .ignore_stdin_write_error() + .fails_with_code(2) + .stderr_is(uucore_error("Invalid range end")); + let (scene, mut c) = ucmd(); + scene.fixtures.write("pcre", "(\n"); + c.args(&["-P", "-f", "pcre"]) + .pipe_in("foo\n") + .ignore_stdin_write_error() + .fails_with_code(2) + .stderr_does_not_contain("pcre:1:"); +} + #[test] fn unreadable_pattern_file_is_error() { // An unreadable -f / --exclude-from file is a usage error (exit 2), not the