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