md-tmpl 0.4.0

Lightweight template engine for .tmpl.md prompt files with typed frontmatter
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
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
# md-tmpl — Language Specification

Complete reference for `.tmpl.md` template syntax and the frontmatter type
system. See the [README](README.md) for API documentation, motivation,
and quick-start examples.

---

## Table of Contents

1. [File Format]#file-format
2. [Frontmatter & Type System]#frontmatter--type-system
3. [Type Aliases]#type-aliases
4. [Cross-Template Imports]#cross-template-imports
5. [Constants]#constants
6. [Enum Literal Expressions]#enum-literal-expressions
7. [Naming Conventions & Collision Rules]#naming-conventions--collision-rules
8. [Expression Syntax]#expression-syntax
9. [Filters]#filters
10. [Built-in Functions]#built-in-functions
11. [Control Flow]#control-flow
12. [Includes]#includes
13. [Inline Templates]#inline-templates
14. [Raw Blocks]#raw-blocks
15. [Comments]#comments
16. [Whitespace Control]#whitespace-control
17. [Error Diagnostics]#error-diagnostics

---

## File Format

Template files use the `.tmpl.md` extension. They are valid markdown
files with a required YAML frontmatter block followed by a body:

```markdown
---
<frontmatter>
---

<body>
```

**Markdown safety** is a core design goal. Template files must render
readably in any standard markdown viewer (GitHub, VS Code, etc.) even
without a `.tmpl.md`-aware parser. This constrains the syntax:

- Compound types use **parentheses**`list(…)`, `struct(…)`, `enum(…)`,
  `option(…)`, `tmpl(…)` — never angle brackets `<…>` (which markdown
  renderers strip as HTML tags).
- Default values use `"quoted"` strings, `[…]` lists, `{…}` structs, and
  `Variant(…)` enum literals — all markdown-safe.
- Control-flow tags use `> {% %}` blockquote prefixes so they render as
  visible blockquotes rather than invisible HTML.

**YAML validity** is a hard requirement. The frontmatter block between
`---` delimiters must be parseable by any standard YAML parser (e.g.
`serde_yaml`, `PyYAML`, `js-yaml`). The engine uses a lightweight custom
parser for `no_std` and cross-platform portability, but YAML conformance
is enforced via `serde_yaml` cross-validation tests. In practice:

- Each `params:`, `consts:`, and `types:` list item is a YAML plain
  scalar string (e.g. `- name = str := "World"`). YAML preserves the
  string verbatim; the engine then parses the type/default syntax.
- YAML's built-in multiline folding handles continuation lines correctly —
  indented lines following a list item are joined to the preceding scalar.
- **Inline params** (`params: [x = str, y = int]`) are only safe for
  simple scalar types. Any param containing commas — compound types like
  `enum(A, B)`, `list(name = str, score = int)`, or defaults with `[…]`  will break because YAML splits on `,` inside flow sequences `[…]`.
  Use the block list format for anything beyond simple scalars.

**Standalone control-flow tags** (`{% %}`) on their own line must carry a `>`
blockquote prefix. **Content lines inside blocks do not** — only the `{% %}`
tags themselves need the prefix. The prose, expressions (`{{ }}`), and other
text between the tags should be written normally. The prefix is stripped before
compilation and has no effect on output. In a markdown editor it renders as a
blockquote, visually separating logic from prose:

<!-- prettier-ignore -->
```markdown

> {% if condition %}

Some prose.

> {% /if %}
```

**Inline tags** on a single line work without any prefix:

```markdown
{% if x %}yes{% else %}no{% /if %}
```

---

## Frontmatter & Type System

All frontmatter keys are **optional** — only the `---` delimiters are
mandatory. Omitted keys default to empty / absent.

```yaml
---
name: my_template
description: A summary
types:
  - Labelled = enum(Known(label = str), Unknown)
  - Priority = enum(High, Medium, Low)

imports:
  - "[shared_types]./shared_types.tmpl.md"

consts:
  - NOTEBOOK_FILENAME = str := "thought_process.md"
  - MAX_RETRIES = int := 3

params:
  - name = str
  - count = int
  - score = float := 0.95
  - active = bool := true
  - items = list(label = str, score = int)
  - config = struct(timeout = int, retries = int)
  - status = enum(Active, Paused, Stopped)
  - outcome = enum(Confirmed(evidence = str), Rejected)
  - category = Labelled
  - ext_type = shared_types.SomeType

allow_unused: false
---
```

### Type Reference

| Annotation                  | Rust equivalent (generated by `include_template!`)  | Notes                                                                    |
| --------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------ |
| `str`                       | `String`                                            |                                                                          |
| `bool`                      | `bool`                                              |                                                                          |
| `int`                       | `i64`                                               |                                                                          |
| `float`                     | `f64`                                               |                                                                          |
| `list(field = type, ...)`   | `Vec<StructName>`                                   | Each field is a typed struct field                                       |
| `list(type)`                | `Vec<RustType>`                                     | Scalar list (e.g. `list(str)`, `list(int)`)                              |
| `struct(field = type, ...)` | Nested generated struct                             |                                                                          |
| `enum(Variant1, Variant2)`  | Generated enum                                      | No payload variants                                                      |
| `enum(V(field = type), V2)` | Generated enum with struct variants                 | Fields accessible inside `{% match %}` arms                              |
| `option(type)`              | Generated enum: `Some(val)` / `None`                | Sugar for `enum(Some(val = T), None)`. See [Option Types]#option-types |
| `tmpl(field = type, ...)`   | Validated `Template` reference                      | Template must match declared param signature                             |
| `tmpl()`                    | Validated `Template` reference (no required params) | Any template with no required params (may have defaulted params)         |
| `AliasName`                 | Resolved type from `types:` block                   | See [Type Aliases]#type-aliases                                        |
| `stem.TypeName`             | Resolved type from imported template                | See [Cross-Template Imports]#cross-template-imports                    |

