From f16ddb14f09e470f902ea5cb93e749685dd89d6a Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Mon, 3 Jul 2023 09:27:04 +0200 Subject: parser: define a struct for Cond --- askama_derive/src/generator.rs | 8 ++++---- askama_derive/src/heritage.rs | 4 ++-- askama_parser/src/node.rs | 22 +++++++++++++++++++--- 3 files changed, 25 insertions(+), 9 deletions(-) diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs index 0c482b5..addde7a 100644 --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -718,8 +718,8 @@ impl<'a> Generator<'a> { let mut flushed = 0; let mut arm_sizes = Vec::new(); let mut has_else = false; - for (i, &(cws, ref cond, ref nodes)) in conds.iter().enumerate() { - self.handle_ws(cws); + for (i, cond) in conds.iter().enumerate() { + self.handle_ws(cond.ws); flushed += self.write_buf_writable(buf)?; if i > 0 { self.locals.pop(); @@ -727,7 +727,7 @@ impl<'a> Generator<'a> { self.locals.push(); let mut arm_size = 0; - if let Some(CondTest { target, expr }) = cond { + if let Some(CondTest { target, expr }) = &cond.cond { if i == 0 { buf.write("if "); } else { @@ -762,7 +762,7 @@ impl<'a> Generator<'a> { buf.writeln(" {")?; - arm_size += self.handle(ctx, nodes, buf, AstLevel::Nested)?; + arm_size += self.handle(ctx, &cond.block, buf, AstLevel::Nested)?; arm_sizes.push(arm_size); } self.handle_ws(ws); diff --git a/askama_derive/src/heritage.rs b/askama_derive/src/heritage.rs index 38c2cc8..66f1a1a 100644 --- a/askama_derive/src/heritage.rs +++ b/askama_derive/src/heritage.rs @@ -83,8 +83,8 @@ impl Context<'_> { } } Node::Cond(branches, _) => { - for (_, _, nodes) in branches { - nested.push(nodes); + for cond in branches { + nested.push(&cond.block); } } Node::Loop(Loop { diff --git a/askama_parser/src/node.rs b/askama_parser/src/node.rs index cd71efc..84b4911 100644 --- a/askama_parser/src/node.rs +++ b/askama_parser/src/node.rs @@ -149,7 +149,11 @@ impl<'a> Node<'a> { )); let (i, (pws1, cond, (nws1, _, (block, elifs, (_, pws2, _, nws2))))) = p(i)?; - let mut res = vec![(Ws(pws1, nws1), Some(cond), block)]; + let mut res = vec![Cond { + ws: Ws(pws1, nws1), + cond: Some(cond), + block, + }]; res.extend(elifs); Ok((i, Self::Cond(res, Ws(pws2, nws2)))) } @@ -593,7 +597,12 @@ pub struct Macro<'a> { #[derive(Clone, Copy, Debug, PartialEq)] pub struct Ws(pub Option, pub Option); -pub type Cond<'a> = (Ws, Option>, Vec>); +#[derive(Debug, PartialEq)] +pub struct Cond<'a> { + pub ws: Ws, + pub cond: Option>, + pub block: Vec>, +} #[derive(Debug, PartialEq)] pub struct CondTest<'a> { @@ -638,7 +647,14 @@ fn cond_block<'a>(i: &'a str, s: &State<'_>) -> IResult<&'a str, Cond<'a>> { ))), )); let (i, (_, pws, _, (cond, nws, _, block))) = p(i)?; - Ok((i, (Ws(pws, nws), cond, block))) + Ok(( + i, + Cond { + ws: Ws(pws, nws), + cond, + block, + }, + )) } fn match_else_block<'a>(i: &'a str, s: &State<'_>) -> IResult<&'a str, When<'a>> { -- cgit