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