about summary refs log tree commit diff
path: root/doc/manual/writing-nix-expressions.xml
blob: 01194d4c6a549690d57e3bd9056ca73e82aae31d (plain) (blame)
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
<chapter xmlns="http://docbook.org/ns/docbook"
         xmlns:xlink="http://www.w3.org/1999/xlink"
         xml:id='chap-writing-nix-expressions'>

<title>Writing Nix Expressions</title>


<para>This chapter shows you how to write Nix expressions, which are
the things that tell Nix how to build components.  It starts with a
simple example (a Nix expression for GNU Hello), and then moves
on to a more in-depth look at the Nix expression language.</para>


<section><title>A simple Nix expression</title>

<para>This section shows how to add and test the <link
xlink:href='http://www.gnu.org/software/hello/hello.html'>GNU Hello
package</link> to the Nix Packages collection.  Hello is a program
that prints out the text <quote>Hello, world!</quote>.</para>

<para>To add a component to the Nix Packages collection, you generally
need to do three things:

<orderedlist>

  <listitem><para>Write a Nix expression for the component.  This is a
  file that describes all the inputs involved in building the
  component, such as dependencies (other components required by the
  component), sources, and so on.</para></listitem>

  <listitem><para>Write a <emphasis>builder</emphasis>.  This is a
  shell script<footnote><para>In fact, it can be written in any
  language, but typically it's a <command>bash</command> shell
  script.</para></footnote> that actually builds the component from
  the inputs.</para></listitem>

  <listitem><para>Add the component to the file
  <filename>pkgs/top-level/all-packages.nix</filename>.  The Nix
  expression written in the first step is a
  <emphasis>function</emphasis>; it requires other components in order
  to build it.  In this step you put it all together, i.e., you call
  the function with the right arguments to build the actual
  component.</para></listitem>

</orderedlist>

</para>


<section><title>The Nix expression</title>

<example xml:id='ex-hello-nix'><title>Nix expression for GNU Hello
(<filename>default.nix</filename>)</title>
<programlisting>
{stdenv, fetchurl, perl}: <co xml:id='ex-hello-nix-co-1' />

stdenv.mkDerivation { <co xml:id='ex-hello-nix-co-2' />
  name = "hello-2.1.1"; <co xml:id='ex-hello-nix-co-3' />
  builder = ./builder.sh; <co xml:id='ex-hello-nix-co-4' />
  src = fetchurl { <co xml:id='ex-hello-nix-co-5' />
    url = ftp://ftp.nluug.nl/pub/gnu/hello/hello-2.1.1.tar.gz;
    md5 = "70c9ccf9fac07f762c24f2df2290784d";
  };
  inherit perl; <co xml:id='ex-hello-nix-co-6' />
}</programlisting>
</example>

<para><xref linkend='ex-hello-nix' /> shows a Nix expression for GNU
Hello.  It's actually already in the Nix Packages collection in
<filename>pkgs/applications/misc/hello/ex-1/default.nix</filename>.
It is customary to place each package in a separate directory and call
the single Nix expression in that directory
<filename>default.nix</filename>.  The file has the following elements
(referenced from the figure by number):

<calloutlist>

  <callout arearefs='ex-hello-nix-co-1'>

    <para>This states that the expression is a
    <emphasis>function</emphasis> that expects to be called with three
    arguments: <varname>stdenv</varname>, <varname>fetchurl</varname>,
    and <varname>perl</varname>.  They are needed to build Hello, but
    we don't know how to build them here; that's why they are function
    arguments.  <varname>stdenv</varname> is a component that is used
    by almost all Nix Packages components; it provides a
    <quote>standard</quote> environment consisting of the things you
    would expect in a basic Unix environment: a C/C++ compiler (GCC,
    to be precise), the Bash shell, fundamental Unix tools such as
    <command>cp</command>, <command>grep</command>,
    <command>tar</command>, etc.  <varname>fetchurl</varname> is a
    function that downloads files.  <varname>perl</varname> is the
    Perl interpreter.</para>

    <para>Nix functions generally have the form <literal>{x, y, ...,
    z}: e</literal> where <varname>x</varname>, <varname>y</varname>,
    etc. are the names of the expected arguments, and where
    <replaceable>e</replaceable> is the body of the function.  So
    here, the entire remainder of the file is the body of the
    function; when given the required arguments, the body should
    describe how to build an instance of the Hello component.</para>
    
  </callout>

  <callout arearefs='ex-hello-nix-co-2'>

    <para>So we have to build a component.  Building something from
    other stuff is called a <emphasis>derivation</emphasis> in Nix (as
    opposed to sources, which are built by humans instead of
    computers).  We perform a derivation by calling
    <varname>stdenv.mkDerivation</varname>.
    <varname>mkDerivation</varname> is a function provided by
    <varname>stdenv</varname> that builds a component from a set of
    <emphasis>attributes</emphasis>.  An attribute set is just a list
    of key/value pairs where each value is an arbitrary Nix
    expression.  They take the general form
    <literal>{<replaceable>name1</replaceable> =
    <replaceable>expr1</replaceable>; <replaceable>...</replaceable>
    <replaceable>nameN</replaceable> =
    <replaceable>exprN</replaceable>;}</literal>.</para>

  </callout>

  <callout arearefs='ex-hello-nix-co-3'>

    <para>The attribute <varname>name</varname> specifies the symbolic
    name and version of the component.  Nix doesn't really care about
    these things, but they are used by for instance <command>nix-env
    -q</command> to show a <quote>human-readable</quote> name for
    components.  This attribute is required by
    <varname>mkDerivation</varname>.</para>

  </callout>

  <callout arearefs='ex-hello-nix-co-4'>

    <para>The attribute <varname>builder</varname> specifies the
    builder.  This attribute can sometimes be omitted, in which case
    <varname>mkDerivation</varname> will fill in a default builder
    (which does a <literal>configure; make; make install</literal>, in
    essence).  Hello is sufficiently simple that the default builder
    would suffice, but in this case, we will show an actual builder
    for educational purposes.  The value
    <command>./builder.sh</command> refers to the shell script shown
    in <xref linkend='ex-hello-builder' />, discussed below.</para>

  </callout>

  <callout arearefs='ex-hello-nix-co-5'>

    <para>The builder has to know what the sources of the component
    are.  Here, the attribute <varname>src</varname> is bound to the
    result of a call to the <command>fetchurl</command> function.
    Given a URL and an MD5 hash of the expected contents of the file
    at that URL, this function builds a derivation that downloads the
    file and checks its hash.  So the sources are a dependency that
    like all other dependencies is built before Hello itself is
    built.</para>

    <para>Instead of <varname>src</varname> any other name could have
    been used, and in fact there can be any number of sources (bound
    to different attributes).  However, <varname>src</varname> is
    customary, and it's also expected by the default builder (which we
    don't use in this example).</para>

  </callout>

  <callout arearefs='ex-hello-nix-co-6'>

    <para>Since the derivation requires Perl, we have to pass the
    value of the <varname>perl</varname> function argument to the
    builder.  All attributes in the set are actually passed as
    environment variables to the builder, so declaring an attribute

    <programlisting>
perl = perl;</programlisting>

    will do the trick: it binds an attribute <varname>perl</varname>
    to the function argument which also happens to be called
    <varname>perl</varname>.  However, it looks a bit silly, so there
    is a shorter syntax.  The <literal>inherit</literal> keyword
    causes the specified attributes to be bound to whatever variables
    with the same name happen to be in scope.</para>

  </callout>
  
</calloutlist>

</para>

</section>


<section><title>The builder</title>

<example xml:id='ex-hello-builder'><title>Build script for GNU Hello
(<filename>builder.sh</filename>)</title>
<programlisting>
source $stdenv/setup <co xml:id='ex-hello-builder-co-1' />

PATH=$perl/bin:$PATH <co xml:id='ex-hello-builder-co-2' />

tar xvfz $src <co xml:id='ex-hello-builder-co-3' />
cd hello-*
./configure --prefix=$out <co xml:id='ex-hello-builder-co-4' />
make <co xml:id='ex-hello-builder-co-5' />
make install</programlisting>
</example>

<para><xref linkend='ex-hello-builder' /> shows the builder referenced
from Hello's Nix expression (stored in
<filename>pkgs/applications/misc/hello/ex-1/builder.sh</filename>).
The builder can actually be made a lot shorter by using the
<emphasis>generic builder</emphasis> functions provided by
<varname>stdenv</varname>, but here we write out the build steps to
elucidate what a builder does.  It performs the following
steps:</para>

