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
2 changes: 1 addition & 1 deletion interpreter/src/builtins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion interpreter/src/ir/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
22 changes: 17 additions & 5 deletions parser/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -226,6 +233,7 @@ impl ParsingError {
| &Self::ReturnOutsideFunction(span)
| &Self::CommandDoubleCall(span, _)
| &Self::NextInForbiddenCtx(span)
| &Self::CannotOpenSource(span, ..)
| &Self::NextFileInForbiddenCtx(span) => Some(span),
}
}
Expand Down Expand Up @@ -294,19 +302,23 @@ impl ParsingError {
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct FileCache(pub Option<Rc<Path>>);
pub enum FileCache {
/// Program text from the command line: the program operand, or the nth `--source`.
Cli(usize),
File(Rc<Path>),
}

impl FileCache {
pub const fn new_file(f: Rc<Path>) -> 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"),
}
}
}
Expand Down
113 changes: 92 additions & 21 deletions parser/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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};
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -154,16 +159,18 @@ 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);
}
lex.expect_with(Token::is_stmnt_end, ParsingError::ExpectedStatementEnd)?;
}
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)?;
Expand Down Expand Up @@ -950,27 +957,49 @@ impl<'a> Parser<'a> {

fn enter_file<T>(
&mut self,
path: Rc<Path>,
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);

let ret = f(self, &mut lex);
(ret, replace(&mut self.file, old))
}

fn include(&mut self, path: Rc<Path>, ns: Option<IdentId>) -> (Result<()>, FileCache) {
/// `span` is the `@include` path's string, where a read error is reported.
fn include(
&mut self,
path: Rc<Path>,
span: Span,
ns: Option<IdentId>,
) -> (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<IdentId>,
) -> (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,
Expand All @@ -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(
Expand All @@ -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<Path>, 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 {
Expand All @@ -1024,11 +1097,11 @@ impl<'a> Ast<'a> {
struct Preprocessor {}

impl Preprocessor {
fn read_to_arena<'a>(&self, path: impl AsRef<Path>, 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<Path>, arena: &'a Bump) -> io::Result<&'a [u8]> {
Comment thread
Alonely0 marked this conversation as resolved.
Resolved
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())
}
}

Expand All @@ -1041,8 +1114,6 @@ fn make_path(blob: BlobId) -> Rc<Path> {

#[cfg(not(unix))]
fn make_path(blob: BlobId) -> Rc<Path> {
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)),
Expand Down
10 changes: 6 additions & 4 deletions parser/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!(
Expand All @@ -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!(
Expand All @@ -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());
}
Loading
Loading