Use 'mlambda' instead of 'memoize'.
[guix.git] / guix / utils.scm
blob72dc0687a4078825e79a391071b34da3d40a9c00
1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2013, 2014, 2015 Mark H Weaver <mhw@netris.org>
4 ;;; Copyright © 2014 Eric Bavier <bavier@member.fsf.org>
5 ;;; Copyright © 2014 Ian Denhardt <ian@zenhack.net>
6 ;;; Copyright © 2016 Mathieu Lirzin <mthl@gnu.org>
7 ;;; Copyright © 2015 David Thompson <davet@gnu.org>
8 ;;;
9 ;;; This file is part of GNU Guix.
10 ;;;
11 ;;; GNU Guix is free software; you can redistribute it and/or modify it
12 ;;; under the terms of the GNU General Public License as published by
13 ;;; the Free Software Foundation; either version 3 of the License, or (at
14 ;;; your option) any later version.
15 ;;;
16 ;;; GNU Guix is distributed in the hope that it will be useful, but
17 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;;; GNU General Public License for more details.
20 ;;;
21 ;;; You should have received a copy of the GNU General Public License
22 ;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.
24 (define-module (guix utils)
25   #:use-module (guix config)
26   #:use-module (srfi srfi-1)
27   #:use-module (srfi srfi-9)
28   #:use-module (srfi srfi-11)
29   #:use-module (srfi srfi-26)
30   #:use-module (srfi srfi-39)
31   #:use-module (srfi srfi-60)
32   #:use-module (rnrs bytevectors)
33   #:use-module (ice-9 binary-ports)
34   #:autoload   (rnrs io ports) (make-custom-binary-input-port)
35   #:use-module ((rnrs bytevectors) #:select (bytevector-u8-set!))
36   #:use-module (guix memoization)
37   #:use-module ((guix build utils) #:select (dump-port))
38   #:use-module ((guix build syscalls) #:select (mkdtemp! fdatasync))
39   #:use-module (ice-9 vlist)
40   #:use-module (ice-9 format)
41   #:autoload   (ice-9 popen)  (open-pipe*)
42   #:autoload   (ice-9 rdelim) (read-line)
43   #:use-module (ice-9 regex)
44   #:use-module (ice-9 match)
45   #:use-module (ice-9 format)
46   #:use-module ((ice-9 iconv) #:select (bytevector->string))
47   #:use-module (system foreign)
48   #:re-export (memoize)         ; for backwards compatibility
49   #:export (bytevector->base16-string
50             base16-string->bytevector
52             strip-keyword-arguments
53             default-keyword-arguments
54             substitute-keyword-arguments
55             ensure-keyword-arguments
57             current-source-directory
59             <location>
60             location
61             location?
62             location-file
63             location-line
64             location-column
65             source-properties->location
66             location->source-properties
68             nix-system->gnu-triplet
69             gnu-triplet->nix-system
70             %current-system
71             %current-target-system
72             package-name->name+version
73             target-mingw?
74             version-compare
75             version>?
76             version>=?
77             version-prefix
78             version-major+minor
79             guile-version>?
80             string-replace-substring
81             arguments-from-environment-variable
82             file-extension
83             file-sans-extension
84             compressed-file?
85             switch-symlinks
86             call-with-temporary-output-file
87             call-with-temporary-directory
88             with-atomic-file-output
89             cache-directory
90             readlink*
91             edit-expression
93             filtered-port
94             compressed-port
95             decompressed-port
96             call-with-decompressed-port
97             compressed-output-port
98             call-with-compressed-output-port
99             canonical-newline-port))
103 ;;; Base 16.
106 (define (bytevector->base16-string bv)
107   "Return the hexadecimal representation of BV's contents."
108   (define len
109     (bytevector-length bv))
111   (let-syntax ((base16-chars (lambda (s)
112                                (syntax-case s ()
113                                  (_
114                                   (let ((v (list->vector
115                                             (unfold (cut > <> 255)
116                                                     (lambda (n)
117                                                       (format #f "~2,'0x" n))
118                                                     1+
119                                                     0))))
120                                     v))))))
121     (define chars base16-chars)
122     (let loop ((i len)
123                (r '()))
124       (if (zero? i)
125           (string-concatenate r)
126           (let ((i (- i 1)))
127             (loop i
128                   (cons (vector-ref chars (bytevector-u8-ref bv i)) r)))))))
130 (define base16-string->bytevector
131   (let ((chars->value (fold (lambda (i r)
132                               (vhash-consv (string-ref (number->string i 16)
133                                                        0)
134                                            i r))
135                             vlist-null
136                             (iota 16))))
137     (lambda (s)
138       "Return the bytevector whose hexadecimal representation is string S."
139       (define bv
140         (make-bytevector (quotient (string-length s) 2) 0))
142       (string-fold (lambda (chr i)
143                      (let ((j (quotient i 2))
144                            (v (and=> (vhash-assv chr chars->value) cdr)))
145                        (if v
146                            (if (zero? (logand i 1))
147                                (bytevector-u8-set! bv j
148                                                    (arithmetic-shift v 4))
149                                (let ((w (bytevector-u8-ref bv j)))
150                                  (bytevector-u8-set! bv j (logior v w))))
151                            (error "invalid hexadecimal character" chr)))
152                      (+ i 1))
153                    0
154                    s)
155       bv)))
160 ;;; Filtering & pipes.
163 (define (filtered-port command input)
164   "Return an input port where data drained from INPUT is filtered through
165 COMMAND (a list).  In addition, return a list of PIDs that the caller must
166 wait.  When INPUT is a file port, it must be unbuffered; otherwise, any
167 buffered data is lost."
168   (let loop ((input input)
169              (pids  '()))
170     (if (file-port? input)
171         (match (pipe)
172           ((in . out)
173            (match (primitive-fork)
174              (0
175               (dynamic-wind
176                 (const #f)
177                 (lambda ()
178                   (close-port in)
179                   (close-port (current-input-port))
180                   (dup2 (fileno input) 0)
181                   (close-port (current-output-port))
182                   (dup2 (fileno out) 1)
183                   (catch 'system-error
184                     (lambda ()
185                       (apply execl (car command) command))
186                     (lambda args
187                       (format (current-error-port)
188                               "filtered-port: failed to execute '~{~a ~}': ~a~%"
189                               command (strerror (system-error-errno args))))))
190                 (lambda ()
191                   (primitive-_exit 1))))
192              (child
193               (close-port out)
194               (values in (cons child pids))))))
196         ;; INPUT is not a file port, so fork just for the sake of tunneling it
197         ;; through a file port.
198         (match (pipe)
199           ((in . out)
200            (match (primitive-fork)
201              (0
202               (dynamic-wind
203                 (const #t)
204                 (lambda ()
205                   (close-port in)
206                   (dump-port input out))
207                 (lambda ()
208                   (false-if-exception (close out))
209                   (primitive-_exit 0))))
210              (child
211               (close-port out)
212               (loop in (cons child pids)))))))))
214 (define (decompressed-port compression input)
215   "Return an input port where INPUT is decompressed according to COMPRESSION,
216 a symbol such as 'xz."
217   (match compression
218     ((or #f 'none) (values input '()))
219     ('bzip2        (filtered-port `(,%bzip2 "-dc") input))
220     ('xz           (filtered-port `(,%xz "-dc") input))
221     ('gzip         (filtered-port `(,%gzip "-dc") input))
222     (else          (error "unsupported compression scheme" compression))))
224 (define (compressed-port compression input)
225   "Return an input port where INPUT is decompressed according to COMPRESSION,
226 a symbol such as 'xz."
227   (match compression
228     ((or #f 'none) (values input '()))
229     ('bzip2        (filtered-port `(,%bzip2 "-c") input))
230     ('xz           (filtered-port `(,%xz "-c") input))
231     ('gzip         (filtered-port `(,%gzip "-c") input))
232     (else          (error "unsupported compression scheme" compression))))
234 (define (call-with-decompressed-port compression port proc)
235   "Call PROC with a wrapper around PORT, a file port, that decompresses data
236 read from PORT according to COMPRESSION, a symbol such as 'xz."
237   (let-values (((decompressed pids)
238                 (decompressed-port compression port)))
239     (dynamic-wind
240       (const #f)
241       (lambda ()
242         (proc decompressed))
243       (lambda ()
244         (close-port decompressed)
245         (unless (every (compose zero? cdr waitpid) pids)
246           (error "decompressed-port failure" pids))))))
248 (define (filtered-output-port command output)
249   "Return an output port.  Data written to that port is filtered through
250 COMMAND and written to OUTPUT, an output file port.  In addition, return a
251 list of PIDs to wait for.  OUTPUT must be unbuffered; otherwise, any buffered
252 data is lost."
253   (match (pipe)
254     ((in . out)
255      (match (primitive-fork)
256        (0
257         (dynamic-wind
258           (const #f)
259           (lambda ()
260             (close-port out)
261             (close-port (current-input-port))
262             (dup2 (fileno in) 0)
263             (close-port (current-output-port))
264             (dup2 (fileno output) 1)
265             (catch 'system-error
266               (lambda ()
267                 (apply execl (car command) command))
268               (lambda args
269                 (format (current-error-port)
270                         "filtered-output-port: failed to execute '~{~a ~}': ~a~%"
271                         command (strerror (system-error-errno args))))))
272           (lambda ()
273             (primitive-_exit 1))))
274        (child
275         (close-port in)
276         (values out (list child)))))))
278 (define* (compressed-output-port compression output
279                                  #:key (options '()))
280   "Return an output port whose input is compressed according to COMPRESSION,
281 a symbol such as 'xz, and then written to OUTPUT.  In addition return a list
282 of PIDs to wait for.  OPTIONS is a list of strings passed to the compression
283 program--e.g., '(\"--fast\")."
284   (match compression
285     ((or #f 'none) (values output '()))
286     ('bzip2        (filtered-output-port `(,%bzip2 "-c" ,@options) output))
287     ('xz           (filtered-output-port `(,%xz "-c" ,@options) output))
288     ('gzip         (filtered-output-port `(,%gzip "-c" ,@options) output))
289     (else          (error "unsupported compression scheme" compression))))
291 (define* (call-with-compressed-output-port compression port proc
292                                            #:key (options '()))
293   "Call PROC with a wrapper around PORT, a file port, that compresses data
294 that goes to PORT according to COMPRESSION, a symbol such as 'xz.  OPTIONS is
295 a list of command-line arguments passed to the compression program."
296   (let-values (((compressed pids)
297                 (compressed-output-port compression port
298                                         #:options options)))
299     (dynamic-wind
300       (const #f)
301       (lambda ()
302         (proc compressed))
303       (lambda ()
304         (close-port compressed)
305         (unless (every (compose zero? cdr waitpid) pids)
306           (error "compressed-output-port failure" pids))))))
308 (define* (edit-expression source-properties proc #:key (encoding "UTF-8"))
309   "Edit the expression specified by SOURCE-PROPERTIES using PROC, which should
310 be a procedure that takes the original expression in string and returns a new
311 one.  ENCODING will be used to interpret all port I/O, it default to UTF-8.
312 This procedure returns #t on success."
313   (with-fluids ((%default-port-encoding encoding))
314     (let* ((file   (assq-ref source-properties 'filename))
315            (line   (assq-ref source-properties 'line))
316            (column (assq-ref source-properties 'column))
317            (in     (open-input-file file))
318            ;; The start byte position of the expression.
319            (start  (begin (while (not (and (= line (port-line in))
320                                            (= column (port-column in))))
321                             (when (eof-object? (read-char in))
322                               (error (format #f "~a: end of file~%" in))))
323                           (ftell in)))
324            ;; The end byte position of the expression.
325            (end    (begin (read in) (ftell in))))
326       (seek in 0 SEEK_SET) ; read from the beginning of the file.
327       (let* ((pre-bv  (get-bytevector-n in start))
328              ;; The expression in string form.
329              (str     (bytevector->string
330                        (get-bytevector-n in (- end start))
331                        (port-encoding in)))
332              (post-bv (get-bytevector-all in))
333              (str*    (proc str)))
334         ;; Verify the edited expression is still a scheme expression.
335         (call-with-input-string str* read)
336         ;; Update the file with edited expression.
337         (with-atomic-file-output file
338           (lambda (out)
339             (put-bytevector out pre-bv)
340             (display str* out)
341             ;; post-bv maybe the end-of-file object.
342             (when (not (eof-object? post-bv))
343               (put-bytevector out post-bv))
344             #t))))))
348 ;;; Keyword arguments.
351 (define (strip-keyword-arguments keywords args)
352   "Remove all of the keyword arguments listed in KEYWORDS from ARGS."
353   (let loop ((args   args)
354              (result '()))
355     (match args
356       (()
357        (reverse result))
358       (((? keyword? kw) arg . rest)
359        (loop rest
360              (if (memq kw keywords)
361                  result
362                  (cons* arg kw result))))
363       ((head . tail)
364        (loop tail (cons head result))))))
366 (define (default-keyword-arguments args defaults)
367   "Return ARGS augmented with any keyword/value from DEFAULTS for
368 keywords not already present in ARGS."
369   (let loop ((defaults defaults)
370              (args     args))
371     (match defaults
372       ((kw value rest ...)
373        (loop rest
374              (if (memq kw args)
375                  args
376                  (cons* kw value args))))
377       (()
378        args))))
380 (define-syntax collect-default-args
381   (syntax-rules ()
382     ((_)
383      '())
384     ((_ (_ _) rest ...)
385      (collect-default-args rest ...))
386     ((_ (kw _ dflt) rest ...)
387      (cons* kw dflt (collect-default-args rest ...)))))
389 (define-syntax substitute-keyword-arguments
390   (syntax-rules ()
391     "Return a new list of arguments where the value for keyword arg KW is
392 replaced by EXP.  EXP is evaluated in a context where VAR is bound to the
393 previous value of the keyword argument, or DFLT if given."
394     ((_ original-args ((kw var dflt ...) exp) ...)
395      (let loop ((args (default-keyword-arguments
396                         original-args
397                         (collect-default-args (kw var dflt ...) ...)))
398                 (before '()))
399        (match args
400          ((kw var rest (... ...))
401           (loop rest (cons* exp kw before)))
402          ...
403          ((x rest (... ...))
404           (loop rest (cons x before)))
405          (()
406           (reverse before)))))))
408 (define (delkw kw lst)
409   "Remove KW and its associated value from LST, a keyword/value list such
410 as '(#:foo 1 #:bar 2)."
411   (let loop ((lst    lst)
412              (result '()))
413     (match lst
414       (()
415        (reverse result))
416       ((kw? value rest ...)
417        (if (eq? kw? kw)
418            (append (reverse result) rest)
419            (loop rest (cons* value kw? result)))))))
421 (define (ensure-keyword-arguments args kw/values)
422   "Force the keywords arguments KW/VALUES in the keyword argument list ARGS.
423 For instance:
425   (ensure-keyword-arguments '(#:foo 2) '(#:foo 2))
426   => (#:foo 2)
428   (ensure-keyword-arguments '(#:foo 2) '(#:bar 3))
429   => (#:foo 2 #:bar 3)
431   (ensure-keyword-arguments '(#:foo 2) '(#:bar 3 #:foo 42))
432   => (#:foo 42 #:bar 3)
434   (let loop ((args      args)
435              (kw/values kw/values)
436              (result    '()))
437     (match args
438       (()
439        (append (reverse result) kw/values))
440       ((kw value rest ...)
441        (match (memq kw kw/values)
442          ((_ value . _)
443           (loop rest (delkw kw kw/values) (cons* value kw result)))
444          (#f
445           (loop rest kw/values (cons* value kw result))))))))
449 ;;; System strings.
452 (define* (nix-system->gnu-triplet
453           #:optional (system (%current-system)) (vendor "unknown"))
454   "Return a guess of the GNU triplet corresponding to Nix system
455 identifier SYSTEM."
456   (match system
457     ("armhf-linux"
458      (string-append "arm-" vendor "-linux-gnueabihf"))
459     (_
460      (let* ((dash (string-index system #\-))
461             (arch (substring system 0 dash))
462             (os   (substring system (+ 1 dash))))
463        (string-append arch
464                       "-" vendor "-"
465                       (if (string=? os "linux")
466                           "linux-gnu"
467                           os))))))
469 (define (gnu-triplet->nix-system triplet)
470   "Return the Nix system type corresponding to TRIPLET, a GNU triplet as
471 returned by `config.guess'."
472   (let ((triplet (cond ((string-match "^i[345]86-(.*)$" triplet)
473                         =>
474                         (lambda (m)
475                           (string-append "i686-" (match:substring m 1))))
476                        (else triplet))))
477     (cond ((string-match "^arm[^-]*-([^-]+-)?linux-gnueabihf" triplet)
478            "armhf-linux")
479           ((string-match "^([^-]+)-([^-]+-)?linux-gnu.*" triplet)
480            =>
481            (lambda (m)
482              ;; Nix omits `-gnu' for GNU/Linux.
483              (string-append (match:substring m 1) "-linux")))
484           ((string-match "^([^-]+)-([^-]+-)?([[:alpha:]]+)([0-9]+\\.?)*$" triplet)
485            =>
486            (lambda (m)
487              ;; Nix strip the version number from names such as `gnu0.3',
488              ;; `darwin10.2.0', etc., and always strips the vendor part.
489              (string-append (match:substring m 1) "-"
490                             (match:substring m 3))))
491           (else triplet))))
493 (define %current-system
494   ;; System type as expected by Nix, usually ARCHITECTURE-KERNEL.
495   ;; By default, this is equal to (gnu-triplet->nix-system %host-type).
496   (make-parameter %system))
498 (define %current-target-system
499   ;; Either #f or a GNU triplet representing the target system we are
500   ;; cross-building to.
501   (make-parameter #f))
503 (define* (package-name->name+version spec
504                                      #:optional (delimiter #\@))
505   "Given SPEC, a package name like \"foo@0.9.1b\", return two values: \"foo\"
506 and \"0.9.1b\".  When the version part is unavailable, SPEC and #f are
507 returned.  Both parts must not contain any '@'.  Optionally, DELIMITER can be
508 a character other than '@'."
509   (match (string-rindex spec delimiter)
510     (#f  (values spec #f))
511     (idx (values (substring spec 0 idx)
512                  (substring spec (1+ idx))))))
514 (define* (target-mingw? #:optional (target (%current-target-system)))
515   (and target
516        (string-suffix? "-mingw32" target)))
518 (define version-compare
519   (let ((strverscmp
520          (let ((sym (or (dynamic-func "strverscmp" (dynamic-link))
521                         (error "could not find `strverscmp' (from GNU libc)"))))
522            (pointer->procedure int sym (list '* '*)))))
523     (lambda (a b)
524       "Return '> when A denotes a newer version than B,
525 '< when A denotes a older version than B,
526 or '= when they denote equal versions."
527       (let ((result (strverscmp (string->pointer a) (string->pointer b))))
528         (cond ((positive? result) '>)
529               ((negative? result) '<)
530               (else '=))))))
532 (define (version-prefix version-string num-parts)
533   "Truncate version-string to the first num-parts components of the version.
534 For example, (version-prefix \"2.1.47.4.23\" 3) returns \"2.1.47\""
535   (string-join (take (string-split version-string #\.) num-parts) "."))
538 (define (version-major+minor version-string)
539   "Return \"<major>.<minor>\", where major and minor are the major and
540 minor version numbers from version-string."
541   (version-prefix version-string 2))
543 (define (version>? a b)
544   "Return #t when A denotes a version strictly newer than B."
545   (eq? '> (version-compare a b)))
547 (define (version>=? a b)
548   "Return #t when A denotes a version newer or equal to B."
549   (case (version-compare a b)
550     ((> =) #t)
551     (else #f)))
553 (define (guile-version>? str)
554   "Return #t if the running Guile version is greater than STR."
555   ;; Note: Using (version>? (version) "2.0.5") or similar doesn't work,
556   ;; because the result of (version) can have a prefix, like "2.0.5-deb1".
557   (version>? (string-append (major-version) "."
558                             (minor-version) "."
559                             (micro-version))
560              str))
562 (define (file-extension file)
563   "Return the extension of FILE or #f if there is none."
564   (let ((dot (string-rindex file #\.)))
565     (and dot (substring file (+ 1 dot) (string-length file)))))
567 (define (file-sans-extension file)
568   "Return the substring of FILE without its extension, if any."
569   (let ((dot (string-rindex file #\.)))
570     (if dot
571         (substring file 0 dot)
572         file)))
574 (define (compressed-file? file)
575   "Return true if FILE denotes a compressed file."
576   (->bool (member (file-extension file)
577                   '("gz" "bz2" "xz" "lz" "tgz" "tbz2" "zip"))))
579 (define (switch-symlinks link target)
580   "Atomically switch LINK, a symbolic link, to point to TARGET.  Works
581 both when LINK already exists and when it does not."
582   (let ((pivot (string-append link ".new")))
583     (symlink target pivot)
584     (rename-file pivot link)))
586 (define* (string-replace-substring str substr replacement
587                                    #:optional
588                                    (start 0)
589                                    (end (string-length str)))
590   "Replace all occurrences of SUBSTR in the START--END range of STR by
591 REPLACEMENT."
592   (match (string-length substr)
593     (0
594      (error "string-replace-substring: empty substring"))
595     (substr-length
596      (let loop ((start  start)
597                 (pieces (list (substring str 0 start))))
598        (match (string-contains str substr start end)
599          (#f
600           (string-concatenate-reverse
601            (cons (substring str start) pieces)))
602          (index
603           (loop (+ index substr-length)
604                 (cons* replacement
605                        (substring str start index)
606                        pieces))))))))
608 (define (arguments-from-environment-variable variable)
609   "Retrieve value of environment variable denoted by string VARIABLE in the
610 form of a list of strings (`char-set:graphic' tokens) suitable for consumption
611 by `args-fold', if VARIABLE is defined, otherwise return an empty list."
612   (let ((env (getenv variable)))
613     (if env
614         (string-tokenize env char-set:graphic)
615         '())))
617 (define (call-with-temporary-output-file proc)
618   "Call PROC with a name of a temporary file and open output port to that
619 file; close the file and delete it when leaving the dynamic extent of this
620 call."
621   (let* ((directory (or (getenv "TMPDIR") "/tmp"))
622          (template  (string-append directory "/guix-file.XXXXXX"))
623          (out       (mkstemp! template)))
624     (dynamic-wind
625       (lambda ()
626         #t)
627       (lambda ()
628         (proc template out))
629       (lambda ()
630         (false-if-exception (close out))
631         (false-if-exception (delete-file template))))))
633 (define (call-with-temporary-directory proc)
634   "Call PROC with a name of a temporary directory; close the directory and
635 delete it when leaving the dynamic extent of this call."
636   (let* ((directory (or (getenv "TMPDIR") "/tmp"))
637          (template  (string-append directory "/guix-directory.XXXXXX"))
638          (tmp-dir   (mkdtemp! template)))
639     (dynamic-wind
640       (const #t)
641       (lambda ()
642         (proc tmp-dir))
643       (lambda ()
644         (false-if-exception (rmdir tmp-dir))))))
646 (define (with-atomic-file-output file proc)
647   "Call PROC with an output port for the file that is going to replace FILE.
648 Upon success, FILE is atomically replaced by what has been written to the
649 output port, and PROC's result is returned."
650   (let* ((template (string-append file ".XXXXXX"))
651          (out      (mkstemp! template)))
652     (with-throw-handler #t
653       (lambda ()
654         (let ((result (proc out)))
655           (fdatasync out)
656           (close-port out)
657           (rename-file template file)
658           result))
659       (lambda (key . args)
660         (false-if-exception (delete-file template))
661         (close-port out)))))
663 (define (cache-directory)
664   "Return the cache directory for Guix, by default ~/.cache/guix."
665   (string-append (or (getenv "XDG_CACHE_HOME")
666                      (and=> (or (getenv "HOME")
667                                 (passwd:dir (getpwuid (getuid))))
668                             (cut string-append <> "/.cache")))
669                  "/guix"))
671 (define (readlink* file)
672   "Call 'readlink' until the result is not a symlink."
673   (define %max-symlink-depth 50)
675   (let loop ((file  file)
676              (depth 0))
677     (define (absolute target)
678       (if (absolute-file-name? target)
679           target
680           (string-append (dirname file) "/" target)))
682     (if (>= depth %max-symlink-depth)
683         file
684         (call-with-values
685             (lambda ()
686               (catch 'system-error
687                 (lambda ()
688                   (values #t (readlink file)))
689                 (lambda args
690                   (let ((errno (system-error-errno args)))
691                     (if (or (= errno EINVAL))
692                         (values #f file)
693                         (apply throw args))))))
694           (lambda (success? target)
695             (if success?
696                 (loop (absolute target) (+ depth 1))
697                 file))))))
699 (define (canonical-newline-port port)
700   "Return an input port that wraps PORT such that all newlines consist
701   of a single carriage return."
702   (define (get-position)
703     (if (port-has-port-position? port) (port-position port) #f))
704   (define (set-position! position)
705     (if (port-has-set-port-position!? port)
706         (set-port-position! position port)
707         #f))
708   (define (close) (close-port port))
709   (define (read! bv start n)
710     (let loop ((count 0)
711                (byte (get-u8 port)))
712       (cond ((eof-object? byte) count)
713             ((= count (- n 1))
714              (bytevector-u8-set! bv (+ start count) byte)
715              n)
716             ;; XXX: consume all LFs even if not followed by CR.
717             ((eqv? byte (char->integer #\return)) (loop count (get-u8 port)))
718             (else
719              (bytevector-u8-set! bv (+ start count) byte)
720              (loop (+ count 1) (get-u8 port))))))
721   (make-custom-binary-input-port "canonical-newline-port"
722                                  read!
723                                  get-position
724                                  set-position!
725                                  close))
728 ;;; Source location.
731 (define (absolute-dirname file)
732   "Return the absolute name of the directory containing FILE, or #f upon
733 failure."
734   (match (search-path %load-path file)
735     (#f #f)
736     ((? string? file)
737      ;; If there are relative names in %LOAD-PATH, FILE can be relative and
738      ;; needs to be canonicalized.
739      (if (string-prefix? "/" file)
740          (dirname file)
741          (canonicalize-path (dirname file))))))
743 (define-syntax current-source-directory
744   (lambda (s)
745     "Return the absolute name of the current directory, or #f if it could not
746 be determined."
747     (syntax-case s ()
748       ((_)
749        (match (assq 'filename (syntax-source s))
750          (('filename . (? string? file-name))
751           ;; If %FILE-PORT-NAME-CANONICALIZATION is 'relative, then FILE-NAME
752           ;; can be relative.  In that case, we try to find out at run time
753           ;; the absolute file name by looking at %LOAD-PATH; doing this at
754           ;; run time rather than expansion time is necessary to allow files
755           ;; to be moved on the file system.
756           (cond ((not file-name)
757                  #f)                ;raising an error would upset Geiser users
758                 ((string-prefix? "/" file-name)
759                  (dirname file-name))
760                 (else
761                  #`(absolute-dirname #,file-name))))
762          (_
763           #f))))))
765 ;; A source location.
766 (define-record-type <location>
767   (make-location file line column)
768   location?
769   (file          location-file)                   ; file name
770   (line          location-line)                   ; 1-indexed line
771   (column        location-column))                ; 0-indexed column
773 (define location
774   (mlambda (file line column)
775     "Return the <location> object for the given FILE, LINE, and COLUMN."
776     (and line column file
777          (make-location file line column))))
779 (define (source-properties->location loc)
780   "Return a location object based on the info in LOC, an alist as returned
781 by Guile's `source-properties', `frame-source', `current-source-location',
782 etc."
783   (let ((file (assq-ref loc 'filename))
784         (line (assq-ref loc 'line))
785         (col  (assq-ref loc 'column)))
786     ;; In accordance with the GCS, start line and column numbers at 1.  Note
787     ;; that unlike LINE and `port-column', COL is actually 1-indexed here...
788     (location file (and line (+ line 1)) col)))
790 (define (location->source-properties loc)
791   "Return the source property association list based on the info in LOC,
792 a location object."
793   `((line     . ,(and=> (location-line loc) 1-))
794     (column   . ,(location-column loc))
795     (filename . ,(location-file loc))))