use winnow::{
Parser,
ascii::{alpha1, dec_uint, space0, space1},
combinator::{alt, delimited, not, opt, peek, preceded, repeat, separated, terminated},
stream::{LocatingSlice, Location},
token::{any, one_of, take_till, take_until, take_while},
};
use super::{SyntaxError, ast::*, span::Span};
pub(crate) fn parse(input: &str) -> Result<Vec<Node>, SyntaxError> {
let original_len = input.len();
let mut located_input = LocatingSlice::new(input);
match template_parser.parse_next(&mut located_input) {
Ok(nodes) => Ok(nodes),
Err(e) => {
let span = Span::new("<input>", 0, original_len);
Err(SyntaxError::ParseError {
span,
message: format!("{}", e),
})
}
}
}
pub(crate) fn parse_expression(input: &str) -> Result<Expression, SyntaxError> {
let mut located_input = LocatingSlice::new(input);
let expression = expression_parser
.parse_next(&mut located_input)
.map_err(|e| SyntaxError::ParseError {
span: Span::new("<input>", 0, input.len()),
message: format!("{}", e),
})?;
if located_input.current_token_start() != input.len() {
return Err(SyntaxError::ParseError {
span: Span::new("<input>", 0, input.len()),
message: format!(
"unexpected trailing input in expression at byte {}",
located_input.current_token_start()
),
});
}
Ok(expression)
}
fn template_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Vec<Node>> {
repeat(0.., node_parser).parse_next(input)
}
fn node_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Node> {
alt((
comment_parser,
variable_parser,
block_if_parser,
block_for_parser,
text_parser,
))
.parse_next(input)
}
fn comment_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Node> {
let start_pos = input.current_token_start();
let text = delimited("{#", take_until(0.., "#}"), "#}").parse_next(input)?;
let end_pos = input.current_token_start();
Ok(Node::Comment(CommentNode {
text: text.to_string(),
span: Span::new("<input>", start_pos, end_pos),
}))
}
fn variable_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Node> {
let start_pos = input.current_token_start();
let expr =
delimited("{{", delimited(space0, expression_parser, space0), "}}").parse_next(input)?;
let end_pos = input.current_token_start();
Ok(Node::Variable(VariableNode {
expression: expr,
span: Span::new("<input>", start_pos, end_pos),
}))
}
fn expression_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Expression> {
or_expression_parser.parse_next(input)
}
fn or_expression_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Expression> {
let first = and_expression_parser.parse_next(input)?;
let rest: Vec<Expression> = repeat(
0..,
preceded(delimited(space1, "or", space1), and_expression_parser),
)
.parse_next(input)?;
Ok(fold_logical(first, rest, LogicalOperator::Or))
}
fn and_expression_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Expression> {
let first = not_expression_parser.parse_next(input)?;
let rest: Vec<Expression> = repeat(
0..,
preceded(delimited(space1, "and", space1), not_expression_parser),
)
.parse_next(input)?;
Ok(fold_logical(first, rest, LogicalOperator::And))
}
fn fold_logical(first: Expression, rest: Vec<Expression>, operator: LogicalOperator) -> Expression {
rest.into_iter().fold(first, |left, right| {
Expression::Logical(LogicalExpression {
left: Box::new(left),
operator,
right: Box::new(right),
})
})
}
fn not_expression_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Expression> {
alt((
preceded(("not", space1), not_expression_parser)
.map(|expr| Expression::Not(Box::new(expr))),
comparison_expression_parser,
))
.parse_next(input)
}
fn comparison_expression_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Expression> {
let left = value_expression_parser.parse_next(input)?;
let rest: Option<(ComparisonOperator, Expression)> = opt((
delimited(space0, comparison_operator_parser, space0),
value_expression_parser,
))
.parse_next(input)?;
Ok(match rest {
Some((operator, right)) => Expression::Comparison(ComparisonExpression {
left: Box::new(left),
operator,
right: Box::new(right),
}),
None => left,
})
}
fn comparison_operator_parser(
input: &mut LocatingSlice<&str>,
) -> winnow::Result<ComparisonOperator> {
alt((
">=".map(|_| ComparisonOperator::GreaterEqual),
"<=".map(|_| ComparisonOperator::LessEqual),
"==".map(|_| ComparisonOperator::Equal),
"!=".map(|_| ComparisonOperator::NotEqual),
">".map(|_| ComparisonOperator::Greater),
"<".map(|_| ComparisonOperator::Less),
))
.parse_next(input)
}
fn value_expression_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Expression> {
let value = additive_expression_parser.parse_next(input)?;
let filters: Vec<FilterCall> = repeat(
0..,
preceded(delimited(space0, '|', space0), filter_call_parser),
)
.parse_next(input)?;
if filters.is_empty() {
Ok(value)
} else {
Ok(Expression::Filter(FilterExpression {
value: Box::new(value),
filters,
}))
}
}
fn additive_expression_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Expression> {
let first = multiplicative_expression_parser.parse_next(input)?;
let rest: Vec<(ArithmeticOperator, Expression)> = repeat(
0..,
(
delimited(space0, additive_operator_parser, space0),
multiplicative_expression_parser,
),
)
.parse_next(input)?;
Ok(fold_arithmetic(first, rest))
}
fn additive_operator_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<ArithmeticOperator> {
one_of(('+', '-'))
.map(|operator| match operator {
'+' => ArithmeticOperator::Add,
_ => ArithmeticOperator::Subtract,
})
.parse_next(input)
}
fn multiplicative_expression_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Expression> {
let first = unary_expression_parser.parse_next(input)?;
let rest: Vec<(ArithmeticOperator, Expression)> = repeat(
0..,
(
delimited(space0, multiplicative_operator_parser, space0),
unary_expression_parser,
),
)
.parse_next(input)?;
Ok(fold_arithmetic(first, rest))
}
fn multiplicative_operator_parser(
input: &mut LocatingSlice<&str>,
) -> winnow::Result<ArithmeticOperator> {
one_of(('*', '/', '%'))
.map(|operator| match operator {
'*' => ArithmeticOperator::Multiply,
'/' => ArithmeticOperator::Divide,
_ => ArithmeticOperator::Remainder,
})
.parse_next(input)
}
fn fold_arithmetic(first: Expression, rest: Vec<(ArithmeticOperator, Expression)>) -> Expression {
rest.into_iter().fold(first, |left, (operator, right)| {
Expression::Arithmetic(ArithmeticExpression {
left: Box::new(left),
operator,
right: Box::new(right),
})
})
}
fn unary_expression_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Expression> {
alt((
primary_expression_parser,
preceded(('-', space0), unary_expression_parser)
.map(|expr| Expression::Negate(Box::new(expr))),
))
.parse_next(input)
}
fn primary_expression_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Expression> {
alt((
parenthesized_expression_parser,
string_literal_expression_parser,
number_literal_expression_parser,
path_expression_parser,
))
.map(keyword_literal)
.parse_next(input)
}
fn parenthesized_expression_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Expression> {
delimited((space0, '('), expression_parser, (space0, ')')).parse_next(input)
}
fn string_literal_expression_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Expression> {
string_literal_parser
.map(|text| Expression::Literal(Literal::String(text)))
.parse_next(input)
}
fn string_literal_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<String> {
let quote = one_of(('"', '\'')).parse_next(input)?;
let mut text = String::new();
loop {
let segment = take_while(0.., |c: char| c != quote && c != '\\').parse_next(input)?;
text.push_str(segment);
if input.starts_with('\\') {
'\\'.parse_next(input)?;
let escaped = any.parse_next(input)?;
text.push(match escaped {
'n' => '\n',
'r' => '\r',
't' => '\t',
'\\' => '\\',
'"' => '"',
'\'' => '\'',
other => other,
});
} else {
break;
}
}
one_of(quote).parse_next(input)?;
Ok(text)
}
fn number_literal_expression_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Expression> {
terminated(
number_literal_parser.map(|text| Expression::Literal(Literal::Number(text))),
peek(not(take_while(1.., is_path_continuation))),
)
.parse_next(input)
}
fn is_path_continuation(c: char) -> bool {
c.is_alphanumeric() || matches!(c, '_' | '.')
}
fn number_literal_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<String> {
(
opt('-'),
take_while(1.., |c: char| c.is_ascii_digit()),
opt(('.', take_while(1.., |c: char| c.is_ascii_digit()))),
opt((
one_of(('e', 'E')),
opt(one_of(('+', '-'))),
take_while(1.., |c: char| c.is_ascii_digit()),
)),
)
.take()
.map(str::to_owned)
.parse_next(input)
}
fn keyword_literal(expression: Expression) -> Expression {
let Expression::Path(path) = &expression else {
return expression;
};
let [PathSegment::Field(name)] = path.segments.as_slice() else {
return expression;
};
match name.as_str() {
"true" => Expression::Literal(Literal::Bool(true)),
"false" => Expression::Literal(Literal::Bool(false)),
"null" => Expression::Literal(Literal::Null),
_ => expression,
}
}
fn filter_call_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<FilterCall> {
let name = filter_name_parser.parse_next(input)?;
let argument = opt(preceded(
delimited(space0, ':', space0),
filter_argument_parser,
))
.parse_next(input)?;
Ok(FilterCall { name, argument })
}
fn filter_name_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<String> {
(
alt((alpha1, "_")),
take_while(0.., |c: char| c.is_alphanumeric() || c == '_'),
)
.take()
.map(|s: &str| s.to_string())
.parse_next(input)
}
fn filter_argument_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<String> {
alt((quoted_argument_parser, bare_argument_parser)).parse_next(input)
}
fn quoted_argument_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<String> {
let quote = one_of(('"', '\'')).parse_next(input)?;
let text = take_while(0.., move |c: char| c != quote).parse_next(input)?;
one_of(quote).parse_next(input)?;
Ok(text.to_owned())
}
fn bare_argument_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<String> {
take_while(1.., |c: char| {
!c.is_whitespace() && !matches!(c, '|' | '}' | '%' | ':' | '(' | ')')
})
.map(|text: &str| text.to_owned())
.parse_next(input)
}
fn path_expression_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Expression> {
path_parser.map(Expression::Path).parse_next(input)
}
fn path_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Path> {
if input.starts_with('.')
&& !input
.chars()
.nth(1)
.is_some_and(|c| c.is_alphanumeric() || c == '_')
{
".".parse_next(input)?;
return Ok(Path::current());
}
let segments = separated(1.., path_segment_parser, ".").parse_next(input)?;
Ok(Path::new(segments))
}
fn path_segment_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<PathSegment> {
alt((
dec_uint.map(PathSegment::Index),
identifier_parser.map(PathSegment::Field),
))
.parse_next(input)
}
fn identifier_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<String> {
(
opt('@'),
alt((alpha1, "_")),
take_while(0.., |c: char| c.is_alphanumeric() || c == '_'),
)
.take()
.map(|s: &str| s.to_string())
.parse_next(input)
}
fn block_if_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Node> {
let start_pos = input.current_token_start();
let condition = delimited(
"{%",
preceded(
(space0, "if", space1),
terminated(expression_parser, space0),
),
"%}",
)
.parse_next(input)?;
let then_branch = parse_branch_body(input)?;
let mut elif_branches: Vec<ElifBranch> = Vec::new();
loop {
let checkpoint = *input;
let Ok(elif_condition) = try_elif_tag(input) else {
*input = checkpoint;
break;
};
let body = parse_branch_body(input)?;
elif_branches.push(ElifBranch {
condition: elif_condition,
body,
});
}
let checkpoint = *input;
let else_branch = if try_else_tag(input).is_ok() {
Some(parse_branch_body(input)?)
} else {
*input = checkpoint;
None
};
try_endif_tag(input)?;
let end_pos = input.current_token_start();
Ok(Node::If(IfNode {
condition,
then_branch,
elif_branches,
else_branch,
span: Span::new("<input>", start_pos, end_pos),
}))
}
fn parse_branch_body(input: &mut LocatingSlice<&str>) -> winnow::Result<Vec<Node>> {
let mut body = Vec::new();
loop {
let checkpoint = *input;
if try_endif_tag(input).is_ok() {
*input = checkpoint;
break;
}
*input = checkpoint;
if try_elif_tag(input).is_ok() {
*input = checkpoint;
break;
}
*input = checkpoint;
if try_else_tag(input).is_ok() {
*input = checkpoint;
break;
}
*input = checkpoint;
body.push(node_parser.parse_next(input)?);
}
Ok(body)
}
fn block_for_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Node> {
let start_pos = input.current_token_start();
let (item_name, iterable) = delimited(
"{%",
preceded(
(space0, "for", space1),
terminated(
(
terminated(identifier_parser, (space1, "in", space1)),
expression_parser,
),
space0,
),
),
"%}",
)
.parse_next(input)?;
let mut body = Vec::new();
loop {
let checkpoint = *input;
if try_endfor_tag(input).is_ok() {
break;
}
*input = checkpoint;
let node = node_parser.parse_next(input)?;
body.push(node);
}
let end_pos = input.current_token_start();
Ok(Node::For(ForNode {
item_name,
iterable,
body,
span: Span::new("<input>", start_pos, end_pos),
}))
}
fn text_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Node> {
let start_pos = input.current_token_start();
let text = take_till(1.., |c| c == '{').parse_next(input)?;
let end_pos = input.current_token_start();
Ok(Node::Text(TextNode {
text: text.to_string(),
span: Span::new("<input>", start_pos, end_pos),
}))
}
fn try_elif_tag(input: &mut LocatingSlice<&str>) -> winnow::Result<Expression> {
delimited(
"{%",
preceded(
(space0, "elif", space1),
terminated(expression_parser, space0),
),
"%}",
)
.parse_next(input)
}
fn try_else_tag(input: &mut LocatingSlice<&str>) -> winnow::Result<()> {
delimited("{%", (space0, "else", space0), "%}")
.void()
.parse_next(input)
}
fn try_endif_tag(input: &mut LocatingSlice<&str>) -> winnow::Result<()> {
delimited("{%", (space0, "endif", space0), "%}")
.void()
.parse_next(input)
}
fn try_endfor_tag(input: &mut LocatingSlice<&str>) -> winnow::Result<()> {
delimited("{%", (space0, "endfor", space0), "%}")
.void()
.parse_next(input)
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
use super::*;
#[test]
fn test_parse_plain_text() {
let nodes = parse("Hello World").unwrap();
assert_eq!(nodes.len(), 1);
match &nodes[0] {
Node::Text(t) => assert_eq!(t.text, "Hello World"),
_ => panic!("Expected Text node"),
}
}
#[test]
fn test_parse_variable() {
let nodes = parse("{{name}}").unwrap();
assert_eq!(nodes.len(), 1);
match &nodes[0] {
Node::Variable(v) => match &v.expression {
Expression::Path(p) => {
assert_eq!(p.segments.len(), 1);
assert_eq!(p.segments[0], PathSegment::Field("name".to_string()));
}
_ => panic!("Expected Path expression"),
},
_ => panic!("Expected Variable node"),
}
}
#[test]
fn test_parse_nested_path() {
let nodes = parse("{{user.name}}").unwrap();
match &nodes[0] {
Node::Variable(v) => match &v.expression {
Expression::Path(p) => {
assert_eq!(p.segments.len(), 2);
assert_eq!(p.segments[0], PathSegment::Field("user".to_string()));
assert_eq!(p.segments[1], PathSegment::Field("name".to_string()));
}
_ => panic!("Expected Path expression"),
},
_ => panic!("Expected Variable node"),
}
}
#[test]
fn test_parse_array_index() {
let nodes = parse("{{items.0}}").unwrap();
match &nodes[0] {
Node::Variable(v) => match &v.expression {
Expression::Path(p) => {
assert_eq!(p.segments.len(), 2);
assert_eq!(p.segments[0], PathSegment::Field("items".to_string()));
assert_eq!(p.segments[1], PathSegment::Index(0));
}
_ => panic!("Expected Path expression"),
},
_ => panic!("Expected Variable node"),
}
}
#[test]
fn test_parse_loop_metadata() {
for name in ["@index", "@first", "@last"] {
let source = format!("{{{{{name}}}}}");
let nodes = parse(&source).unwrap();
match &nodes[0] {
Node::Variable(v) => match &v.expression {
Expression::Path(p) => {
assert_eq!(p.segments, vec![PathSegment::Field(name.to_string())]);
}
_ => panic!("Expected Path expression"),
},
_ => panic!("Expected Variable node"),
}
}
}
#[test]
fn test_parse_not_expression() {
let nodes = parse("{{not active}}").unwrap();
match &nodes[0] {
Node::Variable(v) => match &v.expression {
Expression::Not(inner) => match &**inner {
Expression::Path(p) => {
assert_eq!(p.segments[0], PathSegment::Field("active".to_string()));
}
_ => panic!("Expected Path inside Not"),
},
_ => panic!("Expected Not expression"),
},
_ => panic!("Expected Variable node"),
}
}
#[test]
fn test_parse_filter() {
let expression = parse_expression("name | upper").unwrap();
match expression {
Expression::Filter(filter) => {
assert!(matches!(filter.value.as_ref(), Expression::Path(_)));
assert_eq!(filter.filters.len(), 1);
assert_eq!(filter.filters[0].name, "upper");
assert!(filter.filters[0].argument.is_none());
}
other => panic!("Expected Filter expression, found {other:?}"),
}
}
#[test]
fn test_parse_filter_with_double_quoted_argument() {
let expression = parse_expression("nickname | default: \"friend\"").unwrap();
match expression {
Expression::Filter(filter) => {
assert_eq!(filter.filters[0].argument.as_deref(), Some("friend"));
}
other => panic!("Expected Filter expression, found {other:?}"),
}
}
#[test]
fn test_parse_filter_with_single_quoted_argument() {
let expression = parse_expression("nickname | default: 'friend'").unwrap();
match expression {
Expression::Filter(filter) => {
assert_eq!(filter.filters[0].argument.as_deref(), Some("friend"));
}
other => panic!("Expected Filter expression, found {other:?}"),
}
}
#[test]
fn test_parse_filter_with_bare_argument() {
let expression = parse_expression("amount | round: 2").unwrap();
match expression {
Expression::Filter(filter) => {
assert_eq!(filter.filters[0].argument.as_deref(), Some("2"));
}
other => panic!("Expected Filter expression, found {other:?}"),
}
}
#[test]
fn test_parse_filter_chain() {
let expression = parse_expression("name | trim | upper").unwrap();
match expression {
Expression::Filter(filter) => {
let names: Vec<&str> = filter
.filters
.iter()
.map(|call| call.name.as_str())
.collect();
assert_eq!(names, ["trim", "upper"]);
}
other => panic!("Expected Filter expression, found {other:?}"),
}
}
#[test]
fn test_parse_filter_without_spaces() {
let expression = parse_expression("name|upper").unwrap();
assert!(matches!(expression, Expression::Filter(_)));
}
#[test]
fn test_parse_filter_in_a_condition() {
let nodes = parse("{% if name | len %}Yes{% endif %}").unwrap();
match &nodes[0] {
Node::If(if_node) => {
assert!(matches!(if_node.condition, Expression::Filter(_)));
}
other => panic!("Expected If node, found {other:?}"),
}
}
#[test]
fn test_parse_filter_in_an_iterable() {
let nodes = parse("{% for item in items | default: [] %}{{item}}{% endfor %}").unwrap();
match &nodes[0] {
Node::For(for_node) => {
assert!(matches!(for_node.iterable, Expression::Filter(_)));
}
other => panic!("Expected For node, found {other:?}"),
}
}
#[test]
fn test_parse_filter_without_a_name_fails() {
assert!(parse_expression("name |").is_err());
assert!(parse_expression("name | : value").is_err());
}
#[test]
fn test_parse_if_block() {
let nodes = parse("{% if active %}Yes{% endif %}").unwrap();
assert_eq!(nodes.len(), 1);
match &nodes[0] {
Node::If(if_node) => {
assert_eq!(if_node.then_branch.len(), 1);
assert!(if_node.else_branch.is_none());
}
_ => panic!("Expected If node"),
}
}
#[test]
fn test_parse_if_else_block() {
let nodes = parse("{% if active %}Yes{% else %}No{% endif %}").unwrap();
match &nodes[0] {
Node::If(if_node) => {
assert_eq!(if_node.then_branch.len(), 1);
assert!(if_node.else_branch.is_some());
assert_eq!(if_node.else_branch.as_ref().unwrap().len(), 1);
}
_ => panic!("Expected If node"),
}
}
#[test]
fn test_parse_elif_chain() {
let nodes = parse("{% if a %}A{% elif b %}B{% elif c %}C{% else %}D{% endif %}").unwrap();
match &nodes[0] {
Node::If(if_node) => {
assert_eq!(if_node.then_branch.len(), 1);
assert_eq!(if_node.elif_branches.len(), 2);
assert_eq!(if_node.elif_branches[0].body.len(), 1);
assert_eq!(if_node.elif_branches[1].body.len(), 1);
assert_eq!(if_node.else_branch.as_ref().map(Vec::len), Some(1));
}
other => panic!("Expected If node, found {other:?}"),
}
}
#[test]
fn test_parse_elif_without_else() {
let nodes = parse("{% if a %}A{% elif b %}B{% endif %}").unwrap();
match &nodes[0] {
Node::If(if_node) => {
assert_eq!(if_node.elif_branches.len(), 1);
assert!(if_node.else_branch.is_none());
}
other => panic!("Expected If node, found {other:?}"),
}
}
#[test]
fn test_elif_condition_parses_an_expression() {
let nodes = parse("{% if a %}A{% elif total > 10 and paid %}B{% endif %}").unwrap();
match &nodes[0] {
Node::If(if_node) => {
assert!(matches!(
if_node.elif_branches[0].condition,
Expression::Logical(_)
));
}
other => panic!("Expected If node, found {other:?}"),
}
}
#[test]
fn test_parse_for_loop() {
let nodes = parse("{% for item in items %}{{item}}{% endfor %}").unwrap();
assert_eq!(nodes.len(), 1);
match &nodes[0] {
Node::For(for_node) => {
assert_eq!(for_node.item_name, "item");
assert_eq!(for_node.body.len(), 1);
}
_ => panic!("Expected For node"),
}
}
#[test]
fn test_parse_comment() {
let nodes = parse("{# this is a comment #}").unwrap();
assert_eq!(nodes.len(), 1);
match &nodes[0] {
Node::Comment(c) => assert_eq!(c.text.trim(), "this is a comment"),
_ => panic!("Expected Comment node"),
}
}
#[test]
fn test_parse_mixed_content() {
let nodes = parse("Hello {{name}}!").unwrap();
assert_eq!(nodes.len(), 3);
match (&nodes[0], &nodes[1], &nodes[2]) {
(Node::Text(t1), Node::Variable(_), Node::Text(t2)) => {
assert_eq!(t1.text, "Hello ");
assert_eq!(t2.text, "!");
}
_ => panic!("Expected Text, Variable, Text"),
}
}
#[test]
fn test_parse_current_item() {
let nodes = parse("{{.}}").unwrap();
match &nodes[0] {
Node::Variable(v) => match &v.expression {
Expression::Path(p) => {
assert_eq!(p.segments.len(), 1);
assert_eq!(p.segments[0], PathSegment::Current);
}
_ => panic!("Expected Path expression"),
},
_ => panic!("Expected Variable node"),
}
}
#[test]
fn snapshot_plain_text() {
let nodes = parse("Hello World").unwrap();
insta::assert_debug_snapshot!(nodes);
}
#[test]
fn snapshot_single_variable() {
let nodes = parse("{{name}}").unwrap();
insta::assert_debug_snapshot!(nodes);
}
#[test]
fn snapshot_nested_path() {
let nodes = parse("{{user.name}}").unwrap();
insta::assert_debug_snapshot!(nodes);
}
#[test]
fn snapshot_array_access() {
let nodes = parse("{{items.0.name}}").unwrap();
insta::assert_debug_snapshot!(nodes);
}
#[test]
fn snapshot_not_expression() {
let nodes = parse("{{not active}}").unwrap();
insta::assert_debug_snapshot!(nodes);
}
#[test]
fn snapshot_if_block() {
let nodes = parse("{% if active %}Content{% endif %}").unwrap();
insta::assert_debug_snapshot!(nodes);
}
#[test]
fn snapshot_if_else_block() {
let nodes = parse("{% if active %}Yes{% else %}No{% endif %}").unwrap();
insta::assert_debug_snapshot!(nodes);
}
#[test]
fn snapshot_elif_chain() {
let nodes = parse(
"{% if status == \"open\" %}Open{% elif status == \"pending\" %}Pending{% elif status == \"closed\" %}Closed{% else %}Unknown{% endif %}",
)
.unwrap();
insta::assert_debug_snapshot!(nodes);
}
#[test]
fn snapshot_for_loop() {
let nodes = parse("{% for item in items %}{{item}}{% endfor %}").unwrap();
insta::assert_debug_snapshot!(nodes);
}
#[test]
fn snapshot_nested_blocks() {
let nodes = parse(
"{% for user in users %}{% if user.active %}{{user.name}}{% endif %}{% endfor %}",
)
.unwrap();
insta::assert_debug_snapshot!(nodes);
}
#[test]
fn snapshot_complex_template() {
let template = r#"Hello {{name}}!
{% if premium %}
Premium features:
{% for feature in features %}
- {{feature.name}}: {{feature.description}}
{% endfor %}
{% else %}
Upgrade to premium!
{% endif %}"#;
let nodes = parse(template).unwrap();
insta::assert_debug_snapshot!(nodes);
}
#[test]
fn snapshot_comment() {
let nodes = parse("{# This is a comment #}").unwrap();
insta::assert_debug_snapshot!(nodes);
}
#[test]
fn snapshot_current_item_in_loop() {
let nodes = parse("{% for item in items %}{{.}}{% endfor %}").unwrap();
insta::assert_debug_snapshot!(nodes);
}
fn if_condition(template: &str) -> Expression {
let nodes = parse(template).unwrap();
match &nodes[0] {
Node::If(if_node) => if_node.condition.clone(),
other => panic!("Expected If node, found {other:?}"),
}
}
#[test]
fn test_parse_comparison_with_number() {
let expression = if_condition("{% if total > 100 %}x{% endif %}");
match expression {
Expression::Comparison(comparison) => {
assert_eq!(comparison.operator, ComparisonOperator::Greater);
assert!(matches!(
comparison.left.as_ref(),
Expression::Path(path) if path == &Path::field("total")
));
assert!(matches!(
comparison.right.as_ref(),
Expression::Literal(Literal::Number(raw)) if raw == "100"
));
}
other => panic!("Expected Comparison expression, found {other:?}"),
}
}
#[test]
fn test_parse_all_comparison_operators() {
for (source, expected) in [
("a == 1", ComparisonOperator::Equal),
("a != 1", ComparisonOperator::NotEqual),
("a < 1", ComparisonOperator::Less),
("a <= 1", ComparisonOperator::LessEqual),
("a > 1", ComparisonOperator::Greater),
("a >= 1", ComparisonOperator::GreaterEqual),
] {
let expression = parse_expression(source).unwrap();
match expression {
Expression::Comparison(comparison) => assert_eq!(comparison.operator, expected),
other => panic!("Expected Comparison for {source}, found {other:?}"),
}
}
}
#[test]
fn test_parse_comparison_with_string_literal() {
let expression = if_condition(r#"{% if status == "open" %}x{% endif %}"#);
match expression {
Expression::Comparison(comparison) => {
assert_eq!(comparison.operator, ComparisonOperator::Equal);
assert!(matches!(
comparison.right.as_ref(),
Expression::Literal(Literal::String(text)) if text == "open"
));
}
other => panic!("Expected Comparison expression, found {other:?}"),
}
}
#[test]
fn test_parse_string_literal_with_escapes() {
let expression = parse_expression(r#""a \"quoted\" value\n""#).unwrap();
match expression {
Expression::Literal(Literal::String(text)) => {
assert_eq!(text, "a \"quoted\" value\n");
}
other => panic!("Expected String literal, found {other:?}"),
}
}
#[test]
fn test_parse_boolean_and_null_literals() {
for (source, expected) in [
("true", Literal::Bool(true)),
("false", Literal::Bool(false)),
("null", Literal::Null),
] {
let expression = parse_expression(source).unwrap();
assert!(matches!(expression, Expression::Literal(literal) if literal == expected));
}
}
#[test]
fn test_parse_negative_and_decimal_numbers() {
for source in ["-1", "2.5", "1e3", "1.5E-2"] {
let expression = parse_expression(source).unwrap();
assert!(
matches!(expression, Expression::Literal(Literal::Number(_))),
"{source}"
);
}
}
#[test]
fn test_keyword_paths_stay_paths_when_they_have_segments() {
let expression = parse_expression("true.value").unwrap();
assert!(matches!(expression, Expression::Path(_)), "{expression:?}");
}
#[test]
fn test_parse_and_expression() {
let expression = if_condition("{% if active and verified %}x{% endif %}");
match expression {
Expression::Logical(logical) => {
assert_eq!(logical.operator, LogicalOperator::And);
assert!(matches!(logical.left.as_ref(), Expression::Path(_)));
assert!(matches!(logical.right.as_ref(), Expression::Path(_)));
}
other => panic!("Expected Logical expression, found {other:?}"),
}
}
#[test]
fn test_and_binds_tighter_than_or() {
let expression = parse_expression("a and b or c").unwrap();
match expression {
Expression::Logical(logical) => {
assert_eq!(logical.operator, LogicalOperator::Or);
assert!(matches!(
logical.left.as_ref(),
Expression::Logical(inner) if inner.operator == LogicalOperator::And
));
assert!(matches!(logical.right.as_ref(), Expression::Path(_)));
}
other => panic!("Expected Or expression, found {other:?}"),
}
}
#[test]
fn test_or_keeps_its_order() {
let expression = parse_expression("a or b and c").unwrap();
match expression {
Expression::Logical(logical) => {
assert_eq!(logical.operator, LogicalOperator::Or);
assert!(
matches!(logical.right.as_ref(), Expression::Logical(inner) if inner.operator == LogicalOperator::And)
);
}
other => panic!("Expected Or expression, found {other:?}"),
}
}
#[test]
fn test_parentheses_override_precedence() {
let expression = parse_expression("(a or b) and c").unwrap();
match expression {
Expression::Logical(logical) => {
assert_eq!(logical.operator, LogicalOperator::And);
assert!(matches!(
logical.left.as_ref(),
Expression::Logical(inner) if inner.operator == LogicalOperator::Or
));
}
other => panic!("Expected And expression, found {other:?}"),
}
}
#[test]
fn test_not_binds_around_a_comparison() {
let expression = parse_expression("not total > 100").unwrap();
match expression {
Expression::Not(inner) => {
assert!(matches!(inner.as_ref(), Expression::Comparison(_)));
}
other => panic!("Expected Not expression, found {other:?}"),
}
}
#[test]
fn test_chained_comparisons_are_rejected() {
assert!(parse_expression("a < b < c").is_err());
}
#[test]
fn test_comparison_inside_a_condition_block() {
let nodes = parse("{% if total >= 10 %}yes{% endif %}").unwrap();
assert!(
matches!(&nodes[0], Node::If(if_node) if matches!(if_node.condition, Expression::Comparison(_)))
);
}
#[test]
fn test_multiplication_binds_tighter_than_addition() {
let expression = parse_expression("1 + 2 * 3").unwrap();
match expression {
Expression::Arithmetic(sum) => {
assert_eq!(sum.operator, ArithmeticOperator::Add);
assert!(matches!(
sum.right.as_ref(),
Expression::Arithmetic(product)
if product.operator == ArithmeticOperator::Multiply
));
}
other => panic!("Expected Add expression, found {other:?}"),
}
}
#[test]
fn test_arithmetic_parentheses_override_precedence() {
let expression = parse_expression("(1 + 2) * 3").unwrap();
match expression {
Expression::Arithmetic(product) => {
assert_eq!(product.operator, ArithmeticOperator::Multiply);
assert!(matches!(
product.left.as_ref(),
Expression::Arithmetic(sum) if sum.operator == ArithmeticOperator::Add
));
}
other => panic!("Expected Multiply expression, found {other:?}"),
}
}
#[test]
fn test_unary_minus_parses_around_a_group() {
let expression = parse_expression("-(2 + 3)").unwrap();
assert!(
matches!(expression, Expression::Negate(_)),
"{expression:?}"
);
}
#[test]
fn test_filter_applies_to_the_arithmetic_result() {
let expression = parse_expression("price * quantity | fixed: 2").unwrap();
match expression {
Expression::Filter(filter) => {
assert!(matches!(
filter.value.as_ref(),
Expression::Arithmetic(arithmetic)
if arithmetic.operator == ArithmeticOperator::Multiply
));
assert_eq!(filter.filters[0].argument.as_deref(), Some("2"));
}
other => panic!("Expected Filter expression, found {other:?}"),
}
}
#[test]
fn test_parenthesized_operand_keeps_its_filter() {
let expression = parse_expression("(price | round: 2) * quantity").unwrap();
match expression {
Expression::Arithmetic(product) => {
assert_eq!(product.operator, ArithmeticOperator::Multiply);
assert!(matches!(product.left.as_ref(), Expression::Filter(_)));
}
other => panic!("Expected Multiply expression, found {other:?}"),
}
}
}