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