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