From 3e7983d7af8d19393507e50778b818f8dcf24b91 Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Tue, 3 Jan 2017 09:56:08 +0100 Subject: Extend parser to allow different expression types --- askama_codegen/src/generator.rs | 12 +++++++++--- askama_codegen/src/parser.rs | 12 +++++++++--- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/askama_codegen/src/generator.rs b/askama_codegen/src/generator.rs index 34c9757..b1babce 100644 --- a/askama_codegen/src/generator.rs +++ b/askama_codegen/src/generator.rs @@ -1,4 +1,4 @@ -use parser::Node; +use parser::{Expr, Node}; use std::str; struct Generator { @@ -56,18 +56,24 @@ impl Generator { self.writeln(");"); } - fn visit_expr(&mut self, s: &[u8]) { + fn visit_var(&mut self, s: &[u8]) { let var_name = str::from_utf8(s).unwrap(); let code = format!("std::fmt::Write::write_fmt(\ &mut buf, format_args!(\"{{}}\", self.{})).unwrap();", var_name); self.writeln(&code); } + fn visit_expr(&mut self, expr: &Expr) { + match expr { + &Expr::Var(s) => self.visit_var(s), + } + } + fn handle(&mut self, tokens: &Vec) { for n in tokens { match n { &Node::Lit(val) => { self.visit_lit(val); }, - &Node::Expr(val) => { self.visit_expr(val); }, + &Node::Expr(ref val) => { self.visit_expr(&val); }, } } } diff --git a/askama_codegen/src/parser.rs b/askama_codegen/src/parser.rs index b7a712b..5f3f8c5 100644 --- a/askama_codegen/src/parser.rs +++ b/askama_codegen/src/parser.rs @@ -1,8 +1,12 @@ use nom::{self, IResult}; +pub enum Expr<'a> { + Var(&'a [u8]), +} + pub enum Node<'a> { Lit(&'a [u8]), - Expr(&'a [u8]), + Expr(Expr<'a>), } fn take_content(i: &[u8]) -> IResult<&[u8], Node> { @@ -23,9 +27,11 @@ fn take_content(i: &[u8]) -> IResult<&[u8], Node> { IResult::Done(&i[..0], Node::Lit(&i[..])) } -named!(expr_str, delimited!(tag!("{{"), take_until!("}}"), tag!("}}"))); +named!(expr_var, map!(ws!(nom::alphanumeric), Expr::Var)); + +named!(any_expr, delimited!(tag!("{{"), expr_var, tag!("}}"))); -named!(expr_node, map!(expr_str, Node::Expr)); +named!(expr_node, map!(any_expr, Node::Expr)); named!(parse_template< Vec >, many1!(alt!(take_content | expr_node))); -- cgit