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