From dcfa5e1c694bdcb237801eb09398d70f98a39a97 Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Sun, 2 Jul 2023 11:30:02 +0200 Subject: parser: simplify top-level parser match --- askama_parser/src/lib.rs | 53 ++++++++++++++++++++++-------------------------- 1 file changed, 24 insertions(+), 29 deletions(-) (limited to 'askama_parser/src') diff --git a/askama_parser/src/lib.rs b/askama_parser/src/lib.rs index 9559ee0..ab3eb83 100644 --- a/askama_parser/src/lib.rs +++ b/askama_parser/src/lib.rs @@ -63,40 +63,35 @@ pub struct Ast<'a> { impl<'a> Ast<'a> { pub fn from_str(src: &'a str, syntax: &Syntax<'_>) -> Result { - match Node::parse(src, &State::new(syntax)) { - Ok((left, nodes)) => { - if !left.is_empty() { - Err(ParseError(format!("unable to parse template:\n\n{left:?}"))) - } else { - Ok(Self { nodes }) - } - } - - Err(nom::Err::Error(err)) | Err(nom::Err::Failure(err)) => { - let nom::error::Error { input, .. } = err; - let offset = src.len() - input.len(); - let (source_before, source_after) = src.split_at(offset); + let err = match Node::parse(src, &State::new(syntax)) { + Ok((left, nodes)) => match left.is_empty() { + true => return Ok(Self { nodes }), + false => return Err(ParseError(format!("unable to parse template:\n\n{left:?}"))), + }, + Err(nom::Err::Error(err)) | Err(nom::Err::Failure(err)) => err, + Err(nom::Err::Incomplete(_)) => return Err(ParseError("parsing incomplete".into())), + }; - let source_after = match source_after.char_indices().enumerate().take(41).last() { - Some((40, (i, _))) => format!("{:?}...", &source_after[..i]), - _ => format!("{source_after:?}"), - }; + let nom::error::Error { input, .. } = err; + let offset = src.len() - input.len(); + let (source_before, source_after) = src.split_at(offset); - let (row, last_line) = source_before.lines().enumerate().last().unwrap(); - let column = last_line.chars().count(); + let source_after = match source_after.char_indices().enumerate().take(41).last() { + Some((40, (i, _))) => format!("{:?}...", &source_after[..i]), + _ => format!("{source_after:?}"), + }; - let msg = format!( - "problems parsing template source at row {}, column {} near:\n{}", - row + 1, - column, - source_after, - ); + let (row, last_line) = source_before.lines().enumerate().last().unwrap(); + let column = last_line.chars().count(); - Err(ParseError(msg)) - } + let msg = format!( + "problems parsing template source at row {}, column {} near:\n{}", + row + 1, + column, + source_after, + ); - Err(nom::Err::Incomplete(_)) => Err(ParseError("parsing incomplete".into())), - } + Err(ParseError(msg)) } } -- cgit