home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / share / guile / 1.6 / ice-9 / boot-9.scm < prev    next >
Encoding:
Text File  |  2006-06-19  |  89.7 KB  |  3,115 lines

  1. ;;; installed-scm-file
  2.  
  3. ;;;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
  4. ;;;;
  5. ;;;; This program is free software; you can redistribute it and/or modify
  6. ;;;; it under the terms of the GNU General Public License as published by
  7. ;;;; the Free Software Foundation; either version 2, or (at your option)
  8. ;;;; any later version.
  9. ;;;;
  10. ;;;; This program is distributed in the hope that it will be useful,
  11. ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. ;;;; GNU General Public License for more details.
  14. ;;;;
  15. ;;;; You should have received a copy of the GNU General Public License
  16. ;;;; along with this software; see the file COPYING.  If not, write to
  17. ;;;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  18. ;;;; Boston, MA 02110-1301 USA
  19. ;;;;
  20. ;;;; As a special exception, the Free Software Foundation gives permission
  21. ;;;; for additional uses of the text contained in its release of GUILE.
  22. ;;;;
  23. ;;;; The exception is that, if you link the GUILE library with other files
  24. ;;;; to produce an executable, this does not by itself cause the
  25. ;;;; resulting executable to be covered by the GNU General Public License.
  26. ;;;; Your use of that executable is in no way restricted on account of
  27. ;;;; linking the GUILE library code into it.
  28. ;;;;
  29. ;;;; This exception does not however invalidate any other reasons why
  30. ;;;; the executable file might be covered by the GNU General Public License.
  31. ;;;;
  32. ;;;; This exception applies only to the code released by the
  33. ;;;; Free Software Foundation under the name GUILE.  If you copy
  34. ;;;; code from other Free Software Foundation releases into a copy of
  35. ;;;; GUILE, as the General Public License permits, the exception does
  36. ;;;; not apply to the code that you add in this way.  To avoid misleading
  37. ;;;; anyone as to the status of such modified files, you must delete
  38. ;;;; this exception notice from them.
  39. ;;;;
  40. ;;;; If you write modifications of your own for GUILE, it is your choice
  41. ;;;; whether to permit this exception to apply to your modifications.
  42. ;;;; If you do not wish that, delete this exception notice.
  43. ;;;;
  44.  
  45.  
  46. ;;; Commentary:
  47.  
  48. ;;; This file is the first thing loaded into Guile.  It adds many mundane
  49. ;;; definitions and a few that are interesting.
  50. ;;;
  51. ;;; The module system (hence the hierarchical namespace) are defined in this
  52. ;;; file.
  53. ;;;
  54.  
  55. ;;; Code:
  56.  
  57.  
  58. ;;; {Deprecation}
  59. ;;;
  60.  
  61. ;; We don't have macros here, but we do want to define
  62. ;; `begin-deprecated' early.
  63.  
  64. (define begin-deprecated
  65.   (procedure->memoizing-macro
  66.    (lambda (exp env)
  67.      (if (include-deprecated-features)
  68.      `(begin ,@(cdr exp))
  69.      `#f))))
  70.  
  71.  
  72. ;;; {Features}
  73. ;;
  74.  
  75. (define (provide sym)
  76.   (if (not (memq sym *features*))
  77.       (set! *features* (cons sym *features*))))
  78.  
  79. ;;; Return #t iff FEATURE is available to this Guile interpreter.
  80. ;;; In SLIB, provided? also checks to see if the module is available.
  81. ;;; We should do that too, but don't.
  82. (define (provided? feature)
  83.   (and (memq feature *features*) #t))
  84.  
  85. (begin-deprecated
  86.  (define (feature? sym)
  87.    (issue-deprecation-warning
  88.     "`feature?' is deprecated.  Use `provided?' instead.")
  89.    (provided? sym)))
  90.  
  91. ;;; let format alias simple-format until the more complete version is loaded
  92. (define format simple-format)
  93.  
  94.  
  95. ;;; {R4RS compliance}
  96.  
  97. (primitive-load-path "ice-9/r4rs.scm")
  98.  
  99.  
  100. ;;; {Simple Debugging Tools}
  101. ;;
  102.  
  103.  
  104. ;; peek takes any number of arguments, writes them to the
  105. ;; current ouput port, and returns the last argument.
  106. ;; It is handy to wrap around an expression to look at
  107. ;; a value each time is evaluated, e.g.:
  108. ;;
  109. ;;    (+ 10 (troublesome-fn))
  110. ;;    => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
  111. ;;
  112.  
  113. (define (peek . stuff)
  114.   (newline)
  115.   (display ";;; ")
  116.   (write stuff)
  117.   (newline)
  118.   (car (last-pair stuff)))
  119.  
  120. (define pk peek)
  121.  
  122. (define (warn . stuff)
  123.   (with-output-to-port (current-error-port)
  124.     (lambda ()
  125.       (newline)
  126.       (display ";;; WARNING ")
  127.       (display stuff)
  128.       (newline)
  129.       (car (last-pair stuff)))))
  130.  
  131.  
  132. ;;; {Trivial Functions}
  133. ;;;
  134.  
  135. (define (identity x) x)
  136. (define (1+ n) (+ n 1))
  137. (define (1- n) (+ n -1))
  138. (define (and=> value procedure) (and value (procedure value)))
  139. (define (make-hash-table k) (make-vector k '()))
  140.  
  141. (begin-deprecated
  142.  (define (id x)
  143.    (issue-deprecation-warning "`id' is deprecated.  Use `identity' instead.")
  144.    (identity x))
  145.  (define (-1+ n)
  146.    (issue-deprecation-warning "`-1+' is deprecated.  Use `1-' instead.")
  147.    (1- n))
  148.  (define (return-it . args)
  149.    (issue-deprecation-warning "`return-it' is deprecated.  Use `noop' instead.")
  150.    (apply noop args)))
  151.  
  152. ;;; apply-to-args is functionally redundant with apply and, worse,
  153. ;;; is less general than apply since it only takes two arguments.
  154. ;;;
  155. ;;; On the other hand, apply-to-args is a syntacticly convenient way to
  156. ;;; perform binding in many circumstances when the "let" family of
  157. ;;; of forms don't cut it.  E.g.:
  158. ;;;
  159. ;;;    (apply-to-args (return-3d-mouse-coords)
  160. ;;;      (lambda (x y z)
  161. ;;;        ...))
  162. ;;;
  163.  
  164. (define (apply-to-args args fn) (apply fn args))
  165.  
  166.  
  167.  
  168. ;;; {Integer Math}
  169. ;;;
  170.  
  171. (define (ipow-by-squaring x k acc proc)
  172.   (cond ((zero? k) acc)
  173.     ((= 1 k) (proc acc x))
  174.     (else (ipow-by-squaring (proc x x)
  175.                 (quotient k 2)
  176.                 (if (even? k) acc (proc acc x))
  177.                 proc))))
  178.  
  179. (begin-deprecated
  180.  (define (string-character-length s)
  181.    (issue-deprecation-warning "`string-character-length' is deprecated.  Use `string-length' instead.")
  182.    (string-length s))
  183.  (define (flags . args)
  184.    (issue-deprecation-warning "`flags' is deprecated.  Use `logior' instead.")
  185.    (apply logior args)))
  186.  
  187.  
  188. ;;; {Symbol Properties}
  189. ;;;
  190.  
  191. (define (symbol-property sym prop)
  192.   (let ((pair (assoc prop (symbol-pref sym))))
  193.     (and pair (cdr pair))))
  194.  
  195. (define (set-symbol-property! sym prop val)
  196.   (let ((pair (assoc prop (symbol-pref sym))))
  197.     (if pair
  198.     (set-cdr! pair val)
  199.     (symbol-pset! sym (acons prop val (symbol-pref sym))))))
  200.  
  201. (define (symbol-property-remove! sym prop)
  202.   (let ((pair (assoc prop (symbol-pref sym))))
  203.     (if pair
  204.     (symbol-pset! sym (delq! pair (symbol-pref sym))))))
  205.  
  206. ;;; {General Properties}
  207. ;;;
  208.  
  209. ;; This is a more modern interface to properties.  It will replace all
  210. ;; other property-like things eventually.
  211.  
  212. (define (make-object-property)
  213.   (let ((prop (primitive-make-property #f)))
  214.     (make-procedure-with-setter
  215.      (lambda (obj) (primitive-property-ref prop obj))
  216.      (lambda (obj val) (primitive-property-set! prop obj val)))))
  217.  
  218.  
  219.  
  220. ;;; {Arrays}
  221. ;;;
  222.  
  223. (if (provided? 'array)
  224.     (primitive-load-path "ice-9/arrays.scm"))
  225.  
  226.  
  227. ;;; {Keywords}
  228. ;;;
  229.  
  230. (define (symbol->keyword symbol)
  231.   (make-keyword-from-dash-symbol (symbol-append '- symbol)))
  232.  
  233. (define (keyword->symbol kw)
  234.   (let ((sym (symbol->string (keyword-dash-symbol kw))))
  235.     (string->symbol (substring sym 1 (string-length sym)))))
  236.  
  237. (define (kw-arg-ref args kw)
  238.   (let ((rem (member kw args)))
  239.     (and rem (pair? (cdr rem)) (cadr rem))))
  240.  
  241.  
  242.  
  243. ;;; {Structs}
  244.  
  245. (define (struct-layout s)
  246.   (struct-ref (struct-vtable s) vtable-index-layout))
  247.  
  248.  
  249.  
  250. ;;; Environments
  251.  
  252. (define the-environment
  253.   (procedure->syntax
  254.    (lambda (x e)
  255.      e)))
  256.  
  257. (define the-root-environment (the-environment))
  258.  
  259. (define (environment-module env)
  260.   (let ((closure (and (pair? env) (car (last-pair env)))))
  261.     (and closure (eval-closure-module closure))))
  262.  
  263.  
  264. ;;; {Records}
  265. ;;;
  266.  
  267. ;; Printing records: by default, records are printed as
  268. ;;
  269. ;;   #<type-name field1: val1 field2: val2 ...>
  270. ;;
  271. ;; You can change that by giving a custom printing function to
  272. ;; MAKE-RECORD-TYPE (after the list of field symbols).  This function
  273. ;; will be called like
  274. ;;
  275. ;;   (<printer> object port)
  276. ;;
  277. ;; It should print OBJECT to PORT.
  278.  
  279. (define (inherit-print-state old-port new-port)
  280.   (if (get-print-state old-port)
  281.       (port-with-print-state new-port (get-print-state old-port))
  282.       new-port))
  283.  
  284. ;; 0: type-name, 1: fields
  285. (define record-type-vtable
  286.   (make-vtable-vtable "prpr" 0
  287.               (lambda (s p)
  288.             (cond ((eq? s record-type-vtable)
  289.                    (display "#<record-type-vtable>" p))
  290.                   (else
  291.                    (display "#<record-type " p)
  292.                    (display (record-type-name s) p)
  293.                    (display ">" p))))))
  294.  
  295. (define (record-type? obj)
  296.   (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
  297.  
  298. (define (make-record-type type-name fields . opt)
  299.   (let ((printer-fn (and (pair? opt) (car opt))))
  300.     (let ((struct (make-struct record-type-vtable 0
  301.                    (make-struct-layout
  302.                 (apply string-append
  303.                        (map (lambda (f) "pw") fields)))
  304.                    (or printer-fn
  305.                    (lambda (s p)
  306.                      (display "#<" p)
  307.                      (display type-name p)
  308.                      (let loop ((fields fields)
  309.                         (off 0))
  310.                        (cond
  311.                     ((not (null? fields))
  312.                      (display " " p)
  313.                      (display (car fields) p)
  314.                      (display ": " p)
  315.                      (display (struct-ref s off) p)
  316.                      (loop (cdr fields) (+ 1 off)))))
  317.                      (display ">" p)))
  318.                    type-name
  319.                    (copy-tree fields))))
  320.       ;; Temporary solution: Associate a name to the record type descriptor
  321.       ;; so that the object system can create a wrapper class for it.
  322.       (set-struct-vtable-name! struct (if (symbol? type-name)
  323.                       type-name
  324.                       (string->symbol type-name)))
  325.       struct)))
  326.  
  327. (define (record-type-name obj)
  328.   (if (record-type? obj)
  329.       (struct-ref obj vtable-offset-user)
  330.       (error 'not-a-record-type obj)))
  331.  
  332. (define (record-type-fields obj)
  333.   (if (record-type? obj)
  334.       (struct-ref obj (+ 1 vtable-offset-user))
  335.       (error 'not-a-record-type obj)))
  336.  
  337. (define (record-constructor rtd . opt)
  338.   (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
  339.     (local-eval `(lambda ,field-names
  340.            (make-struct ',rtd 0 ,@(map (lambda (f)
  341.                          (if (memq f field-names)
  342.                              f
  343.                              #f))
  344.                            (record-type-fields rtd))))
  345.         the-root-environment)))
  346.  
  347. (define (record-predicate rtd)
  348.   (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
  349.  
  350. (define (record-accessor rtd field-name)
  351.   (let* ((pos (list-index (record-type-fields rtd) field-name)))
  352.     (if (not pos)
  353.     (error 'no-such-field field-name))
  354.     (local-eval `(lambda (obj)
  355.            (and (eq? ',rtd (record-type-descriptor obj))
  356.             (struct-ref obj ,pos)))
  357.         the-root-environment)))
  358.  
  359. (define (record-modifier rtd field-name)
  360.   (let* ((pos (list-index (record-type-fields rtd) field-name)))
  361.     (if (not pos)
  362.     (error 'no-such-field field-name))
  363.     (local-eval `(lambda (obj val)
  364.            (and (eq? ',rtd (record-type-descriptor obj))
  365.             (struct-set! obj ,pos val)))
  366.         the-root-environment)))
  367.  
  368.  
  369. (define (record? obj)
  370.   (and (struct? obj) (record-type? (struct-vtable obj))))
  371.  
  372. (define (record-type-descriptor obj)
  373.   (if (struct? obj)
  374.       (struct-vtable obj)
  375.       (error 'not-a-record obj)))
  376.  
  377. (provide 'record)
  378.  
  379.  
  380. ;;; {Booleans}
  381. ;;;
  382.  
  383. (define (->bool x) (not (not x)))
  384.  
  385.  
  386. ;;; {Symbols}
  387. ;;;
  388.  
  389. (define (symbol-append . args)
  390.   (string->symbol (apply string-append (map symbol->string args))))
  391.  
  392. (define (list->symbol . args)
  393.   (string->symbol (apply list->string args)))
  394.  
  395. (define (symbol . args)
  396.   (string->symbol (apply string args)))
  397.  
  398.  
  399. ;;; {Lists}
  400. ;;;
  401.  
  402. (define (list-index l k)
  403.   (let loop ((n 0)
  404.          (l l))
  405.     (and (not (null? l))
  406.      (if (eq? (car l) k)
  407.          n
  408.          (loop (+ n 1) (cdr l))))))
  409.  
  410. (define (make-list n . init)
  411.   (if (pair? init) (set! init (car init)))
  412.   (let loop ((answer '())
  413.          (n n))
  414.     (if (<= n 0)
  415.     answer
  416.     (loop (cons init answer) (- n 1)))))
  417.  
  418.  
  419. ;;; {and-map and or-map}
  420. ;;;
  421. ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
  422. ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
  423. ;;;
  424.  
  425. ;; and-map f l
  426. ;;
  427. ;; Apply f to successive elements of l until exhaustion or f returns #f.
  428. ;; If returning early, return #f.  Otherwise, return the last value returned
  429. ;; by f.  If f has never been called because l is empty, return #t.
  430. ;;
  431. (define (and-map f lst)
  432.   (let loop ((result #t)
  433.          (l lst))
  434.     (and result
  435.      (or (and (null? l)
  436.           result)
  437.          (loop (f (car l)) (cdr l))))))
  438.  
  439. ;; or-map f l
  440. ;;
  441. ;; Apply f to successive elements of l until exhaustion or while f returns #f.
  442. ;; If returning early, return the return value of f.
  443. ;;
  444. (define (or-map f lst)
  445.   (let loop ((result #f)
  446.          (l lst))
  447.     (or result
  448.     (and (not (null? l))
  449.          (loop (f (car l)) (cdr l))))))
  450.  
  451.  
  452.  
  453. (if (provided? 'posix)
  454.     (primitive-load-path "ice-9/posix.scm"))
  455.  
  456. (if (provided? 'socket)
  457.     (primitive-load-path "ice-9/networking.scm"))
  458.  
  459. (define file-exists?
  460.   (if (provided? 'posix)
  461.       (lambda (str)
  462.     (->bool (false-if-exception (stat str))))
  463.       (lambda (str)
  464.     (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
  465.                (lambda args #f))))
  466.       (if port (begin (close-port port) #t)
  467.           #f)))))
  468.  
  469. (define file-is-directory?
  470.   (if (provided? 'posix)
  471.       (lambda (str)
  472.     (eq? (stat:type (stat str)) 'directory))
  473.       (lambda (str)
  474.     (let ((port (catch 'system-error
  475.                (lambda () (open-file (string-append str "/.")
  476.                          OPEN_READ))
  477.                (lambda args #f))))
  478.       (if port (begin (close-port port) #t)
  479.           #f)))))
  480.  
  481. (define (has-suffix? str suffix)
  482.   (let ((sufl (string-length suffix))
  483.     (sl (string-length str)))
  484.     (and (> sl sufl)
  485.      (string=? (substring str (- sl sufl) sl) suffix))))
  486.  
  487. (define (system-error-errno args)
  488.   (if (eq? (car args) 'system-error)
  489.       (car (list-ref args 4))
  490.       #f))
  491.  
  492.  
  493. ;;; {Error Handling}
  494. ;;;
  495.  
  496. (define (error . args)
  497.   (save-stack)
  498.   (if (null? args)
  499.       (scm-error 'misc-error #f "?" #f #f)
  500.       (let loop ((msg "~A")
  501.          (rest (cdr args)))
  502.     (if (not (null? rest))
  503.         (loop (string-append msg " ~S")
  504.           (cdr rest))
  505.         (scm-error 'misc-error #f msg args #f)))))
  506.  
  507. ;; bad-throw is the hook that is called upon a throw to a an unhandled
  508. ;; key (unless the throw has four arguments, in which case
  509. ;; it's usually interpreted as an error throw.)
  510. ;; If the key has a default handler (a throw-handler-default property),
  511. ;; it is applied to the throw.
  512. ;;
  513. (define (bad-throw key . args)
  514.   (let ((default (symbol-property key 'throw-handler-default)))
  515.     (or (and default (apply default key args))
  516.     (apply error "unhandled-exception:" key args))))
  517.  
  518.  
  519.  
  520. (define (tm:sec obj) (vector-ref obj 0))
  521. (define (tm:min obj) (vector-ref obj 1))
  522. (define (tm:hour obj) (vector-ref obj 2))
  523. (define (tm:mday obj) (vector-ref obj 3))
  524. (define (tm:mon obj) (vector-ref obj 4))
  525. (define (tm:year obj) (vector-ref obj 5))
  526. (define (tm:wday obj) (vector-ref obj 6))
  527. (define (tm:yday obj) (vector-ref obj 7))
  528. (define (tm:isdst obj) (vector-ref obj 8))
  529. (define (tm:gmtoff obj) (vector-ref obj 9))
  530. (define (tm:zone obj) (vector-ref obj 10))
  531.  
  532. (define (set-tm:sec obj val) (vector-set! obj 0 val))
  533. (define (set-tm:min obj val) (vector-set! obj 1 val))
  534. (define (set-tm:hour obj val) (vector-set! obj 2 val))
  535. (define (set-tm:mday obj val) (vector-set! obj 3 val))
  536. (define (set-tm:mon obj val) (vector-set! obj 4 val))
  537. (define (set-tm:year obj val) (vector-set! obj 5 val))
  538. (define (set-tm:wday obj val) (vector-set! obj 6 val))
  539. (define (set-tm:yday obj val) (vector-set! obj 7 val))
  540. (define (set-tm:isdst obj val) (vector-set! obj 8 val))
  541. (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
  542. (define (set-tm:zone obj val) (vector-set! obj 10 val))
  543.  
  544. (define (tms:clock obj) (vector-ref obj 0))
  545. (define (tms:utime obj) (vector-ref obj 1))
  546. (define (tms:stime obj) (vector-ref obj 2))
  547. (define (tms:cutime obj) (vector-ref obj 3))
  548. (define (tms:cstime obj) (vector-ref obj 4))
  549.  
  550. (define file-position ftell)
  551. (define (file-set-position port offset . whence)
  552.   (let ((whence (if (eq? whence '()) SEEK_SET (car whence))))
  553.     (seek port offset whence)))
  554.  
  555. (define (move->fdes fd/port fd)
  556.   (cond ((integer? fd/port)
  557.      (dup->fdes fd/port fd)
  558.      (close fd/port)
  559.      fd)
  560.     (else
  561.      (primitive-move->fdes fd/port fd)
  562.      (set-port-revealed! fd/port 1)
  563.      fd/port)))
  564.  
  565. (define (release-port-handle port)
  566.   (let ((revealed (port-revealed port)))
  567.     (if (> revealed 0)
  568.     (set-port-revealed! port (- revealed 1)))))
  569.  
  570. (define (dup->port port/fd mode . maybe-fd)
  571.   (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
  572.               mode)))
  573.     (if (pair? maybe-fd)
  574.     (set-port-revealed! port 1))
  575.     port))
  576.  
  577. (define (dup->inport port/fd . maybe-fd)
  578.   (apply dup->port port/fd "r" maybe-fd))
  579.  
  580. (define (dup->outport port/fd . maybe-fd)
  581.   (apply dup->port port/fd "w" maybe-fd))
  582.  
  583. (define (dup port/fd . maybe-fd)
  584.   (if (integer? port/fd)
  585.       (apply dup->fdes port/fd maybe-fd)
  586.       (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
  587.  
  588. (define (duplicate-port port modes)
  589.   (dup->port port modes))
  590.  
  591. (define (fdes->inport fdes)
  592.   (let loop ((rest-ports (fdes->ports fdes)))
  593.     (cond ((null? rest-ports)
  594.        (let ((result (fdopen fdes "r")))
  595.          (set-port-revealed! result 1)
  596.          result))
  597.       ((input-port? (car rest-ports))
  598.        (set-port-revealed! (car rest-ports)
  599.                    (+ (port-revealed (car rest-ports)) 1))
  600.        (car rest-ports))
  601.       (else
  602.        (loop (cdr rest-ports))))))
  603.  
  604. (define (fdes->outport fdes)
  605.   (let loop ((rest-ports (fdes->ports fdes)))
  606.     (cond ((null? rest-ports)
  607.        (let ((result (fdopen fdes "w")))
  608.          (set-port-revealed! result 1)
  609.          result))
  610.       ((output-port? (car rest-ports))
  611.        (set-port-revealed! (car rest-ports)
  612.                    (+ (port-revealed (car rest-ports)) 1))
  613.        (car rest-ports))
  614.       (else
  615.        (loop (cdr rest-ports))))))
  616.  
  617. (define (port->fdes port)
  618.   (set-port-revealed! port (+ (port-revealed port) 1))
  619.   (fileno port))
  620.  
  621. (define (setenv name value)
  622.   (if value
  623.       (putenv (string-append name "=" value))
  624.       (putenv name)))
  625.  
  626.  
  627. ;;; {Load Paths}
  628. ;;;
  629.  
  630. ;;; Here for backward compatability
  631. ;;
  632. (define scheme-file-suffix (lambda () ".scm"))
  633.  
  634. (define (in-vicinity vicinity file)
  635.   (let ((tail (let ((len (string-length vicinity)))
  636.         (if (zero? len)
  637.             #f
  638.             (string-ref vicinity (- len 1))))))
  639.     (string-append vicinity
  640.            (if (or (not tail)
  641.                (eq? tail #\/))
  642.                ""
  643.                "/")
  644.            file)))
  645.  
  646.  
  647. ;;; {Help for scm_shell}
  648. ;;; The argument-processing code used by Guile-based shells generates
  649. ;;; Scheme code based on the argument list.  This page contains help
  650. ;;; functions for the code it generates.
  651.  
  652. (define (command-line) (program-arguments))
  653.  
  654. ;; This is mostly for the internal use of the code generated by
  655. ;; scm_compile_shell_switches.
  656. (define (load-user-init)
  657.   (let* ((home (or (getenv "HOME")
  658.            (false-if-exception (passwd:dir (getpwuid (getuid))))
  659.            "/"))  ;; fallback for cygwin etc.
  660.      (init-file (in-vicinity home ".guile")))
  661.     (if (file-exists? init-file)
  662.     (primitive-load init-file))))
  663.  
  664.  
  665. ;;; {Loading by paths}
  666.  
  667. ;;; Load a Scheme source file named NAME, searching for it in the
  668. ;;; directories listed in %load-path, and applying each of the file
  669. ;;; name extensions listed in %load-extensions.
  670. (define (load-from-path name)
  671.   (start-stack 'load-stack
  672.            (primitive-load-path name)))
  673.  
  674.  
  675.  
  676. ;;; {Transcendental Functions}
  677. ;;;
  678. ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
  679. ;;; Written by Jerry D. Hedden, (C) FSF.
  680. ;;; See the file `COPYING' for terms applying to this program.
  681. ;;;
  682.  
  683. (define (exp z)
  684.   (if (real? z) ($exp z)
  685.       (make-polar ($exp (real-part z)) (imag-part z))))
  686.  
  687. (define (log z)
  688.   (if (and (real? z) (>= z 0))
  689.       ($log z)
  690.       (make-rectangular ($log (magnitude z)) (angle z))))
  691.  
  692. (define (sqrt z)
  693.   (if (real? z)
  694.       (if (negative? z) (make-rectangular 0 ($sqrt (- z)))
  695.       ($sqrt z))
  696.       (make-polar ($sqrt (magnitude z)) (/ (angle z) 2))))
  697.  
  698. (define expt
  699.   (let ((integer-expt integer-expt))
  700.     (lambda (z1 z2)
  701.       (cond ((integer? z2)
  702.              (if (negative? z2)
  703.          (/ 1 (integer-expt z1 (- z2)))
  704.          (integer-expt z1 z2)))
  705.         ((and (real? z2) (real? z1) (>= z1 0))
  706.          ($expt z1 z2))
  707.         (else
  708.          (exp (* z2 (log z1))))))))
  709.  
  710. (define (sinh z)
  711.   (if (real? z) ($sinh z)
  712.       (let ((x (real-part z)) (y (imag-part z)))
  713.     (make-rectangular (* ($sinh x) ($cos y))
  714.               (* ($cosh x) ($sin y))))))
  715. (define (cosh z)
  716.   (if (real? z) ($cosh z)
  717.       (let ((x (real-part z)) (y (imag-part z)))
  718.     (make-rectangular (* ($cosh x) ($cos y))
  719.               (* ($sinh x) ($sin y))))))
  720. (define (tanh z)
  721.   (if (real? z) ($tanh z)
  722.       (let* ((x (* 2 (real-part z)))
  723.          (y (* 2 (imag-part z)))
  724.          (w (+ ($cosh x) ($cos y))))
  725.     (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
  726.  
  727. (define (asinh z)
  728.   (if (real? z) ($asinh z)
  729.       (log (+ z (sqrt (+ (* z z) 1))))))
  730.  
  731. (define (acosh z)
  732.   (if (and (real? z) (>= z 1))
  733.       ($acosh z)
  734.       (log (+ z (sqrt (- (* z z) 1))))))
  735.  
  736. (define (atanh z)
  737.   (if (and (real? z) (> z -1) (< z 1))
  738.       ($atanh z)
  739.       (/ (log (/ (+ 1 z) (- 1 z))) 2)))
  740.  
  741. (define (sin z)
  742.   (if (real? z) ($sin z)
  743.       (let ((x (real-part z)) (y (imag-part z)))
  744.     (make-rectangular (* ($sin x) ($cosh y))
  745.               (* ($cos x) ($sinh y))))))
  746. (define (cos z)
  747.   (if (real? z) ($cos z)
  748.       (let ((x (real-part z)) (y (imag-part z)))
  749.     (make-rectangular (* ($cos x) ($cosh y))
  750.               (- (* ($sin x) ($sinh y)))))))
  751. (define (tan z)
  752.   (if (real? z) ($tan z)
  753.       (let* ((x (* 2 (real-part z)))
  754.          (y (* 2 (imag-part z)))
  755.          (w (+ ($cos x) ($cosh y))))
  756.     (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
  757.  
  758. (define (asin z)
  759.   (if (and (real? z) (>= z -1) (<= z 1))
  760.       ($asin z)
  761.       (* -i (asinh (* +i z)))))
  762.  
  763. (define (acos z)
  764.   (if (and (real? z) (>= z -1) (<= z 1))
  765.       ($acos z)
  766.       (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
  767.  
  768. (define (atan z . y)
  769.   (if (null? y)
  770.       (if (real? z) ($atan z)
  771.       (/ (log (/ (- +i z) (+ +i z))) +2i))
  772.       ($atan2 z (car y))))
  773.  
  774. (define (log10 arg)
  775.   (/ (log arg) (log 10)))
  776.  
  777. (define (numerator q)
  778.   (do ((num q (* 2 num)))
  779.       ((integer? num) num)))
  780.  
  781. (define (denominator q)
  782.   (do ((num q (* 2 num))
  783.        (den (- q q -1) (* 2 den)))
  784.       ((integer? num) den)))
  785.  
  786.  
  787.  
  788. ;;; {Reader Extensions}
  789. ;;;
  790.  
  791. ;;; Reader code for various "#c" forms.
  792. ;;;
  793.  
  794. (read-hash-extend #\' (lambda (c port)
  795.             (read port)))
  796.  
  797. (define read-eval? (make-fluid))
  798. (fluid-set! read-eval? #f)
  799. (read-hash-extend #\.
  800.                   (lambda (c port)
  801.                     (if (fluid-ref read-eval?)
  802.                         (eval (read port) (interaction-environment))
  803.                         (error
  804.                          "#. read expansion found and read-eval? is #f."))))
  805.  
  806.  
  807. ;;; {Command Line Options}
  808. ;;;
  809.  
  810. (define (get-option argv kw-opts kw-args return)
  811.   (cond
  812.    ((null? argv)
  813.     (return #f #f argv))
  814.  
  815.    ((or (not (eq? #\- (string-ref (car argv) 0)))
  816.     (eq? (string-length (car argv)) 1))
  817.     (return 'normal-arg (car argv) (cdr argv)))
  818.  
  819.    ((eq? #\- (string-ref (car argv) 1))
  820.     (let* ((kw-arg-pos (or (string-index (car argv) #\=)
  821.                (string-length (car argv))))
  822.        (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
  823.        (kw-opt? (member kw kw-opts))
  824.        (kw-arg? (member kw kw-args))
  825.        (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
  826.              (substring (car argv)
  827.                     (+ kw-arg-pos 1)
  828.                     (string-length (car argv))))
  829.             (and kw-arg?
  830.              (begin (set! argv (cdr argv)) (car argv))))))
  831.       (if (or kw-opt? kw-arg?)
  832.       (return kw arg (cdr argv))
  833.       (return 'usage-error kw (cdr argv)))))
  834.  
  835.    (else
  836.     (let* ((char (substring (car argv) 1 2))
  837.        (kw (symbol->keyword char)))
  838.       (cond
  839.  
  840.        ((member kw kw-opts)
  841.     (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
  842.            (new-argv (if (= 0 (string-length rest-car))
  843.                  (cdr argv)
  844.                  (cons (string-append "-" rest-car) (cdr argv)))))
  845.       (return kw #f new-argv)))
  846.  
  847.        ((member kw kw-args)
  848.     (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
  849.            (arg (if (= 0 (string-length rest-car))
  850.             (cadr argv)
  851.             rest-car))
  852.            (new-argv (if (= 0 (string-length rest-car))
  853.                  (cddr argv)
  854.                  (cdr argv))))
  855.       (return kw arg new-argv)))
  856.  
  857.        (else (return 'usage-error kw argv)))))))
  858.  
  859. (define (for-next-option proc argv kw-opts kw-args)
  860.   (let loop ((argv argv))
  861.     (get-option argv kw-opts kw-args
  862.         (lambda (opt opt-arg argv)
  863.           (and opt (proc opt opt-arg argv loop))))))
  864.  
  865. (define (display-usage-report kw-desc)
  866.   (for-each
  867.    (lambda (kw)
  868.      (or (eq? (car kw) #t)
  869.      (eq? (car kw) 'else)
  870.      (let* ((opt-desc kw)
  871.         (help (cadr opt-desc))
  872.         (opts (car opt-desc))
  873.         (opts-proper (if (string? (car opts)) (cdr opts) opts))
  874.         (arg-name (if (string? (car opts))
  875.                   (string-append "<" (car opts) ">")
  876.                   ""))
  877.         (left-part (string-append
  878.                 (with-output-to-string
  879.                   (lambda ()
  880.                 (map (lambda (x) (display (keyword->symbol x)) (display " "))
  881.                      opts-proper)))
  882.                 arg-name))
  883.         (middle-part (if (and (< (string-length left-part) 30)
  884.                       (< (string-length help) 40))
  885.                  (make-string (- 30 (string-length left-part)) #\ )
  886.                  "\n\t")))
  887.        (display left-part)
  888.        (display middle-part)
  889.        (display help)
  890.        (newline))))
  891.    kw-desc))
  892.  
  893.  
  894.  
  895. (define (transform-usage-lambda cases)
  896.   (let* ((raw-usage (delq! 'else (map car cases)))
  897.      (usage-sans-specials (map (lambda (x)
  898.                     (or (and (not (list? x)) x)
  899.                     (and (symbol? (car x)) #t)
  900.                     (and (boolean? (car x)) #t)
  901.                     x))
  902.                   raw-usage))
  903.      (usage-desc (delq! #t usage-sans-specials))
  904.      (kw-desc (map car usage-desc))
  905.      (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
  906.      (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
  907.      (transmogrified-cases (map (lambda (case)
  908.                       (cons (let ((opts (car case)))
  909.                           (if (or (boolean? opts) (eq? 'else opts))
  910.                           opts
  911.                           (cond
  912.                            ((symbol? (car opts))  opts)
  913.                            ((boolean? (car opts)) opts)
  914.                            ((string? (caar opts)) (cdar opts))
  915.                            (else (car opts)))))
  916.                         (cdr case)))
  917.                     cases)))
  918.     `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
  919.        (lambda (%argv)
  920.      (let %next-arg ((%argv %argv))
  921.        (get-option %argv
  922.                ',kw-opts
  923.                ',kw-args
  924.                (lambda (%opt %arg %new-argv)
  925.              (case %opt
  926.                ,@ transmogrified-cases))))))))
  927.  
  928.  
  929.  
  930.  
  931. ;;; {Low Level Modules}
  932. ;;;
  933. ;;; These are the low level data structures for modules.
  934. ;;;
  935. ;;; !!! warning: The interface to lazy binder procedures is going
  936. ;;; to be changed in an incompatible way to permit all the basic
  937. ;;; module ops to be virtualized.
  938. ;;;
  939. ;;; (make-module size use-list lazy-binding-proc) => module
  940. ;;; module-{obarray,uses,binder}[|-set!]
  941. ;;; (module? obj) => [#t|#f]
  942. ;;; (module-locally-bound? module symbol) => [#t|#f]
  943. ;;; (module-bound? module symbol) => [#t|#f]
  944. ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
  945. ;;; (module-symbol-interned? module symbol) => [#t|#f]
  946. ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
  947. ;;; (module-variable module symbol) => [#<variable ...> | #f]
  948. ;;; (module-symbol-binding module symbol opt-value)
  949. ;;;        => [ <obj> | opt-value | an error occurs ]
  950. ;;; (module-make-local-var! module symbol) => #<variable...>
  951. ;;; (module-add! module symbol var) => unspecified
  952. ;;; (module-remove! module symbol) =>  unspecified
  953. ;;; (module-for-each proc module) => unspecified
  954. ;;; (make-scm-module) => module ; a lazy copy of the symhash module
  955. ;;; (set-current-module module) => unspecified
  956. ;;; (current-module) => #<module...>
  957. ;;;
  958. ;;;
  959.  
  960.  
  961. ;;; {Printing Modules}
  962. ;; This is how modules are printed.  You can re-define it.
  963. ;; (Redefining is actually more complicated than simply redefining
  964. ;; %print-module because that would only change the binding and not
  965. ;; the value stored in the vtable that determines how record are
  966. ;; printed. Sigh.)
  967.  
  968. (define (%print-module mod port)  ; unused args: depth length style table)
  969.   (display "#<" port)
  970.   (display (or (module-kind mod) "module") port)
  971.   (let ((name (module-name mod)))
  972.     (if name
  973.     (begin
  974.       (display " " port)
  975.       (display name port))))
  976.   (display " " port)
  977.   (display (number->string (object-address mod) 16) port)
  978.   (display ">" port))
  979.  
  980. ;; module-type
  981. ;;
  982. ;; A module is characterized by an obarray in which local symbols
  983. ;; are interned, a list of modules, "uses", from which non-local
  984. ;; bindings can be inherited, and an optional lazy-binder which
  985. ;; is a (CLOSURE module symbol) which, as a last resort, can provide
  986. ;; bindings that would otherwise not be found locally in the module.
  987. ;;
  988. ;; NOTE: If you change here, you also need to change libguile/modules.h.
  989. ;;
  990. (define module-type
  991.   (make-record-type 'module
  992.             '(obarray uses binder eval-closure transformer name kind
  993.                   observers weak-observers observer-id)
  994.             %print-module))
  995.  
  996. ;; make-module &opt size uses binder
  997. ;;
  998. ;; Create a new module, perhaps with a particular size of obarray,
  999. ;; initial uses list, or binding procedure.
  1000. ;;
  1001. (define make-module
  1002.     (lambda args
  1003.  
  1004.       (define (parse-arg index default)
  1005.     (if (> (length args) index)
  1006.         (list-ref args index)
  1007.         default))
  1008.  
  1009.       (if (> (length args) 3)
  1010.       (error "Too many args to make-module." args))
  1011.  
  1012.       (let ((size (parse-arg 0 1021))
  1013.         (uses (parse-arg 1 '()))
  1014.         (binder (parse-arg 2 #f)))
  1015.  
  1016.     (if (not (integer? size))
  1017.         (error "Illegal size to make-module." size))
  1018.     (if (not (and (list? uses)
  1019.               (and-map module? uses)))
  1020.         (error "Incorrect use list." uses))
  1021.     (if (and binder (not (procedure? binder)))
  1022.         (error
  1023.          "Lazy-binder expected to be a procedure or #f." binder))
  1024.  
  1025.     (let ((module (module-constructor (make-vector size '())
  1026.                       uses binder #f #f #f #f
  1027.                       '()
  1028.                       (make-weak-value-hash-table 31)
  1029.                       0)))
  1030.  
  1031.       ;; We can't pass this as an argument to module-constructor,
  1032.       ;; because we need it to close over a pointer to the module
  1033.       ;; itself.
  1034.       (set-module-eval-closure! module (standard-eval-closure module))
  1035.  
  1036.       module))))
  1037.  
  1038. (define module-constructor (record-constructor module-type))
  1039. (define module-obarray  (record-accessor module-type 'obarray))
  1040. (define set-module-obarray! (record-modifier module-type 'obarray))
  1041. (define module-uses  (record-accessor module-type 'uses))
  1042. (define set-module-uses! (record-modifier module-type 'uses))
  1043. (define module-binder (record-accessor module-type 'binder))
  1044. (define set-module-binder! (record-modifier module-type 'binder))
  1045.  
  1046. ;; NOTE: This binding is used in libguile/modules.c.
  1047. (define module-eval-closure (record-accessor module-type 'eval-closure))
  1048.  
  1049. (define module-transformer (record-accessor module-type 'transformer))
  1050. (define set-module-transformer! (record-modifier module-type 'transformer))
  1051. (define module-name (record-accessor module-type 'name))
  1052. (define set-module-name! (record-modifier module-type 'name))
  1053. (define module-kind (record-accessor module-type 'kind))
  1054. (define set-module-kind! (record-modifier module-type 'kind))
  1055. (define module-observers (record-accessor module-type 'observers))
  1056. (define set-module-observers! (record-modifier module-type 'observers))
  1057. (define module-weak-observers (record-accessor module-type 'weak-observers))
  1058. (define module-observer-id (record-accessor module-type 'observer-id))
  1059. (define set-module-observer-id! (record-modifier module-type 'observer-id))
  1060. (define module? (record-predicate module-type))
  1061.  
  1062. (define set-module-eval-closure!
  1063.   (let ((setter (record-modifier module-type 'eval-closure)))
  1064.     (lambda (module closure)
  1065.       (setter module closure)
  1066.       ;; Make it possible to lookup the module from the environment.
  1067.       ;; This implementation is correct since an eval closure can belong
  1068.       ;; to maximally one module.
  1069.       (set-procedure-property! closure 'module module))))
  1070.  
  1071. (begin-deprecated
  1072.  (define (eval-in-module exp mod)
  1073.    (issue-deprecation-warning
  1074.     "`eval-in-module' is deprecated.  Use `eval' instead.")
  1075.    (eval exp mod)))
  1076.  
  1077.  
  1078. ;;; {Observer protocol}
  1079. ;;;
  1080.  
  1081. (define (module-observe module proc)
  1082.   (set-module-observers! module (cons proc (module-observers module)))
  1083.   (cons module proc))
  1084.  
  1085. (define (module-observe-weak module proc)
  1086.   (let ((id (module-observer-id module)))
  1087.     (hash-set! (module-weak-observers module) id proc)
  1088.     (set-module-observer-id! module (+ 1 id))
  1089.     (cons module id)))
  1090.  
  1091. (define (module-unobserve token)
  1092.   (let ((module (car token))
  1093.     (id (cdr token)))
  1094.     (if (integer? id)
  1095.     (hash-remove! (module-weak-observers module) id)
  1096.     (set-module-observers! module (delq1! id (module-observers module)))))
  1097.   *unspecified*)
  1098.  
  1099. (define (module-modified m)
  1100.   (for-each (lambda (proc) (proc m)) (module-observers m))
  1101.   (hash-fold (lambda (id proc res) (proc m)) #f (module-weak-observers m)))
  1102.  
  1103.  
  1104. ;;; {Module Searching in General}
  1105. ;;;
  1106. ;;; We sometimes want to look for properties of a symbol
  1107. ;;; just within the obarray of one module.  If the property
  1108. ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
  1109. ;;; DISPLAY is locally rebound in the module `safe-guile'.''
  1110. ;;;
  1111. ;;;
  1112. ;;; Other times, we want to test for a symbol property in the obarray
  1113. ;;; of M and, if it is not found there, try each of the modules in the
  1114. ;;; uses list of M.  This is the normal way of testing for some
  1115. ;;; property, so we state these properties without qualification as
  1116. ;;; in: ``The symbol 'fnord is interned in module M because it is
  1117. ;;; interned locally in module M2 which is a member of the uses list
  1118. ;;; of M.''
  1119. ;;;
  1120.  
  1121. ;; module-search fn m
  1122. ;;
  1123. ;; return the first non-#f result of FN applied to M and then to
  1124. ;; the modules in the uses of m, and so on recursively.  If all applications
  1125. ;; return #f, then so does this function.
  1126. ;;
  1127. (define (module-search fn m v)
  1128.   (define (loop pos)
  1129.     (and (pair? pos)
  1130.      (or (module-search fn (car pos) v)
  1131.          (loop (cdr pos)))))
  1132.   (or (fn m v)
  1133.       (loop (module-uses m))))
  1134.  
  1135.  
  1136. ;;; {Is a symbol bound in a module?}
  1137. ;;;
  1138. ;;; Symbol S in Module M is bound if S is interned in M and if the binding
  1139. ;;; of S in M has been set to some well-defined value.
  1140. ;;;
  1141.  
  1142. ;; module-locally-bound? module symbol
  1143. ;;
  1144. ;; Is a symbol bound (interned and defined) locally in a given module?
  1145. ;;
  1146. (define (module-locally-bound? m v)
  1147.   (let ((var (module-local-variable m v)))
  1148.     (and var
  1149.      (variable-bound? var))))
  1150.  
  1151. ;; module-bound? module symbol
  1152. ;;
  1153. ;; Is a symbol bound (interned and defined) anywhere in a given module
  1154. ;; or its uses?
  1155. ;;
  1156. (define (module-bound? m v)
  1157.   (module-search module-locally-bound? m v))
  1158.  
  1159. ;;; {Is a symbol interned in a module?}
  1160. ;;;
  1161. ;;; Symbol S in Module M is interned if S occurs in
  1162. ;;; of S in M has been set to some well-defined value.
  1163. ;;;
  1164. ;;; It is possible to intern a symbol in a module without providing
  1165. ;;; an initial binding for the corresponding variable.  This is done
  1166. ;;; with:
  1167. ;;;       (module-add! module symbol (make-undefined-variable))
  1168. ;;;
  1169. ;;; In that case, the symbol is interned in the module, but not
  1170. ;;; bound there.  The unbound symbol shadows any binding for that
  1171. ;;; symbol that might otherwise be inherited from a member of the uses list.
  1172. ;;;
  1173.  
  1174. (define (module-obarray-get-handle ob key)
  1175.   ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
  1176.  
  1177. (define (module-obarray-ref ob key)
  1178.   ((if (symbol? key) hashq-ref hash-ref) ob key))
  1179.  
  1180. (define (module-obarray-set! ob key val)
  1181.   ((if (symbol? key) hashq-set! hash-set!) ob key val))
  1182.  
  1183. (define (module-obarray-remove! ob key)
  1184.   ((if (symbol? key) hashq-remove! hash-remove!) ob key))
  1185.  
  1186. ;; module-symbol-locally-interned? module symbol
  1187. ;;
  1188. ;; is a symbol interned (not neccessarily defined) locally in a given module
  1189. ;; or its uses?  Interned symbols shadow inherited bindings even if
  1190. ;; they are not themselves bound to a defined value.
  1191. ;;
  1192. (define (module-symbol-locally-interned? m v)
  1193.   (not (not (module-obarray-get-handle (module-obarray m) v))))
  1194.  
  1195. ;; module-symbol-interned? module symbol
  1196. ;;
  1197. ;; is a symbol interned (not neccessarily defined) anywhere in a given module
  1198. ;; or its uses?  Interned symbols shadow inherited bindings even if
  1199. ;; they are not themselves bound to a defined value.
  1200. ;;
  1201. (define (module-symbol-interned? m v)
  1202.   (module-search module-symbol-locally-interned? m v))
  1203.  
  1204.  
  1205. ;;; {Mapping modules x symbols --> variables}
  1206. ;;;
  1207.  
  1208. ;; module-local-variable module symbol
  1209. ;; return the local variable associated with a MODULE and SYMBOL.
  1210. ;;
  1211. ;;; This function is very important. It is the only function that can
  1212. ;;; return a variable from a module other than the mutators that store
  1213. ;;; new variables in modules.  Therefore, this function is the location
  1214. ;;; of the "lazy binder" hack.
  1215. ;;;
  1216. ;;; If symbol is defined in MODULE, and if the definition binds symbol
  1217. ;;; to a variable, return that variable object.
  1218. ;;;
  1219. ;;; If the symbols is not found at first, but the module has a lazy binder,
  1220. ;;; then try the binder.
  1221. ;;;
  1222. ;;; If the symbol is not found at all, return #f.
  1223. ;;;
  1224. (define (module-local-variable m v)
  1225. ;  (caddr
  1226. ;   (list m v
  1227.      (let ((b (module-obarray-ref (module-obarray m) v)))
  1228.        (or (and (variable? b) b)
  1229.            (and (module-binder m)
  1230.             ((module-binder m) m v #f)))))
  1231. ;))
  1232.  
  1233. ;; module-variable module symbol
  1234. ;;
  1235. ;; like module-local-variable, except search the uses in the
  1236. ;; case V is not found in M.
  1237. ;;
  1238. ;; NOTE: This function is superseded with C code (see modules.c)
  1239. ;;;      when using the standard eval closure.
  1240. ;;
  1241. (define (module-variable m v)
  1242.   (module-search module-local-variable m v))
  1243.  
  1244.  
  1245. ;;; {Mapping modules x symbols --> bindings}
  1246. ;;;
  1247. ;;; These are similar to the mapping to variables, except that the
  1248. ;;; variable is dereferenced.
  1249. ;;;
  1250.  
  1251. ;; module-symbol-binding module symbol opt-value
  1252. ;;
  1253. ;; return the binding of a variable specified by name within
  1254. ;; a given module, signalling an error if the variable is unbound.
  1255. ;; If the OPT-VALUE is passed, then instead of signalling an error,
  1256. ;; return OPT-VALUE.
  1257. ;;
  1258. (define (module-symbol-local-binding m v . opt-val)
  1259.   (let ((var (module-local-variable m v)))
  1260.     (if var
  1261.     (variable-ref var)
  1262.     (if (not (null? opt-val))
  1263.         (car opt-val)
  1264.         (error "Locally unbound variable." v)))))
  1265.  
  1266. ;; module-symbol-binding module symbol opt-value
  1267. ;;
  1268. ;; return the binding of a variable specified by name within
  1269. ;; a given module, signalling an error if the variable is unbound.
  1270. ;; If the OPT-VALUE is passed, then instead of signalling an error,
  1271. ;; return OPT-VALUE.
  1272. ;;
  1273. (define (module-symbol-binding m v . opt-val)
  1274.   (let ((var (module-variable m v)))
  1275.     (if var
  1276.     (variable-ref var)
  1277.     (if (not (null? opt-val))
  1278.         (car opt-val)
  1279.         (error "Unbound variable." v)))))
  1280.  
  1281.  
  1282.  
  1283. ;;; {Adding Variables to Modules}
  1284. ;;;
  1285. ;;;
  1286.  
  1287.  
  1288. ;; module-make-local-var! module symbol
  1289. ;;
  1290. ;; ensure a variable for V in the local namespace of M.
  1291. ;; If no variable was already there, then create a new and uninitialzied
  1292. ;; variable.
  1293. ;;
  1294. (define (module-make-local-var! m v)
  1295.   (or (let ((b (module-obarray-ref (module-obarray m) v)))
  1296.     (and (variable? b)
  1297.          (begin
  1298.            (module-modified m)
  1299.            b)))
  1300.       (and (module-binder m)
  1301.        ((module-binder m) m v #t))
  1302.       (begin
  1303.     (let ((answer (make-undefined-variable)))
  1304.       (variable-set-name-hint! answer v)
  1305.       (module-obarray-set! (module-obarray m) v answer)
  1306.       (module-modified m)
  1307.       answer))))
  1308.  
  1309. ;; module-ensure-local-variable! module symbol
  1310. ;;
  1311. ;; Ensure that there is a local variable in MODULE for SYMBOL.  If
  1312. ;; there is no binding for SYMBOL, create a new uninitialized
  1313. ;; variable.  Return the local variable.
  1314. ;;
  1315. (define (module-ensure-local-variable! module symbol)
  1316.   (or (module-local-variable module symbol)
  1317.       (let ((var (make-undefined-variable)))
  1318.     (variable-set-name-hint! var symbol)
  1319.     (module-add! module symbol var)
  1320.     var)))
  1321.  
  1322. ;; module-add! module symbol var
  1323. ;;
  1324. ;; ensure a particular variable for V in the local namespace of M.
  1325. ;;
  1326. (define (module-add! m v var)
  1327.   (if (not (variable? var))
  1328.       (error "Bad variable to module-add!" var))
  1329.   (module-obarray-set! (module-obarray m) v var)
  1330.   (module-modified m))
  1331.  
  1332. ;; module-remove!
  1333. ;;
  1334. ;; make sure that a symbol is undefined in the local namespace of M.
  1335. ;;
  1336. (define (module-remove! m v)
  1337.   (module-obarray-remove!  (module-obarray m) v)
  1338.   (module-modified m))
  1339.  
  1340. (define (module-clear! m)
  1341.   (vector-fill! (module-obarray m) '())
  1342.   (module-modified m))
  1343.  
  1344. ;; MODULE-FOR-EACH -- exported
  1345. ;;
  1346. ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
  1347. ;;
  1348. (define (module-for-each proc module)
  1349.   (let ((obarray (module-obarray module)))
  1350.     (do ((index 0 (+ index 1))
  1351.      (end (vector-length obarray)))
  1352.     ((= index end))
  1353.       (for-each
  1354.        (lambda (bucket)
  1355.      (proc (car bucket) (cdr bucket)))
  1356.        (vector-ref obarray index)))))
  1357.  
  1358.  
  1359. (define (module-map proc module)
  1360.   (let* ((obarray (module-obarray module))
  1361.      (end (vector-length obarray)))
  1362.  
  1363.     (let loop ((i 0)
  1364.            (answer '()))
  1365.       (if (= i end)
  1366.       answer
  1367.       (loop (+ 1 i)
  1368.         (append!
  1369.          (map (lambda (bucket)
  1370.             (proc (car bucket) (cdr bucket)))
  1371.               (vector-ref obarray i))
  1372.          answer))))))
  1373.  
  1374.  
  1375. ;;; {Low Level Bootstrapping}
  1376. ;;;
  1377.  
  1378. ;; make-root-module
  1379.  
  1380. ;; A root module uses the pre-modules-obarray as its obarray.  This
  1381. ;; special obarray accumulates all bindings that have been established
  1382. ;; before the module system is fully booted.
  1383. ;;
  1384. ;; (The obarray continues to be used by code that has been closed over
  1385. ;;  before the module system has been booted.)
  1386.  
  1387. (define (make-root-module)
  1388.   (let ((m (make-module 0)))
  1389.     (set-module-obarray! m (%get-pre-modules-obarray))
  1390.     m))
  1391.  
  1392. ;; make-scm-module
  1393.  
  1394. ;; The root interface is a module that uses the same obarray as the
  1395. ;; root module.  It does not allow new definitions, tho.
  1396.  
  1397. (define (make-scm-module)
  1398.   (let ((m (make-module 0)))
  1399.     (set-module-obarray! m (%get-pre-modules-obarray))
  1400.     (set-module-eval-closure! m (standard-interface-eval-closure m))
  1401.     m))
  1402.  
  1403.  
  1404.  
  1405. ;;; {Module-based Loading}
  1406. ;;;
  1407.  
  1408. (define (save-module-excursion thunk)
  1409.   (let ((inner-module (current-module))
  1410.     (outer-module #f))
  1411.     (dynamic-wind (lambda ()
  1412.             (set! outer-module (current-module))
  1413.             (set-current-module inner-module)
  1414.             (set! inner-module #f))
  1415.           thunk
  1416.           (lambda ()
  1417.             (set! inner-module (current-module))
  1418.             (set-current-module outer-module)
  1419.             (set! outer-module #f)))))
  1420.  
  1421. (define basic-load load)
  1422.  
  1423. (define (load-module filename)
  1424.   (save-module-excursion
  1425.    (lambda ()
  1426.      (let ((oldname (and (current-load-port)
  1427.              (port-filename (current-load-port)))))
  1428.        (basic-load (if (and oldname
  1429.                 (> (string-length filename) 0)
  1430.                 (not (char=? (string-ref filename 0) #\/))
  1431.                 (not (string=? (dirname oldname) ".")))
  1432.                (string-append (dirname oldname) "/" filename)
  1433.                filename))))))
  1434.  
  1435.  
  1436.  
  1437. ;;; {MODULE-REF -- exported}
  1438. ;;
  1439. ;; Returns the value of a variable called NAME in MODULE or any of its
  1440. ;; used modules.  If there is no such variable, then if the optional third
  1441. ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
  1442. ;;
  1443. (define (module-ref module name . rest)
  1444.   (let ((variable (module-variable module name)))
  1445.     (if (and variable (variable-bound? variable))
  1446.     (variable-ref variable)
  1447.     (if (null? rest)
  1448.         (error "No variable named" name 'in module)
  1449.         (car rest)            ; default value
  1450.         ))))
  1451.  
  1452. ;; MODULE-SET! -- exported
  1453. ;;
  1454. ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
  1455. ;; to VALUE; if there is no such variable, an error is signaled.
  1456. ;;
  1457. (define (module-set! module name value)
  1458.   (let ((variable (module-variable module name)))
  1459.     (if variable
  1460.     (variable-set! variable value)
  1461.     (error "No variable named" name 'in module))))
  1462.  
  1463. ;; MODULE-DEFINE! -- exported
  1464. ;;
  1465. ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
  1466. ;; variable, it is added first.
  1467. ;;
  1468. (define (module-define! module name value)
  1469.   (let ((variable (module-local-variable module name)))
  1470.     (if variable
  1471.     (begin
  1472.       (variable-set! variable value)
  1473.       (module-modified module))
  1474.     (let ((variable (make-variable value)))
  1475.       (variable-set-name-hint! variable name)
  1476.       (module-add! module name variable)))))
  1477.  
  1478. ;; MODULE-DEFINED? -- exported
  1479. ;;
  1480. ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
  1481. ;; uses)
  1482. ;;
  1483. (define (module-defined? module name)
  1484.   (let ((variable (module-variable module name)))
  1485.     (and variable (variable-bound? variable))))
  1486.  
  1487. ;; MODULE-USE! module interface
  1488. ;;
  1489. ;; Add INTERFACE to the list of interfaces used by MODULE.
  1490. ;;
  1491. (define (module-use! module interface)
  1492.   (set-module-uses! module
  1493.             (cons interface (delq! interface (module-uses module))))
  1494.   (module-modified module))
  1495.  
  1496.  
  1497. ;;; {Recursive Namespaces}
  1498. ;;;
  1499. ;;;
  1500. ;;; A hierarchical namespace emerges if we consider some module to be
  1501. ;;; root, and variables bound to modules as nested namespaces.
  1502. ;;;
  1503. ;;; The routines in this file manage variable names in hierarchical namespace.
  1504. ;;; Each variable name is a list of elements, looked up in successively nested
  1505. ;;; modules.
  1506. ;;;
  1507. ;;;        (nested-ref some-root-module '(foo bar baz))
  1508. ;;;        => <value of a variable named baz in the module bound to bar in
  1509. ;;;            the module bound to foo in some-root-module>
  1510. ;;;
  1511. ;;;
  1512. ;;; There are:
  1513. ;;;
  1514. ;;;    ;; a-root is a module
  1515. ;;;    ;; name is a list of symbols
  1516. ;;;
  1517. ;;;    nested-ref a-root name
  1518. ;;;    nested-set! a-root name val
  1519. ;;;    nested-define! a-root name val
  1520. ;;;    nested-remove! a-root name
  1521. ;;;
  1522. ;;;
  1523. ;;; (current-module) is a natural choice for a-root so for convenience there are
  1524. ;;; also:
  1525. ;;;
  1526. ;;;    local-ref name        ==    nested-ref (current-module) name
  1527. ;;;    local-set! name val    ==    nested-set! (current-module) name val
  1528. ;;;    local-define! name val    ==    nested-define! (current-module) name val
  1529. ;;;    local-remove! name    ==    nested-remove! (current-module) name
  1530. ;;;
  1531.  
  1532.  
  1533. (define (nested-ref root names)
  1534.   (let loop ((cur root)
  1535.          (elts names))
  1536.     (cond
  1537.      ((null? elts)        cur)
  1538.      ((not (module? cur))    #f)
  1539.      (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
  1540.  
  1541. (define (nested-set! root names val)
  1542.   (let loop ((cur root)
  1543.          (elts names))
  1544.     (if (null? (cdr elts))
  1545.     (module-set! cur (car elts) val)
  1546.     (loop (module-ref cur (car elts)) (cdr elts)))))
  1547.  
  1548. (define (nested-define! root names val)
  1549.   (let loop ((cur root)
  1550.          (elts names))
  1551.     (if (null? (cdr elts))
  1552.     (module-define! cur (car elts) val)
  1553.     (loop (module-ref cur (car elts)) (cdr elts)))))
  1554.  
  1555. (define (nested-remove! root names)
  1556.   (let loop ((cur root)
  1557.          (elts names))
  1558.     (if (null? (cdr elts))
  1559.     (module-remove! cur (car elts))
  1560.     (loop (module-ref cur (car elts)) (cdr elts)))))
  1561.  
  1562. (define (local-ref names) (nested-ref (current-module) names))
  1563. (define (local-set! names val) (nested-set! (current-module) names val))
  1564. (define (local-define names val) (nested-define! (current-module) names val))
  1565. (define (local-remove names) (nested-remove! (current-module) names))
  1566.  
  1567.  
  1568.  
  1569. ;;; {The (app) module}
  1570. ;;;
  1571. ;;; The root of conventionally named objects not directly in the top level.
  1572. ;;;
  1573. ;;; (app modules)
  1574. ;;; (app modules guile)
  1575. ;;;
  1576. ;;; The directory of all modules and the standard root module.
  1577. ;;;
  1578.  
  1579. (define (module-public-interface m)
  1580.   (module-ref m '%module-public-interface #f))
  1581. (define (set-module-public-interface! m i)
  1582.   (module-define! m '%module-public-interface i))
  1583. (define (set-system-module! m s)
  1584.   (set-procedure-property! (module-eval-closure m) 'system-module s))
  1585. (define the-root-module (make-root-module))
  1586. (define the-scm-module (make-scm-module))
  1587. (set-module-public-interface! the-root-module the-scm-module)
  1588. (set-module-name! the-root-module '(guile))
  1589. (set-module-name! the-scm-module '(guile))
  1590. (set-module-kind! the-scm-module 'interface)
  1591. (for-each set-system-module! (list the-root-module the-scm-module) '(#t #t))
  1592.  
  1593. ;; NOTE: This binding is used in libguile/modules.c.
  1594. ;;
  1595. (define (make-modules-in module name)
  1596.   (if (null? name)
  1597.       module
  1598.       (cond
  1599.        ((module-ref module (car name) #f)
  1600.     => (lambda (m) (make-modules-in m (cdr name))))
  1601.        (else    (let ((m (make-module 31)))
  1602.           (set-module-kind! m 'directory)
  1603.           (set-module-name! m (append (or (module-name module)
  1604.                           '())
  1605.                           (list (car name))))
  1606.           (module-define! module (car name) m)
  1607.           (make-modules-in m (cdr name)))))))
  1608.  
  1609. (define (beautify-user-module! module)
  1610.   (let ((interface (module-public-interface module)))
  1611.     (if (or (not interface)
  1612.         (eq? interface module))
  1613.     (let ((interface (make-module 31)))
  1614.       (set-module-name! interface (module-name module))
  1615.       (set-module-kind! interface 'interface)
  1616.       (set-module-public-interface! module interface))))
  1617.   (if (and (not (memq the-scm-module (module-uses module)))
  1618.        (not (eq? module the-root-module)))
  1619.       (set-module-uses! module (append (module-uses module) (list the-scm-module)))))
  1620.  
  1621. ;; NOTE: This binding is used in libguile/modules.c.
  1622. ;;
  1623. (define (resolve-module name . maybe-autoload)
  1624.   (let ((full-name (append '(app modules) name)))
  1625.     (let ((already (local-ref full-name)))
  1626.       (if already
  1627.       ;; The module already exists...
  1628.       (if (and (or (null? maybe-autoload) (car maybe-autoload))
  1629.            (not (module-public-interface already)))
  1630.           ;; ...but we are told to load and it doesn't contain source, so
  1631.           (begin
  1632.         (try-load-module name)
  1633.         already)
  1634.           ;; simply return it.
  1635.           already)
  1636.       (begin
  1637.         ;; Try to autoload it if we are told so
  1638.         (if (or (null? maybe-autoload) (car maybe-autoload))
  1639.         (try-load-module name))
  1640.         ;; Get/create it.
  1641.         (make-modules-in (current-module) full-name))))))
  1642.  
  1643. ;; Cheat.  These bindings are needed by modules.c, but we don't want
  1644. ;; to move their real definition here because that would be unnatural.
  1645. ;;
  1646. (define try-module-autoload #f)
  1647. (define process-define-module #f)
  1648. (define process-use-modules #f)
  1649. (define module-export! #f)
  1650.  
  1651. ;; This boots the module system.  All bindings needed by modules.c
  1652. ;; must have been defined by now.
  1653. ;;
  1654. (set-current-module the-root-module)
  1655.  
  1656. (define app (make-module 31))
  1657. (local-define '(app modules) (make-module 31))
  1658. (local-define '(app modules guile) the-root-module)
  1659.  
  1660. ;; (define-special-value '(app modules new-ws) (lambda () (make-scm-module)))
  1661.  
  1662. (define (try-load-module name)
  1663.   (or (begin-deprecated (try-module-linked name))
  1664.       (try-module-autoload name)
  1665.       (begin-deprecated (try-module-dynamic-link name))))
  1666.  
  1667. (define (purify-module! module)
  1668.   "Removes bindings in MODULE which are inherited from the (guile) module."
  1669.   (let ((use-list (module-uses module)))
  1670.     (if (and (pair? use-list)
  1671.          (eq? (car (last-pair use-list)) the-scm-module))
  1672.     (set-module-uses! module (reverse (cdr (reverse use-list)))))))
  1673.  
  1674. ;; Return a module that is an interface to the module designated by
  1675. ;; NAME.
  1676. ;;
  1677. ;; `resolve-interface' takes two keyword arguments:
  1678. ;;
  1679. ;;   #:select SELECTION
  1680. ;;
  1681. ;; SELECTION is a list of binding-specs to be imported; A binding-spec
  1682. ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
  1683. ;; is the name in the used module and SEEN is the name in the using
  1684. ;; module.  Note that SEEN is also passed through RENAMER, below.  The
  1685. ;; default is to select all bindings.  If you specify no selection but
  1686. ;; a renamer, only the bindings that already exist in the used module
  1687. ;; are made available in the interface.  Bindings that are added later
  1688. ;; are not picked up.
  1689. ;;
  1690. ;;   #:renamer RENAMER
  1691. ;;
  1692. ;; RENAMER is a procedure that takes a symbol and returns its new
  1693. ;; name.  The default is to not perform any renaming.
  1694. ;;
  1695. ;; Signal "no code for module" error if module name is not resolvable
  1696. ;; or its public interface is not available.  Signal "no binding"
  1697. ;; error if selected binding does not exist in the used module.
  1698. ;;
  1699. (define (resolve-interface name . args)
  1700.  
  1701.   (define (get-keyword-arg args kw def)
  1702.     (cond ((memq kw args)
  1703.        => (lambda (kw-arg)
  1704.         (if (null? (cdr kw-arg))
  1705.             (error "keyword without value: " kw))
  1706.         (cadr kw-arg)))
  1707.       (else
  1708.        def)))
  1709.  
  1710.   (let* ((select (get-keyword-arg args #:select #f))
  1711.      (renamer (get-keyword-arg args #:renamer identity))
  1712.          (module (resolve-module name))
  1713.          (public-i (and module (module-public-interface module))))
  1714.     (and (or (not module) (not public-i))
  1715.          (error "no code for module" name))
  1716.     (if (and (not select) (eq? renamer identity))
  1717.         public-i
  1718.         (let ((selection (or select (module-map (lambda (sym var) sym)
  1719.                         public-i)))
  1720.               (custom-i (make-module 31)))
  1721.           (set-module-kind! custom-i 'interface)
  1722.       ;; XXX - should use a lazy binder so that changes to the
  1723.       ;; used module are picked up automatically.
  1724.           (for-each (lambda (bspec)
  1725.                       (let* ((direct? (symbol? bspec))
  1726.                              (orig (if direct? bspec (car bspec)))
  1727.                              (seen (if direct? bspec (cdr bspec))))
  1728.                         (module-add! custom-i (renamer seen)
  1729.                                      (or (module-local-variable public-i orig)
  1730.                                          (module-local-variable module orig)
  1731.                                          (error
  1732.                                           ;; fixme: format manually for now
  1733.                                           (simple-format
  1734.                                            #f "no binding `~A' in module ~A"
  1735.                                            orig name))))))
  1736.                     selection)
  1737.           custom-i))))
  1738.  
  1739. (define (symbol-prefix-proc prefix)
  1740.   (lambda (symbol)
  1741.     (symbol-append prefix symbol)))
  1742.  
  1743. ;; This function is called from "modules.c".  If you change it, be
  1744. ;; sure to update "modules.c" as well.
  1745.  
  1746. (define (process-define-module args)
  1747.   (let* ((module-id (car args))
  1748.          (module (resolve-module module-id #f))
  1749.          (kws (cdr args))
  1750.          (unrecognized (lambda (arg)
  1751.                          (error "unrecognized define-module argument" arg))))
  1752.     (beautify-user-module! module)
  1753.     (let loop ((kws kws)
  1754.            (reversed-interfaces '())
  1755.            (exports '())
  1756.            (re-exports '()))
  1757.       (if (null? kws)
  1758.       (begin
  1759.         (for-each (lambda (interface)
  1760.             (module-use! module interface))
  1761.               (reverse reversed-interfaces))
  1762.         (module-export! module exports)
  1763.         (module-re-export! module re-exports))
  1764.       (case (car kws)
  1765.         ((#:use-module #:use-syntax)
  1766.          (or (pair? (cdr kws))
  1767.          (unrecognized kws))
  1768.          (let* ((interface-args (cadr kws))
  1769.             (interface (apply resolve-interface interface-args)))
  1770.            (and (eq? (car kws) #:use-syntax)
  1771.             (or (symbol? (car interface-args))
  1772.             (error "invalid module name for use-syntax"
  1773.                    interface-args))
  1774.             (set-module-transformer!
  1775.              module
  1776.              (module-ref interface (car
  1777.                         (last-pair (car interface-args)))
  1778.                  #f)))
  1779.            (loop (cddr kws)
  1780.              (cons interface reversed-interfaces)
  1781.              exports
  1782.              re-exports)))
  1783.         ((#:autoload)
  1784.          (or (and (pair? (cdr kws)) (pair? (cddr kws)))
  1785.          (unrecognized kws))
  1786.          (loop (cdddr kws)
  1787.            (cons (make-autoload-interface module
  1788.                           (cadr kws)
  1789.                           (caddr kws))
  1790.              reversed-interfaces)
  1791.            exports
  1792.            re-exports))
  1793.         ((#:no-backtrace)
  1794.          (set-system-module! module #t)
  1795.          (loop (cdr kws) reversed-interfaces exports re-exports))
  1796.         ((#:pure)
  1797.          (purify-module! module)
  1798.          (loop (cdr kws) reversed-interfaces exports re-exports))
  1799.         ((#:export #:export-syntax)
  1800.          (or (pair? (cdr kws))
  1801.          (unrecognized kws))
  1802.          (loop (cddr kws)
  1803.            reversed-interfaces
  1804.            (append (cadr kws) exports)
  1805.            re-exports))
  1806.         ((#:re-export #:re-export-syntax)
  1807.          (or (pair? (cdr kws))
  1808.          (unrecognized kws))
  1809.          (loop (cddr kws)
  1810.            reversed-interfaces
  1811.            exports
  1812.            (append (cadr kws) re-exports)))
  1813.         (else
  1814.          (unrecognized kws)))))
  1815.     module))
  1816.  
  1817. ;;; {Autoload}
  1818.  
  1819. (define (make-autoload-interface module name bindings)
  1820.   (let ((b (lambda (a sym definep)
  1821.          (and (memq sym bindings)
  1822.           (let ((i (module-public-interface (resolve-module name))))
  1823.             (if (not i)
  1824.             (error "missing interface for module" name))
  1825.             ;; Replace autoload-interface with interface
  1826.             (set-car! (memq a (module-uses module)) i)
  1827.             (module-local-variable i sym))))))
  1828.     (module-constructor #() '() b #f #f name 'autoload
  1829.             '() (make-weak-value-hash-table 31) 0)))
  1830.  
  1831. ;;; {Compiled module}
  1832.  
  1833. (define load-compiled #f)
  1834.  
  1835.  
  1836. ;;; {Autoloading modules}
  1837.  
  1838. (define autoloads-in-progress '())
  1839.  
  1840. ;; This function is called from "modules.c".  If you change it, be
  1841. ;; sure to update "modules.c" as well.
  1842.  
  1843. (define (try-module-autoload module-name)
  1844.   (let* ((reverse-name (reverse module-name))
  1845.      (name (symbol->string (car reverse-name)))
  1846.      (dir-hint-module-name (reverse (cdr reverse-name)))
  1847.      (dir-hint (apply string-append
  1848.               (map (lambda (elt)
  1849.                  (string-append (symbol->string elt) "/"))
  1850.                    dir-hint-module-name))))
  1851.     (resolve-module dir-hint-module-name #f)
  1852.     (and (not (autoload-done-or-in-progress? dir-hint name))
  1853.      (let ((didit #f))
  1854.        (define (load-file proc file)
  1855.          (save-module-excursion (lambda () (proc file)))
  1856.          (set! didit #t))
  1857.        (dynamic-wind
  1858.         (lambda () (autoload-in-progress! dir-hint name))
  1859.         (lambda ()
  1860.           (let ((file (in-vicinity dir-hint name)))
  1861.         (cond ((and load-compiled
  1862.                 (%search-load-path (string-append file ".go")))
  1863.                => (lambda (full)
  1864.                 (load-file load-compiled full)))
  1865.               ((%search-load-path file)
  1866.                => (lambda (full)
  1867.                 (load-file primitive-load full))))))
  1868.         (lambda () (set-autoloaded! dir-hint name didit)))
  1869.        didit))))
  1870.  
  1871.  
  1872. ;;; Dynamic linking of modules
  1873.  
  1874. ;; This method of dynamically linking Guile Extensions is deprecated.
  1875. ;; Use `load-extension' explicitely from Scheme code instead.
  1876.  
  1877. (begin-deprecated
  1878.  
  1879.  (define (split-c-module-name str)
  1880.    (let loop ((rev '())
  1881.           (start 0)
  1882.           (pos 0)
  1883.           (end (string-length str)))
  1884.      (cond
  1885.       ((= pos end)
  1886.        (reverse (cons (string->symbol (substring str start pos)) rev)))
  1887.       ((eq? (string-ref str pos) #\space)
  1888.        (loop (cons (string->symbol (substring str start pos)) rev)
  1889.          (+ pos 1)
  1890.          (+ pos 1)
  1891.          end))
  1892.       (else
  1893.        (loop rev start (+ pos 1) end)))))
  1894.  
  1895.  (define (convert-c-registered-modules dynobj)
  1896.    (let ((res (map (lambda (c)
  1897.              (list (split-c-module-name (car c)) (cdr c) dynobj))
  1898.            (c-registered-modules))))
  1899.      (c-clear-registered-modules)
  1900.      res))
  1901.  
  1902.  (define registered-modules '())
  1903.  
  1904.  (define (register-modules dynobj)
  1905.    (set! registered-modules
  1906.      (append! (convert-c-registered-modules dynobj)
  1907.           registered-modules)))
  1908.  
  1909.  (define (warn-autoload-deprecation modname)
  1910.    (issue-deprecation-warning
  1911.     "Autoloading of compiled code modules is deprecated."
  1912.     "Write a Scheme file instead that uses `load-extension'.")
  1913.    (issue-deprecation-warning
  1914.     (simple-format #f "(You just autoloaded module ~S.)" modname)))
  1915.  
  1916.  (define (init-dynamic-module modname)
  1917.    ;; Register any linked modules which have been registered on the C level
  1918.    (register-modules #f)
  1919.    (or-map (lambda (modinfo)
  1920.          (if (equal? (car modinfo) modname)
  1921.          (begin
  1922.            (warn-autoload-deprecation modname)
  1923.            (set! registered-modules (delq! modinfo registered-modules))
  1924.            (let ((mod (resolve-module modname #f)))
  1925.              (save-module-excursion
  1926.               (lambda ()
  1927.             (set-current-module mod)
  1928.             (set-module-public-interface! mod mod)
  1929.             (dynamic-call (cadr modinfo) (caddr modinfo))
  1930.             ))
  1931.              #t))
  1932.          #f))
  1933.        registered-modules))
  1934.  
  1935.  (define (dynamic-maybe-call name dynobj)
  1936.    (catch #t                ; could use false-if-exception here
  1937.       (lambda ()
  1938.         (dynamic-call name dynobj))
  1939.       (lambda args
  1940.         #f)))
  1941.  
  1942.  (define (dynamic-maybe-link filename)
  1943.    (catch #t                ; could use false-if-exception here
  1944.       (lambda ()
  1945.         (dynamic-link filename))
  1946.       (lambda args
  1947.         #f)))
  1948.  
  1949.  (define (find-and-link-dynamic-module module-name)
  1950.    (define (make-init-name mod-name)
  1951.      (string-append "scm_init"
  1952.             (list->string (map (lambda (c)
  1953.                      (if (or (char-alphabetic? c)
  1954.                          (char-numeric? c))
  1955.                          c
  1956.                          #\_))
  1957.                        (string->list mod-name)))
  1958.             "_module"))
  1959.  
  1960.    ;; Put the subdirectory for this module in the car of SUBDIR-AND-LIBNAME,
  1961.    ;; and the `libname' (the name of the module prepended by `lib') in the cdr
  1962.    ;; field.  For example, if MODULE-NAME is the list (inet tcp-ip udp), then
  1963.    ;; SUBDIR-AND-LIBNAME will be the pair ("inet/tcp-ip" . "libudp").
  1964.    (let ((subdir-and-libname
  1965.       (let loop ((dirs "")
  1966.              (syms module-name))
  1967.         (if (null? (cdr syms))
  1968.         (cons dirs (string-append "lib" (symbol->string (car syms))))
  1969.         (loop (string-append dirs (symbol->string (car syms)) "/")
  1970.               (cdr syms)))))
  1971.      (init (make-init-name (apply string-append
  1972.                       (map (lambda (s)
  1973.                          (string-append "_"
  1974.                                 (symbol->string s)))
  1975.                        module-name)))))
  1976.      (let ((subdir (car subdir-and-libname))
  1977.        (libname (cdr subdir-and-libname)))
  1978.  
  1979.        ;; Now look in each dir in %LOAD-PATH for `subdir/libfoo.la'.  If that
  1980.        ;; file exists, fetch the dlname from that file and attempt to link
  1981.        ;; against it.  If `subdir/libfoo.la' does not exist, or does not seem
  1982.        ;; to name any shared library, look for `subdir/libfoo.so' instead and
  1983.        ;; link against that.
  1984.        (let check-dirs ((dir-list %load-path))
  1985.      (if (null? dir-list)
  1986.          #f
  1987.          (let* ((dir (in-vicinity (car dir-list) subdir))
  1988.             (sharlib-full
  1989.              (or (try-using-libtool-name dir libname)
  1990.              (try-using-sharlib-name dir libname))))
  1991.            (if (and sharlib-full (file-exists? sharlib-full))
  1992.            (link-dynamic-module sharlib-full init)
  1993.            (check-dirs (cdr dir-list)))))))))
  1994.  
  1995.  (define (try-using-libtool-name libdir libname)
  1996.    (let ((libtool-filename (in-vicinity libdir
  1997.                     (string-append libname ".la"))))
  1998.      (and (file-exists? libtool-filename)
  1999.       libtool-filename)))
  2000.  
  2001.  (define (try-using-sharlib-name libdir libname)
  2002.    (in-vicinity libdir (string-append libname ".so")))
  2003.  
  2004.  (define (link-dynamic-module filename initname)
  2005.    ;; Register any linked modules which have been registered on the C level
  2006.    (register-modules #f)
  2007.    (let ((dynobj (dynamic-link filename)))
  2008.      (dynamic-call initname dynobj)
  2009.      (register-modules dynobj)))
  2010.  
  2011.  (define (try-module-linked module-name)
  2012.    (init-dynamic-module module-name))
  2013.  
  2014.  (define (try-module-dynamic-link module-name)
  2015.    (and (find-and-link-dynamic-module module-name)
  2016.     (init-dynamic-module module-name))))
  2017. ;; end of deprecated section
  2018.  
  2019.  
  2020. (define autoloads-done '((guile . guile)))
  2021.  
  2022. (define (autoload-done-or-in-progress? p m)
  2023.   (let ((n (cons p m)))
  2024.     (->bool (or (member n autoloads-done)
  2025.         (member n autoloads-in-progress)))))
  2026.  
  2027. (define (autoload-done! p m)
  2028.   (let ((n (cons p m)))
  2029.     (set! autoloads-in-progress
  2030.       (delete! n autoloads-in-progress))
  2031.     (or (member n autoloads-done)
  2032.     (set! autoloads-done (cons n autoloads-done)))))
  2033.  
  2034. (define (autoload-in-progress! p m)
  2035.   (let ((n (cons p m)))
  2036.     (set! autoloads-done
  2037.       (delete! n autoloads-done))
  2038.     (set! autoloads-in-progress (cons n autoloads-in-progress))))
  2039.  
  2040. (define (set-autoloaded! p m done?)
  2041.   (if done?
  2042.       (autoload-done! p m)
  2043.       (let ((n (cons p m)))
  2044.     (set! autoloads-done (delete! n autoloads-done))
  2045.     (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
  2046.  
  2047.  
  2048.  
  2049.  
  2050. ;; {EVAL-CASE}
  2051. ;;
  2052. ;; (eval-case ((situation*) forms)* (else forms)?)
  2053. ;;
  2054. ;; Evaluate certain code based on the situation that eval-case is used
  2055. ;; in.  The only defined situation right now is `load-toplevel' which
  2056. ;; triggers for code evaluated at the top-level, for example from the
  2057. ;; REPL or when loading a file.
  2058.  
  2059. (define eval-case
  2060.   (procedure->memoizing-macro
  2061.    (lambda (exp env)
  2062.      (define (toplevel-env? env)
  2063.        (or (not (pair? env)) (not (pair? (car env)))))
  2064.      (define (syntax)
  2065.        (error "syntax error in eval-case"))
  2066.      (let loop ((clauses (cdr exp)))
  2067.        (cond
  2068.     ((null? clauses)
  2069.      #f)
  2070.     ((not (list? (car clauses)))
  2071.      (syntax))
  2072.     ((eq? 'else (caar clauses))
  2073.      (or (null? (cdr clauses))
  2074.          (syntax))
  2075.      (cons 'begin (cdar clauses)))
  2076.     ((not (list? (caar clauses)))
  2077.      (syntax))
  2078.     ((and (toplevel-env? env)
  2079.           (memq 'load-toplevel (caar clauses)))
  2080.      (cons 'begin (cdar clauses)))
  2081.     (else
  2082.      (loop (cdr clauses))))))))
  2083.  
  2084.  
  2085. ;;; {Macros}
  2086. ;;;
  2087.  
  2088. (define (primitive-macro? m)
  2089.   (and (macro? m)
  2090.        (not (macro-transformer m))))
  2091.  
  2092. ;;; {Defmacros}
  2093. ;;;
  2094. (define macro-table (make-weak-key-hash-table 523))
  2095. (define xformer-table (make-weak-key-hash-table 523))
  2096.  
  2097. (define (defmacro? m)  (hashq-ref macro-table m))
  2098. (define (assert-defmacro?! m) (hashq-set! macro-table m #t))
  2099. (define (defmacro-transformer m) (hashq-ref xformer-table m))
  2100. (define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
  2101.  
  2102. (define defmacro:transformer
  2103.   (lambda (f)
  2104.     (let* ((xform (lambda (exp env)
  2105.             (copy-tree (apply f (cdr exp)))))
  2106.        (a (procedure->memoizing-macro xform)))
  2107.       (assert-defmacro?! a)
  2108.       (set-defmacro-transformer! a f)
  2109.       a)))
  2110.  
  2111.  
  2112. (define defmacro
  2113.   (let ((defmacro-transformer
  2114.       (lambda (name parms . body)
  2115.         (let ((transformer `(lambda ,parms ,@body)))
  2116.           `(eval-case
  2117.         ((load-toplevel)
  2118.          (define ,name (defmacro:transformer ,transformer)))
  2119.         (else
  2120.          (error "defmacro can only be used at the top level")))))))
  2121.     (defmacro:transformer defmacro-transformer)))
  2122.  
  2123. (define defmacro:syntax-transformer
  2124.   (lambda (f)
  2125.     (procedure->syntax
  2126.           (lambda (exp env)
  2127.         (copy-tree (apply f (cdr exp)))))))
  2128.  
  2129.  
  2130. ;; XXX - should the definition of the car really be looked up in the
  2131. ;; current module?
  2132.  
  2133. (define (macroexpand-1 e)
  2134.   (cond
  2135.    ((pair? e) (let* ((a (car e))
  2136.              (val (and (symbol? a) (local-ref (list a)))))
  2137.         (if (defmacro? val)
  2138.             (apply (defmacro-transformer val) (cdr e))
  2139.             e)))
  2140.    (#t e)))
  2141.  
  2142. (define (macroexpand e)
  2143.   (cond
  2144.    ((pair? e) (let* ((a (car e))
  2145.              (val (and (symbol? a) (local-ref (list a)))))
  2146.         (if (defmacro? val)
  2147.             (macroexpand (apply (defmacro-transformer val) (cdr e)))
  2148.             e)))
  2149.    (#t e)))
  2150.  
  2151. (provide 'defmacro)
  2152.  
  2153.  
  2154.  
  2155. ;;; {Run-time options}
  2156.  
  2157. (define define-option-interface
  2158.   (let* ((option-name car)
  2159.      (option-value cadr)
  2160.      (option-documentation caddr)
  2161.  
  2162.      (print-option (lambda (option)
  2163.              (display (option-name option))
  2164.              (if (< (string-length
  2165.                  (symbol->string (option-name option)))
  2166.                 8)
  2167.                  (display #\tab))
  2168.              (display #\tab)
  2169.              (display (option-value option))
  2170.              (display #\tab)
  2171.              (display (option-documentation option))
  2172.              (newline)))
  2173.  
  2174.      ;; Below follow the macros defining the run-time option interfaces.
  2175.  
  2176.      (make-options (lambda (interface)
  2177.              `(lambda args
  2178.                 (cond ((null? args) (,interface))
  2179.                   ((list? (car args))
  2180.                    (,interface (car args)) (,interface))
  2181.                   (else (for-each ,print-option
  2182.                           (,interface #t)))))))
  2183.  
  2184.      (make-enable (lambda (interface)
  2185.             `(lambda flags
  2186.                (,interface (append flags (,interface)))
  2187.                (,interface))))
  2188.  
  2189.      (make-disable (lambda (interface)
  2190.              `(lambda flags
  2191.                 (let ((options (,interface)))
  2192.                   (for-each (lambda (flag)
  2193.                       (set! options (delq! flag options)))
  2194.                     flags)
  2195.                   (,interface options)
  2196.                   (,interface)))))
  2197.  
  2198.      (make-set! (lambda (interface)
  2199.               `((name exp)
  2200.             (,'quasiquote
  2201.              (begin (,interface (append (,interface)
  2202.                             (list '(,'unquote name)
  2203.                               (,'unquote exp))))
  2204.                 (,interface)))))))
  2205.     (procedure->macro
  2206.      (lambda (exp env)
  2207.        (cons 'begin
  2208.          (let* ((option-group (cadr exp))
  2209.             (interface (car option-group)))
  2210.            (append (map (lambda (name constructor)
  2211.                   `(define ,name
  2212.                  ,(constructor interface)))
  2213.                 (cadr option-group)
  2214.                 (list make-options
  2215.                   make-enable
  2216.                   make-disable))
  2217.                (map (lambda (name constructor)
  2218.                   `(defmacro ,name
  2219.                  ,@(constructor interface)))
  2220.                 (caddr option-group)
  2221.                 (list make-set!)))))))))
  2222.  
  2223. (define-option-interface
  2224.   (eval-options-interface
  2225.    (eval-options eval-enable eval-disable)
  2226.    (eval-set!)))
  2227.  
  2228. (define-option-interface
  2229.   (debug-options-interface
  2230.    (debug-options debug-enable debug-disable)
  2231.    (debug-set!)))
  2232.  
  2233. (define-option-interface
  2234.   (evaluator-traps-interface
  2235.    (traps trap-enable trap-disable)
  2236.    (trap-set!)))
  2237.  
  2238. (define-option-interface
  2239.   (read-options-interface
  2240.    (read-options read-enable read-disable)
  2241.    (read-set!)))
  2242.  
  2243. (define-option-interface
  2244.   (print-options-interface
  2245.    (print-options print-enable print-disable)
  2246.    (print-set!)))
  2247.  
  2248.  
  2249.  
  2250. ;;; {Running Repls}
  2251. ;;;
  2252.  
  2253. (define (repl read evaler print)
  2254.   (let loop ((source (read (current-input-port))))
  2255.     (print (evaler source))
  2256.     (loop (read (current-input-port)))))
  2257.  
  2258. ;; A provisional repl that acts like the SCM repl:
  2259. ;;
  2260. (define scm-repl-silent #f)
  2261. (define (assert-repl-silence v) (set! scm-repl-silent v))
  2262.  
  2263. (define *unspecified* (if #f #f))
  2264. (define (unspecified? v) (eq? v *unspecified*))
  2265.  
  2266. (define scm-repl-print-unspecified #f)
  2267. (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
  2268.  
  2269. (define scm-repl-verbose #f)
  2270. (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
  2271.  
  2272. (define scm-repl-prompt "guile> ")
  2273.  
  2274. (define (set-repl-prompt! v) (set! scm-repl-prompt v))
  2275.  
  2276. (define (default-lazy-handler key . args)
  2277.   (save-stack lazy-handler-dispatch)
  2278.   (apply throw key args))
  2279.  
  2280. (define (lazy-handler-dispatch key . args)
  2281.   (apply default-lazy-handler key args))
  2282.  
  2283. (define abort-hook (make-hook))
  2284.  
  2285. ;; these definitions are used if running a script.
  2286. ;; otherwise redefined in error-catching-loop.
  2287. (define (set-batch-mode?! arg) #t)
  2288. (define (batch-mode?) #t)
  2289.  
  2290. (define (error-catching-loop thunk)
  2291.   (let ((status #f)
  2292.     (interactive #t))
  2293.     (define (loop first)
  2294.       (let ((next
  2295.          (catch #t
  2296.  
  2297.             (lambda ()
  2298.               (lazy-catch #t
  2299.                   (lambda ()
  2300.                     (dynamic-wind
  2301.                      (lambda () (unmask-signals))
  2302.                      (lambda ()
  2303.                        (with-traps
  2304.                     (lambda ()
  2305.                       (first)
  2306.  
  2307.                       ;; This line is needed because mark
  2308.                       ;; doesn't do closures quite right.
  2309.                       ;; Unreferenced locals should be
  2310.                       ;; collected.
  2311.                       ;;
  2312.                       (set! first #f)
  2313.                       (let loop ((v (thunk)))
  2314.                         (loop (thunk)))
  2315.                       #f)))
  2316.                      (lambda () (mask-signals))))
  2317.  
  2318.                   lazy-handler-dispatch))
  2319.  
  2320.             (lambda (key . args)
  2321.               (case key
  2322.             ((quit)
  2323.              (set! status args)
  2324.              #f)
  2325.  
  2326.             ((switch-repl)
  2327.              (apply throw 'switch-repl args))
  2328.  
  2329.             ((abort)
  2330.              ;; This is one of the closures that require
  2331.              ;; (set! first #f) above
  2332.              ;;
  2333.              (lambda ()
  2334.                (run-hook abort-hook)
  2335.                (force-output (current-output-port))
  2336.                (display "ABORT: "  (current-error-port))
  2337.                (write args (current-error-port))
  2338.                (newline (current-error-port))
  2339.                (if interactive
  2340.                    (begin
  2341.                  (if (and
  2342.                       (not has-shown-debugger-hint?)
  2343.                       (not (memq 'backtrace
  2344.                          (debug-options-interface)))
  2345.                       (stack? (fluid-ref the-last-stack)))
  2346.                      (begin
  2347.                        (newline (current-error-port))
  2348.                        (display
  2349.                     "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
  2350.                     (current-error-port))
  2351.                        (set! has-shown-debugger-hint? #t)))
  2352.                  (force-output (current-error-port)))
  2353.                    (begin
  2354.                  (primitive-exit 1)))
  2355.                (set! stack-saved? #f)))
  2356.  
  2357.             (else
  2358.              ;; This is the other cons-leak closure...
  2359.              (lambda ()
  2360.                (cond ((= (length args) 4)
  2361.                   (apply handle-system-error key args))
  2362.                  (else
  2363.                   (apply bad-throw key args))))))))))
  2364.     (if next (loop next) status)))
  2365.     (set! set-batch-mode?! (lambda (arg)
  2366.                  (cond (arg
  2367.                     (set! interactive #f)
  2368.                     (restore-signals))
  2369.                    (#t
  2370.                     (error "sorry, not implemented")))))
  2371.     (set! batch-mode? (lambda () (not interactive)))
  2372.     (loop (lambda () #t))))
  2373.  
  2374. ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
  2375. (define before-signal-stack (make-fluid))
  2376. (define stack-saved? #f)
  2377.  
  2378. (define (save-stack . narrowing)
  2379.   (or stack-saved?
  2380.       (cond ((not (memq 'debug (debug-options-interface)))
  2381.          (fluid-set! the-last-stack #f)
  2382.          (set! stack-saved? #t))
  2383.         (else
  2384.          (fluid-set!
  2385.           the-last-stack
  2386.           (case (stack-id #t)
  2387.         ((repl-stack)
  2388.          (apply make-stack #t save-stack primitive-eval #t 0 narrowing))
  2389.         ((load-stack)
  2390.          (apply make-stack #t save-stack 0 #t 0 narrowing))
  2391.         ((tk-stack)
  2392.          (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
  2393.         ((#t)
  2394.          (apply make-stack #t save-stack 0 1 narrowing))
  2395.         (else
  2396.          (let ((id (stack-id #t)))
  2397.            (and (procedure? id)
  2398.             (apply make-stack #t save-stack id #t 0 narrowing))))))
  2399.          (set! stack-saved? #t)))))
  2400.  
  2401. (define before-error-hook (make-hook))
  2402. (define after-error-hook (make-hook))
  2403. (define before-backtrace-hook (make-hook))
  2404. (define after-backtrace-hook (make-hook))
  2405.  
  2406. (define has-shown-debugger-hint? #f)
  2407.  
  2408. (define (handle-system-error key . args)
  2409.   (let ((cep (current-error-port)))
  2410.     (cond ((not (stack? (fluid-ref the-last-stack))))
  2411.       ((memq 'backtrace (debug-options-interface))
  2412.        (run-hook before-backtrace-hook)
  2413.        (newline cep)
  2414.        (display "Backtrace:\n")
  2415.        (display-backtrace (fluid-ref the-last-stack) cep)
  2416.        (newline cep)
  2417.        (run-hook after-backtrace-hook)))
  2418.     (run-hook before-error-hook)
  2419.     (apply display-error (fluid-ref the-last-stack) cep args)
  2420.     (run-hook after-error-hook)
  2421.     (force-output cep)
  2422.     (throw 'abort key)))
  2423.  
  2424. (define (quit . args)
  2425.   (apply throw 'quit args))
  2426.  
  2427. (define exit quit)
  2428.  
  2429. ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
  2430.  
  2431. ;; Replaced by C code:
  2432. ;;(define (backtrace)
  2433. ;;  (if (fluid-ref the-last-stack)
  2434. ;;      (begin
  2435. ;;    (newline)
  2436. ;;    (display-backtrace (fluid-ref the-last-stack) (current-output-port))
  2437. ;;    (newline)
  2438. ;;    (if (and (not has-shown-backtrace-hint?)
  2439. ;;         (not (memq 'backtrace (debug-options-interface))))
  2440. ;;        (begin
  2441. ;;          (display
  2442. ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
  2443. ;;automatically if an error occurs in the future.\n")
  2444. ;;          (set! has-shown-backtrace-hint? #t))))
  2445. ;;      (display "No backtrace available.\n")))
  2446.  
  2447. (define (error-catching-repl r e p)
  2448.   (error-catching-loop
  2449.    (lambda ()
  2450.      (call-with-values (lambda () (e (r)))
  2451.        (lambda the-values (for-each p the-values))))))
  2452.  
  2453. (define (gc-run-time)
  2454.   (cdr (assq 'gc-time-taken (gc-stats))))
  2455.  
  2456. (define before-read-hook (make-hook))
  2457. (define after-read-hook (make-hook))
  2458. (define before-eval-hook (make-hook 1))
  2459. (define after-eval-hook (make-hook 1))
  2460. (define before-print-hook (make-hook 1))
  2461. (define after-print-hook (make-hook 1))
  2462.  
  2463. ;;; The default repl-reader function.  We may override this if we've
  2464. ;;; the readline library.
  2465. (define repl-reader
  2466.   (lambda (prompt)
  2467.     (display prompt)
  2468.     (force-output)
  2469.     (run-hook before-read-hook)
  2470.     (read (current-input-port))))
  2471.  
  2472. (define (scm-style-repl)
  2473.  
  2474.   (letrec (
  2475.        (start-gc-rt #f)
  2476.        (start-rt #f)
  2477.        (repl-report-start-timing (lambda ()
  2478.                        (set! start-gc-rt (gc-run-time))
  2479.                        (set! start-rt (get-internal-run-time))))
  2480.        (repl-report (lambda ()
  2481.               (display ";;; ")
  2482.               (display (inexact->exact
  2483.                     (* 1000 (/ (- (get-internal-run-time) start-rt)
  2484.                            internal-time-units-per-second))))
  2485.               (display "  msec  (")
  2486.               (display  (inexact->exact
  2487.                      (* 1000 (/ (- (gc-run-time) start-gc-rt)
  2488.                         internal-time-units-per-second))))
  2489.               (display " msec in gc)\n")))
  2490.  
  2491.        (consume-trailing-whitespace
  2492.         (lambda ()
  2493.           (let ((ch (peek-char)))
  2494.         (cond
  2495.          ((eof-object? ch))
  2496.          ((or (char=? ch #\space) (char=? ch #\tab))
  2497.           (read-char)
  2498.           (consume-trailing-whitespace))
  2499.          ((char=? ch #\newline)
  2500.           (read-char))))))
  2501.        (-read (lambda ()
  2502.             (let ((val
  2503.                (let ((prompt (cond ((string? scm-repl-prompt)
  2504.                         scm-repl-prompt)
  2505.                            ((thunk? scm-repl-prompt)
  2506.                         (scm-repl-prompt))
  2507.                            (scm-repl-prompt "> ")
  2508.                            (else ""))))
  2509.                  (repl-reader prompt))))
  2510.  
  2511.               ;; As described in R4RS, the READ procedure updates the
  2512.               ;; port to point to the first character past the end of
  2513.               ;; the external representation of the object.  This
  2514.               ;; means that it doesn't consume the newline typically
  2515.               ;; found after an expression.  This means that, when
  2516.               ;; debugging Guile with GDB, GDB gets the newline, which
  2517.               ;; it often interprets as a "continue" command, making
  2518.               ;; breakpoints kind of useless.  So, consume any
  2519.               ;; trailing newline here, as well as any whitespace
  2520.               ;; before it.
  2521.               ;; But not if EOF, for control-D.
  2522.               (if (not (eof-object? val))
  2523.               (consume-trailing-whitespace))
  2524.               (run-hook after-read-hook)
  2525.               (if (eof-object? val)
  2526.               (begin
  2527.                 (repl-report-start-timing)
  2528.                 (if scm-repl-verbose
  2529.                 (begin
  2530.                   (newline)
  2531.                   (display ";;; EOF -- quitting")
  2532.                   (newline)))
  2533.                 (quit 0)))
  2534.               val)))
  2535.  
  2536.        (-eval (lambda (sourc)
  2537.             (repl-report-start-timing)
  2538.             (run-hook before-eval-hook sourc)
  2539.             (let ((val (start-stack 'repl-stack
  2540.                         ;; If you change this procedure
  2541.                         ;; (primitive-eval), please also
  2542.                         ;; modify the repl-stack case in
  2543.                         ;; save-stack so that stack cutting
  2544.                         ;; continues to work.
  2545.                         (primitive-eval sourc))))
  2546.               (run-hook after-eval-hook sourc)
  2547.               val)))
  2548.  
  2549.  
  2550.        (-print (let ((maybe-print (lambda (result)
  2551.                     (if (or scm-repl-print-unspecified
  2552.                         (not (unspecified? result)))
  2553.                         (begin
  2554.                           (write result)
  2555.                           (newline))))))
  2556.              (lambda (result)
  2557.                (if (not scm-repl-silent)
  2558.                (begin
  2559.                  (run-hook before-print-hook result)
  2560.                  (maybe-print result)
  2561.                  (run-hook after-print-hook result)
  2562.                  (if scm-repl-verbose
  2563.                  (repl-report))
  2564.                  (force-output))))))
  2565.  
  2566.        (-quit (lambda (args)
  2567.             (if scm-repl-verbose
  2568.             (begin
  2569.               (display ";;; QUIT executed, repl exitting")
  2570.               (newline)
  2571.               (repl-report)))
  2572.             args))
  2573.  
  2574.        (-abort (lambda ()
  2575.              (if scm-repl-verbose
  2576.              (begin
  2577.                (display ";;; ABORT executed.")
  2578.                (newline)
  2579.                (repl-report)))
  2580.              (repl -read -eval -print))))
  2581.  
  2582.     (let ((status (error-catching-repl -read
  2583.                        -eval
  2584.                        -print)))
  2585.       (-quit status))))
  2586.  
  2587.  
  2588.  
  2589. ;;; {IOTA functions: generating lists of numbers}
  2590.  
  2591. (define (iota n)
  2592.   (let loop ((count (1- n)) (result '()))
  2593.     (if (< count 0) result
  2594.         (loop (1- count) (cons count result)))))
  2595.  
  2596.  
  2597. ;;; {While}
  2598. ;;;
  2599. ;;; with `continue' and `break'.
  2600. ;;;
  2601.  
  2602. (defmacro while (cond . body)
  2603.   `(letrec ((continue (lambda () (or (not ,cond) (begin (begin ,@ body) (continue)))))
  2604.         (break (lambda val (apply throw 'break val))))
  2605.      (catch 'break
  2606.         (lambda () (continue))
  2607.         (lambda v (cadr v)))))
  2608.  
  2609. ;;; {collect}
  2610. ;;;
  2611. ;;; Similar to `begin' but returns a list of the results of all constituent
  2612. ;;; forms instead of the result of the last form.
  2613. ;;; (The definition relies on the current left-to-right
  2614. ;;;  order of evaluation of operands in applications.)
  2615.  
  2616. (defmacro collect forms
  2617.   (cons 'list forms))
  2618.  
  2619. ;;; {with-fluids}
  2620.  
  2621. ;; with-fluids is a convenience wrapper for the builtin procedure
  2622. ;; `with-fluids*'.  The syntax is just like `let':
  2623. ;;
  2624. ;;  (with-fluids ((fluid val)
  2625. ;;                ...)
  2626. ;;     body)
  2627.  
  2628. (defmacro with-fluids (bindings . body)
  2629.   `(with-fluids* (list ,@(map car bindings)) (list ,@(map cadr bindings))
  2630.          (lambda () ,@body)))
  2631.  
  2632.  
  2633.  
  2634. ;;; {Macros}
  2635. ;;;
  2636.  
  2637. ;; actually....hobbit might be able to hack these with a little
  2638. ;; coaxing
  2639. ;;
  2640.  
  2641. (defmacro define-macro (first . rest)
  2642.   (let ((name (if (symbol? first) first (car first)))
  2643.     (transformer
  2644.      (if (symbol? first)
  2645.          (car rest)
  2646.          `(lambda ,(cdr first) ,@rest))))
  2647.     `(eval-case
  2648.       ((load-toplevel)
  2649.        (define ,name (defmacro:transformer ,transformer)))
  2650.       (else
  2651.        (error "define-macro can only be used at the top level")))))
  2652.  
  2653.  
  2654. (defmacro define-syntax-macro (first . rest)
  2655.   (let ((name (if (symbol? first) first (car first)))
  2656.     (transformer
  2657.      (if (symbol? first)
  2658.          (car rest)
  2659.          `(lambda ,(cdr first) ,@rest))))
  2660.     `(eval-case
  2661.       ((load-toplevel)
  2662.        (define ,name (defmacro:syntax-transformer ,transformer)))
  2663.       (else
  2664.        (error "define-syntax-macro can only be used at the top level")))))
  2665.  
  2666.  
  2667. ;;; {Module System Macros}
  2668. ;;;
  2669.  
  2670. ;; Return a list of expressions that evaluate to the appropriate
  2671. ;; arguments for resolve-interface according to SPEC.
  2672.  
  2673. (define (compile-interface-spec spec)
  2674.   (define (make-keyarg sym key quote?)
  2675.     (cond ((or (memq sym spec)
  2676.            (memq key spec))
  2677.        => (lambda (rest)
  2678.         (if quote?
  2679.             (list key (list 'quote (cadr rest)))
  2680.             (list key (cadr rest)))))
  2681.       (else
  2682.        '())))
  2683.   (define (map-apply func list)
  2684.     (map (lambda (args) (apply func args)) list))
  2685.   (define keys
  2686.     ;; sym     key      quote?
  2687.     '((:select #:select #t)
  2688.       (:renamer #:renamer #f)))
  2689.   (if (not (pair? (car spec)))
  2690.       `(',spec)
  2691.       `(',(car spec)
  2692.     ,@(apply append (map-apply make-keyarg keys)))))
  2693.  
  2694. (define (keyword-like-symbol->keyword sym)
  2695.   (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
  2696.  
  2697. (define (compile-define-module-args args)
  2698.   ;; Just quote everything except #:use-module and #:use-syntax.  We
  2699.   ;; need to know about all arguments regardless since we want to turn
  2700.   ;; symbols that look like keywords into real keywords, and the
  2701.   ;; keyword args in a define-module form are not regular
  2702.   ;; (i.e. no-backtrace doesn't take a value).
  2703.   (let loop ((compiled-args `((quote ,(car args))))
  2704.          (args (cdr args)))
  2705.     (cond ((null? args)
  2706.        (reverse! compiled-args))
  2707.       ;; symbol in keyword position
  2708.       ((symbol? (car args))
  2709.        (loop compiled-args
  2710.          (cons (keyword-like-symbol->keyword (car args)) (cdr args))))
  2711.       ((memq (car args) '(#:no-backtrace #:pure))
  2712.        (loop (cons (car args) compiled-args)
  2713.          (cdr args)))
  2714.       ((null? (cdr args))
  2715.        (error "keyword without value:" (car args)))
  2716.       ((memq (car args) '(#:use-module #:use-syntax))
  2717.        (loop (cons* `(list ,@(compile-interface-spec (cadr args)))
  2718.             (car args)
  2719.             compiled-args)
  2720.          (cddr args)))
  2721.       ((eq? (car args) #:autoload)
  2722.        (loop (cons* `(quote ,(caddr args))
  2723.             `(quote ,(cadr args))
  2724.             (car args)
  2725.             compiled-args)
  2726.          (cdddr args)))
  2727.       (else
  2728.        (loop (cons* `(quote ,(cadr args))
  2729.             (car args)
  2730.             compiled-args)
  2731.          (cddr args))))))
  2732.  
  2733. (defmacro define-module args
  2734.   `(eval-case
  2735.     ((load-toplevel)
  2736.      (let ((m (process-define-module
  2737.            (list ,@(compile-define-module-args args)))))
  2738.        (set-current-module m)
  2739.        m))
  2740.     (else
  2741.      (error "define-module can only be used at the top level"))))
  2742.  
  2743. ;; The guts of the use-modules macro.  Add the interfaces of the named
  2744. ;; modules to the use-list of the current module, in order.
  2745.  
  2746. (define (process-use-modules module-interface-args)
  2747.   (for-each (lambda (mif-args)
  2748.           (let ((mod-iface (apply resolve-interface mif-args)))
  2749.         (or mod-iface
  2750.             (error "no such module" mif-args))
  2751.         (module-use! (current-module) mod-iface)))
  2752.         module-interface-args))
  2753.  
  2754. (defmacro use-modules modules
  2755.   `(eval-case
  2756.     ((load-toplevel)
  2757.      (process-use-modules
  2758.       (list ,@(map (lambda (m)
  2759.              `(list ,@(compile-interface-spec m)))
  2760.            modules))))
  2761.     (else
  2762.      (error "use-modules can only be used at the top level"))))
  2763.  
  2764. (defmacro use-syntax (spec)
  2765.   `(eval-case
  2766.     ((load-toplevel)
  2767.      ,@(if (pair? spec)
  2768.        `((process-use-modules (list
  2769.                    (list ,@(compile-interface-spec spec))))
  2770.          (set-module-transformer! (current-module)
  2771.                       ,(car (last-pair spec))))
  2772.        `((set-module-transformer! (current-module) ,spec)))
  2773.      (fluid-set! scm:eval-transformer (module-transformer (current-module)))
  2774.      *unspecified*)
  2775.     (else
  2776.      (error "use-syntax can only be used at the top level"))))
  2777.  
  2778. (define define-private define)
  2779.  
  2780. (defmacro define-public args
  2781.   (define (syntax)
  2782.     (error "bad syntax" (list 'define-public args)))
  2783.   (define (defined-name n)
  2784.     (cond
  2785.      ((symbol? n) n)
  2786.      ((pair? n) (defined-name (car n)))
  2787.      (else (syntax))))
  2788.   (cond
  2789.    ((null? args)
  2790.     (syntax))
  2791.    (#t
  2792.     (let ((name (defined-name (car args))))
  2793.       `(begin
  2794.      (define-private ,@args)
  2795.      (eval-case ((load-toplevel) (export ,name))))))))
  2796.  
  2797. (defmacro defmacro-public args
  2798.   (define (syntax)
  2799.     (error "bad syntax" (list 'defmacro-public args)))
  2800.   (define (defined-name n)
  2801.     (cond
  2802.      ((symbol? n) n)
  2803.      (else (syntax))))
  2804.   (cond
  2805.    ((null? args)
  2806.     (syntax))
  2807.    (#t
  2808.     (let ((name (defined-name (car args))))
  2809.       `(begin
  2810.      (eval-case ((load-toplevel) (export ,name)))
  2811.      (defmacro ,@args))))))
  2812.  
  2813. ;; Export a local variable
  2814.  
  2815. ;; This function is called from "modules.c".  If you change it, be
  2816. ;; sure to update "modules.c" as well.
  2817.  
  2818. (define (module-export! m names)
  2819.   (let ((public-i (module-public-interface m)))
  2820.     (for-each (lambda (name)
  2821.         (begin-deprecated
  2822.          (if (not (module-local-variable m name))
  2823.              (let ((v (module-variable m name)))
  2824.                (cond
  2825.             (v
  2826.              (issue-deprecation-warning
  2827.               "Using `export' to re-export imported bindings is deprecated.  Use `re-export' instead.")
  2828.              (issue-deprecation-warning
  2829.               (simple-format #f "(You just re-exported `~a' from `~a'.)"
  2830.                      name (module-name m)))
  2831.              (module-define! m name (variable-ref v)))))))
  2832.         (let ((var (module-ensure-local-variable! m name)))
  2833.           (module-add! public-i name var)))
  2834.           names)))
  2835.  
  2836. ;; Re-export a imported variable
  2837. ;;
  2838. (define (module-re-export! m names)
  2839.   (let ((public-i (module-public-interface m)))
  2840.     (for-each (lambda (name)
  2841.         (let ((var (module-variable m name)))
  2842.           (cond ((not var)
  2843.              (error "Undefined variable:" name))
  2844.             ((eq? var (module-local-variable m name))
  2845.              (error "re-exporting local variable:" name))
  2846.             (else
  2847.              (module-add! public-i name var)))))
  2848.           names)))
  2849.  
  2850. (defmacro export names
  2851.   `(eval-case
  2852.     ((load-toplevel)
  2853.      (module-export! (current-module) ',names))
  2854.     (else
  2855.      (error "export can only be used at the top level"))))
  2856.  
  2857. (defmacro re-export names
  2858.   `(eval-case
  2859.     ((load-toplevel)
  2860.      (module-re-export! (current-module) ',names))
  2861.     (else
  2862.      (error "re-export can only be used at the top level"))))
  2863.  
  2864. (define export-syntax export)
  2865. (define re-export-syntax re-export)
  2866.  
  2867.  
  2868. (define load load-module)
  2869.  
  2870.  
  2871.  
  2872. ;;; {`cond-expand' for SRFI-0 support.}
  2873. ;;;
  2874. ;;; This syntactic form expands into different commands or
  2875. ;;; definitions, depending on the features provided by the Scheme
  2876. ;;; implementation.
  2877. ;;;
  2878. ;;; Syntax:
  2879. ;;;
  2880. ;;; <cond-expand>
  2881. ;;;   --> (cond-expand <cond-expand-clause>+)
  2882. ;;;     | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
  2883. ;;; <cond-expand-clause>
  2884. ;;;   --> (<feature-requirement> <command-or-definition>*)
  2885. ;;; <feature-requirement>
  2886. ;;;   --> <feature-identifier>
  2887. ;;;     | (and <feature-requirement>*)
  2888. ;;;     | (or <feature-requirement>*)
  2889. ;;;     | (not <feature-requirement>)
  2890. ;;; <feature-identifier>
  2891. ;;;   --> <a symbol which is the name or alias of a SRFI>
  2892. ;;;
  2893. ;;; Additionally, this implementation provides the
  2894. ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
  2895. ;;; determine the implementation type and the supported standard.
  2896. ;;;
  2897. ;;; Currently, the following feature identifiers are supported:
  2898. ;;;
  2899. ;;;   guile r5rs srfi-0 srfi-6
  2900. ;;;
  2901. ;;; Remember to update the features list when adding more SRFIs.
  2902.  
  2903. (define %cond-expand-features
  2904.   ;; Adjust the above comment when changing this.
  2905.   '(guile
  2906.     r5rs
  2907.     srfi-0   ;; cond-expand itself
  2908.     srfi-6   ;; open-input-string etc, in the guile core
  2909.     ))
  2910.  
  2911. ;; This table maps module public interfaces to the list of features.
  2912. ;;
  2913. (define %cond-expand-table (make-hash-table 31))
  2914.  
  2915. ;; Add one or more features to the `cond-expand' feature list of the
  2916. ;; module `module'.
  2917. ;;
  2918. (define (cond-expand-provide module features)
  2919.   (let ((mod (module-public-interface module)))
  2920.     (and mod
  2921.      (hashq-set! %cond-expand-table mod
  2922.              (append (hashq-ref %cond-expand-table mod '())
  2923.                  features)))))
  2924.  
  2925. (define cond-expand
  2926.   (procedure->memoizing-macro
  2927.    (lambda (exp env)
  2928.      (let ((clauses (cdr exp))
  2929.        (syntax-error (lambda (cl)
  2930.                (error "invalid clause in `cond-expand'" cl))))
  2931.        (letrec
  2932.        ((test-clause
  2933.          (lambda (clause)
  2934.            (cond
  2935.         ((symbol? clause)
  2936.          (or (memq clause %cond-expand-features)
  2937.              (let lp ((uses (module-uses (env-module env))))
  2938.                (if (pair? uses)
  2939.                (or (memq clause
  2940.                      (hashq-ref %cond-expand-table
  2941.                         (car uses) '()))
  2942.                    (lp (cdr uses)))
  2943.                #f))))
  2944.         ((pair? clause)
  2945.          (cond
  2946.           ((eq? 'and (car clause))
  2947.            (let lp ((l (cdr clause)))
  2948.              (cond ((null? l)
  2949.                 #t)
  2950.                ((pair? l)
  2951.                 (and (test-clause (car l)) (lp (cdr l))))
  2952.                (else
  2953.                 (syntax-error clause)))))
  2954.           ((eq? 'or (car clause))
  2955.            (let lp ((l (cdr clause)))
  2956.              (cond ((null? l)
  2957.                 #f)
  2958.                ((pair? l)
  2959.                 (or (test-clause (car l)) (lp (cdr l))))
  2960.                (else
  2961.                 (syntax-error clause)))))
  2962.           ((eq? 'not (car clause))
  2963.            (cond ((not (pair? (cdr clause)))
  2964.               (syntax-error clause))
  2965.              ((pair? (cddr clause))
  2966.               ((syntax-error clause))))
  2967.            (not (test-clause (cadr clause))))
  2968.           (else
  2969.            (syntax-error clause))))
  2970.         (else
  2971.          (syntax-error clause))))))
  2972.      (let lp ((c clauses))
  2973.        (cond
  2974.         ((null? c)
  2975.          (error "Unfulfilled `cond-expand'"))
  2976.         ((not (pair? c))
  2977.          (syntax-error c))
  2978.         ((not (pair? (car c)))
  2979.          (syntax-error (car c)))
  2980.         ((test-clause (caar c))
  2981.          `(begin ,@(cdar c)))
  2982.         ((eq? (caar c) 'else)
  2983.          (if (pair? (cdr c))
  2984.          (syntax-error c))
  2985.          `(begin ,@(cdar c)))
  2986.         (else
  2987.          (lp (cdr c))))))))))
  2988.  
  2989. ;; This procedure gets called from the startup code with a list of
  2990. ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
  2991. ;;
  2992. (define (use-srfis srfis)
  2993.   (let lp ((s srfis))
  2994.     (if (pair? s)
  2995.         (let* ((srfi (string->symbol
  2996.                       (string-append "srfi-" (number->string (car s)))))
  2997.                (mod-i (resolve-interface (list 'srfi srfi))))
  2998.           (module-use! (current-module) mod-i)
  2999.           (lp (cdr s))))))
  3000.  
  3001.  
  3002.  
  3003. ;;; {Load emacs interface support if emacs option is given.}
  3004.  
  3005. (define (named-module-use! user usee)
  3006.   (module-use! (resolve-module user) (resolve-interface usee)))
  3007.  
  3008. (define (load-emacs-interface)
  3009.   (and (provided? 'debug-extensions)
  3010.        (debug-enable 'backtrace))
  3011.   (named-module-use! '(guile-user) '(ice-9 emacs)))
  3012.  
  3013.  
  3014.  
  3015. (define using-readline?
  3016.   (let ((using-readline? (make-fluid)))
  3017.      (make-procedure-with-setter
  3018.       (lambda () (fluid-ref using-readline?))
  3019.       (lambda (v) (fluid-set! using-readline? v)))))
  3020.  
  3021. (define (top-repl)
  3022.   (let ((guile-user-module (resolve-module '(guile-user))))
  3023.  
  3024.     ;; Load emacs interface support if emacs option is given.
  3025.     (if (and (module-defined? guile-user-module 'use-emacs-interface)
  3026.          (module-ref guile-user-module 'use-emacs-interface))
  3027.     (load-emacs-interface))
  3028.  
  3029.     ;; Use some convenient modules (in reverse order)
  3030.  
  3031.     (if (provided? 'regex)
  3032.     (module-use! guile-user-module (resolve-interface '(ice-9 regex))))
  3033.     (if (provided? 'threads)
  3034.     (module-use! guile-user-module (resolve-interface '(ice-9 threads))))
  3035.     ;; load debugger on demand
  3036.     (module-use! guile-user-module
  3037.          (make-autoload-interface guile-user-module
  3038.                       '(ice-9 debugger) '(debug)))
  3039.     (module-use! guile-user-module (resolve-interface '(ice-9 session)))
  3040.     (module-use! guile-user-module (resolve-interface '(ice-9 debug)))
  3041.     ;; so that builtin bindings will be checked first
  3042.     (module-use! guile-user-module (resolve-interface '(guile)))
  3043.  
  3044.     (set-current-module guile-user-module)
  3045.  
  3046.     (let ((old-handlers #f)
  3047.       (signals (if (provided? 'posix)
  3048.                `((,SIGINT . "User interrupt")
  3049.              (,SIGFPE . "Arithmetic error")
  3050.              (,SIGBUS . "Bad memory access (bus error)")
  3051.              (,SIGSEGV
  3052.               . "Bad memory access (Segmentation violation)"))
  3053.                '())))
  3054.  
  3055.       (dynamic-wind
  3056.  
  3057.       ;; call at entry
  3058.       (lambda ()
  3059.         (let ((make-handler (lambda (msg)
  3060.                   (lambda (sig)
  3061.                     ;; Make a backup copy of the stack
  3062.                     (fluid-set! before-signal-stack
  3063.                         (fluid-ref the-last-stack))
  3064.                     (save-stack %deliver-signals)
  3065.                     (scm-error 'signal
  3066.                            #f
  3067.                            msg
  3068.                            #f
  3069.                            (list sig))))))
  3070.           (set! old-handlers
  3071.             (map (lambda (sig-msg)
  3072.                (sigaction (car sig-msg)
  3073.                       (make-handler (cdr sig-msg))))
  3074.              signals))))
  3075.  
  3076.       ;; the protected thunk.
  3077.       (lambda ()
  3078.         (let ((status (scm-style-repl)))
  3079.           (run-hook exit-hook)
  3080.           status))
  3081.  
  3082.       ;; call at exit.
  3083.       (lambda ()
  3084.         (map (lambda (sig-msg old-handler)
  3085.            (if (not (car old-handler))
  3086.                ;; restore original C handler.
  3087.                (sigaction (car sig-msg) #f)
  3088.                ;; restore Scheme handler, SIG_IGN or SIG_DFL.
  3089.                (sigaction (car sig-msg)
  3090.                   (car old-handler)
  3091.                   (cdr old-handler))))
  3092.          signals old-handlers))))))
  3093.  
  3094. (defmacro false-if-exception (expr)
  3095.   `(catch #t (lambda () ,expr)
  3096.       (lambda args #f)))
  3097.  
  3098. ;;; This hook is run at the very end of an interactive session.
  3099. ;;;
  3100. (define exit-hook (make-hook))
  3101.  
  3102.  
  3103. (append! %load-path (list "."))
  3104.  
  3105. ;; Place the user in the guile-user module.
  3106. ;;
  3107.  
  3108. (define-module (guile-user))
  3109.  
  3110. (begin-deprecated
  3111.  ;; automatic availability of this module is deprecated.
  3112.  (use-modules (ice-9 rdelim)))
  3113.  
  3114. ;;; boot-9.scm ends here
  3115.