compile occam-channel
[bpt/guile.git] / ice-9 / boot-9.scm
index f4089c8..be67560 100644 (file)
@@ -1,22 +1,23 @@
 ;;; installed-scm-file
 
-;;;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
+;;;; Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007
+;;;; Free Software Foundation, Inc.
 ;;;;
-;;;; This program is free software; you can redistribute it and/or modify
-;;;; it under the terms of the GNU General Public License as published by
-;;;; the Free Software Foundation; either version 2, or (at your option)
-;;;; any later version.
-;;;;
-;;;; This program is distributed in the hope that it will be useful,
+;;;; This library is free software; you can redistribute it and/or
+;;;; modify it under the terms of the GNU Lesser General Public
+;;;; License as published by the Free Software Foundation; either
+;;;; version 2.1 of the License, or (at your option) any later version.
+;;;; 
+;;;; This library is distributed in the hope that it will be useful,
 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
-;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-;;;; GNU General Public License for more details.
-;;;;
-;;;; You should have received a copy of the GNU General Public License
-;;;; along with this software; see the file COPYING.  If not, write to
-;;;; the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
-;;;; Boston, MA 02111-1307 USA
+;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;;;; Lesser General Public License for more details.
+;;;; 
+;;;; You should have received a copy of the GNU Lesser General Public
+;;;; License along with this library; if not, write to the Free Software
+;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ;;;;
+
 \f
 
 ;;; Commentary:
 ;;; Code:
 
 \f
