mds-cli 0.4.2

MDS (Markdown Script) compiler — command-line interface
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
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
mod common;
use common::fixture;
use std::collections::HashMap;

#[test]
fn simple_variable_interpolation() {
    let result = mds::compile(fixture("simple.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(result.contains("Hello Alice!"));
    assert!(result.contains("You have 3 items."));
}

#[test]
fn conditional_truthy() {
    let result = mds::compile(fixture("conditional.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(result.contains("Thanks for being premium!"));
    assert!(!result.contains("Upgrade for premium features."));
}

#[test]
fn conditional_falsy() {
    let result = mds::compile(fixture("conditional_false.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(!result.contains("Thanks for being premium!"));
    assert!(result.contains("Upgrade for premium features."));
}

#[test]
fn loop_over_array() {
    let result = mds::compile(fixture("loop.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(result.contains("- apple"));
    assert!(result.contains("- banana"));
    assert!(result.contains("- cherry"));
}

#[test]
fn function_definition_and_call() {
    let result = mds::compile(fixture("function.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(result.contains("Hello Alice!"));
    assert!(result.contains("Hello Bob!"));
}

#[test]
fn escaped_braces() {
    let result = mds::compile(fixture("escaped.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(result.contains("{name}"));
}

#[test]
fn code_block_passthrough() {
    let result = mds::compile(fixture("code_block.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    // Inside code block: no interpolation should occur
    assert!(result.contains("{not_a_var}"));
    assert!(result.contains("{world}"));
    // Outside code block: interpolation should work
    assert!(result.contains("Hello Alice!"));
    assert!(result.contains("Goodbye Alice!"));
}

#[test]
fn runtime_vars_override() {
    let mut vars = HashMap::new();
    vars.insert(
        "name".to_string(),
        mds::Value::String("Override".to_string()),
    );
    let result = mds::compile(fixture("simple.mds"), Some(vars))
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(result.contains("Hello Override!"));
}

#[test]
fn complete_example_welcome() {
    let result = mds::compile(fixture("welcome.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(result.contains("Hello Alice!"));
    assert!(result.contains("- apple"));
    assert!(result.contains("- banana"));
    assert!(result.contains("Thanks for being premium!"));
    assert!(!result.contains("Upgrade for premium features."));
    assert!(result.contains("Thank you for using our service."));
}

#[test]
fn unicode_content() {
    let result = mds::compile(fixture("unicode.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(result.contains("Greetings Rene!"));
    assert!(result.contains("Hello"));
    // Code block content should not be interpolated
    assert!(result.contains("{not_interpolated}"));
    assert!(result.contains("Farewell Rene!"));
}

#[test]
fn compile_str_simple() {
    let source = "---\nname: World\n---\nHello {{name}}!\n";
    let result = mds::compile_str_with(source, None, None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(result.contains("Hello World!"));
}

#[test]
fn compile_str_no_frontmatter() {
    let result = mds::compile_str_with("Just plain text.", None, None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(result.contains("Just plain text."));
}

#[test]
fn nested_loops() {
    let result = mds::compile(fixture("nested_loops.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(result.contains("row1-col1"), "nested loops: row1-col1");
    assert!(result.contains("row1-col2"), "nested loops: row1-col2");
    assert!(result.contains("row2-col1"), "nested loops: row2-col1");
    assert!(result.contains("row2-col2"), "nested loops: row2-col2");
}

#[test]
fn function_called_in_loop() {
    let result = mds::compile(fixture("fn_in_loop.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(result.contains("Hello Alice!"), "fn in loop: Alice");
    assert!(result.contains("Hello Bob!"), "fn in loop: Bob");
    assert!(result.contains("Hello Charlie!"), "fn in loop: Charlie");
}

#[test]
fn loop_var_shadows_outer() {
    let result = mds::compile(fixture("loop_var_shadow.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    // Before loop, outer value
    assert!(
        result.contains("Before: outer_value"),
        "before loop: outer_value"
    );
    // During loop, inner values
    assert!(result.contains("- inner1"), "loop iteration: inner1");
    assert!(result.contains("- inner2"), "loop iteration: inner2");
    // After loop, restored outer value
    assert!(
        result.contains("After: outer_value"),
        "after loop: outer_value restored"
    );
}

#[test]
fn function_param_shadows_outer() {
    let result = mds::compile(fixture("fn_param_shadow.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(
        result.contains("Before: outer"),
        "before fn call: outer name"
    );
    assert!(
        result.contains("Hello inner!"),
        "inside fn: param shadows outer"
    );
    assert!(
        result.contains("After: outer"),
        "after fn call: outer name restored"
    );
}

#[test]
fn nested_function_calls_in_interpolation() {
    let result = mds::compile(fixture("nested_fn_calls.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    // outer(inner("arg")) => outer("arg!") => "[arg!]"
    assert!(
        result.contains("[arg!]"),
        "nested fn calls should produce '[arg!]', got: {result}"
    );
}

#[test]
fn multiple_escaped_braces() {
    let result = mds::compile(fixture("multiple_escaped_braces.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    // In the new syntax, {a} and {b} are literal text (single braces = literal).
    // The fixture uses `{a} and {b}` which outputs them verbatim.
    assert!(
        result.contains("{a") && result.contains("{b"),
        "single-brace text should appear literally in output, got: {result}"
    );
}

#[test]
fn if_falsy_zero() {
    let result = mds::compile(fixture("if_falsy_zero.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(
        result.contains("falsy"),
        "zero should be falsy, got: {result}"
    );
    assert!(
        !result.contains("truthy"),
        "zero should not be truthy, got: {result}"
    );
}

#[test]
fn if_falsy_null() {
    let result = mds::compile(fixture("if_falsy_null.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(
        result.contains("falsy"),
        "null should be falsy, got: {result}"
    );
}

#[test]
fn if_falsy_empty_string() {
    let result = mds::compile(fixture("if_falsy_empty_string.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(
        result.contains("falsy"),
        "empty string should be falsy, got: {result}"
    );
}

#[test]
fn if_falsy_empty_array() {
    let result = mds::compile(fixture("if_falsy_empty_array.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(
        result.contains("falsy"),
        "empty array should be falsy, got: {result}"
    );
}

#[test]
fn if_falsy_boolean_false() {
    // `false` is explicitly listed as a falsy value in Spec 4.3.
    let result = mds::compile(fixture("if_falsy_false.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(
        result.contains("falsy"),
        "boolean false should be falsy, got: {result}"
    );
    assert!(
        !result.contains("truthy"),
        "boolean false should not be truthy, got: {result}"
    );
}

#[test]
fn mutual_recursion_detected() {
    let result = mds::compile(fixture("mutual_recursion.mds"), None);
    assert!(result.is_err(), "mutual recursion should be detected");
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("recursion"),
        "expected recursion error, got: {err}"
    );
}

#[test]
fn crlf_line_endings() {
    // A fixture with Windows (CRLF) line endings must compile without error
    // and produce the same output as its LF counterpart.
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("crlf.mds");
    // Write the file with \r\n line endings (Windows style).
    std::fs::write(&path, b"---\r\nname: Alice\r\n---\r\nHello {{name}}!\r\n").unwrap();

    let result = mds::compile(&path, None).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("Hello Alice!"),
        "CRLF line endings should compile correctly, got: {result}"
    );
}

#[test]
fn multi_param_function() {
    // @define welcome(name, role): with two params, per spec section 4.5
    let result = mds::compile(fixture("multi_param.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(
        result.contains("Hello Alice! You are logged in as admin."),
        "two-param function call with string literals should render correctly, got: {result}"
    );
    assert!(
        result.contains("Hello Bob! You are logged in as editor."),
        "second two-param call should render correctly, got: {result}"
    );
}

#[test]
fn single_quote_string_literal_in_function_args() {
    // {greet('Alice')} — single-quoted string literals in function arguments.
    // The parser already supports this; this test locks in the behaviour.
    let result = mds::compile(fixture("single_quote_args.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(
        result.contains("Hello Alice!"),
        "single-quoted arg should produce same output as double-quoted, got: {result}"
    );
    assert!(
        result.contains("Hello Bob!"),
        "second single-quoted arg call should render correctly, got: {result}"
    );
}

#[test]
fn zero_parameter_function() {
    // @define separator(): produces a fixed separator string with no params
    let source = "@define separator():\n---\n@end\n{{separator()}}\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("---"),
        "zero-parameter function should produce its body, got: {result}"
    );
}

#[test]
fn empty_function_body() {
    // @define empty(): @end — calling it should succeed and produce empty string
    let source = "@define empty():\n@end\nBefore{{empty()}}After\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("BeforeAfter"),
        "empty function body should produce empty string, got: {result}"
    );
}

#[test]
fn deeply_nested_conditionals() {
    let source = "---\na: true\nb: true\nc: true\n---\n\
        @if a:\n\
        @if b:\n\
        @if c:\n\
        deep\n\
        @end\n\
        @end\n\
        @end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("deep"),
        "3-level nested @if should reach innermost body, got: {result}"
    );
}

#[test]
fn function_returning_inner_call() {
    let source = "\
        @define inner():\n\
        inner-result\n\
        @end\n\
        @define outer():\n\
        {{inner()}}\n\
        @end\n\
        {{outer()}}\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("inner-result"),
        "outer() should return result of inner(), got: {result}"
    );
}

#[test]
fn loop_single_element_array() {
    let source = "---\nitems: [only]\n---\n@for item in items:\n- {{item}}\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("- only"),
        "single-element array loop should produce one item, got: {result}"
    );
}

#[test]
fn escaped_brace_inside_function_body() {
    // In the new syntax, single braces are literal text — no backslash escape needed.
    // {literal} inside a @define body outputs as the literal string "{literal}".
    let source = "@define show():\n{literal}\n@end\n{{show()}}\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("{literal}"),
        "single-brace text inside function body should render as literal, got: {result}"
    );
}

#[test]
fn variable_interpolation_in_function_argument() {
    // {{greet(name)}} calls greet with the frontmatter variable `name`
    let source =
        "---\nname: Alice\n---\n@define greet(who):\nHello {{who}}!\n@end\n{{greet(name)}}\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("Hello Alice!"),
        "variable passed as function argument should be resolved, got: {result}"
    );
}

#[test]
fn escaped_braces_in_function_body() {
    // In the new syntax, single braces are literal text — {curly braces} appears verbatim
    // while {{x}} interpolates the parameter. So the fixture produces:
    // "Use {curly braces} for interpolation: Alice"
    let result = mds::compile(fixture("escaped_brace_in_fn.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(
        result.contains("{curly braces"),
        "single-brace text in function body should appear literally, got: {result}"
    );
    assert!(
        result.contains("Alice"),
        "double-brace interpolation inside function body should resolve the param, got: {result}"
    );
}

#[test]
fn escaped_braces_in_blocks() {
    // In the new syntax, {variable} and {item} on the left side are literal text.
    // {{item}} on the right interpolates the loop variable.
    // @if body: "Syntax: {variable}"
    // @for body: "{item} = a" and "{item} = b"
    let result = mds::compile(fixture("escaped_brace_in_blocks.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(
        result.contains("{variable"),
        "single-brace text in @if body should appear literally, got: {result}"
    );
    assert!(
        result.contains("{item") && result.contains("= a"),
        "single-brace literal {{item}} in @for body with interpolated value 'a', got: {result}"
    );
    assert!(
        result.contains("{item") && result.contains("= b"),
        "single-brace literal {{item}} in @for body with interpolated value 'b', got: {result}"
    );
}

#[test]
fn single_close_brace_is_literal() {
    // In the new syntax, a lone `}` is already literal — no escape needed.
    let result = mds::compile_str("Use } to close.")
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(
        result.contains('}'),
        "lone `}}` should appear literally in output, got: {result}"
    );
}

#[test]
fn double_brace_escape_produces_literal_double_brace() {
    // `\{{` is the escape for a literal `{{` in output.
    // `}}` (closing double-brace) is already literal text — no escape needed.
    let result = mds::compile_str("\\{{not interpolated}}")
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(
        result.contains("{{not interpolated}}"),
        "\\{{...}} should produce literal `{{{{...}}}}` in output, got: {result}"
    );
}

#[test]
fn single_brace_in_function_body_is_literal() {
    // In the new syntax, `}` inside a @define body is already literal — no backslash needed.
    // Call uses double-brace interpolation `{{show()}}`.
    let source = "@define show():\nresult}\n@end\n{{show()}}\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("result}"),
        "bare `}}` inside function body should render as literal `}}`, got: {result}"
    );
}

#[test]
fn loop_var_not_visible_after_loop() {
    // The loop variable is scoped to the @for...@end block.
    // After the loop, attempting to use it with {{item}} should fail.
    let source = "---\nitems: [a, b]\n---\n@for item in items:\n- {{item}}\n@end\n{{item}}\n";
    let result = mds::compile_str(source);
    assert!(
        result.is_err(),
        "loop variable should not be visible after @end"
    );
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("item") || err.contains("undefined"),
        "error should mention undefined 'item' after loop, got: {err}"
    );
}

#[test]
fn function_param_not_visible_outside_function() {
    // Function parameters are scoped to the function body.
    // After the call, {{name}} should fail — no frontmatter `name` in scope.
    let source = "@define greet(name):\nHello {{name}}!\n@end\n{{greet(\"Alice\")}}\n{{name}}\n";
    let result = mds::compile_str(source);
    assert!(
        result.is_err(),
        "function param should not be visible outside function body"
    );
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("name") || err.contains("undefined"),
        "error should mention undefined 'name' outside function, got: {err}"
    );
}

#[test]
fn compile_str_empty_frontmatter() {
    // "---\n---\n" is valid: empty frontmatter with no variables.
    let source = "---\n---\nHello World!\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("Hello World!"),
        "empty frontmatter should compile cleanly, got: {result}"
    );
}

#[test]
fn compile_str_truly_no_frontmatter() {
    // Source with no --- fences at all is valid per spec (frontmatter is optional).
    let source = "@define greet(name):\nHi {{name}}!\n@end\n{{greet(\"World\")}}\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("Hi World!"),
        "source with no frontmatter and @define should compile, got: {result}"
    );
}

#[test]
fn for_null_iterable_rejected_at_check_time() {
    // Per spec: iterating over a non-array is a compilation error.
    // `null` must be rejected at validation time so `mds check` and `mds build`
    // both fail consistently — the validator must not accept Value::Null.
    let result = mds::check(fixture("for_null_iterable.mds"), None);
    assert!(
        result.is_err(),
        "@for over a null iterable must fail at check time (validator)"
    );
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("array") || err.contains("type error") || err.contains("null"),
        "error should mention array/type mismatch, got: {err}"
    );
}

#[test]
fn for_null_iterable_rejected_at_build_time() {
    // Same fixture — build must also fail (was already failing; test documents
    // that check and build agree after removing Null from the validator allowlist).
    let result = mds::compile(fixture("for_null_iterable.mds"), None);
    assert!(
        result.is_err(),
        "@for over a null iterable must fail at build time (evaluator)"
    );
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("array") || err.contains("type error") || err.contains("null"),
        "error should mention array/type mismatch, got: {err}"
    );
}

#[test]
fn empty_array_loop() {
    // Iterating over an empty array should produce no output for the loop body
    let mut vars = HashMap::new();
    vars.insert("items".to_string(), mds::Value::Array(vec![]));
    let result = mds::compile(fixture("loop.mds"), Some(vars))
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(!result.contains("- apple"));
    assert!(!result.contains("- banana"));
}

#[test]
fn md_file_with_type_mds_compiles() {
    // Per spec section 9.2: a .md file with type: mds in frontmatter should compile
    let result = mds::compile(fixture("type_mds_md_file.md"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(
        result.contains("Hello World!"),
        "md file with type:mds should compile, got: {result}"
    );
}

#[test]
fn function_calls_function() {
    let result = mds::compile(fixture("fn_calls_fn.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(result.contains("[Alice]"));
}

#[test]
fn recursion_detected() {
    let result = mds::compile(fixture("recursive.mds"), None);
    assert!(result.is_err());
    let err = format!("{}", result.unwrap_err());
    assert!(err.contains("recursion"));
}

#[test]
fn nested_conditionals() {
    let result = mds::compile(fixture("nested_if.mds"), None)
        .unwrap()
        .into_markdown()
        .unwrap();
    assert!(result.contains("outer true"));
    assert!(result.contains("inner false"));
    assert!(!result.contains("inner true"));
    assert!(!result.contains("outer false"));
}

#[test]
fn vars_file_loading() {
    let dir = tempfile::tempdir().unwrap();
    let vars_path = dir.path().join("vars.json");
    std::fs::write(&vars_path, r#"{"name": "FromJSON", "count": 99}"#).unwrap();

    let vars = mds::load_vars_file(&vars_path).unwrap();
    assert_eq!(
        vars.get("name"),
        Some(&mds::Value::String("FromJSON".to_string()))
    );
    assert_eq!(vars.get("count"), Some(&mds::Value::Number(99.0)));
}

#[test]
fn check_valid_file() {
    let result = mds::check(fixture("simple.mds"), None);
    assert!(result.is_ok());
}

#[test]
fn check_invalid_file() {
    let result = mds::check(fixture("undefined_var.mds"), None);
    assert!(result.is_err());
}

#[test]
fn compile_file_compiles_valid_mds() {
    // compile_file is a thin wrapper over compile(); verify it produces correct output
    let path = fixture("simple.mds");
    let path_str = path.to_str().expect("fixture path is valid UTF-8");
    let result = mds::compile_file(path_str);
    assert!(
        result.is_ok(),
        "compile_file should succeed, got: {result:?}"
    );
    let output = result.unwrap().into_markdown().unwrap();
    assert!(
        output.contains("Hello Alice!"),
        "compile_file output should contain 'Hello Alice!', got: {output}"
    );
}

#[test]
fn compile_file_returns_error_for_nonexistent_path() {
    let result = mds::compile_file("nonexistent_file_that_does_not_exist.mds");
    assert!(
        result.is_err(),
        "compile_file should fail for nonexistent file"
    );
    let err = result.unwrap_err();
    let msg = format!("{err}");
    assert!(
        msg.contains("nonexistent") || msg.contains("not found") || msg.contains("No such"),
        "error should describe the missing file, got: {msg}"
    );
}

// ── @if negation (!var) tests ────────────────────────────────────────────────

#[test]
fn if_negation_truthy_variable_skips_then_body() {
    // `@if !premium:` with premium=true → else branch executes
    let source = "---\npremium: true\n---\n@if !premium:\nfree_tier\n@else:\npaid_tier\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("paid_tier"),
        "negation of true must take else branch"
    );
    assert!(!result.contains("free_tier"), "then body must be skipped");
}

#[test]
fn if_negation_falsy_variable_enters_then_body() {
    // `@if !premium:` with premium=false → then branch executes
    let source = "---\npremium: false\n---\n@if !premium:\nfree_tier\n@else:\npaid_tier\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("free_tier"),
        "negation of false must take then branch"
    );
    assert!(!result.contains("paid_tier"), "else body must be skipped");
}

#[test]
fn if_negation_zero_is_truthy_branch() {
    // `@if !count:` with count=0 → 0 is falsy, so !0 is truthy
    let source = "---\ncount: 0\n---\n@if !count:\nzero_branch\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("zero_branch"),
        "negation of 0 must enter then branch"
    );
}

#[test]
fn if_negation_empty_string_is_truthy_branch() {
    // `@if !name:` with name="" → empty string is falsy, so !name is truthy
    let source = "---\nname: \"\"\n---\n@if !name:\nempty_branch\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("empty_branch"),
        "negation of empty string must enter then branch"
    );
}

#[test]
fn if_negation_null_is_truthy_branch() {
    // `@if !val:` with val=null → null is falsy, so !val is truthy
    let source = "---\nval: null\n---\n@if !val:\nnull_branch\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("null_branch"),
        "negation of null must enter then branch"
    );
}

#[test]
fn if_negation_dot_path() {
    // `@if !config.debug:` with config.debug=false → enters then branch
    let source = "---\nconfig:\n  debug: false\n---\n@if !config.debug:\ndebug_off_branch\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("debug_off_branch"),
        "negation of config.debug=false must enter then branch"
    );
}

// ── @if negation with undefined variable tests ───────────────────────────────

#[test]
fn if_negation_undefined_variable_is_error() {
    // `@if !undefined_var:` with no frontmatter defining undefined_var → error
    let source = "@if !undefined_var:\nbranch_body\n@end\n";
    let result = mds::compile_str(source);
    assert!(
        result.is_err(),
        "negation of undefined variable must produce an error, got: {:?}",
        result
    );
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("undefined_var") || err.contains("undefined") || err.contains("not found"),
        "error should mention the undefined variable, got: {err}"
    );
}

// ── @if equality (==) tests ──────────────────────────────────────────────────

#[test]
fn if_eq_string_match_enters_then_body() {
    // `@if role == "admin":` with role=admin → then branch
    let source =
        "---\nrole: admin\n---\n@if role == \"admin\":\nadmin_yes\n@else:\nadmin_no\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("admin_yes"),
        "exact string match must enter then branch"
    );
    assert!(!result.contains("admin_no"), "else body must not appear");
}

#[test]
fn if_eq_string_no_match_enters_else_body() {
    // `@if role == "admin":` with role=user → else branch
    let source =
        "---\nrole: user\n---\n@if role == \"admin\":\nadmin_yes\n@else:\nadmin_no\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("admin_no"),
        "string mismatch must take else branch"
    );
    assert!(!result.contains("admin_yes"), "then body must not appear");
}

#[test]
fn if_eq_number_match() {
    // `@if count == 42:` with count=42 → then branch
    let source =
        "---\ncount: 42\n---\n@if count == 42:\ncount_match\n@else:\ncount_nomatch\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("count_match") && !result.contains("count_nomatch"),
        "number equality must match"
    );
}

#[test]
fn if_eq_bool_true_match() {
    // `@if active == true:` with active=true → then branch
    let source =
        "---\nactive: true\n---\n@if active == true:\nactive_on\n@else:\nactive_off\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("active_on") && !result.contains("active_off"),
        "bool true equality must match"
    );
}

#[test]
fn if_eq_null_match() {
    // `@if val == null:` with val=null → then branch
    let source = "---\nval: null\n---\n@if val == null:\nnull_matches\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(result.contains("null_matches"), "null equality must match");
}

#[test]
fn if_eq_strict_no_type_coercion_number_vs_string() {
    // `@if x == "3":` with x=3 (number) → cross-type comparison is now a TypeMismatch error
    let source = "---\nx: 3\n---\n@if x == \"3\":\ncoercion_yes\n@else:\nstrict_types\n@end\n";
    let err = mds::compile_str(source).unwrap_err();
    let msg = format!("{err}");
    assert!(
        msg.contains("type mismatch") || msg.contains("mds::type_mismatch"),
        "number == string must be a TypeMismatch error, got: {msg}"
    );
}

#[test]
fn if_eq_strict_no_type_coercion_bool_vs_string() {
    // `@if x == "true":` with x=true (bool) → cross-type comparison is now a TypeMismatch error
    let source =
        "---\nx: true\n---\n@if x == \"true\":\ncoercion_yes\n@else:\nstrict_types\n@end\n";
    let err = mds::compile_str(source).unwrap_err();
    let msg = format!("{err}");
    assert!(
        msg.contains("type mismatch") || msg.contains("mds::type_mismatch"),
        "bool == string must be a TypeMismatch error, got: {msg}"
    );
}

#[test]
fn if_eq_single_quoted_rhs() {
    // `@if role == 'admin':` with role=admin → then branch (single quotes)
    let source = "---\nrole: admin\n---\n@if role == 'admin':\nadmin_singlequote\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("admin_singlequote"),
        "single-quoted RHS must work"
    );
}

#[test]
fn if_eq_empty_string_rhs() {
    // `@if name == "":` with name="" → then branch
    let source = "---\nname: \"\"\n---\n@if name == \"\":\nempty_name_branch\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("empty_name_branch"),
        "empty string equality must match"
    );
}

#[test]
fn if_eq_operator_in_string_rhs() {
    // `@if msg == "a == b":` with msg="a == b" → then branch
    // The `==` inside the string must not be mistaken for the operator
    let source = "---\nmsg: \"a == b\"\n---\n@if msg == \"a == b\":\nop_inside_string_match\n@else:\nop_inside_string_nomatch\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("op_inside_string_match"),
        "operator inside string must not confuse the parser"
    );
    assert!(
        !result.contains("op_inside_string_nomatch"),
        "nomatch branch must not appear"
    );
}

#[test]
fn if_eq_negative_number() {
    // `@if temp == -5:` with temp=-5 → then branch
    let source = "---\ntemp: -5\n---\n@if temp == -5:\ncold_branch\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("cold_branch"),
        "negative number equality must match"
    );
}

#[test]
fn if_eq_float() {
    // `@if rate == 3.14:` with rate=3.14 → then branch
    let source = "---\nrate: 3.14\n---\n@if rate == 3.14:\nfloat_match\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(result.contains("float_match"), "float equality must match");
}

// ── @if inequality (!=) tests ────────────────────────────────────────────────

#[test]
fn if_neq_string_no_match_enters_then_body() {
    // `@if role != "admin":` with role=user → then branch
    let source = "---\nrole: user\n---\n@if role != \"admin\":\nnot_admin_branch\n@else:\nis_admin_branch\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("not_admin_branch"),
        "inequality with non-matching value must enter then branch"
    );
    assert!(!result.contains("is_admin_branch"), "else must not appear");
}

#[test]
fn if_neq_string_match_enters_else_body() {
    // `@if role != "admin":` with role=admin → else branch
    let source = "---\nrole: admin\n---\n@if role != \"admin\":\nnot_admin_branch\n@else:\nis_admin_branch\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("is_admin_branch"),
        "inequality with matching value must take else branch"
    );
    assert!(
        !result.contains("not_admin_branch"),
        "then branch must not appear"
    );
}

#[test]
fn if_neq_cross_type_errors() {
    // `@if x != "3":` with x=3 (number) → type mismatch: number vs string is an error
    let source =
        "---\nx: 3\n---\n@if x != \"3\":\ndiff_type_branch\n@else:\nsame_type_branch\n@end\n";
    let err = mds::compile_str(source).unwrap_err();
    let msg = format!("{err}");
    assert!(
        msg.contains("type mismatch") || msg.contains("mds::type_mismatch"),
        "cross-type != must be a TypeMismatch error, got: {msg}"
    );
}

// ── @elseif tests ───────────────────────────────────────────────────────────

#[test]
fn elseif_first_branch_matches() {
    // tier=enterprise → first branch matches
    let source = "---\ntier: enterprise\n---\n@if tier == \"enterprise\":\nenterprise_body\n@elseif tier == \"pro\":\npro_body\n@else:\nfree_body\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("enterprise_body"),
        "enterprise branch must match"
    );
    assert!(!result.contains("pro_body"), "pro branch must not appear");
    assert!(!result.contains("free_body"), "else branch must not appear");
}

#[test]
fn elseif_second_branch_matches() {
    // tier=pro → second branch matches
    let source = "---\ntier: pro\n---\n@if tier == \"enterprise\":\nenterprise_body\n@elseif tier == \"pro\":\npro_body\n@else:\nfree_body\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(result.contains("pro_body"), "pro branch must match");
    assert!(
        !result.contains("enterprise_body"),
        "enterprise branch must not appear"
    );
    assert!(!result.contains("free_body"), "else branch must not appear");
}

#[test]
fn elseif_falls_through_to_else() {
    // tier=starter → falls through to @else
    let source = "---\ntier: starter\n---\n@if tier == \"enterprise\":\nenterprise_body\n@elseif tier == \"pro\":\npro_body\n@else:\nfree_body\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("free_body"),
        "unmatched tiers must fall through to else"
    );
    assert!(
        !result.contains("enterprise_body"),
        "enterprise branch must not appear"
    );
    assert!(!result.contains("pro_body"), "pro branch must not appear");
}

#[test]
fn elseif_no_match_no_else_empty_output() {
    // No matching branch and no @else → only frontmatter in output
    let source = "---\ntier: starter\n---\n@if tier == \"enterprise\":\nenterprise_body\n@elseif tier == \"pro\":\npro_body\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        !result.contains("enterprise_body"),
        "unmatched must produce no enterprise output"
    );
    assert!(
        !result.contains("pro_body"),
        "unmatched must produce no pro output"
    );
}

#[test]
fn elseif_five_branches_matches_fourth() {
    // Five @elseif branches, match on branch 4
    let source = "---\nval: delta\n---\n@if val == \"alpha\":\nalpha_out\n@elseif val == \"bravo\":\nbravo_out\n@elseif val == \"charlie\":\ncharlie_out\n@elseif val == \"delta\":\ndelta_out\n@elseif val == \"echo\":\necho_out\n@else:\nother_out\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(result.contains("delta_out"), "fourth branch must match");
    assert!(
        !result.contains("alpha_out"),
        "alpha branch must not appear"
    );
    assert!(
        !result.contains("bravo_out"),
        "bravo branch must not appear"
    );
    assert!(
        !result.contains("charlie_out"),
        "charlie branch must not appear"
    );
    assert!(!result.contains("echo_out"), "echo branch must not appear");
    assert!(!result.contains("other_out"), "else branch must not appear");
}

#[test]
fn elseif_with_truthiness() {
    // `@if flag_a:` / `@elseif flag_b:` — truthiness conditions
    let source = "---\nflag_a: false\nflag_b: true\n---\n@if flag_a:\nbranch_a\n@elseif flag_b:\nbranch_b\n@else:\nbranch_none\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(result.contains("branch_b"), "elseif truthiness must work");
    assert!(!result.contains("branch_a"), "first branch must not appear");
}

#[test]
fn elseif_with_negation() {
    // `@if flag_x:` / `@elseif !flag_y:` — negation in elseif
    let source = "---\nflag_x: false\nflag_y: false\n---\n@if flag_x:\nbranch_x\n@elseif !flag_y:\nbranch_not_y\n@else:\nbranch_none\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("branch_not_y"),
        "negation in elseif must work"
    );
    assert!(!result.contains("branch_x"), "x branch must not appear");
}

#[test]
fn elseif_with_equality() {
    // `@elseif role == "mod":` — equality in elseif
    let source = "---\nrole: mod\n---\n@if role == \"admin\":\nadmin_body\n@elseif role == \"mod\":\nmod_body\n@else:\nother_body\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(result.contains("mod_body"), "equality in elseif must work");
    assert!(
        !result.contains("admin_body"),
        "admin branch must not appear"
    );
}

#[test]
fn elseif_nested_if_in_body() {
    // Nested @if inside @elseif body
    let source = "---\ntier: pro\nextra: true\n---\n@if tier == \"enterprise\":\nenterprise_body\n@elseif tier == \"pro\":\n@if extra:\npro_plus_body\n@else:\npro_basic_body\n@end\n@else:\nfree_body\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("pro_plus_body"),
        "nested @if inside elseif body must work"
    );
    assert!(
        !result.contains("enterprise_body"),
        "enterprise must not appear"
    );
}

#[test]
fn elseif_mixed_equality_and_inequality_in_chain() {
    // Chain: @if role == "admin" / @elseif role != "visitor" / @else
    // role=mod → first branch (==) fails, second branch (!=) is true → middle branch
    let source = "---\nrole: mod\n---\n\
        @if role == \"admin\":\nadmin_only\n\
        @elseif role != \"visitor\":\nregistered_user\n\
        @else:\nanon_visitor\n\
        @end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("registered_user"),
        "mod != visitor so != branch must match"
    );
    assert!(
        !result.contains("admin_only"),
        "admin branch must not appear"
    );
    assert!(
        !result.contains("anon_visitor"),
        "else branch must not appear"
    );

    // role=visitor → first branch (==) fails, second branch (!=) is false → else branch
    let source2 = "---\nrole: visitor\n---\n\
        @if role == \"admin\":\nadmin_only\n\
        @elseif role != \"visitor\":\nregistered_user\n\
        @else:\nanon_visitor\n\
        @end\n";
    let result2 = mds::compile_str(source2).unwrap().into_markdown().unwrap();
    assert!(
        result2.contains("anon_visitor"),
        "visitor == visitor so != is false, must fall to else"
    );
    assert!(
        !result2.contains("registered_user"),
        "registered branch must not appear"
    );
    assert!(
        !result2.contains("admin_only"),
        "admin branch must not appear"
    );
}

#[test]
fn elseif_short_circuit_only_matched_branch_evaluates() {
    // Short-circuit: once a branch matches, subsequent @elseif are not evaluated.
    let source = "---\nval: first\n---\n@if val == \"first\":\nfirst_match_body\n@elseif val == \"first\":\nduplicate_match_body\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("first_match_body"),
        "first matching branch must win"
    );
    assert!(
        !result.contains("duplicate_match_body"),
        "subsequent branches must be skipped"
    );
}

// ── Built-in function tests ───────────────────────────────────────────────

#[test]
fn builtin_upper_golden_path() {
    // mds build code path: {upper(word)} produces uppercase output
    let source = "---\nword: hello\n---\n{{upper(word)}}\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("HELLO"),
        "upper() should uppercase the string, got: {result}"
    );
}

#[test]
fn builtin_lower_golden_path() {
    let source = "---\nword: WORLD\n---\n{{lower(word)}}\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("world"),
        "lower() should lowercase the string, got: {result}"
    );
}

#[test]
fn builtin_trim_golden_path() {
    // Use compile_str_with to avoid frontmatter passthrough containing the raw value
    let source = "@define show(w):\n{{trim(w)}}\n@end\n{{show(\"  hi  \")}}\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("hi"),
        "trim() should strip whitespace, got: {result}"
    );
    assert!(
        !result.contains("  hi  "),
        "trim() should remove surrounding spaces, got: {result}"
    );
}

#[test]
fn builtin_length_string_golden_path() {
    let source = "---\nword: hello\n---\n{{length(word)}}\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains('5'),
        "length() of 'hello' should be 5, got: {result}"
    );
}

