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
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
|
package eval
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"io/fs"
"math"
"os"
"path"
"path/filepath"
"regexp"
"slices"
"sort"
"strconv"
"strings"
"unicode"
"unicode/utf8"
"github.com/BurntSushi/toml"
)
type builtinEntry struct {
name string
value Value
}
// makeBuiltinTable returns all known builtins as a name→Value map.
func makeBuiltinTable() map[string]Value {
reg := make(map[string]Value)
add := func(name string, v Value) { reg[name] = v }
// opN registers a builtin of arity N. There is deliberately no slice-taking
// variant: a primop that took []Value would force every caller's argument
// slice onto the heap, which is the whole thing PrimOpN exists to avoid.
op1 := func(name string, fn PrimOp1) { reg[name] = VPrimOp{Name: name, Impl: fn} }
op2 := func(name string, fn PrimOp2) { reg[name] = VPrimOp{Name: name, Impl: fn} }
op3 := func(name string, fn PrimOp3) { reg[name] = VPrimOp{Name: name, Impl: fn} }
// Constants — these appear in the WASM env as-is (no __ prefix).
add("true", VTrueSingleton)
add("false", VFalseSingleton)
add("null", VNullSingleton)
add("builtins", VNullSingleton) // placeholder; replaced by registerBuiltins
// Top-level names (no __ prefix in the WASM env).
op1("import", primImport)
op1("abort", primAbort)
op1("throw", primThrow)
op1("toString", primToString)
op1("isNull", primIsNull)
op1("break", primBreak)
op2("map", primMap)
op2("removeAttrs", primRemoveAttrs)
op1("derivationStrict", primDerivationStrict)
op1("baseNameOf", primBaseNameOf)
op1("dirOf", primDirOf)
op2("scopedImport", primScopedImport)
op1("fetchGit", notImplemented("fetchGit"))
op1("fetchMercurial", notImplemented("fetchMercurial"))
op1("fetchTarball", primFetchTarball)
op1("fromTOML", primFromTOML)
op1("placeholder", primPlaceholder)
// Primops registered with __ prefix in the WASM env.
// The attrset member name strips the prefix; the env slot keeps it.
op2("__sub", primSub)
op2("__mul", primMul)
op2("__div", primDiv)
op2("__lessThan", primLessThan)
op2("__findFile", primFindFile)
// __nixPath is handled specially in registerBuiltins as a VList constant.
op2("__add", primAdd)
op1("__addDrvOutputDependencies", primAddDrvOutputDependencies)
op2("__addErrorContext", primAddErrorContext)
op2("__all", primAll)
op2("__any", primAny)
op2("__appendContext", primAppendContext)
op1("__attrNames", primAttrNames)
op1("__attrValues", primAttrValues)
op2("__bitAnd", primBitAnd)
op2("__bitOr", primBitOr)
op2("__bitXor", primBitXor)
op2("__catAttrs", primCatAttrs)
op1("__ceil", primCeil)
op2("__compareVersions", primCompareVersions)
op1("__concatLists", primConcatLists)
op2("__concatMap", primConcatMap)
op2("__concatStringsSep", primConcatStringsSep)
op2("__deepSeq", primDeepSeq)
op2("__elem", primElem)
op2("__elemAt", primElemAt)
op1("__fetchurl", primFetchurl)
op2("__filter", primFilter)
op2("__filterSource", primFilterSource)
op1("__floor", primFloor)
op3("__foldl'", primFoldlStrict)
op1("__fromJSON", primFromJSON)
op1("__functionArgs", primFunctionArgs)
op2("__genList", primGenList)
op1("__genericClosure", primGenericClosure)
op2("__getAttr", primGetAttr)
op1("__getContext", primGetContext)
op1("__getEnv", primGetEnv)
op2("__groupBy", primGroupBy)
op2("__hasAttr", primHasAttr)
op1("__hasContext", primHasContext)
op2("__hashFile", primHashFile)
op2("__hashString", primHashString)
op1("__head", primHead)
op2("__intersectAttrs", primIntersectAttrs)
op1("__isAttrs", primIsAttrs)
op1("__isBool", primIsBool)
op1("__isFloat", primIsFloat)
op1("__isFunction", primIsFunction)
op1("__isInt", primIsInt)
op1("__isList", primIsList)
op1("__isPath", primIsPath)
op1("__isString", primIsString)
op1("__length", primLength)
op1("__listToAttrs", primListToAttrs)
op2("__mapAttrs", primMapAttrs)
op2("__match", primMatch)
op1("__parseDrvName", primParseDrvName)
op2("__partition", primPartition)
op1("__path", primPath)
// pathExists / readDir / readFileType registered in the block above
op1("__pathExists", primPathExists)
op1("__readDir", primReadDir)
op1("__readFile", primReadFile)
op1("__readFileType", primReadFileType)
// readFileType now registered above alongside readDir/pathExists
op3("__replaceStrings", primReplaceStrings)
op2("__seq", primSeq)
op2("__sort", primSort)
op2("__split", primSplit)
op1("__splitVersion", primSplitVersion)
op1("__storePath", notImplemented("storePath"))
op1("__stringLength", primStringLength)
op3("__substring", primSubstring)
op1("__tail", primTail)
op2("__toFile", primToFile)
op1("__toJSON", primToJSON)
op1("__toPath", primToPath)
op1("__toXML", primToXML)
op2("__trace", primTrace)
op2("__traceVerbose", primTrace) // same as trace for now
op1("__tryEval", primTryEval)
op1("__typeOf", primTypeOf)
op1("__unsafeDiscardOutputDependency", primUnsafeDiscardOutputDependency)
op1("__unsafeDiscardStringContext", primUnsafeDiscardStringContext)
op2("__unsafeGetAttrPos", primUnsafeGetAttrPos)
op2("__warn", primWarn)
op2("__zipAttrsWith", primZipAttrsWith)
// Additional names seen in the WASM builtin list.
// __currentSystem is handled specially in registerBuiltins as a VString constant.
op1("__currentTime", notImplemented("currentTime"))
// __langVersion, __nixVersion, __storeDir are constants set in registerBuiltins.
// Register null placeholders here so the table entry exists; registerBuiltins
// replaces them with the real values in displacement order.
add("__langVersion", VNullSingleton) // placeholder; replaced by registerBuiltins
add("__nixVersion", VNullSingleton) // placeholder; replaced by registerBuiltins
add("__storeDir", VNullSingleton) // placeholder; replaced by registerBuiltins
op1("fetchTree", notImplemented("fetchTree"))
op1("parseFlakeRef", primParseFlakeRef)
op1("flakeRefToString", primFlakeRefToString)
op1("getFlake", notImplemented("getFlake"))
op1("getContext", primGetContext)
op2("appendContext", primAppendContext)
return reg
}
// registerBuiltins constructs the base environment in the order given by names.
// names must be the displacement-ordered list from nix_builtin_names (i.e., the
// WASM parser's base env order). This ensures ExprVar.Displ values are correct.
func registerBuiltins(s *EvalState, names []string) *Env {
table := makeBuiltinTable()
env := newEnv(s, nil, len(names))
for i, name := range names {
s.Symbols.Create(name) // intern symbol in displacement order
switch name {
case "__currentSystem":
// currentSystem is a string constant in C++, not a primop.
sys := s.CurrentSystem
if sys == "" {
sys = "x86_64-linux"
}
env.Values[i] = VString{V: sys}
case "__nixPath":
// __nixPath is a list constant built from EvalState.SearchPath.
env.Values[i] = buildNixPathValue(s)
case "__nixVersion":
// nixVersion is a string constant matching the Lix/Nix version.
// nixpkgs requires >= "2.18"; we report a compatible version.
env.Values[i] = VString{V: "2.90.0-gonix"}
case "__langVersion":
// langVersion is an integer constant (6 for nix 2.x / lix).
env.Values[i] = VInt{V: 6}
case "__storeDir":
// storeDir is the store directory path string.
env.Values[i] = VString{V: "/nix/store"}
case "derivation":
// derivation is a lambda produced by evaluating derivation.nix.
// We lazily initialise it on first call via a VPrimOp shim.
env.Values[i] = VPrimOp{Name: "derivation", Impl: PrimOp1(func(s *EvalState, a Value) (Value, error) {
if s.derivationFn == nil {
fn, err := initDerivationBuiltin(s)
if err != nil {
return nil, err
}
s.derivationFn = fn
}
return s.callFunction(s.derivationFn, []Value{a}, NoPosIdx)
})}
default:
if v, ok := table[name]; ok {
env.Values[i] = v
} else {
env.Values[i] = VPrimOp{Name: name, Impl: PrimOp1(notImplemented(name))}
}
}
}
// Build the builtins attrset. Names with "__" prefix are stored in the
// attrset with the prefix stripped (matching C++ addPrimOp behavior).
// The "builtins" slot itself and top-level names (no __ prefix) are
// excluded from the attrset since they're not accessible as builtins.X.
builtinsBindings := newBindings(s, len(names))
for i, name := range names {
attrName := name
if strings.HasPrefix(name, "__") {
attrName = name[2:] // strip __ prefix for attrset membership
}
sym := s.Symbols.Create(attrName)
builtinsBindings.attrs = append(builtinsBindings.attrs, Attr{
Name: sym,
Value: env.Values[i],
})
}
builtinsBindings.Sort()
// Inject extra builtins that are not in the WASM displacement list
// (e.g. experimental-feature builtins like parseFlakeRef/flakeRefToString).
// These are added directly to the attrset so builtins.X works, even though
// they have no env slot (they can't be referenced as bare names).
for name, val := range table {
// Skip names already covered by the WASM list.
attrName := name
if strings.HasPrefix(name, "__") {
attrName = name[2:]
}
sym := s.Symbols.Create(attrName)
if builtinsBindings.Get(sym) == nil {
builtinsBindings.attrs = append(builtinsBindings.attrs, Attr{Name: sym, Value: val})
}
}
builtinsBindings.Sort()
// Replace the "builtins" placeholder slot with the attrset.
builtinsSym := s.Symbols.Create("builtins")
builtinsVal := VAttrs{Bindings: builtinsBindings}
for i, name := range names {
if name == "builtins" {
env.Values[i] = builtinsVal
break
}
}
// Also update the attrset's self-entry.
if attr := builtinsBindings.Get(builtinsSym); attr != nil {
attr.Value = builtinsVal
}
return env
}
// notImplemented returns a primop that always errors.
func notImplemented(name string) PrimOp1 {
return func(_ *EvalState, _ Value) (Value, error) {
return nil, evalErrorf("builtin '%s' is not yet implemented", name)
}
}
// ---------------------------------------------------------------------------
// fetchTarball / fetchurl — fixed-output fetchers
// ---------------------------------------------------------------------------
//
// Both builtins follow the same pattern as C++ fetch() in fetchTree.cc:
//
// 1. Parse args: url (string or attrset with url/sha256/name keys).
// 2. If sha256 is provided, compute the expected fixed-output store path.
// 3. If it already exists on disk, return it immediately (fast path).
// 4. Otherwise, ask the Store (via Realizer.EnsureRealized) to substitute
// it from a binary cache. We never download anything ourselves.
// 5. Return the store path as a VPath.
//
// fetchTarball uses recursive (NAR) ingestion; fetchurl uses flat ingestion.
// parseFetchArgs parses the argument to fetchTarball or fetchurl.
// Returns (url, name, sha256String).
// For a plain string argument, name defaults to baseNameOf(url).
func parseFetchArgs(s *EvalState, args []Value, who, defaultName string) (url, name, sha256 string, err error) {
v := args[0]
if err = s.forceValue(&v, NoPosIdx); err != nil {
return
}
name = defaultName
switch t := v.(type) {
case VString:
url = t.V
case VPath:
url = t.V
case VAttrs:
urlSym := s.Symbols.Create("url")
nameSym := s.Symbols.Create("name")
sha256Sym := s.Symbols.Create("sha256")
if a := t.Bindings.Get(urlSym); a != nil {
uv := a.Value
if err = s.forceValue(&uv, NoPosIdx); err != nil {
return
}
str, _, ferr := s.coerceToString(&uv, CoerceStrict)
if ferr != nil {
err = evalErrorf("builtins.%s: url: %v", who, ferr)
return
}
url = str
}
if a := t.Bindings.Get(nameSym); a != nil {
nv := a.Value
if err = s.forceValue(&nv, NoPosIdx); err != nil {
return
}
str, _, ferr := s.coerceToString(&nv, CoerceStrict)
if ferr != nil {
err = evalErrorf("builtins.%s: name: %v", who, ferr)
return
}
name = str
}
if a := t.Bindings.Get(sha256Sym); a != nil {
hv := a.Value
if err = s.forceValue(&hv, NoPosIdx); err != nil {
return
}
str, _, ferr := s.coerceToString(&hv, CoerceStrict)
if ferr != nil {
err = evalErrorf("builtins.%s: sha256: %v", who, ferr)
return
}
sha256 = str
}
default:
err = evalErrorf("builtins.%s: argument must be a string or attrset, got %s", who, valueType(v))
return
}
if url == "" {
err = evalErrorf("builtins.%s: 'url' argument required", who)
return
}
if name == "" {
// baseNameOf(url)
idx := strings.LastIndexAny(url, "/")
if idx >= 0 {
name = url[idx+1:]
} else {
name = url
}
// strip query string
if q := strings.IndexByte(name, '?'); q >= 0 {
name = name[:q]
}
}
return
}
// ensureFixedOutputPath computes the fixed-output store path for the given
// hash and ensures it exists, first trying the Fetcher interface (which
// synthesizes a builtin:fetchurl derivation and asks the daemon to build it),
// and falling back to Realizer.EnsureRealized (substitution) if no Fetcher.
// recursive=true for fetchTarball (NAR/recursive hash), false for flat hash.
func ensureFixedOutputPath(s *EvalState, who, url, name, sha256Str string, recursive bool) (string, error) {
if sha256Str == "" {
return "", evalErrorf("builtins.%s: 'sha256' argument required in pure mode", who)
}
// Parse the sha256 — accepts nix-base32, hex, or SRI format.
_, hashBytes, err := ParseHashString(sha256Str, "sha256")
if err != nil {
return "", evalErrorf("builtins.%s: invalid sha256 %q: %v", who, sha256Str, err)
}
ingestion := "flat"
if recursive {
ingestion = "recursive"
}
storePath := MakeFixedOutputPathGeneric(name, "sha256", ingestion, hashBytes)
// Fast path: already on disk.
if _, oerr := fs.Stat(s.FS, fsPath(storePath)); oerr == nil {
return storePath, nil
}
// Not on disk — use the Fetcher interface (DaemonStore synthesizes a
// builtin:fetchurl drv and builds it via op 36).
if f, ok := s.Store.(Fetcher); ok {
var ferr error
if recursive {
ferr = f.FetchTarball(storePath, url, name, hashBytes)
} else {
ferr = f.FetchURL(storePath, url, name, hashBytes)
}
if ferr != nil {
return "", evalErrorf("builtins.%s: %v", who, ferr)
}
return storePath, nil
}
// Fallback: try substitution via Realizer (works if path is in a cache).
if r, ok := s.Store.(Realizer); ok {
if rerr := r.EnsureRealized(storePath); rerr != nil {
return "", evalErrorf("builtins.%s: %v", who, rerr)
}
return storePath, nil
}
return "", evalErrorf("builtins.%s: path %s not in store and no daemon configured", who, storePath)
}
func primFetchTarball(s *EvalState, a0 Value) (Value, error) {
url, name, sha256Str, err := parseFetchArgs(s, []Value{a0}, "fetchTarball", "source")
if err != nil {
return nil, err
}
storePath, err := ensureFixedOutputPath(s, "fetchTarball", url, name, sha256Str, true)
if err != nil {
return nil, err
}
return VPath{V: storePath}, nil
}
func primFetchurl(s *EvalState, a0 Value) (Value, error) {
url, name, sha256Str, err := parseFetchArgs(s, []Value{a0}, "fetchurl", "")
if err != nil {
return nil, err
}
storePath, err := ensureFixedOutputPath(s, "fetchurl", url, name, sha256Str, false)
if err != nil {
return nil, err
}
return VPath{V: storePath}, nil
}
// --- arithmetic ---
func primAdd(s *EvalState, a0, a1 Value) (Value, error) {
a, b := a0, a1
if err := s.forceValue(&a, NoPosIdx); err != nil {
return nil, err
}
if err := s.forceValue(&b, NoPosIdx); err != nil {
return nil, err
}
return numericBinOpErr(a, b, "addition",
func(x, y int64) (Value, error) {
if intAddOverflows(x, y) {
return nil, evalErrorf("integer overflow in adding %d + %d", x, y)
}
return VInt{V: x + y}, nil
},
func(x, y float64) Value { return VFloat{V: x + y} },
)
}
func primSub(s *EvalState, a0, a1 Value) (Value, error) {
a, b := a0, a1
if err := s.forceValue(&a, NoPosIdx); err != nil {
return nil, err
}
if err := s.forceValue(&b, NoPosIdx); err != nil {
return nil, err
}
return numericBinOpErr(a, b, "subtraction",
func(x, y int64) (Value, error) {
if intAddOverflows(x, -y) {
return nil, evalErrorf("integer overflow in subtracting %d - %d", x, y)
}
return VInt{V: x - y}, nil
},
func(x, y float64) Value { return VFloat{V: x - y} },
)
}
func primMul(s *EvalState, a0, a1 Value) (Value, error) {
a, b := a0, a1
if err := s.forceValue(&a, NoPosIdx); err != nil {
return nil, err
}
if err := s.forceValue(&b, NoPosIdx); err != nil {
return nil, err
}
return numericBinOpErr(a, b, "multiplication",
func(x, y int64) (Value, error) {
if intMulOverflows(x, y) {
return nil, evalErrorf("integer overflow in multiplying %d * %d", x, y)
}
return VInt{V: x * y}, nil
},
func(x, y float64) Value { return VFloat{V: x * y} },
)
}
func primDiv(s *EvalState, a0, a1 Value) (Value, error) {
a, b := a0, a1
if err := s.forceValue(&a, NoPosIdx); err != nil {
return nil, err
}
if err := s.forceValue(&b, NoPosIdx); err != nil {
return nil, err
}
return numericBinOpErr(a, b, "division",
func(x, y int64) (Value, error) {
if y == 0 {
return nil, evalErrorf("division by zero")
}
// INT64_MIN / -1 overflows
if x == -9223372036854775808 && y == -1 {
return nil, evalErrorf("integer overflow in dividing %d / %d", x, y)
}
return VInt{V: x / y}, nil
},
func(x, y float64) Value { return VFloat{V: x / y} },
)
}
// primLessThan is builtins.lessThan, i.e. the `<` operator: the parser
// desugars a < b, a > b, a <= b and a >= b all into calls to it.
//
// It is exactly C++ prim_lessThan (primops.cc:2807) — force both operands,
// then hand them to the shared ordering. The ordering lives in compareValues
// because genericClosure needs the same relation; see its doc comment for why
// an ordering is not eqValues.
//
// This used to be a hand-written switch that recursed into itself twice per
// list element (once for a<b, once for b<a) and had no path case. Both were
// divergences: `lessThan ./a ./b` errored where nix returns true, and
// `[ {} ] < [ {} ]` errored where nix returns false, because asking the
// ordering about two sets raises even when eqValues would have called them
// equal and moved on.
func primLessThan(s *EvalState, a0, a1 Value) (Value, error) {
lt, err := s.compareValues(a0, a1, NoPosIdx, "")
if err != nil {
return nil, err
}
if lt {
return VTrueSingleton, nil
}
return VFalseSingleton, nil
}
// numericBinOpErr is like numericBinOp but the intOp can return an error.
func numericBinOpErr(a, b Value, opName string,
intOp func(int64, int64) (Value, error),
floatOp func(float64, float64) Value,
) (Value, error) {
toFloat := func(v Value) (float64, bool) {
switch n := v.(type) {
case VInt:
return float64(n.V), true
case VFloat:
return n.V, true
}
return 0, false
}
toInt := func(v Value) (int64, bool) {
n, ok := v.(VInt)
return n.V, ok
}
ai, aIsInt := toInt(a)
bi, bIsInt := toInt(b)
if aIsInt && bIsInt {
return intOp(ai, bi)
}
af, aIsNum := toFloat(a)
bf, bIsNum := toFloat(b)
if aIsNum && bIsNum {
return floatOp(af, bf), nil
}
return nil, evalErrorf("arithmetic %s requires numeric operands, got %s and %s",
opName, valueType(a), valueType(b))
}
func numericBinOp(a, b Value, opName string,
intOp func(int64, int64) Value,
floatOp func(float64, float64) Value,
) (Value, error) {
return numericBinOpErr(a, b, opName,
func(x, y int64) (Value, error) { return intOp(x, y), nil },
floatOp,
)
}
// --- type predicates ---
func primIsNull(s *EvalState, a0 Value) (Value, error) {
v := a0
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
if _, ok := v.(VNull); ok {
return VTrueSingleton, nil
}
return VFalseSingleton, nil
}
func primIsBool(s *EvalState, a0 Value) (Value, error) {
v := a0
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
if _, ok := v.(VBool); ok {
return VTrueSingleton, nil
}
return VFalseSingleton, nil
}
func primIsInt(s *EvalState, a0 Value) (Value, error) {
v := a0
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
if _, ok := v.(VInt); ok {
return VTrueSingleton, nil
}
return VFalseSingleton, nil
}
func primIsFloat(s *EvalState, a0 Value) (Value, error) {
v := a0
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
if _, ok := v.(VFloat); ok {
return VTrueSingleton, nil
}
return VFalseSingleton, nil
}
func primIsString(s *EvalState, a0 Value) (Value, error) {
v := a0
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
if _, ok := v.(VString); ok {
return VTrueSingleton, nil
}
return VFalseSingleton, nil
}
func primIsPath(s *EvalState, a0 Value) (Value, error) {
v := a0
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
if _, ok := v.(VPath); ok {
return VTrueSingleton, nil
}
return VFalseSingleton, nil
}
func primIsList(s *EvalState, a0 Value) (Value, error) {
v := a0
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
if _, ok := v.((*VList)); ok {
return VTrueSingleton, nil
}
return VFalseSingleton, nil
}
func primIsAttrs(s *EvalState, a0 Value) (Value, error) {
v := a0
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
if _, ok := v.(VAttrs); ok {
return VTrueSingleton, nil
}
return VFalseSingleton, nil
}
func primIsFunction(s *EvalState, a0 Value) (Value, error) {
v := a0
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
switch v.(type) {
case *VLambda, VPrimOp, VPrimOpApp:
return VTrueSingleton, nil
}
return VFalseSingleton, nil
}
func primTypeOf(s *EvalState, a0 Value) (Value, error) {
v := a0
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
var name string
switch v.(type) {
case VInt:
name = "int"
case VFloat:
name = "float"
case VBool:
name = "bool"
case VString:
name = "string"
case VPath:
name = "path"
case VNull:
name = "null"
case VAttrs:
name = "set"
case *VList:
name = "list"
case *VLambda, VPrimOp, VPrimOpApp:
name = "lambda"
default:
name = "unknown"
}
return VString{V: name}, nil
}
// --- control flow ---
func primSeq(s *EvalState, a0, a1 Value) (Value, error) {
e := a0
if err := s.forceValue(&e, NoPosIdx); err != nil {
return nil, err
}
v := a1
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
return v, nil
}
func primDeepSeq(s *EvalState, a0, a1 Value) (Value, error) {
e := a0
if err := deepForce(s, &e); err != nil {
return nil, err
}
v := a1
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
return v, nil
}
func deepForce(s *EvalState, vp *Value) error {
return deepForceWithSeen(s, vp, make(map[*Bindings]bool), make(map[*VList]bool))
}
func deepForceWithSeen(s *EvalState, vp *Value, seenAttrs map[*Bindings]bool, seenLists map[*VList]bool) error {
if err := s.forceValue(vp, NoPosIdx); err != nil {
return err
}
switch v := (*vp).(type) {
case *VList:
if seenLists[v] {
return nil
}
seenLists[v] = true
for i := range v.Elems {
if err := deepForceWithSeen(s, &v.Elems[i], seenAttrs, seenLists); err != nil {
return err
}
}
delete(seenLists, v)
case VAttrs:
if seenAttrs[v.Bindings] {
return nil
}
seenAttrs[v.Bindings] = true
all := v.Bindings.All()
for i := range all {
if err := deepForceWithSeen(s, &all[i].Value, seenAttrs, seenLists); err != nil {
return err
}
}
delete(seenAttrs, v.Bindings)
}
return nil
}
func primTrace(s *EvalState, a0, a1 Value) (Value, error) {
// Just return the second arg; tracing to stderr is optional.
v := a1
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
return v, nil
}
func primWarn(s *EvalState, a0, a1 Value) (Value, error) {
msg := a0
if err := s.forceValue(&msg, NoPosIdx); err != nil {
return nil, err
}
if _, ok := msg.(VString); !ok {
return nil, evalErrorf("builtins.warn: expected a string, got %s", valueType(msg))
}
return primTrace(s, a0, a1)
}
func primBreak(_ *EvalState, a0 Value) (Value, error) {
return a0, nil
}
func primAbort(s *EvalState, a0 Value) (Value, error) {
v := a0
msg, _, err := s.coerceToString(&v, CoerceStrict, false)
if err != nil {
return nil, err
}
return nil, evalErrorf("evaluation aborted with the following error message: '%s'", msg)
}
func primThrow(s *EvalState, a0 Value) (Value, error) {
v := a0
msg, _, err := s.coerceToString(&v, CoerceStrict, false)
if err != nil {
return nil, err
}
return nil, &ThrownError{Msg: msg}
}
// ThrownError is a Nix-level throw, catchable by tryEval.
type ThrownError struct{ Msg string }
func (e *ThrownError) Error() string { return e.Msg }
func primTryEval(s *EvalState, a0 Value) (Value, error) {
v := a0
err := s.forceValue(&v, NoPosIdx)
sym_success := s.Symbols.Create("success")
sym_value := s.Symbols.Create("value")
if err != nil {
b := newBindingsOf(s,
Attr{Name: sym_success, Value: VFalseSingleton},
Attr{Name: sym_value, Value: VFalseSingleton},
)
b.Sort()
return VAttrs{Bindings: b}, nil
}
b := newBindingsOf(s,
Attr{Name: sym_success, Value: VTrueSingleton},
Attr{Name: sym_value, Value: v},
)
b.Sort()
return VAttrs{Bindings: b}, nil
}
func primAddErrorContext(_ *EvalState, a0, a1 Value) (Value, error) {
_ = a0
return a1, nil
}
// --- math ---
// floatToIntChecked converts a float to int64, returning (value, true) if the
// conversion is exact and in range, or (0, false) if it would overflow/lose data.
// Mirrors C++ floatToIntChecked which uses llrint + FE_ALL_EXCEPT.
func floatToIntChecked(f float64) (int64, bool) {
if math.IsNaN(f) || math.IsInf(f, 0) {
return 0, false
}
// float64 can exactly represent integers up to 2^53; beyond that check range.
const maxExact = float64(1 << 53)
if f > maxExact || f < -maxExact {
// Check representable range for int64.
// math.MaxInt64 rounds up to 2^63 as float64, so use < not <=.
if f >= float64(math.MaxInt64+1) || f < float64(math.MinInt64) {
return 0, false
}
}
return int64(f), true
}
// floorCeilInt applies fn (math.Floor or math.Ceil) to an integer argument,
// detecting the "corrupt integer" case where float precision changes the value.
// Mirrors C++ floorCeil with the FloorCeilCorruptIntegers deprecation check.
func floorCeilInt(which string, fn func(float64) float64, orig int64) (Value, error) {
result := fn(float64(orig))
i, ok := floatToIntChecked(result)
if !ok {
return nil, evalErrorf("builtins.%s: result %g is out of range for Nix integer", which, result)
}
if i != orig {
return nil, evalErrorf(
"builtins.%s was corrupting your integer (was %d, became %d) in previous "+
"versions due to a historical Nix bug. "+
"To suppress this error, use --extra-deprecated-features floor-ceil-corrupt-integers",
which, orig, i,
)
}
return VInt{V: orig}, nil
}
func primCeil(s *EvalState, a0 Value) (Value, error) {
v := a0
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
switch n := v.(type) {
case VInt:
return floorCeilInt("ceil", math.Ceil, n.V)
case VFloat:
result := math.Ceil(n.V)
i, ok := floatToIntChecked(result)
if !ok {
return nil, evalErrorf("builtins.ceil: result %g is out of range for Nix integer", result)
}
return VInt{V: i}, nil
}
return nil, evalErrorf("builtins.ceil: expected a number")
}
func primFloor(s *EvalState, a0 Value) (Value, error) {
v := a0
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
switch n := v.(type) {
case VInt:
return floorCeilInt("floor", math.Floor, n.V)
case VFloat:
result := math.Floor(n.V)
i, ok := floatToIntChecked(result)
if !ok {
return nil, evalErrorf("builtins.floor: result %g is out of range for Nix integer", result)
}
return VInt{V: i}, nil
}
return nil, evalErrorf("builtins.floor: expected a number")
}
// --- list operations ---
func primLength(s *EvalState, a0 Value) (Value, error) {
v := a0
elems, err := s.forceList(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
return VInt{V: int64(len(elems))}, nil
}
func primHead(s *EvalState, a0 Value) (Value, error) {
v := a0
elems, err := s.forceList(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
if len(elems) == 0 {
return nil, evalErrorf("builtins.head: empty list")
}
r := elems[0]
if err := s.forceValue(&r, NoPosIdx); err != nil {
return nil, err
}
return r, nil
}
func primTail(s *EvalState, a0 Value) (Value, error) {
v := a0
elems, err := s.forceList(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
if len(elems) == 0 {
return nil, evalErrorf("builtins.tail: empty list")
}
return newList(s, elems[1:]), nil
}
func primElemAt(s *EvalState, a0, a1 Value) (Value, error) {
v := a0
elems, err := s.forceList(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
idx, err := s.forceInt(&a1, NoPosIdx)
if err != nil {
return nil, err
}
if idx < 0 || int(idx) >= len(elems) {
return nil, evalErrorf("builtins.elemAt: index %d out of bounds", idx)
}
r := elems[idx]
if err := s.forceValue(&r, NoPosIdx); err != nil {
return nil, err
}
return r, nil
}
func primElem(s *EvalState, a0, a1 Value) (Value, error) {
needle := a0
v := a1
elems, err := s.forceList(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
for _, e := range elems {
eq, err := s.eqValues(needle, e, NoPosIdx)
if err != nil {
return nil, err
}
if eq {
return VTrueSingleton, nil
}
}
return VFalseSingleton, nil
}
func primMap(s *EvalState, a0, a1 Value) (Value, error) {
fn := a0
v := a1
elems, err := s.forceList(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
if len(elems) == 0 {
// C++ returns *args[1] verbatim, preserving pointer identity.
return v, nil
}
// Lazy map: create thunks for each element, matching C++ prim_map which
// creates VApp values. Elements are only evaluated when accessed.
result := make([]Value, len(elems))
for i, e := range elems {
elem := e // capture for closure
result[i] = newCallThunk1(fn, elem)
}
s.Stats.NrCallThunks += uint64(len(elems))
return newList(s, result), nil
}
// primFilter ports C++ prim_filter (primops.cc:2385), including its `same`
// tracking: when the predicate accepts every element, the *original* list value
// is returned rather than a fresh copy.
//
// That is not only about skipping an allocation. eqValues short-circuits on
// *VList pointer identity (coerce.go), so a copy that is equal but not
// identical turns an O(1) comparison into a deep walk. mergeBindings relies on
// the same property for attrsets and documents it at length.
func primFilter(s *EvalState, a0, a1 Value) (Value, error) {
fn := a0
v := a1
elems, err := s.forceList(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
if len(elems) == 0 {
return v, nil
}
var result []Value
same := true
for _, e := range elems {
r, err := s.callFunction(fn, []Value{e}, NoPosIdx)
if err != nil {
return nil, err
}
b, err := s.forceBool(&r, NoPosIdx)
if err != nil {
return nil, err
}
if b {
result = append(result, e)
} else {
same = false
}
}
if same {
return v, nil
}
return newList(s, result), nil
}
func primFoldlStrict(s *EvalState, a0, a1, a2 Value) (Value, error) {
fn := a0
acc := a1
v := a2
elems, err := s.forceList(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
for _, e := range elems {
acc, err = s.callFunction(fn, []Value{acc, e}, NoPosIdx)
if err != nil {
return nil, err
}
if err := s.forceValue(&acc, NoPosIdx); err != nil {
return nil, err
}
}
return acc, nil
}
// primConcatLists ports C++ prim_concatLists via EvalState::concatLists
// (eval.cc:1392), which forces every sublist first and then, if exactly one of
// them accounts for the whole result, returns *that list value* rather than
// building a copy of it. `concatLists [ [] xs [] ]` is the common shape.
//
// The forcing has to happen for *all* sublists before the fast path is taken,
// or a type error in a later empty-looking element would go unreported.
func primConcatLists(s *EvalState, a0 Value) (Value, error) {
// The second of exactly two NrListConcats sites, because C++ has one
// function (EvalState::concatLists, eval.cc:1394) reached from two places:
// the `++` operator and this primop. Counting only the operator would miss
// every builtins.concatLists — and concatMap, which looks like it belongs
// here, deliberately does *not* count: prim_concatMap builds its result
// with newList directly and never enters concatLists (primops.cc:2649).
s.Stats.NrListConcats++
v := a0
outer, err := s.forceList(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
total := 0
var nonEmpty Value
for i := range outer {
elems, err := s.forceList(&outer[i], NoPosIdx, "")
if err != nil {
return nil, err
}
total += len(elems)
if len(elems) > 0 {
nonEmpty = outer[i]
}
}
if nonEmpty != nil {
if l, ok := nonEmpty.(*VList); ok && len(l.Elems) == total {
return nonEmpty, nil
}
}
result := make([]Value, 0, total)
for i := range outer {
l, ok := outer[i].(*VList)
if !ok {
return nil, evalErrorf("builtins.concatLists: expected a list")
}
result = append(result, l.Elems...)
}
return newList(s, result), nil
}
func primConcatMap(s *EvalState, a0, a1 Value) (Value, error) {
fn := a0
v := a1
elems, err := s.forceList(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
var result []Value
for _, e := range elems {
r, err := s.callFunction(fn, []Value{e}, NoPosIdx)
if err != nil {
return nil, err
}
inner, err := s.forceList(&r, NoPosIdx, "")
if err != nil {
return nil, err
}
result = append(result, inner...)
}
return newList(s, result), nil
}
func primGenList(s *EvalState, a0, a1 Value) (Value, error) {
fn := a0
n, err := s.forceInt(&a1, NoPosIdx)
if err != nil {
return nil, err
}
if n < 0 {
return nil, evalErrorf("builtins.genList: negative length")
}
if n > 1<<24 { // 16M elements — same guard as C++ Nix
return nil, evalErrorf("builtins.genList: length %d exceeds maximum", n)
}
// Lazy genList: create thunks for each element, matching C++ prim_genList
// which creates VApp values. Elements are only evaluated when accessed.
result := make([]Value, n)
for i := int64(0); i < n; i++ {
idx := VInt{V: i}
result[i] = newCallThunk1(fn, idx)
}
s.Stats.NrCallThunks += uint64(n)
return newList(s, result), nil
}
func primAll(s *EvalState, a0, a1 Value) (Value, error) {
fn := a0
v := a1
elems, err := s.forceList(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
for _, e := range elems {
r, err := s.callFunction(fn, []Value{e}, NoPosIdx)
if err != nil {
return nil, err
}
b, err := s.forceBool(&r, NoPosIdx)
if err != nil {
return nil, err
}
if !b {
return VFalseSingleton, nil
}
}
return VTrueSingleton, nil
}
func primAny(s *EvalState, a0, a1 Value) (Value, error) {
fn := a0
v := a1
elems, err := s.forceList(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
for _, e := range elems {
r, err := s.callFunction(fn, []Value{e}, NoPosIdx)
if err != nil {
return nil, err
}
b, err := s.forceBool(&r, NoPosIdx)
if err != nil {
return nil, err
}
if b {
return VTrueSingleton, nil
}
}
return VFalseSingleton, nil
}
// primSort is a port of C++ prim_sort (primops.cc:2538).
//
// This used to be a hand-rolled insertion sort, which is O(n²): sorting 4000
// elements took 6.3s against nix's 0.07s, and the gap grows without bound.
// C++ uses std::stable_sort, so the fix is to use the standard library here
// too — but three details of the C++ version have to come with it, because
// they are observable.
//
// 1. Elements are forced *before* sorting, not lazily during comparison.
// `builtins.length (builtins.sort (a: b: a < b) [ (throw "boom") ])`
// errors in C++ nix and used to evaluate to 1 here.
// 2. An empty list is returned unchanged, preserving pointer identity (which
// eqValues short-circuits on).
// 3. The sort must be *stable*. C++ picks stable_sort deliberately — its
// comment notes std::sort can segfault when the comparator is not a strict
// weak ordering, which user-supplied Nix comparators frequently are not.
// Go's sort will not crash, but an unstable one would reorder equal
// elements and so change output and derivation hashes.
//
// Note that slices.SortStableFunc only ever tests `cmp(...) < 0`, so returning
// -1/0 calls the user's predicate exactly once per comparison, as C++ does. A
// three-way comparator would call it twice, doubling both the cost and the
// user-visible function calls.
func primSort(s *EvalState, a0, a1 Value) (Value, error) {
fn := a0
v := a1
elems, err := s.forceList(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
if len(elems) == 0 {
// C++ returns *a1 verbatim for the empty list.
return v, nil
}
sorted := make([]Value, len(elems))
copy(sorted, elems)
// C++ forces every element into the new list before sorting, so an element
// that throws does so even if the comparator would never have looked at it.
for i := range sorted {
if err := s.forceValue(&sorted[i], NoPosIdx); err != nil {
return nil, err
}
}
// The comparator cannot return an error, so the first one is captured and
// re-raised after the sort. Once sortErr is set the comparator stops
// calling into the evaluator and reports "not less" for everything, which
// lets the sort finish quickly over a now-meaningless order; the result is
// discarded anyway.
var sortErr error
slices.SortStableFunc(sorted, func(a, b Value) int {
if sortErr != nil {
return 0
}
r, err := s.callFunction(fn, []Value{a, b}, NoPosIdx)
if err != nil {
sortErr = err
return 0
}
less, err := s.forceBool(&r, NoPosIdx)
if err != nil {
sortErr = err
return 0
}
if less {
return -1
}
return 0
})
if sortErr != nil {
return nil, sortErr
}
return newList(s, sorted), nil
}
// --- attrset operations ---
// lexicoOrder returns the indices of bindings.Attrs in lexicographic name order.
func lexicoOrder(s *EvalState, bindings *Bindings) []int {
all := bindings.All()
idx := make([]int, len(all))
for i := range idx {
idx[i] = i
}
sort.Slice(idx, func(a, b int) bool {
return s.Symbols.Str(all[idx[a]].Name) < s.Symbols.Str(all[idx[b]].Name)
})
return idx
}
func primAttrNames(s *EvalState, a0 Value) (Value, error) {
v := a0
bindings, err := s.forceAttrs(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
idx := lexicoOrder(s, bindings)
all := bindings.All()
names := make([]Value, len(all))
for i, j := range idx {
names[i] = s.Symbols.StrValue(all[j].Name)
}
return newList(s, names), nil
}
func primAttrValues(s *EvalState, a0 Value) (Value, error) {
v := a0
bindings, err := s.forceAttrs(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
idx := lexicoOrder(s, bindings)
all := bindings.All()
vals := make([]Value, len(all))
for i, j := range idx {
vals[i] = all[j].Value
}
return newList(s, vals), nil
}
// primHasAttr ports C++ prim_hasAttr (primops.cc:2036), which calls
// forceStringNoCtx on the name.
//
// The context check is the load-bearing half: the name becomes a Symbol, and a
// Symbol cannot carry the store-path dependency a context records, so
// accepting one silently drops it. `hasAttr "${toFile "n" "a"}" { }` answered
// false here and is an error in C++.
func primHasAttr(s *EvalState, a0, a1 Value) (Value, error) {
name, err := s.forceStringNoContext(&a0, NoPosIdx,
"while evaluating the first argument passed to builtins.hasAttr")
if err != nil {
return nil, err
}
v := a1
bindings, err := s.forceAttrs(&v, NoPosIdx,
"while evaluating the second argument passed to builtins.hasAttr")
if err != nil {
return nil, err
}
sym := s.Symbols.Create(name)
if bindings.Get(sym) != nil {
return VTrueSingleton, nil
}
return VFalseSingleton, nil
}
// primGetAttr ports C++ prim_getAttr (primops.cc:1965), which calls
// forceStringNoCtx on the name. See primHasAttr for why the context check
// matters rather than being pedantic.
func primGetAttr(s *EvalState, a0, a1 Value) (Value, error) {
name, err := s.forceStringNoContext(&a0, NoPosIdx,
"while evaluating the first argument passed to builtins.getAttr")
if err != nil {
return nil, err
}
v := a1
bindings, err := s.forceAttrs(&v, NoPosIdx,
"while evaluating the second argument passed to builtins.getAttr")
if err != nil {
return nil, err
}
sym := s.Symbols.Create(name)
attr := bindings.Get(sym)
if attr == nil {
return nil, evalErrorf("attribute '%s' missing", name)
}
r := attr.Value
if err := s.forceValue(&r, NoPosIdx); err != nil {
return nil, err
}
return r, nil
}
func primRemoveAttrs(s *EvalState, a0, a1 Value) (Value, error) {
v := a0
bindings, err := s.forceAttrs(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
toRemove := a1
names, err := s.forceList(&toRemove, NoPosIdx, "")
if err != nil {
return nil, err
}
// Each name must be *forced* before it can be inspected. Type-asserting the
// element directly only works for values that are already evaluated, which
// for a list literal of string literals they are — ExprString is pre-boxed,
// so maybeThunk returns the value rather than a thunk. Any computed list
// (`map (x: x) [ "a" ]`, `[ (head names) ]`) yields thunks instead, and
// asserting on those rejected programs C++ accepts.
//
// C++ calls forceStringNoCtx per element (primops.cc:2062), which also
// refuses a string carrying context: the name is about to become a Symbol,
// and a Symbol cannot carry the store-path dependency the context records.
syms := make([]Symbol, len(names))
for i := range names {
ns, err := s.forceStringNoContext(&names[i], NoPosIdx,
"while evaluating the values of the second argument passed to builtins.removeAttrs")
if err != nil {
return nil, err
}
syms[i] = s.Symbols.Create(ns)
}
// Sorting the names lets the removal be a merge against the (already
// sorted) attrs rather than a hash lookup per attr, which is what C++ does
// with std::sort + std::set_difference (primops.cc:2069-2085). The result
// needs no re-sort: it is a subset of a sorted sequence, in order.
//
// C++ copies surviving Attrs wholesale, and an Attr carries its own pos, so
// copying the attr carries the position with it.
slices.Sort(syms)
result := newBindings(s, bindings.Len())
j := 0
for _, a := range bindings.All() {
for j < len(syms) && syms[j] < a.Name {
j++
}
if j < len(syms) && syms[j] == a.Name {
continue
}
result.attrs = append(result.attrs, a)
}
return VAttrs{Bindings: result}, nil
}
func primListToAttrs(s *EvalState, a0 Value) (Value, error) {
v := a0
elems, err := s.forceList(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
symName := s.Symbols.Create("name")
symValue := s.Symbols.Create("value")
// C++ inserts with the pair's `value` attr position
// (`attrs.insert(sym, j2->value, j2->pos)`), which an Attr now carries
// directly. This used to need a second pass: positions were collected into
// a parallel slice and attached only if at least one turned out to be real,
// because Pos had to be either nil or exactly parallel to Attrs and never
// partially filled. A per-attr position has no such all-or-nothing rule.
b := newBindings(s, len(elems))
seen := make(map[Symbol]bool)
for _, e := range elems {
pair, err := s.forceAttrs(&e, NoPosIdx, "")
if err != nil {
return nil, err
}
nameAttr := pair.Get(symName)
if nameAttr == nil {
return nil, evalErrorf("builtins.listToAttrs: element missing 'name'")
}
// C++ calls forceStringNoCtx here (primops.cc:2109): the name becomes a
// Symbol, which cannot carry the store-path dependency a context
// records, so a context-carrying name must be refused rather than
// silently stripped.
name, err := s.forceStringNoContext(&nameAttr.Value, nameAttr.Pos,
"while evaluating the `name` attribute of an element of the list passed to builtins.listToAttrs")
if err != nil {
return nil, err
}
// Get, not IndexOf: an index needs the whole set, so it would
// materialise a pair built by `//` just to read one attr of it.
valAttr := pair.Get(symValue)
if valAttr == nil {
return nil, evalErrorf("builtins.listToAttrs: element missing 'value'")
}
sym := s.Symbols.Create(name)
if seen[sym] {
continue // first definition wins
}
seen[sym] = true
b.attrs = append(b.attrs, Attr{
Name: sym,
Pos: valAttr.Pos,
Value: valAttr.Value,
})
}
b.Sort()
return VAttrs{Bindings: b}, nil
}
func primIntersectAttrs(s *EvalState, a0, a1 Value) (Value, error) {
v1 := a0
b1, err := s.forceAttrs(&v1, NoPosIdx, "")
if err != nil {
return nil, err
}
v2 := a1
b2, err := s.forceAttrs(&v2, NoPosIdx, "")
if err != nil {
return nil, err
}
// C++ inserts the *right* operand's whole Attr (`attrs.insert(*r)`), so the
// position comes from the right side along with the value. Copying the Attr
// now does that by construction; when positions lived in a parallel slice
// this site forgot to copy them and silently produced Pos == nil, i.e.
// unsafeGetAttrPos returning null where C++ returns a location.
result := newBindings(s, min(b1.Len(), b2.Len()))
for _, a := range b1.All() {
// Keys come from b1 (left), values come from b2 (right) — matching C++.
// Get, not IndexOf: b1 is walked in full and so materialised, but
// b2 is only probed, and an index would materialise it too.
if a2 := b2.Get(a.Name); a2 != nil {
result.attrs = append(result.attrs, *a2)
}
}
return VAttrs{Bindings: result}, nil
}
// primCatAttrs ports C++ prim_catAttrs (primops.cc:2195), which calls
// forceStringNoCtx on the name. See primHasAttr for why the context check
// matters rather than being pedantic.
func primCatAttrs(s *EvalState, a0, a1 Value) (Value, error) {
name, err := s.forceStringNoContext(&a0, NoPosIdx,
"while evaluating the first argument passed to builtins.catAttrs")
if err != nil {
return nil, err
}
sym := s.Symbols.Create(name)
listV := a1
elems, err := s.forceList(&listV, NoPosIdx,
"while evaluating the second argument passed to builtins.catAttrs")
if err != nil {
return nil, err
}
var result []Value
for _, e := range elems {
bindings, err := s.forceAttrs(&e, NoPosIdx, "")
if err != nil {
return nil, err
}
attr := bindings.Get(sym)
if attr != nil {
result = append(result, attr.Value)
}
}
return newList(s, result), nil
}
func primFunctionArgs(s *EvalState, a0 Value) (Value, error) {
v := a0
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
switch f := v.(type) {
case *VLambda:
ap, ok := f.Fun.Pattern.(AttrsPattern)
if !ok {
return VAttrs{Bindings: EmptyBindings}, nil
}
b := newBindings(s, len(ap.Formals))
for _, formal := range ap.Formals {
var hasDefault Value
if formal.HasDefault {
hasDefault = VTrueSingleton
} else {
hasDefault = VFalseSingleton
}
b.attrs = append(b.attrs, Attr{Name: formal.Name, Pos: formal.Pos, Value: hasDefault})
}
b.Sort()
return VAttrs{Bindings: b}, nil
case VPrimOp:
return VAttrs{Bindings: EmptyBindings}, nil
}
return nil, evalErrorf("builtins.functionArgs: argument is not a function")
}
func primMapAttrs(s *EvalState, a0, a1 Value) (Value, error) {
fn := a0
v := a1
bindings, err := s.forceAttrs(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
result := newBindingsLen(s, bindings.Len())
for i, a := range bindings.All() {
nameStr := s.Symbols.StrValue(a.Name)
// Build a lazy thunk — f name value is deferred until the attr is forced.
// This mirrors C++ mapAttrs which creates a synthetic ExprCall thunk.
thunk := newCallThunk2(fn, nameStr, a.Value)
result.attrs[i] = Attr{Name: a.Name, Value: thunk}
}
s.Stats.NrCallThunks += uint64(bindings.Len())
return VAttrs{Bindings: result}, nil
}
func primZipAttrsWith(s *EvalState, a0, a1 Value) (Value, error) {
fn := a0
v := a1
lists, err := s.forceList(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
// Collect all keys and their values from each attrset in the list.
merged := make(map[Symbol][]Value)
var order []Symbol
for _, listV := range lists {
bindings, err := s.forceAttrs(&listV, NoPosIdx, "")
if err != nil {
return nil, err
}
for _, a := range bindings.All() {
if _, exists := merged[a.Name]; !exists {
order = append(order, a.Name)
}
merged[a.Name] = append(merged[a.Name], a.Value)
}
}
// Build the result attrset with LAZY thunks for each key.
// This matches C++ nix's zipAttrsWith which creates VApp (lazy application)
// nodes, not eagerly evaluated results. Eagerness would cause premature
// forcing of attribute values and trigger false infinite-recursion errors
// in self-referential module-system fixpoints (e.g. nixpkgs evalModules).
result := newBindings(s, len(order))
for _, sym := range order {
vals := merged[sym]
nameStr := s.Symbols.StrValue(sym)
listVal := Value(newList(s, vals))
thunk := newCallThunk2(fn, nameStr, listVal)
result.attrs = append(result.attrs, Attr{Name: sym, Value: thunk})
}
s.Stats.NrCallThunks += uint64(len(order))
result.Sort()
return VAttrs{Bindings: result}, nil
}
func primPartition(s *EvalState, a0, a1 Value) (Value, error) {
fn := a0
v := a1
elems, err := s.forceList(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
var right, wrong []Value
for _, e := range elems {
r, err := s.callFunction(fn, []Value{e}, NoPosIdx)
if err != nil {
return nil, err
}
b, err := s.forceBool(&r, NoPosIdx)
if err != nil {
return nil, err
}
if b {
right = append(right, e)
} else {
wrong = append(wrong, e)
}
}
symRight := s.Symbols.Create("right")
symWrong := s.Symbols.Create("wrong")
b := newBindingsOf(s,
Attr{Name: symRight, Value: newList(s, right)},
Attr{Name: symWrong, Value: newList(s, wrong)},
)
b.Sort()
return VAttrs{Bindings: b}, nil
}
func primGroupBy(s *EvalState, a0, a1 Value) (Value, error) {
fn := a0
v := a1
elems, err := s.forceList(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
groups := make(map[Symbol][]Value)
var order []Symbol
for _, e := range elems {
r, err := s.callFunction(fn, []Value{e}, NoPosIdx)
if err != nil {
return nil, err
}
// C++ calls forceStringNoCtx on the function's result
// (primops.cc:2629): it becomes a Symbol, which cannot carry a
// store-path dependency, so a context-carrying key must be refused.
key, err := s.forceStringNoContext(&r, NoPosIdx,
"while evaluating the return value of the grouping function passed to builtins.groupBy")
if err != nil {
return nil, err
}
sym := s.Symbols.Create(key)
if _, exists := groups[sym]; !exists {
order = append(order, sym)
}
groups[sym] = append(groups[sym], e)
}
b := newBindings(s, len(order))
for _, sym := range order {
b.attrs = append(b.attrs, Attr{Name: sym, Value: newList(s, groups[sym])})
}
b.Sort()
return VAttrs{Bindings: b}, nil
}
// --- string operations ---
func primToString(s *EvalState, a0 Value) (Value, error) {
v := a0
str, ctx, err := s.coerceToString(&v, CoerceToString, false)
if err != nil {
return nil, err
}
return VString{V: str, Context: ctx}, nil
}
func primConcatStringsSep(s *EvalState, a0, a1 Value) (Value, error) {
sep, ok := a0.(VString)
if !ok {
sv := a0
if err := s.forceValue(&sv, NoPosIdx); err != nil {
return nil, err
}
sep, ok = sv.(VString)
if !ok {
return nil, evalErrorf("builtins.concatStringsSep: separator must be a string")
}
}
v := a1
elems, err := s.forceList(&v, NoPosIdx, "")
if err != nil {
return nil, err
}
var parts []string
var ctx NixStringContext
ctx.Merge(sep.Context)
for i := range elems {
str, c, err := s.coerceToString(&elems[i], CoerceStrict)
if err != nil {
return nil, err
}
parts = append(parts, str)
ctx.Merge(c)
}
return VString{V: strings.Join(parts, sep.V), Context: ctx}, nil
}
// primStringLength returns the length of a string in *bytes*, not characters.
//
// C++ prim_stringLength (primops.cc:2881) is `s->size()` on a std::string, so
// "äöü" is 6 and "日本語" is 9. That is not an incidental detail of the C++
// implementation that we are free to improve on: builtins.substring is indexed
// in the same units (see primSubstring), and nixpkgs pairs the two constantly —
// lib/strings.nix:809 defines hasPrefix as
//
// substring 0 (stringLength pref) str == pref
//
// which only works if both count the same thing. Counting runes here while
// substring counts bytes made that idiom return false for any multi-byte
// prefix, so every nixpkgs code path touching a non-ASCII string computed a
// different value than C++ nix and therefore a different derivation hash.
// primStringLength ports C++ prim_stringLength (primops.cc:2881).
//
// copyToStore is left at its default of true, as C++ leaves it. That is not a
// detail: with it false, a path argument measured its *source* path instead of
// the store path it coerces to, so `stringLength ./f` answered 45 here and 58
// in C++. lib.strings.sanitizeDerivationName branches on exactly this length,
// so the two implementations disagreed about a derivation's name.
func primStringLength(s *EvalState, a0 Value) (Value, error) {
v := a0
str, _, err := s.coerceToString(&v, CoerceStrict)
if err != nil {
return nil, err
}
return VInt{V: int64(len(str))}, nil
}
func primSubstring(s *EvalState, a0, a1, a2 Value) (Value, error) {
start, err := s.forceInt(&a0, NoPosIdx)
if err != nil {
return nil, err
}
length, err := s.forceInt(&a1, NoPosIdx)
if err != nil {
return nil, err
}
v := a2
// copyToStore stays true, as in C++ (primops.cc:2864): a path argument is
// copied to the store and the substring is taken of the *store path*, not
// of the source path. `substring 0 3 ./f` is "/ni" in C++ and was "/ho"
// here.
str, ctx, err := s.coerceToString(&v, CoerceStrict)
if err != nil {
return nil, err
}
// C++ substring operates on bytes, not runes, matching the underlying
// std::string byte semantics. This means substring can produce invalid UTF-8.
n := int64(len(str))
if start < 0 {
return nil, evalErrorf("negative start position in 'substring'")
}
if start > n {
return VString{V: "", Context: ctx}, nil
}
end := start + length
if length < 0 || end > n {
end = n
}
return VString{V: str[start:end], Context: ctx}, nil
}
// --- path / string operations ---
// nixBaseNameOf mirrors C++ baseNameOf: strips trailing slashes, returns last
// path component (or "/" for root). Input is already a string or path string.
func nixBaseNameOf(path string) string {
// Strip trailing slashes (except if the entire string is slashes).
p := strings.TrimRight(path, "/")
if p == "" {
return "/"
}
idx := strings.LastIndex(p, "/")
if idx < 0 {
return p
}
return p[idx+1:]
}
func primBaseNameOf(s *EvalState, a0 Value) (Value, error) {
v := a0
str, ctx, err := s.coerceToString(&v, CoerceStrict, false)
if err != nil {
return nil, err
}
return VString{V: nixBaseNameOf(str), Context: ctx}, nil
}
func primDirOf(s *EvalState, a0 Value) (Value, error) {
v := a0
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
if p, ok := v.(VPath); ok {
// Path type: return path parent, matching C++ path.canonical().parent().
dir := filepath.Dir(p.V)
if dir == p.V {
// Already root.
return VPath{V: p.V, Relative: p.Relative}, nil
}
return VPath{V: dir, Relative: p.Relative}, nil
}
// String/coercible: coerce and return dir as a string.
str, ctx, err := s.coerceToString(&v, CoerceStrict, false)
if err != nil {
return nil, err
}
// Everything after the last '/', with no canonicalisation whatsoever.
// This is a literal port of C++ dirOf() in libutil/file-system.cc:153:
//
// Path::size_type pos = path.rfind('/');
// if (pos == std::string::npos) return ".";
// return pos == 0 ? "/" : Path(path, 0, pos);
//
// In particular it does NOT strip a trailing slash and does NOT special-case
// the empty string: `dirOf ""` is "." (no slash found), and `dirOf "a/b/"`
// is "a/b", not "a". Stripping trailing slashes first, as this used to do,
// silently changed the result of nixpkgs' minimal-bootstrap writeTextFile
// (utils.nix:64), which switches on `dirOf destination == "."` with an
// empty `destination` — it took the wrong branch, so the generated
// builder script differed and hashed to a store path that does not exist.
var dir string
if idx := strings.LastIndex(str, "/"); idx < 0 {
dir = "."
} else if idx == 0 {
dir = "/"
} else {
dir = str[:idx]
}
return VString{V: dir, Context: ctx}, nil
}
// hashData computes a hash of data using the named algorithm and returns
// lowercase hex. Supported types: md5, sha1, sha256, sha512.
func hashData(hashType, data string) (string, error) {
switch hashType {
case "md5":
h := md5.Sum([]byte(data))
return hex.EncodeToString(h[:]), nil
case "sha1":
h := sha1.Sum([]byte(data))
return hex.EncodeToString(h[:]), nil
case "sha256":
h := sha256.Sum256([]byte(data))
return hex.EncodeToString(h[:]), nil
case "sha512":
h := sha512.Sum512([]byte(data))
return hex.EncodeToString(h[:]), nil
default:
return "", fmt.Errorf("unknown hash algorithm '%s'", hashType)
}
}
// primHashString ports C++ prim_hashString (primops.cc:2889). The two
// arguments take *different* operations, which is the whole point of the
// distinction: the algorithm name is forceStringNoCtx (it selects a hash
// function, so a store-path dependency would be meaningless), while the
// subject is forceString — a string with a context is perfectly hashable.
func primHashString(s *EvalState, a0, a1 Value) (Value, error) {
htV := a0
hashType, err := s.forceStringNoContext(&htV, NoPosIdx,
"while evaluating the first argument passed to builtins.hashString")
if err != nil {
return nil, err
}
strV := a1
sv, err := s.forceString(&strV, NoPosIdx,
"while evaluating the second argument passed to builtins.hashString")
if err != nil {
return nil, err
}
str := sv.V
h, err := hashData(hashType, str)
if err != nil {
return nil, evalErrorf("%v", err)
}
return VString{V: h}, nil
}
// primHashFile ports C++ prim_hashFile (primops.cc:1601), which calls
// forceStringNoCtx on the algorithm name.
func primHashFile(s *EvalState, a0, a1 Value) (Value, error) {
htV := a0
hashType, err := s.forceStringNoContext(&htV, NoPosIdx,
"while evaluating the first argument passed to builtins.hashFile")
if err != nil {
return nil, err
}
pathV := a1
pathStr, err := s.coerceToPath(&pathV, "hashFile")
if err != nil {
return nil, err
}
data, err := s.readFile(pathStr)
if err != nil {
return nil, evalErrorf("builtins.hashFile: %v", err)
}
h, err := hashData(hashType, string(data))
if err != nil {
return nil, evalErrorf("%v", err)
}
return VString{V: h}, nil
}
// --- import ---
// importFile parses and evaluates a .nix file from s.FS, returning its value.
// absPath is an absolute Nix path (e.g. "/testfs/lib.nix").
// If scope is non-nil (scopedImport), the scope attrset is injected as a
// with-frame around the file's top-level expression — matching C++
// EvalState::importNow / EvalState::evalFile behaviour.
func importFile(s *EvalState, absPath string, scope *Bindings) (Value, error) {
if s.NativeParseFunc == nil {
return nil, evalErrorf("builtin 'import' requires NativeParseFunc (not configured)")
}
// Resolve symlinks so that (a) the import cache uses the canonical path
// and (b) relative imports from the file resolve against the real location
// (matching C++ nix's realpath behaviour).
//
// This runs before the importCache lookup below and so is on the hot path
// of every repeated import, which is why it goes through the memoising
// s.resolvePath rather than calling the filesystem directly.
absPath = s.resolvePath(absPath)
key := fsPath(absPath)
// Cache hit — return the previously evaluated value.
if v, ok := s.importCache[key]; ok {
return v, nil
}
// Tell the predictor this file was really needed, and queue whatever
// followed it in previous runs. Doing this before the parse below means
// the worker can start on the successors while the evaluator is still
// busy with this file.
s.prefetch.observe(key)
// Obtain the AST, which may already have been parsed in the background.
//
// The promise is claimed before any I/O so that a concurrent prefetch of
// the same file cannot start a second parse: whoever creates the entry
// parses, everyone else waits. See parseResult for why one file must map
// to exactly one AST.
res, mine := s.prefetch.astFor(key)
if !mine {
ast, err := s.prefetch.wait(res)
if err != nil {
return nil, err
}
return evalImportedAST(s, ast, key, scope)
}
s.prefetch.inline.Add(1)
// Corepkgs virtual paths (/__corepkgs__/foo.nix) are served from embedded
// Go constants rather than the filesystem.
var src []byte
var err error
if strings.HasPrefix(absPath, corepkgsPrefix) {
name := absPath[len(corepkgsPrefix):]
embedded, ok := corepkgsSources[name]
if !ok {
err = evalErrorf("import: unknown corepkgs file: %s", name)
res.finish(nil, err)
return nil, err
}
src = []byte(embedded)
} else {
// Read on the evaluator's side, not the worker's: this is the path
// that is allowed to trigger import-from-derivation.
src, err = s.readFile(absPath)
if err != nil {
err = evalErrorf("import: %v", err)
res.finish(nil, err)
return nil, err
}
}
ast, parseErr := s.prefetch.parseSource(s, absPath, src)
res.finish(ast, parseErr)
if parseErr != nil {
return nil, parseErr
}
return evalImportedAST(s, ast, key, scope)
}
// evalImportedAST evaluates a parsed file and caches its value.
//
// Split out of importFile because the AST can arrive by two routes — parsed
// inline, or handed over by a background parse — and both must evaluate it
// identically. Evaluation itself stays strictly on the evaluator's goroutine;
// only the parse ever moves.
func evalImportedAST(s *EvalState, ast Expr, key string, scope *Bindings) (Value, error) {
// Build the evaluation environment. If a scope was provided (scopedImport),
// prepend a with-frame exactly as C++ does.
var env *Env
if scope != nil {
env = newEnv(s, s.Builtins, 1)
env.Values[0] = VAttrs{Bindings: scope}
} else {
env = s.Builtins
}
v, err := ast.eval(s, env)
if err != nil {
return nil, err
}
// Cache and return.
if s.importCache == nil {
s.importCache = make(map[string]Value)
}
s.importCache[key] = v
return v, nil
}
// nixImportPath extracts and validates an absolute Nix path from a Value for
// use by import / scopedImport.
func nixImportPath(s *EvalState, v Value, builtin string) (string, error) {
p, err := s.coerceToPath(&v, builtin)
if err != nil {
return "", err
}
// Resolve symlinks early so the directory check and import cache use the
// canonical path, and append /default.nix if that lands on a directory
// (matching C++ EvalPaths::resolveExprPath, eval.cc:2086). Both halves are
// memoised together: this runs before importFile's importCache lookup and
// so is on the hot path of every repeated import.
return s.importPath(p), nil
}
func primImport(s *EvalState, a0 Value) (Value, error) {
v := a0
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
absPath, err := nixImportPath(s, v, "import")
if err != nil {
return nil, err
}
return importFile(s, absPath, nil)
}
func primScopedImport(s *EvalState, a0, a1 Value) (Value, error) {
scopeV := a0
scope, err := s.forceAttrs(&scopeV, NoPosIdx, "")
if err != nil {
return nil, err
}
pathV := a1
if err := s.forceValue(&pathV, NoPosIdx); err != nil {
return nil, err
}
absPath, err := nixImportPath(s, pathV, "scopedImport")
if err != nil {
return nil, err
}
return importFile(s, absPath, scope)
}
// --- search path ---
// buildNixPathValue constructs the __nixPath list constant from EvalState.SearchPath.
// Each entry becomes { path = "..."; prefix = "..."; } (prefix omitted if empty).
func buildNixPathValue(s *EvalState) Value {
elems := make([]Value, len(s.SearchPath))
pathSym := s.Symbols.Create("path")
prefixSym := s.Symbols.Create("prefix")
for i, e := range s.SearchPath {
// Two is an upper bound: prefix is conditional. Counting the bound is
// what C++ does too, since buildBindings takes the capacity.
b := newBindings(s, 2)
b.attrs = append(b.attrs, Attr{Name: pathSym, Value: VString{V: e.Path}})
if e.Prefix != "" {
b.attrs = append(b.attrs, Attr{Name: prefixSym, Value: VString{V: e.Prefix}})
}
b.Sort()
elems[i] = VAttrs{Bindings: b}
}
return newList(s, elems)
}
// primFindFile implements builtins.__findFile: walks a search-path list and
// returns the path of the first matching entry, mirroring C++ EvalPaths::findFile.
//
// The search path list is a list of { path; prefix? } attrsets (usually __nixPath).
// The lookup name (second arg) is matched against each entry:
// - Prefixed entry (e.g. prefix = "nixpkgs"): matches if name == prefix (→ path)
// or name starts with prefix + "/" (→ path + "/" + suffix).
// - Unprefixed entry: always matches; candidate = path + "/" + name.
//
// The candidate must exist in the FS (s.FS.Open succeeds).
// Special fallback: if nothing matches and name starts with "nix/", return
// VPath for "/__corepkgs__/" + rest (the internal corepkgs virtual prefix).
func primFindFile(s *EvalState, a0, a1 Value) (Value, error) {
listV := a0
entries, err := s.forceList(&listV, NoPosIdx, "")
if err != nil {
return nil, evalErrorf("builtins.findFile: first argument must be a list")
}
// C++ prim_findFile calls forceStringNoCtx on the name (primops.cc:1590)
// and on each entry's `prefix` (primops.cc:1550).
nameV := a1
name, err := s.forceStringNoContext(&nameV, NoPosIdx,
"while evaluating the second argument passed to builtins.findFile")
if err != nil {
return nil, err
}
pathSym := s.Symbols.Create("path")
prefixSym := s.Symbols.Create("prefix")
for i := range entries {
bindings, err := s.forceAttrs(&entries[i], NoPosIdx, "")
if err != nil {
return nil, evalErrorf("builtins.findFile: list element must be a set")
}
// Extract path (required).
pathAttr := bindings.Get(pathSym)
if pathAttr == nil {
continue
}
// Force the path value. For VPath, use the raw absolute Nix path so
// we can build FS keys from it directly. For strings, use the value as-is.
pathVal := pathAttr.Value
if err := s.forceValue(&pathVal, NoPosIdx); err != nil {
continue
}
var entryPath string
switch pv := pathVal.(type) {
case VPath:
entryPath = pv.V // raw absolute path, e.g. "/testfs/dir1"
default:
entryPath, _, err = s.coerceToString(&pathVal, CoerceStrict, false)
if err != nil {
continue
}
}
// Extract optional prefix.
var prefix string
if prefixAttr := bindings.Get(prefixSym); prefixAttr != nil {
prefix, err = s.forceStringNoContext(&prefixAttr.Value, prefixAttr.Pos,
"while evaluating the `prefix` attribute of an element of the list passed to builtins.findFile")
if err != nil {
return nil, err
}
}
// Determine candidate path.
var candidate string
if prefix != "" {
if name == prefix {
candidate = entryPath
} else if strings.HasPrefix(name, prefix+"/") {
candidate = entryPath + "/" + name[len(prefix)+1:]
} else {
continue
}
} else {
candidate = entryPath + "/" + name
}
// Check existence in FS.
key := fsPath(candidate)
if _, err := s.FS.Open(key); err == nil {
return VPath{V: candidate, Relative: false}, nil
}
}
// Special fallback: <nix/foo> → /__corepkgs__/foo
if strings.HasPrefix(name, "nix/") {
return VPath{V: "/__corepkgs__/" + name[4:], Relative: false}, nil
}
return nil, evalErrorf("file '%s' was not found in the Nix search path", name)
}
// --- misc ---
// primGetEnv ports C++ prim_getEnv (primops.cc:823).
//
// The name is forced *before* the pure-eval check, as C++ does: pure mode
// changes the result to "" but does not excuse an ill-typed argument, so
// `builtins.getEnv 1` is an error in both modes. Returning early, as this did,
// made the type of the argument unobservable in pure mode.
func primGetEnv(s *EvalState, a0 Value) (Value, error) {
name, err := s.forceStringNoContext(&a0, NoPosIdx,
"while evaluating the first argument passed to builtins.getEnv")
if err != nil {
return nil, err
}
if !s.Impure {
// Pure eval mode: the variable is not read, and every name answers "".
return VString{V: ""}, nil
}
return VString{V: os.Getenv(name)}, nil
}
func primPlaceholder(s *EvalState, a0 Value) (Value, error) {
// C++ prim_placeholder (primops.cc:1379) calls forceStringNoCtx.
name, err := s.forceStringNoContext(&a0, NoPosIdx,
"while evaluating the argument passed to builtins.placeholder")
if err != nil {
return nil, err
}
return VString{V: hashPlaceholder(name)}, nil
}
// primUnsafeDiscardStringContext ports C++ prim_unsafeDiscardStringContext
// (primops/context.cc:10), which *coerces* and always returns a string.
//
// Pattern-matching VString and returning everything else untouched, as this
// did, is a different function: it returned the attrset itself for a
// __toString set (where C++ returns its string), left a path a path (where
// C++ returns the store path it copies to), and passed ints and lists through
// (where C++ is a type error). The name says "discard the context", and the
// only way to have a context to discard is to have coerced first.
func primUnsafeDiscardStringContext(s *EvalState, a0 Value) (Value, error) {
v := a0
str, _, err := s.coerceToString(&v, CoerceStrict)
if err != nil {
return nil, err
}
return VString{V: str}, nil // context deliberately dropped
}
// primHasContext ports C++ prim_hasContext (primops/context.cc:17), which
// calls forceString. See primGetContext: coercing would report the context
// that coercing a path had just created, so `hasContext ./f` answered about
// the wrong value.
func primHasContext(s *EvalState, a0 Value) (Value, error) {
sv, err := s.forceString(&a0, NoPosIdx,
"while evaluating the argument passed to builtins.hasContext")
if err != nil {
return nil, err
}
if !sv.Context.IsEmpty() {
return VTrueSingleton, nil
}
return VFalseSingleton, nil
}
// primGetContext returns the context of a string as a structured attrset.
//
// The returned attrset maps each store path (as a string) to an inner attrset
// with optional fields:
//
// path = true — the path is an opaque store-path dependency (CtxOpaque)
// allOutputs = true — the path is a .drv with all outputs depended on (CtxDrvDeep)
// outputs = ["out"] — list of specific drv output names (CtxBuilt)
//
// Multiple entries for the same path (e.g. both allOutputs and some outputs)
// are merged into one inner attrset.
// primGetContext ports C++ prim_getContext (primops/context.cc:106), which
// calls forceString: the argument must *already* be a string, and its context
// is what the primop reports. Coercing instead, as this did, meant a path
// coerced to a store path and reported the context that coercion had just
// manufactured — answering a question about the argument with a fact about
// the coercion.
func primGetContext(s *EvalState, a0 Value) (Value, error) {
sv, err := s.forceString(&a0, NoPosIdx,
"while evaluating the argument passed to builtins.getContext")
if err != nil {
return nil, err
}
ctx := sv.Context
type info struct {
path bool
allOutputs bool
outputs []string
}
// Group by store path, preserving insertion order for determinism.
byPath := make(map[string]*info)
var order []string
for _, e := range ctx.Entries() {
if _, seen := byPath[e.Path]; !seen {
byPath[e.Path] = &info{}
order = append(order, e.Path)
}
switch e.Kind {
case CtxOpaque:
byPath[e.Path].path = true
case CtxDrvDeep:
byPath[e.Path].allOutputs = true
case CtxBuilt:
byPath[e.Path].outputs = append(byPath[e.Path].outputs, e.Output)
}
}
// Sort the top-level paths for deterministic output.
sort.Strings(order)
outer := newBindings(s, len(order))
pathSym := s.Symbols.Create("path")
allOutputsSym := s.Symbols.Create("allOutputs")
outputsSym := s.Symbols.Create("outputs")
for _, p := range order {
inf := byPath[p]
// path, allOutputs and outputs are each conditional; 3 is the bound.
inner := newBindings(s, 3)
if inf.path {
inner.attrs = append(inner.attrs, Attr{Name: pathSym, Value: VTrueSingleton})
}
if inf.allOutputs {
inner.attrs = append(inner.attrs, Attr{Name: allOutputsSym, Value: VTrueSingleton})
}
if len(inf.outputs) > 0 {
sort.Strings(inf.outputs)
elems := make([]Value, len(inf.outputs))
for i, o := range inf.outputs {
elems[i] = VString{V: o}
}
inner.attrs = append(inner.attrs, Attr{Name: outputsSym, Value: newList(s, elems)})
}
inner.Sort()
outer.attrs = append(outer.attrs, Attr{
Name: s.Symbols.Create(p),
Value: VAttrs{Bindings: inner},
})
}
outer.Sort()
return VAttrs{Bindings: outer}, nil
}
// primAppendContext attaches additional context entries to a string.
// The second argument must be an attrset in the same format that getContext
// returns (keys are store paths, values are attrsets with path/allOutputs/outputs).
// primAppendContext ports C++ prim_appendContext (primops/context.cc:159),
// which calls forceString on the string whose context it extends. Coercing
// would extend a context that coercion had just created.
func primAppendContext(s *EvalState, a0, a1 Value) (Value, error) {
v := a0
sv, err := s.forceString(&v, NoPosIdx,
"while evaluating the first argument passed to builtins.appendContext")
if err != nil {
return nil, err
}
str, ctx := sv.V, sv.Context
ctxAttrs, err := s.forceAttrs(&a1, NoPosIdx, "")
if err != nil {
return nil, evalErrorf("builtins.appendContext: second argument must be a set")
}
pathSym := s.Symbols.Create("path")
allOutputsSym := s.Symbols.Create("allOutputs")
outputsSym := s.Symbols.Create("outputs")
for _, attr := range ctxAttrs.All() {
storePath := s.Symbols.Str(attr.Name)
inner, err := s.forceAttrs(&attr.Value, NoPosIdx, "")
if err != nil {
return nil, evalErrorf("builtins.appendContext: value for %q must be a set", storePath)
}
if a := inner.Get(pathSym); a != nil {
b, err := s.forceBool(&a.Value, NoPosIdx)
if err != nil {
return nil, err
}
if b {
ctx.Add(ContextEntry{Kind: CtxOpaque, Path: storePath})
}
}
if a := inner.Get(allOutputsSym); a != nil {
b, err := s.forceBool(&a.Value, NoPosIdx)
if err != nil {
return nil, err
}
if b {
ctx.Add(ContextEntry{Kind: CtxDrvDeep, Path: storePath})
}
}
if a := inner.Get(outputsSym); a != nil {
elems, err := s.forceList(&a.Value, NoPosIdx, "")
if err != nil {
return nil, err
}
for i := range elems {
// C++ forceStringNoCtx (primops/context.cc:221).
outputName, err := s.forceStringNoContext(&elems[i], NoPosIdx,
"while evaluating an output name within a string context")
if err != nil {
return nil, err
}
ctx.Add(ContextEntry{Kind: CtxBuilt, Path: storePath, Output: outputName})
}
}
}
return VString{V: str, Context: ctx}, nil
}
// primAddDrvOutputDependencies converts a CtxOpaque .drv entry to CtxDrvDeep
// (all-outputs dependency). The string must have exactly one context entry.
// Already-CtxDrvDeep entries are returned unchanged (idempotent).
func primAddDrvOutputDependencies(s *EvalState, a0 Value) (Value, error) {
v := a0
str, ctx, err := s.coerceToString(&v, CoerceStrict, false)
if err != nil {
return nil, err
}
entries := ctx.Entries()
if len(entries) != 1 {
return nil, evalErrorf(
"context of string '%s' must have exactly one element, but has %d",
str, len(entries),
)
}
e := entries[0]
var newCtx NixStringContext
switch e.Kind {
case CtxOpaque:
if !strings.HasSuffix(e.Path, ".drv") {
return nil, evalErrorf("path '%s' is not a derivation", e.Path)
}
newCtx.Add(ContextEntry{Kind: CtxDrvDeep, Path: e.Path})
case CtxDrvDeep:
// Idempotent.
newCtx.Add(e)
case CtxBuilt:
return nil, evalErrorf(
"addDrvOutputDependencies can only act on derivations, not on a derivation output such as '%s'",
e.Output,
)
}
return VString{V: str, Context: newCtx}, nil
}
// primUnsafeDiscardOutputDependency converts CtxDrvDeep entries to CtxOpaque,
// leaving all other entry kinds unchanged.
// primUnsafeGetAttrPos implements builtins.unsafeGetAttrPos attrName attrset.
// Returns { file, line, column } for the attribute's definition site, or null
// if the attribute is absent or has no position information.
func primUnsafeGetAttrPos(s *EvalState, a0, a1 Value) (Value, error) {
// C++ prim_unsafeGetAttrPos (primops.cc:1984) calls forceStringNoCtx.
attrName, err := s.forceStringNoContext(&a0, NoPosIdx,
"while evaluating the first argument passed to builtins.unsafeGetAttrPos")
if err != nil {
return nil, err
}
bindings, err := s.forceAttrs(&a1, NoPosIdx, "")
if err != nil {
return nil, err
}
sym := s.Symbols.Create(attrName)
if bindings.Get(sym) == nil {
return VNullSingleton, nil
}
return s.mkPos(bindings.GetPos(sym)), nil
}
// primUnsafeDiscardOutputDependency ports C++
// prim_unsafeDiscardOutputDependency (primops/context.cc:24). copyToStore is
// true there, so a path argument yields the store path; passing false here
// returned the source path instead.
func primUnsafeDiscardOutputDependency(s *EvalState, a0 Value) (Value, error) {
v := a0
str, ctx, err := s.coerceToString(&v, CoerceStrict)
if err != nil {
return nil, err
}
var newCtx NixStringContext
for _, e := range ctx.Entries() {
if e.Kind == CtxDrvDeep {
newCtx.Add(ContextEntry{Kind: CtxOpaque, Path: e.Path})
} else {
newCtx.Add(e)
}
}
return VString{V: str, Context: newCtx}, nil
}
func primBitAnd(s *EvalState, a0, a1 Value) (Value, error) {
a, err := s.forceInt(&a0, NoPosIdx)
if err != nil {
return nil, err
}
b, err := s.forceInt(&a1, NoPosIdx)
if err != nil {
return nil, err
}
return VInt{V: a & b}, nil
}
func primBitOr(s *EvalState, a0, a1 Value) (Value, error) {
a, err := s.forceInt(&a0, NoPosIdx)
if err != nil {
return nil, err
}
b, err := s.forceInt(&a1, NoPosIdx)
if err != nil {
return nil, err
}
return VInt{V: a | b}, nil
}
func primBitXor(s *EvalState, a0, a1 Value) (Value, error) {
a, err := s.forceInt(&a0, NoPosIdx)
if err != nil {
return nil, err
}
b, err := s.forceInt(&a1, NoPosIdx)
if err != nil {
return nil, err
}
return VInt{V: a ^ b}, nil
}
// --- fromJSON ---
// primFromJSON ports C++ prim_fromJSON (primops.cc:1694), which calls
// forceStringNoCtx: JSON text is parsed, not coerced.
func primFromJSON(s *EvalState, a0 Value) (Value, error) {
v := a0
str, err := s.forceStringNoContext(&v, NoPosIdx,
"while evaluating the first argument passed to builtins.fromJSON")
if err != nil {
return nil, err
}
// Use UseNumber() so numbers are preserved as strings, letting us
// distinguish JSON integers from JSON floats (matching C++ nlohmann SAX
// behaviour: number_integer → VInt, number_unsigned overflow → VFloat,
// number_float → VFloat).
dec := json.NewDecoder(strings.NewReader(str))
dec.UseNumber()
var raw interface{}
if err := dec.Decode(&raw); err != nil {
return nil, evalErrorf("builtins.fromJSON: invalid JSON: %v", err)
}
// Decode stops after one value and leaves the rest of the input alone, so
// `fromJSON "1 trailing garbage"` returned 1. nlohmann — which nix uses —
// parses the whole document and rejects anything after the top-level
// value, so this has to check for itself that the input is exhausted.
//
// io.EOF from a second Decode is the check: any other outcome means there
// were more tokens, whether they parse as JSON ("[1] [2]") or not.
if err := dec.Decode(new(interface{})); err != io.EOF {
return nil, evalErrorf("builtins.fromJSON: invalid JSON: unexpected data after the top-level value")
}
return jsonToValue(s, raw)
}
func jsonToValue(s *EvalState, v interface{}) (Value, error) {
switch t := v.(type) {
case nil:
return VNullSingleton, nil
case bool:
if t {
return VTrueSingleton, nil
}
return VFalseSingleton, nil
case json.Number:
numStr := t.String()
// If it has no decimal point or exponent, try to parse as int64 first.
// This matches C++ nlohmann: integer literals → number_integer/unsigned.
if !strings.ContainsAny(numStr, ".eE") {
if i, err := strconv.ParseInt(numStr, 10, 64); err == nil {
return VInt{V: i}, nil
}
// Overflows int64 → fall through to float (matches number_unsigned overflow path).
}
f, err := strconv.ParseFloat(numStr, 64)
if err != nil {
return nil, evalErrorf("builtins.fromJSON: invalid number %q", numStr)
}
return VFloat{V: f}, nil
case string:
return VString{V: t}, nil
case []interface{}:
elems := make([]Value, len(t))
for i, elem := range t {
v, err := jsonToValue(s, elem)
if err != nil {
return nil, err
}
elems[i] = v
}
return newList(s, elems), nil
case map[string]interface{}:
b := newBindings(s, len(t))
for key, val := range t {
v, err := jsonToValue(s, val)
if err != nil {
return nil, err
}
b.attrs = append(b.attrs, Attr{Name: s.Symbols.Create(key), Value: v})
}
b.Sort()
return VAttrs{Bindings: b}, nil
default:
return nil, evalErrorf("builtins.fromJSON: unsupported JSON type %T", v)
}
}
// ---------------------------------------------------------------------------
// replaceStrings
// ---------------------------------------------------------------------------
func primReplaceStrings(s *EvalState, a0, a1, a2 Value) (Value, error) {
fromV := a0
fromElems, err := s.forceList(&fromV, NoPosIdx, "")
if err != nil {
return nil, err
}
toV := a1
toElems, err := s.forceList(&toV, NoPosIdx, "")
if err != nil {
return nil, err
}
if len(fromElems) != len(toElems) {
return nil, evalErrorf("builtins.replaceStrings: 'from' and 'to' lists must have the same length")
}
// C++ forceString for the subject and for every `from` element
// (primops.cc:3059 and :3070) — neither coerces, so a path argument is a
// type error rather than something silently copied to the store. The
// subject's context is carried into the result; `to` elements are forced
// lazily below, as C++ does, so an unused replacement is never evaluated.
strV := a2
subject, err := s.forceString(&strV, NoPosIdx,
"while evaluating the third argument passed to builtins.replaceStrings")
if err != nil {
return nil, err
}
str, ctx := subject.V, subject.Context
froms := make([]string, len(fromElems))
for i := range fromElems {
fv, err := s.forceString(&fromElems[i], NoPosIdx,
"while evaluating one of the strings to replace passed to builtins.replaceStrings")
if err != nil {
return nil, err
}
froms[i] = fv.V
}
type toEntry struct {
str string
ctx NixStringContext
}
tos := make([]toEntry, len(toElems))
toForced := make([]bool, len(toElems))
var sb strings.Builder
// Iterate one past the end to handle empty-string from entries at the end.
for p := 0; p <= len(str); {
matched := false
for i, from := range froms {
if strings.HasPrefix(str[p:], from) {
// Force the corresponding to-string lazily and collect its context.
if !toForced[i] {
ts, tc, err := s.coerceToString(&toElems[i], CoerceStrict)
if err != nil {
return nil, err
}
tos[i] = toEntry{str: ts, ctx: tc}
toForced[i] = true
}
ctx.Merge(tos[i].ctx)
sb.WriteString(tos[i].str)
if from == "" {
// Empty from: emit current char (if not past end) and advance by 1.
if p < len(str) {
sb.WriteByte(str[p])
p++
} else {
p++
}
} else {
p += len(from)
}
matched = true
break
}
}
if !matched {
if p < len(str) {
sb.WriteByte(str[p])
}
p++
}
}
return VString{V: sb.String(), Context: ctx}, nil
}
// ---------------------------------------------------------------------------
// match / split (regex)
// ---------------------------------------------------------------------------
// regex returns the compiled form of pat, compiling it at most once per
// evaluation.
//
// This mirrors C++ RegexCache (lix/libexpr/primops.cc:2902), which exists for
// the same reason: compiling a regex costs far more than running it, and Nix
// code calls `match` with the same handful of patterns over and over. A NixOS
// system evaluation issues 47387 match/split calls over **61 distinct
// patterns** — so 99.9% of the compilations were redundant. Measured against
// C++ on the same expression, an uncached `builtins.match "a" "a"` cost 6.9 us
// against Lix's 1.0 us; essentially all of that gap was regexp.Compile.
//
// anchored selects the `match` flavour, which must match the whole subject and
// so wraps the pattern. It is part of the key because the two flavours compile
// to different programs and `split` must not pick up `match`'s anchors.
//
// The cache is unbounded, unlike C++'s, and that is deliberate rather than an
// oversight: the key space is the set of regex literals reachable in the
// evaluated expression, which the measurement above shows is tiny. Note that
// `lib.hasInfix` synthesises a pattern from its argument (".*${escapeRegex
// infix}.*"), so the bound is really "distinct infixes searched for", not
// "regexes written in the source" — still small, but this is the assumption to
// re-check if an evaluation is ever found to retain an implausible number of
// compiled programs.
//
// Not synchronised, because primops only ever run on the evaluator's own
// goroutine. Background prefetch workers run parseSource and nothing else; see
// the hazard list in prefetch.go.
func (s *EvalState) regex(pat string, anchored bool) (*regexp.Regexp, error) {
key := regexKey{pat: pat, anchored: anchored}
if r, ok := s.regexCache[key]; ok {
return r.re, r.err
}
src := pat
if anchored {
src = `\A(?:` + pat + `)\z`
}
re, err := regexp.Compile(src)
if err != nil {
// Cache the failure too. A pattern that does not compile will not
// compile on the next call either, and Nix code can reach a failing
// match repeatedly inside a tryEval.
err = evalErrorf("invalid regex %q: %v", pat, err)
re = nil
}
if s.regexCache == nil {
s.regexCache = make(map[regexKey]compiledRegex)
}
s.regexCache[key] = compiledRegex{re: re, err: err}
return re, err
}
// primMatch ports C++ prim_match (primops.cc:2926). Like hashString, the two
// arguments take different operations: the pattern is forceStringNoCtx (it is
// a regex, and a store-path dependency in one is meaningless), the subject is
// forceString (matching against a string that carries a context is fine).
//
// Neither coerces. Coercing the subject made `match ".*" ./f` match against a
// store path that matching had itself created.
func primMatch(s *EvalState, a0, a1 Value) (Value, error) {
patV := a0
pat, err := s.forceStringNoContext(&patV, NoPosIdx,
"while evaluating the first argument passed to builtins.match")
if err != nil {
return nil, err
}
strV := a1
sv, err := s.forceString(&strV, NoPosIdx,
"while evaluating the second argument passed to builtins.match")
if err != nil {
return nil, err
}
str := sv.V
// Full-string match: anchor the pattern.
r, err := s.regex(pat, true)
if err != nil {
return nil, evalErrorf("builtins.match: %v", err)
}
// Take indices rather than strings: the group text is a slice of str at
// the positions reported here, so one pass yields both, and a -1 start
// distinguishes a group that did not participate from one that matched
// empty. The previous code re-ran the whole match once per capture group
// to recover those indices, making an n-group pattern cost n+1 matches.
idx := r.FindStringSubmatchIndex(str)
if idx == nil {
return VNullSingleton, nil
}
// idx[0:2] is the full match; the pairs after it are the capture groups.
n := len(idx)/2 - 1
elems := make([]Value, n)
for i := 0; i < n; i++ {
start, end := idx[2+i*2], idx[2+i*2+1]
if start < 0 {
elems[i] = VNullSingleton
} else {
elems[i] = VString{V: str[start:end]}
}
}
return newList(s, elems), nil
}
// primSplit ports C++ prim_split (primops.cc:2961): pattern
// forceStringNoCtx, subject forceString. See primMatch.
func primSplit(s *EvalState, a0, a1 Value) (Value, error) {
patV := a0
pat, err := s.forceStringNoContext(&patV, NoPosIdx,
"while evaluating the first argument passed to builtins.split")
if err != nil {
return nil, err
}
strV := a1
sv, err := s.forceString(&strV, NoPosIdx,
"while evaluating the second argument passed to builtins.split")
if err != nil {
return nil, err
}
str := sv.V
r, err := s.regex(pat, false)
if err != nil {
return nil, evalErrorf("builtins.split: %v", err)
}
matches := r.FindAllStringSubmatchIndex(str, -1)
if len(matches) == 0 {
// C++ returns *args[1] itself here (primops.cc:2983), not a fresh
// string built from its bytes. Rebuilding drops the context: for
// `split "X" "${toFile "n" "a"}"` the single element came back with
// no context at all, so a store-path dependency vanished through a
// primop that had not matched anything.
return newList(s, []Value{sv}), nil
}
// Result: [pre, [groups], mid, [groups], ..., post]
numGroups := r.NumSubexp()
var elems []Value
prev := 0
for _, loc := range matches {
// Text before this match.
elems = append(elems, VString{V: str[prev:loc[0]]})
// Capture groups for this match.
groups := make([]Value, numGroups)
for i := 0; i < numGroups; i++ {
s2, e2 := loc[2+i*2], loc[2+i*2+1]
if s2 < 0 {
groups[i] = VNullSingleton
} else {
groups[i] = VString{V: str[s2:e2]}
}
}
elems = append(elems, newList(s, groups))
prev = loc[1]
}
// Trailing text.
elems = append(elems, VString{V: str[prev:]})
return newList(s, elems), nil
}
// ---------------------------------------------------------------------------
// flakeRefToString / parseFlakeRef
//
// Pure string/attrset transformations — no fetching.
// Supports the github:, gitlab:, sourcehut: and indirect: (flake-id) schemes.
// Mirrors C++ FlakeRef::to_string() / FlakeRef::toAttrs() / parseFlakeRef().
// ---------------------------------------------------------------------------
// gitArchiveSchemes are the scheme names that use "owner/repo[/ref-or-rev]" path format.
var gitArchiveSchemes = map[string]bool{
"github": true, "gitlab": true, "sourcehut": true,
}
// isRevHash returns true if s looks like a 40-char lowercase hex SHA.
func isRevHash(s string) bool {
if len(s) != 40 {
return false
}
for _, c := range s {
if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) {
return false
}
}
return true
}
// flakeURLSplit splits "scheme:path?query" into (scheme, path, query-map).
// query-map keys are in sorted order (mirrors std::map).
func flakeURLSplit(url string) (scheme, pathPart string, query map[string]string, err error) {
// Split off fragment (ignored for flake refs).
url, _, _ = strings.Cut(url, "#")
// Split scheme.
colon := strings.IndexByte(url, ':')
if colon < 0 {
return "", "", nil, evalErrorf("parseFlakeRef: missing scheme in %q", url)
}
scheme = url[:colon]
rest := url[colon+1:]
// Split path and query.
pathPart, queryStr, _ := strings.Cut(rest, "?")
query = make(map[string]string)
if queryStr != "" {
for _, kv := range strings.Split(queryStr, "&") {
k, v, _ := strings.Cut(kv, "=")
query[k] = v
}
}
return scheme, pathPart, query, nil
}
// flakeEncodeQuery encodes a sorted map as "k=v&k=v" (mirrors C++ encodeQuery).
// The path and keys only use characters that don't need percent-encoding for
// these simple flake ref strings.
func flakeEncodeQuery(q map[string]string) string {
keys := make([]string, 0, len(q))
for k := range q {
keys = append(keys, k)
}
sort.Strings(keys)
var sb strings.Builder
for i, k := range keys {
if i > 0 {
sb.WriteByte('&')
}
sb.WriteString(k)
sb.WriteByte('=')
sb.WriteString(q[k])
}
return sb.String()
}
// primParseFlakeRef implements builtins.parseFlakeRef.
// Parses a flake URL string into an attrset of string/int attributes.
// Mirrors C++ prim_parseFlakeRef + FlakeRef::toAttrs().
func primParseFlakeRef(s *EvalState, a0 Value) (Value, error) {
// C++ flake::prim_parseFlakeRef (flake/flake.cc:993) calls
// forceStringNoCtx.
v := a0
urlStr, err := s.forceStringNoContext(&v, NoPosIdx,
"while evaluating the argument passed to builtins.parseFlakeRef")
if err != nil {
return nil, err
}
scheme, pathPart, query, err := flakeURLSplit(urlStr)
if err != nil {
return nil, err
}
// Mutually exclusive scheme branches, each adding at most four attrs plus
// the query loop. Left as a small fixed bound rather than a computed one:
// the alternative is to pre-scan the query string, which would cost more
// than the growth it avoids on a builtin called a handful of times.
attrs := newBindings(s, 4)
if gitArchiveSchemes[scheme] {
// github:owner/repo[/ref-or-rev][?query]
parts := strings.Split(pathPart, "/")
if len(parts) < 2 {
return nil, evalErrorf("parseFlakeRef: invalid %s URL %q", scheme, urlStr)
}
typeSym := s.Symbols.Create("type")
ownerSym := s.Symbols.Create("owner")
repoSym := s.Symbols.Create("repo")
attrs.attrs = append(attrs.attrs,
Attr{Name: typeSym, Value: VString{V: scheme}},
Attr{Name: ownerSym, Value: VString{V: parts[0]}},
Attr{Name: repoSym, Value: VString{V: parts[1]}},
)
if len(parts) >= 3 {
refOrRev := strings.Join(parts[2:], "/")
if isRevHash(refOrRev) {
revSym := s.Symbols.Create("rev")
attrs.attrs = append(attrs.attrs, Attr{Name: revSym, Value: VString{V: refOrRev}})
} else {
refSym := s.Symbols.Create("ref")
attrs.attrs = append(attrs.attrs, Attr{Name: refSym, Value: VString{V: refOrRev}})
}
}
// Query params: lastModified → int, others → string.
for k, val := range query {
sym := s.Symbols.Create(k)
if k == "lastModified" {
n, err := strconv.ParseUint(val, 10, 64)
if err != nil {
return nil, evalErrorf("parseFlakeRef: lastModified %q is not an integer", val)
}
attrs.attrs = append(attrs.attrs, Attr{Name: sym, Value: VInt{V: int64(n)}})
} else {
attrs.attrs = append(attrs.attrs, Attr{Name: sym, Value: VString{V: val}})
}
}
} else if scheme == "flake" {
// flake:id[/ref-or-rev] — indirect ref
typeSym := s.Symbols.Create("type")
idSym := s.Symbols.Create("id")
parts := strings.SplitN(pathPart, "/", 2)
attrs.attrs = append(attrs.attrs,
Attr{Name: typeSym, Value: VString{V: "indirect"}},
Attr{Name: idSym, Value: VString{V: parts[0]}},
)
if len(parts) == 2 && parts[1] != "" {
refOrRev := parts[1]
if isRevHash(refOrRev) {
revSym := s.Symbols.Create("rev")
attrs.attrs = append(attrs.attrs, Attr{Name: revSym, Value: VString{V: refOrRev}})
} else {
refSym := s.Symbols.Create("ref")
attrs.attrs = append(attrs.attrs, Attr{Name: refSym, Value: VString{V: refOrRev}})
}
}
} else if scheme == "path" {
typeSym := s.Symbols.Create("type")
pathSym := s.Symbols.Create("path")
attrs.attrs = append(attrs.attrs,
Attr{Name: typeSym, Value: VString{V: "path"}},
Attr{Name: pathSym, Value: VString{V: pathPart}},
)
} else {
return nil, evalErrorf("parseFlakeRef: unsupported scheme %q in %q", scheme, urlStr)
}
attrs.Sort()
return VAttrs{Bindings: attrs}, nil
}
// primFlakeRefToString implements builtins.flakeRefToString.
// Converts a flake ref attrset back to its URL string form.
// Mirrors C++ prim_flakeRefToString + FlakeRef::to_string().
func primFlakeRefToString(s *EvalState, a0 Value) (Value, error) {
bindings, err := s.forceAttrs(&a0, NoPosIdx,
"while evaluating the argument passed to builtins.flakeRefToString")
if err != nil {
return nil, err
}
// Collect attrs into a plain Go map.
typeSym := s.Symbols.Create("type")
typeAttr := bindings.Get(typeSym)
if typeAttr == nil {
return nil, evalErrorf("flakeRefToString: missing 'type' attribute")
}
tv := typeAttr.Value
if err := s.forceValue(&tv, NoPosIdx); err != nil {
return nil, err
}
typStr, ok := tv.(VString)
if !ok {
return nil, evalErrorf("flakeRefToString: 'type' must be a string")
}
// Collect all attributes as string/int values.
strAttrs := make(map[string]string)
all := bindings.All()
for i := range all {
a := &all[i]
av := a.Value
if err := s.forceValue(&av, NoPosIdx); err != nil {
return nil, err
}
name := s.Symbols.Str(a.Name)
switch t := av.(type) {
case VString:
strAttrs[name] = t.V
case VInt:
if t.V < 0 {
return nil, evalErrorf("flakeRefToString: negative value for attr %q: %d", name, t.V)
}
strAttrs[name] = strconv.FormatInt(t.V, 10)
case VBool:
if t.V {
strAttrs[name] = "1"
} else {
strAttrs[name] = "0"
}
default:
return nil, evalErrorf(
"flakeRefToString: attribute %q must be a string, integer, or bool", name)
}
}
typ := typStr.V
dir := strAttrs["dir"] // may be ""
var result string
if gitArchiveSchemes[typ] {
owner := strAttrs["owner"]
repo := strAttrs["repo"]
ref := strAttrs["ref"]
rev := strAttrs["rev"]
p := owner + "/" + repo
if ref != "" {
p += "/" + ref
} else if rev != "" {
p += "/" + rev
}
// Build query from remaining attrs (not type/owner/repo/ref/rev/dir).
skip := map[string]bool{"type": true, "owner": true, "repo": true,
"ref": true, "rev": true, "dir": true}
q := make(map[string]string)
for k, v := range strAttrs {
if !skip[k] {
q[k] = v
}
}
if dir != "" {
q["dir"] = dir
}
result = typ + ":" + p
if len(q) > 0 {
result += "?" + flakeEncodeQuery(q)
}
} else if typ == "indirect" {
id := strAttrs["id"]
ref := strAttrs["ref"]
rev := strAttrs["rev"]
p := id
if ref != "" {
p += "/" + ref
} else if rev != "" {
p += "/" + rev
}
result = "flake:" + p
if dir != "" {
result += "?dir=" + dir
}
} else if typ == "path" {
p := strAttrs["path"]
result = "path:" + p
if dir != "" {
result += "?dir=" + dir
}
} else {
return nil, evalErrorf("flakeRefToString: unsupported type %q", typ)
}
return VString{V: result}, nil
}
// ---------------------------------------------------------------------------
// toXML
// ---------------------------------------------------------------------------
// primToXML implements builtins.toXML.
// Mirrors C++ prim_toXML: strict=true, location=false.
// Returns the XML as a Nix string (with accumulated string context).
func primToXML(s *EvalState, a0 Value) (Value, error) {
v := a0
var sb strings.Builder
var ctx NixStringContext
sb.WriteString("<?xml version='1.0' encoding='utf-8'?>\n")
sb.WriteString("<expr>\n")
if err := xmlPrintValue(s, &v, 1, &sb, &ctx, make(map[string]bool), make(map[*Bindings]bool)); err != nil {
return nil, err
}
sb.WriteString("</expr>\n")
return VString{V: sb.String(), Context: ctx}, nil
}
// xmlEscapeAttr escapes a string for use in an XML attribute value.
// Mirrors C++ XMLWriter::writeAttrs: escapes ", <, >, &, \n only.
func xmlEscapeAttr(s string) string {
var sb strings.Builder
for i := 0; i < len(s); i++ {
switch s[i] {
case '"':
sb.WriteString(""")
case '<':
sb.WriteString("<")
case '>':
sb.WriteString(">")
case '&':
sb.WriteString("&")
case '\n':
sb.WriteString("
")
default:
sb.WriteByte(s[i])
}
}
return sb.String()
}
// xmlIndent writes depth*2 spaces.
func xmlIndent(sb *strings.Builder, depth int) {
for i := 0; i < depth*2; i++ {
sb.WriteByte(' ')
}
}
// xmlOpenElement writes an indented opening tag with sorted attributes.
// attrs is a slice of [key, val] pairs; keys must already be in the order
// they should appear (callers sort alphabetically, mirroring std::map).
func xmlOpenElement(sb *strings.Builder, depth int, tag string, attrs [][2]string) {
xmlIndent(sb, depth)
sb.WriteByte('<')
sb.WriteString(tag)
for _, a := range attrs {
sb.WriteByte(' ')
sb.WriteString(a[0])
sb.WriteString(`="`)
sb.WriteString(xmlEscapeAttr(a[1]))
sb.WriteByte('"')
}
sb.WriteString(">\n")
}
// xmlCloseElement writes an indented closing tag.
func xmlCloseElement(sb *strings.Builder, depth int, tag string) {
xmlIndent(sb, depth)
sb.WriteString("</")
sb.WriteString(tag)
sb.WriteString(">\n")
}
// xmlEmptyElement writes an indented self-closing element with sorted attributes.
func xmlEmptyElement(sb *strings.Builder, depth int, tag string, attrs [][2]string) {
xmlIndent(sb, depth)
sb.WriteByte('<')
sb.WriteString(tag)
for _, a := range attrs {
sb.WriteByte(' ')
sb.WriteString(a[0])
sb.WriteString(`="`)
sb.WriteString(xmlEscapeAttr(a[1]))
sb.WriteByte('"')
}
sb.WriteString(" />\n")
}
// xmlPrintValue is the recursive XML serializer.
// Mirrors C++ printValueAsXML with strict=true, location=false.
func xmlPrintValue(
s *EvalState,
vp *Value,
depth int,
sb *strings.Builder,
ctx *NixStringContext,
drvsSeen map[string]bool,
attrsSeen map[*Bindings]bool,
) error {
if err := s.forceValue(vp, NoPosIdx); err != nil {
return err
}
switch t := (*vp).(type) {
case VInt:
xmlEmptyElement(sb, depth, "int", [][2]string{{"value", strconv.FormatInt(t.V, 10)}})
case VFloat:
xmlEmptyElement(sb, depth, "float", [][2]string{{"value", formatFloat(t.V)}})
case VBool:
val := "false"
if t.V {
val = "true"
}
xmlEmptyElement(sb, depth, "bool", [][2]string{{"value", val}})
case VNull:
xmlEmptyElement(sb, depth, "null", nil)
case VString:
// Collect string context (mirrors C++ copyContext).
ctx.Merge(t.Context)
xmlEmptyElement(sb, depth, "string", [][2]string{{"value", t.V}})
case VPath:
real := s.FS.RealPath(fsPath(t.V), t.Relative)
xmlEmptyElement(sb, depth, "path", [][2]string{{"value", real}})
case VAttrs:
if s.isDerivationAttrs(t.Bindings) {
return xmlPrintDerivation(s, t.Bindings, depth, sb, ctx, drvsSeen, attrsSeen)
}
if attrsSeen[t.Bindings] {
xmlEmptyElement(sb, depth, "repeated", nil)
return nil
}
attrsSeen[t.Bindings] = true
xmlOpenElement(sb, depth, "attrs", nil)
if err := xmlShowAttrs(s, t.Bindings, depth+1, sb, ctx, drvsSeen, attrsSeen); err != nil {
delete(attrsSeen, t.Bindings)
return err
}
delete(attrsSeen, t.Bindings)
xmlCloseElement(sb, depth, "attrs")
case *VList:
xmlOpenElement(sb, depth, "list", nil)
for i := range t.Elems {
if err := xmlPrintValue(s, &t.Elems[i], depth+1, sb, ctx, drvsSeen, attrsSeen); err != nil {
return err
}
}
xmlCloseElement(sb, depth, "list")
case *VLambda:
// location=false: no pos attributes on the function element.
xmlOpenElement(sb, depth, "function", nil)
if ap, ok := t.Fun.Pattern.(AttrsPattern); ok {
// attrspat: attrs may have "ellipsis" and/or "name"; alphabetical.
var patAttrs [][2]string
if ap.Ellipsis {
patAttrs = append(patAttrs, [2]string{"ellipsis", "1"})
}
if ap.Name != 0 {
patAttrs = append(patAttrs, [2]string{"name", s.Symbols.Str(ap.Name)})
}
// "ellipsis" < "name" alphabetically — already in order.
xmlOpenElement(sb, depth+1, "attrspat", patAttrs)
// Formals in lexicographic order of their string names.
type namedFormal struct {
name string
f Formal
}
fnames := make([]namedFormal, len(ap.Formals))
for i, f := range ap.Formals {
fnames[i] = namedFormal{s.Symbols.Str(f.Name), f}
}
sort.Slice(fnames, func(i, j int) bool { return fnames[i].name < fnames[j].name })
for _, nf := range fnames {
xmlEmptyElement(sb, depth+2, "attr", [][2]string{{"name", nf.name}})
}
xmlCloseElement(sb, depth+1, "attrspat")
} else if sp, ok := t.Fun.Pattern.(SimplePattern); ok {
xmlEmptyElement(sb, depth+1, "varpat", [][2]string{{"name", s.Symbols.Str(sp.Name)}})
}
xmlCloseElement(sb, depth, "function")
case VPrimOp, VPrimOpApp:
// C++ FIXME: serialize primops as unevaluated.
xmlEmptyElement(sb, depth, "unevaluated", nil)
default:
// Thunks shouldn't reach here with strict=true; anything else → unevaluated.
xmlEmptyElement(sb, depth, "unevaluated", nil)
}
return nil
}
// xmlShowAttrs serializes attrset bindings in alphabetical name order.
// Mirrors C++ showAttrs which uses StringSet (std::set<std::string>).
func xmlShowAttrs(
s *EvalState,
b *Bindings,
depth int,
sb *strings.Builder,
ctx *NixStringContext,
drvsSeen map[string]bool,
attrsSeen map[*Bindings]bool,
) error {
// Collect names as strings and sort.
type namedAttr struct {
name string
attr *Attr
}
all := b.All()
named := make([]namedAttr, len(all))
for i := range all {
named[i] = namedAttr{s.Symbols.Str(all[i].Name), &all[i]}
}
sort.Slice(named, func(i, j int) bool { return named[i].name < named[j].name })
for _, na := range named {
xmlOpenElement(sb, depth, "attr", [][2]string{{"name", na.name}})
if err := xmlPrintValue(s, &na.attr.Value, depth+1, sb, ctx, drvsSeen, attrsSeen); err != nil {
return err
}
xmlCloseElement(sb, depth, "attr")
}
return nil
}
// xmlPrintDerivation serializes a derivation attrset, with cycle detection.
// Mirrors the nAttrs+isDerivation branch of C++ printValueAsXML.
func xmlPrintDerivation(
s *EvalState,
b *Bindings,
depth int,
sb *strings.Builder,
ctx *NixStringContext,
drvsSeen map[string]bool,
attrsSeen map[*Bindings]bool,
) error {
// Collect drvPath and outPath (alphabetical: drvPath < outPath).
var drvPath, outPath string
drvPathSym := s.Symbols.Create("drvPath")
outPathSym := s.Symbols.Create("outPath")
if a := b.Get(drvPathSym); a != nil {
v := a.Value
if err := s.forceValue(&v, NoPosIdx); err == nil {
if sv, ok := v.(VString); ok {
drvPath = sv.V
}
}
}
if a := b.Get(outPathSym); a != nil {
v := a.Value
if err := s.forceValue(&v, NoPosIdx); err == nil {
if sv, ok := v.(VString); ok {
outPath = sv.V
}
}
}
// Build attrs in alphabetical order (std::map iteration order).
var attrs [][2]string
if drvPath != "" {
attrs = append(attrs, [2]string{"drvPath", drvPath})
}
if outPath != "" {
attrs = append(attrs, [2]string{"outPath", outPath})
}
xmlOpenElement(sb, depth, "derivation", attrs)
if drvPath != "" && !drvsSeen[drvPath] {
drvsSeen[drvPath] = true
if err := xmlShowAttrs(s, b, depth+1, sb, ctx, drvsSeen, attrsSeen); err != nil {
return err
}
} else {
xmlEmptyElement(sb, depth+1, "repeated", nil)
}
xmlCloseElement(sb, depth, "derivation")
return nil
}
// ---------------------------------------------------------------------------
// toJSON
// ---------------------------------------------------------------------------
func primToJSON(s *EvalState, a0 Value) (Value, error) {
v := a0
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
var sb strings.Builder
var ctx NixStringContext
if err := valueToJSON(s, &v, &sb, &ctx, make(map[*Bindings]bool)); err != nil {
return nil, err
}
return VString{V: sb.String(), Context: ctx}, nil
}
// writeJSONString appends str to sb as a quoted JSON string, escaped the way
// C++ nix escapes it.
//
// Matching nix here means *not* using encoding/json, for two reasons.
//
// The first is correctness. Go's encoder escapes U+2028 and U+2029
// unconditionally — they are legal in JSON but break JSONP, so it emits
// \u2028 regardless of SetEscapeHTML (encoding/json/encode.go:1054). nlohmann,
// which nix uses, emits them raw. Every other byte agrees, verified against
// nix-instantiate for the control bytes, DEL, and multi-byte UTF-8; those two
// code points were the only divergence, and they changed the hash of any
// __structuredAttrs derivation whose attributes contained one.
//
// The second is cost. The old implementation built a strings.Builder and a
// json.Encoder per call and copied the result out through []byte(s) — three
// allocations to escape a string that, at every one of the ten call sites, was
// about to be written straight into a strings.Builder the caller already had.
// That was 1.16M objects per system evaluation. Appending into the caller's
// builder is none.
//
// The escaping itself is what nlohmann's serializer does: \b \t \n \f \r for
// those five, \uXXXX for the remaining bytes below 0x20, \" and \\ for the two
// mandatory ones, and everything else — including DEL, <, >, & and all
// multi-byte UTF-8 — verbatim.
func writeJSONString(sb *strings.Builder, str string) {
sb.WriteByte('"')
// Bytes are copied in runs: only the characters needing an escape are
// written individually, so an unescaped string costs one WriteString.
start := 0
for i := 0; i < len(str); i++ {
c := str[i]
if c >= 0x20 && c != '"' && c != '\\' {
continue
}
if start < i {
sb.WriteString(str[start:i])
}
switch c {
case '"':
sb.WriteString(`\"`)
case '\\':
sb.WriteString(`\\`)
case '\b':
sb.WriteString(`\b`)
case '\f':
sb.WriteString(`\f`)
case '\n':
sb.WriteString(`\n`)
case '\r':
sb.WriteString(`\r`)
case '\t':
sb.WriteString(`\t`)
default:
const hex = "0123456789abcdef"
sb.WriteString(`\u00`)
sb.WriteByte(hex[c>>4])
sb.WriteByte(hex[c&0xF])
}
start = i + 1
}
if start < len(str) {
sb.WriteString(str[start:])
}
sb.WriteByte('"')
}
func valueToJSON(s *EvalState, vp *Value, sb *strings.Builder, ctx *NixStringContext, seen map[*Bindings]bool) error {
if err := s.forceValue(vp, NoPosIdx); err != nil {
return err
}
switch v := (*vp).(type) {
case VNull:
sb.WriteString("null")
case VBool:
if v.V {
sb.WriteString("true")
} else {
sb.WriteString("false")
}
case VInt:
sb.WriteString(strconv.FormatInt(v.V, 10))
case VFloat:
// Match C++ output: use strconv with shortest representation.
sb.WriteString(formatJSONFloat(v.V))
case VString:
if !utf8.ValidString(v.V) {
return evalErrorf("builtins.toJSON: string contains invalid UTF-8")
}
ctx.Merge(v.Context)
writeJSONString(sb, v.V)
case VPath:
// Mirrors C++ printValueAsJSON with copyToStore=true: NAR-hash the path,
// add it to the store, and record a CtxOpaque context entry.
key := fsPath(v.V)
name := path.Base(key)
storePath, err := s.Store.AddPathToStore(name, s.FS, key, v.V)
if err != nil {
return err
}
ctx.Add(ContextEntry{Kind: CtxOpaque, Path: storePath})
writeJSONString(sb, storePath)
case *VList:
sb.WriteByte('[')
for i := range v.Elems {
if i > 0 {
sb.WriteByte(',')
}
if err := valueToJSON(s, &v.Elems[i], sb, ctx, seen); err != nil {
return err
}
}
sb.WriteByte(']')
case VAttrs:
// Check for __toString first, then outPath (derivation-like).
// This mirrors C++ printValueAsJSON which calls tryAttrsToString
// (handles __toString) and then checks outPath before recursing
// into the attrset as a JSON object. Without the outPath check,
// derivation attrsets cause infinite recursion through the self-
// referential `all` attribute.
toStrSym := s.Symbols.Create("__toString")
if attr := v.Bindings.Get(toStrSym); attr != nil {
coerced := *vp
str, c, err := s.coerceToString(&coerced, CoerceStrict)
if err != nil {
return err
}
ctx.Merge(c)
writeJSONString(sb, str)
return nil
}
outPathSym := s.Symbols.Create("outPath")
if attr := v.Bindings.Get(outPathSym); attr != nil {
return valueToJSON(s, &attr.Value, sb, ctx, seen)
}
// Cycle detection for self-referential attrsets.
if seen[v.Bindings] {
return evalErrorf("builtins.toJSON: infinite recursion in attrset")
}
seen[v.Bindings] = true
// Emit attrset as JSON object, keys in lexicographic order.
sb.WriteByte('{')
idxs := lexicoOrder(s, v.Bindings)
all := v.Bindings.All()
for n, i := range idxs {
if n > 0 {
sb.WriteByte(',')
}
attr := &all[i]
writeJSONString(sb, s.Symbols.Str(attr.Name))
sb.WriteByte(':')
if err := valueToJSON(s, &attr.Value, sb, ctx, seen); err != nil {
delete(seen, v.Bindings)
return err
}
}
delete(seen, v.Bindings)
sb.WriteByte('}')
default:
return evalErrorf("builtins.toJSON: cannot convert %s to JSON", valueType(*vp))
}
return nil
}
// valueToJSONCtx serializes a Nix value as JSON into sb, collecting any string
// context into ctx. Mirrors C++ printValueAsJSON used in structuredAttrs.
func valueToJSONCtx(s *EvalState, vp *Value, sb *strings.Builder, ctx *NixStringContext, seen map[*Bindings]bool) error {
if err := s.forceValue(vp, NoPosIdx); err != nil {
return err
}
switch v := (*vp).(type) {
case VNull:
sb.WriteString("null")
case VBool:
if v.V {
sb.WriteString("true")
} else {
sb.WriteString("false")
}
case VInt:
sb.WriteString(strconv.FormatInt(v.V, 10))
case VFloat:
sb.WriteString(formatJSONFloat(v.V))
case VString:
if !utf8.ValidString(v.V) {
return evalErrorf("structuredAttrs: string contains invalid UTF-8")
}
ctx.Merge(v.Context)
writeJSONString(sb, v.V)
case VPath:
// Mirrors C++ printValueAsJSON with copyToStore=true: NAR-hash the path,
// add it to the store, and record a CtxOpaque context entry so the path
// appears in the derivation's inputSrcs. Without this, patch files and
// other path-valued attributes in __structuredAttrs derivations would be
// silently missing from the derivation's inputs.
key := fsPath(v.V)
name := path.Base(key)
storePath, err := s.Store.AddPathToStore(name, s.FS, key, v.V)
if err != nil {
return err
}
ctx.Add(ContextEntry{Kind: CtxOpaque, Path: storePath})
writeJSONString(sb, storePath)
case *VList:
sb.WriteByte('[')
for i := range v.Elems {
if i > 0 {
sb.WriteByte(',')
}
if err := valueToJSONCtx(s, &v.Elems[i], sb, ctx, seen); err != nil {
return err
}
}
sb.WriteByte(']')
case VAttrs:
// Check for __toString / outPath (derivation-like) first.
toStrSym := s.Symbols.Create("__toString")
if attr := v.Bindings.Get(toStrSym); attr != nil {
coerced := *vp
str, c, err := s.coerceToString(&coerced, CoerceStrict)
if err != nil {
return err
}
ctx.Merge(c)
writeJSONString(sb, str)
return nil
}
outPathSym := s.Symbols.Create("outPath")
if attr := v.Bindings.Get(outPathSym); attr != nil {
coerced := attr.Value
str, c, err := s.coerceToString(&coerced, CoerceStrict)
if err != nil {
return err
}
ctx.Merge(c)
writeJSONString(sb, str)
return nil
}
// Cycle detection for self-referential attrsets.
if seen[v.Bindings] {
return evalErrorf("structuredAttrs: infinite recursion in attrset")
}
seen[v.Bindings] = true
// Emit as JSON object with keys in lexicographic order.
sb.WriteByte('{')
idxs := lexicoOrder(s, v.Bindings)
all := v.Bindings.All()
for n, i := range idxs {
if n > 0 {
sb.WriteByte(',')
}
attr := &all[i]
writeJSONString(sb, s.Symbols.Str(attr.Name))
sb.WriteByte(':')
if err := valueToJSONCtx(s, &attr.Value, sb, ctx, seen); err != nil {
delete(seen, v.Bindings)
return err
}
}
delete(seen, v.Bindings)
sb.WriteByte('}')
default:
return evalErrorf("structuredAttrs: cannot convert %s to JSON", valueType(*vp))
}
return nil
}
// formatJSONFloat formats a float64 for JSON output matching C++ behaviour.
func formatJSONFloat(f float64) string {
if math.IsInf(f, 1) {
return "1.7976931348623157e+308" // C++ clamps to max double
}
if math.IsInf(f, -1) {
return "-1.7976931348623157e+308"
}
if math.IsNaN(f) {
return "null"
}
// Use shortest decimal representation that round-trips.
s := strconv.FormatFloat(f, 'f', -1, 64)
// If it has no decimal point and no exponent, add .0 to distinguish from int.
// But JSON doesn't require this — match C++ nlohmann which emits plain digits.
return s
}
// ---------------------------------------------------------------------------
// genericClosure
// ---------------------------------------------------------------------------
// primGenericClosure is builtins.genericClosure, a literal port of C++
// prim_genericClosure (lix/libexpr/primops.cc:565).
//
// It computes the transitive closure of startSet under operator, deduping
// elements by their `key` attribute. nixpkgs leans on it in exactly one place
// that matters here: lib/modules.nix:529 walks the NixOS module graph with it,
// so both the dedupe rule and the traversal order are inputs to every NixOS
// derivation hash.
//
// Three things about this function are ordering-sensitive and were each wrong
// before. They are listed here because none is visible from the Go code alone.
//
// 1. startSet is fetched and forced *before* operator, and an empty startSet
// returns immediately — so `genericClosure { startSet = []; }` is `[ ]` in
// nix even though `operator` is missing. Fetching operator first turned
// that into "missing 'operator'".
//
// 2. The empty case returns the startSet *value itself*, not a fresh empty
// list, which keeps pointer identity for eqValues to short-circuit on.
//
// 3. Elements are forced when they are *pushed* onto the work set
// (primops.cc:643), not when they are popped. With a throwing element
// later in the operator's return list, forcing on pop lets a subsequent
// iteration's error surface first, so the reported error differs from
// nix's.
func primGenericClosure(s *EvalState, a0 Value) (Value, error) {
argV := a0
bindings, err := s.forceAttrs(&argV, NoPosIdx, "while evaluating the first argument passed to builtins.genericClosure")
if err != nil {
return nil, err
}
// startSet first, and return it unchanged when empty — see (1) and (2).
startSetAttr := bindings.Get(s.Symbols.Create("startSet"))
if startSetAttr == nil {
return nil, evalErrorf("builtins.genericClosure: missing 'startSet'")
}
startElems, err := s.forceList(&startSetAttr.Value, NoPosIdx,
"while evaluating the 'startSet' attribute passed as argument to builtins.genericClosure")
if err != nil {
return nil, err
}
if len(startElems) == 0 {
return startSetAttr.Value, nil
}
operatorAttr := bindings.Get(s.Symbols.Create("operator"))
if operatorAttr == nil {
return nil, evalErrorf("builtins.genericClosure: missing 'operator'")
}
// C++ forceFunction's here, before any element is touched, so a
// non-function operator is reported even when an element would throw.
if err := s.forceFunction(&operatorAttr.Value, NoPosIdx,
"while evaluating the 'operator' attribute passed as argument to builtins.genericClosure"); err != nil {
return nil, err
}
const keyCtx = "while comparing the `key` attributes of two genericClosure elements"
keySym := s.Symbols.Create("key")
var result []Value
// worklist is a slice used as a queue.
worklist := make([]Value, len(startElems))
copy(worklist, startElems)
// doneKeys holds the keys already seen, kept sorted by compareValues so
// membership is a binary search.
//
// C++ uses std::set<Value, CompareValues>, and matching *that* — rather
// than the eqValues scan this used to do — is what fixes two things at
// once. Correctness: the ordering rejects key types eqValues accepts, so
// `key = true` now errors as it does in nix instead of silently deduping.
// Complexity: the old scan called eqValues against every previously-seen
// key, i.e. O(n^2) with a full deep comparison per step.
//
// A Go map is not available as an alternative: keys may be lists, which
// are not comparable in Go's sense, and the ordering is the only total
// relation defined over them.
var doneKeys []Value
// seenKey reports whether k is already in doneKeys, inserting it if not.
seenKey := func(k Value) (bool, error) {
// A hand-rolled binary search rather than sort.Search, because the
// predicate can fail (comparing two incomparable keys is an error)
// and sort.Search's signature has nowhere to put that.
lo, hi := 0, len(doneKeys)
for lo < hi {
mid := int(uint(lo+hi) >> 1)
less, err := s.compareValues(doneKeys[mid], k, NoPosIdx, keyCtx)
if err != nil {
return false, err
}
if less {
lo = mid + 1
} else {
hi = mid
}
}
// lo is the first index whose key is not < k. It is a duplicate iff
// that key is also not > k, i.e. the two are equivalent under the
// ordering — which is what std::set membership means. Note this is
// deliberately *not* eqValues: equivalence-under-the-ordering is the
// relation C++'s set uses, and for int/float keys they differ.
if lo < len(doneKeys) {
greater, err := s.compareValues(k, doneKeys[lo], NoPosIdx, keyCtx)
if err != nil {
return false, err
}
if !greater {
return true, nil
}
}
doneKeys = append(doneKeys, nil)
copy(doneKeys[lo+1:], doneKeys[lo:])
doneKeys[lo] = k
return false, nil
}
// Force each start element up front, matching the push-time forcing the
// operator's results get below.
for i := range worklist {
if err := s.forceValue(&worklist[i], NoPosIdx); err != nil {
return nil, err
}
}
for len(worklist) > 0 {
elem := worklist[0]
worklist = worklist[1:]
elemBindings, err := s.forceAttrs(&elem, NoPosIdx,
"while evaluating one of the elements generated by (or initially passed to) builtins.genericClosure")
if err != nil {
return nil, err
}
keyAttr := elemBindings.Get(keySym)
if keyAttr == nil {
return nil, evalErrorf("attribute 'key' missing, " +
"in one of the attrsets generated by (or initially passed to) builtins.genericClosure")
}
keyVal := keyAttr.Value
if err := s.forceValue(&keyVal, NoPosIdx); err != nil {
return nil, err
}
dup, err := seenKey(keyVal)
if err != nil {
return nil, err
}
if dup {
continue
}
result = append(result, elem)
// Call operator(elem) to get new elements.
newElems, err := s.callFunction(operatorAttr.Value, []Value{elem}, NoPosIdx)
if err != nil {
return nil, err
}
newList, err := s.forceList(&newElems, NoPosIdx,
"while evaluating the return value of the `operator` passed to builtins.genericClosure")
if err != nil {
return nil, err
}
// Force on push, not on pop — see (3).
for i := range newList {
v := newList[i]
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
worklist = append(worklist, v)
}
}
return newList(s, result), nil
}
// ---------------------------------------------------------------------------
// version builtins: splitVersion, parseDrvName, compareVersions
// ---------------------------------------------------------------------------
// nixVersionComponents splits a version string into components, matching C++
// names.cc nextComponent: skip . and - separators, consume digit or alpha runs.
func nixVersionComponents(v string) []string {
var parts []string
i := 0
for i < len(v) {
// Skip separators.
for i < len(v) && (v[i] == '.' || v[i] == '-') {
i++
}
if i >= len(v) {
break
}
j := i
if v[j] >= '0' && v[j] <= '9' {
for j < len(v) && v[j] >= '0' && v[j] <= '9' {
j++
}
} else {
for j < len(v) && v[j] != '.' && v[j] != '-' && !(v[j] >= '0' && v[j] <= '9') {
j++
}
}
parts = append(parts, v[i:j])
i = j
}
return parts
}
// primSplitVersion ports C++ prim_splitVersion (primops.cc:3140), which
// calls forceStringNoCtx.
func primSplitVersion(s *EvalState, a0 Value) (Value, error) {
v := a0
str, err := s.forceStringNoContext(&v, NoPosIdx,
"while evaluating the first argument passed to builtins.splitVersion")
if err != nil {
return nil, err
}
parts := nixVersionComponents(str)
elems := make([]Value, len(parts))
for i, p := range parts {
elems[i] = VString{V: p}
}
return newList(s, elems), nil
}
// primParseDrvName ports C++ prim_parseDrvName (primops.cc:3122), which
// calls forceStringNoCtx.
func primParseDrvName(s *EvalState, a0 Value) (Value, error) {
v := a0
str, err := s.forceStringNoContext(&v, NoPosIdx,
"while evaluating the first argument passed to builtins.parseDrvName")
if err != nil {
return nil, err
}
// Find first '-' not followed by a letter.
name, version := str, ""
for i := 0; i < len(str); i++ {
if str[i] == '-' && (i+1 >= len(str) || !unicode.IsLetter(rune(str[i+1]))) {
name = str[:i]
version = str[i+1:]
break
}
}
b := newBindings(s, 2)
b.attrs = append(b.attrs,
Attr{Name: s.Symbols.Create("name"), Value: VString{V: name}},
Attr{Name: s.Symbols.Create("version"), Value: VString{V: version}},
)
b.Sort()
return VAttrs{Bindings: b}, nil
}
// componentLT compares two version components matching C++ componentsLT.
// Order: pre < "" < alpha < number (with lexicographic within same class).
func componentLT(a, b string) bool {
aIsNum := len(a) > 0 && a[0] >= '0' && a[0] <= '9'
bIsNum := len(b) > 0 && b[0] >= '0' && b[0] <= '9'
switch {
case a == b:
return false
case a == "pre":
return true // pre < everything else
case b == "pre":
return false // everything > pre
case a == "":
return true // empty < number or alpha (but not pre, handled above)
case b == "":
return false // number or alpha > empty
case aIsNum && bIsNum:
ai, _ := strconv.Atoi(a)
bi, _ := strconv.Atoi(b)
return ai < bi
case aIsNum:
return false // number > alpha
case bIsNum:
return true // alpha < number
default:
return a < b // lexicographic
}
}
func compareVersionStrings(v1, v2 string) int {
c1 := nixVersionComponents(v1)
c2 := nixVersionComponents(v2)
maxLen := len(c1)
if len(c2) > maxLen {
maxLen = len(c2)
}
for i := 0; i < maxLen; i++ {
var a, b string
if i < len(c1) {
a = c1[i]
}
if i < len(c2) {
b = c2[i]
}
if componentLT(a, b) {
return -1
}
if componentLT(b, a) {
return 1
}
}
return 0
}
// primCompareVersions ports C++ prim_compareVersions (primops.cc:3132), which
// calls forceStringNoCtx on both arguments.
func primCompareVersions(s *EvalState, a0, a1 Value) (Value, error) {
v1V := a0
v1, err := s.forceStringNoContext(&v1V, NoPosIdx,
"while evaluating the first argument passed to builtins.compareVersions")
if err != nil {
return nil, err
}
v2V := a1
v2, err := s.forceStringNoContext(&v2V, NoPosIdx,
"while evaluating the second argument passed to builtins.compareVersions")
if err != nil {
return nil, err
}
return VInt{V: int64(compareVersionStrings(v1, v2))}, nil
}
// ---------------------------------------------------------------------------
// readFile
// ---------------------------------------------------------------------------
// nixPathStr extracts a path string from a forced Value (VPath or VString).
// coerceToPath coerces a value to an absolute path string, handling VPath,
// VString, and VAttrs (via outPath/__toString). Mirrors C++
// EvalState::coerceToPath → coerceToString(Strict, copyToStore=false).
func (s *EvalState) coerceToPath(vp *Value, builtin string) (string, error) {
str, _, err := s.coerceToString(vp, CoerceStrict, false)
if err != nil {
return "", evalErrorf("builtins.%s: %v", builtin, err)
}
if str == "" || str[0] != '/' {
return "", evalErrorf("builtins.%s: string '%s' doesn't represent an absolute path", builtin, str)
}
return str, nil
}
// realisePath coerces a value to a path string and realises any store paths
// in its string context (IFD: import-from-derivation). This mirrors C++
// realisePath which calls realiseContext before accessing the file.
func (s *EvalState) realisePath(vp *Value, builtin string) (string, error) {
str, ctx, err := s.coerceToString(vp, CoerceStrict, false)
if err != nil {
return "", evalErrorf("builtins.%s: %v", builtin, err)
}
if str == "" || str[0] != '/' {
return "", evalErrorf("builtins.%s: string '%s' doesn't represent an absolute path", builtin, str)
}
if err := s.realiseContext(ctx); err != nil {
return "", evalErrorf("builtins.%s: while realising context of '%s': %v", builtin, str, err)
}
return str, nil
}
// realiseContext ensures all store paths referenced in the string context
// exist on disk, building them via the daemon if necessary. This is the
// mechanism behind import-from-derivation (IFD).
func (s *EvalState) realiseContext(ctx NixStringContext) error {
if ctx.IsEmpty() {
return nil
}
r, ok := s.Store.(Realizer)
if !ok {
return nil // no daemon — can't realise, hope the paths exist
}
for _, e := range ctx.Entries() {
var storePath string
switch e.Kind {
case CtxOpaque:
storePath = e.Path
case CtxBuilt:
// For CtxBuilt, the path is the .drv path and Output is the output name.
// We need the output store path. Look up the derivation to find it.
drv := s.Store.GetDerivation(e.Path)
if drv == nil {
// Not a known drv — try realising the drv path itself.
storePath = e.Path
} else {
out, ok := drv.Outputs[e.Output]
if !ok {
return evalErrorf("realiseContext: derivation %s has no output '%s'", e.Path, e.Output)
}
storePath = out.Path
}
case CtxDrvDeep:
storePath = e.Path
default:
continue
}
if err := r.EnsureRealized(storePath); err != nil {
return err
}
// The store has been mutated: paths may exist now that did not when we
// last resolved them. See EvalState.resolvePath.
s.ifdHappened = true
}
return nil
}
// nixPathStr coerces a value to an absolute path string.
// It is a thin wrapper around coerceToPath for use by path-accepting builtins.
func (s *EvalState) nixPathStr(vp *Value, builtin string) (string, error) {
return s.coerceToPath(vp, builtin)
}
// primPath implements builtins.path { path, name?, filter?, recursive?, sha256? }.
// It walks the filesystem tree at `path`, applying `filter` to each entry,
// serialises the filtered tree as a NAR, hashes it with SHA256, optionally
// verifies the hash against the expected `sha256`, computes the store path,
// and returns a string value with CtxOpaque context.
// Mirrors C++ addPath / prim_path in primops.cc.
func primPath(s *EvalState, a0 Value) (Value, error) {
bindings, err := s.forceAttrs(&a0, NoPosIdx, "while evaluating the argument passed to 'builtins.path'")
if err != nil {
return nil, err
}
// --- parse attributes ---
var nixAbsPath string // the Nix-level absolute path (e.g. "/pwd")
var name string
var filterFun *Value
recursive := true // default
var expectedHash []byte
all := bindings.All()
for i := range all {
attr := &all[i]
attrPos := attr.Pos
attrName := s.Symbols.Str(attr.Name)
switch attrName {
case "path":
v := attr.Value
if err := s.forceValue(&v, attrPos); err != nil {
return nil, err
}
switch t := v.(type) {
case VPath:
nixAbsPath = t.V
case VString:
nixAbsPath = t.V
default:
return nil, evalErrorf("builtins.path: 'path' must be a path or string, got %s", valueType(v))
}
case "name":
// C++ forceStringNoCtx (primops.cc:1870).
v := attr.Value
name, err = s.forceStringNoContext(&v, attrPos,
"while evaluating the `name` attribute passed to builtins.path")
if err != nil {
return nil, err
}
case "filter":
v := attr.Value
if err := s.forceValue(&v, attrPos); err != nil {
return nil, err
}
filterFun = &all[i].Value
case "recursive":
v := attr.Value
recursive, err = s.forceBool(&v, attrPos)
if err != nil {
return nil, evalErrorf("while evaluating the 'recursive' attribute passed to builtins.path: %v", err)
}
case "sha256":
// C++ forceStringNoCtx (primops.cc:1889).
v := attr.Value
hashStr, err := s.forceStringNoContext(&v, attrPos,
"while evaluating the `sha256` attribute passed to builtins.path")
if err != nil {
return nil, err
}
expectedHash, err = ParseNixHash(hashStr)
if err != nil {
return nil, evalErrorf("builtins.path: invalid sha256 %q: %v", hashStr, err)
}
default:
return nil, evalErrorf("unsupported argument '%s' to builtins.path", attrName)
}
}
if nixAbsPath == "" {
return nil, evalErrorf("missing required 'path' attribute in the first argument to builtins.path")
}
// Default name to the basename of the path.
if name == "" {
name = path.Base(nixAbsPath)
}
// The fs.FS key for the root path.
rootKey := fsPath(nixAbsPath)
// The display path passed to the filter matches the user-provided path.
rootNixPath := nixAbsPath
// Build the filter callback: wraps the Nix filter function.
var goFilter func(nixPath, fileType string) (bool, error)
if filterFun != nil {
fn := *filterFun
goFilter = func(nixPath, fileType string) (bool, error) {
pv := Value(VString{V: nixPath})
tv := Value(VString{V: fileType})
result, err := s.callFunction(fn, []Value{pv, tv}, NoPosIdx)
if err != nil {
return false, err
}
b, err := s.forceBool(&result, NoPosIdx)
if err != nil {
return false, evalErrorf("filter function must return a boolean: %v", err)
}
return b, nil
}
}
// Compute the NAR hash of the filtered tree.
narHash, err := NARHashPath(s.FS, rootKey, rootNixPath, goFilter)
if err != nil {
return nil, evalErrorf("while adding path '%s': %v", nixAbsPath, err)
}
// If the caller provided an expected hash, verify it.
if expectedHash != nil {
if len(narHash) != len(expectedHash) || !bytesEqual(narHash, expectedHash) {
return nil, evalErrorf(
"store path mismatch in (possibly filtered) path added from '%s'",
nixAbsPath,
)
}
}
// Compute the store path via the Store.
method := "recursive"
if !recursive {
method = "flat"
}
storePath, err := s.Store.AddFixedOutputPath(name, "sha256", method, narHash)
if err != nil {
return nil, evalErrorf("while computing store path for '%s': %v", nixAbsPath, err)
}
// Return as a string with CtxOpaque context (mirrors allowAndSetStorePathString).
var ctx NixStringContext
ctx.Add(ContextEntry{Kind: CtxOpaque, Path: storePath})
return VString{V: storePath, Context: ctx}, nil
}
// primFilterSource implements builtins.filterSource filter path.
// It is equivalent to builtins.path { filter = filter; path = path; } with
// the name defaulting to baseNameOf(path) and recursive = true.
// Mirrors C++ prim_filterSource in primops.cc.
func primFilterSource(s *EvalState, a0, a1 Value) (Value, error) {
// a0 = filter function, a1 = path
filterVal := a0
if err := s.forceValue(&filterVal, NoPosIdx); err != nil {
return nil, err
}
pathVal := a1
nixAbsPath, err := s.nixPathStr(&pathVal, "filterSource")
if err != nil {
return nil, err
}
name := path.Base(nixAbsPath)
rootKey := fsPath(nixAbsPath)
fn := filterVal
goFilter := func(nixPath, fileType string) (bool, error) {
pv := Value(VString{V: nixPath})
tv := Value(VString{V: fileType})
result, err := s.callFunction(fn, []Value{pv, tv}, NoPosIdx)
if err != nil {
return false, err
}
b, err := s.forceBool(&result, NoPosIdx)
if err != nil {
return false, evalErrorf("filter function must return a boolean: %v", err)
}
return b, nil
}
narHash, err := NARHashPath(s.FS, rootKey, nixAbsPath, goFilter)
if err != nil {
return nil, evalErrorf("while adding path '%s': %v", nixAbsPath, err)
}
storePath, err := s.Store.AddFixedOutputPath(name, "sha256", "recursive", narHash)
if err != nil {
return nil, evalErrorf("while computing store path for '%s': %v", nixAbsPath, err)
}
var ctx NixStringContext
ctx.Add(ContextEntry{Kind: CtxOpaque, Path: storePath})
return VString{V: storePath, Context: ctx}, nil
}
// bytesEqual reports whether a and b have the same contents.
func bytesEqual(a, b []byte) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
func primPathExists(s *EvalState, a0 Value) (Value, error) {
v := a0
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
// mustBeDir: a string argument ending with "/" or "/." means the path must
// be a directory (uses stat, follows symlinks). VPath arguments never set
// mustBeDir (C++: only nString values carry trailing-slash information).
// Mirrors C++ prim_pathExists: arg.str().ends_with("/") || ends_with("/.").
// Check the original value before coercion so we preserve the string type.
mustBeDir := false
if sv, isStr := v.(VString); isStr {
mustBeDir = strings.HasSuffix(sv.V, "/") || strings.HasSuffix(sv.V, "/.")
}
pathStr, err := s.nixPathStr(&v, "pathExists")
if err != nil {
return nil, err
}
key := filepath.Clean(fsPath(pathStr))
if mustBeDir {
// stat (follows all symlinks): path must exist and be a directory.
info, statErr := fs.Stat(s.FS, key)
if statErr != nil || !info.IsDir() {
return VFalseSingleton, nil
}
return VTrueSingleton, nil
}
// lstat semantics: follow intermediate symlinks, but a broken final
// symlink still counts as "exists".
// Try stat first — succeeds for regular paths and paths through symlinks.
if _, statErr := fs.Stat(s.FS, key); statErr == nil {
return VTrueSingleton, nil
}
// Stat failed: may be a broken symlink. ReadFileType is lstat-like
// (checks the map entry directly without following the final symlink).
if _, typeErr := s.FS.ReadFileType(key); typeErr == nil {
return VTrueSingleton, nil
}
return VFalseSingleton, nil
}
func primReadDir(s *EvalState, a0 Value) (Value, error) {
v := a0
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
pathStr, err := s.nixPathStr(&v, "readDir")
if err != nil {
return nil, err
}
key := filepath.Clean(fsPath(pathStr))
entries, err := fs.ReadDir(s.FS, key)
if err != nil {
return nil, evalErrorf("builtins.readDir: %v", err)
}
b := newBindings(s, len(entries))
for _, e := range entries {
var typStr string
// Use lstat semantics (no symlink follow) matching C++.
if e.Type()&fs.ModeSymlink != 0 {
typStr = "symlink"
} else if e.IsDir() {
typStr = "directory"
} else {
typStr = "regular"
}
b.attrs = append(b.attrs, Attr{
Name: s.Symbols.Create(e.Name()),
Value: VString{V: typStr},
})
}
b.Sort()
return VAttrs{Bindings: b}, nil
}
func primReadFileType(s *EvalState, a0 Value) (Value, error) {
v := a0
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
pathStr, err := s.nixPathStr(&v, "readFileType")
if err != nil {
return nil, err
}
key := filepath.Clean(fsPath(pathStr))
typStr, err := s.FS.ReadFileType(key)
if err != nil {
return nil, evalErrorf("builtins.readFileType: %v", err)
}
return VString{V: typStr}, nil
}
// primToFile implements builtins.toFile: compute a store path for a text file
// with string context references, mirroring C++ prim_toFile.
// The result is a string with an Opaque context entry for the store path.
// primToFile ports C++ prim_toFile (primops.cc:1707): the file name is
// forceStringNoCtx, the contents forceString. Neither coerces — the contents
// are written to the store verbatim, so accepting a path (and silently
// writing *its* store path as the file's text) is not a coercion anyone
// asked for.
func primToFile(s *EvalState, a0, a1 Value) (Value, error) {
nameV := a0
contentV := a1
name, err := s.forceStringNoContext(&nameV, NoPosIdx,
"while evaluating the first argument passed to builtins.toFile")
if err != nil {
return nil, err
}
contentSv, err := s.forceString(&contentV, NoPosIdx,
"while evaluating the second argument passed to builtins.toFile")
if err != nil {
return nil, err
}
content, ctx := contentSv.V, contentSv.Context
// Collect store-path references from the string context.
// C++ rejects drv-deep context entries in toFile (they can't be listed as refs).
var refs []string
refSet := make(map[string]bool)
for _, entry := range ctx.Entries() {
if entry.Kind == CtxDrvDeep {
return nil, evalErrorf("builtins.toFile: file '%s' has drv-deep context; cannot be added to the store", name)
}
if !refSet[entry.Path] {
refs = append(refs, entry.Path)
refSet[entry.Path] = true
}
}
sort.Strings(refs)
// Compute the store path via the Store.
storePath, err := s.Store.AddTextToStore(name, content, refs)
if err != nil {
return nil, evalErrorf("builtins.toFile: %v", err)
}
// Build output context: opaque reference to the store path + all input refs.
var outCtx NixStringContext
outCtx.Add(ContextEntry{Kind: CtxOpaque, Path: storePath})
for _, r := range refs {
outCtx.Add(ContextEntry{Kind: CtxOpaque, Path: r})
}
return VString{V: storePath, Context: outCtx}, nil
}
func primToPath(s *EvalState, a0 Value) (Value, error) {
v := a0
str, ctx, err := s.coerceToString(&v, CoerceStrict, false)
if err != nil {
return nil, err
}
// Validate that it's an absolute path.
if len(str) == 0 || str[0] != '/' {
return nil, evalErrorf("builtins.toPath: not an absolute path: '%s'", str)
}
return VString{V: filepath.Clean(str), Context: ctx}, nil
}
func primReadFile(s *EvalState, a0 Value) (Value, error) {
v := a0
pathStr, err := s.realisePath(&v, "readFile")
if err != nil {
return nil, err
}
data, err := s.readFile(pathStr)
if err != nil {
return nil, evalErrorf("builtins.readFile: %v", err)
}
return VString{V: string(data)}, nil
}
// ---------------------------------------------------------------------------
// fromTOML
// ---------------------------------------------------------------------------
// primFromTOML ports C++ prim_fromTOML (primops/fromTOML.cc:10), which calls
// forceStringNoCtx.
func primFromTOML(s *EvalState, a0 Value) (Value, error) {
v := a0
str, err := s.forceStringNoContext(&v, NoPosIdx,
"while evaluating the argument passed to builtins.fromTOML")
if err != nil {
return nil, err
}
var raw interface{}
if err := toml.Unmarshal([]byte(str), &raw); err != nil {
return nil, evalErrorf("builtins.fromTOML: %v", err)
}
return tomlToValue(s, raw)
}
func tomlToValue(s *EvalState, v interface{}) (Value, error) {
switch t := v.(type) {
case nil:
return VNullSingleton, nil
case bool:
if t {
return VTrueSingleton, nil
}
return VFalseSingleton, nil
case int64:
return VInt{V: t}, nil
case float64:
return VFloat{V: t}, nil
case string:
return VString{V: t}, nil
case []interface{}:
elems := make([]Value, len(t))
for i, elem := range t {
val, err := tomlToValue(s, elem)
if err != nil {
return nil, err
}
elems[i] = val
}
return newList(s, elems), nil
case []map[string]interface{}:
// TOML array-of-tables comes as []map[string]interface{} not []interface{}.
elems := make([]Value, len(t))
for i, elem := range t {
val, err := tomlToValue(s, elem)
if err != nil {
return nil, err
}
elems[i] = val
}
return newList(s, elems), nil
case map[string]interface{}:
b := newBindings(s, len(t))
for key, val := range t {
v, err := tomlToValue(s, val)
if err != nil {
return nil, err
}
b.attrs = append(b.attrs, Attr{Name: s.Symbols.Create(key), Value: v})
}
b.Sort()
return VAttrs{Bindings: b}, nil
default:
return nil, evalErrorf("builtins.fromTOML: unsupported TOML type %T (dates/times not supported)", v)
}
}
// ---------------------------------------------------------------------------
// derivationStrict
// ---------------------------------------------------------------------------
// derivationNixSrc is the Nix source of the `derivation` wrapper function,
// embedded verbatim from lix/libexpr/primops/derivation.nix.
// It is parsed lazily on first call to the `derivation` builtin.
const derivationNixSrc = `
drvAttrs@{
outputs ? [ "out" ],
...
}:
let
strict = derivationStrict drvAttrs;
commonAttrs =
drvAttrs
// (builtins.listToAttrs outputsList)
// {
all = map (x: x.value) outputsList;
inherit drvAttrs;
};
outputToAttrListElement = outputName: {
name = outputName;
value = commonAttrs // {
outPath = builtins.getAttr outputName strict;
drvPath = strict.drvPath;
type = "derivation";
inherit outputName;
};
};
outputsList = map outputToAttrListElement outputs;
in
(builtins.head outputsList).value
`
// fetchurlNixSrc is the Nix source of the built-in fetchurl function,
// embedded verbatim from lix/libexpr/fetchurl.nix.
// Served from the virtual /__corepkgs__/fetchurl.nix path.
const fetchurlNixSrc = `
{
system ? "",
url,
hash ? "",
md5 ? "",
sha1 ? "",
sha256 ? "",
sha512 ? "",
outputHash ?
if hash != "" then hash
else if sha512 != "" then sha512
else if sha1 != "" then sha1
else if md5 != "" then md5
else sha256,
outputHashAlgo ?
if hash != "" then ""
else if sha512 != "" then "sha512"
else if sha1 != "" then "sha1"
else if md5 != "" then "md5"
else "sha256",
executable ? false,
unpack ? false,
name ? baseNameOf (toString url),
impure ? false,
}:
derivation (
{
builder = "builtin:fetchurl";
outputHashMode = if unpack || executable then "recursive" else "flat";
inherit name url executable unpack;
system = "builtin";
preferLocalBuild = true;
impureEnvVars = [ "http_proxy" "https_proxy" "ftp_proxy" "all_proxy" "no_proxy" ];
urls = [ url ];
}
// (if impure then { __impure = true; } else { inherit outputHashAlgo outputHash; })
)
`
// corepkgsPrefix is the virtual path prefix under which the embedded sources
// below are served. Nothing under it exists on disk, so it is also the marker
// that tells the filesystem-touching paths (importPath's directory probe,
// prefetch's speculative read) not to go looking.
const corepkgsPrefix = "/__corepkgs__/"
// corepkgsSources maps virtual /__corepkgs__/<name> paths to their embedded
// Nix source, mirroring the C++ corepkgsPrefix virtual filesystem.
var corepkgsSources = map[string]string{
"fetchurl.nix": fetchurlNixSrc,
}
// primDerivationStrict implements builtins.derivationStrict.
// It mirrors C++ derivationStrictInternal:
// 1. Iterates attrs in lexicographic order, coercing values to strings.
// 2. Processes string context → inputDrvs / inputSrcs.
// 3. Computes output store paths via the masked-ATerm hash.
// 4. Computes the .drv store path.
// 5. Returns an attrset with drvPath (CtxDrvDeep) and per-output paths (CtxBuilt).
//
// Limitations vs C++:
// - __structuredAttrs is not supported (TODO).
// - Fixed-output derivations (outputHash/outputHashAlgo) are not supported (TODO).
// - CtxDrvDeep context in attrs → simplified: adds the .drv path to inputSrcs
// instead of computing the full closure (requires a real store).
func primDerivationStrict(s *EvalState, a0 Value) (Value, error) {
attrs, err := s.forceAttrs(&a0, NoPosIdx, "")
if err != nil {
return nil, evalErrorf("builtins.derivationStrict: argument must be a set")
}
// Extract name first.
nameSym := s.Symbols.Create("name")
nameAttr := attrs.Get(nameSym)
if nameAttr == nil {
return nil, evalErrorf("required attribute 'name' missing")
}
// C++ forceStringNoCtx (primops.cc:937). Like `system` and the outputHash
// attributes below, this is strict: the derivation's name is not a place
// that coerces a path or a __toString set.
drvName, err := s.forceStringNoContext(&nameAttr.Value, nameAttr.Pos,
"while evaluating the `name` attribute passed to builtins.derivationStrict")
if err != nil {
return nil, err
}
if strings.HasSuffix(drvName, ".drv") {
return nil, evalErrorf("derivation names are not allowed to end in '.drv'")
}
// Check for __structuredAttrs.
structAttrsSym := s.Symbols.Create("__structuredAttrs")
structuredAttrs := false
if a := attrs.Get(structAttrsSym); a != nil {
b, err := s.forceBool(&a.Value, NoPosIdx)
if err == nil {
structuredAttrs = b
}
}
// Check for __ignoreNulls.
ignoreNullsSym := s.Symbols.Create("__ignoreNulls")
ignoreNulls := false
if a := attrs.Get(ignoreNullsSym); a != nil {
b, err := s.forceBool(&a.Value, NoPosIdx)
if err == nil {
ignoreNulls = b
}
}
drv := NewDerivation(drvName)
var sharedCtx NixStringContext
var outputHash string
var outputHashAlgo string
var ingestionMethod string // "recursive" or "flat"
outputs := []string{"out"}
// Special attribute symbols.
argsSym := s.Symbols.Create("args")
builderSym := s.Symbols.Create("builder")
systemSym := s.Symbols.Create("system")
outputsSym := s.Symbols.Create("outputs")
outputHashSym := s.Symbols.Create("outputHash")
outputHashAlgoSym := s.Symbols.Create("outputHashAlgo")
outputHashModeSym := s.Symbols.Create("outputHashMode")
// Iterate attrs in lexicographic order (matching C++ lexicographicOrder).
// Our Bindings are already sorted by symbol ID (creation order), which
// matches the C++ symbol table order and thus lexicographic order.
// But to be safe, sort by name string.
type namedAttr struct {
name string
attr *Attr
}
all := attrs.All()
ordered := make([]namedAttr, 0, len(all))
for i := range all {
ordered = append(ordered, namedAttr{
name: s.Symbols.Str(all[i].Name),
attr: &all[i],
})
}
sort.Slice(ordered, func(i, j int) bool {
return ordered[i].name < ordered[j].name
})
// For __structuredAttrs, we build a JSON object instead of coercing
// each attr to a string. jsonBuf accumulates the JSON object body
// (between the outer braces).
var jsonBuf strings.Builder
jsonFirstKey := true
jsonSeen := make(map[*Bindings]bool)
for _, na := range ordered {
key := na.name
sym := na.attr.Name
val := na.attr.Value
// Skip internal attrs.
if key == "__ignoreNulls" {
continue
}
// Skip __structuredAttrs only in structured-attrs mode (in normal mode
// it is coerced to "" and added to the env, matching C++ behaviour).
if key == "__structuredAttrs" && structuredAttrs {
continue
}
if ignoreNulls {
v := val
if err := s.forceValue(&v, NoPosIdx); err != nil {
return nil, err
}
if _, isNull := v.(VNull); isNull {
continue
}
}
if sym == argsSym {
// args: list of builder arguments — same for both modes.
elems, err := s.forceList(&val, NoPosIdx, "")
if err != nil {
return nil, evalErrorf("'args' must be a list: %v", err)
}
for i := range elems {
str, ctx, err := s.coerceToString(&elems[i], CoerceToString)
if err != nil {
return nil, evalErrorf("in 'args': %v", err)
}
drv.Args = append(drv.Args, str)
sharedCtx.Merge(ctx)
}
continue
}
if structuredAttrs {
// Structured attrs mode: serialize value as JSON into jsonBuf,
// and extract special attrs (builder, system, outputs, etc.)
// directly from their values rather than from string coercion.
// Mirrors C++ derivationStrictInternal jsonObject branch.
if !jsonFirstKey {
jsonBuf.WriteByte(',')
}
jsonFirstKey = false
writeJSONString(&jsonBuf, key)
jsonBuf.WriteByte(':')
vCopy := val
if err := valueToJSONCtx(s, &vCopy, &jsonBuf, &sharedCtx, jsonSeen); err != nil {
return nil, evalErrorf("in derivation attribute '%s': %v", key, err)
}
// Extract special attrs from the forced value.
switch sym {
case builderSym:
str, ctx, err := s.coerceToString(&val, CoerceStrict)
if err != nil {
return nil, evalErrorf("'builder': %v", err)
}
drv.Builder = str
sharedCtx.Merge(ctx)
case systemSym:
str, err := s.forceStringNoContext(&val, NoPosIdx,
"while evaluating the `system` attribute passed to builtins.derivationStrict")
if err != nil {
return nil, err
}
drv.Platform = str
case outputHashSym:
str, err := s.forceStringNoContext(&val, NoPosIdx,
"while evaluating the `outputHash` attribute passed to builtins.derivationStrict")
if err != nil {
return nil, err
}
outputHash = str
case outputHashAlgoSym:
str, err := s.forceStringNoContext(&val, NoPosIdx,
"while evaluating the `outputHashAlgo` attribute passed to builtins.derivationStrict")
if err != nil {
return nil, err
}
outputHashAlgo = str
case outputHashModeSym:
str, err := s.forceStringNoContext(&val, NoPosIdx,
"while evaluating the `outputHashMode` attribute passed to builtins.derivationStrict")
if err != nil {
return nil, err
}
switch str {
case "recursive", "flat":
ingestionMethod = str
default:
return nil, evalErrorf("invalid value '%s' for 'outputHashMode'", str)
}
case outputsSym:
elems, err := s.forceList(&val, NoPosIdx, "")
if err != nil {
return nil, evalErrorf("'outputs' must be a list: %v", err)
}
outputs = outputs[:0]
for i := range elems {
o, err := s.forceStringNoContext(&elems[i], NoPosIdx,
"while evaluating the `outputs` attribute passed to builtins.derivationStrict")
if err != nil {
return nil, err
}
if o == "drv" {
return nil, evalErrorf("invalid derivation output name 'drv'")
}
outputs = append(outputs, o)
}
if len(outputs) == 0 {
return nil, evalErrorf("derivation cannot have an empty set of outputs")
}
}
} else {
// Normal mode: coerce each attr to a string.
str, ctx, err := s.coerceToString(&val, CoerceToString)
if err != nil {
return nil, evalErrorf("in derivation attribute '%s': %v", key, err)
}
drv.Env[key] = str
sharedCtx.Merge(ctx)
switch sym {
case builderSym:
drv.Builder = str
case systemSym:
drv.Platform = str
case outputHashSym:
outputHash = str
case outputHashAlgoSym:
outputHashAlgo = str
case outputHashModeSym:
switch str {
case "recursive", "flat":
ingestionMethod = str
default:
return nil, evalErrorf("invalid value '%s' for 'outputHashMode'", str)
}
case outputsSym:
// Tokenize space-separated output names.
outputs = strings.Fields(str)
if len(outputs) == 0 {
return nil, evalErrorf("derivation cannot have an empty set of outputs")
}
for _, o := range outputs {
if o == "drv" {
return nil, evalErrorf("invalid derivation output name 'drv'")
}
}
}
}
}
// In structured attrs mode, finalise the __json env var.
if structuredAttrs {
drv.Env["__json"] = "{" + jsonBuf.String() + "}"
}
// Validate required fields.
if drv.Builder == "" {
return nil, evalErrorf("required attribute 'builder' missing")
}
if drv.Platform == "" {
return nil, evalErrorf("required attribute 'system' missing")
}
// Process context entries → inputDrvs / inputSrcs.
for _, e := range sharedCtx.Entries() {
switch e.Kind {
case CtxOpaque:
drv.InputSrcs.Add(e.Path)
case CtxBuilt:
if drv.InputDrvs[e.Path] == nil {
drv.InputDrvs[e.Path] = make(StringSet)
}
drv.InputDrvs[e.Path].Add(e.Output)
case CtxDrvDeep:
// Simplified: add the .drv path as an inputSrc.
// Full C++ behaviour requires computeFSClosure (needs a real store).
drv.InputSrcs.Add(e.Path)
}
}
if outputHash != "" {
// Fixed-output derivation: only a single "out" output is allowed.
if len(outputs) != 1 || outputs[0] != "out" {
return nil, evalErrorf("multiple outputs are not supported in fixed-output derivations")
}
// Parse the hash (SRI, prefixed, or bare with algo hint).
algoHint := outputHashAlgo
if algoHint == "null" {
algoHint = ""
}
hashAlgo, hashRaw, err := ParseHashString(outputHash, algoHint)
if err != nil {
return nil, evalErrorf("builtins.derivationStrict: invalid outputHash for %q (outputHashAlgo=%q, outputHash=%q): %v", drvName, algoHint, outputHash, err)
}
// Default ingestionMethod is "flat".
method := ingestionMethod
if method == "" {
method = "flat"
}
// Compute the fixed-output store path via the Store.
outName := outputPathName(drv.Name, "out")
outPath, err := s.Store.AddFixedOutputPath(outName, hashAlgo, method, hashRaw)
if err != nil {
return nil, evalErrorf("builtins.derivationStrict: computing output path: %v", err)
}
// ATerm HashAlgo: "r:algo" for recursive, "algo" for flat.
atermAlgo := hashAlgo
if method == "recursive" {
atermAlgo = "r:" + hashAlgo
}
atermHash := hex.EncodeToString(hashRaw)
drv.Env["out"] = outPath
drv.Outputs["out"] = DerivationOutput{
Path: outPath,
HashAlgo: atermAlgo,
Hash: atermHash,
}
// Compute .drv store path and record via Store.
drvPath, aterm := drv.DrvPath()
s.Store.RecordDerivation(drvPath, aterm, drv)
// Populate the modulo cache for this FOD, mirroring C++ primops.cc which
// calls hashDerivationModulo and caches the result for every derivation
// immediately after recording it. Without this, any input-addressed drv
// that depends on this FOD would not find it in the cache and error out.
{
modulo := s.Store.moduloCache()
moduloHashes := make(map[string][]byte, len(drv.Outputs))
var traceT *HashTrace
if s.Store.IsTracing() {
traceT = &HashTrace{
DrvPath: drvPath,
DrvName: drv.Name,
Type: "fixed-output",
OutputHash: make(map[string]string),
FixedInner: make(map[string]string),
}
}
for outName, o := range drv.Outputs {
inner := "fixed:out:" + o.HashAlgo + ":" + o.Hash + ":" + o.Path
h := sha256.Sum256([]byte(inner))
moduloHashes[outName] = h[:]
if traceT != nil {
traceT.OutputHash[outName] = hex.EncodeToString(h[:])
traceT.FixedInner[outName] = inner
}
}
modulo[drvPath] = moduloHashes
if traceT != nil {
s.Store.StoreHashTrace(drvPath, traceT)
}
}
result := newBindings(s, 2) // drvPath + "out"
drvPathSym := s.Symbols.Create("drvPath")
var drvCtx NixStringContext
drvCtx.Add(ContextEntry{Kind: CtxDrvDeep, Path: drvPath})
result.attrs = append(result.attrs, Attr{
Name: drvPathSym,
Value: VString{V: drvPath, Context: drvCtx},
})
var outCtx NixStringContext
outCtx.Add(ContextEntry{Kind: CtxBuilt, Path: drvPath, Output: "out"})
result.attrs = append(result.attrs, Attr{
Name: s.Symbols.Create("out"),
Value: VString{V: outPath, Context: outCtx},
})
result.Sort()
return VAttrs{Bindings: result}, nil
}
// Input-addressed derivation: compute output paths from masked ATerm hash.
for _, o := range outputs {
drv.Env[o] = "" // masked initially
drv.Outputs[o] = DerivationOutput{}
}
var hashTrace *HashTrace
var moduloHash []byte
if s.Store.IsTracing() {
moduloHash, hashTrace = drv.ComputeInputAddressedOutputsTraced(s.Store)
} else {
moduloHash = drv.ComputeInputAddressedOutputs(s.Store)
}
// Compute .drv store path and record via Store.
drvPath, aterm := drv.DrvPath()
if hashTrace != nil {
hashTrace.DrvPath = drvPath
s.Store.StoreHashTrace(drvPath, hashTrace)
}
s.Store.RecordDerivation(drvPath, aterm, drv)
// Populate the modulo cache for this derivation, mirroring C++ primops.cc.
// For input-addressed drvs all outputs share the same modulo hash.
{
modulo := s.Store.moduloCache()
moduloHashes := make(map[string][]byte, len(drv.Outputs))
for outName := range drv.Outputs {
moduloHashes[outName] = moduloHash
}
modulo[drvPath] = moduloHashes
}
// Build the result attrset: drvPath + one entry per output.
result := newBindings(s, 1+len(outputs)) // drvPath + one per output
drvPathSym := s.Symbols.Create("drvPath")
var drvCtx NixStringContext
drvCtx.Add(ContextEntry{Kind: CtxDrvDeep, Path: drvPath})
result.attrs = append(result.attrs, Attr{
Name: drvPathSym,
Value: VString{V: drvPath, Context: drvCtx},
})
for _, o := range outputs {
outPath := drv.Outputs[o].Path
var outCtx NixStringContext
outCtx.Add(ContextEntry{Kind: CtxBuilt, Path: drvPath, Output: o})
result.attrs = append(result.attrs, Attr{
Name: s.Symbols.Create(o),
Value: VString{V: outPath, Context: outCtx},
})
}
result.Sort()
return VAttrs{Bindings: result}, nil
}
// initDerivationBuiltin parses and evaluates derivation.nix, returning the
// lambda that wraps derivationStrict. Called lazily on first use.
func initDerivationBuiltin(s *EvalState) (Value, error) {
if s.NativeParseFunc == nil {
return nil, evalErrorf("derivation: NativeParseFunc not set")
}
// derivation.nix is compiled into the evaluator rather than read from
// disk, so it has no user-visible location: C++ parses it with Pos::Hidden
// (lix/libexpr/primops.cc:3225) and mkPos therefore reports null for it.
// Claim the name here with that origin; the parse below goes through
// NativeParseFunc (which registers names as OriginPath) but AddFile keeps
// the origin recorded by whoever registered the name first.
//
// The length must be the real one. A span is bounded by the size given
// when the name was first registered, and the parse below re-registers
// this name with len(derivationNixSrc): claiming 0 here would make that
// re-registration a *grown* source, which AddFile refuses, and every
// position in derivation.nix would come out as NoPos. (Refusing is the
// safe half of that bargain — the alternative, letting the parse run past
// its span, would put derivation.nix's positions inside the next file's
// range and have unsafeGetAttrPos report a location in someone else's
// source.)
s.Pos.AddFile("", OriginHidden, len(derivationNixSrc))
expr, err := s.NativeParseFunc(s, []byte(derivationNixSrc), "/", "")
if err != nil {
return nil, evalErrorf("derivation: parsing derivation.nix: %v", err)
}
return expr.eval(s, s.Builtins)
}
|