All parameters **must** have explicit types. Bare `- name` without a type is a
hard error.

#### Template Parameter Signature Matching

When a value of type `tmpl(...)` is provided (via `Value::Tmpl` in Rust,
or passed through `with` in templates), its parameter declarations are
validated against the declared signature:

1. **All signature params must exist** — the template must declare every
   parameter listed in the `tmpl(...)` signature, with matching types.
2. **Extra params allowed if defaulted** — the template may declare
   additional parameters beyond the signature, but only if they have
   default values. Extra required params (no default) cause a type error.
3. **`tmpl()` (empty)** — accepts any template that has no required
   parameters. The template may still have defaulted params.

```yaml
# Example: signature matching

params:
  - widget = tmpl(name = str)
```

A template with `params: [name = str]` matches ✅.
A template with `params: [name = str, color = str := "gray"]` matches ✅
(extra `color` has a default).
A template with `params: [name = str, color = str]` does NOT match ❌
(extra `color` has no default).
A template with `params: [age = int]` does NOT match ❌
(`name` is missing, `age` is not in the signature).

#### Compound Type Delimiters & Quoting

For all compound types (`list`, `struct`, `enum`, `option`, `tmpl`), enclosing delimiters **must** be parentheses `(...)` (e.g., `list(str)`, `option(int)`, `struct(name = str)`). Angle brackets `<...>` and square brackets `[...]` fallback are strictly prohibited and will produce a syntax error.

In YAML frontmatter declarations, outer quotes around type expressions (or entire parameter/type declarations) are automatically stripped before parsing (e.g., `items = "list(str)"`). Unquoted placeholder notation (such as legacy `<str>` or `<int>`) is strictly prohibited.

### Type Nesting Rules

Compound types can be nested, with one restriction:

```markdown
# ✅ Valid nesting

- items = list(name = str, score = int) # list of structs (the correct way)
- grid = list(list(str)) # nested list (matrix/grid)
- tags = list(enum(High, Medium, Low)) # list of enum values
- config = struct(pos = struct(x = int, y = int), label = str) # nested struct
- entries = struct(status = enum(Active, Done), items = list(str))
- label = option(str) # required (caller must provide string or null)
- scores = list(option(int)) # list of optional ints
- meta = option(struct(key = str, value = str)) # optional struct

# ❌ Forbidden — redundant raw struct wrapper

- items = list(struct(name = str, score = int)) # ERROR: use list(name = str, score = int) or list(MyAlias)
```

**Raw `list(struct(...))` is forbidden** because `list(name = str, score = int)`
already creates a list of structs, making the explicit `struct()` wrapper redundant.
However, referencing a strong struct type alias inside a list (e.g., `list(MyStructAlias)`)
**is allowed** and unwraps the struct fields directly into the list elements.

### Default Values

Append `:= {literal}` after the type:

```markdown
# Scalar defaults

- name = str := "World"
- count = int := 42
- verbose = bool := false
- threshold = float := 0.95

# Enum defaults — unit variants

- status = enum(Active, Paused) := Active

# Enum defaults — struct variants (inline fields)

- outcome = enum(Confirmed(evidence = str), Rejected) := Confirmed(evidence = "found it")

# Option defaults

- label = option(str) := None # absent value (parameter becomes optional)
- label = option(str) := "hello" # present value (auto-wraps to Some)

# Struct defaults

- config = struct(timeout = int, label = str) := {timeout = 10, label = "fast"}

# List defaults

- tags = list(str) := ["rust", "go", "python"]
- items = list(name = str, score = int) := [{name = "a", score = 10}]

# Const-reference defaults — use a const name instead of a literal

- retries = int := MAX_RETRIES
- output_file = str := config.DEFAULT_PATH
```

**Rules:**

- String defaults must be quoted (`"World"` or `'World'` — both single and
  double quotes are valid for string literals).
- Enum unit variant defaults are unquoted (`Active`, not `"Active"`).
- Struct variant defaults use `VariantName(field = value)` syntax (parentheses).
- Bare struct variant names without fields are rejected (e.g., `:= Confirmed`
  fails when `Confirmed` has required fields).
- Unknown variant names are rejected at parse time.
- Struct defaults use `{key = value}` syntax (curly braces with `=`).
- List defaults use `[value, ...]` syntax.
- **Const-reference defaults**: a default value can reference a local
  constant (`consts:` entry) or an imported constant (`stem.NAME`) by name.
  The referenced constant's type must match the parameter's declared type.
  Local consts are parsed before params, so order within frontmatter does
  not matter. Imported constants are resolved after import resolution.
- **YAML constraint**: the inline format (`params: [...]`) only works
  for simple scalar params without commas in the type or default.
  Compound types and `[…]`/`{…}` defaults must use the block list
  format (`params:` on its own line, each param as `- …`).

Defaults are type-checked at compile/parse time. If a param with a default is
omitted from the render context, the default is injected automatically.

Query defaults programmatically:

```rust
use md_tmpl::Template;

let tmpl = Template::from_source(
"---
params:
  - name = str := \"World\"
---
Hello {{ name }}!").unwrap();
let defaults = tmpl.defaults();
assert_eq!(defaults.len(), 1);

let ctx = md_tmpl::Context::new();
assert_eq!(tmpl.render_ctx(&ctx).unwrap(), "Hello World!");
```