<calloutlist>

  <callout arearefs='ex-hello-builder-co-1'>

    <para>When Nix runs a builder, it initially completely clears the
    environment (except for the attributes declared in the
    derivation).  For instance, the <envar>PATH</envar> variable is
    empty<footnote><para>Actually, it's initialised to
    <filename>/path-not-set</filename> to prevent Bash from setting it
    to a default value.</para></footnote>.  This is done to prevent
    undeclared inputs from being used in the build process.  If for
    example the <envar>PATH</envar> contained
    <filename>/usr/bin</filename>, then you might accidentally use
    <filename>/usr/bin/gcc</filename>.</para>

    <para>So the first step is to set up the environment.  This is
    done by calling the <filename>setup</filename> script of the
    standard environment.  The environment variable
    <envar>stdenv</envar> points to the location of the standard
    environment being used.  (It wasn't specified explicitly as an
    attribute in <xref linkend='ex-hello-nix' />, but
    <varname>mkDerivation</varname> adds it automatically.)</para>

  </callout>

  <callout arearefs='ex-hello-builder-co-2'>

    <para>Since Hello needs Perl, we have to make sure that Perl is in
    the <envar>PATH</envar>.  The <envar>perl</envar> environment
    variable points to the location of the Perl component (since it
    was passed in as an attribute to the derivation), so
    <filename><replaceable>$perl</replaceable>/bin</filename> is the
    directory containing the Perl interpreter.</para>

  </callout>

  <callout arearefs='ex-hello-builder-co-3'>

    <para>Now we have to unpack the sources.  The
    <varname>src</varname> attribute was bound to the result of
    fetching the Hello source tarball from the network, so the
    <envar>src</envar> environment variable points to the location in
    the Nix store to which the tarball was downloaded.  After
    unpacking, we <command>cd</command> to the resulting source
    directory.</para>

    <para>The whole build is performed in a temporary directory
    created in <varname>/tmp</varname>, by the way.  This directory is
    removed after the builder finishes, so there is no need to clean
    up the sources afterwards.  Also, the temporary directory is
    always newly created, so you don't have to worry about files from
    previous builds interfering with the current build.</para>

  </callout>

  <callout arearefs='ex-hello-builder-co-4'>

    <para>GNU Hello is a typical Autoconf-based package, so we first
    have to run its <filename>configure</filename> script.  In Nix
    every component is stored in a separate location in the Nix store,
    for instance
    <filename>/nix/store/9a54ba97fb71b65fda531012d0443ce2-hello-2.1.1</filename>.
    Nix computes this path by cryptographically hashing all attributes
    of the derivation.  The path is passed to the builder through the
    <envar>out</envar> environment variable.  So here we give
    <filename>configure</filename> the parameter
    <literal>--prefix=$out</literal> to cause Hello to be installed in
    the expected location.</para>

  </callout>

  <callout arearefs='ex-hello-builder-co-5'>

    <para>Finally we build Hello (<literal>make</literal>) and install
    it into the location specified by <envar>out</envar>
    (<literal>make install</literal>).</para>

  </callout>
  
</calloutlist>

<para>If you are wondering about the absence of error checking on the
result of various commands called in the builder: this is because the
shell script is evaluated with Bash's <option>-e</option> option,
which causes the script to be aborted if any command fails without an
error check.</para>

</section>


<section><title>Composition</title>

<example xml:id='ex-hello-composition'><title>Composing GNU Hello
(<filename>all-packages.nix</filename>)</title>
<programlisting>
...

rec { <co xml:id='ex-hello-composition-co-1' />
  
  hello = (import ../applications/misc/hello/ex-1 <co xml:id='ex-hello-composition-co-2' />) { <co xml:id='ex-hello-composition-co-3' />
    inherit fetchurl stdenv perl;
  };

  perl = (import ../development/interpreters/perl) { <co xml:id='ex-hello-composition-co-4' />
    inherit fetchurl stdenv;
  };

  fetchurl = (import ../build-support/fetchurl) { 
    inherit stdenv; ...
  };
  
  stdenv = ...;

}
</programlisting>
</example>

<para>The Nix expression in <xref linkend='ex-hello-nix' /> is a
function; it is missing some arguments that have to be filled in
somewhere.  In the Nix Packages collection this is done in the file
<filename>pkgs/top-level/all-packages.nix</filename>, where all
Nix expressions for components are imported and called with the
appropriate arguments.  <xref linkend='ex-hello-composition' /> shows
some fragments of
<filename>all-packages.nix</filename>.</para>

<calloutlist>

  <callout arearefs='ex-hello-composition-co-1'>

    <para>This file defines a set of attributes, all of which are
    concrete derivations (i.e., not functions).  In fact, we define a
    <emphasis>mutually recursive</emphasis> set of attributes.  That
    is, the attributes can refer to each other.  This is precisely
    what we want since we want to <quote>plug</quote> the
    various components into each other.</para>

  </callout>

  <callout arearefs='ex-hello-composition-co-2'>

    <para>Here we <emphasis>import</emphasis> the Nix expression for
    GNU Hello.  The import operation just loads and returns the
    specified Nix expression. In fact, we could just have put the
    contents of <xref linkend='ex-hello-nix' /> in
    <filename>all-packages.nix</filename> at this point.  That
    would be completely equivalent, but it would make the file rather
    bulky.</para>

    <para>Note that we refer to
    <filename>../applications/misc/hello/ex-1</filename>, not
    <filename>../applications/misc/hello/ex-1/default.nix</filename>.
    When you try to import a directory, Nix automatically appends
    <filename>/default.nix</filename> to the file name.</para>

  </callout>

  <callout arearefs='ex-hello-composition-co-3'>

    <para>This is where the actual composition takes place.  Here we
    <emphasis>call</emphasis> the function imported from
    <filename>../applications/misc/hello/ex-1</filename> with an
    attribute set containing the things that the function expects,
    namely <varname>fetchurl</varname>, <varname>stdenv</varname>, and
    <varname>perl</varname>.  We use inherit again to use the
    attributes defined in the surrounding scope (we could also have
    written <literal>fetchurl = fetchurl;</literal>, etc.).</para>

    <para>The result of this function call is an actual derivation
    that can be built by Nix (since when we fill in the arguments of
    the function, what we get is its body, which is the call to
    <varname>stdenv.mkDerivation</varname> in <xref
    linkend='ex-hello-nix' />).</para>

  </callout>

  <callout arearefs='ex-hello-composition-co-4'>

    <para>Likewise, we have to instantiate Perl,
    <varname>fetchurl</varname>, and the standard environment.</para>

  </callout>

</calloutlist>

</section>


<section><title>Testing</title>

<para>You can now try to build Hello.  Of course, you could do
<literal>nix-env -f pkgs/top-level/all-packages.nix -i hello</literal>,
but you may not want to install a possibly broken package just yet.
The best way to test the package is by using the command <command
linkend="sec-nix-build">nix-build</command>, which builds a Nix
expression and creates a symlink named <filename>result</filename> in
the current directory:

<screen>
$ nix-build pkgs/top-level/all-packages.nix -A hello
building path `/nix/store/632d2b22514d...-hello-2.1.1'
hello-2.1.1/
hello-2.1.1/intl/
hello-2.1.1/intl/ChangeLog
<replaceable>...</replaceable>

$ ls -l result
lrwxrwxrwx ... 2006-09-29 10:43 result -> /nix/store/632d2b22514d...-hello-2.1.1

$ ./result/bin/hello
Hello, world!</screen>

The <link linkend='opt-attr'><option>-A</option></link> option selects
the <literal>hello</literal> attribute from
<filename>all-packages.nix</filename>.  This is faster than using the
symbolic package name specified by the <literal>name</literal>
attribute (which also happens to be <literal>hello</literal>) and is
unambiguous (there can be multiple packages with the symbolic name
<literal>hello</literal>, but there can be only one attribute in a set
named <literal>hello</literal>).</para>

<para><command>nix-build</command> registers the
<filename>./result</filename> symlink as a garbage collection root, so
unless and until you delete the <filename>./result</filename> symlink,
the output of the build will be safely kept on your system.  You can
use <command>nix-build</command>’s <option
linkend='opt-out-link'>-o</option> switch to give the symlink another
name.</para>

<para>Nix has a transactional semantics.  Once a build finishes
successfully, Nix makes a note of this in its database: it registers
that the path denoted by <envar>out</envar> is now
<quote>valid</quote>.  If you try to build the derivation again, Nix
will see that the path is already valid and finish immediately.  If a
build fails, either because it returns a non-zero exit code, because
Nix or the builder are killed, or because the machine crashes, then
the output path will not be registered as valid.  If you try to build
the derivation again, Nix will remove the output path if it exists
(e.g., because the builder died half-way through <literal>make
install</literal>) and try again.  Note that there is no
<quote>negative caching</quote>: Nix doesn't remember that a build
failed, and so a failed build can always be repeated.  This is because
Nix cannot distinguish between permanent failures (e.g., a compiler
error due to a syntax error in the source) and transient failures
(e.g., a disk full condition).</para>

<para>Nix also performs locking.  If you run multiple Nix builds
simultaneously, and they try to build the same derivation, the first
Nix instance that gets there will perform the build, while the others
block (or perform other derivations if available) until the build
finishes:

<screen>
$ nix-build pkgs/top-level/all-packages.nix -A hello
waiting for lock on `/nix/store/0h5b7hp8d4hqfrw8igvx97x1xawrjnac-hello-2.1.1x'</screen>

So it is always safe to run multiple instances of Nix in parallel
(which isn’t the case with, say, <command>make</command>).</para>

<para>If you have a system with multiple CPUs, you may want to have
Nix build different derivations in parallel (insofar as possible).
Just pass the option <link linkend='opt-max-jobs'><option>-j
<replaceable>N</replaceable></option></link>, where
<replaceable>N</replaceable> is the maximum number of jobs to be run
in parallel, or set.  Typically this should be the number of
CPUs.</para>

</section>


<section><title>The generic builder</title>

<para>Recall from <xref linkend='ex-hello-builder' /> that the builder
looked something like this:

