summaryrefslogtreecommitdiff
path: root/guix/gexp.scm
blob: dfeadbd15d633dfa2914b2df3e9e416f8fe902f9 (about) (plain)
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
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2014-2022 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2018 Clément Lassieur <clement@lassieur.org>
;;; Copyright © 2018 Jan Nieuwenhuizen <janneke@gnu.org>
;;; Copyright © 2019, 2020 Mathieu Othacehe <m.othacehe@gmail.com>
;;; Copyright © 2020 Maxim Cournoyer <maxim.cournoyer@gmail.com>
;;; Copyright © 2021 Maxime Devos <maximedevos@telenet.be>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.

(define-module (guix gexp)
  #:use-module (guix store)
  #:use-module (guix monads)
  #:use-module (guix derivations)
  #:use-module (guix grafts)
  #:use-module (guix utils)
  #:use-module (guix diagnostics)
  #:use-module (guix i18n)
  #:use-module (rnrs bytevectors)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-9)
  #:use-module (srfi srfi-9 gnu)
  #:use-module (srfi srfi-26)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-35)
  #:use-module (ice-9 format)
  #:use-module (ice-9 match)
  #:export (gexp
            gexp?
            sexp->gexp
            with-imported-modules
            with-extensions
            let-system
            gexp->approximate-sexp

            gexp-input
            gexp-input?
            gexp-input-thing
            gexp-input-output
            gexp-input-native?

            assume-valid-file-name
            local-file
            local-file?
            local-file-file
            local-file-absolute-file-name
            local-file-name
            local-file-recursive?
            local-file-select?

            plain-file
            plain-file?
            plain-file-name
            plain-file-content

            computed-file
            computed-file?
            computed-file-name
            computed-file-gexp
            computed-file-options

            program-file
            program-file?
            program-file-name
            program-file-gexp
            program-file-guile
            program-file-module-path

            scheme-file
            scheme-file?
            scheme-file-name
            scheme-file-gexp

            file-append
            file-append?
            file-append-base
            file-append-suffix

            raw-derivation-file
            raw-derivation-file?

            with-parameters
            parameterized?

            load-path-expression
            gexp-modules

            lower-gexp
            lowered-gexp?
            lowered-gexp-sexp
            lowered-gexp-inputs
            lowered-gexp-sources
            lowered-gexp-guile
            lowered-gexp-load-path
            lowered-gexp-load-compiled-path

            with-build-variables
            input-tuples->gexp
            outputs->gexp

            gexp->derivation
            gexp->file
            gexp->script
            text-file*
            mixed-text-file
            file-union
            directory-union

            imported-files
            imported-modules
            compiled-modules

            define-gexp-compiler
            gexp-compiler?
            file-like?
            lower-object

            &gexp-error
            gexp-error?
            &gexp-input-error
            gexp-input-error?
            gexp-error-invalid-input))

;;; Commentary:
;;;
;;; This module implements "G-expressions", or "gexps".  Gexps are like
;;; S-expressions (sexps), with two differences:
;;;
;;;   1. References (un-quotations) to derivations or packages in a gexp are
;;;      replaced by the corresponding output file name; in addition, the
;;;      'ungexp-native' unquote-like form allows code to explicitly refer to
;;;      the native code of a given package, in case of cross-compilation;
;;;
;;;   2. Gexps embed information about the derivations they refer to.
;;;
;;; Gexps make it easy to write to files Scheme code that refers to store
;;; items, or to write Scheme code to build derivations.
;;;
;;; Code:

;; "G expressions".
(define-record-type <gexp>
  (make-gexp references modules extensions proc location)
  gexp?
  (references gexp-references)                    ;list of <gexp-input>
  (modules    gexp-self-modules)                  ;list of module names
  (extensions gexp-self-extensions)               ;list of lowerable things
  (proc       gexp-proc)                          ;procedure
  (location   %gexp-location))                    ;location alist

(define (gexp-location gexp)
  "Return the source code location of GEXP."
  (and=> (%gexp-location gexp) source-properties->location))

