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