From fa3a3271ee8d2514cf96e6a7733312a958a78962 Mon Sep 17 00:00:00 2001 From: René Kijewski Date: Tue, 1 Aug 2023 03:53:15 +0200 Subject: parser: add type for `Node::Let` --- askama_parser/src/lib.rs | 2 +- askama_parser/src/node.rs | 58 +++++++++++++++++++++++++++-------------------- 2 files changed, 34 insertions(+), 26 deletions(-) (limited to 'askama_parser') diff --git a/askama_parser/src/lib.rs b/askama_parser/src/lib.rs index c0650ee..560507a 100644 --- a/askama_parser/src/lib.rs +++ b/askama_parser/src/lib.rs @@ -16,7 +16,7 @@ use nom::{error_position, AsChar, IResult, InputTakeAtPosition}; pub use self::expr::Expr; pub use self::node::{ - BlockDef, Call, Cond, CondTest, Import, Lit, Loop, Macro, Match, Node, Raw, Target, When, + BlockDef, Call, Cond, CondTest, Import, Let, Lit, Loop, Macro, Match, Node, Raw, Target, When, Whitespace, Ws, }; diff --git a/askama_parser/src/node.rs b/askama_parser/src/node.rs index ebab746..9055d99 100644 --- a/askama_parser/src/node.rs +++ b/askama_parser/src/node.rs @@ -20,8 +20,7 @@ pub enum Node<'a> { Comment(Ws), Expr(Ws, Expr<'a>), Call(Call<'a>), - LetDecl(Ws, Target<'a>), - Let(Ws, Target<'a>, Expr<'a>), + Let(Let<'a>), Cond(Vec>, Ws), Match(Match<'a>), Loop(Loop<'a>), @@ -50,7 +49,7 @@ impl<'a> Node<'a> { |i| s.tag_block_start(i), alt(( map(Call::parse, Self::Call), - Self::r#let, + map(Let::parse, Self::Let), |i| Self::r#if(i, s), |i| Self::r#for(i, s), map(|i| Match::parse(i, s), Self::Match), @@ -69,28 +68,6 @@ impl<'a> Node<'a> { Ok((i, contents)) } - fn r#let(i: &'a str) -> IResult<&'a str, Self> { - let mut p = tuple(( - opt(Whitespace::parse), - ws(alt((keyword("let"), keyword("set")))), - cut(tuple(( - ws(Target::parse), - opt(tuple((ws(char('=')), ws(Expr::parse)))), - opt(Whitespace::parse), - ))), - )); - let (i, (pws, _, (var, val, nws))) = p(i)?; - - Ok(( - i, - if let Some((_, val)) = val { - Self::Let(Ws(pws, nws), var, val) - } else { - Self::LetDecl(Ws(pws, nws), var) - }, - )) - } - fn r#if(i: &'a str, s: &State<'_>) -> IResult<&'a str, Self> { let mut p = tuple(( opt(Whitespace::parse), @@ -821,6 +798,37 @@ impl<'a> Raw<'a> { } } +#[derive(Debug, PartialEq)] +pub struct Let<'a> { + pub ws: Ws, + pub var: Target<'a>, + pub val: Option>, +} + +impl<'a> Let<'a> { + fn parse(i: &'a str) -> IResult<&'a str, Self> { + let mut p = tuple(( + opt(Whitespace::parse), + ws(alt((keyword("let"), keyword("set")))), + cut(tuple(( + ws(Target::parse), + opt(preceded(ws(char('=')), ws(Expr::parse))), + opt(Whitespace::parse), + ))), + )); + let (i, (pws, _, (var, val, nws))) = p(i)?; + + Ok(( + i, + Let { + ws: Ws(pws, nws), + var, + val, + }, + )) + } +} + /// First field is "minus/plus sign was used on the left part of the item". /// /// Second field is "minus/plus sign was used on the right part of the item". -- cgit