#[test]
fn builtin_join_split_golden_path() {
    // Compose split + join: split("a,b,c", ",") then join with " | "
    let source = "---\ncsv: a,b,c\n---\n{{join(split(csv, \",\"), \" | \")}}\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("a | b | c"),
        "join(split()) should produce 'a | b | c', got: {result}"
    );
}

#[test]
fn builtin_arity_mismatch_error_via_check() {
    // mds check code path: calling upper() with zero args must fail with arity error
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("bad_arity.mds");
    std::fs::write(&path, "{{upper()}}\n").unwrap();
    let result = mds::check(&path, None);
    assert!(
        result.is_err(),
        "arity mismatch on built-in should fail at check time"
    );
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("upper") || err.contains("arity") || err.contains("argument"),
        "error should mention the function name or arity, got: {err}"
    );
}

#[test]
fn builtin_too_many_args_error_via_check() {
    // mds check code path: calling trim() with two args must fail with arity error
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("bad_arity2.mds");
    std::fs::write(&path, "---\na: hello\nb: world\n---\n{{trim(a, b)}}\n").unwrap();
    let result = mds::check(&path, None);
    assert!(
        result.is_err(),
        "too many args on built-in trim() should fail at check time"
    );
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("trim") || err.contains("arity") || err.contains("argument"),
        "error should mention the function name or arity, got: {err}"
    );
}

