1.0.29.23: simple-fun and closure cleanups
[sbcl.git] / src / code / defboot.lisp
1 ;;;; bootstrapping fundamental machinery (e.g. DEFUN, DEFCONSTANT,
2 ;;;; DEFVAR) from special forms and primitive functions
3 ;;;;
4 ;;;; KLUDGE: The bootstrapping aspect of this is now obsolete. It was
5 ;;;; originally intended that this file file would be loaded into a
6 ;;;; Lisp image which had Common Lisp primitives defined, and DEFMACRO
7 ;;;; defined, and little else. Since then that approach has been
8 ;;;; dropped and this file has been modified somewhat to make it work
9 ;;;; more cleanly when used to predefine macros at
10 ;;;; build-the-cross-compiler time.
11
12 ;;;; This software is part of the SBCL system. See the README file for
13 ;;;; more information.
14 ;;;;
15 ;;;; This software is derived from the CMU CL system, which was
16 ;;;; written at Carnegie Mellon University and released into the
17 ;;;; public domain. The software is in the public domain and is
18 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
19 ;;;; files for more information.
20
21 (in-package "SB!IMPL")
22
23 \f
24 ;;;; IN-PACKAGE
25
26 (defmacro-mundanely in-package (string-designator)
27   (let ((string (string string-designator)))
28     `(eval-when (:compile-toplevel :load-toplevel :execute)
29        (setq *package* (find-undeleted-package-or-lose ,string)))))
30 \f
31 ;;;; MULTIPLE-VALUE-FOO
32
33 (defun list-of-symbols-p (x)
34   (and (listp x)
35        (every #'symbolp x)))
36
37 (defmacro-mundanely multiple-value-bind (vars value-form &body body)
38   (if (list-of-symbols-p vars)
39     ;; It's unclear why it would be important to special-case the LENGTH=1 case
40     ;; at this level, but the CMU CL code did it, so.. -- WHN 19990411
41     (if (= (length vars) 1)
42       `(let ((,(car vars) ,value-form))
43          ,@body)
44       (let ((ignore (sb!xc:gensym)))
45         `(multiple-value-call #'(lambda (&optional ,@(mapcar #'list vars)
46                                          &rest ,ignore)
47                                   (declare (ignore ,ignore))
48                                   ,@body)
49                               ,value-form)))
50     (error "Vars is not a list of symbols: ~S" vars)))
51
52 (defmacro-mundanely multiple-value-setq (vars value-form)
53   (unless (list-of-symbols-p vars)
54     (error "Vars is not a list of symbols: ~S" vars))
55   ;; MULTIPLE-VALUE-SETQ is required to always return just the primary
56   ;; value of the value-from, even if there are no vars. (SETF VALUES)
57   ;; in turn is required to return as many values as there are
58   ;; value-places, hence this:
59   (if vars
60       `(values (setf (values ,@vars) ,value-form))
61       `(values ,value-form)))
62
63 (defmacro-mundanely multiple-value-list (value-form)
64   `(multiple-value-call #'list ,value-form))
65 \f
66 ;;;; various conditional constructs
67
68 ;;; COND defined in terms of IF
69 (defmacro-mundanely cond (&rest clauses)
70   (if (endp clauses)
71       nil
72       (let ((clause (first clauses))
73             (more (rest clauses)))
74         (if (atom clause)
75             (error "COND clause is not a list: ~S" clause)
76             (let ((test (first clause))
77                   (forms (rest clause)))
78               (if (endp forms)
79                   (let ((n-result (gensym)))
80                     `(let ((,n-result ,test))
81                        (if ,n-result
82                            ,n-result
83                            (cond ,@more))))
84                   (if (eq t test)
85                       ;; THE to perserve non-toplevelness for FOO in
86                       ;;   (COND (T (FOO)))
87                       `(the t (progn ,@forms))
88                       `(if ,test
89                            (progn ,@forms)
90                            ,(when more `(cond ,@more))))))))))
91
92 (defmacro-mundanely when (test &body forms)
93   #!+sb-doc
94   "If the first argument is true, the rest of the forms are
95 evaluated as a PROGN."
96   `(if ,test (progn ,@forms) nil))
97
98 (defmacro-mundanely unless (test &body forms)
99   #!+sb-doc
100   "If the first argument is not true, the rest of the forms are
101 evaluated as a PROGN."
102   `(if ,test nil (progn ,@forms)))
103
104 (defmacro-mundanely and (&rest forms)
105   (cond ((endp forms) t)
106         ((endp (rest forms))
107          ;; Preserve non-toplevelness of the form!
108          `(the t ,(first forms)))
109         (t
110          `(if ,(first forms)
111               (and ,@(rest forms))
112               nil))))
113
114 (defmacro-mundanely or (&rest forms)
115   (cond ((endp forms) nil)
116         ((endp (rest forms))
117          ;; Preserve non-toplevelness of the form!
118          `(the t ,(first forms)))
119         (t
120          (let ((n-result (gensym)))
121            `(let ((,n-result ,(first forms)))
122               (if ,n-result
123                   ,n-result
124                   (or ,@(rest forms))))))))
125 \f
126 ;;;; various sequencing constructs
127
128 (flet ((prog-expansion-from-let (varlist body-decls let)
129          (multiple-value-bind (body decls)
130              (parse-body body-decls :doc-string-allowed nil)
131            `(block nil
132               (,let ,varlist
133                 ,@decls
134                 (tagbody ,@body))))))
135   (defmacro-mundanely prog (varlist &body body-decls)
136     (prog-expansion-from-let varlist body-decls 'let))
137   (defmacro-mundanely prog* (varlist &body body-decls)
138     (prog-expansion-from-let varlist body-decls 'let*)))
139
140 (defmacro-mundanely prog1 (result &body body)
141   (let ((n-result (gensym)))
142     `(let ((,n-result ,result))
143        ,@body
144        ,n-result)))
145
146 (defmacro-mundanely prog2 (form1 result &body body)
147   `(prog1 (progn ,form1 ,result) ,@body))
148 \f
149 ;;;; DEFUN
150
151 ;;; Should we save the inline expansion of the function named NAME?
152 (defun inline-fun-name-p (name)
153   (or
154    ;; the normal reason for saving the inline expansion
155    (info :function :inlinep name)
156    ;; another reason for saving the inline expansion: If the
157    ;; ANSI-recommended idiom
158    ;;   (DECLAIM (INLINE FOO))
159    ;;   (DEFUN FOO ..)
160    ;;   (DECLAIM (NOTINLINE FOO))
161    ;; has been used, and then we later do another
162    ;;   (DEFUN FOO ..)
163    ;; without a preceding
164    ;;   (DECLAIM (INLINE FOO))
165    ;; what should we do with the old inline expansion when we see the
166    ;; new DEFUN? Overwriting it with the new definition seems like
167    ;; the only unsurprising choice.
168    (info :function :inline-expansion-designator name)))
169
170 (defmacro-mundanely defun (&environment env name args &body body)
171   "Define a function at top level."
172   #+sb-xc-host
173   (unless (symbol-package (fun-name-block-name name))
174     (warn "DEFUN of uninterned function name ~S (tricky for GENESIS)" name))
175   (multiple-value-bind (forms decls doc) (parse-body body)
176     (let* (;; stuff shared between LAMBDA and INLINE-LAMBDA and NAMED-LAMBDA
177            (lambda-guts `(,args
178                           ,@decls
179                           (block ,(fun-name-block-name name)
180                             ,@forms)))
181            (lambda `(lambda ,@lambda-guts))
182            #-sb-xc-host
183            (named-lambda `(named-lambda ,name ,@lambda-guts))
184            (inline-lambda
185             (when (inline-fun-name-p name)
186               ;; we want to attempt to inline, so complain if we can't
187               (or (sb!c:maybe-inline-syntactic-closure lambda env)
188                   (progn
189                     (#+sb-xc-host warn
190                      #-sb-xc-host sb!c:maybe-compiler-notify
191                      "lexical environment too hairy, can't inline DEFUN ~S"
192                      name)
193                     nil)))))
194       `(progn
195          ;; In cross-compilation of toplevel DEFUNs, we arrange for
196          ;; the LAMBDA to be statically linked by GENESIS.
197          ;;
198          ;; It may seem strangely inconsistent not to use NAMED-LAMBDA
199          ;; here instead of LAMBDA. The reason is historical:
200          ;; COLD-FSET was written before NAMED-LAMBDA, and has special
201          ;; logic of its own to notify the compiler about NAME.
202          #+sb-xc-host
203          (cold-fset ,name ,lambda)
204
205          (eval-when (:compile-toplevel)
206            (sb!c:%compiler-defun ',name ',inline-lambda t))
207          (eval-when (:load-toplevel :execute)
208            (%defun ',name
209                    ;; In normal compilation (not for cold load) this is
210                    ;; where the compiled LAMBDA first appears. In
211                    ;; cross-compilation, we manipulate the
212                    ;; previously-statically-linked LAMBDA here.
213                    #-sb-xc-host ,named-lambda
214                    #+sb-xc-host (fdefinition ',name)
215                    ,doc
216                    ',inline-lambda
217                    (sb!c:source-location)))))))
218
219 #-sb-xc-host
220 (defun %defun (name def doc inline-lambda source-location)
221   (declare (type function def))
222   (declare (type (or null simple-string) doc))
223   (aver (legal-fun-name-p name)) ; should've been checked by DEFMACRO DEFUN
224   (sb!c:%compiler-defun name inline-lambda nil)
225   (when (fboundp name)
226     (/show0 "redefining NAME in %DEFUN")
227     (style-warn 'sb!kernel::redefinition-with-defun :name name
228                 :old (fdefinition name) :new def
229                 :new-location source-location))
230   (setf (sb!xc:fdefinition name) def)
231
232   (sb!c::note-name-defined name :function)
233
234   (when doc
235     (setf (fdocumentation name 'function) doc)
236     #!+sb-eval
237     (when (typep def 'sb!eval:interpreted-function)
238       (setf (sb!eval:interpreted-function-documentation def)
239             doc)))
240   name)
241 \f
242 ;;;; DEFVAR and DEFPARAMETER
243
244 (defmacro-mundanely defvar (var &optional (val nil valp) (doc nil docp))
245   #!+sb-doc
246   "Define a special variable at top level. Declare the variable
247   SPECIAL and, optionally, initialize it. If the variable already has a
248   value, the old value is not clobbered. The third argument is an optional
249   documentation string for the variable."
250   `(progn
251      (eval-when (:compile-toplevel)
252        (%compiler-defvar ',var))
253      (eval-when (:load-toplevel :execute)
254        (%defvar ',var (unless (boundp ',var) ,val)
255                 ',valp ,doc ',docp
256                 (sb!c:source-location)))))
257
258 (defmacro-mundanely defparameter (var val &optional (doc nil docp))
259   #!+sb-doc
260   "Define a parameter that is not normally changed by the program,
261   but that may be changed without causing an error. Declare the
262   variable special and sets its value to VAL, overwriting any
263   previous value. The third argument is an optional documentation
264   string for the parameter."
265   `(progn
266      (eval-when (:compile-toplevel)
267        (%compiler-defvar ',var))
268      (eval-when (:load-toplevel :execute)
269        (%defparameter ',var ,val ,doc ',docp (sb!c:source-location)))))
270
271 (defun %compiler-defvar (var)
272   (sb!xc:proclaim `(special ,var)))
273
274 #-sb-xc-host
275 (defun %defvar (var val valp doc docp source-location)
276   (%compiler-defvar var)
277   (when valp
278     (unless (boundp var)
279       (set var val)))
280   (when docp
281     (setf (fdocumentation var 'variable) doc))
282   (sb!c:with-source-location (source-location)
283     (setf (info :source-location :variable var) source-location))
284   var)
285
286 #-sb-xc-host
287 (defun %defparameter (var val doc docp source-location)
288   (%compiler-defvar var)
289   (set var val)
290   (when docp
291     (setf (fdocumentation var 'variable) doc))
292   (sb!c:with-source-location (source-location)
293     (setf (info :source-location :variable var) source-location))
294   var)
295 \f
296 ;;;; iteration constructs
297
298 ;;; (These macros are defined in terms of a function FROB-DO-BODY which
299 ;;; is also used by SB!INT:DO-ANONYMOUS. Since these macros should not
300 ;;; be loaded on the cross-compilation host, but SB!INT:DO-ANONYMOUS
301 ;;; and FROB-DO-BODY should be, these macros can't conveniently be in
302 ;;; the same file as FROB-DO-BODY.)
303 (defmacro-mundanely do (varlist endlist &body body)
304   #!+sb-doc
305   "DO ({(Var [Init] [Step])}*) (Test Exit-Form*) Declaration* Form*
306   Iteration construct. Each Var is initialized in parallel to the value of the
307   specified Init form. On subsequent iterations, the Vars are assigned the
308   value of the Step form (if any) in parallel. The Test is evaluated before
309   each evaluation of the body Forms. When the Test is true, the Exit-Forms
310   are evaluated as a PROGN, with the result being the value of the DO. A block
311   named NIL is established around the entire expansion, allowing RETURN to be
312   used as an alternate exit mechanism."
313   (frob-do-body varlist endlist body 'let 'psetq 'do nil))
314 (defmacro-mundanely do* (varlist endlist &body body)
315   #!+sb-doc
316   "DO* ({(Var [Init] [Step])}*) (Test Exit-Form*) Declaration* Form*
317   Iteration construct. Each Var is initialized sequentially (like LET*) to the
318   value of the specified Init form. On subsequent iterations, the Vars are
319   sequentially assigned the value of the Step form (if any). The Test is
320   evaluated before each evaluation of the body Forms. When the Test is true,
321   the Exit-Forms are evaluated as a PROGN, with the result being the value
322   of the DO. A block named NIL is established around the entire expansion,
323   allowing RETURN to be used as an laternate exit mechanism."
324   (frob-do-body varlist endlist body 'let* 'setq 'do* nil))
325
326 ;;; DOTIMES and DOLIST could be defined more concisely using
327 ;;; destructuring macro lambda lists or DESTRUCTURING-BIND, but then
328 ;;; it'd be tricky to use them before those things were defined.
329 ;;; They're used enough times before destructuring mechanisms are
330 ;;; defined that it looks as though it's worth just implementing them
331 ;;; ASAP, at the cost of being unable to use the standard
332 ;;; destructuring mechanisms.
333 (defmacro-mundanely dotimes ((var count &optional (result nil)) &body body)
334   (cond ((numberp count)
335         `(do ((,var 0 (1+ ,var)))
336              ((>= ,var ,count) ,result)
337            (declare (type unsigned-byte ,var))
338            ,@body))
339         (t
340          (let ((c (gensym "COUNT")))
341            `(do ((,var 0 (1+ ,var))
342                  (,c ,count))
343                 ((>= ,var ,c) ,result)
344               (declare (type unsigned-byte ,var)
345                        (type integer ,c))
346               ,@body)))))
347
348 (defmacro-mundanely dolist ((var list &optional (result nil)) &body body &environment env)
349   ;; We repeatedly bind the var instead of setting it so that we never
350   ;; have to give the var an arbitrary value such as NIL (which might
351   ;; conflict with a declaration). If there is a result form, we
352   ;; introduce a gratuitous binding of the variable to NIL without the
353   ;; declarations, then evaluate the result form in that
354   ;; environment. We spuriously reference the gratuitous variable,
355   ;; since we don't want to use IGNORABLE on what might be a special
356   ;; var.
357   (multiple-value-bind (forms decls) (parse-body body :doc-string-allowed nil)
358     (let* ((n-list (gensym "N-LIST"))
359            (start (gensym "START"))
360            (tmp (gensym "TMP")))
361       (multiple-value-bind (clist members clist-ok)
362           (cond ((sb!xc:constantp list env)
363                  (let ((value (constant-form-value list env)))
364                    (multiple-value-bind (all dot) (list-members value)
365                      (when dot
366                        ;; Full warning is too much: the user may terminate the loop
367                        ;; early enough. Contents are still right, though.
368                        (style-warn "Dotted list ~S in DOLIST." value))
369                      (values value all t))))
370                 ((and (consp list) (eq 'list (car list))
371                       (every (lambda (arg) (sb!xc:constantp arg env)) (cdr list)))
372                  (let ((values (mapcar (lambda (arg) (constant-form-value arg env)) (cdr list))))
373                    (values values values t)))
374                 (t
375                  (values nil nil nil)))
376         `(block nil
377            (let ((,n-list ,(if clist-ok (list 'quote clist) list)))
378              (tagbody
379                 ,start
380                 (unless (endp ,n-list)
381                   (let* (,@(if clist-ok
382                                `((,tmp (truly-the (member ,@members) (car ,n-list)))
383                                  (,var ,tmp))
384                                `((,var (car ,n-list)))))
385                     ,@decls
386                     (setq ,n-list (cdr ,n-list))
387                     (tagbody ,@forms))
388                   (go ,start))))
389            ,(if result
390                 `(let ((,var nil))
391                    ;; Filter out TYPE declarations (VAR gets bound to NIL,
392                    ;; and might have a conflicting type declaration) and
393                    ;; IGNORE (VAR might be ignored in the loop body, but
394                    ;; it's used in the result form).
395                    ,@(filter-dolist-declarations decls)
396                    ,var
397                    ,result)
398                 nil))))))
399 \f
400 ;;;; conditions, handlers, restarts
401
402 ;;; KLUDGE: we PROCLAIM these special here so that we can use restart
403 ;;; macros in the compiler before the DEFVARs are compiled.
404 (sb!xc:proclaim
405  '(special *handler-clusters* *restart-clusters* *condition-restarts*))
406
407 (defmacro-mundanely with-condition-restarts
408     (condition-form restarts-form &body body)
409   #!+sb-doc
410   "Evaluates the BODY in a dynamic environment where the restarts in the list
411    RESTARTS-FORM are associated with the condition returned by CONDITION-FORM.
412    This allows FIND-RESTART, etc., to recognize restarts that are not related
413    to the error currently being debugged. See also RESTART-CASE."
414   (let ((n-cond (gensym)))
415     `(let ((*condition-restarts*
416             (cons (let ((,n-cond ,condition-form))
417                     (cons ,n-cond
418                           (append ,restarts-form
419                                   (cdr (assoc ,n-cond *condition-restarts*)))))
420                   *condition-restarts*)))
421        ,@body)))
422
423 (defmacro-mundanely restart-bind (bindings &body forms)
424   #!+sb-doc
425   "Executes forms in a dynamic context where the given restart bindings are
426    in effect. Users probably want to use RESTART-CASE. When clauses contain
427    the same restart name, FIND-RESTART will find the first such clause."
428   `(let ((*restart-clusters*
429           (cons (list
430                  ,@(mapcar (lambda (binding)
431                              (unless (or (car binding)
432                                          (member :report-function
433                                                  binding
434                                                  :test #'eq))
435                                (warn "Unnamed restart does not have a ~
436                                       report function: ~S"
437                                      binding))
438                              `(make-restart :name ',(car binding)
439                                             :function ,(cadr binding)
440                                             ,@(cddr binding)))
441                            bindings))
442                 *restart-clusters*)))
443      ,@forms))
444
445 ;;; Wrap the RESTART-CASE expression in a WITH-CONDITION-RESTARTS if
446 ;;; appropriate. Gross, but it's what the book seems to say...
447 (defun munge-restart-case-expression (expression env)
448   (let ((exp (sb!xc:macroexpand expression env)))
449     (if (consp exp)
450         (let* ((name (car exp))
451                (args (if (eq name 'cerror) (cddr exp) (cdr exp))))
452           (if (member name '(signal error cerror warn))
453               (once-only ((n-cond `(coerce-to-condition
454                                     ,(first args)
455                                     (list ,@(rest args))
456                                     ',(case name
457                                         (warn 'simple-warning)
458                                         (signal 'simple-condition)
459                                         (t 'simple-error))
460                                     ',name)))
461                 `(with-condition-restarts
462                      ,n-cond
463                      (car *restart-clusters*)
464                    ,(if (eq name 'cerror)
465                         `(cerror ,(second exp) ,n-cond)
466                         `(,name ,n-cond))))
467               expression))
468         expression)))
469
470 ;;; FIXME: I did a fair amount of rearrangement of this code in order to
471 ;;; get WITH-KEYWORD-PAIRS to work cleanly. This code should be tested..
472 (defmacro-mundanely restart-case (expression &body clauses &environment env)
473   #!+sb-doc
474   "(RESTART-CASE form
475    {(case-name arg-list {keyword value}* body)}*)
476    The form is evaluated in a dynamic context where the clauses have special
477    meanings as points to which control may be transferred (see INVOKE-RESTART).
478    When clauses contain the same case-name, FIND-RESTART will find the first
479    such clause. If Expression is a call to SIGNAL, ERROR, CERROR or WARN (or
480    macroexpands into such) then the signalled condition will be associated with
481    the new restarts."
482   (flet ((transform-keywords (&key report interactive test)
483            (let ((result '()))
484              (when report
485                (setq result (list* (if (stringp report)
486                                        `#'(lambda (stream)
487                                             (write-string ,report stream))
488                                        `#',report)
489                                    :report-function
490                                    result)))
491              (when interactive
492                (setq result (list* `#',interactive
493                                    :interactive-function
494                                    result)))
495              (when test
496                (setq result (list* `#',test :test-function result)))
497              (nreverse result)))
498          (parse-keyword-pairs (list keys)
499            (do ((l list (cddr l))
500                 (k '() (list* (cadr l) (car l) k)))
501                ((or (null l) (not (member (car l) keys)))
502                 (values (nreverse k) l)))))
503     (let ((block-tag (sb!xc:gensym "BLOCK"))
504           (temp-var (gensym))
505           (data
506            (macrolet (;; KLUDGE: This started as an old DEFMACRO
507                       ;; WITH-KEYWORD-PAIRS general utility, which was used
508                       ;; only in this one place in the code. It was translated
509                       ;; literally into this MACROLET in order to avoid some
510                       ;; cross-compilation bootstrap problems. It would almost
511                       ;; certainly be clearer, and it would certainly be more
512                       ;; concise, to do a more idiomatic translation, merging
513                       ;; this with the TRANSFORM-KEYWORDS logic above.
514                       ;;   -- WHN 19990925
515                       (with-keyword-pairs ((names expression) &body forms)
516                         (let ((temp (member '&rest names)))
517                           (unless (= (length temp) 2)
518                             (error "&REST keyword is ~:[missing~;misplaced~]."
519                                    temp))
520                           (let* ((key-vars (ldiff names temp))
521                                  (keywords (mapcar #'keywordicate key-vars))
522                                  (key-var (gensym))
523                                  (rest-var (cadr temp)))
524                             `(multiple-value-bind (,key-var ,rest-var)
525                                  (parse-keyword-pairs ,expression ',keywords)
526                                (let ,(mapcar (lambda (var keyword)
527                                                `(,var (getf ,key-var
528                                                             ,keyword)))
529                                              key-vars keywords)
530                                  ,@forms))))))
531              (mapcar (lambda (clause)
532                        (with-keyword-pairs ((report interactive test
533                                                     &rest forms)
534                                             (cddr clause))
535                          (list (car clause) ;name=0
536                                (sb!xc:gensym "TAG") ;tag=1
537                                (transform-keywords :report report ;keywords=2
538                                                    :interactive interactive
539                                                    :test test)
540                                (cadr clause) ;bvl=3
541                                forms))) ;body=4
542                    clauses))))
543       `(block ,block-tag
544          (let ((,temp-var nil))
545            (tagbody
546             (restart-bind
547                 ,(mapcar (lambda (datum)
548                            (let ((name (nth 0 datum))
549                                  (tag  (nth 1 datum))
550                                  (keys (nth 2 datum)))
551                              `(,name #'(lambda (&rest temp)
552                                          (setq ,temp-var temp)
553                                          (go ,tag))
554                                      ,@keys)))
555                          data)
556               (return-from ,block-tag
557                            ,(munge-restart-case-expression expression env)))
558             ,@(mapcan (lambda (datum)
559                         (let ((tag  (nth 1 datum))
560                               (bvl  (nth 3 datum))
561                               (body (nth 4 datum)))
562                           (list tag
563                                 `(return-from ,block-tag
564                                    (apply (lambda ,bvl ,@body)
565                                           ,temp-var)))))
566                       data)))))))
567
568 (defmacro-mundanely with-simple-restart ((restart-name format-string
569                                                        &rest format-arguments)
570                                          &body forms)
571   #!+sb-doc
572   "(WITH-SIMPLE-RESTART (restart-name format-string format-arguments)
573    body)
574    If restart-name is not invoked, then all values returned by forms are
575    returned. If control is transferred to this restart, it immediately
576    returns the values NIL and T."
577   `(restart-case
578        ;; If there's just one body form, then don't use PROGN. This allows
579        ;; RESTART-CASE to "see" calls to ERROR, etc.
580        ,(if (= (length forms) 1) (car forms) `(progn ,@forms))
581      (,restart-name ()
582         :report (lambda (stream)
583                   (format stream ,format-string ,@format-arguments))
584       (values nil t))))
585
586 (defmacro-mundanely %handler-bind (bindings form)
587   (let ((member-if (member-if (lambda (x)
588                                 (not (proper-list-of-length-p x 2)))
589                               bindings)))
590     (when member-if
591       (error "ill-formed handler binding: ~S" (first member-if))))
592   (let* ((local-funs nil)
593          (mapped-bindings (mapcar (lambda (binding)
594                                     (destructuring-bind (type handler) binding
595                                       (let ((lambda-form handler))
596                                         (if (and (consp handler)
597                                                  (or (eq 'lambda (car handler))
598                                                      (and (eq 'function (car handler))
599                                                           (consp (cdr handler))
600                                                           (let ((x (second handler)))
601                                                             (and (consp x)
602                                                                  (eq 'lambda (car x))
603                                                                  (setf lambda-form x))))))
604                                             (let ((name (sb!xc:gensym "LAMBDA")))
605                                               (push `(,name ,@(cdr lambda-form)) local-funs)
606                                               (list type `(function ,name)))
607                                             binding))))
608                                   bindings)))
609     `(dx-flet (,@(reverse local-funs))
610        (let ((*handler-clusters*
611               (cons (list ,@(mapcar (lambda (x) `(cons ',(car x) ,(cadr x)))
612                                     mapped-bindings))
613                     *handler-clusters*)))
614          #!+stack-allocatable-fixed-objects
615          (declare (truly-dynamic-extent *handler-clusters*))
616          (progn ,form)))))
617
618 (defmacro-mundanely handler-bind (bindings &body forms)
619   #!+sb-doc
620   "(HANDLER-BIND ( {(type handler)}* )  body)
621
622 Executes body in a dynamic context where the given handler bindings are in
623 effect. Each handler must take the condition being signalled as an argument.
624 The bindings are searched first to last in the event of a signalled
625 condition."
626   `(%handler-bind ,bindings
627                   #!-x86 (progn ,@forms)
628                   ;; Need to catch FP errors here!
629                   #!+x86 (multiple-value-prog1 (progn ,@forms) (float-wait))))
630
631 (defmacro-mundanely handler-case (form &rest cases)
632   "(HANDLER-CASE form { (type ([var]) body) }* )
633
634 Execute FORM in a context with handlers established for the condition types. A
635 peculiar property allows type to be :NO-ERROR. If such a clause occurs, and
636 form returns normally, all its values are passed to this clause as if by
637 MULTIPLE-VALUE-CALL. The :NO-ERROR clause accepts more than one var
638 specification."
639   (let ((no-error-clause (assoc ':no-error cases)))
640     (if no-error-clause
641         (let ((normal-return (make-symbol "normal-return"))
642               (error-return  (make-symbol "error-return")))
643           `(block ,error-return
644              (multiple-value-call (lambda ,@(cdr no-error-clause))
645                (block ,normal-return
646                  (return-from ,error-return
647                    (handler-case (return-from ,normal-return ,form)
648                      ,@(remove no-error-clause cases)))))))
649         (let* ((local-funs nil)
650                (annotated-cases
651                 (mapcar (lambda (case)
652                           (with-unique-names (tag fun)
653                             (destructuring-bind (type ll &body body) case
654                               (push `(,fun ,ll ,@body) local-funs)
655                               (list tag type ll fun))))
656                         cases)))
657           (with-unique-names (block cell form-fun)
658             `(dx-flet ((,form-fun ()
659                          #!-x86 ,form
660                          ;; Need to catch FP errors here!
661                          #!+x86 (multiple-value-prog1 ,form (float-wait)))
662                        ,@(reverse local-funs))
663                (declare (optimize (sb!c::check-tag-existence 0)))
664                (block ,block
665                  ;; KLUDGE: We use a dx CONS cell instead of just assigning to
666                  ;; the variable directly, so that we can stack allocate
667                  ;; robustly: dx value cells don't work quite right, and it is
668                  ;; possible to construct user code that should loop
669                  ;; indefinitely, but instead eats up some stack each time
670                  ;; around.
671                  (dx-let ((,cell (cons :condition nil)))
672                    (declare (ignorable ,cell))
673                    (tagbody
674                       (%handler-bind
675                        ,(mapcar (lambda (annotated-case)
676                                   (destructuring-bind (tag type ll fun-name) annotated-case
677                                     (declare (ignore fun-name))
678                                     (list type
679                                           `(lambda (temp)
680                                              ,(if ll
681                                                   `(setf (cdr ,cell) temp)
682                                                   '(declare (ignore temp)))
683                                              (go ,tag)))))
684                                 annotated-cases)
685                        (return-from ,block (,form-fun)))
686                       ,@(mapcan
687                          (lambda (annotated-case)
688                            (destructuring-bind (tag type ll fun-name) annotated-case
689                              (declare (ignore type))
690                              (list tag
691                                    `(return-from ,block
692                                       ,(if ll
693                                            `(,fun-name (cdr ,cell))
694                                            `(,fun-name))))))
695                          annotated-cases))))))))))
696 \f
697 ;;;; miscellaneous
698
699 (defmacro-mundanely return (&optional (value nil))
700   `(return-from nil ,value))
701
702 (defmacro-mundanely psetq (&rest pairs)
703   #!+sb-doc
704   "PSETQ {var value}*
705    Set the variables to the values, like SETQ, except that assignments
706    happen in parallel, i.e. no assignments take place until all the
707    forms have been evaluated."
708   ;; Given the possibility of symbol-macros, we delegate to PSETF
709   ;; which knows how to deal with them, after checking that syntax is
710   ;; compatible with PSETQ.
711   (do ((pair pairs (cddr pair)))
712       ((endp pair) `(psetf ,@pairs))
713     (unless (symbolp (car pair))
714       (error 'simple-program-error
715              :format-control "variable ~S in PSETQ is not a SYMBOL"
716              :format-arguments (list (car pair))))))
717
718 (defmacro-mundanely lambda (&whole whole args &body body)
719   (declare (ignore args body))
720   `#',whole)
721
722 (defmacro-mundanely named-lambda (&whole whole name args &body body)
723   (declare (ignore name args body))
724   `#',whole)
725
726 (defmacro-mundanely lambda-with-lexenv (&whole whole
727                                         declarations macros symbol-macros
728                                         &body body)
729   (declare (ignore declarations macros symbol-macros body))
730   `#',whole)
731
732 ;;; this eliminates a whole bundle of unknown function STYLE-WARNINGs
733 ;;; when cross-compiling.  It's not critical for behaviour, but is
734 ;;; aesthetically pleasing, except inasmuch as there's this list of
735 ;;; magic functions here.  -- CSR, 2003-04-01
736 #+sb-xc-host
737 (sb!xc:proclaim '(ftype (function * *)
738                         ;; functions appearing in fundamental defining
739                         ;; macro expansions:
740                         %compiler-deftype
741                         %compiler-defvar
742                         %defun
743                         %defsetf
744                         %defparameter
745                         %defvar
746                         sb!c:%compiler-defun
747                         sb!c::%define-symbol-macro
748                         sb!c::%defconstant
749                         sb!c::%define-compiler-macro
750                         sb!c::%defmacro
751                         sb!kernel::%compiler-defstruct
752                         sb!kernel::%compiler-define-condition
753                         sb!kernel::%defstruct
754                         sb!kernel::%define-condition
755                         ;; miscellaneous functions commonly appearing
756                         ;; as a result of macro expansions or compiler
757                         ;; transformations:
758                         sb!int:find-undeleted-package-or-lose ; IN-PACKAGE
759                         sb!kernel::arg-count-error ; PARSE-DEFMACRO
760                         ))