<programlisting>
PATH=$perl/bin:$PATH
tar xvfz $src
cd hello-*
./configure --prefix=$out
make
make install</programlisting>

The builders for almost all Unix packages look like this — set up some
environment variables, unpack the sources, configure, build, and
install.  For this reason the standard environment provides some Bash
functions that automate the build process.  A builder using the
generic build facilities in shown in <xref linkend='ex-hello-builder2'
/>.</para>

<example xml:id='ex-hello-builder2'><title>Build script using the generic
build functions</title>
<programlisting>
buildInputs="$perl" <co xml:id='ex-hello-builder2-co-1' />

source $stdenv/setup <co xml:id='ex-hello-builder2-co-2' />

genericBuild <co xml:id='ex-hello-builder2-co-3' /></programlisting>
</example>

<calloutlist>

  <callout arearefs='ex-hello-builder2-co-1'>
    
    <para>The <envar>buildInputs</envar> variable tells
    <filename>setup</filename> to use the indicated components as
    <quote>inputs</quote>.  This means that if a component provides a
    <filename>bin</filename> subdirectory, it's added to
    <envar>PATH</envar>; if it has a <filename>include</filename>
    subdirectory, it's added to GCC's header search path; and so
    on.</para>

  </callout>

  <callout arearefs='ex-hello-builder2-co-2'>

    <para>The function <function>genericBuild</function> is defined in
    the file <literal>$stdenv/setup</literal>.</para>

  </callout>
  
  <callout arearefs='ex-hello-builder2-co-3'>

    <para>The final step calls the shell function
    <function>genericBuild</function>, which performs the steps that
    were done explicitly in <xref linkend='ex-hello-builder' />.  The
    generic builder is smart enough to figure out whether to unpack
    the sources using <command>gzip</command>,
    <command>bzip2</command>, etc.  It can be customised in many ways;
    see <xref linkend='sec-standard-environment' />.</para>

  </callout>
  
</calloutlist>

<para>Discerning readers will note that the
<envar>buildInputs</envar> could just as well have been set in the Nix
expression, like this:

<programlisting>
  buildInputs = [perl];</programlisting>

The <varname>perl</varname> attribute can then be removed, and the
builder becomes even shorter:

<programlisting>
source $stdenv/setup
genericBuild</programlisting>

In fact, <varname>mkDerivation</varname> provides a default builder
that looks exactly like that, so it is actually possible to omit the
builder for Hello entirely.</para>

</section>


</section>



<section><title>The Nix expression language</title>

<para>The Nix expression language is a pure, lazy, functional
language.  Purity means that operations in the language don't have
side-effects (for instance, there is no variable assignment).
Laziness means that arguments to functions are evaluated only when
they are needed.  Functional means that functions are
<quote>normal</quote> values that can be passed around and manipulated
in interesting ways.  The language is not a full-featured, general
purpose language.  It's main job is to describe components,
compositions of components, and the variability within
components.</para>

<para>This section presents the various features of the
language.</para>


<section xml:id='ssec-values'><title>Values</title>


<simplesect><title>Simple values</title>

<para>Nix has the following basic datatypes:

