From 883887197c13f17341696029d8ebdb35a7942ddf Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Thu, 19 Nov 2026 05:00:46 +0530 Subject: [PATCH 1/4] awk: report an unreadable -f file and run --source programs -f with a file that can't be read panicked, and --source was ignored. Read the -f files and --source texts in command-line order like gawk, keeping adjacent --source texts together so a construct can span them. A -f file that can't be read is fatal with gawk's message and status 2; an @include that can't be read is a diagnostic at its path. With -f or --source there is no program operand, so the first operand is an input. --- parser/src/diagnostics.rs | 3 ++ parser/src/lib.rs | 101 ++++++++++++++++++++++++++++++++------ src/cli.rs | 26 +++++----- src/main.rs | 82 +++++++++++++++++++++++++++---- src/utils.rs | 6 +++ tests/by-util/test_awk.rs | 90 +++++++++++++++++++++++++++++++++ 6 files changed, 271 insertions(+), 37 deletions(-) diff --git a/parser/src/diagnostics.rs b/parser/src/diagnostics.rs index 0ed908c..71a1879 100644 --- a/parser/src/diagnostics.rs +++ b/parser/src/diagnostics.rs @@ -177,6 +177,8 @@ pub enum ParsingError { NextInForbiddenCtx(Span), #[error("`nextfile` is forbidden in BEGIN, END, and ENDFILE rules!")] NextFileInForbiddenCtx(Span), + #[error("cannot open source file `{}' for reading: {}", .1, .2)] + CannotOpenSource(Span, String, String), } impl ParsingError { @@ -226,6 +228,7 @@ impl ParsingError { | &Self::ReturnOutsideFunction(span) | &Self::CommandDoubleCall(span, _) | &Self::NextInForbiddenCtx(span) + | &Self::CannotOpenSource(span, ..) | &Self::NextFileInForbiddenCtx(span) => Some(span), } } diff --git a/parser/src/lib.rs b/parser/src/lib.rs index 5b86df1..041a180 100644 --- a/parser/src/lib.rs +++ b/parser/src/lib.rs @@ -13,9 +13,11 @@ mod sexpr; mod tests; use std::{ + borrow::Cow, fs::File, + io, mem::{replace, take}, - path::{Path, PathBuf}, + path::Path, rc::Rc, }; @@ -154,8 +156,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 +166,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)?; @@ -962,9 +966,31 @@ 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(path, source, ns), + Err(err) => { + let reason = read_reason(&err).into_owned(); + let error = + ParsingError::CannotOpenSource(span, path.display().to_string(), reason); + (Err(error), FileCache(None)) + } + } + } + + fn include_source( + &mut self, + path: Rc, + 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; @@ -981,10 +1007,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 program pieces in command-line order, as gawk reads `-f` files + /// and `--source` texts. + pub fn include_many( + &mut self, + sources: &[ProgramSource<'_>], + ) -> std::result::Result<&mut Ast<'a>, IncludeError> { + for source in sources { + let (path, source): (Rc, &'a [u8]) = match source { + ProgramSource::File(path) => { + let path = Rc::from(*path); + match self.preprocessor.read_to_arena(&path, self.arena) { + Ok(source) => (path, source), + Err(err) => return Err(IncludeError::CannotOpen { path, err }), + } + } + // gawk names command-line program text this way in its messages. + ProgramSource::Text(text) => ( + Rc::from(Path::new("cmd. line")), + self.arena.alloc_slice_copy(text), + ), + }; + let (res, file) = self.include_source(path, source, Some(StaticInterner::awk_ident())); if let Err(error) = res { error.add_diagnostic_cached( @@ -995,13 +1039,38 @@ 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. +pub enum ProgramSource<'s> { + File(&'s Path), + Text(std::vec::Vec), +} + +/// Why [`Parser::include_many`] has no program to run. +#[derive(Debug, thiserror::Error)] +pub enum IncludeError { + #[error("cannot open source file `{}' for reading: {}", .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 +1093,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,7 +1110,7 @@ fn make_path(blob: BlobId) -> Rc { #[cfg(not(unix))] fn make_path(blob: BlobId) -> Rc { - use std::borrow::Cow; + use std::path::PathBuf; StaticInterner::resolve(blob, |s| match String::from_utf8_lossy(s) { Cow::Borrowed(s) => Rc::from(Path::new(s)), diff --git a/src/cli.rs b/src/cli.rs index 0e1a8e3..946d6ee 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -25,11 +25,7 @@ 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 = "-" - )] + #[arg(trailing_var_arg = true, allow_hyphen_values = true)] pub read_queue: Vec, #[arg(short = 'f', long)] pub file: Vec, @@ -110,6 +106,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 +207,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..2b73e3a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,14 +18,14 @@ use std::{ }; use bumpalo::Bump; -use clap::Parser as ClapParser; +use clap::{CommandFactory, FromArgMatches}; use interpreter::{CodeGen, ExecMode, Interpreter}; -use parser::{FileCache, Parser}; +use parser::{FileCache, IncludeError, Parser, ProgramSource}; use crate::{ - cli::{Args, KeyValue}, + cli::{ArgQueueItem, Args, KeyValue}, event::AwkRt, - utils::{AWK_FATAL_CODE, EXIT_FAILURE, ensure_consistent_panic, exit_err}, + utils::{AWK_FATAL_CODE, EXIT_FAILURE, ensure_consistent_panic, exit_err, exit_fatal}, }; fn main() { @@ -35,23 +35,50 @@ fn main() { } fn uu_main() -> Result<(), Box> { - let args = match Args::try_parse_from(args_os()) { - Ok(args) => args, + // The matches keep each option's position, which orders -f and --source. + let matches = match Args::command().try_get_matches_from(args_os()) { + Ok(matches) => matches, Err(msg) => { msg.print()?; exit_err(Option::<&str>::None, EXIT_FAILURE) } }; + let mut args = Args::from_arg_matches(&matches)?; + + // With -f or --source there is no program operand: the first operand is an input. + if (!args.file.is_empty() || !args.source.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); + } + + // Like gawk, each --source text is read as if it ended with a newline. + let mut source_text = Vec::new(); + for text in &args.source { + source_text.extend_from_slice(text.as_encoded_bytes()); + source_text.push(b'\n'); + } 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 code = args.code.as_ref().unwrap(); - parser.parse(FileCache(None), code.as_encoded_bytes()) + let code = match &args.code { + Some(code) => code.as_encoded_bytes(), + None => &source_text, + }; + parser.parse(FileCache(None), code) } else { - parser.include_many(&args.file) + match parser.include_many(&program_sources(&matches, &args)) { + Ok(ast) => Ok(ast), + Err(IncludeError::Invalid(diagnostics)) => Err(diagnostics), + Err(err) => exit_fatal(err), + } }; let ast = match ast { Ok(ast) => ast, @@ -125,3 +152,40 @@ fn uu_main() -> Result<(), Box> { Ok(()) } + +/// The -f files and --source texts in command-line order, as gawk reads them. +/// Adjacent --source texts stay one piece, so a construct can span them. +fn program_sources<'a>(matches: &clap::ArgMatches, args: &'a Args) -> Vec> { + let files = matches + .indices_of("file") + .into_iter() + .flatten() + .zip(&args.file); + let texts = matches + .indices_of("source") + .into_iter() + .flatten() + .zip(&args.source); + let mut pieces: Vec<(usize, Option<&'a std::path::Path>, &'a [u8])> = files + .map(|(i, path)| (i, Some(path.as_path()), &[][..])) + .chain(texts.map(|(i, text)| (i, None, text.as_encoded_bytes()))) + .collect(); + pieces.sort_by_key(|&(i, ..)| i); + + let mut sources = Vec::new(); + for (_, path, text) in pieces { + match (path, sources.last_mut()) { + (Some(path), _) => sources.push(ProgramSource::File(path)), + (None, Some(ProgramSource::Text(joined))) => { + joined.extend_from_slice(text); + joined.push(b'\n'); + } + (None, _) => { + let mut joined = text.to_vec(); + joined.push(b'\n'); + sources.push(ProgramSource::Text(joined)); + } + } + } + sources +} diff --git a/src/utils.rs b/src/utils.rs index 2fa96ac..0744e5d 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -65,3 +65,9 @@ pub fn exit_err(err: Option, code: i32) -> ! { } exit(code) } + +/// Prints a fatal error and exits with 2, gawk's status for fatal errors. +pub fn exit_fatal(msg: impl Display) -> ! { + let _ = writeln!(io::stderr(), "awk: fatal: {msg}"); + exit(AWK_FATAL_CODE) +} diff --git a/tests/by-util/test_awk.rs b/tests/by-util/test_awk.rs index 947d5ae..91801e2 100644 --- a/tests/by-util/test_awk.rs +++ b/tests/by-util/test_awk.rs @@ -59,6 +59,96 @@ 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 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"]) + .run() + .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() From 639ee3257b4673c19bb22d15947fc63864c331ff Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Mon, 23 Nov 2026 14:10:35 +0530 Subject: [PATCH 2/4] awk: parse each --source text on its own Each -f file and --source text is now its own piece in include_many, so an error's line number counts from the start of its own text and each text starts in the awk namespace, like gawk. FileCache gets a Cli(n) variant so every --source text has its own diagnostics entry. The order of -f and --source now comes from a clap Args impl, so main.rs no longer reads the arg matches. --source texts are borrowed from the arguments instead of copied into the arena. --- interpreter/src/builtins.rs | 2 +- interpreter/src/ir/tests.rs | 2 +- parser/src/diagnostics.rs | 14 +++++--- parser/src/lib.rs | 50 +++++++++++++-------------- parser/src/tests.rs | 10 +++--- src/cli.rs | 69 ++++++++++++++++++++++++++++++++++--- src/main.rs | 67 +++++------------------------------ tests/by-util/test_awk.rs | 33 ++++++++++++++++++ 8 files changed, 148 insertions(+), 99 deletions(-) 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 71a1879..8a62573 100644 --- a/parser/src/diagnostics.rs +++ b/parser/src/diagnostics.rs @@ -297,19 +297,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 041a180..de46fbe 100644 --- a/parser/src/lib.rs +++ b/parser/src/lib.rs @@ -14,10 +14,11 @@ mod tests; use std::{ borrow::Cow, + ffi::OsString, fs::File, io, mem::{replace, take}, - path::Path, + path::{Path, PathBuf}, rc::Rc, }; @@ -69,7 +70,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, @@ -954,11 +955,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); @@ -974,19 +975,19 @@ impl<'a> Parser<'a> { ns: Option, ) -> (Result<()>, FileCache) { match self.preprocessor.read_to_arena(&path, self.arena) { - Ok(source) => self.include_source(path, source, ns), + 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), FileCache(None)) + (Err(error), self.file.clone()) } } } fn include_source( &mut self, - path: Rc, + file: FileCache, source: &'a [u8], ns: Option, ) -> (Result<()>, FileCache) { @@ -996,7 +997,7 @@ impl<'a> Parser<'a> { 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, @@ -1007,28 +1008,28 @@ impl<'a> Parser<'a> { (Ok(()), file) } - /// Parses the program pieces in command-line order, as gawk reads `-f` files - /// and `--source` texts. + /// 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: &[ProgramSource<'_>], + sources: &'a [ProgramSource], ) -> std::result::Result<&mut Ast<'a>, IncludeError> { + let mut texts = 0; for source in sources { - let (path, source): (Rc, &'a [u8]) = match source { + let (file, source) = match source { ProgramSource::File(path) => { - let path = Rc::from(*path); + let path = Rc::from(path.as_path()); match self.preprocessor.read_to_arena(&path, self.arena) { - Ok(source) => (path, source), + Ok(source) => (FileCache::new_file(path), source), Err(err) => return Err(IncludeError::CannotOpen { path, err }), } } - // gawk names command-line program text this way in its messages. - ProgramSource::Text(text) => ( - Rc::from(Path::new("cmd. line")), - self.arena.alloc_slice_copy(text), - ), + ProgramSource::Text(text) => { + texts += 1; + (FileCache::Cli(texts - 1), text.as_encoded_bytes()) + } }; - let (res, file) = self.include_source(path, source, Some(StaticInterner::awk_ident())); + let (res, file) = self.include_source(file, source, Some(StaticInterner::awk_ident())); if let Err(error) = res { error.add_diagnostic_cached( @@ -1047,9 +1048,10 @@ impl<'a> Parser<'a> { } /// One piece of the program: a `-f` file, or `--source` text. -pub enum ProgramSource<'s> { - File(&'s Path), - Text(std::vec::Vec), +#[derive(Clone, Debug)] +pub enum ProgramSource { + File(PathBuf), + Text(OsString), } /// Why [`Parser::include_many`] has no program to run. @@ -1110,8 +1112,6 @@ fn make_path(blob: BlobId) -> Rc { #[cfg(not(unix))] fn make_path(blob: BlobId) -> Rc { - use std::path::PathBuf; - 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 946d6ee..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,10 +27,10 @@ use memchr::memchr; pub struct Args { #[arg(required_unless_present_any = ["file", "source"])] pub code: Option, + #[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)] @@ -49,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)] @@ -99,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), diff --git a/src/main.rs b/src/main.rs index 2b73e3a..c21903f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,9 +18,9 @@ use std::{ }; use bumpalo::Bump; -use clap::{CommandFactory, FromArgMatches}; +use clap::Parser as ClapParser; use interpreter::{CodeGen, ExecMode, Interpreter}; -use parser::{FileCache, IncludeError, Parser, ProgramSource}; +use parser::{FileCache, IncludeError, Parser}; use crate::{ cli::{ArgQueueItem, Args, KeyValue}, @@ -35,18 +35,16 @@ fn main() { } fn uu_main() -> Result<(), Box> { - // The matches keep each option's position, which orders -f and --source. - let matches = match Args::command().try_get_matches_from(args_os()) { - Ok(matches) => matches, + let mut args = match Args::try_parse_from(args_os()) { + Ok(args) => args, Err(msg) => { msg.print()?; exit_err(Option::<&str>::None, EXIT_FAILURE) } }; - let mut args = Args::from_arg_matches(&matches)?; // With -f or --source there is no program operand: the first operand is an input. - if (!args.file.is_empty() || !args.source.is_empty()) + if !args.program.0.is_empty() && let Some(operand) = args.code.take() { args.read_queue @@ -56,25 +54,15 @@ fn uu_main() -> Result<(), Box> { args.read_queue.push(ArgQueueItem::Stdio); } - // Like gawk, each --source text is read as if it ended with a newline. - let mut source_text = Vec::new(); - for text in &args.source { - source_text.extend_from_slice(text.as_encoded_bytes()); - source_text.push(b'\n'); - } - 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 code = match &args.code { - Some(code) => code.as_encoded_bytes(), - None => &source_text, - }; - parser.parse(FileCache(None), code) + let ast = if args.program.0.is_empty() { + let code = args.code.as_ref().unwrap(); + parser.parse(FileCache::Cli(0), code.as_encoded_bytes()) } else { - match parser.include_many(&program_sources(&matches, &args)) { + match parser.include_many(&args.program.0) { Ok(ast) => Ok(ast), Err(IncludeError::Invalid(diagnostics)) => Err(diagnostics), Err(err) => exit_fatal(err), @@ -152,40 +140,3 @@ fn uu_main() -> Result<(), Box> { Ok(()) } - -/// The -f files and --source texts in command-line order, as gawk reads them. -/// Adjacent --source texts stay one piece, so a construct can span them. -fn program_sources<'a>(matches: &clap::ArgMatches, args: &'a Args) -> Vec> { - let files = matches - .indices_of("file") - .into_iter() - .flatten() - .zip(&args.file); - let texts = matches - .indices_of("source") - .into_iter() - .flatten() - .zip(&args.source); - let mut pieces: Vec<(usize, Option<&'a std::path::Path>, &'a [u8])> = files - .map(|(i, path)| (i, Some(path.as_path()), &[][..])) - .chain(texts.map(|(i, text)| (i, None, text.as_encoded_bytes()))) - .collect(); - pieces.sort_by_key(|&(i, ..)| i); - - let mut sources = Vec::new(); - for (_, path, text) in pieces { - match (path, sources.last_mut()) { - (Some(path), _) => sources.push(ProgramSource::File(path)), - (None, Some(ProgramSource::Text(joined))) => { - joined.extend_from_slice(text); - joined.push(b'\n'); - } - (None, _) => { - let mut joined = text.to_vec(); - joined.push(b'\n'); - sources.push(ProgramSource::Text(joined)); - } - } - } - sources -} diff --git a/tests/by-util/test_awk.rs b/tests/by-util/test_awk.rs index 91801e2..bcabf6e 100644 --- a/tests/by-util/test_awk.rs +++ b/tests/by-util/test_awk.rs @@ -99,6 +99,39 @@ fn source_texts_end_with_a_newline() { .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"); From fe17a9f9634462e77fa8068c98cfe1186b6b157c Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Wed, 25 Nov 2026 17:53:30 +0530 Subject: [PATCH 3/4] awk: share the cannot-open message and exit fatal from main --- parser/src/diagnostics.rs | 7 ++++++- parser/src/lib.rs | 6 ++++-- src/main.rs | 4 ++-- src/utils.rs | 6 ------ 4 files changed, 12 insertions(+), 11 deletions(-) diff --git a/parser/src/diagnostics.rs b/parser/src/diagnostics.rs index 8a62573..6cc5f54 100644 --- a/parser/src/diagnostics.rs +++ b/parser/src/diagnostics.rs @@ -177,10 +177,15 @@ pub enum ParsingError { NextInForbiddenCtx(Span), #[error("`nextfile` is forbidden in BEGIN, END, and ENDFILE rules!")] NextFileInForbiddenCtx(Span), - #[error("cannot open source file `{}' for reading: {}", .1, .2)] + #[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 { pub const fn span(&self) -> Option { match self { diff --git a/parser/src/lib.rs b/parser/src/lib.rs index de46fbe..024554b 100644 --- a/parser/src/lib.rs +++ b/parser/src/lib.rs @@ -32,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}; @@ -1057,7 +1059,7 @@ pub enum ProgramSource { /// Why [`Parser::include_many`] has no program to run. #[derive(Debug, thiserror::Error)] pub enum IncludeError { - #[error("cannot open source file `{}' for reading: {}", .path.display(), read_reason(.err))] + #[error("{}", cannot_open_source(.path.display(), read_reason(.err)))] CannotOpen { path: Rc, err: io::Error }, #[error("the program has errors")] Invalid(DiagnosticStore), diff --git a/src/main.rs b/src/main.rs index c21903f..4dfd50b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -25,7 +25,7 @@ use parser::{FileCache, IncludeError, Parser}; use crate::{ cli::{ArgQueueItem, Args, KeyValue}, event::AwkRt, - utils::{AWK_FATAL_CODE, EXIT_FAILURE, ensure_consistent_panic, exit_err, exit_fatal}, + utils::{AWK_FATAL_CODE, EXIT_FAILURE, ensure_consistent_panic, exit_err}, }; fn main() { @@ -65,7 +65,7 @@ fn uu_main() -> Result<(), Box> { match parser.include_many(&args.program.0) { Ok(ast) => Ok(ast), Err(IncludeError::Invalid(diagnostics)) => Err(diagnostics), - Err(err) => exit_fatal(err), + Err(err) => exit_err(Some(format!("awk: fatal: {err}")), AWK_FATAL_CODE), } }; let ast = match ast { diff --git a/src/utils.rs b/src/utils.rs index 0744e5d..2fa96ac 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -65,9 +65,3 @@ pub fn exit_err(err: Option, code: i32) -> ! { } exit(code) } - -/// Prints a fatal error and exits with 2, gawk's status for fatal errors. -pub fn exit_fatal(msg: impl Display) -> ! { - let _ = writeln!(io::stderr(), "awk: fatal: {msg}"); - exit(AWK_FATAL_CODE) -} From 151d222157587447a2a9fafc2171032f2c3234ad Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Wed, 25 Nov 2026 02:27:01 +0530 Subject: [PATCH 4/4] tests/awk: check the exit code of an unreadable @include gawk 5.4.2 reports it as an error and exits 1, not a fatal 2 like -f. --- tests/by-util/test_awk.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/by-util/test_awk.rs b/tests/by-util/test_awk.rs index bcabf6e..bb05544 100644 --- a/tests/by-util/test_awk.rs +++ b/tests/by-util/test_awk.rs @@ -164,7 +164,7 @@ fn unreadable_include_is_reported_without_a_panic() { .write("prog.awk", "@include \"no-such-include.awk\"\n"); ts.cmd(crate::TESTS_BINARY) .args(&["-f", "prog.awk"]) - .run() + .fails_with_code(1) .stderr_contains( "cannot open source file `no-such-include.awk' for reading: No such file or directory", )