diff --git a/interpreter/src/builtins.rs b/interpreter/src/builtins.rs index de4cef4..08dc153 100644 --- a/interpreter/src/builtins.rs +++ b/interpreter/src/builtins.rs @@ -421,7 +421,7 @@ mod tests { #[test] fn builtin_error_converts_with_span() { let err = BuiltinError::Arity { expected: 2, given: 1 }; - let span = AriadneSpan(parser::FileCache(None), Span::new(0, 1)); + let span = AriadneSpan(parser::FileCache::Cli(0), Span::new(0, 1)); assert!(matches!( err.into_interpreter_error(span), InterpreterError::ArityMismatch(_, 2, 1) diff --git a/interpreter/src/ir/tests.rs b/interpreter/src/ir/tests.rs index bdee696..32a271c 100644 --- a/interpreter/src/ir/tests.rs +++ b/interpreter/src/ir/tests.rs @@ -7,7 +7,7 @@ fn with_lower(source: &str, f: impl FnOnce(&CodeGen)) { let arena = Bump::new(); let mut parser = Parser::new(&arena, false); let ast = parser - .parse(FileCache(None), source.as_bytes()) + .parse(FileCache::Cli(0), source.as_bytes()) .expect("parse"); let mut cg = CodeGen::new(&arena); cg.lower_ast(ast); diff --git a/parser/src/diagnostics.rs b/parser/src/diagnostics.rs index 0ed908c..6cc5f54 100644 --- a/parser/src/diagnostics.rs +++ b/parser/src/diagnostics.rs @@ -177,6 +177,13 @@ pub enum ParsingError { NextInForbiddenCtx(Span), #[error("`nextfile` is forbidden in BEGIN, END, and ENDFILE rules!")] NextFileInForbiddenCtx(Span), + #[error("{}", cannot_open_source(.1, .2))] + CannotOpenSource(Span, String, String), +} + +/// The message for a source file that cannot be read. +pub fn cannot_open_source(path: impl Display, reason: impl Display) -> String { + format!("cannot open source file `{path}' for reading: {reason}") } impl ParsingError { @@ -226,6 +233,7 @@ impl ParsingError { | &Self::ReturnOutsideFunction(span) | &Self::CommandDoubleCall(span, _) | &Self::NextInForbiddenCtx(span) + | &Self::CannotOpenSource(span, ..) | &Self::NextFileInForbiddenCtx(span) => Some(span), } } @@ -294,19 +302,23 @@ impl ParsingError { } #[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub struct FileCache(pub Option>); +pub enum FileCache { + /// Program text from the command line: the program operand, or the nth `--source`. + Cli(usize), + File(Rc), +} impl FileCache { pub const fn new_file(f: Rc) -> Self { - Self(Some(f)) + Self::File(f) } } impl Display for FileCache { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match &self.0 { - Some(p) => write!(f, "{}", p.display()), - None => f.write_str("CLI"), + match self { + Self::File(p) => write!(f, "{}", p.display()), + Self::Cli(_) => f.write_str("CLI"), } } } diff --git a/parser/src/lib.rs b/parser/src/lib.rs index 5b86df1..024554b 100644 --- a/parser/src/lib.rs +++ b/parser/src/lib.rs @@ -13,7 +13,10 @@ mod sexpr; mod tests; use std::{ + borrow::Cow, + ffi::OsString, fs::File, + io, mem::{replace, take}, path::{Path, PathBuf}, rc::Rc, @@ -29,7 +32,9 @@ pub use lexer::{BlobId, IdentId, Span, StaticInterner}; pub use crate::{ ast::*, - diagnostics::{AriadneSpan, Diagnostic, DiagnosticStore, FileCache, ParsingError}, + diagnostics::{ + AriadneSpan, Diagnostic, DiagnosticStore, FileCache, ParsingError, cannot_open_source, + }, lex::{Lexer, SpanExt}, }; use crate::{lex::TokenExt, pratt::Pratt}; @@ -67,7 +72,7 @@ impl<'a> Parser<'a> { ast: Ast::new(arena), arena, preprocessor: Preprocessor {}, - file: FileCache(None), + file: FileCache::Cli(0), namespace: StaticInterner::awk_ident(), concurrent: false, dry, @@ -154,8 +159,9 @@ impl<'a> Parser<'a> { } Token::IncludeDirective => { let path = lex.expect_string()?; + let span = lex.span(); if let (Err(e), _) = - self.include(make_path(path), Some(StaticInterner::awk_ident())) + self.include(make_path(path), span, Some(StaticInterner::awk_ident())) { return Err(e); } @@ -163,7 +169,8 @@ impl<'a> Parser<'a> { } Token::NsIncludeDirective => { let path = lex.expect_string()?; - if let (Err(e), _) = self.include(make_path(path), None) { + let span = lex.span(); + if let (Err(e), _) = self.include(make_path(path), span, None) { return Err(e); } lex.expect_with(Token::is_stmnt_end, ParsingError::ExpectedStatementEnd)?; @@ -950,11 +957,11 @@ impl<'a> Parser<'a> { fn enter_file( &mut self, - path: Rc, + file: FileCache, source: &'a [u8], f: impl FnOnce(&mut Self, &mut Lexer<'a>) -> T, ) -> (T, FileCache) { - let old = replace(&mut self.file, FileCache::new_file(path)); + let old = replace(&mut self.file, file); self.ast.diagnostics.cache(self.file.clone(), source); let mut lex = Lexer::new(source); @@ -962,15 +969,37 @@ impl<'a> Parser<'a> { (ret, replace(&mut self.file, old)) } - fn include(&mut self, path: Rc, ns: Option) -> (Result<()>, FileCache) { + /// `span` is the `@include` path's string, where a read error is reported. + fn include( + &mut self, + path: Rc, + span: Span, + ns: Option, + ) -> (Result<()>, FileCache) { + match self.preprocessor.read_to_arena(&path, self.arena) { + Ok(source) => self.include_source(FileCache::new_file(path), source, ns), + Err(err) => { + let reason = read_reason(&err).into_owned(); + let error = + ParsingError::CannotOpenSource(span, path.display().to_string(), reason); + (Err(error), self.file.clone()) + } + } + } + + fn include_source( + &mut self, + file: FileCache, + source: &'a [u8], + ns: Option, + ) -> (Result<()>, FileCache) { let old_namespace = self.namespace; - let source = self.preprocessor.read_to_arena(path.clone(), self.arena); if let Some(ns) = ns { self.namespace = ns; } - let file = match self.enter_file(path, source, |this, lex| { + let file = match self.enter_file(file, source, |this, lex| { this.parse_top(lex, false).map(|_| ()) }) { (Ok(()), file) => file, @@ -981,10 +1010,28 @@ impl<'a> Parser<'a> { (Ok(()), file) } - pub fn include_many(&mut self, files: &[PathBuf]) -> Result<&mut Ast<'a>, DiagnosticStore> { - for path in files { - let path = Rc::from(path.as_path()); - let (res, file) = self.include(path, Some(StaticInterner::awk_ident())); + /// Parses the `-f` files and `--source` texts in command-line order. Like gawk, + /// each one is parsed on its own and starts in the `awk` namespace. + pub fn include_many( + &mut self, + sources: &'a [ProgramSource], + ) -> std::result::Result<&mut Ast<'a>, IncludeError> { + let mut texts = 0; + for source in sources { + let (file, source) = match source { + ProgramSource::File(path) => { + let path = Rc::from(path.as_path()); + match self.preprocessor.read_to_arena(&path, self.arena) { + Ok(source) => (FileCache::new_file(path), source), + Err(err) => return Err(IncludeError::CannotOpen { path, err }), + } + } + ProgramSource::Text(text) => { + texts += 1; + (FileCache::Cli(texts - 1), text.as_encoded_bytes()) + } + }; + let (res, file) = self.include_source(file, source, Some(StaticInterner::awk_ident())); if let Err(error) = res { error.add_diagnostic_cached( @@ -995,13 +1042,39 @@ impl<'a> Parser<'a> { } if self.ast.diagnostics.is_unrecoverable() { - Err(take(&mut self.ast.diagnostics)) + Err(IncludeError::Invalid(take(&mut self.ast.diagnostics))) } else { Ok(&mut self.ast) } } } +/// One piece of the program: a `-f` file, or `--source` text. +#[derive(Clone, Debug)] +pub enum ProgramSource { + File(PathBuf), + Text(OsString), +} + +/// Why [`Parser::include_many`] has no program to run. +#[derive(Debug, thiserror::Error)] +pub enum IncludeError { + #[error("{}", cannot_open_source(.path.display(), read_reason(.err)))] + CannotOpen { path: Rc, err: io::Error }, + #[error("the program has errors")] + Invalid(DiagnosticStore), +} + +/// GNU's wording for the errors reading a source file can hit, which Rust words differently. +fn read_reason(err: &io::Error) -> Cow<'static, str> { + match err.kind() { + io::ErrorKind::NotFound => "No such file or directory".into(), + io::ErrorKind::PermissionDenied => "Permission denied".into(), + io::ErrorKind::IsADirectory => "Is a directory".into(), + _ => err.to_string().into(), + } +} + impl<'a> Ast<'a> { pub(crate) fn new(arena: &'a Bump) -> Self { Self { @@ -1024,11 +1097,11 @@ impl<'a> Ast<'a> { struct Preprocessor {} impl Preprocessor { - fn read_to_arena<'a>(&self, path: impl AsRef, arena: &'a Bump) -> &'a [u8] { - let mut f = File::open(path).unwrap(); - let mut buf = Vec::with_capacity_in(f.metadata().unwrap().len() as _, arena); - std::io::copy(&mut f, &mut buf).unwrap(); - buf.into_bump_slice() + fn read_to_arena<'a>(&self, path: impl AsRef, arena: &'a Bump) -> io::Result<&'a [u8]> { + let mut f = File::open(path)?; + let mut buf = Vec::with_capacity_in(f.metadata()?.len() as _, arena); + io::copy(&mut f, &mut buf)?; + Ok(buf.into_bump_slice()) } } @@ -1041,8 +1114,6 @@ fn make_path(blob: BlobId) -> Rc { #[cfg(not(unix))] fn make_path(blob: BlobId) -> Rc { - use std::borrow::Cow; - StaticInterner::resolve(blob, |s| match String::from_utf8_lossy(s) { Cow::Borrowed(s) => Rc::from(Path::new(s)), Cow::Owned(s) => Rc::from(PathBuf::from(s)), diff --git a/parser/src/tests.rs b/parser/src/tests.rs index fb740a1..a8ef06c 100644 --- a/parser/src/tests.rs +++ b/parser/src/tests.rs @@ -937,7 +937,7 @@ fn test_pretty_print_omits_default_namespace() { let arena = Bump::new(); let parser = arena.alloc(Parser::new(&arena, true)); let source = "{ print a + b }"; - let ast = parser.parse(FileCache(None), source.as_bytes()).unwrap(); + let ast = parser.parse(FileCache::Cli(0), source.as_bytes()).unwrap(); let mut printed = String::new(); write!(printed, "{ast}").unwrap(); assert!( @@ -957,7 +957,7 @@ fn test_pretty_print_namespace_directive() { @namespace "my_ns"; function bar(x) { print x } "#; - let ast = parser.parse(FileCache(None), source.as_bytes()).unwrap(); + let ast = parser.parse(FileCache::Cli(0), source.as_bytes()).unwrap(); let mut printed = String::new(); write!(printed, "{ast}").unwrap(); assert!( @@ -981,13 +981,15 @@ fn test_pretty_print_namespace_roundtrip() { function bar() { x = 1 } { print y } "#; - let ast = parser.parse(FileCache(None), source.as_bytes()).unwrap(); + let ast = parser.parse(FileCache::Cli(0), source.as_bytes()).unwrap(); let mut printed = String::new(); write!(printed, "{ast}").unwrap(); let arena2 = Bump::new(); let parser2 = arena2.alloc(Parser::new(&arena2, true)); - let reparsed = parser2.parse(FileCache(None), printed.as_bytes()).unwrap(); + let reparsed = parser2 + .parse(FileCache::Cli(0), printed.as_bytes()) + .unwrap(); assert_eq!(ast.functions.len(), reparsed.functions.len()); assert_eq!(ast.rules.len(), reparsed.rules.len()); } diff --git a/src/cli.rs b/src/cli.rs index 0e1a8e3..529b4da 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -12,12 +12,14 @@ use std::{ }; use clap::{ - ArgAction, Error, Parser, ValueEnum, + ArgAction, ArgMatches, Error, FromArgMatches, Parser, ValueEnum, builder::{TypedValueParser, ValueParserFactory}, error::ErrorKind, + value_parser, }; use lexer::{BlobId, IdentId, StaticInterner, Token}; use memchr::memchr; +use parser::ProgramSource; #[derive(Parser, Debug)] #[clap(version, name = "uutils AWK")] @@ -25,14 +27,10 @@ use memchr::memchr; pub struct Args { #[arg(required_unless_present_any = ["file", "source"])] pub code: Option, - #[arg( - trailing_var_arg = true, - allow_hyphen_values = true, - default_value = "-" - )] + #[command(flatten)] + pub program: ProgramSources, + #[arg(trailing_var_arg = true, allow_hyphen_values = true)] pub read_queue: Vec, - #[arg(short = 'f', long)] - pub file: Vec, #[arg(short = 'F', long)] pub field_separator: Option, #[arg(short = 'v', long)] @@ -53,8 +51,6 @@ pub struct Args { pub dump_variables: Option, #[arg(short = 'D', long, num_args = 0..=1, default_missing_value = "", value_parser = parse_debug_mode)] pub debug: Option, - #[arg(short = 'e', long)] - pub source: Vec, #[arg(short = 'E', long)] pub exec: Option, #[arg(short = 'g', long)] @@ -103,6 +99,65 @@ pub struct Args { pub csv: bool, } +/// The `-f` files and `--source` texts in command-line order, as gawk reads them. +/// clap keeps each option in its own list, so the order comes from their indices. +#[derive(Clone, Debug, Default)] +pub struct ProgramSources(pub Vec); + +impl FromArgMatches for ProgramSources { + fn from_arg_matches(matches: &ArgMatches) -> Result { + let files = matches.indices_of("file").into_iter().flatten().zip( + matches + .get_many::("file") + .into_iter() + .flatten() + .map(|path| ProgramSource::File(path.clone())), + ); + let texts = matches.indices_of("source").into_iter().flatten().zip( + matches + .get_many::("source") + .into_iter() + .flatten() + .map(|text| ProgramSource::Text(text.clone())), + ); + let mut sources: Vec<_> = files.chain(texts).collect(); + sources.sort_by_key(|&(index, _)| index); + Ok(Self( + sources.into_iter().map(|(_, source)| source).collect(), + )) + } + + fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> { + *self = Self::from_arg_matches(matches)?; + Ok(()) + } +} + +impl clap::Args for ProgramSources { + fn augment_args(cmd: clap::Command) -> clap::Command { + cmd.arg( + clap::Arg::new("file") + .short('f') + .long("file") + .value_name("FILE") + .action(ArgAction::Append) + .value_parser(value_parser!(PathBuf)), + ) + .arg( + clap::Arg::new("source") + .short('e') + .long("source") + .value_name("SOURCE") + .action(ArgAction::Append) + .value_parser(value_parser!(OsString)), + ) + } + + fn augment_args_for_update(cmd: clap::Command) -> clap::Command { + Self::augment_args(cmd) + } +} + #[derive(Clone, Debug)] pub enum ArgQueueItem { File(PathBuf), @@ -110,6 +165,18 @@ pub enum ArgQueueItem { Stdio, } +impl ArgQueueItem { + pub fn from_operand(value: &OsStr) -> Self { + if value == OsStr::new("-") { + Self::Stdio + } else if let Ok(key_val) = KeyValue::parse_from(value) { + Self::Assignment(key_val) + } else { + Self::File(PathBuf::from(value)) + } + } +} + #[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)] pub enum LintMode { Basic, @@ -199,13 +266,7 @@ impl TypedValueParser for ArgQueueItemFactory { _arg: Option<&clap::Arg>, value: &OsStr, ) -> Result { - if value == OsStr::new("-") { - Ok(ArgQueueItem::Stdio) - } else if let Ok(key_val) = KeyValue::parse_from(value) { - Ok(ArgQueueItem::Assignment(key_val)) - } else { - Ok(ArgQueueItem::File(PathBuf::from(value))) - } + Ok(ArgQueueItem::from_operand(value)) } } diff --git a/src/main.rs b/src/main.rs index eaa69f1..4dfd50b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -20,10 +20,10 @@ use std::{ use bumpalo::Bump; use clap::Parser as ClapParser; use interpreter::{CodeGen, ExecMode, Interpreter}; -use parser::{FileCache, Parser}; +use parser::{FileCache, IncludeError, Parser}; use crate::{ - cli::{Args, KeyValue}, + cli::{ArgQueueItem, Args, KeyValue}, event::AwkRt, utils::{AWK_FATAL_CODE, EXIT_FAILURE, ensure_consistent_panic, exit_err}, }; @@ -35,7 +35,7 @@ fn main() { } fn uu_main() -> Result<(), Box> { - let args = match Args::try_parse_from(args_os()) { + let mut args = match Args::try_parse_from(args_os()) { Ok(args) => args, Err(msg) => { msg.print()?; @@ -43,15 +43,30 @@ fn uu_main() -> Result<(), Box> { } }; + // With -f or --source there is no program operand: the first operand is an input. + if !args.program.0.is_empty() + && let Some(operand) = args.code.take() + { + args.read_queue + .insert(0, ArgQueueItem::from_operand(&operand)); + } + if args.read_queue.is_empty() { + args.read_queue.push(ArgQueueItem::Stdio); + } + let rt_arena = Bump::with_capacity(4000); // 4KB minus metadata-ish let (mut cg, metadata, diagnostics) = { let ast_arena = Bump::with_capacity(4000); let mut parser = Parser::new(&ast_arena, args.pretty_print.is_some()); - let ast = if args.file.is_empty() { + let ast = if args.program.0.is_empty() { let code = args.code.as_ref().unwrap(); - parser.parse(FileCache(None), code.as_encoded_bytes()) + parser.parse(FileCache::Cli(0), code.as_encoded_bytes()) } else { - parser.include_many(&args.file) + match parser.include_many(&args.program.0) { + Ok(ast) => Ok(ast), + Err(IncludeError::Invalid(diagnostics)) => Err(diagnostics), + Err(err) => exit_err(Some(format!("awk: fatal: {err}")), AWK_FATAL_CODE), + } }; let ast = match ast { Ok(ast) => ast, diff --git a/tests/by-util/test_awk.rs b/tests/by-util/test_awk.rs index 947d5ae..bb05544 100644 --- a/tests/by-util/test_awk.rs +++ b/tests/by-util/test_awk.rs @@ -59,6 +59,129 @@ fn no_args_fails_code_one() { ucmd().fails_with_code(1); } +#[test] +fn missing_program_file_is_fatal() { + ucmd() + .args(&["-f", "no-such-prog.awk"]) + .fails_with_code(2) + .stderr_contains( + "awk: fatal: cannot open source file `no-such-prog.awk' for reading: No such file or directory", + ) + .stderr_does_not_contain("panicked") + .no_stdout(); +} + +#[test] +fn program_file_takes_the_first_operand_as_input() { + let ts = uutests::util::TestScenario::new("awk"); + ts.fixtures.write("prog.awk", "{ print FILENAME, $0 }\n"); + ts.fixtures.write("in.txt", "one\n"); + ts.cmd(crate::TESTS_BINARY) + .args(&["-f", "prog.awk", "in.txt"]) + .succeeds() + .stdout_only("in.txt one\n"); +} + +#[test] +fn source_option_is_the_program() { + ucmd() + .args(&["--source", "BEGIN { print \"via --source\" }"]) + .succeeds() + .stdout_only("via --source\n"); +} + +#[test] +fn source_texts_end_with_a_newline() { + ucmd() + .args(&["-e", "NR == 1", "-e", "{ print \"every\" }"]) + .pipe_in("first\nsecond\n") + .succeeds() + .stdout_only("first\nevery\nevery\n"); +} + +#[test] +fn source_texts_are_parsed_one_by_one() { + // gawk rejects a rule split across two -e texts too. + ucmd() + .args(&["-e", "BEGIN {", "-e", "print \"spanned\" }"]) + .fails_with_code(1) + .stderr_contains("Syntax error") + .no_stdout(); +} + +#[test] +fn source_text_errors_count_lines_from_their_own_text() { + ucmd() + .args(&["-e", "BEGIN { print 1 }", "-e", "BEGIN { x = }"]) + .fails_with_code(1) + .stderr_contains("CLI:1:13") + .stderr_contains("BEGIN { x = }") + .no_stdout(); +} + +#[test] +fn each_source_text_starts_in_the_awk_namespace() { + ucmd() + .args(&[ + "-e", + "@namespace \"foo\"\nfunction g() { return \"foo\" }", + "-e", + "function g() { return \"awk\" }\nBEGIN { print g(), foo::g() }", + ]) + .succeeds() + .stdout_only("awk foo\n"); +} + +#[test] +fn program_files_and_source_texts_run_in_command_line_order() { + let ts = uutests::util::TestScenario::new("awk"); + ts.fixtures + .write("prog.awk", "BEGIN { print \"from -f\" }\n"); + ts.cmd(crate::TESTS_BINARY) + .args(&[ + "--source", + "BEGIN { print \"from --source\" }", + "-f", + "prog.awk", + ]) + .succeeds() + .stdout_only("from --source\nfrom -f\n"); + ts.cmd(crate::TESTS_BINARY) + .args(&[ + "-f", + "prog.awk", + "--source", + "BEGIN { print \"from --source\" }", + ]) + .succeeds() + .stdout_only("from -f\nfrom --source\n"); +} + +#[test] +fn unreadable_include_is_reported_without_a_panic() { + let ts = uutests::util::TestScenario::new("awk"); + ts.fixtures + .write("prog.awk", "@include \"no-such-include.awk\"\n"); + ts.cmd(crate::TESTS_BINARY) + .args(&["-f", "prog.awk"]) + .fails_with_code(1) + .stderr_contains( + "cannot open source file `no-such-include.awk' for reading: No such file or directory", + ) + .stderr_does_not_contain("panicked") + .no_stdout(); +} + +#[test] +fn source_option_takes_the_first_operand_as_input() { + let ts = uutests::util::TestScenario::new("awk"); + ts.fixtures.write("in.txt", "one\n"); + ts.cmd(crate::TESTS_BINARY) + .args(&["--source", "{ print FILENAME, $0 }", "in.txt"]) + .succeeds() + .stdout_only("in.txt one\n"); +} + #[test] fn switch_default_in_middle_fallthrough() { ucmd()