Make COND a non-recursive macro
[sbcl.git] / src / code / defboot.lisp
blobd73e2409f0d6881ea71fa343c37d4a692e06b527
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.
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.
21 (in-package "SB!IMPL")
24 ;;;; IN-PACKAGE
26 (sb!xc:proclaim '(special *package*))
27 (sb!xc:defmacro in-package (string-designator)
28 (let ((string (string string-designator)))
29 `(eval-when (:compile-toplevel :load-toplevel :execute)
30 (setq *package* (find-undeleted-package-or-lose ,string)))))
32 ;;;; MULTIPLE-VALUE-FOO
34 (flet ((validate-vars (vars)
35 (unless (and (listp vars) (every #'symbolp vars))
36 (error "Vars is not a list of symbols: ~S" vars))))
38 (sb!xc:defmacro multiple-value-bind (vars value-form &body body)
39 (validate-vars vars)
40 (if (= (length vars) 1)
41 ;; Not only does it look nicer to reduce to LET in this special case,
42 ;; if might produce better code or at least compile quicker.
43 ;; Certainly for the evaluator it's preferable.
44 `(let ((,(car vars) ,value-form))
45 ,@body)
46 (let ((ignore (sb!xc:gensym)))
47 `(multiple-value-call #'(lambda (&optional ,@(mapcar #'list vars)
48 &rest ,ignore)
49 (declare (ignore ,ignore))
50 ,@body)
51 ,value-form))))
53 (sb!xc:defmacro multiple-value-setq (vars value-form)
54 (validate-vars 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))))
63 (sb!xc:defmacro multiple-value-list (value-form)
64 `(multiple-value-call #'list ,value-form))
66 ;;;; various conditional constructs
68 (flet ((prognify (forms)
69 (cond ((singleton-p forms) (car forms))
70 ((not forms) nil)
71 (t `(progn ,@forms)))))
72 ;; COND defined in terms of IF
73 (sb!xc:defmacro cond (&rest clauses)
74 (named-let make-clauses ((clauses clauses))
75 (if (endp clauses)
76 nil
77 (let ((clause (first clauses))
78 (more (rest clauses)))
79 (if (atom clause)
80 (error 'simple-type-error
81 :format-control "COND clause is not a ~S: ~S"
82 :format-arguments (list 'cons clause)
83 :expected-type 'cons
84 :datum clause)
85 (let ((test (first clause))
86 (forms (rest clause)))
87 (if (endp forms)
88 `(or ,test ,(make-clauses more))
89 (if (and (eq test t)
90 (not more))
91 ;; THE to preserve non-toplevelness for FOO in
92 ;; (COND (T (FOO)))
93 `(the t ,(prognify forms))
94 `(if ,test
95 ,(prognify forms)
96 ,(when more (make-clauses more)))))))))))
98 (sb!xc:defmacro when (test &body forms)
99 #!+sb-doc
100 "If the first argument is true, the rest of the forms are
101 evaluated as a PROGN."
102 `(if ,test ,(prognify forms)))
104 (sb!xc:defmacro unless (test &body forms)
105 #!+sb-doc
106 "If the first argument is not true, the rest of the forms are
107 evaluated as a PROGN."
108 `(if ,test nil ,(prognify forms))))
110 (sb!xc:defmacro and (&rest forms)
111 (cond ((endp forms) t)
112 ((endp (rest forms))
113 ;; Preserve non-toplevelness of the form!
114 `(the t ,(first forms)))
116 `(if ,(first forms)
117 (and ,@(rest forms))
118 nil))))
120 (sb!xc:defmacro or (&rest forms)
121 (cond ((endp forms) nil)
122 ((endp (rest forms))
123 ;; Preserve non-toplevelness of the form!
124 `(the t ,(first forms)))
126 (let ((n-result (gensym)))
127 `(let ((,n-result ,(first forms)))
128 (if ,n-result
129 ,n-result
130 (or ,@(rest forms))))))))
132 ;;;; various sequencing constructs
134 (flet ((prog-expansion-from-let (varlist body-decls let)
135 (multiple-value-bind (body decls) (parse-body body-decls nil)
136 `(block nil
137 (,let ,varlist
138 ,@decls
139 (tagbody ,@body))))))
140 (sb!xc:defmacro prog (varlist &body body-decls)
141 (prog-expansion-from-let varlist body-decls 'let))
142 (sb!xc:defmacro prog* (varlist &body body-decls)
143 (prog-expansion-from-let varlist body-decls 'let*)))
145 (sb!xc:defmacro prog1 (result &body body)
146 (let ((n-result (gensym)))
147 `(let ((,n-result ,result))
148 ,@body
149 ,n-result)))
151 (sb!xc:defmacro prog2 (form1 result &body body)
152 `(prog1 (progn ,form1 ,result) ,@body))
154 ;;;; DEFUN
156 ;;; Should we save the inline expansion of the function named NAME?
157 (defun inline-fun-name-p (name)
159 ;; the normal reason for saving the inline expansion
160 (let ((inlinep (info :function :inlinep name)))
161 (member inlinep '(:inline :maybe-inline)))
162 ;; another reason for saving the inline expansion: If the
163 ;; ANSI-recommended idiom
164 ;; (DECLAIM (INLINE FOO))
165 ;; (DEFUN FOO ..)
166 ;; (DECLAIM (NOTINLINE FOO))
167 ;; has been used, and then we later do another
168 ;; (DEFUN FOO ..)
169 ;; without a preceding
170 ;; (DECLAIM (INLINE FOO))
171 ;; what should we do with the old inline expansion when we see the
172 ;; new DEFUN? Overwriting it with the new definition seems like
173 ;; the only unsurprising choice.
174 (info :function :inline-expansion-designator name)))
176 (sb!xc:defmacro defun (&environment env name lambda-list &body body)
177 #!+sb-doc
178 "Define a function at top level."
179 #+sb-xc-host
180 (unless (symbol-package (fun-name-block-name name))
181 (warn "DEFUN of uninterned function name ~S (tricky for GENESIS)" name))
182 (multiple-value-bind (forms decls doc) (parse-body body t)
183 (let* (;; stuff shared between LAMBDA and INLINE-LAMBDA and NAMED-LAMBDA
184 (lambda-guts `(,@decls (block ,(fun-name-block-name name) ,@forms)))
185 (lambda `(lambda ,lambda-list ,@lambda-guts))
186 (named-lambda `(named-lambda ,name ,lambda-list
187 ,@(when doc (list doc)) ,@lambda-guts))
188 (inline-thing
189 (or (sb!kernel::defstruct-generated-defn-p name lambda-list body)
190 (when (inline-fun-name-p name)
191 ;; we want to attempt to inline, so complain if we can't
192 (acond ((sb!c:maybe-inline-syntactic-closure lambda env)
193 (list 'quote it))
195 (#+sb-xc-host warn
196 #-sb-xc-host sb!c:maybe-compiler-notify
197 "lexical environment too hairy, can't inline DEFUN ~S"
198 name)
199 nil))))))
200 `(progn
201 (eval-when (:compile-toplevel)
202 (sb!c:%compiler-defun ',name ,inline-thing t))
203 (%defun ',name ,named-lambda (sb!c:source-location)
204 ,@(and inline-thing (list inline-thing)))
205 ;; This warning, if produced, comes after the DEFUN happens.
206 ;; When compiling, there's no real difference, but when interpreting,
207 ;; if there is a handler for style-warning that nonlocally exits,
208 ;; it's wrong to have skipped the DEFUN itself, since if there is no
209 ;; function, then the warning ought not to have been issued at all.
210 ,@(when (typep name '(cons (eql setf)))
211 `((eval-when (:compile-toplevel :execute)
212 (sb!c::warn-if-setf-macro ',name))
213 ',name))))))
215 #-sb-xc-host
216 (defun %defun (name def source-location &optional inline-lambda)
217 (declare (type function def))
218 ;; should've been checked by DEFMACRO DEFUN
219 (aver (legal-fun-name-p name))
220 (sb!c:%compiler-defun name inline-lambda nil)
221 (when (fboundp name)
222 (warn 'redefinition-with-defun
223 :name name :new-function def :new-location source-location))
224 (setf (sb!xc:fdefinition name) def)
225 ;; %COMPILER-DEFUN doesn't do this except at compile-time, when it
226 ;; also checks package locks. By doing this here we let (SETF
227 ;; FDEFINITION) do the load-time package lock checking before
228 ;; we frob any existing inline expansions.
229 (sb!c::%set-inline-expansion name nil inline-lambda)
230 (sb!c::note-name-defined name :function)
231 name)
233 ;;;; DEFVAR and DEFPARAMETER
235 (sb!xc:defmacro defvar (var &optional (val nil valp) (doc nil docp))
236 #!+sb-doc
237 "Define a special variable at top level. Declare the variable
238 SPECIAL and, optionally, initialize it. If the variable already has a
239 value, the old value is not clobbered. The third argument is an optional
240 documentation string for the variable."
241 `(progn
242 (eval-when (:compile-toplevel)
243 (%compiler-defvar ',var))
244 (%defvar ',var
245 (sb!c:source-location)
246 ,@(and valp
247 `((unless (boundp ',var) ,val)))
248 ,@(and docp
249 `(',doc)))))
251 (sb!xc:defmacro defparameter (var val &optional (doc nil docp))
252 #!+sb-doc
253 "Define a parameter that is not normally changed by the program,
254 but that may be changed without causing an error. Declare the
255 variable special and sets its value to VAL, overwriting any
256 previous value. The third argument is an optional documentation
257 string for the parameter."
258 `(progn
259 (eval-when (:compile-toplevel)
260 (%compiler-defvar ',var))
261 (%defparameter ',var ,val (sb!c:source-location)
262 ,@(and docp
263 `(',doc)))))
265 (defun %compiler-defvar (var)
266 (sb!xc:proclaim `(special ,var)))
268 #-sb-xc-host
269 (defun %defvar (var source-location &optional (val nil valp) (doc nil docp))
270 (%compiler-defvar var)
271 (when (and valp
272 (not (boundp var)))
273 (set var val))
274 (when docp
275 (setf (fdocumentation var 'variable) doc))
276 (when source-location
277 (setf (info :source-location :variable var) source-location))
278 var)
280 #-sb-xc-host
281 (defun %defparameter (var val source-location &optional (doc nil docp))
282 (%compiler-defvar var)
283 (set var val)
284 (when docp
285 (setf (fdocumentation var 'variable) doc))
286 (when source-location
287 (setf (info :source-location :variable var) source-location))
288 var)
290 ;;;; iteration constructs
292 (flet
293 ((frob-do-body (varlist endlist decls-and-code bind step name block)
294 ;; Check for illegal old-style DO.
295 (when (or (not (listp varlist)) (atom endlist))
296 (error "ill-formed ~S -- possibly illegal old style DO?" name))
297 (collect ((steps))
298 (let ((inits
299 (mapcar (lambda (var)
300 (or (cond ((symbolp var) var)
301 ((listp var)
302 (unless (symbolp (first var))
303 (error "~S step variable is not a symbol: ~S"
304 name (first var)))
305 (case (length var)
306 ((1 2) var)
307 (3 (steps (first var) (third var))
308 (list (first var) (second var))))))
309 (error "~S is an illegal form for a ~S varlist."
310 var name)))
311 varlist)))
312 (multiple-value-bind (code decls) (parse-body decls-and-code nil)
313 (let ((label-1 (sb!xc:gensym)) (label-2 (sb!xc:gensym)))
314 `(block ,block
315 (,bind ,inits
316 ,@decls
317 (tagbody
318 (go ,label-2)
319 ,label-1
320 (tagbody ,@code)
321 (,step ,@(steps))
322 ,label-2
323 (unless ,(first endlist) (go ,label-1))
324 (return-from ,block (progn ,@(rest endlist))))))))))))
326 ;; This is like DO, except it has no implicit NIL block.
327 (sb!xc:defmacro do-anonymous (varlist endlist &rest body)
328 (frob-do-body varlist endlist body 'let 'psetq 'do-anonymous (sb!xc:gensym)))
330 (sb!xc:defmacro do (varlist endlist &body body)
331 #!+sb-doc
332 "DO ({(Var [Init] [Step])}*) (Test Exit-Form*) Declaration* Form*
333 Iteration construct. Each Var is initialized in parallel to the value of the
334 specified Init form. On subsequent iterations, the Vars are assigned the
335 value of the Step form (if any) in parallel. The Test is evaluated before
336 each evaluation of the body Forms. When the Test is true, the Exit-Forms
337 are evaluated as a PROGN, with the result being the value of the DO. A block
338 named NIL is established around the entire expansion, allowing RETURN to be
339 used as an alternate exit mechanism."
340 (frob-do-body varlist endlist body 'let 'psetq 'do nil))
342 (sb!xc:defmacro do* (varlist endlist &body body)
343 #!+sb-doc
344 "DO* ({(Var [Init] [Step])}*) (Test Exit-Form*) Declaration* Form*
345 Iteration construct. Each Var is initialized sequentially (like LET*) to the
346 value of the specified Init form. On subsequent iterations, the Vars are
347 sequentially assigned the value of the Step form (if any). The Test is
348 evaluated before each evaluation of the body Forms. When the Test is true,
349 the Exit-Forms are evaluated as a PROGN, with the result being the value
350 of the DO. A block named NIL is established around the entire expansion,
351 allowing RETURN to be used as an alternate exit mechanism."
352 (frob-do-body varlist endlist body 'let* 'setq 'do* nil)))
354 (sb!xc:defmacro dotimes ((var count &optional (result nil)) &body body)
355 ;; A nice optimization would be that if VAR is never referenced,
356 ;; it's slightly more efficient to count backwards, but that's tricky.
357 (let ((c (if (integerp count) count (sb!xc:gensym))))
358 `(do ((,var 0 (1+ ,var))
359 ,@(if (symbolp c) `((,c (the integer ,count)))))
360 ((>= ,var ,c) ,result)
361 (declare (type unsigned-byte ,var))
362 ,@body)))
364 (sb!xc:defmacro dolist ((var list &optional (result nil)) &body body &environment env)
365 ;; We repeatedly bind the var instead of setting it so that we never
366 ;; have to give the var an arbitrary value such as NIL (which might
367 ;; conflict with a declaration). If there is a result form, we
368 ;; introduce a gratuitous binding of the variable to NIL without the
369 ;; declarations, then evaluate the result form in that
370 ;; environment. We spuriously reference the gratuitous variable,
371 ;; since we don't want to use IGNORABLE on what might be a special
372 ;; var.
373 (multiple-value-bind (forms decls) (parse-body body nil)
374 (let* ((n-list (gensym "N-LIST"))
375 (start (gensym "START")))
376 (multiple-value-bind (clist members clist-ok)
377 (cond ((sb!xc:constantp list env)
378 (let ((value (constant-form-value list env)))
379 (multiple-value-bind (all dot) (list-members value :max-length 20)
380 (when (eql dot t)
381 ;; Full warning is too much: the user may terminate the loop
382 ;; early enough. Contents are still right, though.
383 (style-warn "Dotted list ~S in DOLIST." value))
384 (if (eql dot :maybe)
385 (values value nil nil)
386 (values value all t)))))
387 ((and (consp list) (eq 'list (car list))
388 (every (lambda (arg) (sb!xc:constantp arg env)) (cdr list)))
389 (let ((values (mapcar (lambda (arg) (constant-form-value arg env)) (cdr list))))
390 (values values values t)))
392 (values nil nil nil)))
393 `(block nil
394 (let ((,n-list ,(if clist-ok (list 'quote clist) list)))
395 (tagbody
396 ,start
397 (unless (endp ,n-list)
398 (let ((,var ,(if clist-ok
399 `(truly-the (member ,@members) (car ,n-list))
400 `(car ,n-list))))
401 ,@decls
402 (setq ,n-list (cdr ,n-list))
403 (tagbody ,@forms))
404 (go ,start))))
405 ,(if result
406 `(let ((,var nil))
407 ;; Filter out TYPE declarations (VAR gets bound to NIL,
408 ;; and might have a conflicting type declaration) and
409 ;; IGNORE (VAR might be ignored in the loop body, but
410 ;; it's used in the result form).
411 ,@(filter-dolist-declarations decls)
412 ,var
413 ,result)
414 nil))))))
416 ;;;; conditions, handlers, restarts
418 ;;; KLUDGE: we PROCLAIM these special here so that we can use restart
419 ;;; macros in the compiler before the DEFVARs are compiled.
421 ;;; For an explanation of these data structures, see DEFVARs in
422 ;;; target-error.lisp.
423 (sb!xc:proclaim '(special *handler-clusters* *restart-clusters*))
425 ;;; Generated code need not check for unbound-marker in *HANDLER-CLUSTERS*
426 ;;; (resp *RESTART-). To elicit this we must poke at the info db.
427 ;;; SB!XC:PROCLAIM SPECIAL doesn't advise the host Lisp that *HANDLER-CLUSTERS*
428 ;;; is special and so it rightfully complains about a SETQ of the variable.
429 ;;; But I must SETQ if proclaming ALWAYS-BOUND because the xc asks the host
430 ;;; whether it's currently bound.
431 ;;; But the DEFVARs are in target-error. So it's one hack or another.
432 (setf (info :variable :always-bound '*handler-clusters*)
433 #+sb-xc :always-bound #-sb-xc :eventually)
434 (setf (info :variable :always-bound '*restart-clusters*)
435 #+sb-xc :always-bound #-sb-xc :eventually)
437 (sb!xc:defmacro with-condition-restarts
438 (condition-form restarts-form &body body)
439 #!+sb-doc
440 "Evaluates the BODY in a dynamic environment where the restarts in the list
441 RESTARTS-FORM are associated with the condition returned by CONDITION-FORM.
442 This allows FIND-RESTART, etc., to recognize restarts that are not related
443 to the error currently being debugged. See also RESTART-CASE."
444 (once-only ((condition-form condition-form)
445 (restarts restarts-form))
446 (with-unique-names (restart)
447 ;; FIXME: check the need for interrupt-safety.
448 `(unwind-protect
449 (progn
450 (dolist (,restart ,restarts)
451 (push ,condition-form
452 (restart-associated-conditions ,restart)))
453 ,@body)
454 (dolist (,restart ,restarts)
455 (pop (restart-associated-conditions ,restart)))))))
457 (sb!xc:defmacro restart-bind (bindings &body forms)
458 #!+sb-doc
459 "(RESTART-BIND ({(case-name function {keyword value}*)}*) forms)
460 Executes forms in a dynamic context where the given bindings are in
461 effect. Users probably want to use RESTART-CASE. A case-name of NIL
462 indicates an anonymous restart. When bindings contain the same
463 restart name, FIND-RESTART will find the first such binding."
464 (flet ((parse-binding (binding)
465 (unless (>= (length binding) 2)
466 (error "ill-formed restart binding: ~S" binding))
467 (destructuring-bind (name function
468 &key interactive-function
469 test-function
470 report-function)
471 binding
472 (unless (or name report-function)
473 (warn "Unnamed restart does not have a report function: ~
474 ~S" binding))
475 `(make-restart ',name ,function
476 ,@(and (or report-function
477 interactive-function
478 test-function)
479 `(,report-function))
480 ,@(and (or interactive-function
481 test-function)
482 `(,interactive-function))
483 ,@(and test-function
484 `(,test-function))))))
485 `(let ((*restart-clusters*
486 (cons (list ,@(mapcar #'parse-binding bindings))
487 *restart-clusters*)))
488 (declare (truly-dynamic-extent *restart-clusters*))
489 ,@forms)))
491 ;;; Wrap the RESTART-CASE expression in a WITH-CONDITION-RESTARTS if
492 ;;; appropriate. Gross, but it's what the book seems to say...
493 (defun munge-restart-case-expression (expression env)
494 (let ((exp (%macroexpand expression env)))
495 (if (consp exp)
496 (let* ((name (car exp))
497 (args (if (eq name 'cerror) (cddr exp) (cdr exp))))
498 (if (member name '(signal error cerror warn))
499 (once-only ((n-cond `(coerce-to-condition
500 ,(first args)
501 (list ,@(rest args))
502 ',(case name
503 (warn 'simple-warning)
504 (signal 'simple-condition)
505 (t 'simple-error))
506 ',name)))
507 `(with-condition-restarts
508 ,n-cond
509 (car *restart-clusters*)
510 ,(if (eq name 'cerror)
511 `(cerror ,(second exp) ,n-cond)
512 `(,name ,n-cond))))
513 expression))
514 expression)))
516 (sb!xc:defmacro restart-case (expression &body clauses &environment env)
517 #!+sb-doc
518 "(RESTART-CASE form {(case-name arg-list {keyword value}* body)}*)
519 The form is evaluated in a dynamic context where the clauses have
520 special meanings as points to which control may be transferred (see
521 INVOKE-RESTART). When clauses contain the same case-name,
522 FIND-RESTART will find the first such clause. If form is a call to
523 SIGNAL, ERROR, CERROR or WARN (or macroexpands into such) then the
524 signalled condition will be associated with the new restarts."
525 ;; PARSE-CLAUSE (which uses PARSE-KEYWORDS-AND-BODY) is used to
526 ;; parse all clauses into lists of the form
528 ;; (NAME TAG KEYWORDS LAMBDA-LIST BODY)
530 ;; where KEYWORDS are suitable keywords for use in HANDLER-BIND
531 ;; bindings. These lists are then passed to
532 ;; * MAKE-BINDING which generates bindings for the respective NAME
533 ;; for HANDLER-BIND
534 ;; * MAKE-APPLY-AND-RETURN which generates TAGBODY entries executing
535 ;; the respective BODY.
536 (let ((block-tag (sb!xc:gensym "BLOCK"))
537 (temp-var (gensym)))
538 (labels ((parse-keywords-and-body (keywords-and-body)
539 (do ((form keywords-and-body (cddr form))
540 (result '())) (nil)
541 (destructuring-bind (&optional key (arg nil argp) &rest rest)
542 form
543 (declare (ignore rest))
544 (setq result
545 (append
546 (cond
547 ((and (eq key :report) argp)
548 (list :report-function
549 (if (stringp arg)
550 `#'(lambda (stream)
551 (write-string ,arg stream))
552 `#',arg)))
553 ((and (eq key :interactive) argp)
554 (list :interactive-function `#',arg))
555 ((and (eq key :test) argp)
556 (list :test-function `#',arg))
558 (return (values result form))))
559 result)))))
560 (parse-clause (clause)
561 (unless (and (listp clause) (>= (length clause) 2)
562 (listp (second clause)))
563 (error "ill-formed ~S clause, no lambda-list:~% ~S"
564 'restart-case clause))
565 (destructuring-bind (name lambda-list &body body) clause
566 (multiple-value-bind (keywords body)
567 (parse-keywords-and-body body)
568 (list name (sb!xc:gensym "TAG") keywords lambda-list body))))
569 (make-binding (clause-data)
570 (destructuring-bind (name tag keywords lambda-list body) clause-data
571 (declare (ignore body))
572 `(,name
573 (lambda ,(cond ((null lambda-list)
575 ((and (null (cdr lambda-list))
576 (not (member (car lambda-list)
577 '(&optional &key &aux))))
578 '(temp))
580 '(&rest temp)))
581 ,@(when lambda-list `((setq ,temp-var temp)))
582 (locally (declare (optimize (safety 0)))
583 (go ,tag)))
584 ,@keywords)))
585 (make-apply-and-return (clause-data)
586 (destructuring-bind (name tag keywords lambda-list body) clause-data
587 (declare (ignore name keywords))
588 `(,tag (return-from ,block-tag
589 ,(cond ((null lambda-list)
590 `(progn ,@body))
591 ((and (null (cdr lambda-list))
592 (not (member (car lambda-list)
593 '(&optional &key &aux))))
594 `(funcall (lambda ,lambda-list ,@body) ,temp-var))
596 `(apply (lambda ,lambda-list ,@body) ,temp-var))))))))
597 (let ((clauses-data (mapcar #'parse-clause clauses)))
598 `(block ,block-tag
599 (let ((,temp-var nil))
600 (declare (ignorable ,temp-var))
601 (tagbody
602 (restart-bind
603 ,(mapcar #'make-binding clauses-data)
604 (return-from ,block-tag
605 ,(munge-restart-case-expression expression env)))
606 ,@(mapcan #'make-apply-and-return clauses-data))))))))
608 (sb!xc:defmacro with-simple-restart ((restart-name format-string
609 &rest format-arguments)
610 &body forms)
611 #!+sb-doc
612 "(WITH-SIMPLE-RESTART (restart-name format-string format-arguments)
613 body)
614 If restart-name is not invoked, then all values returned by forms are
615 returned. If control is transferred to this restart, it immediately
616 returns the values NIL and T."
617 (let ((stream (sb!xc:gensym "STREAM")))
618 `(restart-case
619 ;; If there's just one body form, then don't use PROGN. This allows
620 ;; RESTART-CASE to "see" calls to ERROR, etc.
621 ,(if (= (length forms) 1) (car forms) `(progn ,@forms))
622 (,restart-name ()
623 :report (lambda (,stream)
624 (declare (type stream ,stream))
625 (format ,stream ,format-string ,@format-arguments))
626 (values nil t)))))
628 (sb!xc:defmacro %handler-bind (bindings form &environment env)
629 (unless bindings
630 (return-from %handler-bind form))
631 ;; As an optimization, this looks at the handler parts of BINDINGS
632 ;; and turns handlers of the forms (lambda ...) and (function
633 ;; (lambda ...)) into local, dynamic-extent functions.
635 ;; Type specifiers in BINDINGS which name classoids are parsed
636 ;; into the classoid, otherwise are translated local TYPEP wrappers.
638 ;; As a further optimization, it is possible to eliminate some runtime
639 ;; consing (which is a speed win if not a space win, since it's dx already)
640 ;; in special cases such as (HANDLER-BIND ((WARNING #'MUFFLE-WARNING)) ...).
641 ;; If all bindings are optimizable, then the runtime cost of making them
642 ;; is one dx cons cell for the whole cluster.
643 ;; Otherwise it takes 1+2N cons cells where N is the number of bindings.
645 (collect ((local-functions) (cluster-entries) (dummy-forms))
646 (flet ((const-cons (test handler)
647 ;; If possible, render HANDLER as a load-time constant so that
648 ;; consing the test and handler is also load-time constant.
649 (let ((name (when (typep handler
650 '(cons (member function quote)
651 (cons symbol null)))
652 (cadr handler))))
653 (cond ((or (not name)
654 (assq name (local-functions))
655 (and (eq (car handler) 'function)
656 (sb!c::fun-locally-defined-p name env)))
657 `(cons ,(case (car test)
658 ((named-lambda function) test)
659 (t `(load-time-value ,test t)))
660 ,(if (typep handler '(cons (eql function)))
661 handler
662 ;; Regardless of lexical policy, never allow
663 ;; a non-callable into handler-clusters.
664 `(let ((x ,handler))
665 (declare (optimize (safety 3)))
666 (the callable x)))))
667 ((info :function :info name) ; known
668 ;; This takes care of CONTINUE,ABORT,MUFFLE-WARNING.
669 ;; #' will be evaluated in the null environment.
670 `(load-time-value (cons ,test #',name) t))
672 ;; For each handler specified as #'F we must verify
673 ;; that F is fboundp upon entering the binding scope.
674 ;; Referencing #'F is enough to ensure a warning if the
675 ;; function isn't defined at compile-time, but the
676 ;; compiler considers it elidable unless something forces
677 ;; an apparent use of the form at runtime,
678 ;; so instead use SAFE-FDEFN-FUN on the fdefn.
679 (when (eq (car handler) 'function)
680 (dummy-forms `(sb!c:safe-fdefn-fun
681 (load-time-value
682 (find-or-create-fdefn ',name) t))))
683 ;; Resolve to an fdefn at load-time.
684 `(load-time-value
685 (cons ,test (find-or-create-fdefn ',name))
686 t)))))
688 (const-list (items)
689 ;; If the resultant list is (LIST (L-T-V ...) (L-T-V ...) ...)
690 ;; then pull the L-T-V outside.
691 (if (every (lambda (x) (typep x '(cons (eql load-time-value))))
692 items)
693 `(load-time-value (list ,@(mapcar #'second items)) t)
694 `(list ,@items))))
696 (dolist (binding bindings)
697 (unless (proper-list-of-length-p binding 2)
698 (error "ill-formed handler binding: ~S" binding))
699 (destructuring-bind (type handler) binding
700 (setq type (typexpand type env))
701 ;; Simplify a singleton AND or OR.
702 (when (typep type '(cons (member and or) (cons t null)))
703 (setf type (second type)))
704 (cluster-entries
705 (const-cons
706 ;; Compute the test expression
707 (cond ((member type '(t condition))
708 ;; Every signal is necesarily a CONDITION, so whether you
709 ;; wrote T or CONDITION, this is always an eligible handler.
710 '#'constantly-t)
711 ((typep type '(cons (eql satisfies) (cons t null)))
712 ;; (SATISFIES F) => #'F but never a local definition of F.
713 ;; The predicate is used only if needed - it's not an error
714 ;; if not fboundp (though dangerously stupid) - so just
715 ;; reference #'F for the compiler to see the use of the name.
716 ;; But (KLUDGE): since the ref is to force a compile-time
717 ;; effect, the interpreter should not see that form,
718 ;; because there is no way for it to perform an unsafe ref,
719 ;; (and it wouldn't signal a style-warning anyway),
720 ;; and so it would actually fail immediately if predicate
721 ;; were not defined.
722 (let ((name (second type)))
723 (when (typep env 'lexenv)
724 (dummy-forms `#',name))
725 `(find-or-create-fdefn ',name)))
726 ((and (symbolp type)
727 (condition-classoid-p (find-classoid type nil)))
728 ;; It's debatable whether we need to go through a
729 ;; classoid-cell instead of just using load-time-value
730 ;; on FIND-CLASS, but the extra indirection is
731 ;; safer, and no slower than what TYPEP does.
732 `(find-classoid-cell ',type :create t))
733 (t ; No runtime consing here- this is not a closure.
734 `(named-lambda (%handler-bind ,type) (c)
735 (declare (optimize (sb!c::verify-arg-count 0)))
736 (typep c ',type))))
737 ;; Compute the handler expression
738 (let ((lexpr (typecase handler
739 ((cons (eql lambda)) handler)
740 ((cons (eql function)
741 (cons (cons (eql lambda)) null))
742 (cadr handler)))))
743 (if lexpr
744 (let ((name (let ((sb!xc:*gensym-counter*
745 (length (cluster-entries))))
746 (sb!xc:gensym "H"))))
747 (local-functions `(,name ,@(rest lexpr)))
748 `#',name)
749 handler))))))
751 `(dx-flet ,(local-functions)
752 ,@(dummy-forms)
753 (dx-let ((*handler-clusters*
754 (cons ,(const-list (cluster-entries))
755 *handler-clusters*)))
756 ,form)))))
758 (sb!xc:defmacro handler-bind (bindings &body forms)
759 #!+sb-doc
760 "(HANDLER-BIND ( {(type handler)}* ) body)
762 Executes body in a dynamic context where the given handler bindings are in
763 effect. Each handler must take the condition being signalled as an argument.
764 The bindings are searched first to last in the event of a signalled
765 condition."
766 ;; Bindings which meet specific criteria can be established with
767 ;; slightly less runtime overhead than in general.
768 ;; To allow the optimization, TYPE must be either be (SATISFIES P)
769 ;; or a symbol naming a condition class at compile time,
770 ;; and HANDLER must be a global function specified as either 'F or #'F.
771 `(%handler-bind ,bindings
772 #!-x86 (progn ,@forms)
773 ;; Need to catch FP errors here!
774 #!+x86 (multiple-value-prog1 (progn ,@forms) (float-wait))))
776 (sb!xc:defmacro handler-case (form &rest cases)
777 #!+sb-doc
778 "(HANDLER-CASE form { (type ([var]) body) }* )
780 Execute FORM in a context with handlers established for the condition types. A
781 peculiar property allows type to be :NO-ERROR. If such a clause occurs, and
782 form returns normally, all its values are passed to this clause as if by
783 MULTIPLE-VALUE-CALL. The :NO-ERROR clause accepts more than one var
784 specification."
785 (let ((no-error-clause (assoc ':no-error cases)))
786 (if no-error-clause
787 (let ((normal-return (make-symbol "normal-return"))
788 (error-return (make-symbol "error-return")))
789 `(block ,error-return
790 (multiple-value-call (lambda ,@(cdr no-error-clause))
791 (block ,normal-return
792 (return-from ,error-return
793 (handler-case (return-from ,normal-return ,form)
794 ,@(remove no-error-clause cases)))))))
795 (let* ((local-funs nil)
796 (annotated-cases
797 (mapcar (lambda (case)
798 (with-unique-names (tag fun)
799 (destructuring-bind (type ll &body body) case
800 (push `(,fun ,ll ,@body) local-funs)
801 (list tag type ll fun))))
802 cases)))
803 (with-unique-names (block cell form-fun)
804 `(dx-flet ((,form-fun ()
805 #!-x86 ,form
806 ;; Need to catch FP errors here!
807 #!+x86 (multiple-value-prog1 ,form (float-wait)))
808 ,@(reverse local-funs))
809 (declare (optimize (sb!c::check-tag-existence 0)))
810 (block ,block
811 ;; KLUDGE: We use a dx CONS cell instead of just assigning to
812 ;; the variable directly, so that we can stack allocate
813 ;; robustly: dx value cells don't work quite right, and it is
814 ;; possible to construct user code that should loop
815 ;; indefinitely, but instead eats up some stack each time
816 ;; around.
817 (dx-let ((,cell (cons :condition nil)))
818 (declare (ignorable ,cell))
819 (tagbody
820 (%handler-bind
821 ,(mapcar (lambda (annotated-case)
822 (destructuring-bind (tag type ll fun-name) annotated-case
823 (declare (ignore fun-name))
824 (list type
825 `(lambda (temp)
826 ,(if ll
827 `(setf (cdr ,cell) temp)
828 '(declare (ignore temp)))
829 (go ,tag)))))
830 annotated-cases)
831 (return-from ,block (,form-fun)))
832 ,@(mapcan
833 (lambda (annotated-case)
834 (destructuring-bind (tag type ll fun-name) annotated-case
835 (declare (ignore type))
836 (list tag
837 `(return-from ,block
838 ,(if ll
839 `(,fun-name (cdr ,cell))
840 `(,fun-name))))))
841 annotated-cases))))))))))
843 ;;;; miscellaneous
845 (sb!xc:defmacro return (&optional (value nil))
846 `(return-from nil ,value))
848 (sb!xc:defmacro lambda (&whole whole args &body body)
849 (declare (ignore args body))
850 `#',whole)
852 (sb!xc:defmacro named-lambda (&whole whole name args &body body)
853 (declare (ignore name args body))
854 `#',whole)
856 (sb!xc:defmacro lambda-with-lexenv (&whole whole
857 declarations macros symbol-macros
858 &body body)
859 (declare (ignore declarations macros symbol-macros body))
860 `#',whole)