// ── Default argument tests ────────────────────────────────────────────────

#[test]
fn default_arg_string_used_when_omitted() {
    // mds build code path: calling greet() without arg uses string default "World"
    let source = "@define greet(name = \"World\"):\nHello {{name}}!\n@end\n{{greet()}}\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("Hello World!"),
        "omitted arg should use string default, got: {result}"
    );
}

#[test]
fn default_arg_overridden_when_provided() {
    let source = "@define greet(name = \"World\"):\nHello {{name}}!\n@end\n{{greet(\"Alice\")}}\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("Hello Alice!"),
        "provided arg should override default, got: {result}"
    );
}

#[test]
fn default_arg_number_used_when_omitted() {
    let source = "@define show(x = 42):\nvalue={{x}}\n@end\n{{show()}}\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("value=42"),
        "omitted arg should use numeric default, got: {result}"
    );
}

#[test]
fn default_arg_check_valid_call() {
    // mds check code path: calls with and without optional arg must both pass check
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("default_ok.mds");
    std::fs::write(
        &path,
        "@define greet(name = \"World\"):\nHello {{name}}!\n@end\n{{greet()}}\n{{greet(\"Alice\")}}\n",
    )
    .unwrap();
    let result = mds::check(&path, None);
    assert!(
        result.is_ok(),
        "valid calls with and without optional arg should pass check, got: {:?}",
        result
    );
}

