0.pre8.84:
[sbcl.git] / src / code / target-error.lisp
1 ;;;; that part of the condition system which can or should come early
2 ;;;; (mostly macro-related)
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!KERNEL")
14 \f
15 ;;;; restarts
16
17 ;;; a list of lists of restarts
18 (defvar *restart-clusters* '())
19
20 ;;; an ALIST (condition . restarts) which records the restarts currently
21 ;;; associated with Condition
22 (defvar *condition-restarts* ())
23
24 (defstruct (restart (:copier nil) (:predicate nil))
25   (name (missing-arg) :type symbol :read-only t)
26   (function (missing-arg) :type function)
27   (report-function nil :type (or null function))
28   (interactive-function nil :type (or null function))
29   (test-function (lambda (cond) (declare (ignore cond)) t) :type function))
30 (def!method print-object ((restart restart) stream)
31   (if *print-escape*
32       (print-unreadable-object (restart stream :type t :identity t)
33         (prin1 (restart-name restart) stream))
34       (restart-report restart stream)))
35
36 (defun compute-restarts (&optional condition)
37   #!+sb-doc
38   "Return a list of all the currently active restarts ordered from most
39    recently established to less recently established. If CONDITION is
40    specified, then only restarts associated with CONDITION (or with no
41    condition) will be returned."
42   (let ((associated ())
43         (other ()))
44     (dolist (alist *condition-restarts*)
45       (if (eq (car alist) condition)
46           (setq associated (cdr alist))
47           (setq other (append (cdr alist) other))))
48     (collect ((res))
49       (dolist (restart-cluster *restart-clusters*)
50         (dolist (restart restart-cluster)
51           (when (and (or (not condition)
52                          (member restart associated)
53                          (not (member restart other)))
54                      (funcall (restart-test-function restart)
55                               condition))
56             (res restart))))
57       (res))))
58
59 #!+sb-doc
60 (setf (fdocumentation 'restart-name 'function)
61       "Return the name of the given restart object.")
62
63 (defun restart-report (restart stream)
64   (funcall (or (restart-report-function restart)
65                (let ((name (restart-name restart)))
66                  (lambda (stream)
67                    (if name (format stream "~S" name)
68                        (format stream "~S" restart)))))
69            stream))
70
71 (defmacro with-condition-restarts (condition-form restarts-form &body body)
72   #!+sb-doc
73   "WITH-CONDITION-RESTARTS Condition-Form Restarts-Form Form*
74    Evaluates the Forms in a dynamic environment where the restarts in the list
75    Restarts-Form are associated with the condition returned by Condition-Form.
76    This allows FIND-RESTART, etc., to recognize restarts that are not related
77    to the error currently being debugged. See also RESTART-CASE."
78   (let ((n-cond (gensym)))
79     `(let ((*condition-restarts*
80             (cons (let ((,n-cond ,condition-form))
81                     (cons ,n-cond
82                           (append ,restarts-form
83                                   (cdr (assoc ,n-cond *condition-restarts*)))))
84                   *condition-restarts*)))
85        ,@body)))
86
87 (defmacro restart-bind (bindings &body forms)
88   #!+sb-doc
89   "Executes forms in a dynamic context where the given restart bindings are
90    in effect. Users probably want to use RESTART-CASE. When clauses contain
91    the same restart name, FIND-RESTART will find the first such clause."
92   `(let ((*restart-clusters*
93           (cons (list
94                  ,@(mapcar (lambda (binding)
95                              (unless (or (car binding)
96                                          (member :report-function
97                                                  binding
98                                                  :test #'eq))
99                                (warn "Unnamed restart does not have a ~
100                                         report function: ~S"
101                                      binding))
102                              `(make-restart :name ',(car binding)
103                                             :function ,(cadr binding)
104                                             ,@(cddr binding)))
105                            bindings))
106                 *restart-clusters*)))
107      ,@forms))
108
109 (defun find-restart (name &optional condition)
110   #!+sb-doc
111   "Return the first restart named NAME. If NAME names a restart, the restart
112    is returned if it is currently active. If no such restart is found, NIL is
113    returned. It is an error to supply NIL as a name. If CONDITION is specified
114    and not NIL, then only restarts associated with that condition (or with no
115    condition) will be returned."
116   (let ((restarts (compute-restarts condition)))
117     (declare (type list restarts))
118     (find-if (lambda (x)
119                (or (eq x name)
120                    (eq (restart-name x) name)))
121              restarts)))
122
123 (defun find-restart-or-lose (restart-designator)
124   (let ((real-restart (find-restart restart-designator)))
125     (unless real-restart
126       (error 'simple-control-error
127              :format-control "Restart ~S is not active."
128              :format-arguments (list restart-designator)))
129     real-restart))
130
131 (defun invoke-restart (restart &rest values)
132   #!+sb-doc
133   "Calls the function associated with the given restart, passing any given
134    arguments. If the argument restart is not a restart or a currently active
135    non-nil restart name, then a control-error is signalled."
136   (/show "entering INVOKE-RESTART" restart)
137   (let ((real-restart (find-restart-or-lose restart)))
138     (apply (restart-function real-restart) values)))
139
140 (defun interactive-restart-arguments (real-restart)
141   (let ((interactive-function (restart-interactive-function real-restart)))
142     (if interactive-function
143         (funcall interactive-function)
144         '())))
145
146 (defun invoke-restart-interactively (restart)
147   #!+sb-doc
148   "Calls the function associated with the given restart, prompting for any
149    necessary arguments. If the argument restart is not a restart or a
150    currently active non-nil restart name, then a control-error is signalled."
151   (let* ((real-restart (find-restart-or-lose restart))
152          (args (interactive-restart-arguments real-restart)))
153     (apply (restart-function real-restart) args)))
154
155 (eval-when (:compile-toplevel :load-toplevel :execute)
156 ;;; Wrap the RESTART-CASE expression in a WITH-CONDITION-RESTARTS if
157 ;;; appropriate. Gross, but it's what the book seems to say...
158 (defun munge-restart-case-expression (expression env)
159   (let ((exp (sb!xc:macroexpand expression env)))
160     (if (consp exp)
161         (let* ((name (car exp))
162                (args (if (eq name 'cerror) (cddr exp) (cdr exp))))
163           (if (member name '(signal error cerror warn))
164               (once-only ((n-cond `(coerce-to-condition
165                                     ,(first args)
166                                     (list ,@(rest args))
167                                     ',(case name
168                                         (warn 'simple-warning)
169                                         (signal 'simple-condition)
170                                         (t 'simple-error))
171                                     ',name)))
172                 `(with-condition-restarts
173                      ,n-cond
174                      (car *restart-clusters*)
175                    ,(if (eq name 'cerror)
176                         `(cerror ,(second expression) ,n-cond)
177                         `(,name ,n-cond))))
178               expression))
179         expression)))
180 ) ; EVAL-WHEN
181
182 ;;; FIXME: I did a fair amount of rearrangement of this code in order to
183 ;;; get WITH-KEYWORD-PAIRS to work cleanly. This code should be tested..
184 (defmacro restart-case (expression &body clauses &environment env)
185   #!+sb-doc
186   "(RESTART-CASE form
187    {(case-name arg-list {keyword value}* body)}*)
188    The form is evaluated in a dynamic context where the clauses have special
189    meanings as points to which control may be transferred (see INVOKE-RESTART).
190    When clauses contain the same case-name, FIND-RESTART will find the first
191    such clause. If Expression is a call to SIGNAL, ERROR, CERROR or WARN (or
192    macroexpands into such) then the signalled condition will be associated with
193    the new restarts."
194   (flet ((transform-keywords (&key report interactive test)
195            (let ((result '()))
196              (when report
197                (setq result (list* (if (stringp report)
198                                        `#'(lambda (stream)
199                                             (write-string ,report stream))
200                                        `#',report)
201                                    :report-function
202                                    result)))
203              (when interactive
204                (setq result (list* `#',interactive
205                                    :interactive-function
206                                    result)))
207              (when test
208                (setq result (list* `#',test :test-function result)))
209              (nreverse result)))
210          (parse-keyword-pairs (list keys)
211            (do ((l list (cddr l))
212                 (k '() (list* (cadr l) (car l) k)))
213                ((or (null l) (not (member (car l) keys)))
214                 (values (nreverse k) l)))))
215     (let ((block-tag (gensym))
216           (temp-var (gensym))
217           (data
218            (macrolet (;; KLUDGE: This started as an old DEFMACRO
219                       ;; WITH-KEYWORD-PAIRS general utility, which was used
220                       ;; only in this one place in the code. It was translated
221                       ;; literally into this MACROLET in order to avoid some
222                       ;; cross-compilation bootstrap problems. It would almost
223                       ;; certainly be clearer, and it would certainly be more
224                       ;; concise, to do a more idiomatic translation, merging
225                       ;; this with the TRANSFORM-KEYWORDS logic above.
226                       ;;   -- WHN 19990925
227                       (with-keyword-pairs ((names expression) &body forms)
228                         (let ((temp (member '&rest names)))
229                           (unless (= (length temp) 2)
230                             (error "&REST keyword is ~:[missing~;misplaced~]."
231                                    temp))
232                           (let* ((key-vars (ldiff names temp))
233                                  (keywords (mapcar #'keywordicate key-vars))
234                                  (key-var (gensym))
235                                  (rest-var (cadr temp)))
236                             `(multiple-value-bind (,key-var ,rest-var)
237                                  (parse-keyword-pairs ,expression ',keywords)
238                                (let ,(mapcar (lambda (var keyword)
239                                                `(,var (getf ,key-var
240                                                             ,keyword)))
241                                              key-vars keywords)
242                                  ,@forms))))))
243              (mapcar (lambda (clause)
244                        (with-keyword-pairs ((report interactive test
245                                                     &rest forms)
246                                             (cddr clause))
247                          (list (car clause) ;name=0
248                                (gensym) ;tag=1
249                                (transform-keywords :report report ;keywords=2
250                                                    :interactive interactive
251                                                    :test test)
252                                (cadr clause) ;bvl=3
253                                forms))) ;body=4
254                    clauses))))
255       `(block ,block-tag
256          (let ((,temp-var nil))
257            (tagbody
258             (restart-bind
259                 ,(mapcar (lambda (datum)
260                            (let ((name (nth 0 datum))
261                                  (tag  (nth 1 datum))
262                                  (keys (nth 2 datum)))
263                              `(,name #'(lambda (&rest temp)
264                                          (setq ,temp-var temp)
265                                          (go ,tag))
266                                      ,@keys)))
267                          data)
268               (return-from ,block-tag
269                            ,(munge-restart-case-expression expression env)))
270             ,@(mapcan (lambda (datum)
271                         (let ((tag  (nth 1 datum))
272                               (bvl  (nth 3 datum))
273                               (body (nth 4 datum)))
274                           (list tag
275                                 `(return-from ,block-tag
276                                    (apply (lambda ,bvl ,@body)
277                                           ,temp-var)))))
278                       data)))))))
279
280 (defmacro with-simple-restart ((restart-name format-string
281                                              &rest format-arguments)
282                                &body forms)
283   #!+sb-doc
284   "(WITH-SIMPLE-RESTART (restart-name format-string format-arguments)
285    body)
286    If restart-name is not invoked, then all values returned by forms are
287    returned. If control is transferred to this restart, it immediately
288    returns the values NIL and T."
289   `(restart-case
290        ;; If there's just one body form, then don't use PROGN. This allows
291        ;; RESTART-CASE to "see" calls to ERROR, etc.
292        ,(if (= (length forms) 1) (car forms) `(progn ,@forms))
293      (,restart-name ()
294         :report (lambda (stream)
295                   (format stream ,format-string ,@format-arguments))
296       (values nil t))))
297 \f
298 ;;;; HANDLER-BIND
299
300 (defvar *handler-clusters* nil)
301
302 (defmacro handler-bind (bindings &body forms)
303   #!+sb-doc
304   "(HANDLER-BIND ( {(type handler)}* )  body)
305    Executes body in a dynamic context where the given handler bindings are
306    in effect. Each handler must take the condition being signalled as an
307    argument. The bindings are searched first to last in the event of a
308    signalled condition."
309   (let ((member-if (member-if (lambda (x)
310                                 (not (proper-list-of-length-p x 2)))
311                               bindings)))
312     (when member-if
313       (error "ill-formed handler binding: ~S" (first member-if))))
314   `(let ((*handler-clusters*
315           (cons (list ,@(mapcar (lambda (x) `(cons ',(car x) ,(cadr x)))
316                                 bindings))
317                 *handler-clusters*)))
318      (multiple-value-prog1
319          (progn
320            ,@forms)
321        ;; Wait for any float exceptions.
322        #!+x86 (float-wait))))
323 \f
324 ;;;; HANDLER-CASE
325
326 (defmacro handler-case (form &rest cases)
327   "(HANDLER-CASE form
328    { (type ([var]) body) }* )
329    Execute FORM in a context with handlers established for the condition
330    types. A peculiar property allows type to be :NO-ERROR. If such a clause
331    occurs, and form returns normally, all its values are passed to this clause
332    as if by MULTIPLE-VALUE-CALL.  The :NO-ERROR clause accepts more than one
333    var specification."
334
335   ;; FIXME: Replacing CADR, CDDDR and friends with DESTRUCTURING-BIND
336   ;; and names for the subexpressions would make it easier to
337   ;; understand the code below.
338   (let ((no-error-clause (assoc ':no-error cases)))
339     (if no-error-clause
340         (let ((normal-return (make-symbol "normal-return"))
341               (error-return  (make-symbol "error-return")))
342           `(block ,error-return
343              (multiple-value-call (lambda ,@(cdr no-error-clause))
344                (block ,normal-return
345                  (return-from ,error-return
346                    (handler-case (return-from ,normal-return ,form)
347                      ,@(remove no-error-clause cases)))))))
348         (let ((tag (gensym))
349               (var (gensym))
350               (annotated-cases (mapcar (lambda (case) (cons (gensym) case))
351                                        cases)))
352           `(block ,tag
353              (let ((,var nil))
354                (declare (ignorable ,var))
355                (tagbody
356                 (handler-bind
357                     ,(mapcar (lambda (annotated-case)
358                                (list (cadr annotated-case)
359                                      `(lambda (temp)
360                                         ,(if (caddr annotated-case)
361                                              `(setq ,var temp)
362                                              '(declare (ignore temp)))
363                                         (go ,(car annotated-case)))))
364                              annotated-cases)
365                   (return-from ,tag
366                     #!-x86 ,form
367                     #!+x86 (multiple-value-prog1 ,form
368                              ;; Need to catch FP errors here!
369                              (float-wait))))
370                 ,@(mapcan
371                    (lambda (annotated-case)
372                      (list (car annotated-case)
373                            (let ((body (cdddr annotated-case)))
374                              `(return-from
375                                   ,tag
376                                 ,(cond ((caddr annotated-case)
377                                         `(let ((,(caaddr annotated-case)
378                                                 ,var))
379                                            ,@body))
380                                        ((not (cdr body))
381                                         (car body))
382                                        (t
383                                         `(progn ,@body)))))))
384                    annotated-cases))))))))
385 \f
386 ;;;; helper functions for restartable error handling which couldn't be
387 ;;;; defined 'til now 'cause they use the RESTART-CASE macro
388
389 (defun assert-error (assertion places datum &rest arguments)
390   (let ((cond (if datum
391                 (coerce-to-condition datum
392                                                     arguments
393                                                     'simple-error
394                                                     'error)
395                 (make-condition 'simple-error
396                                 :format-control "The assertion ~S failed."
397                                 :format-arguments (list assertion)))))
398     (restart-case
399         (error cond)
400       (continue ()
401                 :report (lambda (stream)
402                           (format stream "Retry assertion")
403                           (if places
404                               (format stream
405                                       " with new value~P for ~{~S~^, ~}."
406                                       (length places)
407                                       places)
408                               (format stream ".")))
409                 nil))))
410
411 ;;; READ-EVALUATED-FORM is used as the interactive method for restart cases
412 ;;; setup by the Common Lisp "casing" (e.g., CCASE and CTYPECASE) macros
413 ;;; and by CHECK-TYPE.
414 (defun read-evaluated-form ()
415   (format *query-io* "~&Type a form to be evaluated:~%")
416   (list (eval (read *query-io*))))
417
418 (defun check-type-error (place place-value type type-string)
419   (let ((cond (if type-string
420                   (make-condition 'simple-type-error
421                                   :datum place
422                                   :expected-type type
423                                   :format-control
424                                   "The value of ~S is ~S, which is not ~A."
425                                   :format-arguments (list place
426                                                           place-value
427                                                           type-string))
428                   (make-condition 'simple-type-error
429                                   :datum place
430                                   :expected-type type
431                                   :format-control
432                           "The value of ~S is ~S, which is not of type ~S."
433                                   :format-arguments (list place
434                                                           place-value
435                                                           type)))))
436     (restart-case (error cond)
437       (store-value (value)
438         :report (lambda (stream)
439                   (format stream "Supply a new value for ~S." place))
440         :interactive read-evaluated-form
441         value))))
442
443 (defun case-body-error (name keyform keyform-value expected-type keys)
444   (restart-case
445       (error 'case-failure
446              :name name
447              :datum keyform-value
448              :expected-type expected-type
449              :possibilities keys)
450     (store-value (value)
451       :report (lambda (stream)
452                 (format stream "Supply a new value for ~S." keyform))
453       :interactive read-evaluated-form
454       value)))