docx-templating 1.0.0

Rust library for DOCX templating with variable replacement, conditionals, and loops
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
//! winnow-based parser for template syntax.
//!
//! This module implements a single-pass parser using winnow combinators.
//! The parser converts template strings into AST nodes.

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};

/// Parse a complete template into a vector of nodes.
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),
            })
        }
    }
}

/// Parse a standalone expression, rejecting trailing input.
///
/// Used by the binding layer to read the condition of an `if` tag and the
/// iterable of a `for` tag without wrapping them in a variable placeholder.
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)
}

/// Top-level parser that parses a sequence of nodes until end of input.
fn template_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Vec<Node>> {
    repeat(0.., node_parser).parse_next(input)
}

/// Parse a single node (text, variable, block, or comment).
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)
}

/// Parse a comment: `{# ... #}`.
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),
    }))
}

/// Parse a variable placeholder: `{{expression}}`.
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),
    }))
}

/// Parse an expression, including comparisons and boolean logic.
fn expression_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Expression> {
    or_expression_parser.parse_next(input)
}

/// Parse `or` separated expressions, the lowest precedence.
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))
}

/// Parse `and` separated expressions.
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))
}

/// Fold a left associative chain of the same logical operator.
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),
        })
    })
}

/// Parse `not expression` or a comparison.
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)
}

/// Parse one comparison or a plain value.
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,
    })
}

/// Parse a comparison operator.
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)
}

/// Parse an arithmetic expression, then any filters.
///
/// A filter applies to the whole arithmetic result, so
/// `price * quantity | fixed: 2` formats the product. To format one operand,
/// group it first: `(price | round: 2) * quantity`.
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,
        }))
    }
}

/// Parse `+` and `-` separated terms, the lowest arithmetic precedence.
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))
}

/// Parse an additive operator.
fn additive_operator_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<ArithmeticOperator> {
    one_of(('+', '-'))
        .map(|operator| match operator {
            '+' => ArithmeticOperator::Add,
            _ => ArithmeticOperator::Subtract,
        })
        .parse_next(input)
}

/// Parse `*`, `/` and `%` separated factors.
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))
}

/// Parse a multiplicative operator.
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)
}

/// Fold a left associative chain of arithmetic operators.
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),
        })
    })
}

/// Parse a negative expression or a primary value.
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)
}

/// Parse a parenthesized expression, a literal or a path.
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)
}

/// Parse a parenthesized expression: `(expression)`.
fn parenthesized_expression_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Expression> {
    delimited((space0, '('), expression_parser, (space0, ')')).parse_next(input)
}

/// Parse a quoted string literal.
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)
}

/// Parse a string literal with backslash escapes.
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)
}

/// Parse a number literal and keep its source spelling.
///
/// A number only counts as a literal when it is not the first segment of a
/// longer path, so `items.0` stays a path while `total > 100` compares against
/// the number one hundred.
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)
}

/// Whether a character continues a path, so a number before it is a path
/// segment rather than a literal.
fn is_path_continuation(c: char) -> bool {
    c.is_alphanumeric() || matches!(c, '_' | '.')
}

/// Parse a number: `42`, `-1`, `2.5`, `1e3`.
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)
}

/// Turn a standalone `true`, `false` or `null` path into a literal.
///
/// These names stay available as a path when they are part of a longer path or
/// carry a filter.
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,
    }
}

/// Parse one filter: `name` or `name: argument`.
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 })
}

/// Parse a filter name: letters, digits and underscores, with no `@` prefix.
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)
}

/// Parse a filter argument as a quoted string or a bare token.
fn filter_argument_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<String> {
    alt((quoted_argument_parser, bare_argument_parser)).parse_next(input)
}

/// Parse a quoted argument. Both quote styles are accepted, and the text runs
/// to the matching quote.
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())
}

/// Parse an unquoted argument such as `2`, `de_DE` or `false`.
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)
}

/// Parse a path expression.
fn path_expression_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Expression> {
    path_parser.map(Expression::Path).parse_next(input)
}

/// Parse a path: `.`, `name`, `user.name`, `items.0`.
fn path_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Path> {
    // Handle current item: `.`
    // Use nth(1).map_or to safely handle the case where `.` is the only character
    // or is followed by a non-alphanumeric (e.g. `}}`, space, end of input).
    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))
}

/// Parse a single path segment: field name or numeric index.
fn path_segment_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<PathSegment> {
    alt((
        // dec_uint parses a decimal unsigned integer and fails cleanly on overflow —
        // no unwrap, no panic, no try_map boilerplate.
        dec_uint.map(PathSegment::Index),
        identifier_parser.map(PathSegment::Field),
    ))
    .parse_next(input)
}

/// Parse an identifier: an optional `@` prefix, then alphanumeric + underscore.
///
/// The `@` prefix marks loop metadata such as `@index`, `@first` and `@last`.
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)
}

/// Parse an if block: `{% if expr %}...{% elif expr %}...{% else %}...{% endif %}`.
fn block_if_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Node> {
    let start_pos = input.current_token_start();

    // Parse opening tag: {% if expr %}
    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),
    }))
}

/// Parse nodes until the next `elif`, `else` or `endif` tag, leaving that tag
/// in the input for the caller.
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)
}

/// Parse a for loop: `{% for item in items %}...{% endfor %}`.
fn block_for_parser(input: &mut LocatingSlice<&str>) -> winnow::Result<Node> {
    let start_pos = input.current_token_start();

    // Parse opening tag: {% for item in items %}
    let (item_name, iterable) = delimited(
        "{%",
        preceded(
            (space0, "for", space1),
            terminated(
                (
                    terminated(identifier_parser, (space1, "in", space1)),
                    expression_parser,
                ),
                space0,
            ),
        ),
        "%}",
    )
    .parse_next(input)?;

    // Parse body until {% endfor %}
    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),
    }))
}

/// Parse plain text (everything until next template syntax).
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),
    }))
}

/// Helper: try to parse `{% elif expr %}` tag, returning the condition.
fn try_elif_tag(input: &mut LocatingSlice<&str>) -> winnow::Result<Expression> {
    delimited(
        "{%",
        preceded(
            (space0, "elif", space1),
            terminated(expression_parser, space0),
        ),
        "%}",
    )
    .parse_next(input)
}

/// Helper: try to parse `{% else %}` tag.
fn try_else_tag(input: &mut LocatingSlice<&str>) -> winnow::Result<()> {
    delimited("{%", (space0, "else", space0), "%}")
        .void()
        .parse_next(input)
}

/// Helper: try to parse `{% endif %}` tag.
fn try_endif_tag(input: &mut LocatingSlice<&str>) -> winnow::Result<()> {
    delimited("{%", (space0, "endif", space0), "%}")
        .void()
        .parse_next(input)
}

/// Helper: try to parse `{% endfor %}` tag.
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"),
        }
    }

    // Snapshot tests for AST verification
    #[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:?}"),
        }
    }
}