-;;; {Deprecation}
-;;;
-
-;; We don't have macros here, but we do want to define
-;; `begin-deprecated' early.
 
-(define begin-deprecated
-  (procedure->memoizing-macro
-   (lambda (exp env)
-     (if (include-deprecated-features)
-        `(begin ,@(cdr exp))
-        `#f))))
-
-\f
 ;;; {Features}
-;;
+;;;
 
 (define (provide sym)
   (if (not (memq sym *features*))
       (set! *features* (cons sym *features*))))
 
-;;; Return #t iff FEATURE is available to this Guile interpreter.
-;;; In SLIB, provided? also checks to see if the module is available.
-;;; We should do that too, but don't.
+;; Return #t iff FEATURE is available to this Guile interpreter.  In SLIB,
+;; provided? also checks to see if the module is available.  We should do that
+;; too, but don't.
+
 (define (provided? feature)
   (and (memq feature *features*) #t))
 
-;;; presumably deprecated.
-(define feature? provided?)
+;; let format alias simple-format until the more complete version is loaded
 
-;;; let format alias simple-format until the more complete version is loaded
 (define format simple-format)
 
+;; this is scheme wrapping the C code so the final pred call is a tail call,
+;; per SRFI-13 spec
+(define (string-any char_pred s . rest)
+  (let ((start (if (null? rest)
+                  0 (car rest)))
+       (end   (if (or (null? rest) (null? (cdr rest)))
+                  (string-length s) (cadr rest))))
+    (if (and (procedure? char_pred)
+            (> end start)
+            (<= end (string-length s))) ;; let c-code handle range error
+       (or (string-any-c-code char_pred s start (1- end))
+           (char_pred (string-ref s (1- end))))
+       (string-any-c-code char_pred s start end))))
+
+;; this is scheme wrapping the C code so the final pred call is a tail call,
+;; per SRFI-13 spec
+(define (string-every char_pred s . rest)
+  (let ((start (if (null? rest)
+                  0 (car rest)))
+       (end   (if (or (null? rest) (null? (cdr rest)))
+                  (string-length s) (cadr rest))))
+    (if (and (procedure? char_pred)
+            (> end start)
+            (<= end (string-length s))) ;; let c-code handle range error
+       (and (string-every-c-code char_pred s start (1- end))
+            (char_pred (string-ref s (1- end))))
+       (string-every-c-code char_pred s start end))))
+
+;; A variant of string-fill! that we keep for compatability
+;;
+(define (substring-fill! str start end fill)
+  (string-fill! str fill start end))
+
+\f
+
+;;; {EVAL-CASE}
+;;;
+
+;; (eval-case ((situation*) forms)* (else forms)?)
+;;
+;; Evaluate certain code based on the situation that eval-case is used
+;; in. There are three situations defined. `load-toplevel' triggers for
+;; code evaluated at the top-level, for example from the REPL or when
+;; loading a file. `compile-toplevel' triggers for code compiled at the
+;; toplevel. `execute' triggers during execution of code not at the top
+;; level.
+
+(define eval-case
+  (procedure->memoizing-macro
+   (lambda (exp env)
+     (define (toplevel-env? env)
+       (or (not (pair? env)) (not (pair? (car env)))))
+     (define (syntax)
+       (error "syntax error in eval-case"))
+     (let loop ((clauses (cdr exp)))
+       (cond
+       ((null? clauses)
+        #f)
+       ((not (list? (car clauses)))
+        (syntax))
+       ((eq? 'else (caar clauses))
+        (or (null? (cdr clauses))
+            (syntax))
+        (cons 'begin (cdar clauses)))
+       ((not (list? (caar clauses)))
+        (syntax))
+       ((and (toplevel-env? env)
+             (memq 'load-toplevel (caar clauses)))
+        (cons 'begin (cdar clauses)))
+       (else
+        (loop (cdr clauses))))))))
+
+\f
+
+;; Before compiling, make sure any symbols are resolved in the (guile)
+;; module, the primary location of those symbols, rather than in
+;; (guile-user), the default module that we compile in.
+
+(eval-case
+ ((compile-toplevel)
+  (set-current-module (resolve-module '(guile)))))
+
+;;; {Defmacros}
+;;;
+;;; Depends on: features, eval-case
+;;;
+
+(define macro-table (make-weak-key-hash-table 61))
+(define xformer-table (make-weak-key-hash-table 61))
+
+(define (defmacro? m)  (hashq-ref macro-table m))
+(define (assert-defmacro?! m) (hashq-set! macro-table m #t))
+(define (defmacro-transformer m) (hashq-ref xformer-table m))
+(define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
+
+(define defmacro:transformer
+  (lambda (f)
+    (let* ((xform (lambda (exp env)
+                   (copy-tree (apply f (cdr exp)))))
+          (a (procedure->memoizing-macro xform)))
+      (assert-defmacro?! a)
+      (set-defmacro-transformer! a f)
+      a)))
+
+
+(define defmacro
+  (let ((defmacro-transformer
+         (lambda (name parms . body)
+           (let ((transformer `(lambda ,parms ,@body)))
+             `(eval-case
+                ((load-toplevel compile-toplevel)
+                 (define ,name (defmacro:transformer ,transformer)))
+               (else
+                (error "defmacro can only be used at the top level")))))))
+    (defmacro:transformer defmacro-transformer)))
+
+
+;; XXX - should the definition of the car really be looked up in the
+;; current module?
+
+(define (macroexpand-1 e)
+  (cond
+   ((pair? e) (let* ((a (car e))
+                    (val (and (symbol? a) (local-ref (list a)))))
+               (if (defmacro? val)
+                   (apply (defmacro-transformer val) (cdr e))
+                   e)))
+   (#t e)))
+
+(define (macroexpand e)
+  (cond
+   ((pair? e) (let* ((a (car e))
+                    (val (and (symbol? a) (local-ref (list a)))))
+               (if (defmacro? val)
+                   (macroexpand (apply (defmacro-transformer val) (cdr e)))
+                   e)))
+   (#t e)))
+
+(provide 'defmacro)
+
+\f
+
+;;; {Deprecation}
+;;;
+;;; Depends on: defmacro
+;;;
+
+(defmacro begin-deprecated forms
+  (if (include-deprecated-features)
+      `(begin ,@forms)
+      (begin)))
+
 \f
+
 ;;; {R4RS compliance}
+;;;
 
-(primitive-load-path "ice-9/r4rs.scm")
+(primitive-load-path "ice-9/r4rs")
 
 \f
-;;; {Simple Debugging Tools}
-;;
 
+;;; {Simple Debugging Tools}
+;;;
 
 ;; peek takes any number of arguments, writes them to the
 ;; current ouput port, and returns the last argument.
       (car (last-pair stuff)))))
 
 \f
+
 ;;; {Trivial Functions}
 ;;;
 
 (define (identity x) x)
-(define (1+ n) (+ n 1))
-(define (1- n) (+ n -1))
 (define (and=> value procedure) (and value (procedure value)))
-(define (make-hash-table k) (make-vector k '()))
-
-(begin-deprecated
- (define (id x)
-   (issue-deprecation-warning "`id' is deprecated.  Use `identity' instead.")
-   (identity x))
- (define (-1+ n)
-   (issue-deprecation-warning "`-1+' is deprecated.  Use `1-' instead.")
-   (1- n))
- (define (return-it . args)
-   (issue-deprecation-warning "`return-it' is deprecated.  Use `noop' instead.")
-   (apply noop args)))
+(define call/cc call-with-current-continuation)
 
 ;;; apply-to-args is functionally redundant with apply and, worse,
 ;;; is less general than apply since it only takes two arguments.
 
 (define (apply-to-args args fn) (apply fn args))
 
+(defmacro false-if-exception (expr)
+  `(catch #t (lambda () ,expr)
+         (lambda args #f)))
+
 \f
 
-;;; {Integer Math}
+;;; {General Properties}
 ;;;
 
-(define (ipow-by-squaring x k acc proc)
-  (cond ((zero? k) acc)
-       ((= 1 k) (proc acc x))
-       (else (ipow-by-squaring (proc x x)
-                               (quotient k 2)
-                               (if (even? k) acc (proc acc x))
-                               proc))))
+;; This is a more modern interface to properties.  It will replace all
+;; other property-like things eventually.
 
-(begin-deprecated
- (define (string-character-length s)
-   (issue-deprecation-warning "`string-character-length' is deprecated.  Use `string-length' instead.")
-   (string-length s))
- (define (flags . args)
-   (issue-deprecation-warning "`flags' is deprecated.  Use `logior' instead.")
-   (apply logior args)))
+(define (make-object-property)
+  (let ((prop (primitive-make-property #f)))
+    (make-procedure-with-setter
+     (lambda (obj) (primitive-property-ref prop obj))
+     (lambda (obj val) (primitive-property-set! prop obj val)))))
 
 \f
+
 ;;; {Symbol Properties}
 ;;;
 
     (if pair
        (symbol-pset! sym (delq! pair (symbol-pref sym))))))
 
-;;; {General Properties}
-;;;
-
-;; This is a more modern interface to properties.  It will replace all
-;; other property-like things eventually.
-
-(define (make-object-property)
-  (let ((prop (primitive-make-property #f)))
-    (make-procedure-with-setter
-     (lambda (obj) (primitive-property-ref prop obj))
-     (lambda (obj val) (primitive-property-set! prop obj val)))))
-
 \f
 
 ;;; {Arrays}
 ;;;
 
-(if (provided? 'array)
-    (primitive-load-path "ice-9/arrays.scm"))
+(define (array-shape a)
+  (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
+       (array-dimensions a)))
 
 \f
+
 ;;; {Keywords}
 ;;;
 
-(define (symbol->keyword symbol)
-  (make-keyword-from-dash-symbol (symbol-append '- symbol)))
-
-(define (keyword->symbol kw)
-  (let ((sym (symbol->string (keyword-dash-symbol kw))))
-    (string->symbol (substring sym 1 (string-length sym)))))
-
 (define (kw-arg-ref args kw)
   (let ((rem (member kw args)))
     (and rem (pair? (cdr rem)) (cadr rem))))
 \f
 
 ;;; {Structs}
+;;;
 
 (define (struct-layout s)
   (struct-ref (struct-vtable s) vtable-index-layout))
 
 \f
 
-;;; Environments
-
-(define the-environment
-  (procedure->syntax
-   (lambda (x e)
-     e)))
-
-(define the-root-environment (the-environment))
-
-(define (environment-module env)
-  (let ((closure (and (pair? env) (car (last-pair env)))))
-    (and closure (procedure-property closure 'module))))
-
-\f
 ;;; {Records}
 ;;;
 
 
 (define (record-constructor rtd . opt)
   (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
-    (local-eval `(lambda ,field-names
-                  (make-struct ',rtd 0 ,@(map (lambda (f)
-                                                (if (memq f field-names)
-                                                    f
-                                                    #f))
-                                              (record-type-fields rtd))))
-               the-root-environment)))
-
+    (primitive-eval
+     `(lambda ,field-names
+        (make-struct ',rtd 0 ,@(map (lambda (f)
+                                      (if (memq f field-names)
+                                          f
+                                          #f))
+                                    (record-type-fields rtd)))))))
+          
 (define (record-predicate rtd)
   (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
 
+(define (%record-type-error rtd obj)  ;; private helper
+  (or (eq? rtd (record-type-descriptor obj))
+      (scm-error 'wrong-type-arg "%record-type-check"
+                "Wrong type record (want `~S'): ~S"
+                (list (record-type-name rtd) obj)
+                #f)))
+
 (define (record-accessor rtd field-name)
-  (let* ((pos (list-index (record-type-fields rtd) field-name)))
+  (let ((pos (list-index (record-type-fields rtd) field-name)))
     (if (not pos)
        (error 'no-such-field field-name))
-    (local-eval `(lambda (obj)
-                  (and (eq? ',rtd (record-type-descriptor obj))
-                       (struct-ref obj ,pos)))
-               the-root-environment)))
+    (lambda (obj)
+      (if (eq? (struct-vtable obj) rtd)
+          (struct-ref obj pos)
+          (%record-type-error rtd obj)))))
 
 (define (record-modifier rtd field-name)
-  (let* ((pos (list-index (record-type-fields rtd) field-name)))
+  (let ((pos (list-index (record-type-fields rtd) field-name)))
     (if (not pos)
        (error 'no-such-field field-name))
-    (local-eval `(lambda (obj val)
-                  (and (eq? ',rtd (record-type-descriptor obj))
-                       (struct-set! obj ,pos val)))
-               the-root-environment)))
-
+    (lambda (obj val)
+      (if (eq? (struct-vtable obj) rtd)
+          (struct-set! obj pos val)
+          (%record-type-error rtd obj)))))
 
 (define (record? obj)
   (and (struct? obj) (record-type? (struct-vtable obj))))
 (provide 'record)
 
 \f
+
 ;;; {Booleans}
 ;;;
 
 (define (->bool x) (not (not x)))
 
 \f
+
 ;;; {Symbols}
 ;;;
 
   (string->symbol (apply string args)))
 
 \f
+
 ;;; {Lists}
 ;;;
 
             n
             (loop (+ n 1) (cdr l))))))
 
-(define (make-list n . init)
-  (if (pair? init) (set! init (car init)))
-  (let loop ((answer '())
-            (n n))
-    (if (<= n 0)
-       answer
-       (loop (cons init answer) (- n 1)))))
-
 \f
+
 ;;; {and-map and or-map}
 ;;;
 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
 \f
 
 (if (provided? 'posix)
-    (primitive-load-path "ice-9/posix.scm"))
+    (primitive-load-path "ice-9/posix"))
 
 (if (provided? 'socket)
-    (primitive-load-path "ice-9/networking.scm"))
+    (primitive-load-path "ice-9/networking"))
 
+;; For reference, Emacs file-exists-p uses stat in this same way.
+;; ENHANCE-ME: Catching an exception from stat is a bit wasteful, do this in
+;; C where all that's needed is to inspect the return from stat().
 (define file-exists?
   (if (provided? 'posix)
       (lambda (str)
-       (access? str F_OK))
+       (->bool (false-if-exception (stat str))))
       (lambda (str)
        (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
                           (lambda args #f))))
              #f)))))
 
 (define (has-suffix? str suffix)
-  (let ((sufl (string-length suffix))
-       (sl (string-length str)))
-    (and (> sl sufl)
-        (string=? (substring str (- sl sufl) sl) suffix))))
+  (string-suffix? suffix str))
+
+(define (system-error-errno args)
+  (if (eq? (car args) 'system-error)
+      (car (list-ref args 4))
+      #f))
 
 \f
+
 ;;; {Error Handling}
 ;;;
 
 (define (tms:cutime obj) (vector-ref obj 3))
 (define (tms:cstime obj) (vector-ref obj 4))
 
-(define (file-position . args) (apply ftell args))
-(define (file-set-position . args) (apply fseek args))
+(define file-position ftell)
+(define (file-set-position port offset . whence)
+  (let ((whence (if (eq? whence '()) SEEK_SET (car whence))))
+    (seek port offset whence)))
 
 (define (move->fdes fd/port fd)
   (cond ((integer? fd/port)
       (putenv (string-append name "=" value))
       (putenv name)))
 
+(define (unsetenv name)
+  "Remove the entry for NAME from the environment."
+  (putenv name))
+
 \f
+
 ;;; {Load Paths}
 ;;;
 
                   file)))
 
 \f
+
 ;;; {Help for scm_shell}
+;;;
 ;;; The argument-processing code used by Guile-based shells generates
 ;;; Scheme code based on the argument list.  This page contains help
 ;;; functions for the code it generates.
+;;;
 
 (define (command-line) (program-arguments))
 
 ;; This is mostly for the internal use of the code generated by
 ;; scm_compile_shell_switches.
+
+(define (turn-on-debugging)
+  (debug-enable 'debug)
+  (debug-enable 'backtrace)
+  (read-enable 'positions))
+
 (define (load-user-init)
   (let* ((home (or (getenv "HOME")
                   (false-if-exception (passwd:dir (getpwuid (getuid))))
        (primitive-load init-file))))
 
 \f
+
+;;; {The interpreter stack}
+;;;
+
+(defmacro start-stack (tag exp)
+  `(%start-stack ,tag (lambda () ,exp)))
+
+\f
+
 ;;; {Loading by paths}
+;;;
 
 ;;; Load a Scheme source file named NAME, searching for it in the
 ;;; directories listed in %load-path, and applying each of the file
 
 
 \f
+
 ;;; {Transcendental Functions}
 ;;;
 ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
 ;;; See the file `COPYING' for terms applying to this program.
 ;;;
 
-(define (exp z)
-  (if (real? z) ($exp z)
-      (make-polar ($exp (real-part z)) (imag-part z))))
-
-(define (log z)
-  (if (and (real? z) (>= z 0))
-      ($log z)
-      (make-rectangular ($log (magnitude z)) (angle z))))
-
-(define (sqrt z)
-  (if (real? z)
-      (if (negative? z) (make-rectangular 0 ($sqrt (- z)))
-         ($sqrt z))
-      (make-polar ($sqrt (magnitude z)) (/ (angle z) 2))))
-
 (define expt
   (let ((integer-expt integer-expt))
     (lambda (z1 z2)
-      (cond ((integer? z2)
-            (if (>= z2 0)
-                (integer-expt z1 z2)
-                (/ 1 (integer-expt z1 (- z2)))))
+      (cond ((and (exact? z2) (integer? z2))
+            (integer-expt z1 z2))
            ((and (real? z2) (real? z1) (>= z1 0))
             ($expt z1 z2))
            (else
          (/ (log (/ (- +i z) (+ +i z))) +2i))
       ($atan2 z (car y))))
 
-(define (log10 arg)
-  (/ (log arg) (log 10)))
-
 \f
 
 ;;; {Reader Extensions}
 ;;;
-
 ;;; Reader code for various "#c" forms.
 ;;;
 
 (read-hash-extend #\' (lambda (c port)
                        (read port)))
-(read-hash-extend #\. (lambda (c port)
-                       (eval (read port) (interaction-environment))))
+
+(define read-eval? (make-fluid))
+(fluid-set! read-eval? #f)
+(read-hash-extend #\.
+                  (lambda (c port)
+                    (if (fluid-ref read-eval?)
+                        (eval (read port) (interaction-environment))
+                        (error
+                         "#. read expansion found and read-eval? is #f."))))
 
 \f
+
 ;;; {Command Line Options}
 ;;;
 
                (left-part (string-append
                            (with-output-to-string
                              (lambda ()
-                               (map (lambda (x) (display (keyword-symbol x)) (display " "))
+                               (map (lambda (x) (display (keyword->symbol x)) (display " "))
                                     opts-proper)))
                            arg-name))
                (middle-part (if (and (< (string-length left-part) 30)
 ;;;
 ;;; These are the low level data structures for modules.
 ;;;
+;;; Every module object is of the type 'module-type', which is a record
+;;; consisting of the following members:
+;;;
+;;; - eval-closure: the function that defines for its module the strategy that
+;;;   shall be followed when looking up symbols in the module.
+;;;
+;;;   An eval-closure is a function taking two arguments: the symbol to be
+;;;   looked up and a boolean value telling whether a binding for the symbol
+;;;   should be created if it does not exist yet.  If the symbol lookup
+;;;   succeeded (either because an existing binding was found or because a new
+;;;   binding was created), a variable object representing the binding is
+;;;   returned.  Otherwise, the value #f is returned.  Note that the eval
+;;;   closure does not take the module to be searched as an argument: During
+;;;   construction of the eval-closure, the eval-closure has to store the
+;;;   module it belongs to in its environment.  This means, that any
+;;;   eval-closure can belong to only one module.
+;;;
+;;;   The eval-closure of a module can be defined arbitrarily.  However, three
+;;;   special cases of eval-closures are to be distinguished: During startup
+;;;   the module system is not yet activated.  In this phase, no modules are
+;;;   defined and all bindings are automatically stored by the system in the
+;;;   pre-modules-obarray.  Since no eval-closures exist at this time, the
+;;;   functions which require an eval-closure as their argument need to be
+;;;   passed the value #f.
+;;;
+;;;   The other two special cases of eval-closures are the
+;;;   standard-eval-closure and the standard-interface-eval-closure.  Both
+;;;   behave equally for the case that no new binding is to be created.  The
+;;;   difference between the two comes in, when the boolean argument to the
+;;;   eval-closure indicates that a new binding shall be created if it is not
+;;;   found.
+;;;
+;;;   Given that no new binding shall be created, both standard eval-closures
+;;;   define the following standard strategy of searching bindings in the
+;;;   module: First, the module's obarray is searched for the symbol.  Second,
+;;;   if no binding for the symbol was found in the module's obarray, the
+;;;   module's binder procedure is exececuted.  If this procedure did not
+;;;   return a binding for the symbol, the modules referenced in the module's
+;;;   uses list are recursively searched for a binding of the symbol.  If the
+;;;   binding can not be found in these modules also, the symbol lookup has
+;;;   failed.
+;;;
+;;;   If a new binding shall be created, the standard-interface-eval-closure
+;;;   immediately returns indicating failure.  That is, it does not even try
+;;;   to look up the symbol.  In contrast, the standard-eval-closure would
+;;;   first search the obarray, and if no binding was found there, would
+;;;   create a new binding in the obarray, therefore not calling the binder
+;;;   procedure or searching the modules in the uses list.
+;;;
+;;;   The explanation of the following members obarray, binder and uses
+;;;   assumes that the symbol lookup follows the strategy that is defined in
+;;;   the standard-eval-closure and the standard-interface-eval-closure.
+;;;
+;;; - obarray: a hash table that maps symbols to variable objects.  In this
+;;;   hash table, the definitions are found that are local to the module (that
+;;;   is, not imported from other modules).  When looking up bindings in the
+;;;   module, this hash table is searched first.
+;;;
+;;; - binder: either #f or a function taking a module and a symbol argument.
+;;;   If it is a function it is called after the obarray has been
+;;;   unsuccessfully searched for a binding.  It then can provide bindings
+;;;   that would otherwise not be found locally in the module.
+;;;
+;;; - uses: a list of modules from which non-local bindings can be inherited.
+;;;   These modules are the third place queried for bindings after the obarray
+;;;   has been unsuccessfully searched and the binder function did not deliver
+;;;   a result either.
+;;;
+;;; - transformer: either #f or a function taking a scheme expression as
+;;;   delivered by read.  If it is a function, it will be called to perform
+;;;   syntax transformations (e. g. makro expansion) on the given scheme
+;;;   expression. The output of the transformer function will then be passed
+;;;   to Guile's internal memoizer.  This means that the output must be valid
+;;;   scheme code.  The only exception is, that the output may make use of the
+;;;   syntax extensions provided to identify the modules that a binding
+;;;   belongs to.
+;;;
+;;; - name: the name of the module.  This is used for all kinds of printing
+;;;   outputs.  In certain places the module name also serves as a way of
+;;;   identification.  When adding a module to the uses list of another
+;;;   module, it is made sure that the new uses list will not contain two
+;;;   modules of the same name.
+;;;
+;;; - kind: classification of the kind of module.  The value is (currently?)
+;;;   only used for printing.  It has no influence on how a module is treated.
+;;;   Currently the following values are used when setting the module kind:
+;;;   'module, 'directory, 'interface, 'custom-interface.  If no explicit kind
+;;;   is set, it defaults to 'module.
+;;;
+;;; - duplicates-handlers: a list of procedures that get called to make a
+;;;   choice between two duplicate bindings when name clashes occur.  See the
+;;;   `duplicate-handlers' global variable below.
+;;;
+;;; - observers: a list of procedures that get called when the module is
+;;;   modified.
+;;;
+;;; - weak-observers: a weak-key hash table of procedures that get called
+;;;   when the module is modified.  See `module-observe-weak' for details.
+;;;
+;;; In addition, the module may (must?) contain a binding for
+;;; `%module-public-interface'.  This variable should be bound to a module
+;;; representing the exported interface of a module.  See the
+;;; `module-public-interface' and `module-export!' procedures.
+;;;
 ;;; !!! warning: The interface to lazy binder procedures is going
 ;;; to be changed in an incompatible way to permit all the basic
 ;;; module ops to be virtualized.
 ;;;
 
 \f
+
 ;;; {Printing Modules}
+;;;
+
 ;; This is how modules are printed.  You can re-define it.
 ;; (Redefining is actually more complicated than simply redefining
 ;; %print-module because that would only change the binding and not
 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
 ;; bindings that would otherwise not be found locally in the module.
 ;;
-;; NOTE: If you change here, you also need to change libguile/modules.h.
+;; NOTE: If you change anything here, you also need to change
+;; libguile/modules.h.
 ;;
 (define module-type
   (make-record-type 'module
                    '(obarray uses binder eval-closure transformer name kind
-                             observers weak-observers observer-id)
+                     duplicates-handlers import-obarray
+                     observers weak-observers)
                    %print-module))
 
 ;; make-module &opt size uses binder
            (list-ref args index)
            default))
 
+      (define %default-import-size
+        ;; Typical number of imported bindings actually used by a module.
+        600)
+
       (if (> (length args) 3)
          (error "Too many args to make-module." args))
 
-      (let ((size (parse-arg 0 1021))
+      (let ((size (parse-arg 0 31))
            (uses (parse-arg 1 '()))
            (binder (parse-arg 2 #f)))
 
            (error
             "Lazy-binder expected to be a procedure or #f." binder))
 
-       (let ((module (module-constructor (make-vector size '())
-                                         uses binder #f #f #f #f
+       (let ((module (module-constructor (make-hash-table size)
+                                         uses binder #f #f #f #f #f
+                                         (make-hash-table %default-import-size)
                                          '()
-                                         (make-weak-value-hash-table 31)
-                                         0)))
+                                         (make-weak-key-hash-table 31))))
 
          ;; We can't pass this as an argument to module-constructor,
          ;; because we need it to close over a pointer to the module
 (define set-module-name! (record-modifier module-type 'name))
 (define module-kind (record-accessor module-type 'kind))
 (define set-module-kind! (record-modifier module-type 'kind))
+(define module-duplicates-handlers
+  (record-accessor module-type 'duplicates-handlers))
+(define set-module-duplicates-handlers!
+  (record-modifier module-type 'duplicates-handlers))
 (define module-observers (record-accessor module-type 'observers))
 (define set-module-observers! (record-modifier module-type 'observers))
 (define module-weak-observers (record-accessor module-type 'weak-observers))
-(define module-observer-id (record-accessor module-type 'observer-id))
-(define set-module-observer-id! (record-modifier module-type 'observer-id))
 (define module? (record-predicate module-type))
 
+(define module-import-obarray (record-accessor module-type 'import-obarray))
+
 (define set-module-eval-closure!
   (let ((setter (record-modifier module-type 'eval-closure)))
     (lambda (module closure)
       ;; to maximally one module.
       (set-procedure-property! closure 'module module))))
 
-(begin-deprecated
- (define (eval-in-module exp mod)
-   (issue-deprecation-warning
-    "`eval-in-module' is deprecated.  Use `eval' instead.")
-   (eval exp mod)))
-
 \f
+
 ;;; {Observer protocol}
 ;;;
 
   (set-module-observers! module (cons proc (module-observers module)))
   (cons module proc))
 
-(define (module-observe-weak module proc)
-  (let ((id (module-observer-id module)))
-    (hash-set! (module-weak-observers module) id proc)
-    (set-module-observer-id! module (+ 1 id))
-    (cons module id)))
+(define (module-observe-weak module observer-id . proc)
+  ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
+  ;; be any Scheme object).  PROC is invoked and passed MODULE any time
+  ;; MODULE is modified.  PROC gets unregistered when OBSERVER-ID gets GC'd
+  ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
+  ;; for instance).
+
+  ;; The two-argument version is kept for backward compatibility: when called
+  ;; with two arguments, the observer gets unregistered when closure PROC
+  ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
+
+  (let ((proc (if (null? proc) observer-id (car proc))))
+    (hashq-set! (module-weak-observers module) observer-id proc)))
 
 (define (module-unobserve token)
   (let ((module (car token))
        (set-module-observers! module (delq1! id (module-observers module)))))
   *unspecified*)
 
+(define module-defer-observers #f)
+(define module-defer-observers-mutex (make-mutex))
+(define module-defer-observers-table (make-hash-table))
+
 (define (module-modified m)
+  (if module-defer-observers
+      (hash-set! module-defer-observers-table m #t)
+      (module-call-observers m)))
+
+;;; This function can be used to delay calls to observers so that they
+;;; can be called once only in the face of massive updating of modules.
+;;;
+(define (call-with-deferred-observers thunk)
+  (dynamic-wind
+      (lambda ()
+       (lock-mutex module-defer-observers-mutex)
+       (set! module-defer-observers #t))
+      thunk
+      (lambda ()
+       (set! module-defer-observers #f)
+       (hash-for-each (lambda (m dummy)
+                        (module-call-observers m))
+                      module-defer-observers-table)
+       (hash-clear! module-defer-observers-table)
+       (unlock-mutex module-defer-observers-mutex))))
+
+(define (module-call-observers m)
   (for-each (lambda (proc) (proc m)) (module-observers m))
-  (hash-fold (lambda (id proc res) (proc m)) #f (module-weak-observers m)))
+
+  ;; We assume that weak observers don't (un)register themselves as they are
+  ;; called since this would preclude proper iteration over the hash table
+  ;; elements.
+  (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
 
 \f
+
 ;;; {Module Searching in General}
 ;;;
 ;;; We sometimes want to look for properties of a symbol
 ;;;
 ;;; If the symbol is not found at all, return #f.
 ;;;
-(define (module-local-variable m v)
-;  (caddr
-;   (list m v
-        (let ((b (module-obarray-ref (module-obarray m) v)))
-          (or (and (variable? b) b)
-              (and (module-binder m)
-                   ((module-binder m) m v #f)))))
-;))
-
-;; module-variable module symbol
-;;
-;; like module-local-variable, except search the uses in the
-;; case V is not found in M.
-;;
-;; NOTE: This function is superseded with C code (see modules.c)
-;;;      when using the standard eval closure.
-;;
-(define (module-variable m v)
-  (module-search module-local-variable m v))
-
+;;; (This is now written in C, see `modules.c'.)
+;;;
 
 ;;; {Mapping modules x symbols --> bindings}
 ;;;
 ;;
 (define (module-symbol-local-binding m v . opt-val)
   (let ((var (module-local-variable m v)))
-    (if var
+    (if (and var (variable-bound? var))
        (variable-ref var)
        (if (not (null? opt-val))
            (car opt-val)
 ;;
 (define (module-symbol-binding m v . opt-val)
   (let ((var (module-variable m v)))
-    (if var
+    (if (and var (variable-bound? var))
        (variable-ref var)
        (if (not (null? opt-val))
            (car opt-val)
 
 
 \f
+
 ;;; {Adding Variables to Modules}
 ;;;
-;;;
-
 
 ;; module-make-local-var! module symbol
 ;;
 ;; If no variable was already there, then create a new and uninitialzied
 ;; variable.
 ;;
+;; This function is used in modules.c.
+;;
 (define (module-make-local-var! m v)
   (or (let ((b (module-obarray-ref (module-obarray m) v)))
        (and (variable? b)
             (begin
+              ;; Mark as modified since this function is called when
+              ;; the standard eval closure defines a binding
               (module-modified m)
               b)))
-      (and (module-binder m)
-          ((module-binder m) m v #t))
-      (begin
-       (let ((answer (make-undefined-variable)))
-         (variable-set-name-hint! answer v)
-         (module-obarray-set! (module-obarray m) v answer)
-         (module-modified m)
-         answer))))
+
+      ;; Create a new local variable.
+      (let ((local-var (make-undefined-variable)))
+        (module-add! m v local-var)
+        local-var)))
+
+;; module-ensure-local-variable! module symbol
+;;
+;; Ensure that there is a local variable in MODULE for SYMBOL.  If
+;; there is no binding for SYMBOL, create a new uninitialized
+;; variable.  Return the local variable.
+;;
+(define (module-ensure-local-variable! module symbol)
+  (or (module-local-variable module symbol)
+      (let ((var (make-undefined-variable)))
+       (module-add! module symbol var)
+       var)))
 
 ;; module-add! module symbol var
 ;;
 ;; make sure that a symbol is undefined in the local namespace of M.
 ;;
 (define (module-remove! m v)
-  (module-obarray-remove!  (module-obarray m) v)
+  (module-obarray-remove! (module-obarray m) v)
   (module-modified m))
 
 (define (module-clear! m)
-  (vector-fill! (module-obarray m) '())
+  (hash-clear! (module-obarray m))
   (module-modified m))
 
 ;; MODULE-FOR-EACH -- exported
 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
 ;;
 (define (module-for-each proc module)
-  (let ((obarray (module-obarray module)))
-    (do ((index 0 (+ index 1))
-        (end (vector-length obarray)))
-       ((= index end))
-      (for-each
-       (lambda (bucket)
-        (proc (car bucket) (cdr bucket)))
-       (vector-ref obarray index)))))
-
+  (hash-for-each proc (module-obarray module)))
 
 (define (module-map proc module)
-  (let* ((obarray (module-obarray module))
-        (end (vector-length obarray)))
-
-    (let loop ((i 0)
-              (answer '()))
-      (if (= i end)
-         answer
-         (loop (+ 1 i)
-               (append!
-                (map (lambda (bucket)
-                       (proc (car bucket) (cdr bucket)))
-                     (vector-ref obarray i))
-                answer))))))
+  (hash-map->list proc (module-obarray module)))
+
 \f
 
 ;;; {Low Level Bootstrapping}
 
 
 \f
+
 ;;; {Module-based Loading}
 ;;;
 
 
 (define basic-load load)
 
-(define (load-module filename)
+(define (load-module filename . reader)
   (save-module-excursion
    (lambda ()
      (let ((oldname (and (current-load-port)
                         (port-filename (current-load-port)))))
-       (basic-load (if (and oldname
-                           (> (string-length filename) 0)
-                           (not (char=? (string-ref filename 0) #\/))
-                           (not (string=? (dirname oldname) ".")))
-                      (string-append (dirname oldname) "/" filename)
-                      filename))))))
+       (apply basic-load
+             (if (and oldname
+                      (> (string-length filename) 0)
+                      (not (char=? (string-ref filename 0) #\/))
+                      (not (string=? (dirname oldname) ".")))
+                 (string-append (dirname oldname) "/" filename)
+                 filename)
+             reader)))))
 
 
 \f
+
 ;;; {MODULE-REF -- exported}
-;;
+;;;
+
 ;; Returns the value of a variable called NAME in MODULE or any of its
 ;; used modules.  If there is no such variable, then if the optional third
 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
          (variable-set! variable value)
          (module-modified module))
        (let ((variable (make-variable value)))
-         (variable-set-name-hint! variable name)
          (module-add! module name variable)))))
 
 ;; MODULE-DEFINED? -- exported
 ;; Add INTERFACE to the list of interfaces used by MODULE.
 ;;
 (define (module-use! module interface)
+  (if (not (eq? module interface))
+      (begin
+        ;; Newly used modules must be appended rather than consed, so that
+        ;; `module-variable' traverses the use list starting from the first
+        ;; used module.
+        (set-module-uses! module
+                          (append (filter (lambda (m)
+                                            (not
+                                             (equal? (module-name m)
+                                                     (module-name interface))))
+                                          (module-uses module))
+                                  (list interface)))
+
+        (module-modified module))))
+
+;; MODULE-USE-INTERFACES! module interfaces
+;;
+;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
+;;
+(define (module-use-interfaces! module interfaces)
   (set-module-uses! module
-                   (cons interface (delq! interface (module-uses module))))
+                    (append (module-uses module) interfaces))
   (module-modified module))
 
 \f
+
 ;;; {Recursive Namespaces}
 ;;;
-;;;
 ;;; A hierarchical namespace emerges if we consider some module to be
 ;;; root, and variables bound to modules as nested namespaces.
 ;;;
 
 
 \f
-;;; {The (app) module}
+
+;;; {The (%app) module}
 ;;;
 ;;; The root of conventionally named objects not directly in the top level.
 ;;;
-;;; (app modules)
-;;; (app modules guile)
+;;; (%app modules)
+;;; (%app modules guile)
 ;;;
 ;;; The directory of all modules and the standard root module.
 ;;;
 
-(define (module-public-interface m)
-  (module-ref m '%module-public-interface #f))
+;; module-public-interface is defined in C.
 (define (set-module-public-interface! m i)
   (module-define! m '%module-public-interface i))
 (define (set-system-module! m s)
 (define (make-modules-in module name)
   (if (null? name)
       module
-      (cond
-       ((module-ref module (car name) #f)
-       => (lambda (m) (make-modules-in m (cdr name))))
-       (else   (let ((m (make-module 31)))
-                 (set-module-kind! m 'directory)
-                 (set-module-name! m (append (or (module-name module)
-                                                 '())
-                                             (list (car name))))
-                 (module-define! module (car name) m)
-                 (make-modules-in m (cdr name)))))))
+      (make-modules-in
+       (let* ((var (module-local-variable module (car name)))
+              (val (and var (variable-bound? var) (variable-ref var))))
+         (if (module? val)
+             val
+             (let ((m (make-module 31)))
+               (set-module-kind! m 'directory)
+               (set-module-name! m (append (or (module-name module) '())
+                                           (list (car name))))
+               (module-define! module (car name) m)
+               m)))
+       (cdr name))))
 
 (define (beautify-user-module! module)
   (let ((interface (module-public-interface module)))
          (set-module-public-interface! module interface))))
   (if (and (not (memq the-scm-module (module-uses module)))
           (not (eq? module the-root-module)))
-      (set-module-uses! module (append (module-uses module) (list the-scm-module)))))
+      ;; Import the default set of bindings (from the SCM module) in MODULE.
+      (module-use! module the-scm-module)))
 
 ;; NOTE: This binding is used in libguile/modules.c.
 ;;
-(define (resolve-module name . maybe-autoload)
-  (let ((full-name (append '(app modules) name)))
-    (let ((already (local-ref full-name)))
-      (if already
-         ;; The module already exists...
-         (if (and (or (null? maybe-autoload) (car maybe-autoload))
-                  (not (module-public-interface already)))
-             ;; ...but we are told to load and it doesn't contain source, so
-             (begin
-               (try-load-module name)
-               already)
-             ;; simply return it.
-             already)
-         (begin
-           ;; Try to autoload it if we are told so
-           (if (or (null? maybe-autoload) (car maybe-autoload))
-               (try-load-module name))
-           ;; Get/create it.
-           (make-modules-in (current-module) full-name))))))
+(define resolve-module
+  (let ((the-root-module the-root-module))
+    (lambda (name . maybe-autoload)
+      (if (equal? name '(guile))
+          the-root-module
+          (let ((full-name (append '(%app modules) name)))
+            (let ((already (nested-ref the-root-module full-name))
+                  (autoload (or (null? maybe-autoload) (car maybe-autoload))))
+              (cond
+               ((and already (module? already)
+                     (or (not autoload) (module-public-interface already)))
+                ;; A hit, a palpable hit.
+                already)
+               (autoload
+                ;; Try to autoload the module, and recurse.
+                (try-load-module name)
+                (resolve-module name #f))
+               (else
+                ;; A module is not bound (but maybe something else is),
+                ;; we're not autoloading -- here's the weird semantics,
+                ;; we create an empty module.
+                (make-modules-in the-root-module full-name)))))))))
 
 ;; Cheat.  These bindings are needed by modules.c, but we don't want
 ;; to move their real definition here because that would be unnatural.
 (define process-define-module #f)
 (define process-use-modules #f)
 (define module-export! #f)
+(define default-duplicate-binding-procedures #f)
+
+(define %app (make-module 31))
+(define app %app) ;; for backwards compatability
+
+(local-define '(%app modules) (make-module 31))
+(local-define '(%app modules guile) the-root-module)
 
 ;; This boots the module system.  All bindings needed by modules.c
 ;; must have been defined by now.
 ;;
 (set-current-module the-root-module)
 
-(define app (make-module 31))
-(local-define '(app modules) (make-module 31))
-(local-define '(app modules guile) the-root-module)
-
-;; (define-special-value '(app modules new-ws) (lambda () (make-scm-module)))
+;; (define-special-value '(%app modules new-ws) (lambda () (make-scm-module)))
 
 (define (try-load-module name)
-  (or (try-module-linked name)
+  (or (begin-deprecated (try-module-linked name))
       (try-module-autoload name)
-      (try-module-dynamic-link name)))
+      (begin-deprecated (try-module-dynamic-link name))))
 
 (define (purify-module! module)
   "Removes bindings in MODULE which are inherited from the (guile) module."
             (eq? (car (last-pair use-list)) the-scm-module))
        (set-module-uses! module (reverse (cdr (reverse use-list)))))))
 
-;; Return a module interface made from SPEC.
-;; SPEC can be a list of symbols, in which case it names a module
-;; whose public interface is found and returned.
-;;
-;; SPEC can also be of the form:
-;;  (MODULE-NAME [:select SELECTION] [:rename RENAMER])
-;; in which case a partial interface is newly created and returned.
-;; MODULE-NAME is a list of symbols, as above; SELECTION is a list of
-;; binding-specs to be imported; and RENAMER is a procedure that takes a
-;; symbol and returns its new name.  A binding-spec is either a symbol or a
-;; pair of symbols (ORIG . SEEN), where ORIG is the name in the used module
-;; and SEEN is the name in the using module.  Note that SEEN is also passed
-;; through RENAMER.
-;;
-;; The `:select' and `:rename' clauses are optional.  If both are omitted, the
-;; returned interface has no bindings.  If the `:select' clause is omitted,
-;; RENAMER operates on the used module's public interface.
-;;
-;; Signal "no code for module" error if module name is not resolvable or its
-;; public interface is not available.  Signal "no binding" error if selected
-;; binding does not exist in the used module.
-;;
-(define (resolve-interface spec)
-  (let* ((simple? (not (pair? (car spec))))
-         (name (if simple? spec (car spec)))
+;; Return a module that is an interface to the module designated by
+;; NAME.
+;;
+;; `resolve-interface' takes four keyword arguments:
+;;
+;;   #:select SELECTION
+;;
+;; SELECTION is a list of binding-specs to be imported; A binding-spec
+;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
+;; is the name in the used module and SEEN is the name in the using
+;; module.  Note that SEEN is also passed through RENAMER, below.  The
+;; default is to select all bindings.  If you specify no selection but
+;; a renamer, only the bindings that already exist in the used module
+;; are made available in the interface.  Bindings that are added later
+;; are not picked up.
+;;
+;;   #:hide BINDINGS
+;;
+;; BINDINGS is a list of bindings which should not be imported.
+;;
+;;   #:prefix PREFIX
+;;
+;; PREFIX is a symbol that will be appended to each exported name.
+;; The default is to not perform any renaming.
+;;
+;;   #:renamer RENAMER
+;;
+;; RENAMER is a procedure that takes a symbol and returns its new
+;; name.  The default is not perform any renaming.
+;;
+;; Signal "no code for module" error if module name is not resolvable
+;; or its public interface is not available.  Signal "no binding"
+;; error if selected binding does not exist in the used module.
+;;
+(define (resolve-interface name . args)
+
+  (define (get-keyword-arg args kw def)
+    (cond ((memq kw args)
+          => (lambda (kw-arg)
+               (if (null? (cdr kw-arg))
+                   (error "keyword without value: " kw))
+               (cadr kw-arg)))
+         (else
+          def)))
+
+  (let* ((select (get-keyword-arg args #:select #f))
+        (hide (get-keyword-arg args #:hide '()))
+        (renamer (or (get-keyword-arg args #:renamer #f)
+                     (let ((prefix (get-keyword-arg args #:prefix #f)))
+                       (and prefix (symbol-prefix-proc prefix)))
+                     identity))
          (module (resolve-module name))
          (public-i (and module (module-public-interface module))))
     (and (or (not module) (not public-i))
          (error "no code for module" name))
-    (if simple?
+    (if (and (not select) (null? hide) (eq? renamer identity))
         public-i
-        (let ((selection (cond ((memq ':select spec) => cadr)
-                               (else (module-map (lambda (sym var) sym)
-                                                 public-i))))
-              (rename (cond ((memq ':rename spec)
-                             => (lambda (x)
-                                  ;; fixme:ttn -- move to macroexpansion time
-                                  (eval (cadr x) (current-module))))
-                            (else identity)))
+        (let ((selection (or select (module-map (lambda (sym var) sym)
+                                               public-i)))
               (custom-i (make-module 31)))
-          (set-module-kind! custom-i 'interface)
-          (for-each (lambda (bspec)
-                      (let* ((direct? (symbol? bspec))
-                             (orig (if direct? bspec (car bspec)))
-                             (seen (if direct? bspec (cdr bspec))))
-                        (module-add! custom-i (rename seen)
-                                     (or (module-local-variable module orig)
-                                         (error
-                                          ;; fixme: format manually for now
-                                          (simple-format
-                                           #f "no binding `~A' in module ~A"
-                                           orig name))))))
-                    selection)
+          (set-module-kind! custom-i 'custom-interface)
+         (set-module-name! custom-i name)
+         ;; XXX - should use a lazy binder so that changes to the
+         ;; used module are picked up automatically.
+         (for-each (lambda (bspec)
+                     (let* ((direct? (symbol? bspec))
+                            (orig (if direct? bspec (car bspec)))
+                            (seen (if direct? bspec (cdr bspec)))
+                            (var (or (module-local-variable public-i orig)
+                                     (module-local-variable module orig)
+                                     (error
+                                      ;; fixme: format manually for now
+                                      (simple-format
+                                       #f "no binding `~A' in module ~A"
+                                       orig name)))))
+                       (if (memq orig hide)
+                           (set! hide (delq! orig hide))
+                           (module-add! custom-i
+                                        (renamer seen)
+                                        var))))
+                   selection)
+         ;; Check that we are not hiding bindings which don't exist
+         (for-each (lambda (binding)
+                     (if (not (module-local-variable public-i binding))
+                         (error
+                          (simple-format
+                           #f "no binding `~A' to hide in module ~A"
+                           binding name))))
+                   hide)
           custom-i))))
 
 (define (symbol-prefix-proc prefix)
   (lambda (symbol)
     (symbol-append prefix symbol)))
 
+;; This function is called from "modules.c".  If you change it, be
+;; sure to update "modules.c" as well.
+
 (define (process-define-module args)
   (let* ((module-id (car args))
          (module (resolve-module module-id #f))
                          (error "unrecognized define-module argument" arg))))
     (beautify-user-module! module)
     (let loop ((kws kws)
-              (reversed-interfaces '())
-              (exports '()))
+               (reversed-interfaces '())
+               (exports '())
+               (re-exports '())
+               (replacements '())
+               (autoloads '()))
+
       (if (null? kws)
-         (begin
-           (for-each (lambda (interface)
-                       (module-use! module interface))
-                     (reverse reversed-interfaces))
-           (module-export! module exports))
-         (let ((keyword (if (keyword? (car kws))
-                            (keyword->symbol (car kws))
-                            (and (symbol? (car kws))
-                                 (let ((s (symbol->string (car kws))))
-                                   (and (eq? (string-ref s 0) #\:)
-                                        (string->symbol (substring s 1))))))))
-           (case keyword
-             ((use-module use-syntax)
-              (or (pair? (cdr kws))
-                  (unrecognized kws))
-               (let* ((spec (cadr kws))
-                      (interface (resolve-interface spec)))
-                 (and (eq? keyword 'use-syntax)
-                      (or (symbol? (car spec))
-                          (error "invalid module name for use-syntax"
-                                 spec))
-                      (set-module-transformer!
-                       module
-                       (module-ref interface (car (last-pair spec))
-                                   #f)))
-                 (loop (cddr kws)
-                       (cons interface reversed-interfaces)
-                       exports)))
-             ((autoload)
-              (or (and (pair? (cdr kws)) (pair? (cddr kws)))
-                   (unrecognized kws))
-              (loop (cdddr kws)
-                    (cons (make-autoload-interface module
-                                                   (cadr kws)
-                                                   (caddr kws))
-                          reversed-interfaces)
-                    exports))
-             ((no-backtrace)
-              (set-system-module! module #t)
-              (loop (cdr kws) reversed-interfaces exports))
-             ((pure)
-              (purify-module! module)
-              (loop (cdr kws) reversed-interfaces exports))
-             ((export)
-              (or (pair? (cdr kws))
-                   (unrecognized kws))
-              (loop (cddr kws)
-                    reversed-interfaces
-                    (append (cadr kws) exports)))
-             (else
-               (unrecognized kws))))))
+          (call-with-deferred-observers
+           (lambda ()
+             (module-use-interfaces! module (reverse reversed-interfaces))
+             (module-export! module exports)
+             (module-replace! module replacements)
+             (module-re-export! module re-exports)
+             (if (not (null? autoloads))
+                 (apply module-autoload! module autoloads))))
+          (case (car kws)
+            ((#:use-module #:use-syntax)
+             (or (pair? (cdr kws))
+                 (unrecognized kws))
+             (let* ((interface-args (cadr kws))
+                    (interface (apply resolve-interface interface-args)))
+               (and (eq? (car kws) #:use-syntax)
+                    (or (symbol? (caar interface-args))
+                        (error "invalid module name for use-syntax"
+                               (car interface-args)))
+                    (set-module-transformer!
+                     module
+                     (module-ref interface
+                                 (car (last-pair (car interface-args)))
+                                 #f)))
+               (loop (cddr kws)
+                     (cons interface reversed-interfaces)
+                     exports
+                     re-exports
+                     replacements
+                     autoloads)))
+            ((#:autoload)
+             (or (and (pair? (cdr kws)) (pair? (cddr kws)))
+                 (unrecognized kws))
+             (loop (cdddr kws)
+                   reversed-interfaces
+                   exports
+                   re-exports
+                   replacements
+                   (let ((name (cadr kws))
+                         (bindings (caddr kws)))
+                     (cons* name bindings autoloads))))
+            ((#:no-backtrace)
+             (set-system-module! module #t)
+             (loop (cdr kws) reversed-interfaces exports re-exports
+                   replacements autoloads))
+            ((#:pure)
+             (purify-module! module)
+             (loop (cdr kws) reversed-interfaces exports re-exports
+                   replacements autoloads))
+            ((#:duplicates)
+             (if (not (pair? (cdr kws)))
+                 (unrecognized kws))
+             (set-module-duplicates-handlers!
+              module
+              (lookup-duplicates-handlers (cadr kws)))
+             (loop (cddr kws) reversed-interfaces exports re-exports
+                   replacements autoloads))
+            ((#:export #:export-syntax)
+             (or (pair? (cdr kws))
+                 (unrecognized kws))
+             (loop (cddr kws)
+                   reversed-interfaces
+                   (append (cadr kws) exports)
+                   re-exports
+                   replacements
+                   autoloads))
+            ((#:re-export #:re-export-syntax)
+             (or (pair? (cdr kws))
+                 (unrecognized kws))
+             (loop (cddr kws)
+                   reversed-interfaces
+                   exports
+                   (append (cadr kws) re-exports)
+                   replacements
+                   autoloads))
+            ((#:replace #:replace-syntax)
+             (or (pair? (cdr kws))
+                 (unrecognized kws))
+             (loop (cddr kws)
+                   reversed-interfaces
+                   exports
+                   re-exports
+                   (append (cadr kws) replacements)
+                   autoloads))
+            (else
+             (unrecognized kws)))))
+    (run-hook module-defined-hook module)
     module))
 
+;; `module-defined-hook' is a hook that is run whenever a new module
+;; is defined.  Its members are called with one argument, the new
+;; module.
+(define module-defined-hook (make-hook 1))
+
+\f
+
 ;;; {Autoload}
+;;;
 
 (define (make-autoload-interface module name bindings)
   (let ((b (lambda (a sym definep)
                  (let ((i (module-public-interface (resolve-module name))))
                    (if (not i)
                        (error "missing interface for module" name))
-                   ;; Replace autoload-interface with interface
-                   (set-car! (memq a (module-uses module)) i)
+                   (let ((autoload (memq a (module-uses module))))
+                     ;; Replace autoload-interface with actual interface if
+                     ;; that has not happened yet.
+                     (if (pair? autoload)
+                         (set-car! autoload i)))
                    (module-local-variable i sym))))))
-    (module-constructor #() '() b #f #f name 'autoload
-                       '() (make-weak-value-hash-table 31) 0)))
+    (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
+                        (make-hash-table 0) '() (make-weak-value-hash-table 31))))
+
+(define (module-autoload! module . args)
+  "Have @var{module} automatically load the module named @var{name} when one
+of the symbols listed in @var{bindings} is looked up.  @var{args} should be a
+list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
+module '(ice-9 q) '(make-q q-length))}."
+  (let loop ((args args))
+    (cond ((null? args)
+           #t)
+          ((null? (cdr args))
+           (error "invalid name+binding autoload list" args))
+          (else
+           (let ((name     (car args))
+                 (bindings (cadr args)))
+             (module-use! module (make-autoload-interface module
+                                                          name bindings))
+             (loop (cddr args)))))))
+
 
 ;;; {Compiled module}
 
-(define load-compiled #f)
+(if (not (defined? 'load-compiled))
+    (define load-compiled #f))
 
 \f
+
 ;;; {Autoloading modules}
+;;;
 
 (define autoloads-in-progress '())
 
+;; This function is called from "modules.c".  If you change it, be
+;; sure to update "modules.c" as well.
+
 (define (try-module-autoload module-name)
   (let* ((reverse-name (reverse module-name))
         (name (symbol->string (car reverse-name)))
            (lambda () (autoload-in-progress! dir-hint name))
            (lambda ()
              (let ((file (in-vicinity dir-hint name)))
-               (cond ((and load-compiled
-                           (%search-load-path (string-append file ".go")))
-                      => (lambda (full)
-                           (load-file load-compiled full)))
-                     ((%search-load-path file)
-                      => (lambda (full)
-                           (load-file primitive-load full))))))
+                (let ((compiled (and load-compiled
+                                     (%search-load-path
+                                      (string-append file ".go"))))
+                      (source (%search-load-path file)))
+                  (cond ((and source
+                              (or (not compiled)
+                                  (< (stat:mtime (stat compiled))
+                                     (stat:mtime (stat source)))))
+                         (if compiled
+                             (warn "source file" source "newer than" compiled))
+                         (with-fluids ((current-reader #f))
+                           (load-file primitive-load source)))
+                        (compiled
+                         (load-file load-compiled compiled))))))
            (lambda () (set-autoloaded! dir-hint name didit)))
           didit))))
 
 \f
-;;; Dynamic linking of modules
-
-;; This method of dynamically linking Guile Extensions is deprecated.
-;; Use `dynamic-link' and `dynamic-call' explicitely from Scheme code
-;; instead.
-
-;; XXX - We can not offer the removal of this code thru the
-;; deprecation mechanism since we have no complete replacement yet.
-
-(define (split-c-module-name str)
-  (let loop ((rev '())
-            (start 0)
-            (pos 0)
-            (end (string-length str)))
-    (cond
-     ((= pos end)
-      (reverse (cons (string->symbol (substring str start pos)) rev)))
-     ((eq? (string-ref str pos) #\space)
-      (loop (cons (string->symbol (substring str start pos)) rev)
-           (+ pos 1)
-           (+ pos 1)
-           end))
-     (else
-      (loop rev start (+ pos 1) end)))))
-
-(define (convert-c-registered-modules dynobj)
-  (let ((res (map (lambda (c)
-                   (list (split-c-module-name (car c)) (cdr c) dynobj))
-                 (c-registered-modules))))
-    (c-clear-registered-modules)
-    res))
-
-(define registered-modules '())
-
-(define (register-modules dynobj)
-  (set! registered-modules
-       (append! (convert-c-registered-modules dynobj)
-                registered-modules)))
-
-(define (warn-autoload-deprecation modname)
-  ;; Do nothing here until we can deprecate the code for real.
-  (if #f
-      (issue-deprecation-warning
-       "Autoloading of compiled code modules is deprecated."
-       "Write a Scheme file instead that uses `dynamic-link' directly.")))
-
-(define (init-dynamic-module modname)
-  ;; Register any linked modules which have been registered on the C level
-  (register-modules #f)
-  (or-map (lambda (modinfo)
-           (if (equal? (car modinfo) modname)
-               (begin
-                 (warn-autoload-deprecation modname)
-                 (set! registered-modules (delq! modinfo registered-modules))
-                 (let ((mod (resolve-module modname #f)))
-                   (save-module-excursion
-                    (lambda ()
-                      (set-current-module mod)
-                      (set-module-public-interface! mod mod)
-                      (dynamic-call (cadr modinfo) (caddr modinfo))
-                      ))
-                   #t))
-               #f))
-         registered-modules))
-
-(define (dynamic-maybe-call name dynobj)
-  (catch #t                            ; could use false-if-exception here
-        (lambda ()
-          (dynamic-call name dynobj))
-        (lambda args
-          #f)))
-
-(define (dynamic-maybe-link filename)
-  (catch #t                            ; could use false-if-exception here
-        (lambda ()
-          (dynamic-link filename))
-        (lambda args
-          #f)))
-
-(define (find-and-link-dynamic-module module-name)
-  (define (make-init-name mod-name)
-    (string-append "scm_init"
-                  (list->string (map (lambda (c)
-                                       (if (or (char-alphabetic? c)
-                                               (char-numeric? c))
-                                           c
-                                           #\_))
-                                     (string->list mod-name)))
-                  "_module"))
-
-  ;; Put the subdirectory for this module in the car of SUBDIR-AND-LIBNAME,
-  ;; and the `libname' (the name of the module prepended by `lib') in the cdr
-  ;; field.  For example, if MODULE-NAME is the list (inet tcp-ip udp), then
-  ;; SUBDIR-AND-LIBNAME will be the pair ("inet/tcp-ip" . "libudp").
-  (let ((subdir-and-libname
-        (let loop ((dirs "")
-                   (syms module-name))
-          (if (null? (cdr syms))
-              (cons dirs (string-append "lib" (symbol->string (car syms))))
-              (loop (string-append dirs (symbol->string (car syms)) "/")
-                    (cdr syms)))))
-       (init (make-init-name (apply string-append
-                                    (map (lambda (s)
-                                           (string-append "_"
-                                                          (symbol->string s)))
-                                         module-name)))))
-    (let ((subdir (car subdir-and-libname))
-         (libname (cdr subdir-and-libname)))
-
-      ;; Now look in each dir in %LOAD-PATH for `subdir/libfoo.la'.  If that
-      ;; file exists, fetch the dlname from that file and attempt to link
-      ;; against it.  If `subdir/libfoo.la' does not exist, or does not seem
-      ;; to name any shared library, look for `subdir/libfoo.so' instead and
-      ;; link against that.
-      (let check-dirs ((dir-list %load-path))
-       (if (null? dir-list)
-           #f
-           (let* ((dir (in-vicinity (car dir-list) subdir))
-                  (sharlib-full
-                   (or (try-using-libtool-name dir libname)
-                       (try-using-sharlib-name dir libname))))
-             (if (and sharlib-full (file-exists? sharlib-full))
-                 (link-dynamic-module sharlib-full init)
-                 (check-dirs (cdr dir-list)))))))))
-
-(define (try-using-libtool-name libdir libname)
-  (let ((libtool-filename (in-vicinity libdir
-                                      (string-append libname ".la"))))
-    (and (file-exists? libtool-filename)
-        libtool-filename)))
-
-(define (try-using-sharlib-name libdir libname)
-  (in-vicinity libdir (string-append libname ".so")))
-
-(define (link-dynamic-module filename initname)
-  ;; Register any linked modules which has been registered on the C level
-  (register-modules #f)
-  (let ((dynobj (dynamic-link filename)))
-    (dynamic-call initname dynobj)
-    (register-modules dynobj)))
-
-(define (try-module-linked module-name)
-  (init-dynamic-module module-name))
-
-(define (try-module-dynamic-link module-name)
-  (and (find-and-link-dynamic-module module-name)
-       (init-dynamic-module module-name)))
-
 
+;;; {Dynamic linking of modules}
+;;;
 
 (define autoloads-done '((guile . guile)))
 
        (set! autoloads-done (delete! n autoloads-done))
        (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
 
-
-
-\f
-;; {EVAL-CASE}
-;;
-;; (eval-case ((situation*) forms)* (else forms)?)
-;;
-;; Evaluate certain code based on the situation that eval-case is used
-;; in.  The only defined situation right now is `load-toplevel' which
-;; triggers for code evaluated at the top-level, for example from the
-;; REPL or when loading a file.
-
-(define eval-case
-  (procedure->memoizing-macro
-   (lambda (exp env)
-     (define (toplevel-env? env)
-       (or (not (pair? env)) (not (pair? (car env)))))
-     (define (syntax)
-       (error "syntax error in eval-case"))
-     (let loop ((clauses (cdr exp)))
-       (cond
-       ((null? clauses)
-        #f)
-       ((not (list? (car clauses)))
-        (syntax))
-       ((eq? 'else (caar clauses))
-        (or (null? (cdr clauses))
-            (syntax))
-        (cons 'begin (cdar clauses)))
-       ((not (list? (caar clauses)))
-        (syntax))
-       ((and (toplevel-env? env)
-             (memq 'load-toplevel (caar clauses)))
-        (cons 'begin (cdar clauses)))
-       (else
-        (loop (cdr clauses))))))))
-
-\f
-;;; {Macros}
-;;;
-
-(define (primitive-macro? m)
-  (and (macro? m)
-       (not (macro-transformer m))))
-
-;;; {Defmacros}
-;;;
-(define macro-table (make-weak-key-hash-table 523))
-(define xformer-table (make-weak-key-hash-table 523))
-
-(define (defmacro? m)  (hashq-ref macro-table m))
-(define (assert-defmacro?! m) (hashq-set! macro-table m #t))
-(define (defmacro-transformer m) (hashq-ref xformer-table m))
-(define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
-
-(define defmacro:transformer
-  (lambda (f)
-    (let* ((xform (lambda (exp env)
-                   (copy-tree (apply f (cdr exp)))))
-          (a (procedure->memoizing-macro xform)))
-      (assert-defmacro?! a)
-      (set-defmacro-transformer! a f)
-      a)))
-
-
-(define defmacro
-  (let ((defmacro-transformer
-         (lambda (name parms . body)
-           (let ((transformer `(lambda ,parms ,@body)))
-             `(eval-case
-               ((load-toplevel)
-                (define ,name (defmacro:transformer ,transformer)))
-               (else
-                (error "defmacro can only be used at the top level")))))))
-    (defmacro:transformer defmacro-transformer)))
-
-(define defmacro:syntax-transformer
-  (lambda (f)
-    (procedure->syntax
-             (lambda (exp env)
-               (copy-tree (apply f (cdr exp)))))))
-
-
-;; XXX - should the definition of the car really be looked up in the
-;; current module?
-
-(define (macroexpand-1 e)
-  (cond
-   ((pair? e) (let* ((a (car e))
-                    (val (and (symbol? a) (local-ref (list a)))))
-               (if (defmacro? val)
-                   (apply (defmacro-transformer val) (cdr e))
-                   e)))
-   (#t e)))
-
-(define (macroexpand e)
-  (cond
-   ((pair? e) (let* ((a (car e))
-                    (val (and (symbol? a) (local-ref (list a)))))
-               (if (defmacro? val)
-                   (macroexpand (apply (defmacro-transformer val) (cdr e)))
-                   e)))
-   (#t e)))
-
-(provide 'defmacro)
-
 \f
 
 ;;; {Run-time options}
+;;;
 
-(define define-option-interface
+(defmacro define-option-interface (option-group)
   (let* ((option-name car)
         (option-value cadr)
         (option-documentation caddr)
 
-        (print-option (lambda (option)
-                        (display (option-name option))
-                        (if (< (string-length
-                                (symbol->string (option-name option)))
-                               8)
-                            (display #\tab))
-                        (display #\tab)
-                        (display (option-value option))
-                        (display #\tab)
-                        (display (option-documentation option))
-                        (newline)))
-
         ;; Below follow the macros defining the run-time option interfaces.
 
         (make-options (lambda (interface)
                            (cond ((null? args) (,interface))
                                  ((list? (car args))
                                   (,interface (car args)) (,interface))
-                                 (else (for-each ,print-option
-                                                 (,interface #t)))))))
+                                 (else (for-each
+                                         (lambda (option)
+                                           (display (option-name option))
+                                           (if (< (string-length
+                                                   (symbol->string (option-name option)))
+                                                  8)
+                                               (display #\tab))
+                                           (display #\tab)
+                                           (display (option-value option))
+                                           (display #\tab)
+                                           (display (option-documentation option))
+                                           (newline))
+                                         (,interface #t)))))))
 
         (make-enable (lambda (interface)
                        `(lambda flags
                                          (set! options (delq! flag options)))
                                        flags)
                              (,interface options)
-                             (,interface)))))
-
-        (make-set! (lambda (interface)
-                     `((name exp)
-                       (,'quasiquote
-                        (begin (,interface (append (,interface)
-                                                   (list '(,'unquote name)
-                                                         (,'unquote exp))))
-                               (,interface)))))))
-    (procedure->macro
-     (lambda (exp env)
-       (cons 'begin
-            (let* ((option-group (cadr exp))
-                   (interface (car option-group)))
-              (append (map (lambda (name constructor)
-                             `(define ,name
-                                ,(constructor interface)))
-                           (cadr option-group)
-                           (list make-options
-                                 make-enable
-                                 make-disable))
-                      (map (lambda (name constructor)
-                             `(defmacro ,name
-                                ,@(constructor interface)))
-                           (caddr option-group)
-                           (list make-set!)))))))))
+                             (,interface))))))
+    (let* ((interface (car option-group))
+           (options/enable/disable (cadr option-group)))
+      `(begin
+         (define ,(car options/enable/disable)
+           ,(make-options interface))
+         (define ,(cadr options/enable/disable)
+           ,(make-enable interface))
+         (define ,(caddr options/enable/disable)
+           ,(make-disable interface))
+         (defmacro ,(caaddr option-group) (opt val)
+           `(,',(car options/enable/disable)
+             (append (,',(car options/enable/disable))
+                     (list ',opt ,val))))))))
 
 (define-option-interface
   (eval-options-interface
   (save-stack lazy-handler-dispatch)
   (apply throw key args))
 
-(define enter-frame-handler default-lazy-handler)
-(define apply-frame-handler default-lazy-handler)
-(define exit-frame-handler default-lazy-handler)
-
 (define (lazy-handler-dispatch key . args)
-  (case key
-    ((apply-frame)
-     (apply apply-frame-handler key args))
-    ((exit-frame)
-     (apply exit-frame-handler key args))
-    ((enter-frame)
-     (apply enter-frame-handler key args))
-    (else
-     (apply default-lazy-handler key args))))
+  (apply default-lazy-handler key args))
 
 (define abort-hook (make-hook))
 
             (catch #t
 
                    (lambda ()
-                     (lazy-catch #t
-                                 (lambda ()
-                                   (dynamic-wind
-                                    (lambda () (unmask-signals))
-                                    (lambda ()
-                                      (with-traps
-                                       (lambda ()
-                                         (first)
-
-                                         ;; This line is needed because mark
-                                         ;; doesn't do closures quite right.
-                                         ;; Unreferenced locals should be
-                                         ;; collected.
-                                         ;;
-                                         (set! first #f)
-                                         (let loop ((v (thunk)))
-                                           (loop (thunk)))
-                                         #f)))
-                                    (lambda () (mask-signals))))
-
-                                 lazy-handler-dispatch))
+                     (call-with-unblocked-asyncs
+                      (lambda ()
+                        (with-traps
+                         (lambda ()
+                           (first)
+
+                           ;; This line is needed because mark
+                           ;; doesn't do closures quite right.
+                           ;; Unreferenced locals should be
+                           ;; collected.
+                           (set! first #f)
+                           (let loop ((v (thunk)))
+                             (loop (thunk)))
+                           #f)))))
 
                    (lambda (key . args)
                      (case key
                           (cond ((= (length args) 4)
                                  (apply handle-system-error key args))
                                 (else
-                                 (apply bad-throw key args))))))))))
+                                 (apply bad-throw key args)))))))
+
+                   ;; Note that having just `lazy-handler-dispatch'
+                   ;; here is connected with the mechanism that
+                   ;; produces a nice backtrace upon error.  If, for
+                   ;; example, this is replaced with (lambda args
+                   ;; (apply lazy-handler-dispatch args)), the stack
+                   ;; cutting (in save-stack) goes wrong and ends up
+                   ;; saving no stack at all, so there is no
+                   ;; backtrace.
+                   lazy-handler-dispatch)))
+
        (if next (loop next) status)))
     (set! set-batch-mode?! (lambda (arg)
                             (cond (arg
                                   (#t
                                    (error "sorry, not implemented")))))
     (set! batch-mode? (lambda () (not interactive)))
-    (loop (lambda () #t))))
+    (call-with-blocked-asyncs
+     (lambda () (loop (lambda () #t))))))
 
 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
 (define before-signal-stack (make-fluid))
   (let ((cep (current-error-port)))
     (cond ((not (stack? (fluid-ref the-last-stack))))
          ((memq 'backtrace (debug-options-interface))
-          (run-hook before-backtrace-hook)
-          (newline cep)
-          (display "Backtrace:\n")
-          (display-backtrace (fluid-ref the-last-stack) cep)
-          (newline cep)
-          (run-hook after-backtrace-hook)))
+          (let ((highlights (if (or (eq? key 'wrong-type-arg)
+                                    (eq? key 'out-of-range))
+                                (list-ref args 3)
+                                '())))
+            (run-hook before-backtrace-hook)
+            (newline cep)
+            (display "Backtrace:\n")
+            (display-backtrace (fluid-ref the-last-stack) cep
+                               #f #f highlights)
+            (newline cep)
+            (run-hook after-backtrace-hook))))
     (run-hook before-error-hook)
     (apply display-error (fluid-ref the-last-stack) cep args)
     (run-hook after-error-hook)
 ;;; the readline library.
 (define repl-reader
   (lambda (prompt)
-    (display prompt)
+    (display (if (string? prompt) prompt (prompt)))
     (force-output)
     (run-hook before-read-hook)
-    (read (current-input-port))))
+    ((or (fluid-ref current-reader) read) (current-input-port))))
 
 (define (scm-style-repl)
 
 
 
 \f
+
 ;;; {IOTA functions: generating lists of numbers}
+;;;
 
 (define (iota n)
   (let loop ((count (1- n)) (result '()))
         (loop (1- count) (cons count result)))))
 
 \f
-;;; {While}
-;;;
-;;; with `continue' and `break'.
-;;;
-
-(defmacro while (cond . body)
-  `(letrec ((continue (lambda () (or (not ,cond) (begin (begin ,@ body) (continue)))))
-           (break (lambda val (apply throw 'break val))))
-     (catch 'break
-           (lambda () (continue))
-           (lambda v (cadr v)))))
 
 ;;; {collect}
 ;;;
 ;;; forms instead of the result of the last form.
 ;;; (The definition relies on the current left-to-right
 ;;;  order of evaluation of operands in applications.)
+;;;
 
 (defmacro collect forms
   (cons 'list forms))
 
+\f
+
 ;;; {with-fluids}
+;;;
 
 ;; with-fluids is a convenience wrapper for the builtin procedure
 ;; `with-fluids*'.  The syntax is just like `let':
 ;;     body)
 
 (defmacro with-fluids (bindings . body)
-  `(with-fluids* (list ,@(map car bindings)) (list ,@(map cadr bindings))
-                (lambda () ,@body)))
+  (let ((fluids (map car bindings))
+       (values (map cadr bindings)))
+    (if (and (= (length fluids) 1) (= (length values) 1))
+       `(with-fluid* ,(car fluids) ,(car values) (lambda () ,@body))
+       `(with-fluids* (list ,@fluids) (list ,@values)
+                      (lambda () ,@body)))))
 
 \f
 
 ;; coaxing
 ;;
 
+(define (primitive-macro? m)
+  (and (macro? m)
+       (not (macro-transformer m))))
+
 (defmacro define-macro (first . rest)
   (let ((name (if (symbol? first) first (car first)))
        (transformer
             (car rest)
             `(lambda ,(cdr first) ,@rest))))
     `(eval-case
-      ((load-toplevel)
+      ((load-toplevel compile-toplevel)
        (define ,name (defmacro:transformer ,transformer)))
       (else
        (error "define-macro can only be used at the top level")))))
 
 
-(defmacro define-syntax-macro (first . rest)
-  (let ((name (if (symbol? first) first (car first)))
-       (transformer
-        (if (symbol? first)
-            (car rest)
-            `(lambda ,(cdr first) ,@rest))))
-    `(eval-case
-      ((load-toplevel)
-       (define ,name (defmacro:syntax-transformer ,transformer)))
-      (else
-       (error "define-syntax-macro can only be used at the top level")))))
+\f
+
+;;; {While}
+;;;
+;;; with `continue' and `break'.
+;;;
+
+;; The inner `do' loop avoids re-establishing a catch every iteration,
+;; that's only necessary if continue is actually used.  A new key is
+;; generated every time, so break and continue apply to their originating
+;; `while' even when recursing.
+;;
+;; FIXME: This macro is unintentionally unhygienic with respect to let,
+;; make-symbol, do, throw, catch, lambda, and not.
+;;
+(define-macro (while cond . body)
+  (let ((keyvar (make-symbol "while-keyvar")))
+    `(let ((,keyvar (make-symbol "while-key")))
+       (do ()
+           ((catch ,keyvar
+                   (lambda ()
+                     (let ((break (lambda () (throw ,keyvar #t)))
+                           (continue (lambda () (throw ,keyvar #f))))
+                       (do ()
+                           ((not ,cond))
+                         ,@body)
+                       #t))
+                   (lambda (key arg)
+                     arg)))))))
+
 
 \f
+
 ;;; {Module System Macros}
 ;;;
 
+;; Return a list of expressions that evaluate to the appropriate
+;; arguments for resolve-interface according to SPEC.
+
+(eval-case
+ ((compile-toplevel)
+  (if (memq 'prefix (read-options))
+      (error "boot-9 must be compiled with #:kw, not :kw"))))
+
+(define (compile-interface-spec spec)
+  (define (make-keyarg sym key quote?)
+    (cond ((or (memq sym spec)
+              (memq key spec))
+          => (lambda (rest)
+               (if quote?
+                   (list key (list 'quote (cadr rest)))
+                   (list key (cadr rest)))))
+         (else
+          '())))
+  (define (map-apply func list)
+    (map (lambda (args) (apply func args)) list))
+  (define keys
+    ;; sym     key      quote?
+    '((:select #:select #t)
+      (:hide   #:hide  #t)
+      (:prefix #:prefix #t)
+      (:renamer #:renamer #f)))
+  (if (not (pair? (car spec)))
+      `(',spec)
+      `(',(car spec)
+       ,@(apply append (map-apply make-keyarg keys)))))
+
+(define (keyword-like-symbol->keyword sym)
+  (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
+
+(define (compile-define-module-args args)
+  ;; Just quote everything except #:use-module and #:use-syntax.  We
+  ;; need to know about all arguments regardless since we want to turn
+  ;; symbols that look like keywords into real keywords, and the
+  ;; keyword args in a define-module form are not regular
+  ;; (i.e. no-backtrace doesn't take a value).
+  (let loop ((compiled-args `((quote ,(car args))))
+            (args (cdr args)))
+    (cond ((null? args)
+          (reverse! compiled-args))
+         ;; symbol in keyword position
+         ((symbol? (car args))
+          (loop compiled-args
+                (cons (keyword-like-symbol->keyword (car args)) (cdr args))))
+         ((memq (car args) '(#:no-backtrace #:pure))
+          (loop (cons (car args) compiled-args)
+                (cdr args)))
+         ((null? (cdr args))
+          (error "keyword without value:" (car args)))
+         ((memq (car args) '(#:use-module #:use-syntax))
+          (loop (cons* `(list ,@(compile-interface-spec (cadr args)))
+                       (car args)
+                       compiled-args)
+                (cddr args)))
+         ((eq? (car args) #:autoload)
+          (loop (cons* `(quote ,(caddr args))
+                       `(quote ,(cadr args))
+                       (car args)
+                       compiled-args)
+                (cdddr args)))
+         (else
+          (loop (cons* `(quote ,(cadr args))
+                       (car args)
+                       compiled-args)
+                (cddr args))))))
+
 (defmacro define-module args
   `(eval-case
-    ((load-toplevel)
-     (let ((m (process-define-module ',args)))
+    ((load-toplevel compile-toplevel)
+     (let ((m (process-define-module
+              (list ,@(compile-define-module-args args)))))
        (set-current-module m)
        m))
     (else
      (error "define-module can only be used at the top level"))))
 
-;; the guts of the use-modules macro.  add the interfaces of the named
-;; modules to the use-list of the current module, in order
-(define (process-use-modules module-interface-specs)
-  (for-each (lambda (mif-spec)
-             (let ((mod-iface (resolve-interface mif-spec)))
-               (or mod-iface
-                   (error "no such module" mif-spec))
-               (module-use! (current-module) mod-iface)))
-            module-interface-specs))
+;; The guts of the use-modules macro.  Add the interfaces of the named
+;; modules to the use-list of the current module, in order.
+
+;; This function is called by "modules.c".  If you change it, be sure
+;; to change scm_c_use_module as well.
+
+(define (process-use-modules module-interface-args)
+  (let ((interfaces (map (lambda (mif-args)
+                          (or (apply resolve-interface mif-args)
+                              (error "no such module" mif-args)))
+                        module-interface-args)))
+    (call-with-deferred-observers
+     (lambda ()
+       (module-use-interfaces! (current-module) interfaces)))))
 
 (defmacro use-modules modules
   `(eval-case
-    ((load-toplevel)
-     (process-use-modules ',modules))
+    ((load-toplevel compile-toplevel)
+     (process-use-modules
+      (list ,@(map (lambda (m)
+                    `(list ,@(compile-interface-spec m)))
+                  modules)))
+     *unspecified*)
     (else
      (error "use-modules can only be used at the top level"))))
 
 (defmacro use-syntax (spec)
   `(eval-case
-    ((load-toplevel)
+    ((load-toplevel compile-toplevel)
      ,@(if (pair? spec)
-          `((process-use-modules ',(list spec))
+          `((process-use-modules (list
+                                  (list ,@(compile-interface-spec spec))))
             (set-module-transformer! (current-module)
                                      ,(car (last-pair spec))))
           `((set-module-transformer! (current-module) ,spec)))
-     (begin-deprecated
-      (fluid-set! scm:eval-transformer (module-transformer (current-module)))))
+     *unspecified*)
     (else
      (error "use-syntax can only be used at the top level"))))
 
+;; Dirk:FIXME:: This incorrect (according to R5RS) syntax needs to be changed
+;; as soon as guile supports hygienic macros.
 (define define-private define)
 
 (defmacro define-public args
    (#t
     (let ((name (defined-name (car args))))
       `(begin
-        (eval-case ((load-toplevel) (export ,name)))
-        (define-private ,@args))))))
+        (define-private ,@args)
+        (eval-case ((load-toplevel compile-toplevel) (export ,name))))))))
 
 (defmacro defmacro-public args
   (define (syntax)
    (#t
     (let ((name (defined-name (car args))))
       `(begin
-        (eval-case ((load-toplevel) (export ,name)))
+        (eval-case ((load-toplevel compile-toplevel) (export-syntax ,name)))
         (defmacro ,@args))))))
 
+;; Export a local variable
+
+;; This function is called from "modules.c".  If you change it, be
+;; sure to update "modules.c" as well.
+
 (define (module-export! m names)
   (let ((public-i (module-public-interface m)))
     (for-each (lambda (name)
-               ;; Make sure there is a local variable:
-               (module-define! m name (module-ref m name #f))
-               ;; Make sure that local is exported:
-               (module-add! public-i name (module-variable m name)))
+               (let ((var (module-ensure-local-variable! m name)))
+                 (module-add! public-i name var)))
+             names)))
+
+(define (module-replace! m names)
+  (let ((public-i (module-public-interface m)))
+    (for-each (lambda (name)
+               (let ((var (module-ensure-local-variable! m name)))
+                 (set-object-property! var 'replace #t)
+                 (module-add! public-i name var)))
+             names)))
+
+;; Re-export a imported variable
+;;
+(define (module-re-export! m names)
+  (let ((public-i (module-public-interface m)))
+    (for-each (lambda (name)
+               (let ((var (module-variable m name)))
+                 (cond ((not var)
+                        (error "Undefined variable:" name))
+                       ((eq? var (module-local-variable m name))
+                        (error "re-exporting local variable:" name))
+                       (else
+                        (module-add! public-i name var)))))
              names)))
 
 (defmacro export names
   `(eval-case
-    ((load-toplevel)
-     (module-export! (current-module) ',names))
+    ((load-toplevel compile-toplevel)
+     (call-with-deferred-observers
+      (lambda ()
+       (module-export! (current-module) ',names))))
     (else
      (error "export can only be used at the top level"))))
 
-(define export-syntax export)
+(defmacro re-export names
+  `(eval-case
+    ((load-toplevel compile-toplevel)
+     (call-with-deferred-observers
+      (lambda ()
+       (module-re-export! (current-module) ',names))))
+    (else
+     (error "re-export can only be used at the top level"))))
+
+(defmacro export-syntax names
+  `(export ,@names))
 
+(defmacro re-export-syntax names
+  `(re-export ,@names))
 
 (define load load-module)
 
+;; The following macro allows one to write, for example,
+;;
+;;    (@ (ice-9 pretty-print) pretty-print)
+;;
+;; to refer directly to the pretty-print variable in module (ice-9
+;; pretty-print).  It works by looking up the variable and inserting
+;; it directly into the code.  This is understood by the evaluator.
+;; Indeed, all references to global variables are memoized into such
+;; variable objects.
+
+(define-macro (@ mod-name var-name)
+  (let ((var (module-variable (resolve-interface mod-name) var-name)))
+    (if (not var)
+       (error "no such public variable" (list '@ mod-name var-name)))
+    var))
+
+;; The '@@' macro is like '@' but it can also access bindings that
+;; have not been explicitely exported.
+
+(define-macro (@@ mod-name var-name)
+  (let ((var (module-variable (resolve-module mod-name) var-name)))
+    (if (not var)
+       (error "no such variable" (list '@@ mod-name var-name)))
+    var))
+
+\f
+
+;;; {Compiler interface}
+;;;
+;;; The full compiler interface can be found in (system). Here we put a
+;;; few useful procedures into the global namespace.
+
+(module-autoload! the-scm-module
+                  '(system base compile)
+                  '(compile
+                    compile-time-environment))
+
+
+\f
+
+;;; {Parameters}
+;;;
+
+(define make-mutable-parameter
+  (let ((make (lambda (fluid converter)
+               (lambda args
+                 (if (null? args)
+                     (fluid-ref fluid)
+                     (fluid-set! fluid (converter (car args))))))))
+    (lambda (init . converter)
+      (let ((fluid (make-fluid))
+           (converter (if (null? converter)
+                          identity
+                          (car converter))))
+       (fluid-set! fluid (converter init))
+       (make fluid converter)))))
+
+\f
+
+;;; {Handling of duplicate imported bindings}
+;;;
+
+;; Duplicate handlers take the following arguments:
+;;
+;; module  importing module
+;; name           conflicting name
+;; int1           old interface where name occurs
+;; val1           value of binding in old interface
+;; int2           new interface where name occurs
+;; val2           value of binding in new interface
+;; var    previous resolution or #f
+;; val    value of previous resolution
+;;
+;; A duplicate handler can take three alternative actions:
+;;
+;; 1. return #f => leave responsibility to next handler
+;; 2. exit with an error
+;; 3. return a variable resolving the conflict
+;;
+
+(define duplicate-handlers
+  (let ((m (make-module 7)))
+    
+    (define (check module name int1 val1 int2 val2 var val)
+      (scm-error 'misc-error
+                #f
+                "~A: `~A' imported from both ~A and ~A"
+                (list (module-name module)
+                      name
+                      (module-name int1)
+                      (module-name int2))
+                #f))
+    
+    (define (warn module name int1 val1 int2 val2 var val)
+      (format (current-error-port)
+             "WARNING: ~A: `~A' imported from both ~A and ~A\n"
+             (module-name module)
+             name
+             (module-name int1)
+             (module-name int2))
+      #f)
+     
+    (define (replace module name int1 val1 int2 val2 var val)
+      (let ((old (or (and var (object-property var 'replace) var)
+                    (module-variable int1 name)))
+           (new (module-variable int2 name)))
+       (if (object-property old 'replace)
+           (and (or (eq? old new)
+                    (not (object-property new 'replace)))
+                old)
+           (and (object-property new 'replace)
+                new))))
+    
+    (define (warn-override-core module name int1 val1 int2 val2 var val)
+      (and (eq? int1 the-scm-module)
+          (begin
+            (format (current-error-port)
+                    "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
+                    (module-name module)
+                    (module-name int2)
+                    name)
+            (module-local-variable int2 name))))
+     
+    (define (first module name int1 val1 int2 val2 var val)
+      (or var (module-local-variable int1 name)))
+     
+    (define (last module name int1 val1 int2 val2 var val)
+      (module-local-variable int2 name))
+     
+    (define (noop module name int1 val1 int2 val2 var val)
+      #f)
+    
+    (set-module-name! m 'duplicate-handlers)
+    (set-module-kind! m 'interface)
+    (module-define! m 'check check)
+    (module-define! m 'warn warn)
+    (module-define! m 'replace replace)
+    (module-define! m 'warn-override-core warn-override-core)
+    (module-define! m 'first first)
+    (module-define! m 'last last)
+    (module-define! m 'merge-generics noop)
+    (module-define! m 'merge-accessors noop)
+    m))
+
+(define (lookup-duplicates-handlers handler-names)
+  (and handler-names
+       (map (lambda (handler-name)
+             (or (module-symbol-local-binding
+                  duplicate-handlers handler-name #f)
+                 (error "invalid duplicate handler name:"
+                        handler-name)))
+           (if (list? handler-names)
+               handler-names
+               (list handler-names)))))
+
+(define default-duplicate-binding-procedures
+  (make-mutable-parameter #f))
+
+(define default-duplicate-binding-handler
+  (make-mutable-parameter '(replace warn-override-core warn last)
+                         (lambda (handler-names)
+                           (default-duplicate-binding-procedures
+                             (lookup-duplicates-handlers handler-names))
+                           handler-names)))
+
 \f
 
 ;;; {`cond-expand' for SRFI-0 support.}
 ;;;
 ;;; Currently, the following feature identifiers are supported:
 ;;;
-;;;   guile r5rs srfi-0
+;;;   guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
 ;;;
 ;;; Remember to update the features list when adding more SRFIs.
+;;;
 
 (define %cond-expand-features
   ;; Adjust the above comment when changing this.
-  '(guile r5rs srfi-0))
+  '(guile
+    r5rs
+    srfi-0   ;; cond-expand itself
+    srfi-4   ;; homogenous numeric vectors
+    srfi-6   ;; open-input-string etc, in the guile core
+    srfi-13  ;; string library
+    srfi-14  ;; character sets
+    srfi-55  ;; require-extension
+    srfi-61  ;; general cond clause
+    ))
 
 ;; This table maps module public interfaces to the list of features.
 ;;
 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
 ;;
 (define (use-srfis srfis)
-  (let lp ((s srfis))
-    (if (pair? s)
-        (let* ((srfi (string->symbol
-                      (string-append "srfi-" (number->string (car s)))))
-               (mod-i (resolve-interface (list 'srfi srfi))))
-          (module-use! (current-module) mod-i)
-          (lp (cdr s))))))
+  (process-use-modules
+   (map (lambda (num)
+         (list (list 'srfi (string->symbol
+                            (string-append "srfi-" (number->string num))))))
+       srfis)))
+
+\f
+
+;;; srfi-55: require-extension
+;;;
+
+(define-macro (require-extension extension-spec)
+  ;; This macro only handles the srfi extension, which, at present, is
+  ;; the only one defined by the standard.
+  (if (not (pair? extension-spec))
+      (scm-error 'wrong-type-arg "require-extension"
+                 "Not an extension: ~S" (list extension-spec) #f))
+  (let ((extension (car extension-spec))
+        (extension-args (cdr extension-spec)))
+    (case extension
+      ((srfi)
+       (let ((use-list '()))
+         (for-each
+          (lambda (i)
+            (if (not (integer? i))
+                (scm-error 'wrong-type-arg "require-extension"
+                           "Invalid srfi name: ~S" (list i) #f))
+            (let ((srfi-sym (string->symbol
+                             (string-append "srfi-" (number->string i)))))
+              (if (not (memq srfi-sym %cond-expand-features))
+                  (set! use-list (cons `(use-modules (srfi ,srfi-sym))
+                                       use-list)))))
+          extension-args)
+         (if (pair? use-list)
+             ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
+             `(begin ,@(reverse! use-list)))))
+      (else
+       (scm-error
+        'wrong-type-arg "require-extension"
+        "Not a recognized extension type: ~S" (list extension) #f)))))
 
 \f
 
 ;;; {Load emacs interface support if emacs option is given.}
+;;;
 
 (define (named-module-use! user usee)
-  (module-use! (resolve-module user) (resolve-module usee)))
+  (module-use! (resolve-module user) (resolve-interface usee)))
 
 (define (load-emacs-interface)
   (and (provided? 'debug-extensions)
   (let ((guile-user-module (resolve-module '(guile-user))))
 
     ;; Load emacs interface support if emacs option is given.
-    (if (and (module-defined? the-root-module 'use-emacs-interface)
-            (module-ref the-root-module 'use-emacs-interface))
+    (if (and (module-defined? guile-user-module 'use-emacs-interface)
+            (module-ref guile-user-module 'use-emacs-interface))
        (load-emacs-interface))
 
     ;; Use some convenient modules (in reverse order)
-    
-    (if (provided? 'regex)
-       (module-use! guile-user-module (resolve-module '(ice-9 regex))))
-    (if (provided? 'threads)
-       (module-use! guile-user-module (resolve-module '(ice-9 threads))))
-    ;; load debugger on demand
-    (module-use! guile-user-module 
-                (make-autoload-interface guile-user-module
-                                         '(ice-9 debugger) '(debug)))
-    (module-use! guile-user-module (resolve-module '(ice-9 session)))
-    (module-use! guile-user-module (resolve-module '(ice-9 debug)))
-    ;; so that builtin bindings will be checked first
-    (module-use! guile-user-module (resolve-module '(guile))) 
 
     (set-current-module guile-user-module)
+    (process-use-modules 
+     (append
+      '(((ice-9 r5rs))
+       ((ice-9 session))
+       ((ice-9 debug)))
+      (if (provided? 'regex)
+         '(((ice-9 regex)))
+         '())
+      (if (provided? 'threads)
+         '(((ice-9 threads)))
+         '())))
+    ;; load debugger on demand
+    (module-autoload! guile-user-module '(ice-9 debugger) '(debug))
 
+    ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
+    ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
+    ;; no effect.
     (let ((old-handlers #f)
+          (start-repl (module-ref (resolve-interface '(system repl repl))
+                                  'start-repl))
          (signals (if (provided? 'posix)
                       `((,SIGINT . "User interrupt")
                         (,SIGFPE . "Arithmetic error")
-                        (,SIGBUS . "Bad memory access (bus error)")
                         (,SIGSEGV
                          . "Bad memory access (Segmentation violation)"))
                       '())))
+      ;; no SIGBUS on mingw
+      (if (defined? 'SIGBUS)
+         (set! signals (acons SIGBUS "Bad memory access (bus error)"
+                              signals)))
 
       (dynamic-wind
 
                                    ;; Make a backup copy of the stack
                                    (fluid-set! before-signal-stack
                                                (fluid-ref the-last-stack))
-                                   (save-stack %deliver-signals)
+                                   (save-stack 2)
                                    (scm-error 'signal
                                               #f
                                               msg
                           (sigaction (car sig-msg)
                                      (make-handler (cdr sig-msg))))
                         signals))))
-         
+
          ;; the protected thunk.
          (lambda ()
-           (let ((status (scm-style-repl)))
+            (let ((status (start-repl 'scheme)))
              (run-hook exit-hook)
              status))
-         
+
          ;; call at exit.
          (lambda ()
            (map (lambda (sig-msg old-handler)
                                  (cdr old-handler))))
                 signals old-handlers))))))
 
-(defmacro false-if-exception (expr)
-  `(catch #t (lambda () ,expr)
-         (lambda args #f)))
-
 ;;; This hook is run at the very end of an interactive session.
 ;;;
 (define exit-hook (make-hook))
 
 \f
-(append! %load-path (list "."))
 
-;; Place the user in the guile-user module.
-;;
+;;; {Deprecated stuff}
+;;;
+
+(begin-deprecated
+ (define (feature? sym)
+   (issue-deprecation-warning
+    "`feature?' is deprecated.  Use `provided?' instead.")
+   (provided? sym)))
+
+(begin-deprecated
+ (primitive-load-path "ice-9/deprecated"))
+
+\f
+
+;;; Place the user in the guile-user module.
+;;;
+
 (define-module (guile-user))
 
 ;;; boot-9.scm ends here