Debian Codegraph @

third_party/rust/askama_parser/src/node.rs

raw
1 use std::collections::HashSet;
2 use std::str::{self, FromStr};
3
4 use winnow::combinator::{
5 alt, cut_err, delimited, empty, eof, fail, not, opt, peek, preceded, repeat, separated,
6 terminated,
7 };
8 use winnow::stream::Stream as _;
9 use winnow::token::{any, literal, rest};
10 use winnow::{ModalParser, Parser};
11
12 use crate::memchr_splitter::{Splitter1, Splitter2, Splitter3};
13 use crate::{
14 ErrorContext, Expr, Filter, ParseResult, Span, State, Target, WithSpan, filter, identifier,
15 is_rust_keyword, keyword, skip_till, skip_ws0, str_lit_without_prefix, ws,
16 };
17
18 #[derive(Debug, PartialEq)]
19 pub enum Node<'a> {
20 Lit(WithSpan<'a, Lit<'a>>),
21 Comment(WithSpan<'a, Comment<'a>>),
22 Expr(Ws, WithSpan<'a, Expr<'a>>),
23 Call(WithSpan<'a, Call<'a>>),
24 Let(WithSpan<'a, Let<'a>>),
25 If(WithSpan<'a, If<'a>>),
26 Match(WithSpan<'a, Match<'a>>),
27 Loop(Box<WithSpan<'a, Loop<'a>>>),
28 Extends(WithSpan<'a, Extends<'a>>),
29 BlockDef(WithSpan<'a, BlockDef<'a>>),
30 Include(WithSpan<'a, Include<'a>>),
31 Import(WithSpan<'a, Import<'a>>),
32 Macro(WithSpan<'a, Macro<'a>>),
33 Raw(WithSpan<'a, Raw<'a>>),
34 Break(WithSpan<'a, Ws>),
35 Continue(WithSpan<'a, Ws>),
36 FilterBlock(WithSpan<'a, FilterBlock<'a>>),
37 }
38
39 impl<'a> Node<'a> {
40 pub(super) fn parse_template(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, Vec<Self>> {
41 let start = *i;
42 let result = match (|i: &mut _| Self::many(i, s)).parse_next(i) {
43 Ok(result) => result,
44 Err(err) => {
45 if let winnow::error::ErrMode::Backtrack(err) | winnow::error::ErrMode::Cut(err) =
46 &err
47 {
48 if err.message.is_none() {
49 *i = start;
50 if let Some(mut span) = err.span.as_suffix_of(i) {
51 opt(|i: &mut _| unexpected_tag(i, s)).parse_next(&mut span)?;
52 }
53 }
54 }
55 return Err(err);
56 }
57 };
58 opt(|i: &mut _| unexpected_tag(i, s)).parse_next(i)?;
59 let is_eof = opt(eof).parse_next(i)?;
60 if is_eof.is_none() {
61 return Err(winnow::error::ErrMode::Cut(ErrorContext::new(
62 "cannot parse entire template\n\
63 you should never encounter this error\n\
64 please report this error to <https://github.com/askama-rs/askama/issues>",
65 *i,
66 )));
67 }
68 Ok(result)
69 }
70
71 fn many(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, Vec<Self>> {
72 repeat(
73 0..,
74 alt((
75 |i: &mut _| Lit::parse(i, s).map(Self::Lit),
76 |i: &mut _| Comment::parse(i, s).map(Self::Comment),
77 |i: &mut _| Self::expr(i, s),
78 |i: &mut _| Self::parse(i, s),
79 )),
80 )
81 .map(|v: Vec<_>| v)
82 .parse_next(i)
83 }
84
85 fn parse(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, Self> {
86 let mut start = *i;
87 let tag = preceded(
88 |i: &mut _| s.tag_block_start(i),
89 peek(preceded((opt(Whitespace::parse), skip_ws0), identifier)),
90 )
91 .parse_next(i)?;
92
93 let func = match tag {
94 "call" => |i: &mut _, s| Call::parse(i, s).map(Self::Call),
95 "let" | "set" => |i: &mut _, s| Let::parse(i, s).map(Self::Let),
96 "if" => |i: &mut _, s| If::parse(i, s).map(Self::If),
97 "for" => |i: &mut _, s| Loop::parse(i, s).map(|n| Self::Loop(Box::new(n))),
98 "match" => |i: &mut _, s| Match::parse(i, s).map(Self::Match),
99 "extends" => |i: &mut _, _s| Extends::parse(i).map(Self::Extends),
100 "include" => |i: &mut _, _s| Include::parse(i).map(Self::Include),
101 "import" => |i: &mut _, _s| Import::parse(i).map(Self::Import),
102 "block" => |i: &mut _, s| BlockDef::parse(i, s).map(Self::BlockDef),
103 "macro" => |i: &mut _, s| Macro::parse(i, s).map(Self::Macro),
104 "raw" => |i: &mut _, s| Raw::parse(i, s).map(Self::Raw),
105 "break" => |i: &mut _, s| Self::r#break(i, s),
106 "continue" => |i: &mut _, s| Self::r#continue(i, s),
107 "filter" => |i: &mut _, s| FilterBlock::parse(i, s).map(Self::FilterBlock),
108 _ => return fail.parse_next(&mut start),
109 };
110
111 let _level_guard = s.level.nest(i)?;
112 let node = func(i, s)?;
113 let closed = cut_node(
114 None,
115 alt((
116 ws(eof).value(false),
117 (|i: &mut _| s.tag_block_end(i)).value(true),
118 )),
119 )
120 .parse_next(i)?;
121 match closed {
122 true => Ok(node),
123 false => Err(ErrorContext::unclosed("block", s.syntax.block_end, start).cut()),
124 }
125 }
126
127 fn r#break(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, Self> {
128 let mut p = (
129 opt(Whitespace::parse),
130 ws(keyword("break")),
131 opt(Whitespace::parse),
132 );
133
134 let start = *i;
135 let (pws, _, nws) = p.parse_next(i)?;
136 if !s.is_in_loop() {
137 return Err(winnow::error::ErrMode::Cut(ErrorContext::new(
138 "you can only `break` inside a `for` loop",
139 start,
140 )));
141 }
142 Ok(Self::Break(WithSpan::new(Ws(pws, nws), start)))
143 }
144
145 fn r#continue(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, Self> {
146 let mut p = (
147 opt(Whitespace::parse),
148 ws(keyword("continue")),
149 opt(Whitespace::parse),
150 );
151
152 let start = *i;
153 let (pws, _, nws) = p.parse_next(i)?;
154 if !s.is_in_loop() {
155 return Err(winnow::error::ErrMode::Cut(ErrorContext::new(
156 "you can only `continue` inside a `for` loop",
157 start,
158 )));
159 }
160 Ok(Self::Continue(WithSpan::new(Ws(pws, nws), start)))
161 }
162
163 fn expr(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, Self> {
164 let start = *i;
165 let level = s.level;
166 let (pws, expr) = preceded(
167 |i: &mut _| s.tag_expr_start(i),
168 cut_node(
169 None,
170 (
171 opt(Whitespace::parse),
172 ws(|i: &mut _| Expr::parse(i, level, false)),
173 ),
174 ),
175 )
176 .parse_next(i)?;
177
178 let (nws, closed) = cut_node(
179 None,
180 (
181 opt(Whitespace::parse),
182 alt((
183 (|i: &mut _| s.tag_expr_end(i)).value(true),
184 ws(eof).value(false),
185 )),
186 ),
187 )
188 .parse_next(i)?;
189 match closed {
190 true => Ok(Self::Expr(Ws(pws, nws), expr)),
191 false => Err(ErrorContext::unclosed("expression", s.syntax.expr_end, start).cut()),
192 }
193 }
194
195 #[must_use]
196 pub fn span(&self) -> Span<'a> {
197 match self {
198 Self::Lit(span) => span.span,
199 Self::Comment(span) => span.span,
200 Self::Expr(_, span) => span.span,
201 Self::Call(span) => span.span,
202 Self::Let(span) => span.span,
203 Self::If(span) => span.span,
204 Self::Match(span) => span.span,
205 Self::Loop(span) => span.span,
206 Self::Extends(span) => span.span,
207 Self::BlockDef(span) => span.span,
208 Self::Include(span) => span.span,
209 Self::Import(span) => span.span,
210 Self::Macro(span) => span.span,
211 Self::Raw(span) => span.span,
212 Self::Break(span) => span.span,
213 Self::Continue(span) => span.span,
214 Self::FilterBlock(span) => span.span,
215 }
216 }
217 }
218
219 fn cut_node<'a, O>(
220 kind: Option<&'static str>,
221 inner: impl ModalParser<&'a str, O, ErrorContext<'a>>,
222 ) -> impl ModalParser<&'a str, O, ErrorContext<'a>> {
223 let mut inner = cut_err(inner);
224 move |i: &mut &'a str| {
225 let start = *i;
226 let result = inner.parse_next(i);
227 if let Err(winnow::error::ErrMode::Cut(err) | winnow::error::ErrMode::Backtrack(err)) =
228 &result
229 {
230 if err.message.is_none() {
231 *i = start;
232 if let Some(mut span) = err.span.as_suffix_of(i) {
233 opt(|i: &mut _| unexpected_raw_tag(kind, i)).parse_next(&mut span)?;
234 }
235 }
236 }
237 result
238 }
239 }
240
241 fn unexpected_tag<'a>(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, ()> {
242 (
243 |i: &mut _| s.tag_block_start(i),
244 opt(Whitespace::parse),
245 |i: &mut _| unexpected_raw_tag(None, i),
246 )
247 .void()
248 .parse_next(i)
249 }
250
251 fn unexpected_raw_tag<'a>(kind: Option<&'static str>, i: &mut &'a str) -> ParseResult<'a, ()> {
252 let tag = peek(ws(identifier)).parse_next(i)?;
253 let msg = match tag {
254 "end" | "elif" | "else" | "when" => match kind {
255 Some(kind) => {
256 format!("node `{tag}` was not expected in the current context: `{kind}` block")
257 }
258 None => format!("node `{tag}` was not expected in the current context"),
259 },
260 tag if tag.starts_with("end") => format!("unexpected closing tag `{tag}`"),
261 tag => format!("unknown node `{tag}`"),
262 };
263 Err(winnow::error::ErrMode::Cut(ErrorContext::new(msg, *i)))
264 }
265
266 #[derive(Debug, PartialEq)]
267 pub struct When<'a> {
268 pub ws: Ws,
269 pub target: Vec<Target<'a>>,
270 pub nodes: Vec<Node<'a>>,
271 }
272
273 impl<'a> When<'a> {
274 fn r#else(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, WithSpan<'a, Self>> {
275 let mut p = (
276 |i: &mut _| s.tag_block_start(i),
277 opt(Whitespace::parse),
278 ws(keyword("else")),
279 cut_node(
280 Some("match-else"),
281 (
282 opt(Whitespace::parse),
283 |i: &mut _| s.tag_block_end(i),
284 cut_node(Some("match-else"), |i: &mut _| Node::many(i, s)),
285 ),
286 ),
287 );
288
289 let start = *i;
290 let (_, pws, _, (nws, _, nodes)) = p.parse_next(i)?;
291 Ok(WithSpan::new(
292 Self {
293 ws: Ws(pws, nws),
294 target: vec![Target::Placeholder(WithSpan::new((), start))],
295 nodes,
296 },
297 start,
298 ))
299 }
300
301 #[allow(clippy::self_named_constructors)]
302 fn when(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, WithSpan<'a, Self>> {
303 let start = *i;
304 let endwhen = ws((
305 delimited(
306 |i: &mut _| s.tag_block_start(i),
307 opt(Whitespace::parse),
308 ws(keyword("endwhen")),
309 ),
310 cut_node(
311 Some("match-endwhen"),
312 (
313 opt(Whitespace::parse),
314 |i: &mut _| s.tag_block_end(i),
315 repeat(0.., ws(|i: &mut _| Comment::parse(i, s))).map(|()| ()),
316 ),
317 ),
318 ))
319 .with_taken()
320 .map(|((pws, _), span)| {
321 // A comment node is used to pass the whitespace suppressing information to the
322 // generator. This way we don't have to fix up the next `when` node or the closing
323 // `endmatch`. Any whitespaces after `endwhen` are to be suppressed. Actually, they
324 // don't wind up in the AST anyway.
325 Node::Comment(WithSpan::new(
326 Comment {
327 ws: Ws(pws, Some(Whitespace::Suppress)),
328 content: "",
329 },
330 span,
331 ))
332 });
333 let mut p = (
334 |i: &mut _| s.tag_block_start(i),
335 opt(Whitespace::parse),
336 ws(keyword("when")),
337 cut_node(
338 Some("match-when"),
339 (
340 separated(1.., ws(|i: &mut _| Target::parse(i, s)), '|'),
341 opt(Whitespace::parse),
342 |i: &mut _| s.tag_block_end(i),
343 cut_node(Some("match-when"), |i: &mut _| Node::many(i, s)),
344 opt(endwhen),
345 ),
346 ),
347 );
348 let (_, pws, _, (target, nws, _, mut nodes, endwhen)) = p.parse_next(i)?;
349 if let Some(endwhen) = endwhen {
350 nodes.push(endwhen);
351 }
352 Ok(WithSpan::new(
353 Self {
354 ws: Ws(pws, nws),
355 target,
356 nodes,
357 },
358 start,
359 ))
360 }
361 }
362
363 #[derive(Debug, PartialEq)]
364 pub struct Cond<'a> {
365 pub ws: Ws,
366 pub cond: Option<CondTest<'a>>,
367 pub nodes: Vec<Node<'a>>,
368 }
369
370 impl<'a> Cond<'a> {
371 fn parse(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, WithSpan<'a, Self>> {
372 let start = *i;
373 let (_, pws, cond, nws, _, nodes) = (
374 |i: &mut _| s.tag_block_start(i),
375 opt(Whitespace::parse),
376 alt((
377 preceded(ws(keyword("else")), opt(|i: &mut _| CondTest::parse(i, s))),
378 preceded(
379 ws(keyword("elif")),
380 cut_node(Some("if-elif"), |i: &mut _| {
381 CondTest::parse_cond(i, s).map(Some)
382 }),
383 ),
384 )),
385 opt(Whitespace::parse),
386 cut_node(Some("if"), |i: &mut _| s.tag_block_end(i)),
387 cut_node(Some("if"), |i: &mut _| Node::many(i, s)),
388 )
389 .parse_next(i)?;
390 Ok(WithSpan::new(
391 Self {
392 ws: Ws(pws, nws),
393 cond,
394 nodes,
395 },
396 start,
397 ))
398 }
399 }
400
401 #[derive(Debug, PartialEq, Clone)]
402 pub struct CondTest<'a> {
403 pub target: Option<Target<'a>>,
404 pub expr: WithSpan<'a, Expr<'a>>,
405 pub contains_bool_lit_or_is_defined: bool,
406 }
407
408 impl<'a> CondTest<'a> {
409 fn parse(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, Self> {
410 preceded(
411 ws(keyword("if")),
412 cut_node(Some("if"), |i: &mut _| Self::parse_cond(i, s)),
413 )
414 .parse_next(i)
415 }
416
417 fn parse_cond(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, Self> {
418 let (target, expr) = (
419 opt(delimited(
420 ws(alt((keyword("let"), keyword("set")))),
421 ws(|i: &mut _| Target::parse(i, s)),
422 ws('='),
423 )),
424 ws(|i: &mut _| {
425 let start = *i;
426 let mut expr = Expr::parse(i, s.level, false)?;
427 if let Expr::BinOp(_, _, ref mut right) = expr.inner {
428 if matches!(right.inner, Expr::Var("set" | "let")) {
429 let _level_guard = s.level.nest(i)?;
430 *i = right.span.as_suffix_of(start).unwrap();
431 let start_span = Span::from(*i);
432 let new_right = Self::parse_cond(i, s)?;
433 right.inner = Expr::LetCond(Box::new(WithSpan::new(new_right, start_span)));
434 }
435 }
436 Ok(expr)
437 }),
438 )
439 .parse_next(i)?;
440 let contains_bool_lit_or_is_defined = expr.contains_bool_lit_or_is_defined();
441 Ok(Self {
442 target,
443 expr,
444 contains_bool_lit_or_is_defined,
445 })
446 }
447 }
448
449 #[derive(Clone, Copy, Default, PartialEq, Eq, Debug, Hash)]
450 #[cfg_attr(feature = "config", derive(serde_derive::Deserialize))]
451 #[cfg_attr(feature = "config", serde(field_identifier, rename_all = "lowercase"))]
452 pub enum Whitespace {
453 #[default]
454 Preserve,
455 Suppress,
456 Minimize,
457 }
458
459 impl Whitespace {
460 fn parse<'i>(i: &mut &'i str) -> ParseResult<'i, Self> {
461 any.verify_map(Self::parse_char).parse_next(i)
462 }
463
464 fn parse_char(c: char) -> Option<Self> {
465 match c {
466 '+' => Some(Self::Preserve),
467 '-' => Some(Self::Suppress),
468 '~' => Some(Self::Minimize),
469 _ => None,
470 }
471 }
472 }
473
474 impl FromStr for Whitespace {
475 type Err = String;
476
477 fn from_str(s: &str) -> Result<Self, Self::Err> {
478 match s {
479 "+" | "preserve" => Ok(Whitespace::Preserve),
480 "-" | "suppress" => Ok(Whitespace::Suppress),
481 "~" | "minimize" => Ok(Whitespace::Minimize),
482 s => Err(format!("invalid value for `whitespace`: {s:?}")),
483 }
484 }
485 }
486
487 fn check_block_start<'a>(
488 i: &mut &'a str,
489 start: &'a str,
490 s: &State<'_, '_>,
491 node: &str,
492 expected: &str,
493 ) -> ParseResult<'a, ()> {
494 if i.is_empty() {
495 return Err(winnow::error::ErrMode::Cut(ErrorContext::new(
496 format!("expected `{expected}` to terminate `{node}` node, found nothing"),
497 start,
498 )));
499 }
500 (|i: &mut _| s.tag_block_start(i)).parse_next(i)
501 }
502
503 #[derive(Debug, PartialEq)]
504 pub struct Loop<'a> {
505 pub ws1: Ws,
506 pub var: Target<'a>,
507 pub iter: WithSpan<'a, Expr<'a>>,
508 pub cond: Option<WithSpan<'a, Expr<'a>>>,
509 pub body: Vec<Node<'a>>,
510 pub ws2: Ws,
511 pub else_nodes: Vec<Node<'a>>,
512 pub ws3: Ws,
513 }
514
515 impl<'a> Loop<'a> {
516 fn parse(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, WithSpan<'a, Self>> {
517 fn content<'a>(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, Vec<Node<'a>>> {
518 s.enter_loop();
519 let result = (|i: &mut _| Node::many(i, s)).parse_next(i);
520 s.leave_loop();
521 result
522 }
523
524 let start = *i;
525 let if_cond = preceded(
526 ws(keyword("if")),
527 cut_node(
528 Some("for-if"),
529 ws(|i: &mut _| Expr::parse(i, s.level, true)),
530 ),
531 );
532
533 let else_block = |i: &mut _| {
534 let mut p = preceded(
535 ws(keyword("else")),
536 cut_node(
537 Some("for-else"),
538 (
539 opt(Whitespace::parse),
540 delimited(
541 |i: &mut _| s.tag_block_end(i),
542 |i: &mut _| Node::many(i, s),
543 |i: &mut _| s.tag_block_start(i),
544 ),
545 opt(Whitespace::parse),
546 ),
547 ),
548 );
549 let (pws, nodes, nws) = p.parse_next(i)?;
550 Ok((pws, nodes, nws))
551 };
552
553 let body_and_end = |i: &mut _| {
554 let (body, (_, pws, else_block, _, nws)) = cut_node(
555 Some("for"),
556 (
557 |i: &mut _| content(i, s),
558 cut_node(
559 Some("for"),
560 (
561 |i: &mut _| check_block_start(i, start, s, "for", "endfor"),
562 opt(Whitespace::parse),
563 opt(else_block),
564 end_node("for", "endfor"),
565 opt(Whitespace::parse),
566 ),
567 ),
568 ),
569 )
570 .parse_next(i)?;
571 Ok((body, pws, else_block, nws))
572 };
573
574 let mut p = (
575 opt(Whitespace::parse),
576 ws(keyword("for")),
577 cut_node(
578 Some("for"),
579 (
580 ws(|i: &mut _| Target::parse(i, s)),
581 ws(keyword("in")),
582 cut_node(
583 Some("for"),
584 (
585 ws(|i: &mut _| Expr::parse(i, s.level, true)),
586 opt(if_cond),
587 opt(Whitespace::parse),
588 |i: &mut _| s.tag_block_end(i),
589 body_and_end,
590 ),
591 ),
592 ),
593 ),
594 );
595 let (pws1, _, (var, _, (iter, cond, nws1, _, (body, pws2, else_block, nws2)))) =
596 p.parse_next(i)?;
597 let (nws3, else_nodes, pws3) = else_block.unwrap_or_default();
598 Ok(WithSpan::new(
599 Self {
600 ws1: Ws(pws1, nws1),
601 var,
602 iter,
603 cond,
604 body,
605 ws2: Ws(pws2, nws3),
606 else_nodes,
607 ws3: Ws(pws3, nws2),
608 },
609 start,
610 ))
611 }
612 }
613
614 #[derive(Debug, PartialEq)]
615 pub struct Macro<'a> {
616 pub ws1: Ws,
617 pub name: &'a str,
618 pub args: Vec<(&'a str, Option<WithSpan<'a, Expr<'a>>>)>,
619 pub nodes: Vec<Node<'a>>,
620 pub ws2: Ws,
621 }
622
623 fn check_duplicated_name<'a>(
624 names: &mut HashSet<&'a str>,
625 arg_name: &'a str,
626 i: &'a str,
627 ) -> Result<(), crate::ParseErr<'a>> {
628 if !names.insert(arg_name) {
629 return Err(winnow::error::ErrMode::Cut(ErrorContext::new(
630 format!("duplicated argument `{arg_name}`"),
631 i,
632 )));
633 }
634 Ok(())
635 }
636
637 impl<'a> Macro<'a> {
638 fn parse(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, WithSpan<'a, Self>> {
639 let level = s.level;
640 #[allow(clippy::type_complexity)]
641 let parameters = |i: &mut _| -> ParseResult<
642 '_,
643 Option<Vec<(&str, Option<WithSpan<'_, Expr<'_>>>)>>,
644 > {
645 let args = opt(preceded(
646 '(',
647 (
648 opt(terminated(
649 separated(
650 1..,
651 (
652 ws(identifier),
653 opt(preceded('=', ws(|i: &mut _| Expr::parse(i, level, false)))),
654 ),
655 ',',
656 ),
657 opt(','),
658 )),
659 ws(opt(')')),
660 ),
661 ))
662 .parse_next(i)?;
663 match args {
664 Some((args, Some(_))) => Ok(args),
665 Some((_, None)) => Err(winnow::error::ErrMode::Cut(ErrorContext::new(
666 "expected `)` to close macro argument list",
667 *i,
668 ))),
669 None => Ok(None),
670 }
671 };
672
673 let start_s = *i;
674 let mut start = (
675 opt(Whitespace::parse),
676 ws(keyword("macro")),
677 cut_node(
678 Some("macro"),
679 (
680 ws(identifier),
681 parameters,
682 opt(Whitespace::parse),
683 |i: &mut _| s.tag_block_end(i),
684 ),
685 ),
686 );
687 let (pws1, _, (name, params, nws1, _)) = start.parse_next(i)?;
688 if is_rust_keyword(name) {
689 return Err(winnow::error::ErrMode::Cut(ErrorContext::new(
690 format!("'{name}' is not a valid name for a macro"),
691 start_s,
692 )));
693 }
694
695 if let Some(ref params) = params {
696 let mut names = HashSet::new();
697
698 let mut iter = params.iter();
699 while let Some((arg_name, default_value)) = iter.next() {
700 check_duplicated_name(&mut names, arg_name, start_s)?;
701 if default_value.is_some() {
702 for (new_arg_name, default_value) in iter.by_ref() {
703 check_duplicated_name(&mut names, new_arg_name, start_s)?;
704 if default_value.is_none() {
705 return Err(winnow::error::ErrMode::Cut(ErrorContext::new(
706 format!(
707 "all arguments following `{arg_name}` should have a default \
708 value, `{new_arg_name}` doesn't have a default value"
709 ),
710 start_s,
711 )));
712 }
713 }
714 }
715 }
716 }
717
718 let mut end = cut_node(
719 Some("macro"),
720 (
721 |i: &mut _| Node::many(i, s),
722 cut_node(
723 Some("macro"),
724 (
725 |i: &mut _| check_block_start(i, start_s, s, "macro", "endmacro"),
726 opt(Whitespace::parse),
727 end_node("macro", "endmacro"),
728 cut_node(
729 Some("macro"),
730 preceded(
731 opt(|i: &mut _| {
732 let before = *i;
733 let end_name = ws(identifier).parse_next(i)?;
734 check_end_name(before, name, end_name, "macro")
735 }),
736 opt(Whitespace::parse),
737 ),
738 ),
739 ),
740 ),
741 ),
742 );
743 let (contents, (_, pws2, _, nws2)) = end.parse_next(i)?;
744
745 Ok(WithSpan::new(
746 Self {
747 ws1: Ws(pws1, nws1),
748 name,
749 args: params.unwrap_or_default(),
750 nodes: contents,
751 ws2: Ws(pws2, nws2),
752 },
753 start_s,
754 ))
755 }
756 }
757
758 #[derive(Debug, PartialEq)]
759 pub struct FilterBlock<'a> {
760 pub ws1: Ws,
761 pub filters: Filter<'a>,
762 pub nodes: Vec<Node<'a>>,
763 pub ws2: Ws,
764 }
765
766 impl<'a> FilterBlock<'a> {
767 fn parse(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, WithSpan<'a, Self>> {
768 let start_s = *i;
769 let mut level_guard = s.level.guard();
770 let mut start = (
771 opt(Whitespace::parse),
772 ws(keyword("filter")),
773 cut_node(
774 Some("filter"),
775 (
776 ws(identifier),
777 opt(|i: &mut _| crate::expr::call_generics(i, s.level)),
778 opt(|i: &mut _| Expr::arguments(i, s.level, false)),
779 repeat(0.., |i: &mut _| {
780 #[allow(clippy::explicit_auto_deref)] // false positive
781 level_guard.nest(*i)?;
782 let start = *i;
783 filter(i, s.level)
784 .map(|(name, generics, params)| (name, generics, params, start))
785 })
786 .map(|v: Vec<_>| v),
787 ws(empty),
788 opt(Whitespace::parse),
789 |i: &mut _| s.tag_block_end(i),
790 ),
791 ),
792 );
793 let (pws1, _, (filter_name, generics, params, extra_filters, (), nws1, _)) =
794 start.parse_next(i)?;
795
796 let mut arguments = params.unwrap_or_default();
797 arguments.insert(0, WithSpan::new(Expr::FilterSource, start_s));
798 let mut filters = Filter {
799 name: filter_name,
800 arguments,
801 generics: generics.unwrap_or_default(),
802 };
803 for (filter_name, generics, args, span) in extra_filters {
804 filters = Filter {
805 name: filter_name,
806 arguments: {
807 let mut args = args.unwrap_or_default();
808 args.insert(0, WithSpan::new(Expr::Filter(filters), span));
809 args
810 },
811 generics,
812 };
813 }
814
815 let mut end = cut_node(
816 Some("filter"),
817 (
818 |i: &mut _| Node::many(i, s),
819 cut_node(
820 Some("filter"),
821 (
822 |i: &mut _| check_block_start(i, start_s, s, "filter", "endfilter"),
823 opt(Whitespace::parse),
824 end_node("filter", "endfilter"),
825 opt(Whitespace::parse),
826 ),
827 ),
828 ),
829 );
830 let (nodes, (_, pws2, _, nws2)) = end.parse_next(i)?;
831
832 Ok(WithSpan::new(
833 Self {
834 ws1: Ws(pws1, nws1),
835 filters,
836 nodes,
837 ws2: Ws(pws2, nws2),
838 },
839 start_s,
840 ))
841 }
842 }
843
844 #[derive(Debug, PartialEq)]
845 pub struct Import<'a> {
846 pub ws: Ws,
847 pub path: &'a str,
848 pub scope: &'a str,
849 }
850
851 impl<'a> Import<'a> {
852 fn parse(i: &mut &'a str) -> ParseResult<'a, WithSpan<'a, Self>> {
853 let start = *i;
854 let mut p = (
855 opt(Whitespace::parse),
856 ws(keyword("import")),
857 cut_node(
858 Some("import"),
859 (
860 ws(str_lit_without_prefix),
861 ws(keyword("as")),
862 cut_node(Some("import"), (ws(identifier), opt(Whitespace::parse))),
863 ),
864 ),
865 );
866 let (pws, _, (path, _, (scope, nws))) = p.parse_next(i)?;
867 Ok(WithSpan::new(
868 Self {
869 ws: Ws(pws, nws),
870 path,
871 scope,
872 },
873 start,
874 ))
875 }
876 }
877
878 #[derive(Debug, PartialEq)]
879 pub struct Call<'a> {
880 pub ws: Ws,
881 pub scope: Option<&'a str>,
882 pub name: &'a str,
883 pub args: Vec<WithSpan<'a, Expr<'a>>>,
884 }
885
886 impl<'a> Call<'a> {
887 fn parse(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, WithSpan<'a, Self>> {
888 let start = *i;
889 let mut p = (
890 opt(Whitespace::parse),
891 ws(keyword("call")),
892 cut_node(
893 Some("call"),
894 (
895 opt((ws(identifier), ws("::"))),
896 ws(identifier),
897 opt(ws(|nested: &mut _| Expr::arguments(nested, s.level, true))),
898 opt(Whitespace::parse),
899 ),
900 ),
901 );
902 let (pws, _, (scope, name, args, nws)) = p.parse_next(i)?;
903 let scope = scope.map(|(scope, _)| scope);
904 let args = args.unwrap_or_default();
905 Ok(WithSpan::new(
906 Self {
907 ws: Ws(pws, nws),
908 scope,
909 name,
910 args,
911 },
912 start,
913 ))
914 }
915 }
916
917 #[derive(Debug, PartialEq)]
918 pub struct Match<'a> {
919 pub ws1: Ws,
920 pub expr: WithSpan<'a, Expr<'a>>,
921 pub arms: Vec<WithSpan<'a, When<'a>>>,
922 pub ws2: Ws,
923 }
924
925 impl<'a> Match<'a> {
926 fn parse(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, WithSpan<'a, Self>> {
927 let start = *i;
928 let mut p = (
929 opt(Whitespace::parse),
930 ws(keyword("match")),
931 cut_node(
932 Some("match"),
933 (
934 ws(|i: &mut _| Expr::parse(i, s.level, false)),
935 opt(Whitespace::parse),
936 |i: &mut _| s.tag_block_end(i),
937 cut_node(
938 Some("match"),
939 (
940 ws(repeat(0.., ws(|i: &mut _| Comment::parse(i, s)))).map(|()| ()),
941 repeat(0.., |i: &mut _| When::when(i, s)).map(|v: Vec<_>| v),
942 cut_node(
943 Some("match"),
944 (
945 opt(|i: &mut _| When::r#else(i, s)),
946 cut_node(
947 Some("match"),
948 (
949 ws(|i: &mut _| {
950 check_block_start(i, start, s, "match", "endmatch")
951 }),
952 opt(Whitespace::parse),
953 end_node("match", "endmatch"),
954 opt(Whitespace::parse),
955 ),
956 ),
957 ),
958 ),
959 ),
960 ),
961 ),
962 ),
963 );
964 let (pws1, _, (expr, nws1, _, (_, mut arms, (else_arm, (_, pws2, _, nws2))))) =
965 p.parse_next(i)?;
966
967 if let Some(arm) = else_arm {
968 arms.push(arm);
969 }
970 if arms.is_empty() {
971 return Err(winnow::error::ErrMode::Cut(ErrorContext::new(
972 "`match` nodes must contain at least one `when` node and/or an `else` case",
973 start,
974 )));
975 }
976
977 Ok(WithSpan::new(
978 Self {
979 ws1: Ws(pws1, nws1),
980 expr,
981 arms,
982 ws2: Ws(pws2, nws2),
983 },
984 start,
985 ))
986 }
987 }
988
989 #[derive(Debug, PartialEq)]
990 pub struct BlockDef<'a> {
991 pub ws1: Ws,
992 pub name: &'a str,
993 pub nodes: Vec<Node<'a>>,
994 pub ws2: Ws,
995 }
996
997 impl<'a> BlockDef<'a> {
998 fn parse(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, WithSpan<'a, Self>> {
999 let start_s = *i;
1000 let mut start = (
1001 opt(Whitespace::parse),
1002 ws(keyword("block")),
1003 cut_node(
1004 Some("block"),
1005 (ws(identifier), opt(Whitespace::parse), |i: &mut _| {
1006 s.tag_block_end(i)
1007 }),
1008 ),
1009 );
1010 let (pws1, _, (name, nws1, _)) = start.parse_next(i)?;
1011
1012 let mut end = cut_node(
1013 Some("block"),
1014 (
1015 |i: &mut _| Node::many(i, s),
1016 cut_node(
1017 Some("block"),
1018 (
1019 |i: &mut _| check_block_start(i, start_s, s, "block", "endblock"),
1020 opt(Whitespace::parse),
1021 end_node("block", "endblock"),
1022 cut_node(
1023 Some("block"),
1024 (
1025 opt(|i: &mut _| {
1026 let before = *i;
1027 let end_name = ws(identifier).parse_next(i)?;
1028 check_end_name(before, name, end_name, "block")
1029 }),
1030 opt(Whitespace::parse),
1031 ),
1032 ),
1033 ),
1034 ),
1035 ),
1036 );
1037 let (nodes, (_, pws2, _, (_, nws2))) = end.parse_next(i)?;
1038
1039 Ok(WithSpan::new(
1040 BlockDef {
1041 ws1: Ws(pws1, nws1),
1042 name,
1043 nodes,
1044 ws2: Ws(pws2, nws2),
1045 },
1046 start_s,
1047 ))
1048 }
1049 }
1050
1051 fn check_end_name<'a>(
1052 before: &'a str,
1053 name: &'a str,
1054 end_name: &'a str,
1055 kind: &str,
1056 ) -> ParseResult<'a> {
1057 if name == end_name {
1058 return Ok(end_name);
1059 }
1060
1061 Err(winnow::error::ErrMode::Cut(ErrorContext::new(
1062 match name.is_empty() && !end_name.is_empty() {
1063 true => format!("unexpected name `{end_name}` in `end{kind}` tag for unnamed `{kind}`"),
1064 false => format!("expected name `{name}` in `end{kind}` tag, found `{end_name}`"),
1065 },
1066 before,
1067 )))
1068 }
1069
1070 #[derive(Debug, PartialEq)]
1071 pub struct Lit<'a> {
1072 pub lws: &'a str,
1073 pub val: &'a str,
1074 pub rws: &'a str,
1075 }
1076
1077 impl<'a> Lit<'a> {
1078 fn parse(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, WithSpan<'a, Self>> {
1079 let start = *i;
1080 not(eof).parse_next(i)?;
1081
1082 let candidate_finder = Splitter3::new(
1083 s.syntax.block_start,
1084 s.syntax.comment_start,
1085 s.syntax.expr_start,
1086 );
1087 let p_start = alt((
1088 literal(s.syntax.block_start),
1089 literal(s.syntax.comment_start),
1090 literal(s.syntax.expr_start),
1091 ));
1092
1093 let content = opt(skip_till(candidate_finder, p_start).take()).parse_next(i)?;
1094 let content = match content {
1095 Some("") => {
1096 // {block,comment,expr}_start follows immediately.
1097 return fail.parse_next(i);
1098 }
1099 Some(content) => content,
1100 None => rest.parse_next(i)?, /* there is no {block,comment,expr}_start: take everything */
1101 };
1102 Ok(WithSpan::new(Self::split_ws_parts(content), start))
1103 }
1104
1105 pub(crate) fn split_ws_parts(s: &'a str) -> Self {
1106 let trimmed_start = s.trim_ascii_start();
1107 let len_start = s.len() - trimmed_start.len();
1108 let trimmed = trimmed_start.trim_ascii_end();
1109 Self {
1110 lws: &s[..len_start],
1111 val: trimmed,
1112 rws: &trimmed_start[trimmed.len()..],
1113 }
1114 }
1115 }
1116
1117 #[derive(Debug, PartialEq)]
1118 pub struct Raw<'a> {
1119 pub ws1: Ws,
1120 pub lit: Lit<'a>,
1121 pub ws2: Ws,
1122 }
1123
1124 impl<'a> Raw<'a> {
1125 fn parse(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, WithSpan<'a, Self>> {
1126 let start = *i;
1127 let endraw = (
1128 |i: &mut _| s.tag_block_start(i),
1129 opt(Whitespace::parse),
1130 ws(keyword("endraw")), // sic: ignore `{% end %}` in raw blocks
1131 opt(Whitespace::parse),
1132 peek(|i: &mut _| s.tag_block_end(i)),
1133 );
1134
1135 let mut p = (
1136 opt(Whitespace::parse),
1137 ws(keyword("raw")),
1138 cut_node(
1139 Some("raw"),
1140 (
1141 opt(Whitespace::parse),
1142 |i: &mut _| s.tag_block_end(i),
1143 skip_till(Splitter1::new(s.syntax.block_start), endraw).with_taken(),
1144 ),
1145 ),
1146 );
1147
1148 let (pws1, _, (nws1, _, ((new_i, (_, pws2, _, nws2, _)), contents))) = p.parse_next(i)?;
1149 *i = new_i;
1150 let lit = Lit::split_ws_parts(contents);
1151 let ws1 = Ws(pws1, nws1);
1152 let ws2 = Ws(pws2, nws2);
1153 Ok(WithSpan::new(Self { ws1, lit, ws2 }, start))
1154 }
1155 }
1156
1157 #[derive(Debug, PartialEq)]
1158 pub struct Let<'a> {
1159 pub ws: Ws,
1160 pub var: Target<'a>,
1161 pub val: Option<WithSpan<'a, Expr<'a>>>,
1162 }
1163
1164 impl<'a> Let<'a> {
1165 fn parse(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, WithSpan<'a, Self>> {
1166 let start = *i;
1167 let mut p = (
1168 opt(Whitespace::parse),
1169 ws(alt((keyword("let"), keyword("set")))),
1170 cut_node(
1171 Some("let"),
1172 (
1173 ws(|i: &mut _| Target::parse(i, s)),
1174 opt(preceded(
1175 ws('='),
1176 ws(|i: &mut _| Expr::parse(i, s.level, false)),
1177 )),
1178 opt(Whitespace::parse),
1179 ),
1180 ),
1181 );
1182 let (pws, _, (var, val, nws)) = p.parse_next(i)?;
1183 if val.is_none() {
1184 let kind = match &var {
1185 Target::Name(_) => None,
1186 Target::Tuple(..) => Some("a tuple"),
1187 Target::Array(..) => Some("an array"),
1188 Target::Struct(..) => Some("a struct"),
1189 Target::NumLit(..)
1190 | Target::StrLit(..)
1191 | Target::CharLit(..)
1192 | Target::BoolLit(..) => Some("a literal"),
1193 Target::Path(..) => Some("a path or enum variant"),
1194 Target::OrChain(..) | Target::Placeholder(..) | Target::Rest(..) => {
1195 Some("a pattern")
1196 }
1197 };
1198 if let Some(kind) = kind {
1199 return Err(winnow::error::ErrMode::Cut(ErrorContext::new(
1200 format!(
1201 "when you forward-define a variable, you cannot use {kind} in place of \
1202 a variable name"
1203 ),
1204 start,
1205 )));
1206 }
1207 }
1208
1209 Ok(WithSpan::new(
1210 Let {
1211 ws: Ws(pws, nws),
1212 var,
1213 val,
1214 },
1215 start,
1216 ))
1217 }
1218 }
1219
1220 #[derive(Debug, PartialEq)]
1221 pub struct If<'a> {
1222 pub ws: Ws,
1223 pub branches: Vec<WithSpan<'a, Cond<'a>>>,
1224 }
1225
1226 impl<'a> If<'a> {
1227 fn parse(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, WithSpan<'a, Self>> {
1228 let start = *i;
1229 let mut p = (
1230 opt(Whitespace::parse),
1231 |i: &mut _| CondTest::parse(i, s),
1232 cut_node(
1233 Some("if"),
1234 (
1235 opt(Whitespace::parse),
1236 |i: &mut _| s.tag_block_end(i),
1237 cut_node(
1238 Some("if"),
1239 (
1240 |i: &mut _| Node::many(i, s),
1241 repeat(0.., |i: &mut _| Cond::parse(i, s)).map(|v: Vec<_>| v),
1242 cut_node(
1243 Some("if"),
1244 (
1245 |i: &mut _| check_block_start(i, start, s, "if", "endif"),
1246 opt(Whitespace::parse),
1247 end_node("if", "endif"),
1248 opt(Whitespace::parse),
1249 ),
1250 ),
1251 ),
1252 ),
1253 ),
1254 ),
1255 );
1256
1257 let (pws1, cond, (nws1, _, (nodes, elifs, (_, pws2, _, nws2)))) = p.parse_next(i)?;
1258 let mut branches = vec![WithSpan::new(
1259 Cond {
1260 ws: Ws(pws1, nws1),
1261 cond: Some(cond),
1262 nodes,
1263 },
1264 start,
1265 )];
1266 branches.extend(elifs);
1267
1268 Ok(WithSpan::new(
1269 Self {
1270 ws: Ws(pws2, nws2),
1271 branches,
1272 },
1273 start,
1274 ))
1275 }
1276 }
1277
1278 #[derive(Debug, PartialEq)]
1279 pub struct Include<'a> {
1280 pub ws: Ws,
1281 pub path: &'a str,
1282 }
1283
1284 impl<'a> Include<'a> {
1285 fn parse(i: &mut &'a str) -> ParseResult<'a, WithSpan<'a, Self>> {
1286 let start = *i;
1287 let mut p = (
1288 opt(Whitespace::parse),
1289 ws(keyword("include")),
1290 cut_node(
1291 Some("include"),
1292 (ws(str_lit_without_prefix), opt(Whitespace::parse)),
1293 ),
1294 );
1295 let (pws, _, (path, nws)) = p.parse_next(i)?;
1296 Ok(WithSpan::new(
1297 Self {
1298 ws: Ws(pws, nws),
1299 path,
1300 },
1301 start,
1302 ))
1303 }
1304 }
1305
1306 #[derive(Debug, PartialEq)]
1307 pub struct Extends<'a> {
1308 pub path: &'a str,
1309 }
1310
1311 impl<'a> Extends<'a> {
1312 fn parse(i: &mut &'a str) -> ParseResult<'a, WithSpan<'a, Self>> {
1313 let start = *i;
1314 preceded(
1315 (opt(Whitespace::parse), ws(keyword("extends"))),
1316 cut_node(
1317 Some("extends"),
1318 terminated(ws(str_lit_without_prefix), opt(Whitespace::parse)),
1319 ),
1320 )
1321 .map(|path| WithSpan::new(Self { path }, start))
1322 .parse_next(i)
1323 }
1324 }
1325
1326 #[derive(Debug, PartialEq)]
1327 pub struct Comment<'a> {
1328 pub ws: Ws,
1329 pub content: &'a str,
1330 }
1331
1332 impl<'a> Comment<'a> {
1333 fn parse(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, WithSpan<'a, Self>> {
1334 #[derive(Debug, Clone, Copy)]
1335 enum Tag {
1336 Open,
1337 Close,
1338 }
1339
1340 fn tag<'a>(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a, Tag> {
1341 alt((
1342 (|i: &mut _| s.tag_comment_start(i)).value(Tag::Open),
1343 (|i: &mut _| s.tag_comment_end(i)).value(Tag::Close),
1344 ))
1345 .parse_next(i)
1346 }
1347
1348 fn content<'a>(i: &mut &'a str, s: &State<'_, '_>) -> ParseResult<'a> {
1349 let mut depth = 0usize;
1350 let start = *i;
1351 loop {
1352 let splitter = Splitter2::new(s.syntax.comment_start, s.syntax.comment_end);
1353 let tag = opt(skip_till(splitter, |i: &mut _| tag(i, s))).parse_next(i)?;
1354 let Some((inclusive, tag)) = tag else {
1355 return Err(
1356 ErrorContext::unclosed("comment", s.syntax.comment_end, start).cut(),
1357 );
1358 };
1359 match tag {
1360 Tag::Open => match depth.checked_add(1) {
1361 Some(new_depth) => depth = new_depth,
1362 None => {
1363 return Err(winnow::error::ErrMode::Cut(ErrorContext::new(
1364 "too deeply nested comments",
1365 start,
1366 )));
1367 }
1368 },
1369 Tag::Close => match depth.checked_sub(1) {
1370 Some(new_depth) => depth = new_depth,
1371 None => {
1372 let exclusive = *i;
1373 *i = inclusive;
1374 return Ok(&start[..start.len() - exclusive.len()]);
1375 }
1376 },
1377 }
1378 *i = inclusive;
1379 }
1380 }
1381
1382 let start = *i;
1383 let content = preceded(
1384 |i: &mut _| s.tag_comment_start(i),
1385 cut_node(Some("comment"), |i: &mut _| content(i, s)),
1386 )
1387 .parse_next(i)?;
1388
1389 let mut ws = Ws(None, None);
1390 if content.len() == 1 && matches!(content, "-" | "+" | "~") {
1391 return Err(winnow::error::ErrMode::Cut(ErrorContext::new(
1392 format!(
1393 "ambiguous whitespace stripping\n\
1394 use `{}{content} {content}{}` to apply the same whitespace stripping on both \
1395 sides",
1396 s.syntax.comment_start, s.syntax.comment_end,
1397 ),
1398 start,
1399 )));
1400 } else if content.len() >= 2 {
1401 ws.0 = Whitespace::parse_char(content.chars().next().unwrap_or_default());
1402 ws.1 = Whitespace::parse_char(content.chars().next_back().unwrap_or_default());
1403 }
1404
1405 Ok(WithSpan::new(Self { ws, content }, start))
1406 }
1407 }
1408
1409 /// First field is "minus/plus sign was used on the left part of the item".
1410 ///
1411 /// Second field is "minus/plus sign was used on the right part of the item".
1412 #[derive(Clone, Copy, Debug, PartialEq)]
1413 pub struct Ws(pub Option<Whitespace>, pub Option<Whitespace>);
1414
1415 fn end_node<'a, 'g: 'a>(
1416 node: &'g str,
1417 expected: &'g str,
1418 ) -> impl ModalParser<&'a str, &'a str, ErrorContext<'a>> + 'g {
1419 move |i: &mut &'a str| {
1420 let start = i.checkpoint();
1421 let actual = ws(identifier).parse_next(i)?;
1422 if actual == expected {
1423 Ok(actual)
1424 } else if actual.starts_with("end") {
1425 i.reset(&start);
1426 Err(winnow::error::ErrMode::Cut(ErrorContext::new(
1427 format!("expected `{expected}` to terminate `{node}` node, found `{actual}`"),
1428 *i,
1429 )))
1430 } else {
1431 i.reset(&start);
1432 fail.parse_next(i)
1433 }
1434 }
1435 }