parser: allow match nodes w/o when if there is an else

This commit is contained in:
René Kijewski 2024-08-07 08:52:45 +02:00
parent f39ef737db
commit f818c582bf
4 changed files with 35 additions and 4 deletions

View File

@ -4,7 +4,7 @@ use nom::branch::alt;
use nom::bytes::complete::{tag, take_till};
use nom::character::complete::char;
use nom::combinator::{complete, consumed, cut, eof, fail, map, not, opt, peek, recognize, value};
use nom::multi::{many0, many1, separated_list0};
use nom::multi::{many0, separated_list0};
use nom::sequence::{delimited, pair, preceded, tuple};
use crate::memchr_splitter::{Splitter1, Splitter2, Splitter3};
@ -632,7 +632,7 @@ impl<'a> Match<'a> {
|i| s.tag_block_end(i),
cut(tuple((
ws(many0(ws(value((), |i| Comment::parse(i, s))))),
many1(|i| When::when(i, s)),
many0(|i| When::when(i, s)),
cut(tuple((
opt(|i| When::r#match(i, s)),
cut(tuple((
@ -645,12 +645,17 @@ impl<'a> Match<'a> {
))),
))),
));
let (i, (pws1, _, (expr, nws1, _, (_, arms, (else_arm, (_, pws2, _, nws2)))))) = p(i)?;
let (i, (pws1, _, (expr, nws1, _, (_, mut arms, (else_arm, (_, pws2, _, nws2)))))) = p(i)?;
let mut arms = arms;
if let Some(arm) = else_arm {
arms.push(arm);
}
if arms.is_empty() {
return Err(nom::Err::Failure(ErrorContext::new(
"`match` nodes must contain at least one `when` node and/or an `else` case",
start,
)));
}
Ok((
i,

View File

@ -224,3 +224,15 @@ fn test_match_enum_or() {
};
assert_eq!(template.render().unwrap(), "The card is red\n");
}
#[derive(Template)]
#[template(
source = "{% match true %}{% else %}otherwise{% endmatch %}",
ext = "html"
)]
struct EmptyMatch;
#[test]
fn test_empty_match() {
assert_eq!(EmptyMatch.to_string(), "otherwise");
}

View File

@ -0,0 +1,7 @@
use rinja::Template;
#[derive(Template)]
#[template(source = "{% match true %}{% endmatch %}", ext = "html")]
struct EmptyMatch;
fn main() {}

View File

@ -0,0 +1,7 @@
error: `match` nodes must contain at least one `when` node and/or an `else` case
--> <source attribute>:1:2
" match true %}{% endmatch %}"
--> tests/ui/empty-match.rs:4:21
|
4 | #[template(source = "{% match true %}{% endmatch %}", ext = "html")]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^