#[test]
fn default_arg_arity_error_too_many_args_via_check() {
    // mds check code path: passing more args than the function accepts must fail
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("too_many.mds");
    std::fs::write(
        &path,
        "@define greet(name = \"World\"):\nHello {{name}}!\n@end\n{{greet(\"Alice\", \"extra\")}}\n",
    )
    .unwrap();
    let result = mds::check(&path, None);
    assert!(
        result.is_err(),
        "too many args for a function with one optional param should fail"
    );
    let err = format!("{}", result.unwrap_err());
    assert!(
        err.contains("greet") || err.contains("arity") || err.contains("argument"),
        "error should mention the function name or arity, got: {err}"
    );
}

// ── Logical operator tests (&&, ||) ──────────────────────────────────────

#[test]
fn logical_and_both_true_enters_body() {
    // @if a && b: — both truthy → enters then body
    let source = "---\na: true\nb: true\n---\n@if a && b:\nboth_true\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("both_true"),
        "@if a && b: with both true must enter then body, got: {result}"
    );
}

#[test]
fn logical_and_first_false_skips_body() {
    // @if a && b: — a falsy → skips body (short-circuit)
    let source = "---\na: false\nb: true\n---\n@if a && b:\nshould_not_appear\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        !result.contains("should_not_appear"),
        "@if a && b: with a=false must skip body, got: {result}"
    );
}

