parser: better error message for unknown nodes

This commit is contained in:
René Kijewski 2023-08-02 10:18:21 +02:00 committed by Dirkjan Ochtman
parent 04e585b9d2
commit d09041bd0a
2 changed files with 8 additions and 9 deletions

View File

@ -8,10 +8,10 @@ use nom::branch::alt;
use nom::bytes::complete::{escaped, is_not, tag, take_till}; use nom::bytes::complete::{escaped, is_not, tag, take_till};
use nom::character::complete::char; use nom::character::complete::char;
use nom::character::complete::{anychar, digit1}; use nom::character::complete::{anychar, digit1};
use nom::combinator::{map, opt, recognize, value}; use nom::combinator::{cut, eof, map, opt, recognize, value};
use nom::error::ErrorKind; use nom::error::ErrorKind;
use nom::multi::separated_list1; use nom::multi::separated_list1;
use nom::sequence::{delimited, pair, tuple}; use nom::sequence::{delimited, pair, terminated, tuple};
use nom::{error_position, AsChar, IResult, InputTakeAtPosition}; use nom::{error_position, AsChar, IResult, InputTakeAtPosition};
pub mod expr; pub mod expr;
@ -75,11 +75,10 @@ pub struct Ast<'a> {
impl<'a> Ast<'a> { impl<'a> Ast<'a> {
pub fn from_str(src: &'a str, syntax: &Syntax<'_>) -> Result<Self, ParseError> { pub fn from_str(src: &'a str, syntax: &Syntax<'_>) -> Result<Self, ParseError> {
let err = match Node::many(src, &State::new(syntax)) { let parse = |i: &'a str| Node::many(i, &State::new(syntax));
Ok((left, nodes)) => match left.is_empty() { let err = match terminated(parse, cut(eof))(src) {
true => return Ok(Self { nodes }), Ok(("", nodes)) => return Ok(Self { nodes }),
false => return Err(ParseError(format!("unable to parse template:\n\n{left:?}"))), Ok(_) => unreachable!("eof() is not eof?"),
},
Err(nom::Err::Error(err)) | Err(nom::Err::Failure(err)) => err, Err(nom::Err::Error(err)) | Err(nom::Err::Failure(err)) => err,
Err(nom::Err::Incomplete(_)) => return Err(ParseError("parsing incomplete".into())), Err(nom::Err::Incomplete(_)) => return Err(ParseError("parsing incomplete".into())),
}; };
@ -93,7 +92,7 @@ impl<'a> Ast<'a> {
_ => format!("{source_after:?}"), _ => format!("{source_after:?}"),
}; };
let (row, last_line) = source_before.lines().enumerate().last().unwrap(); let (row, last_line) = source_before.lines().enumerate().last().unwrap_or_default();
let column = last_line.chars().count(); let column = last_line.chars().count();
let msg = format!( let msg = format!(

View File

@ -702,7 +702,7 @@ fn test_missing_space_after_kw() {
let err = Ast::from_str("{%leta=b%}", &syntax).unwrap_err(); let err = Ast::from_str("{%leta=b%}", &syntax).unwrap_err();
assert!(matches!( assert!(matches!(
&*err.to_string(), &*err.to_string(),
"unable to parse template:\n\n\"{%leta=b%}\"" "problems parsing template source at row 1, column 0 near:\n\"{%leta=b%}\"",
)); ));
} }