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