Skip to content

Commit

Permalink
Don't panic on parse error at EOF in macro grammar
Browse files Browse the repository at this point in the history
Fixes #376
  • Loading branch information
kevinmehall committed Jun 2, 2024
1 parent ffcead2 commit d888952
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 2 deletions.
7 changes: 6 additions & 1 deletion peg-macros/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ extern crate proc_macro;
extern crate proc_macro2;
extern crate quote;

use peg::Parse;
use quote::quote_spanned;

// This can't use the `peg` crate as it would be a circular dependency, but the generated code in grammar.rs
Expand All @@ -23,7 +24,11 @@ pub fn parser(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let grammar = match grammar::peg::peg_grammar(&tokens) {
Ok(g) => g,
Err(err) => {
let msg = format!("expected {}", err.expected);
let msg = if tokens.is_eof(err.location.1) {
format!("expected {} at end of input", err.expected)
} else {
format!("expected {}", err.expected)
};
return quote_spanned!(err.location.0=> compile_error!(#msg);).into();
}
};
Expand Down
7 changes: 6 additions & 1 deletion peg-macros/tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,12 @@ impl Parse for FlatTokenStream {
}

fn position_repr(&self, pos: usize) -> Sp {
Sp(self.tokens[pos].span(), pos)
let span = self.tokens.get(pos)
.map_or_else(
|| Span::call_site(),
|t| t.span()
);
Sp(span, pos)
}
}

Expand Down
8 changes: 8 additions & 0 deletions tests/compile-fail/incomplete_grammar.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@

peg::parser!();

peg::parser!(
grammar parser() for str
);

fn main() {}
17 changes: 17 additions & 0 deletions tests/compile-fail/incomplete_grammar.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
error: expected one of "#", "grammar", "pub" at end of input
--> tests/compile-fail/incomplete_grammar.rs:2:1
|
2 | peg::parser!();
| ^^^^^^^^^^^^^^
|
= note: this error originates in the macro `peg::parser` (in Nightly builds, run with -Z macro-backtrace for more info)

error: expected one of "::", "<", "{" at end of input
--> tests/compile-fail/incomplete_grammar.rs:4:1
|
4 | / peg::parser!(
5 | | grammar parser() for str
6 | | );
| |_^
|
= note: this error originates in the macro `peg::parser` (in Nightly builds, run with -Z macro-backtrace for more info)

0 comments on commit d888952

Please sign in to comment.