#[test]
fn logical_and_second_false_skips_body() {
    // @if a && b: — b falsy → skips body
    let source = "---\na: true\nb: false\n---\n@if a && b:\nshould_not_appear\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        !result.contains("should_not_appear"),
        "@if a && b: with b=false must skip body, got: {result}"
    );
}

#[test]
fn logical_or_first_true_enters_body() {
    // @if a || b: — a truthy → enters body
    let source = "---\na: true\nb: false\n---\n@if a || b:\nor_body\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("or_body"),
        "@if a || b: with a=true must enter body, got: {result}"
    );
}

#[test]
fn logical_or_second_true_enters_body() {
    // @if a || b: — a falsy, b truthy → enters body
    let source = "---\na: false\nb: true\n---\n@if a || b:\nor_body\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("or_body"),
        "@if a || b: with b=true must enter body, got: {result}"
    );
}

#[test]
fn logical_or_both_false_skips_body() {
    // @if a || b: — both falsy → skips body, enters else
    let source =
        "---\na: false\nb: false\n---\n@if a || b:\nshould_not_appear\n@else:\nor_else\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        !result.contains("should_not_appear"),
        "@if a || b: with both false must skip then body, got: {result}"
    );
    assert!(
        result.contains("or_else"),
        "@if a || b: with both false must enter else body, got: {result}"
    );
}

#[test]
fn logical_and_or_precedence() {
    // @if a && b || c: — AND binds tighter than OR → (a && b) || c
    // a=false, b=true, c=true → (false && true) || true → true
    let source = "---\na: false\nb: true\nc: true\n---\n@if a && b || c:\nprecedence_ok\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("precedence_ok"),
        "&& should bind tighter than ||, got: {result}"
    );
}

#[test]
fn logical_operator_with_equality() {
    // @if role == "admin" || role == "mod": — compound with equality conditions
    let source = "---\nrole: mod\n---\n@if role == \"admin\" || role == \"mod\":\nprivileged\n@else:\nregular\n@end\n";
    let result = mds::compile_str(source).unwrap().into_markdown().unwrap();
    assert!(
        result.contains("privileged"),
        "|| combining equality conditions must work, got: {result}"
    );
    assert!(!result.contains("regular"), "else must not appear");
}