### Unused Parameters and Type Aliases

Declared params that are never referenced in the body (not even in a
`{# comment #}`) are a hard error by default. Similarly, type aliases
declared in `types:` but never referenced by any parameter or constant
declaration are also rejected. **Enum types are exempt** — they are
implicitly used as namespace constants (see
[Enum Literal Expressions](#enum-literal-expressions)).

Disable both checks with `allow_unused: true` in frontmatter, or call
`Template::from_source_allowing_unused()`.

> **Note:** Undeclared params (referenced in the body but absent from
> `params:`) are always rejected, even with `allow_unused: true`.

---

### Markdown Blockquotes, Statement Tags, and Comments

Statement tags (`{% ... %}`) and comments (`{# ... #}`) that start a line **must** be prefixed with a markdown blockquote `> `. This is enforced at compile time — bare tags or comments at line start are syntax errors.

- **Tags and Comments at line start**: If `{%` or `{#` is at the beginning of a line, it **must** start with `> ` (e.g., `> {% ... %}` or `> {# ... #}`). For comments, spaces are required around the content (`{# comment #}`).
- **Mandatory Blank Lines**: If `{%` or `{#` is at the beginning of a line, the line before and after **must** be blank unless the adjacent line is frontmatter (`---`) or also starts with a blockquote tag/comment (`> {%` or `> {#`).
- **Multiple Comments and Mixed Tags on a Line**: `{%` and `{#` in the same line work seamlessly (no matter how many follow). Text on the line is treated normally, and any `{# ... #}` comments are omitted from output while preserving the rest of the line.
- **Content lines inside blocks are normal text.** The lines between `> {% for ... %}` and `> {% /for %}` (or any other block) are just regular template content. The `> ` prefix stripping applies **exclusively** to lines where the first non-whitespace content after `> ` is `{% ` or `{# `. If a content line starts with `> ` (for example, a standard Markdown blockquote), it is **not** stripped and is kept verbatim in the rendered output.

Example — only the `{% %}` tag lines carry the `> ` prefix; the prose
lines inside the block do not:

<!-- prettier-ignore -->
```markdown

> {% for task in tasks %}

- **{{ task.title }}** ({{ task.priority }})

> {% /for %}
```

## Type Aliases

The optional `types:` block defines named type aliases that can be
referenced by name in `params:` declarations. This avoids repeating
complex type definitions and enables type sharing across parameters
and templates.

Any type expression (`enum(…)`, `list(…)`, `struct(…)`, `tmpl(…)`, or even scalar
types) can be aliased.

### Syntax

Type aliases are declared as YAML mappings in the `types:` block:

```yaml
---
types:
  - Category = enum(Labelled(label = str), Unlabelled)
  - Priority = enum(High, Medium, Low)
  - TaskList = list(title = str, category = Category, priority = Priority)
  - Config = struct(timeout = int, retries = int)

params:
  - tasks = TaskList
  - components = list(name = str, category = Labelled)
  - cfg = Config
---
```

Each entry maps an alias name to a type expression. The alias name can
then be used anywhere a type is expected in `params:`.

### Resolution Order

When a type name appears in `params:`, it is resolved in this order:

1. **Built-in types**`str`, `bool`, `int`, `float`, `list(…)`, `struct(…)`, `enum(…)`, `tmpl(…)`
2. **Local `types:` entries** — exact name match from the same template's `types:` block
3. **Imported types via dotted path**`stem.TypeName` from `imports:` (see [Cross-Template Imports]#cross-template-imports)

If a type name is not found in any of these, it is an "unknown type" error.

### Chained Aliases

Type aliases can reference previously defined aliases (defined earlier
in the same `types:` block):

```yaml
types:
  - Severity = enum(Critical, High, Medium, Low)
  - TaskInfo = struct(title = str, severity = Severity)
```

Forward references (referencing an alias defined later in the block)
are not supported.

### Implicit Param Types

Every param or constant with a compound type (`list`, `struct`, or `enum`)
implicitly creates a named type entry using the declaration's name in
`PascalCase`. This implicit type is importable from other templates via
dotted path, alongside explicit `types:` entries.

For example, given:

```yaml
params:
  - tasks = list(title = str, priority = str)

consts:
  - DEFAULT_ITEMS = list(label = str) := [{label = "init"}]
```

The param `tasks` implicitly creates a type named `Tasks`, and the
constant `DEFAULT_ITEMS` implicitly creates a type named `DefaultItems`.
Other templates can reference these as `template_stem.Tasks` or
`template_stem.DefaultItems` via an import.

If an explicit `types:` entry with the same `PascalCase` name already
exists, the implicit entry is **not** generated — explicit aliases take
precedence.

---

## Cross-Template Imports

The optional `imports:` block declares dependencies on other templates,
allowing you to reference their type aliases and implicit param types
via dotted paths.

### Syntax

Each import entry uses quoted markdown link syntax:

```yaml
---
imports:
  - "[task_list_item]./task_list_item.tmpl.md"

params:
  - tasks = task_list_item.tasks
  - label = task_list_item.Category
---
```

The `[stem]` part is the namespace prefix used in dotted paths.
The `(path.tmpl.md)` is the file path, resolved relative to the
importing template's directory (same as `{% include %}`).

**Strict Path Requirement**: All relative file import paths **must** begin explicitly with `./` or `../`. Bare relative filenames (e.g., `[my_types](my_types.tmpl.md)`) are rejected with syntax errors. Absolute paths beginning with `/` are also permitted.

### Stem Validation

The link text (stem) **must** match the filename without `.tmpl.md`.
For example, `"[my_types](./my_types.tmpl.md)"` is valid, but
`"[alias](./my_types.tmpl.md)"` is an error because `alias` ≠ `my_types`.

### Importable Names

Both explicit `types:` entries and implicit param types (compound params)
from the imported template are available via `stem.Name`:

- `task_list_item.Category` — references a `types:` entry named `Category`
- `task_list_item.tasks` — references the implicit type from a compound param named `tasks`

### Circular Import Detection

Circular imports are detected and produce an error. If template A
imports template B and template B imports template A, compilation fails
with a clear error message.

### Transitive Imports

Imported templates that themselves have imports are resolved
transitively. Types from transitive imports are accessible through
nested dotted paths.

---

## Constants

The optional `consts:` block in frontmatter declares file-scoped constant
values. Constants are available everywhere in the template body without
being passed via `with`.

### Syntax

Each entry follows `- NAME = type := value`:

```markdown
---
consts:
  - NOTEBOOK_FILENAME = str := "thought_process.md"
  - MAX_RETRIES = int := 3
  - STAGES = struct(DESIGN = str, BUILD = str) := {DESIGN = "Design", BUILD = "Build"}
---

Notebook: {{ NOTEBOOK_FILENAME }}
Max retries: {{ MAX_RETRIES }}
Stage: {{ STAGES.DESIGN }}
```

Constants are type-checked at parse time. The value is mandatory — a
`consts:` entry without `:= value` is a hard error.

### Scoping

- **File-scoped**: constants are visible throughout the template body,
  including inside `{% for %}`, `{% if %}`, and `{% match %}` blocks.
- **Inherited by inline templates**: `{% tmpl %}` blocks inherit the
  parent template's constants automatically (see
  [Inline Templates — Scoping Rules]#scoping-rules).
- **Not passed via `with`**: constants are injected automatically into
  the template's scope. They do not appear in `params:` and cannot be
  overridden at render time.

### Imported Constants

When a template is imported via `imports:`, its constants become
accessible via dotted path `stem.CONST_NAME`:

```markdown
---
imports:
  - "[config]./config.tmpl.md"
---

Notebook: {{ config.NOTEBOOK_FILENAME }}
```

Imported constants follow the same resolution rules as imported types.
They do not need to be passed via `with`.

---

## Enum Literal Expressions

When an enum type is declared in `types:` (or as an inline param type),
its variants are automatically available as **namespace constants** using
`TypeName.VariantName` dotted-path syntax. No manual `consts:` entry is
needed — the type declaration itself populates the template scope.

Enum literal expressions **must** be wrapped in the `kind()` built-in
function, which returns the variant name as a string. Bare access
(e.g., `{{ Stage.Design }}`) is a compile error.

### Basic Usage

```markdown
---
types:
  - Stage = enum(Design, Build, Deploy)
  - Status = enum(Active, Paused(reason = str))

params: []
---

{{ kind(Stage.Design) }} {# renders: Design #}
{{ kind(Stage.Build) }} {# renders: Build #}
{{ kind(Status.Paused) }} {# renders: Paused #}
```

Both **unit variants** (no fields) and **struct variants** (with fields)
work the same way — `kind()` extracts the variant name as a string
(e.g., `kind(Stage.Design)` → `"Design"`,
`kind(Status.Paused)` → `"Paused"`).

### Bare Access Is a Compile Error

Using an enum literal without `kind()` is rejected at compile time:

```markdown
{{ Stage.Design }} {# ❌ COMPILE ERROR #}
```

Error message:

> bare enum literal 'Stage.Design' is not allowed — use
> kind(Stage.Design) to get the variant name as a string

**Rationale:** requiring `kind()` prevents confusion between enum type
namespace access and regular variable dot-access (e.g., `struct.field`).
The explicit `kind()` call makes the intent unambiguous.

### Imported Enum Literals

Enum types from imported templates are accessible via the import
stem, following the same dotted-path convention as imported types
and constants:

```markdown
---
imports:
  - "[lib]./lib.tmpl.md"

params: []
---

{{ kind(lib.Stage.Design) }} {# renders: Design #}
{{ kind(lib.Status.Paused) }} {# renders: Paused #}
```

The path follows the pattern `stem.TypeName.VariantName`.

### Precedence

If a user-defined constant in `consts:` has the same name as a `types:`
entry, the constant takes precedence in the template scope. However,
this situation is normally prevented by the
[collision rules](#naming-conventions--collision-rules) — a `consts:`
name that collides with a `types:` name is a compile error.

### Compile-Time Guarantees

- **Bare access**`{{ Stage.Design }}` without `kind()` is a
  compile error.
- **Unknown variant**`kind(Stage.Nonexistent)` is a compile error.
- **Unknown type**`kind(Nonexistent.Design)` is a compile error.
- **Non-enum type** — accessing variants on a `struct` or scalar type
  is a compile error.

---

## Naming Conventions & Collision Rules

### PascalCase Naming

Generated Rust and Python types use `PascalCase` for type names:

- Param `tasks` → type `Tasks`
- Param `category` → type `Category`
- Param `code_review` → type `CodeReview`

Type alias names in `types:` are used as-is (they should already be
`PascalCase` by convention).

### Collision Rules

The following naming rules prevent ambiguity. All checks run at
parse time and produce syntax errors.

1. **Reserved keywords**`str`, `bool`, `int`, `float`, `list`,
   `struct`, `enum`, `tmpl`, and `params` cannot be used as parameter
   names, constant names, or type alias names.

2. **Duplicate names** — duplicate param names, duplicate constant
   names, and duplicate type alias names are each rejected within
   their own block.

3. **Param ↔ const conflict** — a parameter and a constant cannot
   share the same name. Both occupy the same runtime scope, so the
   constant would silently shadow the parameter value.

4. **Type/param `PascalCase` conflict** — if a `types:` entry exists
   whose name equals the `PascalCase` of a param or constant name
   (e.g., type `Tasks` and param `tasks`), the declaration's type
   **must** be that alias. `tasks = Tasks` is valid; `tasks = str` when
   type `Tasks` exists is an error.

5. **Type alias ↔ import stem** — a type alias cannot have the same
   name as an import stem (e.g., `types: [Shared = …]` when
   `imports: ["[Shared](./shared.tmpl.md)"]`).

6. **Param `PascalCase` ↔ import stem** — a param whose `PascalCase`
   name equals an import stem is rejected.

7. **Built-in shadowing** — a type alias cannot shadow a built-in type
   name (`str`, `bool`, `int`, `float`, `list`, `struct`, `enum`, `tmpl`).

8. **Unused type aliases** — a `types:` entry that is never referenced
   by any parameter or constant declaration is rejected (unless
   `allow_unused: true`). Enum types are exempt — they are always
   considered used because their variants are injected as namespace
   constants. Pure type-library templates (no params, no consts)
   skip this check entirely.

9. **Import stem ↔ inline template** — an import stem cannot collide
   with an inline template name (`{% tmpl name %}`), since both are
   reachable via `{% include %}`.

10. **Param/const ↔ inline template** — a param or constant name
    cannot collide with an inline template name.

11. **For-loop binding shadowing** — a `{% for %}` binding must not
    shadow a declared param, constant, import stem, or inline template
    name. The binding is scoped to the loop body and does not persist
    after `{% /for %}`, so **sequential loops may reuse the same
    binding name**.

    ```markdown
    {# OK — sequential reuse #}

    > {% for item in list_a %}{{ item.name }}
    > {% /for %}
    > {% for item in list_b %}{{ item.name }}
    > {% /for %}

    {# ERROR — 'x' shadows declared param 'x' #}

    > {% for x in items %}{{ x.name }}
    > {% /for %}
    ```

---

## Expression Syntax

Variable substitution: `{{ expr }}`

```markdown
{{ name }}
{{ task.title }}
{{ task.component.label }}
```

Dotted paths resolve nested struct and enum fields. Accessing a field that does
not exist on the resolved type is a compile-time error.

### Renderable Types

Only **scalar types** can appear directly in `{{ }}` expressions:

| Type    | Rendered as                 |
| ------- | --------------------------- |
| `str`   | The string value            |
| `int`   | Decimal integer (e.g. `42`) |
| `float` | Decimal float (e.g. `3.14`) |
| `bool`  | `true` or `false`           |

Attempting to render a non-scalar type directly is a **compile-time error**:

```markdown
{{ items }} {# ❌ ERROR: cannot display list — use {% for %} #}
{{ config }} {# ❌ ERROR: cannot display struct — access fields #}
{{ status }} {# ❌ ERROR: cannot display enum — use {% match %} or kind() #}
{{ widget }} {# ❌ ERROR: cannot display tmpl — use {% include %} #}
{{ maybe_x }} {# ❌ ERROR: cannot display option — use {% if has(x) %} #}
```

**How to use non-scalar types:**

| Type     | Correct usage                                                       |
| -------- | ------------------------------------------------------------------- |
| `list`   | `{% for item in items %}{{ item.field }}{% /for %}`                 |
| `struct` | `{{ config.timeout }}` (access individual fields)                   |
| `enum`   | `{% match status %}` or `{{ kind(status) }}`                        |
| `tmpl`   | `{% include widget with field = value %}`                           |
| `option` | `{% if has(x) %}{{ x }}{% /if %}` (narrowing unwraps to inner type) |

Enum types declared in `types:` also support dotted-path access to their
variants via the `kind()` function — see
[Enum Literal Expressions](#enum-literal-expressions).

---

## Filters

Pipe operator chains transforms left-to-right: `{{ expr | filter | filter }}`

```markdown
{{ name | upper }}
{{ name | trim | lower }}
{{ score | fixed(2) }}
{{ items | join(", ") }}
```

| Filter        | Input  | Output | Description                       |
| ------------- | ------ | ------ | --------------------------------- |
| `upper`       | str    | str    | UPPERCASE                         |
| `lower`       | str    | str    | lowercase                         |
| `trim`        | str    | str    | Strip leading/trailing whitespace |
| `fixed(N)`    | number | str    | Format with N decimal places      |
| `join("sep")` | list   | str    | Join list items with separator    |
| `limit(N)`    | list   | list   | Take first N elements             |
| `add(N)`      | number | number | Add N to the value                |
| `sub(N)`      | number | number | Subtract N from the value         |

---

## Built-in Functions

| Function       | Returns | Description                                                                                                                                           |
| -------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `idx(binding)` | int     | 0-based loop index of a `for` binding                                                                                                                 |
| `len(expr)`    | int     | Length of a list, string, or struct                                                                                                                   |
| `kind(expr)`   | str     | Variant name of an enum value (errors on non-enum). Also works with [enum literal expressions]#enum-literal-expressions, e.g. `kind(Status.Paused)` |
| `has(expr)`    | bool    | `true` if an `option(T)` value is `Some`, `false` if `None`. See [Option Types]#option-types                                                        |

`idx()` tracks each loop variable independently in nested loops:

```rust
use md_tmpl::{ctx, Template};

let tmpl = Template::from_source("---
params:
  - outer = list(label = str)
  - inner = list(label = str)
---
> {% for a in outer %}{% for b in inner %}{{ idx(a) }}.{{ idx(b) }} {% /for %}{% /for %}").unwrap();

let output = tmpl.render_ctx(&ctx! {
    outer: [{ label: "x" }, { label: "y" }],
    inner: [{ label: "p" }, { label: "q" }],
}).unwrap();
assert_eq!(output, "0.0 0.1 1.0 1.1 ");
```

---

## Control Flow

### For Loops

```markdown
> {% for task in tasks %}

- **{{ task.title }}**: {{ task.description }}

> {% /for %}
```

`{% for x in y %}` requires `y` to be a `list` type — enforced at compile time.

#### `for...else`

An optional `{% else %}` block renders when the list is **empty**:

```markdown
> {% for agent in agents %}

- {{ agent.name }}

> {% else %}

No agents available.

> {% /for %}
```

- When `agents` has items → only the loop body is rendered.
- When `agents` is empty → only the else body is rendered.
- `{% else %}` inside nested `{% if %}` or `{% for %}` blocks is
  correctly scoped — it does **not** interfere with the for-else.
- The loop binding (e.g. `agent`) is **not** in scope inside the else body.

### Conditionals

<!-- prettier-ignore -->
```markdown

> {% if severity == "critical" %}

🔴 Immediate action required.

> {% elif severity == "high" %}

🟠 High priority.

> {% else %}

🟢 Normal.

> {% /if %}
```

Operators: `==`, `!=`, `<`, `>`, `<=`, `>=`. Plain identifiers are evaluated
for truthiness.

#### Truthiness

Values are evaluated as follows:

| Value               | Truthy? |
| ------------------- | ------- |
| `false`             | ❌      |
| `true`              | ✅      |
| `0` (int)           | ❌      |
| non-zero int        | ✅      |
| `0.0` (float)       | ❌      |
| non-zero float      | ✅      |
| `""` (empty string) | ❌      |
| non-empty string    | ✅      |
| `[]` (empty list)   | ❌      |
| non-empty list      | ✅      |
| `{}` (empty struct) | ❌      |
| non-empty struct    | ✅      |
| any `tmpl`          | ✅      |

> **Note:** Enum values cannot be compared with `==`/`!=`. Use `{% match %}` for
> enum dispatch — it provides exhaustiveness checking and struct variant support.

### Match / Case (Enums)

Dispatch on enum variants with compile-time exhaustiveness checking:

**Multi-arm** (must cover all variants):

<!-- prettier-ignore -->
```markdown

> {% match outcome %}
> {% case Confirmed %}

Confirmed with evidence.

> {% case NotConfirmed %}

Not confirmed.

> {% /match %}
```

**Catch-all arm** (fallback for unmatched variants):

<!-- prettier-ignore -->
```markdown

> {% match outcome %}
> {% case Confirmed %}

Confirmed with evidence: {{ outcome.evidence }}

> {% case NotConfirmed %}

Not confirmed.

> {% else %}

Outcome pending.

> {% /match %}
```

The `{% else %}` arm matches any variant not covered by preceding `{% case %}` arms.
It must be the last arm — placing `{% case %}` after `{% else %}` is a compile error.

**Multi-variant arm** (shared body for several variants):

<!-- prettier-ignore -->
```markdown

> {% case Confirmed | ConfirmedWithCaveats %}

Evidence found.
```

**Inline guard** (renders only if variant matches):

```markdown
> {% match category case Labelled %}({{ category.label }}){% /match %}
```

Inside a `{% match %}` arm, the variant's fields are accessible via `expr.field`
after type narrowing:

- `{% case A | B %}` — only fields present on **both** A and B are accessible.
- `{{ outcome.evidence }}` outside a `{% case Confirmed %}` is a compile error
  if `evidence` is not shared by all variants.

#### Compile-time guarantees for `match`

1. **Variant validation** — unknown variant names → compile error.
2. **Field narrowing** — field access outside a matching arm → compile error.
3. **Multi-variant intersection** — only shared fields are accessible.
4. **Exhaustiveness** — multi-arm matches must cover **all** variants. Adding a
   new variant to the enum and forgetting to handle it is a compile error.
   Use `{% else %}` as a catch-all if you don't need per-variant handling.
5. **No `==` on enums** — comparing an enum with `==` or `!=` is a compile error.
   Use `{% match %}` instead, which is exhaustive and supports struct variants.

---

## Option Types

`option(T)` is a first-class way to express optional/nullable values.

### Declaration

```yaml
params:
  - name = option(str) # required — caller MUST provide a value or null
  - score = option(int) := None # optional — defaults to absent
  - label = option(str) := "hello" # optional — defaults to "hello"
```

**Important:** `option(T)` without a default is a **required** parameter, just
like any other type. There is no automatic default to `None`. If you want
the parameter to be optional, you must explicitly declare `:= None`.

### Transparent Representation

Option values are **transparent** — the inner value is used directly. This means `{{ name }}` renders
the value directly, without needing `.val` (as long it's been checked with match or if has() before).

| Input (JS/Python/Go) | Template `Value`    | `{{ x }}` output |
| -------------------- | ------------------- | ---------------- |
| `null` / `None`      | `NoneValue`         | `""` (empty)     |
| `42`                 | `IntValue(42)`      | `42`             |
| `"hello"`            | `StrValue("hello")` | `hello`          |

### Checking presence with `has()`

The `has()` built-in function returns `true` when an option holds a value
(`Some`) and `false` when it is `None`:

```markdown
> {% if has(name) %}

Hello {{ name }}!

> {% else %}

Hello stranger!

> {% /if %}
```

### Matching with `{% match %}`

Use `{% match %}` for exhaustive option handling:

```markdown
> {% match name %}
> {% case Some %}

Name: {{ name }}

> {% case None %}

_(no name provided)_

> {% /match %}
```

Inside `{% case Some %}`, `{{ name }}` renders the inner value directly.
Outside the match, `{{ name }}` on a `None` value renders as empty string.

### Runtime representation

At runtime, option values use **transparent** representation:

| Template value    | Runtime `Value` | JS representation |
| ----------------- | --------------- | ----------------- |
| `None`            | `NoneValue`     | `null`            |
| `Some(val = "x")` | `StrValue("x")` | `"x"`             |
| `Some(val = 42)`  | `IntValue(42)`  | `42`              |

### Nesting

Options can be nested with any type:

```yaml
params:
  - items = list(option(str)) # list of optional strings
  - meta = option(struct(k = str)) # optional struct
  - nested = option(option(int)) # double-optional (unusual but valid)
```

---

## Includes

```markdown
> {% include [name](./path.tmpl.md) %}
> {% include [child](./child.tmpl.md) with msg=greeting %}
> {% include [row](./row.tmpl.md) for item in items %}
> {% include [row](./row.tmpl.md) for item in items with extra=val %}
```

- The `[name]` part is a standard markdown link — clickable in editors.
- The `(path.tmpl.md)` is the file path, resolved **relative to the including
  template's directory**. All relative include paths **must** begin explicitly with `./` or `../`. Bare relative filenames (e.g., `[child](child.tmpl.md)`) are rejected with syntax errors. Named template references (e.g. `{% include my_tmpl %}`) and absolute paths starting with `/` do not require relative path prefixes.
- **Explicit parameter passing** via `with` is required; no implicit scope
  leaking.
- **Iterated includes** via `for binding in list` unroll the list: for
  each element, the included template is rendered with `binding` set to the
  current item. The binding name satisfies the included template's
  parameter declaration of the same name. `idx(binding)` provides the
  0-based loop index inside the included template. Combined `for + with`
  syntax is also supported, passing additional explicit overrides alongside
  the iteration binding.
- **Bare name includes**: if the include name refers to an inline template
  defined via `{% tmpl name %}` (or a variable of type `tmpl(...)`), use
  `{% include name with ... %}` without the markdown link syntax. The
  engine resolves inline templates before falling back to the filesystem.
- Parameters are type-checked against the included template's frontmatter.

### Depth Limits

- **Runtime**: Maximum nesting depth defaults to 16. Configurable via
  `.with_max_include_depth(n)` (builder-style) or `.set_max_include_depth(n)`
  (mutable setter) on the `Template`:

  ```rust
  let dir = tempfile::tempdir().unwrap();
  let path = dir.path().join("deep.tmpl.md");
  std::fs::write(
      &path, "---\nparams: []\n---\nok"
  ).unwrap();

  let tmpl = md_tmpl::Template::from_file(&path)
      .unwrap()
      .with_max_include_depth(4); // builder-style

  let mut tmpl2 = md_tmpl::Template::from_file(&path).unwrap();
  tmpl2.set_max_include_depth(4); // mutable setter
  ```

- **Compile-time** (`include_template!`): Maximum depth
  defaults to 64. Override with the `MD_TMPL_MAX_INCLUDE_DEPTH`
  environment variable at build time.
- **Circular includes** are detected at both compile time (via canonical
  path tracking) and runtime (via depth limit). A cycle is not a hard error
  at compile time — the included template's declarations are loaded for
  boundary type checking, but the body is not recursed into.

### Self-Recursive Includes

A template can include **itself** to render recursive data structures
(trees, nested comments, etc.). The depth limit prevents infinite loops.

> **Note:** The type system does not support self-referential type
> definitions. For recursive data, model the tree as a flat list
> with explicit depth fields, or use an enum to capture node kinds.

### Heterogeneous Lists and Structs

Untyped `list()` and `struct()` are **not allowed** — all containers must
have explicit types. For collections with mixed element types, define
an enum and use it as the element or field type:

<!-- prettier-ignore -->
```markdown
---
types:
  - TreeNode = enum(Leaf(label = str), Branch(label = str, depth = int))

params:
  - nodes = list(TreeNode)
---

> {% for node in nodes %}

> {% match node %}
> {% case Leaf %}

- 🍃 {{ node.label }}

> {% case Branch %}

- 🌿 {{ node.label }} (depth {{ node.depth }})

> {% /match %}
> {% /for %}
```

The same pattern works for structs with heterogeneous value types:

```yaml
types:
  - ConfigVal = enum(Text(val = str), Num(val = int), Flag(val = bool))

params:
  - settings = struct(timeout = ConfigVal, label = ConfigVal)
```

This replaces untyped containers with **exhaustive, type-checked
dispatch** via `{% match %}` — the compiler verifies all variants
are handled.

### Path Resolution

- Include paths are resolved relative to the directory of the file
  containing the `{% include %}` directive.
- At compile time, paths are canonicalized (`realpath`) for cycle detection
  and deduplication. `../common/header.tmpl.md` and `./header.tmpl.md` from
  different directories correctly resolve to the same file.
- The same file included from multiple places is compiled once and its body
  is type-checked once (deduplication by canonical path / `Arc` identity).

---

## Inline Templates

Define reusable fragments inline, without separate files:

```markdown
> {% tmpl task_row %}

---

params:

- title = str
- priority = str

---

- **{{ title }}** ({{ priority }})

> {% /tmpl %}

> {% for task in tasks %}
> {% include task_row with title=task.title, priority=task.priority %}
> {% /for %}
```

Inline templates use standard `---` delimited frontmatter inside the
`{% tmpl %}` block — the same syntax as file-based templates. They are
parsed through the same `parse_frontmatter()` path, so all frontmatter
features work identically.

Inline templates support: typed frontmatter (including `types:` and
`imports:` blocks), `with` parameter passing, `for` iteration, and full
type checking. They are compiled once and reused at every include site.

### Scoping Rules

Inline template names (`{% tmpl name %}`) are **scoped to their defining
file**. Each `.tmpl.md` file has its own namespace:

- **No leaking upward**: an included file's `{% tmpl %}` definitions are
  not visible to the parent template.
- **No leaking downward**: a parent's `{% tmpl %}` definitions are not
  visible inside included files.
- **Same name, different files**: two files can both define `{% tmpl row %}`
  with different content. Each file's `{% include row %}` resolves to its
  own definition.
- **Duplicate names in the same file**: rejected at parse time.

This scoping applies identically at compile time (proc macros) and runtime
(dynamic include resolution).

### Type Resolution in Inline Templates

Inline templates can define their own `types:` and `imports:` blocks,
and they also inherit the parent template's `types:` and `imports:`
via lexical scoping. Own definitions shadow parent definitions on name
conflict.

Resolution order for type names in an inline template:

1. Built-in types
2. Own `types:` entries
3. Parent `types:` entries
4. Own `imports:` (dotted path)
5. Parent `imports:` (dotted path)

**Constants** (both local `consts:` and imported constants from the
parent) are inherited by inline templates automatically.

**Params** are _not_ inherited — they must be explicitly passed via
`with` at the include site.

This is by design: constants are file-scoped values (analogous to
`#define`), while params are function arguments that flow through
explicit call sites.

---

## Raw Blocks

Output literal template syntax without processing:

```rust
use md_tmpl::{Context, Template};

let tmpl = Template::from_source("---
params: []
---

> {% raw %}

{{ not_processed }}

> {% /raw %}").unwrap();

let ctx = Context::new();
assert_eq!(tmpl.render_ctx(&ctx).unwrap(), "{{ not_processed }}\n");
```

Custom delimiter to escape `{% /raw %}` itself:

```markdown
> {% raw=# %}
> This outputs {% raw %}...{% /raw %} literally.
> {% /# %}
```

Any string works as the delimiter — `#` is a common choice:

```markdown
> {% raw=# %}{{ not_a_variable }}{% /# %}
```

---

## Comments

Template comments are stripped from output. Parameters referenced inside
`{{ }}` delimiters within comments count as "used" for unused-parameter analysis.
Bare variable names (without `{{ }}`) do **not** count:

```markdown
{# This comment won't appear in output #}
{# {{ reserved_var }} — suppresses unused-parameter error #}
{# reserved_var — bare name, does NOT suppress the error #}
Hello {{ name }}!
```

Use the `{# unused: ... #}` pattern to document intentionally unused parameters:

```markdown
{# unused: {{ role_type }}, {{ agent_name }} #}
```

Multiple `{{ }}` references in a single comment are all tracked. Dotted paths
like `{{ item.label }}` track the root variable (`item`).

---

## Whitespace Control

Add `-` inside any delimiter to strip adjacent whitespace:

| Delimiter | Effect                                                        |
| --------- | ------------------------------------------------------------- |
| `{%-`     | Strips whitespace _before_ the tag (back to previous newline) |
| `-%}`     | Strips whitespace _after_ the tag (through next newline)      |
| `{{-`     | Strips whitespace _before_ the expression                     |
| `-}}`     | Strips whitespace _after_ the expression                      |

```rust
use md_tmpl::{ctx, Template};

let tmpl = Template::from_source("---
params:
  - name = str
---
hello  {{- name -}}
bye").unwrap();

let output = tmpl.render_ctx(&ctx! { name: "world" }).unwrap();
assert_eq!(output, "helloworldbye");
```

---

## Error Diagnostics

All errors are returned as `TemplateError` variants with structured fields:

```rust
use md_tmpl::{Context, Template, TemplateError};

let err = Template::from_source("---
params:
  - x = str
---
{{ x | badfilter }}").unwrap_err();

if let TemplateError::Syntax(syn) = &err {
    assert!(syn.line.is_some());
    assert!(syn.snippet.is_some());
    assert!(syn.message.contains("badfilter"));
}
```

Type mismatches include the path to the failing field:

```rust
use md_tmpl::{VarType, VarDecl, TypeCheckError, Value};
use std::sync::Arc;

let var_type = VarType::List(vec![VarDecl {
    name: "score".into(),
    var_type: VarType::Int,
    default_value: None,
}]);

let items = Value::List(Arc::new(vec![
    Value::Struct(Arc::new([("score".into(), Value::Int(10))].into())),
    Value::Struct(Arc::new([("score".into(), Value::Str("bad".into()))].into())),
]));

let err = var_type.check(&items).unwrap_err();
assert_eq!(err.path, "[1].score");
assert_eq!(err.expected, "int");
assert_eq!(err.actual, "str");
```

---

> **Rust API & SDK Documentation**: For language-specific APIs (macros,
> `CompileOptions`, loading, caching, serde integration,
> typed-builder), see the [README]README.md.