<itemizedlist>

  <listitem>

    <para><emphasis>Strings</emphasis> are enclosed between double
    quotes, e.g., <literal>"foo bar"</literal>.  Strings can span
    multiple lines.  The special characters <literal>"</literal> and
    <literal>\</literal> and the character sequence
    <literal>${</literal> must be escaped by prefixing them with a
    backslash (<literal>\</literal>).  Newlines, carriage returns and
    tabs can be written as <literal>\n</literal>,
    <literal>\r</literal> and <literal>\t</literal>,
    respectively.</para>

    <para>You can include the result of an expression into a string by
    enclosing it in
    <literal>${<replaceable>...</replaceable>}</literal>, a feature
    known as <emphasis>antiquotation</emphasis>.  The enclosed
    expression must evaluate to something that can be coerced into a
    string (meaning that it must be a string, a path, or a
    derivation).  For instance, rather than writing

<programlisting>
"--with-freetype2-library=" + freetype + "/lib"</programlisting>

    (where <varname>freetype</varname> is a derivation), you can
    instead write the more natural

<programlisting>
"--with-freetype2-library=${freetype}/lib"</programlisting>

    The latter is automatically translated to the former.  A more
    complicated example (from the Nix expression for <link
    xlink:href='http://www.trolltech.com/products/qt'>Qt</link>):

<programlisting>
configureFlags = "
  -system-zlib -system-libpng -system-libjpeg
  ${if openglSupport then "-dlopen-opengl
    -L${mesa}/lib -I${mesa}/include
    -L${libXmu}/lib -I${libXmu}/include" else ""}
  ${if threadSupport then "-thread" else "-no-thread"}
";</programlisting>

    Note that Nix expressions and strings can be arbitrarily nested;
    in this case the outer string contains various antiquotations that
    themselves contain strings (e.g., <literal>"-thread"</literal>),
    some of which in turn contain expressions (e.g.,
    <literal>${mesa}</literal>).</para>

    <para>As a convenience, <emphasis>URIs</emphasis> as defined in
    appendix B of <link
    xlink:href='http://www.ietf.org/rfc/rfc2396.txt'>RFC 2396</link>
    can be written <emphasis>as is</emphasis>, without quotes.  For
    instance, the string
    <literal>"https://svn.cs.uu.nl:12443/dist/trace/trace-nix-trunk.tar.bz2"</literal>
    can also be written as
    <literal>https://svn.cs.uu.nl:12443/dist/trace/trace-nix-trunk.tar.bz2</literal>.</para>

  </listitem>

  <listitem><para><emphasis>Integers</emphasis>, e.g.,
  <literal>123</literal>.</para></listitem>

  <listitem><para><emphasis>Paths</emphasis>, e.g.,
  <filename>/bin/sh</filename> or <filename>./builder.sh</filename>.
  A path must contain at least one slash to be recognised as such; for
  instance, <filename>builder.sh</filename> is not a
  path<footnote><para>It's parsed as an expression that selects the
  attribute <varname>sh</varname> from the variable
  <varname>builder</varname>.</para></footnote>.  If the filename is
  relative, i.e., if it does not begin with a slash, it is made
  absolute at parse time relative to the directory of the Nix
  expression that contained it.  For instance, if a Nix expression in
  <filename>/foo/bar/bla.nix</filename> refers to
  <filename>../xyzzy/fnord.nix</filename>, the absolutised path is
  <filename>/foo/xyzzy/fnord.nix</filename>.</para></listitem>

  <listitem><para><emphasis>Booleans</emphasis> with values
  <literal>true</literal> and
  <literal>false</literal>.</para></listitem>
  
</itemizedlist>

</para>

</simplesect>


<simplesect><title>Lists</title>

<para>Lists are formed by enclosing a whitespace-separated list of
values between square bracktes.  For example,

<programlisting>
[ 123 ./foo.nix "abc" (f {x=y;}) ]</programlisting>

defines a list of four elements, the last being the result of a call
to the function <varname>f</varname>.  Note that function calls have
to be enclosed in parentheses.  If they had been omitted, e.g.,

<programlisting>
[ 123 ./foo.nix "abc" f {x=y;} ]</programlisting>

the result would be a list of five elements, the fourth one being a
function and the fifth being an attribute set.</para>

</simplesect>


<simplesect><title>Attribute sets</title>

<para>Attribute sets are really the core of the language, since
ultimately it's all about creating derivations, which are really just
sets of attributes to be passed to build scripts.</para>

<para>Attribute sets are just a list of name/value pairs enclosed in
curly brackets, where each value is an arbitrary expression terminated
by a semicolon.  For example:

<programlisting>
{ x = 123;
  text = "Hello";
  y = f { bla = 456; };
}</programlisting>

This defines an attribute set with attributes named
<varname>x</varname>, <varname>test</varname>, <varname>y</varname>.
The order of the attributes is irrelevant.  An attribute name may only
occur once.</para>

<para>Attributes can be selected from an attribute set using the
<literal>.</literal> operator.  For instance,

<programlisting>
{ a = "Foo"; b = "Bar"; }.a</programlisting>

evaluates to <literal>"Foo"</literal>.</para>

</simplesect>


</section>


<section><title>Language constructs</title>


<simplesect><title>Recursive attribute sets</title>

<para>Recursive attribute sets are just normal attribute sets, but the
attributes can refer to each other.  For example,

<programlisting>
rec {
  x = y;
  y = 123;
}.x
</programlisting>

evaluates to <literal>123</literal>.  Note that without
<literal>rec</literal> the binding <literal>x = y;</literal> would
refer to the variable <varname>y</varname> in the surrounding scope,
if one exists, and would be invalid if no such variable exists.  That
is, in a normal (non-recursive) attribute set, attributes are not
added to the lexical scope; in a recursive set, they are.</para>

<para>Recursive attribute sets of course introduce the danger of
infinite recursion.  For example,

<programlisting>
rec {
  x = y;
  y = x;
}.x</programlisting>

does not terminate<footnote><para>Actually, Nix detects infinite
recursion in this case and aborts (<quote>infinite recursion
encountered</quote>).</para></footnote>.</para>

</simplesect>


<simplesect><title>Let-expressions</title>

<para>A let-expression allows you define local
variables for an expression.  For instance,

<programlisting>
let
  x = "foo";
  y = "bar";
in x + y</programlisting>

evaluates to <literal>"foobar"</literal>.

</para>

<note><para>There is also an obsolete form of let-expression,
<literal>let { <replaceable>attrs</replaceable> }</literal>, which is
translated to <literal>rec { <replaceable>attrs</replaceable>
}.body</literal>.  That is, the body of the let-expression is the
<literal>body</literal> attribute of the attribute set.</para></note>

</simplesect>


<simplesect><title>Inheriting attributes</title>

<para>When defining an attribute set it is often convenient to copy
variables from the surrounding lexical scope (e.g., when you want to
propagate attributes).  This can be shortened using the
<literal>inherit</literal> keyword.  For instance,

<programlisting>
let
  x = 123;
in 
  {
    inherit x;
    y = 456;
  }</programlisting>

evaluates to <literal>{x = 123; y = 456;}</literal>.  (Note that this
works because <varname>x</varname> is added to the lexical scope by
the <literal>let</literal> construct.)  It is also possible to inherit
attributes from another attribute set.  For instance, in this fragment
from <filename>all-packages.nix</filename>,

<programlisting>
  graphviz = (import ../tools/graphics/graphviz) {
    inherit fetchurl stdenv libpng libjpeg expat x11 yacc;
    inherit (xlibs) libXaw;
  };

  xlibs = {
    libX11 = ...;
    libXaw = ...;
    ...
  }

  libpng = ...;
  libjpg = ...;
  ...</programlisting>

the attribute set used in the function call to the function defined in
<filename>../tools/graphics/graphviz</filename> inherits a number of
variables from the surrounding scope (<varname>fetchurl</varname>
... <varname>yacc</varname>), but also inherits
<varname>libXaw</varname> (the X Athena Widgets) from the
<varname>xlibs</varname> (X11 client-side libraries) attribute
set.</para>

</simplesect>


<simplesect xml:id="ss-functions"><title>Functions</title>

<para>Functions have the following form:

<programlisting>
{<replaceable>params</replaceable>}: <replaceable>body</replaceable></programlisting>

This defines a function that must be called with an attribute set
containing the attributes listed in <replaceable>params</replaceable>,
which is a comma-separated list of attribute names.  Optionally, for
each parameter a <emphasis>default value</emphasis> may be specified
by writing <literal><replaceable>param</replaceable> ?
<replaceable>e</replaceable></literal>, where
<replaceable>e</replaceable> is an arbitrary expression.  If a
parameter has a default, the corresponding attribute may be omitted in
function calls.</para>

<para>Note that functions do not have names.  If you want to give them
a name, you can bind them to an attribute, e.g.,

<programlisting>
let concat = {x, y}: x + y;
in concat {x = "foo"; y = "bar";}</programlisting>

</para>

<para>It is also possible to define a function that takes a single
argument and that does not need to be called with an attribute set as
argument.  The syntax is

<programlisting>
<replaceable>var</replaceable>: <replaceable>body</replaceable></programlisting>

where <replaceable>var</replaceable> is the name of the argument.  It
is not possible to define a default.  Example:

<programlisting>
let negate = x: !x;
    concat = x: y: x + y;
in if negate true then concat "foo" "bar" else ""</programlisting>

Note that <function>concat</function> is a function that takes one
arguments and returns a function that takes another argument.  This
allows partial parameterisation (i.e., only filling some of the
arguments of a function); e.g.,

<programlisting>
map (concat "foo") ["bar" "bla" "abc"]</programlisting>

evaluates to <literal>["foobar" "foobla" "fooabc"]</literal>.</para>

</simplesect>


<simplesect><title>Conditionals</title>

<para>Conditionals look like this:

<programlisting>
if <replaceable>e1</replaceable> then <replaceable>e2</replaceable> else <replaceable>e3</replaceable></programlisting>

where <replaceable>e1</replaceable> is an expression that should
evaluate to a boolean value (<literal>true</literal> or
<literal>false</literal>).</para>

</simplesect>


<simplesect><title>Assertions</title>

<para>Assertions are generally used to check that certain requirements
on or between features and dependencies hold.  They look like this:

<programlisting>
assert <replaceable>e1</replaceable>; <replaceable>e2</replaceable></programlisting>

where <replaceable>e1</replaceable> is an expression that should
evaluate to a boolean value.  If it evaluates to
<literal>true</literal>, <replaceable>e2</replaceable> is returned;
otherwise expression evaluation is aborted and a backtrace is printed.</para>

<example xml:id='ex-subversion-nix'><title>Nix expression for Subversion</title>
<programlisting>
{ localServer ? false
, httpServer ? false
, sslSupport ? false
, pythonBindings ? false
, javaSwigBindings ? false
, javahlBindings ? false
, stdenv, fetchurl
, openssl ? null, httpd ? null, db4 ? null, expat, swig ? null, j2sdk ? null
}:

assert localServer -> db4 != null; <co xml:id='ex-subversion-nix-co-1' />
assert httpServer -> httpd != null &amp;&amp; httpd.expat == expat; <co xml:id='ex-subversion-nix-co-2' />
assert sslSupport -> openssl != null &amp;&amp; (httpServer -> httpd.openssl == openssl); <co xml:id='ex-subversion-nix-co-3' />
assert pythonBindings -> swig != null &amp;&amp; swig.pythonSupport;
assert javaSwigBindings -> swig != null &amp;&amp; swig.javaSupport;
assert javahlBindings -> j2sdk != null;

stdenv.mkDerivation {
  name = "subversion-1.1.1";
  ...
  openssl = if sslSupport then openssl else null; <co xml:id='ex-subversion-nix-co-4' />
  ...
}</programlisting>
</example>

<para><xref linkend='ex-subversion-nix' /> show how assertions are
used in the Nix expression for Subversion.</para>

<calloutlist>

  <callout arearefs='ex-subversion-nix-co-1'>
    <para>This assertion states that if Subversion is to have support
    for local repositories, then Berkeley DB is needed.  So if the
    Subversion function is called with the
    <varname>localServer</varname> argument set to
    <literal>true</literal> but the <varname>db4</varname> argument
    set to <literal>null</literal>, then the evaluation fails.</para>
  </callout>

  <callout arearefs='ex-subversion-nix-co-2'>
    <para>This is a more subtle condition: if Subversion is built with
    Apache (<literal>httpServer</literal>) support, then the Expat
    library (an XML library) used by Subversion should be same as the
    one used by Apache.  This is because in this configuration
    Subversion code ends up being linked with Apache code, and if the
    Expat libraries do not match, a build- or runtime link error or
    incompatibility might occur.</para>
  </callout>

  <callout arearefs='ex-subversion-nix-co-2'>
    <para>This assertion says that in order for Subversion to have SSL
    support (so that it can access <literal>https</literal> URLs), an
    OpenSSL library must be passed.  Additionally, it says that
    <emphasis>if</emphasis> Apache support is enabled, then Apache's
    OpenSSL should match Subversion's.  (Note that if Apache support
    is not enabled, we don't care about Apache's OpenSSL.)</para>
  </callout>

  <callout arearefs='ex-subversion-nix-co-4'>
    <para>The conditional here is not really related to assertions,
    but is worth pointing out: it ensures that if SSL support is
    disabled, then the Subversion derivation is not dependent on
    OpenSSL, even if a non-<literal>null</literal> value was passed.
    This prevents an unnecessary rebuild of Subversion if OpenSSL
    changes.</para>
  </callout>

</calloutlist>

</simplesect>
  


<simplesect><title>With-expressions</title>

<para>A <emphasis>with-expression</emphasis>,

<programlisting>
with <replaceable>e1</replaceable>; <replaceable>e2</replaceable></programlisting>

introduces the attribute set <replaceable>e1</replaceable> into the
lexical scope of the expression <replaceable>e2</replaceable>.  For
instance,

<programlisting>
let as = {x = "foo"; y = "bar";};
in with as; x + y</programlisting>

evaluates to <literal>"foobar"</literal> since the
<literal>with</literal> adds the <varname>x</varname> and
<varname>y</varname> attributes of <varname>as</varname> to the
lexical scope in the expression <literal>x + y</literal>.  The most
common use of <literal>with</literal> is in conjunction with the
<function>import</function> function.  E.g.,

<programlisting>
with (import ./definitions.nix); ...</programlisting>

makes all attributes defined in the file
<filename>definitions.nix</filename> available as if they were defined
locally in a <literal>rec</literal>-expression.</para>

</simplesect>


<simplesect><title>Comments</title>

<para>Comments can be single-line, started with a <literal>#</literal>
character, or inline/multi-line, enclosed within <literal>/*
... */</literal>.</para>

</simplesect>


</section>


<section><title>Operators</title>

<para><xref linkend='table-operators' /> lists the operators in the
Nix expression language, in order of precedence (from strongest to
weakest binding).</para>

<table xml:id='table-operators'>
  <title>Operators</title>
  <tgroup cols='3'>
    <thead>
      <row>
        <entry>Syntax</entry>
        <entry>Associativity</entry>
        <entry>Description</entry>
      </row>
    </thead>
    <tbody>
      <row>
        <entry><replaceable>e</replaceable> .
        <replaceable>id</replaceable></entry>
        <entry>none</entry>
        <entry>Select attribute named <replaceable>id</replaceable>
        from attribute set <replaceable>e</replaceable>.  Abort
        evaluation if the attribute doesn’t exist.</entry>
      </row>
      <row>
        <entry><replaceable>e1</replaceable> <replaceable>e2</replaceable></entry>
        <entry>left</entry>
        <entry>Call function <replaceable>e1</replaceable> with
        argument <replaceable>e2</replaceable>.</entry>
      </row>
      <row>
        <entry><replaceable>e</replaceable> ?
        <replaceable>id</replaceable></entry>
        <entry>none</entry>
        <entry>Test whether attribute set <replaceable>e</replaceable>
        contains an attribute named <replaceable>id</replaceable>;
        return <literal>true</literal> or
        <literal>false</literal>.</entry>
      </row>
      <row>
        <entry><replaceable>e1</replaceable> ++ <replaceable>e2</replaceable></entry>
        <entry>right</entry>
        <entry>List concatenation.</entry>
      </row>
      <row>
        <entry><replaceable>e1</replaceable> + <replaceable>e2</replaceable></entry>
        <entry>left</entry>
        <entry>String or path concatenation.</entry>
      </row>
      <row>
        <entry>! <replaceable>e</replaceable></entry>
        <entry>left</entry>
        <entry>Boolean negation.</entry>
      </row>
      <row>
        <entry><replaceable>e1</replaceable> //
        <replaceable>e2</replaceable></entry>
        <entry>right</entry>
        <entry>Return an attribute set consisting of the attributes in
        <replaceable>e1</replaceable> and
        <replaceable>e2</replaceable> (with the latter taking
        precedence over the former in case of equally named attributes).</entry>
      </row>
      <row>
        <entry><replaceable>e1</replaceable> ==
        <replaceable>e2</replaceable></entry>
        <entry>none</entry>
        <entry>Equality.</entry>
      </row>
      <row>
        <entry><replaceable>e1</replaceable> !=
        <replaceable>e2</replaceable></entry>
        <entry>none</entry>
        <entry>Inequality.</entry>
      </row>
      <row>
        <entry><replaceable>e1</replaceable> &amp;&amp;
        <replaceable>e2</replaceable></entry>
        <entry>left</entry>
        <entry>Logical AND.</entry>
      </row>
      <row>
        <entry><replaceable>e1</replaceable> ||
        <replaceable>e2</replaceable></entry>
        <entry>left</entry>
        <entry>Logical OR.</entry>
      </row>
      <row>
        <entry><replaceable>e1</replaceable> ->
        <replaceable>e2</replaceable></entry>
        <entry>none</entry>
        <entry>Logical implication (equivalent to
        <literal>!<replaceable>e1</replaceable> ||
        <replaceable>e2</replaceable></literal>).</entry>
      </row>
    </tbody>
  </tgroup>
</table>

</section>


<section xml:id="ssec-derivation"><title>Derivations</title>

<para>The most important built-in function is
<function>derivation</function>, which is used to describe a
single derivation (a build action).  It takes as input an attribute
set, the attributes of which specify the inputs of the build.</para>

<itemizedlist>

  <listitem xml:id="attr-system"><para>There must be an attribute named
  <varname>system</varname> whose value must be a string specifying a
  Nix platform identifier, such as <literal>"i686-linux"</literal> or
  <literal>"powerpc-darwin"</literal><footnote><para>To figure out
  your platform identifier, look at the line <quote>Checking for the
  canonical Nix system name</quote> in the output of Nix's
  <filename>configure</filename> script.</para></footnote> The build
  can only be performed on a machine and operating system matching the
  platform identifier.  (Nix can automatically forward builds for
  other platforms by forwarding them to other machines; see <xref
  linkend='sec-distributed-builds' />.)</para></listitem>

  <listitem><para>There must be an attribute named
  <varname>name</varname> whose value must be a string.  This is used
  as a symbolic name for the component by <command>nix-env</command>,
  and it is appended to the hash in the output path of the
  derivation.</para></listitem>

  <listitem><para>There must be an attribute named
  <varname>builder</varname> that identifies the program that is
  executed to perform the build.  It can be either a derivation or a
  source (a local file reference, e.g.,
  <filename>./builder.sh</filename>).</para></listitem>

  <listitem><para>Every attribute is passed as an environment variable
  to the builder.  Attribute values are translated to environment
  variables as follows:

    <itemizedlist>

      <listitem><para>Strings, URIs, and integers are just passed
      verbatim.</para></listitem>

      <listitem><para>A <emphasis>path</emphasis> (e.g.,
      <filename>../foo/sources.tar</filename>) causes the referenced
      file to be copied to the store; its location in the store is put
      in the environment variable.  The idea is that all sources
      should reside in the Nix store, since all inputs to a derivation
      should reside in the Nix store.</para></listitem>

      <listitem><para>A <emphasis>derivation</emphasis> causes that
      derivation to be built prior to the present derivation; the
      output path is put in the environment
      variable.</para></listitem>

      <listitem><para>Lists of the previous types are also allowed.
      They are simply concatenated, separated by
      spaces.</para></listitem>

      <listitem><para><emphasis>true</emphasis> is passed as 
      <emphasis>1</emphasis>, <emphasis>false</emphasis>
      and <emphasis>null</emphasis> are passed as empty string.
      </para></listitem>
    </itemizedlist>

  </para></listitem>

  <listitem><para>The optional argument <varname>args</varname>
  specifies command-line arguments to be passed to the builder.  It
  should be a list.</para></listitem>

</itemizedlist>

<para>(Note that <function>mkDerivation</function> in the standard
environment is a wrapper around <function>derivation</function> that
adds a default value for <varname>system</varname> and always uses
Bash as the builder, to which the supplied builder is passed as a
command-line argument.  See <xref linkend='sec-standard-environment'
/>.)</para>

<para>The builder is executed as follows:

<itemizedlist>

  <listitem><para>A temporary directory is created under the directory
  specified by <envar>TMPDIR</envar> (default
  <filename>/tmp</filename>) where the build will take place.  The
  current directory is changed to this directory.</para></listitem>

  <listitem><para>The environment is cleared and set to the derivation
  attributes, as specified above.</para></listitem>

  <listitem><para>In addition, the following variables are set:

  <itemizedlist>

    <listitem><para><envar>NIX_BUILD_TOP</envar> contains the path of
    the temporary directory for this build.</para></listitem>

    <listitem><para>Also, <envar>TMPDIR</envar>,
    <envar>TEMPDIR</envar>, <envar>TMP</envar>, <envar>TEMP</envar>
    are set to point to the temporary directory.  This is to prevent
    the builder from accidentally writing temporary files anywhere
    else.  Doing so might cause interference by other
    processes.</para></listitem>

    <listitem><para><envar>PATH</envar> is set to
    <filename>/path-not-set</filename> to prevent shells from
    initialising it to their built-in default value.</para></listitem>

    <listitem><para><envar>HOME</envar> is set to
    <filename>/homeless-shelter</filename> to prevent programs from
    using <filename>/etc/passwd</filename> or the like to find the
    user's home directory, which could cause impurity.  Usually, when
    <envar>HOME</envar> is set, it is used as the location of the home
    directory, even if it points to a non-existent
    path.</para></listitem>

    <listitem><para><envar>NIX_STORE</envar> is set to the path of the
    top-level Nix store directory (typically,
    <filename>/nix/store</filename>).</para></listitem>

    <listitem><para><envar>out</envar> is set to point to the output
    path of the derivation, which is a subdirectory of the Nix store.
    The output path is a concatenation of the cryptographic hash of
    all build inputs, and the <varname>name</varname>
    attribute.</para></listitem>
    
  </itemizedlist>

  </para></listitem>

  <listitem><para>If the output path already exists, it is removed.
  Also, locks are acquired to prevent multiple Nix instances from
  performing the same build at the same time.</para></listitem>

  <listitem><para>A log of the combined standard output and error is
  written to <filename>/nix/var/log/nix</filename>.</para></listitem>

  <listitem><para>The builder is executed with the arguments specified
  by the attribute <varname>args</varname>.  If it exits with exit
  code 0, it is considered to have succeeded.</para></listitem>

  <listitem><para>The temporary directory is removed (unless the
  <option>-K</option> option was specified).</para></listitem>

  <listitem><para>If the build was successful, Nix scans the output
  for references to the paths of the inputs.  These so-called
  <emphasis>retained dependencies</emphasis> could be used when the
  output of the derivation is used (e.g., when it's executed or used
  as input to another derivation), so if we deploy the derivation, we
  should copy the retained dependencies as well.  The scan is
  performed by looking for the hash parts of file names of the
  inputs.</para></listitem>

  <listitem><para>After the build, Nix sets the last-modified
  timestamp on all files in the build result to 0 (00:00:00 1/1/1970
  UTC), sets the group to the default group, and sets the mode of the
  file to 0444 or 0555 (i.e., read-only, with execute permission
  enabled if the file was originally executable).  Note that possible
  <literal>setuid</literal> and <literal>setgid</literal> bits are
  cleared.  Setuid and setgid programs are not currently supported by
  Nix.  This is because the Nix archives used in deployment have no
  concept of ownership information, and because it makes the build
  result dependent on the user performing the build.</para></listitem>

</itemizedlist>

</para>

</section>


<section><title>Built-in functions</title>

<para>This section lists the functions and constants built into the
Nix expression evaluator.  (The built-in function
<function>derivation</function> is discussed above.)  Some built-ins,
such as <function>derivation</function>, are always in scope of every
Nix expression; you can just access them right away.  But to prevent
polluting the namespace too much, most built-ins are not in scope.
Instead, you can access them through the <varname>builtins</varname>
built-in value, which is an attribute set that contains all built-in
functions and values.  For instance, <function>derivation</function>
is also available as <function>builtins.derivation</function>.</para>


<variablelist>

  
  <varlistentry><term><function>abort</function> <replaceable>s</replaceable></term>

    <listitem><para>Abort Nix expression evaluation, print error
    message <replaceable>s</replaceable>.</para></listitem>

  </varlistentry>

  
  <varlistentry><term><function>builtins.add</function>
  <replaceable>e1</replaceable> <replaceable>e2</replaceable></term>

    <listitem><para>Return the sum of the integers
    <replaceable>e1</replaceable> and
    <replaceable>e2</replaceable>.</para></listitem>

  </varlistentry>

  
  <varlistentry><term><function>builtins.attrNames</function>
  <replaceable>attrs</replaceable></term>

    <listitem><para>Return the names of the attributes in the
    attribute set <replaceable>attrs</replaceable> in a sorted list.
    For instance, <literal>builtins.attrNames {y = 1; x =
    "foo";}</literal> evaluates to <literal>["x" "y"]</literal>.
    There is no built-in function <function>attrValues</function>, but
    you can easily define it yourself:

<programlisting>
attrValues = attrs: map (name: builtins.getAttr name attrs) (builtins.attrNames attrs);</programlisting>

    </para></listitem>

  </varlistentry>

  
  <varlistentry><term><function>baseNameOf</function> <replaceable>s</replaceable></term>

    <listitem><para>Return the <emphasis>base name</emphasis> of the
    string <replaceable>s</replaceable>, that is, everything following
    the final slash in the string.  This is similar to the GNU
    <command>basename</command> command.</para></listitem>

  </varlistentry>

  
  <varlistentry><term><varname>builtins</varname></term>

    <listitem><para>The attribute set <varname>builtins</varname>
    contains all the built-in functions and values.  You can use
    <varname>builtins</varname> to test for the availability of
    features in the Nix installation, e.g.,

<programlisting>
if builtins ? getEnv then builtins.getEnv "PATH" else ""</programlisting>

    This allows a Nix expression to fall back gracefully on older Nix
    installations that don’t have the desired built-in function.
    However, in that case you should not write

<programlisting>
if builtins ? getEnv then __getEnv "PATH" else ""</programlisting>

    This Nix expression will trigger an “undefined variable” error on
    older Nix versions since <function>__getEnv</function> doesn’t
    exist.  <literal>builtins.getEnv</literal>, on the other hand, is
    safe since <literal>builtins</literal> always exists and attribute
    selection is lazy, so it’s only performed if the test
    succeeds.</para></listitem>

  </varlistentry>

  
  <varlistentry
  xml:id='builtin-currentSystem'><term><varname>builtins.currentSystem</varname></term>

    <listitem><para>The built-in value <varname>currentSystem</varname>
    evaluates to the Nix platform identifier for the Nix installation
    on which the expression is being evaluated, such as
    <literal>"i686-linux"</literal> or
    <literal>"powerpc-darwin"</literal>.</para></listitem>

  </varlistentry>


  <!--
  <varlistentry><term><function>currentTime</function></term>

    <listitem><para>The built-in value <varname>currentTime</varname>
    returns the current system time in seconds since 00:00:00 1/1/1970
    UTC.  Due to the evaluation model of Nix expressions
    (<emphasis>maximal laziness</emphasis>), it always yields the same
    value within an execution of Nix.</para></listitem>

  </varlistentry>
  -->

  
  <!--
  <varlistentry><term><function>dependencyClosure</function></term>

    <listitem><para>TODO</para></listitem>

  </varlistentry>
  -->

  
  <varlistentry><term><function>derivation</function>
  <replaceable>attrs</replaceable></term>

    <listitem><para><function>derivation</function> is described in
    <xref linkend='ssec-derivation' />.</para></listitem>

  </varlistentry>


  <varlistentry><term><function>dirOf</function> <replaceable>s</replaceable></term>

    <listitem><para>Return the directory part of the string
    <replaceable>s</replaceable>, that is, everything before the final
    slash in the string.  This is similar to the GNU
    <command>dirname</command> command.</para></listitem>

  </varlistentry>

  
  <varlistentry><term><function>builtins.getAttr</function>
  <replaceable>s</replaceable> <replaceable>attrs</replaceable></term>

    <listitem><para><function>getAttr</function> returns the attribute
    named <replaceable>s</replaceable> from the attribute set
    <replaceable>attrs</replaceable>.  Evaluation aborts if the
    attribute doesn’t exist.  This is a dynamic version of the
    <literal>.</literal> operator, since <replaceable>s</replaceable>
    is an expression rather than an identifier.</para></listitem>

  </varlistentry>

  
  <varlistentry><term><function>builtins.getEnv</function>
  <replaceable>s</replaceable></term>

    <listitem><para><function>getEnv</function> returns the value of
    the environment variable <replaceable>s</replaceable>, or an empty
    string if the variable doesn’t exist.  This function should be
    used with care, as it can introduce all sorts of nasty environment
    dependencies in your Nix expression.</para>

    <para><function>getEnv</function> is used in Nix Packages to
    locate the file <filename>~/.nixpkgs/config.nix</filename>, which
    contains user-local settings for Nix Packages.  (That is, it does
    a <literal>getEnv "HOME"</literal> to locate the user’s home
    directory.)</para></listitem>

  </varlistentry>

  
  <varlistentry><term><function>builtins.hasAttr</function>
  <replaceable>s</replaceable> <replaceable>attrs</replaceable></term>

    <listitem><para><function>hasAttr</function> returns
    <literal>true</literal> if the attribute set
    <replaceable>attrs</replaceable> has an attribute named
    <replaceable>s</replaceable>, and <literal>false</literal>
    otherwise.  This is a dynamic version of the <literal>?</literal>
    operator, since <replaceable>s</replaceable> is an expression
    rather than an identifier.</para></listitem>

  </varlistentry>

  
  <varlistentry><term><function>builtins.head</function>
  <replaceable>list</replaceable></term>

    <listitem><para>Return the first element of a list; abort
    evaluation if the argument isn’t a list or is an empty list.  You
    can test whether a list is empty by comparing it with
    <literal>[]</literal>.</para></listitem>

  </varlistentry>

  
  <varlistentry><term><function>import</function>
  <replaceable>path</replaceable></term>

    <listitem><para>Load, parse and return the Nix expression in the
    file <replaceable>path</replaceable>.  Evaluation aborts if the
    file doesn’t exist or contains an incorrect Nix
    expression.  <function>import</function> implements Nix’s module
    system: you can put any Nix expression (such as an attribute set
    or a function) in a separate file, and use it from Nix expressions
    in other files.</para>

    <para>A Nix expression loaded by <function>import</function> must
    not contain any <emphasis>free variables</emphasis> (identifiers
    that are not defined in the Nix expression itself and are not
    built-in).  Therefore, it cannot refer to variables that are in
    scope at the call site.  For instance, if you have a calling
    expression
    
<programlisting>
rec {
  x = 123;
  y = import ./foo.nix;
}</programlisting>

    then the following <filename>foo.nix</filename> will give an
    error:

<programlisting>
x + 456</programlisting>

    since <varname>x</varname> is not in scope in
    <filename>foo.nix</filename>.  If you want <varname>x</varname>
    to be available in <filename>foo.nix</filename>, you should pass
    it as a function argument:

<programlisting>
rec {
  x = 123;
  y = import ./foo.nix x;
}</programlisting>

    and

<programlisting>
x: x + 456</programlisting>

    (The function argument doesn’t have to be called
    <varname>x</varname> in <filename>foo.nix</filename>; any name
    would work.)</para></listitem>

  </varlistentry>

  
  <varlistentry><term><function>builtins.isList</function>
  <replaceable>e</replaceable></term>

    <listitem><para>Return <literal>true</literal> if
    <replaceable>e</replaceable> evaluates to a list, and
    <literal>false</literal> otherwise.</para></listitem>

  </varlistentry>

  
  <varlistentry><term><function>isNull</function>
  <replaceable>e</replaceable></term>

    <listitem><para>Return <literal>true</literal> if
    <replaceable>e</replaceable> evaluates to <literal>null</literal>,
    and <literal>false</literal> otherwise.</para>

    <warning><para>This function is <emphasis>deprecated</emphasis>;
    just write <literal>e == null</literal> instead.</para></warning>
    
    </listitem>

  </varlistentry>

  
  <varlistentry><term><function>builtins.lessThan</function>
  <replaceable>e1</replaceable> <replaceable>e2</replaceable></term>

    <listitem><para>Return <literal>true</literal> if the integer
    <replaceable>e1</replaceable> is less than the integer
    <replaceable>e2</replaceable>, and <literal>false</literal>
    otherwise.  Evaluation aborts if either
    <replaceable>e1</replaceable> or <replaceable>e2</replaceable>
    does not evaluate to an integer.</para></listitem>

  </varlistentry>

  
  <varlistentry><term><function>map</function>
  <replaceable>f</replaceable> <replaceable>list</replaceable></term>

    <listitem><para>Apply the function <replaceable>f</replaceable> to
    each element in the list <replaceable>list</replaceable>.  For
    example,

<programlisting>
map (x: "foo" + x) ["bar" "bla" "abc"]</programlisting>

    evaluates to <literal>["foobar" "foobla"
    "fooabc"]</literal>.</para></listitem>
    
  </varlistentry>

  
  <varlistentry><term><function>builtins.pathExists</function>
  <replaceable>path</replaceable></term>

    <listitem><para>Return <literal>true</literal> if the path
    <replaceable>path</replaceable> exists, and
    <literal>false</literal> otherwise.  One application of this
    function is to conditionally include a Nix expression containing
    user configuration:

<programlisting>
let
  fileName = builtins.getEnv "CONFIG_FILE";
  config =
    if fileName != "" &amp;&amp; builtins.pathExists (builtins.toPath fileName)
    then import (builtins.toPath fileName)
    else { someSetting = false; }; <lineannotation># default configuration</lineannotation>
in config.someSetting</programlisting>

    (Note that <envar>CONFIG_FILE</envar> must be an absolute path for
    this to work.)</para></listitem>

  </varlistentry>


  <!--
  <varlistentry><term><function>relativise</function></term>

    <listitem><para>TODO</para></listitem>

  </varlistentry>
  -->

  
  <varlistentry><term><function>removeAttrs</function>
  <replaceable>attrs</replaceable> <replaceable>list</replaceable></term>

    <listitem><para>Remove the attributes listed in
    <replaceable>list</replaceable> from the attribute set
    <replaceable>attrs</replaceable>.  The attributes don’t have to
    exist in <replaceable>attrs</replaceable>. For instance,

<screen>
removeAttrs { x = 1; y = 2; z = 3; } ["a" "x" "z"]</screen>

    evaluates to <literal>{y = 2;}</literal>.</para></listitem>

  </varlistentry>

  
  <varlistentry><term><function>builtins.tail</function>
  <replaceable>list</replaceable></term>

    <listitem><para>Return the second to last elements of a list;
    abort evaluation if the argument isn’t a list or is an empty
    list.</para></listitem>

  </varlistentry>

  
  <varlistentry
  xml:id='builtin-toFile'><term><function>builtins.toFile</function>
  <replaceable>name</replaceable> <replaceable>s</replaceable></term>

    <listitem><para>Store the string <replaceable>s</replaceable> in a
    file in the Nix store and return its path.  The file has suffix
    <replaceable>name</replaceable>.  This file can be used as an
    input to derivations.  One application is to write builders
    “inline”.  For instance, the following Nix expression combines
    <xref linkend='ex-hello-nix' /> and <xref
    linkend='ex-hello-builder' /> into one file:

<programlisting>
{stdenv, fetchurl, perl}:

stdenv.mkDerivation {
  name = "hello-2.1.1";
  
  builder = builtins.toFile "builder.sh" "
    source $stdenv/setup

    PATH=$perl/bin:$PATH

    tar xvfz $src
    cd hello-*
    ./configure --prefix=$out
    make
    make install
  ";

  src = fetchurl {
    url = http://nix.cs.uu.nl/dist/tarballs/hello-2.1.1.tar.gz;
    md5 = "70c9ccf9fac07f762c24f2df2290784d";
  };
  inherit perl;
}</programlisting>
  
    </para>

    <para>It is even possible for one file to refer to another, e.g.,

<programlisting>
  builder = let
    configFile = builtins.toFile "foo.conf" "
      # This is some dummy configuration file.
      <replaceable>...</replaceable>
    ";
  in builtins.toFile "builder.sh" "
    source $stdenv/setup
    <replaceable>...</replaceable>
    cp ${configFile} $out/etc/foo.conf
  ";</programlisting>

    Note that <literal>${configFile}</literal> is an antiquotation
    (see <xref linkend='ssec-values' />), so the result of the
    expression <literal>configFile</literal> (i.e., a path like
    <filename>/nix/store/m7p7jfny445k...-foo.conf</filename>) will be
    spliced into the resulting string.</para>

    <para>It is however <emphasis>not</emphasis> allowed to have files
    mutually referring to each other, like so:

<programlisting>
let
  foo = builtins.toFile "foo" "...${bar}...";
  bar = builtins.toFile "bar" "...${foo}...";
in foo</programlisting>

    This is not allowed because it would cause a cyclic dependency in
    the computation of the cryptographic hashes for
    <varname>foo</varname> and <varname>bar</varname>.</para></listitem>

  </varlistentry>

  
  <varlistentry><term><function>builtins.toPath</function> <replaceable>s</replaceable></term>

    <listitem><para>Convert the string value
    <replaceable>s</replaceable> into a path value.  The string
    <replaceable>s</replaceable> must represent an absolute path
    (i.e., must start with <literal>/</literal>).  The path need not
    exist.  The resulting path is canonicalised, e.g.,
    <literal>builtins.toPath "//foo/xyzzy/../bar/"</literal> returns
    <literal>/foo/bar</literal>.</para></listitem>

  </varlistentry>

  
  <varlistentry><term><function>toString</function> <replaceable>e</replaceable></term>

    <listitem><para>Convert the expression
    <replaceable>e</replaceable> to a string.
    <replaceable>e</replaceable> can be a string (in which case
    <function>toString</function> is a no-op) or a path (e.g.,
    <literal>toString /foo/bar</literal> yields
    <literal>"/foo/bar"</literal>.</para></listitem>

  </varlistentry>

  
  <varlistentry xml:id='builtin-toXML'><term><function>builtins.toXML</function> <replaceable>e</replaceable></term>

    <listitem><para>Return a string containing an XML representation
    of <replaceable>e</replaceable>.  The main application for
    <function>toXML</function> is to communicate information with the
    builder in a more structured format than plain environment
    variables.</para>

    <!-- TODO: more formally describe the schema of the XML
    representation -->

    <para><xref linkend='ex-toxml' /> shows an example where this is
    the case.  The builder is supposed to generate the configuration
    file for a <link xlink:href='http://jetty.mortbay.org/'>Jetty
    servlet container</link>.  A servlet container contains a number
    of servlets (<filename>*.war</filename> files) each exported under
    a specific URI prefix.  So the servlet configuration is a list of
    attribute sets containing the <varname>path</varname> and
    <varname>war</varname> of the servlet (<xref
    linkend='ex-toxml-co-servlets' />).  This kind of information is
    difficult to communicate with the normal method of passing
    information through an environment variable, which just
    concatenates everything together into a string (which might just
    work in this case, but wouldn’t work if fields are optional or
    contain lists themselves).  Instead the Nix expression is
    converted to an XML representation with
    <function>toXML</function>, which is unambiguous and can easily be
    processed with the appropriate tools.  For instance, in the
    example an XSLT stylesheet (<xref linkend='ex-toxml-co-stylesheet'
    />) is applied to it (<xref linkend='ex-toxml-co-apply' />) to
    generate the XML configuration file for the Jetty server.  The XML
    representation produced from <xref linkend='ex-toxml-co-servlets'
    /> by <function>toXML</function> is shown in <xref
    linkend='ex-toxml-result' />.</para>

    <para>Note that <xref linkend='ex-toxml' /> uses the <function
    linkend='builtin-toFile'>toFile</function> built-in to write the
    builder and the stylesheet “inline” in the Nix expression.  The
    path of the stylesheet is spliced into the builder at
    <literal>xsltproc ${stylesheet}
    <replaceable>...</replaceable></literal>.</para>

    <example xml:id='ex-toxml'><title>Passing information to a builder
    using <function>toXML</function></title>
    
<programlisting><![CDATA[
{stdenv, fetchurl, libxslt, jira, uberwiki}:

stdenv.mkDerivation (rec {
  name = "web-server";

  buildInputs = [libxslt];
  
  builder = builtins.toFile "builder.sh" "
    source $stdenv/setup
    mkdir $out
    echo $servlets | xsltproc ${stylesheet} - > $out/server-conf.xml]]> <co xml:id='ex-toxml-co-apply' /> <![CDATA[
  ";

  stylesheet = builtins.toFile "stylesheet.xsl"]]> <co xml:id='ex-toxml-co-stylesheet' /> <![CDATA[
   "<?xml version='1.0' encoding='UTF-8'?>
    <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>
      <xsl:template match='/'>
        <Configure>
          <xsl:for-each select='/expr/list/attrs'>
            <Call name='addWebApplication'>
              <Arg><xsl:value-of select=\"attr[@name = 'path']/string/@value\" /></Arg>
              <Arg><xsl:value-of select=\"attr[@name = 'war']/path/@value\" /></Arg>
            </Call>
          </xsl:for-each>
        </Configure>
      </xsl:template>
    </xsl:stylesheet>
  ";

  servlets = builtins.toXML []]> <co xml:id='ex-toxml-co-servlets' /> <![CDATA[
    { path = "/bugtracker"; war = jira + "/lib/atlassian-jira.war"; }
    { path = "/wiki"; war = uberwiki + "/uberwiki.war"; }
  ];
})]]></programlisting>

    </example>

    <example xml:id='ex-toxml-result'><title>XML representation produced by
    <function>toXML</function></title>
    
<programlisting><![CDATA[<?xml version='1.0' encoding='utf-8'?>
<expr>
  <list>
    <attrs>
      <attr name="path">
        <string value="/bugtracker" />
      </attr>
      <attr name="war">
        <path value="/nix/store/d1jh9pasa7k2...-jira/lib/atlassian-jira.war" />
      </attr>
    </attrs>
    <attrs>
      <attr name="path">
        <string value="/wiki" />
      </attr>
      <attr name="war">
        <path value="/nix/store/y6423b1yi4sx...-uberwiki/uberwiki.war" />
      </attr>
    </attrs>
  </list>
</expr>]]></programlisting>

    </example>

    </listitem>

  </varlistentry>

  
</variablelist>

</section>


</section>



<section xml:id='sec-standard-environment'><title>The standard environment</title>

<para>The standard build environment in the Nix Packages collection
provides a basic environment for building Unix packages.  It consists
of the following components:

<itemizedlist>

  <listitem><para>The GNU C Compiler, configured with C and C++
  support.  On Linux, the compiler has been patched to provide greater
  <quote>purity</quote> assurance.  For instance, the compiler doesn't
  search in locations such as <filename>/usr/include</filename>.  In
  fact, attempts to add such directories through the
  <option>-I</option> flag are filtered out.  Likewise, the linker
  (from GNU binutils) doesn't search in standard locations such as
  <filename>/usr/lib</filename>.  Programs built on Linux are linked
  against a GNU C Library that likewise doesn't search in the default
  system locations.</para></listitem>

  <listitem><para>GNU coreutils (contains a few dozen standard Unix
  commands).</para></listitem>

  <listitem><para>GNU findutils (contains
  <command>find</command>).</para></listitem>

  <listitem><para>GNU diffutils (contains <command>diff</command>,
  <command>cmp</command>).</para></listitem>

  <listitem><para>GNU <command>sed</command>.</para></listitem>

  <listitem><para>GNU <command>grep</command>.</para></listitem>

  <listitem><para>GNU <command>awk</command>.</para></listitem>

  <listitem><para>GNU <command>tar</command>.</para></listitem>

  <listitem><para><command>gzip</command> and
  <command>bzip2</command>.</para></listitem>

  <listitem><para>GNU Make.  It has been patched to provide
  <quote>nested</quote> output that can be fed into the
  <command>nix-log2xml</command> command and
  <command>log2html</command> stylesheet to create a structured,
  readable output of the build steps performed by
  Make.</para></listitem>

  <listitem><para>Bash.  This is the shell used for all builders in
  the Nix Packages collection.  Not using <command>/bin/sh</command>
  removes a large source of portability problems.</para></listitem>

  <listitem><para>Patch.</para></listitem>

</itemizedlist>

</para>

<para>The standard environment is used by passing it as an input
called <envar>stdenv</envar> to the derivation, and then doing

<programlisting>
source $stdenv/setup</programlisting>

at the top of the builder.</para>

<para>Apart from adding the aforementioned commands to the
<envar>PATH</envar>, <filename>setup</filename> also does the
following:

<itemizedlist>

  <listitem><para>All input components specified in the
  <envar>buildInputs</envar> environment variable have their
  <filename>/bin</filename> subdirectory added to <envar>PATH</envar>,
  their <filename>/include</filename> subdirectory added to the C/C++
  header file search path, and their <filename>/lib</filename>
  subdirectory added to the linker search path.  This can be extended.
  For instance, when the <command>pkgconfig</command> component is
  used, the subdirectory <filename>/lib/pkgconfig</filename> of each
  input is added to the <envar>PKG_CONFIG_PATH</envar> environment
  variable.</para></listitem>

  <listitem><para>The environment variable
  <envar>NIX_CFLAGS_STRIP</envar> is set so that the compiler strips
  debug information from object files.  This can be disabled by
  setting <envar>NIX_STRIP_DEBUG</envar> to
  <literal>0</literal>.</para></listitem>

</itemizedlist>

</para>

<para>The <filename>setup</filename> script also exports a function
called <function>genericBuild</function> that knows how to build
typical Autoconf-style components.  It can be customised to perform
builds for any type of component.  It is advisable to use
<function>genericBuild</function> since it provides facilities that
are almost always useful such as unpacking of sources, patching of
sources, nested logging, etc.</para>

<para>The definitive, up-to-date documentation of the generic builder
is the source itself, which resides in
<filename>pkgs/stdenv/generic/setup.sh</filename>.</para>


<section><title>Customising the generic builder</title>

<para>The operation of the generic builder can be modified in many
places by setting certain variables.  These <emphasis>hook
variables</emphasis> are typically set to the name of some shell
function defined by you.  For instance, to perform some additional
steps after <command>make install</command> you would set the
<varname>postInstall</varname> variable:

<programlisting>
postInstall=myPostInstall

myPostInstall() {
    mkdir $out/share/extra
    cp extrafiles/* $out/share/extra
}</programlisting>

</para>

<para>The generic builder has a number of <emphasis>phases</emphasis>,
each of which can be override in its entirety by setting the indicated
variable.  The phases are:

<itemizedlist>

  <listitem>

    <para><function>unpackPhase</function> unpacks the source files
    listed in the <envar>src</envar> environment variable to the
    current directory.  It supports <filename>tar</filename> files,
    optionally compressed with <command>gzip</command> or
    <command>bzip2</command>; Zip files (but note that the
    <command>unzip</command> command is not a part of the standard
    environment; you should add it as a build input yourself); and
    unpacked source trees (i.e., directories; they are copied
    verbatim).  You can add support for other file types by setting
    the <varname>findUnpacker</varname> hook.  This hook should set
    the variable <varname>unpackCmd</varname> to contain the command
    to be executed to unpack the file.</para>

    <para>After unpacking all source files,
    <function>unpackPhase</function> changes the current directory to
    the directory created by unpacking the sources.  If there are
    multiple source directories, you should set
    <varname>sourceRoot</varname> to the name of the intended
    directory.</para>

    <para>It also calls the hook <varname>postUnpack</varname> after
    unpacking.</para>

  </listitem>

  <listitem><para><function>patchPhase</function> calls the
  <command>patch</command> command with the <option>-p1</option>
  option for each patch file listed in the <envar>patches</envar>
  variable.</para></listitem>

  <listitem>

    <para><function>configurePhase</function> runs the script called
    <filename>configure</filename> in the current directory with a
    <option>--prefix</option> set to the output path.  You can add
    additional flags through the <varname>configureFlags</varname>
    variable.  If <filename>configure</filename> does not exist,
    nothing happens.</para>

    <para>Before and after running <filename>configure</filename>, the
    hooks <varname>preConfigure</varname> and
    <varname>postConfigure</varname> are called, respectively.</para>

  </listitem>

  <listitem>

    <para><function>buildPhase</function> calls
    <command>make</command>.  You can set flags for
    <command>make</command> through the <varname>makeFlags</varname>
    variable.</para>

    <para>Before and after running <command>make</command>, the hooks
    <varname>preBuild</varname> and <varname>postBuild</varname> are
    called, respectively.</para>
    
  </listitem>

  <listitem><para><function>checkPhase</function> calls <command>make
  check</command>, but only if the <varname>doCheck</varname> variable
  is set to <literal>1</literal>.  Additional flags can be set through
  the <varname>checkFlags</varname> variable.</para></listitem>

  <listitem>

    <para><function>installPhase</function> calls <command>make
    install</command>.  Additional flags can be set through the
    <varname>installFlags</varname> variable.  It also strips any
    static libraries in the output path of debug information unless
    <varname>dontStrip</varname> is set to
    <literal>1</literal>.</para>

    <para>Before and after running <command>make install</command>,
    the hooks <varname>preInstall</varname> and
    <varname>postInstall</varname> are called, respectively.</para>

  </listitem>

  <listitem>

    <para><function>distPhase</function> calls <command>make
    dist</command>, but only if the <varname>doDist</varname> variable
    is set to <literal>1</literal>.  Additional flags can be set
    through the <varname>distFlags</varname> variable.  The resulting
    tarball is copied to the <filename>/tarballs</filename>
    subdirectory of the output path.</para>

    <para>Before and after running <command>make dist</command>, the
    hooks <varname>preDist</varname> and <varname>postDist</varname>
    are called, respectively.</para>
    
  </listitem>

</itemizedlist>

</para>

<para>You can change the order in which phases are executed, or add
new phases, by setting the <varname>phases</varname> variable.  The
default is <literal>patchPhase configurePhase buildPhase checkPhase
installPhase distPhase</literal>.</para>

</section>


<section><title>Debugging failed builds</title>

<para>At the beginning of each phase, the set of all shell variables
is written to the file <filename>env-vars</filename> at the top-level
build directory.  This is useful for debugging: it allows you to
recreate the environment in which a build was performed.  For
instance, if a build fails, then assuming you used the
<option>-K</option> flag, you can go to the output directory and
<quote>switch</quote> to the environment of the builder:

<screen>
$ nix-build -K ./foo.nix
... fails, keeping build directory `/tmp/nix-1234-0'

$ cd /tmp/nix-1234-0

$ source env-vars

<lineannotation>(edit some files...)</lineannotation>

$ make

<lineannotation>(execution continues with the same GCC, make, etc.)</lineannotation></screen>

</para>

</section>


</section>


</chapter>