1.0.48.28: make TRULY-THE macroexpandable
[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     (warn 'sb!kernel::redefinition-with-defun
228           :name name
229           :new-function def
230           :new-location source-location))
231   (setf (sb!xc:fdefinition name) def)
232   ;; %COMPILER-DEFUN doesn't do this except at compile-time, when it
233   ;; also checks package locks. By doing this here we let (SETF
234   ;; FDEFINITION) do the load-time package lock checking before
235   ;; we frob any existing inline expansions.
236   (sb!c::%set-inline-expansion name nil inline-lambda)
237
238   (sb!c::note-name-defined name :function)
239
240   (when doc
241     (setf (%fun-doc def) doc))
242
243   name)
244 \f
245 ;;;; DEFVAR and DEFPARAMETER
246
247 (defmacro-mundanely defvar (var &optional (val nil valp) (doc nil docp))
248   #!+sb-doc
249   "Define a special variable at top level. Declare the variable
250   SPECIAL and, optionally, initialize it. If the variable already has a
251   value, the old value is not clobbered. The third argument is an optional
252   documentation string for the variable."
253   `(progn
254      (eval-when (:compile-toplevel)
255        (%compiler-defvar ',var))
256      (eval-when (:load-toplevel :execute)
257        (%defvar ',var (unless (boundp ',var) ,val)
258                 ',valp ,doc ',docp
259                 (sb!c:source-location)))))
260
261 (defmacro-mundanely defparameter (var val &optional (doc nil docp))
262   #!+sb-doc
263   "Define a parameter that is not normally changed by the program,
264   but that may be changed without causing an error. Declare the
265   variable special and sets its value to VAL, overwriting any
266   previous value. The third argument is an optional documentation
267   string for the parameter."
268   `(progn
269      (eval-when (:compile-toplevel)
270        (%compiler-defvar ',var))
271      (eval-when (:load-toplevel :execute)
272        (%defparameter ',var ,val ,doc ',docp (sb!c:source-location)))))
273
274 (defun %compiler-defvar (var)
275   (sb!xc:proclaim `(special ,var)))
276
277 #-sb-xc-host
278 (defun %defvar (var val valp doc docp source-location)
279   (%compiler-defvar var)
280   (when valp
281     (unless (boundp var)
282       (set var val)))
283   (when docp
284     (setf (fdocumentation var 'variable) doc))
285   (sb!c:with-source-location (source-location)
286     (setf (info :source-location :variable var) source-location))
287   var)
288
289 #-sb-xc-host
290 (defun %defparameter (var val doc docp source-location)
291   (%compiler-defvar var)
292   (set var val)
293   (when docp
294     (setf (fdocumentation var 'variable) doc))
295   (sb!c:with-source-location (source-location)
296     (setf (info :source-location :variable var) source-location))
297   var)
298 \f
299 ;;;; iteration constructs
300
301 ;;; (These macros are defined in terms of a function FROB-DO-BODY which
302 ;;; is also used by SB!INT:DO-ANONYMOUS. Since these macros should not
303 ;;; be loaded on the cross-compilation host, but SB!INT:DO-ANONYMOUS
304 ;;; and FROB-DO-BODY should be, these macros can't conveniently be in
305 ;;; the same file as FROB-DO-BODY.)
306 (defmacro-mundanely do (varlist endlist &body body)
307   #!+sb-doc
308   "DO ({(Var [Init] [Step])}*) (Test Exit-Form*) Declaration* Form*
309   Iteration construct. Each Var is initialized in parallel to the value of the
310   specified Init form. On subsequent iterations, the Vars are assigned the
311   value of the Step form (if any) in parallel. The Test is evaluated before
312   each evaluation of the body Forms. When the Test is true, the Exit-Forms
313   are evaluated as a PROGN, with the result being the value of the DO. A block
314   named NIL is established around the entire expansion, allowing RETURN to be
315   used as an alternate exit mechanism."
316   (frob-do-body varlist endlist body 'let 'psetq 'do nil))
317 (defmacro-mundanely do* (varlist endlist &body body)
318   #!+sb-doc
319   "DO* ({(Var [Init] [Step])}*) (Test Exit-Form*) Declaration* Form*
320   Iteration construct. Each Var is initialized sequentially (like LET*) to the
321   value of the specified Init form. On subsequent iterations, the Vars are
322   sequentially assigned the value of the Step form (if any). The Test is
323   evaluated before each evaluation of the body Forms. When the Test is true,
324   the Exit-Forms are evaluated as a PROGN, with the result being the value
325   of the DO. A block named NIL is established around the entire expansion,
326   allowing RETURN to be used as an laternate exit mechanism."
327   (frob-do-body varlist endlist body 'let* 'setq 'do* nil))
328
329 ;;; DOTIMES and DOLIST could be defined more concisely using
330 ;;; destructuring macro lambda lists or DESTRUCTURING-BIND, but then
331 ;;; it'd be tricky to use them before those things were defined.
332 ;;; They're used enough times before destructuring mechanisms are
333 ;;; defined that it looks as though it's worth just implementing them
334 ;;; ASAP, at the cost of being unable to use the standard
335 ;;; destructuring mechanisms.
336 (defmacro-mundanely dotimes ((var count &optional (result nil)) &body body)
337   (cond ((integerp count)
338         `(do ((,var 0 (1+ ,var)))
339              ((>= ,var ,count) ,result)
340            (declare (type unsigned-byte ,var))
341            ,@body))
342         (t
343          (let ((c (gensym "COUNT")))
344            `(do ((,var 0 (1+ ,var))
345                  (,c ,count))
346                 ((>= ,var ,c) ,result)
347               (declare (type unsigned-byte ,var)
348                        (type integer ,c))
349               ,@body)))))
350
351 (defmacro-mundanely dolist ((var list &optional (result nil)) &body body &environment env)
352   ;; We repeatedly bind the var instead of setting it so that we never
353   ;; have to give the var an arbitrary value such as NIL (which might
354   ;; conflict with a declaration). If there is a result form, we
355   ;; introduce a gratuitous binding of the variable to NIL without the
356   ;; declarations, then evaluate the result form in that
357   ;; environment. We spuriously reference the gratuitous variable,
358   ;; since we don't want to use IGNORABLE on what might be a special
359   ;; var.
360   (multiple-value-bind (forms decls) (parse-body body :doc-string-allowed nil)
361     (let* ((n-list (gensym "N-LIST"))
362            (start (gensym "START"))
363            (tmp (gensym "TMP")))
364       (multiple-value-bind (clist members clist-ok)
365           (cond ((sb!xc:constantp list env)
366                  (let ((value (constant-form-value list env)))
367                    (multiple-value-bind (all dot) (list-members value)
368                      (when dot
369                        ;; Full warning is too much: the user may terminate the loop
370                        ;; early enough. Contents are still right, though.
371                        (style-warn "Dotted list ~S in DOLIST." value))
372                      (values value all t))))
373                 ((and (consp list) (eq 'list (car list))
374                       (every (lambda (arg) (sb!xc:constantp arg env)) (cdr list)))
375                  (let ((values (mapcar (lambda (arg) (constant-form-value arg env)) (cdr list))))
376                    (values values values t)))
377                 (t
378                  (values nil nil nil)))
379         `(block nil
380            (let ((,n-list ,(if clist-ok (list 'quote clist) list)))
381              (tagbody
382                 ,start
383                 (unless (endp ,n-list)
384                   (let* (,@(if clist-ok
385                                `((,tmp (truly-the (member ,@members) (car ,n-list)))
386                                  (,var ,tmp))
387                                `((,var (car ,n-list)))))
388                     ,@decls
389                     (setq ,n-list (cdr ,n-list))
390                     (tagbody ,@forms))
391                   (go ,start))))
392            ,(if result
393                 `(let ((,var nil))
394                    ;; Filter out TYPE declarations (VAR gets bound to NIL,
395                    ;; and might have a conflicting type declaration) and
396                    ;; IGNORE (VAR might be ignored in the loop body, but
397                    ;; it's used in the result form).
398                    ,@(filter-dolist-declarations decls)
399                    ,var
400                    ,result)
401                 nil))))))
402 \f
403 ;;;; conditions, handlers, restarts
404
405 ;;; KLUDGE: we PROCLAIM these special here so that we can use restart
406 ;;; macros in the compiler before the DEFVARs are compiled.
407 (sb!xc:proclaim
408  '(special *handler-clusters* *restart-clusters* *condition-restarts*))
409
410 (defmacro-mundanely with-condition-restarts
411     (condition-form restarts-form &body body)
412   #!+sb-doc
413   "Evaluates the BODY in a dynamic environment where the restarts in the list
414    RESTARTS-FORM are associated with the condition returned by CONDITION-FORM.
415    This allows FIND-RESTART, etc., to recognize restarts that are not related
416    to the error currently being debugged. See also RESTART-CASE."
417   (let ((n-cond (gensym)))
418     `(let ((*condition-restarts*
419             (cons (let ((,n-cond ,condition-form))
420                     (cons ,n-cond
421                           (append ,restarts-form
422                                   (cdr (assoc ,n-cond *condition-restarts*)))))
423                   *condition-restarts*)))
424        ,@body)))
425
426 (defmacro-mundanely restart-bind (bindings &body forms)
427   #!+sb-doc
428   "Executes forms in a dynamic context where the given restart bindings are
429    in effect. Users probably want to use RESTART-CASE. When clauses contain
430    the same restart name, FIND-RESTART will find the first such clause."
431   `(let ((*restart-clusters*
432           (cons (list
433                  ,@(mapcar (lambda (binding)
434                              (unless (or (car binding)
435                                          (member :report-function
436                                                  binding
437                                                  :test #'eq))
438                                (warn "Unnamed restart does not have a ~
439                                       report function: ~S"
440                                      binding))
441                              `(make-restart :name ',(car binding)
442                                             :function ,(cadr binding)
443                                             ,@(cddr binding)))
444                            bindings))
445                 *restart-clusters*)))
446      ,@forms))
447
448 ;;; Wrap the RESTART-CASE expression in a WITH-CONDITION-RESTARTS if
449 ;;; appropriate. Gross, but it's what the book seems to say...
450 (defun munge-restart-case-expression (expression env)
451   (let ((exp (%macroexpand expression env)))
452     (if (consp exp)
453         (let* ((name (car exp))
454                (args (if (eq name 'cerror) (cddr exp) (cdr exp))))
455           (if (member name '(signal error cerror warn))
456               (once-only ((n-cond `(coerce-to-condition
457                                     ,(first args)
458                                     (list ,@(rest args))
459                                     ',(case name
460                                         (warn 'simple-warning)
461                                         (signal 'simple-condition)
462                                         (t 'simple-error))
463                                     ',name)))
464                 `(with-condition-restarts
465                      ,n-cond
466                      (car *restart-clusters*)
467                    ,(if (eq name 'cerror)
468                         `(cerror ,(second exp) ,n-cond)
469                         `(,name ,n-cond))))
470               expression))
471         expression)))
472
473 ;;; FIXME: I did a fair amount of rearrangement of this code in order to
474 ;;; get WITH-KEYWORD-PAIRS to work cleanly. This code should be tested..
475 (defmacro-mundanely restart-case (expression &body clauses &environment env)
476   #!+sb-doc
477   "(RESTART-CASE form
478    {(case-name arg-list {keyword value}* body)}*)
479    The form is evaluated in a dynamic context where the clauses have special
480    meanings as points to which control may be transferred (see INVOKE-RESTART).
481    When clauses contain the same case-name, FIND-RESTART will find the first
482    such clause. If Expression is a call to SIGNAL, ERROR, CERROR or WARN (or
483    macroexpands into such) then the signalled condition will be associated with
484    the new restarts."
485   (flet ((transform-keywords (&key report interactive test)
486            (let ((result '()))
487              (when report
488                (setq result (list* (if (stringp report)
489                                        `#'(lambda (stream)
490                                             (write-string ,report stream))
491                                        `#',report)
492                                    :report-function
493                                    result)))
494              (when interactive
495                (setq result (list* `#',interactive
496                                    :interactive-function
497                                    result)))
498              (when test
499                (setq result (list* `#',test :test-function result)))
500              (nreverse result)))
501          (parse-keyword-pairs (list keys)
502            (do ((l list (cddr l))
503                 (k '() (list* (cadr l) (car l) k)))
504                ((or (null l) (not (member (car l) keys)))
505                 (values (nreverse k) l)))))
506     (let ((block-tag (sb!xc:gensym "BLOCK"))
507           (temp-var (gensym))
508           (data
509            (macrolet (;; KLUDGE: This started as an old DEFMACRO
510                       ;; WITH-KEYWORD-PAIRS general utility, which was used
511                       ;; only in this one place in the code. It was translated
512                       ;; literally into this MACROLET in order to avoid some
513                       ;; cross-compilation bootstrap problems. It would almost
514                       ;; certainly be clearer, and it would certainly be more
515                       ;; concise, to do a more idiomatic translation, merging
516                       ;; this with the TRANSFORM-KEYWORDS logic above.
517                       ;;   -- WHN 19990925
518                       (with-keyword-pairs ((names expression) &body forms)
519                         (let ((temp (member '&rest names)))
520                           (unless (= (length temp) 2)
521                             (error "&REST keyword is ~:[missing~;misplaced~]."
522                                    temp))
523                           (let* ((key-vars (ldiff names temp))
524                                  (keywords (mapcar #'keywordicate key-vars))
525                                  (key-var (gensym))
526                                  (rest-var (cadr temp)))
527                             `(multiple-value-bind (,key-var ,rest-var)
528                                  (parse-keyword-pairs ,expression ',keywords)
529                                (let ,(mapcar (lambda (var keyword)
530                                                `(,var (getf ,key-var
531                                                             ,keyword)))
532                                              key-vars keywords)
533                                  ,@forms))))))
534              (mapcar (lambda (clause)
535                        (unless (listp (second clause))
536                          (error "Malformed ~S clause, no lambda-list:~%  ~S"
537                                 'restart-case clause))
538                        (with-keyword-pairs ((report interactive test
539                                                     &rest forms)
540                                             (cddr clause))
541                          (list (car clause) ;name=0
542                                (sb!xc:gensym "TAG") ;tag=1
543                                (transform-keywords :report report ;keywords=2
544                                                    :interactive interactive
545                                                    :test test)
546                                (cadr clause) ;bvl=3
547                                forms))) ;body=4
548                    clauses))))
549       `(block ,block-tag
550          (let ((,temp-var nil))
551            (tagbody
552             (restart-bind
553                 ,(mapcar (lambda (datum)
554                            (let ((name (nth 0 datum))
555                                  (tag  (nth 1 datum))
556                                  (keys (nth 2 datum)))
557                              `(,name #'(lambda (&rest temp)
558                                          (setq ,temp-var temp)
559                                          (go ,tag))
560                                      ,@keys)))
561                          data)
562               (return-from ,block-tag
563                            ,(munge-restart-case-expression expression env)))
564             ,@(mapcan (lambda (datum)
565                         (let ((tag  (nth 1 datum))
566                               (bvl  (nth 3 datum))
567                               (body (nth 4 datum)))
568                           (list tag
569                                 `(return-from ,block-tag
570                                    (apply (lambda ,bvl ,@body)
571                                           ,temp-var)))))
572                       data)))))))
573
574 (defmacro-mundanely with-simple-restart ((restart-name format-string
575                                                        &rest format-arguments)
576                                          &body forms)
577   #!+sb-doc
578   "(WITH-SIMPLE-RESTART (restart-name format-string format-arguments)
579    body)
580    If restart-name is not invoked, then all values returned by forms are
581    returned. If control is transferred to this restart, it immediately
582    returns the values NIL and T."
583   `(restart-case
584        ;; If there's just one body form, then don't use PROGN. This allows
585        ;; RESTART-CASE to "see" calls to ERROR, etc.
586        ,(if (= (length forms) 1) (car forms) `(progn ,@forms))
587      (,restart-name ()
588         :report (lambda (stream)
589                   (format stream ,format-string ,@format-arguments))
590       (values nil t))))
591
592 (defmacro-mundanely %handler-bind (bindings form)
593   (let ((member-if (member-if (lambda (x)
594                                 (not (proper-list-of-length-p x 2)))
595                               bindings)))
596     (when member-if
597       (error "ill-formed handler binding: ~S" (first member-if))))
598   (let* ((local-funs nil)
599          (mapped-bindings (mapcar (lambda (binding)
600                                     (destructuring-bind (type handler) binding
601                                       (let ((lambda-form handler))
602                                         (if (and (consp handler)
603                                                  (or (eq 'lambda (car handler))
604                                                      (and (eq 'function (car handler))
605                                                           (consp (cdr handler))
606                                                           (let ((x (second handler)))
607                                                             (and (consp x)
608                                                                  (eq 'lambda (car x))
609                                                                  (setf lambda-form x))))))
610                                             (let ((name (sb!xc:gensym "LAMBDA")))
611                                               (push `(,name ,@(cdr lambda-form)) local-funs)
612                                               (list type `(function ,name)))
613                                             binding))))
614                                   bindings)))
615     `(dx-flet (,@(reverse local-funs))
616        (let ((*handler-clusters*
617               (cons (list ,@(mapcar (lambda (x) `(cons ',(car x) ,(cadr x)))
618                                     mapped-bindings))
619                     *handler-clusters*)))
620          #!+stack-allocatable-fixed-objects
621          (declare (truly-dynamic-extent *handler-clusters*))
622          (progn ,form)))))
623
624 (defmacro-mundanely handler-bind (bindings &body forms)
625   #!+sb-doc
626   "(HANDLER-BIND ( {(type handler)}* )  body)
627
628 Executes body in a dynamic context where the given handler bindings are in
629 effect. Each handler must take the condition being signalled as an argument.
630 The bindings are searched first to last in the event of a signalled
631 condition."
632   `(%handler-bind ,bindings
633                   #!-x86 (progn ,@forms)
634                   ;; Need to catch FP errors here!
635                   #!+x86 (multiple-value-prog1 (progn ,@forms) (float-wait))))
636
637 (defmacro-mundanely handler-case (form &rest cases)
638   "(HANDLER-CASE form { (type ([var]) body) }* )
639
640 Execute FORM in a context with handlers established for the condition types. A
641 peculiar property allows type to be :NO-ERROR. If such a clause occurs, and
642 form returns normally, all its values are passed to this clause as if by
643 MULTIPLE-VALUE-CALL. The :NO-ERROR clause accepts more than one var
644 specification."
645   (let ((no-error-clause (assoc ':no-error cases)))
646     (if no-error-clause
647         (let ((normal-return (make-symbol "normal-return"))
648               (error-return  (make-symbol "error-return")))
649           `(block ,error-return
650              (multiple-value-call (lambda ,@(cdr no-error-clause))
651                (block ,normal-return
652                  (return-from ,error-return
653                    (handler-case (return-from ,normal-return ,form)
654                      ,@(remove no-error-clause cases)))))))
655         (let* ((local-funs nil)
656                (annotated-cases
657                 (mapcar (lambda (case)
658                           (with-unique-names (tag fun)
659                             (destructuring-bind (type ll &body body) case
660                               (push `(,fun ,ll ,@body) local-funs)
661                               (list tag type ll fun))))
662                         cases)))
663           (with-unique-names (block cell form-fun)
664             `(dx-flet ((,form-fun ()
665                          #!-x86 ,form
666                          ;; Need to catch FP errors here!
667                          #!+x86 (multiple-value-prog1 ,form (float-wait)))
668                        ,@(reverse local-funs))
669                (declare (optimize (sb!c::check-tag-existence 0)))
670                (block ,block
671                  ;; KLUDGE: We use a dx CONS cell instead of just assigning to
672                  ;; the variable directly, so that we can stack allocate
673                  ;; robustly: dx value cells don't work quite right, and it is
674                  ;; possible to construct user code that should loop
675                  ;; indefinitely, but instead eats up some stack each time
676                  ;; around.
677                  (dx-let ((,cell (cons :condition nil)))
678                    (declare (ignorable ,cell))
679                    (tagbody
680                       (%handler-bind
681                        ,(mapcar (lambda (annotated-case)
682                                   (destructuring-bind (tag type ll fun-name) annotated-case
683                                     (declare (ignore fun-name))
684                                     (list type
685                                           `(lambda (temp)
686                                              ,(if ll
687                                                   `(setf (cdr ,cell) temp)
688                                                   '(declare (ignore temp)))
689                                              (go ,tag)))))
690                                 annotated-cases)
691                        (return-from ,block (,form-fun)))
692                       ,@(mapcan
693                          (lambda (annotated-case)
694                            (destructuring-bind (tag type ll fun-name) annotated-case
695                              (declare (ignore type))
696                              (list tag
697                                    `(return-from ,block
698                                       ,(if ll
699                                            `(,fun-name (cdr ,cell))
700                                            `(,fun-name))))))
701                          annotated-cases))))))))))
702 \f
703 ;;;; miscellaneous
704
705 (defmacro-mundanely return (&optional (value nil))
706   `(return-from nil ,value))
707
708 (defmacro-mundanely psetq (&rest pairs)
709   #!+sb-doc
710   "PSETQ {var value}*
711    Set the variables to the values, like SETQ, except that assignments
712    happen in parallel, i.e. no assignments take place until all the
713    forms have been evaluated."
714   ;; Given the possibility of symbol-macros, we delegate to PSETF
715   ;; which knows how to deal with them, after checking that syntax is
716   ;; compatible with PSETQ.
717   (do ((pair pairs (cddr pair)))
718       ((endp pair) `(psetf ,@pairs))
719     (unless (symbolp (car pair))
720       (error 'simple-program-error
721              :format-control "variable ~S in PSETQ is not a SYMBOL"
722              :format-arguments (list (car pair))))))
723
724 (defmacro-mundanely lambda (&whole whole args &body body)
725   (declare (ignore args body))
726   `#',whole)
727
728 (defmacro-mundanely named-lambda (&whole whole name args &body body)
729   (declare (ignore name args body))
730   `#',whole)
731
732 (defmacro-mundanely lambda-with-lexenv (&whole whole
733                                         declarations macros symbol-macros
734                                         &body body)
735   (declare (ignore declarations macros symbol-macros body))
736   `#',whole)
737
738 ;;; this eliminates a whole bundle of unknown function STYLE-WARNINGs
739 ;;; when cross-compiling.  It's not critical for behaviour, but is
740 ;;; aesthetically pleasing, except inasmuch as there's this list of
741 ;;; magic functions here.  -- CSR, 2003-04-01
742 #+sb-xc-host
743 (sb!xc:proclaim '(ftype (function * *)
744                         ;; functions appearing in fundamental defining
745                         ;; macro expansions:
746                         %compiler-deftype
747                         %compiler-defvar
748                         %defun
749                         %defsetf
750                         %defparameter
751                         %defvar
752                         sb!c:%compiler-defun
753                         sb!c::%define-symbol-macro
754                         sb!c::%defconstant
755                         sb!c::%define-compiler-macro
756                         sb!c::%defmacro
757                         sb!kernel::%compiler-defstruct
758                         sb!kernel::%compiler-define-condition
759                         sb!kernel::%defstruct
760                         sb!kernel::%define-condition
761                         ;; miscellaneous functions commonly appearing
762                         ;; as a result of macro expansions or compiler
763                         ;; transformations:
764                         sb!int:find-undeleted-package-or-lose ; IN-PACKAGE
765                         sb!kernel::arg-count-error ; PARSE-DEFMACRO
766                         ))