0.7.13.1
[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 data)
159   (let ((exp (macroexpand expression)))
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                      (list ,@(mapcar (lambda (da)
175                                        `(find-restart ',(nth 0 da)))
176                                      data))
177                    ,(if (eq name 'cerror)
178                         `(cerror ,(second expression) ,n-cond)
179                         `(,name ,n-cond))))
180               expression))
181         expression)))
182 ) ; EVAL-WHEN
183
184 ;;; FIXME: I did a fair amount of rearrangement of this code in order to
185 ;;; get WITH-KEYWORD-PAIRS to work cleanly. This code should be tested..
186 (defmacro restart-case (expression &body clauses)
187   #!+sb-doc
188   "(RESTART-CASE form
189    {(case-name arg-list {keyword value}* body)}*)
190    The form is evaluated in a dynamic context where the clauses have special
191    meanings as points to which control may be transferred (see INVOKE-RESTART).
192    When clauses contain the same case-name, FIND-RESTART will find the first
193    such clause. If Expression is a call to SIGNAL, ERROR, CERROR or WARN (or
194    macroexpands into such) then the signalled condition will be associated with
195    the new restarts."
196   (flet ((transform-keywords (&key report interactive test)
197            (let ((result '()))
198              (when report
199                (setq result (list* (if (stringp report)
200                                        `#'(lambda (stream)
201                                             (write-string ,report stream))
202                                        `#',report)
203                                    :report-function
204                                    result)))
205              (when interactive
206                (setq result (list* `#',interactive
207                                    :interactive-function
208                                    result)))
209              (when test
210                (setq result (list* `#',test :test-function result)))
211              (nreverse result)))
212          (parse-keyword-pairs (list keys)
213            (do ((l list (cddr l))
214                 (k '() (list* (cadr l) (car l) k)))
215                ((or (null l) (not (member (car l) keys)))
216                 (values (nreverse k) l)))))
217     (let ((block-tag (gensym))
218           (temp-var (gensym))
219           (data
220            (macrolet (;; KLUDGE: This started as an old DEFMACRO
221                       ;; WITH-KEYWORD-PAIRS general utility, which was used
222                       ;; only in this one place in the code. It was translated
223                       ;; literally into this MACROLET in order to avoid some
224                       ;; cross-compilation bootstrap problems. It would almost
225                       ;; certainly be clearer, and it would certainly be more
226                       ;; concise, to do a more idiomatic translation, merging
227                       ;; this with the TRANSFORM-KEYWORDS logic above.
228                       ;;   -- WHN 19990925
229                       (with-keyword-pairs ((names expression) &body forms)
230                         (let ((temp (member '&rest names)))
231                           (unless (= (length temp) 2)
232                             (error "&REST keyword is ~:[missing~;misplaced~]."
233                                    temp))
234                           (let* ((key-vars (ldiff names temp))
235                                  (keywords (mapcar #'keywordicate key-vars))
236                                  (key-var (gensym))
237                                  (rest-var (cadr temp)))
238                             `(multiple-value-bind (,key-var ,rest-var)
239                                  (parse-keyword-pairs ,expression ',keywords)
240                                (let ,(mapcar (lambda (var keyword)
241                                                `(,var (getf ,key-var
242                                                             ,keyword)))
243                                              key-vars keywords)
244                                  ,@forms))))))
245              (mapcar (lambda (clause)
246                        (with-keyword-pairs ((report interactive test
247                                                     &rest forms)
248                                             (cddr clause))
249                          (list (car clause) ;name=0
250                                (gensym) ;tag=1
251                                (transform-keywords :report report ;keywords=2
252                                                    :interactive interactive
253                                                    :test test)
254                                (cadr clause) ;bvl=3
255                                forms))) ;body=4
256                    clauses))))
257       `(block ,block-tag
258          (let ((,temp-var nil))
259            (tagbody
260             (restart-bind
261                 ,(mapcar (lambda (datum)
262                            (let ((name (nth 0 datum))
263                                  (tag  (nth 1 datum))
264                                  (keys (nth 2 datum)))
265                              `(,name #'(lambda (&rest temp)
266                                          (setq ,temp-var temp)
267                                          (go ,tag))
268                                      ,@keys)))
269                          data)
270               (return-from ,block-tag
271                            ,(munge-restart-case-expression expression data)))
272             ,@(mapcan (lambda (datum)
273                         (let ((tag  (nth 1 datum))
274                               (bvl  (nth 3 datum))
275                               (body (nth 4 datum)))
276                           (list tag
277                                 `(return-from ,block-tag
278                                    (apply (lambda ,bvl ,@body)
279                                           ,temp-var)))))
280                       data)))))))
281
282 (defmacro with-simple-restart ((restart-name format-string
283                                              &rest format-arguments)
284                                &body forms)
285   #!+sb-doc
286   "(WITH-SIMPLE-RESTART (restart-name format-string format-arguments)
287    body)
288    If restart-name is not invoked, then all values returned by forms are
289    returned. If control is transferred to this restart, it immediately
290    returns the values NIL and T."
291   `(restart-case
292        ;; If there's just one body form, then don't use PROGN. This allows
293        ;; RESTART-CASE to "see" calls to ERROR, etc.
294        ,(if (= (length forms) 1) (car forms) `(progn ,@forms))
295      (,restart-name ()
296         :report (lambda (stream)
297                   (format stream ,format-string ,@format-arguments))
298       (values nil t))))
299 \f
300 ;;;; HANDLER-BIND
301
302 (defvar *handler-clusters* nil)
303
304 (defmacro handler-bind (bindings &body forms)
305   #!+sb-doc
306   "(HANDLER-BIND ( {(type handler)}* )  body)
307    Executes body in a dynamic context where the given handler bindings are
308    in effect. Each handler must take the condition being signalled as an
309    argument. The bindings are searched first to last in the event of a
310    signalled condition."
311   (let ((member-if (member-if (lambda (x)
312                                 (not (proper-list-of-length-p x 2)))
313                               bindings)))
314     (when member-if
315       (error "ill-formed handler binding: ~S" (first member-if))))
316   `(let ((*handler-clusters*
317           (cons (list ,@(mapcar (lambda (x) `(cons ',(car x) ,(cadr x)))
318                                 bindings))
319                 *handler-clusters*)))
320      (multiple-value-prog1
321          (progn
322            ,@forms)
323        ;; Wait for any float exceptions.
324        #!+x86 (float-wait))))
325 \f
326 ;;;; HANDLER-CASE
327
328 (defmacro handler-case (form &rest cases)
329   "(HANDLER-CASE form
330    { (type ([var]) body) }* )
331    Execute FORM in a context with handlers established for the condition
332    types. A peculiar property allows type to be :NO-ERROR. If such a clause
333    occurs, and form returns normally, all its values are passed to this clause
334    as if by MULTIPLE-VALUE-CALL.  The :NO-ERROR clause accepts more than one
335    var specification."
336
337   ;; FIXME: Replacing CADR, CDDDR and friends with DESTRUCTURING-BIND
338   ;; and names for the subexpressions would make it easier to
339   ;; understand the code below.
340   (let ((no-error-clause (assoc ':no-error cases)))
341     (if no-error-clause
342         (let ((normal-return (make-symbol "normal-return"))
343               (error-return  (make-symbol "error-return")))
344           `(block ,error-return
345              (multiple-value-call (lambda ,@(cdr no-error-clause))
346                (block ,normal-return
347                  (return-from ,error-return
348                    (handler-case (return-from ,normal-return ,form)
349                      ,@(remove no-error-clause cases)))))))
350         (let ((tag (gensym))
351               (var (gensym))
352               (annotated-cases (mapcar (lambda (case) (cons (gensym) case))
353                                        cases)))
354           `(block ,tag
355              (let ((,var nil))
356                (declare (ignorable ,var))
357                (tagbody
358                 (handler-bind
359                     ,(mapcar (lambda (annotated-case)
360                                (list (cadr annotated-case)
361                                      `(lambda (temp)
362                                         ,(if (caddr annotated-case)
363                                              `(setq ,var temp)
364                                              '(declare (ignore temp)))
365                                         (go ,(car annotated-case)))))
366                              annotated-cases)
367                   (return-from ,tag
368                     #!-x86 ,form
369                     #!+x86 (multiple-value-prog1 ,form
370                              ;; Need to catch FP errors here!
371                              (float-wait))))
372                 ,@(mapcan
373                    (lambda (annotated-case)
374                      (list (car annotated-case)
375                            (let ((body (cdddr annotated-case)))
376                              `(return-from
377                                   ,tag
378                                 ,(cond ((caddr annotated-case)
379                                         `(let ((,(caaddr annotated-case)
380                                                 ,var))
381                                            ,@body))
382                                        ((not (cdr body))
383                                         (car body))
384                                        (t
385                                         `(progn ,@body)))))))
386                    annotated-cases))))))))
387 \f
388 ;;;; helper functions for restartable error handling which couldn't be
389 ;;;; defined 'til now 'cause they use the RESTART-CASE macro
390
391 (defun assert-error (assertion places datum &rest arguments)
392   (let ((cond (if datum
393                 (coerce-to-condition datum
394                                                     arguments
395                                                     'simple-error
396                                                     'error)
397                 (make-condition 'simple-error
398                                 :format-control "The assertion ~S failed."
399                                 :format-arguments (list assertion)))))
400     (restart-case
401         (error cond)
402       (continue ()
403                 :report (lambda (stream)
404                           (format stream "Retry assertion")
405                           (if places
406                               (format stream
407                                       " with new value~P for ~{~S~^, ~}."
408                                       (length places)
409                                       places)
410                               (format stream ".")))
411                 nil))))
412
413 ;;; READ-EVALUATED-FORM is used as the interactive method for restart cases
414 ;;; setup by the Common Lisp "casing" (e.g., CCASE and CTYPECASE) macros
415 ;;; and by CHECK-TYPE.
416 (defun read-evaluated-form ()
417   (format *query-io* "~&Type a form to be evaluated:~%")
418   (list (eval (read *query-io*))))
419
420 (defun check-type-error (place place-value type type-string)
421   (let ((cond (if type-string
422                   (make-condition 'simple-type-error
423                                   :datum place
424                                   :expected-type type
425                                   :format-control
426                                   "The value of ~S is ~S, which is not ~A."
427                                   :format-arguments (list place
428                                                           place-value
429                                                           type-string))
430                   (make-condition 'simple-type-error
431                                   :datum place
432                                   :expected-type type
433                                   :format-control
434                           "The value of ~S is ~S, which is not of type ~S."
435                                   :format-arguments (list place
436                                                           place-value
437                                                           type)))))
438     (restart-case (error cond)
439       (store-value (value)
440         :report (lambda (stream)
441                   (format stream "Supply a new value for ~S." place))
442         :interactive read-evaluated-form
443         value))))
444
445 (defun case-body-error (name keyform keyform-value expected-type keys)
446   (restart-case
447       (error 'case-failure
448              :name name
449              :datum keyform-value
450              :expected-type expected-type
451              :possibilities keys)
452     (store-value (value)
453       :report (lambda (stream)
454                 (format stream "Supply a new value for ~S." keyform))
455       :interactive read-evaluated-form
456       value)))