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