Optimize RESTART-BIND.
[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
15 (defun muffle-warning-p (warning)
16   (declare (special *muffled-warnings*))
17   (typep warning *muffled-warnings*))
18
19 (defun initial-handler-clusters ()
20   `(((warning . ,#'(lambda (warning)
21                      (when (muffle-warning-p warning)
22                        (muffle-warning warning)))))))
23
24 ;;; an alist with elements of the form
25 ;;;
26 ;;;  (CONDITION . (HANDLER1 HANDLER2 ...))
27 ;;;
28 ;;; Recently established handlers are added at the beginning of the
29 ;;; list. Elements to the left of the alist take precedence over
30 ;;; elements to the right.
31 (defvar *handler-clusters* (initial-handler-clusters))
32
33 ;;; a list of lists of currently active RESTART instances. maintained
34 ;;; by RESTART-BIND.
35 (defvar *restart-clusters* '())
36
37 (declaim (inline restart-test-function
38                  restart-associated-conditions
39                  (setf restart-associated-conditions)))
40 (defstruct (restart (:constructor make-restart
41                         ;; Having TEST-FUNCTION at the end allows
42                         ;; to not replicate its default value in RESTART-BIND.
43                         (name function
44                          &optional report-function
45                                    interactive-function
46                                    test-function))
47                     (:copier nil) (:predicate nil))
48   (name (missing-arg) :type symbol :read-only t)
49   (function (missing-arg) :type function :read-only t)
50   (report-function nil :type (or null function) :read-only t)
51   (interactive-function nil :type (or null function) :read-only t)
52   (test-function (lambda (cond) (declare (ignore cond)) t) :type function :read-only t)
53   ;; the list of conditions which are currently associated to the
54   ;; restart. maintained by WITH-CONDITION-RESTARTS in a neither
55   ;; thread- nor interrupt-safe way. This should not be a problem
56   ;; however, since safe uses of restarts have to assume dynamic
57   ;; extent.
58   (associated-conditions '() :type list))
59
60 #!-sb-fluid (declaim (freeze-type restart))
61
62 (def!method print-object ((restart restart) stream)
63   (if *print-escape*
64       (print-unreadable-object (restart stream :type t :identity t)
65         (prin1 (restart-name restart) stream))
66       (restart-report restart stream)))
67
68 #!+sb-doc
69 (setf (fdocumentation 'restart-name 'function)
70       "Return the name of the given restart object.")
71
72 (defun restart-report (restart stream)
73   (funcall (or (restart-report-function restart)
74                (lambda (stream)
75                  (format stream "~S" (or (restart-name restart)
76                                          restart))))
77            stream))
78
79 (defvar *restart-test-stack* nil)
80
81 ;; Call FUNCTION with all restarts in the current dynamic environment,
82 ;; 1) that are associated to CONDITION (when CONDITION is NIL, all
83 ;;    restarts are processed)
84 ;; 2) and for which the restart test returns non-NIL for CONDITION.
85 ;; When CALL-TEST-P is non-NIL, all restarts are processed.
86 (defun map-restarts (function &optional condition (call-test-p t))
87   ;; FIXME: if MAP-RESTARTS is internal, we could require the FUNCTION
88   ;; argument to be of type FUNCTION.
89   (let ((function (coerce function 'function))
90         (stack *restart-test-stack*))
91     (dolist (restart-cluster *restart-clusters*)
92       (dolist (restart restart-cluster)
93         (when (and (or (not condition)
94                        (null (restart-associated-conditions restart))
95                        (memq condition (restart-associated-conditions restart)))
96                    ;; A call to COMPUTE-RESTARTS -- from an error,
97                    ;; from user code, whatever -- inside the test
98                    ;; function would cause infinite recursion here, so
99                    ;; we disable each restart using
100                    ;; *restart-test-stack* for the duration of the
101                    ;; test call.
102                    (not (memq restart stack))
103                    (or (not call-test-p)
104                        (let ((*restart-test-stack* (cons restart stack)))
105                          (declare (truly-dynamic-extent *restart-test-stack*))
106                          (funcall (restart-test-function restart) condition))))
107           (funcall function restart))))))
108
109 (defun compute-restarts (&optional condition)
110   #!+sb-doc
111   "Return a list of all the currently active restarts ordered from most recently
112 established to less recently established. If CONDITION is specified, then only
113 restarts associated with CONDITION (or with no condition) will be returned."
114   (collect ((result))
115     (map-restarts (lambda (restart) (result restart)) condition)
116     (result)))
117
118 (defun %find-restart (identifier &optional condition (call-test-p t))
119   (flet ((eq-restart-p (restart)
120            (when (eq identifier restart)
121              (return-from %find-restart restart)))
122          (named-restart-p (restart)
123            (when (eq identifier (restart-name restart))
124              (return-from %find-restart restart))))
125     ;; TODO Question for reviewer: does the compiler infer this dx
126     ;; automatically?
127     (declare (truly-dynamic-extent #'eq-restart-p #'named-restart-p))
128     (if (typep identifier 'restart)
129         ;; TODO Questions for reviewer:
130         ;;
131         ;; The code under #+previous-... below breaks the abstraction
132         ;; introduced by MAP-RESTARTS, but is about twice as
133         ;; fast as #+equivalent-... . Also, it is a common case due to
134         ;;
135         ;;    (INVOKE-RESTART RESTART)
136         ;; -> (FIND-RESTART-OR-CONTROL-ERROR RESTART)
137         ;; -> (FIND-RESTART RESTART)
138         ;;
139         ;; However, both #+previous-... and #+equivalent-... may be
140         ;; wrong altogether because of
141         ;; https://bugs.launchpad.net/sbcl/+bug/774410:
142         ;; The behavior expected in that report can be achieved by the
143         ;; following line (which is, of course, the slowest of all
144         ;; possibilities):
145         (map-restarts #'eq-restart-p condition call-test-p)
146
147         #+equivalent-to-previous-sbcl-behavior--faster-but-see-bug-774410
148         (map-restarts #'eq-restart-p nil nil)
149
150         #+previous-behavior--fastest-but-see-bug-774410
151         (and (find-if (lambda (cluster) (find identifier cluster)) *restart-clusters*)
152              identifier)
153
154         (map-restarts #'named-restart-p condition call-test-p))))
155
156 (defun find-restart (identifier &optional condition)
157   #!+sb-doc
158   "Return the first restart identified by IDENTIFIER. If IDENTIFIER is a symbol,
159 then the innermost applicable restart with that name is returned. If IDENTIFIER
160 is a restart, it is returned if it is currently active. Otherwise NIL is
161 returned. If CONDITION is specified and not NIL, then only restarts associated
162 with that condition (or with no condition) will be returned."
163   ;; Calls MAP-RESTARTS such that restart test functions are
164   ;; respected.
165   (%find-restart identifier condition))
166
167 ;;; helper for the various functions which are ANSI-spec'ed to do
168 ;;; something with a restart or signal CONTROL-ERROR if there is none
169 (defun find-restart-or-control-error (identifier &optional condition (call-test-p t))
170   (or (%find-restart identifier condition call-test-p)
171       (error 'simple-control-error
172              :format-control "No restart ~S is active~@[ for ~S~]."
173              :format-arguments (list identifier condition))))
174
175 (defun invoke-restart (restart &rest values)
176   #!+sb-doc
177   "Calls the function associated with the given restart, passing any given
178    arguments. If the argument restart is not a restart or a currently active
179    non-nil restart name, then a CONTROL-ERROR is signalled."
180   (/show "entering INVOKE-RESTART" restart)
181   ;; The following code calls MAP-RESTARTS (through
182   ;; FIND-RESTART-OR-CONTROL-ERROR -> %FIND-RESTART) such that restart
183   ;; test functions are respected when RESTART is a symbol, but not
184   ;; when RESTART is a RESTART instance.
185   ;;
186   ;; Without disabling test functions for the RESTART instance case,
187   ;; the following problem would arise:
188   ;;
189   ;;  (restart-case
190   ;;      (handler-bind
191   ;;          ((some-condition (lambda (c)
192   ;;                             (invoke-restart (find-restart 'foo c)) ; a)
193   ;;                             (invoke-restart 'foo)                  ; b)
194   ;;                             )))
195   ;;        (signal 'some-condition))
196   ;;    (foo ()
197   ;;     :test (lambda (c) (typep c 'some-condition))))
198   ;;
199   ;; In case a), INVOKE-RESTART receives the RESTART instance, but
200   ;; cannot supply the condition instance needed by the test. In case
201   ;; b) INVOKE-RESTART calls FIND-RESTART, but again cannot supply the
202   ;; condition instance. As a result, the restart would be impossible
203   ;; the invoke.
204   (let ((real-restart (find-restart-or-control-error
205                        restart nil (symbolp restart))))
206     (apply (restart-function real-restart) values)))
207
208 (defun interactive-restart-arguments (real-restart)
209   (let ((interactive-function (restart-interactive-function real-restart)))
210     (if interactive-function
211         (funcall interactive-function)
212         '())))
213
214 (defun invoke-restart-interactively (restart)
215   #!+sb-doc
216   "Calls the function associated with the given restart, prompting for any
217    necessary arguments. If the argument restart is not a restart or a
218    currently active non-NIL restart name, then a CONTROL-ERROR is signalled."
219   (let* ((real-restart (find-restart-or-control-error restart))
220          (args (interactive-restart-arguments real-restart)))
221     (apply (restart-function real-restart) args)))
222 \f
223 (defun assert-error (assertion args-and-values places datum &rest arguments)
224   (let ((cond (if datum
225                   (coerce-to-condition
226                    datum arguments 'simple-error 'error)
227                   (make-condition
228                    'simple-error
229                    :format-control "~@<The assertion ~S failed~:[.~:; ~
230                                     with ~:*~{~{~S = ~S~}~^, ~}.~]~:@>"
231                    :format-arguments (list assertion args-and-values)))))
232     (restart-case
233         (error cond)
234       (continue ()
235         :report (lambda (stream)
236                   (format stream "Retry assertion")
237                   (if places
238                       (format stream " with new value~P for ~{~S~^, ~}."
239                               (length places) places)
240                       (format stream ".")))
241         nil))))
242
243 ;;; READ-EVALUATED-FORM is used as the interactive method for restart cases
244 ;;; setup by the Common Lisp "casing" (e.g., CCASE and CTYPECASE) macros
245 ;;; and by CHECK-TYPE.
246 (defun read-evaluated-form (&optional (prompt-control nil promptp)
247                             &rest prompt-args)
248   (apply #'format *query-io*
249          (if promptp prompt-control "~&Type a form to be evaluated: ")
250          prompt-args)
251   (finish-output *query-io*)
252   (list (eval (read *query-io*))))
253
254 (defun check-type-error (place place-value type type-string)
255   (let ((condition
256          (make-condition
257           'simple-type-error
258           :datum place-value
259           :expected-type type
260           :format-control
261           "The value of ~S is ~S, which is not ~:[of type ~S~;~:*~A~]."
262           :format-arguments (list place place-value type-string type))))
263     (restart-case (error condition)
264       (store-value (value)
265         :report (lambda (stream)
266                   (format stream "Supply a new value for ~S." place))
267         :interactive read-evaluated-form
268         value))))
269
270 (defun case-failure (name value keys)
271   (error 'case-failure
272          :name name
273          :datum value
274          :expected-type (if (eq name 'ecase)
275                             `(member ,@keys)
276                             `(or ,@keys))
277          :possibilities keys))
278
279 (defun case-body-error (name keyform keyform-value expected-type keys)
280   (restart-case
281       (error 'case-failure
282              :name name
283              :datum keyform-value
284              :expected-type expected-type
285              :possibilities keys)
286     (store-value (value)
287       :report (lambda (stream)
288                 (format stream "Supply a new value for ~S." keyform))
289       :interactive read-evaluated-form
290       value)))