(define* (gexp->approximate-sexp gexp)
  "Return the S-expression corresponding to GEXP, but do not lower anything.
As a result, the S-expression will be approximate if GEXP has references."
  (define (gexp-like? thing)
    (or (gexp? thing) (gexp-input? thing)))
  (apply (gexp-proc gexp)
         (map (lambda (reference)
                (match reference
                  (($ <gexp-input> thing output native)
                   (if (gexp-like? thing)
                       (gexp->approximate-sexp thing)
                       ;; Simply returning 'thing' won't work in some
                       ;; situations; see 'write-gexp' below.
                       '(*approximate*)))
                  (_ '(*approximate*))))
              (gexp-references gexp))))

(define (write-gexp gexp port)
  "Write GEXP on PORT."
  (display "#<gexp " port)

  ;; Try to write the underlying sexp.  Now, this trick doesn't work when
  ;; doing things like (ungexp-splicing (gexp ())) because GEXP's procedure
  ;; tries to use 'append' on that, which fails with wrong-type-arg.
  (false-if-exception
   (write (apply (gexp-proc gexp)
                 (gexp-references gexp))
          port))

  (let ((loc (gexp-location gexp)))
    (when loc
      (format port " ~a" (location->string loc))))

  (format port " ~a>"
          (number->string (object-address gexp) 16)))

(set-record-type-printer! <gexp> write-gexp)

(define (gexp-with-hidden-inputs gexp inputs)
  "Add INPUTS, a list of <gexp-input>, to the references of GEXP.  These are
\"hidden inputs\" because they do not actually appear in the expansion of GEXP
returned by 'gexp->sexp'."
  (make-gexp (append inputs (gexp-references gexp))
             (gexp-self-modules gexp)
             (gexp-self-extensions gexp)
             (let ((extra (length inputs)))
               (lambda args
                 (apply (gexp-proc gexp) (drop args extra))))
             (gexp-location gexp)))


;;;
;;; Methods.
;;;

;; Compiler for a type of objects that may be introduced in a gexp.
(define-record-type <gexp-compiler>
  (gexp-compiler type lower expand)
  gexp-compiler?
  (type       gexp-compiler-type)                 ;record type descriptor
  (lower      gexp-compiler-lower)
  (expand     gexp-compiler-expand))              ;#f | DRV -> sexp

(define-condition-type &gexp-error &error
  gexp-error?)

(define-condition-type &gexp-input-error &gexp-error
  gexp-input-error?
  (input gexp-error-invalid-input))


(define %gexp-compilers
  ;; 'eq?' mapping of record type descriptor to <gexp-compiler>.
  (make-hash-table 20))

(define (default-expander thing obj output)
  "This is the default expander for \"things\" that appear in gexps.  It
returns its output file name of OBJ's OUTPUT."
  (match obj
    ((? derivation? drv)
     (derivation->output-path drv output))
    ((? string? file)
     file)
    ((? self-quoting? obj)
     obj)))

(define (register-compiler! compiler)
  "Register COMPILER as a gexp compiler."
  (hashq-set! %gexp-compilers
              (gexp-compiler-type compiler) compiler))

(define (lookup-compiler object)
  "Search for a compiler for OBJECT.  Upon success, return the three argument
procedure to lower it; otherwise return #f."
  (and=> (hashq-ref %gexp-compilers (struct-vtable object))
         gexp-compiler-lower))

(define (file-like? object)
  "Return #t if OBJECT leads to a file in the store once unquoted in a
G-expression; otherwise return #f."
  (and (struct? object) (->bool (lookup-compiler object))))

(define (lookup-expander object)
  "Search for an expander for OBJECT.  Upon success, return the three argument
procedure to expand it; otherwise return #f."
  (and=> (hashq-ref %gexp-compilers (struct-vtable object))
         gexp-compiler-expand))

(define* (lower-object obj
                       #:optional (system (%current-system))
                       #:key (target 'current))
  "Return as a value in %STORE-MONAD the derivation or store item
corresponding to OBJ for SYSTEM, cross-compiling for TARGET if TARGET is true.
OBJ must be an object that has an associated gexp compiler, such as a
<package>."
  (mlet %store-monad ((target (if (eq? target 'current)
                                  (current-target-system)
                                  (return target)))
                      (graft? (grafting?)))
    (let loop ((obj obj))
      (match (lookup-compiler obj)
        (#f
         (raise (condition (&gexp-input-error (input obj)))))
        (lower
         ;; Cache in STORE the result of lowering OBJ.  If OBJ is a
         ;; derivation, bypass the cache.
         (if (derivation? obj)
             (return obj)
             (mcached (mlet %store-monad ((lowered (lower obj system target)))
                        (if (and (struct? lowered)
                                 (not (derivation? lowered)))
                            (loop lowered)
                            (return lowered)))
                      obj
                      system target graft?)))))))

(define* (lower+expand-object obj
                              #:optional (system (%current-system))
                              #:key target (output "out"))
  "Return as a value in %STORE-MONAD the output of object OBJ expands to for
SYSTEM and TARGET.  Object such as <package>, <file-append>, or <plain-file>
expand to file names, but it's possible to expand to a plain data type."
  (let loop ((obj obj)
             (expand (and (struct? obj) (lookup-expander obj))))
    (match (lookup-compiler obj)
      (#f
       (raise (condition (&gexp-input-error (input obj)))))
      (lower
       (mlet* %store-monad ((graft?  (grafting?))
                            (lowered (if (derivation? obj)
                                         (return obj)
                                         (mcached (lower obj system target)
                                                  obj
                                                  system target graft?))))
         ;; LOWER might return something that needs to be further
         ;; lowered.
         (if (struct? lowered)
             ;; If we lack an expander, delegate to that of LOWERED.
             (if (not expand)
                 (loop lowered (lookup-expander lowered))
                 (return (expand obj lowered output)))
             (if (not expand)                     ;self-quoting
                 (return lowered)
                 (return (expand obj lowered output)))))))))

(define-syntax define-gexp-compiler
  (syntax-rules (=> compiler expander)
    "Define NAME as a compiler for objects matching PREDICATE encountered in
gexps.

In the simplest form of the macro, BODY must return (1) a derivation for
a record of the specified type, for SYSTEM and TARGET (the latter of which is
#f except when cross-compiling), (2) another record that can itself be
compiled down to a derivation, or (3) an object of a primitive data type.

The more elaborate form allows you to specify an expander:

  (define-gexp-compiler something-compiler <something>
    compiler => (lambda (param system target) ...)
    expander => (lambda (param drv output) ...))

The expander specifies how an object is converted to its sexp representation."
    ((_ (name (param record-type) system target) body ...)
     (define-gexp-compiler name record-type
       compiler => (lambda (param system target) body ...)
       expander => default-expander))
    ((_ name record-type
        compiler => compile
        expander => expand)
     (begin
       (define name
         (gexp-compiler record-type compile expand))
       (register-compiler! name)))))

(define-gexp-compiler (derivation-compiler (drv <derivation>) system target)
  ;; Derivations are the lowest-level representation, so this is the identity
  ;; compiler.
  (with-monad %store-monad
    (return drv)))

;; Expand to a raw ".drv" file for the lowerable object it wraps.  In other
;; words, this gives the raw ".drv" file instead of its build result.
(define-record-type <raw-derivation-file>
  (raw-derivation-file obj)
  raw-derivation-file?
  (obj  raw-derivation-file-object))              ;lowerable object

(define-gexp-compiler raw-derivation-file-compiler <raw-derivation-file>
  compiler => (lambda (obj system target)
                (mlet %store-monad ((obj (lower-object
                                          (raw-derivation-file-object obj)
                                          system #:target target)))
                  ;; Returning the .drv file name instead of the <derivation>
                  ;; record ensures that 'lower-gexp' will classify it as a
                  ;; "source" and not as an "input".
                  (return (if (derivation? obj)
                              (derivation-file-name obj)
                              obj))))
  expander => (lambda (obj lowered output)
                (if (derivation? lowered)
                    (derivation-file-name lowered)
                    lowered)))


;;;
;;; System dependencies.
;;;

;; Binding form for the current system and cross-compilation target.
(define-record-type <system-binding>
  (system-binding proc)
  system-binding?
  (proc system-binding-proc))

(define-syntax let-system
  (syntax-rules ()
    "Introduce a system binding in a gexp.  The simplest form is:

  (let-system system
    (cond ((string=? system \"x86_64-linux\") ...)
          (else ...)))

which binds SYSTEM to the currently targeted system.  The second form is
similar, but it also shows the cross-compilation target:

  (let-system (system target)
    ...)

Here TARGET is bound to the cross-compilation triplet or #f."
    ((_ (system target) exp0 exp ...)
     (system-binding (lambda (system target)
                       exp0 exp ...)))
    ((_ system exp0 exp ...)
     (system-binding (lambda (system target)
                       exp0 exp ...)))))

(define-gexp-compiler system-binding-compiler <system-binding>
  compiler => (lambda (binding system target)
                (match binding
                  (($ <system-binding> proc)
                   (with-monad %store-monad
                     ;; PROC is expected to return a lowerable object.
                     ;; 'lower-object' takes care of residualizing it to a
                     ;; derivation or similar.
                     (return (proc system target))))))

  ;; Delegate to the expander of the object returned by PROC.
  expander => #f)


;;;
;;; File declarations.
;;;

;; A local file name.  FILE is the file name the user entered, which can be a
;; relative file name, and ABSOLUTE is a promise that computes its canonical
;; absolute file name.  We keep it in a promise to compute it lazily and avoid
;; repeated 'stat' calls.
(define-record-type <local-file>
  (%%local-file file absolute name recursive? select?)
  local-file?
  (file       local-file-file)                    ;string
  (absolute   %local-file-absolute-file-name)     ;promise string
  (name       local-file-name)                    ;string
  (recursive? local-file-recursive?)              ;Boolean
  (select?    local-file-select?))                ;string stat -> Boolean

(define (true file stat) #t)

(define* (%local-file file promise #:optional (name (basename file))
                      #:key
                      (literal? #t) location
                      recursive? (select? true))
  ;; This intermediate procedure is part of our ABI, but the underlying
  ;; %%LOCAL-FILE is not.
  (when (and (not literal?) (not (string-prefix? "/" file)))
    (warning (and=> location source-properties->location)
             (G_ "resolving '~a' relative to current directory~%")
             file))
  (%%local-file file promise name recursive? select?))

(define (absolute-file-name file directory)
  "Return the canonical absolute file name for FILE, which lives in the
vicinity of DIRECTORY."
  (canonicalize-path
   (cond ((string-prefix? "/" file) file)
         ((not directory) file)
         ((string-prefix? "/" directory)
          (string-append directory "/" file))
         (else file))))

(define-syntax-rule (assume-valid-file-name file)
  "This is a syntactic keyword to tell 'local-file' that it can assume that
the given file name is valid, even if it's not a string literal, and thus not
warn about it."
  file)

(define-syntax local-file
  (lambda (s)
    "Return an object representing local file FILE to add to the store; this
object can be used in a gexp.  If FILE is a relative file name, it is looked
up relative to the source file where this form appears.  FILE will be added to
the store under NAME--by default the base name of FILE.

When RECURSIVE? is true, the contents of FILE are added recursively; if FILE
designates a flat file and RECURSIVE? is true, its contents are added, and its
permission bits are kept.

When RECURSIVE? is true, call (SELECT?  FILE STAT) for each directory entry,
where FILE is the entry's absolute file name and STAT is the result of
'lstat'; exclude entries for which SELECT? does not return true.

This is the declarative counterpart of the 'interned-file' monadic procedure.
It is implemented as a macro to capture the current source directory where it
appears."
    (syntax-case s (assume-valid-file-name)
      ((_ file rest ...)
       (string? (syntax->datum #'file))
       ;; FILE is a literal, so resolve it relative to the source directory.
       #'(%local-file file
                      (delay (absolute-file-name file (current-source-directory)))
                      rest ...))
      ((_ (assume-valid-file-name file) rest ...)
       ;; FILE is not a literal, so resolve it relative to the current
       ;; directory.  Since the user declared FILE is valid, do not pass
       ;; #:literal? #f so that we do not warn about it later on.
       #'(%local-file file
                      (delay (absolute-file-name file (getcwd)))
                      rest ...))
      ((_ file rest ...)
       ;; Resolve FILE relative to the current directory.
       (with-syntax ((location (datum->syntax s (syntax-source s))))
        #`(%local-file file
                       (delay (absolute-file-name file (getcwd)))
                       rest ...
                       #:location 'location
                       #:literal? #f)))           ;warn if FILE is relative
      ((_)
       #'(syntax-error "missing file name"))
      (id
       (identifier? #'id)
       ;; XXX: We could return #'(lambda (file . rest) ...).  However,
       ;; (syntax-source #'id) is #f so (current-source-directory) would not
       ;; work.  Thus, simply forbid this form.
       #'(syntax-error
          "'local-file' is a macro and cannot be used like this")))))

(define (local-file-absolute-file-name file)
  "Return the absolute file name for FILE, a <local-file> instance.  A
'system-error' exception is raised if FILE could not be found."
  (force (%local-file-absolute-file-name file)))

(define-gexp-compiler (local-file-compiler (file <local-file>) system target)
  ;; "Compile" FILE by adding it to the store.
  (match file
    (($ <local-file> file (= force absolute) name recursive? select?)
     ;; Canonicalize FILE so that if it's a symlink, it is resolved.  Failing
     ;; to do that, when RECURSIVE? is #t, we could end up creating a dangling
     ;; symlink in the store, and when RECURSIVE? is #f 'add-to-store' would
     ;; just throw an error, both of which are inconvenient.
     (interned-file absolute name
                    #:recursive? recursive? #:select? select?))))

(define-record-type <plain-file>
  (%plain-file name content references)
  plain-file?
  (name        plain-file-name)                   ;string
  (content     plain-file-content)                ;string or bytevector
  (references  plain-file-references))            ;list (currently unused)

(define (plain-file name content)
  "Return an object representing a text file called NAME with the given
CONTENT (a string) to be added to the store.

This is the declarative counterpart of 'text-file'."
  ;; XXX: For now just ignore 'references' because it's not clear how to use
  ;; them in a declarative context.
  (%plain-file name content '()))

(define-gexp-compiler (plain-file-compiler (file <plain-file>) system target)
  ;; "Compile" FILE by adding it to the store.
  (match file
    (($ <plain-file> name (and (? string?) content) references)
     (text-file name content references))
    (($ <plain-file> name (and (? bytevector?) content) references)
     (binary-file name content references))))

(define-record-type <computed-file>
  (%computed-file name gexp guile options)
  computed-file?
  (name       computed-file-name)                 ;string
  (gexp       computed-file-gexp)                 ;gexp
  (guile      computed-file-guile)                ;<package>
  (options    computed-file-options))             ;list of arguments

(define* (computed-file name gexp
                        #:key guile (local-build? #t) (options '()))
  "Return an object representing the store item NAME, a file or directory
computed by GEXP.  When LOCAL-BUILD? is #t (the default), it ensures the
corresponding derivation is built locally.  OPTIONS may be used to pass
additional arguments to 'gexp->derivation'.

This is the declarative counterpart of 'gexp->derivation'."
  (let ((options* `(#:local-build? ,local-build? ,@options)))
    (%computed-file name gexp guile options*)))

(define-gexp-compiler (computed-file-compiler (file <computed-file>)
                                              system target)
  ;; Compile FILE by returning a derivation whose build expression is its
  ;; gexp.
  (match file
    (($ <computed-file> name gexp guile options)
     (mlet %store-monad ((guile (lower-object (or guile (default-guile))
                                              system #:target target)))
       (apply gexp->derivation name gexp #:guile-for-build guile
              #:system system #:target target options)))))

(define-record-type <program-file>
  (%program-file name gexp guile path)
  program-file?
  (name       program-file-name)                  ;string
  (gexp       program-file-gexp)                  ;gexp
  (guile      program-file-guile)                 ;package
  (path       program-file-module-path))          ;list of strings

(define* (program-file name gexp #:key (guile #f) (module-path %load-path))
  "Return an object representing the executable store item NAME that runs
GEXP.  GUILE is the Guile package used to execute that script.  Imported
modules of GEXP are looked up in MODULE-PATH.

This is the declarative counterpart of 'gexp->script'."
  (%program-file name gexp guile module-path))

(define-gexp-compiler (program-file-compiler (file <program-file>)
                                             system target)
  ;; Compile FILE by returning a derivation that builds the script.
  (match file
    (($ <program-file> name gexp guile module-path)
     (gexp->script name gexp
                   #:module-path module-path
                   #:guile (or guile (default-guile))
                   #:system system
                   #:target target))))

(define-record-type <scheme-file>
  (%scheme-file name gexp splice? load-path?)
  scheme-file?
  (name       scheme-file-name)                  ;string
  (gexp       scheme-file-gexp)                  ;gexp
  (splice?    scheme-file-splice?)               ;Boolean
  (load-path? scheme-file-set-load-path?))       ;Boolean

(define* (scheme-file name gexp #:key splice? (set-load-path? #t))
  "Return an object representing the Scheme file NAME that contains GEXP.

This is the declarative counterpart of 'gexp->file'."
  (%scheme-file name gexp splice? set-load-path?))

(define-gexp-compiler (scheme-file-compiler (file <scheme-file>)
                                            system target)
  ;; Compile FILE by returning a derivation that builds the file.
  (match file
    (($ <scheme-file> name gexp splice? set-load-path?)
     (gexp->file name gexp
                 #:set-load-path? set-load-path?
                 #:splice? splice?
                 #:system system
                 #:target target))))

;; Appending SUFFIX to BASE's output file name.
(define-record-type <file-append>
  (%file-append base suffix)
  file-append?
  (base   file-append-base)                    ;<package> | <derivation> | ...
  (suffix file-append-suffix))                 ;list of strings

(define (write-file-append file port)
  (match file
    (($ <file-append> base suffix)
     (format port "#<file-append ~s ~s>" base
             (string-join suffix)))))

(set-record-type-printer! <file-append> write-file-append)

(define (file-append base . suffix)
  "Return a <file-append> object that expands to the concatenation of BASE and
SUFFIX."
  (%file-append base suffix))

(define-gexp-compiler file-append-compiler <file-append>
  compiler => (lambda (obj system target)
                (match obj
                  (($ <file-append> base _)
                   (lower-object base system #:target target))))
  expander => (lambda (obj lowered output)
                (match obj
                  (($ <file-append> base suffix)
                   (let* ((expand (or (lookup-expander base)
                                      (lookup-expander lowered)))
                          (base   (expand base lowered output)))
                     (string-append base (string-concatenate suffix)))))))

;; Representation of SRFI-39 parameter settings in the dynamic scope of an
;; object lowering.
(define-record-type <parameterized>
  (parameterized bindings thunk)
  parameterized?
  (bindings parameterized-bindings)             ;list of parameter/value pairs
  (thunk    parameterized-thunk))               ;thunk

(define-syntax-rule (with-parameters ((param value) ...) body ...)
  "Bind each PARAM to the corresponding VALUE for the extent during which BODY
is lowered.  Consider this example:

  (with-parameters ((%current-system \"x86_64-linux\"))
    coreutils)

It returns a <parameterized> object that ensures %CURRENT-SYSTEM is set to
x86_64-linux when COREUTILS is lowered."
  (parameterized (list (list param (lambda () value)) ...)
                 (lambda ()
                   body ...)))

(define-gexp-compiler compile-parameterized <parameterized>
  compiler =>
  (lambda (parameterized system target)
    (match (parameterized-bindings parameterized)
      (((parameters values) ...)
       (let ((fluids (map parameter-fluid parameters))
             (thunk  (parameterized-thunk parameterized)))
         ;; Install the PARAMETERS for the dynamic extent of THUNK.
         (with-fluids* fluids
           (map (lambda (thunk) (thunk)) values)
           (lambda ()
             ;; Special-case '%current-system' and '%current-target-system' to
             ;; make sure we get the desired effect.
             (let ((system (if (memq %current-system parameters)
                               (%current-system)
                               system))
                   (target (if (memq %current-target-system parameters)
                               (%current-target-system)
                               target)))
               (lower-object (thunk) system #:target target))))))))

  expander => (lambda (parameterized lowered output)
                (match (parameterized-bindings parameterized)
                  (((parameters values) ...)
                   (let ((fluids (map parameter-fluid parameters))
                         (thunk  (parameterized-thunk parameterized)))
                     ;; Install the PARAMETERS for the dynamic extent of THUNK.
                     (with-fluids* fluids
                       (map (lambda (thunk) (thunk)) values)
                       (lambda ()
                         ;; Delegate to the expander of the wrapped object.
                         (let* ((base   (thunk))
                                (expand (lookup-expander base)))
                           (expand base lowered output)))))))))


;;;
;;; Inputs & outputs.
;;;

;; The input of a gexp.
(define-record-type <gexp-input>
  (%gexp-input thing output native?)
  gexp-input?
  (thing     gexp-input-thing)       ;<package> | <origin> | <derivation> | ...
  (output    gexp-input-output)      ;string
  (native?   gexp-input-native?))    ;Boolean

(define (write-gexp-input input port)
  (match input
    (($ <gexp-input> thing output #f)
     (format port "#<gexp-input ~s:~a>" thing output))
    (($ <gexp-input> thing output #t)
     (format port "#<gexp-input native ~s:~a>" thing output))))

(set-record-type-printer! <gexp-input> write-gexp-input)

(define* (gexp-input thing                        ;convenience procedure
                     #:optional (output "out")
                     #:key native?)
  "Return a new <gexp-input> for the OUTPUT of THING; NATIVE? determines
whether this should be considered a \"native\" input or not."
  (%gexp-input thing output native?))

;; Reference to one of the derivation's outputs, for gexps used in
;; derivations.
(define-record-type <gexp-output>
  (gexp-output name)
  gexp-output?
  (name gexp-output-name))

(define (write-gexp-output output port)
  (match output
    (($ <gexp-output> name)
     (format port "#<gexp-output ~a>" name))))

(set-record-type-printer! <gexp-output> write-gexp-output)

(define* (gexp-attribute gexp self-attribute #:optional (equal? equal?)
                         #:key (validate (const #t)))
  "Recurse on GEXP and the expressions it refers to, summing the items
returned by SELF-ATTRIBUTE, a procedure that takes a gexp.  Use EQUAL? as the
second argument to 'delete-duplicates'.  Pass VALIDATE every gexp and
attribute that is traversed."
  (if (gexp? gexp)
      (delete-duplicates
       (append (let ((attribute (self-attribute gexp)))
                 (validate gexp attribute)
                 attribute)
               (reverse
                (fold (lambda (input result)
                        (match input
                          (($ <gexp-input> (? gexp? exp))
                           (append (gexp-attribute exp self-attribute
                                                   #:validate validate)
                                   result))
                          (($ <gexp-input> (lst ...))
                           (fold/tree (lambda (obj result)
                                        (match obj
                                          ((? gexp? exp)
                                           (append (gexp-attribute exp self-attribute
                                                                   #:validate validate)
                                                   result))
                                          (_
                                           result)))
                                      result
                                      lst))
                          (_
                           result)))
                      '()
                      (gexp-references gexp))))
       equal?)
      '()))                                       ;plain Scheme data type

(define (gexp-modules gexp)
  "Return the list of Guile module names GEXP relies on.  If (gexp? GEXP) is
false, meaning that GEXP is a plain Scheme object, return the empty list."
  (define (module=? m1 m2)
    ;; Return #t when M1 equals M2.  Special-case '=>' specs because their
    ;; right-hand side may not be comparable with 'equal?': it's typically a
    ;; file-like object that embeds a gexp, which in turn embeds closure;
    ;; those closures may be 'eq?' when running compiled code but are unlikely
    ;; to be 'eq?' when running on 'eval'.  Ignore the right-hand side to
    ;; avoid this discrepancy.
    (match m1
      (((name1 ...) '=> _)
       (match m2
         (((name2 ...) '=> _) (equal? name1 name2))
         (_ #f)))
      (_
       (equal? m1 m2))))

  (define (validate-modules gexp modules)
    ;; Warn if MODULES, imported by GEXP, contains modules that in general
    ;; should not be imported from the host because they vary from user to
    ;; user and may thus be a source of non-reproducibility.  This includes
    ;; (guix config) as well as modules that come with Guile.
    (match (filter (match-lambda
                     ((or ('guix 'config) ('ice-9 . _)) #t)
                     (_ #f))
                   modules)
      (() #t)
      (suspects
       (warning (gexp-location gexp)
                (N_ "importing module~{ ~a~} from the host~%"
                    "importing modules~{ ~a~} from the host~%"
                    (length suspects))
                suspects))))

  (gexp-attribute gexp gexp-self-modules module=?
                  #:validate validate-modules))

(define (gexp-extensions gexp)
  "Return the list of Guile extensions (packages) GEXP relies on.  If (gexp?
GEXP) is false, meaning that GEXP is a plain Scheme object, return the empty
list."
  (gexp-attribute gexp gexp-self-extensions))

(define (self-quoting? x)
  (letrec-syntax ((one-of (syntax-rules ()
                            ((_) #f)
                            ((_ pred rest ...)
                             (or (pred x)
                                 (one-of rest ...))))))
    (one-of symbol? string? keyword? pair? null? array?
            number? boolean? char?)))

(define (lower-inputs inputs system target)
  "Turn any object from INPUTS into a derivation input for SYSTEM or a store
item (a \"source\"); return the corresponding input list as a monadic value.
When TARGET is true, use it as the cross-compilation target triplet."
  (define (store-item? obj)
    (and (string? obj) (store-path? obj)))

  (define filterm
    (lift1 (cut filter ->bool <>) %store-monad))

  (with-monad %store-monad
    (>>= (mapm/accumulate-builds
          (match-lambda
            (($ <gexp-input> (? store-item? item))
             (return item))
            (($ <gexp-input> thing output native?)
             (mlet %store-monad ((obj (lower-object thing system
                                                    #:target
                                                    (and (not native?)
                                                         target))))
               (return (match obj
                         ((? derivation? drv)
                          (derivation-input drv (list output)))
                         ((? store-item? item)
                          item)
                         ((? self-quoting?)
                          ;; Some inputs such as <system-binding> can lower to
                          ;; a self-quoting object that FILTERM will filter
                          ;; out.
                          #f))))))
          inputs)
         filterm)))

(define* (lower-reference-graphs graphs #:key system target)
  "Given GRAPHS, a list of (FILE-NAME INPUT ...) lists for use as a
#:reference-graphs argument, lower it such that each INPUT is replaced by the
corresponding <derivation-input> or store item."
  (define tuple->gexp-input
    (match-lambda
      ((thing)
       (%gexp-input thing "out" (not target)))
      ((thing output)
       (%gexp-input thing output (not target)))))

  (match graphs
    (((file-names . inputs) ...)
     (mlet %store-monad ((inputs (lower-inputs (map tuple->gexp-input inputs)
                                               system target)))
       (return (map cons file-names inputs))))))

(define* (lower-references lst #:key system target)
  "Based on LST, a list of output names and packages, return a list of output
names and file names suitable for the #:allowed-references argument to
'derivation'."
  (with-monad %store-monad
    (define lower
      (match-lambda
       ((? string? output)
        (return output))
       (($ <gexp-input> thing output native?)
        (mlet %store-monad ((drv (lower-object thing system
                                               #:target (if native?
                                                            #f target))))
          (return (derivation->output-path drv output))))
       (thing
        (mlet %store-monad ((drv (lower-object thing system
                                               #:target target)))
          (return (derivation->output-path drv))))))

    (mapm/accumulate-builds lower lst)))

(define default-guile-derivation
  ;; Here we break the abstraction by talking to the higher-level layer.
  ;; Thus, do the resolution lazily to hide the circular dependency.
  (let ((proc (delay
                (let ((iface (resolve-interface '(guix packages))))
                  (module-ref iface 'default-guile-derivation)))))
    (lambda (system)
      ((force proc) system))))

;; Representation of a gexp instantiated for a given target and system.
;; It's an intermediate representation between <gexp> and <derivation>.
(define-record-type <lowered-gexp>
  (lowered-gexp sexp inputs sources guile load-path load-compiled-path)
  lowered-gexp?
  (sexp                lowered-gexp-sexp)         ;sexp
  (inputs              lowered-gexp-inputs)       ;list of <derivation-input>
  (sources             lowered-gexp-sources)      ;list of store items
  (guile               lowered-gexp-guile)        ;<derivation-input> | #f
  (load-path           lowered-gexp-load-path)    ;list of store items
  (load-compiled-path  lowered-gexp-load-compiled-path)) ;list of store items

(define* (imported+compiled-modules modules system
                                    #:key (extensions '())
                                    deprecation-warnings guile
                                    (module-path %load-path))
  "Return a pair where the first element is the imported MODULES and the
second element is the derivation to compile them."
  (mcached equal?
           (mlet %store-monad ((modules  (if (pair? modules)
                                             (imported-modules modules
                                                               #:guile guile
                                                               #:system system
                                                               #:module-path module-path)
                                             (return #f)))
                               (compiled (if (pair? modules)
                                             (compiled-modules modules
                                                               #:system system
                                                               #:module-path module-path
                                                               #:extensions extensions
                                                               #:guile guile
                                                               #:deprecation-warnings
                                                               deprecation-warnings)
                                             (return #f))))
             (return (cons modules compiled)))
           modules
           system extensions guile deprecation-warnings module-path))

(define (sexp->string sexp)
  "Like 'object->string', but deterministic and slightly faster."
  ;; Explicitly use UTF-8 for determinism, and also because UTF-8 output is
  ;; faster.
  (with-fluids ((%default-port-encoding "UTF-8"))
    (call-with-output-string
     (lambda (port)
       (write sexp port)))))

(define* (lower-gexp exp
                     #:key
                     (module-path %load-path)
                     (system (%current-system))
                     (target 'current)
                     (graft? (%graft?))
                     (guile-for-build (%guile-for-build))
                     (effective-version "3.0")

                     deprecation-warnings)
  "*Note: This API is subject to change; use at your own risk!*

Lower EXP, a gexp, instantiating it for SYSTEM and TARGET.  Return a
<lowered-gexp> ready to be used.

Lowered gexps are an intermediate representation that's useful for
applications that deal with gexps outside in a way that is disconnected from
derivations--e.g., code evaluated for its side effects."
  (define %modules
    (delete-duplicates (gexp-modules exp)))

  (define (search-path modules extensions suffix)
    (append (match modules
              ((? derivation? drv)
               (list (derivation->output-path drv)))
              (#f
               '())
              ((? store-path? item)
               (list item)))
            (map (lambda (extension)
                   (string-append (match extension
                                    ((? derivation? drv)
                                     (derivation->output-path drv))
                                    ((? store-path? item)
                                     item))
                                  suffix))
                 extensions)))

  (mlet* %store-monad ( ;; The following binding forces '%current-system' and
                       ;; '%current-target-system' to be looked up at >>=
                       ;; time.
                       (graft?    (set-grafting graft?))

                       (system -> (or system (%current-system)))
                       (target -> (if (eq? target 'current)
                                      (%current-target-system)
                                      target))
                       (guile     (if guile-for-build
                                      (return guile-for-build)
                                      (default-guile-derivation system)))
                       (inputs   (lower-inputs (gexp-inputs exp)
                                               system target))
                       (sexp     (gexp->sexp exp system target))
                       (extensions -> (gexp-extensions exp))
                       (exts     (mapm %store-monad
                                       (lambda (obj)
                                         (lower-object obj system
                                                       #:target #f))
                                       extensions))
                       (modules+compiled (imported+compiled-modules
                                          %modules system
                                          #:extensions extensions
                                          #:deprecation-warnings
                                          deprecation-warnings
                                          #:guile guile
                                          #:module-path module-path))
                       (modules ->  (car modules+compiled))
                       (compiled -> (cdr modules+compiled)))
    (define load-path
      (search-path modules exts
                   (string-append "/share/guile/site/" effective-version)))

    (define load-compiled-path
      (search-path compiled exts
                   (string-append "/lib/guile/" effective-version
                                  "/site-ccache")))

    (mbegin %store-monad
      (set-grafting graft?)                       ;restore the initial setting
      (return (lowered-gexp sexp
                            `(,@(if (derivation? modules)
                                    (list (derivation-input modules))
                                    '())
                              ,@(if compiled
                                    (list (derivation-input compiled))
                                    '())
                              ,@(map derivation-input exts)
                              ,@(filter derivation-input? inputs))
                            (filter string? (cons modules inputs))
                            (derivation-input guile '("out"))
                            load-path
                            load-compiled-path)))))

(define* (gexp->derivation name exp
                           #:key
                           system (target 'current)
                           hash hash-algo recursive?
                           (env-vars '())
                           (modules '())
                           (module-path %load-path)
                           (guile-for-build (%guile-for-build))
                           (effective-version "3.0")
                           (graft? (%graft?))
                           references-graphs
                           allowed-references disallowed-references
                           leaked-env-vars
                           local-build? (substitutable? #t)
                           (properties '())
                           deprecation-warnings
                           (script-name (string-append name "-builder")))
  "Return a derivation NAME that runs EXP (a gexp) with GUILE-FOR-BUILD (a
derivation) on SYSTEM; EXP is stored in a file called SCRIPT-NAME.  When
TARGET is true, it is used as the cross-compilation target triplet for
packages referred to by EXP.

MODULES is deprecated in favor of 'with-imported-modules'.  Its meaning is to
make MODULES available in the evaluation context of EXP; MODULES is a list of
names of Guile modules searched in MODULE-PATH to be copied in the store,
compiled, and made available in the load path during the execution of
EXP---e.g., '((guix build utils) (guix build gnu-build-system)).

EFFECTIVE-VERSION determines the string to use when adding extensions of
EXP (see 'with-extensions') to the search path---e.g., \"2.2\".

GRAFT? determines whether packages referred to by EXP should be grafted when
applicable.

When REFERENCES-GRAPHS is true, it must be a list of tuples of one of the
following forms:

  (FILE-NAME PACKAGE)
  (FILE-NAME PACKAGE OUTPUT)
  (FILE-NAME DERIVATION)
  (FILE-NAME DERIVATION OUTPUT)
  (FILE-NAME STORE-ITEM)

The right-hand-side of each element of REFERENCES-GRAPHS is automatically made
an input of the build process of EXP.  In the build environment, each
FILE-NAME contains the reference graph of the corresponding item, in a simple
text format.

ALLOWED-REFERENCES must be either #f or a list of output names and packages.
In the latter case, the list denotes store items that the result is allowed to
refer to.  Any reference to another store item will lead to a build error.
Similarly for DISALLOWED-REFERENCES, which can list items that must not be
referenced by the outputs.

DEPRECATION-WARNINGS determines whether to show deprecation warnings while
compiling modules.  It can be #f, #t, or 'detailed.

The other arguments are as for 'derivation'."
  (define outputs (gexp-outputs exp))
  (define requested-graft? graft?)

  (define (graphs-file-names graphs)
    ;; Return a list of (FILE-NAME . STORE-PATH) pairs made from GRAPHS.
    (map (match-lambda
           ((file-name . (? derivation-input? input))
            (cons file-name (first (derivation-input-output-paths input))))
           ((file-name . (? string? item))
            (cons file-name item)))
         graphs))

  (define (add-modules exp modules)
    (if (null? modules)
        exp
        (make-gexp (gexp-references exp)
                   (append modules (gexp-self-modules exp))
                   (gexp-self-extensions exp)
                   (gexp-proc exp)
                   (gexp-location exp))))

  (mlet* %store-monad ( ;; The following binding forces '%current-system' and
                       ;; '%current-target-system' to be looked up at >>=
                       ;; time.
                       (graft?    (set-grafting graft?))

                       (system -> (or system (%current-system)))
                       (target -> (if (eq? target 'current)
                                      (%current-target-system)
                                      target))
                       (exp ->    (add-modules exp modules))
                       (lowered   (lower-gexp exp
                                              #:module-path module-path
                                              #:system system
                                              #:target target
                                              #:graft? requested-graft?
                                              #:guile-for-build
                                              guile-for-build
                                              #:effective-version
                                              effective-version
                                              #:deprecation-warnings
                                              deprecation-warnings))

                       (graphs   (if references-graphs
                                     (lower-reference-graphs references-graphs
                                                             #:system system
                                                             #:target target)
                                     (return #f)))
                       (allowed  (if allowed-references
                                     (lower-references allowed-references
                                                       #:system system
                                                       #:target target)
                                     (return #f)))
                       (disallowed (if disallowed-references
                                       (lower-references disallowed-references
                                                         #:system system
                                                         #:target target)
                                       (return #f)))
                       (guile -> (lowered-gexp-guile lowered))
                       (builder  (text-file script-name
                                            (sexp->string
                                             (lowered-gexp-sexp lowered)))))
    (mbegin %store-monad
      (set-grafting graft?)                       ;restore the initial setting
      (raw-derivation name
                      (string-append (derivation-input-output-path guile)
                                     "/bin/guile")
                      `("--no-auto-compile"
                        ,@(append-map (lambda (directory)
                                        `("-L" ,directory))
                                      (lowered-gexp-load-path lowered))
                        ,@(append-map (lambda (directory)
                                        `("-C" ,directory))
                                      (lowered-gexp-load-compiled-path lowered))
                        ,builder)
                      #:outputs outputs
                      #:env-vars env-vars
                      #:system system
                      #:inputs `(,guile
                                 ,@(lowered-gexp-inputs lowered)
                                 ,@(match graphs
                                     (((_ . inputs) ...)
                                      (filter derivation-input? inputs))
                                     (#f '())))
                      #:sources `(,builder
                                  ,@(if (and (string? modules)
                                             (store-path? modules))
                                        (list modules)
                                        '())
                                  ,@(lowered-gexp-sources lowered)
                                  ,@(match graphs
                                      (((_ . inputs) ...)
                                       (filter string? inputs))
                                      (#f '())))

                      #:hash hash #:hash-algo hash-algo #:recursive? recursive?
                      #:references-graphs (and=> graphs graphs-file-names)
                      #:allowed-references allowed
                      #:disallowed-references disallowed
                      #:leaked-env-vars leaked-env-vars
                      #:local-build? local-build?
                      #:substitutable? substitutable?
                      #:properties properties))))

(define (fold/tree proc seed lst)
  "Like 'fold', but recurse into sub-lists of LST and accept improper lists."
  (let loop ((obj lst)
             (result seed))
    (match obj
      ((head . tail)
       (loop tail (loop head result)))
      (_
       (proc obj result)))))

(define (gexp-inputs exp)
  "Return the list of <gexp-input> for EXP."
  (define set-gexp-input-native?
    (match-lambda
      (($ <gexp-input> thing output)
       (%gexp-input thing output #t))))

  (define (interesting? obj)
    (or (file-like? obj)
        (and (string? obj) (direct-store-path? obj))))

  (define (add-reference-inputs ref result)
    (match ref
      (($ <gexp-input> (? gexp? exp) _ #t)
       (append (map set-gexp-input-native? (gexp-inputs exp))
               result))
      (($ <gexp-input> (? gexp? exp) _ #f)
       (append (gexp-inputs exp) result))
      (($ <gexp-input> (? string? str))
       (if (direct-store-path? str)
           (cons ref result)
           result))
      (($ <gexp-input> (? struct? thing) output n?)
       (if (lookup-compiler thing)
           ;; THING is a derivation, or a package, or an origin, etc.
           (cons ref result)
           result))
      (($ <gexp-input> (? pair? lst) output n?)
       ;; XXX: Scan LST for inputs.  Inherit N?.
       (fold/tree (lambda (obj result)
                    (match obj
                      ((? gexp-input? x)
                       (cons (%gexp-input (gexp-input-thing x)
                                          (gexp-input-output x)
                                          n?)
                             result))
                      ((? interesting? x)
                       (cons (%gexp-input x "out" n?) result))
                      ((? gexp? x)
                       (append (gexp-inputs x) result))
                      (_
                       result)))
                  result
                  lst))
      (_
       ;; Ignore references to other kinds of objects.
       result)))

  (fold-right add-reference-inputs
              '()
              (gexp-references exp)))

(define (gexp-outputs exp)
  "Return the outputs referred to by EXP as a list of strings."
  (define (add-reference-output ref result)
    (match ref
      (($ <gexp-output> name)
       (cons name result))
      (($ <gexp-input> (? gexp? exp))
       (append (gexp-outputs exp) result))
      (($ <gexp-input> (? pair? lst))
       ;; XXX: Scan LST for outputs.
       (fold/tree (lambda (obj result)
                    (match obj
                      (($ <gexp-output> name) (cons name result))
                      ((? gexp? x) (append (gexp-outputs x) result))
                      (_ result)))
                  result
                  lst))
      (_
       result)))

  (delete-duplicates
   (fold add-reference-output '() (gexp-references exp))))

(define (gexp->sexp exp system target)
  "Return (monadically) the sexp corresponding to EXP for the given OUTPUT,
and in the current monad setting (system type, etc.)"
  (define* (reference->sexp ref #:optional native?)
    (with-monad %store-monad
      (match ref
        (($ <gexp-output> output)
         ;; Output file names are not known in advance but the daemon defines
         ;; an environment variable for each of them at build time, so use
         ;; that trick.
         (return `((@ (guile) getenv) ,output)))
        (($ <gexp-input> (? gexp? exp) output n?)
         (gexp->sexp exp
                     system (if (or n? native?) #f target)))
        (($ <gexp-input> (refs ...) output n?)
         (mapm %store-monad
               (lambda (ref)
                 ;; XXX: Automatically convert REF to an gexp-input.
                 (if (or (symbol? ref) (number? ref)
                         (boolean? ref) (null? ref) (array? ref))
                     (return ref)
                     (reference->sexp
                      (if (gexp-input? ref)
                          ref
                          (%gexp-input ref "out" n?))
                      (or n? native?))))
               refs))
        (($ <gexp-input> (? struct? thing) output n?)
         (let ((target (if (or n? native?) #f target)))
           (lower+expand-object thing system
                                #:target target
                                #:output output)))
        (($ <gexp-input> (? self-quoting? x))
         (return x))
        (($ <gexp-input> x)
         (raise (condition (&gexp-input-error (input x)))))
        (x
         (return x)))))

  (mlet %store-monad
      ((args (mapm %store-monad
                   reference->sexp (gexp-references exp))))
    (return (apply (gexp-proc exp) args))))

(define-syntax-parameter current-imported-modules
  ;; Current list of imported modules.
  (identifier-syntax '()))

(define-syntax-rule (with-imported-modules modules body ...)
  "Mark the gexps defined in BODY... as requiring MODULES in their execution
environment."
  (syntax-parameterize ((current-imported-modules
                         (identifier-syntax modules)))
    body ...))

(define-syntax-parameter current-imported-extensions
  ;; Current list of extensions.
  (identifier-syntax '()))

(define-syntax-rule (with-extensions extensions body ...)
  "Mark the gexps defined in BODY... as requiring EXTENSIONS in their
execution environment."
  (syntax-parameterize ((current-imported-extensions
                         (identifier-syntax extensions)))
    body ...))

(define-syntax gexp
  (lambda (s)
    (define (collect-escapes exp)
      ;; Return all the 'ungexp' present in EXP.
      (let loop ((exp    exp)
                 (result '()))
        (syntax-case exp (ungexp
                          ungexp-splicing
                          ungexp-native
                          ungexp-native-splicing)
          ((ungexp _)
           (cons exp result))
          ((ungexp _ _)
           (cons exp result))
          ((ungexp-splicing _ ...)
           (cons exp result))
          ((ungexp-native _ ...)
           (cons exp result))
          ((ungexp-native-splicing _ ...)
           (cons exp result))
          ((exp0 . exp)
           (let ((result (loop #'exp0 result)))
             (loop  #'exp result)))
          (_
           result))))

    (define (escape->ref exp)
      ;; Turn 'ungexp' form EXP into a "reference".
      (syntax-case exp (ungexp ungexp-splicing
                        ungexp-native ungexp-native-splicing
                        output)
        ((ungexp output)
         #'(gexp-output "out"))
        ((ungexp output name)
         #'(gexp-output name))
        ((ungexp thing)
         #'(%gexp-input thing "out" #f))
        ((ungexp drv-or-pkg out)
         #'(%gexp-input drv-or-pkg out #f))
        ((ungexp-splicing lst)
         #'(%gexp-input lst "out" #f))
        ((ungexp-native thing)
         #'(%gexp-input thing "out" #t))
        ((ungexp-native drv-or-pkg out)
         #'(%gexp-input drv-or-pkg out #t))
        ((ungexp-native-splicing lst)
         #'(%gexp-input lst "out" #t))))

    (define (substitute-ungexp exp substs)
      ;; Given EXP, an 'ungexp' or 'ungexp-native' form, substitute it with
      ;; the corresponding form in SUBSTS.
      (match (assoc exp substs)
        ((_ id)
         id)
        (_                                        ;internal error
         (with-syntax ((exp exp))
           #'(syntax-error "error: no 'ungexp' substitution" exp)))))

    (define (substitute-ungexp-splicing exp substs)
      (syntax-case exp ()
        ((exp rest ...)
         (match (assoc #'exp substs)
           ((_ id)
            (with-syntax ((id id))
              #`(append id
                        #,(substitute-references #'(rest ...) substs))))
           (_
            #'(syntax-error "error: no 'ungexp-splicing' substitution"
                            exp))))))

    (define (substitute-references exp substs)
      ;; Return a variant of EXP where all the cars of SUBSTS have been
      ;; replaced by the corresponding cdr.
      (syntax-case exp (ungexp ungexp-native
                        ungexp-splicing ungexp-native-splicing)
        ((ungexp _ ...)
         (substitute-ungexp exp substs))
        ((ungexp-native _ ...)
         (substitute-ungexp exp substs))
        (((ungexp-splicing _ ...) rest ...)
         (substitute-ungexp-splicing exp substs))
        (((ungexp-native-splicing _ ...) rest ...)
         (substitute-ungexp-splicing exp substs))
        ((exp0 . exp)
         #`(cons #,(substitute-references #'exp0 substs)
                 #,(substitute-references #'exp substs)))
        (x #''x)))

    (syntax-case s (ungexp output)
      ((_ exp)
       (let* ((escapes (delete-duplicates (collect-escapes #'exp)))
              (formals (generate-temporaries escapes))
              (sexp    (substitute-references #'exp (zip escapes formals)))
              (refs    (map escape->ref escapes)))
         #`(make-gexp (list #,@refs)
                      current-imported-modules
                      current-imported-extensions
                      (lambda #,formals
                        #,sexp)
                      (current-source-location)))))))


;;;
;;; Module handling.
;;;

(define %utils-module
  ;; This file provides 'mkdir-p', needed to implement 'imported-files' and
  ;; other primitives below.  Note: We give the file name relative to this
  ;; file you are currently reading; 'search-path' could return a file name
  ;; relative to the current working directory.
  (local-file "build/utils.scm"
              "build-utils.scm"))

(define* (imported-files/derivation files
                                    #:key (name "file-import")
                                    (symlink? #f)
                                    (system (%current-system))
                                    (guile (%guile-for-build)))
  "Return a derivation that imports FILES into STORE.  FILES must be a list
of (FINAL-PATH . FILE) pairs.  Each FILE is mapped to FINAL-PATH in the
resulting store path.  FILE can be either a file name, or a file-like object,
as returned by 'local-file' for example.  If SYMLINK? is true, create symlinks
to the source files instead of copying them."
  (define file-pair
    (match-lambda
     ((final-path . (? string? file-name))
      (mlet %store-monad ((file (interned-file file-name
                                               (basename final-path))))
        (return (list final-path file))))
     ((final-path . file-like)
      (mlet %store-monad ((file (lower-object file-like system)))
        (return (list final-path file))))))

  (mlet %store-monad ((files (mapm %store-monad file-pair files)))
    (define build
      (gexp
       (begin
         (primitive-load (ungexp %utils-module))  ;for 'mkdir-p'
         (use-modules (ice-9 match))

         (mkdir (ungexp output)) (chdir (ungexp output))
         (for-each (match-lambda
                    ((final-path store-path)
                     (mkdir-p (dirname final-path))
                     ((ungexp (if symlink? 'symlink 'copy-file))
                      store-path final-path)))
                   '(ungexp files)))))

    ;; TODO: Pass FILES as an environment variable so that BUILD remains
    ;; exactly the same regardless of FILES: less disk space, and fewer
    ;; 'add-to-store' RPCs.
    (gexp->derivation name build
                      #:system system
                      #:guile-for-build guile
                      #:local-build? #t
                      #:substitutable? #f

                      ;; Avoid deprecation warnings about the use of the _IO*
                      ;; constants in (guix build utils).
                      #:env-vars
                      '(("GUILE_WARN_DEPRECATED" . "no")))))

(define* (imported-files files
                         #:key (name "file-import")
                         ;; The following parameters make sense when creating
                         ;; an actual derivation.
                         (system (%current-system))
                         (guile (%guile-for-build)))
  "Import FILES into the store and return the resulting derivation or store
file name (a derivation is created if and only if some elements of FILES are
file-like objects and not local file names.)  FILES must be a list
of (FINAL-PATH . FILE) pairs.  Each FILE is mapped to FINAL-PATH in the
resulting store path.  FILE can be either a file name, or a file-like object,
as returned by 'local-file' for example."
  (if (any (match-lambda
             ((_ . (? struct? source)) #t)
             (_ #f))
           files)
      (imported-files/derivation files #:name name
                                 #:symlink? derivation?
                                 #:system system #:guile guile)
      (interned-file-tree `(,name directory
                                  ,@(file-mapping->tree files)))))

(define* (imported-modules modules
                           #:key (name "module-import")
                           (system (%current-system))
                           (guile (%guile-for-build))
                           (module-path %load-path))
  "Return a derivation that contains the source files of MODULES, a list of
module names such as `(ice-9 q)'.  All of MODULES must be either names of
modules to be found in the MODULE-PATH search path, or a module name followed
by an arrow followed by a file-like object.  For example:

  (imported-modules `((guix build utils)
                      (guix gcrypt)
                      ((guix config) => ,(scheme-file …))))

In this example, the first two modules are taken from MODULE-PATH, and the
last one is created from the given <scheme-file> object."
  (let ((files (map (match-lambda
                      (((module ...) '=> file)
                       (cons (module->source-file-name module)
                             file))
                      ((module ...)
                       (let ((f (module->source-file-name module)))
                         (cons f (search-path* module-path f)))))
                    modules)))
    (imported-files files #:name name
                    #:system system
                    #:guile guile)))

(define* (compiled-modules modules
                           #:key (name "module-import-compiled")
                           (system (%current-system))
                           target
                           (guile (%guile-for-build))
                           (module-path %load-path)
                           (extensions '())
                           (deprecation-warnings #f)
                           (optimization-level 1))
  "Return a derivation that builds a tree containing the `.go' files
corresponding to MODULES.  All the MODULES are built in a context where
they can refer to each other.  When TARGET is true, cross-compile MODULES for
TARGET, a GNU triplet."
  (define total (length modules))

  (mlet %store-monad ((modules (imported-modules modules
                                                 #:system system
                                                 #:guile guile
                                                 #:module-path
                                                 module-path))
                      (extensions (mapm %store-monad
                                        (lambda (extension)
                                          (lower-object extension system
                                                        #:target #f))
                                        extensions)))
    (define build
      (gexp-with-hidden-inputs
       (gexp
        (begin
          (primitive-load (ungexp %utils-module)) ;for 'mkdir-p'

          (use-modules (ice-9 ftw)
                       (ice-9 format)
                       (srfi srfi-1)
                       (srfi srfi-26)
                       (system base target)
                       (system base compile))

          (define modules
            (getenv "modules"))

          (define total
            (string->number (getenv "module count")))

          (define extensions
            (string-split (getenv "extensions") #\space))

          (define target
            (getenv "target"))

          (define optimization-level
            (string->number (getenv "optimization level")))

          (define optimizations-for-level
            (or (and=> (false-if-exception
                        (resolve-interface '(system base optimize)))
                       (lambda (iface)
                         (module-ref iface 'optimizations-for-level))) ;Guile 3.0
                (const '())))

          (define (regular? file)
            (not (member file '("." ".."))))

          (define (process-entry entry output processed)
            (if (file-is-directory? entry)
                (let ((output (string-append output "/" (basename entry))))
                  (mkdir-p output)
                  (process-directory entry output processed))
                (let* ((base   (basename entry ".scm"))
                       (output (string-append output "/" base ".go")))
                  (format #t "[~2@a/~2@a] Compiling '~a'...~%"
                          (+ 1 processed total)
                          (* total 2)
                          entry)

                  (with-target (or target %host-type)
                               (lambda ()
                                 (compile-file entry
                                               #:output-file output
                                               #:opts
                                               `(,@%auto-compilation-options
                                                 ,@(optimizations-for-level
                                                    optimization-level)))))

                  (+ 1 processed))))

          (define (process-directory directory output processed)
            (let ((entries (map (cut string-append directory "/" <>)
                                (scandir directory regular?))))
              (fold (cut process-entry <> output <>)
                    processed
                    entries)))

          (define* (load-from-directory directory
                                        #:optional (loaded 0))
            "Load all the source files found in DIRECTORY."
            ;; XXX: This works around <https://bugs.gnu.org/15602>.
            (let ((entries (map (cut string-append directory "/" <>)
                                (scandir directory regular?))))
              (fold (lambda (file loaded)
                      (if (file-is-directory? file)
                          (load-from-directory file loaded)
                          (begin
                            (format #t "[~2@a/~2@a] Loading '~a'...~%"
                                    (+ 1 loaded) (* 2 total)
                                    file)
                            (save-module-excursion
                             (lambda ()
                               (primitive-load file)))
                            (+ 1 loaded))))
                    loaded
                    entries)))

          (setvbuf (current-output-port)
                   (cond-expand (guile-2.2 'line) (else _IOLBF)))

          (define mkdir-p
            ;; Capture 'mkdir-p'.
            (@ (guix build utils) mkdir-p))

          ;; Remove environment variables for internal consumption.
          (unsetenv "modules")
          (unsetenv "module count")
          (unsetenv "extensions")
          (unsetenv "target")
          (unsetenv "optimization level")

          ;; Add EXTENSIONS to the search path.
          (set! %load-path
            (append (map (lambda (extension)
                           (string-append extension
                                          "/share/guile/site/"
                                          (effective-version)))
                         extensions)
                    %load-path))
          (set! %load-compiled-path
            (append (map (lambda (extension)
                           (string-append extension "/lib/guile/"
                                          (effective-version)
                                          "/site-ccache"))
                         extensions)
                    %load-compiled-path))

          (set! %load-path (cons modules %load-path))

          ;; Above we loaded our own (guix build utils) but now we may need to
          ;; load a compile a different one.  Thus, force a reload.
          (let ((utils (string-append modules
                                      "/guix/build/utils.scm")))
            (when (file-exists? utils)
              (load utils)))

          (mkdir (ungexp output))
          (chdir modules)

          (load-from-directory ".")
          (process-directory "." (ungexp output) 0)))
       (append (map gexp-input extensions)
               (list (gexp-input modules)))))

    (gexp->derivation name build
                      #:script-name "compile-modules"
                      #:system system
                      #:target target
                      #:guile-for-build guile
                      #:local-build? #t
                      #:env-vars
                      `(("modules"
                         . ,(if (derivation? modules)
                                (derivation->output-path modules)
                                modules))
                        ("module count" . ,(number->string total))
                        ("extensions"
                         . ,(string-join
                             (map (match-lambda
                                    ((? derivation? drv)
                                     (derivation->output-path drv))
                                    ((? string? str) str))
                                  extensions)))
                        ("optimization level"
                         . ,(number->string optimization-level))
                        ,@(if target
                              `(("target" . ,target))
                              '())
                        ,@(case deprecation-warnings
                            ((#f)
                             '(("GUILE_WARN_DEPRECATED" . "no")))
                            ((detailed)
                             '(("GUILE_WARN_DEPRECATED" . "detailed")))
                            (else
                             '()))))))


;;;
;;; Convenience procedures.
;;;

(define (default-guile)
  ;; Lazily resolve 'guile-3.0' (not 'guile-final' because this is for
  ;; programs returned by 'program-file' and we don't want to keep references
  ;; to several Guile packages).  This module must not refer to (gnu …)
  ;; modules directly, to avoid circular dependencies, hence this hack.
  (module-ref (resolve-interface '(gnu packages guile))
              'guile-3.0))

(define* (load-path-expression modules #:optional (path %load-path)
                               #:key (extensions '()) system target
                               (guile (default-guile)))
  "Return as a monadic value a gexp that sets '%load-path' and
'%load-compiled-path' to point to MODULES, a list of module names.  MODULES
are searched for in PATH.  Return #f when MODULES and EXTENSIONS are empty.
Assume MODULES are compiled with GUILE."
  (if (and (null? modules) (null? extensions))
      (with-monad %store-monad
        (return #f))
      (mlet* %store-monad ((guile    (lower-object guile system #:target #f))
                           (compiled (compiled-modules modules
                                                       #:guile guile
                                                       #:extensions extensions
                                                       #:module-path path
                                                       #:system system
                                                       #:target target))
                           (modules  (imported-modules modules
                                                       #:guile guile
                                                       #:module-path path
                                                       #:system system)))
        (return
         (gexp (eval-when (expand load eval)
                 ;; Augment the load paths and delete duplicates.  Do that
                 ;; without loading (srfi srfi-1) or anything.
                 (let ((extensions '((ungexp-splicing extensions)))
                       (prepend (lambda (items lst)
                                  ;; This is O(N²) but N is typically small.
                                  (let loop ((items items)
                                             (lst lst))
                                    (if (null? items)
                                        lst
                                        (loop (cdr items)
                                              (cons (car items)
                                                    (delete (car items) lst))))))))
                   (set! %load-path
                     (prepend (cons (ungexp modules)
                                    (map (lambda (extension)
                                           (string-append extension
                                                          "/share/guile/site/"
                                                          (effective-version)))
                                         extensions))
                              %load-path))
                   (set! %load-compiled-path
                     (prepend (cons (ungexp compiled)
                                    (map (lambda (extension)
                                           (string-append extension
                                                          "/lib/guile/"
                                                          (effective-version)
                                                          "/site-ccache"))
                                         extensions))
                              %load-compiled-path)))))))))

(define* (input-tuples->gexp inputs #:key native?)
  "Given INPUTS, a list of label/gexp-input tuples, return a gexp that expands
to an input alist."
  (define references
    (map (match-lambda
           ((label input) input))
         inputs))

  (define labels
    (match inputs
      (((labels . _) ...)
       labels)))

  (define (proc . args)
    (cons 'quote (list (map cons labels args))))

  ;; This gexp is more efficient than an equivalent hand-written gexp: fewer
  ;; allocations, no need to scan long list-valued <gexp-input> records in
  ;; search of file-like objects, etc.
  (make-gexp references '() '() proc
             (source-properties inputs)))

(define (outputs->gexp outputs)
  "Given OUTPUTS, a list of output names, return a gexp that expands to an
output alist."
  (define references
    (map gexp-output outputs))

  (define (proc . args)
    `(list ,@(map (lambda (name)
                    `(cons ,name ((@ (guile) getenv) ,name)))
                  outputs)))

  ;; This gexp is more efficient than an equivalent hand-written gexp.
  (make-gexp references '() '() proc
             (source-properties outputs)))

(define (with-build-variables inputs outputs body)
  "Return a gexp that surrounds BODY with a definition of the legacy
'%build-inputs', '%outputs', and '%output' variables based on INPUTS, a list
of name/gexp-input tuples, and OUTPUTS, a list of strings."

  ;; These two variables are defined for backward compatibility.  They are
  ;; used by package expressions.  These must be top-level defines so that
  ;; 'use-modules' form in BODY that are required for macro expansion work as
  ;; expected.
  (gexp (begin
          (define %build-inputs
            (ungexp (input-tuples->gexp inputs)))
          (define %outputs
            (ungexp (outputs->gexp outputs)))
          (define %output
            (assoc-ref %outputs "out"))

          (ungexp body))))

(define (sexp->gexp sexp)
  "Turn SEXP into a gexp without any references.

Using this is a way for the caller to tell that SEXP doesn't need to be
scanned for file-like objects, thereby reducing processing costs.  This is
particularly useful if SEXP is a long list or a deep tree."
  (make-gexp '() '() '()
             (lambda () sexp)
             (source-properties sexp)))

(define* (gexp->script name exp
                       #:key (guile (default-guile))
                       (module-path %load-path)
                       (system (%current-system))
                       (target 'current))
  "Return an executable script NAME that runs EXP using GUILE, with EXP's
imported modules in its search path.  Look up EXP's modules in MODULE-PATH."
  (mlet* %store-monad ((target (if (eq? target 'current)
                                   (current-target-system)
                                   (return target)))
                       (set-load-path
                        (load-path-expression (gexp-modules exp)
                                              module-path
                                              #:guile guile
                                              #:extensions
                                              (gexp-extensions exp)
                                              #:system system
                                              #:target target))
                       (guile-for-build
                        (lower-object guile system #:target #f)))
    (gexp->derivation name
                      (gexp
                       (call-with-output-file (ungexp output)
                         (lambda (port)
                           ;; Note: that makes a long shebang.  When the store
                           ;; is /gnu/store, that fits within the 128-byte
                           ;; limit imposed by Linux, but that may go beyond
                           ;; when running tests.
                           (format port
                                   "#!~a/bin/guile --no-auto-compile~%!#~%"
                                   (ungexp guile))

                           (ungexp-splicing
                            (if set-load-path
                                (gexp ((write '(ungexp set-load-path) port)))
                                (gexp ())))

                           (write '(ungexp exp) port)
                           (chmod port #o555))))
                      #:system system
                      #:target target
                      #:module-path module-path
                      #:guile-for-build guile-for-build

                      ;; These derivations are not worth offloading or
                      ;; substituting.
                      #:local-build? #t
                      #:substitutable? #f)))

(define* (gexp->file name exp #:key
                     (set-load-path? #t)
                     (module-path %load-path)
                     (splice? #f)
                     (system (%current-system))
                     (target 'current))
  "Return a derivation that builds a file NAME containing EXP.  When SPLICE?
is true, EXP is considered to be a list of expressions that will be spliced in
the resulting file.

When SET-LOAD-PATH? is true, emit code in the resulting file to set
'%load-path' and '%load-compiled-path' to honor EXP's imported modules.
Lookup EXP's modules in MODULE-PATH."
  (define modules (gexp-modules exp))
  (define extensions (gexp-extensions exp))

  (mlet* %store-monad
      ((target (if (eq? target 'current)
                   (current-target-system)
                   (return target)))
       (no-load-path? -> (or (not set-load-path?)
                             (and (null? modules)
                                  (null? extensions))))
       (set-load-path
        (load-path-expression modules module-path
                              #:extensions extensions
                              #:system system
                              #:target target)))
    (if no-load-path?
        (gexp->derivation name
                          (gexp
                           (call-with-output-file (ungexp output)
                             (lambda (port)
                               (for-each
                                (lambda (exp)
                                  (write exp port))
                                '(ungexp (if splice?
                                             exp
                                             (gexp ((ungexp exp)))))))))
                          #:local-build? #t
                          #:substitutable? #f
                          #:system system
                          #:target target)
        (gexp->derivation name
                          (gexp
                           (call-with-output-file (ungexp output)
                             (lambda (port)
                               (write '(ungexp set-load-path) port)
                               (for-each
                                (lambda (exp)
                                  (write exp port))
                                '(ungexp (if splice?
                                             exp
                                             (gexp ((ungexp exp)))))))))
                          #:module-path module-path
                          #:local-build? #t
                          #:substitutable? #f
                          #:system system
                          #:target target))))

(define* (text-file* name #:rest text)
  "Return as a monadic value a derivation that builds a text file containing
all of TEXT.  TEXT may list, in addition to strings, objects of any type that
can be used in a gexp: packages, derivations, local file objects, etc.  The
resulting store file holds references to all these."
  (define builder
    (gexp (call-with-output-file (ungexp output "out")
            (lambda (port)
              (display (string-append (ungexp-splicing text)) port)))))

  (gexp->derivation name builder
                    #:local-build? #t
                    #:substitutable? #f))

(define* (mixed-text-file name #:key guile #:rest text)
  "Return an object representing store file NAME containing TEXT.  TEXT is a
sequence of strings and file-like objects, as in:

  (mixed-text-file \"profile\"
                   \"export PATH=\" coreutils \"/bin:\" grep \"/bin\")

This is the declarative counterpart of 'text-file*'."
  (define build
    (let ((text (if guile (drop text 2) text)))
      (gexp (call-with-output-file (ungexp output "out")
              (lambda (port)
                (set-port-encoding! port "UTF-8")
                (display (string-append (ungexp-splicing text)) port))))))

  (computed-file name build #:guile guile))

(define* (file-union name files #:key guile)
  "Return a <computed-file> that builds a directory containing all of FILES.
Each item in FILES must be a two-element list where the first element is the
file name to use in the new directory, and the second element is a gexp
denoting the target file.  Here's an example:

  (file-union \"etc\"
              `((\"hosts\" ,(plain-file \"hosts\"
                                        \"127.0.0.1 localhost\"))
                (\"bashrc\" ,(plain-file \"bashrc\"
                                         \"alias ls='ls --color'\"))
                (\"libvirt/qemu.conf\" ,(plain-file \"qemu.conf\" \"\"))))

This yields an 'etc' directory containing these two files."
  (computed-file name
                 (with-imported-modules '((guix build utils))
                   (gexp
                    (begin
                      (use-modules (guix build utils))

                      (mkdir (ungexp output))
                      (chdir (ungexp output))
                      (ungexp-splicing
                       (map (match-lambda
                              ((target source)
                               (gexp
                                (begin
                                  ;; Stat the source to abort early if it does
                                  ;; not exist.
                                  (stat (ungexp source))

                                  (mkdir-p (dirname (ungexp target)))
                                  (symlink (ungexp source)
                                           (ungexp target))))))
                            files)))))
                 #:guile guile))

(define* (directory-union name things
                          #:key (copy? #f) (quiet? #f)
                          (resolve-collision 'warn-about-collision))
  "Return a directory that is the union of THINGS, where THINGS is a list of
file-like objects denoting directories.  For example:

  (directory-union \"guile+emacs\" (list guile emacs))

yields a directory that is the union of the 'guile' and 'emacs' packages.

Call RESOLVE-COLLISION when several files collide, passing it the list of
colliding files.  RESOLVE-COLLISION must return the chosen file or #f, in
which case the colliding entry is skipped altogether.

When HARD-LINKS? is true, create hard links instead of symlinks.  When QUIET?
is true, the derivation will not print anything."
  (define symlink
    (if copy?
        (gexp (lambda (old new)
                (if (file-is-directory? old)
                    (symlink old new)
                    (copy-file old new))))
        (gexp symlink)))

  (define log-port
    (if quiet?
        (gexp (%make-void-port "w"))
        (gexp (current-error-port))))

  (match things
    ((one)
     ;; Only one thing; return it.
     one)
    (_
     (computed-file name
                    (with-imported-modules '((guix build union))
                      (gexp (begin
                              (use-modules (guix build union)
                                           (srfi srfi-1)) ;for 'first' and 'last'

                              (union-build (ungexp output)
                                           '(ungexp things)

                                           #:log-port (ungexp log-port)
                                           #:symlink (ungexp symlink)
                                           #:resolve-collision
                                           (ungexp resolve-collision)))))))))


;;;
;;; Syntactic sugar.
;;;

(eval-when (expand load eval)
  (define* (read-ungexp chr port #:optional native?)
    "Read an 'ungexp' or 'ungexp-splicing' form from PORT.  When NATIVE? is
true, use 'ungexp-native' and 'ungexp-native-splicing' instead."
    (define unquote-symbol
      (match (peek-char port)
        (#\@
         (read-char port)
         (if native?
             'ungexp-native-splicing
             'ungexp-splicing))
        (_
         (if native?
             'ungexp-native
             'ungexp))))

    (match (read port)
      ((? symbol? symbol)
       (let ((str (symbol->string symbol)))
         (match (string-index-right str #\:)
           (#f
            `(,unquote-symbol ,symbol))
           (colon
            (let ((name   (string->symbol (substring str 0 colon)))
                  (output (substring str (+ colon 1))))
              `(,unquote-symbol ,name ,output))))))
      (x
       `(,unquote-symbol ,x))))

  (define (read-gexp chr port)
    "Read a 'gexp' form from PORT."
    `(gexp ,(read port)))

  ;; Extend the reader
  (read-hash-extend #\~ read-gexp)
  (read-hash-extend #\$ read-ungexp)
  (read-hash-extend #\+ (cut read-ungexp <> <> #t)))

;;; gexp.scm ends here