0.pre7.124:
[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
27   report-function
28   interactive-function
29   (test-function (lambda (cond) (declare (ignore cond)) t)))
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) condition))
55             (res restart))))
56       (res))))
57
58 #!+sb-doc
59 (setf (fdocumentation 'restart-name 'function)
60       "Return the name of the given restart object.")
61
62 (defun restart-report (restart stream)
63   (funcall (or (restart-report-function restart)
64                (let ((name (restart-name restart)))
65                  (lambda (stream)
66                    (if name (format stream "~S" name)
67                        (format stream "~S" restart)))))
68            stream))
69
70 (defmacro with-condition-restarts (condition-form restarts-form &body body)
71   #!+sb-doc
72   "WITH-CONDITION-RESTARTS Condition-Form Restarts-Form Form*
73    Evaluates the Forms in a dynamic environment where the restarts in the list
74    Restarts-Form are associated with the condition returned by Condition-Form.
75    This allows FIND-RESTART, etc., to recognize restarts that are not related
76    to the error currently being debugged. See also RESTART-CASE."
77   (let ((n-cond (gensym)))
78     `(let ((*condition-restarts*
79             (cons (let ((,n-cond ,condition-form))
80                     (cons ,n-cond
81                           (append ,restarts-form
82                                   (cdr (assoc ,n-cond *condition-restarts*)))))
83                   *condition-restarts*)))
84        ,@body)))
85
86 (defmacro restart-bind (bindings &body forms)
87   #!+sb-doc
88   "Executes forms in a dynamic context where the given restart bindings are
89    in effect. Users probably want to use RESTART-CASE. When clauses contain
90    the same restart name, FIND-RESTART will find the first such clause."
91   `(let ((*restart-clusters*
92           (cons (list
93                  ,@(mapcar (lambda (binding)
94                              (unless (or (car binding)
95                                          (member :report-function
96                                                  binding
97                                                  :test #'eq))
98                                (warn "Unnamed restart does not have a ~
99                                         report function: ~S"
100                                      binding))
101                              `(make-restart :name ',(car binding)
102                                             :function ,(cadr binding)
103                                             ,@(cddr binding)))
104                            bindings))
105                 *restart-clusters*)))
106      ,@forms))
107
108 (defun find-restart (name &optional condition)
109   #!+sb-doc
110   "Return the first restart named NAME. If NAME names a restart, the restart
111    is returned if it is currently active. If no such restart is found, NIL is
112    returned. It is an error to supply NIL as a name. If CONDITION is specified
113    and not NIL, then only restarts associated with that condition (or with no
114    condition) will be returned."
115   (find-if (lambda (x)
116              (or (eq x name)
117                  (eq (restart-name x) name)))
118            (compute-restarts condition)))
119
120 (defun invoke-restart (restart &rest values)
121   #!+sb-doc
122   "Calls the function associated with the given restart, passing any given
123    arguments. If the argument restart is not a restart or a currently active
124    non-nil restart name, then a control-error is signalled."
125   (/show "entering INVOKE-RESTART" restart)
126   (let ((real-restart (find-restart restart)))
127     (unless real-restart
128       (error 'simple-control-error
129              :format-control "Restart ~S is not active."
130              :format-arguments (list restart)))
131     (/show (restart-name real-restart))
132     (apply (restart-function real-restart) values)))
133
134 (defun invoke-restart-interactively (restart)
135   #!+sb-doc
136   "Calls the function associated with the given restart, prompting for any
137    necessary arguments. If the argument restart is not a restart or a
138    currently active non-nil restart name, then a control-error is signalled."
139   (/show "entering INVOKE-RESTART-INTERACTIVELY" restart)
140   (let ((real-restart (find-restart restart)))
141     (unless real-restart
142       (error 'simple-control-error
143              :format-control "Restart ~S is not active."
144              :format-arguments (list restart)))
145     (/show (restart-name real-restart))
146     (/show0 "falling through to APPLY of RESTART-FUNCTION")
147     (apply (restart-function real-restart)
148            (let ((interactive-function
149                   (restart-interactive-function real-restart)))
150              (if interactive-function
151                  (funcall interactive-function)
152                  '())))))
153
154 (eval-when (:compile-toplevel :load-toplevel :execute)
155 ;;; Wrap the RESTART-CASE expression in a WITH-CONDITION-RESTARTS if
156 ;;; appropriate. Gross, but it's what the book seems to say...
157 (defun munge-restart-case-expression (expression data)
158   (let ((exp (macroexpand expression)))
159     (if (consp exp)
160         (let* ((name (car exp))
161                (args (if (eq name 'cerror) (cddr exp) (cdr exp))))
162           (if (member name '(signal error cerror warn))
163               (once-only ((n-cond `(coerce-to-condition
164                                     ,(first args)
165                                     (list ,@(rest args))
166                                     ',(case name
167                                         (warn 'simple-warning)
168                                         (signal 'simple-condition)
169                                         (t 'simple-error))
170                                     ',name)))
171                 `(with-condition-restarts
172                      ,n-cond
173                      (list ,@(mapcar (lambda (da)
174                                        `(find-restart ',(nth 0 da)))
175                                      data))
176                    ,(if (eq name 'cerror)
177                         `(cerror ,(second expression) ,n-cond)
178                         `(,name ,n-cond))))
179               expression))
180         expression)))
181 ) ; EVAL-WHEN
182
183 ;;; FIXME: I did a fair amount of rearrangement of this code in order to
184 ;;; get WITH-KEYWORD-PAIRS to work cleanly. This code should be tested..
185 (defmacro restart-case (expression &body clauses)
186   #!+sb-doc
187   "(RESTART-CASE form
188    {(case-name arg-list {keyword value}* body)}*)
189    The form is evaluated in a dynamic context where the clauses have special
190    meanings as points to which control may be transferred (see INVOKE-RESTART).
191    When clauses contain the same case-name, FIND-RESTART will find the first
192    such clause. If Expression is a call to SIGNAL, ERROR, CERROR or WARN (or
193    macroexpands into such) then the signalled condition will be associated with
194    the new restarts."
195   (flet ((transform-keywords (&key report interactive test)
196            (let ((result '()))
197              (when report
198                (setq result (list* (if (stringp report)
199                                        `#'(lambda (stream)
200                                             (write-string ,report stream))
201                                        `#',report)
202                                    :report-function
203                                    result)))
204              (when interactive
205                (setq result (list* `#',interactive
206                                    :interactive-function
207                                    result)))
208              (when test
209                (setq result (list* `#',test
210                                    :test-function
211                                    result)))
212              (nreverse result)))
213          (parse-keyword-pairs (list keys)
214            (do ((l list (cddr l))
215                 (k '() (list* (cadr l) (car l) k)))
216                ((or (null l) (not (member (car l) keys)))
217                 (values (nreverse k) l)))))
218     (let ((block-tag (gensym))
219           (temp-var (gensym))
220           (data
221            (macrolet (;; KLUDGE: This started as an old DEFMACRO
222                       ;; WITH-KEYWORD-PAIRS general utility, which was used
223                       ;; only in this one place in the code. It was translated
224                       ;; literally into this MACROLET in order to avoid some
225                       ;; cross-compilation bootstrap problems. It would almost
226                       ;; certainly be clearer, and it would certainly be more
227                       ;; concise, to do a more idiomatic translation, merging
228                       ;; this with the TRANSFORM-KEYWORDS logic above.
229                       ;;   -- WHN 19990925
230                       (with-keyword-pairs ((names expression) &body forms)
231                         (let ((temp (member '&rest names)))
232                           (unless (= (length temp) 2)
233                             (error "&REST keyword is ~:[missing~;misplaced~]."
234                                    temp))
235                           (let* ((key-vars (ldiff names temp))
236                                  (keywords (mapcar #'keywordicate key-vars))
237                                  (key-var (gensym))
238                                  (rest-var (cadr temp)))
239                             `(multiple-value-bind (,key-var ,rest-var)
240                                  (parse-keyword-pairs ,expression ',keywords)
241                                (let ,(mapcar (lambda (var keyword)
242                                                `(,var (getf ,key-var
243                                                             ,keyword)))
244                                              key-vars keywords)
245                                  ,@forms))))))
246              (mapcar (lambda (clause)
247                        (with-keyword-pairs ((report interactive test
248                                                     &rest forms)
249                                             (cddr clause))
250                          (list (car clause) ;name=0
251                                (gensym) ;tag=1
252                                (transform-keywords :report report ;keywords=2
253                                                    :interactive interactive
254                                                    :test test)
255                                (cadr clause) ;bvl=3
256                                forms))) ;body=4
257                    clauses))))
258       `(block ,block-tag
259          (let ((,temp-var nil))
260            (tagbody
261             (restart-bind
262                 ,(mapcar (lambda (datum)
263                            (let ((name (nth 0 datum))
264                                  (tag  (nth 1 datum))
265                                  (keys (nth 2 datum)))
266                              `(,name #'(lambda (&rest temp)
267                                          (setq ,temp-var temp)
268                                          (go ,tag))
269                                      ,@keys)))
270                          data)
271               (return-from ,block-tag
272                            ,(munge-restart-case-expression expression data)))
273             ,@(mapcan (lambda (datum)
274                         (let ((tag  (nth 1 datum))
275                               (bvl  (nth 3 datum))
276                               (body (nth 4 datum)))
277                           (list tag
278                                 `(return-from ,block-tag
279                                    (apply (lambda ,bvl ,@body)
280                                           ,temp-var)))))
281                       data)))))))
282
283 (defmacro with-simple-restart ((restart-name format-string
284                                              &rest format-arguments)
285                                &body forms)
286   #!+sb-doc
287   "(WITH-SIMPLE-RESTART (restart-name format-string format-arguments)
288    body)
289    If restart-name is not invoked, then all values returned by forms are
290    returned. If control is transferred to this restart, it immediately
291    returns the values NIL and T."
292   `(restart-case
293        ;; If there's just one body form, then don't use PROGN. This allows
294        ;; RESTART-CASE to "see" calls to ERROR, etc.
295        ,(if (= (length forms) 1) (car forms) `(progn ,@forms))
296      (,restart-name ()
297         :report (lambda (stream)
298                   (format stream ,format-string ,@format-arguments))
299       (values nil t))))
300 \f
301 ;;;; HANDLER-BIND
302
303 (defvar *handler-clusters* nil)
304
305 (defmacro handler-bind (bindings &body forms)
306   #!+sb-doc
307   "(HANDLER-BIND ( {(type handler)}* )  body)
308    Executes body in a dynamic context where the given handler bindings are
309    in effect. Each handler must take the condition being signalled as an
310    argument. The bindings are searched first to last in the event of a
311    signalled condition."
312   (let ((member-if (member-if (lambda (x)
313                                 (not (proper-list-of-length-p x 2)))
314                               bindings)))
315     (when member-if
316       (error "ill-formed handler binding: ~S" (first member-if))))
317   `(let ((*handler-clusters*
318           (cons (list ,@(mapcar (lambda (x) `(cons ',(car x) ,(cadr x)))
319                                 bindings))
320                 *handler-clusters*)))
321      (multiple-value-prog1
322          (progn
323            ,@forms)
324        ;; Wait for any float exceptions.
325        #!+x86 (float-wait))))
326 \f
327 ;;;; HANDLER-CASE
328
329 (defmacro handler-case (form &rest clauses)
330   "(HANDLER-CASE form
331    { (type ([var]) body) }* )
332    Execute FORM in a context with handlers established for the condition
333    types. A peculiar property allows type to be :no-error. If such a clause
334    occurs, and form returns normally, all its values are passed to this clause
335    as if by MULTIPLE-VALUE-CALL.  The :NO-ERROR clause accepts more than one
336    var specification."
337
338   ;; FIXME: This old SBCL code uses multiple nested THROW/CATCH
339   ;; operations, which seems like an ugly way to handle lexical
340   ;; nonlocal exit. MNA sbcl-devel 2001-07-17 provided a patch
341   ;; (included below this form, but #+NIL'ed out) to switch over to
342   ;; RETURN-FROM, which seems like basically a better idea.
343   ;; Unfortunately when using his patch, this reasonable code
344   ;;    (DEFUN FOO1I ()
345   ;;      (IF (NOT (IGNORE-ERRORS
346   ;;                 (MAKE-PATHNAME :HOST "FOO"
347   ;;                                :DIRECTORY "!BLA"
348   ;;                                :NAME "BAR")))
349   ;;          (PRINT "OK")
350   ;;          (ERROR "NOTUNLESSNOT")))
351   ;; fails (doing ERROR "NOTUNLESSNOT" when it should PRINT "OK"
352   ;; instead). I think this may not be a bug in MNA's patch, but 
353   ;; instead in the rest of the compiler (e.g. handling of RETURN-FROM)
354   ;; but whatever the reason. (I noticed this problem in
355   ;; sbcl-0.pre7.14.flaky4.11, and reverted to the old code at that point.
356   ;; The problem also occurs at least in sbcl-0.6.12.59 and
357   ;; sbcl-0.6.13.) -- WHN
358   ;;
359   ;; Note also: I think the old nested THROW/CATCH version became
360   ;; easier to read once I converted it to use DESTRUCTURING-BIND and
361   ;; mnemonic names, and it would probably be a useful to do that to
362   ;; the RETURN-FROM version when/if it's adopted.
363   (let ((no-error-clause (assoc ':no-error clauses)))
364     (if no-error-clause
365         (let ((normal-return (make-symbol "normal-return"))
366               (error-return  (make-symbol "error-return")))
367           `(block ,error-return
368              (multiple-value-call #'(lambda ,@(cdr no-error-clause))
369                (block ,normal-return
370                  (return-from ,error-return
371                    (handler-case (return-from ,normal-return ,form)
372                      ;; FIXME: What if there's more than one :NO-ERROR
373                      ;; clause? The code here and above doesn't seem
374                      ;; either to remove both of them or to signal
375                      ;; a good error, so it's probably wrong.
376                      ,@(remove no-error-clause clauses)))))))
377         (let ((var (gensym "HC-VAR-"))
378               (outer-tag (gensym "OUTER-HC-TAG-"))
379               (inner-tag (gensym "INNER-HC-TAG-"))
380               (tag-var (gensym "HC-TAG-VAR-"))
381               (tagged-clauses (mapcar (lambda (clause)
382                                         (cons (gensym "HC-TAG-") clause))
383                                       clauses)))
384           `(let ((,outer-tag (cons nil nil))
385                  (,inner-tag (cons nil nil))
386                  ,var ,tag-var)
387              ;; FIXME: should be (DECLARE (IGNORABLE ,VAR))
388              ,var                       ;ignoreable
389              (catch ,outer-tag
390                (catch ,inner-tag
391                  (throw ,outer-tag
392                         (handler-bind
393                             ,(mapcar (lambda (tagged-clause)
394                                        (destructuring-bind
395                                            (tag typespec args &body body)
396                                            tagged-clause
397                                          (declare (ignore body))
398                                          `(,typespec
399                                            (lambda (temp)
400                                              ,(if args
401                                                   `(setq ,var temp)
402                                                   '(declare (ignore temp)))
403                                              (setf ,tag-var ',tag)
404                                              (/show "THROWing INNER-TAG from HANDLER-BIND closure for" ',typespec)
405                                              (throw ,inner-tag nil)))))
406                                      tagged-clauses)
407                           ,form)))
408                (case ,tag-var
409                  ,@(mapcar (lambda (tagged-clause)
410                              (destructuring-bind
411                                  (tag typespec args &body body)
412                                  tagged-clause
413                                (declare (ignore typespec))
414                                `(,tag
415                                  ,@(if args
416                                        (destructuring-bind (arg) args
417                                          `((let ((,arg ,var))
418                                              ,@body)))
419                                        body))))
420                            tagged-clauses)))))))
421   #+nil ; MNA's patched version -- see FIXME above
422   (let ((no-error-clause (assoc ':no-error cases)))
423     (if no-error-clause
424         (let ((normal-return (make-symbol "normal-return"))
425               (error-return  (make-symbol "error-return")))
426           `(block ,error-return
427              (multiple-value-call (lambda ,@(cdr no-error-clause))
428                (block ,normal-return
429                  (return-from ,error-return
430                    (handler-case (return-from ,normal-return ,form)
431                      ,@(remove no-error-clause cases)))))))
432         (let ((tag (gensym))
433               (var (gensym))
434               (annotated-cases (mapcar (lambda (case) (cons (gensym) case))
435                                        cases)))
436           `(block ,tag
437              (let ((,var nil))
438                (declare (ignorable ,var))
439                (tagbody
440                 (handler-bind
441                     ,(mapcar (lambda (annotated-case)
442                                (list (cadr annotated-case)
443                                      `(lambda (temp)
444                                         ,(if (caddr annotated-case)
445                                              `(setq ,var temp)
446                                              '(declare (ignore temp)))
447                                         (go ,(car annotated-case)))))
448                              annotated-cases)
449                   (return-from ,tag
450                     #!-x86 ,form
451                     #!+x86 (multiple-value-prog1 ,form
452                              ;; Need to catch FP errors here!
453                              (float-wait))))
454                 ,@(mapcan
455                    (lambda (annotated-case)
456                      (list (car annotated-case)
457                            (let ((body (cdddr annotated-case)))
458                              `(return-from
459                                   ,tag
460                                 ,(cond ((caddr annotated-case)
461                                         `(let ((,(caaddr annotated-case)
462                                                 ,var))
463                                            ,@body))
464                                        ((not (cdr body))
465                                         (car body))
466                                        (t
467                                         `(progn ,@body)))))))
468                    annotated-cases))))))))
469 \f
470 ;;;; helper functions for restartable error handling which couldn't be
471 ;;;; defined 'til now 'cause they use the RESTART-CASE macro
472
473 (defun assert-error (assertion places datum &rest arguments)
474   (let ((cond (if datum
475                 (coerce-to-condition datum
476                                                     arguments
477                                                     'simple-error
478                                                     'error)
479                 (make-condition 'simple-error
480                                 :format-control "The assertion ~S failed."
481                                 :format-arguments (list assertion)))))
482     (restart-case
483         (error cond)
484       (continue ()
485                 :report (lambda (stream)
486                           (format stream "Retry assertion")
487                           (if places
488                               (format stream
489                                       " with new value~P for ~{~S~^, ~}."
490                                       (length places)
491                                       places)
492                               (format stream ".")))
493                 nil))))
494
495 ;;; READ-EVALUATED-FORM is used as the interactive method for restart cases
496 ;;; setup by the Common Lisp "casing" (e.g., CCASE and CTYPECASE) macros
497 ;;; and by CHECK-TYPE.
498 (defun read-evaluated-form ()
499   (format *query-io* "~&Type a form to be evaluated:~%")
500   (list (eval (read *query-io*))))
501
502 (defun check-type-error (place place-value type type-string)
503   (let ((cond (if type-string
504                   (make-condition 'simple-type-error
505                                   :datum place
506                                   :expected-type type
507                                   :format-control
508                                   "The value of ~S is ~S, which is not ~A."
509                                   :format-arguments (list place
510                                                           place-value
511                                                           type-string))
512                   (make-condition 'simple-type-error
513                                   :datum place
514                                   :expected-type type
515                                   :format-control
516                           "The value of ~S is ~S, which is not of type ~S."
517                                   :format-arguments (list place
518                                                           place-value
519                                                           type)))))
520     (restart-case (error cond)
521       (store-value (value)
522         :report (lambda (stream)
523                   (format stream "Supply a new value for ~S." place))
524         :interactive read-evaluated-form
525         value))))
526
527 (defun case-body-error (name keyform keyform-value expected-type keys)
528   (restart-case
529       (error 'case-failure
530              :name name
531              :datum keyform-value
532              :expected-type expected-type
533              :possibilities keys)
534     (store-value (value)
535       :report (lambda (stream)
536                 (format stream "Supply a new value for ~S." keyform))
537       :interactive read-evaluated-form
538       value)))