From 05597b61daabfa1ab4c675c2943ceeefcb82db36 Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Wed, 16 Aug 2017 12:50:52 +0200 Subject: Allow separation of variable declaration and defintion --- askama_derive/src/generator.rs | 17 ++++++++++++++++- askama_derive/src/parser.rs | 14 +++++++++++--- 2 files changed, 27 insertions(+), 4 deletions(-) (limited to 'askama_derive/src') diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs index faf4e48..43c2a49 100644 --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -312,7 +312,7 @@ impl<'a> Generator<'a> { self.writeln("))?;"); } - fn write_let(&mut self, ws: &WS, var: &'a Target, val: &Expr) { + fn write_let_decl(&mut self, ws: &WS, var: &'a Target) { self.handle_ws(ws); self.write("let "); match *var { @@ -321,6 +321,20 @@ impl<'a> Generator<'a> { self.write(name); }, } + self.writeln(";"); + } + + fn write_let(&mut self, ws: &WS, var: &'a Target, val: &Expr) { + self.handle_ws(ws); + match *var { + Target::Name(name) => { + if !self.locals.contains(name) { + self.write("let "); + self.locals.insert(name); + } + self.write(name); + }, + } self.write(" = "); self.visit_expr(val); self.writeln(";"); @@ -417,6 +431,7 @@ impl<'a> Generator<'a> { Node::Lit(lws, val, rws) => { self.write_lit(lws, val, rws); } Node::Comment() => {}, Node::Expr(ref ws, ref val) => { self.write_expr(ws, val); }, + Node::LetDecl(ref ws, ref var) => { self.write_let_decl(ws, var); }, Node::Let(ref ws, ref var, ref val) => { self.write_let(ws, var, val); }, Node::Cond(ref conds, ref ws) => { self.write_cond(conds, ws); diff --git a/askama_derive/src/parser.rs b/askama_derive/src/parser.rs index 2a6a602..c6c437c 100644 --- a/askama_derive/src/parser.rs +++ b/askama_derive/src/parser.rs @@ -26,6 +26,7 @@ pub enum Node<'a> { Lit(&'a str, &'a str, &'a str), Comment(), Expr(WS, Expr<'a>), + LetDecl(WS, Target<'a>), Let(WS, Target<'a>, Expr<'a>), Cond(Vec<(WS, Option>, Vec>)>, WS), Loop(WS, Target<'a>, Expr<'a>, Vec>, WS), @@ -282,10 +283,17 @@ named!(block_let, do_parse!( pws: opt!(tag_s!("-")) >> ws!(tag_s!("let")) >> var: ws!(target_single) >> - ws!(tag_s!("=")) >> - val: ws!(expr_any) >> + val: opt!(do_parse!( + ws!(tag_s!("=")) >> + val: ws!(expr_any) >> + (val) + )) >> nws: opt!(tag_s!("-")) >> - (Node::Let(WS(pws.is_some(), nws.is_some()), var, val)) + (if val.is_some() { + Node::Let(WS(pws.is_some(), nws.is_some()), var, val.unwrap()) + } else { + Node::LetDecl(WS(pws.is_some(), nws.is_some()), var) + }) )); named!(block_for, do_parse!( -- cgit