From 2257afd356e6985244e702554aeda74af63b7ff1 Mon Sep 17 00:00:00 2001 From: Anthony Nowell Date: Wed, 1 Nov 2017 21:19:34 -0700 Subject: Support matching custom enums --- askama_shared/src/parser.rs | 46 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) (limited to 'askama_shared/src/parser.rs') diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs index 76125ef..338bf1e 100644 --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -15,6 +15,14 @@ pub enum Expr<'a> { MethodCall(Box>, &'a str, Vec>), } +#[derive(Debug)] +pub enum MatchVariant<'a> { + Path(Vec<&'a str>), + Name(&'a str), + NumLit(&'a str), + StrLit(&'a str), +} + #[derive(Debug)] pub enum MatchParameter<'a> { Name(&'a str), @@ -57,7 +65,7 @@ pub enum Node<'a> { } pub type Cond<'a> = (WS, Option>, Vec>); -pub type When<'a> = (WS, Option>, Vec>, Vec>); +pub type When<'a> = (WS, Option>, Vec>, Vec>); fn split_ws_parts(s: &[u8]) -> Node { if s.is_empty() { @@ -154,6 +162,10 @@ named!(expr_array_lit, do_parse!( }) )); +named!(variant_num_lit, map!(num_lit, + |s| MatchVariant::NumLit(s) +)); + named!(param_num_lit, map!(num_lit, |s| MatchParameter::NumLit(s) )); @@ -163,6 +175,11 @@ named!(expr_str_lit, map!( |s| Expr::StrLit(str::from_utf8(s).unwrap()) )); +named!(variant_str_lit, map!( + delimited!(char!('"'), is_not!("\""), char!('"')), + |s| MatchVariant::StrLit(str::from_utf8(s).unwrap()) +)); + named!(param_str_lit, map!( delimited!(char!('"'), is_not!("\""), char!('"')), |s| MatchParameter::StrLit(str::from_utf8(s).unwrap()) @@ -186,10 +203,28 @@ named!(expr_path, do_parse!( }) )); +named!(variant_path, do_parse!( + start: call!(identifier) >> + rest: many1!(do_parse!( + tag_s!("::") >> + part: identifier >> + (part) + )) >> + ({ + let mut path = vec![start]; + path.extend(rest); + MatchVariant::Path(path) + }) +)); + named!(target_single, map!(identifier, |s| Target::Name(s) )); +named!(variant_name, map!(identifier, + |s| MatchVariant::Name(s) +)); + named!(param_name, map!(identifier, |s| MatchParameter::Name(s) )); @@ -266,6 +301,13 @@ named!(expr_single, alt!( expr_group )); +named!(match_variant, alt!( + variant_path | + variant_name | + variant_num_lit | + variant_str_lit +)); + named!(match_parameter, alt!( param_name | param_num_lit | @@ -421,7 +463,7 @@ named!(when_block, do_parse!( tag_s!("{%") >> pws: opt!(tag_s!("-")) >> ws!(tag_s!("when")) >> - variant: ws!(match_parameter) >> + variant: ws!(match_variant) >> params: opt!(ws!(with_parameters)) >> nws: opt!(tag_s!("-")) >> tag_s!("%}") >> -- cgit