polydat 0.11.2

Polydat — a variates construction engine
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
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
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
---
type: specification
title: The Polydat Grammar
timestamp: 2026-09-25
description: "The normative surface language: lexical rules, productions, operators, type inference, casts, modules, and the G-axioms."
tags: [language]
---

# The Polydat Grammar

This document specifies the Polydat surface language: its lexical
grammar, statement and expression productions, type-naming vocabulary,
desugaring and projection behaviour, and rejection rules. It also
states the type rules and the six G-axioms that the substrate,
compiler, runtime, and embedding specifications depend on
(§[18](#sec-gaxioms)), and lists the productions
(§[21](#sec-productions)). Every example in it is checked by the test
suite (§[0.1](#sec-roundtrip)).

**Ownership:** the `polydat-grammar` crate.

**Related specifications:** [`graph_compiler.md`](graph_compiler.md)
(the compilation passes applied to what this document parses),
[`comprehension_forms.md`](comprehension_forms.md) (the algebra behind
the `for` construct, §[16](#sec-for)), [`polytile.md`](polytile.md)
(the semantics of tiles, §[17](#sec-tiles)),
[`type_system.md`](type_system.md) (the adapter machinery behind the
type keywords), and
[`polydat_grammar_programmatic.md`](polydat_grammar_programmatic.md)
(the same examples built through the AST types).

<a id="sec-authority"></a>
## 0. Authority

This document is the normative reference for the Polydat surface
language.

The language is implemented by its own crate, `polydat-grammar`: the
lexer, the parser, the AST and its projector, the free-name collector,
pragmas, the diagnostic types, the tile template parsers, the
comprehension sub-language with its algebra, and the port type
vocabulary, with no runtime behind them. `polydat` depends on it and
re-exports every module at the paths `polydat::dsl::ast`,
`polydat::dsl::parser`, `polydat::iteration::comprehension::parse`, and
`polydat::ast::PortType`. A tool that only reads, checks, or prints
Polydat source can link the grammar crate alone. The runtime defines
what the grammar's results mean when executed: what a type means to a
compiled buffer (its slot color and width) is defined by an extension
trait in `polydat::ast`, and the runtime likewise defines what a
comprehension evaluates to, what a tile renders, and what a cursor
sugar rewrites into.

The following diagram shows the path of source text through the
grammar crate and where the compiler takes over. Operators stay
`BinOp` nodes in the AST and become calls in the compiler.

![Source text passes through the polydat-grammar crate's lexer and parser to a PolydatFile AST, which pp_file prints as canonical source and the polydat compiler compiles](../diagrams/polydat_grammar-pipeline.png)

<a id="sec-roundtrip"></a>
### 0.1 How the examples are verified — the round-trip contract

Polydat ships a projector,
[`polydat::dsl::pprint::pp_file`](../../../polydat-grammar/src/pprint.rs), that turns a
parsed AST back into canonical `.polydat` source. Throughout this spec,
**“the syntax the runtime gives back”** means the output of `pp_file`.

The projector's guarantee is **idempotence**, not textual fidelity:

```text
let p1 = pp_file(parse(src));
let p2 = pp_file(parse(p1));
assert_eq!(p1, p2);            // second-pass print == first-pass print
```

Projection is *canonicalizing*: its output differs from the input text
in three ways.

1. **Every `BinOp` is fully parenthesized.** `y := x + 1` projects as
   `y := (x + 1)`. This is uniformly safe and makes precedence explicit.
2. **String interpolation is desugared at parse time.** `name := "{a}-{b}"`
   parses to a `printf` call and projects as
   `name := printf("{}-{}", a, b)` (see §[9]#sec-interpolation).
3. **Integer-valued finite floats gain a trailing `.0`.** `60.0` stays
   `60.0`; `6.283185307179586` is preserved exactly.

Code blocks tagged <code>```polydat</code> in this document are parsed
and checked for idempotent round-trip. Blocks additionally tagged
<code>```polydat compile</code> are also compiled (and must succeed).
Blocks tagged <code>```text</code> are illustrative only — EBNF,
token tables, rejected forms, and programs that need wires or modules
this file does not define — and are **not** parsed.

A second document,
[`polydat_grammar_programmatic.md`](polydat_grammar_programmatic.md),
builds a selection of these same kernels **programmatically** through
the public AST types, and the test checks that the two construction
paths project to **identical** canonical syntax
(`pp_file(builder_ast) == pp_file(parse(grammar_src))`). Those paired
examples are flagged **[↔ programmatic]** below.

---

<a id="sec-lexical"></a>
## 1. Lexical basics

Polydat source is a sequence of **statements**. It is
**newline-insensitive and has no statement terminators** — statement
boundaries are determined entirely by the parser, not by line breaks or
semicolons. Identifiers are ASCII `[A-Za-z_][A-Za-z0-9_]*`.

<a id="sec-comments"></a>
### 1.1 Comments

Three comment forms exist; all are stripped by the lexer:

- `#` to end of line
- `//` (and `///`) to end of line
- `/* … */` block comments — **non-nesting**

```text
# a hash comment, to end of line
x := 1   // a line comment after a statement
y := 2   /* a block comment */
/* block comments do /* not */ nest — this trailing text is live code
```

Note that `pragma` (§[14](#sec-pragmas)) is a real first-class statement,
**not** a comment, despite looking directive-like.

<a id="sec-keywords"></a>
### 1.2 Keywords

There are exactly **ten hard keyword tokens**:

```text
const   input   extern   shared   volatile   cursor   over   pragma   for   tile
```

Everything else — including `module`, `as`, `if`, `else`, `range`, and
every type name (`u64`, `f64`, …) — is an ordinary identifier. Three of
the ten are **soft** in expression position and may be used as names:
`input`, `cursor`, `over`. The other seven (`const`, `extern`, `shared`,
`volatile`, `pragma`, `for`, `tile`) cannot be used as names. `for` and
`tile` are also the two keywords after which the lexer captures raw
text: the comprehension text after `for` (§[16](#sec-for)) and the
template body after a tile's `:=` (§[17](#sec-tiles)). `as` is a *soft
postfix keyword*: it is a cast only in `<expr> as <type>` position and is
otherwise an ordinary identifier (it is also the conventional module
parameter name). `if` is a soft keyword: `if(` is the call form of the
intrinsic and `if <cond> {` its block form (§[7.1](#sec-if-block)), and
a wire may still be named `if` where no block can follow.

<a id="sec-operators"></a>
### 1.3 Operator and punctuation tokens

```text
+  -  *  /  %  **          arithmetic ( ** = power )
&  |  ^  <<  >>            bitwise / shift
&&  ||  !                  logical and/or (eager), bitwise NOT
==  !=  <  >  <=  >=       comparison
:=                         binding
=                          only after `extern …: T` and `cursor …`
:  ->  .  ,                annotation, module arrow, field access, separator
( ) [ ] { }               grouping, arrays, module bodies
```

Two tokens are easy to confuse:

- `:=` (`ColonEq`) is the **binding** operator, used by *every* binding
  form. `=` (`Eq`) is used **only** by `extern …: T = default` and
  `cursor … = constructor`. `x = 1` is **not** a binding.
- `-` is always the minus token; there is no negative-literal token.
  `-5` is unary negation applied to `5` (§[6.3](#sec-unary)).

There is **no `..` token**: `..` lexes as two `.` tokens, and `range(a, b)`
is an ordinary function call, not special syntax.

---

<a id="sec-literals"></a>
## 2. Literals

<a id="sec-int-literals"></a>
### 2.1 Integer literals

Decimal and `0x`/`0X` hexadecimal only (no binary or octal). Integer
literals have type `u64`.

```polydat
decimal := 1000
hexa := 0xFF
big := 4294967296
```

> **Gotcha — no underscore separators.** `1_000` does **not** lex as
> `1000`; it lexes as `1` followed by the identifier `_000`. Write
> `1000`.

<a id="sec-float-literals"></a>
### 2.2 Float literals

A digit run becomes a float only when a `.` is **followed by a digit**.
This is what disambiguates a float from a field access: `1.0` is the
float one; `1.foo` is `1` `.` `foo`; `.5` is `.` then `5`; `1.` is `1`
then `.`. Scientific notation (`1e10`, `2.5e3`, `3.14e-2`) is supported,
with or without a decimal point. Float literals have type `f64`.

```polydat
pi := 3.14
scaled := 1e10
small := 3.14e-2
tau := 6.283185307179586
```

<a id="sec-si-suffixes"></a>
### 2.3 SI suffixes on numbers

A numeric literal may carry an SI suffix, applied only when the
character after the suffix is not identifier-continuation:

| Class | Suffixes | Multiplier |
|---|---|---|
| Decimal | `K` `M` `G` `T` `P` | 10³ … 10¹⁵ |
| Binary | `Ki` `Mi` `Gi` `Ti` `Pi` | 2¹⁰ … 2⁵⁰ |
| Sub-unit | `m` `u` `n` | 10⁻³, 10⁻⁶, 10⁻⁹ |

The two-character binary forms are checked first (so `K` does not eat the
`K` of `Ki`). An SI value that is exactly integral collapses to a `u64`;
a sub-unit suffix promotes to `f64`.

```polydat
thousand := 1K
kibi := 1Ki
half_milli := 5m
integral := 1.5K
not_a_suffix := 1
distance_label := one_Kilometer
```

Here `1K` → `1000` (`u64`), `1Ki` → `1024`, `5m` → `0.005` (`f64`),
`1.5K` → `1500` (`u64`, integral). `1Kilometers` would lex as `1`
followed by the identifier `Kilometers` — the suffix only applies when
nothing identifier-like follows it.

<a id="sec-string-literals"></a>
### 2.4 String literals

Delimited by `"…"` or `'…'`; both kinds are ordinary string literals
(single quotes are **not** character literals — they are commonly used
for charset specs like `'0-9A-Za-z'`). Recognized escapes are `\n`,
`\t`, `\\`, and the active quote character; any other `\x` keeps the
backslash literally.

```polydat
greeting := "hello world"
charset := '0-9A-Za-z'
escaped := "line one\nline two"
quote := "she said \"hi\""
```

`{…}` placeholders inside a string are **interpolation**, desugared to a
`printf` call — see §[9](#sec-interpolation).

<a id="sec-array-literals"></a>
### 2.5 Array literals

`[expr, …]`, possibly empty.

```polydat
weights := [60.0, 20.0, 15.0, 5.0]
empty := []
```

<a id="sec-bool"></a>
### 2.6 `true` and `false`

`true` and `false` are **plain identifiers**, not a distinct boolean
literal token. Comparison and logical operators yield a `u64` `0`/`1`,
not a separate bool value at the wire level (§[7](#sec-comparison)).

---

<a id="sec-bindings"></a>
## 3. Bindings  **[↔ programmatic]**

The fundamental statement is a **binding**: a name `:=` an expression.
In this document a *cycle* is one write of the coordinate inputs by
`set_inputs` (§[4](#sec-inputs)), and a *per-cycle* value is one that
may differ from one cycle to the next. A bare binding, one without a
modifier (§[5](#sec-modifiers)), is **per-cycle**: it is re-evaluated
at the first read after an input it depends on is written, so it may
take a new value every cycle.

```polydat compile
input cycle: u64
hashed := hash(cycle)
user_id := mod(hashed, 1000000)
```

This is the minimal program: it takes a cycle coordinate and returns a
bounded id. Its projection is byte-for-byte the same as the source (no `BinOp`, no interpolation, no
float to canonicalize). It is verified end-to-end — built both from this
source and from a hand-constructed AST — in
[the programmatic guide](polydat_grammar_programmatic.md#p-minimal).

<a id="sec-destructuring"></a>
### 3.1 Tuple-destructuring bindings  **[↔ programmatic]**

A multi-output node call binds to a parenthesized target list. The
binding operator is still `:=`.

```polydat compile
input cycle: u64
(region, store, tx) := mixed_radix(cycle, 50, 200, 0)
region_id := mod(hash(region), 10000)
store_id := mod(hash(interleave(region, store)), 100000)
```

`mixed_radix` decomposes a flat cycle into positional digits; a trailing
radix of `0` means unbounded. Paired AST builder:
[programmatic guide](polydat_grammar_programmatic.md#p-destructure).

---

<a id="sec-inputs"></a>
## 4. Inputs

`input name: type` declares a per-cycle coordinate slot driven by
`set_inputs`. The type annotation is **optional and advisory** — every
coordinate input is held as a `u64` at runtime regardless of the annotation;
the annotation aids inference and documents intent.

```polydat
input cycle: u64
input thread
```

The declaration may be **omitted entirely**. A name a program
references but never binds locally becomes a slot the host must supply,
which the bind pass discovers by collecting free names
([graph_compiler.md §2](graph_compiler.md)) — so `y := hash(cycle)` is
a complete program with one coordinate input. An `input` line declares
the same slot explicitly, which is useful where the intent or the type
matters to a reader. In both cases the host boundary applies the same
check: a host that fails to supply an inferred slot gets a reported
mismatch, not a default.

The compiler treats `cycle` like any other name. It is the
conventional name of the primary coordinate, the one a host advances,
and the examples use it for that reason. A program may
name its coordinates anything, take several, or take one and decompose
it (§[3.1](#sec-destructuring)).

<a id="sec-input-tuple"></a>
### 4.1 Tuple input form

`input (a: T, b: T, …)` is sugar that **desugars at parse time** into N
separate `InputDecl`s. The empty form `input ()` is rejected.

```polydat compile
input (cycle: u64, thread: u64)
combined := interleave(cycle, thread)
row_key := mod(hash(combined), 1000000)
```

> **Projection note.** Because the tuple form desugars to N decls, this
> program projects back as two lines —
> `input cycle: u64` / `input thread: u64` — not as the tuple. That is
> the canonical form, and the round-trip is still idempotent. The
> [programmatic builder]polydat_grammar_programmatic.md#p-tuple-input
> constructs the two `InputDecl`s directly, matching the projection.

---

<a id="sec-modifiers"></a>
## 5. Binding modifiers — `const`, `shared`, `volatile`

A binding may be prefixed by one or more **wire modifiers**, in any
order. A modifier declares the binding's *lifecycle*: when its value is
computed and how long it is kept. The compiler checks the declaration
against the chain of wires the binding reads; it does not infer the
lifecycle from them (G-axiom **G2**, §[18](#sec-gaxioms)). In the
table, a *scope* is the top-level program or one `for` body
(§[16](#sec-for)), and a scope is *activated* when it starts: once for
the top-level program, and once per tuple for a `for` body.

| Modifier | Meaning |
|---|---|
| `const` | Evaluated at kernel initialization: once when the scope's kernel is initialized, from its inputs as they are then, and fixed for the kernel's life. A literal right-hand side folds at build. Cannot be shadowed by an inner scope. |
| `shared` | A mutable cell that propagates upward to the enclosing scope after a `for` traversal body. Last-write-wins by default. |
| `volatile` | Forced Dynamic and re-evaluated at every read that reaches it: excluded from compile-time folding and from program-identity hashing, and never cached from one read to the next. |

```polydat compile
input cycle: u64
const base := 42
const seed := hash(base)
shared error_budget := 100
volatile attempt := mod(hash(cycle), 8)
user_id := mod(hash(cycle), 1000000)
```

`base` has a literal right-hand side and folds at build. `seed` is
evaluated when the kernel is initialized; its expression reads only
`base`, so its value is the same in every kernel. `user_id` varies per
cycle, and `attempt` is evaluated again at every read.

A `const` may not read a coordinate, directly or through plain
bindings, since a coordinate advances every cycle; that is a compile
error. A `const` may read an extern: the extern's value at
initialization is the const's value, and a later write to the extern
does not change it until the host calls `Kernel::init`
([Evaluation Model](evaluation_model.md), "Const Binding Contract").

<a id="sec-modifier-combos"></a>
### 5.1 Valid and rejected combinations

`shared volatile` is a valid combination. Two combinations are
**rejected at parse time** because their modifiers contradict each
other. `const volatile` pairs a value evaluated once per kernel with one
evaluated at every read. `shared const` pairs a value fixed for the
kernel's life with a register that other scopes write. A **duplicate
modifier** is rejected as well. A `const` whose expression reads a
volatile wire or a nondeterministic node is valid: it captures that
value once, at initialization.

A `shared` binding's starting value may be any expression that reads no
coordinate. The declaring scope evaluates it once, at initialization,
and a scope that attaches to the register does not evaluate it again
([Scope Model](scope_model.md) §6).

```text
const volatile x := 1       # REJECTED: contradictory modifiers
const const y := 2          # REJECTED: duplicate modifier
shared const z := 100       # REJECTED: contradictory modifiers
shared w := hash(42) % 10   # OK: starting value computed at initialization
```

> There are no `init` or `final` modifiers; `const` covers both roles,
> and the language does not add them. A `const` is evaluated at kernel
> initialization, which is the `init` role, and its value is fixed for
> the kernel's life, which is the `final` role; over a volatile
> expression the same rule makes it a capture, such as
> `const session_start := current_epoch_millis()`.

<a id="sec-shared-typed"></a>
### 5.2 Typed shared cells — `shared x: T := …`

A `shared` binding may carry a type annotation between the name and
`:=`. The annotation pins the cell's type for the cell's lifetime
([Scope Model](scope_model.md) §6.1: a cell keeps one `PortType` and a
write never changes it), so the cell's type does not depend on literal
inference (`1` versus `1.0`). An integer literal initializer
widens to an `f64`-annotated cell; any other mismatch between the
initializer's type and the annotation is a compile error at the
declaration. The annotation is accepted **only** on `shared` bindings,
because only a `shared` binding has a cell whose type an annotation can
pin; on any other binding it is a parse error pointing at
`extern name: T = …` as the typed-slot form. The annotation is part of
the canonical projection.

```text
shared total: f64 := 0          # a float cell, initialised from an integer literal
shared status: str := "init"
const scale: f64 := 1           # REJECTED: annotation only on `shared`
shared count: u64 := 1.5        # REJECTED: initializer does not match the annotation
```

---

<a id="sec-expressions"></a>
## 6. Expressions and operators

There is one expression grammar, used identically for a four-character
expression and a two-hundred-line kernel (G-axiom **G6**). The non-sugar
constructors are: identifier, integer literal, float literal, string
literal, array literal, call, field access, the `as` cast
(§[10](#sec-casts)), and the `for` expression (§[16](#sec-for)). Three
**sugar** forms — binary operator, unary negation (`-`), and bitwise NOT
(`!`) — desugar to calls, as does the block form of `if`
(§[7.1](#sec-if-block)).

<a id="sec-precedence"></a>
### 6.1 Precedence and associativity

Loosest to tightest; all left-associative except `**`:

```text
||                     (lowest)
&&
== !=
< > <= >=
|
^
&
<< >>
+ -
* / %
**                     (RIGHT-associative)
unary - !              (- = arithmetic negate; ! = bitwise NOT)
postfix  as <type>     (tightest; binds to the atom; chains left-to-right)
```

So `a > b && c > d` parses as `(a > b) && (c > d)`; `a + b < c * d` as
`(a + b) < (c * d)`; `a + b as u64` as `a + (b as u64)`; and `2 ** 3 ** 2`
as `2 ** (3 ** 2)` (right-associative).

<a id="sec-arithmetic"></a>
### 6.2 Arithmetic

`+ - * / %` choose `u64_*` when **both** operands are `u64`, otherwise
the `f64_*` form with the `u64` side widened by an inserted `to_f64`
adapter. `**` is always `pow` (`f64`). Bitwise/shift operators
(`& | ^ << >>`) and prefix `!` are `u64` unconditionally: they desugar
to the `u64_*` node whatever the operand type, so an `f64` operand is
wired to a `u64` port and the wire fails to resolve — a compile error
naming both types, never a silent reinterpretation of the float's bits.

Widening is the only implicit numeric conversion, and it is always
logged. The inserted `to_f64` is logged at advisory level (`widening
u64 → f64 in operator *`), so an author reviewing a module can find
every place the compiler chose the float variant rather than the
integer one. The reverse direction is never implicit: narrowing an
`f64` to a `u64` takes a named cast function, because the rounding is
the author's choice to make (§[10](#sec-casts)).

```polydat compile
input cycle: u64
a := hash(cycle)
sum := a + 7
masked := a & 0xFF
shifted := a >> 3
power := 2 ** 10
```

Projected, the binops are fully parenthesized: `sum := (a + 7)`,
`masked := (a & 255)`, `power := (2 ** 10)`. (Note `0xFF` projects as its
decimal value `255` — the projector emits a canonical integer.)

<a id="sec-unary"></a>
### 6.3 Unary `-` and `!`

`-x` desugars to `f64_sub(0.0, x)`; `!x` desugars to bitwise NOT
(`u64_not`), **not** logical negation.

```polydat
delta := -100.0
bits := !0
```

`delta` projects as `(-100.0)` and `bits` as `(!0)`.

---

<a id="sec-comparison"></a>
## 7. Comparisons and logical operators

Comparison operators (`== != < > <= >=`) select `str_*`/`f64_*`/`u64_*`
by operand family (string beats float beats u64) and produce a `u64`
`0`/`1`. Ordered comparisons (`< > <= >=`) on **strings are a compile
error**; only `==`/`!=` are defined for strings.

The logical operators `&&` and `||` are **eager** (no short-circuit —
both sides always evaluate): each operand is reduced to truthiness
(`x != 0`) and combined with `u64_and`/`u64_or`.

```polydat compile
input cycle: u64
x := hash(cycle)
big := x > 1000000
in_band := (x > 100) && (x < 1000000)
flag := (x == 0) || big
```

`big` projects as `(x > 1000000)`; `in_band` as
`((x > 100) && (x < 1000000))`; `flag` as `((x == 0) || big)`.

The built-in `if(cond, a, b)` is a compiler intrinsic (a closed
parse-time form, G-axiom **G6.i**) lowering to `select_u64/f64/str`;
like the logical operators it evaluates **both** branches. The branch
type is chosen by priority `Str` > `f64` > `u64`: when one branch is
`u64` and the other `f64`, the `u64` branch is widened through `to_f64`.
The condition is `u64`; any nonzero value selects `a`, zero selects `b`.

```polydat compile
input cycle: u64
optimize_for := "LATENCY"
latency_factor := 1.5
recall_factor := 9.5
overscan := if(optimize_for == "LATENCY", latency_factor, recall_factor)
```

<a id="sec-if-block"></a>
### 7.1 The block form — `if cond { a } else { b }`

The same intrinsic has a block spelling. The parser rewrites
`if <cond> { <then> } else { <else> }` to `if(cond, then, else)` before
anything else sees it, in the same way `a + b` becomes `u64_add(a, b)`,
so branch-type dispatch, the `u64`→`f64` widening, and the `select_*`
node are identical between the two spellings: one construct, two ways
to write it. `else if` chains by recursion, so
`if a { 1 } else if b { 2 } else { 3 }` is `if(a, 1, if(b, 2, 3))`. The
block form is an expression and composes like one
(`scaled := 1 + if hot { 10 } else { 0 }`).

```polydat compile
input cycle: u64
n := 12
out := if n > 0 { 100 } else { 7 }
```

```polydat compile
input cycle: u64
n := 5
out := if n > 10 { 1 } else if n > 3 { 2 } else { 3 }
```

```polydat compile
input cycle: u64
s := "LATENCY"
out := if s == "LATENCY" { "fast" } else { "thorough" }
```

Two rules follow from Polydat being a dataflow language:

- **`else` is mandatory.** A Polydat expression always produces a value
  and there is no unit type, so a one-armed `if` would have no result on
  the false path. A missing `else` is a parse error.
- **The braces are not a guard.** Both branches always evaluate, so
  `if n > 0 { total / n } else { 0 }` does *not* protect the division;
  write `total / max(n, 1)` instead. The block form looks imperative;
  the semantics remain dataflow.

> **Projection note.** The block form projects as the canonical call
> form: `out := if((n > 0), 100, 7)`. The round-trip is idempotent from
> there.

---

<a id="sec-calls"></a>
## 8. Function calls

`name(arg, …)`, where each argument is either **positional** (`expr`) or
**named** (`ident: expr`). Positional and named may be mixed (positional
first by convention); the empty call `name()` is allowed. The soft
keyword `input` is accepted as an argument name.

```polydat compile
input cycle: u64
h := hash(cycle)
u := unit_interval(h)
raw := icd_normal(u, 100.0, 15.0)
clamped := clamp_f64(raw, -50.0, 50.0)
```

Named-argument form (common for stdlib module calls):

```polydat
v := dist_normal(mean: 72.0, stddev: 5.0)
weights := combinations(seed: 0, charset: "A-Z0-9", length: 8)
```

An argument that is a bare literal is **promoted** to an anonymous
constant node, which is why calls mix wires and literals freely:
`pow(x, 2.0)` and `exp := 2.0` followed by `pow(x, exp)` compile to the
same graph. The promoted node is compile-constant, so constant folding
removes it at compile time and the literal adds no per-cycle work.
Promotion is one of the closed set of parse-time intrinsics
(§[18](#sec-gaxioms), G6.i) — a library cannot add another.

---

<a id="sec-interpolation"></a>
## 9. String interpolation

A string literal containing `{…}` placeholders is **desugared at parse
time** into a `printf` call. The placeholder body is parsed as a full
expression; `{{`/`}}` are literal braces; a malformed placeholder (e.g. a
printf format spec like `{:05}`) silently stays a plain `StringLit`.

```polydat compile
input cycle: u64
(tenant, device, reading) := mixed_radix(cycle, 100, 1000, 0)
tenant_code := mod(hash(tenant), 10000)
device_seq := mod(hash(interleave(tenant, device)), 100000)
device_id := "{tenant_code}-{device_seq}"
label := "sensor_reading"
```

> **Projection note (important).** `device_id := "{tenant_code}-{device_seq}"`
> parses to a `printf` call, so it **projects back as**
> `device_id := printf("{}-{}", tenant_code, device_seq)`. The
> placeholder-free `label` stays `"sensor_reading"`. The projection is
> the desugared form, and the round-trip is idempotent from there.

---

<a id="sec-casts"></a>
## 10. `as` casts

`<expr> as <type>` declares the type a wire should have and inserts the
adapter that gets it there. The rule, in order:

- same type → a no-op passthrough;
- `str as u64` → the string-to-number parse (`StrToU64`): a declared
  reading of text, not a narrowing;
- `f64 as u64` → a **hard compile error**. Narrowing a float to an
  integer under `as` is disallowed because the rounding is a semantic
  choice the author must make by name: `f64_to_u64` (truncate),
  `round_to_u64`, `floor_to_u64`, or `ceil_to_u64`;
- any other pair → exactly the adapter the assembler would insert
  between a wire of the expression's type and a port of the target type,
  from the whole adapter catalog ([Type System]type_system.md §3):
  every lossless widening (`u64 as f64` is `to_f64`), every register
  retag, and the JSON and byte-string conversions the catalog defines. A
  pair the catalog has no adapter for is a compile error naming both
  types.

Casts may chain (`x as u64 as f64`). A hole's declared type in a tile
(`${x: u64}`, §[17](#sec-tiles)) follows the same rule, so a tile hole
can use every catalog adapter a binding can.

```polydat compile
input cycle: u64
x := hash(cycle)
ratio := (x as f64) / 4294967296.0
```

`ratio` projects as `((x as f64) / 4294967296.0)`. The cast binds tighter
than `/`, so the projection's parenthesization matches the source's.

```text
narrowed := some_f64 as u64    # REJECTED: use round_to_u64 / f64_to_u64 / …
```

---

<a id="sec-fields-cursors"></a>
## 11. Field access and cursors  **[↔ programmatic]**

<a id="sec-field-access"></a>
### 11.1 Field access

`base.field` projects a field from a source-typed base. The base must be
a bare identifier (or soft keyword); field access does **not** apply to
call results or parenthesized groups. **Chained** dots are accepted and
flattened with `__`: `q.cursor.idx` becomes
`FieldAccess { source: "q__cursor", field: "idx" }`, reading wire
`q__cursor__idx`.

<a id="sec-cursors"></a>
### 11.2 Cursors

A **cursor** is a named `u64` ordinal: a position into a dataset,
used to read its records. Its declaration uses `=` (not `:=`):
`cursor <name> = <constructor> [over <expr>]`. A cursor has no fields or
schema of its own; data is read through accessor functions that take
the cursor's ordinal and return the record's values. The optional `over <expr>` clause
([Cursor Partitions](cursor_partitions.md)) supplies a partition source.

```polydat
cursor users = range(0, 1000000)
```

```polydat
cursor q = range(0, 100) over p
i := q.cursor.idx
ratio := (i as f64) / 100.0
```

> The `over` clause is part of the canonical projection — `pp_cursor`
> emits it, so a cursor with `over` round-trips faithfully. The paired
> AST builder is in the
> [programmatic guide]polydat_grammar_programmatic.md#p-cursor-over.

The **constructor** is an ordinary expression. `range(start, end)` is the
finite-ordinal form. The cursor-sugar forms of §[11.3](#sec-cursor-sugar)
rewrite to a `range(…)` constructor at compile time.

<a id="sec-cursor-sugar"></a>
### 11.3 Cursor sugar

A **cursor sugar** form is a cursor constructor that the compiler
rewrites into a `range(…)` constructor plus bindings placed after the
cursor. A node module registers each form (`dsl::cursor_sugar`), and
the registry is open to any node module. The vectordata module
registers three forms. They parse in every build and compile under the
`vectordata` feature, so the blocks in this section are round-tripped
and not compiled.

Each form reads one facet of a dataset profile, the base vectors or the
query vectors. Its arguments are string literals, and the compiler joins
the dataset and the profile into one source name, `"<dataset>:<profile>"`.

| Sugar | Means |
|---|---|
| `vectordata_base(dataset, profile)` | `vectordata_source(dataset, profile, "base")` |
| `vectordata_query(dataset, profile)` | `vectordata_source(dataset, profile, "query")` |
| `vectordata_source(dataset, profile, facet)` | The long form below for `facet`, which is `"base"` or `"query"`. |

The base facet, as sugar:

```polydat
cursor row = vectordata_base("example", "label_00")
```

The long form it means:

```polydat
cursor row = range(0, vector_count("example:label_00"))
__row_prebuffer := dataset_prebuffer("example:label_00")
row__vector := vector_at("example:label_00", row.ordinal)
```

The query facet, as sugar:

```polydat
cursor q = vectordata_query("example", "label_00")
```

The long form it means:

```polydat
cursor q = range(0, query_count("example:label_00"))
__q_prebuffer := dataset_prebuffer("example:label_00")
q__vector := query_vector_at("example:label_00", q.ordinal)
```

The cursor ranges over every vector of the facet. `__<cursor>_prebuffer`
loads the profile once, when the kernel is initialized, so reads at
cycle time hit memory that is already loaded. `<cursor>__vector` is the
vector at the cursor's ordinal. The sugar also declares that binding as
the cursor's `vector` projection, so `row.vector` reads it and a host
lists it among the cursor's projections. The long form binds the same
wire, which `row.vector` reads (§[11.1](#sec-field-access)), but it
declares no projection. A facet's other columns, such as metadata or
ground truth, have no sugar and are read with their accessor functions.

---

<a id="sec-externs"></a>
## 12. Externs  **[↔ programmatic]**

`extern name: type [= default]` declares a typed input that the host
writes by name. Its value is fixed when the scope is initialised (via
Context Fusion) rather than advancing per cycle like an `input`. The
default is optional.

```polydat compile
input cycle: u64
extern scale: u64
result := cycle * scale
```

`result` projects as `(cycle * scale)`. Externs are the typed,
host-written counterpart to coordinate inputs; the paired builder is in
the [programmatic guide](polydat_grammar_programmatic.md#p-extern).

```polydat
extern balance: f64 = 0.0
extern session_id: u64 = 0
```

---

<a id="sec-modules"></a>
## 13. Module definitions  **[↔ programmatic]**

A module is a named, typed, reusable computation unit:
`name(params) -> (outputs) := { body }`. Parameters are input slots,
outputs are output ports, the body is a statement block. Modules infer
inputs from unbound references and outputs from terminal bindings; the
explicit signature pins the contract.

```polydat compile
sine_wave(input: u64, period: u64) -> (value: f64) := {
    pos := to_f64(input % period)
    per := to_f64(period)
    value := sin((pos / per) * 6.283185307179586)
}
```

The body uses `input` (a soft keyword) as a parameter name and type-aware
infix that resolves to `f64` once operands are `f64`. The paired builder
is in the [programmatic guide](polydat_grammar_programmatic.md#p-module).

> **Projection note.** Module bodies project with four-space-indented
> statements inside `{ … }`, and inner binops are parenthesized while
> calls are not — so the body projects as
> `pos := to_f64((input % period))` / `per := to_f64(period)` /
> `value := sin(((pos / per) * 6.283185307179586))`. Idempotent from there.

---

<a id="sec-pragmas"></a>
## 14. Pragmas

`pragma <name>` is a statement that opts a scope into a compile-time
check. It takes a bare name and no arguments. The recognized pragmas
are these:

- `strict_values` turns on the strict-wire checks
  ([graph_compiler.md §2.3]graph_compiler.md#sec-strict-wires). A
  constant fed to a port that declares a value constraint is checked at
  build, and any other source feeding such a port gets a runtime guard.
- `strict_types` is accepted and acknowledged, and it has no effect.
  Wires are statically typed, so a runtime type assertion would have
  nothing to catch.
- `strict` is a pragma of its own. It implies `strict_values` and
  `strict_types`, and it turns on strict name checking: a comprehension
  read in its scope that reads a name nothing binds is refused
  (`ValidationError::V3UnresolvedNames`, comprehension_forms.md §5 V3).
  Outside `strict` such a name compiles with a V3 warning on the
  program's compile ledger and reads None. `strict_values` and
  `strict_types`, alone or together, do not check names strictly.

**Unknown pragmas are forward-compatible.** An unknown name is logged
as a warning (`UnknownPragma`), never an error.

```polydat
pragma strict_types
```

**The host's strict switch is `pragma strict` at the top scope.** A
host that compiles with `CompileOptions::strict`, or the binary's
`--strict`, compiles the program as if `pragma strict` were written at
its top: strict value checks, strict type checks, and strict name
checking hold in the program and in every scope that inherits its
pragmas (§[14.1](#sec-pragma-scoping)). A module body follows its own
pragmas alone under a strict host as under any other. The switch also
turns on the checks that have no pragma, such as the refusal of an
implicit type coercion, a binding nothing reads, and a positional module
argument; those are listed on `CompileOptions`.

<a id="sec-pragma-scoping"></a>
### 14.1 Pragma scoping

Pragma scoping is **lexical**. A pragma applies to the scope it is
written in and to every scope nested in it. The scopes are a program, a
`for` body, and a module body. A pragma applies to its whole scope,
wherever in the scope it is written. A `for` body is a nested scope: it
compiles under the enclosing scope's pragmas plus its own. Pragmas are
presence-only, so a nested scope can add to the set and never conflicts
with it. A pragma never reaches an enclosing scope.

A module body is a scope of its own and is not nested in the program
that calls the module. It compiles under the pragmas it declares and no
others, whether the module is defined in the calling program or in a
library file, so a module compiles the same way under every host.

A tile (§[17](#sec-tiles)) is not a scope. It declares no pragmas, and
its holes and its projection bodies compile under the pragmas of the
scope the tile is written in: a tile in a program under the program's, a
tile in a `for` body under the body's, and a tile in a module body under
the module's own ([Polytile](polytile.md) §6). A projection body is
compiled as a `for` body is, with that scope's set.

A pragma in a `for` body applies to the body. The program around it is
unchecked:

```polydat compile
input cycle: u64
d := mod(hash(cycle), 100)
b := mod_wire(cycle, d)
for k in 1..3 {
    pragma strict_values
    c := mod_wire(cycle, k)
}
```

Here `c`'s divisor gets a runtime guard and `b`'s does not.

A module's pragma applies to the module's own bindings. It does not reach
the host that calls the module:

```polydat compile
checked(a: u64, n: u64) -> (out: u64) := {
    pragma strict_values
    out := mod_wire(a, n)
}
input cycle: u64
s := checked(cycle, 7)
b := mod_wire(cycle, s)
```

The module's `mod_wire` is checked: its divisor is the constant 7, which
is checked at build. The host's `mod_wire` is not checked. In the other
direction, a `pragma strict_values` in the host checks the host's
bindings and none of the bindings of a module that declares no pragma.

An enclosing scope's pragma applies to every nested scope, so this
program fails at build on the constant zero divisor in its body:

```text
pragma strict_values
input cycle: u64
for k in 1..3 {
    c := mod_wire(k, 0)
}
```

The type round-trip lint ([graph_compiler.md §2.3](graph_compiler.md#sec-strict-wires))
follows the same rule. Each binding is linted under the pragmas of the
scope it is written in, so a round trip is an error when that scope has
`strict_values` on and a warning otherwise. A round trip inside a
module that declares `strict_values` fails the build under a host that
declares no pragma, and the host's own round trips stay warnings. A
round trip inside a module that declares no pragma is a warning under a
strict host, whose own round trips fail the build.

Name checking (comprehension_forms.md §5 V3) follows the same rule. A
comprehension's names are checked under the pragmas of the scope its
statement is written in: a `for` statement's and a producer binding's in
the scope that holds the statement, and a producer binding's in a module
body under the module's own. Under `strict` a name nothing binds fails
the build; otherwise the build records a warning and the name reads
None. This program compiles, and its traversal dispenses nothing,
because `limit` is bound nowhere and reads None:

```polydat compile
input cycle: u64
for k in 1..4 where {k} > {limit} {
    x := hash(k)
}
```

The same traversal nested in a body that declares `strict` fails the
build, and the program around the body stays unchecked:

```text
input cycle: u64
for j in 1..3 {
    pragma strict
    for k in 1..4 where {k} > {limit} {
        x := hash(k)
    }
}
```

A module that declares `strict` refuses its own producers' unbound
names under a host that declares no pragma, and a module that declares
no pragma warns about them under a `strict` host.

---

<a id="sec-types"></a>
## 15. Types nameable in syntax

The complete set of type keywords usable in `input x: T`, `extern x: T`,
`<expr> as T`, and module signatures is fixed by `PortType::from_keyword`
(`polydat-grammar/src/port_type.rs`, re-exported as `polydat::ast::PortType`):

```text
u64 f64  u32 i32  i64 f32  u8 i8  u16 i16  f16  u128 i128
reg128  reg_i8x16 reg_i16x8 reg_i32x4 reg_i64x2 reg_f16x8 reg_f32x4 reg_f64x2
bool
str
bytes
json
ext
handle
vec_f32 vec_i32 vec_f64 vec_i64 vec_f16 vec_i16 vec_i8
forms fragment admitted_rows
```

The last three are the **dataset types**: what a vector dataset
publishes about its predicates and records, carried as the types
`vectordata` defines ([type_system.md](type_system.md) §1.8). A `forms`
wire is a constant holding the forms of a facet's records, a `fragment`
wire names one record among them for a cycle, and an `admitted_rows`
wire is the set of base positions a query's predicate admits. Only the
dataset nodes of the `vectordata` feature make their values, and a
program names the types where it passes one between scopes
(`extern outer: forms`).

> **Spelling gotchas.** Vector keywords are **underscored**: `vec_f32`,
> not `vecf32`. Register-lane keywords are `reg_i8x16` … `reg_f64x2` plus
> raw `reg128`. There is **no `f128`** (stable Rust has no such type) and
> **no `none`** keyword (`None` is a runtime `Value` sentinel, not a
> type). An unknown keyword is a loud diagnostic, never a silent default:
> the parser refuses it where it is written, in every declaration form
> (`` `strr` is not a type keyword ``).
> Each type has exactly one keyword, the one `Display` and
> `PortType::to_keyword` print. The capitalised spellings polydat
> accepted before 0.10.0 (`String` and `Str`, `Json`, `Ext`) are refused
> wherever a type is named, with the keyword to write instead:
> `` `String` is no longer a type keyword; write `str` ``
> (`PortType::retired_keyword`).

```polydat
input cycle: u64
extern threshold: f64 = 0.5
extern tag: str
extern embedding: vec_f32
```

---

<a id="sec-for"></a>
<a id="sec-comprehension"></a>
## 16. The `for` construct

`for` is one keyword with two readings that share one compiled form
([The `for` Construct](for_traversal.md)). As an **expression**,
`name := for <comprehension>` binds the comprehension as a value: a
**producer** wire of type `Streamer`. As a **statement**,
`for <source> { body }` with no l-value is a **traversal**: one child
scope activates per tuple, and the comprehension's element names are
wires inside the body. The comprehension algebra itself (constructors,
validity axioms, optimizer rewrites, IR) is specified in
[`comprehension_forms.md`](comprehension_forms.md); this section
specifies the statement-language surface.

```text
statement          ::= ... | for_stmt
binding            ::= modifier* ident ":=" expr        (* expr may be for_expr *)
expr               ::= ... | for_expr

for_expr           ::= "for" comprehension_text
                    |  "for" ident ("where" predicate)? ("order" strategy ("/" int)?)?   (* derivation *)
for_stmt           ::= "for" for_source "{" statement* "}"
for_source         ::= comprehension_text                (* inline comprehension *)
                    |  ident                             (* a bound producer *)

comprehension_text ::= clause ("," clause)* ("where" predicate)? ("order" strategy ("/" int)?)?
                    |  "[" ("for" comprehension_text ","?)+ "]" ("where" predicate)? ("order" strategy ("/" int)?)?   (* union *)
clause             ::= ident "in" source
                    |  "(" ident ("," ident)+ ")" "in" source
```

<a id="sec-for-capture"></a>
### 16.1 The captured text

The lexer captures everything after `for` as **one token**: up to the end
of the line at bracket depth zero or a `{` at bracket depth zero, whichever
comes first (a bracketed union runs across lines, one member per line), with
string literals skipped whole. The captured text is handed to the
comprehension parser unchanged, so the comprehension grammar is defined
only by that parser and `pp_file` prints the text back as written. Three
rules follow:

- A traversal's `{` must open **on the same line** as its comprehension;
  `for k in 1..4` followed by a newline is a parse error naming the
  missing block.
- A `{name}` reference inside a `where` predicate is part of the text
  (a block brace is never immediately followed by an identifier and a
  closing brace), so `for k in 1..9 where {k} > 3 {` reads as intended.
- A trailing `//` or `#` comment on the line is not captured.

<a id="sec-for-sources"></a>
### 16.2 Sources, predicates, and order

`source` is the comprehension's source surface: literal lists
(`10,20,30`, `load,verify`, `true,false`), `lo..hi` ranges (`a..=b`
inclusive, `a..b step c`), generator calls such as
`partitions("*/4", n)` and `subdivide(p, n)`, string comprehensions, and
`{name}` references to wires of the enclosing scope, which are resolved
when the traversal is opened. A continuous source is a float range
(`0.0..1.0`, uniform over the interval) or a named measure,
`normal(0, 1)`, drawing from the measure's own support, and
`exponential(1) on 0.0..1.0` for the measure restricted to an interval;
the measures are the closed set `normal`, `exponential`, `pareto`,
`beta`, `log_normal`, `gamma`, and `uniform01`, each taking its own
parameters in order or none for the standard ones. A continuous source
projects only under a sampling order, per the order rules below.
A depth-0 comma starts a new clause only
when followed by `<ident> in`, so value-list and argument commas stay
inside one clause. Tuple clauses `(a, b) in (…)` zip in parallel;
`zip_truncate(…)` and `zip_cycle(…)` choose the zip mode.

`where <predicate>` keeps the tuples for which the predicate is true.
A predicate is a boolean expression over the tuple's elements, each
written `{name}`; a `{name}` the tuple does not bind resolves in the
scope the traversal opens in. It groups by the language's one
precedence table (§[6.1](#sec-precedence)):

| Binds | Operators in a predicate |
|---|---|
| tightest | unary `!` and `-` |
| | arithmetic (`**`, then `* / %`, then `+ -`), then the bitwise operators, in §6.1's order |
| | comparisons: `< <= > >=` and membership `{name} in [v1, v2, …]`, then `== !=` |
| | `&&` |
| loosest | `\|\|` |

So `!{done} || {retry}` is `(!{done}) || {retry}`, `{a} || {b} && {c}`
is `{a} || ({b} && {c})`, and `{x} + 1 > {y} * 2` compares the two
sums. Parentheses group as anywhere else.

A predicate evaluates per tuple, and three of its rules differ from the
statement language's operators of §[7](#sec-comparison). `&&` and `||`
evaluate their operands left to right and stop at the operand that
decides the result, so `{n} != 0 && {total} / {n} > 2` never evaluates
the division when `{n}` is zero. `!` negates a truth value (a boolean,
or a number that is true when non-zero) rather than inverting bits.
Values compare as scalars: numbers with numbers, strings with strings
(ordered comparisons included), booleans with booleans; a value is
never equal to a value of another kind, so `{name} != 2` holds for a
string, and ordering values of different kinds is an error.
comprehension_forms.md §10.9.1 specifies the evaluation in full.

A string in a predicate is quoted, as everywhere in the language:
`{region} == "us-east"` or `{region} == 'us-east'`. A bare word is a
name, never a string, and a predicate has no names beside its elements,
so `{region} == us-east` reads `us - east` as a subtraction of two names
that nothing supplies. Under `pragma strict` the compile refuses it,
saying a string is quoted; otherwise the compile warns, saying the same,
and the two names read None, so the predicate keeps no tuple.

Every name a source or a predicate reads is bound by the comprehension
or is a name of the scope the traversal opens in: a source reads the
elements of the clauses before it, a predicate its tuple's elements, and
both read the enclosing scope's wires, which the traversal captures when
it opens. A name that is neither is bound nowhere (comprehension_forms.md
§5 V3). Under `pragma strict` (§[14](#sec-pragmas)) the compile refuses
it, naming it and where it is read. Otherwise the compile records a
warning naming the same, and the name reads None: a source reading it
yields nothing, and a predicate that reads it for a tuple keeps that
tuple not.

```polydat compile
input cycle: u64
for k in 1..10, region in ["us-east", "eu-west"] where {k} > 3 && {region} == "us-east" {
    x := hash(k)
}
```

`order <strategy>[/<n>]` permutes and optionally truncates;
the strategy names the text grammar accepts are `lex`, `reverse_lex`,
`diagonal`, `antidiagonal`, `extrema`, `shells`, `halton`, `sobol`, `lhs`,
and `shuffle`, plus the meta-form `space_filling(<halton|sobol|lhs>, …)`, as a
bare `name`, terse `name/N`, or keyword `name(arg=val, …)`. The keyword
form carries `seed=<u64>` for `shuffle` and `lhs`, the authored seed those
strategies derive their permutation from; any other strategy refuses a
seed. The set is closed: a name outside it is a parse error that lists
the set and says so, and there is no form that names a function of the
author's own. An order after a `where` ranks only the tuples that pass,
by their positions in the unfiltered space, and keeps its truncation's
worth of them: `where {k} != 5 order extrema/1` is the most extreme
stratum any passing tuple is in (comprehension_forms.md §5 V5). An
order over a producer's order, `for sweep order shuffle` over `sweep :=
for u in 0.0..1.0 order halton/50`, orders that order's output: its
tuples as one axis in the order it selected them, so this shuffles the
50 points (comprehension_forms.md §3.6, §7.4).

<a id="sec-for-elements"></a>
### 16.3 Element types

Each element name is typed at compile time from its source:

| Source form | Element type |
|---|---|
| Integer literal list or `lo..hi` range | `u64` |
| Float literal list or continuous interval | `f64` |
| String literal list or string comprehension | `str` |
| Boolean literal list | `bool` |
| `partitions(...)`, `subdivide(...)`, `<name>.partitions` | `ext` carrying `Partition` |
| A generator node call | the node's declared return type |
| A bound `Streamer` used as a source | `Streamer` |

An integer among floats widens the element to `f64`; a list mixing
numbers and strings is a compile error.

```polydat compile
input cycle: u64
for a in 1..4, b in 10,20,30, c in 1.5,2.5, d in load,verify, e in true,false, p in partitions("*/2", 100) {
    x := hash(a)
}
```

<a id="sec-for-traversal"></a>
### 16.4 Traversals

The body is a statement list compiled once, at parent compile time, into
a child program keyed by the statement's lexical position. Every
statement kind is allowed inside it: bindings, `const`, cursors, module
calls, tiles, nested `for` statements, and nested producers. Element
names are typed inputs of the child; outer wires the body references
become inputs of the child with the parent's types; the only coordinate a body may
declare is `cycle`. The projection indents the body four spaces.

```polydat compile
input cycle: u64
for k in 1..4, limit in 10,20,30 {
    f := hash(k)
    g := u64_add(limit, k)
}
```

A cursor inside a body may be declared `over` an element; at activation
the cursor is narrowed to that partition and the body iterates the
slice:

```polydat compile
input cycle: u64
for p in partitions("*/4", 1000) {
    cursor rows = range(0, 1000) over p
    row := mod_in(cycle, rows.cursor)
}
```

Bodies nest; each level is one program, however many tuples flow, and a
nested comprehension may name the enclosing tuple's elements:

```polydat compile
input cycle: u64
for p in partitions("*/4", 1000) {
    outer := cardinality(p)
    for t in 0..20 {
        mid := u64_add(outer, t)
        for d in 0..50 {
            leaf := u64_add(mid, d)
        }
    }
}
```

<a id="sec-for-producer"></a>
### 16.5 Producers and derivations

`name := for <comprehension>` binds a `Streamer`. The binding is
`const`: the compiler lowers it to `const name := streamer("<payload>")`
over the resolved comprehension, so the wire's value is the
comprehension, held as an `ext` value. A traversal may name a producer instead of inline
text, and reads the producer's element names. A **derivation**,
`for <producer> where …` or `for <producer> order …` (or both), applies
the algebra's filter and order to a producer bound earlier in the same
scope; derivations chain. A bare producer name alone in expression
position (`x := for sweep`) is a parse error, since it modifies nothing.

```polydat compile
input cycle: u64
sweep := for k in 1..4, limit in 10, 20, 30 order halton/5
for sweep {
    f := hash(k)
    g := u64_add(limit, k)
}
```

A derivation names the producer it starts from and adds a `where`, an
`order`, or both. The result is another producer, so a derivation can
be traversed, or derived from again:

```polydat compile
input cycle: u64
sweep := for k in 1..9, limit in 10, 20, 30
large := for sweep where {k} > 3
ordered := for large order lex
for ordered {
    f := hash(k)
    g := u64_add(limit, k)
}
```

The full surface, with both readings, a producer traversal, an inline
traversal, and nesting, round-trips through `pp_file` byte for byte
(this block is not compiled: `myfunc` and `otherfunc` are not defined
here):

```polydat
sweep := for k in 1..4, limit in 10, 20, 30 order halton/5
for sweep {
    f := myfunc(k)
    g := otherfunc(limit, k)
}
for phase in load, verify, p in partitions("*/4", 1000000) {
    row := mod_in(cycle, p)
    for q in 1..2 {
        z := hash(q)
    }
}
```

```text
base     := for k in 1..100, limit in 1..100
boundary := for base where {k} == 1 || {k} == 100
sampled  := for base order halton/50
```

---

<a id="sec-tiles"></a>
## 17. Tiles

A **tile** is a compiled variate template: a skeleton of static bytes
with typed holes bound to wires ([Polytile](polytile.md)). A tile
statement has the shape of every other wire binding,
`modifier name : type := value`: `tile` is the modifier, the encoding
is the type of the document on the wire (its port type is `str`), and
`:=` binds the wire, so another tile reads it as `${doc!}` and a
binding as `f(doc)`. `:=` is mandatory in every body form; a header
without it is a parse error naming the tile.

```text
statement   ::= ... | tile_def

tile_def    ::= "tile" ident (":" encoding)? options? ":=" tile_body
encoding    ::= "json" | "text" | "csv"                (* default text *)
options     ::= "(" option ("," option)* ")"
option      ::= "delims" string string                  (* hole delimiters *)
             |  "sigil" string                          (* directive prefix *)
             |  "strict"
             |  "instring"

tile_body   ::= json_block                              (* json: balanced { } or [ ] *)
             |  heredoc                                 (* <<< ... >>> *)
             |  string_literal                          (* one-line tiles *)
```

The lexer captures a tile body **raw** after `:=`, as it captures the
text after `for`: a `json` body is a brace- or bracket-balanced block,
string-aware; a heredoc is everything between `<<<` and `>>>`; a string
literal is an ordinary Polydat string. A block body keeps the author's
layout but not the indentation of the statement around it (the common
leading whitespace of the lines after the first is removed), so a tile
inside a `for` body renders the same bytes as at top level; heredoc and
string bodies are exact.

<a id="sec-tile-template"></a>
### 17.1 The template grammar

Inside a body:

```text
hole        ::= open expr (":" type)? ("|" format)? ("!")? close
projection  ::= sigil "for" for_source ("sep" string)? "{" body "}"
branch      ::= sigil "if" expr "{" body "}" (sigil "else" "{" body "}")?
splice      ::= open tile_name close
escape      ::= open open                               (* a literal open delimiter *)
```

`open` and `close` default to `${` and `}`; `sigil` defaults to `@`;
all three are overridable per tile with `delims` and `sigil`. A **hole**
is a Polydat expression in the enclosing scope; `:type` declares the
hole's type by the `as` rule (§[10](#sec-casts)), `|format` is a printf
format spec applied before encoding, and `!` marks the hole raw (no
escaping). Named arguments inside a hole expression are not type
declarations. A **projection** repeats its body once per tuple of a
comprehension; `for_source` is the `for` construct's source surface
(§[16](#sec-for)), inline text or a bound producer, and the element
names are wires inside the body. A **branch** renders one of two bodies
by a `u64` condition. A **splice** names another tile of the same
encoding and inlines its skeleton at compile time. A doubled open
delimiter is a literal open delimiter. The braces of a directive block
delimit it and whitespace padding them is not body; braces inside body
text are balanced, so JSON objects sit in a block unescaped; a hole
cannot appear in a directive header, but `{name}` interpolation may.

```polydat compile
input cycle: u64
tile t := "n=${cycle}"
```

Every body form, with a projection, a raw hole, and per-tile options,
round-trips through `pp_file` byte for byte (not compiled here: the
holes name wires this block does not define):

```polydat
tile doc : json := {
    "tenant": ${tenant_id},
    "samples": [ @for s in 0..4 { { "n": ${s} } } ]
}
tile load : text := <<<
INSERT ${keyspace} '${doc!}'
>>>
tile row : csv := "${a},${b}"
tile odd : text (delims "<%" "%>", sigil "#", strict) := "<%x%> #if c { y }"
```

<a id="sec-tile-typing"></a>
### 17.2 Typing, encodings, and the host forms

Every hole has a type known at compile time, from its declaration, else
its expression's inferred type, else the position's contextual
expectation, and the encoder for the hole is chosen by that type: in a
`json` value position a `str` wire is quoted and a number bare; inside a
string literal or an object key any type renders as escaped text; `csv`
fields are quoted when needed; `text` is the display form. A `json` tile
is checked at compile time as JSON with `0` in every hole. A projection's
comprehension must have bounded cardinality; a continuous source projects
only under a sampling order (`halton`, `sobol`, `lhs`, `shuffle`, or
`extrema`) with a count. Under `(strict)` or the compiler's strict mode, implicit adapters
at holes are rejected as they are on wires. The rules in full are
[Polytile](polytile.md) §4 and §5.

`name := polytile(encoding, body, options...)` and
`name := polytile_json(body, options...)` are binding forms the parser
rewrites into `tile` statements, so a host that holds only a string
lowers it to a tile as a program transform; the body is taken raw and
never evaluated. `tile` is a hard keyword; directives and delimiters have
no meaning outside a tile body.

---

<a id="sec-gaxioms"></a>
## 18. Foundations: the type rules and the six G-axioms

The grammar has twelve expression constructors and eight statement
kinds. This section states the type rules (§[18.1](#sec-type-rules))
and the six structural commitments of the grammar, the **G-axioms**
(§[18.3](#sec-axiom-statements)), on which the substrate, compiler,
runtime, and embedding specifications depend. The axioms are **not**
optimizations: without them the contracts of those specifications
would not hold, and each axiom is stated with the contract that fails
in its absence.

<a id="sec-type-rules"></a>
### 18.1 Type rules

The type system is `PortType` (§[15](#sec-types)). Every well-formed
expression has an output type derivable from its structure.

```text
T-IntLit:     n ∈ integer literal          ⊢  n  :  U64
T-FloatLit:   n ∈ float literal            ⊢  n  :  F64
T-StringLit:  s ∈ string literal           ⊢  s  :  Str
T-ArrayLit:   e_1 … e_n literals           ⊢  [e_1, …, e_n]  :  Str
                                              (the rendered element text)
```

Polydat does not distinguish signed from unsigned at the literal tier;
an integer literal is `U64`, and signed values arrive through explicit
conversion nodes. There is no boolean literal rule: `true` and `false`
are ordinary identifiers and comparisons yield a `u64` `0`/`1`
(§[2.6](#sec-bool)).

`T-ArrayLit` differs from the other literal rules. A list literal binds to a
constant string holding its rendered elements, not to a vector: there
is no const-vector node, and list literals exist to be sweep axes and
comprehension-source text, which are consumed as `{name}` interpolation
or as source syntax. A wire that needs the elements as numbers parses
them (`str_to_vec_i32`, `str_to_vec_f32`). A list
literal is a **binding-position** form; it has no meaning as a call
argument, and one written there is a compile error naming the form and
telling the author to bind it first.

```text
T-LocalIdent:  ident declared in this scope by `input`, `extern`,
               `cursor`, or a binding, with declared type T
               ⊢  ident  :  T

T-OuterIdent:  ident not declared in this scope but declared in some
               outer scope with type T (found by auto-extern at
               compile time)
               ⊢  ident  :  T

T-Unknown:     ident declared nowhere reachable
               ⊢  compile error
```

`T-OuterIdent` is the formal form of G1: an identifier the local scope
cannot resolve is searched up the chain, and if found an extern slot is
synthesised in the current scope's program.

```text
T-Call:        func declared (p_1: T_1, …, p_k: T_k) -> (out: U)
               args : (T_1, …, T_k)
               ⊢  func(args)  :  U

T-Call-OverloadResolve:
               func an overload of forms S_1 … S_m; R the forms every
               argument reaches, by its own type or a lossless adapter;
               S_i the earliest form of R (of all forms, when R is
               empty) agreeing with the most argument types by position
               ⊢  func(args)  :  U_i

T-BinOp:       a : U64, b : U64   ⊢  a + b  ≡  u64_add(a, b)  :  U64
               a : F64, b : F64   ⊢  a + b  ≡  f64_add(a, b)  :  F64
               a : U64, b : F64   ⊢  a + b  ≡  f64_add(to_f64(a), b) : F64

T-FieldAccess: source declared with type S, S projecting "field" : T
               ⊢  source.field  :  T
```

The operator rules depend on overload resolution: `add` exists as both
`u64_add` and `f64_add`, and the desugar picks by operand type
(§[6.2](#sec-arithmetic)). A cross-type operator causes an adapter from
the catalog to be inserted. A call to an overloaded name resolves the
same way, against the forms a node module registers for it
(`dsl::registry::Overload`): `vec_dot` over two `vec_f64` wires builds
`vec_dot_f64`, `vec_scale(v, 2)` over a `vec_f64` builds `vec_scale_f64`
and widens the integer, `vec_dot` over a `vec_f64` and a `vec_f32`
builds `vec_dot_f64` and widens the `vec_f32`, since the f32 form would
narrow, and over operands that reach every form equally, such as two
`vec_i32` lists, `vec_dot` builds its first form, `vec_dot_f32`, which
the adapters then reach. A source's field projections come from the
source binding's declared type, so the grammar does not enumerate them
(§[11.2](#sec-cursors)).

The rules cover every expression constructor, and there is no untyped
expression form, so G4 holds.

<a id="sec-soundness"></a>
### 18.2 Consequences of the rules

- **Type soundness.** A compiled expression has one inferred output
  `PortType`, and every runtime value written to that output satisfies
  it. Node metadata fixes the local port types; the assembler connects
  equal types, inserts a catalog adapter, or rejects the graph, and
  typed runtime writes perform the matching boundary check. So long as
  each node honours its declared metadata, a well-typed expression
  evaluates only to a value satisfying its inferred type — or to
  `Value::None`, the absence sentinel
  ([none_semantics.md]none_semantics.md).
- **Cross-statement inference.** Statements compile in dependency
  order. A binding's right-hand side is inferred from literals,
  references, and node signatures, and its port type enters the
  environment the downstream statements are inferred against. An
  explicit declaration constrains that result. Unresolved references,
  incompatible constraints, and dependency cycles are compile errors.
- **Interpolation has a type.** Interpolation is parser desugaring, not
  an AST form. Every interpolated string lowers to `printf(...)` and
  has type `Str`, including a lone placeholder: `"{name}"` is a `Str`,
  while `name` without quotes is a typed passthrough
  (§[9]#sec-interpolation).
- **`ext` stays opaque.** `PortType::Ext` is opaque to the grammar. No
  structural inference or implicit conversion looks inside an
  extension value; a reflected value supplies its own type identity,
  display, JSON projection, and field access. Extension-producing nodes
  still carry ordinary metadata, so lifecycle and purity classification
  operate on the node and its wires rather than on what the extension
  holds.

<a id="sec-axiom-statements"></a>
### 18.3 The six axioms

**G1 — Auto-extern as syntactic discovery.** *Every identifier
reference is classified local or outer-scope by the grammar, without
being syntactically distinguished by which one it is. The resolution
rule (`T-LocalIdent` then `T-OuterIdent`) is total and deterministic,
and an identifier not found locally is searched up the chain and
synthesised as an extern slot in the current scope's program.*

Under G1 the compiler finds a body's synthesis surface (the set of
extern slots synthesised for its outer-scope references) by walking
the body rather than by reading declarations, and `{name}`
interpolation uses the same rule: a host's `{k}` resolves to the
binding a bare `k` would. Without G1, every cross-scope dependency
would be declared by hand, doubling the surface and requiring an
update each time a body changes.

**G2 — Lifecycle declared at the surface.** *The binding modifiers
declare lifecycle. The compiler verifies the declaration against the
wire chain; it does not infer lifecycle from the expression's contents
(§[5](#sec-modifiers)).*

The const-binding contract checks the chain against the author's
declaration (a `const` reads no coordinate), and the hoisting pass, which separates work done once per
scope activation from per-cycle work, partitions on it. Without G2,
lifecycle would be inferred per call site, the analysis would have to
be richer, and the wire-chain check would have nothing declarative to
check.

**G3 — Scope-chain transparency.** *An identifier referencing an
outer-scope binding is written exactly like a local one. There is no
`outer` keyword, no parent qualifier, no ceremony: the author writes
`k` whichever scope binds `k`.*

The scope layers do not appear in the syntax, so an expression can be
embedded as written: a host can pass an expression that reads its
context without adapting the syntax. Without G3, every expression that
referenced another scope would have to name the substrate's layering.

**G4 — Port-typed expressions.** *Every well-formed expression has a
derivable output `PortType`. The rules of §18.1 are total: every
constructor has a rule, the rules compose, and no expression form
lacks an output type.*

Because both ends of every wire are typed, a mismatch is rejected or
repaired with an adapter at construction rather than at runtime, and a
returned value's type follows from the program's structure rather than
being discovered at runtime. Without G4, type checking would
move to runtime and the typed-result guarantee would become a runtime
concern.

**G5 — Two-lifecycle structural classification.** *Every wire is
classifiable Effectively-const (computed once per kernel, at build or
at initialization) or Dynamic (may change per cycle, or at every read
when volatile) by analysing the wire chain alone — the join of its
upstream cone's lifecycles, plus the declared modifiers of G2. A
`const` binding is effectively-const whatever its expression reads,
because it is evaluated at initialization. The classification does not
depend on runtime state or evaluation history.*

The compiler relies on G5 to emit a partitioned program: one buffer
evaluated once at initialization, another per cycle. Without G5,
lifecycle would be discovered during evaluation, the partition could
not be compiled, and the cost-determinism guarantee would lose its
structural basis.

**G6 — One grammar for expressions and programs.** *A single
expression and a full multi-binding program are the same grammar: an
expression is a program of one anonymous output, and a program is a
sequence of named bindings. There is no expression grammar separate
from a program grammar.*

Consequently one compiler compiles a four-character expression and a
two-hundred-line kernel with no expression mode, and an embedded
expression can call every node a program can call. Without G6 a host
would choose between two grammars and the compiler would maintain two
pipelines.

**G6.i — Intrinsics are a closed parse-time set.** *A small fixed set
of forms that look like calls or values are intrinsics: the parser
recognises them and emits desugared graph shapes. The set is closed and
each member rewrites into registered library nodes or constant
emission, so the compiler receives nothing that an author could not
have written by hand.*

The set is the conditional in both spellings
(§[7.1](#sec-if-block)), literal promotion (§[8](#sec-calls)),
interpolation to `printf` (§[9](#sec-interpolation)), and the
`polytile` rewrites into `tile` statements (§[17](#sec-tiles)). Because
the set is closed, an embedded expression using `"x={y}"` compiles to
the graph the author could have written, so the embedding contract has
no special forms, and after parsing the compiler's main loop handles
only registered nodes. Without G6.i, parse-time desugars would have to live in
library code behind some "declare yourself intrinsic" mechanism, or the
grammar would grow constructs the compiler treats opaquely.

**G6.p — Precedence is a grammar-structural commitment.** *Infix
operators follow a stable Rust-like precedence, and parse-tree shape is
determined by it. The table (§[6.1](#sec-precedence)) is part of the
grammar's contract, not an implementation detail.*

An author can write `a + b * c < d & e` and predict the parse; a tool
that walks or rewrites the AST can rely on the shape; the type rules
operate on a determinate tree. Without G6.p, either everything needs
parentheses or the parse is implementation-defined and tooling needs
implementation-specific knowledge.

<a id="sec-axioms-compose"></a>
### 18.4 How they compose

```text
            Grammar
            G1 G2 G3 G4 G5 G6
              │
              ▼
        slot contract       ← G1+G4 → S1+T1
              │
              ▼
        compiler passes     ← G2+G5 → H1+CF1
              │
              ▼
        runtime model       ← G4+G5 → R1+D1
              │
              ▼
        embedding           ← G3+G6 → E1+E4
```

Each layer above the grammar states axioms of its own that depend on
grammar-level commitments. Without G1, the substrate's synthesis
surface would be discovered at runtime. Without G2, the two-lifecycle
classification would be made at runtime. Without G3, embedding would
need syntactic adaptation. The substrate relies on these commitments
instead of repeating them, so the six axioms are requirements, not
conveniences.

| Document | What it depends on the grammar for |
|---|---|
| [Composition Substrate]composition_substrate.md | G1+G4 underwrite S1+T1; G3+G4 underwrite L1+L2; G5 underwrites L2's structural classification. |
| [Graph Compiler]graph_compiler.md | G2+G5 underwrite H1+H2; G1 underwrites CF1; G4 underwrites NF1. |
| [Runtime Model]runtime_model.md | G4 underwrites D1; G5 underwrites R1+D3; G3 underwrites L1's runtime realisation. |
| [Expression Engine]expression_engine.md | G3+G6 underwrite E1+E4; G4 underwrites E2; G6 underwrites the expression-as-kernel correspondence. |
| [Evaluation Model]evaluation_model.md | G2+G5 are the commitments the lifecycle taxonomy rests on. |
| [Scope Model]scope_model.md | G1+G3 are the commitments for auto-extern discovery and parent-gated materialization. |
| [Wire Materialization]wire_materialization.md | G1's auto-extern discovery is what the gradient classification operates over. |

---

<a id="sec-rejections"></a>
## 19. Rejection rules (summary)

The parser/compiler reject, with diagnostics:

- `const volatile` together, and any duplicate modifier
  (§[5.1]#sec-modifier-combos).
- A type annotation on a binding that is not `shared`, and a `shared`
  initializer whose type does not match its annotation
  (§[5.2]#sec-shared-typed).
- `input ()` — the empty input tuple (§[4.1]#sec-input-tuple).
- `f64 as u64`, and any `as` pair the adapter catalog has no adapter for
  (§[10]#sec-casts) — narrowing requires an explicit rounding node.
- Ordered comparison (`< > <= >=`) on strings
  (§[7]#sec-comparison).
- An `if` block without `else`, or with anything but `{` or `if` after
  `else` (§[7.1]#sec-if-block).
- A `for` statement whose `{` is not on the comprehension's line; a bare
  producer name as a `for` expression; a traversal over a producer that
  is not bound in scope; a body declaring an `input` other than `cycle`;
  a literal list mixing numbers and strings (§[16]#sec-for).
- A tile header without `:=`; an unknown encoding; an unterminated hole,
  block, or heredoc; a projection over a source of unbounded
  cardinality (§[17]#sec-tiles).
- A bare expression that is not a complete statement (every top-level
  construct must be a statement).
- Undefined wire / unknown function / forward reference (at validate).

> There is **no** “reserved word used as a name” error beyond the seven
> hard-unusable keywords, and **no** “chained dot rejected” error —
> chained field access is accepted (§[11.1]#sec-field-access). Do not
> assume rejections this spec does not list.

---

<a id="sec-projection-summary"></a>
## 20. Appendix: projection canonicalization, at a glance

What “the syntax the runtime gives back” changes, relative to your input:

| You write | It projects as | Why |
|---|---|---|
| `y := x + 1` | `y := (x + 1)` | BinOps fully parenthesized |
| `name := "{a}-{b}"` | `name := printf("{}-{}", a, b)` | interpolation desugared at parse |
| `m := 0xFF` | `m := 255` | canonical integer rendering |
| `f := 60` (into f64 ctx) / `60.0` | `60.0` | integral floats keep `.0` |
| `input (a: u64, b: u64)` | `input a: u64` / `input b: u64` | tuple input desugared |
| `cursor q = range(0,1) over p` | `cursor q = range(0, 1) over p` | `over` retained |
| `out := if n > 0 { 1 } else { 2 }` | `out := if((n > 0), 1, 2)` | block `if` desugared at parse |
| `for k in 1..4 {` … | `for k in 1..4 {` … | the captured text is printed as written; the body indents four spaces |
| `tile t := "n=${ cycle }"` | `tile t := "n=${cycle}"` | the body is rendered from the template, so a hole is canonical like any other expression |

Everything in this table is exercised by the suite, which extracts
every <code>```polydat</code> block above, asserts idempotent
round-trip, compiles the <code>compile</code>-tagged ones, and proves
the **[↔ programmatic]** examples project identically to their
hand-built ASTs in
[`polydat_grammar_programmatic.md`](polydat_grammar_programmatic.md).

---

<a id="sec-productions"></a>
## 21. Appendix: the grammar in productions

The sections above state each form with a verified example. This
appendix lays the same grammar out as productions, for cross-reference
and for anyone writing a tool against it. The notation is EBNF-ish;
`ident` is `[A-Za-z_][A-Za-z0-9_]*` and `type` is any keyword of
§[15](#sec-types).

```ebnf
polydat_file   ::= statement*

statement      ::= input_decl
                |  binding
                |  module_def
                |  extern_port
                |  cursor_decl
                |  pragma
                |  for_stmt                   (* §16 *)
                |  tile_def                   (* §17 *)

input_decl     ::= "input" ident (":" type)?
                |  "input" "(" (ident (":" type)?)+ ")"

extern_port    ::= "extern" ident ":" type ("=" expr)?

binding        ::= modifier* ident ":=" expr
                |  modifier* "(" ident ("," ident)* ")" ":=" expr
modifier       ::= "const" | "shared" | "volatile"

module_def     ::= ident "(" typed_param_list ")"
                   "->" "(" typed_param_list ")"
                   ":=" "{" statement* "}"
typed_param    ::= ident ":" type

pragma         ::= "pragma" ident
```

Statement order is not constrained syntactically; the compiler's
dependency analysis orders the resulting graph. An `input` declares a
coordinate slot advanced by the leading `set_inputs` prefix, an
`extern` a typed non-coordinate slot; the tuple binding form is
destructuring sugar over a tuple-producing expression
(§[3.1](#sec-destructuring)).

```ebnf
expr           ::= ident
                |  int_literal
                |  float_literal
                |  string_literal
                |  array_literal
                |  call_expr
                |  field_access
                |  cast_expr
                |  for_expr                   (* §16 *)
                |  bin_op_expr                (* sugar *)
                |  unary_expr                 (* sugar *)

call_expr      ::= ident "(" arg_list? ")"
arg_list       ::= arg ("," arg)*
arg            ::= expr                       (* positional *)
                |  ident ":" expr             (* named *)

cast_expr      ::= expr "as" type             (* postfix; binds to the atom *)
field_access   ::= ident "." ident

bin_op_expr    ::= expr bin_op expr
bin_op         ::= "+" | "-" | "*" | "/" | "%" | "**"
                |  "&" | "|" | "^" | "<<" | ">>"
                |  "==" | "!=" | "<" | ">" | "<=" | ">="
                |  "&&" | "||"

unary_expr     ::= "-" expr                   (* arithmetic negate *)
                |  "!" expr                   (* bitwise NOT *)

string_literal ::= ("\"" | "'") ( char | "{" expr "}" | "{{" | "}}" )* (matching quote)
array_literal  ::= "[" (expr ("," expr)*)? "]"
```

Twelve expression constructors, matching the AST: nine that survive
parse as themselves (`Ident`, `IntLit`, `FloatLit`, `StringLit`,
`ArrayLit`, `Call`, `FieldAccess`, `Cast`, `For`) and three sugar forms
(`BinOp`, `UnaryNeg`, `UnaryBitNot`) that desugar to calls. The block
form of `if` is not a constructor: the parser rewrites it to the
`if(…)` call before anything else sees it
(§[18.3](#sec-axiom-statements), G6.i).

Three things this appendix deliberately does not cover. Tokenisation,
whitespace, and escape rules are the lexer's, sketched in
§[1](#sec-lexical) and definitive only in the code. What a named node
computes is the [library catalog](library_catalog.md)'s; the grammar
names the call form and stops. Parse-error recovery is the parser's
strategy, not a grammar commitment.