records: Add support for 'innate' fields.
[guix.git] / guix / gexp.scm
blob10056e5a1f8eed96f6de25d6f8784cf6a8642d31
1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2014, 2015 Ludovic Courtès <ludo@gnu.org>
3 ;;;
4 ;;; This file is part of GNU Guix.
5 ;;;
6 ;;; GNU Guix is free software; you can redistribute it and/or modify it
7 ;;; under the terms of the GNU General Public License as published by
8 ;;; the Free Software Foundation; either version 3 of the License, or (at
9 ;;; your option) any later version.
10 ;;;
11 ;;; GNU Guix is distributed in the hope that it will be useful, but
12 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 ;;; GNU General Public License for more details.
15 ;;;
16 ;;; You should have received a copy of the GNU General Public License
17 ;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.
19 (define-module (guix gexp)
20   #:use-module (guix store)
21   #:use-module (guix monads)
22   #:use-module (guix derivations)
23   #:use-module (guix utils)
24   #:use-module (srfi srfi-1)
25   #:use-module (srfi srfi-9)
26   #:use-module (srfi srfi-9 gnu)
27   #:use-module (srfi srfi-26)
28   #:use-module (ice-9 match)
29   #:export (gexp
30             gexp?
32             gexp-input
33             gexp-input?
35             local-file
36             local-file?
37             local-file-file
38             local-file-name
39             local-file-recursive?
41             plain-file
42             plain-file?
43             plain-file-name
44             plain-file-content
46             gexp->derivation
47             gexp->file
48             gexp->script
49             text-file*
50             imported-files
51             imported-modules
52             compiled-modules
54             define-gexp-compiler
55             gexp-compiler?))
57 ;;; Commentary:
58 ;;;
59 ;;; This module implements "G-expressions", or "gexps".  Gexps are like
60 ;;; S-expressions (sexps), with two differences:
61 ;;;
62 ;;;   1. References (un-quotations) to derivations or packages in a gexp are
63 ;;;      replaced by the corresponding output file name; in addition, the
64 ;;;      'ungexp-native' unquote-like form allows code to explicitly refer to
65 ;;;      the native code of a given package, in case of cross-compilation;
66 ;;;
67 ;;;   2. Gexps embed information about the derivations they refer to.
68 ;;;
69 ;;; Gexps make it easy to write to files Scheme code that refers to store
70 ;;; items, or to write Scheme code to build derivations.
71 ;;;
72 ;;; Code:
74 ;; "G expressions".
75 (define-record-type <gexp>
76   (make-gexp references natives proc)
77   gexp?
78   (references gexp-references)                    ; ((DRV-OR-PKG OUTPUT) ...)
79   (natives    gexp-native-references)             ; ((DRV-OR-PKG OUTPUT) ...)
80   (proc       gexp-proc))                         ; procedure
82 (define (write-gexp gexp port)
83   "Write GEXP on PORT."
84   (display "#<gexp " port)
86   ;; Try to write the underlying sexp.  Now, this trick doesn't work when
87   ;; doing things like (ungexp-splicing (gexp ())) because GEXP's procedure
88   ;; tries to use 'append' on that, which fails with wrong-type-arg.
89   (false-if-exception
90    (write (apply (gexp-proc gexp)
91                  (append (gexp-references gexp)
92                          (gexp-native-references gexp)))
93           port))
94   (format port " ~a>"
95           (number->string (object-address gexp) 16)))
97 (set-record-type-printer! <gexp> write-gexp)
101 ;;; Methods.
104 ;; Compiler for a type of objects that may be introduced in a gexp.
105 (define-record-type <gexp-compiler>
106   (gexp-compiler predicate lower)
107   gexp-compiler?
108   (predicate  gexp-compiler-predicate)
109   (lower      gexp-compiler-lower))
111 (define %gexp-compilers
112   ;; List of <gexp-compiler>.
113   '())
115 (define (register-compiler! compiler)
116   "Register COMPILER as a gexp compiler."
117   (set! %gexp-compilers (cons compiler %gexp-compilers)))
119 (define (lookup-compiler object)
120   "Search a compiler for OBJECT.  Upon success, return the three argument
121 procedure to lower it; otherwise return #f."
122   (any (match-lambda
123         (($ <gexp-compiler> predicate lower)
124          (and (predicate object) lower)))
125        %gexp-compilers))
127 (define-syntax-rule (define-gexp-compiler (name (param predicate)
128                                                 system target)
129                       body ...)
130   "Define NAME as a compiler for objects matching PREDICATE encountered in
131 gexps.  BODY must return a derivation for PARAM, an object that matches
132 PREDICATE, for SYSTEM and TARGET (the latter of which is #f except when
133 cross-compiling.)"
134   (begin
135     (define name
136       (gexp-compiler predicate
137                      (lambda (param system target)
138                        body ...)))
139     (register-compiler! name)))
141 (define-gexp-compiler (derivation-compiler (drv derivation?) system target)
142   ;; Derivations are the lowest-level representation, so this is the identity
143   ;; compiler.
144   (with-monad %store-monad
145     (return drv)))
149 ;;; File declarations.
152 (define-record-type <local-file>
153   (%local-file file name recursive?)
154   local-file?
155   (file       local-file-file)                    ;string
156   (name       local-file-name)                    ;string
157   (recursive? local-file-recursive?))             ;Boolean
159 (define* (local-file file #:optional (name (basename file))
160                      #:key (recursive? #t))
161   "Return an object representing local file FILE to add to the store; this
162 object can be used in a gexp.  FILE will be added to the store under NAME--by
163 default the base name of FILE.
165 When RECURSIVE? is true, the contents of FILE are added recursively; if FILE
166 designates a flat file and RECURSIVE? is true, its contents are added, and its
167 permission bits are kept.
169 This is the declarative counterpart of the 'interned-file' monadic procedure."
170   (%local-file file name recursive?))
172 (define-gexp-compiler (local-file-compiler (file local-file?) system target)
173   ;; "Compile" FILE by adding it to the store.
174   (match file
175     (($ <local-file> file name recursive?)
176      (interned-file file name #:recursive? recursive?))))
178 (define-record-type <plain-file>
179   (%plain-file name content references)
180   plain-file?
181   (name        plain-file-name)                   ;string
182   (content     plain-file-content)                ;string
183   (references  plain-file-references))            ;list (currently unused)
185 (define (plain-file name content)
186   "Return an object representing a text file called NAME with the given
187 CONTENT (a string) to be added to the store.
189 This is the declarative counterpart of 'text-file'."
190   ;; XXX: For now just ignore 'references' because it's not clear how to use
191   ;; them in a declarative context.
192   (%plain-file name content '()))
194 (define-gexp-compiler (plain-file-compiler (file plain-file?) system target)
195   ;; "Compile" FILE by adding it to the store.
196   (match file
197     (($ <plain-file> name content references)
198      (text-file name content references))))
202 ;;; Inputs & outputs.
205 ;; The input of a gexp.
206 (define-record-type <gexp-input>
207   (%gexp-input thing output native?)
208   gexp-input?
209   (thing     gexp-input-thing)       ;<package> | <origin> | <derivation> | ...
210   (output    gexp-input-output)      ;string
211   (native?   gexp-input-native?))    ;Boolean
213 (define (write-gexp-input input port)
214   (match input
215     (($ <gexp-input> thing output #f)
216      (format port "#<gexp-input ~s:~a>" thing output))
217     (($ <gexp-input> thing output #t)
218      (format port "#<gexp-input native ~s:~a>" thing output))))
220 (set-record-type-printer! <gexp-input> write-gexp-input)
222 (define* (gexp-input thing                        ;convenience procedure
223                      #:optional (output "out")
224                      #:key native?)
225   "Return a new <gexp-input> for the OUTPUT of THING; NATIVE? determines
226 whether this should be considered a \"native\" input or not."
227   (%gexp-input thing output native?))
229 ;; Reference to one of the derivation's outputs, for gexps used in
230 ;; derivations.
231 (define-record-type <gexp-output>
232   (gexp-output name)
233   gexp-output?
234   (name gexp-output-name))
236 (define (write-gexp-output output port)
237   (match output
238     (($ <gexp-output> name)
239      (format port "#<gexp-output ~a>" name))))
241 (set-record-type-printer! <gexp-output> write-gexp-output)
243 (define raw-derivation
244   (store-lift derivation))
246 (define* (lower-inputs inputs
247                        #:key system target)
248   "Turn any package from INPUTS into a derivation for SYSTEM; return the
249 corresponding input list as a monadic value.  When TARGET is true, use it as
250 the cross-compilation target triplet."
251   (with-monad %store-monad
252     (sequence %store-monad
253               (map (match-lambda
254                      (((? struct? thing) sub-drv ...)
255                       (mlet* %store-monad ((lower -> (lookup-compiler thing))
256                                            (drv (lower thing system target)))
257                         (return `(,drv ,@sub-drv))))
258                      (input
259                       (return input)))
260                    inputs))))
262 (define* (lower-reference-graphs graphs #:key system target)
263   "Given GRAPHS, a list of (FILE-NAME INPUT ...) lists for use as a
264 #:reference-graphs argument, lower it such that each INPUT is replaced by the
265 corresponding derivation."
266   (match graphs
267     (((file-names . inputs) ...)
268      (mlet %store-monad ((inputs (lower-inputs inputs
269                                                #:system system
270                                                #:target target)))
271        (return (map cons file-names inputs))))))
273 (define* (lower-references lst #:key system target)
274   "Based on LST, a list of output names and packages, return a list of output
275 names and file names suitable for the #:allowed-references argument to
276 'derivation'."
277   ;; XXX: Currently outputs other than "out" are not supported, and things
278   ;; other than packages aren't either.
279   (with-monad %store-monad
280     (define lower
281       (match-lambda
282        ((? string? output)
283         (return output))
284        (($ <gexp-input> thing output native?)
285         (mlet* %store-monad ((lower -> (lookup-compiler thing))
286                              (drv      (lower thing system
287                                               (if native? #f target))))
288           (return (derivation->output-path drv output))))
289        (thing
290         (mlet* %store-monad ((lower -> (lookup-compiler thing))
291                              (drv      (lower thing system target)))
292           (return (derivation->output-path drv))))))
294     (sequence %store-monad (map lower lst))))
296 (define default-guile-derivation
297   ;; Here we break the abstraction by talking to the higher-level layer.
298   ;; Thus, do the resolution lazily to hide the circular dependency.
299   (let ((proc (delay
300                 (let ((iface (resolve-interface '(guix packages))))
301                   (module-ref iface 'default-guile-derivation)))))
302     (lambda (system)
303       ((force proc) system))))
305 (define* (gexp->derivation name exp
306                            #:key
307                            system (target 'current)
308                            hash hash-algo recursive?
309                            (env-vars '())
310                            (modules '())
311                            (module-path %load-path)
312                            (guile-for-build (%guile-for-build))
313                            (graft? (%graft?))
314                            references-graphs
315                            allowed-references
316                            leaked-env-vars
317                            local-build?)
318   "Return a derivation NAME that runs EXP (a gexp) with GUILE-FOR-BUILD (a
319 derivation) on SYSTEM.  When TARGET is true, it is used as the
320 cross-compilation target triplet for packages referred to by EXP.
322 Make MODULES available in the evaluation context of EXP; MODULES is a list of
323 names of Guile modules searched in MODULE-PATH to be copied in the store,
324 compiled, and made available in the load path during the execution of
325 EXP---e.g., '((guix build utils) (guix build gnu-build-system)).
327 GRAFT? determines whether packages referred to by EXP should be grafted when
328 applicable.
330 When REFERENCES-GRAPHS is true, it must be a list of tuples of one of the
331 following forms:
333   (FILE-NAME PACKAGE)
334   (FILE-NAME PACKAGE OUTPUT)
335   (FILE-NAME DERIVATION)
336   (FILE-NAME DERIVATION OUTPUT)
337   (FILE-NAME STORE-ITEM)
339 The right-hand-side of each element of REFERENCES-GRAPHS is automatically made
340 an input of the build process of EXP.  In the build environment, each
341 FILE-NAME contains the reference graph of the corresponding item, in a simple
342 text format.
344 ALLOWED-REFERENCES must be either #f or a list of output names and packages.
345 In the latter case, the list denotes store items that the result is allowed to
346 refer to.  Any reference to another store item will lead to a build error.
348 The other arguments are as for 'derivation'."
349   (define %modules modules)
350   (define outputs (gexp-outputs exp))
352   (define (graphs-file-names graphs)
353     ;; Return a list of (FILE-NAME . STORE-PATH) pairs made from GRAPHS.
354     (map (match-lambda
355           ;; TODO: Remove 'derivation?' special cases.
356            ((file-name (? derivation? drv))
357             (cons file-name (derivation->output-path drv)))
358            ((file-name (? derivation? drv) sub-drv)
359             (cons file-name (derivation->output-path drv sub-drv)))
360            ((file-name thing)
361             (cons file-name thing)))
362          graphs))
364   (mlet* %store-monad (;; The following binding forces '%current-system' and
365                        ;; '%current-target-system' to be looked up at >>=
366                        ;; time.
367                        (graft?    (set-grafting graft?))
369                        (system -> (or system (%current-system)))
370                        (target -> (if (eq? target 'current)
371                                       (%current-target-system)
372                                       target))
373                        (normals  (lower-inputs (gexp-inputs exp)
374                                                #:system system
375                                                #:target target))
376                        (natives  (lower-inputs (gexp-native-inputs exp)
377                                                #:system system
378                                                #:target #f))
379                        (inputs -> (append normals natives))
380                        (sexp     (gexp->sexp exp
381                                              #:system system
382                                              #:target target))
383                        (builder  (text-file (string-append name "-builder")
384                                             (object->string sexp)))
385                        (modules  (if (pair? %modules)
386                                      (imported-modules %modules
387                                                        #:system system
388                                                        #:module-path module-path
389                                                        #:guile guile-for-build)
390                                      (return #f)))
391                        (compiled (if (pair? %modules)
392                                      (compiled-modules %modules
393                                                        #:system system
394                                                        #:module-path module-path
395                                                        #:guile guile-for-build)
396                                      (return #f)))
397                        (graphs   (if references-graphs
398                                      (lower-reference-graphs references-graphs
399                                                              #:system system
400                                                              #:target target)
401                                      (return #f)))
402                        (allowed  (if allowed-references
403                                      (lower-references allowed-references
404                                                        #:system system
405                                                        #:target target)
406                                      (return #f)))
407                        (guile    (if guile-for-build
408                                      (return guile-for-build)
409                                      (default-guile-derivation system))))
410     (mbegin %store-monad
411       (set-grafting graft?)                       ;restore the initial setting
412       (raw-derivation name
413                       (string-append (derivation->output-path guile)
414                                      "/bin/guile")
415                       `("--no-auto-compile"
416                         ,@(if (pair? %modules)
417                               `("-L" ,(derivation->output-path modules)
418                                 "-C" ,(derivation->output-path compiled))
419                               '())
420                         ,builder)
421                       #:outputs outputs
422                       #:env-vars env-vars
423                       #:system system
424                       #:inputs `((,guile)
425                                  (,builder)
426                                  ,@(if modules
427                                        `((,modules) (,compiled) ,@inputs)
428                                        inputs)
429                                  ,@(match graphs
430                                      (((_ . inputs) ...) inputs)
431                                      (_ '())))
432                       #:hash hash #:hash-algo hash-algo #:recursive? recursive?
433                       #:references-graphs (and=> graphs graphs-file-names)
434                       #:allowed-references allowed
435                       #:leaked-env-vars leaked-env-vars
436                       #:local-build? local-build?))))
438 (define* (gexp-inputs exp #:key native?)
439   "Return the input list for EXP.  When NATIVE? is true, return only native
440 references; otherwise, return only non-native references."
441   (define (add-reference-inputs ref result)
442     (match ref
443       (($ <gexp-input> (? gexp? exp) _ #t)
444        (if native?
445            (append (gexp-inputs exp)
446                    (gexp-inputs exp #:native? #t)
447                    result)
448            result))
449       (($ <gexp-input> (? gexp? exp) _ #f)
450        (if native?
451            (append (gexp-inputs exp #:native? #t)
452                    result)
453            (append (gexp-inputs exp)
454                    result)))
455       (($ <gexp-input> (? string? str))
456        (if (direct-store-path? str)
457            (cons `(,str) result)
458            result))
459       (($ <gexp-input> (? struct? thing) output)
460        (if (lookup-compiler thing)
461            ;; THING is a derivation, or a package, or an origin, etc.
462            (cons `(,thing ,output) result)
463            result))
464       (($ <gexp-input> (lst ...) output n?)
465        (fold-right add-reference-inputs result
466                    ;; XXX: For now, automatically convert LST to a list of
467                    ;; gexp-inputs.
468                    (map (match-lambda
469                          ((? gexp-input? x) x)
470                          (x (%gexp-input x "out" (or n? native?))))
471                         lst)))
472       (_
473        ;; Ignore references to other kinds of objects.
474        result)))
476   (fold-right add-reference-inputs
477               '()
478               (if native?
479                   (gexp-native-references exp)
480                   (gexp-references exp))))
482 (define gexp-native-inputs
483   (cut gexp-inputs <> #:native? #t))
485 (define (gexp-outputs exp)
486   "Return the outputs referred to by EXP as a list of strings."
487   (define (add-reference-output ref result)
488     (match ref
489       (($ <gexp-output> name)
490        (cons name result))
491       (($ <gexp-input> (? gexp? exp))
492        (append (gexp-outputs exp) result))
493       (($ <gexp-input> (lst ...) output native?)
494        ;; XXX: Automatically convert LST.
495        (add-reference-output (map (match-lambda
496                                    ((? gexp-input? x) x)
497                                    (x (%gexp-input x "out" native?)))
498                                   lst)
499                              result))
500       ((lst ...)
501        (fold-right add-reference-output result lst))
502       (_
503        result)))
505   (delete-duplicates
506    (add-reference-output (gexp-references exp) '())))
508 (define* (gexp->sexp exp #:key
509                      (system (%current-system))
510                      (target (%current-target-system)))
511   "Return (monadically) the sexp corresponding to EXP for the given OUTPUT,
512 and in the current monad setting (system type, etc.)"
513   (define* (reference->sexp ref #:optional native?)
514     (with-monad %store-monad
515       (match ref
516         (($ <gexp-output> output)
517          ;; Output file names are not known in advance but the daemon defines
518          ;; an environment variable for each of them at build time, so use
519          ;; that trick.
520          (return `((@ (guile) getenv) ,output)))
521         (($ <gexp-input> (? gexp? exp) output n?)
522          (gexp->sexp exp
523                      #:system system
524                      #:target (if (or n? native?) #f target)))
525         (($ <gexp-input> (refs ...) output n?)
526          (sequence %store-monad
527                    (map (lambda (ref)
528                           ;; XXX: Automatically convert REF to an gexp-input.
529                           (reference->sexp
530                            (if (gexp-input? ref)
531                                ref
532                                (%gexp-input ref "out" n?))
533                            native?))
534                         refs)))
535         (($ <gexp-input> (? struct? thing) output n?)
536          (let ((lower  (lookup-compiler thing))
537                (target (if (or n? native?) #f target)))
538            (mlet %store-monad ((obj (lower thing system target)))
539              ;; OBJ must be either a derivation or a store file name.
540              (return (match obj
541                        ((? derivation? drv)
542                         (derivation->output-path drv output))
543                        ((? string? file)
544                         file))))))
545         (($ <gexp-input> x)
546          (return x))
547         (x
548          (return x)))))
550   (mlet %store-monad
551       ((args (sequence %store-monad
552                        (append (map reference->sexp (gexp-references exp))
553                                (map (cut reference->sexp <> #t)
554                                     (gexp-native-references exp))))))
555     (return (apply (gexp-proc exp) args))))
557 (define (syntax-location-string s)
558   "Return a string representing the source code location of S."
559   (let ((props (syntax-source s)))
560     (if props
561         (let ((file   (assoc-ref props 'filename))
562               (line   (and=> (assoc-ref props 'line) 1+))
563               (column (assoc-ref props 'column)))
564           (if file
565               (simple-format #f "~a:~a:~a"
566                              file line column)
567               (simple-format #f "~a:~a" line column)))
568         "<unknown location>")))
570 (define-syntax gexp
571   (lambda (s)
572     (define (collect-escapes exp)
573       ;; Return all the 'ungexp' present in EXP.
574       (let loop ((exp    exp)
575                  (result '()))
576         (syntax-case exp (ungexp
577                           ungexp-splicing
578                           ungexp-native
579                           ungexp-native-splicing)
580           ((ungexp _)
581            (cons exp result))
582           ((ungexp _ _)
583            (cons exp result))
584           ((ungexp-splicing _ ...)
585            (cons exp result))
586           ((ungexp-native _ ...)
587            result)
588           ((ungexp-native-splicing _ ...)
589            result)
590           ((exp0 exp ...)
591            (let ((result (loop #'exp0 result)))
592              (fold loop result #'(exp ...))))
593           (_
594            result))))
596     (define (collect-native-escapes exp)
597       ;; Return all the 'ungexp-native' forms present in EXP.
598       (let loop ((exp    exp)
599                  (result '()))
600         (syntax-case exp (ungexp
601                           ungexp-splicing
602                           ungexp-native
603                           ungexp-native-splicing)
604           ((ungexp-native _)
605            (cons exp result))
606           ((ungexp-native _ _)
607            (cons exp result))
608           ((ungexp-native-splicing _ ...)
609            (cons exp result))
610           ((ungexp _ ...)
611            result)
612           ((ungexp-splicing _ ...)
613            result)
614           ((exp0 exp ...)
615            (let ((result (loop #'exp0 result)))
616              (fold loop result #'(exp ...))))
617           (_
618            result))))
620     (define (escape->ref exp)
621       ;; Turn 'ungexp' form EXP into a "reference".
622       (syntax-case exp (ungexp ungexp-splicing
623                         ungexp-native ungexp-native-splicing
624                         output)
625         ((ungexp output)
626          #'(gexp-output "out"))
627         ((ungexp output name)
628          #'(gexp-output name))
629         ((ungexp thing)
630          #'(%gexp-input thing "out" #f))
631         ((ungexp drv-or-pkg out)
632          #'(%gexp-input drv-or-pkg out #f))
633         ((ungexp-splicing lst)
634          #'(%gexp-input lst "out" #f))
635         ((ungexp-native thing)
636          #'(%gexp-input thing "out" #t))
637         ((ungexp-native drv-or-pkg out)
638          #'(%gexp-input drv-or-pkg out #t))
639         ((ungexp-native-splicing lst)
640          #'(%gexp-input lst "out" #t))))
642     (define (substitute-ungexp exp substs)
643       ;; Given EXP, an 'ungexp' or 'ungexp-native' form, substitute it with
644       ;; the corresponding form in SUBSTS.
645       (match (assoc exp substs)
646         ((_ id)
647          id)
648         (_
649          #'(syntax-error "error: no 'ungexp' substitution"
650                          #'ref))))
652     (define (substitute-ungexp-splicing exp substs)
653       (syntax-case exp ()
654         ((exp rest ...)
655          (match (assoc #'exp substs)
656            ((_ id)
657             (with-syntax ((id id))
658               #`(append id
659                         #,(substitute-references #'(rest ...) substs))))
660            (_
661             #'(syntax-error "error: no 'ungexp-splicing' substitution"
662                             #'ref))))))
664     (define (substitute-references exp substs)
665       ;; Return a variant of EXP where all the cars of SUBSTS have been
666       ;; replaced by the corresponding cdr.
667       (syntax-case exp (ungexp ungexp-native
668                         ungexp-splicing ungexp-native-splicing)
669         ((ungexp _ ...)
670          (substitute-ungexp exp substs))
671         ((ungexp-native _ ...)
672          (substitute-ungexp exp substs))
673         (((ungexp-splicing _ ...) rest ...)
674          (substitute-ungexp-splicing exp substs))
675         (((ungexp-native-splicing _ ...) rest ...)
676          (substitute-ungexp-splicing exp substs))
677         ((exp0 exp ...)
678          #`(cons #,(substitute-references #'exp0 substs)
679                  #,(substitute-references #'(exp ...) substs)))
680         (x #''x)))
682     (syntax-case s (ungexp output)
683       ((_ exp)
684        (let* ((normals (delete-duplicates (collect-escapes #'exp)))
685               (natives (delete-duplicates (collect-native-escapes #'exp)))
686               (escapes (append normals natives))
687               (formals (generate-temporaries escapes))
688               (sexp    (substitute-references #'exp (zip escapes formals)))
689               (refs    (map escape->ref normals))
690               (nrefs   (map escape->ref natives)))
691          #`(make-gexp (list #,@refs) (list #,@nrefs)
692                       (lambda #,formals
693                         #,sexp)))))))
697 ;;; Module handling.
700 (define %mkdir-p-definition
701   ;; The code for 'mkdir-p' is copied from (guix build utils).  We use it in
702   ;; derivations that cannot use the #:modules argument of 'gexp->derivation'
703   ;; precisely because they implement that functionality.
704   (gexp
705    (define (mkdir-p dir)
706      (define absolute?
707        (string-prefix? "/" dir))
709      (define not-slash
710        (char-set-complement (char-set #\/)))
712      (let loop ((components (string-tokenize dir not-slash))
713                 (root       (if absolute? "" ".")))
714        (match components
715          ((head tail ...)
716           (let ((path (string-append root "/" head)))
717             (catch 'system-error
718               (lambda ()
719                 (mkdir path)
720                 (loop tail path))
721               (lambda args
722                 (if (= EEXIST (system-error-errno args))
723                     (loop tail path)
724                     (apply throw args))))))
725          (() #t))))))
727 (define* (imported-files files
728                          #:key (name "file-import")
729                          (system (%current-system))
730                          (guile (%guile-for-build)))
731   "Return a derivation that imports FILES into STORE.  FILES must be a list
732 of (FINAL-PATH . FILE-NAME) pairs; each FILE-NAME is read from the file
733 system, imported, and appears under FINAL-PATH in the resulting store path."
734   (define file-pair
735     (match-lambda
736      ((final-path . file-name)
737       (mlet %store-monad ((file (interned-file file-name
738                                                (basename final-path))))
739         (return (list final-path file))))))
741   (mlet %store-monad ((files (sequence %store-monad
742                                        (map file-pair files))))
743     (define build
744       (gexp
745        (begin
746          (use-modules (ice-9 match))
748          (ungexp %mkdir-p-definition)
750          (mkdir (ungexp output)) (chdir (ungexp output))
751          (for-each (match-lambda
752                     ((final-path store-path)
753                      (mkdir-p (dirname final-path))
754                      (symlink store-path final-path)))
755                    '(ungexp files)))))
757     ;; TODO: Pass FILES as an environment variable so that BUILD remains
758     ;; exactly the same regardless of FILES: less disk space, and fewer
759     ;; 'add-to-store' RPCs.
760     (gexp->derivation name build
761                       #:system system
762                       #:guile-for-build guile
763                       #:local-build? #t)))
765 (define search-path*
766   ;; A memoizing version of 'search-path' so 'imported-modules' does not end
767   ;; up looking for the same files over and over again.
768   (memoize search-path))
770 (define* (imported-modules modules
771                            #:key (name "module-import")
772                            (system (%current-system))
773                            (guile (%guile-for-build))
774                            (module-path %load-path))
775   "Return a derivation that contains the source files of MODULES, a list of
776 module names such as `(ice-9 q)'.  All of MODULES must be in the MODULE-PATH
777 search path."
778   ;; TODO: Determine the closure of MODULES, build the `.go' files,
779   ;; canonicalize the source files through read/write, etc.
780   (let ((files (map (lambda (m)
781                       (let ((f (string-append
782                                 (string-join (map symbol->string m) "/")
783                                 ".scm")))
784                         (cons f (search-path* module-path f))))
785                     modules)))
786     (imported-files files #:name name #:system system
787                     #:guile guile)))
789 (define* (compiled-modules modules
790                            #:key (name "module-import-compiled")
791                            (system (%current-system))
792                            (guile (%guile-for-build))
793                            (module-path %load-path))
794   "Return a derivation that builds a tree containing the `.go' files
795 corresponding to MODULES.  All the MODULES are built in a context where
796 they can refer to each other."
797   (mlet %store-monad ((modules (imported-modules modules
798                                                  #:system system
799                                                  #:guile guile
800                                                  #:module-path
801                                                  module-path)))
802     (define build
803       (gexp
804        (begin
805          (use-modules (ice-9 ftw)
806                       (ice-9 match)
807                       (srfi srfi-26)
808                       (system base compile))
810          (ungexp %mkdir-p-definition)
812          (define (regular? file)
813            (not (member file '("." ".."))))
815          (define (process-directory directory output)
816            (let ((entries (map (cut string-append directory "/" <>)
817                                (scandir directory regular?))))
818              (for-each (lambda (entry)
819                          (if (file-is-directory? entry)
820                              (let ((output (string-append output "/"
821                                                           (basename entry))))
822                                (mkdir-p output)
823                                (process-directory entry output))
824                              (let* ((base   (string-drop-right
825                                              (basename entry)
826                                              4)) ;.scm
827                                     (output (string-append output "/" base
828                                                            ".go")))
829                                (compile-file entry
830                                              #:output-file output
831                                              #:opts
832                                              %auto-compilation-options))))
833                        entries)))
835          (set! %load-path (cons (ungexp modules) %load-path))
836          (mkdir (ungexp output))
837          (chdir (ungexp modules))
838          (process-directory "." (ungexp output)))))
840     ;; TODO: Pass MODULES as an environment variable.
841     (gexp->derivation name build
842                       #:system system
843                       #:guile-for-build guile
844                       #:local-build? #t)))
848 ;;; Convenience procedures.
851 (define (default-guile)
852   ;; Lazily resolve 'guile-final'.  This module must not refer to (gnu …)
853   ;; modules directly, to avoid circular dependencies, hence this hack.
854   (module-ref (resolve-interface '(gnu packages commencement))
855               'guile-final))
857 (define* (gexp->script name exp
858                        #:key (modules '()) (guile (default-guile)))
859   "Return an executable script NAME that runs EXP using GUILE with MODULES in
860 its search path."
861   (mlet %store-monad ((modules  (imported-modules modules))
862                       (compiled (compiled-modules modules)))
863     (gexp->derivation name
864                       (gexp
865                        (call-with-output-file (ungexp output)
866                          (lambda (port)
867                            ;; Note: that makes a long shebang.  When the store
868                            ;; is /gnu/store, that fits within the 128-byte
869                            ;; limit imposed by Linux, but that may go beyond
870                            ;; when running tests.
871                            (format port
872                                    "#!~a/bin/guile --no-auto-compile~%!#~%"
873                                    (ungexp guile))
875                            ;; Write the 'eval-when' form so that it can be
876                            ;; compiled.
877                            (write
878                             '(eval-when (expand load eval)
879                                (set! %load-path
880                                     (cons (ungexp modules) %load-path))
881                                (set! %load-compiled-path
882                                      (cons (ungexp compiled)
883                                            %load-compiled-path)))
884                             port)
885                            (write '(ungexp exp) port)
886                            (chmod port #o555)))))))
888 (define (gexp->file name exp)
889   "Return a derivation that builds a file NAME containing EXP."
890   (gexp->derivation name
891                     (gexp
892                      (call-with-output-file (ungexp output)
893                        (lambda (port)
894                          (write '(ungexp exp) port))))
895                     #:local-build? #t))
897 (define* (text-file* name #:rest text)
898   "Return as a monadic value a derivation that builds a text file containing
899 all of TEXT.  TEXT may list, in addition to strings, objects of any type that
900 can be used in a gexp: packages, derivations, local file objects, etc.  The
901 resulting store file holds references to all these."
902   (define builder
903     (gexp (call-with-output-file (ungexp output "out")
904             (lambda (port)
905               (display (string-append (ungexp-splicing text)) port)))))
907   (gexp->derivation name builder))
911 ;;; Syntactic sugar.
914 (eval-when (expand load eval)
915   (define* (read-ungexp chr port #:optional native?)
916     "Read an 'ungexp' or 'ungexp-splicing' form from PORT.  When NATIVE? is
917 true, use 'ungexp-native' and 'ungexp-native-splicing' instead."
918     (define unquote-symbol
919       (match (peek-char port)
920         (#\@
921          (read-char port)
922          (if native?
923              'ungexp-native-splicing
924              'ungexp-splicing))
925         (_
926          (if native?
927              'ungexp-native
928              'ungexp))))
930     (match (read port)
931       ((? symbol? symbol)
932        (let ((str (symbol->string symbol)))
933          (match (string-index-right str #\:)
934            (#f
935             `(,unquote-symbol ,symbol))
936            (colon
937             (let ((name   (string->symbol (substring str 0 colon)))
938                   (output (substring str (+ colon 1))))
939               `(,unquote-symbol ,name ,output))))))
940       (x
941        `(,unquote-symbol ,x))))
943   (define (read-gexp chr port)
944     "Read a 'gexp' form from PORT."
945     `(gexp ,(read port)))
947   ;; Extend the reader
948   (read-hash-extend #\~ read-gexp)
949   (read-hash-extend #\$ read-ungexp)
950   (read-hash-extend #\+ (cut read-ungexp <> <> #t)))
952 ;;; gexp.scm ends here