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
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
|
//! The simplest way to parse ZON at runtime is to use `fromSlice`. If you need to parse ZON at
//! compile time, you may use `@import`.
//!
//! Parsing from individual Zoir nodes is also available:
//! * `fromZoir`
//! * `fromZoirNode`
//!
//! For lower level control, it is possible to operate on `std.zig.Zoir` directly.
const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const Ast = std.zig.Ast;
const Zoir = std.zig.Zoir;
const ZonGen = std.zig.ZonGen;
const TokenIndex = std.zig.Ast.TokenIndex;
const Base = std.zig.number_literal.Base;
const StrLitErr = std.zig.string_literal.Error;
const NumberLiteralError = std.zig.number_literal.Error;
const assert = std.debug.assert;
const ArrayListUnmanaged = std.ArrayListUnmanaged;
/// Rename when adding or removing support for a type.
const valid_types = {};
/// Configuration for the runtime parser.
pub const Options = struct {
/// If true, unknown fields do not error.
ignore_unknown_fields: bool = false,
/// If true, the parser cleans up partially parsed values on error. This requires some extra
/// bookkeeping, so you may want to turn it off if you don't need this feature (e.g. because
/// you're using arena allocation.)
free_on_error: bool = true,
};
pub const Error = union(enum) {
zoir: Zoir.CompileError,
type_check: Error.TypeCheckFailure,
pub const Note = union(enum) {
zoir: Zoir.CompileError.Note,
type_check: TypeCheckFailure.Note,
pub const Iterator = struct {
index: usize = 0,
err: Error,
diag: *const Diagnostics,
pub fn next(self: *@This()) ?Note {
switch (self.err) {
.zoir => |err| {
if (self.index >= err.note_count) return null;
const note = err.getNotes(self.diag.zoir)[self.index];
self.index += 1;
return .{ .zoir = note };
},
.type_check => |err| {
if (self.index >= err.getNoteCount()) return null;
const note = err.getNote(self.index);
self.index += 1;
return .{ .type_check = note };
},
}
}
};
fn formatMessage(self: []const u8, w: *std.io.Writer) std.io.Writer.Error!void {
// Just writes the string for now, but we're keeping this behind a formatter so we have
// the option to extend it in the future to print more advanced messages (like `Error`
// does) without breaking the API.
try w.writeAll(self);
}
pub fn fmtMessage(self: Note, diag: *const Diagnostics) std.fmt.Formatter([]const u8, Note.formatMessage) {
return .{ .data = switch (self) {
.zoir => |note| note.msg.get(diag.zoir),
.type_check => |note| note.msg,
} };
}
pub fn getLocation(self: Note, diag: *const Diagnostics) Ast.Location {
switch (self) {
.zoir => |note| return zoirErrorLocation(diag.ast, note.token, note.node_or_offset),
.type_check => |note| return diag.ast.tokenLocation(note.offset, note.token),
}
}
};
pub const Iterator = struct {
index: usize = 0,
diag: *const Diagnostics,
pub fn next(self: *@This()) ?Error {
if (self.index < self.diag.zoir.compile_errors.len) {
const result: Error = .{ .zoir = self.diag.zoir.compile_errors[self.index] };
self.index += 1;
return result;
}
if (self.diag.type_check) |err| {
if (self.index == self.diag.zoir.compile_errors.len) {
const result: Error = .{ .type_check = err };
self.index += 1;
return result;
}
}
return null;
}
};
const TypeCheckFailure = struct {
const Note = struct {
token: Ast.TokenIndex,
offset: u32,
msg: []const u8,
owned: bool,
fn deinit(self: @This(), gpa: Allocator) void {
if (self.owned) gpa.free(self.msg);
}
};
message: []const u8,
owned: bool,
token: Ast.TokenIndex,
offset: u32,
note: ?@This().Note,
fn deinit(self: @This(), gpa: Allocator) void {
if (self.note) |note| note.deinit(gpa);
if (self.owned) gpa.free(self.message);
}
fn getNoteCount(self: @This()) usize {
return @intFromBool(self.note != null);
}
fn getNote(self: @This(), index: usize) @This().Note {
assert(index == 0);
return self.note.?;
}
};
const FormatMessage = struct {
err: Error,
diag: *const Diagnostics,
};
fn formatMessage(self: FormatMessage, w: *std.io.Writer) std.io.Writer.Error!void {
switch (self.err) {
.zoir => |err| try w.writeAll(err.msg.get(self.diag.zoir)),
.type_check => |tc| try w.writeAll(tc.message),
}
}
pub fn fmtMessage(self: @This(), diag: *const Diagnostics) std.fmt.Formatter(FormatMessage, formatMessage) {
return .{ .data = .{
.err = self,
.diag = diag,
} };
}
pub fn getLocation(self: @This(), diag: *const Diagnostics) Ast.Location {
return switch (self) {
.zoir => |err| return zoirErrorLocation(
diag.ast,
err.token,
err.node_or_offset,
),
.type_check => |err| return diag.ast.tokenLocation(err.offset, err.token),
};
}
pub fn iterateNotes(self: @This(), diag: *const Diagnostics) Note.Iterator {
return .{ .err = self, .diag = diag };
}
fn zoirErrorLocation(ast: Ast, maybe_token: Ast.OptionalTokenIndex, node_or_offset: u32) Ast.Location {
if (maybe_token.unwrap()) |token| {
var location = ast.tokenLocation(0, token);
location.column += node_or_offset;
return location;
} else {
const ast_node: Ast.Node.Index = @enumFromInt(node_or_offset);
const token = ast.nodeMainToken(ast_node);
return ast.tokenLocation(0, token);
}
}
};
/// Information about the success or failure of a parse.
pub const Diagnostics = struct {
ast: Ast = .{
.source = "",
.tokens = .empty,
.nodes = .empty,
.extra_data = &.{},
.mode = .zon,
.errors = &.{},
},
zoir: Zoir = .{
.nodes = .empty,
.extra = &.{},
.limbs = &.{},
.string_bytes = &.{},
.compile_errors = &.{},
.error_notes = &.{},
},
type_check: ?Error.TypeCheckFailure = null,
fn assertEmpty(self: Diagnostics) void {
assert(self.ast.tokens.len == 0);
assert(self.zoir.nodes.len == 0);
assert(self.type_check == null);
}
pub fn deinit(self: *Diagnostics, gpa: Allocator) void {
self.ast.deinit(gpa);
self.zoir.deinit(gpa);
if (self.type_check) |tc| tc.deinit(gpa);
self.* = undefined;
}
pub fn iterateErrors(self: *const Diagnostics) Error.Iterator {
return .{ .diag = self };
}
pub fn format(self: *const @This(), w: *std.io.Writer) std.io.Writer.Error!void {
var errors = self.iterateErrors();
while (errors.next()) |err| {
const loc = err.getLocation(self);
const msg = err.fmtMessage(self);
try w.print("{d}:{d}: error: {f}\n", .{ loc.line + 1, loc.column + 1, msg });
var notes = err.iterateNotes(self);
while (notes.next()) |note| {
const note_loc = note.getLocation(self);
const note_msg = note.fmtMessage(self);
try w.print("{d}:{d}: note: {f}\n", .{
note_loc.line + 1,
note_loc.column + 1,
note_msg,
});
}
}
}
};
/// Parses the given slice as ZON.
///
/// Returns `error.OutOfMemory` on allocation failure, or `error.ParseZon` error if the ZON is
/// invalid or can not be deserialized into type `T`.
///
/// When the parser returns `error.ParseZon`, it will also store a human readable explanation in
/// `diag` if non null. If diag is not null, it must be initialized to `.{}`.
pub fn fromSlice(
/// The type to deserialize into. May not be or contain any of the following types:
/// * Any comptime-only type, except in a comptime field
/// * `type`
/// * `void`, except as a union payload
/// * `noreturn`
/// * An error set/error union
/// * A many-pointer or C-pointer
/// * An opaque type, including `anyopaque`
/// * An async frame type, including `anyframe` and `anyframe->T`
/// * A function
///
/// All other types are valid. Unsupported types will fail at compile time.
T: type,
gpa: Allocator,
source: [:0]const u8,
diag: ?*Diagnostics,
options: Options,
) error{ OutOfMemory, ParseZon }!T {
if (diag) |s| s.assertEmpty();
var ast = try std.zig.Ast.parse(gpa, source, .zon);
defer if (diag == null) ast.deinit(gpa);
if (diag) |s| s.ast = ast;
// If there's no diagnostics, Zoir exists for the lifetime of this function. If there is a
// diagnostics, ownership is transferred to diagnostics.
var zoir = try ZonGen.generate(gpa, ast, .{ .parse_str_lits = false });
defer if (diag == null) zoir.deinit(gpa);
if (diag) |s| s.* = .{};
return fromZoir(T, gpa, ast, zoir, diag, options);
}
/// Like `fromSlice`, but operates on `Zoir` instead of ZON source.
pub fn fromZoir(
T: type,
gpa: Allocator,
ast: Ast,
zoir: Zoir,
diag: ?*Diagnostics,
options: Options,
) error{ OutOfMemory, ParseZon }!T {
return fromZoirNode(T, gpa, ast, zoir, .root, diag, options);
}
/// Like `fromZoir`, but the parse starts on `node` instead of root.
pub fn fromZoirNode(
T: type,
gpa: Allocator,
ast: Ast,
zoir: Zoir,
node: Zoir.Node.Index,
diag: ?*Diagnostics,
options: Options,
) error{ OutOfMemory, ParseZon }!T {
comptime assert(canParseType(T));
if (diag) |s| {
s.assertEmpty();
s.ast = ast;
s.zoir = zoir;
}
if (zoir.hasCompileErrors()) {
return error.ParseZon;
}
var parser: Parser = .{
.gpa = gpa,
.ast = ast,
.zoir = zoir,
.options = options,
.diag = diag,
};
return parser.parseExpr(T, node);
}
/// Frees ZON values.
///
/// Provided for convenience, you may also free these values on your own using the same allocator
/// passed into the parser.
///
/// Asserts at comptime that sufficient information is available via the type system to free this
/// value. Untagged unions, for example, will fail this assert.
pub fn free(gpa: Allocator, value: anytype) void {
const Value = @TypeOf(value);
_ = valid_types;
switch (@typeInfo(Value)) {
.bool, .int, .float, .@"enum" => {},
.pointer => |pointer| {
switch (pointer.size) {
.one => {
free(gpa, value.*);
gpa.destroy(value);
},
.slice => {
for (value) |item| {
free(gpa, item);
}
gpa.free(value);
},
.many, .c => comptime unreachable,
}
},
.array => for (value) |item| {
free(gpa, item);
},
.@"struct" => |@"struct"| inline for (@"struct".fields) |field| {
free(gpa, @field(value, field.name));
},
.@"union" => |@"union"| if (@"union".tag_type == null) {
if (comptime requiresAllocator(Value)) unreachable;
} else switch (value) {
inline else => |_, tag| {
free(gpa, @field(value, @tagName(tag)));
},
},
.optional => if (value) |some| {
free(gpa, some);
},
.vector => |vector| for (0..vector.len) |i| free(gpa, value[i]),
.void => {},
else => comptime unreachable,
}
}
fn requiresAllocator(T: type) bool {
_ = valid_types;
return switch (@typeInfo(T)) {
.pointer => true,
.array => |array| return array.len > 0 and requiresAllocator(array.child),
.@"struct" => |@"struct"| inline for (@"struct".fields) |field| {
if (requiresAllocator(field.type)) {
break true;
}
} else false,
.@"union" => |@"union"| inline for (@"union".fields) |field| {
if (requiresAllocator(field.type)) {
break true;
}
} else false,
.optional => |optional| requiresAllocator(optional.child),
.vector => |vector| return vector.len > 0 and requiresAllocator(vector.child),
else => false,
};
}
const Parser = struct {
gpa: Allocator,
ast: Ast,
zoir: Zoir,
diag: ?*Diagnostics,
options: Options,
fn parseExpr(self: *@This(), T: type, node: Zoir.Node.Index) error{ ParseZon, OutOfMemory }!T {
return self.parseExprInner(T, node) catch |err| switch (err) {
error.WrongType => return self.failExpectedType(T, node),
else => |e| return e,
};
}
fn parseExprInner(
self: *@This(),
T: type,
node: Zoir.Node.Index,
) error{ ParseZon, OutOfMemory, WrongType }!T {
if (T == Zoir.Node.Index) {
return node;
}
switch (@typeInfo(T)) {
.optional => |optional| if (node.get(self.zoir) == .null) {
return null;
} else {
return try self.parseExprInner(optional.child, node);
},
.bool => return self.parseBool(node),
.int => return self.parseInt(T, node),
.float => return self.parseFloat(T, node),
.@"enum" => return self.parseEnumLiteral(T, node),
.pointer => |pointer| switch (pointer.size) {
.one => {
const result = try self.gpa.create(pointer.child);
errdefer self.gpa.destroy(result);
result.* = try self.parseExprInner(pointer.child, node);
return result;
},
.slice => return self.parseSlicePointer(T, node),
else => comptime unreachable,
},
.array => return self.parseArray(T, node),
.@"struct" => |@"struct"| if (@"struct".is_tuple)
return self.parseTuple(T, node)
else
return self.parseStruct(T, node),
.@"union" => return self.parseUnion(T, node),
.vector => return self.parseVector(T, node),
else => comptime unreachable,
}
}
/// Prints a message of the form `expected T` where T is first converted to a ZON type. For
/// example, `**?**u8` becomes `?u8`, and types that involve user specified type names are just
/// referred to by the type of container.
fn failExpectedType(
self: @This(),
T: type,
node: Zoir.Node.Index,
) error{ ParseZon, OutOfMemory } {
@branchHint(.cold);
return self.failExpectedTypeInner(T, false, node);
}
fn failExpectedTypeInner(
self: @This(),
T: type,
opt: bool,
node: Zoir.Node.Index,
) error{ ParseZon, OutOfMemory } {
_ = valid_types;
switch (@typeInfo(T)) {
.@"struct" => |@"struct"| if (@"struct".is_tuple) {
if (opt) {
return self.failNode(node, "expected optional tuple");
} else {
return self.failNode(node, "expected tuple");
}
} else {
if (opt) {
return self.failNode(node, "expected optional struct");
} else {
return self.failNode(node, "expected struct");
}
},
.@"union" => if (opt) {
return self.failNode(node, "expected optional union");
} else {
return self.failNode(node, "expected union");
},
.array => if (opt) {
return self.failNode(node, "expected optional array");
} else {
return self.failNode(node, "expected array");
},
.pointer => |pointer| switch (pointer.size) {
.one => return self.failExpectedTypeInner(pointer.child, opt, node),
.slice => {
if (pointer.child == u8 and
pointer.is_const and
(pointer.sentinel() == null or pointer.sentinel() == 0) and
pointer.alignment == 1)
{
if (opt) {
return self.failNode(node, "expected optional string");
} else {
return self.failNode(node, "expected string");
}
} else {
if (opt) {
return self.failNode(node, "expected optional array");
} else {
return self.failNode(node, "expected array");
}
}
},
else => comptime unreachable,
},
.vector, .bool, .int, .float => if (opt) {
return self.failNodeFmt(node, "expected type '{s}'", .{@typeName(?T)});
} else {
return self.failNodeFmt(node, "expected type '{s}'", .{@typeName(T)});
},
.@"enum" => if (opt) {
return self.failNode(node, "expected optional enum literal");
} else {
return self.failNode(node, "expected enum literal");
},
.optional => |optional| {
return self.failExpectedTypeInner(optional.child, true, node);
},
else => comptime unreachable,
}
}
fn parseBool(self: @This(), node: Zoir.Node.Index) !bool {
switch (node.get(self.zoir)) {
.true => return true,
.false => return false,
else => return error.WrongType,
}
}
fn parseInt(self: @This(), T: type, node: Zoir.Node.Index) !T {
switch (node.get(self.zoir)) {
.int_literal => |int| switch (int) {
.small => |val| return std.math.cast(T, val) orelse
self.failCannotRepresent(T, node),
.big => |val| return val.toInt(T) catch
self.failCannotRepresent(T, node),
},
.float_literal => |val| return intFromFloatExact(T, val) orelse
self.failCannotRepresent(T, node),
.char_literal => |val| return std.math.cast(T, val) orelse
self.failCannotRepresent(T, node),
else => return error.WrongType,
}
}
fn parseFloat(self: @This(), T: type, node: Zoir.Node.Index) !T {
switch (node.get(self.zoir)) {
.int_literal => |int| switch (int) {
.small => |val| return @floatFromInt(val),
.big => |val| return val.toFloat(T, .nearest_even)[0],
},
.float_literal => |val| return @floatCast(val),
.pos_inf => return std.math.inf(T),
.neg_inf => return -std.math.inf(T),
.nan => return std.math.nan(T),
.char_literal => |val| return @floatFromInt(val),
else => return error.WrongType,
}
}
fn parseEnumLiteral(self: @This(), T: type, node: Zoir.Node.Index) !T {
switch (node.get(self.zoir)) {
.enum_literal => |field_name| {
// Create a comptime string map for the enum fields
const enum_fields = @typeInfo(T).@"enum".fields;
comptime var kvs_list: [enum_fields.len]struct { []const u8, T } = undefined;
inline for (enum_fields, 0..) |field, i| {
kvs_list[i] = .{ field.name, @enumFromInt(field.value) };
}
const enum_tags = std.StaticStringMap(T).initComptime(kvs_list);
// Get the tag if it exists
const field_name_str = field_name.get(self.zoir);
return enum_tags.get(field_name_str) orelse
self.failUnexpected(T, "enum literal", node, null, field_name_str);
},
else => return error.WrongType,
}
}
fn parseSlicePointer(self: *@This(), T: type, node: Zoir.Node.Index) !T {
switch (node.get(self.zoir)) {
.string_literal => return self.parseString(T, node),
.array_literal => |nodes| return self.parseSlice(T, nodes),
.empty_literal => return self.parseSlice(T, .{ .start = node, .len = 0 }),
else => return error.WrongType,
}
}
fn parseString(self: *@This(), T: type, node: Zoir.Node.Index) !T {
const ast_node = node.getAstNode(self.zoir);
const pointer = @typeInfo(T).pointer;
var size_hint = ZonGen.strLitSizeHint(self.ast, ast_node);
if (pointer.sentinel() != null) size_hint += 1;
var buf: std.ArrayListUnmanaged(u8) = try .initCapacity(self.gpa, size_hint);
defer buf.deinit(self.gpa);
switch (try ZonGen.parseStrLit(self.ast, ast_node, buf.writer(self.gpa))) {
.success => {},
.failure => |err| {
const token = self.ast.nodeMainToken(ast_node);
const raw_string = self.ast.tokenSlice(token);
return self.failTokenFmt(token, @intCast(err.offset()), "{f}", .{err.fmt(raw_string)});
},
}
if (pointer.child != u8 or
pointer.size != .slice or
!pointer.is_const or
(pointer.sentinel() != null and pointer.sentinel() != 0) or
pointer.alignment != 1)
{
return error.WrongType;
}
if (pointer.sentinel() != null) {
return buf.toOwnedSliceSentinel(self.gpa, 0);
} else {
return buf.toOwnedSlice(self.gpa);
}
}
fn parseSlice(self: *@This(), T: type, nodes: Zoir.Node.Index.Range) !T {
const pointer = @typeInfo(T).pointer;
// Make sure we're working with a slice
switch (pointer.size) {
.slice => {},
.one, .many, .c => comptime unreachable,
}
// Allocate the slice
const slice = try self.gpa.allocWithOptions(
pointer.child,
nodes.len,
.fromByteUnits(pointer.alignment),
pointer.sentinel(),
);
errdefer self.gpa.free(slice);
// Parse the elements and return the slice
for (slice, 0..) |*elem, i| {
errdefer if (self.options.free_on_error) {
for (slice[0..i]) |item| {
free(self.gpa, item);
}
};
elem.* = try self.parseExpr(pointer.child, nodes.at(@intCast(i)));
}
return slice;
}
fn parseArray(self: *@This(), T: type, node: Zoir.Node.Index) !T {
const nodes: Zoir.Node.Index.Range = switch (node.get(self.zoir)) {
.array_literal => |nodes| nodes,
.empty_literal => .{ .start = node, .len = 0 },
else => return error.WrongType,
};
const array_info = @typeInfo(T).array;
// Check if the size matches
if (nodes.len < array_info.len) {
return self.failNodeFmt(
node,
"expected {} array elements; found {}",
.{ array_info.len, nodes.len },
);
} else if (nodes.len > array_info.len) {
return self.failNodeFmt(
nodes.at(array_info.len),
"index {} outside of array of length {}",
.{ array_info.len, array_info.len },
);
}
// Parse the elements and return the array
var result: T = undefined;
for (&result, 0..) |*elem, i| {
// If we fail to parse this field, free all fields before it
errdefer if (self.options.free_on_error) {
for (result[0..i]) |item| {
free(self.gpa, item);
}
};
elem.* = try self.parseExpr(array_info.child, nodes.at(@intCast(i)));
}
return result;
}
fn parseStruct(self: *@This(), T: type, node: Zoir.Node.Index) !T {
const repr = node.get(self.zoir);
const fields: @FieldType(Zoir.Node, "struct_literal") = switch (repr) {
.struct_literal => |nodes| nodes,
.empty_literal => .{ .names = &.{}, .vals = .{ .start = node, .len = 0 } },
else => return error.WrongType,
};
const field_infos = @typeInfo(T).@"struct".fields;
// Build a map from field name to index.
// The special value `comptime_field` indicates that this is actually a comptime field.
const comptime_field = std.math.maxInt(usize);
const field_indices: std.StaticStringMap(usize) = comptime b: {
var kvs_list: [field_infos.len]struct { []const u8, usize } = undefined;
for (&kvs_list, field_infos, 0..) |*kv, field, i| {
kv.* = .{ field.name, if (field.is_comptime) comptime_field else i };
}
break :b .initComptime(kvs_list);
};
// Parse the struct
var result: T = undefined;
var field_found: [field_infos.len]bool = @splat(false);
// If we fail partway through, free all already initialized fields
var initialized: usize = 0;
errdefer if (self.options.free_on_error and field_infos.len > 0) {
for (fields.names[0..initialized]) |name_runtime| {
switch (field_indices.get(name_runtime.get(self.zoir)) orelse continue) {
inline 0...(field_infos.len - 1) => |name_index| {
const name = field_infos[name_index].name;
free(self.gpa, @field(result, name));
},
else => unreachable, // Can't be out of bounds
}
}
};
// Fill in the fields we found
for (0..fields.names.len) |i| {
const name = fields.names[i].get(self.zoir);
const field_index = field_indices.get(name) orelse {
if (self.options.ignore_unknown_fields) continue;
return self.failUnexpected(T, "field", node, i, name);
};
if (field_index == comptime_field) {
return self.failComptimeField(node, i);
}
// Mark the field as found. Assert that the found array is not zero length to satisfy
// the type checker (it can't be since we made it into an iteration of this loop.)
if (field_found.len == 0) unreachable;
field_found[field_index] = true;
switch (field_index) {
inline 0...(field_infos.len - 1) => |j| {
if (field_infos[j].is_comptime) unreachable;
@field(result, field_infos[j].name) = try self.parseExpr(
field_infos[j].type,
fields.vals.at(@intCast(i)),
);
},
else => unreachable, // Can't be out of bounds
}
initialized += 1;
}
// Fill in any missing default fields
inline for (field_found, 0..) |found, i| {
if (!found) {
const field_info = field_infos[i];
if (field_info.default_value_ptr) |default| {
const typed: *const field_info.type = @ptrCast(@alignCast(default));
@field(result, field_info.name) = typed.*;
} else {
return self.failNodeFmt(
node,
"missing required field {s}",
.{field_infos[i].name},
);
}
}
}
return result;
}
fn parseTuple(self: *@This(), T: type, node: Zoir.Node.Index) !T {
const nodes: Zoir.Node.Index.Range = switch (node.get(self.zoir)) {
.array_literal => |nodes| nodes,
.empty_literal => .{ .start = node, .len = 0 },
else => return error.WrongType,
};
var result: T = undefined;
const field_infos = @typeInfo(T).@"struct".fields;
if (nodes.len > field_infos.len) {
return self.failNodeFmt(
nodes.at(field_infos.len),
"index {} outside of tuple length {}",
.{ field_infos.len, field_infos.len },
);
}
inline for (0..field_infos.len) |i| {
// Check if we're out of bounds
if (i >= nodes.len) {
if (field_infos[i].default_value_ptr) |default| {
const typed: *const field_infos[i].type = @ptrCast(@alignCast(default));
@field(result, field_infos[i].name) = typed.*;
} else {
return self.failNodeFmt(node, "missing tuple field with index {}", .{i});
}
} else {
// If we fail to parse this field, free all fields before it
errdefer if (self.options.free_on_error) {
inline for (0..i) |j| {
if (j >= i) break;
free(self.gpa, result[j]);
}
};
if (field_infos[i].is_comptime) {
return self.failComptimeField(node, i);
} else {
result[i] = try self.parseExpr(field_infos[i].type, nodes.at(i));
}
}
}
return result;
}
fn parseUnion(self: *@This(), T: type, node: Zoir.Node.Index) !T {
const @"union" = @typeInfo(T).@"union";
const field_infos = @"union".fields;
if (field_infos.len == 0) comptime unreachable;
// Gather info on the fields
const field_indices = b: {
comptime var kvs_list: [field_infos.len]struct { []const u8, usize } = undefined;
inline for (field_infos, 0..) |field, i| {
kvs_list[i] = .{ field.name, i };
}
break :b std.StaticStringMap(usize).initComptime(kvs_list);
};
// Parse the union
switch (node.get(self.zoir)) {
.enum_literal => |field_name| {
// The union must be tagged for an enum literal to coerce to it
if (@"union".tag_type == null) {
return error.WrongType;
}
// Get the index of the named field. We don't use `parseEnum` here as
// the order of the enum and the order of the union might not match!
const field_index = b: {
const field_name_str = field_name.get(self.zoir);
break :b field_indices.get(field_name_str) orelse
return self.failUnexpected(T, "field", node, null, field_name_str);
};
// Initialize the union from the given field.
switch (field_index) {
inline 0...field_infos.len - 1 => |i| {
// Fail if the field is not void
if (field_infos[i].type != void)
return self.failNode(node, "expected union");
// Instantiate the union
return @unionInit(T, field_infos[i].name, {});
},
else => unreachable, // Can't be out of bounds
}
},
.struct_literal => |struct_fields| {
if (struct_fields.names.len != 1) {
return error.WrongType;
}
// Fill in the field we found
const field_name = struct_fields.names[0];
const field_name_str = field_name.get(self.zoir);
const field_val = struct_fields.vals.at(0);
const field_index = field_indices.get(field_name_str) orelse
return self.failUnexpected(T, "field", node, 0, field_name_str);
switch (field_index) {
inline 0...field_infos.len - 1 => |i| {
if (field_infos[i].type == void) {
return self.failNode(field_val, "expected type 'void'");
} else {
const value = try self.parseExpr(field_infos[i].type, field_val);
return @unionInit(T, field_infos[i].name, value);
}
},
else => unreachable, // Can't be out of bounds
}
},
else => return error.WrongType,
}
}
fn parseVector(
self: *@This(),
T: type,
node: Zoir.Node.Index,
) !T {
const vector_info = @typeInfo(T).vector;
const nodes: Zoir.Node.Index.Range = switch (node.get(self.zoir)) {
.array_literal => |nodes| nodes,
.empty_literal => .{ .start = node, .len = 0 },
else => return error.WrongType,
};
var result: T = undefined;
if (nodes.len != vector_info.len) {
return self.failNodeFmt(
node,
"expected {} vector elements; found {}",
.{ vector_info.len, nodes.len },
);
}
for (0..vector_info.len) |i| {
errdefer for (0..i) |j| free(self.gpa, result[j]);
result[i] = try self.parseExpr(vector_info.child, nodes.at(@intCast(i)));
}
return result;
}
fn failTokenFmt(
self: @This(),
token: Ast.TokenIndex,
offset: u32,
comptime fmt: []const u8,
args: anytype,
) error{ OutOfMemory, ParseZon } {
@branchHint(.cold);
return self.failTokenFmtNote(token, offset, fmt, args, null);
}
fn failTokenFmtNote(
self: @This(),
token: Ast.TokenIndex,
offset: u32,
comptime fmt: []const u8,
args: anytype,
note: ?Error.TypeCheckFailure.Note,
) error{ OutOfMemory, ParseZon } {
@branchHint(.cold);
comptime assert(args.len > 0);
if (self.diag) |s| s.type_check = .{
.token = token,
.offset = offset,
.message = std.fmt.allocPrint(self.gpa, fmt, args) catch |err| {
if (note) |n| n.deinit(self.gpa);
return err;
},
.owned = true,
.note = note,
};
return error.ParseZon;
}
fn failNodeFmt(
self: @This(),
node: Zoir.Node.Index,
comptime fmt: []const u8,
args: anytype,
) error{ OutOfMemory, ParseZon } {
@branchHint(.cold);
const token = self.ast.nodeMainToken(node.getAstNode(self.zoir));
return self.failTokenFmt(token, 0, fmt, args);
}
fn failToken(
self: @This(),
failure: Error.TypeCheckFailure,
) error{ParseZon} {
@branchHint(.cold);
if (self.diag) |s| s.type_check = failure;
return error.ParseZon;
}
fn failNode(
self: @This(),
node: Zoir.Node.Index,
message: []const u8,
) error{ParseZon} {
@branchHint(.cold);
const token = self.ast.nodeMainToken(node.getAstNode(self.zoir));
return self.failToken(.{
.token = token,
.offset = 0,
.message = message,
.owned = false,
.note = null,
});
}
fn failCannotRepresent(
self: @This(),
T: type,
node: Zoir.Node.Index,
) error{ OutOfMemory, ParseZon } {
@branchHint(.cold);
return self.failNodeFmt(node, "type '{s}' cannot represent value", .{@typeName(T)});
}
fn failUnexpected(
self: @This(),
T: type,
item_kind: []const u8,
node: Zoir.Node.Index,
field: ?usize,
name: []const u8,
) error{ OutOfMemory, ParseZon } {
@branchHint(.cold);
const token = if (field) |f| b: {
var buf: [2]Ast.Node.Index = undefined;
const struct_init = self.ast.fullStructInit(&buf, node.getAstNode(self.zoir)).?;
const field_node = struct_init.ast.fields[f];
break :b self.ast.firstToken(field_node) - 2;
} else self.ast.nodeMainToken(node.getAstNode(self.zoir));
switch (@typeInfo(T)) {
inline .@"struct", .@"union", .@"enum" => |info| {
const note: Error.TypeCheckFailure.Note = if (info.fields.len == 0) b: {
break :b .{
.token = token,
.offset = 0,
.msg = "none expected",
.owned = false,
};
} else b: {
const msg = "supported: ";
var buf: std.ArrayListUnmanaged(u8) = try .initCapacity(self.gpa, 64);
defer buf.deinit(self.gpa);
const writer = buf.writer(self.gpa);
try writer.writeAll(msg);
inline for (info.fields, 0..) |field_info, i| {
if (i != 0) try writer.writeAll(", ");
try writer.print("'{f}'", .{std.zig.fmtIdFlags(field_info.name, .{
.allow_primitive = true,
.allow_underscore = true,
})});
}
break :b .{
.token = token,
.offset = 0,
.msg = try buf.toOwnedSlice(self.gpa),
.owned = true,
};
};
return self.failTokenFmtNote(
token,
0,
"unexpected {s} '{s}'",
.{ item_kind, name },
note,
);
},
else => comptime unreachable,
}
}
// Technically we could do this if we were willing to do a deep equal to verify
// the value matched, but doing so doesn't seem to support any real use cases
// so isn't worth the complexity at the moment.
fn failComptimeField(
self: @This(),
node: Zoir.Node.Index,
field: usize,
) error{ OutOfMemory, ParseZon } {
@branchHint(.cold);
const ast_node = node.getAstNode(self.zoir);
var buf: [2]Ast.Node.Index = undefined;
const token = if (self.ast.fullStructInit(&buf, ast_node)) |struct_init| b: {
const field_node = struct_init.ast.fields[field];
break :b self.ast.firstToken(field_node);
} else b: {
const array_init = self.ast.fullArrayInit(&buf, ast_node).?;
const value_node = array_init.ast.elements[field];
break :b self.ast.firstToken(value_node);
};
return self.failToken(.{
.token = token,
.offset = 0,
.message = "cannot initialize comptime field",
.owned = false,
.note = null,
});
}
};
fn intFromFloatExact(T: type, value: anytype) ?T {
if (value > std.math.maxInt(T) or value < std.math.minInt(T)) {
return null;
}
if (std.math.isNan(value) or std.math.trunc(value) != value) {
return null;
}
return @intFromFloat(value);
}
fn canParseType(T: type) bool {
comptime return canParseTypeInner(T, &.{}, false);
}
fn canParseTypeInner(
T: type,
/// Visited structs and unions, to avoid infinite recursion.
/// Tracking more types is unnecessary, and a little complex due to optional nesting.
visited: []const type,
parent_is_optional: bool,
) bool {
return switch (@typeInfo(T)) {
.bool,
.int,
.float,
.null,
.@"enum",
=> true,
.noreturn,
.void,
.type,
.undefined,
.error_union,
.error_set,
.@"fn",
.frame,
.@"anyframe",
.@"opaque",
.comptime_int,
.comptime_float,
.enum_literal,
=> false,
.pointer => |pointer| switch (pointer.size) {
.one => canParseTypeInner(pointer.child, visited, parent_is_optional),
.slice => canParseTypeInner(pointer.child, visited, false),
.many, .c => false,
},
.optional => |optional| if (parent_is_optional)
false
else
canParseTypeInner(optional.child, visited, true),
.array => |array| canParseTypeInner(array.child, visited, false),
.vector => |vector| canParseTypeInner(vector.child, visited, false),
.@"struct" => |@"struct"| {
for (visited) |V| if (T == V) return true;
const new_visited = visited ++ .{T};
for (@"struct".fields) |field| {
if (!field.is_comptime and !canParseTypeInner(field.type, new_visited, false)) {
return false;
}
}
return true;
},
.@"union" => |@"union"| {
for (visited) |V| if (T == V) return true;
const new_visited = visited ++ .{T};
for (@"union".fields) |field| {
if (field.type != void and !canParseTypeInner(field.type, new_visited, false)) {
return false;
}
}
return true;
},
};
}
test "std.zon parse canParseType" {
try std.testing.expect(!comptime canParseType(void));
try std.testing.expect(!comptime canParseType(struct { f: [*]u8 }));
try std.testing.expect(!comptime canParseType(struct { error{foo} }));
try std.testing.expect(!comptime canParseType(union(enum) { a: void, b: [*c]u8 }));
try std.testing.expect(!comptime canParseType(@Vector(0, [*c]u8)));
try std.testing.expect(!comptime canParseType(*?[*c]u8));
try std.testing.expect(comptime canParseType(enum(u8) { _ }));
try std.testing.expect(comptime canParseType(union { foo: void }));
try std.testing.expect(comptime canParseType(union(enum) { foo: void }));
try std.testing.expect(!comptime canParseType(comptime_float));
try std.testing.expect(!comptime canParseType(comptime_int));
try std.testing.expect(comptime canParseType(struct { comptime foo: ??u8 = null }));
try std.testing.expect(!comptime canParseType(@TypeOf(.foo)));
try std.testing.expect(comptime canParseType(?u8));
try std.testing.expect(comptime canParseType(*?*u8));
try std.testing.expect(comptime canParseType(?struct {
foo: ?struct {
?union(enum) {
a: ?@Vector(0, ?*u8),
},
?struct {
f: ?[]?u8,
},
},
}));
try std.testing.expect(!comptime canParseType(??u8));
try std.testing.expect(!comptime canParseType(?*?u8));
try std.testing.expect(!comptime canParseType(*?*?*u8));
try std.testing.expect(!comptime canParseType(struct { x: comptime_int = 2 }));
try std.testing.expect(!comptime canParseType(struct { x: comptime_float = 2 }));
try std.testing.expect(comptime canParseType(struct { comptime x: @TypeOf(.foo) = .foo }));
try std.testing.expect(!comptime canParseType(struct { comptime_int }));
const Recursive = struct { foo: ?*@This() };
try std.testing.expect(comptime canParseType(Recursive));
// Make sure we validate nested optional before we early out due to already having seen
// a type recursion!
try std.testing.expect(!comptime canParseType(struct {
add_to_visited: ?u8,
retrieve_from_visited: ??u8,
}));
}
test "std.zon requiresAllocator" {
try std.testing.expect(!requiresAllocator(u8));
try std.testing.expect(!requiresAllocator(f32));
try std.testing.expect(!requiresAllocator(enum { foo }));
try std.testing.expect(!requiresAllocator(struct { f32 }));
try std.testing.expect(!requiresAllocator(struct { x: f32 }));
try std.testing.expect(!requiresAllocator([0][]const u8));
try std.testing.expect(!requiresAllocator([2]u8));
try std.testing.expect(!requiresAllocator(union { x: f32, y: f32 }));
try std.testing.expect(!requiresAllocator(union(enum) { x: f32, y: f32 }));
try std.testing.expect(!requiresAllocator(?f32));
try std.testing.expect(!requiresAllocator(void));
try std.testing.expect(!requiresAllocator(@TypeOf(null)));
try std.testing.expect(!requiresAllocator(@Vector(3, u8)));
try std.testing.expect(!requiresAllocator(@Vector(0, *const u8)));
try std.testing.expect(requiresAllocator([]u8));
try std.testing.expect(requiresAllocator(*struct { u8, u8 }));
try std.testing.expect(requiresAllocator([1][]const u8));
try std.testing.expect(requiresAllocator(struct { x: i32, y: []u8 }));
try std.testing.expect(requiresAllocator(union { x: i32, y: []u8 }));
try std.testing.expect(requiresAllocator(union(enum) { x: i32, y: []u8 }));
try std.testing.expect(requiresAllocator(?[]u8));
try std.testing.expect(requiresAllocator(@Vector(3, *const u8)));
}
test "std.zon ast errors" {
const gpa = std.testing.allocator;
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(struct {}, gpa, ".{.x = 1 .y = 2}", &diag, .{}),
);
try std.testing.expectFmt("1:13: error: expected ',' after initializer\n", "{f}", .{diag});
}
test "std.zon comments" {
const gpa = std.testing.allocator;
try std.testing.expectEqual(@as(u8, 10), fromSlice(u8, gpa,
\\// comment
\\10 // comment
\\// comment
, null, .{}));
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(u8, gpa,
\\//! comment
\\10 // comment
\\// comment
, &diag, .{}));
try std.testing.expectFmt(
"1:1: error: expected expression, found 'a document comment'\n",
"{f}",
.{diag},
);
}
}
test "std.zon failure/oom formatting" {
const gpa = std.testing.allocator;
var failing_allocator = std.testing.FailingAllocator.init(gpa, .{
.fail_index = 0,
.resize_fail_index = 0,
});
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.OutOfMemory, fromSlice(
[]const u8,
failing_allocator.allocator(),
"\"foo\"",
&diag,
.{},
));
try std.testing.expectFmt("", "{f}", .{diag});
}
test "std.zon fromSlice syntax error" {
try std.testing.expectError(
error.ParseZon,
fromSlice(u8, std.testing.allocator, ".{", null, .{}),
);
}
test "std.zon optional" {
const gpa = std.testing.allocator;
// Basic usage
{
const none = try fromSlice(?u32, gpa, "null", null, .{});
try std.testing.expect(none == null);
const some = try fromSlice(?u32, gpa, "1", null, .{});
try std.testing.expect(some.? == 1);
}
// Deep free
{
const none = try fromSlice(?[]const u8, gpa, "null", null, .{});
try std.testing.expect(none == null);
const some = try fromSlice(?[]const u8, gpa, "\"foo\"", null, .{});
defer free(gpa, some);
try std.testing.expectEqualStrings("foo", some.?);
}
}
test "std.zon unions" {
const gpa = std.testing.allocator;
// Unions
{
const Tagged = union(enum) { x: f32, @"y y": bool, z, @"z z" };
const Untagged = union { x: f32, @"y y": bool, z: void, @"z z": void };
const tagged_x = try fromSlice(Tagged, gpa, ".{.x = 1.5}", null, .{});
try std.testing.expectEqual(Tagged{ .x = 1.5 }, tagged_x);
const tagged_y = try fromSlice(Tagged, gpa, ".{.@\"y y\" = true}", null, .{});
try std.testing.expectEqual(Tagged{ .@"y y" = true }, tagged_y);
const tagged_z_shorthand = try fromSlice(Tagged, gpa, ".z", null, .{});
try std.testing.expectEqual(@as(Tagged, .z), tagged_z_shorthand);
const tagged_zz_shorthand = try fromSlice(Tagged, gpa, ".@\"z z\"", null, .{});
try std.testing.expectEqual(@as(Tagged, .@"z z"), tagged_zz_shorthand);
const untagged_x = try fromSlice(Untagged, gpa, ".{.x = 1.5}", null, .{});
try std.testing.expect(untagged_x.x == 1.5);
const untagged_y = try fromSlice(Untagged, gpa, ".{.@\"y y\" = true}", null, .{});
try std.testing.expect(untagged_y.@"y y");
}
// Deep free
{
const Union = union(enum) { bar: []const u8, baz: bool };
const noalloc = try fromSlice(Union, gpa, ".{.baz = false}", null, .{});
try std.testing.expectEqual(Union{ .baz = false }, noalloc);
const alloc = try fromSlice(Union, gpa, ".{.bar = \"qux\"}", null, .{});
defer free(gpa, alloc);
try std.testing.expectEqualDeep(Union{ .bar = "qux" }, alloc);
}
// Unknown field
{
const Union = union { x: f32, y: f32 };
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(Union, gpa, ".{.z=2.5}", &diag, .{}),
);
try std.testing.expectFmt(
\\1:4: error: unexpected field 'z'
\\1:4: note: supported: 'x', 'y'
\\
,
"{f}",
.{diag},
);
}
// Explicit void field
{
const Union = union(enum) { x: void };
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(Union, gpa, ".{.x=1}", &diag, .{}),
);
try std.testing.expectFmt("1:6: error: expected type 'void'\n", "{f}", .{diag});
}
// Extra field
{
const Union = union { x: f32, y: bool };
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(Union, gpa, ".{.x = 1.5, .y = true}", &diag, .{}),
);
try std.testing.expectFmt("1:2: error: expected union\n", "{f}", .{diag});
}
// No fields
{
const Union = union { x: f32, y: bool };
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(Union, gpa, ".{}", &diag, .{}),
);
try std.testing.expectFmt("1:2: error: expected union\n", "{f}", .{diag});
}
// Enum literals cannot coerce into untagged unions
{
const Union = union { x: void };
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(Union, gpa, ".x", &diag, .{}));
try std.testing.expectFmt("1:2: error: expected union\n", "{f}", .{diag});
}
// Unknown field for enum literal coercion
{
const Union = union(enum) { x: void };
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(Union, gpa, ".y", &diag, .{}));
try std.testing.expectFmt(
\\1:2: error: unexpected field 'y'
\\1:2: note: supported: 'x'
\\
,
"{f}",
.{diag},
);
}
// Non void field for enum literal coercion
{
const Union = union(enum) { x: f32 };
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(Union, gpa, ".x", &diag, .{}));
try std.testing.expectFmt("1:2: error: expected union\n", "{f}", .{diag});
}
}
test "std.zon structs" {
const gpa = std.testing.allocator;
// Structs (various sizes tested since they're parsed differently)
{
const Vec0 = struct {};
const Vec1 = struct { x: f32 };
const Vec2 = struct { x: f32, y: f32 };
const Vec3 = struct { x: f32, y: f32, z: f32 };
const zero = try fromSlice(Vec0, gpa, ".{}", null, .{});
try std.testing.expectEqual(Vec0{}, zero);
const one = try fromSlice(Vec1, gpa, ".{.x = 1.2}", null, .{});
try std.testing.expectEqual(Vec1{ .x = 1.2 }, one);
const two = try fromSlice(Vec2, gpa, ".{.x = 1.2, .y = 3.4}", null, .{});
try std.testing.expectEqual(Vec2{ .x = 1.2, .y = 3.4 }, two);
const three = try fromSlice(Vec3, gpa, ".{.x = 1.2, .y = 3.4, .z = 5.6}", null, .{});
try std.testing.expectEqual(Vec3{ .x = 1.2, .y = 3.4, .z = 5.6 }, three);
}
// Deep free (structs and arrays)
{
const Foo = struct { bar: []const u8, baz: []const []const u8 };
const parsed = try fromSlice(
Foo,
gpa,
".{.bar = \"qux\", .baz = .{\"a\", \"b\"}}",
null,
.{},
);
defer free(gpa, parsed);
try std.testing.expectEqualDeep(Foo{ .bar = "qux", .baz = &.{ "a", "b" } }, parsed);
}
// Unknown field
{
const Vec2 = struct { x: f32, y: f32 };
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(Vec2, gpa, ".{.x=1.5, .z=2.5}", &diag, .{}),
);
try std.testing.expectFmt(
\\1:12: error: unexpected field 'z'
\\1:12: note: supported: 'x', 'y'
\\
,
"{f}",
.{diag},
);
}
// Duplicate field
{
const Vec2 = struct { x: f32, y: f32 };
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(Vec2, gpa, ".{.x=1.5, .x=2.5, .x=3.5}", &diag, .{}),
);
try std.testing.expectFmt(
\\1:4: error: duplicate struct field name
\\1:12: note: duplicate name here
\\
, "{f}", .{diag});
}
// Ignore unknown fields
{
const Vec2 = struct { x: f32, y: f32 = 2.0 };
const parsed = try fromSlice(Vec2, gpa, ".{ .x = 1.0, .z = 3.0 }", null, .{
.ignore_unknown_fields = true,
});
try std.testing.expectEqual(Vec2{ .x = 1.0, .y = 2.0 }, parsed);
}
// Unknown field when struct has no fields (regression test)
{
const Vec2 = struct {};
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(Vec2, gpa, ".{.x=1.5, .z=2.5}", &diag, .{}),
);
try std.testing.expectFmt(
\\1:4: error: unexpected field 'x'
\\1:4: note: none expected
\\
, "{f}", .{diag});
}
// Missing field
{
const Vec2 = struct { x: f32, y: f32 };
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(Vec2, gpa, ".{.x=1.5}", &diag, .{}),
);
try std.testing.expectFmt("1:2: error: missing required field y\n", "{f}", .{diag});
}
// Default field
{
const Vec2 = struct { x: f32, y: f32 = 1.5 };
const parsed = try fromSlice(Vec2, gpa, ".{.x = 1.2}", null, .{});
try std.testing.expectEqual(Vec2{ .x = 1.2, .y = 1.5 }, parsed);
}
// Comptime field
{
const Vec2 = struct { x: f32, comptime y: f32 = 1.5 };
const parsed = try fromSlice(Vec2, gpa, ".{.x = 1.2}", null, .{});
try std.testing.expectEqual(Vec2{ .x = 1.2, .y = 1.5 }, parsed);
}
// Comptime field assignment
{
const Vec2 = struct { x: f32, comptime y: f32 = 1.5 };
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
const parsed = fromSlice(Vec2, gpa, ".{.x = 1.2, .y = 1.5}", &diag, .{});
try std.testing.expectError(error.ParseZon, parsed);
try std.testing.expectFmt(
\\1:18: error: cannot initialize comptime field
\\
, "{f}", .{diag});
}
// Enum field (regression test, we were previously getting the field name in an
// incorrect way that broke for enum values)
{
const Vec0 = struct { x: enum { x } };
const parsed = try fromSlice(Vec0, gpa, ".{ .x = .x }", null, .{});
try std.testing.expectEqual(Vec0{ .x = .x }, parsed);
}
// Enum field and struct field with @
{
const Vec0 = struct { @"x x": enum { @"x x" } };
const parsed = try fromSlice(Vec0, gpa, ".{ .@\"x x\" = .@\"x x\" }", null, .{});
try std.testing.expectEqual(Vec0{ .@"x x" = .@"x x" }, parsed);
}
// Type expressions are not allowed
{
// Structs
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
const parsed = fromSlice(struct {}, gpa, "Empty{}", &diag, .{});
try std.testing.expectError(error.ParseZon, parsed);
try std.testing.expectFmt(
\\1:1: error: types are not available in ZON
\\1:1: note: replace the type with '.'
\\
, "{f}", .{diag});
}
// Arrays
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
const parsed = fromSlice([3]u8, gpa, "[3]u8{1, 2, 3}", &diag, .{});
try std.testing.expectError(error.ParseZon, parsed);
try std.testing.expectFmt(
\\1:1: error: types are not available in ZON
\\1:1: note: replace the type with '.'
\\
, "{f}", .{diag});
}
// Slices
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
const parsed = fromSlice([]u8, gpa, "[]u8{1, 2, 3}", &diag, .{});
try std.testing.expectError(error.ParseZon, parsed);
try std.testing.expectFmt(
\\1:1: error: types are not available in ZON
\\1:1: note: replace the type with '.'
\\
, "{f}", .{diag});
}
// Tuples
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
const parsed = fromSlice(
struct { u8, u8, u8 },
gpa,
"Tuple{1, 2, 3}",
&diag,
.{},
);
try std.testing.expectError(error.ParseZon, parsed);
try std.testing.expectFmt(
\\1:1: error: types are not available in ZON
\\1:1: note: replace the type with '.'
\\
, "{f}", .{diag});
}
// Nested
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
const parsed = fromSlice(struct {}, gpa, ".{ .x = Tuple{1, 2, 3} }", &diag, .{});
try std.testing.expectError(error.ParseZon, parsed);
try std.testing.expectFmt(
\\1:9: error: types are not available in ZON
\\1:9: note: replace the type with '.'
\\
, "{f}", .{diag});
}
}
}
test "std.zon tuples" {
const gpa = std.testing.allocator;
// Structs (various sizes tested since they're parsed differently)
{
const Tuple0 = struct {};
const Tuple1 = struct { f32 };
const Tuple2 = struct { f32, bool };
const Tuple3 = struct { f32, bool, u8 };
const zero = try fromSlice(Tuple0, gpa, ".{}", null, .{});
try std.testing.expectEqual(Tuple0{}, zero);
const one = try fromSlice(Tuple1, gpa, ".{1.2}", null, .{});
try std.testing.expectEqual(Tuple1{1.2}, one);
const two = try fromSlice(Tuple2, gpa, ".{1.2, true}", null, .{});
try std.testing.expectEqual(Tuple2{ 1.2, true }, two);
const three = try fromSlice(Tuple3, gpa, ".{1.2, false, 3}", null, .{});
try std.testing.expectEqual(Tuple3{ 1.2, false, 3 }, three);
}
// Deep free
{
const Tuple = struct { []const u8, []const u8 };
const parsed = try fromSlice(Tuple, gpa, ".{\"hello\", \"world\"}", null, .{});
defer free(gpa, parsed);
try std.testing.expectEqualDeep(Tuple{ "hello", "world" }, parsed);
}
// Extra field
{
const Tuple = struct { f32, bool };
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(Tuple, gpa, ".{0.5, true, 123}", &diag, .{}),
);
try std.testing.expectFmt("1:14: error: index 2 outside of tuple length 2\n", "{f}", .{diag});
}
// Extra field
{
const Tuple = struct { f32, bool };
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(Tuple, gpa, ".{0.5}", &diag, .{}),
);
try std.testing.expectFmt(
"1:2: error: missing tuple field with index 1\n",
"{f}",
.{diag},
);
}
// Tuple with unexpected field names
{
const Tuple = struct { f32 };
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(Tuple, gpa, ".{.foo = 10.0}", &diag, .{}),
);
try std.testing.expectFmt("1:2: error: expected tuple\n", "{f}", .{diag});
}
// Struct with missing field names
{
const Struct = struct { foo: f32 };
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(Struct, gpa, ".{10.0}", &diag, .{}),
);
try std.testing.expectFmt("1:2: error: expected struct\n", "{f}", .{diag});
}
// Comptime field
{
const Vec2 = struct { f32, comptime f32 = 1.5 };
const parsed = try fromSlice(Vec2, gpa, ".{ 1.2 }", null, .{});
try std.testing.expectEqual(Vec2{ 1.2, 1.5 }, parsed);
}
// Comptime field assignment
{
const Vec2 = struct { f32, comptime f32 = 1.5 };
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
const parsed = fromSlice(Vec2, gpa, ".{ 1.2, 1.5}", &diag, .{});
try std.testing.expectError(error.ParseZon, parsed);
try std.testing.expectFmt(
\\1:9: error: cannot initialize comptime field
\\
, "{f}", .{diag});
}
}
// Test sizes 0 to 3 since small sizes get parsed differently
test "std.zon arrays and slices" {
if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // https://github.com/ziglang/zig/issues/20881
const gpa = std.testing.allocator;
// Literals
{
// Arrays
{
const zero = try fromSlice([0]u8, gpa, ".{}", null, .{});
try std.testing.expectEqualSlices(u8, &@as([0]u8, .{}), &zero);
const one = try fromSlice([1]u8, gpa, ".{'a'}", null, .{});
try std.testing.expectEqualSlices(u8, &@as([1]u8, .{'a'}), &one);
const two = try fromSlice([2]u8, gpa, ".{'a', 'b'}", null, .{});
try std.testing.expectEqualSlices(u8, &@as([2]u8, .{ 'a', 'b' }), &two);
const two_comma = try fromSlice([2]u8, gpa, ".{'a', 'b',}", null, .{});
try std.testing.expectEqualSlices(u8, &@as([2]u8, .{ 'a', 'b' }), &two_comma);
const three = try fromSlice([3]u8, gpa, ".{'a', 'b', 'c'}", null, .{});
try std.testing.expectEqualSlices(u8, &.{ 'a', 'b', 'c' }, &three);
const sentinel = try fromSlice([3:'z']u8, gpa, ".{'a', 'b', 'c'}", null, .{});
const expected_sentinel: [3:'z']u8 = .{ 'a', 'b', 'c' };
try std.testing.expectEqualSlices(u8, &expected_sentinel, &sentinel);
}
// Slice literals
{
const zero = try fromSlice([]const u8, gpa, ".{}", null, .{});
defer free(gpa, zero);
try std.testing.expectEqualSlices(u8, @as([]const u8, &.{}), zero);
const one = try fromSlice([]u8, gpa, ".{'a'}", null, .{});
defer free(gpa, one);
try std.testing.expectEqualSlices(u8, &.{'a'}, one);
const two = try fromSlice([]const u8, gpa, ".{'a', 'b'}", null, .{});
defer free(gpa, two);
try std.testing.expectEqualSlices(u8, &.{ 'a', 'b' }, two);
const two_comma = try fromSlice([]const u8, gpa, ".{'a', 'b',}", null, .{});
defer free(gpa, two_comma);
try std.testing.expectEqualSlices(u8, &.{ 'a', 'b' }, two_comma);
const three = try fromSlice([]u8, gpa, ".{'a', 'b', 'c'}", null, .{});
defer free(gpa, three);
try std.testing.expectEqualSlices(u8, &.{ 'a', 'b', 'c' }, three);
const sentinel = try fromSlice([:'z']const u8, gpa, ".{'a', 'b', 'c'}", null, .{});
defer free(gpa, sentinel);
const expected_sentinel: [:'z']const u8 = &.{ 'a', 'b', 'c' };
try std.testing.expectEqualSlices(u8, expected_sentinel, sentinel);
}
}
// Deep free
{
// Arrays
{
const parsed = try fromSlice([1][]const u8, gpa, ".{\"abc\"}", null, .{});
defer free(gpa, parsed);
const expected: [1][]const u8 = .{"abc"};
try std.testing.expectEqualDeep(expected, parsed);
}
// Slice literals
{
const parsed = try fromSlice([]const []const u8, gpa, ".{\"abc\"}", null, .{});
defer free(gpa, parsed);
const expected: []const []const u8 = &.{"abc"};
try std.testing.expectEqualDeep(expected, parsed);
}
}
// Sentinels and alignment
{
// Arrays
{
const sentinel = try fromSlice([1:2]u8, gpa, ".{1}", null, .{});
try std.testing.expectEqual(@as(usize, 1), sentinel.len);
try std.testing.expectEqual(@as(u8, 1), sentinel[0]);
try std.testing.expectEqual(@as(u8, 2), sentinel[1]);
}
// Slice literals
{
const sentinel = try fromSlice([:2]align(4) u8, gpa, ".{1}", null, .{});
defer free(gpa, sentinel);
try std.testing.expectEqual(@as(usize, 1), sentinel.len);
try std.testing.expectEqual(@as(u8, 1), sentinel[0]);
try std.testing.expectEqual(@as(u8, 2), sentinel[1]);
}
}
// Expect 0 find 3
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([0]u8, gpa, ".{'a', 'b', 'c'}", &diag, .{}),
);
try std.testing.expectFmt(
"1:3: error: index 0 outside of array of length 0\n",
"{f}",
.{diag},
);
}
// Expect 1 find 2
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([1]u8, gpa, ".{'a', 'b'}", &diag, .{}),
);
try std.testing.expectFmt(
"1:8: error: index 1 outside of array of length 1\n",
"{f}",
.{diag},
);
}
// Expect 2 find 1
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([2]u8, gpa, ".{'a'}", &diag, .{}),
);
try std.testing.expectFmt(
"1:2: error: expected 2 array elements; found 1\n",
"{f}",
.{diag},
);
}
// Expect 3 find 0
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([3]u8, gpa, ".{}", &diag, .{}),
);
try std.testing.expectFmt(
"1:2: error: expected 3 array elements; found 0\n",
"{f}",
.{diag},
);
}
// Wrong inner type
{
// Array
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([3]bool, gpa, ".{'a', 'b', 'c'}", &diag, .{}),
);
try std.testing.expectFmt("1:3: error: expected type 'bool'\n", "{f}", .{diag});
}
// Slice
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([]bool, gpa, ".{'a', 'b', 'c'}", &diag, .{}),
);
try std.testing.expectFmt("1:3: error: expected type 'bool'\n", "{f}", .{diag});
}
}
// Complete wrong type
{
// Array
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([3]u8, gpa, "'a'", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected array\n", "{f}", .{diag});
}
// Slice
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([]u8, gpa, "'a'", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected array\n", "{f}", .{diag});
}
}
// Address of is not allowed (indirection for slices in ZON is implicit)
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([]u8, gpa, " &.{'a', 'b', 'c'}", &diag, .{}),
);
try std.testing.expectFmt(
"1:3: error: pointers are not available in ZON\n",
"{f}",
.{diag},
);
}
}
test "std.zon string literal" {
const gpa = std.testing.allocator;
// Basic string literal
{
const parsed = try fromSlice([]const u8, gpa, "\"abc\"", null, .{});
defer free(gpa, parsed);
try std.testing.expectEqualStrings(@as([]const u8, "abc"), parsed);
}
// String literal with escape characters
{
const parsed = try fromSlice([]const u8, gpa, "\"ab\\nc\"", null, .{});
defer free(gpa, parsed);
try std.testing.expectEqualStrings(@as([]const u8, "ab\nc"), parsed);
}
// String literal with embedded null
{
const parsed = try fromSlice([]const u8, gpa, "\"ab\\x00c\"", null, .{});
defer free(gpa, parsed);
try std.testing.expectEqualStrings(@as([]const u8, "ab\x00c"), parsed);
}
// Passing string literal to a mutable slice
{
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([]u8, gpa, "\"abcd\"", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected array\n", "{f}", .{diag});
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([]u8, gpa, "\\\\abcd", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected array\n", "{f}", .{diag});
}
}
// Passing string literal to a array
{
{
var ast = try std.zig.Ast.parse(gpa, "\"abcd\"", .zon);
defer ast.deinit(gpa);
var zoir = try ZonGen.generate(gpa, ast, .{ .parse_str_lits = false });
defer zoir.deinit(gpa);
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([4:0]u8, gpa, "\"abcd\"", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected array\n", "{f}", .{diag});
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([4:0]u8, gpa, "\\\\abcd", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected array\n", "{f}", .{diag});
}
}
// Zero terminated slices
{
{
const parsed: [:0]const u8 = try fromSlice(
[:0]const u8,
gpa,
"\"abc\"",
null,
.{},
);
defer free(gpa, parsed);
try std.testing.expectEqualStrings("abc", parsed);
try std.testing.expectEqual(@as(u8, 0), parsed[3]);
}
{
const parsed: [:0]const u8 = try fromSlice(
[:0]const u8,
gpa,
"\\\\abc",
null,
.{},
);
defer free(gpa, parsed);
try std.testing.expectEqualStrings("abc", parsed);
try std.testing.expectEqual(@as(u8, 0), parsed[3]);
}
}
// Other value terminated slices
{
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([:1]const u8, gpa, "\"foo\"", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected array\n", "{f}", .{diag});
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([:1]const u8, gpa, "\\\\foo", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected array\n", "{f}", .{diag});
}
}
// Expecting string literal, getting something else
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([]const u8, gpa, "true", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected string\n", "{f}", .{diag});
}
// Expecting string literal, getting an incompatible tuple
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([]const u8, gpa, ".{false}", &diag, .{}),
);
try std.testing.expectFmt("1:3: error: expected type 'u8'\n", "{f}", .{diag});
}
// Invalid string literal
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([]const i8, gpa, "\"\\a\"", &diag, .{}),
);
try std.testing.expectFmt("1:3: error: invalid escape character: 'a'\n", "{f}", .{diag});
}
// Slice wrong child type
{
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([]const i8, gpa, "\"a\"", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected array\n", "{f}", .{diag});
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([]const i8, gpa, "\\\\a", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected array\n", "{f}", .{diag});
}
}
// Bad alignment
{
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([]align(2) const u8, gpa, "\"abc\"", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected array\n", "{f}", .{diag});
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice([]align(2) const u8, gpa, "\\\\abc", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected array\n", "{f}", .{diag});
}
}
// Multi line strings
inline for (.{ []const u8, [:0]const u8 }) |String| {
// Nested
{
const S = struct {
message: String,
message2: String,
message3: String,
};
const parsed = try fromSlice(S, gpa,
\\.{
\\ .message =
\\ \\hello, world!
\\
\\ \\this is a multiline string!
\\ \\
\\ \\...
\\
\\ ,
\\ .message2 =
\\ \\this too...sort of.
\\ ,
\\ .message3 =
\\ \\
\\ \\and this.
\\}
, null, .{});
defer free(gpa, parsed);
try std.testing.expectEqualStrings(
"hello, world!\nthis is a multiline string!\n\n...",
parsed.message,
);
try std.testing.expectEqualStrings("this too...sort of.", parsed.message2);
try std.testing.expectEqualStrings("\nand this.", parsed.message3);
}
}
}
test "std.zon enum literals" {
const gpa = std.testing.allocator;
const Enum = enum {
foo,
bar,
baz,
@"ab\nc",
};
// Tags that exist
try std.testing.expectEqual(Enum.foo, try fromSlice(Enum, gpa, ".foo", null, .{}));
try std.testing.expectEqual(Enum.bar, try fromSlice(Enum, gpa, ".bar", null, .{}));
try std.testing.expectEqual(Enum.baz, try fromSlice(Enum, gpa, ".baz", null, .{}));
try std.testing.expectEqual(
Enum.@"ab\nc",
try fromSlice(Enum, gpa, ".@\"ab\\nc\"", null, .{}),
);
// Bad tag
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(Enum, gpa, ".qux", &diag, .{}),
);
try std.testing.expectFmt(
\\1:2: error: unexpected enum literal 'qux'
\\1:2: note: supported: 'foo', 'bar', 'baz', '@"ab\nc"'
\\
,
"{f}",
.{diag},
);
}
// Bad tag that's too long for parser
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(Enum, gpa, ".@\"foobarbaz\"", &diag, .{}),
);
try std.testing.expectFmt(
\\1:2: error: unexpected enum literal 'foobarbaz'
\\1:2: note: supported: 'foo', 'bar', 'baz', '@"ab\nc"'
\\
,
"{f}",
.{diag},
);
}
// Bad type
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(Enum, gpa, "true", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected enum literal\n", "{f}", .{diag});
}
// Test embedded nulls in an identifier
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(Enum, gpa, ".@\"\\x00\"", &diag, .{}),
);
try std.testing.expectFmt(
"1:2: error: identifier cannot contain null bytes\n",
"{f}",
.{diag},
);
}
}
test "std.zon parse bool" {
const gpa = std.testing.allocator;
// Correct bools
try std.testing.expectEqual(true, try fromSlice(bool, gpa, "true", null, .{}));
try std.testing.expectEqual(false, try fromSlice(bool, gpa, "false", null, .{}));
// Errors
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(bool, gpa, " foo", &diag, .{}),
);
try std.testing.expectFmt(
\\1:2: error: invalid expression
\\1:2: note: ZON allows identifiers 'true', 'false', 'null', 'inf', and 'nan'
\\1:2: note: precede identifier with '.' for an enum literal
\\
, "{f}", .{diag});
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(bool, gpa, "123", &diag, .{}));
try std.testing.expectFmt("1:1: error: expected type 'bool'\n", "{f}", .{diag});
}
}
test "std.zon intFromFloatExact" {
// Valid conversions
try std.testing.expectEqual(@as(u8, 10), intFromFloatExact(u8, @as(f32, 10.0)).?);
try std.testing.expectEqual(@as(i8, -123), intFromFloatExact(i8, @as(f64, @as(f64, -123.0))).?);
try std.testing.expectEqual(@as(i16, 45), intFromFloatExact(i16, @as(f128, @as(f128, 45.0))).?);
// Out of range
try std.testing.expectEqual(@as(?u4, null), intFromFloatExact(u4, @as(f32, 16.0)));
try std.testing.expectEqual(@as(?i4, null), intFromFloatExact(i4, @as(f64, -17.0)));
try std.testing.expectEqual(@as(?u8, null), intFromFloatExact(u8, @as(f128, -2.0)));
// Not a whole number
try std.testing.expectEqual(@as(?u8, null), intFromFloatExact(u8, @as(f32, 0.5)));
try std.testing.expectEqual(@as(?i8, null), intFromFloatExact(i8, @as(f64, 0.01)));
// Infinity and NaN
try std.testing.expectEqual(@as(?u8, null), intFromFloatExact(u8, std.math.inf(f32)));
try std.testing.expectEqual(@as(?u8, null), intFromFloatExact(u8, -std.math.inf(f32)));
try std.testing.expectEqual(@as(?u8, null), intFromFloatExact(u8, std.math.nan(f32)));
}
test "std.zon parse int" {
const gpa = std.testing.allocator;
// Test various numbers and types
try std.testing.expectEqual(@as(u8, 10), try fromSlice(u8, gpa, "10", null, .{}));
try std.testing.expectEqual(@as(i16, 24), try fromSlice(i16, gpa, "24", null, .{}));
try std.testing.expectEqual(@as(i14, -4), try fromSlice(i14, gpa, "-4", null, .{}));
try std.testing.expectEqual(@as(i32, -123), try fromSlice(i32, gpa, "-123", null, .{}));
// Test limits
try std.testing.expectEqual(@as(i8, 127), try fromSlice(i8, gpa, "127", null, .{}));
try std.testing.expectEqual(@as(i8, -128), try fromSlice(i8, gpa, "-128", null, .{}));
// Test characters
try std.testing.expectEqual(@as(u8, 'a'), try fromSlice(u8, gpa, "'a'", null, .{}));
try std.testing.expectEqual(@as(u8, 'z'), try fromSlice(u8, gpa, "'z'", null, .{}));
// Test big integers
try std.testing.expectEqual(
@as(u65, 36893488147419103231),
try fromSlice(u65, gpa, "36893488147419103231", null, .{}),
);
try std.testing.expectEqual(
@as(u65, 36893488147419103231),
try fromSlice(u65, gpa, "368934_881_474191032_31", null, .{}),
);
// Test big integer limits
try std.testing.expectEqual(
@as(i66, 36893488147419103231),
try fromSlice(i66, gpa, "36893488147419103231", null, .{}),
);
try std.testing.expectEqual(
@as(i66, -36893488147419103232),
try fromSlice(i66, gpa, "-36893488147419103232", null, .{}),
);
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(
i66,
gpa,
"36893488147419103232",
&diag,
.{},
));
try std.testing.expectFmt(
"1:1: error: type 'i66' cannot represent value\n",
"{f}",
.{diag},
);
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(
i66,
gpa,
"-36893488147419103233",
&diag,
.{},
));
try std.testing.expectFmt(
"1:1: error: type 'i66' cannot represent value\n",
"{f}",
.{diag},
);
}
// Test parsing whole number floats as integers
try std.testing.expectEqual(@as(i8, -1), try fromSlice(i8, gpa, "-1.0", null, .{}));
try std.testing.expectEqual(@as(i8, 123), try fromSlice(i8, gpa, "123.0", null, .{}));
// Test non-decimal integers
try std.testing.expectEqual(@as(i16, 0xff), try fromSlice(i16, gpa, "0xff", null, .{}));
try std.testing.expectEqual(@as(i16, -0xff), try fromSlice(i16, gpa, "-0xff", null, .{}));
try std.testing.expectEqual(@as(i16, 0o77), try fromSlice(i16, gpa, "0o77", null, .{}));
try std.testing.expectEqual(@as(i16, -0o77), try fromSlice(i16, gpa, "-0o77", null, .{}));
try std.testing.expectEqual(@as(i16, 0b11), try fromSlice(i16, gpa, "0b11", null, .{}));
try std.testing.expectEqual(@as(i16, -0b11), try fromSlice(i16, gpa, "-0b11", null, .{}));
// Test non-decimal big integers
try std.testing.expectEqual(@as(u65, 0x1ffffffffffffffff), try fromSlice(
u65,
gpa,
"0x1ffffffffffffffff",
null,
.{},
));
try std.testing.expectEqual(@as(i66, 0x1ffffffffffffffff), try fromSlice(
i66,
gpa,
"0x1ffffffffffffffff",
null,
.{},
));
try std.testing.expectEqual(@as(i66, -0x1ffffffffffffffff), try fromSlice(
i66,
gpa,
"-0x1ffffffffffffffff",
null,
.{},
));
try std.testing.expectEqual(@as(u65, 0x1ffffffffffffffff), try fromSlice(
u65,
gpa,
"0o3777777777777777777777",
null,
.{},
));
try std.testing.expectEqual(@as(i66, 0x1ffffffffffffffff), try fromSlice(
i66,
gpa,
"0o3777777777777777777777",
null,
.{},
));
try std.testing.expectEqual(@as(i66, -0x1ffffffffffffffff), try fromSlice(
i66,
gpa,
"-0o3777777777777777777777",
null,
.{},
));
try std.testing.expectEqual(@as(u65, 0x1ffffffffffffffff), try fromSlice(
u65,
gpa,
"0b11111111111111111111111111111111111111111111111111111111111111111",
null,
.{},
));
try std.testing.expectEqual(@as(i66, 0x1ffffffffffffffff), try fromSlice(
i66,
gpa,
"0b11111111111111111111111111111111111111111111111111111111111111111",
null,
.{},
));
try std.testing.expectEqual(@as(i66, -0x1ffffffffffffffff), try fromSlice(
i66,
gpa,
"-0b11111111111111111111111111111111111111111111111111111111111111111",
null,
.{},
));
// Number with invalid character in the middle
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(u8, gpa, "32a32", &diag, .{}));
try std.testing.expectFmt(
"1:3: error: invalid digit 'a' for decimal base\n",
"{f}",
.{diag},
);
}
// Failing to parse as int
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(u8, gpa, "true", &diag, .{}));
try std.testing.expectFmt("1:1: error: expected type 'u8'\n", "{f}", .{diag});
}
// Failing because an int is out of range
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(u8, gpa, "256", &diag, .{}));
try std.testing.expectFmt(
"1:1: error: type 'u8' cannot represent value\n",
"{f}",
.{diag},
);
}
// Failing because a negative int is out of range
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(i8, gpa, "-129", &diag, .{}));
try std.testing.expectFmt(
"1:1: error: type 'i8' cannot represent value\n",
"{f}",
.{diag},
);
}
// Failing because an unsigned int is negative
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(u8, gpa, "-1", &diag, .{}));
try std.testing.expectFmt(
"1:1: error: type 'u8' cannot represent value\n",
"{f}",
.{diag},
);
}
// Failing because a float is non-whole
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(u8, gpa, "1.5", &diag, .{}));
try std.testing.expectFmt(
"1:1: error: type 'u8' cannot represent value\n",
"{f}",
.{diag},
);
}
// Failing because a float is negative
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(u8, gpa, "-1.0", &diag, .{}));
try std.testing.expectFmt(
"1:1: error: type 'u8' cannot represent value\n",
"{f}",
.{diag},
);
}
// Negative integer zero
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(i8, gpa, "-0", &diag, .{}));
try std.testing.expectFmt(
\\1:2: error: integer literal '-0' is ambiguous
\\1:2: note: use '0' for an integer zero
\\1:2: note: use '-0.0' for a floating-point signed zero
\\
, "{f}", .{diag});
}
// Negative integer zero casted to float
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(f32, gpa, "-0", &diag, .{}));
try std.testing.expectFmt(
\\1:2: error: integer literal '-0' is ambiguous
\\1:2: note: use '0' for an integer zero
\\1:2: note: use '-0.0' for a floating-point signed zero
\\
, "{f}", .{diag});
}
// Negative float 0 is allowed
try std.testing.expect(
std.math.isNegativeZero(try fromSlice(f32, gpa, "-0.0", null, .{})),
);
try std.testing.expect(std.math.isPositiveZero(try fromSlice(f32, gpa, "0.0", null, .{})));
// Double negation is not allowed
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(i8, gpa, "--2", &diag, .{}));
try std.testing.expectFmt(
"1:1: error: expected number or 'inf' after '-'\n",
"{f}",
.{diag},
);
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(f32, gpa, "--2.0", &diag, .{}),
);
try std.testing.expectFmt(
"1:1: error: expected number or 'inf' after '-'\n",
"{f}",
.{diag},
);
}
// Invalid int literal
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(u8, gpa, "0xg", &diag, .{}));
try std.testing.expectFmt("1:3: error: invalid digit 'g' for hex base\n", "{f}", .{diag});
}
// Notes on invalid int literal
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(u8, gpa, "0123", &diag, .{}));
try std.testing.expectFmt(
\\1:1: error: number '0123' has leading zero
\\1:1: note: use '0o' prefix for octal literals
\\
, "{f}", .{diag});
}
}
test "std.zon negative char" {
const gpa = std.testing.allocator;
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(f32, gpa, "-'a'", &diag, .{}));
try std.testing.expectFmt(
"1:1: error: expected number or 'inf' after '-'\n",
"{f}",
.{diag},
);
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(i16, gpa, "-'a'", &diag, .{}));
try std.testing.expectFmt(
"1:1: error: expected number or 'inf' after '-'\n",
"{f}",
.{diag},
);
}
}
test "std.zon parse float" {
const gpa = std.testing.allocator;
// Test decimals
try std.testing.expectEqual(@as(f16, 0.5), try fromSlice(f16, gpa, "0.5", null, .{}));
try std.testing.expectEqual(
@as(f32, 123.456),
try fromSlice(f32, gpa, "123.456", null, .{}),
);
try std.testing.expectEqual(
@as(f64, -123.456),
try fromSlice(f64, gpa, "-123.456", null, .{}),
);
try std.testing.expectEqual(@as(f128, 42.5), try fromSlice(f128, gpa, "42.5", null, .{}));
// Test whole numbers with and without decimals
try std.testing.expectEqual(@as(f16, 5.0), try fromSlice(f16, gpa, "5.0", null, .{}));
try std.testing.expectEqual(@as(f16, 5.0), try fromSlice(f16, gpa, "5", null, .{}));
try std.testing.expectEqual(@as(f32, -102), try fromSlice(f32, gpa, "-102.0", null, .{}));
try std.testing.expectEqual(@as(f32, -102), try fromSlice(f32, gpa, "-102", null, .{}));
// Test characters and negated characters
try std.testing.expectEqual(@as(f32, 'a'), try fromSlice(f32, gpa, "'a'", null, .{}));
try std.testing.expectEqual(@as(f32, 'z'), try fromSlice(f32, gpa, "'z'", null, .{}));
// Test big integers
try std.testing.expectEqual(
@as(f32, 36893488147419103231),
try fromSlice(f32, gpa, "36893488147419103231", null, .{}),
);
try std.testing.expectEqual(
@as(f32, -36893488147419103231),
try fromSlice(f32, gpa, "-36893488147419103231", null, .{}),
);
try std.testing.expectEqual(@as(f128, 0x1ffffffffffffffff), try fromSlice(
f128,
gpa,
"0x1ffffffffffffffff",
null,
.{},
));
try std.testing.expectEqual(@as(f32, 0x1ffffffffffffffff), try fromSlice(
f32,
gpa,
"0x1ffffffffffffffff",
null,
.{},
));
// Exponents, underscores
try std.testing.expectEqual(
@as(f32, 123.0E+77),
try fromSlice(f32, gpa, "12_3.0E+77", null, .{}),
);
// Hexadecimal
try std.testing.expectEqual(
@as(f32, 0x103.70p-5),
try fromSlice(f32, gpa, "0x103.70p-5", null, .{}),
);
try std.testing.expectEqual(
@as(f32, -0x103.70),
try fromSlice(f32, gpa, "-0x103.70", null, .{}),
);
try std.testing.expectEqual(
@as(f32, 0x1234_5678.9ABC_CDEFp-10),
try fromSlice(f32, gpa, "0x1234_5678.9ABC_CDEFp-10", null, .{}),
);
// inf, nan
try std.testing.expect(std.math.isPositiveInf(try fromSlice(f32, gpa, "inf", null, .{})));
try std.testing.expect(std.math.isNegativeInf(try fromSlice(f32, gpa, "-inf", null, .{})));
try std.testing.expect(std.math.isNan(try fromSlice(f32, gpa, "nan", null, .{})));
// Negative nan not allowed
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(f32, gpa, "-nan", &diag, .{}));
try std.testing.expectFmt(
"1:1: error: expected number or 'inf' after '-'\n",
"{f}",
.{diag},
);
}
// nan as int not allowed
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(i8, gpa, "nan", &diag, .{}));
try std.testing.expectFmt("1:1: error: expected type 'i8'\n", "{f}", .{diag});
}
// nan as int not allowed
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(i8, gpa, "nan", &diag, .{}));
try std.testing.expectFmt("1:1: error: expected type 'i8'\n", "{f}", .{diag});
}
// inf as int not allowed
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(i8, gpa, "inf", &diag, .{}));
try std.testing.expectFmt("1:1: error: expected type 'i8'\n", "{f}", .{diag});
}
// -inf as int not allowed
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(i8, gpa, "-inf", &diag, .{}));
try std.testing.expectFmt("1:1: error: expected type 'i8'\n", "{f}", .{diag});
}
// Bad identifier as float
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(f32, gpa, "foo", &diag, .{}));
try std.testing.expectFmt(
\\1:1: error: invalid expression
\\1:1: note: ZON allows identifiers 'true', 'false', 'null', 'inf', and 'nan'
\\1:1: note: precede identifier with '.' for an enum literal
\\
, "{f}", .{diag});
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(error.ParseZon, fromSlice(f32, gpa, "-foo", &diag, .{}));
try std.testing.expectFmt(
"1:1: error: expected number or 'inf' after '-'\n",
"{f}",
.{diag},
);
}
// Non float as float
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(f32, gpa, "\"foo\"", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected type 'f32'\n", "{f}", .{diag});
}
}
test "std.zon free on error" {
// Test freeing partially allocated structs
{
const Struct = struct {
x: []const u8,
y: []const u8,
z: bool,
};
try std.testing.expectError(error.ParseZon, fromSlice(Struct, std.testing.allocator,
\\.{
\\ .x = "hello",
\\ .y = "world",
\\ .z = "fail",
\\}
, null, .{}));
}
// Test freeing partially allocated tuples
{
const Struct = struct {
[]const u8,
[]const u8,
bool,
};
try std.testing.expectError(error.ParseZon, fromSlice(Struct, std.testing.allocator,
\\.{
\\ "hello",
\\ "world",
\\ "fail",
\\}
, null, .{}));
}
// Test freeing structs with missing fields
{
const Struct = struct {
x: []const u8,
y: bool,
};
try std.testing.expectError(error.ParseZon, fromSlice(Struct, std.testing.allocator,
\\.{
\\ .x = "hello",
\\}
, null, .{}));
}
// Test freeing partially allocated arrays
{
try std.testing.expectError(error.ParseZon, fromSlice(
[3][]const u8,
std.testing.allocator,
\\.{
\\ "hello",
\\ false,
\\ false,
\\}
,
null,
.{},
));
}
// Test freeing partially allocated slices
{
try std.testing.expectError(error.ParseZon, fromSlice(
[][]const u8,
std.testing.allocator,
\\.{
\\ "hello",
\\ "world",
\\ false,
\\}
,
null,
.{},
));
}
// We can parse types that can't be freed, as long as they contain no allocations, e.g. untagged
// unions.
try std.testing.expectEqual(
@as(f32, 1.5),
(try fromSlice(union { x: f32 }, std.testing.allocator, ".{ .x = 1.5 }", null, .{})).x,
);
// We can also parse types that can't be freed if it's impossible for an error to occur after
// the allocation, as is the case here.
{
const result = try fromSlice(
union { x: []const u8 },
std.testing.allocator,
".{ .x = \"foo\" }",
null,
.{},
);
defer free(std.testing.allocator, result.x);
try std.testing.expectEqualStrings("foo", result.x);
}
// However, if it's possible we could get an error requiring we free the value, but the value
// cannot be freed (e.g. untagged unions) then we need to turn off `free_on_error` for it to
// compile.
{
const S = struct {
union { x: []const u8 },
bool,
};
const result = try fromSlice(
S,
std.testing.allocator,
".{ .{ .x = \"foo\" }, true }",
null,
.{ .free_on_error = false },
);
defer free(std.testing.allocator, result[0].x);
try std.testing.expectEqualStrings("foo", result[0].x);
try std.testing.expect(result[1]);
}
// Again but for structs.
{
const S = struct {
a: union { x: []const u8 },
b: bool,
};
const result = try fromSlice(
S,
std.testing.allocator,
".{ .a = .{ .x = \"foo\" }, .b = true }",
null,
.{
.free_on_error = false,
},
);
defer free(std.testing.allocator, result.a.x);
try std.testing.expectEqualStrings("foo", result.a.x);
try std.testing.expect(result.b);
}
// Again but for arrays.
{
const S = [2]union { x: []const u8 };
const result = try fromSlice(
S,
std.testing.allocator,
".{ .{ .x = \"foo\" }, .{ .x = \"bar\" } }",
null,
.{
.free_on_error = false,
},
);
defer free(std.testing.allocator, result[0].x);
defer free(std.testing.allocator, result[1].x);
try std.testing.expectEqualStrings("foo", result[0].x);
try std.testing.expectEqualStrings("bar", result[1].x);
}
// Again but for slices.
{
const S = []union { x: []const u8 };
const result = try fromSlice(
S,
std.testing.allocator,
".{ .{ .x = \"foo\" }, .{ .x = \"bar\" } }",
null,
.{
.free_on_error = false,
},
);
defer std.testing.allocator.free(result);
defer free(std.testing.allocator, result[0].x);
defer free(std.testing.allocator, result[1].x);
try std.testing.expectEqualStrings("foo", result[0].x);
try std.testing.expectEqualStrings("bar", result[1].x);
}
}
test "std.zon vector" {
if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // https://github.com/ziglang/zig/issues/15330
const gpa = std.testing.allocator;
// Passing cases
try std.testing.expectEqual(
@Vector(0, bool){},
try fromSlice(@Vector(0, bool), gpa, ".{}", null, .{}),
);
try std.testing.expectEqual(
@Vector(3, bool){ true, false, true },
try fromSlice(@Vector(3, bool), gpa, ".{true, false, true}", null, .{}),
);
try std.testing.expectEqual(
@Vector(0, f32){},
try fromSlice(@Vector(0, f32), gpa, ".{}", null, .{}),
);
try std.testing.expectEqual(
@Vector(3, f32){ 1.5, 2.5, 3.5 },
try fromSlice(@Vector(3, f32), gpa, ".{1.5, 2.5, 3.5}", null, .{}),
);
try std.testing.expectEqual(
@Vector(0, u8){},
try fromSlice(@Vector(0, u8), gpa, ".{}", null, .{}),
);
try std.testing.expectEqual(
@Vector(3, u8){ 2, 4, 6 },
try fromSlice(@Vector(3, u8), gpa, ".{2, 4, 6}", null, .{}),
);
{
try std.testing.expectEqual(
@Vector(0, *const u8){},
try fromSlice(@Vector(0, *const u8), gpa, ".{}", null, .{}),
);
const pointers = try fromSlice(@Vector(3, *const u8), gpa, ".{2, 4, 6}", null, .{});
defer free(gpa, pointers);
try std.testing.expectEqualDeep(@Vector(3, *const u8){ &2, &4, &6 }, pointers);
}
{
try std.testing.expectEqual(
@Vector(0, ?*const u8){},
try fromSlice(@Vector(0, ?*const u8), gpa, ".{}", null, .{}),
);
const pointers = try fromSlice(@Vector(3, ?*const u8), gpa, ".{2, null, 6}", null, .{});
defer free(gpa, pointers);
try std.testing.expectEqualDeep(@Vector(3, ?*const u8){ &2, null, &6 }, pointers);
}
// Too few fields
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(@Vector(2, f32), gpa, ".{0.5}", &diag, .{}),
);
try std.testing.expectFmt(
"1:2: error: expected 2 vector elements; found 1\n",
"{f}",
.{diag},
);
}
// Too many fields
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(@Vector(2, f32), gpa, ".{0.5, 1.5, 2.5}", &diag, .{}),
);
try std.testing.expectFmt(
"1:2: error: expected 2 vector elements; found 3\n",
"{f}",
.{diag},
);
}
// Wrong type fields
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(@Vector(3, f32), gpa, ".{0.5, true, 2.5}", &diag, .{}),
);
try std.testing.expectFmt(
"1:8: error: expected type 'f32'\n",
"{f}",
.{diag},
);
}
// Wrong type
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(@Vector(3, u8), gpa, "true", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected type '@Vector(3, u8)'\n", "{f}", .{diag});
}
// Elements should get freed on error
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(@Vector(3, *u8), gpa, ".{1, true, 3}", &diag, .{}),
);
try std.testing.expectFmt("1:6: error: expected type 'u8'\n", "{f}", .{diag});
}
}
test "std.zon add pointers" {
const gpa = std.testing.allocator;
// Primitive with varying levels of pointers
{
const result = try fromSlice(*u32, gpa, "10", null, .{});
defer free(gpa, result);
try std.testing.expectEqual(@as(u32, 10), result.*);
}
{
const result = try fromSlice(**u32, gpa, "10", null, .{});
defer free(gpa, result);
try std.testing.expectEqual(@as(u32, 10), result.*.*);
}
{
const result = try fromSlice(***u32, gpa, "10", null, .{});
defer free(gpa, result);
try std.testing.expectEqual(@as(u32, 10), result.*.*.*);
}
// Primitive optional with varying levels of pointers
{
const some = try fromSlice(?*u32, gpa, "10", null, .{});
defer free(gpa, some);
try std.testing.expectEqual(@as(u32, 10), some.?.*);
const none = try fromSlice(?*u32, gpa, "null", null, .{});
defer free(gpa, none);
try std.testing.expectEqual(null, none);
}
{
const some = try fromSlice(*?u32, gpa, "10", null, .{});
defer free(gpa, some);
try std.testing.expectEqual(@as(u32, 10), some.*.?);
const none = try fromSlice(*?u32, gpa, "null", null, .{});
defer free(gpa, none);
try std.testing.expectEqual(null, none.*);
}
{
const some = try fromSlice(?**u32, gpa, "10", null, .{});
defer free(gpa, some);
try std.testing.expectEqual(@as(u32, 10), some.?.*.*);
const none = try fromSlice(?**u32, gpa, "null", null, .{});
defer free(gpa, none);
try std.testing.expectEqual(null, none);
}
{
const some = try fromSlice(*?*u32, gpa, "10", null, .{});
defer free(gpa, some);
try std.testing.expectEqual(@as(u32, 10), some.*.?.*);
const none = try fromSlice(*?*u32, gpa, "null", null, .{});
defer free(gpa, none);
try std.testing.expectEqual(null, none.*);
}
{
const some = try fromSlice(**?u32, gpa, "10", null, .{});
defer free(gpa, some);
try std.testing.expectEqual(@as(u32, 10), some.*.*.?);
const none = try fromSlice(**?u32, gpa, "null", null, .{});
defer free(gpa, none);
try std.testing.expectEqual(null, none.*.*);
}
// Pointer to an array
{
const result = try fromSlice(*[3]u8, gpa, ".{ 1, 2, 3 }", null, .{});
defer free(gpa, result);
try std.testing.expectEqual([3]u8{ 1, 2, 3 }, result.*);
}
// A complicated type with nested internal pointers and string allocations
{
const Inner = struct {
f1: *const ?*const []const u8,
f2: *const ?*const []const u8,
};
const Outer = struct {
f1: *const ?*const Inner,
f2: *const ?*const Inner,
};
const expected: Outer = .{
.f1 = &&.{
.f1 = &null,
.f2 = &&"foo",
},
.f2 = &null,
};
const found = try fromSlice(?*Outer, gpa,
\\.{
\\ .f1 = .{
\\ .f1 = null,
\\ .f2 = "foo",
\\ },
\\ .f2 = null,
\\}
, null, .{});
defer free(gpa, found);
try std.testing.expectEqualDeep(expected, found.?.*);
}
// Test that optional types are flattened correctly in errors
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(*const ?*const u8, gpa, "true", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected type '?u8'\n", "{f}", .{diag});
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(*const ?*const f32, gpa, "true", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected type '?f32'\n", "{f}", .{diag});
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(*const ?*const @Vector(3, u8), gpa, "true", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected type '?@Vector(3, u8)'\n", "{f}", .{diag});
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(*const ?*const bool, gpa, "10", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected type '?bool'\n", "{f}", .{diag});
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(*const ?*const struct { a: i32 }, gpa, "true", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected optional struct\n", "{f}", .{diag});
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(*const ?*const struct { i32 }, gpa, "true", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected optional tuple\n", "{f}", .{diag});
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(*const ?*const union { x: void }, gpa, "true", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected optional union\n", "{f}", .{diag});
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(*const ?*const [3]u8, gpa, "true", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected optional array\n", "{f}", .{diag});
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(?[3]u8, gpa, "true", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected optional array\n", "{f}", .{diag});
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(*const ?*const []u8, gpa, "true", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected optional array\n", "{f}", .{diag});
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(?[]u8, gpa, "true", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected optional array\n", "{f}", .{diag});
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(*const ?*const []const u8, gpa, "true", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected optional string\n", "{f}", .{diag});
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
try std.testing.expectError(
error.ParseZon,
fromSlice(*const ?*const enum { foo }, gpa, "true", &diag, .{}),
);
try std.testing.expectFmt("1:1: error: expected optional enum literal\n", "{f}", .{diag});
}
}
test "std.zon stop on node" {
const gpa = std.testing.allocator;
{
const Vec2 = struct {
x: Zoir.Node.Index,
y: f32,
};
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
const result = try fromSlice(Vec2, gpa, ".{ .x = 1.5, .y = 2.5 }", &diag, .{});
try std.testing.expectEqual(result.y, 2.5);
try std.testing.expectEqual(Zoir.Node{ .float_literal = 1.5 }, result.x.get(diag.zoir));
}
{
var diag: Diagnostics = .{};
defer diag.deinit(gpa);
const result = try fromSlice(Zoir.Node.Index, gpa, "1.23", &diag, .{});
try std.testing.expectEqual(Zoir.Node{ .float_literal = 1.23 }, result.get(diag.zoir));
}
}
|